]> git.xonotic.org Git - xonotic/netradiant.git/commitdiff
Merge commit 'e7c45da823515747a88569374d62717b72dcf078' into garux-merge
authorThomas Debesse <dev@illwieckz.net>
Mon, 25 May 2020 19:33:45 +0000 (21:33 +0200)
committerThomas Debesse <dev@illwieckz.net>
Mon, 25 May 2020 19:33:45 +0000 (21:33 +0200)
17 files changed:
1  2 
Makefile
libs/string/string.h
radiant/build.cpp
radiant/build.h
radiant/csg.cpp
radiant/environment.cpp
radiant/environment.h
radiant/findtexturedialog.cpp
radiant/main.cpp
radiant/mainframe.cpp
radiant/map.cpp
radiant/server.cpp
tools/quake3/q3map2/brush.c
tools/quake3/q3map2/bspfile_abstract.c
tools/quake3/q3map2/main.c
tools/quake3/q3map2/q3map2.h
tools/quake3/q3map2/shaders.c

diff --combined Makefile
index bf98684f13c36c55cf4768731771b3e33714f9de,bcb1f6f601ff720c7658ecb26cf0d0c37e739f03..8e63b813c38f4833bd6890e3a71a4a6bb2d39632
+++ b/Makefile
@@@ -18,7 -18,6 +18,7 @@@ RADIANT_ABOUTMSG   ?= Custom buil
  # warning: this directory may NOT contain any files other than the ones written by this Makefile!
  # NEVER SET THIS TO A SYSTEM WIDE "bin" DIRECTORY!
  INSTALLDIR         ?= install
 +DOWNLOADDIR        ?= build/download
  
  CC                 ?= gcc
  CXX                ?= g++
@@@ -37,7 -36,7 +37,7 @@@ ECHO_NOLF          ?= echo -
  CAT                ?= cat
  MKDIR              ?= mkdir -p
  CP                 ?= cp
 -CP_R               ?= $(CP) -r
 +CP_R               ?= $(CP) -r --preserve=timestamps
  LN                 ?= ln
  LN_SNF             ?= $(LN) -snf
  RM                 ?= rm
@@@ -68,9 -67,6 +68,9 @@@ LIBS_XML           ?= $(shell PKG_CONFI
  CPPFLAGS_PNG       ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libpng --cflags $(STDERR_TO_DEVNULL))
  LIBS_PNG           ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libpng --libs-only-L $(STDERR_TO_DEVNULL)) \
                        $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libpng --libs-only-l $(STDERR_TO_DEVNULL))
 +CPPFLAGS_WEBP      ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libwebp --cflags $(STDERR_TO_DEVNULL))
 +LIBS_WEBP          ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libwebp --libs-only-L $(STDERR_TO_DEVNULL)) \
 +                      $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libwebp --libs-only-l $(STDERR_TO_DEVNULL))
  CPPFLAGS_GTK       ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtk+-2.0 --cflags $(STDERR_TO_DEVNULL))
  LIBS_GTK           ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtk+-2.0 --libs-only-L $(STDERR_TO_DEVNULL)) \
                        $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtk+-2.0 --libs-only-l $(STDERR_TO_DEVNULL))
@@@ -85,7 -81,7 +85,7 @@@ LIBS_GL            ?= -lGL # -lopengl3
  CPPFLAGS_DL        ?=
  LIBS_DL            ?= -ldl # nothing on Win32
  CPPFLAGS_ZLIB      ?=
 -LIBS_ZLIB          ?= -lz
 +LIBS_ZLIB          ?= -lz -lminizip
  CPPFLAGS_JPEG      ?=
  LIBS_JPEG          ?= -ljpeg
  DEPEND_ON_MAKEFILE ?= yes
@@@ -117,7 -113,7 +117,7 @@@ CFLAGS_COMMON = -MMD -W -Wall -Wcast-al
  CPPFLAGS_COMMON =
  LDFLAGS_COMMON =
  LIBS_COMMON =
 -CXXFLAGS_COMMON = -Wno-non-virtual-dtor -Wreorder -fno-exceptions -fno-rtti
 +CXXFLAGS_COMMON = -std=c++11 -Wno-non-virtual-dtor -Wreorder -fno-exceptions -fno-rtti
  
  ifeq ($(BUILD),debug)
  ifeq ($(findstring $(CFLAGS),-g),)
@@@ -169,7 -165,7 +169,7 @@@ ifeq ($(findstring $(CFLAGS),-O),
        CFLAGS_COMMON += -O3
        # only add -O3 if no -O flag is in $(CFLAGS)
  endif
 -      CFLAGS_COMMON += -march=native -mcpu=native
 +      CFLAGS_COMMON += -march=native -mtune=native
        CPPFLAGS_COMMON +=
        LDFLAGS_COMMON += -s
  else
@@@ -237,6 -233,8 +237,6 @@@ ifeq ($(OS),Darwin
        # workaround: we have no "ldd" for OS X, so...
        LDD =
        OTOOL = otool
 -
 -      INSTALLDIR := $(INSTALLDIR_BASE)/NetRadiant.app/Contents/MacOS/install
  else
  
  $(error Unsupported build OS: $(OS))
@@@ -245,11 -243,10 +245,11 @@@ endi
  endif
  
  # VERSION!
 -RADIANT_VERSION_NUMBER = 1.5.0
 +RADIANT_MAJOR_VERSION = 1
 +RADIANT_MINOR_VERSION = 5
 +RADIANT_PATCH_VERSION = 0
 +RADIANT_VERSION_NUMBER = $(RADIANT_MAJOR_VERSION).$(RADIANT_MINOR_VERSION).$(RADIANT_PATCH_VERSION)
  RADIANT_VERSION = $(RADIANT_VERSION_NUMBER)n
 -RADIANT_MAJOR_VERSION = 5
 -RADIANT_MINOR_VERSION = 0
  Q3MAP_VERSION = 2.5.17n
  
  # Executable extension
@@@ -261,8 -258,7 +261,8 @@@ ifneq ($(GIT_VERSION),
        Q3MAP_VERSION := $(Q3MAP_VERSION)-git-$(GIT_VERSION)
  endif
  
 -CPPFLAGS += -DRADIANT_VERSION="\"$(RADIANT_VERSION)\"" -DRADIANT_MAJOR_VERSION="\"$(RADIANT_MAJOR_VERSION)\"" -DRADIANT_MINOR_VERSION="\"$(RADIANT_MINOR_VERSION)\"" -DRADIANT_ABOUTMSG="\"$(RADIANT_ABOUTMSG)\"" -DQ3MAP_VERSION="\"$(Q3MAP_VERSION)\"" -DRADIANT_EXECUTABLE="\"$(RADIANT_EXECUTABLE)\""
 +CPPFLAGS += -DRADIANT_VERSION="\"$(RADIANT_VERSION)\"" -DRADIANT_MAJOR_VERSION="\"$(RADIANT_MAJOR_VERSION)\"" -DRADIANT_MINOR_VERSION="\"$(RADIANT_MINOR_VERSION)\"" -DRADIANT_PATCH_VERSION="\"$(RADIANT_PATCH_VERSION)\"" -DRADIANT_ABOUTMSG="\"$(RADIANT_ABOUTMSG)\"" -DQ3MAP_VERSION="\"$(Q3MAP_VERSION)\"" -DRADIANT_EXECUTABLE="\"$(RADIANT_EXECUTABLE)\""
 +CPPFLAGS += -DGTK_TARGET=2
  
  .PHONY: all
  all: \
@@@ -355,7 -351,6 +355,7 @@@ dependencies-check
        checkheader libglib2.0-dev glib.h g_path_is_absolute "$(CPPFLAGS_GLIB)" "$(LIBS_GLIB)"; \
        checkheader libxml2-dev libxml/xpath.h xmlXPathInit "$(CPPFLAGS_XML)" "$(LIBS_XML)"; \
        checkheader libpng12-dev png.h png_create_read_struct "$(CPPFLAGS_PNG)" "$(LIBS_PNG)"; \
 +      checkheader libwebp-dev webp/decode.h WebPGetInfo "$(CPPFLAGS_WEBP)" "$(LIBS_WEBP)"; \
        checkheader "mesa-common-dev (or another OpenGL library)" GL/gl.h glClear "$(CPPFLAGS_GL)" "$(LIBS_GL)"; \
        checkheader libgtk2.0-dev gtk/gtkdialog.h gtk_dialog_run "$(CPPFLAGS_GTK)" "$(LIBS_GTK)"; \
        checkheader libpango1.0-dev pango/pangoft2.h pango_ft2_font_map_new "$(CPPFLAGS_PANGOFT2)" "$(LIBS_PANGOFT2)"; \
@@@ -386,7 -381,6 +386,7 @@@ binaries-radiant-modules: 
        $(INSTALLDIR)/modules/image.$(DLL) \
        $(INSTALLDIR)/modules/imagehl.$(DLL) \
        $(INSTALLDIR)/modules/imagepng.$(DLL) \
 +      $(INSTALLDIR)/modules/imagewebp.$(DLL) \
        $(INSTALLDIR)/modules/imageq2.$(DLL) \
        $(INSTALLDIR)/modules/mapq3.$(DLL) \
        $(INSTALLDIR)/modules/mapxml.$(DLL) \
@@@ -403,6 -397,7 +403,6 @@@ binaries-radiant-plugins: 
        $(INSTALLDIR)/plugins/shaderplug.$(DLL) \
        $(INSTALLDIR)/plugins/sunplug.$(DLL) \
        $(INSTALLDIR)/plugins/ufoaiplug.$(DLL) \
 -      $(INSTALLDIR)/plugins/meshtex.$(DLL) \
  
  .PHONY: binaries-radiant
  binaries-radiant-core: \
@@@ -454,7 -449,6 +454,7 @@@ binaries-q3map2: 
  .PHONY: clean
  clean:
        $(RM_R) $(INSTALLDIR_BASE)/
 +      $(RM_R) $(DOWNLOADDIR)/
        $(FIND) . \( -name \*.o -o -name \*.d -o -name \*.$(DLL) -o -name \*.$(A) -o -name \*.$(EXE) \) -exec $(RM) {} \;
        $(RM) icons/*.rc
  
@@@ -489,9 -483,11 +489,11 @@@ endi
  %.o: %.c $(if $(findstring $(DEPEND_ON_MAKEFILE),yes),$(wildcard Makefile*),) | dependencies-check
        $(CC) $< $(CFLAGS) $(CFLAGS_COMMON) $(CPPFLAGS_EXTRA) $(CPPFLAGS_COMMON) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@
  
- $(INSTALLDIR)/q3map2.$(EXE): LDFLAGS_EXTRA := -Wl,--large-address-aware
+ ifeq ($(OS),Win32)
+ $(INSTALLDIR)/q3map2.$(EXE): LDFLAGS_EXTRA := -Wl,--large-address-aware,--stack,4194304
+ endif
 -$(INSTALLDIR)/q3map2.$(EXE): LIBS_EXTRA := $(LIBS_XML) $(LIBS_GLIB) $(LIBS_PNG) $(LIBS_JPEG) $(LIBS_ZLIB)
 -$(INSTALLDIR)/q3map2.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) $(CPPFLAGS_PNG) $(CPPFLAGS_JPEG) -Itools/quake3/common -Ilibs -Iinclude
 +$(INSTALLDIR)/q3map2.$(EXE): LIBS_EXTRA := $(LIBS_XML) $(LIBS_GLIB) $(LIBS_PNG) $(LIBS_JPEG) $(LIBS_WEBP) $(LIBS_ZLIB)
 +$(INSTALLDIR)/q3map2.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) $(CPPFLAGS_PNG) $(CPPFLAGS_JPEG) $(CPPFLAGS_WEBP) -Itools/quake3/common -Ilibs -Iinclude
  $(INSTALLDIR)/q3map2.$(EXE): \
        tools/quake3/common/cmdlib.o \
        tools/quake3/common/imagelib.o \
        tools/quake3/common/polylib.o \
        tools/quake3/common/scriplib.o \
        tools/quake3/common/threads.o \
 -      tools/quake3/common/unzip.o \
        tools/quake3/common/vfs.o \
        tools/quake3/common/miniz.o \
        tools/quake3/q3map2/brush.o \
        tools/quake3/q3map2/bspfile_ibsp.o \
        tools/quake3/q3map2/bspfile_rbsp.o \
        tools/quake3/q3map2/bsp.o \
 +      tools/quake3/q3map2/bsp_analyze.o \
 +      tools/quake3/q3map2/bsp_scale.o \
 +      tools/quake3/q3map2/bsp_info.o \
        tools/quake3/q3map2/convert_ase.o \
 +      tools/quake3/q3map2/convert_bsp.o \
        tools/quake3/q3map2/convert_obj.o \
        tools/quake3/q3map2/convert_map.o \
        tools/quake3/q3map2/decals.o \
 +      tools/quake3/q3map2/exportents.o \
        tools/quake3/q3map2/facebsp.o \
 +      tools/quake3/q3map2/fixaas.o \
        tools/quake3/q3map2/fog.o \
 +      tools/quake3/q3map2/help.o \
        tools/quake3/q3map2/image.o \
        tools/quake3/q3map2/leakfile.o \
        tools/quake3/q3map2/light_bounce.o \
        tools/quake3/q3map2/light_ydnar.o \
        tools/quake3/q3map2/main.o \
        tools/quake3/q3map2/map.o \
 +      tools/quake3/q3map2/minimap.o \
        tools/quake3/q3map2/mesh.o \
        tools/quake3/q3map2/model.o \
        tools/quake3/q3map2/patch.o \
        tools/quake3/q3map2/vis.o \
        tools/quake3/q3map2/writebsp.o \
        libddslib.$(A) \
 +      libetclib.$(A) \
        libfilematch.$(A) \
        libl_net.$(A) \
        libmathlib.$(A) \
@@@ -601,10 -589,6 +603,10 @@@ libddslib.$(A): CPPFLAGS_EXTRA := -Ilib
  libddslib.$(A): \
        libs/ddslib/ddslib.o \
  
 +libetclib.$(A): CPPFLAGS_EXTRA := -Ilibs
 +libetclib.$(A): \
 +      libs/etclib.o \
 +
  $(INSTALLDIR)/q3data.$(EXE): LIBS_EXTRA := $(LIBS_XML) $(LIBS_GLIB) $(LIBS_ZLIB)
  $(INSTALLDIR)/q3data.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) $(CPPFLAGS_ZLIB) -Itools/quake3/common -Ilibs -Iinclude
  $(INSTALLDIR)/q3data.$(EXE): \
        tools/quake3/common/md4.o \
        tools/quake3/common/scriplib.o \
        tools/quake3/common/trilib.o \
 -      tools/quake3/common/unzip.o \
        tools/quake3/common/vfs.o \
        tools/quake3/common/miniz.o \
        tools/quake3/q3data/3dslib.o \
        tools/quake3/q3data/stripper.o \
        tools/quake3/q3data/video.o \
        libfilematch.$(A) \
 +      libetclib.$(A) \
        libl_net.$(A) \
        libmathlib.$(A) \
        $(if $(findstring $(OS),Win32),icons/q3data.o,) \
@@@ -709,7 -693,6 +711,7 @@@ $(INSTALLDIR)/radiant.$(EXE): 
        radiant/stacktrace.o \
        radiant/surfacedialog.o \
        radiant/texmanip.o \
 +      radiant/textureentry.o \
        radiant/textures.o \
        radiant/texwindow.o \
        radiant/timer.o \
        radiant/xywindow.o \
        libcmdlib.$(A) \
        libgtkutil.$(A) \
 +      libuilib.$(A) \
        libl_net.$(A) \
        libmathlib.$(A) \
        libprofile.$(A) \
@@@ -749,6 -731,8 +751,6 @@@ libgtkutil.$(A): 
        libs/gtkutil/accelerator.o \
        libs/gtkutil/button.o \
        libs/gtkutil/clipboard.o \
 -      libs/gtkutil/closure.o \
 -      libs/gtkutil/container.o \
        libs/gtkutil/cursor.o \
        libs/gtkutil/dialog.o \
        libs/gtkutil/entry.o \
        libs/gtkutil/frame.o \
        libs/gtkutil/glfont.o \
        libs/gtkutil/glwidget.o \
 -      libs/gtkutil/idledraw.o \
        libs/gtkutil/image.o \
        libs/gtkutil/menu.o \
        libs/gtkutil/messagebox.o \
        libs/gtkutil/nonmodal.o \
        libs/gtkutil/paned.o \
 -      libs/gtkutil/pointer.o \
        libs/gtkutil/toolbar.o \
        libs/gtkutil/widget.o \
        libs/gtkutil/window.o \
        libs/gtkutil/xorrectangle.o \
  
 +libuilib.$(A): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) $(CPPFLAGS_GTKGLEXT) -Ilibs -Iinclude
 +libuilib.$(A): \
 +      libs/uilib/uilib.o \
 +
  libxmllib.$(A): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) -Ilibs -Iinclude
  libxmllib.$(A): \
 -      libs/xml/ixml.o \
 -      libs/xml/xmlelement.o \
 -      libs/xml/xmlparser.o \
        libs/xml/xmltextags.o \
 -      libs/xml/xmlwriter.o \
  
  $(INSTALLDIR)/modules/archivezip.$(DLL): LIBS_EXTRA := $(LIBS_ZLIB)
  $(INSTALLDIR)/modules/archivezip.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_ZLIB) -Ilibs -Iinclude
  $(INSTALLDIR)/modules/archivezip.$(DLL): \
        plugins/archivezip/archive.o \
 -      plugins/archivezip/pkzip.o \
        plugins/archivezip/plugin.o \
 -      plugins/archivezip/zlibstream.o \
  
  $(INSTALLDIR)/modules/archivewad.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude
  $(INSTALLDIR)/modules/archivewad.$(DLL): \
        plugins/archivewad/archive.o \
        plugins/archivewad/plugin.o \
 -      plugins/archivewad/wad.o \
  
  $(INSTALLDIR)/modules/archivepak.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude
  $(INSTALLDIR)/modules/archivepak.$(DLL): \
        plugins/archivepak/archive.o \
 -      plugins/archivepak/pak.o \
        plugins/archivepak/plugin.o \
  
 -$(INSTALLDIR)/modules/entity.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude
 +$(INSTALLDIR)/modules/entity.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) -Ilibs -Iinclude
  $(INSTALLDIR)/modules/entity.$(DLL): \
 -      plugins/entity/angle.o \
 -      plugins/entity/angles.o \
 -      plugins/entity/colour.o \
        plugins/entity/doom3group.o \
        plugins/entity/eclassmodel.o \
        plugins/entity/entity.o \
        plugins/entity/group.o \
        plugins/entity/light.o \
        plugins/entity/miscmodel.o \
 -      plugins/entity/model.o \
 -      plugins/entity/modelskinkey.o \
 -      plugins/entity/namedentity.o \
 -      plugins/entity/origin.o \
        plugins/entity/plugin.o \
 -      plugins/entity/rotation.o \
 -      plugins/entity/scale.o \
        plugins/entity/skincache.o \
        plugins/entity/targetable.o \
  
@@@ -811,11 -810,9 +813,11 @@@ $(INSTALLDIR)/modules/image.$(DLL): 
        plugins/image/dds.o \
        plugins/image/image.o \
        plugins/image/jpeg.o \
 +      plugins/image/ktx.o \
        plugins/image/pcx.o \
        plugins/image/tga.o \
        libddslib.$(A) \
 +      libetclib.$(A) \
  
  $(INSTALLDIR)/modules/imageq2.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude
  $(INSTALLDIR)/modules/imageq2.$(DLL): \
@@@ -835,12 -832,7 +837,12 @@@ $(INSTALLDIR)/modules/imagepng.$(DLL): 
  $(INSTALLDIR)/modules/imagepng.$(DLL): \
        plugins/imagepng/plugin.o \
  
 -$(INSTALLDIR)/modules/mapq3.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude
 +$(INSTALLDIR)/modules/imagewebp.$(DLL): LIBS_EXTRA := $(LIBS_WEBP)
 +$(INSTALLDIR)/modules/imagewebp.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_WEBP) -Ilibs -Iinclude
 +$(INSTALLDIR)/modules/imagewebp.$(DLL): \
 +      plugins/imagewebp/plugin.o \
 +
 +$(INSTALLDIR)/modules/mapq3.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) -Ilibs -Iinclude
  $(INSTALLDIR)/modules/mapq3.$(DLL): \
        plugins/mapq3/parse.o \
        plugins/mapq3/plugin.o \
@@@ -1013,6 -1005,23 +1015,6 @@@ $(INSTALLDIR)/plugins/ufoaiplug.$(DLL)
        contrib/ufoaiplug/ufoai_level.o \
        contrib/ufoaiplug/ufoai.o \
  
 -$(INSTALLDIR)/plugins/meshtex.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK)
 -$(INSTALLDIR)/plugins/meshtex.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) -Ilibs -Iinclude
 -$(INSTALLDIR)/plugins/meshtex.$(DLL): \
 -      contrib/meshtex/GeneralFunctionDialog.o \
 -      contrib/meshtex/GenericDialog.o \
 -      contrib/meshtex/GenericMainMenu.o \
 -      contrib/meshtex/GenericPluginUI.o \
 -      contrib/meshtex/GetInfoDialog.o \
 -      contrib/meshtex/MainMenu.o \
 -      contrib/meshtex/MeshEntity.o \
 -      contrib/meshtex/MeshVisitor.o \
 -      contrib/meshtex/PluginModule.o \
 -      contrib/meshtex/PluginRegistration.o \
 -      contrib/meshtex/PluginUI.o \
 -      contrib/meshtex/RefCounted.o \
 -      contrib/meshtex/SetScaleDialog.o \
 -
  $(INSTALLDIR)/plugins/bkgrnd2d.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK)
  $(INSTALLDIR)/plugins/bkgrnd2d.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) -Ilibs -Iinclude
  $(INSTALLDIR)/plugins/bkgrnd2d.$(DLL): \
@@@ -1059,22 -1068,29 +1061,22 @@@ $(INSTALLDIR)/heretic2/h2data.$(EXE): 
  .PHONY: install-data
  install-data: binaries
        $(MKDIR) $(INSTALLDIR)/games
 -      $(FIND) $(INSTALLDIR_BASE)/ -name .svn -exec $(RM_R) {} \; -prune
 -      [ "$(OS)" != "Darwin" ] || $(CP_R) setup/data/osx/NetRadiant.app/* $(INSTALLDIR_BASE)/NetRadiant.app/
 -      DOWNLOAD_GAMEPACKS="$(DOWNLOAD_GAMEPACKS)" GIT="$(GIT)" SVN="$(SVN)" WGET="$(WGET)" RM_R="$(RM_R)" MV="$(MV)" UNZIPPER="$(UNZIPPER)" ECHO="$(ECHO)" SH="$(SH)" CP="$(CP)" CP_R="$(CP_R)" $(SH) install-gamepacks.sh "$(INSTALLDIR)"
 -      $(ECHO) $(RADIANT_MINOR_VERSION) > $(INSTALLDIR)/RADIANT_MINOR
 +      DOWNLOAD_GAMEPACKS="$(DOWNLOAD_GAMEPACKS)" DOWNLOADDIR="$(DOWNLOADDIR)" INSTALLDIR="$(INSTALLDIR)" GIT="$(GIT)" SVN="$(SVN)" WGET="$(WGET)" RM_R="$(RM_R)" MV="$(MV)" UNZIPPER="$(UNZIPPER)" ECHO="$(ECHO)" SH="$(SH)" CP="$(CP)" CP_R="$(CP_R)" $(SH) gamepack-manager
        $(ECHO) $(RADIANT_MAJOR_VERSION) > $(INSTALLDIR)/RADIANT_MAJOR
 +      $(ECHO) $(RADIANT_MINOR_VERSION) > $(INSTALLDIR)/RADIANT_MINOR
 +      $(ECHO) $(RADIANT_PATCH_VERSION) > $(INSTALLDIR)/RADIANT_PATCH
        $(CP_R) setup/data/tools/* $(INSTALLDIR)/
        $(MKDIR) $(INSTALLDIR)/docs
        $(CP_R) docs/* $(INSTALLDIR)/docs/
 -      $(FIND) $(INSTALLDIR_BASE)/ -name .svn -exec $(RM_R) {} \; -prune
  
  .PHONY: install-dll
  ifeq ($(OS),Win32)
  install-dll: binaries
        MKDIR="$(MKDIR)" CP="$(CP)" CAT="$(CAT)" GTKDIR="$(GTKDIR)" WHICHDLL="$(WHICHDLL)" INSTALLDIR="$(INSTALLDIR)" $(SH) $(DLLINSTALL) 
  else
 -ifeq ($(OS),Darwin)
 -install-dll: binaries
 -      EXE="$(EXE)" MACLIBDIR="$(MACLIBDIR)" CP="$(CP)" OTOOL="$(OTOOL)" INSTALLDIR="$(INSTALLDIR)" $(SH) install-dylibs.sh
 -else
  install-dll: binaries
        @$(ECHO) No DLL inclusion implemented for this target.
  endif
 -endif
  
  # release building... NOT for general users
  # these may use tools not in the list that is checked by the build system
diff --combined libs/string/string.h
index ff7dc4536c9245ce116e612534f0d1ff826a49a6,dd67d2aff25513a6192114d292c8f3c6bc842854..e780303b595f81c9ee8270857a1c119234825a49
@@@ -22,8 -22,6 +22,8 @@@
  #if !defined( INCLUDED_STRING_STRING_H )
  #define INCLUDED_STRING_STRING_H
  
 +#include "globaldefs.h"
 +
  /// \file
  /// C-style null-terminated-character-array string library.
  
@@@ -83,7 -81,7 +83,7 @@@ inline bool string_greater( const char
  /// Returns 0 if \p string is lexicographically equal to \p other after converting both to lower-case.
  /// O(n)
  inline int string_compare_nocase( const char* string, const char* other ){
 -#ifdef WIN32
 +#if GDEF_OS_WINDOWS
        return _stricmp( string, other );
  #else
        return strcasecmp( string, other );
@@@ -96,7 -94,7 +96,7 @@@
  /// Treats all ascii characters as lower-case during comparisons.
  /// O(n)
  inline int string_compare_nocase_n( const char* string, const char* other, std::size_t n ){
 -#ifdef WIN32
 +#if GDEF_OS_WINDOWS
        return _strnicmp( string, other, n );
  #else
        return strncasecmp( string, other, n );
@@@ -150,6 -148,11 +150,11 @@@ inline bool string_equal_suffix( const 
        return string_equal_n( s , suffix, string_length( suffix ) );
  }
  
+ inline bool string_equal_suffix_nocase( const char* string, const char* suffix){
+       const char *s = string + string_length( string ) - string_length( suffix );
+       return string_equal_nocase_n( s , suffix, string_length( suffix ) );
+ }
  /// \brief Copies \p other into \p string and returns \p string.
  /// Assumes that the space allocated for \p string is at least string_length(other) + 1.
  /// O(n)
@@@ -196,14 -199,6 +201,14 @@@ inline char* string_new( std::size_t le
        return string_new( length, allocator );
  }
  
 +/// \brief Allocates a new buffer large enough to hold two concatenated strings and fills it with strings.
 +inline char* string_new_concat( const char* a, const char* b ){
 +      char* str = string_new( string_length( a ) + string_length( b ) );
 +      strcpy( str, a );
 +      strcat( str, b );
 +      return str;
 +}
 +
  /// \brief Deallocates the \p buffer large enough to hold \p length characters.
  inline void string_release( char* string, std::size_t length ){
        DefaultAllocator<char> allocator;
diff --combined radiant/build.cpp
index 5e86dc85037db67a52d44290298e23984dd1eb50,baa39568a68851be40f521accb150fd0d0d9a91b..3a524a76465f7fa727d966f19eab7f445b7a820f
@@@ -22,7 -22,6 +22,7 @@@
  #include "build.h"
  #include "debugging/debugging.h"
  
 +#include <gtk/gtk.h>
  #include <map>
  #include <list>
  #include "stream/stringstream.h"
@@@ -56,7 -55,6 +56,7 @@@ const char* build_get_variable( const c
  class Evaluatable
  {
  public:
 +virtual ~Evaluatable() = default;
  virtual void evaluate( StringBuffer& output ) = 0;
  virtual void exportXML( XMLImporter& importer ) = 0;
  };
@@@ -173,7 -171,6 +173,7 @@@ void exportXML( XMLImporter& importer )
  class XMLElementParser : public TextOutputStream
  {
  public:
 +virtual ~XMLElementParser() = default;
  virtual XMLElementParser& pushElement( const XMLElement& element ) = 0;
  virtual void popElement( const char* name ) = 0;
  };
@@@ -296,7 -293,7 +296,7 @@@ void popElement( const char* name )
  };
  
  typedef std::pair<CopiedString, Build> BuildPair;
 -#define SEPARATOR_STRING "-"
 +const char *SEPARATOR_STRING = "-";
  static bool is_separator( const BuildPair &p ){
        if ( !string_equal( p.first.c_str(), SEPARATOR_STRING ) ) {
                return false;
  }
  
  
 -class BuildPairEqual
 -{
 -const char* m_name;
 -public:
 -BuildPairEqual( const char* name ) : m_name( name ){
 -}
 -bool operator()( const BuildPair& self ) const {
 -      return string_equal( self.first.c_str(), m_name );
 -}
 -};
 -
  typedef std::list<BuildPair> Project;
  
  Project::iterator Project_find( Project& project, const char* name ){
 -      return std::find_if( project.begin(), project.end(), BuildPairEqual( name ) );
 +      return std::find_if(project.begin(), project.end(), [&](const BuildPair &self) {
 +              return string_equal(self.first.c_str(), name);
 +      });
  }
  
  Project::iterator Project_find( Project& project, std::size_t index ){
@@@ -627,46 -633,59 +627,46 @@@ void build_commands_write( const char* 
  
  
  #include <gdk/gdkkeysyms.h>
 -#include <gtk/gtkmain.h>
 -#include <gtk/gtkbox.h>
 -#include <gtk/gtktable.h>
 -#include <gtk/gtktreeview.h>
 -#include <gtk/gtkcellrenderertext.h>
 -#include <gtk/gtktreeselection.h>
 -#include <gtk/gtkliststore.h>
 -#include <gtk/gtkscrolledwindow.h>
  
  #include "gtkutil/dialog.h"
  #include "gtkutil/closure.h"
  #include "gtkutil/window.h"
  #include "gtkdlgs.h"
  
 -void Build_refreshMenu( GtkMenu* menu );
 +void Build_refreshMenu( ui::Menu menu );
  
  
 -void BSPCommandList_Construct( GtkListStore* store, Project& project ){
 -      gtk_list_store_clear( store );
 +void BSPCommandList_Construct( ui::ListStore store, Project& project ){
 +      store.clear();
  
        for ( Project::iterator i = project.begin(); i != project.end(); ++i )
        {
 -              const char* buildName = ( *i ).first.c_str();
 -
 -              GtkTreeIter buildIter;
 -              gtk_list_store_append( store, &buildIter );
 -              gtk_list_store_set( store, &buildIter, 0, const_cast<char*>( buildName ), -1 );
 +              store.append(0, (*i).first.c_str());
        }
  
 -      GtkTreeIter lastIter;
 -      gtk_list_store_append( store, &lastIter );
 +      store.append();
  }
  
  class ProjectList
  {
  public:
  Project& m_project;
 -GtkListStore* m_store;
 +ui::ListStore m_store{ui::null};
  GtkWidget* m_buildView;
  bool m_changed;
  ProjectList( Project& project ) : m_project( project ), m_changed( false ){
  }
  };
  
 -gboolean project_cell_edited( GtkCellRendererText* cell, gchar* path_string, gchar* new_text, ProjectList* projectList ){
 +gboolean project_cell_edited(ui::CellRendererText cell, gchar* path_string, gchar* new_text, ProjectList* projectList ){
        Project& project = projectList->m_project;
  
 -      GtkTreePath* path = gtk_tree_path_new_from_string( path_string );
 +      auto path = ui::TreePath( path_string );
  
        ASSERT_MESSAGE( gtk_tree_path_get_depth( path ) == 1, "invalid path length" );
  
        GtkTreeIter iter;
 -      gtk_tree_model_get_iter( GTK_TREE_MODEL( projectList->m_store ), &iter, path );
 +      gtk_tree_model_get_iter(projectList->m_store, &iter, path );
  
        Project::iterator i = Project_find( project, gtk_tree_path_get_indices( path )[0] );
        if ( i != project.end() ) {
                project.push_back( Project::value_type( new_text, Build() ) );
  
                gtk_list_store_set( projectList->m_store, &iter, 0, new_text, -1 );
 -              GtkTreeIter lastIter;
 -              gtk_list_store_append( projectList->m_store, &lastIter );
 +              projectList->m_store.append();
                //make command field activatable
                g_signal_emit_by_name( G_OBJECT( gtk_tree_view_get_selection( GTK_TREE_VIEW( projectList->m_buildView ) ) ), "changed" );
        }
        return FALSE;
  }
  
 -gboolean project_key_press( GtkWidget* widget, GdkEventKey* event, ProjectList* projectList ){
 +gboolean project_key_press( ui::TreeView widget, GdkEventKey* event, ProjectList* projectList ){
        Project& project = projectList->m_project;
  
 -      if ( event->keyval == GDK_Delete ) {
 -              GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( widget ) );
 +      if ( event->keyval == GDK_KEY_Delete ) {
 +              auto selection = ui::TreeSelection::from(gtk_tree_view_get_selection(widget));
                GtkTreeIter iter;
                GtkTreeModel* model;
                if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) {
 -                      GtkTreePath* path = gtk_tree_model_get_path( model, &iter );
 +                      auto path = gtk_tree_model_get_path( model, &iter );
                        Project::iterator x = Project_find( project, gtk_tree_path_get_indices( path )[0] );
                        gtk_tree_path_free( path );
  
  
  Build* g_current_build = 0;
  
 -gboolean project_selection_changed( GtkTreeSelection* selection, GtkListStore* store ){
 +gboolean project_selection_changed( ui::TreeSelection selection, ui::ListStore store ){
        Project& project = g_build_project;
  
 -      gtk_list_store_clear( store );
 +      store.clear();
  
        GtkTreeIter iter;
        GtkTreeModel* model;
        if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) {
 -              GtkTreePath* path = gtk_tree_model_get_path( model, &iter );
 +              auto path = gtk_tree_model_get_path( model, &iter );
                Project::iterator x = Project_find( project, gtk_tree_path_get_indices( path )[0] );
                gtk_tree_path_free( path );
  
  
                        for ( Build::iterator i = build.begin(); i != build.end(); ++i )
                        {
 -                              GtkTreeIter commandIter;
 -                              gtk_list_store_append( store, &commandIter );
 -                              gtk_list_store_set( store, &commandIter, 0, const_cast<char*>( ( *i ).c_str() ), -1 );
 +                              store.append(0, (*i).c_str());
                        }
 -                      GtkTreeIter lastIter;
 -                      gtk_list_store_append( store, &lastIter );
 +                      store.append();
                }
                else
                {
        return FALSE;
  }
  
 -gboolean commands_cell_edited( GtkCellRendererText* cell, gchar* path_string, gchar* new_text, GtkListStore* store ){
 +gboolean commands_cell_edited(ui::CellRendererText cell, gchar* path_string, gchar* new_text, ui::ListStore store ){
        if ( g_current_build == 0 ) {
                return FALSE;
        }
        Build& build = *g_current_build;
  
 -      GtkTreePath* path = gtk_tree_path_new_from_string( path_string );
 +      auto path = ui::TreePath( path_string );
  
        ASSERT_MESSAGE( gtk_tree_path_get_depth( path ) == 1, "invalid path length" );
  
        GtkTreeIter iter;
 -      gtk_tree_model_get_iter( GTK_TREE_MODEL( store ), &iter, path );
 +      gtk_tree_model_get_iter(store, &iter, path );
  
        Build::iterator i = Build_find( build, gtk_tree_path_get_indices( path )[0] );
        if ( i != build.end() ) {
  
                gtk_list_store_set( store, &iter, 0, new_text, -1 );
  
 -              GtkTreeIter lastIter;
 -              gtk_list_store_append( store, &lastIter );
 +              store.append();
        }
  
        gtk_tree_path_free( path );
        return FALSE;
  }
  
 -gboolean commands_key_press( GtkWidget* widget, GdkEventKey* event, GtkListStore* store ){
 +gboolean commands_key_press( ui::TreeView widget, GdkEventKey* event, ui::ListStore store ){
        if ( g_current_build == 0 ) {
                return FALSE;
        }
        Build& build = *g_current_build;
  
 -      if ( event->keyval == GDK_Delete ) {
 -              GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( widget ) );
 +      if ( event->keyval == GDK_KEY_Delete ) {
 +              auto selection = gtk_tree_view_get_selection(widget );
                GtkTreeIter iter;
                GtkTreeModel* model;
                if ( gtk_tree_selection_get_selected( selection, &model, &iter ) ) {
 -                      GtkTreePath* path = gtk_tree_model_get_path( model, &iter );
 +                      auto path = gtk_tree_model_get_path( model, &iter );
                        Build::iterator i = Build_find( build, gtk_tree_path_get_indices( path )[0] );
                        gtk_tree_path_free( path );
  
  }
  
  
 -GtkWindow* BuildMenuDialog_construct( ModalDialog& modal, ProjectList& projectList ){
 -      GtkWindow* window = create_dialog_window( MainFrame_getWindow(), "Build Menu", G_CALLBACK( dialog_delete_callback ), &modal, -1, 400 );
 -
 -      GtkWidget* buildView = 0;
 +ui::Window BuildMenuDialog_construct( ModalDialog& modal, ProjectList& projectList ){
 +      ui::Window window = MainFrame_getWindow().create_dialog_window("Build Menu", G_CALLBACK(dialog_delete_callback ), &modal, -1, 400 );
  
        {
 -              GtkTable* table1 = create_dialog_table( 2, 2, 4, 4, 4 );
 -              gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( table1 ) );
 +              auto table1 = create_dialog_table( 2, 2, 4, 4, 4 );
 +              window.add(table1);
                {
 -                      GtkVBox* vbox = create_dialog_vbox( 4 );
 -                      gtk_table_attach( table1, GTK_WIDGET( vbox ), 1, 2, 0, 1,
 -                                                        (GtkAttachOptions) ( GTK_FILL ),
 -                                                        (GtkAttachOptions) ( GTK_FILL ), 0, 0 );
 +                      auto vbox = create_dialog_vbox( 4 );
 +            table1.attach(vbox, {1, 2, 0, 1}, {GTK_FILL, GTK_FILL});
                        {
 -                              GtkButton* button = create_dialog_button( "OK", G_CALLBACK( dialog_button_ok ), &modal );
 -                              gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
 +                              auto button = create_dialog_button( "OK", G_CALLBACK( dialog_button_ok ), &modal );
 +                              vbox.pack_start( button, FALSE, FALSE, 0 );
                        }
                        {
 -                              GtkButton* button = create_dialog_button( "Cancel", G_CALLBACK( dialog_button_cancel ), &modal );
 -                              gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
 +                              auto button = create_dialog_button( "Cancel", G_CALLBACK( dialog_button_cancel ), &modal );
 +                              vbox.pack_start( button, FALSE, FALSE, 0 );
                        }
                }
 +              auto buildViewStore = ui::ListStore::from(gtk_list_store_new( 1, G_TYPE_STRING ));
 +              auto buildView = ui::TreeView( ui::TreeModel::from( buildViewStore._handle ));
                {
 -                      GtkFrame* frame = create_dialog_frame( "Build menu" );
 -                      gtk_table_attach( table1, GTK_WIDGET( frame ), 0, 1, 0, 1,
 -                                                        (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
 -                                                        (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 );
 +                      auto frame = create_dialog_frame( "Build menu" );
 +            table1.attach(frame, {0, 1, 0, 1});
                        {
 -                              GtkScrolledWindow* scr = create_scrolled_window( GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4 );
 -                              gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( scr ) );
 +                              auto scr = create_scrolled_window( ui::Policy::NEVER, ui::Policy::AUTOMATIC, 4 );
 +                              frame.add(scr);
  
                                {
 -                                      GtkListStore* store = gtk_list_store_new( 1, G_TYPE_STRING );
 +                                      auto view = buildView;
 +                                      auto store = buildViewStore;
 +                                      gtk_tree_view_set_headers_visible(view, FALSE );
  
 -                                      GtkWidget* view = gtk_tree_view_new_with_model( GTK_TREE_MODEL( store ) );
 -                                      gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( view ), FALSE );
 -
 -                                      GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
 +                                      auto renderer = ui::CellRendererText(ui::New);
                                        object_set_boolean_property( G_OBJECT( renderer ), "editable", TRUE );
 -                                      g_signal_connect( renderer, "edited", G_CALLBACK( project_cell_edited ), &projectList );
 +                                      renderer.connect("edited", G_CALLBACK( project_cell_edited ), &projectList );
  
 -                                      GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes( "", renderer, "text", 0, 0 );
 -                                      gtk_tree_view_append_column( GTK_TREE_VIEW( view ), column );
 +                                      auto column = ui::TreeViewColumn( "", renderer, {{"text", 0}} );
 +                                      gtk_tree_view_append_column(view, column );
  
 -                                      GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( view ) );
 +                                      auto selection = gtk_tree_view_get_selection(view );
                                        gtk_tree_selection_set_mode( selection, GTK_SELECTION_BROWSE );
  
 -                                      gtk_widget_show( view );
 +                                      view.show();
  
 -                                      buildView = view;
                                        projectList.m_buildView = buildView;
                                        projectList.m_store = store;
 -                                      gtk_container_add( GTK_CONTAINER( scr ), view );
 +                                      scr.add(view);
  
 -                                      g_signal_connect( G_OBJECT( view ), "key_press_event", G_CALLBACK( project_key_press ), &projectList );
 +                                      view.connect( "key_press_event", G_CALLBACK( project_key_press ), &projectList );
  
 -                                      g_object_unref( G_OBJECT( store ) );
 +                                      store.unref();
                                }
                        }
                }
                {
 -                      GtkFrame* frame = create_dialog_frame( "Commandline" );
 -                      gtk_table_attach( table1, GTK_WIDGET( frame ), 0, 1, 1, 2,
 -                                                        (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
 -                                                        (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), 0, 0 );
 +                      auto frame = create_dialog_frame( "Commandline" );
 +            table1.attach(frame, {0, 1, 1, 2});
                        {
 -                              GtkScrolledWindow* scr = create_scrolled_window( GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4 );
 -                              gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( scr ) );
 +                              auto scr = create_scrolled_window( ui::Policy::NEVER, ui::Policy::AUTOMATIC, 4 );
 +                              frame.add(scr);
  
                                {
 -                                      GtkListStore* store = gtk_list_store_new( 1, G_TYPE_STRING );
 +                                      auto store = ui::ListStore::from(gtk_list_store_new( 1, G_TYPE_STRING ));
  
 -                                      GtkWidget* view = gtk_tree_view_new_with_model( GTK_TREE_MODEL( store ) );
 -                                      gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( view ), FALSE );
 +                                      auto view = ui::TreeView(ui::TreeModel::from( store._handle ));
 +                                      gtk_tree_view_set_headers_visible(view, FALSE );
  
 -                                      GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
 +                                      auto renderer = ui::CellRendererText(ui::New);
                                        object_set_boolean_property( G_OBJECT( renderer ), "editable", TRUE );
 -                                      g_signal_connect( renderer, "edited", G_CALLBACK( commands_cell_edited ), store );
 +                                      renderer.connect( "edited", G_CALLBACK( commands_cell_edited ), store );
  
 -                                      GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes( "", renderer, "text", 0, 0 );
 -                                      gtk_tree_view_append_column( GTK_TREE_VIEW( view ), column );
 +                                      auto column = ui::TreeViewColumn( "", renderer, {{"text", 0}} );
 +                                      gtk_tree_view_append_column(view, column );
  
 -                                      GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( view ) );
 +                                      auto selection = gtk_tree_view_get_selection(view );
                                        gtk_tree_selection_set_mode( selection, GTK_SELECTION_BROWSE );
  
 -                                      gtk_widget_show( view );
 +                                      view.show();
  
 -                                      gtk_container_add( GTK_CONTAINER( scr ), view );
 +                                      scr.add(view);
  
 -                                      g_object_unref( G_OBJECT( store ) );
 +                                      store.unref();
  
 -                                      g_signal_connect( G_OBJECT( view ), "key_press_event", G_CALLBACK( commands_key_press ), store );
 +                                      view.connect( "key_press_event", G_CALLBACK( commands_key_press ), store );
  
 -                                      g_signal_connect( G_OBJECT( gtk_tree_view_get_selection( GTK_TREE_VIEW( buildView ) ) ), "changed", G_CALLBACK( project_selection_changed ), store );
 +                                      auto sel = ui::TreeSelection::from(gtk_tree_view_get_selection(buildView ));
 +                                      sel.connect( "changed", G_CALLBACK( project_selection_changed ), store );
                                }
                        }
                }
  namespace
  {
  CopiedString g_buildMenu;
+ CopiedString g_lastExecutedBuild;
  }
  
  void LoadBuildMenu();
@@@ -932,7 -964,7 +933,7 @@@ void DoBuildMenu()
  
        ProjectList projectList( g_build_project );
  
 -      GtkWindow* window = BuildMenuDialog_construct( modal, projectList );
 +      ui::Window window = BuildMenuDialog_construct( modal, projectList );
  
        if ( modal_dialog_show( window, modal ) == eIDCANCEL ) {
                build_commands_clear();
                g_build_changed = true;
        }
  
 -      gtk_widget_destroy( GTK_WIDGET( window ) );
 +      window.destroy();
  }
  
  
  #include "preferences.h"
  #include "qe3.h"
  
 -typedef struct _GtkMenuItem GtkMenuItem;
 -
  class BuildMenuItem
  {
  const char* m_name;
  public:
 -GtkMenuItem* m_item;
 -BuildMenuItem( const char* name, GtkMenuItem* item )
 +ui::MenuItem m_item;
 +BuildMenuItem( const char* name, ui::MenuItem item )
        : m_name( name ), m_item( item ){
  }
  void run(){
+       g_lastExecutedBuild = m_name;
        RunBSP( m_name );
  }
 -typedef MemberCaller<BuildMenuItem, &BuildMenuItem::run> RunCaller;
 +typedef MemberCaller<BuildMenuItem, void(), &BuildMenuItem::run> RunCaller;
  };
  
  typedef std::list<BuildMenuItem> BuildMenuItems;
  BuildMenuItems g_BuildMenuItems;
  
  
 -GtkMenu* g_bsp_menu;
 +ui::Menu g_bsp_menu{ui::null};
  
 -void Build_constructMenu( GtkMenu* menu ){
 +void Build_constructMenu( ui::Menu menu ){
        for ( Project::iterator i = g_build_project.begin(); i != g_build_project.end(); ++i )
        {
 -              g_BuildMenuItems.push_back( BuildMenuItem( ( *i ).first.c_str(), 0 ) );
 +              g_BuildMenuItems.push_back( BuildMenuItem( ( *i ).first.c_str(), ui::MenuItem(ui::null) ) );
                if ( is_separator( *i ) ) {
                        g_BuildMenuItems.back().m_item = menu_separator( menu );
                }
  }
  
  
 -void Build_refreshMenu( GtkMenu* menu ){
 -      for ( BuildMenuItems::iterator i = g_BuildMenuItems.begin(); i != g_BuildMenuItems.end(); ++i )
 +void Build_refreshMenu( ui::Menu menu ){
 +      for (auto i = g_BuildMenuItems.begin(); i != g_BuildMenuItems.end(); ++i )
        {
 -              gtk_container_remove( GTK_CONTAINER( menu ), GTK_WIDGET( ( *i ).m_item ) );
 +              menu.remove(ui::MenuItem(i->m_item));
        }
  
        g_BuildMenuItems.clear();
@@@ -1030,9 -1065,19 +1032,19 @@@ void SaveBuildMenu()
  #include "stringio.h"
  
  void BuildMenu_Construct(){
 -      GlobalPreferenceSystem().registerPreference( "BuildMenu", CopiedStringImportStringCaller( g_buildMenu ), CopiedStringExportStringCaller( g_buildMenu ) );
 +      GlobalPreferenceSystem().registerPreference( "BuildMenu", make_property_string( g_buildMenu ) );
        LoadBuildMenu();
  }
  void BuildMenu_Destroy(){
        SaveBuildMenu();
  }
+ void Build_runRecentExecutedBuild(){
+       if( g_lastExecutedBuild.empty() ){
+               g_BuildMenuItems.begin()->run();
+       }
+       else{
+               RunBSP( g_lastExecutedBuild.c_str() );
+       }
+ }
diff --combined radiant/build.h
index 4e49414637fa0a292adc1521ce7040143ef7dcb5,39024fad1e21b91808f0a98ca7d051f5f3e00c49..f6cfe9c309231e28c74655a6c5e386d91fa1891c
@@@ -18,8 -18,6 +18,8 @@@
     along with GtkRadiant; if not, write to the Free Software
     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   */
 +#include <uilib/uilib.h>
 +
  #if !defined( INCLUDED_BUILD_H )
  #define INCLUDED_BUILD_H
  
@@@ -38,8 -36,10 +38,9 @@@ void DoBuildMenu()
  void BuildMenu_Construct();
  void BuildMenu_Destroy();
  
 -typedef struct _GtkMenu GtkMenu;
 -void Build_constructMenu( GtkMenu* menu );
 -extern GtkMenu* g_bsp_menu;
 +void Build_constructMenu( ui::Menu menu );
 +extern ui::Menu g_bsp_menu;
  
+ void Build_runRecentExecutedBuild();
  
  #endif
diff --combined radiant/csg.cpp
index b9ebfcd035402b02eafd1fc791d857cbdfad8636,5b9eb44a2c52e9f6861c968c475d5d78c51410bd..2b7d82be09393aa61933a59c37c0808761a19925
@@@ -29,7 -29,6 +29,7 @@@
  #include "brushmanip.h"
  #include "brushnode.h"
  #include "grid.h"
 +
  /*
  void Face_makeBrush( Face& face, const Brush& brush, brush_vector_t& out, float offset ){
        if ( face.contributes() ) {
@@@ -369,7 -368,6 +369,7 @@@ public
  BrushGatherSelected( brush_vector_t& brushlist )
        : m_brushlist( brushlist ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.top().get().visible() ) {
                Brush* brush = Node_getBrush( path.top() );
@@@ -473,9 -471,11 +473,9 @@@ class Dereferenc
  {
  const Functor& functor;
  public:
 -typedef typename RemoveReference<typename Functor::first_argument_type>::type* first_argument_type;
 -typedef typename Functor::result_type result_type;
  Dereference( const Functor& functor ) : functor( functor ){
  }
 -result_type operator()( first_argument_type firstArgument ) const {
 +get_result_type<Functor> operator()( typename RemoveReference<get_argument<Functor, 0>>::type *firstArgument ) const {
        return functor( *firstArgument );
  }
  };
@@@ -497,14 -497,15 +497,14 @@@ Face* Brush_findIf( const Brush& brush
  template<typename Caller>
  class BindArguments1
  {
 -typedef typename Caller::second_argument_type FirstBound;
 +typedef get_argument<Caller, 1> FirstBound;
  FirstBound firstBound;
  public:
 -typedef typename Caller::result_type result_type;
 -typedef typename Caller::first_argument_type first_argument_type;
  BindArguments1( FirstBound firstBound )
        : firstBound( firstBound ){
  }
 -result_type operator()( first_argument_type firstArgument ) const {
 +
 +get_result_type<Caller> operator()( get_argument<Caller, 0> firstArgument ) const {
        return Caller::call( firstArgument, firstBound );
  }
  };
  template<typename Caller>
  class BindArguments2
  {
 -typedef typename Caller::second_argument_type FirstBound;
 -typedef typename Caller::third_argument_type SecondBound;
 +typedef get_argument<Caller, 1> FirstBound;
 +typedef get_argument<Caller, 2> SecondBound;
  FirstBound firstBound;
  SecondBound secondBound;
  public:
 -typedef typename Caller::result_type result_type;
 -typedef typename Caller::first_argument_type first_argument_type;
  BindArguments2( FirstBound firstBound, SecondBound secondBound )
        : firstBound( firstBound ), secondBound( secondBound ){
  }
 -result_type operator()( first_argument_type firstArgument ) const {
 +
 +get_result_type<Caller> operator()( get_argument<Caller, 0> firstArgument ) const {
        return Caller::call( firstArgument, firstBound, secondBound );
  }
  };
@@@ -534,8 -536,8 +534,8 @@@ BindArguments2<Caller> bindArguments( c
  inline bool Face_testPlane( const Face& face, const Plane3& plane, bool flipped ){
        return face.contributes() && !Winding_TestPlane( face.getWinding(), plane, flipped );
  }
 -typedef Function3<const Face&, const Plane3&, bool, bool, Face_testPlane> FaceTestPlane;
  
 +typedef Function<bool ( const Face &, const Plane3 &, bool ), Face_testPlane> FaceTestPlane;
  
  
  /// \brief Returns true if
@@@ -612,14 -614,12 +612,14 @@@ public
  SubtractBrushesFromUnselected( const brush_vector_t& brushlist, std::size_t& before, std::size_t& after )
        : m_brushlist( brushlist ), m_before( before ), m_after( after ), m_eraseParent( false ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.top().get().visible() ) {
                return true;
        }
        return false;
  }
 +
  void post( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.top().get().visible() ) {
                Brush* brush = Node_getBrush( path.top() );
                                                delete ( *i );
                                        }
                                }
+                               scene::Node& parent = path.parent();
                                Path_deleteTop( path );
-                               if( Node_getTraversable( path.parent() )->empty() ){
+                               if( Node_getTraversable( parent )->empty() ){
                                        m_eraseParent = true;
                                }
                        }
@@@ -725,11 -726,9 +726,11 @@@ public
  BrushSplitByPlaneSelected( const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection, EBrushSplit split )
        : m_p0( p0 ), m_p1( p1 ), m_p2( p2 ), m_shader( shader ), m_projection( projection ), m_split( split ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        return true;
  }
 +
  void post( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.top().get().visible() ) {
                Brush* brush = Node_getBrush( path.top() );
@@@ -793,7 -792,6 +794,7 @@@ public
  BrushInstanceSetClipPlane( const Plane3& plane )
        : m_plane( plane ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        BrushInstance* brush = Instance_getBrush( instance );
        if ( brush != 0
@@@ -959,8 -957,7 +960,8 @@@ void CSG_Merge( void )
  struct CSGToolDialog
  {
        GtkSpinButton* spin;
 -      GtkWindow *window;
 +      bool allocated{false};
 +      ui::Window window{ui::null};
        GtkToggleButton *radXYZ, *radX, *radY, *radZ, *caulk, *removeInner;
  };
  
@@@ -1084,10 -1081,8 +1085,10 @@@ static gboolean CSGdlg_delete( GtkWidge
  }
  
  void CSG_Tool(){
 -      if ( g_csgtool_dialog.window == NULL ) {
 -              g_csgtool_dialog.window = create_dialog_window( MainFrame_getWindow(), "CSG Tool", G_CALLBACK( CSGdlg_delete ), &g_csgtool_dialog );
 +      // FIXME: there is probably improvements to do less raw GTK stuff, more GTK wrapper
 +      if ( !g_csgtool_dialog.allocated ) {
 +              g_csgtool_dialog.allocated = true;
 +              g_csgtool_dialog.window = MainFrame_getWindow().create_dialog_window( "CSG Tool", G_CALLBACK( CSGdlg_delete ), &g_csgtool_dialog );
                gtk_window_set_type_hint( g_csgtool_dialog.window, GDK_WINDOW_TYPE_HINT_UTILITY );
  
                //GtkAccelGroup* accel = gtk_accel_group_new();
                global_accel_connect_window( g_csgtool_dialog.window );
  
                {
 -                      GtkHBox* hbox = create_dialog_hbox( 4, 4 );
 +                      auto hbox = create_dialog_hbox( 4, 4 );
                        gtk_container_add( GTK_CONTAINER( g_csgtool_dialog.window ), GTK_WIDGET( hbox ) );
                        {
 -                              GtkTable* table = create_dialog_table( 3, 8, 4, 4 );
 +                              auto table = create_dialog_table( 3, 8, 4, 4 );
                                gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( table ), TRUE, TRUE, 0 );
                                {
                                        //GtkWidget* label = gtk_label_new( "<->" );
                                        //gtk_widget_show( label );
 -                                      GtkWidget* button = gtk_button_new_with_label( "Grid->" );
 -                                      gtk_table_attach( table, button, 0, 1, 0, 1,
 -                                                                        (GtkAttachOptions) ( 0 ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 -                                      gtk_widget_show( button );
 +                                      auto button = ui::Button( "Grid->" );
 +                                      table.attach( button, {0, 1, 0, 1}, {0, 0} );
 +                                      button.show();
                                        g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_grid2spin ), &g_csgtool_dialog );
                                }
                                {
                                }
                                {
                                        GtkWidget* button = gtk_toggle_button_new();
 -                                      button_set_icon( GTK_BUTTON( button ), "f-caulk.png" );
 +                                      auto ubutton = ui::Button::from( button );
 +                                      button_set_icon( ubutton, "f-caulk.png" );
                                        gtk_button_set_relief( GTK_BUTTON( button ), GTK_RELIEF_NONE );
 -                                      gtk_table_attach( table, button, 6, 7, 0, 1,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      table.attach( ubutton, { 6, 7, 0, 1 }, { GTK_EXPAND, 0 } );
                                        gtk_widget_set_tooltip_text( button, "Caulk some faces" );
                                        gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( button ), TRUE );
 -                                      gtk_widget_show( button );
 +                                      ubutton.show();
                                        g_csgtool_dialog.caulk = GTK_TOGGLE_BUTTON( button );
                                }
                                {
                                        GtkWidget* button = gtk_toggle_button_new();
 -                                      button_set_icon( GTK_BUTTON( button ), "csgtool_removeinner.png" );
 +                                      auto ubutton = ui::Button::from( button );
 +                                      button_set_icon( ubutton, "csgtool_removeinner.png" );
                                        gtk_button_set_relief( GTK_BUTTON( button ), GTK_RELIEF_NONE );
 -                                      gtk_table_attach( table, button, 7, 8, 0, 1,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      table.attach( ubutton, { 7, 8, 0, 1 }, { GTK_EXPAND, 0 } );
                                        gtk_widget_set_tooltip_text( button, "Remove inner brush" );
                                        gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( button ), TRUE );
 -                                      gtk_widget_show( button );
 +                                      ubutton.show();
                                        g_csgtool_dialog.removeInner = GTK_TOGGLE_BUTTON( button );
                                }
                                {
                                }
                                {
                                        GtkWidget* button = gtk_button_new();
 -                                      button_set_icon( GTK_BUTTON( button ), "csgtool_shrink.png" );
 -                                      gtk_table_attach( table, button, 0, 1, 2, 3,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      auto ubutton = ui::Button::from( button );
 +                                      button_set_icon( ubutton, "csgtool_shrink.png" );
 +                                      table.attach( ubutton, { 0, 1, 2, 3 }, { GTK_EXPAND, 0 } );
                                        gtk_widget_set_tooltip_text( button, "Shrink brush" );
 -                                      gtk_widget_show( button );
 +                                      ubutton.show();
                                        g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_BrushShrink ), &g_csgtool_dialog );
                                }
                                {
                                        GtkWidget* button = gtk_button_new();
 -                                      button_set_icon( GTK_BUTTON( button ), "csgtool_expand.png" );
 -                                      gtk_table_attach( table, button, 1, 2, 2, 3,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      auto ubutton = ui::Button::from( button );
 +                                      button_set_icon( ubutton, "csgtool_expand.png" );
 +                                      table.attach( ubutton, { 1, 2, 2, 3 }, { GTK_EXPAND, 0 } );
                                        gtk_widget_set_tooltip_text( button, "Expand brush" );
 -                                      gtk_widget_show( button );
 +                                      ubutton.show();
                                        g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_BrushExpand ), &g_csgtool_dialog );
                                }
                                {
                                        GtkWidget* button = gtk_button_new();
 -                                      button_set_icon( GTK_BUTTON( button ), "csgtool_diagonal.png" );
 -                                      gtk_table_attach( table, button, 3, 4, 2, 3,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      auto ubutton = ui::Button::from( button );
 +                                      button_set_icon( ubutton, "csgtool_diagonal.png" );
 +                                      table.attach( ubutton, { 3, 4, 2, 3 }, { GTK_EXPAND, 0 } );
                                        gtk_widget_set_tooltip_text( button, "Hollow::diagonal joints" );
 -                                      gtk_widget_show( button );
 +                                      ubutton.show();
                                        g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_HollowDiag ), &g_csgtool_dialog );
                                }
                                {
                                        GtkWidget* button = gtk_button_new();
 -                                      button_set_icon( GTK_BUTTON( button ), "csgtool_wrap.png" );
 -                                      gtk_table_attach( table, button, 4, 5, 2, 3,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      auto ubutton = ui::Button::from( button );
 +                                      button_set_icon( ubutton, "csgtool_wrap.png" );
 +                                      table.attach( ubutton, { 4, 5, 2, 3 }, { GTK_EXPAND, 0 } );
                                        gtk_widget_set_tooltip_text( button, "Hollow::warp" );
 -                                      gtk_widget_show( button );
 +                                      ubutton.show();
                                        g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_HollowWrap ), &g_csgtool_dialog );
                                }
                                {
                                        GtkWidget* button = gtk_button_new();
 -                                      button_set_icon( GTK_BUTTON( button ), "csgtool_extrude.png" );
 -                                      gtk_table_attach( table, button, 5, 6, 2, 3,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      auto ubutton = ui::Button::from( button );
 +                                      button_set_icon( ubutton, "csgtool_extrude.png" );
 +                                      table.attach( ubutton, { 5, 6, 2, 3 }, { GTK_EXPAND, 0 } );
                                        gtk_widget_set_tooltip_text( button, "Hollow::extrude faces" );
 -                                      gtk_widget_show( button );
 +                                      ubutton.show();
                                        g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_HollowExtrude ), &g_csgtool_dialog );
                                }
                                {
                                        GtkWidget* button = gtk_button_new();
 -                                      button_set_icon( GTK_BUTTON( button ), "csgtool_pull.png" );
 -                                      gtk_table_attach( table, button, 6, 7, 2, 3,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      auto ubutton = ui::Button::from( button );
 +                                      button_set_icon( ubutton, "csgtool_pull.png" );
 +                                      table.attach( ubutton, { 6, 7, 2, 3 }, { GTK_EXPAND, 0 } );
                                        gtk_widget_set_tooltip_text( button, "Hollow::pull faces" );
 -                                      gtk_widget_show( button );
 +                                      ubutton.show();
                                        g_signal_connect( G_OBJECT( button ), "clicked", G_CALLBACK( CSGdlg_HollowPull ), &g_csgtool_dialog );
                                }
  
diff --combined radiant/environment.cpp
index a84a7d42bc7ba0b10fc25b465aa2098fbff582ae,ad0edd774b526451f29458a48bdb9daf85533043..a1a13b8686442e5faf01f6fdb7582ec56ae502cd
@@@ -20,7 -20,6 +20,7 @@@
   */
  
  #include "environment.h"
 +#include "globaldefs.h"
  
  #include "stream/textstream.h"
  #include "string/string.h"
  #include "cmdlib.h"
  
  int g_argc;
 -char** g_argv;
 +char const** g_argv;
  
 -void args_init( int argc, char* argv[] ){
 +void args_init( int argc, char const* argv[] ){
        int i, j, k;
  
        for ( i = 1; i < argc; i++ )
        {
                for ( k = i; k < argc; k++ )
 +              {
                        if ( argv[k] != 0 ) {
                                break;
                        }
 +              }
  
                if ( k > i ) {
                        k -= i;
                        for ( j = i + k; j < argc; j++ )
 +                      {
                                argv[j - k] = argv[j];
 +                      }
                        argc -= k;
                }
        }
@@@ -59,9 -54,8 +59,9 @@@
        g_argv = argv;
  }
  
 -char *gamedetect_argv_buffer[1024];
 -void gamedetect_found_game( char *game, char *path ){
 +char const *gamedetect_argv_buffer[1024];
 +
 +void gamedetect_found_game( char const *game, char *path ){
        int argc;
        static char buf[128];
  
@@@ -85,7 -79,7 +85,7 @@@
        g_argv = gamedetect_argv_buffer;
  }
  
 -bool gamedetect_check_game( char *gamefile, const char *checkfile1, const char *checkfile2, char *buf /* must have 64 bytes free after bufpos */, int bufpos ){
 +bool gamedetect_check_game( char const *gamefile, const char *checkfile1, const char *checkfile2, char *buf /* must have 64 bytes free after bufpos */, int bufpos ){
        buf[bufpos] = '/';
  
        strcpy( buf + bufpos + 1, checkfile1 );
@@@ -114,14 -108,12 +114,14 @@@ void gamedetect()
        bool nogamedetect = true;
        int i;
        for ( i = 1; i < g_argc - 1; ++i )
 +      {
                if ( g_argv[i][0] == '-' ) {
                        if ( !strcmp( g_argv[i], "-gamedetect" ) ) {
                                nogamedetect = !strcmp( g_argv[i + 1], "false" );
                        }
                        ++i;
                }
 +      }
        if ( !nogamedetect ) {
                static char buf[1024 + 64];
                strncpy( buf, environment_get_app_path(), sizeof( buf ) );
                        // TODO add more games to this
  
                        // try to detect Nexuiz installs
 -#if defined( WIN32 )
 +#if GDEF_OS_WINDOWS
                        if ( gamedetect_check_game( "nexuiz.game", "data/common-spog.pk3", "nexuiz.exe", buf, p - buf ) )
 -#elif defined( __APPLE__ )
 +#elif GDEF_OS_MACOS
                        if ( gamedetect_check_game( "nexuiz.game", "data/common-spog.pk3", "Nexuiz.app/Contents/Info.plist", buf, p - buf ) )
  #else
                        if ( gamedetect_check_game( "nexuiz.game", "data/common-spog.pk3", "nexuiz-linux-glx.sh", buf, p - buf ) )
  #endif
                        { return; }
  
 -                      // try to detect Q2World installs
 -                      if ( gamedetect_check_game( "q2w.game", "default/quake2world.version", NULL, buf, p - buf ) ) {
 +                      // try to detect Quetoo installs
 +                      if ( gamedetect_check_game( "quetoo.game", "default/icons/quetoo.png", NULL, buf, p - buf ) ) {
                                return;
                        }
  
@@@ -188,7 -180,21 +188,21 @@@ bool portable_app_setup()
        return false;
  }
  
 -char* openCmdMap;
 -#if defined( POSIX )
++const char* openCmdMap;
+ void cmdMap(){
+       openCmdMap = NULL;
+       for ( int i = 1; i < g_argc; ++i )
+       {
+               //if ( !stricmp( g_argv[i] + strlen(g_argv[i]) - 4, ".map" ) ){
+               if( string_equal_suffix_nocase( g_argv[i], ".map" ) ){
+                       openCmdMap = g_argv[i];
+               }
+       }
+ }
 +#if GDEF_OS_POSIX
  
  #include <stdlib.h>
  #include <pwd.h>
  #include <glib.h>
  
  const char* LINK_NAME =
 -#if defined ( __linux__ )
 +#if GDEF_OS_LINUX
        "/proc/self/exe"
  #else // FreeBSD and OSX
        "/proc/curproc/file"
  ;
  
  /// brief Returns the filename of the executable belonging to the current process, or 0 if not found.
 -char* getexename( char *buf ){
 +char const* getexename( char *buf ){
        /* Now read the symbolic link */
        int ret = readlink( LINK_NAME, buf, PATH_MAX );
  
        return buf;
  }
  
 -void environment_init( int argc, char* argv[] ){
 +void environment_init( int argc, char const* argv[] ){
        // Give away unnecessary root privileges.
        // Important: must be done before calling gtk_init().
        char *loginname;
  
        if ( !portable_app_setup() ) {
                StringOutputStream home( 256 );
 -              home << DirectoryCleaned( g_get_home_dir() ) << ".netradiant/";
 +              home << DirectoryCleaned( g_get_user_config_dir() ) << "netradiant/";
                Q_mkdir( home.c_str() );
                home_path = home.c_str();
        }
        gamedetect();
+       cmdMap();
  }
  
 -#elif defined( WIN32 )
 +#elif GDEF_OS_WINDOWS
  
  #include <windows.h>
  
- char* openCmdMap;
- void cmdMap(){
-       openCmdMap = NULL;
-       for ( int i = 1; i < g_argc; ++i )
-       {
-               if ( !stricmp( g_argv[i] + strlen(g_argv[i]) - 4, ".map" ) ){
-                       openCmdMap = g_argv[i];
-               }
-       }
- }
 -void environment_init( int argc, char* argv[] ){
 +void environment_init( int argc, char const* argv[] ){
        args_init( argc, argv );
  
        {
        if ( !portable_app_setup() ) {
                char *appdata = getenv( "APPDATA" );
                StringOutputStream home( 256 );
 -              if ( !appdata || string_empty( appdata ) ) {
 -                      ERROR_MESSAGE( "Application Data folder not available.\n"
 -                                                 "Radiant will use C:\\ for user preferences.\n" );
 -                      home << "C:";
 -              }
 -              else
 -              {
 -                      home << PathCleaned( appdata );
 -              }
 +              home << PathCleaned( appdata );
                home << "/NetRadiantSettings/";
                Q_mkdir( home.c_str() );
                home_path = home.c_str();
diff --combined radiant/environment.h
index 98c33ab94568a90d726896e0298ac94db8f97969,b5dc6c1523183aadb8651202eb680187b9c72b67..566a307e64874662845ce835551e689991f1495a
  #if !defined( INCLUDED_ENVIRONMENT_H )
  #define INCLUDED_ENVIRONMENT_H
  
 -void environment_init( int argc, char* argv[] );
 +void environment_init( int argc, char const* argv[] );
  const char* environment_get_home_path();
  const char* environment_get_app_path();
  
  extern int g_argc;
 -extern char** g_argv;
 -
 -extern char* openCmdMap;
 +extern char const** g_argv;
  
- #if defined( WIN32 )
- extern char* openCmdMap;
- #endif
++extern const char* openCmdMap;
  
  #endif
index 21db5d78c747cea7ead7b20d44f1dd26e0a46478,88d283207a3c7110f3ce3e6ec4cdf8481d73680f..fcb78edd0d8e3bf7ea34553b0d174124c58a3e1d
  
  #include "findtexturedialog.h"
  
 +#include <gtk/gtk.h>
 +
  #include "debugging/debugging.h"
  
  #include "ishaders.h"
  
 -#include <gtk/gtkhbox.h>
 -#include <gtk/gtkentry.h>
 -#include <gtk/gtkvbox.h>
 -#include <gtk/gtkframe.h>
 -#include <gtk/gtklabel.h>
 -#include <gtk/gtktable.h>
 -#include <gtk/gtkbutton.h>
 -#include <gtk/gtktogglebutton.h>
 -#include <gtk/gtkcheckbutton.h>
 -#include <gtk/gtkmenuitem.h>
 -#include <gtk/gtkarrow.h>
 -
  #include "gtkutil/window.h"
  #include "stream/stringstream.h"
  
@@@ -51,14 -61,14 +51,14 @@@ static void setReplaceStr( const char* 
  static void setFindStr( const char* name );
  static bool isOpen();
  static void show();
 -typedef FreeCaller<&FindTextureDialog::show> ShowCaller;
 +typedef FreeCaller<void(), &FindTextureDialog::show> ShowCaller;
  static void updateTextures( const char* name );
  
  FindTextureDialog();
  virtual ~FindTextureDialog();
 -GtkWindow* BuildDialog();
 +ui::Window BuildDialog();
  
 -void constructWindow( GtkWindow* parent ){
 +void constructWindow( ui::Window parent ){
        m_parent = parent;
        Create();
  }
@@@ -86,33 -96,33 +86,33 @@@ void FindTextureDialog_apply()
        FindReplaceTextures( find.c_str(), replace.c_str(), g_FindTextureDialog.m_bSelectedOnly );
  }
  
 -static void OnApply( GtkWidget* widget, gpointer data ){
 +static void OnApply( ui::Widget widget, gpointer data ){
        g_FindTextureDialog.exportData();
        FindTextureDialog_apply();
  }
  
 -static void OnFind( GtkWidget* widget, gpointer data ){
 +static void OnFind( ui::Widget widget, gpointer data ){
        g_FindTextureDialog.exportData();
        FindTextureDialog_apply();
  }
  
 -static void OnOK( GtkWidget* widget, gpointer data ){
 +static void OnOK( ui::Widget widget, gpointer data ){
        g_FindTextureDialog.exportData();
        FindTextureDialog_apply();
        g_FindTextureDialog.HideDlg();
  }
  
 -static void OnClose( GtkWidget* widget, gpointer data ){
 +static void OnClose( ui::Widget widget, gpointer data ){
        g_FindTextureDialog.HideDlg();
  }
  
  
 -static gint find_focus_in( GtkWidget* widget, GdkEventFocus *event, gpointer data ){
 +static gint find_focus_in( ui::Widget widget, GdkEventFocus *event, gpointer data ){
        g_bFindActive = true;
        return FALSE;
  }
  
 -static gint replace_focus_in( GtkWidget* widget, GdkEventFocus *event, gpointer data ){
 +static gint replace_focus_in( ui::Widget widget, GdkEventFocus *event, gpointer data ){
        g_bFindActive = false;
        return FALSE;
  }
  
  FindTextureDialog::FindTextureDialog(){
        m_bSelectedOnly = FALSE;
-       //m_position_tracker.setPosition( c_default_window_pos );
+       m_position_tracker.setPosition( WindowPosition( -1, -1, 0, 0 ) );
  }
  
  FindTextureDialog::~FindTextureDialog(){
  }
  
 -GtkWindow* FindTextureDialog::BuildDialog(){
 -      GtkWidget* vbox, *hbox, *table, *label;
 -      GtkWidget* button, *check, *entry;
 +ui::Window FindTextureDialog::BuildDialog(){
 +    ui::Widget label{ui::null};
 +      ui::Widget button{ui::null};
 +      ui::Entry entry{ui::null};
  
 -      GtkWindow* dlg = create_floating_window( "Find / Replace Texture(s)", m_parent );
 +      auto dlg = ui::Window(create_floating_window( "Find / Replace Texture(s)", m_parent ));
  
        m_position_tracker.connect( dlg );
  
 -      hbox = gtk_hbox_new( FALSE, 5 );
 -      gtk_widget_show( hbox );
 -      gtk_container_add( GTK_CONTAINER( dlg ), GTK_WIDGET( hbox ) );
 +      auto hbox = ui::HBox( FALSE, 5 );
 +      hbox.show();
 +      dlg.add(hbox);
        gtk_container_set_border_width( GTK_CONTAINER( hbox ), 5 );
  
 -      vbox = gtk_vbox_new( FALSE, 5 );
 -      gtk_widget_show( vbox );
 -      gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( vbox ), TRUE, TRUE, 0 );
 -
 -      table = gtk_table_new( 2, 2, FALSE );
 -      gtk_widget_show( table );
 -      gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( table ), TRUE, TRUE, 0 );
 -      gtk_table_set_row_spacings( GTK_TABLE( table ), 5 );
 -      gtk_table_set_col_spacings( GTK_TABLE( table ), 5 );
 -
 -      label = gtk_label_new( "Find:" );
 -      gtk_widget_show( label );
 -      gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1,
 -                                        (GtkAttachOptions) ( GTK_FILL ),
 -                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +      auto vbox = ui::VBox( FALSE, 5 );
 +      vbox.show();
 +      hbox.pack_start( vbox, TRUE, TRUE, 0 );
 +
 +    auto table = ui::Table(2, 2, FALSE);
 +      table.show();
 +      vbox.pack_start( table, TRUE, TRUE, 0 );
 +    gtk_table_set_row_spacings(table, 5);
 +    gtk_table_set_col_spacings(table, 5);
 +
 +      label = ui::Label( "Find:" );
 +      label.show();
 +    table.attach(label, {0, 1, 0, 1}, {GTK_FILL, 0});
        gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
  
 -      label = gtk_label_new( "Replace:*" );
 +      label = ui::Label( "Replace:*" );
        gtk_widget_set_tooltip_text( label, "Empty = search mode" );
 -      gtk_widget_show( label );
 -      gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2,
 -                                        (GtkAttachOptions) ( GTK_FILL ),
 -                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +      label.show();
 +    table.attach(label, {0, 1, 1, 2}, {GTK_FILL, 0});
        gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
  
 -      entry = gtk_entry_new();
 -      gtk_widget_show( entry );
 -      gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 0, 1,
 -                                        (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
 -                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 -      g_signal_connect( G_OBJECT( entry ), "focus_in_event",
 +      entry = ui::Entry(ui::New);
 +      entry.show();
 +    table.attach(entry, {1, 2, 0, 1}, {GTK_EXPAND | GTK_FILL, 0});
 +      entry.connect( "focus_in_event",
                                          G_CALLBACK( find_focus_in ), 0 );
 -      AddDialogData( *GTK_ENTRY( entry ), m_strFind );
 -      GlobalTextureEntryCompletion::instance().connect( GTK_ENTRY( entry ) );
 +      AddDialogData( entry, m_strFind );
 +      GlobalTextureEntryCompletion::instance().connect( entry );
  
 -      entry = gtk_entry_new();
 +      entry = ui::Entry(ui::New);
        gtk_widget_set_tooltip_text( entry, "Empty = search mode" );
 -      gtk_widget_show( entry );
 -      gtk_table_attach( GTK_TABLE( table ), entry, 1, 2, 1, 2,
 -                                        (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
 -                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 -      g_signal_connect( G_OBJECT( entry ), "focus_in_event",
 +      entry.show();
 +    table.attach(entry, {1, 2, 1, 2}, {GTK_EXPAND | GTK_FILL, 0});
 +      entry.connect( "focus_in_event",
                                          G_CALLBACK( replace_focus_in ), 0 );
 -      AddDialogData( *GTK_ENTRY( entry ), m_strReplace );
 -      GlobalTextureEntryCompletion::instance().connect( GTK_ENTRY( entry ) );
 -
 -      check = gtk_check_button_new_with_label( "Within selected brushes only" );
 -      gtk_widget_show( check );
 -      gtk_box_pack_start( GTK_BOX( vbox ), check, TRUE, TRUE, 0 );
 -      AddDialogData( *GTK_TOGGLE_BUTTON( check ), m_bSelectedOnly );
 -
 -      vbox = gtk_vbox_new( FALSE, 5 );
 -      gtk_widget_show( vbox );
 -      gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( vbox ), FALSE, FALSE, 0 );
 -
 -      button = gtk_button_new_with_label( "Apply" );
 -      gtk_widget_show( button );
 -      gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 0 );
 -      g_signal_connect( G_OBJECT( button ), "clicked",
 +      AddDialogData( entry, m_strReplace );
 +      GlobalTextureEntryCompletion::instance().connect( entry );
 +
 +      auto check = ui::CheckButton( "Within selected brushes only" );
 +      check.show();
 +      vbox.pack_start( check, TRUE, TRUE, 0 );
 +      AddDialogData( check, m_bSelectedOnly );
 +
 +      vbox = ui::VBox( FALSE, 5 );
 +      vbox.show();
 +      hbox.pack_start( vbox, FALSE, FALSE, 0 );
 +
 +      button = ui::Button( "Apply" );
 +      button.show();
 +      vbox.pack_start( button, FALSE, FALSE, 0 );
 +      button.connect( "clicked",
                                          G_CALLBACK( OnApply ), 0 );
 -      gtk_widget_set_usize( button, 60, -2 );
 +      button.dimensions(60, -1);
  
 -      button = gtk_button_new_with_label( "Close" );
 -      gtk_widget_show( button );
 -      gtk_box_pack_start( GTK_BOX( vbox ), button, FALSE, FALSE, 0 );
 -      g_signal_connect( G_OBJECT( button ), "clicked",
 +      button = ui::Button( "Close" );
 +      button.show();
 +      vbox.pack_start( button, FALSE, FALSE, 0 );
 +      button.connect( "clicked",
                                          G_CALLBACK( OnClose ), 0 );
 -      gtk_widget_set_usize( button, 60, -2 );
 +      button.dimensions(60, -1);
  
        return dlg;
  }
@@@ -220,7 -237,7 +220,7 @@@ void FindTextureDialog::updateTextures
  }
  
  bool FindTextureDialog::isOpen(){
 -      return GTK_WIDGET_VISIBLE( g_FindTextureDialog.GetWidget() ) == TRUE;
 +      return g_FindTextureDialog.GetWidget().visible();
  }
  
  void FindTextureDialog::setFindStr( const char* name ){
@@@ -243,7 -260,7 +243,7 @@@ void FindTextureDialog::show()
  }
  
  
 -void FindTextureDialog_constructWindow( GtkWindow* main_window ){
 +void FindTextureDialog_constructWindow( ui::Window main_window ){
        g_FindTextureDialog.constructWindow( main_window );
  }
  
@@@ -263,7 -280,7 +263,7 @@@ void FindTextureDialog_selectTexture( c
  
  void FindTextureDialog_Construct(){
        GlobalCommands_insert( "FindReplaceTextures", FindTextureDialog::ShowCaller() );
 -      GlobalPreferenceSystem().registerPreference( "FindReplacehWnd", WindowPositionTrackerImportStringCaller( g_FindTextureDialog.m_position_tracker ), WindowPositionTrackerExportStringCaller( g_FindTextureDialog.m_position_tracker ) );
 +      GlobalPreferenceSystem().registerPreference( "FindReplacehWnd",  make_property_string<WindowPositionTracker_String>( g_FindTextureDialog.m_position_tracker ) );
  }
  
  void FindTextureDialog_Destroy(){
diff --combined radiant/main.cpp
index 88cd0cad4fd89e7a774ca8941be1a9fbd5b60144,d17db3d6aa4f619eb26aedfcaa02d5eac1a47ab3..6093f87971528835fb0898f467869efed8ddb52b
@@@ -49,7 -49,7 +49,7 @@@
     \link math/plane.h math/plane.h \endlink - Planes \n
     \link math/aabb.h math/aabb.h \endlink - AABBs \n
  
 -   Callback MemberCaller FunctionCaller - callbacks similar to using boost::function with boost::bind \n
 +   Callback MemberCaller0 FunctionCaller - callbacks similar to using boost::function with boost::bind \n
     SmartPointer SmartReference - smart-pointer and smart-reference similar to Loki's SmartPtr \n
  
     \link generic/bitfield.h generic/bitfield.h \endlink - Type-safe bitfield \n
@@@ -62,7 -62,6 +62,7 @@@
   */
  
  #include "main.h"
 +#include "globaldefs.h"
  
  #include "version.h"
  
@@@ -70,7 -69,7 +70,7 @@@
  
  #include "iundo.h"
  
 -#include <gtk/gtkmain.h>
 +#include "uilib/uilib.h"
  
  #include "cmdlib.h"
  #include "os/file.h"
@@@ -90,7 -89,7 +90,7 @@@
  #include "referencecache.h"
  #include "stacktrace.h"
  
 -#ifdef WIN32
 +#if GDEF_OS_WINDOWS
  #include <windows.h>
  #endif
  
@@@ -209,17 -208,19 +209,17 @@@ void error_redirect( const gchar *domai
        // spam it...
        globalErrorStream() << buf << "\n";
  
 -      // FIXME why are warnings is_fatal?
 -#ifndef _DEBUG
 -      if ( is_fatal )
 -#endif
 -      ERROR_MESSAGE( "GTK+ error: " << buf );
 +      if (is_fatal) {
 +          ERROR_MESSAGE( "GTK+ error: " << buf );
 +    }
  }
  
 -#if defined ( _DEBUG ) && defined ( WIN32 ) && defined ( _MSC_VER )
 +#if GDEF_COMPILER_MSVC && GDEF_DEBUG
  #include "crtdbg.h"
  #endif
  
  void crt_init(){
 -#if defined ( _DEBUG ) && defined ( WIN32 ) && defined ( _MSC_VER )
 +#if GDEF_COMPILER_MSVC && GDEF_DEBUG
        _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
  #endif
  }
@@@ -302,16 -303,16 +302,16 @@@ bool handleMessage()
        globalErrorStream() << m_buffer.c_str();
        if ( !m_lock.locked() ) {
                ScopedLock lock( m_lock );
 -#if defined _DEBUG
 -              m_buffer << "Break into the debugger?\n";
 -              bool handled = gtk_MessageBox( 0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_YESNO, eMB_ICONERROR ) == eIDNO;
 -              m_buffer.clear();
 -              return handled;
 -#else
 -              m_buffer << "Please report this error to the developers\n";
 -              gtk_MessageBox( 0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_OK, eMB_ICONERROR );
 -              m_buffer.clear();
 -#endif
 +        if (GDEF_DEBUG) {
 +            m_buffer << "Break into the debugger?\n";
 +            bool handled = ui::alert(ui::root, m_buffer.c_str(), "Radiant - Runtime Error", ui::alert_type::YESNO, ui::alert_icon::Error) == ui::alert_response::NO;
 +            m_buffer.clear();
 +            return handled;
 +        } else {
 +            m_buffer << "Please report this error to the developers\n";
 +            ui::alert(ui::root, m_buffer.c_str(), "Radiant - Runtime Error", ui::alert_type::OK, ui::alert_icon::Error);
 +            m_buffer.clear();
 +        }
        }
        return true;
  }
@@@ -325,7 -326,14 +325,7 @@@ void streams_init()
  }
  
  void paths_init(){
 -      const char* home = environment_get_home_path();
 -      Q_mkdir( home );
 -
 -      {
 -              StringOutputStream path( 256 );
 -              path << home << "1." << RADIANT_MAJOR_VERSION "." << RADIANT_MINOR_VERSION << '/';
 -              g_strSettingsPath = path.c_str();
 -      }
 +      g_strSettingsPath = environment_get_home_path();
  
        Q_mkdir( g_strSettingsPath.c_str() );
  
@@@ -368,31 -376,34 +368,31 @@@ bool check_version()
        // make something idiot proof and someone will make better idiots, this may be overkill
        // let's leave it disabled in debug mode in any case
        // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=431
 -#ifndef _DEBUG
 -#define CHECK_VERSION
 -#endif
 -#ifdef CHECK_VERSION
 -      // locate and open RADIANT_MAJOR and RADIANT_MINOR
 -      bool bVerIsGood = true;
 -      {
 -              StringOutputStream ver_file_name( 256 );
 -              ver_file_name << AppPath_get() << "RADIANT_MAJOR";
 -              bVerIsGood = check_version_file( ver_file_name.c_str(), RADIANT_MAJOR_VERSION );
 -      }
 -      {
 -              StringOutputStream ver_file_name( 256 );
 -              ver_file_name << AppPath_get() << "RADIANT_MINOR";
 -              bVerIsGood = check_version_file( ver_file_name.c_str(), RADIANT_MINOR_VERSION );
 -      }
 -
 -      if ( !bVerIsGood ) {
 -              StringOutputStream msg( 256 );
 -              msg << "This editor binary (" RADIANT_VERSION ") doesn't match what the latest setup has configured in this directory\n"
 -                                                                                                        "Make sure you run the right/latest editor binary you installed\n"
 -                      << AppPath_get();
 -              gtk_MessageBox( 0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONDEFAULT );
 -      }
 -      return bVerIsGood;
 -#else
 -      return true;
 -#endif
 +    if (GDEF_DEBUG) {
 +        return true;
 +    }
 +    // locate and open RADIANT_MAJOR and RADIANT_MINOR
 +    bool bVerIsGood = true;
 +    {
 +        StringOutputStream ver_file_name(256);
 +        ver_file_name << AppPath_get() << "RADIANT_MAJOR";
 +        bVerIsGood = check_version_file(ver_file_name.c_str(), RADIANT_MAJOR_VERSION);
 +    }
 +    {
 +        StringOutputStream ver_file_name(256);
 +        ver_file_name << AppPath_get() << "RADIANT_MINOR";
 +        bVerIsGood = check_version_file(ver_file_name.c_str(), RADIANT_MINOR_VERSION);
 +    }
 +
 +    if (!bVerIsGood) {
 +        StringOutputStream msg(256);
 +        msg
 +                << "This editor binary (" RADIANT_VERSION ") doesn't match what the latest setup has configured in this directory\n"
 +                        "Make sure you run the right/latest editor binary you installed\n"
 +                << AppPath_get();
 +        ui::alert(ui::root, msg.c_str(), "Radiant", ui::alert_type::OK, ui::alert_icon::Default);
 +    }
 +    return bVerIsGood;
  }
  
  void create_global_pid(){
                if ( remove( g_pidFile.c_str() ) == -1 ) {
                        StringOutputStream msg( 256 );
                        msg << "WARNING: Could not delete " << g_pidFile.c_str();
 -                      gtk_MessageBox( 0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR );
 +                      ui::alert( ui::root, msg.c_str(), "Radiant", ui::alert_type::OK, ui::alert_icon::Error );
                }
  
                // in debug, never prompt to clean registry, turn console logging auto after a failed start
 -#if !defined( _DEBUG )
 -              StringOutputStream msg( 256 );
 -              msg << "Radiant failed to start properly the last time it was run.\n"
 -                         "The failure may be related to current global preferences.\n"
 -                         "Do you want to reset global preferences to defaults?";
 -
 -              if ( gtk_MessageBox( 0, msg.c_str(), "Radiant - Startup Failure", eMB_YESNO, eMB_ICONQUESTION ) == eIDYES ) {
 -                      g_GamesDialog.Reset();
 -              }
 +              if (!GDEF_DEBUG) {
 +                      StringOutputStream msg(256);
 +                      msg << "Radiant failed to start properly the last time it was run.\n"
 +                                      "The failure may be related to current global preferences.\n"
 +                                      "Do you want to reset global preferences to defaults?";
 +
 +                      if (ui::alert(ui::root, msg.c_str(), "Radiant - Startup Failure", ui::alert_type::YESNO, ui::alert_icon::Question) == ui::alert_response::YES) {
 +                              g_GamesDialog.Reset();
 +                      }
  
 -              msg.clear();
 -              msg << "Logging console output to " << SettingsPath_get() << "radiant.log\nRefer to the log if Radiant fails to start again.";
 +                      msg.clear();
 +                      msg << "Logging console output to " << SettingsPath_get()
 +                              << "radiant.log\nRefer to the log if Radiant fails to start again.";
  
 -              gtk_MessageBox( 0, msg.c_str(), "Radiant - Console Log", eMB_OK );
 -#endif
 +                      ui::alert(ui::root, msg.c_str(), "Radiant - Console Log", ui::alert_type::OK);
 +              }
  
                // set without saving, the class is not in a coherent state yet
                // just do the value change and call to start logging, CGamesDialog will pickup when relevant
@@@ -457,7 -467,7 +457,7 @@@ void remove_global_pid()
        if ( remove( g_pidFile.c_str() ) == -1 ) {
                StringOutputStream msg( 256 );
                msg << "WARNING: Could not delete " << g_pidFile.c_str();
 -              gtk_MessageBox( 0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR );
 +              ui::alert( ui::root, msg.c_str(), "Radiant", ui::alert_type::OK, ui::alert_icon::Error );
        }
  }
  
@@@ -475,26 -485,25 +475,26 @@@ void create_local_pid()
                if ( remove( g_pidGameFile.c_str() ) == -1 ) {
                        StringOutputStream msg;
                        msg << "WARNING: Could not delete " << g_pidGameFile.c_str();
 -                      gtk_MessageBox( 0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR );
 +                      ui::alert( ui::root, msg.c_str(), "Radiant", ui::alert_type::OK, ui::alert_icon::Error );
                }
  
                // in debug, never prompt to clean registry, turn console logging auto after a failed start
 -#if !defined( _DEBUG )
 -              StringOutputStream msg;
 -              msg << "Radiant failed to start properly the last time it was run.\n"
 -                         "The failure may be caused by current preferences.\n"
 -                         "Do you want to reset all preferences to defaults?";
 -
 -              if ( gtk_MessageBox( 0, msg.c_str(), "Radiant - Startup Failure", eMB_YESNO, eMB_ICONQUESTION ) == eIDYES ) {
 -                      Preferences_Reset();
 -              }
 +              if (!GDEF_DEBUG) {
 +                      StringOutputStream msg;
 +                      msg << "Radiant failed to start properly the last time it was run.\n"
 +                                      "The failure may be caused by current preferences.\n"
 +                                      "Do you want to reset all preferences to defaults?";
  
 -              msg.clear();
 -              msg << "Logging console output to " << SettingsPath_get() << "radiant.log\nRefer to the log if Radiant fails to start again.";
 +                      if (ui::alert(ui::root, msg.c_str(), "Radiant - Startup Failure", ui::alert_type::YESNO, ui::alert_icon::Question) == ui::alert_response::YES) {
 +                              Preferences_Reset();
 +                      }
  
 -              gtk_MessageBox( 0, msg.c_str(), "Radiant - Console Log", eMB_OK );
 -#endif
 +                      msg.clear();
 +                      msg << "Logging console output to " << SettingsPath_get()
 +                              << "radiant.log\nRefer to the log if Radiant fails to start again.";
 +
 +                      ui::alert(ui::root, msg.c_str(), "Radiant - Console Log", ui::alert_type::OK);
 +              }
  
                // force console logging on! (will go in prefs too)
                g_GamesDialog.m_bForceLogConsole = true;
@@@ -535,15 -544,6 +535,15 @@@ void user_shortcuts_save()
  }
  
  void add_local_rc_files(){
 +#define GARUX_DISABLE_GTKTHEME
 +#ifndef GARUX_DISABLE_GTKTHEME
 +/* FIXME: HACK: not GTK3 compatible
 + https://developer.gnome.org/gtk2/stable/gtk2-Resource-Files.html#gtk-rc-add-default-file
 + https://developer.gnome.org/gtk3/stable/gtk3-Resource-Files.html#gtk-rc-add-default-file
 + > gtk_rc_add_default_file has been deprecated since version 3.0 and should not be used in newly-written code.
 + > Use GtkStyleContext with a custom GtkStyleProvider instead
 +*/
 +
        {
                StringOutputStream path( 512 );
                path << AppPath_get() << ".gtkrc-2.0.radiant";
                gtk_rc_add_default_file( path.c_str() );
        }
  #endif
 +#endif // GARUX_DISABLE_GTKTHEME
  }
  
  int main( int argc, char* argv[] ){
  
        streams_init();
  
 -#ifdef WIN32
 +#if GDEF_OS_WINDOWS
        HMODULE lib;
        lib = LoadLibrary( "dwmapi.dll" );
        if ( lib != 0 ) {
        _setmaxstdio(2048);
  #endif
  
 -      gtk_disable_setlocale();
 +      const char* mapname = NULL;
 +    char const *error = NULL;
 +      if ( !ui::init( &argc, &argv, "<filename.map>", &error) ) {
 +              g_print( "%s\n", error );
 +              return -1;
 +      }
  
 -      gtk_init( &argc, &argv );
 +      // Gtk already removed parsed `--options`
 +      if (argc == 2) {
 +              if ( strlen( argv[1] ) > 1 ) {
 +                      if ( g_str_has_suffix( argv[1], ".map" ) ) {
 +                              if ( g_path_is_absolute( argv[1] ) ) {
 +                                      mapname = argv[1];
 +                              }
 +                              else {
 +                                      mapname = g_build_filename( g_get_current_dir(), argv[1], NULL );
 +                              }
 +                      }
 +                      else {
 +                              g_print( "bad file name, will not load: %s\n", argv[1] );
 +                      }
 +              }
 +      }
 +      else if (argc > 2) {
 +              g_print ( "%s\n", "too many arguments" );
 +              return -1;
 +      }
  
        // redirect Gtk warnings to the console
        g_log_set_handler( "Gdk", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING |
  
        GlobalDebugMessageHandler::instance().setHandler( GlobalPopupDebugMessageHandler::instance() );
  
 -      environment_init( argc, argv );
 +      environment_init(argc, (char const **) argv);
  
        paths_init();
  
  
        Radiant_Initialise();
  
 -      global_accel_init();
 -
        user_shortcuts_init();
  
        g_pParentWnd = 0;
  
        hide_splash();
  
- #ifdef WIN32
        if( openCmdMap && *openCmdMap ){
                Map_LoadFile( openCmdMap );
        }
-       else
- #endif // WIN32
-       if ( mapname != NULL ) {
++      else if ( mapname != NULL ) {
 +              Map_LoadFile( mapname );
 +      }
        else if ( g_bLoadLastMap && !g_strLastMap.empty() ) {
                Map_LoadFile( g_strLastMap.c_str() );
        }
  
        remove_local_pid();
  
 -      gtk_main();
 +      ui::main();
  
        // avoid saving prefs when the app is minimized
        if ( g_pParentWnd->IsSleeping() ) {
  
        user_shortcuts_save();
  
 -      global_accel_destroy();
 -
        Radiant_Shutdown();
  
        // close the log file if any
diff --combined radiant/mainframe.cpp
index 16c237096b357275218e0c0176e45148472d179a,0bb43da61d022752d524ed978b0e3f79d243572d..4bd30a9561f140282d9028b0245b36ac3cb46c3f
  //
  
  #include "mainframe.h"
 +#include "globaldefs.h"
  
 -#include "debugging/debugging.h"
 -#include "version.h"
 +#include <gtk/gtk.h>
  
  #include "ifilesystem.h"
  #include "iundo.h"
 -#include "ifilter.h"
 -#include "itoolbar.h"
  #include "editable.h"
  #include "ientity.h"
  #include "ishaders.h"
  #include <ctime>
  
  #include <gdk/gdkkeysyms.h>
 -#include <gtk/gtkhbox.h>
 -#include <gtk/gtkvbox.h>
 -#include <gtk/gtkframe.h>
 -#include <gtk/gtklabel.h>
 -#include <gtk/gtkhpaned.h>
 -#include <gtk/gtkvpaned.h>
 -#include <gtk/gtktoolbar.h>
 -#include <gtk/gtkmenubar.h>
 -#include <gtk/gtkimage.h>
 -#include <gtk/gtktable.h>
  
  
  #include "cmdlib.h"
 -#include "scenelib.h"
  #include "stream/stringstream.h"
  #include "signal/isignal.h"
  #include "os/path.h"
  #include "moduleobservers.h"
  
  #include "gtkutil/clipboard.h"
 -#include "gtkutil/container.h"
  #include "gtkutil/frame.h"
 -#include "gtkutil/glfont.h"
  #include "gtkutil/glwidget.h"
  #include "gtkutil/image.h"
  #include "gtkutil/menu.h"
  #include "gtkutil/paned.h"
 -#include "gtkutil/widget.h"
  
  #include "autosave.h"
  #include "build.h"
  #include "pluginmanager.h"
  #include "pluginmenu.h"
  #include "plugintoolbar.h"
 -#include "points.h"
  #include "preferences.h"
  #include "qe3.h"
  #include "qgl.h"
  #include "renderstate.h"
  #include "feedback.h"
  #include "referencecache.h"
 -
 +#include "texwindow.h"
  #include "filterbar.h"
 +
 +#define GARUX_DISABLE_GTKTHEME
 +#ifndef GARUX_DISABLE_GTKTHEME
  #include "gtktheme.h"
 +#endif
  
  
  struct layout_globals_t
        layout_globals_t() :
                m_position( -1, -1, 640, 480 ),
  
-               nXYHeight( 300 ),
-               nXYWidth( 300 ),
-               nCamWidth( 200 ),
-               nCamHeight( 200 ),
-               nState( GDK_WINDOW_STATE_MAXIMIZED ){
+               nXYHeight( 350 ),
+               nXYWidth( 600 ),
+               nCamWidth( 300 ),
+               nCamHeight( 210 ),
+               nState( 0 ){
        }
  };
  
@@@ -135,48 -148,22 +135,48 @@@ glwindow_globals_t g_glwindow_globals
  
  
  // VFS
 +
 +bool g_vfsInitialized = false;
 +
 +void VFS_Init(){
 +      if ( g_vfsInitialized ) return;
 +      QE_InitVFS();
 +      GlobalFileSystem().initialise();
 +      g_vfsInitialized = true;
 +}
 +
 +void VFS_Shutdown(){
 +      if ( !g_vfsInitialized ) return;
 +      GlobalFileSystem().shutdown();
 +      g_vfsInitialized = false;
 +}
 +
 +void VFS_Refresh(){
 +      if ( !g_vfsInitialized ) return;
 +      GlobalFileSystem().clear();
 +      QE_InitVFS();
 +      GlobalFileSystem().refresh();
 +      g_vfsInitialized = true;
 +      // also refresh models
 +      RefreshReferences();
 +      // also refresh texture browser
 +      TextureBrowser_RefreshShaders();
 +}
 +
 +void VFS_Restart(){
 +      VFS_Shutdown();
 +      VFS_Init();
 +}
 +
  class VFSModuleObserver : public ModuleObserver
  {
 -std::size_t m_unrealised;
  public:
 -VFSModuleObserver() : m_unrealised( 1 ){
 -}
  void realise(){
 -      if ( --m_unrealised == 0 ) {
 -              QE_InitVFS();
 -              GlobalFileSystem().initialise();
 +      VFS_Init();
        }
 -}
 +
  void unrealise(){
 -      if ( ++m_unrealised == 1 ) {
 -              GlobalFileSystem().shutdown();
 -      }
 +      VFS_Shutdown();
  }
  };
  
@@@ -185,14 -172,13 +185,14 @@@ VFSModuleObserver g_VFSModuleObserver
  void VFS_Construct(){
        Radiant_attachHomePathsObserver( g_VFSModuleObserver );
  }
 +
  void VFS_Destroy(){
        Radiant_detachHomePathsObserver( g_VFSModuleObserver );
  }
  
  // Home Paths
  
 -#ifdef WIN32
 +#if GDEF_OS_WINDOWS
  #include <shlobj.h>
  #include <objbase.h>
  const GUID qFOLDERID_SavedGames = {0x4C5C32FF, 0xBB9D, 0x43b0, {0xB5, 0xB4, 0x2D, 0x72, 0xE5, 0x4E, 0xAA, 0xA4}};
  typedef HRESULT ( WINAPI qSHGetKnownFolderPath_t )( qREFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath );
  static qSHGetKnownFolderPath_t *qSHGetKnownFolderPath;
  #endif
 +
  void HomePaths_Realise(){
        do
        {
                if ( !string_empty( prefix ) ) {
                        StringOutputStream path( 256 );
  
 -#if defined( __APPLE__ )
 +#if GDEF_OS_MACOS
                        path.clear();
                        path << DirectoryCleaned( g_get_home_dir() ) << "Library/Application Support" << ( prefix + 1 ) << "/";
                        if ( file_is_directory( path.c_str() ) ) {
                                g_qeglobals.m_userEnginePath = path.c_str();
                                break;
                        }
 +                      path.clear();
 +                      path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
  #endif
  
 -#if defined( WIN32 )
 +#if GDEF_OS_WINDOWS
                        TCHAR mydocsdir[MAX_PATH + 1];
                        wchar_t *mydocsdirw;
                        HMODULE shfolder = LoadLibrary( "shfolder.dll" );
                        }
  #endif
  
 -#if defined( POSIX )
 +#if GDEF_OS_POSIX
                        path.clear();
                        path << DirectoryCleaned( g_get_home_dir() ) << prefix << "/";
                        g_qeglobals.m_userEnginePath = path.c_str();
@@@ -299,14 -282,12 +299,14 @@@ std::size_t m_unrealised
  public:
  HomePathsModuleObserver() : m_unrealised( 1 ){
  }
 +
  void realise(){
        if ( --m_unrealised == 0 ) {
                HomePaths_Realise();
                g_homePathObservers.realise();
        }
  }
 +
  void unrealise(){
        if ( ++m_unrealised == 1 ) {
                g_homePathObservers.unrealise();
@@@ -319,7 -300,6 +319,7 @@@ HomePathsModuleObserver g_HomePathsModu
  void HomePaths_Construct(){
        Radiant_attachEnginePathObserver( g_HomePathsModuleObserver );
  }
 +
  void HomePaths_Destroy(){
        Radiant_detachEnginePathObserver( g_HomePathsModuleObserver );
  }
@@@ -386,59 -366,6 +386,59 @@@ void setEnginePath( const char* path )
        }
  }
  
 +// Pak Path
 +
 +CopiedString g_strPakPath[g_pakPathCount] = { "", "", "", "", "" };
 +ModuleObservers g_pakPathObservers[g_pakPathCount];
 +std::size_t g_pakpath_unrealised[g_pakPathCount] = { 1, 1, 1, 1, 1 };
 +
 +void Radiant_attachPakPathObserver( int num, ModuleObserver& observer ){
 +      g_pakPathObservers[num].attach( observer );
 +}
 +
 +void Radiant_detachPakPathObserver( int num, ModuleObserver& observer ){
 +      g_pakPathObservers[num].detach( observer );
 +}
 +
 +
 +void PakPath_Realise( int num ){
 +      if ( --g_pakpath_unrealised[num] == 0 ) {
 +              g_pakPathObservers[num].realise();
 +      }
 +}
 +
 +const char* PakPath_get( int num ){
 +      std::string message = "PakPath_get: pak path " + std::to_string(num) + " not realised";
 +      ASSERT_MESSAGE( g_pakpath_unrealised[num] == 0, message.c_str() );
 +      return g_strPakPath[num].c_str();
 +}
 +
 +void PakPath_Unrealise( int num ){
 +      if ( ++g_pakpath_unrealised[num] == 1 ) {
 +              g_pakPathObservers[num].unrealise();
 +      }
 +}
 +
 +void setPakPath( int num, const char* path ){
 +      if (!g_strcmp0( path, "")) {
 +              g_strPakPath[num] = "";
 +              return;
 +      }
 +
 +      StringOutputStream buffer( 256 );
 +      buffer << DirectoryCleaned( path );
 +      if ( !path_equal( buffer.c_str(), g_strPakPath[num].c_str() ) ) {
 +              std::string message = "Changing Pak Path " + std::to_string(num);
 +              ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", message.c_str() );
 +
 +              PakPath_Unrealise(num);
 +
 +              g_strPakPath[num] = buffer.c_str();
 +
 +              PakPath_Realise(num);
 +      }
 +}
 +
  
  // App Path
  
@@@ -462,7 -389,6 +462,7 @@@ const char* LocalRcPath_get( void )
  /// directory for temp files
  /// NOTE: on *nix this is were we check for .pid
  CopiedString g_strSettingsPath;
 +
  const char* SettingsPath_get(){
        return g_strSettingsPath.c_str();
  }
@@@ -483,129 -409,41 +483,129 @@@ const char* GameToolsPath_get()
        return g_strGameToolsPath.c_str();
  }
  
 -void EnginePathImport( CopiedString& self, const char* value ){
 +struct EnginePath {
 +      static void Export(const CopiedString &self, const Callback<void(const char *)> &returnz) {
 +              returnz(self.c_str());
 +      }
 +
 +      static void Import(CopiedString &self, const char *value) {
        setEnginePath( value );
  }
 -typedef ReferenceCaller1<CopiedString, const char*, EnginePathImport> EnginePathImportCaller;
 +};
 +
 +struct PakPath0 {
 +      static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
 +              returnz( self.c_str() );
 +      }
 +
 +      static void Import( CopiedString &self, const char *value ) {
 +              setPakPath( 0, value );
 +      }
 +};
 +
 +struct PakPath1 {
 +      static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
 +              returnz( self.c_str() );
 +      }
 +
 +      static void Import( CopiedString &self, const char *value ) {
 +              setPakPath( 1, value );
 +      }
 +};
 +
 +struct PakPath2 {
 +      static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
 +              returnz( self.c_str() );
 +      }
 +
 +      static void Import( CopiedString &self, const char *value ) {
 +              setPakPath( 2, value );
 +      }
 +};
 +
 +struct PakPath3 {
 +      static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
 +              returnz( self.c_str() );
 +      }
 +
 +      static void Import( CopiedString &self, const char *value ) {
 +              setPakPath( 3, value );
 +      }
 +};
 +
 +struct PakPath4 {
 +      static void Export( const CopiedString &self, const Callback<void(const char*)> &returnz ) {
 +              returnz( self.c_str() );
 +      }
 +
 +      static void Import( CopiedString &self, const char *value ) {
 +              setPakPath( 4, value );
 +      }
 +};
 +
 +bool g_disableEnginePath = false;
 +bool g_disableHomePath = false;
  
  void Paths_constructPreferences( PreferencesPage& page ){
 -      page.appendPathEntry( "Engine Path", true,
 -                                                StringImportCallback( EnginePathImportCaller( g_strEnginePath ) ),
 -                                                StringExportCallback( StringExportCaller( g_strEnginePath ) )
 +      page.appendPathEntry( "Engine Path", true, make_property<EnginePath>(g_strEnginePath) );
 +
 +      page.appendCheckBox(
 +              "", "Do not use Engine Path",
 +              g_disableEnginePath
                                                  );
 +
 +      page.appendCheckBox(
 +              "", "Do not use Home Path",
 +              g_disableHomePath
 +              );
 +
 +      for ( int i = 0; i < g_pakPathCount; i++ ) {
 +              std::string label = "Pak Path " + std::to_string(i);
 +              switch (i) {
 +                      case 0:
 +                      page.appendPathEntry( label.c_str(), true, make_property<PakPath0>( g_strPakPath[i] ) );
 +                      break;
 +                      case 1:
 +                      page.appendPathEntry( label.c_str(), true, make_property<PakPath1>( g_strPakPath[i] ) );
 +                      break;
 +                      case 2:
 +                      page.appendPathEntry( label.c_str(), true, make_property<PakPath2>( g_strPakPath[i] ) );
 +                      break;
 +                      case 3:
 +                      page.appendPathEntry( label.c_str(), true, make_property<PakPath3>( g_strPakPath[i] ) );
 +                      break;
 +                      case 4:
 +                      page.appendPathEntry( label.c_str(), true, make_property<PakPath4>( g_strPakPath[i] ) );
 +                      break;
 +}
 +      }
  }
 +
  void Paths_constructPage( PreferenceGroup& group ){
        PreferencesPage page( group.createPage( "Paths", "Path Settings" ) );
        Paths_constructPreferences( page );
  }
 +
  void Paths_registerPreferencesPage(){
 -      PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Paths_constructPage>() );
 +      PreferencesDialog_addSettingsPage( makeCallbackF(Paths_constructPage) );
  }
  
  
  class PathsDialog : public Dialog
  {
  public:
 -GtkWindow* BuildDialog(){
 -      GtkFrame* frame = create_dialog_frame( "Path settings", GTK_SHADOW_ETCHED_IN );
 +ui::Window BuildDialog(){
 +      auto frame = create_dialog_frame( "Path settings", ui::Shadow::ETCHED_IN );
  
 -      GtkVBox* vbox2 = create_dialog_vbox( 0, 4 );
 -      gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( vbox2 ) );
 +      auto vbox2 = create_dialog_vbox( 0, 4 );
 +      frame.add(vbox2);
  
        {
 -              PreferencesPage preferencesPage( *this, GTK_WIDGET( vbox2 ) );
 +              PreferencesPage preferencesPage( *this, vbox2 );
                Paths_constructPreferences( preferencesPage );
        }
  
 -      return create_simple_modal_dialog_window( "Engine Path Not Found", m_modal, GTK_WIDGET( frame ) );
 +      return ui::Window(create_simple_modal_dialog_window( "Engine Path Not Found", m_modal, frame ));
  }
  };
  
@@@ -677,30 -515,36 +677,30 @@@ void gamemode_set( const char* gamemod
        }
  }
  
 -#include "os/dir.h"
  
 -class CLoadModule
 -{
 -const char* m_path;
 -public:
 -CLoadModule( const char* path ) : m_path( path ){
 -}
 -void operator()( const char* name ) const {
 -      char fullname[1024];
 -      ASSERT_MESSAGE( strlen( m_path ) + strlen( name ) < 1024, "" );
 -      strcpy( fullname, m_path );
 -      strcat( fullname, name );
 -      globalOutputStream() << "Found '" << fullname << "'\n";
 -      GlobalModuleServer_loadModule( fullname );
 -}
 -};
 +#include "os/dir.h"
  
  const char* const c_library_extension =
 -#if defined( WIN32 )
 +#if defined( CMAKE_SHARED_MODULE_SUFFIX )
 +    CMAKE_SHARED_MODULE_SUFFIX
 +#elif GDEF_OS_WINDOWS
        "dll"
 -#elif defined ( __APPLE__ )
 +#elif GDEF_OS_MACOS
        "dylib"
 -#elif defined( __linux__ ) || defined ( __FreeBSD__ )
 +#elif GDEF_OS_LINUX || GDEF_OS_BSD
        "so"
  #endif
  ;
  
  void Radiant_loadModules( const char* path ){
 -      Directory_forEach( path, MatchFileExtension<CLoadModule>( c_library_extension, CLoadModule( path ) ) );
 +      Directory_forEach(path, matchFileExtension(c_library_extension, [&](const char *name) {
 +              char fullname[1024];
 +              ASSERT_MESSAGE(strlen(path) + strlen(name) < 1024, "");
 +              strcpy(fullname, path);
 +              strcat(fullname, name);
 +              globalOutputStream() << "Found '" << fullname << "'\n";
 +              GlobalModuleServer_loadModule(fullname);
 +      }));
  }
  
  void Radiant_loadModulesFromRoot( const char* directory ){
@@@ -732,13 -576,11 +732,13 @@@ std::size_t m_unrealised
  public:
  WorldspawnColourEntityClassObserver() : m_unrealised( 1 ){
  }
 +
  void realise(){
        if ( --m_unrealised == 0 ) {
                SetWorldspawnColour( g_xywindow_globals.color_brushes );
        }
  }
 +
  void unrealise(){
        if ( ++m_unrealised == 1 ) {
        }
@@@ -951,8 -793,8 +951,8 @@@ void ColorScheme_Ydnar()
        XY_UpdateAllWindows();
  }
  
 -typedef Callback1<Vector3&> GetColourCallback;
 -typedef Callback1<const Vector3&> SetColourCallback;
 +typedef Callback<void(Vector3&)> GetColourCallback;
 +typedef Callback<void(const Vector3&)> SetColourCallback;
  
  class ChooseColour
  {
@@@ -962,56 -804,50 +962,56 @@@ public
  ChooseColour( const GetColourCallback& get, const SetColourCallback& set )
        : m_get( get ), m_set( set ){
  }
 +
  void operator()(){
        Vector3 colour;
        m_get( colour );
 -      color_dialog( GTK_WIDGET( MainFrame_getWindow() ), colour );
 +      color_dialog( MainFrame_getWindow(), colour );
        m_set( colour );
  }
  };
  
  
 -
  void Colour_get( const Vector3& colour, Vector3& other ){
        other = colour;
  }
 -typedef ConstReferenceCaller1<Vector3, Vector3&, Colour_get> ColourGetCaller;
 +
 +typedef ConstReferenceCaller<Vector3, void(Vector3&), Colour_get> ColourGetCaller;
  
  void Colour_set( Vector3& colour, const Vector3& other ){
        colour = other;
        SceneChangeNotify();
  }
 -typedef ReferenceCaller1<Vector3, const Vector3&, Colour_set> ColourSetCaller;
 +
 +typedef ReferenceCaller<Vector3, void(const Vector3&), Colour_set> ColourSetCaller;
  
  void BrushColour_set( const Vector3& other ){
        g_xywindow_globals.color_brushes = other;
        SetWorldspawnColour( g_xywindow_globals.color_brushes );
        SceneChangeNotify();
  }
 -typedef FreeCaller1<const Vector3&, BrushColour_set> BrushColourSetCaller;
 +
 +typedef FreeCaller<void(const Vector3&), BrushColour_set> BrushColourSetCaller;
  
  void ClipperColour_set( const Vector3& other ){
        g_xywindow_globals.color_clipper = other;
        Brush_clipperColourChanged();
        SceneChangeNotify();
  }
 -typedef FreeCaller1<const Vector3&, ClipperColour_set> ClipperColourSetCaller;
 +
 +typedef FreeCaller<void(const Vector3&), ClipperColour_set> ClipperColourSetCaller;
  
  void TextureBrowserColour_get( Vector3& other ){
        other = TextureBrowser_getBackgroundColour( GlobalTextureBrowser() );
  }
 -typedef FreeCaller1<Vector3&, TextureBrowserColour_get> TextureBrowserColourGetCaller;
 +
 +typedef FreeCaller<void(Vector3&), TextureBrowserColour_get> TextureBrowserColourGetCaller;
  
  void TextureBrowserColour_set( const Vector3& other ){
        TextureBrowser_setBackgroundColour( GlobalTextureBrowser(), other );
  }
 -typedef FreeCaller1<const Vector3&, TextureBrowserColour_set> TextureBrowserColourSetCaller;
 +
 +typedef FreeCaller<void(const Vector3&), TextureBrowserColour_set> TextureBrowserColourSetCaller;
  
  
  class ColoursMenu
@@@ -1052,14 -888,14 +1052,14 @@@ ColoursMenu() 
  
  ColoursMenu g_ColoursMenu;
  
 -GtkMenuItem* create_colours_menu(){
 -      GtkMenuItem* colours_menu_item = new_sub_menu_item_with_mnemonic( "Colors" );
 -      GtkMenu* menu_in_menu = GTK_MENU( gtk_menu_item_get_submenu( colours_menu_item ) );
 +ui::MenuItem create_colours_menu(){
 +      auto colours_menu_item = new_sub_menu_item_with_mnemonic( "Colors" );
 +      auto menu_in_menu = ui::Menu::from( gtk_menu_item_get_submenu( colours_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu_in_menu );
        }
  
 -      GtkMenu* menu_3 = create_sub_menu_with_mnemonic( menu_in_menu, "Themes" );
 +      auto menu_3 = create_sub_menu_with_mnemonic( menu_in_menu, "Themes" );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu_3 );
        }
        create_menu_item_with_mnemonic( menu_3, "Black and Green", "ColorSchemeBlackAndGreen" );
        create_menu_item_with_mnemonic( menu_3, "Maya/Max/Lightwave Emulation", "ColorSchemeYdnar" );
  
 +#ifndef GARUX_DISABLE_GTKTHEME
        create_menu_item_with_mnemonic( menu_in_menu, "GTK Theme...", "gtkThemeDlg" );
 +#endif
  
        menu_separator( menu_in_menu );
  
@@@ -1111,39 -945,59 +1111,39 @@@ void thunk_OnSleep()
        g_pParentWnd->OnSleep();
  }
  
 -void OpenUpdateURL(){
 -      // build the URL
 -      StringOutputStream URL( 256 );
 -      URL << "http://www.icculus.org/netradiant/?cmd=update&data=dlupdate&query_dlup=1";
 -#ifdef WIN32
 -      URL << "&OS_dlup=1";
 -#elif defined( __APPLE__ )
 -      URL << "&OS_dlup=2";
 -#else
 -      URL << "&OS_dlup=3";
 -#endif
 -      URL << "&Version_dlup=" RADIANT_VERSION;
 -      g_GamesDialog.AddPacksURL( URL );
 -      OpenURL( URL.c_str() );
 -}
 -
 -// open the Q3Rad manual
  void OpenHelpURL(){
 -      // at least on win32, AppPath + "docs/index.html"
 -      StringOutputStream help( 256 );
 -      help << AppPath_get() << "docs/index.html";
 -      OpenURL( help.c_str() );
 +      OpenURL( "https://gitlab.com/xonotic/xonotic/wikis/Mapping" );
  }
  
  void OpenBugReportURL(){
 -      OpenURL( "http://www.icculus.org/netradiant/?cmd=bugs" );
 +      OpenURL( "https://gitlab.com/xonotic/netradiant/issues" );
  }
  
  
 -GtkWidget* g_page_console;
 +ui::Widget g_page_console{ui::null};
  
  void Console_ToggleShow(){
        GroupDialog_showPage( g_page_console );
  }
  
 -GtkWidget* g_page_entity;
 +ui::Widget g_page_entity{ui::null};
  
  void EntityInspector_ToggleShow(){
        GroupDialog_showPage( g_page_entity );
  }
  
  
 -
  void SetClipMode( bool enable );
 +
  void ModeChangeNotify();
  
  typedef void ( *ToolMode )();
 +
  ToolMode g_currentToolMode = 0;
  bool g_currentToolModeSupportsComponentEditing = false;
  ToolMode g_defaultToolMode = 0;
  
  
 -
  void SelectionSystem_DefaultMode(){
        GlobalSelectionSystem().SetMode( SelectionSystem::ePrimitive );
        GlobalSelectionSystem().SetComponentMode( SelectionSystem::eDefault );
@@@ -1170,24 -1024,24 +1170,24 @@@ template<bool( *BoolFunction ) ( )
  class BoolFunctionExport
  {
  public:
 -static void apply( const BoolImportCallback& importCallback ){
 +static void apply( const Callback<void(bool)> & importCallback ){
        importCallback( BoolFunction() );
  }
  };
  
 -typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<EdgeMode>::apply> EdgeModeApplyCaller;
 +typedef FreeCaller<void(const Callback<void(bool)> &), &BoolFunctionExport<EdgeMode>::apply> EdgeModeApplyCaller;
  EdgeModeApplyCaller g_edgeMode_button_caller;
 -BoolExportCallback g_edgeMode_button_callback( g_edgeMode_button_caller );
 +Callback<void(const Callback<void(bool)> &)> g_edgeMode_button_callback( g_edgeMode_button_caller );
  ToggleItem g_edgeMode_button( g_edgeMode_button_callback );
  
 -typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<VertexMode>::apply> VertexModeApplyCaller;
 +typedef FreeCaller<void(const Callback<void(bool)> &), &BoolFunctionExport<VertexMode>::apply> VertexModeApplyCaller;
  VertexModeApplyCaller g_vertexMode_button_caller;
 -BoolExportCallback g_vertexMode_button_callback( g_vertexMode_button_caller );
 +Callback<void(const Callback<void(bool)> &)> g_vertexMode_button_callback( g_vertexMode_button_caller );
  ToggleItem g_vertexMode_button( g_vertexMode_button_callback );
  
 -typedef FreeCaller1<const BoolImportCallback&, &BoolFunctionExport<FaceMode>::apply> FaceModeApplyCaller;
 +typedef FreeCaller<void(const Callback<void(bool)> &), &BoolFunctionExport<FaceMode>::apply> FaceModeApplyCaller;
  FaceModeApplyCaller g_faceMode_button_caller;
 -BoolExportCallback g_faceMode_button_callback( g_faceMode_button_caller );
 +Callback<void(const Callback<void(bool)> &)> g_faceMode_button_callback( g_faceMode_button_caller );
  ToggleItem g_faceMode_button( g_faceMode_button_callback );
  
  void ComponentModeChanged(){
@@@ -1284,7 -1138,6 +1284,7 @@@ NodeSmartReference worldspawn
  public:
  CloneSelected( bool d ) : doMakeUnique( d ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.size() == 1 ) {
                return true;
  
        return true;
  }
 +
  void post( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.size() == 1 ) {
                return;
@@@ -1351,7 -1203,6 +1351,7 @@@ struct AxisBas
        Vector3 x;
        Vector3 y;
        Vector3 z;
 +
        AxisBase( const Vector3& x_, const Vector3& y_, const Vector3& z_ )
                : x( x_ ), y( y_ ), z( z_ ){
        }
@@@ -1464,44 -1315,44 +1464,44 @@@ void Selection_NudgeRight()
  }
  
  
 -void TranslateToolExport( const BoolImportCallback& importCallback ){
 +void TranslateToolExport( const Callback<void(bool)> & importCallback ){
        importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eTranslate );
  }
  
 -void RotateToolExport( const BoolImportCallback& importCallback ){
 +void RotateToolExport( const Callback<void(bool)> & importCallback ){
        importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eRotate );
  }
  
 -void ScaleToolExport( const BoolImportCallback& importCallback ){
 +void ScaleToolExport( const Callback<void(bool)> & importCallback ){
        importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eScale );
  }
  
 -void DragToolExport( const BoolImportCallback& importCallback ){
 +void DragToolExport( const Callback<void(bool)> & importCallback ){
        importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag );
  }
  
 -void ClipperToolExport( const BoolImportCallback& importCallback ){
 +void ClipperToolExport( const Callback<void(bool)> & importCallback ){
        importCallback( GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip );
  }
  
 -FreeCaller1<const BoolImportCallback&, TranslateToolExport> g_translatemode_button_caller;
 -BoolExportCallback g_translatemode_button_callback( g_translatemode_button_caller );
 +FreeCaller<void(const Callback<void(bool)> &), TranslateToolExport> g_translatemode_button_caller;
 +Callback<void(const Callback<void(bool)> &)> g_translatemode_button_callback( g_translatemode_button_caller );
  ToggleItem g_translatemode_button( g_translatemode_button_callback );
  
 -FreeCaller1<const BoolImportCallback&, RotateToolExport> g_rotatemode_button_caller;
 -BoolExportCallback g_rotatemode_button_callback( g_rotatemode_button_caller );
 +FreeCaller<void(const Callback<void(bool)> &), RotateToolExport> g_rotatemode_button_caller;
 +Callback<void(const Callback<void(bool)> &)> g_rotatemode_button_callback( g_rotatemode_button_caller );
  ToggleItem g_rotatemode_button( g_rotatemode_button_callback );
  
 -FreeCaller1<const BoolImportCallback&, ScaleToolExport> g_scalemode_button_caller;
 -BoolExportCallback g_scalemode_button_callback( g_scalemode_button_caller );
 +FreeCaller<void(const Callback<void(bool)> &), ScaleToolExport> g_scalemode_button_caller;
 +Callback<void(const Callback<void(bool)> &)> g_scalemode_button_callback( g_scalemode_button_caller );
  ToggleItem g_scalemode_button( g_scalemode_button_callback );
  
 -FreeCaller1<const BoolImportCallback&, DragToolExport> g_dragmode_button_caller;
 -BoolExportCallback g_dragmode_button_callback( g_dragmode_button_caller );
 +FreeCaller<void(const Callback<void(bool)> &), DragToolExport> g_dragmode_button_caller;
 +Callback<void(const Callback<void(bool)> &)> g_dragmode_button_callback( g_dragmode_button_caller );
  ToggleItem g_dragmode_button( g_dragmode_button_callback );
  
 -FreeCaller1<const BoolImportCallback&, ClipperToolExport> g_clipper_button_caller;
 -BoolExportCallback g_clipper_button_callback( g_clipper_button_caller );
 +FreeCaller<void(const Callback<void(bool)> &), ClipperToolExport> g_clipper_button_caller;
 +Callback<void(const Callback<void(bool)> &)> g_clipper_button_callback( g_clipper_button_caller );
  ToggleItem g_clipper_button( g_clipper_button_callback );
  
  void ToolChanged(){
@@@ -1709,7 -1560,6 +1709,7 @@@ public
  SnappableSnapToGridSelected( float snap )
        : m_snap( snap ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.top().get().visible() ) {
                Snappable* snappable = Node_getSnappable( path.top() );
@@@ -1733,7 -1583,6 +1733,7 @@@ public
  ComponentSnappableSnapToGridSelected( float snap )
        : m_snap( snap ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.top().get().visible() ) {
                ComponentSnappable* componentSnappable = Instance_getComponentSnappable( instance );
@@@ -1781,47 -1630,47 +1781,47 @@@ guint s_qe_every_second_id = 0
  
  void EverySecondTimer_enable(){
        if ( s_qe_every_second_id == 0 ) {
 -              s_qe_every_second_id = gtk_timeout_add( 1000, qe_every_second, 0 );
 +              s_qe_every_second_id = g_timeout_add( 1000, qe_every_second, 0 );
        }
  }
  
  void EverySecondTimer_disable(){
        if ( s_qe_every_second_id != 0 ) {
 -              gtk_timeout_remove( s_qe_every_second_id );
 +              g_source_remove( s_qe_every_second_id );
                s_qe_every_second_id = 0;
        }
  }
  
 -gint window_realize_remove_decoration( GtkWidget* widget, gpointer data ){
 -      gdk_window_set_decorations( widget->window, (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) );
 +gint window_realize_remove_decoration( ui::Widget widget, gpointer data ){
 +      gdk_window_set_decorations( gtk_widget_get_window(widget), (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) );
        return FALSE;
  }
  
  class WaitDialog
  {
  public:
 -GtkWindow* m_window;
 -GtkLabel* m_label;
 +ui::Window m_window{ui::null};
 +ui::Label m_label{ui::null};
  };
  
  WaitDialog create_wait_dialog( const char* title, const char* text ){
        WaitDialog dialog;
  
 -      dialog.m_window = create_floating_window( title, MainFrame_getWindow() );
 +      dialog.m_window = MainFrame_getWindow().create_floating_window(title);
        gtk_window_set_resizable( dialog.m_window, FALSE );
        gtk_container_set_border_width( GTK_CONTAINER( dialog.m_window ), 0 );
        gtk_window_set_position( dialog.m_window, GTK_WIN_POS_CENTER_ON_PARENT );
  
 -      g_signal_connect( G_OBJECT( dialog.m_window ), "realize", G_CALLBACK( window_realize_remove_decoration ), 0 );
 +      dialog.m_window.connect( "realize", G_CALLBACK( window_realize_remove_decoration ), 0 );
  
        {
 -              dialog.m_label = GTK_LABEL( gtk_label_new( text ) );
 +              dialog.m_label = ui::Label( text );
                gtk_misc_set_alignment( GTK_MISC( dialog.m_label ), 0.0, 0.5 );
                gtk_label_set_justify( dialog.m_label, GTK_JUSTIFY_LEFT );
 -              gtk_widget_show( GTK_WIDGET( dialog.m_label ) );
 -              gtk_widget_set_size_request( GTK_WIDGET( dialog.m_label ), 200, -1 );
 +              dialog.m_label.show();
 +              dialog.m_label.dimensions(200, -1);
  
 -              gtk_container_add( GTK_CONTAINER( dialog.m_window ), GTK_WIDGET( dialog.m_label ) );
 +              dialog.m_window.add(dialog.m_label);
        }
        return dialog;
  }
@@@ -1847,7 -1696,7 +1847,7 @@@ bool MainFrame_isActiveApp()
        for ( GList* i = list; i != 0; i = g_list_next( i ) )
        {
                //globalOutputStream() << "toplevel.. ";
 -              if ( gtk_window_is_active( GTK_WINDOW( i->data ) ) ) {
 +              if ( gtk_window_is_active( ui::Window::from( i->data ) ) ) {
                        //globalOutputStream() << "is active\n";
                        return true;
                }
@@@ -1865,8 -1714,8 +1865,8 @@@ bool ScreenUpdates_Enabled()
  }
  
  void ScreenUpdates_process(){
 -      if ( redrawRequired() && GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
 -              process_gui();
 +      if ( redrawRequired() && g_wait.m_window.visible() ) {
 +              ui::process();
        }
  }
  
@@@ -1875,20 -1724,20 +1875,20 @@@ void ScreenUpdates_Disable( const char
        if ( g_wait_stack.empty() ) {
                EverySecondTimer_disable();
  
 -              process_gui();
 +              ui::process();
  
                bool isActiveApp = MainFrame_isActiveApp();
  
                g_wait = create_wait_dialog( title, message );
 -              gtk_grab_add( GTK_WIDGET( g_wait.m_window ) );
 +              gtk_grab_add( g_wait.m_window  );
  
                if ( isActiveApp ) {
 -                      gtk_widget_show( GTK_WIDGET( g_wait.m_window ) );
 +                      g_wait.m_window.show();
                        ScreenUpdates_process();
                }
        }
 -      else if ( GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
 -              gtk_label_set_text( g_wait.m_label, message );
 +      else if ( g_wait.m_window.visible() ) {
 +              g_wait.m_label.text(message);
                ScreenUpdates_process();
        }
        g_wait_stack.push_back( message );
@@@ -1899,21 -1748,22 +1899,21 @@@ void ScreenUpdates_Enable()
        g_wait_stack.pop_back();
        if ( g_wait_stack.empty() ) {
                EverySecondTimer_enable();
 -              //gtk_widget_set_sensitive(GTK_WIDGET(MainFrame_getWindow()), TRUE);
 +              //gtk_widget_set_sensitive(MainFrame_getWindow(), TRUE);
  
 -              gtk_grab_remove( GTK_WIDGET( g_wait.m_window ) );
 +              gtk_grab_remove( g_wait.m_window  );
                destroy_floating_window( g_wait.m_window );
 -              g_wait.m_window = 0;
 +              g_wait.m_window = ui::Window{ui::null};
  
                //gtk_window_present(MainFrame_getWindow());
        }
 -      else if ( GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
 -              gtk_label_set_text( g_wait.m_label, g_wait_stack.back().c_str() );
 +      else if ( g_wait.m_window.visible() ) {
 +              g_wait.m_label.text(g_wait_stack.back().c_str());
                ScreenUpdates_process();
        }
  }
  
  
 -
  void GlobalCamera_UpdateWindow(){
        if ( g_pParentWnd != 0 ) {
                CamWnd_Update( *g_pParentWnd->GetCamWnd() );
@@@ -1966,17 -1816,18 +1966,17 @@@ void ClipperChangeNotify()
  }
  
  
 -LatchedInt g_Layout_viewStyle( 0, "Window Layout" );
 -LatchedBool g_Layout_enableDetachableMenus( true, "Detachable Menus" );
 -LatchedBool g_Layout_enablePatchToolbar( true, "Patch Toolbar" );
 -LatchedBool g_Layout_enablePluginToolbar( true, "Plugin Toolbar" );
 -LatchedBool g_Layout_enableFilterToolbar( true, "Filter Toolbar" );
 -
 +LatchedValue<int> g_Layout_viewStyle( 0, "Window Layout" );
 +LatchedValue<bool> g_Layout_enableDetachableMenus( true, "Detachable Menus" );
 +LatchedValue<bool> g_Layout_enablePatchToolbar( true, "Patch Toolbar" );
 +LatchedValue<bool> g_Layout_enablePluginToolbar( true, "Plugin Toolbar" );
 +LatchedValue<bool> g_Layout_enableFilterToolbar( true, "Filter Toolbar" );
  
  
 -GtkMenuItem* create_file_menu(){
 +ui::MenuItem create_file_menu(){
        // File menu
 -      GtkMenuItem* file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( file_menu_item ) );
 +      auto file_menu_item = new_sub_menu_item_with_mnemonic( "_File" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( file_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
        menu_separator( menu );
        create_menu_item_with_mnemonic( menu, "_Save", "SaveMap" );
        create_menu_item_with_mnemonic( menu, "Save _as...", "SaveMapAs" );
 -      create_menu_item_with_mnemonic( menu, "Save s_elected...", "SaveSelected" );
 +      create_menu_item_with_mnemonic( menu, "_Export selected...", "ExportSelected" );
        create_menu_item_with_mnemonic( menu, "Save re_gion...", "SaveRegion" );
        menu_separator( menu );
  //    menu_separator( menu );
        return file_menu_item;
  }
  
 -GtkMenuItem* create_edit_menu(){
 +ui::MenuItem create_edit_menu(){
        // Edit menu
 -      GtkMenuItem* edit_menu_item = new_sub_menu_item_with_mnemonic( "_Edit" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( edit_menu_item ) );
 +      auto edit_menu_item = new_sub_menu_item_with_mnemonic( "_Edit" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( edit_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
  
        menu_separator( menu );
  
 -//    GtkMenu* convert_menu = create_sub_menu_with_mnemonic( menu, "E_xpand Selection" );
 +//    auto convert_menu = create_sub_menu_with_mnemonic( menu, "E_xpand Selection" );
  //    if ( g_Layout_enableDetachableMenus.m_value ) {
  //            menu_tearoff( convert_menu );
  //    }
        return edit_menu_item;
  }
  
 -void fill_view_xy_top_menu( GtkMenu* menu ){
 +void fill_view_xy_top_menu( ui::Menu menu ){
        create_check_menu_item_with_mnemonic( menu, "XY (Top) View", "ToggleView" );
  }
  
  
 -void fill_view_yz_side_menu( GtkMenu* menu ){
 +void fill_view_yz_side_menu( ui::Menu menu ){
        create_check_menu_item_with_mnemonic( menu, "YZ (Side) View", "ToggleSideView" );
  }
  
  
 -void fill_view_xz_front_menu( GtkMenu* menu ){
 +void fill_view_xz_front_menu( ui::Menu menu ){
        create_check_menu_item_with_mnemonic( menu, "XZ (Front) View", "ToggleFrontView" );
  }
  
  
 -GtkWidget* g_toggle_z_item = 0;
 -GtkWidget* g_toggle_console_item = 0;
 -GtkWidget* g_toggle_entity_item = 0;
 -GtkWidget* g_toggle_entitylist_item = 0;
 +ui::Widget g_toggle_z_item{ui::null};
 +ui::Widget g_toggle_console_item{ui::null};
 +ui::Widget g_toggle_entity_item{ui::null};
 +ui::Widget g_toggle_entitylist_item{ui::null};
  
 -GtkMenuItem* create_view_menu( MainFrame::EViewStyle style ){
 +ui::MenuItem create_view_menu( MainFrame::EViewStyle style ){
        // View menu
 -      GtkMenuItem* view_menu_item = new_sub_menu_item_with_mnemonic( "Vie_w" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( view_menu_item ) );
 +      auto view_menu_item = new_sub_menu_item_with_mnemonic( "Vie_w" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( view_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
  
        menu_separator( menu );
        {
 -              GtkMenu* camera_menu = create_sub_menu_with_mnemonic( menu, "Camera" );
 +              auto camera_menu = create_sub_menu_with_mnemonic( menu, "Camera" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( camera_menu );
                }
        }
        menu_separator( menu );
        {
 -              GtkMenu* orthographic_menu = create_sub_menu_with_mnemonic( menu, "Orthographic" );
 +              auto orthographic_menu = create_sub_menu_with_mnemonic( menu, "Orthographic" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( orthographic_menu );
                }
        menu_separator( menu );
  
        {
 -              GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Show" );
 +              auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Show" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( menu_in_menu );
                }
        }
  
        {
 -              GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Filter" );
 +              auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Filter" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( menu_in_menu );
                }
        }
        menu_separator( menu );
        {
 -              GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Region" );
 +              auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Region" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( menu_in_menu );
                }
        return view_menu_item;
  }
  
 -GtkMenuItem* create_selection_menu(){
 +ui::MenuItem create_selection_menu(){
        // Selection menu
 -      GtkMenuItem* selection_menu_item = new_sub_menu_item_with_mnemonic( "M_odify" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( selection_menu_item ) );
 +      auto selection_menu_item = new_sub_menu_item_with_mnemonic( "M_odify" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( selection_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
  
        {
 -              GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Components" );
 +              auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Components" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( menu_in_menu );
                }
        menu_separator( menu );
  
        {
 -              GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Nudge" );
 +              auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Nudge" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( menu_in_menu );
                }
                create_menu_item_with_mnemonic( menu_in_menu, "Nudge Down", "SelectNudgeDown" );
        }
        {
 -              GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Rotate" );
 +              auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Rotate" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( menu_in_menu );
                }
                create_menu_item_with_mnemonic( menu_in_menu, "Rotate Z", "RotateSelectionZ" );
        }
        {
 -              GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic( menu, "Flip" );
 +              auto menu_in_menu = create_sub_menu_with_mnemonic( menu, "Flip" );
                if ( g_Layout_enableDetachableMenus.m_value ) {
                        menu_tearoff( menu_in_menu );
                }
        return selection_menu_item;
  }
  
 -GtkMenuItem* create_bsp_menu(){
 +ui::MenuItem create_bsp_menu(){
        // BSP menu
 -      GtkMenuItem* bsp_menu_item = new_sub_menu_item_with_mnemonic( "_Build" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( bsp_menu_item ) );
 +      auto bsp_menu_item = new_sub_menu_item_with_mnemonic( "_Build" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( bsp_menu_item ) );
  
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
  
        create_menu_item_with_mnemonic( menu, "Customize...", "BuildMenuCustomize" );
+       create_menu_item_with_mnemonic( menu, "Run recent build", "Build_runRecentExecutedBuild" );
  
        menu_separator( menu );
  
        return bsp_menu_item;
  }
  
 -GtkMenuItem* create_grid_menu(){
 +ui::MenuItem create_grid_menu(){
        // Grid menu
 -      GtkMenuItem* grid_menu_item = new_sub_menu_item_with_mnemonic( "_Grid" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( grid_menu_item ) );
 +      auto grid_menu_item = new_sub_menu_item_with_mnemonic( "_Grid" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( grid_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
        return grid_menu_item;
  }
  
 -GtkMenuItem* create_misc_menu(){
 +ui::MenuItem create_misc_menu(){
        // Misc menu
 -      GtkMenuItem* misc_menu_item = new_sub_menu_item_with_mnemonic( "M_isc" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( misc_menu_item ) );
 +      auto misc_menu_item = new_sub_menu_item_with_mnemonic( "M_isc" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( misc_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
  
  #if 0
 -      create_menu_item_with_mnemonic( menu, "_Benchmark", FreeCaller<GlobalCamera_Benchmark>() );
 +      create_menu_item_with_mnemonic( menu, "_Benchmark", makeCallbackF(GlobalCamera_Benchmark) );
  #endif
 -      gtk_container_add( GTK_CONTAINER( menu ), GTK_WIDGET( create_colours_menu() ) );
 +    menu.add(create_colours_menu());
  
        create_menu_item_with_mnemonic( menu, "Find brush...", "FindBrush" );
        create_menu_item_with_mnemonic( menu, "Map Info...", "MapInfo" );
        // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
 -//  create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller<WXY_Print>());
 -      create_menu_item_with_mnemonic( menu, "_Background select", FreeCaller<WXY_BackgroundSelect>() );
 +//  create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller<void(), WXY_Print>());
 +      create_menu_item_with_mnemonic( menu, "_Background select", makeCallbackF(WXY_BackgroundSelect) );
+       create_menu_item_with_mnemonic( menu, "Fullscreen", "Fullscreen" );
        return misc_menu_item;
  }
  
 -GtkMenuItem* create_entity_menu(){
 +ui::MenuItem create_entity_menu(){
        // Brush menu
 -      GtkMenuItem* entity_menu_item = new_sub_menu_item_with_mnemonic( "E_ntity" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( entity_menu_item ) );
 +      auto entity_menu_item = new_sub_menu_item_with_mnemonic( "E_ntity" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( entity_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
        return entity_menu_item;
  }
  
 -GtkMenuItem* create_brush_menu(){
 +ui::MenuItem create_brush_menu(){
        // Brush menu
 -      GtkMenuItem* brush_menu_item = new_sub_menu_item_with_mnemonic( "B_rush" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( brush_menu_item ) );
 +      auto brush_menu_item = new_sub_menu_item_with_mnemonic( "B_rush" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( brush_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
        return brush_menu_item;
  }
  
 -GtkMenuItem* create_patch_menu(){
 +ui::MenuItem create_patch_menu(){
        // Curve menu
 -      GtkMenuItem* patch_menu_item = new_sub_menu_item_with_mnemonic( "_Curve" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( patch_menu_item ) );
 +      auto patch_menu_item = new_sub_menu_item_with_mnemonic( "_Curve" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( patch_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
        return patch_menu_item;
  }
  
 -GtkMenuItem* create_help_menu(){
 +ui::MenuItem create_help_menu(){
        // Help menu
 -      GtkMenuItem* help_menu_item = new_sub_menu_item_with_mnemonic( "_Help" );
 -      GtkMenu* menu = GTK_MENU( gtk_menu_item_get_submenu( help_menu_item ) );
 +      auto help_menu_item = new_sub_menu_item_with_mnemonic( "_Help" );
 +      auto menu = ui::Menu::from( gtk_menu_item_get_submenu( help_menu_item ) );
        if ( g_Layout_enableDetachableMenus.m_value ) {
                menu_tearoff( menu );
        }
        // it will take care of hooking the Sys_OpenURL calls etc.
        create_game_help_menu( menu );
  
 -//    create_menu_item_with_mnemonic( menu, "Bug report", FreeCaller<OpenBugReportURL>() );
 -      create_menu_item_with_mnemonic( menu, "Shortcuts list", FreeCaller<DoCommandListDlg>() );
 -      create_menu_item_with_mnemonic( menu, "_About", FreeCaller<DoAbout>() );
 +      create_menu_item_with_mnemonic( menu, "Bug report", makeCallbackF(OpenBugReportURL) );
 +      create_menu_item_with_mnemonic( menu, "Shortcuts list", makeCallbackF(DoCommandListDlg) );
 +      create_menu_item_with_mnemonic( menu, "_About", makeCallbackF(DoAbout) );
  
        return help_menu_item;
  }
  
 -GtkMenuBar* create_main_menu( MainFrame::EViewStyle style ){
 -      GtkMenuBar* menu_bar = GTK_MENU_BAR( gtk_menu_bar_new() );
 -      gtk_widget_show( GTK_WIDGET( menu_bar ) );
 +ui::MenuBar create_main_menu( MainFrame::EViewStyle style ){
 +      auto menu_bar = ui::MenuBar::from( gtk_menu_bar_new() );
 +      menu_bar.show();
  
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_file_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_edit_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_view_menu( style ) ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_selection_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_bsp_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_grid_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_misc_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_entity_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_brush_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_patch_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_plugins_menu() ) );
 -      gtk_container_add( GTK_CONTAINER( menu_bar ), GTK_WIDGET( create_help_menu() ) );
 +      menu_bar.add(create_file_menu());
 +      menu_bar.add(create_edit_menu());
 +      menu_bar.add(create_view_menu(style));
 +      menu_bar.add(create_selection_menu());
 +      menu_bar.add(create_bsp_menu());
 +      menu_bar.add(create_grid_menu());
 +      menu_bar.add(create_misc_menu());
 +      menu_bar.add(create_entity_menu());
 +      menu_bar.add(create_brush_menu());
 +      menu_bar.add(create_patch_menu());
 +      menu_bar.add(create_plugins_menu());
 +      menu_bar.add(create_help_menu());
  
        return menu_bar;
  }
@@@ -2396,14 -2249,14 +2398,14 @@@ void PatchInspector_registerShortcuts()
  }
  
  void Patch_registerShortcuts(){
 -//    command_connect_accelerator( "InvertCurveTextureX" );
 -//    command_connect_accelerator( "InvertCurveTextureY" );
 -//    command_connect_accelerator( "PatchInsertInsertColumn" );
 -//    command_connect_accelerator( "PatchInsertInsertRow" );
 -//    command_connect_accelerator( "PatchDeleteLastColumn" );
 -//    command_connect_accelerator( "PatchDeleteLastRow" );
 -//    command_connect_accelerator( "NaturalizePatch" );
 -      //command_connect_accelerator("CapCurrentCurve");
 +      command_connect_accelerator( "InvertCurveTextureX" );
 +      command_connect_accelerator( "InvertCurveTextureY" );
 +      command_connect_accelerator( "PatchInsertInsertColumn" );
 +      command_connect_accelerator( "PatchInsertInsertRow" );
 +      command_connect_accelerator( "PatchDeleteLastColumn" );
 +      command_connect_accelerator( "PatchDeleteLastRow" );
 +      command_connect_accelerator( "NaturalizePatch" );
 +      command_connect_accelerator( "CapCurrentCurve");
  }
  
  void Manipulators_registerShortcuts(){
@@@ -2479,17 -2332,17 +2481,17 @@@ void register_shortcuts()
        Misc_registerShortcuts();
  }
  
 -void File_constructToolbar( GtkToolbar* toolbar ){
 +void File_constructToolbar( ui::Toolbar toolbar ){
        toolbar_append_button( toolbar, "Open an existing map (CTRL + O)", "file_open.png", "OpenMap" );
        toolbar_append_button( toolbar, "Save the active map (CTRL + S)", "file_save.png", "SaveMap" );
  }
  
 -void UndoRedo_constructToolbar( GtkToolbar* toolbar ){
 +void UndoRedo_constructToolbar( ui::Toolbar toolbar ){
        toolbar_append_button( toolbar, "Undo (CTRL + Z)", "undo.png", "Undo" );
        toolbar_append_button( toolbar, "Redo (CTRL + Y)", "redo.png", "Redo" );
  }
  
 -void RotateFlip_constructToolbar( GtkToolbar* toolbar ){
 +void RotateFlip_constructToolbar( ui::Toolbar toolbar ){
        toolbar_append_button( toolbar, "x-axis Flip", "brush_flipx.png", "MirrorSelectionX" );
        toolbar_append_button( toolbar, "x-axis Rotate", "brush_rotatex.png", "RotateSelectionX" );
        toolbar_append_button( toolbar, "y-axis Flip", "brush_flipy.png", "MirrorSelectionY" );
        toolbar_append_button( toolbar, "z-axis Rotate", "brush_rotatez.png", "RotateSelectionZ" );
  }
  
 -void Select_constructToolbar( GtkToolbar* toolbar ){
 +void Select_constructToolbar( ui::Toolbar toolbar ){
        toolbar_append_button( toolbar, "Select touching", "selection_selecttouching.png", "SelectTouching" );
        toolbar_append_button( toolbar, "Select inside", "selection_selectinside.png", "SelectInside" );
  }
  
 -void CSG_constructToolbar( GtkToolbar* toolbar ){
 +void CSG_constructToolbar( ui::Toolbar toolbar ){
        toolbar_append_button( toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.png", "CSGSubtract" );
        toolbar_append_button( toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.png", "CSGMerge" );
 -      toolbar_append_button( toolbar, "Room", "selection_makeroom.png", "CSGroom" );
 +      toolbar_append_button( toolbar, "Make Room", "selection_makeroom.png", "CSGRoom" );
        toolbar_append_button( toolbar, "CSG Tool", "ellipsis.png", "CSGTool" );
  }
  
 -void ComponentModes_constructToolbar( GtkToolbar* toolbar ){
 +void ComponentModes_constructToolbar( ui::Toolbar toolbar ){
        toolbar_append_toggle_button( toolbar, "Select Vertices (V)", "modify_vertices.png", "DragVertices" );
        toolbar_append_toggle_button( toolbar, "Select Edges (E)", "modify_edges.png", "DragEdges" );
        toolbar_append_toggle_button( toolbar, "Select Faces (F)", "modify_faces.png", "DragFaces" );
  }
  
 -void Clipper_constructToolbar( GtkToolbar* toolbar ){
 +void Clipper_constructToolbar( ui::Toolbar toolbar ){
  
        toolbar_append_toggle_button( toolbar, "Clipper (X)", "view_clipper.png", "ToggleClipper" );
  }
  
 -void XYWnd_constructToolbar( GtkToolbar* toolbar ){
 +void XYWnd_constructToolbar( ui::Toolbar toolbar ){
        toolbar_append_button( toolbar, "Change views (CTRL + TAB)", "view_change.png", "NextView" );
  }
  
 -void Manipulators_constructToolbar( GtkToolbar* toolbar ){
 +void Manipulators_constructToolbar( ui::Toolbar toolbar ){
        toolbar_append_toggle_button( toolbar, "Translate (W)", "select_mousetranslate.png", "MouseTranslate" );
        toolbar_append_toggle_button( toolbar, "Rotate (R)", "select_mouserotate.png", "MouseRotate" );
        toolbar_append_toggle_button( toolbar, "Scale (Q)", "select_mousescale.png", "MouseScale" );
        Clipper_constructToolbar( toolbar );
  }
  
 -GtkToolbar* create_main_toolbar( MainFrame::EViewStyle style ){
 -      GtkToolbar* toolbar = GTK_TOOLBAR( gtk_toolbar_new() );
 -      gtk_toolbar_set_orientation( toolbar, GTK_ORIENTATION_HORIZONTAL );
 +ui::Toolbar create_main_toolbar( MainFrame::EViewStyle style ){
 +      auto toolbar = ui::Toolbar::from( gtk_toolbar_new() );
 +      gtk_orientable_set_orientation( GTK_ORIENTABLE(toolbar), GTK_ORIENTATION_HORIZONTAL );
        gtk_toolbar_set_style( toolbar, GTK_TOOLBAR_ICONS );
  
 -      gtk_widget_show( GTK_WIDGET( toolbar ) );
 +      toolbar.show();
 +
 +      auto space = [&]() {
 +              auto btn = ui::ToolItem::from(gtk_separator_tool_item_new());
 +              btn.show();
 +              toolbar.add(btn);
 +      };
  
        File_constructToolbar( toolbar );
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
        UndoRedo_constructToolbar( toolbar );
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
        RotateFlip_constructToolbar( toolbar );
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
        Select_constructToolbar( toolbar );
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
        CSG_constructToolbar( toolbar );
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
        ComponentModes_constructToolbar( toolbar );
  
        if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft ) {
 -              gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +              space();
  
                XYWnd_constructToolbar( toolbar );
        }
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
        CamWnd_constructToolbar( toolbar );
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
        Manipulators_constructToolbar( toolbar );
  
        if ( g_Layout_enablePatchToolbar.m_value ) {
 -              gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +              space();
  
                Patch_constructToolbar( toolbar );
        }
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
 -      toolbar_append_toggle_button( toolbar, "Texture Lock (SHIFT + T)", "texture_lock.png", "TogTexLock" );
 +      toolbar_append_toggle_button( toolbar, "Texture Lock (SHIFT +T)", "texture_lock.png", "TogTexLock" );
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 +      space();
  
 -      GtkButton* g_view_entities_button = toolbar_append_button( toolbar, "Entities (N)", "entities.png", "ToggleEntityInspector" );
 -      // disable the console and texture button in the regular layouts
 -      if ( style != MainFrame::eRegular && style != MainFrame::eRegularLeft ) {
 -              GtkButton* g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.png", "ToggleConsole" );
 -              GtkButton* g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.png", "ToggleTextures" );
 +      /*auto g_view_entities_button =*/ toolbar_append_button( toolbar, "Entities (N)", "entities.png", "ToggleEntityInspector" );
 +      if ( style == MainFrame::eRegular || style == MainFrame::eRegularLeft ) {
 +              auto g_view_console_button = toolbar_append_button( toolbar, "Console (O)", "console.png", "ToggleConsole" );
 +              auto g_view_textures_button = toolbar_append_button( toolbar, "Texture Browser (T)", "texture_browser.png", "ToggleTextures" );
        }
 -
        // TODO: call light inspector
        //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.png", "ToggleLightInspector");
  
 -      gtk_toolbar_append_space( GTK_TOOLBAR( toolbar ) );
 -      GtkButton* g_refresh_models_button = toolbar_append_button( toolbar, "Refresh Models", "refresh_models.png", "RefreshReferences" );
 +      space();
 +      /*auto g_refresh_models_button =*/ toolbar_append_button( toolbar, "Refresh Models", "refresh_models.png", "RefreshReferences" );
  
        return toolbar;
  }
  
 -GtkWidget* create_main_statusbar( GtkWidget *pStatusLabel[c_count_status] ){
 -      GtkTable* table = GTK_TABLE( gtk_table_new( 1, c_count_status, FALSE ) );
 -      gtk_widget_show( GTK_WIDGET( table ) );
 +ui::Widget create_main_statusbar( ui::Widget pStatusLabel[c_count_status] ){
 +      auto table = ui::Table( 1, c_count_status, FALSE );
 +      table.show();
  
        {
 -              GtkLabel* label = GTK_LABEL( gtk_label_new( "Label" ) );
 +              auto label = ui::Label( "Label" );
                gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
                gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
 -              gtk_widget_show( GTK_WIDGET( label ) );
 -              gtk_table_attach_defaults( table, GTK_WIDGET( label ), 0, 1, 0, 1 );
 -              pStatusLabel[c_command_status] = GTK_WIDGET( label );
 +              label.show();
 +              table.attach(label, {0, 1, 0, 1});
 +              pStatusLabel[c_command_status] = ui::Widget(label );
        }
  
 -      for ( int i = 1; i < c_count_status; ++i )
 +      for (unsigned int i = 1; (int) i < c_count_status; ++i)
        {
 -              GtkFrame* frame = GTK_FRAME( gtk_frame_new( 0 ) );
 -              gtk_widget_show( GTK_WIDGET( frame ) );
 -              gtk_table_attach_defaults( table, GTK_WIDGET( frame ), i, i + 1, 0, 1 );
 +              auto frame = ui::Frame();
 +              frame.show();
 +              table.attach(frame, {i, i + 1, 0, 1});
                gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN );
  
 -              GtkLabel* label = GTK_LABEL( gtk_label_new( "Label" ) );
 +              auto label = ui::Label( "Label" );
                gtk_label_set_ellipsize( label, PANGO_ELLIPSIZE_END );
                gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
                gtk_misc_set_padding( GTK_MISC( label ), 4, 2 );
 -              gtk_widget_show( GTK_WIDGET( label ) );
 -              gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( label ) );
 -              pStatusLabel[i] = GTK_WIDGET( label );
 +              label.show();
 +              frame.add(label);
 +              pStatusLabel[i] = ui::Widget(label );
        }
  
 -      return GTK_WIDGET( table );
 +      return ui::Widget(table );
  }
  
  #if 0
@@@ -2650,15 -2499,15 +2652,15 @@@ class WindowFocusPrinte
  {
  const char* m_name;
  
 -static gboolean frame_event( GtkWidget *widget, GdkEvent* event, WindowFocusPrinter* self ){
 +static gboolean frame_event( ui::Widget widget, GdkEvent* event, WindowFocusPrinter* self ){
        globalOutputStream() << self->m_name << " frame_event\n";
        return FALSE;
  }
 -static gboolean keys_changed( GtkWidget *widget, WindowFocusPrinter* self ){
 +static gboolean keys_changed( ui::Widget widget, WindowFocusPrinter* self ){
        globalOutputStream() << self->m_name << " keys_changed\n";
        return FALSE;
  }
 -static gboolean notify( GtkWindow* window, gpointer dummy, WindowFocusPrinter* self ){
 +static gboolean notify( ui::Window window, gpointer dummy, WindowFocusPrinter* self ){
        if ( gtk_window_is_active( window ) ) {
                globalOutputStream() << self->m_name << " takes toplevel focus\n";
        }
  public:
  WindowFocusPrinter( const char* name ) : m_name( name ){
  }
 -void connect( GtkWindow* toplevel_window ){
 -      g_signal_connect( G_OBJECT( toplevel_window ), "notify::has_toplevel_focus", G_CALLBACK( notify ), this );
 -      g_signal_connect( G_OBJECT( toplevel_window ), "notify::is_active", G_CALLBACK( notify ), this );
 -      g_signal_connect( G_OBJECT( toplevel_window ), "keys_changed", G_CALLBACK( keys_changed ), this );
 -      g_signal_connect( G_OBJECT( toplevel_window ), "frame_event", G_CALLBACK( frame_event ), this );
 +void connect( ui::Window toplevel_window ){
 +      toplevel_window.connect( "notify::has_toplevel_focus", G_CALLBACK( notify ), this );
 +      toplevel_window.connect( "notify::is_active", G_CALLBACK( notify ), this );
 +      toplevel_window.connect( "keys_changed", G_CALLBACK( keys_changed ), this );
 +      toplevel_window.connect( "frame_event", G_CALLBACK( frame_event ), this );
  }
  };
  
@@@ -2685,17 -2534,16 +2687,17 @@@ WindowFocusPrinter g_mainframeFocusPrin
  
  class MainWindowActive
  {
 -static gboolean notify( GtkWindow* window, gpointer dummy, MainWindowActive* self ){
 -      if ( g_wait.m_window != 0 && gtk_window_is_active( window ) && !GTK_WIDGET_VISIBLE( g_wait.m_window ) ) {
 -              gtk_widget_show( GTK_WIDGET( g_wait.m_window ) );
 +static gboolean notify( ui::Window window, gpointer dummy, MainWindowActive* self ){
 +      if ( g_wait.m_window && gtk_window_is_active( window ) && !g_wait.m_window.visible() ) {
 +              g_wait.m_window.show();
        }
  
        return FALSE;
  }
 +
  public:
 -void connect( GtkWindow* toplevel_window ){
 -      g_signal_connect( G_OBJECT( toplevel_window ), "notify::is-active", G_CALLBACK( notify ), this );
 +void connect( ui::Window toplevel_window ){
 +      toplevel_window.connect( "notify::is-active", G_CALLBACK( notify ), this );
  }
  };
  
@@@ -2722,14 -2570,16 +2724,14 @@@ void XYWindowMouseDown_disconnect( Mous
  
  MainFrame* g_pParentWnd = 0;
  
 -GtkWindow* MainFrame_getWindow(){
 -      if ( g_pParentWnd == 0 ) {
 -              return 0;
 -      }
 -      return g_pParentWnd->m_window;
 +ui::Window MainFrame_getWindow()
 +{
 +      return g_pParentWnd ? g_pParentWnd->m_window : ui::Window{ui::null};
  }
  
 -std::vector<GtkWidget*> g_floating_windows;
 +std::vector<ui::Widget> g_floating_windows;
  
 -MainFrame::MainFrame() : m_window( 0 ), m_idleRedrawStatusText( RedrawStatusTextCaller( *this ) ){
 +MainFrame::MainFrame() : m_idleRedrawStatusText( RedrawStatusTextCaller( *this ) ){
        m_pXYWnd = 0;
        m_pCamWnd = 0;
        m_pZWnd = 0;
        m_pXZWnd = 0;
        m_pActiveXY = 0;
  
 -      for ( int n = 0; n < c_count_status; n++ )
 -      {
 -              m_pStatusLabel[n] = 0;
 +      for (auto &n : m_pStatusLabel) {
 +        n = NULL;
        }
  
        m_bSleeping = false;
  MainFrame::~MainFrame(){
        SaveWindowInfo();
  
 -      gtk_widget_hide( GTK_WIDGET( m_window ) );
 +      m_window.hide();
  
        Shutdown();
  
 -      for ( std::vector<GtkWidget*>::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i )
 +      for ( std::vector<ui::Widget>::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i )
        {
 -              gtk_widget_destroy( *i );
 +              i->destroy();
        }
  
 -      gtk_widget_destroy( GTK_WIDGET( m_window ) );
 +      m_window.destroy();
  }
  
  void MainFrame::SetActiveXY( XYWnd* p ){
@@@ -2820,7 -2671,7 +2822,7 @@@ void MainFrame::CreateContexts()
  #endif
  }
  
 -#ifdef _DEBUG
 +#if GDEF_DEBUG
  //#define DBG_SLEEP
  #endif
  
@@@ -2878,35 -2729,35 +2880,35 @@@ void MainFrame::OnSleep()
  }
  
  
 -GtkWindow* create_splash(){
 -      GtkWindow* window = GTK_WINDOW( gtk_window_new( GTK_WINDOW_TOPLEVEL ) );
 -      gtk_window_set_decorated( window, FALSE );
 -      gtk_window_set_resizable( window, FALSE );
 -      gtk_window_set_modal( window, TRUE );
 +ui::Window create_splash(){
 +      auto window = ui::Window( ui::window_type::TOP );
 +      gtk_window_set_decorated(window, false);
 +      gtk_window_set_resizable(window, false);
 +      gtk_window_set_modal(window, true);
        gtk_window_set_default_size( window, -1, -1 );
        gtk_window_set_position( window, GTK_WIN_POS_CENTER );
 -      gtk_container_set_border_width( GTK_CONTAINER( window ), 0 );
 +      gtk_container_set_border_width(window, 0);
  
 -      GtkImage* image = new_local_image( "splash.png" );
 -      gtk_widget_show( GTK_WIDGET( image ) );
 -      gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( image ) );
 +      auto image = new_local_image( "splash.png" );
 +      image.show();
 +      window.add(image);
  
 -      gtk_widget_set_size_request( GTK_WIDGET( window ), -1, -1 );
 -      gtk_widget_show( GTK_WIDGET( window ) );
 +      window.dimensions(-1, -1);
 +      window.show();
  
        return window;
  }
  
 -static GtkWindow *splash_screen = 0;
 +static ui::Window splash_screen{ui::null};
  
  void show_splash(){
        splash_screen = create_splash();
  
 -      process_gui();
 +      ui::process();
  }
  
  void hide_splash(){
 -      gtk_widget_destroy( GTK_WIDGET( splash_screen ) );
 +      splash_screen.destroy();
  }
  
  WindowPositionTracker g_posCamWnd;
@@@ -2914,7 -2765,7 +2916,7 @@@ WindowPositionTracker g_posXYWnd
  WindowPositionTracker g_posXZWnd;
  WindowPositionTracker g_posYZWnd;
  
 -static gint mainframe_delete( GtkWidget *widget, GdkEvent *event, gpointer data ){
 +static gint mainframe_delete( ui::Widget widget, GdkEvent *event, gpointer data ){
        if ( ConfirmModified( "Exit Radiant" ) ) {
                gtk_main_quit();
        }
  }
  
  void MainFrame::Create(){
 -      GtkWindow* window = GTK_WINDOW( gtk_window_new( GTK_WINDOW_TOPLEVEL ) );
 +      ui::Window window = ui::Window( ui::window_type::TOP );
  
        GlobalWindowObservers_connectTopLevel( window );
  
        gtk_window_set_transient_for( splash_screen, window );
  
 -#if !defined( WIN32 )
 +#if !GDEF_OS_WINDOWS
        {
                GdkPixbuf* pixbuf = pixbuf_new_from_file_with_mask( "bitmaps/icon.png" );
                if ( pixbuf != 0 ) {
        }
  #endif
  
 -      gtk_widget_add_events( GTK_WIDGET( window ), GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK );
 -      g_signal_connect( G_OBJECT( window ), "delete_event", G_CALLBACK( mainframe_delete ), this );
 +      gtk_widget_add_events( window , GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK );
 +      window.connect( "delete_event", G_CALLBACK( mainframe_delete ), this );
  
        m_position_tracker.connect( window );
  
  
        g_MainWindowActive.connect( window );
  
 -      GetPlugInMgr().Init( GTK_WIDGET( window ) );
 +      GetPlugInMgr().Init( window );
  
 -      GtkWidget* vbox = gtk_vbox_new( FALSE, 0 );
 -      gtk_container_add( GTK_CONTAINER( window ), vbox );
 -      gtk_widget_show( vbox );
 +      auto vbox = ui::VBox( FALSE, 0 );
 +      window.add(vbox);
 +      vbox.show();
        gtk_container_set_focus_chain( GTK_CONTAINER( vbox ), NULL );
  
        global_accel_connect_window( window );
  
        register_shortcuts();
  
 -      GtkMenuBar* main_menu = create_main_menu( CurrentStyle() );
 -      gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( main_menu ), FALSE, FALSE, 0 );
 -
 -      GtkToolbar* main_toolbar = create_main_toolbar( CurrentStyle() );
 -      gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( main_toolbar ), FALSE, FALSE, 0 );
 -
 -
 +    auto main_menu = create_main_menu( CurrentStyle() );
 +      vbox.pack_start( main_menu, FALSE, FALSE, 0 );
  
 +    auto main_toolbar = create_main_toolbar( CurrentStyle() );
 +      vbox.pack_start( main_toolbar, FALSE, FALSE, 0 );
  
        if ( g_Layout_enablePluginToolbar.m_value || g_Layout_enableFilterToolbar.m_value ){
 -              GtkWidget* PFbox = gtk_hbox_new( FALSE, 3 );
 -              gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( PFbox ), FALSE, FALSE, 0 );
 -              gtk_widget_show( PFbox );
 +              auto PFbox = ui::HBox( FALSE, 3 );
 +              vbox.pack_start( PFbox, FALSE, FALSE, 0 );
 +              PFbox.show();
                if ( g_Layout_enablePluginToolbar.m_value ){
 -                      GtkToolbar* plugin_toolbar = create_plugin_toolbar();
 +                      auto plugin_toolbar = create_plugin_toolbar();
                        if ( g_Layout_enableFilterToolbar.m_value ){
 -                              gtk_box_pack_start( GTK_BOX( PFbox ), GTK_WIDGET( plugin_toolbar ), FALSE, FALSE, 0 );
 +                              PFbox.pack_start( plugin_toolbar, FALSE, FALSE, 0 );
                        }
                        else{
 -                              gtk_box_pack_start( GTK_BOX( PFbox ), GTK_WIDGET( plugin_toolbar ), TRUE, TRUE, 0 );
 +                              PFbox.pack_start( plugin_toolbar, TRUE, TRUE, 0 );
                        }
                }
                if ( g_Layout_enableFilterToolbar.m_value ){
 -                      GtkToolbar* filter_toolbar = create_filter_toolbar();
 -                      gtk_box_pack_start( GTK_BOX( PFbox ), GTK_WIDGET( filter_toolbar ), TRUE, TRUE, 0 );
 +                      ui::Toolbar filter_toolbar = create_filter_toolbar();
 +                      PFbox.pack_start( filter_toolbar, TRUE, TRUE, 0 );
                }
        }
  
                gtk_widget_hide( GTK_WIDGET( plugin_toolbar ) );
        }*/
  
 -
 -
 -
 -      GtkWidget* main_statusbar = create_main_statusbar( m_pStatusLabel );
 -      gtk_box_pack_end( GTK_BOX( vbox ), main_statusbar, FALSE, TRUE, 2 );
 +      ui::Widget main_statusbar = create_main_statusbar(reinterpret_cast<ui::Widget *>(m_pStatusLabel));
 +      vbox.pack_end(main_statusbar, FALSE, TRUE, 2);
  
        GroupDialog_constructWindow( window );
  
                g_page_console = GroupDialog_addPage( "Console", Console_constructWindow( GroupDialog_getWindow() ), RawStringExportCaller( "Console" ) );
        }
  
 -#ifdef WIN32
 +#if GDEF_OS_WINDOWS
        if ( g_multimon_globals.m_bStartOnPrimMon ) {
                PositionWindowOnPrimaryScreen( g_layout_globals.m_position );
-               window_set_position( window, g_layout_globals.m_position );
        }
-       else
  #endif
-       if ( g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED ) {
-               gtk_window_maximize( window );
-               WindowPosition default_position( -1, -1, 640, 480 );
-               window_set_position( window, default_position );
-       }
-       else
-       {
-               window_set_position( window, g_layout_globals.m_position );
-       }
+       window_set_position( window, g_layout_globals.m_position );
  
        m_window = window;
  
 -      gtk_widget_show( GTK_WIDGET( window ) );
 +      window.show();
  
        if ( CurrentStyle() == eRegular || CurrentStyle() == eRegularLeft ) {
                {
 -                      GtkWidget* hsplit = gtk_hpaned_new();
 +                      ui::Widget hsplit = ui::HPaned(ui::New);
                        m_hSplit = hsplit;
 -                      gtk_box_pack_start( GTK_BOX( vbox ), hsplit, TRUE, TRUE, 0 );
 -                      gtk_widget_show( hsplit );
 +
 +                      vbox.pack_start( hsplit, TRUE, TRUE, 0 );
 +                      hsplit.show();
 +
                        {
 -                              GtkWidget* vsplit = gtk_vpaned_new();
 -                              gtk_widget_show( vsplit );
 +                              ui::Widget vsplit = ui::VPaned(ui::New);
 +                              vsplit.show();
                                m_vSplit = vsplit;
 -                              GtkWidget* vsplit2 = gtk_vpaned_new();
 -                              gtk_widget_show( vsplit2 );
 +
 +                              ui::Widget vsplit2 = ui::VPaned(ui::New);
 +                              vsplit2.show();
                                m_vSplit2 = vsplit2;
 +
                                if ( CurrentStyle() == eRegular ){
-                                       gtk_paned_add1( GTK_PANED( hsplit ), vsplit );
-                                       gtk_paned_add2( GTK_PANED( hsplit ), vsplit2 );
+                                       gtk_paned_pack1( GTK_PANED( hsplit ), vsplit, TRUE, TRUE );
+                                       gtk_paned_pack2( GTK_PANED( hsplit ), vsplit2, TRUE, TRUE );
                                }
                                else{
-                                       gtk_paned_add2( GTK_PANED( hsplit ), vsplit );
-                                       gtk_paned_add1( GTK_PANED( hsplit ), vsplit2 );
+                                       gtk_paned_pack2( GTK_PANED( hsplit ), vsplit, TRUE, TRUE );
+                                       gtk_paned_pack1( GTK_PANED( hsplit ), vsplit2, TRUE, TRUE );
                                }
 +
                                // console
 -                              GtkWidget* console_window = Console_constructWindow( window );
 +                              ui::Widget console_window = Console_constructWindow( window );
-                               gtk_paned_pack2( GTK_PANED( vsplit ), console_window, FALSE, TRUE );
+                               gtk_paned_pack2( GTK_PANED( vsplit ), console_window, TRUE, TRUE );
 -
 +                              
                                // xy
                                m_pXYWnd = new XYWnd();
                                m_pXYWnd->SetViewType( XY );
 -                              GtkWidget* xy_window = GTK_WIDGET( create_framed_widget( m_pXYWnd->GetWidget() ) );
 +                              ui::Widget xy_window = ui::Widget(create_framed_widget( m_pXYWnd->GetWidget( ) ));
-                               gtk_paned_add1( GTK_PANED( vsplit ), xy_window );
+                               gtk_paned_pack1( GTK_PANED( vsplit ), xy_window, TRUE, TRUE );
 +
                                {
                                        // camera
                                        m_pCamWnd = NewCamWnd();
                                        GlobalCamera_setCamWnd( *m_pCamWnd );
                                        CamWnd_setParent( *m_pCamWnd, window );
 -                                      GtkFrame* camera_window = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
 +                                      auto camera_window = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
  
-                                       gtk_paned_add1( GTK_PANED( vsplit2 ), camera_window  );
 -                                      gtk_paned_pack1( GTK_PANED( vsplit2 ), GTK_WIDGET( camera_window ), TRUE, TRUE );
++                                      gtk_paned_pack1( GTK_PANED( vsplit2 ), GTK_WIDGET( camera_window ) , TRUE, TRUE);
  
                                        // textures
 -                                      GtkFrame* texture_window = create_framed_widget( TextureBrowser_constructWindow( window ) );
 +                                      auto texture_window = create_framed_widget( TextureBrowser_constructWindow( window ) );
  
-                                       gtk_paned_add2( GTK_PANED( vsplit2 ), texture_window  );
+                                       gtk_paned_pack2( GTK_PANED( vsplit2 ), GTK_WIDGET( texture_window ), TRUE, TRUE );
                                }
                        }
                }
-               gtk_paned_set_position( GTK_PANED( m_vSplit ), g_layout_globals.nXYHeight );
-               if ( CurrentStyle() == eRegular ) {
-                       gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nXYWidth );
-               }
-               else
-               {
-                       gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nCamWidth );
-               }
-               gtk_paned_set_position( GTK_PANED( m_vSplit2 ), g_layout_globals.nCamHeight );
        }
        else if ( CurrentStyle() == eFloating ) {
                {
 -                      GtkWindow* window = create_persistent_floating_window( "Camera", m_window );
 +                      ui::Window window = ui::Window(create_persistent_floating_window( "Camera", m_window ));
                        global_accel_connect_window( window );
                        g_posCamWnd.connect( window );
  
 -                      gtk_widget_show( GTK_WIDGET( window ) );
 +                      window.show();
  
                        m_pCamWnd = NewCamWnd();
                        GlobalCamera_setCamWnd( *m_pCamWnd );
  
                        {
 -                              GtkFrame* frame = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
 -                              gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
 +                              auto frame = create_framed_widget( CamWnd_getWidget( *m_pCamWnd ) );
 +                              window.add(frame);
                        }
                        CamWnd_setParent( *m_pCamWnd, window );
 +#define GARUX_GTK_WORKAROUND
 +#ifndef GARUX_GTK_WORKAROUND
                        /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */
                        g_object_set_data( G_OBJECT( window ), "glwidget", CamWnd_getWidget( *m_pCamWnd ) );
 +#endif
  
 -                      g_floating_windows.push_back( GTK_WIDGET( window ) );
 +                      g_floating_windows.push_back( window );
                }
  
                {
 -                      GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( XY ), m_window );
 +                      ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( XY ), m_window ));
                        global_accel_connect_window( window );
                        g_posXYWnd.connect( window );
  
  
  
                        {
 -                              GtkFrame* frame = create_framed_widget( m_pXYWnd->GetWidget() );
 -                              gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
 +                              auto frame = create_framed_widget( m_pXYWnd->GetWidget() );
 +                              window.add(frame);
                        }
                        XY_Top_Shown_Construct( window );
 +#ifndef GARUX_GTK_WORKAROUND
                        /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */
                        g_object_set_data( G_OBJECT( window ), "glwidget", m_pXYWnd->GetWidget() );
 +#endif
  
 -                      g_floating_windows.push_back( GTK_WIDGET( window ) );
 +                      g_floating_windows.push_back( window );
                }
  
                {
 -                      GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( XZ ), m_window );
 +                      ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( XZ ), m_window ));
                        global_accel_connect_window( window );
                        g_posXZWnd.connect( window );
  
                        m_pXZWnd->SetViewType( XZ );
  
                        {
 -                              GtkFrame* frame = create_framed_widget( m_pXZWnd->GetWidget() );
 -                              gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
 +                              auto frame = create_framed_widget( m_pXZWnd->GetWidget() );
 +                              window.add(frame);
                        }
  
                        XZ_Front_Shown_Construct( window );
 +#ifndef GARUX_GTK_WORKAROUND
                        /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */
                        g_object_set_data( G_OBJECT( window ), "glwidget", m_pXZWnd->GetWidget() );
 +#endif
  
 -                      g_floating_windows.push_back( GTK_WIDGET( window ) );
 +                      g_floating_windows.push_back( window );
                }
  
                {
 -                      GtkWindow* window = create_persistent_floating_window( ViewType_getTitle( YZ ), m_window );
 +                      ui::Window window = ui::Window(create_persistent_floating_window( ViewType_getTitle( YZ ), m_window ));
                        global_accel_connect_window( window );
                        g_posYZWnd.connect( window );
  
                        m_pYZWnd->SetViewType( YZ );
  
                        {
 -                              GtkFrame* frame = create_framed_widget( m_pYZWnd->GetWidget() );
 -                              gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( frame ) );
 +                              auto frame = create_framed_widget( m_pYZWnd->GetWidget() );
 +                              window.add(frame);
                        }
  
                        YZ_Side_Shown_Construct( window );
 +#ifndef GARUX_GTK_WORKAROUND
                        /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */
                        g_object_set_data( G_OBJECT( window ), "glwidget", m_pYZWnd->GetWidget() );
 +#endif
  
 -                      g_floating_windows.push_back( GTK_WIDGET( window ) );
 +                      g_floating_windows.push_back( window );
                }
  
                {
 -                      GtkFrame* frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
 -                      g_page_textures = GroupDialog_addPage( "Textures", GTK_WIDGET( frame ), TextureBrowserExportTitleCaller() );
 +                      auto frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
 +                      g_page_textures = GroupDialog_addPage( "Textures", frame, TextureBrowserExportTitleCaller() );
 +#ifndef GARUX_GTK_WORKAROUND
                        /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */
                        g_object_set_data( G_OBJECT( GroupDialog_getWindow() ), "glwidget", TextureBrowser_getGLWidget() );
 +#endif
  
                }
  
                GlobalCamera_setCamWnd( *m_pCamWnd );
                CamWnd_setParent( *m_pCamWnd, window );
  
 -              GtkWidget* camera = CamWnd_getWidget( *m_pCamWnd );
 +              ui::Widget camera = CamWnd_getWidget( *m_pCamWnd );
  
                m_pYZWnd = new XYWnd();
                m_pYZWnd->SetViewType( YZ );
  
 -              GtkWidget* yz = m_pYZWnd->GetWidget();
 +              ui::Widget yz = m_pYZWnd->GetWidget();
  
                m_pXYWnd = new XYWnd();
                m_pXYWnd->SetViewType( XY );
  
 -              GtkWidget* xy = m_pXYWnd->GetWidget();
 +              ui::Widget xy = m_pXYWnd->GetWidget();
  
                m_pXZWnd = new XYWnd();
                m_pXZWnd->SetViewType( XZ );
  
 -              GtkWidget* xz = m_pXZWnd->GetWidget();
 +              ui::Widget xz = m_pXZWnd->GetWidget();
  
 -              GtkHPaned* split = create_split_views( camera, yz, xy, xz );
 -              gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( split ), TRUE, TRUE, 0 );
 +        auto split = create_split_views( camera, yz, xy, xz );
 +              vbox.pack_start( split, TRUE, TRUE, 0 );
  
                {
 -                      GtkFrame* frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
 -                      g_page_textures = GroupDialog_addPage( "Textures", GTK_WIDGET( frame ), TextureBrowserExportTitleCaller() );
 +            auto frame = create_framed_widget( TextureBrowser_constructWindow( GroupDialog_getWindow() ) );
 +                      g_page_textures = GroupDialog_addPage( "Textures", frame, TextureBrowserExportTitleCaller() );
 +#ifndef GARUX_GTK_WORKAROUND
                        /* workaround for gtk 2.24 issue: not displayed glwidget after toggle */
                        g_object_set_data( G_OBJECT( GroupDialog_getWindow() ), "glwidget", TextureBrowser_getGLWidget() );
 +#endif
                }
        }
  
        SetActiveXY( m_pXYWnd );
  
        AddGridChangeCallback( SetGridStatusCaller( *this ) );
 -      AddGridChangeCallback( ReferenceCaller<MainFrame, XY_UpdateAllWindows>( *this ) );
 +      AddGridChangeCallback( ReferenceCaller<MainFrame, void(), XY_UpdateAllWindows>( *this ) );
  
        g_defaultToolMode = DragMode;
        g_defaultToolMode();
  
        EverySecondTimer_enable();
  
+       if ( g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED ) {
+               gtk_window_maximize( window );
+       }
+       if ( g_layout_globals.nState & GDK_WINDOW_STATE_FULLSCREEN ) {
+               gtk_window_fullscreen( window );
+       }
+       if ( !FloatingGroupDialog() ) {
+               gtk_paned_set_position( GTK_PANED( m_vSplit ), g_layout_globals.nXYHeight );
+               if ( CurrentStyle() == eRegular ) {
+                       gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nXYWidth );
+               }
+               else
+               {
+                       gtk_paned_set_position( GTK_PANED( m_hSplit ), g_layout_globals.nCamWidth );
+               }
+               gtk_paned_set_position( GTK_PANED( m_vSplit2 ), g_layout_globals.nCamHeight );
+       }
        //GlobalShortcuts_reportUnregistered();
  }
  
@@@ -3271,9 -3106,11 +3270,11 @@@ void MainFrame::SaveWindowInfo()
                g_layout_globals.nCamHeight = gtk_paned_get_position( GTK_PANED( m_vSplit2 ) );
        }
  
-       g_layout_globals.m_position = m_position_tracker.getPosition();
+       if( gdk_window_get_state( GTK_WIDGET( m_window )->window ) == 0 ){
+               g_layout_globals.m_position = m_position_tracker.getPosition();
+       }
  
 -      g_layout_globals.nState = gdk_window_get_state( GTK_WIDGET( m_window )->window );
 +      g_layout_globals.nState = gdk_window_get_state( gtk_widget_get_window(m_window ) );
  }
  
  void MainFrame::Shutdown(){
  }
  
  void MainFrame::RedrawStatusText(){
 -      gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_command_status] ), m_command_status.c_str() );
 -      gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_position_status] ), m_position_status.c_str() );
 -      gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_brushcount_status] ), m_brushcount_status.c_str() );
 -      gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_texture_status] ), m_texture_status.c_str() );
 -      gtk_label_set_text( GTK_LABEL( m_pStatusLabel[c_grid_status] ), m_grid_status.c_str() );
 +      ui::Label::from(m_pStatusLabel[c_command_status]).text(m_command_status.c_str());
 +      ui::Label::from(m_pStatusLabel[c_position_status]).text(m_position_status.c_str());
 +      ui::Label::from(m_pStatusLabel[c_brushcount_status]).text(m_brushcount_status.c_str());
 +      ui::Label::from(m_pStatusLabel[c_texture_status]).text(m_texture_status.c_str());
 +      ui::Label::from(m_pStatusLabel[c_grid_status]).text(m_grid_status.c_str());
  }
  
  void MainFrame::UpdateStatusText(){
@@@ -3336,11 -3173,8 +3337,11 @@@ int getFarClipDistance()
  }
  
  float ( *GridStatus_getGridSize )() = GetGridSize;
 +
  int ( *GridStatus_getRotateIncrement )() = getRotateIncrement;
 +
  int ( *GridStatus_getFarClipDistance )() = getFarClipDistance;
 +
  bool ( *GridStatus_getTextureLockEnabled )();
  
  void MainFrame::SetGridStatus(){
@@@ -3366,8 -3200,7 +3367,8 @@@ void GlobalGL_sharedContextCreated()
        globalOutputStream() << "GL_VENDOR: " << reinterpret_cast<const char*>( glGetString( GL_VENDOR ) ) << "\n";
        globalOutputStream() << "GL_RENDERER: " << reinterpret_cast<const char*>( glGetString( GL_RENDERER ) ) << "\n";
        globalOutputStream() << "GL_VERSION: " << reinterpret_cast<const char*>( glGetString( GL_VERSION ) ) << "\n";
 -      globalOutputStream() << "GL_EXTENSIONS: " << reinterpret_cast<const char*>( glGetString( GL_EXTENSIONS ) ) << "\n";
 +    const auto extensions = reinterpret_cast<const char*>( glGetString(GL_EXTENSIONS ) );
 +    globalOutputStream() << "GL_EXTENSIONS: " << (extensions ? extensions : "") << "\n";
  
        QGL_sharedContextCreated( GlobalOpenGL() );
  
        GlobalShaderCache().realise();
        Textures_Realise();
  
 -#ifdef WIN32
 +#if GDEF_OS_WINDOWS
        /* win32 is dodgy here, just use courier new then */
        g_font = glfont_create( "arial 9" );
  #else
 -      GtkSettings *settings = gtk_settings_get_default();
 +      auto settings = gtk_settings_get_default();
        gchar *fontname;
        g_object_get( settings, "gtk-font-name", &fontname, NULL );
        g_font = glfont_create( fontname );
@@@ -3403,26 -3236,31 +3404,26 @@@ void Layout_constructPreferences( Prefe
                page.appendRadioIcons(
                        "Window Layout",
                        STRING_ARRAY_RANGE( layouts ),
 -                      LatchedIntImportCaller( g_Layout_viewStyle ),
 -                      IntExportCaller( g_Layout_viewStyle.m_latched )
 +                      make_property( g_Layout_viewStyle )
                        );
        }
        page.appendCheckBox(
                "", "Detachable Menus",
 -              LatchedBoolImportCaller( g_Layout_enableDetachableMenus ),
 -              BoolExportCaller( g_Layout_enableDetachableMenus.m_latched )
 +              make_property( g_Layout_enableDetachableMenus )
                );
        if ( !string_empty( g_pGameDescription->getKeyValue( "no_patch" ) ) ) {
                page.appendCheckBox(
                        "", "Patch Toolbar",
 -                      LatchedBoolImportCaller( g_Layout_enablePatchToolbar ),
 -                      BoolExportCaller( g_Layout_enablePatchToolbar.m_latched )
 +                      make_property( g_Layout_enablePatchToolbar )
                        );
        }
        page.appendCheckBox(
                "", "Plugin Toolbar",
 -              LatchedBoolImportCaller( g_Layout_enablePluginToolbar ),
 -              BoolExportCaller( g_Layout_enablePluginToolbar.m_latched )
 +              make_property( g_Layout_enablePluginToolbar )
                );
        page.appendCheckBox(
                "", "Filter Toolbar",
 -              LatchedBoolImportCaller( g_Layout_enableFilterToolbar ),
 -              BoolExportCaller( g_Layout_enableFilterToolbar.m_latched )
 +              make_property( g_Layout_enableFilterToolbar )
                );
  }
  
@@@ -3432,92 -3270,112 +3433,113 @@@ void Layout_constructPage( PreferenceGr
  }
  
  void Layout_registerPreferencesPage(){
 -      PreferencesDialog_addInterfacePage( FreeCaller1<PreferenceGroup&, Layout_constructPage>() );
 +      PreferencesDialog_addInterfacePage( makeCallbackF(Layout_constructPage) );
  }
  
+ void MainFrame_toggleFullscreen(){
+       GtkWindow* wnd = MainFrame_getWindow();
+       if( gdk_window_get_state( GTK_WIDGET( wnd )->window ) & GDK_WINDOW_STATE_FULLSCREEN ){
+               //some portion of buttsex, because gtk_window_unfullscreen doesn't work correctly after calling some modal window
+               bool maximize = ( gdk_window_get_state( GTK_WIDGET( wnd )->window ) & GDK_WINDOW_STATE_MAXIMIZED );
+               gtk_window_unfullscreen( wnd );
+               if( maximize ){
+                       gtk_window_unmaximize( wnd );
+                       gtk_window_maximize( wnd );
+               }
+               else{
+                       gtk_window_move( wnd, g_layout_globals.m_position.x, g_layout_globals.m_position.y );
+                       gtk_window_resize( wnd, g_layout_globals.m_position.w, g_layout_globals.m_position.h );
+               }
+       }
+       else{
+               gtk_window_fullscreen( wnd );
+       }
+ }
  
  #include "preferencesystem.h"
  #include "stringio.h"
  
  void MainFrame_Construct(){
 -      GlobalCommands_insert( "OpenManual", FreeCaller<OpenHelpURL>(), Accelerator( GDK_F1 ) );
 -
 -      GlobalCommands_insert( "Sleep", FreeCaller<thunk_OnSleep>(), Accelerator( 'P', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
 -      GlobalCommands_insert( "NewMap", FreeCaller<NewMap>() );
 -      GlobalCommands_insert( "OpenMap", FreeCaller<OpenMap>(), Accelerator( 'O', (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "ImportMap", FreeCaller<ImportMap>() );
 -      GlobalCommands_insert( "SaveMap", FreeCaller<SaveMap>(), Accelerator( 'S', (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "SaveMapAs", FreeCaller<SaveMapAs>() );
 -      GlobalCommands_insert( "SaveSelected", FreeCaller<ExportMap>() );
 -      GlobalCommands_insert( "SaveRegion", FreeCaller<SaveRegion>() );
 -      GlobalCommands_insert( "RefreshReferences", FreeCaller<RefreshReferences>() );
 -      GlobalCommands_insert( "ProjectSettings", FreeCaller<DoProjectSettings>() );
 -      GlobalCommands_insert( "CheckForUpdate", FreeCaller<OpenUpdateURL>() );
 -      GlobalCommands_insert( "Exit", FreeCaller<Exit>() );
 -
 -      GlobalCommands_insert( "Undo", FreeCaller<Undo>(), Accelerator( 'Z', (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "Redo", FreeCaller<Redo>(), Accelerator( 'Y', (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "Copy", FreeCaller<Copy>(), Accelerator( 'C', (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "Paste", FreeCaller<Paste>(), Accelerator( 'V', (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "PasteToCamera", FreeCaller<PasteToCamera>(), Accelerator( 'V', (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "CloneSelection", FreeCaller<Selection_Clone>(), Accelerator( GDK_space ) );
 -      GlobalCommands_insert( "CloneSelectionAndMakeUnique", FreeCaller<Selection_Clone_MakeUnique>(), Accelerator( GDK_space, (GdkModifierType)GDK_SHIFT_MASK ) );
 -//    GlobalCommands_insert( "DeleteSelection", FreeCaller<deleteSelection>(), Accelerator( GDK_BackSpace ) );
 -      GlobalCommands_insert( "DeleteSelection2", FreeCaller<deleteSelection>(), Accelerator( GDK_BackSpace ) );
 -      GlobalCommands_insert( "DeleteSelection", FreeCaller<deleteSelection>(), Accelerator( 'Z' ) );
 -      GlobalCommands_insert( "ParentSelection", FreeCaller<Scene_parentSelected>() );
 -//    GlobalCommands_insert( "UnSelectSelection", FreeCaller<Selection_Deselect>(), Accelerator( GDK_Escape ) );
 -      GlobalCommands_insert( "UnSelectSelection2", FreeCaller<Selection_Deselect>(), Accelerator( GDK_Escape ) );
 -      GlobalCommands_insert( "UnSelectSelection", FreeCaller<Selection_Deselect>(), Accelerator( 'C' ) );
 -      GlobalCommands_insert( "InvertSelection", FreeCaller<Select_Invert>(), Accelerator( 'I' ) );
 -      GlobalCommands_insert( "SelectInside", FreeCaller<Select_Inside>() );
 -      GlobalCommands_insert( "SelectTouching", FreeCaller<Select_Touching>() );
 -      GlobalCommands_insert( "ExpandSelectionToEntities", FreeCaller<Scene_ExpandSelectionToEntities>(), Accelerator( 'E', (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "Preferences", FreeCaller<PreferencesDialog_showDialog>(), Accelerator( 'P' ) );
 -
 -      GlobalCommands_insert( "ToggleConsole", FreeCaller<Console_ToggleShow>(), Accelerator( 'O' ) );
 -      GlobalCommands_insert( "ToggleEntityInspector", FreeCaller<EntityInspector_ToggleShow>(), Accelerator( 'N' ) );
 -      GlobalCommands_insert( "EntityList", FreeCaller<EntityList_toggleShown>(), Accelerator( 'L' ) );
 -
 -      GlobalCommands_insert( "ShowHidden", FreeCaller<Select_ShowAllHidden>(), Accelerator( 'H', (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "HideSelected", FreeCaller<HideSelected>(), Accelerator( 'H' ) );
 -
 -      GlobalToggles_insert( "DragVertices", FreeCaller<SelectVertexMode>(), ToggleItem::AddCallbackCaller( g_vertexMode_button ), Accelerator( 'V' ) );
 -      GlobalToggles_insert( "DragEdges", FreeCaller<SelectEdgeMode>(), ToggleItem::AddCallbackCaller( g_edgeMode_button ), Accelerator( 'E' ) );
 -      GlobalToggles_insert( "DragFaces", FreeCaller<SelectFaceMode>(), ToggleItem::AddCallbackCaller( g_faceMode_button ), Accelerator( 'F' ) );
 -
 -      GlobalCommands_insert( "MirrorSelectionX", FreeCaller<Selection_Flipx>() );
 -      GlobalCommands_insert( "RotateSelectionX", FreeCaller<Selection_Rotatex>() );
 -      GlobalCommands_insert( "MirrorSelectionY", FreeCaller<Selection_Flipy>() );
 -      GlobalCommands_insert( "RotateSelectionY", FreeCaller<Selection_Rotatey>() );
 -      GlobalCommands_insert( "MirrorSelectionZ", FreeCaller<Selection_Flipz>() );
 -      GlobalCommands_insert( "RotateSelectionZ", FreeCaller<Selection_Rotatez>() );
 -
 -      GlobalCommands_insert( "ArbitraryRotation", FreeCaller<DoRotateDlg>(), Accelerator( 'R', (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "ArbitraryScale", FreeCaller<DoScaleDlg>(), Accelerator( 'S', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
 -
 -      GlobalCommands_insert( "BuildMenuCustomize", FreeCaller<DoBuildMenu>() );
 -      GlobalCommands_insert( "Build_runRecentExecutedBuild", FreeCaller<Build_runRecentExecutedBuild>(), Accelerator( GDK_F5 ) );
 -
 -      GlobalCommands_insert( "FindBrush", FreeCaller<DoFind>() );
 -
 -      GlobalCommands_insert( "MapInfo", FreeCaller<DoMapInfo>(), Accelerator( 'M' ) );
 -
 -
 -      GlobalToggles_insert( "ToggleClipper", FreeCaller<ClipperMode>(), ToggleItem::AddCallbackCaller( g_clipper_button ), Accelerator( 'X' ) );
 -
 -      GlobalToggles_insert( "MouseTranslate", FreeCaller<TranslateMode>(), ToggleItem::AddCallbackCaller( g_translatemode_button ), Accelerator( 'W' ) );
 -      GlobalToggles_insert( "MouseRotate", FreeCaller<RotateMode>(), ToggleItem::AddCallbackCaller( g_rotatemode_button ), Accelerator( 'R' ) );
 -      GlobalToggles_insert( "MouseScale", FreeCaller<ScaleMode>(), ToggleItem::AddCallbackCaller( g_scalemode_button ) );
 -      GlobalToggles_insert( "MouseDrag", FreeCaller<DragMode>(), ToggleItem::AddCallbackCaller( g_dragmode_button ) );
 -      GlobalCommands_insert( "MouseRotateOrScale", FreeCaller<ToggleRotateScaleModes>() );
 -      GlobalCommands_insert( "MouseDragOrScale", FreeCaller<ToggleDragScaleModes>(), Accelerator( 'Q' ) );
 -
 -      GlobalCommands_insert( "gtkThemeDlg", FreeCaller<gtkThemeDlg>() );
 -      GlobalCommands_insert( "ColorSchemeOriginal", FreeCaller<ColorScheme_Original>() );
 -      GlobalCommands_insert( "ColorSchemeQER", FreeCaller<ColorScheme_QER>() );
 -      GlobalCommands_insert( "ColorSchemeBlackAndGreen", FreeCaller<ColorScheme_Black>() );
 -      GlobalCommands_insert( "ColorSchemeYdnar", FreeCaller<ColorScheme_Ydnar>() );
 +      GlobalCommands_insert( "OpenManual", makeCallbackF(OpenHelpURL), Accelerator( GDK_KEY_F1 ) );
 +
 +      GlobalCommands_insert( "Sleep", makeCallbackF(thunk_OnSleep), Accelerator( 'P', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
 +      GlobalCommands_insert( "NewMap", makeCallbackF(NewMap) );
 +      GlobalCommands_insert( "OpenMap", makeCallbackF(OpenMap), Accelerator( 'O', (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "ImportMap", makeCallbackF(ImportMap) );
 +      GlobalCommands_insert( "SaveMap", makeCallbackF(SaveMap), Accelerator( 'S', (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "SaveMapAs", makeCallbackF(SaveMapAs) );
 +      GlobalCommands_insert( "ExportSelected", makeCallbackF(ExportMap) );
 +      GlobalCommands_insert( "SaveRegion", makeCallbackF(SaveRegion) );
 +      GlobalCommands_insert( "RefreshReferences", makeCallbackF(VFS_Refresh) );
 +      GlobalCommands_insert( "ProjectSettings", makeCallbackF(DoProjectSettings) );
 +      GlobalCommands_insert( "Exit", makeCallbackF(Exit) );
 +
 +      GlobalCommands_insert( "Undo", makeCallbackF(Undo), Accelerator( 'Z', (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "Redo", makeCallbackF(Redo), Accelerator( 'Y', (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "Copy", makeCallbackF(Copy), Accelerator( 'C', (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "Paste", makeCallbackF(Paste), Accelerator( 'V', (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "PasteToCamera", makeCallbackF(PasteToCamera), Accelerator( 'V', (GdkModifierType)GDK_MOD1_MASK ) );
 +      GlobalCommands_insert( "CloneSelection", makeCallbackF(Selection_Clone), Accelerator( GDK_KEY_space ) );
 +      GlobalCommands_insert( "CloneSelectionAndMakeUnique", makeCallbackF(Selection_Clone_MakeUnique), Accelerator( GDK_KEY_space, (GdkModifierType)GDK_SHIFT_MASK ) );
 +//    GlobalCommands_insert( "DeleteSelection", makeCallbackF(deleteSelection), Accelerator( GDK_KEY_BackSpace ) );
 +      GlobalCommands_insert( "DeleteSelection2", makeCallbackF(deleteSelection), Accelerator( GDK_KEY_BackSpace ) );
 +      GlobalCommands_insert( "DeleteSelection", makeCallbackF(deleteSelection), Accelerator( 'Z' ) );
 +      GlobalCommands_insert( "ParentSelection", makeCallbackF(Scene_parentSelected) );
 +//    GlobalCommands_insert( "UnSelectSelection", makeCallbackF(Selection_Deselect), Accelerator( GDK_KEY_Escape ) );
 +      GlobalCommands_insert( "UnSelectSelection2", makeCallbackF(Selection_Deselect), Accelerator( GDK_KEY_Escape ) );
 +      GlobalCommands_insert( "UnSelectSelection", makeCallbackF(Selection_Deselect), Accelerator( 'C' ) );
 +      GlobalCommands_insert( "InvertSelection", makeCallbackF(Select_Invert), Accelerator( 'I' ) );
 +      GlobalCommands_insert( "SelectInside", makeCallbackF(Select_Inside) );
 +      GlobalCommands_insert( "SelectTouching", makeCallbackF(Select_Touching) );
 +      GlobalCommands_insert( "ExpandSelectionToEntities", makeCallbackF(Scene_ExpandSelectionToEntities), Accelerator( 'E', (GdkModifierType)( GDK_MOD1_MASK | GDK_CONTROL_MASK ) ) );
 +      GlobalCommands_insert( "Preferences", makeCallbackF(PreferencesDialog_showDialog), Accelerator( 'P' ) );
 +
 +      GlobalCommands_insert( "ToggleConsole", makeCallbackF(Console_ToggleShow), Accelerator( 'O' ) );
 +      GlobalCommands_insert( "ToggleEntityInspector", makeCallbackF(EntityInspector_ToggleShow), Accelerator( 'N' ) );
 +      GlobalCommands_insert( "EntityList", makeCallbackF(EntityList_toggleShown), Accelerator( 'L' ) );
 +
 +      GlobalCommands_insert( "ShowHidden", makeCallbackF(Select_ShowAllHidden), Accelerator( 'H', (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "HideSelected", makeCallbackF(HideSelected), Accelerator( 'H' ) );
 +
 +      GlobalToggles_insert( "DragVertices", makeCallbackF(SelectVertexMode), ToggleItem::AddCallbackCaller( g_vertexMode_button ), Accelerator( 'V' ) );
 +      GlobalToggles_insert( "DragEdges", makeCallbackF(SelectEdgeMode), ToggleItem::AddCallbackCaller( g_edgeMode_button ), Accelerator( 'E' ) );
 +      GlobalToggles_insert( "DragFaces", makeCallbackF(SelectFaceMode), ToggleItem::AddCallbackCaller( g_faceMode_button ), Accelerator( 'F' ) );
 +
 +      GlobalCommands_insert( "MirrorSelectionX", makeCallbackF(Selection_Flipx) );
 +      GlobalCommands_insert( "RotateSelectionX", makeCallbackF(Selection_Rotatex) );
 +      GlobalCommands_insert( "MirrorSelectionY", makeCallbackF(Selection_Flipy) );
 +      GlobalCommands_insert( "RotateSelectionY", makeCallbackF(Selection_Rotatey) );
 +      GlobalCommands_insert( "MirrorSelectionZ", makeCallbackF(Selection_Flipz) );
 +      GlobalCommands_insert( "RotateSelectionZ", makeCallbackF(Selection_Rotatez) );
 +
 +      GlobalCommands_insert( "ArbitraryRotation", makeCallbackF(DoRotateDlg) );
 +      GlobalCommands_insert( "ArbitraryScale", makeCallbackF(DoScaleDlg) );
 +
 +      GlobalCommands_insert( "BuildMenuCustomize", makeCallbackF(DoBuildMenu) );
++      GlobalCommands_insert( "Build_runRecentExecutedBuild", makeCallbackF(Build_runRecentExecutedBuild), Accelerator( GDK_F5 ) );
 +
 +      GlobalCommands_insert( "FindBrush", makeCallbackF(DoFind) );
 +
 +      GlobalCommands_insert( "MapInfo", makeCallbackF(DoMapInfo), Accelerator( 'M' ) );
 +
 +
 +      GlobalToggles_insert( "ToggleClipper", makeCallbackF(ClipperMode), ToggleItem::AddCallbackCaller( g_clipper_button ), Accelerator( 'X' ) );
 +
 +      GlobalToggles_insert( "MouseTranslate", makeCallbackF(TranslateMode), ToggleItem::AddCallbackCaller( g_translatemode_button ), Accelerator( 'W' ) );
 +      GlobalToggles_insert( "MouseRotate", makeCallbackF(RotateMode), ToggleItem::AddCallbackCaller( g_rotatemode_button ), Accelerator( 'R' ) );
 +      GlobalToggles_insert( "MouseScale", makeCallbackF(ScaleMode), ToggleItem::AddCallbackCaller( g_scalemode_button ) );
 +      GlobalToggles_insert( "MouseDrag", makeCallbackF(DragMode), ToggleItem::AddCallbackCaller( g_dragmode_button ) );
 +      GlobalCommands_insert( "MouseRotateOrScale", makeCallbackF(ToggleRotateScaleModes) );
 +      GlobalCommands_insert( "MouseDragOrScale", makeCallbackF(ToggleDragScaleModes), Accelerator( 'Q' ) );
 +
 +#ifndef GARUX_DISABLE_GTKTHEME
 +      GlobalCommands_insert( "gtkThemeDlg", makeCallbackF(gtkThemeDlg) );
 +#endif
 +      GlobalCommands_insert( "ColorSchemeOriginal", makeCallbackF(ColorScheme_Original) );
 +      GlobalCommands_insert( "ColorSchemeQER", makeCallbackF(ColorScheme_QER) );
 +      GlobalCommands_insert( "ColorSchemeBlackAndGreen", makeCallbackF(ColorScheme_Black) );
 +      GlobalCommands_insert( "ColorSchemeYdnar", makeCallbackF(ColorScheme_Ydnar) );
        GlobalCommands_insert( "ChooseTextureBackgroundColor", makeCallback( g_ColoursMenu.m_textureback ) );
        GlobalCommands_insert( "ChooseGridBackgroundColor", makeCallback( g_ColoursMenu.m_xyback ) );
        GlobalCommands_insert( "ChooseGridMajorColor", makeCallback( g_ColoursMenu.m_gridmajor ) );
        GlobalCommands_insert( "ChooseClipperColor", makeCallback( g_ColoursMenu.m_clipper ) );
        GlobalCommands_insert( "ChooseOrthoViewNameColor", makeCallback( g_ColoursMenu.m_viewname ) );
  
 -      GlobalCommands_insert( "Fullscreen", FreeCaller<MainFrame_toggleFullscreen>(), Accelerator( GDK_F11 ) );
++      GlobalCommands_insert( "Fullscreen", makeCallbackF( MainFrame_toggleFullscreen ), Accelerator( GDK_F11 ) );
  
 -      GlobalCommands_insert( "CSGSubtract", FreeCaller<CSG_Subtract>(), Accelerator( 'U', (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "CSGMerge", FreeCaller<CSG_Merge>(), Accelerator( 'U', (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "CSGroom", FreeCaller<CSG_MakeRoom>() );
 -      GlobalCommands_insert( "CSGTool", FreeCaller<CSG_Tool>() );
 +      GlobalCommands_insert( "CSGSubtract", makeCallbackF(CSG_Subtract), Accelerator( 'U', (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "CSGMerge", makeCallbackF(CSG_Merge), Accelerator( 'U', (GdkModifierType) GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "CSGRoom", makeCallbackF(CSG_MakeRoom) );
 +      GlobalCommands_insert( "CSGTool", makeCallbackF(CSG_Tool) );
  
        Grid_registerCommands();
  
 -      GlobalCommands_insert( "SnapToGrid", FreeCaller<Selection_SnapToGrid>(), Accelerator( 'G', (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "SnapToGrid", makeCallbackF(Selection_SnapToGrid), Accelerator( 'G', (GdkModifierType)GDK_CONTROL_MASK ) );
  
 -      GlobalCommands_insert( "SelectAllOfType", FreeCaller<Select_AllOfType>(), Accelerator( 'A', (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "SelectAllOfType", makeCallbackF(Select_AllOfType), Accelerator( 'A', (GdkModifierType)GDK_SHIFT_MASK ) );
  
 -      GlobalCommands_insert( "TexRotateClock", FreeCaller<Texdef_RotateClockwise>(), Accelerator( GDK_Next, (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "TexRotateCounter", FreeCaller<Texdef_RotateAntiClockwise>(), Accelerator( GDK_Prior, (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "TexScaleUp", FreeCaller<Texdef_ScaleUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "TexScaleDown", FreeCaller<Texdef_ScaleDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "TexScaleLeft", FreeCaller<Texdef_ScaleLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "TexScaleRight", FreeCaller<Texdef_ScaleRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_CONTROL_MASK ) );
 -      GlobalCommands_insert( "TexShiftUp", FreeCaller<Texdef_ShiftUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "TexShiftDown", FreeCaller<Texdef_ShiftDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "TexShiftLeft", FreeCaller<Texdef_ShiftLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_SHIFT_MASK ) );
 -      GlobalCommands_insert( "TexShiftRight", FreeCaller<Texdef_ShiftRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "TexRotateClock", makeCallbackF(Texdef_RotateClockwise), Accelerator( GDK_KEY_Next, (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "TexRotateCounter", makeCallbackF(Texdef_RotateAntiClockwise), Accelerator( GDK_KEY_Prior, (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "TexScaleUp", makeCallbackF(Texdef_ScaleUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "TexScaleDown", makeCallbackF(Texdef_ScaleDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "TexScaleLeft", makeCallbackF(Texdef_ScaleLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "TexScaleRight", makeCallbackF(Texdef_ScaleRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_CONTROL_MASK ) );
 +      GlobalCommands_insert( "TexShiftUp", makeCallbackF(Texdef_ShiftUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "TexShiftDown", makeCallbackF(Texdef_ShiftDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "TexShiftLeft", makeCallbackF(Texdef_ShiftLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_SHIFT_MASK ) );
 +      GlobalCommands_insert( "TexShiftRight", makeCallbackF(Texdef_ShiftRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_SHIFT_MASK ) );
  
 -      GlobalCommands_insert( "MoveSelectionDOWN", FreeCaller<Selection_MoveDown>(), Accelerator( GDK_KP_Subtract ) );
 -      GlobalCommands_insert( "MoveSelectionUP", FreeCaller<Selection_MoveUp>(), Accelerator( GDK_KP_Add ) );
 +      GlobalCommands_insert( "MoveSelectionDOWN", makeCallbackF(Selection_MoveDown), Accelerator( GDK_KEY_KP_Subtract ) );
 +      GlobalCommands_insert( "MoveSelectionUP", makeCallbackF(Selection_MoveUp), Accelerator( GDK_KEY_KP_Add ) );
  
 -      GlobalCommands_insert( "SelectNudgeLeft", FreeCaller<Selection_NudgeLeft>(), Accelerator( GDK_Left, (GdkModifierType)GDK_MOD1_MASK ) );
 -      GlobalCommands_insert( "SelectNudgeRight", FreeCaller<Selection_NudgeRight>(), Accelerator( GDK_Right, (GdkModifierType)GDK_MOD1_MASK ) );
 -      GlobalCommands_insert( "SelectNudgeUp", FreeCaller<Selection_NudgeUp>(), Accelerator( GDK_Up, (GdkModifierType)GDK_MOD1_MASK ) );
 -      GlobalCommands_insert( "SelectNudgeDown", FreeCaller<Selection_NudgeDown>(), Accelerator( GDK_Down, (GdkModifierType)GDK_MOD1_MASK ) );
 +      GlobalCommands_insert( "SelectNudgeLeft", makeCallbackF(Selection_NudgeLeft), Accelerator( GDK_KEY_Left, (GdkModifierType)GDK_MOD1_MASK ) );
 +      GlobalCommands_insert( "SelectNudgeRight", makeCallbackF(Selection_NudgeRight), Accelerator( GDK_KEY_Right, (GdkModifierType)GDK_MOD1_MASK ) );
 +      GlobalCommands_insert( "SelectNudgeUp", makeCallbackF(Selection_NudgeUp), Accelerator( GDK_KEY_Up, (GdkModifierType)GDK_MOD1_MASK ) );
 +      GlobalCommands_insert( "SelectNudgeDown", makeCallbackF(Selection_NudgeDown), Accelerator( GDK_KEY_Down, (GdkModifierType)GDK_MOD1_MASK ) );
  
        Patch_registerCommands();
        XYShow_registerCommands();
  
 -      typedef FreeCaller1<const Selectable&, ComponentMode_SelectionChanged> ComponentModeSelectionChangedCaller;
 +      typedef FreeCaller<void(const Selectable&), ComponentMode_SelectionChanged> ComponentModeSelectionChangedCaller;
        GlobalSelectionSystem().addSelectionChangeCallback( ComponentModeSelectionChangedCaller() );
  
 -      GlobalPreferenceSystem().registerPreference( "DetachableMenus", BoolImportStringCaller( g_Layout_enableDetachableMenus.m_latched ), BoolExportStringCaller( g_Layout_enableDetachableMenus.m_latched ) );
 -      GlobalPreferenceSystem().registerPreference( "PatchToolBar", BoolImportStringCaller( g_Layout_enablePatchToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePatchToolbar.m_latched ) );
 -      GlobalPreferenceSystem().registerPreference( "PluginToolBar", BoolImportStringCaller( g_Layout_enablePluginToolbar.m_latched ), BoolExportStringCaller( g_Layout_enablePluginToolbar.m_latched ) );
 -      GlobalPreferenceSystem().registerPreference( "FilterToolBar", BoolImportStringCaller( g_Layout_enableFilterToolbar.m_latched ), BoolExportStringCaller( g_Layout_enableFilterToolbar.m_latched ) );
 -      GlobalPreferenceSystem().registerPreference( "QE4StyleWindows", IntImportStringCaller( g_Layout_viewStyle.m_latched ), IntExportStringCaller( g_Layout_viewStyle.m_latched ) );
 -      GlobalPreferenceSystem().registerPreference( "XYHeight", IntImportStringCaller( g_layout_globals.nXYHeight ), IntExportStringCaller( g_layout_globals.nXYHeight ) );
 -      GlobalPreferenceSystem().registerPreference( "XYWidth", IntImportStringCaller( g_layout_globals.nXYWidth ), IntExportStringCaller( g_layout_globals.nXYWidth ) );
 -      GlobalPreferenceSystem().registerPreference( "CamWidth", IntImportStringCaller( g_layout_globals.nCamWidth ), IntExportStringCaller( g_layout_globals.nCamWidth ) );
 -      GlobalPreferenceSystem().registerPreference( "CamHeight", IntImportStringCaller( g_layout_globals.nCamHeight ), IntExportStringCaller( g_layout_globals.nCamHeight ) );
 -
 -      GlobalPreferenceSystem().registerPreference( "State", IntImportStringCaller( g_layout_globals.nState ), IntExportStringCaller( g_layout_globals.nState ) );
 -      GlobalPreferenceSystem().registerPreference( "PositionX", IntImportStringCaller( g_layout_globals.m_position.x ), IntExportStringCaller( g_layout_globals.m_position.x ) );
 -      GlobalPreferenceSystem().registerPreference( "PositionY", IntImportStringCaller( g_layout_globals.m_position.y ), IntExportStringCaller( g_layout_globals.m_position.y ) );
 -      GlobalPreferenceSystem().registerPreference( "Width", IntImportStringCaller( g_layout_globals.m_position.w ), IntExportStringCaller( g_layout_globals.m_position.w ) );
 -      GlobalPreferenceSystem().registerPreference( "Height", IntImportStringCaller( g_layout_globals.m_position.h ), IntExportStringCaller( g_layout_globals.m_position.h ) );
 -
 -      GlobalPreferenceSystem().registerPreference( "CamWnd", WindowPositionTrackerImportStringCaller( g_posCamWnd ), WindowPositionTrackerExportStringCaller( g_posCamWnd ) );
 -      GlobalPreferenceSystem().registerPreference( "XYWnd", WindowPositionTrackerImportStringCaller( g_posXYWnd ), WindowPositionTrackerExportStringCaller( g_posXYWnd ) );
 -      GlobalPreferenceSystem().registerPreference( "YZWnd", WindowPositionTrackerImportStringCaller( g_posYZWnd ), WindowPositionTrackerExportStringCaller( g_posYZWnd ) );
 -      GlobalPreferenceSystem().registerPreference( "XZWnd", WindowPositionTrackerImportStringCaller( g_posXZWnd ), WindowPositionTrackerExportStringCaller( g_posXZWnd ) );
 -
 -      GlobalPreferenceSystem().registerPreference( "EnginePath", CopiedStringImportStringCaller( g_strEnginePath ), CopiedStringExportStringCaller( g_strEnginePath ) );
 +      GlobalPreferenceSystem().registerPreference( "DetachableMenus", make_property_string( g_Layout_enableDetachableMenus.m_latched ) );
 +      GlobalPreferenceSystem().registerPreference( "PatchToolBar", make_property_string( g_Layout_enablePatchToolbar.m_latched ) );
 +      GlobalPreferenceSystem().registerPreference( "PluginToolBar", make_property_string( g_Layout_enablePluginToolbar.m_latched ) );
 +      GlobalPreferenceSystem().registerPreference( "FilterToolBar", make_property_string( g_Layout_enableFilterToolbar.m_latched ) );
 +      GlobalPreferenceSystem().registerPreference( "QE4StyleWindows", make_property_string( g_Layout_viewStyle.m_latched ) );
 +      GlobalPreferenceSystem().registerPreference( "XYHeight", make_property_string( g_layout_globals.nXYHeight ) );
 +      GlobalPreferenceSystem().registerPreference( "XYWidth", make_property_string( g_layout_globals.nXYWidth ) );
 +      GlobalPreferenceSystem().registerPreference( "CamWidth", make_property_string( g_layout_globals.nCamWidth ) );
 +      GlobalPreferenceSystem().registerPreference( "CamHeight", make_property_string( g_layout_globals.nCamHeight ) );
 +
 +      GlobalPreferenceSystem().registerPreference( "State", make_property_string( g_layout_globals.nState ) );
 +      GlobalPreferenceSystem().registerPreference( "PositionX", make_property_string( g_layout_globals.m_position.x ) );
 +      GlobalPreferenceSystem().registerPreference( "PositionY", make_property_string( g_layout_globals.m_position.y ) );
 +      GlobalPreferenceSystem().registerPreference( "Width", make_property_string( g_layout_globals.m_position.w ) );
 +      GlobalPreferenceSystem().registerPreference( "Height", make_property_string( g_layout_globals.m_position.h ) );
 +
 +      GlobalPreferenceSystem().registerPreference( "CamWnd", make_property<WindowPositionTracker_String>(g_posCamWnd) );
 +      GlobalPreferenceSystem().registerPreference( "XYWnd", make_property<WindowPositionTracker_String>(g_posXYWnd) );
 +      GlobalPreferenceSystem().registerPreference( "YZWnd", make_property<WindowPositionTracker_String>(g_posYZWnd) );
 +      GlobalPreferenceSystem().registerPreference( "XZWnd", make_property<WindowPositionTracker_String>(g_posXZWnd) );
 +
 +      GlobalPreferenceSystem().registerPreference( "EnginePath", make_property_string( g_strEnginePath ) );
        if ( g_strEnginePath.empty() )
        {
                g_strEnginePath_was_empty_1st_start = true;
                const char* ENGINEPATH_ATTRIBUTE =
 -#if defined( WIN32 )
 +#if GDEF_OS_WINDOWS
                        "enginepath_win32"
 -#elif defined( __linux__ ) || defined ( __FreeBSD__ )
 -                      "enginepath_linux"
 -#elif defined( __APPLE__ )
 +#elif GDEF_OS_MACOS
                        "enginepath_macos"
 +#elif GDEF_OS_LINUX || GDEF_OS_BSD
 +                      "enginepath_linux"
  #else
  #error "unknown platform"
  #endif
                StringOutputStream path( 256 );
                path << DirectoryCleaned( g_pGameDescription->getRequiredKeyValue( ENGINEPATH_ATTRIBUTE ) );
                g_strEnginePath = path.c_str();
 -              GlobalPreferenceSystem().registerPreference( "EnginePath", CopiedStringImportStringCaller( g_strEnginePath ), CopiedStringExportStringCaller( g_strEnginePath ) );
 +              GlobalPreferenceSystem().registerPreference( "EnginePath", make_property_string( g_strEnginePath ) );
        }
  
 +      GlobalPreferenceSystem().registerPreference( "DisableEnginePath", make_property_string( g_disableEnginePath ) );
 +      GlobalPreferenceSystem().registerPreference( "DisableHomePath", make_property_string( g_disableHomePath ) );
  
 +      for ( int i = 0; i < g_pakPathCount; i++ ) {
 +              std::string label = "PakPath" + std::to_string( i );
 +              GlobalPreferenceSystem().registerPreference( label.c_str(), make_property_string( g_strPakPath[i] ) );
 +      }
  
        g_Layout_viewStyle.useLatched();
        g_Layout_enableDetachableMenus.useLatched();
        Layout_registerPreferencesPage();
        Paths_registerPreferencesPage();
  
 -      g_brushCount.setCountChangedCallback( FreeCaller<QE_brushCountChanged>() );
 -      g_entityCount.setCountChangedCallback( FreeCaller<QE_entityCountChanged>() );
 +      g_brushCount.setCountChangedCallback( makeCallbackF(QE_brushCountChanged) );
 +      g_entityCount.setCountChangedCallback( makeCallbackF(QE_entityCountChanged) );
        GlobalEntityCreator().setCounter( &g_entityCount );
  
        GLWidget_sharedContextCreated = GlobalGL_sharedContextCreated;
@@@ -3643,13 -3497,13 +3667,13 @@@ void MainFrame_Destroy()
        GlobalEntityClassManager().detach( g_WorldspawnColourEntityClassObserver );
  
        GlobalEntityCreator().setCounter( 0 );
 -      g_entityCount.setCountChangedCallback( Callback() );
 -      g_brushCount.setCountChangedCallback( Callback() );
 +      g_entityCount.setCountChangedCallback( Callback<void()>() );
 +      g_brushCount.setCountChangedCallback( Callback<void()>() );
  }
  
  
  void GLWindow_Construct(){
 -      GlobalPreferenceSystem().registerPreference( "MouseButtons", IntImportStringCaller( g_glwindow_globals.m_nMouseType ), IntExportStringCaller( g_glwindow_globals.m_nMouseType ) );
 +      GlobalPreferenceSystem().registerPreference( "MouseButtons", make_property_string( g_glwindow_globals.m_nMouseType ) );
  }
  
  void GLWindow_Destroy(){
diff --combined radiant/map.cpp
index 0d2e5b331badd23a0a21037486fe0113c8ee297d,4040ab3cd822d3da8b39b174152af9b9c6790179..5f22997c5af01156d8e36732dea94119f60d9833
  
  #include "map.h"
  
 +#include <gtk/gtk.h>
 +
  #include "debugging/debugging.h"
  
  #include "imap.h"
 +
  MapModules& ReferenceAPI_getMapModules();
 +
  #include "iselection.h"
  #include "iundo.h"
  #include "ibrush.h"
  #include "irender.h"
  #include "ientity.h"
  #include "editable.h"
 +#include "iarchive.h"
  #include "ifilesystem.h"
  #include "namespace.h"
  #include "moduleobserver.h"
  
  #include <set>
  
 -#include <gtk/gtkmain.h>
 -#include <gtk/gtkbox.h>
 -#include <gtk/gtkentry.h>
 -#include <gtk/gtklabel.h>
 -#include <gtk/gtktable.h>
 -#include <gtk/gtktreemodel.h>
 -#include <gtk/gtktreeview.h>
 -#include <gtk/gtkliststore.h>
 -#include <gtk/gtkcellrenderertext.h>
 +#include <gdk/gdkkeysyms.h>
 +#include "uilib/uilib.h"
  
  #include "scenelib.h"
  #include "transformlib.h"
@@@ -59,7 -61,6 +59,7 @@@
  #include "cmdlib.h"
  #include "stream/textfilestream.h"
  #include "os/path.h"
 +#include "os/file.h"
  #include "uniquenames.h"
  #include "modulesystem/singletonmodule.h"
  #include "modulesystem/moduleregistry.h"
@@@ -79,7 -80,6 +79,7 @@@
  #include "xywindow.h"
  #include "mainframe.h"
  #include "preferences.h"
 +#include "preferencesystem.h"
  #include "referencecache.h"
  #include "mru.h"
  #include "commands.h"
@@@ -87,8 -87,6 +87,8 @@@
  #include "brushmodule.h"
  #include "brush.h"
  
 +bool g_writeMapComments = true;
 +
  class NameObserver
  {
  UniqueNames& m_names;
@@@ -100,7 -98,6 +100,7 @@@ void construct()
                m_names.insert( name_read( c_str() ) );
        }
  }
 +
  void destroy(){
        if ( !empty() ) {
                //globalOutputStream() << "destroy " << makeQuoted(c_str()) << "\n";
  }
  
  NameObserver& operator=( const NameObserver& other );
 +
  public:
  NameObserver( UniqueNames& names ) : m_names( names ){
        construct();
  NameObserver( const NameObserver& other ) : m_names( other.m_names ), m_name( other.m_name ){
        construct();
  }
 +
  ~NameObserver(){
        destroy();
  }
 +
  bool empty() const {
        return string_empty( c_str() );
  }
 +
  const char* c_str() const {
        return m_name.c_str();
  }
 +
  void nameChanged( const char* name ){
        destroy();
        m_name = name;
        construct();
  }
 -typedef MemberCaller1<NameObserver, const char*, &NameObserver::nameChanged> NameChangedCaller;
 +
 +typedef MemberCaller<NameObserver, void(const char*), &NameObserver::nameChanged> NameChangedCaller;
  };
  
  class BasicNamespace : public Namespace
@@@ -148,14 -139,12 +148,14 @@@ public
  ~BasicNamespace(){
        ASSERT_MESSAGE( m_names.empty(), "namespace: names still registered at shutdown" );
  }
 +
  void attach( const NameCallback& setName, const NameCallbackCallback& attachObserver ){
        std::pair<Names::iterator, bool> result = m_names.insert( Names::value_type( setName, m_uniqueNames ) );
        ASSERT_MESSAGE( result.second, "cannot attach name" );
        attachObserver( NameObserver::NameChangedCaller( ( *result.first ).second ) );
        //globalOutputStream() << "attach: " << reinterpret_cast<const unsigned int&>(setName) << "\n";
  }
 +
  void detach( const NameCallback& setName, const NameCallbackCallback& detachObserver ){
        Names::iterator i = m_names.find( setName );
        ASSERT_MESSAGE( i != m_names.end(), "cannot detach name" );
@@@ -210,13 -199,11 +210,13 @@@ class NamespaceAP
  Namespace* m_namespace;
  public:
  typedef Namespace Type;
 +
  STRING_CONSTANT( Name, "*" );
  
  NamespaceAPI(){
        m_namespace = &g_defaultNamespace;
  }
 +
  Namespace* getTable(){
        return m_namespace;
  }
@@@ -274,7 -261,6 +274,7 @@@ public
  WorldNode()
        : m_node( 0 ){
  }
 +
  void set( scene::Node* node ){
        if ( m_node != 0 ) {
                m_node->DecRef();
                m_node->IncRef();
        }
  }
 +
  scene::Node* get() const {
        return m_node;
  }
  
  class Map;
  void Map_SetValid( Map& map, bool valid );
 +
  void Map_UpdateTitle( const Map& map );
 +
  void Map_SetWorldspawn( Map& map, scene::Node* node );
  
  
@@@ -306,7 -289,6 +306,7 @@@ Resource* m_resource
  bool m_valid;
  
  bool m_modified;
 +
  void ( *m_modified_changed )( const Map& );
  
  Signal0 m_mapValidCallbacks;
@@@ -337,7 -319,6 +337,7 @@@ void realise()
                Map_SetValid( g_map, true );
        }
  }
 +
  void unrealise(){
        if ( m_resource != 0 ) {
                Map_SetValid( g_map, false );
@@@ -405,6 -386,7 +405,6 @@@ void Map_UpdateTitle( const Map& map )
  }
  
  
 -
  scene::Node* Map_GetWorldspawn( const Map& map ){
        return map.m_world_node.get();
  }
@@@ -420,7 -402,6 +420,7 @@@ float g_MaxWorldCoord = 64 * 1024
  float g_MinWorldCoord = -64 * 1024;
  
  void AddRegionBrushes( void );
 +
  void RemoveRegionBrushes( void );
  
  
@@@ -451,7 -432,6 +451,7 @@@ public
  EntityFindByClassname( const char* name, Entity*& entity ) : m_name( name ), m_entity( entity ){
        m_entity = 0;
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( m_entity == 0 ) {
                Entity* entity = Node_getEntity( path.top() );
@@@ -561,7 -541,6 +561,7 @@@ UnsortedNodeSet& m_nodes
  public:
  CollectAllWalker( scene::Node& root, UnsortedNodeSet& nodes ) : m_root( root ), m_nodes( nodes ){
  }
 +
  bool pre( scene::Node& node ) const {
        m_nodes.insert( NodeSmartReference( node ) );
        Node_getTraversable( m_root )->erase( node );
@@@ -605,14 -584,12 +605,14 @@@ public
  MapMergeAll( const scene::Path& root )
        : m_path( root ){
  }
 +
  bool pre( scene::Node& node ) const {
        Node_getTraversable( m_path.top() )->insert( node );
        m_path.push( makeReference( node ) );
        selectPath( m_path, true );
        return false;
  }
 +
  void post( scene::Node& node ) const {
        m_path.pop();
  }
@@@ -625,7 -602,6 +625,7 @@@ public
  MapMergeEntities( const scene::Path& root )
        : m_path( root ){
  }
 +
  bool pre( scene::Node& node ) const {
        if ( node_is_worldspawn( node ) ) {
                scene::Node* world_node = Map_FindWorldspawn( g_map );
        }
        return false;
  }
 +
  void post( scene::Node& node ) const {
        m_path.pop();
  }
@@@ -670,7 -645,6 +670,7 @@@ public
  TypeCasts(){
        NodeContainedCast<BasicContainer, scene::Traversable>::install( m_casts );
  }
 +
  NodeTypeCastTable& get(){
        return m_casts;
  }
@@@ -688,11 -662,9 +688,11 @@@ scene::Traversable& get( NullType<scene
  
  BasicContainer() : m_node( this, this, StaticTypeCasts::instance().get() ){
  }
 +
  void release(){
        delete this;
  }
 +
  scene::Node& node(){
        return m_node;
  }
  void MergeMap( scene::Node& node ){
        Node_getTraversable( node )->traverse( MapMergeEntities( scene::Path( makeReference( GlobalSceneGraph().root() ) ) ) );
  }
 +
  void Map_ImportSelected( TextInputStream& in, const MapFormat& format ){
        NodeSmartReference node( ( new BasicContainer )->node() );
        format.readGraph( node, in, GlobalEntityCreator() );
@@@ -731,7 -702,6 +731,7 @@@ public
  CloneAll( scene::Node& root )
        : m_path( makeReference( root ) ){
  }
 +
  bool pre( scene::Node& node ) const {
        if ( node.isRoot() ) {
                return false;
  
        return true;
  }
 +
  void post( scene::Node& node ) const {
        if ( node.isRoot() ) {
                return;
@@@ -774,17 -743,14 +774,17 @@@ public
  EntityBreakdownWalker( EntityBreakdown& entitymap )
        : m_entitymap( entitymap ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        Entity* entity = Node_getEntity( path.top() );
        if ( entity != 0 ) {
                const EntityClass& eclass = entity->getEntityClass();
                if ( m_entitymap.find( eclass.name() ) == m_entitymap.end() ) {
                        m_entitymap[eclass.name()] = 1;
 +              } else
 +              {
 +                      ++m_entitymap[eclass.name()];
                }
 -              else{ ++m_entitymap[eclass.name()]; }
        }
        return true;
  }
@@@ -799,98 -765,106 +799,98 @@@ WindowPosition g_posMapInfoWnd( c_defau
  
  void DoMapInfo(){
        ModalDialog dialog;
 -      GtkEntry* brushes_entry;
 -      GtkEntry* entities_entry;
 -      GtkListStore* EntityBreakdownWalker;
 +      ui::Entry brushes_entry{ui::null};
 +      ui::Entry entities_entry{ui::null};
 +      ui::ListStore EntityBreakdownWalker{ui::null};
  
 -      GtkWindow* window = create_dialog_window( MainFrame_getWindow(), "Map Info", G_CALLBACK( dialog_delete_callback ), &dialog );
 +      ui::Window window = MainFrame_getWindow().create_dialog_window("Map Info", G_CALLBACK(dialog_delete_callback ), &dialog );
  
        window_set_position( window, g_posMapInfoWnd );
  
        {
 -              GtkVBox* vbox = create_dialog_vbox( 4, 4 );
 -              gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( vbox ) );
 +              auto vbox = create_dialog_vbox( 4, 4 );
 +              window.add(vbox);
  
                {
 -                      GtkHBox* hbox = create_dialog_hbox( 4 );
 -                      gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( hbox ), FALSE, TRUE, 0 );
 +                      auto hbox = create_dialog_hbox( 4 );
 +                      vbox.pack_start( hbox, FALSE, TRUE, 0 );
  
                        {
 -                              GtkTable* table = create_dialog_table( 2, 2, 4, 4 );
 -                              gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( table ), TRUE, TRUE, 0 );
 +                              auto table = create_dialog_table( 2, 2, 4, 4 );
 +                              hbox.pack_start( table, TRUE, TRUE, 0 );
  
                                {
 -                                      GtkEntry* entry = GTK_ENTRY( gtk_entry_new() );
 -                                      gtk_widget_show( GTK_WIDGET( entry ) );
 -                                      gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 0, 1,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 -                                      gtk_entry_set_editable( entry, FALSE );
 +                                      auto entry = ui::Entry(ui::New);
 +                                      entry.show();
 +                    table.attach(entry, {1, 2, 0, 1}, {GTK_EXPAND | GTK_FILL, 0});
 +                                      gtk_editable_set_editable( GTK_EDITABLE(entry), FALSE );
  
                                        brushes_entry = entry;
                                }
                                {
 -                                      GtkEntry* entry = GTK_ENTRY( gtk_entry_new() );
 -                                      gtk_widget_show( GTK_WIDGET( entry ) );
 -                                      gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 1, 2,
 -                                                                        (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 -                                      gtk_entry_set_editable( entry, FALSE );
 +                                      auto entry = ui::Entry(ui::New);
 +                                      entry.show();
 +                    table.attach(entry, {1, 2, 1, 2}, {GTK_EXPAND | GTK_FILL, 0});
 +                                      gtk_editable_set_editable( GTK_EDITABLE(entry), FALSE );
  
                                        entities_entry = entry;
                                }
                                {
 -                                      GtkWidget* label = gtk_label_new( "Total Brushes" );
 -                                      gtk_widget_show( label );
 -                                      gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1,
 -                                                                        (GtkAttachOptions) ( GTK_FILL ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      ui::Widget label = ui::Label( "Total Brushes" );
 +                                      label.show();
 +                    table.attach(label, {0, 1, 0, 1}, {GTK_FILL, 0});
                                        gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
                                }
                                {
 -                                      GtkWidget* label = gtk_label_new( "Total Entities" );
 -                                      gtk_widget_show( label );
 -                                      gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2,
 -                                                                        (GtkAttachOptions) ( GTK_FILL ),
 -                                                                        (GtkAttachOptions) ( 0 ), 0, 0 );
 +                                      ui::Widget label = ui::Label( "Total Entities" );
 +                                      label.show();
 +                    table.attach(label, {0, 1, 1, 2}, {GTK_FILL, 0});
                                        gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
                                }
                        }
                        {
 -                              GtkVBox* vbox2 = create_dialog_vbox( 4 );
 -                              gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( vbox2 ), FALSE, FALSE, 0 );
 +                              auto vbox2 = create_dialog_vbox( 4 );
 +                              hbox.pack_start( vbox2, FALSE, FALSE, 0 );
  
                                {
 -                                      GtkButton* button = create_dialog_button( "Close", G_CALLBACK( dialog_button_ok ), &dialog );
 -                                      gtk_box_pack_start( GTK_BOX( vbox2 ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
 +                                      auto button = create_dialog_button( "Close", G_CALLBACK( dialog_button_ok ), &dialog );
 +                                      vbox2.pack_start( button, FALSE, FALSE, 0 );
                                }
                        }
                }
                {
 -                      GtkWidget* label = gtk_label_new( "Entity breakdown" );
 -                      gtk_widget_show( label );
 -                      gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( label ), FALSE, TRUE, 0 );
 +                      ui::Widget label = ui::Label( "Entity breakdown" );
 +                      label.show();
 +                      vbox.pack_start( label, FALSE, TRUE, 0 );
                        gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 );
                }
                {
 -                      GtkScrolledWindow* scr = create_scrolled_window( GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4 );
 -                      gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( scr ), TRUE, TRUE, 0 );
 +                      auto scr = create_scrolled_window( ui::Policy::NEVER, ui::Policy::AUTOMATIC, 4 );
 +                      vbox.pack_start( scr, TRUE, TRUE, 0 );
  
                        {
 -                              GtkListStore* store = gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING );
 +                              auto store = ui::ListStore::from(gtk_list_store_new( 2, G_TYPE_STRING, G_TYPE_STRING ));
  
 -                              GtkWidget* view = gtk_tree_view_new_with_model( GTK_TREE_MODEL( store ) );
 -                              gtk_tree_view_set_headers_clickable( GTK_TREE_VIEW( view ), TRUE );
 +                              auto view = ui::TreeView(ui::TreeModel::from(store._handle));
 +                              gtk_tree_view_set_headers_clickable(view, TRUE );
  
                                {
 -                                      GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
 -                                      GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes( "Entity", renderer, "text", 0, 0 );
 -                                      gtk_tree_view_append_column( GTK_TREE_VIEW( view ), column );
 +                                      auto renderer = ui::CellRendererText(ui::New);
 +                                      auto column = ui::TreeViewColumn( "Entity", renderer, {{"text", 0}} );
 +                                      gtk_tree_view_append_column(view, column );
                                        gtk_tree_view_column_set_sort_column_id( column, 0 );
                                }
  
                                {
 -                                      GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
 -                                      GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes( "Count", renderer, "text", 1, 0 );
 -                                      gtk_tree_view_append_column( GTK_TREE_VIEW( view ), column );
 +                                      auto renderer = ui::CellRendererText(ui::New);
 +                                      auto column = ui::TreeViewColumn( "Count", renderer, {{"text", 1}} );
 +                                      gtk_tree_view_append_column(view, column );
                                        gtk_tree_view_column_set_sort_column_id( column, 1 );
                                }
  
 -                              gtk_widget_show( view );
 +                              view.show();
  
 -                              gtk_container_add( GTK_CONTAINER( scr ), view );
 +                              scr.add(view);
  
                                EntityBreakdownWalker = store;
                        }
                {
                        char tmp[16];
                        sprintf( tmp, "%u", Unsigned( ( *i ).second ) );
 -                      GtkTreeIter iter;
 -                      gtk_list_store_append( GTK_LIST_STORE( EntityBreakdownWalker ), &iter );
 -                      gtk_list_store_set( GTK_LIST_STORE( EntityBreakdownWalker ), &iter, 0, ( *i ).first.c_str(), 1, tmp, -1 );
 +                      EntityBreakdownWalker.append(0, (*i).first.c_str(), 1, tmp);
                }
        }
  
 -      g_object_unref( G_OBJECT( EntityBreakdownWalker ) );
 +      EntityBreakdownWalker.unref();
  
        char tmp[16];
        sprintf( tmp, "%u", Unsigned( g_brushCount.get() ) );
 -      gtk_entry_set_text( GTK_ENTRY( brushes_entry ), tmp );
 +      brushes_entry.text(tmp);
        sprintf( tmp, "%u", Unsigned( g_entityCount.get() ) );
 -      gtk_entry_set_text( GTK_ENTRY( entities_entry ), tmp );
 +      entities_entry.text(tmp);
  
        modal_dialog_show( window, dialog );
  
        // save before exit
        window_get_position( window, g_posMapInfoWnd );
  
 -      gtk_widget_destroy( GTK_WIDGET( window ) );
 +    window.destroy();
  }
  
  
@@@ -938,15 -914,12 +938,15 @@@ ScopeTimer( const char* message 
        : m_message( message ){
        m_timer.start();
  }
 +
  ~ScopeTimer(){
        double elapsed_time = m_timer.elapsed_msec() / 1000.f;
        globalOutputStream() << m_message << " timer: " << FloatFormat( elapsed_time, 5, 2 ) << " second(s) elapsed\n";
  }
  };
  
 +CopiedString g_strLastMapFolder = "";
 +
  /*
     ================
     Map_LoadFile
   */
  
  void Map_LoadFile( const char *filename ){
 +      g_map.m_name = filename;
 +
 +      // refresh VFS to apply new pak filtering based on mapname
 +      // needed for daemon DPK VFS
 +      VFS_Refresh();
 +
        globalOutputStream() << "Loading map from " << filename << "\n";
        ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Map" );
  
 +      MRU_AddFile( filename );
 +      g_strLastMapFolder = g_path_get_dirname( filename );
 +
        {
                ScopeTimer timer( "map load" );
  
                                Map_Free();
                        }
                        Brush_toggleFormat( i );
 -                      g_map.m_name = filename;
                        Map_UpdateTitle( g_map );
 +
                        g_map.m_resource = GlobalReferenceCache().capture( g_map.m_name.c_str() );
                        if ( format ) {
                                format->wrongFormat = false;
@@@ -1029,7 -993,6 +1029,7 @@@ public
  ExcludeWalker( const scene::Traversable::Walker& walker, const Excluder& exclude )
        : m_walker( walker ), m_exclude( &exclude ), m_skip( false ){
  }
 +
  bool pre( scene::Node& node ) const {
        if ( m_exclude->excluded( node ) || node.isRoot() ) {
                m_skip = true;
        }
        return true;
  }
 +
  void post( scene::Node& node ) const {
        if ( m_skip ) {
                m_skip = false;
@@@ -1060,7 -1022,6 +1060,7 @@@ public
  AnyInstanceSelected( bool& selected ) : m_selected( selected ){
        m_selected = false;
  }
 +
  void visit( scene::Instance& instance ) const {
        Selectable* selectable = Instance_getSelectable( instance );
        if ( selectable != 0
@@@ -1122,12 -1083,10 +1122,12 @@@ mutable bool m_skip
  bool selectedParent() const {
        return m_selected != 0;
  }
 +
  public:
  IncludeSelectedWalker( const scene::Traversable::Walker& walker )
        : m_walker( walker ), m_selected( 0 ), m_skip( false ){
  }
 +
  bool pre( scene::Node& node ) const {
        // include node if:
        // node is not a 'root' AND ( node is selected OR any child of node is selected OR any parent of node is selected )
                return false;
        }
  }
 +
  void post( scene::Node& node ) const {
        if ( m_skip ) {
                m_skip = false;
@@@ -1171,7 -1129,7 +1171,7 @@@ void Map_Traverse_Selected( scene::Node
  }
  
  void Map_ExportSelected( TextOutputStream& out, const MapFormat& format ){
 -      format.writeGraph( GlobalSceneGraph().root(), Map_Traverse_Selected, out );
 +      format.writeGraph( GlobalSceneGraph().root(), Map_Traverse_Selected, out, g_writeMapComments );
  }
  
  void Map_Traverse( scene::Node& root, const scene::Traversable::Walker& walker ){
@@@ -1226,9 -1184,6 +1226,9 @@@ void Map_RenameAbsolute( const char* ab
        Map_UpdateTitle( g_map );
  
        g_map.m_resource->attach( g_map );
 +      // refresh VFS to apply new pak filtering based on mapname
 +      // needed for daemon DPK VFS
 +      VFS_Refresh();
  }
  
  void Map_Rename( const char* filename ){
@@@ -1276,10 -1231,6 +1276,10 @@@ void Map_New()
        FocusViews( g_vector3_identity, 0 );
  
        g_currentMap = &g_map;
 +
 +      // restart VFS to apply new pak filtering based on mapname
 +      // needed for daemon DPK VFS
 +      VFS_Restart();
  }
  
  extern void ConstructRegionBrushes( scene::Node * brushes[6], const Vector3 &region_mins, const Vector3 &region_maxs );
@@@ -1370,7 -1321,6 +1370,7 @@@ public
  ExcludeAllWalker( bool exclude )
        : m_exclude( exclude ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        exclude_node( path.top(), m_exclude );
  
@@@ -1394,7 -1344,6 +1394,7 @@@ public
  ExcludeSelectedWalker( bool exclude )
        : m_exclude( exclude ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        exclude_node( path.top(), ( instance.isSelected() || instance.childSelected() || instance.parentSelected() ) == m_exclude );
        return true;
@@@ -1412,7 -1361,6 +1412,7 @@@ public
  ExcludeRegionedWalker( bool exclude )
        : m_exclude( exclude ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        exclude_node(
                path.top(),
@@@ -1530,8 -1478,6 +1530,8 @@@ void Map_RegionBrush( void )
  bool Map_ImportFile( const char* filename ){
        ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Map" );
  
 +      g_strLastMapFolder = g_path_get_dirname( filename );
 +
        bool success = false;
  
        if ( extension_equal( path_get_extension( filename ), "bsp" ) ) {
@@@ -1588,27 -1534,7 +1588,27 @@@ tryDecompile
                output.push_string( EnginePath_get() );
                output.push_string( "\" -fs_homepath \"" );
                output.push_string( g_qeglobals.m_userEnginePath.c_str() );
 -              output.push_string( "\" -fs_game " );
 +              output.push_string( "\"" );
 +
 +              // extra pakpaths
 +              for ( int i = 0; i < g_pakPathCount; i++ ) {
 +                      if ( g_strcmp0( g_strPakPath[i].c_str(), "") ) {
 +                              output.push_string( " -fs_pakpath \"" );
 +                              output.push_string( g_strPakPath[i].c_str() );
 +                              output.push_string( "\"" );
 +                      }
 +              }
 +
 +              // extra switches
 +              if ( g_disableEnginePath ) {
 +                      output.push_string( " -fs_nobasepath " );
 +              }
 +
 +              if ( g_disableHomePath ) {
 +                      output.push_string( " -fs_nohomepath " );
 +              }
 +
 +              output.push_string( " -fs_game " );
                output.push_string( gamename_get() );
                output.push_string( " -convert -format " );
                output.push_string( Brush::m_type == eBrushTypeQuake3BP ? "map_bp" : "map" );
   */
  bool Map_SaveFile( const char* filename ){
        ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Saving Map" );
 -      return MapResource_saveFile( MapFormat_forFile( filename ), GlobalSceneGraph().root(), Map_Traverse, filename );
 +      bool success = MapResource_saveFile( MapFormat_forFile( filename ), GlobalSceneGraph().root(), Map_Traverse, filename );
 +      if ( success ) {
 +              // refresh VFS to apply new pak filtering based on mapname
 +              // needed for daemon DPK VFS
 +              VFS_Refresh();
 +      }
 +      return success;
  }
  
  //
@@@ -1683,7 -1603,6 +1683,7 @@@ class ParentSelectedBrushesToEntityWalk
  public:
  ParentSelectedBrushesToEntityWalker( scene::Node& parent ) : m_parent( parent ), m_emptyOldParent( false ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.top().get_pointer() != &m_parent && ( Node_isPrimitive( path.top() ) || m_emptyOldParent ) ) {
                Selectable* selectable = Instance_getSelectable( instance );
        }
        return true;
  }
 +
  void post( const scene::Path& path, scene::Instance& instance ) const {
        if ( path.top().get_pointer() == &m_parent )
                return;
@@@ -1737,7 -1655,6 +1737,7 @@@ public
  CountSelectedBrushes( std::size_t& count ) : m_count( count ), m_depth( 0 ){
        m_count = 0;
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( ++m_depth != 1 && path.top().get().isRoot() ) {
                return false;
        }
        return true;
  }
 +
  void post( const scene::Path& path, scene::Instance& instance ) const {
        --m_depth;
  }
@@@ -1837,7 -1753,6 +1837,7 @@@ void Scene_parentSelected()
  public:
                ParentSelectedBrushesToEntityWalker( const scene::Path& parent ) : m_parent( parent ){
                }
 +
                void visit( scene::Instance& instance ) const {
                        if ( &m_parent != &instance.path() ) {
                                Path_parent( m_parent, instance.path() );
  }
  
  
 -
  void NewMap(){
        if ( ConfirmModified( "New Map" ) ) {
                Map_RegionOff();
@@@ -1869,32 -1785,16 +1869,32 @@@ const char* getMapsPath()
        return g_mapsPath.c_str();
  }
  
 +const char* getLastMapFolderPath(){
 +      if (g_strLastMapFolder.empty()) {
 +              GlobalPreferenceSystem().registerPreference( "LastMapFolder", make_property_string( g_strLastMapFolder ) );
 +              if (g_strLastMapFolder.empty()) {
 +                      StringOutputStream buffer( 1024 );
 +                      buffer << getMapsPath();
 +                      if ( !file_readable( buffer.c_str() ) ) {
 +                              buffer.clear();
 +                              buffer << g_qeglobals.m_userGamePath.c_str() << "/";
 +                      }
 +                      g_strLastMapFolder = buffer.c_str();
 +              }
 +      }
 +      return g_strLastMapFolder.c_str();
 +}
 +
  const char* map_open( const char* title ){
 -      return file_dialog( GTK_WIDGET( MainFrame_getWindow() ), TRUE, title, getMapsPath(), MapFormat::Name(), true, false, false );
 +      return MainFrame_getWindow().file_dialog( TRUE, title, getLastMapFolderPath(), MapFormat::Name(), true, false, false );
  }
  
  const char* map_import( const char* title ){
 -      return file_dialog( GTK_WIDGET( MainFrame_getWindow() ), TRUE, title, getMapsPath(), MapFormat::Name(), false, true, false );
 +      return MainFrame_getWindow().file_dialog( TRUE, title, getLastMapFolderPath(), MapFormat::Name(), false, true, false );
  }
  
  const char* map_save( const char* title ){
 -      return file_dialog( GTK_WIDGET( MainFrame_getWindow() ), FALSE, title, getMapsPath(), MapFormat::Name(), false, false, true );
 +      return MainFrame_getWindow().file_dialog( FALSE, title, getLastMapFolderPath(), MapFormat::Name(), false, false, true );
  }
  
  void OpenMap(){
  
        const char* filename = map_open( "Open Map" );
  
 -      if ( filename != 0 ) {
 +      if ( filename != NULL ) {
                MRU_AddFile( filename );
                Map_RegionOff();
                Map_Free();
  void ImportMap(){
        const char* filename = map_import( "Import Map" );
  
 -      if ( filename != 0 ) {
 +      if ( filename != NULL ) {
                UndoableCommand undo( "mapImport" );
                Map_ImportFile( filename );
        }
  bool Map_SaveAs(){
        const char* filename = map_save( "Save Map" );
  
 -      if ( filename != 0 ) {
 +      if ( filename != NULL ) {
 +              g_strLastMapFolder = g_path_get_dirname( filename );
                MRU_AddFile( filename );
                Map_Rename( filename );
                return Map_Save();
@@@ -1943,17 -1842,14 +1943,15 @@@ void SaveMap()
        }
        else if ( Map_Modified( g_map ) ) {
                Map_Save();
- #ifdef WIN32
                MRU_AddFile( g_map.m_name.c_str() );    //add on saving, but not opening via cmd line: spoils the list
- #endif
        }
  }
  
  void ExportMap(){
        const char* filename = map_save( "Export Selection" );
  
 -      if ( filename != 0 ) {
 +      if ( filename != NULL ) {
 +              g_strLastMapFolder = g_path_get_dirname( filename );
                Map_SaveSelected( filename );
        }
  }
  void SaveRegion(){
        const char* filename = map_save( "Export Region" );
  
 -      if ( filename != 0 ) {
 +      if ( filename != NULL ) {
 +              g_strLastMapFolder = g_path_get_dirname( filename );
                Map_SaveRegion( filename );
        }
  }
@@@ -2005,7 -1900,6 +2003,7 @@@ public
  BrushFindByIndexWalker( std::size_t index, scene::Path& path )
        : m_index( index ), m_path( path ){
  }
 +
  bool pre( scene::Node& node ) const {
        if ( Node_isPrimitive( node ) && m_index-- == 0 ) {
                m_path.push( makeReference( node ) );
@@@ -2022,7 -1916,6 +2020,7 @@@ public
  EntityFindByIndexWalker( std::size_t index, scene::Path& path )
        : m_index( index ), m_path( path ){
  }
 +
  bool pre( scene::Node& node ) const {
        if ( Node_isEntity( node ) && m_index-- == 0 ) {
                m_path.push( makeReference( node ) );
@@@ -2071,7 -1964,6 +2069,7 @@@ public
  BrushFindIndexWalker( const scene::Node& node, std::size_t& count )
        : m_node( &node ), m_count( count ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( Node_isPrimitive( path.top() ) ) {
                if ( m_node == path.top().get_pointer() ) {
@@@ -2093,7 -1985,6 +2091,7 @@@ public
  EntityFindIndexWalker( const scene::Node& node, std::size_t& count )
        : m_node( &node ), m_count( count ){
  }
 +
  bool pre( const scene::Path& path, scene::Instance& instance ) const {
        if ( Node_isEntity( path.top() ) ) {
                if ( m_node == path.top().get_pointer() ) {
@@@ -2122,58 -2013,66 +2120,58 @@@ static void GetSelectionIndex( int *ent
  
  void DoFind(){
        ModalDialog dialog;
 -      GtkEntry* entity;
 -      GtkEntry* brush;
 +      ui::Entry entity{ui::null};
 +      ui::Entry brush{ui::null};
  
 -      GtkWindow* window = create_dialog_window( MainFrame_getWindow(), "Find Brush", G_CALLBACK( dialog_delete_callback ), &dialog );
 +      ui::Window window = MainFrame_getWindow().create_dialog_window("Find Brush", G_CALLBACK(dialog_delete_callback ), &dialog );
  
 -      GtkAccelGroup* accel = gtk_accel_group_new();
 -      gtk_window_add_accel_group( window, accel );
 +      auto accel = ui::AccelGroup(ui::New);
 +      window.add_accel_group( accel );
  
        {
 -              GtkVBox* vbox = create_dialog_vbox( 4, 4 );
 -              gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( vbox ) );
 +              auto vbox = create_dialog_vbox( 4, 4 );
 +              window.add(vbox);
                {
 -                      GtkTable* table = create_dialog_table( 2, 2, 4, 4 );
 -                      gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( table ), TRUE, TRUE, 0 );
 +                      auto table = create_dialog_table( 2, 2, 4, 4 );
 +                      vbox.pack_start( table, TRUE, TRUE, 0 );
                        {
 -                              GtkWidget* label = gtk_label_new( "Entity number" );
 -                              gtk_widget_show( label );
 -                              gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 0, 1,
 -                                                                (GtkAttachOptions) ( 0 ),
 -                                                                (GtkAttachOptions) ( 0 ), 0, 0 );
 +                              ui::Widget label = ui::Label( "Entity number" );
 +                              label.show();
 +                (table).attach(label, {0, 1, 0, 1}, {0, 0});
                        }
                        {
 -                              GtkWidget* label = gtk_label_new( "Brush number" );
 -                              gtk_widget_show( label );
 -                              gtk_table_attach( GTK_TABLE( table ), label, 0, 1, 1, 2,
 -                                                                (GtkAttachOptions) ( 0 ),
 -                                                                (GtkAttachOptions) ( 0 ), 0, 0 );
 +                              ui::Widget label = ui::Label( "Brush number" );
 +                              label.show();
 +                (table).attach(label, {0, 1, 1, 2}, {0, 0});
                        }
                        {
 -                              GtkEntry* entry = GTK_ENTRY( gtk_entry_new() );
 -                              gtk_widget_show( GTK_WIDGET( entry ) );
 -                              gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 0, 1,
 -                                                                (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
 -                                                                (GtkAttachOptions) ( 0 ), 0, 0 );
 -                              gtk_widget_grab_focus( GTK_WIDGET( entry ) );
 +                              auto entry = ui::Entry(ui::New);
 +                              entry.show();
 +                table.attach(entry, {1, 2, 0, 1}, {GTK_EXPAND | GTK_FILL, 0});
 +                              gtk_widget_grab_focus( entry  );
                                entity = entry;
                        }
                        {
 -                              GtkEntry* entry = GTK_ENTRY( gtk_entry_new() );
 -                              gtk_widget_show( GTK_WIDGET( entry ) );
 -                              gtk_table_attach( table, GTK_WIDGET( entry ), 1, 2, 1, 2,
 -                                                                (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
 -                                                                (GtkAttachOptions) ( 0 ), 0, 0 );
 +                              auto entry = ui::Entry(ui::New);
 +                              entry.show();
 +                table.attach(entry, {1, 2, 1, 2}, {GTK_EXPAND | GTK_FILL, 0});
  
                                brush = entry;
                        }
                }
                {
 -                      GtkHBox* hbox = create_dialog_hbox( 4 );
 -                      gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( hbox ), TRUE, TRUE, 0 );
 +                      auto hbox = create_dialog_hbox( 4 );
 +                      vbox.pack_start( hbox, TRUE, TRUE, 0 );
                        {
 -                              GtkButton* button = create_dialog_button( "Find", G_CALLBACK( dialog_button_ok ), &dialog );
 -                              gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
 -                              widget_make_default( GTK_WIDGET( button ) );
 -                              gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0 );
 +                              auto button = create_dialog_button( "Find", G_CALLBACK( dialog_button_ok ), &dialog );
 +                              hbox.pack_start( button, FALSE, FALSE, 0 );
 +                              widget_make_default( button );
 +                              gtk_widget_add_accelerator( button , "clicked", accel, GDK_KEY_Return, (GdkModifierType)0, (GtkAccelFlags)0 );
                        }
                        {
 -                              GtkButton* button = create_dialog_button( "Close", G_CALLBACK( dialog_button_cancel ), &dialog );
 -                              gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
 -                              gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0 );
 +                              auto button = create_dialog_button( "Close", G_CALLBACK( dialog_button_cancel ), &dialog );
 +                              hbox.pack_start( button, FALSE, FALSE, 0 );
 +                              gtk_widget_add_accelerator( button , "clicked", accel, GDK_KEY_Escape, (GdkModifierType)0, (GtkAccelFlags)0 );
                        }
                }
        }
  
        GetSelectionIndex( &ent, &br );
        sprintf( buf, "%i", ent );
 -      gtk_entry_set_text( entity, buf );
 +      entity.text(buf);
        sprintf( buf, "%i", br );
 -      gtk_entry_set_text( brush, buf );
 +      brush.text(buf);
  
        if ( modal_dialog_show( window, dialog ) == eIDOK ) {
                const char *entstr = gtk_entry_get_text( entity );
                SelectBrush( atoi( entstr ), atoi( brushstr ) );
        }
  
 -      gtk_widget_destroy( GTK_WIDGET( window ) );
 +    window.destroy();
  }
  
  void Map_constructPreferences( PreferencesPage& page ){
 -      page.appendCheckBox( "", "Load last map on open", g_bLoadLastMap );
 +      page.appendCheckBox( "", "Load last map at startup", g_bLoadLastMap );
 +      page.appendCheckBox( "", "Add entity and brush number comments on map write", g_writeMapComments );
  }
  
  
@@@ -2209,7 -2107,6 +2207,7 @@@ std::size_t m_unrealised
  public:
  MapEntityClasses() : m_unrealised( 1 ){
  }
 +
  void realise(){
        if ( --m_unrealised == 0 ) {
                if ( g_map.m_resource != 0 ) {
                }
        }
  }
 +
  void unrealise(){
        if ( ++m_unrealised == 1 ) {
                if ( g_map.m_resource != 0 ) {
@@@ -2238,7 -2134,6 +2236,7 @@@ std::size_t m_unrealised
  public:
  MapModuleObserver() : m_unrealised( 1 ){
  }
 +
  void realise(){
        if ( --m_unrealised == 0 ) {
                ASSERT_MESSAGE( !string_empty( g_qeglobals.m_userGamePath.c_str() ), "maps_directory: user-game-path is empty" );
                g_mapsPath = buffer.c_str();
        }
  }
 +
  void unrealise(){
        if ( ++m_unrealised == 1 ) {
                g_mapsPath = "";
  
  MapModuleObserver g_MapModuleObserver;
  
 -#include "preferencesystem.h"
 -
  CopiedString g_strLastMap;
  bool g_bLoadLastMap = false;
  
  void Map_Construct(){
 -      GlobalCommands_insert( "RegionOff", FreeCaller<RegionOff>() );
 -      GlobalCommands_insert( "RegionSetXY", FreeCaller<RegionXY>() );
 -      GlobalCommands_insert( "RegionSetBrush", FreeCaller<RegionBrush>() );
 -      GlobalCommands_insert( "RegionSetSelection", FreeCaller<RegionSelected>(), Accelerator( 'R', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
 +      GlobalCommands_insert( "RegionOff", makeCallbackF(RegionOff) );
 +      GlobalCommands_insert( "RegionSetXY", makeCallbackF(RegionXY) );
 +      GlobalCommands_insert( "RegionSetBrush", makeCallbackF(RegionBrush) );
 +      GlobalCommands_insert( "RegionSetSelection", makeCallbackF(RegionSelected), Accelerator( 'R', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
  
 -      GlobalPreferenceSystem().registerPreference( "LastMap", CopiedStringImportStringCaller( g_strLastMap ), CopiedStringExportStringCaller( g_strLastMap ) );
 -      GlobalPreferenceSystem().registerPreference( "LoadLastMap", BoolImportStringCaller( g_bLoadLastMap ), BoolExportStringCaller( g_bLoadLastMap ) );
 -      GlobalPreferenceSystem().registerPreference( "MapInfoDlg", WindowPositionImportStringCaller( g_posMapInfoWnd ), WindowPositionExportStringCaller( g_posMapInfoWnd ) );
 +      GlobalPreferenceSystem().registerPreference( "LastMap", make_property_string( g_strLastMap ) );
 +      GlobalPreferenceSystem().registerPreference( "LoadLastMap", make_property_string( g_bLoadLastMap ) );
 +      GlobalPreferenceSystem().registerPreference( "MapInfoDlg", make_property<WindowPosition_String>( g_posMapInfoWnd ) );
 +      GlobalPreferenceSystem().registerPreference( "WriteMapComments", make_property_string( g_writeMapComments ) );
  
 -      PreferencesDialog_addSettingsPreferences( FreeCaller1<PreferencesPage&, Map_constructPreferences>() );
 +      PreferencesDialog_addSettingsPreferences( makeCallbackF(Map_constructPreferences) );
  
        GlobalEntityClassManager().attach( g_MapEntityClasses );
        Radiant_attachHomePathsObserver( g_MapModuleObserver );
diff --combined radiant/server.cpp
index 2a264e6dcd14ede2803c2ee7e3789f5dff3aa416,aad08221da63c23ff317a02b491387a7ff6e873f..679e56bbd626250ef74722d506d25c6b917d5553
@@@ -20,7 -20,6 +20,7 @@@
   */
  
  #include "server.h"
 +#include "globaldefs.h"
  
  #include "debugging/debugging.h"
  #include "warnings.h"
@@@ -61,6 -60,7 +61,6 @@@ DebugMessageHandler& getDebugMessageHan
  }
  
  void registerModule( const char* type, int version, const char* name, Module& module ){
 -      ASSERT_NOTNULL( &module );
        if ( !m_modules.insert( Modules_::value_type( ModuleKey( ModuleType( type, version ), name ), &module ) ).second ) {
                globalErrorStream() << "module already registered: type=" << makeQuoted( type ) << " name=" << makeQuoted( name ) << "\n";
        }
@@@ -89,11 -89,11 +89,11 @@@ void foreachModule( const char* type, i
  };
  
  
 -#if defined( WIN32 )
 +#if GDEF_OS_WINDOWS
  
  #include <windows.h>
  
 -#define FORMAT_BUFSIZE 2048
 +const int FORMAT_BUFSIZE = 2048;
  const char* FormatGetLastError(){
        static char buf[FORMAT_BUFSIZE];
        FormatMessage(
@@@ -140,17 -140,22 +140,21 @@@ FunctionPointer findSymbol( const char
  }
  };
  
 -#elif defined( POSIX )
 +#elif GDEF_OS_POSIX
  
  #include <dlfcn.h>
  
 -class DynamicLibrary
 -{
 -void* m_library;
+ #ifndef RTLD_DEEPBIND
+ #define RTLD_DEEPBIND 0
+ #endif
 +class DynamicLibrary {
 +      void *m_library;
  public:
  typedef int ( *FunctionPointer )();
  
  DynamicLibrary( const char* filename ){
-       m_library = dlopen( filename, RTLD_NOW );
+       m_library = dlopen( filename, RTLD_NOW | (RTLD_DEEPBIND + 0) );
  }
  ~DynamicLibrary(){
        if ( !failed() ) {
index c6400cbc1ac3fc4859e2e917a34b3516b7c754bb,e15d5612cf2ec303080ba83a524a28d4966b0ac1..7769a0c5cc4650483bb621f1e7bba07261787c01
@@@ -93,11 -93,13 +93,12 @@@ brush_t *AllocBrush( int numSides )
        brush_t     *bb;
        size_t c;
  
 -
        /* allocate and clear */
-       if ( numSides <= 0 ) {
+       /*if ( numSides <= 0 ) {
                Error( "AllocBrush called with numsides = %d", numSides );
        }
-       c = (size_t)&( ( (brush_t*) 0 )->sides[ numSides ] );
+       c = (size_t)&( ( (brush_t*) 0 )->sides[ numSides ] );*/
+       c = sizeof(*bb) + (numSides > 6 ? sizeof(side_t)*(numSides - 6) : 0);
        bb = safe_malloc( c );
        memset( bb, 0, c );
        if ( numthreads == 1 ) {
@@@ -255,7 -257,7 +256,7 @@@ void SnapWeldVector( vec3_t a, vec3_t b
        {
                /* round to integer */
                ai = Q_rint( a[ i ] );
 -              bi = Q_rint( a[ i ] );
 +              bi = Q_rint( b[ i ] );
  
                /* prefer exact integer */
                if ( ai == a[ i ] ) {
                }
  
                /* use nearest */
 -              else if ( fabs( ai - a[ i ] ) < fabs( bi < b[ i ] ) ) {
 +              else if ( fabs( ai - a[ i ] ) < fabs( bi - b[ i ] ) ) {
                        out[ i ] = a[ i ];
                }
                else{
        }
  }
  
 +
 +
  /*
     ==================
     SnapWeldVectorAccu
@@@ -330,8 -330,6 +331,8 @@@ void SnapWeldVectorAccu( vec3_accu_t a
        }
  }
  
 +
 +
  /*
     FixWinding() - ydnar
     removes degenerate edges from a winding
@@@ -1044,9 -1042,8 +1045,9 @@@ void SplitBrush( brush_t *brush, int pl
                if ( !w ) {
                        continue;
                }
 +              /* strict, in parallel case we get the face back because it also is the midwinding */
                ClipWindingEpsilonStrict( w, plane->normal, plane->dist,
 -                                                                0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1] ); /* strict, in parallel case we get the face back because it also is the midwinding */
 +                                                      0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1] );
                for ( j = 0 ; j < 2 ; j++ )
                {
                        if ( !cw[j] ) {
index a42ba5ed01bd37ee5898930d23dc2ea8bc33b5c8,6ec7e21c0e6c7b140747a275c96da736bb341620..a751f83a5fd2e538ca2c6797ae800544ad3c7e5a
@@@ -109,7 -109,7 +109,7 @@@ void SetDrawSurfacesBuffer()
  
        bspDrawSurfaces = safe_malloc_info( sizeof( bspDrawSurface_t ) * numBSPDrawSurfacesBuffer, "IncDrawSurfaces" );
  
 -      memset( bspDrawSurfaces, 0, MAX_MAP_DRAW_SURFS * sizeof( bspDrawVert_t ) );
 +      memset( bspDrawSurfaces, 0, MAX_MAP_DRAW_SURFS * sizeof( bspDrawSurface_t ) );
  }
  
  void SetDrawSurfaces( int n ){
  
        bspDrawSurfaces = safe_malloc_info( sizeof( bspDrawSurface_t ) * numBSPDrawSurfacesBuffer, "IncDrawSurfaces" );
  
 -      memset( bspDrawSurfaces, 0, n * sizeof( bspDrawVert_t ) );
 +      memset( bspDrawSurfaces, 0, n * sizeof( bspDrawSurface_t ) );
  }
  
  void BSPFilesCleanup(){
@@@ -277,7 -277,7 +277,7 @@@ int GetLumpElements( bspHeader_t *heade
        /* check for odd size */
        if ( header->lumps[ lump ].length % size ) {
                if ( force ) {
 -                      Sys_Printf( "WARNING: GetLumpElements: odd lump size (%d) in lump %d\n", header->lumps[ lump ].length, lump );
 +                      Sys_FPrintf( SYS_WRN, "WARNING: GetLumpElements: odd lump size (%d) in lump %d\n", header->lumps[ lump ].length, lump );
                        return 0;
                }
                else{
@@@ -321,7 -321,7 +321,7 @@@ int CopyLump( bspHeader_t *header, int 
        }
        if ( length % size ) {
                if ( force ) {
 -                      Sys_Printf( "WARNING: CopyLump: odd lump size (%d) in lump %d\n", length, lump );
 +                      Sys_FPrintf( SYS_WRN, "WARNING: CopyLump: odd lump size (%d) in lump %d\n", length, lump );
                        return 0;
                }
                else{
@@@ -619,8 -619,6 +619,8 @@@ void ParseEntities( void )
        numBSPEntities = numEntities;
  }
  
 +
 +
  /*
   * must be called before UnparseEntities
   */
@@@ -632,10 -630,9 +632,9 @@@ void InjectCommandLine( char **argv, in
        char *sentinel = newCommandLine + sizeof( newCommandLine ) - 1;
        int i;
  
- if (nocmdline)
- {
-       return;
- }
+       if ( nocmdline ){
+               return;
+       }
        previousCommandLine = ValueForKey( &entities[0], "_q3map2_cmdline" );
        if ( previousCommandLine && *previousCommandLine ) {
                inpos = previousCommandLine;
        SetKeyValue( &entities[0], "_q3map2_version", Q3MAP_VERSION );
  }
  
 +
 +
  /*
     UnparseEntities()
     generates the dentdata string from all the entities.
@@@ -794,8 -789,6 +793,8 @@@ void SetKeyValue( entity_t *ent, const 
        ep->value = copystring( value );
  }
  
 +
 +
  /*
     KeyExists()
     returns true if entity has this key
@@@ -816,8 -809,6 +815,8 @@@ qboolean KeyExists( const entity_t *ent
        return qfalse;
  }
  
 +
 +
  /*
     ValueForKey()
     gets the value for an entity key
@@@ -881,7 -872,7 +880,7 @@@ vec_t FloatForKey( const entity_t *ent
     gets a 3-element vector value for an entity key
   */
  
 -void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ){
 +qboolean GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ){
        const char  *k;
        double v1, v2, v3;
  
        vec[ 0 ] = v1;
        vec[ 1 ] = v2;
        vec[ 2 ] = v3;
 +
 +      /* true if the key is found, false otherwise */
 +      return strlen( k );
  }
  
  
index bfcd53adf65b75a4046e255381bb86fa708577ba,fe097bef79dfa9374c8009f42a7c29dcac16b150..139a242a0ca5fafde3bec1f9aa298b009c04e352
@@@ -1,4 -1,4 +1,4 @@@
 -/* -------------------------------------------------------------------------------;
 +/* -------------------------------------------------------------------------------
  
     Copyright (C) 1999-2007 id Software, Inc. and contributors.
     For a list of contributors, see the accompanying CONTRIBUTORS file.
  
  /* dependencies */
  #include "q3map2.h"
 -
 -
 -
 -/*
 -   Random()
 -   returns a pseudorandom number between 0 and 1
 - */
 -
 -vec_t Random( void ){
 -      return (vec_t) rand() / RAND_MAX;
 -}
 -
 -
 -char *Q_strncpyz( char *dst, const char *src, size_t len ) {
 -      if ( len == 0 ) {
 -              abort();
 -      }
 -
 -      strncpy( dst, src, len );
 -      dst[ len - 1 ] = '\0';
 -      return dst;
 -}
 -
 -
 -char *Q_strcat( char *dst, size_t dlen, const char *src ) {
 -      size_t n = strlen( dst );
 -
 -      if ( n > dlen ) {
 -              abort(); /* buffer overflow */
 -      }
 -
 -      return Q_strncpyz( dst + n, src, dlen - n );
 -}
 -
 -
 -char *Q_strncat( char *dst, size_t dlen, const char *src, size_t slen ) {
 -      size_t n = strlen( dst );
 -
 -      if ( n > dlen ) {
 -              abort(); /* buffer overflow */
 -      }
 -
 -      return Q_strncpyz( dst + n, src, MIN( slen, dlen - n ) );
 -}
 -
 -
 -/*
 -   ExitQ3Map()
 -   cleanup routine
 - */
 -
 -static void ExitQ3Map( void ){
 -      BSPFilesCleanup();
 -      if ( mapDrawSurfs != NULL ) {
 -              free( mapDrawSurfs );
 -      }
 -}
 -
 -
 -
 -/* minimap stuff */
 -
 -typedef struct minimap_s
 -{
 -      bspModel_t *model;
 -      int width;
 -      int height;
 -      int samples;
 -      float *sample_offsets;
 -      float sharpen_boxmult;
 -      float sharpen_centermult;
 -      float boost, brightness, contrast;
 -      float *data1f;
 -      float *sharpendata1f;
 -      vec3_t mins, size;
 -}
 -minimap_t;
 -static minimap_t minimap;
 -
 -qboolean BrushIntersectionWithLine( bspBrush_t *brush, vec3_t start, vec3_t dir, float *t_in, float *t_out ){
 -      int i;
 -      qboolean in = qfalse, out = qfalse;
 -      bspBrushSide_t *sides = &bspBrushSides[brush->firstSide];
 -
 -      for ( i = 0; i < brush->numSides; ++i )
 -      {
 -              bspPlane_t *p = &bspPlanes[sides[i].planeNum];
 -              float sn = DotProduct( start, p->normal );
 -              float dn = DotProduct( dir, p->normal );
 -              if ( dn == 0 ) {
 -                      if ( sn > p->dist ) {
 -                              return qfalse; // outside!
 -                      }
 -              }
 -              else
 -              {
 -                      float t = ( p->dist - sn ) / dn;
 -                      if ( dn < 0 ) {
 -                              if ( !in || t > *t_in ) {
 -                                      *t_in = t;
 -                                      in = qtrue;
 -                                      // as t_in can only increase, and t_out can only decrease, early out
 -                                      if ( out && *t_in >= *t_out ) {
 -                                              return qfalse;
 -                                      }
 -                              }
 -                      }
 -                      else
 -                      {
 -                              if ( !out || t < *t_out ) {
 -                                      *t_out = t;
 -                                      out = qtrue;
 -                                      // as t_in can only increase, and t_out can only decrease, early out
 -                                      if ( in && *t_in >= *t_out ) {
 -                                              return qfalse;
 -                                      }
 -                              }
 -                      }
 -              }
 -      }
 -      return in && out;
 -}
 -
 -static float MiniMapSample( float x, float y ){
 -      vec3_t org, dir;
 -      int i, bi;
 -      float t0, t1;
 -      float samp;
 -      bspBrush_t *b;
 -      bspBrushSide_t *s;
 -      int cnt;
 -
 -      org[0] = x;
 -      org[1] = y;
 -      org[2] = 0;
 -      dir[0] = 0;
 -      dir[1] = 0;
 -      dir[2] = 1;
 -
 -      cnt = 0;
 -      samp = 0;
 -      for ( i = 0; i < minimap.model->numBSPBrushes; ++i )
 -      {
 -              bi = minimap.model->firstBSPBrush + i;
 -              if ( opaqueBrushes[bi >> 3] & ( 1 << ( bi & 7 ) ) ) {
 -                      b = &bspBrushes[bi];
 -
 -                      // sort out mins/maxs of the brush
 -                      s = &bspBrushSides[b->firstSide];
 -                      if ( x < -bspPlanes[s[0].planeNum].dist ) {
 -                              continue;
 -                      }
 -                      if ( x > +bspPlanes[s[1].planeNum].dist ) {
 -                              continue;
 -                      }
 -                      if ( y < -bspPlanes[s[2].planeNum].dist ) {
 -                              continue;
 -                      }
 -                      if ( y > +bspPlanes[s[3].planeNum].dist ) {
 -                              continue;
 -                      }
 -
 -                      if ( BrushIntersectionWithLine( b, org, dir, &t0, &t1 ) ) {
 -                              samp += t1 - t0;
 -                              ++cnt;
 -                      }
 -              }
 -      }
 -
 -      return samp;
 -}
 -
 -void RandomVector2f( float v[2] ){
 -      do
 -      {
 -              v[0] = 2 * Random() - 1;
 -              v[1] = 2 * Random() - 1;
 -      }
 -      while ( v[0] * v[0] + v[1] * v[1] > 1 );
 -}
 -
 -static void MiniMapRandomlySupersampled( int y ){
 -      int x, i;
 -      float *p = &minimap.data1f[y * minimap.width];
 -      float ymin = minimap.mins[1] + minimap.size[1] * ( y / (float) minimap.height );
 -      float dx   =                   minimap.size[0]      / (float) minimap.width;
 -      float dy   =                   minimap.size[1]      / (float) minimap.height;
 -      float uv[2];
 -      float thisval;
 -
 -      for ( x = 0; x < minimap.width; ++x )
 -      {
 -              float xmin = minimap.mins[0] + minimap.size[0] * ( x / (float) minimap.width );
 -              float val = 0;
 -
 -              for ( i = 0; i < minimap.samples; ++i )
 -              {
 -                      RandomVector2f( uv );
 -                      thisval = MiniMapSample(
 -                              xmin + ( uv[0] + 0.5 ) * dx, /* exaggerated random pattern for better results */
 -                              ymin + ( uv[1] + 0.5 ) * dy  /* exaggerated random pattern for better results */
 -                              );
 -                      val += thisval;
 -              }
 -              val /= minimap.samples * minimap.size[2];
 -              *p++ = val;
 -      }
 -}
 -
 -static void MiniMapSupersampled( int y ){
 -      int x, i;
 -      float *p = &minimap.data1f[y * minimap.width];
 -      float ymin = minimap.mins[1] + minimap.size[1] * ( y / (float) minimap.height );
 -      float dx   =                   minimap.size[0]      / (float) minimap.width;
 -      float dy   =                   minimap.size[1]      / (float) minimap.height;
 -
 -      for ( x = 0; x < minimap.width; ++x )
 -      {
 -              float xmin = minimap.mins[0] + minimap.size[0] * ( x / (float) minimap.width );
 -              float val = 0;
 -
 -              for ( i = 0; i < minimap.samples; ++i )
 -              {
 -                      float thisval = MiniMapSample(
 -                              xmin + minimap.sample_offsets[2 * i + 0] * dx,
 -                              ymin + minimap.sample_offsets[2 * i + 1] * dy
 -                              );
 -                      val += thisval;
 -              }
 -              val /= minimap.samples * minimap.size[2];
 -              *p++ = val;
 -      }
 -}
 -
 -static void MiniMapNoSupersampling( int y ){
 -      int x;
 -      float *p = &minimap.data1f[y * minimap.width];
 -      float ymin = minimap.mins[1] + minimap.size[1] * ( ( y + 0.5 ) / (float) minimap.height );
 -
 -      for ( x = 0; x < minimap.width; ++x )
 -      {
 -              float xmin = minimap.mins[0] + minimap.size[0] * ( ( x + 0.5 ) / (float) minimap.width );
 -              *p++ = MiniMapSample( xmin, ymin ) / minimap.size[2];
 -      }
 -}
 -
 -static void MiniMapSharpen( int y ){
 -      int x;
 -      qboolean up = ( y > 0 );
 -      qboolean down = ( y < minimap.height - 1 );
 -      float *p = &minimap.data1f[y * minimap.width];
 -      float *q = &minimap.sharpendata1f[y * minimap.width];
 -
 -      for ( x = 0; x < minimap.width; ++x )
 -      {
 -              qboolean left = ( x > 0 );
 -              qboolean right = ( x < minimap.width - 1 );
 -              float val = p[0] * minimap.sharpen_centermult;
 -
 -              if ( left && up ) {
 -                      val += p[-1 - minimap.width] * minimap.sharpen_boxmult;
 -              }
 -              if ( left && down ) {
 -                      val += p[-1 + minimap.width] * minimap.sharpen_boxmult;
 -              }
 -              if ( right && up ) {
 -                      val += p[+1 - minimap.width] * minimap.sharpen_boxmult;
 -              }
 -              if ( right && down ) {
 -                      val += p[+1 + minimap.width] * minimap.sharpen_boxmult;
 -              }
 -
 -              if ( left ) {
 -                      val += p[-1] * minimap.sharpen_boxmult;
 -              }
 -              if ( right ) {
 -                      val += p[+1] * minimap.sharpen_boxmult;
 -              }
 -              if ( up ) {
 -                      val += p[-minimap.width] * minimap.sharpen_boxmult;
 -              }
 -              if ( down ) {
 -                      val += p[+minimap.width] * minimap.sharpen_boxmult;
 -              }
 -
 -              ++p;
 -              *q++ = val;
 -      }
 -}
 -
 -static void MiniMapContrastBoost( int y ){
 -      int x;
 -      float *q = &minimap.data1f[y * minimap.width];
 -      for ( x = 0; x < minimap.width; ++x )
 -      {
 -              *q = *q * minimap.boost / ( ( minimap.boost - 1 ) * *q + 1 );
 -              ++q;
 -      }
 -}
 -
 -static void MiniMapBrightnessContrast( int y ){
 -      int x;
 -      float *q = &minimap.data1f[y * minimap.width];
 -      for ( x = 0; x < minimap.width; ++x )
 -      {
 -              *q = *q * minimap.contrast + minimap.brightness;
 -              ++q;
 -      }
 -}
 -
 -void MiniMapMakeMinsMaxs( vec3_t mins_in, vec3_t maxs_in, float border, qboolean keepaspect ){
 -      vec3_t mins, maxs, extend;
 -      VectorCopy( mins_in, mins );
 -      VectorCopy( maxs_in, maxs );
 -
 -      // line compatible to nexuiz mapinfo
 -      Sys_Printf( "size %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2] );
 -
 -      if ( keepaspect ) {
 -              VectorSubtract( maxs, mins, extend );
 -              if ( extend[1] > extend[0] ) {
 -                      mins[0] -= ( extend[1] - extend[0] ) * 0.5;
 -                      maxs[0] += ( extend[1] - extend[0] ) * 0.5;
 -              }
 -              else
 -              {
 -                      mins[1] -= ( extend[0] - extend[1] ) * 0.5;
 -                      maxs[1] += ( extend[0] - extend[1] ) * 0.5;
 -              }
 -      }
 -
 -      /* border: amount of black area around the image */
 -      /* input: border, 1-2*border, border but we need border/(1-2*border) */
 -
 -      VectorSubtract( maxs, mins, extend );
 -      VectorScale( extend, border / ( 1 - 2 * border ), extend );
 -
 -      VectorSubtract( mins, extend, mins );
 -      VectorAdd( maxs, extend, maxs );
 -
 -      VectorCopy( mins, minimap.mins );
 -      VectorSubtract( maxs, mins, minimap.size );
 -
 -      // line compatible to nexuiz mapinfo
 -      Sys_Printf( "size_texcoords %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2] );
 -}
 -
 -/*
 -   MiniMapSetupBrushes()
 -   determines solid non-sky brushes in the world
 - */
 -
 -void MiniMapSetupBrushes( void ){
 -      SetupBrushesFlags( C_SOLID | C_SKY, C_SOLID, 0, 0 );
 -      // at least one must be solid
 -      // none may be sky
 -      // not all may be nodraw
 -}
 -
 -qboolean MiniMapEvaluateSampleOffsets( int *bestj, int *bestk, float *bestval ){
 -      float val, dx, dy;
 -      int j, k;
 -
 -      *bestj = *bestk = -1;
 -      *bestval = 3; /* max possible val is 2 */
 -
 -      for ( j = 0; j < minimap.samples; ++j )
 -              for ( k = j + 1; k < minimap.samples; ++k )
 -              {
 -                      dx = minimap.sample_offsets[2 * j + 0] - minimap.sample_offsets[2 * k + 0];
 -                      dy = minimap.sample_offsets[2 * j + 1] - minimap.sample_offsets[2 * k + 1];
 -                      if ( dx > +0.5 ) {
 -                              dx -= 1;
 -                      }
 -                      if ( dx < -0.5 ) {
 -                              dx += 1;
 -                      }
 -                      if ( dy > +0.5 ) {
 -                              dy -= 1;
 -                      }
 -                      if ( dy < -0.5 ) {
 -                              dy += 1;
 -                      }
 -                      val = dx * dx + dy * dy;
 -                      if ( val < *bestval ) {
 -                              *bestj = j;
 -                              *bestk = k;
 -                              *bestval = val;
 -                      }
 -              }
 -
 -      return *bestval < 3;
 -}
 -
 -void MiniMapMakeSampleOffsets(){
 -      int i, j, k, jj, kk;
 -      float val, valj, valk, sx, sy, rx, ry;
 -
 -      Sys_Printf( "Generating good sample offsets (this may take a while)...\n" );
 -
 -      /* start with entirely random samples */
 -      for ( i = 0; i < minimap.samples; ++i )
 -      {
 -              minimap.sample_offsets[2 * i + 0] = Random();
 -              minimap.sample_offsets[2 * i + 1] = Random();
 -      }
 -
 -      for ( i = 0; i < 1000; ++i )
 -      {
 -              if ( MiniMapEvaluateSampleOffsets( &j, &k, &val ) ) {
 -                      sx = minimap.sample_offsets[2 * j + 0];
 -                      sy = minimap.sample_offsets[2 * j + 1];
 -                      minimap.sample_offsets[2 * j + 0] = rx = Random();
 -                      minimap.sample_offsets[2 * j + 1] = ry = Random();
 -                      if ( !MiniMapEvaluateSampleOffsets( &jj, &kk, &valj ) ) {
 -                              valj = -1;
 -                      }
 -                      minimap.sample_offsets[2 * j + 0] = sx;
 -                      minimap.sample_offsets[2 * j + 1] = sy;
 -
 -                      sx = minimap.sample_offsets[2 * k + 0];
 -                      sy = minimap.sample_offsets[2 * k + 1];
 -                      minimap.sample_offsets[2 * k + 0] = rx;
 -                      minimap.sample_offsets[2 * k + 1] = ry;
 -                      if ( !MiniMapEvaluateSampleOffsets( &jj, &kk, &valk ) ) {
 -                              valk = -1;
 -                      }
 -                      minimap.sample_offsets[2 * k + 0] = sx;
 -                      minimap.sample_offsets[2 * k + 1] = sy;
 -
 -                      if ( valj > valk ) {
 -                              if ( valj > val ) {
 -                                      /* valj is the greatest */
 -                                      minimap.sample_offsets[2 * j + 0] = rx;
 -                                      minimap.sample_offsets[2 * j + 1] = ry;
 -                                      i = -1;
 -                              }
 -                              else
 -                              {
 -                                      /* valj is the greater and it is useless - forget it */
 -                              }
 -                      }
 -                      else
 -                      {
 -                              if ( valk > val ) {
 -                                      /* valk is the greatest */
 -                                      minimap.sample_offsets[2 * k + 0] = rx;
 -                                      minimap.sample_offsets[2 * k + 1] = ry;
 -                                      i = -1;
 -                              }
 -                              else
 -                              {
 -                                      /* valk is the greater and it is useless - forget it */
 -                              }
 -                      }
 -              }
 -              else{
 -                      break;
 -              }
 -      }
 -}
 -
 -void MergeRelativePath( char *out, const char *absolute, const char *relative ){
 -      const char *endpos = absolute + strlen( absolute );
 -      while ( endpos != absolute && ( endpos[-1] == '/' || endpos[-1] == '\\' ) )
 -              --endpos;
 -      while ( relative[0] == '.' && relative[1] == '.' && ( relative[2] == '/' || relative[2] == '\\' ) )
 -      {
 -              relative += 3;
 -              while ( endpos != absolute )
 -              {
 -                      --endpos;
 -                      if ( *endpos == '/' || *endpos == '\\' ) {
 -                              break;
 -                      }
 -              }
 -              while ( endpos != absolute && ( endpos[-1] == '/' || endpos[-1] == '\\' ) )
 -                      --endpos;
 -      }
 -      memcpy( out, absolute, endpos - absolute );
 -      out[endpos - absolute] = '/';
 -      strcpy( out + ( endpos - absolute + 1 ), relative );
 -}
 -
 -int MiniMapBSPMain( int argc, char **argv ){
 -      char minimapFilename[1024];
 -      char basename[1024];
 -      char path[1024];
 -      char relativeMinimapFilename[1024];
 -      qboolean autolevel;
 -      float minimapSharpen;
 -      float border;
 -      byte *data4b, *p;
 -      float *q;
 -      int x, y;
 -      int i;
 -      miniMapMode_t mode;
 -      vec3_t mins, maxs;
 -      qboolean keepaspect;
 -
 -      /* arg checking */
 -      if ( argc < 2 ) {
 -              Sys_Printf( "Usage: q3map [-v] -minimap [-size n] [-sharpen f] [-samples n | -random n] [-o filename.tga] [-minmax Xmin Ymin Zmin Xmax Ymax Zmax] <mapname>\n" );
 -              return 0;
 -      }
 -
 -      /* load the BSP first */
 -      strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
 -      StripExtension( source );
 -      DefaultExtension( source, ".bsp" );
 -      Sys_Printf( "Loading %s\n", source );
 -      //BeginMapShaderFile( source ); //do not delete q3map2_*.shader on minimap generation
 -      LoadShaderInfo();
 -      LoadBSPFile( source );
 -
 -      minimap.model = &bspModels[0];
 -      VectorCopy( minimap.model->mins, mins );
 -      VectorCopy( minimap.model->maxs, maxs );
 -
 -      *minimapFilename = 0;
 -      minimapSharpen = game->miniMapSharpen;
 -      minimap.width = minimap.height = game->miniMapSize;
 -      border = game->miniMapBorder;
 -      keepaspect = game->miniMapKeepAspect;
 -      mode = game->miniMapMode;
 -
 -      autolevel = qfalse;
 -      minimap.samples = 1;
 -      minimap.sample_offsets = NULL;
 -      minimap.boost = 1.0;
 -      minimap.brightness = 0.0;
 -      minimap.contrast = 1.0;
 -
 -      /* process arguments */
 -      for ( i = 1; i < ( argc - 1 ); i++ )
 -      {
 -              if ( !strcmp( argv[ i ],  "-size" ) ) {
 -                      minimap.width = minimap.height = atoi( argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Image size set to %i\n", minimap.width );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-sharpen" ) ) {
 -                      minimapSharpen = atof( argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Sharpening coefficient set to %f\n", minimapSharpen );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-samples" ) ) {
 -                      minimap.samples = atoi( argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Samples set to %i\n", minimap.samples );
 -                      if ( minimap.sample_offsets ) {
 -                              free( minimap.sample_offsets );
 -                      }
 -                      minimap.sample_offsets = malloc( 2 * sizeof( *minimap.sample_offsets ) * minimap.samples );
 -                      MiniMapMakeSampleOffsets();
 -              }
 -              else if ( !strcmp( argv[ i ],  "-random" ) ) {
 -                      minimap.samples = atoi( argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Random samples set to %i\n", minimap.samples );
 -                      if ( minimap.sample_offsets ) {
 -                              free( minimap.sample_offsets );
 -                      }
 -                      minimap.sample_offsets = NULL;
 -              }
 -              else if ( !strcmp( argv[ i ],  "-border" ) ) {
 -                      border = atof( argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Border set to %f\n", border );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-keepaspect" ) ) {
 -                      keepaspect = qtrue;
 -                      Sys_Printf( "Keeping aspect ratio by letterboxing\n", border );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-nokeepaspect" ) ) {
 -                      keepaspect = qfalse;
 -                      Sys_Printf( "Not keeping aspect ratio\n", border );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-o" ) ) {
 -                      strcpy( minimapFilename, argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Output file name set to %s\n", minimapFilename );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-minmax" ) && i < ( argc - 7 ) ) {
 -                      mins[0] = atof( argv[i + 1] );
 -                      mins[1] = atof( argv[i + 2] );
 -                      mins[2] = atof( argv[i + 3] );
 -                      maxs[0] = atof( argv[i + 4] );
 -                      maxs[1] = atof( argv[i + 5] );
 -                      maxs[2] = atof( argv[i + 6] );
 -                      i += 6;
 -                      Sys_Printf( "Map mins/maxs overridden\n" );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-gray" ) ) {
 -                      mode = MINIMAP_MODE_GRAY;
 -                      Sys_Printf( "Writing as white-on-black image\n" );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-black" ) ) {
 -                      mode = MINIMAP_MODE_BLACK;
 -                      Sys_Printf( "Writing as black alpha image\n" );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-white" ) ) {
 -                      mode = MINIMAP_MODE_WHITE;
 -                      Sys_Printf( "Writing as white alpha image\n" );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-boost" ) && i < ( argc - 2 ) ) {
 -                      minimap.boost = atof( argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Contrast boost set to %f\n", minimap.boost );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-brightness" ) && i < ( argc - 2 ) ) {
 -                      minimap.brightness = atof( argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Brightness set to %f\n", minimap.brightness );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-contrast" ) && i < ( argc - 2 ) ) {
 -                      minimap.contrast = atof( argv[i + 1] );
 -                      i++;
 -                      Sys_Printf( "Contrast set to %f\n", minimap.contrast );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-autolevel" ) ) {
 -                      autolevel = qtrue;
 -                      Sys_Printf( "Auto level enabled\n", border );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-noautolevel" ) ) {
 -                      autolevel = qfalse;
 -                      Sys_Printf( "Auto level disabled\n", border );
 -              }
 -      }
 -
 -      MiniMapMakeMinsMaxs( mins, maxs, border, keepaspect );
 -
 -      if ( !*minimapFilename ) {
 -              ExtractFileBase( source, basename );
 -              ExtractFilePath( source, path );
 -              sprintf( relativeMinimapFilename, game->miniMapNameFormat, basename );
 -              MergeRelativePath( minimapFilename, path, relativeMinimapFilename );
 -              Sys_Printf( "Output file name automatically set to %s\n", minimapFilename );
 -      }
 -      ExtractFilePath( minimapFilename, path );
 -      Q_mkdir( path );
 -
 -      if ( minimapSharpen >= 0 ) {
 -              minimap.sharpen_centermult = 8 * minimapSharpen + 1;
 -              minimap.sharpen_boxmult    =    -minimapSharpen;
 -      }
 -
 -      minimap.data1f = safe_malloc( minimap.width * minimap.height * sizeof( *minimap.data1f ) );
 -      data4b = safe_malloc( minimap.width * minimap.height * 4 );
 -      if ( minimapSharpen >= 0 ) {
 -              minimap.sharpendata1f = safe_malloc( minimap.width * minimap.height * sizeof( *minimap.data1f ) );
 -      }
 -
 -      MiniMapSetupBrushes();
 -
 -      if ( minimap.samples <= 1 ) {
 -              Sys_Printf( "\n--- MiniMapNoSupersampling (%d) ---\n", minimap.height );
 -              RunThreadsOnIndividual( minimap.height, qtrue, MiniMapNoSupersampling );
 -      }
 -      else
 -      {
 -              if ( minimap.sample_offsets ) {
 -                      Sys_Printf( "\n--- MiniMapSupersampled (%d) ---\n", minimap.height );
 -                      RunThreadsOnIndividual( minimap.height, qtrue, MiniMapSupersampled );
 -              }
 -              else
 -              {
 -                      Sys_Printf( "\n--- MiniMapRandomlySupersampled (%d) ---\n", minimap.height );
 -                      RunThreadsOnIndividual( minimap.height, qtrue, MiniMapRandomlySupersampled );
 -              }
 -      }
 -
 -      if ( minimap.boost != 1.0 ) {
 -              Sys_Printf( "\n--- MiniMapContrastBoost (%d) ---\n", minimap.height );
 -              RunThreadsOnIndividual( minimap.height, qtrue, MiniMapContrastBoost );
 -      }
 -
 -      if ( autolevel ) {
 -              Sys_Printf( "\n--- MiniMapAutoLevel (%d) ---\n", minimap.height );
 -              float mi = 1, ma = 0;
 -              float s, o;
 -
 -              // TODO threads!
 -              q = minimap.data1f;
 -              for ( y = 0; y < minimap.height; ++y )
 -                      for ( x = 0; x < minimap.width; ++x )
 -                      {
 -                              float v = *q++;
 -                              if ( v < mi ) {
 -                                      mi = v;
 -                              }
 -                              if ( v > ma ) {
 -                                      ma = v;
 -                              }
 -                      }
 -              if ( ma > mi ) {
 -                      s = 1 / ( ma - mi );
 -                      o = mi / ( ma - mi );
 -
 -                      // equations:
 -                      //   brightness + contrast * v
 -                      // after autolevel:
 -                      //   brightness + contrast * (v * s - o)
 -                      // =
 -                      //   (brightness - contrast * o) + (contrast * s) * v
 -                      minimap.brightness = minimap.brightness - minimap.contrast * o;
 -                      minimap.contrast *= s;
 -
 -                      Sys_Printf( "Auto level: Brightness changed to %f\n", minimap.brightness );
 -                      Sys_Printf( "Auto level: Contrast changed to %f\n", minimap.contrast );
 -              }
 -              else{
 -                      Sys_Printf( "Auto level: failed because all pixels are the same value\n" );
 -              }
 -      }
 -
 -      if ( minimap.brightness != 0 || minimap.contrast != 1 ) {
 -              Sys_Printf( "\n--- MiniMapBrightnessContrast (%d) ---\n", minimap.height );
 -              RunThreadsOnIndividual( minimap.height, qtrue, MiniMapBrightnessContrast );
 -      }
 -
 -      if ( minimap.sharpendata1f ) {
 -              Sys_Printf( "\n--- MiniMapSharpen (%d) ---\n", minimap.height );
 -              RunThreadsOnIndividual( minimap.height, qtrue, MiniMapSharpen );
 -              q = minimap.sharpendata1f;
 -      }
 -      else
 -      {
 -              q = minimap.data1f;
 -      }
 -
 -      Sys_Printf( "\nConverting..." );
 -
 -      switch ( mode )
 -      {
 -      case MINIMAP_MODE_GRAY:
 -              p = data4b;
 -              for ( y = 0; y < minimap.height; ++y )
 -                      for ( x = 0; x < minimap.width; ++x )
 -                      {
 -                              byte b;
 -                              float v = *q++;
 -                              if ( v < 0 ) {
 -                                      v = 0;
 -                              }
 -                              if ( v > 255.0 / 256.0 ) {
 -                                      v = 255.0 / 256.0;
 -                              }
 -                              b = v * 256;
 -                              *p++ = b;
 -                      }
 -              Sys_Printf( " writing to %s...", minimapFilename );
 -              WriteTGAGray( minimapFilename, data4b, minimap.width, minimap.height );
 -              break;
 -      case MINIMAP_MODE_BLACK:
 -              p = data4b;
 -              for ( y = 0; y < minimap.height; ++y )
 -                      for ( x = 0; x < minimap.width; ++x )
 -                      {
 -                              byte b;
 -                              float v = *q++;
 -                              if ( v < 0 ) {
 -                                      v = 0;
 -                              }
 -                              if ( v > 255.0 / 256.0 ) {
 -                                      v = 255.0 / 256.0;
 -                              }
 -                              b = v * 256;
 -                              *p++ = 0;
 -                              *p++ = 0;
 -                              *p++ = 0;
 -                              *p++ = b;
 -                      }
 -              Sys_Printf( " writing to %s...", minimapFilename );
 -              WriteTGA( minimapFilename, data4b, minimap.width, minimap.height );
 -              break;
 -      case MINIMAP_MODE_WHITE:
 -              p = data4b;
 -              for ( y = 0; y < minimap.height; ++y )
 -                      for ( x = 0; x < minimap.width; ++x )
 -                      {
 -                              byte b;
 -                              float v = *q++;
 -                              if ( v < 0 ) {
 -                                      v = 0;
 -                              }
 -                              if ( v > 255.0 / 256.0 ) {
 -                                      v = 255.0 / 256.0;
 -                              }
 -                              b = v * 256;
 -                              *p++ = 255;
 -                              *p++ = 255;
 -                              *p++ = 255;
 -                              *p++ = b;
 -                      }
 -              Sys_Printf( " writing to %s...", minimapFilename );
 -              WriteTGA( minimapFilename, data4b, minimap.width, minimap.height );
 -              break;
 -      }
 -
 -      Sys_Printf( " done.\n" );
 -
 -      /* return to sender */
 -      return 0;
 -}
 -
 -
 -
 -
 -
 -/*
 -   MD4BlockChecksum()
 -   calculates an md4 checksum for a block of data
 - */
 -
 -static int MD4BlockChecksum( void *buffer, int length ){
 -      return Com_BlockChecksum( buffer, length );
 -}
 -
 -/*
 -   FixAAS()
 -   resets an aas checksum to match the given BSP
 - */
 -
 -int FixAAS( int argc, char **argv ){
 -      int length, checksum;
 -      void        *buffer;
 -      FILE        *file;
 -      char aas[ 1024 ], **ext;
 -      char        *exts[] =
 -      {
 -              ".aas",
 -              "_b0.aas",
 -              "_b1.aas",
 -              NULL
 -      };
 -
 -
 -      /* arg checking */
 -      if ( argc < 2 ) {
 -              Sys_Printf( "Usage: q3map -fixaas [-v] <mapname>\n" );
 -              return 0;
 -      }
 -
 -      /* do some path mangling */
 -      strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
 -      StripExtension( source );
 -      DefaultExtension( source, ".bsp" );
 -
 -      /* note it */
 -      Sys_Printf( "--- FixAAS ---\n" );
 -
 -      /* load the bsp */
 -      Sys_Printf( "Loading %s\n", source );
 -      length = LoadFile( source, &buffer );
 -
 -      /* create bsp checksum */
 -      Sys_Printf( "Creating checksum...\n" );
 -      checksum = LittleLong( MD4BlockChecksum( buffer, length ) );
 -
 -      /* write checksum to aas */
 -      ext = exts;
 -      while ( *ext )
 -      {
 -              /* mangle name */
 -              strcpy( aas, source );
 -              StripExtension( aas );
 -              strcat( aas, *ext );
 -              Sys_Printf( "Trying %s\n", aas );
 -              ext++;
 -
 -              /* fix it */
 -              file = fopen( aas, "r+b" );
 -              if ( !file ) {
 -                      continue;
 -              }
 -              if ( fwrite( &checksum, 4, 1, file ) != 1 ) {
 -                      Error( "Error writing checksum to %s", aas );
 -              }
 -              fclose( file );
 -      }
 -
 -      /* return to sender */
 -      return 0;
 -}
 -
 -
 -
 -/*
 -   AnalyzeBSP() - ydnar
 -   analyzes a Quake engine BSP file
 - */
 -
 -typedef struct abspHeader_s
 -{
 -      char ident[ 4 ];
 -      int version;
 -
 -      bspLump_t lumps[ 1 ];       /* unknown size */
 -}
 -abspHeader_t;
 -
 -typedef struct abspLumpTest_s
 -{
 -      int radix, minCount;
 -      char            *name;
 -}
 -abspLumpTest_t;
 -
 -int AnalyzeBSP( int argc, char **argv ){
 -      abspHeader_t            *header;
 -      int size, i, version, offset, length, lumpInt, count;
 -      char ident[ 5 ];
 -      void                    *lump;
 -      float lumpFloat;
 -      char lumpString[ 1024 ], source[ 1024 ];
 -      qboolean lumpSwap = qfalse;
 -      abspLumpTest_t          *lumpTest;
 -      static abspLumpTest_t lumpTests[] =
 -      {
 -              { sizeof( bspPlane_t ),         6,      "IBSP LUMP_PLANES" },
 -              { sizeof( bspBrush_t ),         1,      "IBSP LUMP_BRUSHES" },
 -              { 8,                            6,      "IBSP LUMP_BRUSHSIDES" },
 -              { sizeof( bspBrushSide_t ),     6,      "RBSP LUMP_BRUSHSIDES" },
 -              { sizeof( bspModel_t ),         1,      "IBSP LUMP_MODELS" },
 -              { sizeof( bspNode_t ),          2,      "IBSP LUMP_NODES" },
 -              { sizeof( bspLeaf_t ),          1,      "IBSP LUMP_LEAFS" },
 -              { 104,                          3,      "IBSP LUMP_DRAWSURFS" },
 -              { 44,                           3,      "IBSP LUMP_DRAWVERTS" },
 -              { 4,                            6,      "IBSP LUMP_DRAWINDEXES" },
 -              { 128 * 128 * 3,                1,      "IBSP LUMP_LIGHTMAPS" },
 -              { 256 * 256 * 3,                1,      "IBSP LUMP_LIGHTMAPS (256 x 256)" },
 -              { 512 * 512 * 3,                1,      "IBSP LUMP_LIGHTMAPS (512 x 512)" },
 -              { 0, 0, NULL }
 -      };
 -
 -
 -      /* arg checking */
 -      if ( argc < 1 ) {
 -              Sys_Printf( "Usage: q3map -analyze [-lumpswap] [-v] <mapname>\n" );
 -              return 0;
 -      }
 -
 -      /* process arguments */
 -      for ( i = 1; i < ( argc - 1 ); i++ )
 -      {
 -              /* -format map|ase|... */
 -              if ( !strcmp( argv[ i ],  "-lumpswap" ) ) {
 -                      Sys_Printf( "Swapped lump structs enabled\n" );
 -                      lumpSwap = qtrue;
 -              }
 -      }
 -
 -      /* clean up map name */
 -      strcpy( source, ExpandArg( argv[ i ] ) );
 -      Sys_Printf( "Loading %s\n", source );
 -
 -      /* load the file */
 -      size = LoadFile( source, (void**) &header );
 -      if ( size == 0 || header == NULL ) {
 -              Sys_Printf( "Unable to load %s.\n", source );
 -              return -1;
 -      }
 -
 -      /* analyze ident/version */
 -      memcpy( ident, header->ident, 4 );
 -      ident[ 4 ] = '\0';
 -      version = LittleLong( header->version );
 -
 -      Sys_Printf( "Identity:      %s\n", ident );
 -      Sys_Printf( "Version:       %d\n", version );
 -      Sys_Printf( "---------------------------------------\n" );
 -
 -      /* analyze each lump */
 -      for ( i = 0; i < 100; i++ )
 -      {
 -              /* call of duty swapped lump pairs */
 -              if ( lumpSwap ) {
 -                      offset = LittleLong( header->lumps[ i ].length );
 -                      length = LittleLong( header->lumps[ i ].offset );
 -              }
 -
 -              /* standard lump pairs */
 -              else
 -              {
 -                      offset = LittleLong( header->lumps[ i ].offset );
 -                      length = LittleLong( header->lumps[ i ].length );
 -              }
 -
 -              /* extract data */
 -              lump = (byte*) header + offset;
 -              lumpInt = LittleLong( (int) *( (int*) lump ) );
 -              lumpFloat = LittleFloat( (float) *( (float*) lump ) );
 -              memcpy( lumpString, (char*) lump, ( (size_t)length < sizeof( lumpString ) ? (size_t)length : sizeof( lumpString ) - 1 ) );
 -              lumpString[ sizeof( lumpString ) - 1 ] = '\0';
 -
 -              /* print basic lump info */
 -              Sys_Printf( "Lump:          %d\n", i );
 -              Sys_Printf( "Offset:        %d bytes\n", offset );
 -              Sys_Printf( "Length:        %d bytes\n", length );
 -
 -              /* only operate on valid lumps */
 -              if ( length > 0 ) {
 -                      /* print data in 4 formats */
 -                      Sys_Printf( "As hex:        %08X\n", lumpInt );
 -                      Sys_Printf( "As int:        %d\n", lumpInt );
 -                      Sys_Printf( "As float:      %f\n", lumpFloat );
 -                      Sys_Printf( "As string:     %s\n", lumpString );
 -
 -                      /* guess lump type */
 -                      if ( lumpString[ 0 ] == '{' && lumpString[ 2 ] == '"' ) {
 -                              Sys_Printf( "Type guess:    IBSP LUMP_ENTITIES\n" );
 -                      }
 -                      else if ( strstr( lumpString, "textures/" ) ) {
 -                              Sys_Printf( "Type guess:    IBSP LUMP_SHADERS\n" );
 -                      }
 -                      else
 -                      {
 -                              /* guess based on size/count */
 -                              for ( lumpTest = lumpTests; lumpTest->radix > 0; lumpTest++ )
 -                              {
 -                                      if ( ( length % lumpTest->radix ) != 0 ) {
 -                                              continue;
 -                                      }
 -                                      count = length / lumpTest->radix;
 -                                      if ( count < lumpTest->minCount ) {
 -                                              continue;
 -                                      }
 -                                      Sys_Printf( "Type guess:    %s (%d x %d)\n", lumpTest->name, count, lumpTest->radix );
 -                              }
 -                      }
 -              }
 -
 -              Sys_Printf( "---------------------------------------\n" );
 -
 -              /* end of file */
 -              if ( offset + length >= size ) {
 -                      break;
 -              }
 -      }
 -
 -      /* last stats */
 -      Sys_Printf( "Lump count:    %d\n", i + 1 );
 -      Sys_Printf( "File size:     %d bytes\n", size );
 -
 -      /* return to caller */
 -      return 0;
 -}
 -
 -
 -
 -/*
 -   BSPInfo()
 -   emits statistics about the bsp file
 - */
 -
 -int BSPInfo( int count, char **fileNames ){
 -      int i;
 -      char source[ 1024 ], ext[ 64 ];
 -      int size;
 -      FILE        *f;
 -
 -
 -      /* dummy check */
 -      if ( count < 1 ) {
 -              Sys_Printf( "No files to dump info for.\n" );
 -              return -1;
 -      }
 -
 -      /* enable info mode */
 -      infoMode = qtrue;
 -
 -      /* walk file list */
 -      for ( i = 0; i < count; i++ )
 -      {
 -              Sys_Printf( "---------------------------------\n" );
 -
 -              /* mangle filename and get size */
 -              strcpy( source, fileNames[ i ] );
 -              ExtractFileExtension( source, ext );
 -              if ( !Q_stricmp( ext, "map" ) ) {
 -                      StripExtension( source );
 -              }
 -              DefaultExtension( source, ".bsp" );
 -              f = fopen( source, "rb" );
 -              if ( f ) {
 -                      size = Q_filelength( f );
 -                      fclose( f );
 -              }
 -              else{
 -                      size = 0;
 -              }
 -
 -              /* load the bsp file and print lump sizes */
 -              Sys_Printf( "%s\n", source );
 -              LoadBSPFile( source );
 -              PrintBSPFileSizes();
 -
 -              /* print sizes */
 -              Sys_Printf( "\n" );
 -              Sys_Printf( "          total         %9d\n", size );
 -              Sys_Printf( "                        %9d KB\n", size / 1024 );
 -              Sys_Printf( "                        %9d MB\n", size / ( 1024 * 1024 ) );
 -
 -              Sys_Printf( "---------------------------------\n" );
 -      }
 -
 -      /* return count */
 -      return i;
 -}
 -
 -
 -static void ExtrapolateTexcoords( const float *axyz, const float *ast, const float *bxyz, const float *bst, const float *cxyz, const float *cst, const float *axyz_new, float *ast_out, const float *bxyz_new, float *bst_out, const float *cxyz_new, float *cst_out ){
 -      vec4_t scoeffs, tcoeffs;
 -      float md;
 -      m4x4_t solvematrix;
 -
 -      vec3_t norm;
 -      vec3_t dab, dac;
 -      VectorSubtract( bxyz, axyz, dab );
 -      VectorSubtract( cxyz, axyz, dac );
 -      CrossProduct( dab, dac, norm );
 -
 -      // assume:
 -      //   s = f(x, y, z)
 -      //   s(v + norm) = s(v) when n ortho xyz
 -
 -      // s(v) = DotProduct(v, scoeffs) + scoeffs[3]
 -
 -      // solve:
 -      //   scoeffs * (axyz, 1) == ast[0]
 -      //   scoeffs * (bxyz, 1) == bst[0]
 -      //   scoeffs * (cxyz, 1) == cst[0]
 -      //   scoeffs * (norm, 0) == 0
 -      // scoeffs * [axyz, 1 | bxyz, 1 | cxyz, 1 | norm, 0] = [ast[0], bst[0], cst[0], 0]
 -      solvematrix[0] = axyz[0];
 -      solvematrix[4] = axyz[1];
 -      solvematrix[8] = axyz[2];
 -      solvematrix[12] = 1;
 -      solvematrix[1] = bxyz[0];
 -      solvematrix[5] = bxyz[1];
 -      solvematrix[9] = bxyz[2];
 -      solvematrix[13] = 1;
 -      solvematrix[2] = cxyz[0];
 -      solvematrix[6] = cxyz[1];
 -      solvematrix[10] = cxyz[2];
 -      solvematrix[14] = 1;
 -      solvematrix[3] = norm[0];
 -      solvematrix[7] = norm[1];
 -      solvematrix[11] = norm[2];
 -      solvematrix[15] = 0;
 -
 -      md = m4_det( solvematrix );
 -      if ( md * md < 1e-10 ) {
 -              Sys_Printf( "Cannot invert some matrix, some texcoords aren't extrapolated!" );
 -              return;
 -      }
 -
 -      m4x4_invert( solvematrix );
 -
 -      scoeffs[0] = ast[0];
 -      scoeffs[1] = bst[0];
 -      scoeffs[2] = cst[0];
 -      scoeffs[3] = 0;
 -      m4x4_transform_vec4( solvematrix, scoeffs );
 -      tcoeffs[0] = ast[1];
 -      tcoeffs[1] = bst[1];
 -      tcoeffs[2] = cst[1];
 -      tcoeffs[3] = 0;
 -      m4x4_transform_vec4( solvematrix, tcoeffs );
 -
 -      ast_out[0] = scoeffs[0] * axyz_new[0] + scoeffs[1] * axyz_new[1] + scoeffs[2] * axyz_new[2] + scoeffs[3];
 -      ast_out[1] = tcoeffs[0] * axyz_new[0] + tcoeffs[1] * axyz_new[1] + tcoeffs[2] * axyz_new[2] + tcoeffs[3];
 -      bst_out[0] = scoeffs[0] * bxyz_new[0] + scoeffs[1] * bxyz_new[1] + scoeffs[2] * bxyz_new[2] + scoeffs[3];
 -      bst_out[1] = tcoeffs[0] * bxyz_new[0] + tcoeffs[1] * bxyz_new[1] + tcoeffs[2] * bxyz_new[2] + tcoeffs[3];
 -      cst_out[0] = scoeffs[0] * cxyz_new[0] + scoeffs[1] * cxyz_new[1] + scoeffs[2] * cxyz_new[2] + scoeffs[3];
 -      cst_out[1] = tcoeffs[0] * cxyz_new[0] + tcoeffs[1] * cxyz_new[1] + tcoeffs[2] * cxyz_new[2] + tcoeffs[3];
 -}
 +#include <glib.h>
  
  /*
 -   ScaleBSPMain()
 -   amaze and confuse your enemies with wierd scaled maps!
 +   Random()
 +   returns a pseudorandom number between 0 and 1
   */
  
 -int ScaleBSPMain( int argc, char **argv ){
 -      int i, j;
 -      float f, a;
 -      vec3_t scale;
 -      vec3_t vec;
 -      char str[ 1024 ];
 -      int uniform, axis;
 -      qboolean texscale;
 -      float *old_xyzst = NULL;
 -      float spawn_ref = 0;
 +vec_t Random( void ){
 +      return (vec_t) rand() / RAND_MAX;
 +}
  
  
 -      /* arg checking */
 -      if ( argc < 3 ) {
 -              Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref <value>] <value> <mapname>\n" );
 -              return 0;
 +char *Q_strncpyz( char *dst, const char *src, size_t len ) {
 +      if ( len == 0 ) {
 +              abort();
        }
  
 -      texscale = qfalse;
 -      for ( i = 1; i < argc - 2; ++i )
 -      {
 -              if ( !strcmp( argv[i], "-tex" ) ) {
 -                      texscale = qtrue;
 -              }
 -              else if ( !strcmp( argv[i], "-spawn_ref" ) ) {
 -                      spawn_ref = atof( argv[i + 1] );
 -                      ++i;
 -              }
 -              else{
 -                      break;
 -              }
 -      }
 +      strncpy( dst, src, len );
 +      dst[ len - 1 ] = '\0';
 +      return dst;
 +}
  
 -      /* get scale */
 -      // if(argc-2 >= i) // always true
 -      scale[2] = scale[1] = scale[0] = atof( argv[ argc - 2 ] );
 -      if ( argc - 3 >= i ) {
 -              scale[1] = scale[0] = atof( argv[ argc - 3 ] );
 -      }
 -      if ( argc - 4 >= i ) {
 -              scale[0] = atof( argv[ argc - 4 ] );
 -      }
  
 -      uniform = ( ( scale[0] == scale[1] ) && ( scale[1] == scale[2] ) );
 +char *Q_strcat( char *dst, size_t dlen, const char *src ) {
 +      size_t n = strlen( dst );
  
 -      if ( scale[0] == 0.0f || scale[1] == 0.0f || scale[2] == 0.0f ) {
 -              Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref <value>] <value> <mapname>\n" );
 -              Sys_Printf( "Non-zero scale value required.\n" );
 -              return 0;
 +      if ( n > dlen ) {
 +              abort(); /* buffer overflow */
        }
  
 -      /* do some path mangling */
 -      strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
 -      StripExtension( source );
 -      DefaultExtension( source, ".bsp" );
 -
 -      /* load the bsp */
 -      Sys_Printf( "Loading %s\n", source );
 -      LoadBSPFile( source );
 -      ParseEntities();
 -
 -      /* note it */
 -      Sys_Printf( "--- ScaleBSP ---\n" );
 -      Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities );
 -
 -      /* scale entity keys */
 -      for ( i = 0; i < numBSPEntities && i < numEntities; i++ )
 -      {
 -              /* scale origin */
 -              GetVectorForKey( &entities[ i ], "origin", vec );
 -              if ( ( vec[ 0 ] || vec[ 1 ] || vec[ 2 ] ) ) {
 -                      if ( !strncmp( ValueForKey( &entities[i], "classname" ), "info_player_", 12 ) ) {
 -                              vec[2] += spawn_ref;
 -                      }
 -                      vec[0] *= scale[0];
 -                      vec[1] *= scale[1];
 -                      vec[2] *= scale[2];
 -                      if ( !strncmp( ValueForKey( &entities[i], "classname" ), "info_player_", 12 ) ) {
 -                              vec[2] -= spawn_ref;
 -                      }
 -                      sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
 -                      SetKeyValue( &entities[ i ], "origin", str );
 -              }
 -
 -              a = FloatForKey( &entities[ i ], "angle" );
 -              if ( a == -1 || a == -2 ) { // z scale
 -                      axis = 2;
 -              }
 -              else if ( fabs( sin( DEG2RAD( a ) ) ) < 0.707 ) {
 -                      axis = 0;
 -              }
 -              else{
 -                      axis = 1;
 -              }
 -
 -              /* scale door lip */
 -              f = FloatForKey( &entities[ i ], "lip" );
 -              if ( f ) {
 -                      f *= scale[axis];
 -                      sprintf( str, "%f", f );
 -                      SetKeyValue( &entities[ i ], "lip", str );
 -              }
 -
 -              /* scale plat height */
 -              f = FloatForKey( &entities[ i ], "height" );
 -              if ( f ) {
 -                      f *= scale[2];
 -                      sprintf( str, "%f", f );
 -                      SetKeyValue( &entities[ i ], "height", str );
 -              }
 -
 -              // TODO maybe allow a definition file for entities to specify which values are scaled how?
 -      }
 +      return Q_strncpyz( dst + n, src, dlen - n );
 +}
  
 -      /* scale models */
 -      for ( i = 0; i < numBSPModels; i++ )
 -      {
 -              bspModels[ i ].mins[0] *= scale[0];
 -              bspModels[ i ].mins[1] *= scale[1];
 -              bspModels[ i ].mins[2] *= scale[2];
 -              bspModels[ i ].maxs[0] *= scale[0];
 -              bspModels[ i ].maxs[1] *= scale[1];
 -              bspModels[ i ].maxs[2] *= scale[2];
 -      }
  
 -      /* scale nodes */
 -      for ( i = 0; i < numBSPNodes; i++ )
 -      {
 -              bspNodes[ i ].mins[0] *= scale[0];
 -              bspNodes[ i ].mins[1] *= scale[1];
 -              bspNodes[ i ].mins[2] *= scale[2];
 -              bspNodes[ i ].maxs[0] *= scale[0];
 -              bspNodes[ i ].maxs[1] *= scale[1];
 -              bspNodes[ i ].maxs[2] *= scale[2];
 -      }
 +char *Q_strncat( char *dst, size_t dlen, const char *src, size_t slen ) {
 +      size_t n = strlen( dst );
  
 -      /* scale leafs */
 -      for ( i = 0; i < numBSPLeafs; i++ )
 -      {
 -              bspLeafs[ i ].mins[0] *= scale[0];
 -              bspLeafs[ i ].mins[1] *= scale[1];
 -              bspLeafs[ i ].mins[2] *= scale[2];
 -              bspLeafs[ i ].maxs[0] *= scale[0];
 -              bspLeafs[ i ].maxs[1] *= scale[1];
 -              bspLeafs[ i ].maxs[2] *= scale[2];
 -      }
 -
 -      if ( texscale ) {
 -              Sys_Printf( "Using texture unlocking (and probably breaking texture alignment a lot)\n" );
 -              old_xyzst = safe_malloc( sizeof( *old_xyzst ) * numBSPDrawVerts * 5 );
 -              for ( i = 0; i < numBSPDrawVerts; i++ )
 -              {
 -                      old_xyzst[5 * i + 0] = bspDrawVerts[i].xyz[0];
 -                      old_xyzst[5 * i + 1] = bspDrawVerts[i].xyz[1];
 -                      old_xyzst[5 * i + 2] = bspDrawVerts[i].xyz[2];
 -                      old_xyzst[5 * i + 3] = bspDrawVerts[i].st[0];
 -                      old_xyzst[5 * i + 4] = bspDrawVerts[i].st[1];
 -              }
 +      if ( n > dlen ) {
 +              abort(); /* buffer overflow */
        }
  
 -      /* scale drawverts */
 -      for ( i = 0; i < numBSPDrawVerts; i++ )
 -      {
 -              bspDrawVerts[i].xyz[0] *= scale[0];
 -              bspDrawVerts[i].xyz[1] *= scale[1];
 -              bspDrawVerts[i].xyz[2] *= scale[2];
 -              bspDrawVerts[i].normal[0] /= scale[0];
 -              bspDrawVerts[i].normal[1] /= scale[1];
 -              bspDrawVerts[i].normal[2] /= scale[2];
 -              VectorNormalize( bspDrawVerts[i].normal, bspDrawVerts[i].normal );
 -      }
 +      return Q_strncpyz( dst + n, src, MIN( slen, dlen - n ) );
 +}
  
 -      if ( texscale ) {
 -              for ( i = 0; i < numBSPDrawSurfaces; i++ )
 -              {
 -                      switch ( bspDrawSurfaces[i].surfaceType )
 -                      {
 -                      case SURFACE_FACE:
 -                      case SURFACE_META:
 -                              if ( bspDrawSurfaces[i].numIndexes % 3 ) {
 -                                      Error( "Not a triangulation!" );
 -                              }
 -                              for ( j = bspDrawSurfaces[i].firstIndex; j < bspDrawSurfaces[i].firstIndex + bspDrawSurfaces[i].numIndexes; j += 3 )
 -                              {
 -                                      int ia = bspDrawIndexes[j] + bspDrawSurfaces[i].firstVert, ib = bspDrawIndexes[j + 1] + bspDrawSurfaces[i].firstVert, ic = bspDrawIndexes[j + 2] + bspDrawSurfaces[i].firstVert;
 -                                      bspDrawVert_t *a = &bspDrawVerts[ia], *b = &bspDrawVerts[ib], *c = &bspDrawVerts[ic];
 -                                      float *oa = &old_xyzst[ia * 5], *ob = &old_xyzst[ib * 5], *oc = &old_xyzst[ic * 5];
 -                                      // extrapolate:
 -                                      //   a->xyz -> oa
 -                                      //   b->xyz -> ob
 -                                      //   c->xyz -> oc
 -                                      ExtrapolateTexcoords(
 -                                              &oa[0], &oa[3],
 -                                              &ob[0], &ob[3],
 -                                              &oc[0], &oc[3],
 -                                              a->xyz, a->st,
 -                                              b->xyz, b->st,
 -                                              c->xyz, c->st );
 -                              }
 -                              break;
 -                      }
 -              }
 -      }
  
 -      /* scale planes */
 -      if ( uniform ) {
 -              for ( i = 0; i < numBSPPlanes; i++ )
 -              {
 -                      bspPlanes[ i ].dist *= scale[0];
 -              }
 -      }
 -      else
 -      {
 -              for ( i = 0; i < numBSPPlanes; i++ )
 -              {
 -                      bspPlanes[ i ].normal[0] /= scale[0];
 -                      bspPlanes[ i ].normal[1] /= scale[1];
 -                      bspPlanes[ i ].normal[2] /= scale[2];
 -                      f = 1 / VectorLength( bspPlanes[i].normal );
 -                      VectorScale( bspPlanes[i].normal, f, bspPlanes[i].normal );
 -                      bspPlanes[ i ].dist *= f;
 -              }
 -      }
 +/*
 +   ExitQ3Map()
 +   cleanup routine
 + */
  
 -      /* scale gridsize */
 -      GetVectorForKey( &entities[ 0 ], "gridsize", vec );
 -      if ( ( vec[ 0 ] + vec[ 1 ] + vec[ 2 ] ) == 0.0f ) {
 -              VectorCopy( gridSize, vec );
 +static void ExitQ3Map( void ){
 +      BSPFilesCleanup();
 +      if ( mapDrawSurfs != NULL ) {
 +              free( mapDrawSurfs );
        }
 -      vec[0] *= scale[0];
 -      vec[1] *= scale[1];
 -      vec[2] *= scale[2];
 -      sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
 -      SetKeyValue( &entities[ 0 ], "gridsize", str );
 -
 -      /* inject command line parameters */
 -      InjectCommandLine( argv, 0, argc - 1 );
 -
 -      /* write the bsp */
 -      UnparseEntities();
 -      StripExtension( source );
 -      DefaultExtension( source, "_s.bsp" );
 -      Sys_Printf( "Writing %s\n", source );
 -      WriteBSPFile( source );
 -
 -      /* return to sender */
 -      return 0;
  }
  
  
@@@ -156,13 -1532,13 +156,13 @@@ int ShiftBSPMain( int argc, char **arg
                /* shift origin */
                GetVectorForKey( &entities[ i ], "origin", vec );
                if ( ( vec[ 0 ] || vec[ 1 ] || vec[ 2 ] ) ) {
 -                      if ( !strncmp( ValueForKey( &entities[i], "classname" ), "info_player_", 12 ) ) {
 +                      if ( !!strncmp( ValueForKey( &entities[i], "classname" ), "info_player_", 12 ) ) {
                                vec[2] += spawn_ref;
                        }
                        vec[0] += scale[0];
                        vec[1] += scale[1];
                        vec[2] += scale[2];
 -                      if ( !strncmp( ValueForKey( &entities[i], "classname" ), "info_player_", 12 ) ) {
 +                      if ( !!strncmp( ValueForKey( &entities[i], "classname" ), "info_player_", 12 ) ) {
                                vec[2] -= spawn_ref;
                        }
                        sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
@@@ -1007,8 -2383,14 +1007,14 @@@ skipEXfile
                                Sys_Printf( "++%s\n", temp );
                                continue;
                        }
-                       Sys_Printf( "  !FAIL! %s\n", pk3Shaders + i*65 );
-                       if ( i != pk3ShadersN - 1 ) packFAIL = qtrue; //levelshot typically
+                       if ( i == pk3ShadersN - 1 ){ //levelshot typically
+                               Sys_Printf( "  ~fail  %s\n", pk3Shaders + i*65 );
+                       }
+                       else{
+                               Sys_Printf( "  !FAIL! %s\n", pk3Shaders + i*65 );
+                               packFAIL = qtrue;
+                       }
                }
        }
  
                        Sys_Printf( "++%s\n", temp );
                }
        else{
-               Sys_Printf( "  !FAIL! %s\n", temp );
+               Sys_Printf( "  ~fail  %s\n", temp );
        }
  
        sprintf( temp, "scripts/%s.arena", nameOFmap );
                        Sys_Printf( "++%s\n", temp );
                }
        else{
-               Sys_Printf( "  !FAIL! %s\n", temp );
+               Sys_Printf( "  ~fail  %s\n", temp );
        }
  
        sprintf( temp, "scripts/%s.defi", nameOFmap );
                        Sys_Printf( "++%s\n", temp );
                }
        else{
-               Sys_Printf( "  !FAIL! %s\n", temp );
+               Sys_Printf( "  ~fail  %s\n", temp );
        }
  
        if ( !packFAIL ){
@@@ -2068,6 -3450,246 +2074,6 @@@ skipEXrefile
  
  
  
 -/*
 -   PseudoCompileBSP()
 -   a stripped down ProcessModels
 - */
 -void PseudoCompileBSP( qboolean need_tree ){
 -      int models;
 -      char modelValue[10];
 -      entity_t *entity;
 -      face_t *faces;
 -      tree_t *tree;
 -      node_t *node;
 -      brush_t *brush;
 -      side_t *side;
 -      int i;
 -
 -      SetDrawSurfacesBuffer();
 -      mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
 -      memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
 -      numMapDrawSurfs = 0;
 -
 -      BeginBSPFile();
 -      models = 1;
 -      for ( mapEntityNum = 0; mapEntityNum < numEntities; mapEntityNum++ )
 -      {
 -              /* get entity */
 -              entity = &entities[ mapEntityNum ];
 -              if ( entity->brushes == NULL && entity->patches == NULL ) {
 -                      continue;
 -              }
 -
 -              if ( mapEntityNum != 0 ) {
 -                      sprintf( modelValue, "*%d", models++ );
 -                      SetKeyValue( entity, "model", modelValue );
 -              }
 -
 -              /* process the model */
 -              Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", numBSPModels );
 -              BeginModel();
 -
 -              entity->firstDrawSurf = numMapDrawSurfs;
 -
 -              ClearMetaTriangles();
 -              PatchMapDrawSurfs( entity );
 -
 -              if ( mapEntityNum == 0 && need_tree ) {
 -                      faces = MakeStructuralBSPFaceList( entities[0].brushes );
 -                      tree = FaceBSP( faces );
 -                      node = tree->headnode;
 -              }
 -              else
 -              {
 -                      node = AllocNode();
 -                      node->planenum = PLANENUM_LEAF;
 -                      tree = AllocTree();
 -                      tree->headnode = node;
 -              }
 -
 -              /* a minimized ClipSidesIntoTree */
 -              for ( brush = entity->brushes; brush; brush = brush->next )
 -              {
 -                      /* walk the brush sides */
 -                      for ( i = 0; i < brush->numsides; i++ )
 -                      {
 -                              /* get side */
 -                              side = &brush->sides[ i ];
 -                              if ( side->winding == NULL ) {
 -                                      continue;
 -                              }
 -                              /* shader? */
 -                              if ( side->shaderInfo == NULL ) {
 -                                      continue;
 -                              }
 -                              /* save this winding as a visible surface */
 -                              DrawSurfaceForSide( entity, brush, side, side->winding );
 -                      }
 -              }
 -
 -              if ( meta ) {
 -                      ClassifyEntitySurfaces( entity );
 -                      MakeEntityDecals( entity );
 -                      MakeEntityMetaTriangles( entity );
 -                      SmoothMetaTriangles();
 -                      MergeMetaTriangles();
 -              }
 -              FilterDrawsurfsIntoTree( entity, tree );
 -
 -              FilterStructuralBrushesIntoTree( entity, tree );
 -              FilterDetailBrushesIntoTree( entity, tree );
 -
 -              EmitBrushes( entity->brushes, &entity->firstBrush, &entity->numBrushes );
 -              EndModel( entity, node );
 -      }
 -      EndBSPFile( qfalse );
 -}
 -
 -/*
 -   ConvertBSPMain()
 -   main argument processing function for bsp conversion
 - */
 -
 -int ConvertBSPMain( int argc, char **argv ){
 -      int i;
 -      int ( *convertFunc )( char * );
 -      game_t  *convertGame;
 -      char ext[1024];
 -      qboolean map_allowed, force_bsp, force_map;
 -
 -
 -      /* set default */
 -      convertFunc = ConvertBSPToASE;
 -      convertGame = NULL;
 -      map_allowed = qfalse;
 -      force_bsp = qfalse;
 -      force_map = qfalse;
 -
 -      /* arg checking */
 -      if ( argc < 1 ) {
 -              Sys_Printf( "Usage: q3map -convert [-format <ase|obj|map_bp|map>] [-shadersasbitmap|-lightmapsastexcoord|-deluxemapsastexcoord] [-readbsp|-readmap [-meta|-patchmeta]] [-v] <mapname>\n" );
 -              return 0;
 -      }
 -
 -      /* process arguments */
 -      for ( i = 1; i < ( argc - 1 ); i++ )
 -      {
 -              /* -format map|ase|... */
 -              if ( !strcmp( argv[ i ],  "-format" ) ) {
 -                      i++;
 -                      if ( !Q_stricmp( argv[ i ], "ase" ) ) {
 -                              convertFunc = ConvertBSPToASE;
 -                              map_allowed = qfalse;
 -                      }
 -                      else if ( !Q_stricmp( argv[ i ], "obj" ) ) {
 -                              convertFunc = ConvertBSPToOBJ;
 -                              map_allowed = qfalse;
 -                      }
 -                      else if ( !Q_stricmp( argv[ i ], "map_bp" ) ) {
 -                              convertFunc = ConvertBSPToMap_BP;
 -                              map_allowed = qtrue;
 -                      }
 -                      else if ( !Q_stricmp( argv[ i ], "map" ) ) {
 -                              convertFunc = ConvertBSPToMap;
 -                              map_allowed = qtrue;
 -                      }
 -                      else
 -                      {
 -                              convertGame = GetGame( argv[ i ] );
 -                              map_allowed = qfalse;
 -                              if ( convertGame == NULL ) {
 -                                      Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] );
 -                              }
 -                      }
 -              }
 -              else if ( !strcmp( argv[ i ],  "-ne" ) ) {
 -                      normalEpsilon = atof( argv[ i + 1 ] );
 -                      i++;
 -                      Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-de" ) ) {
 -                      distanceEpsilon = atof( argv[ i + 1 ] );
 -                      i++;
 -                      Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon );
 -              }
 -              else if ( !strcmp( argv[ i ],  "-shaderasbitmap" ) || !strcmp( argv[ i ],  "-shadersasbitmap" ) ) {
 -                      shadersAsBitmap = qtrue;
 -              }
 -              else if ( !strcmp( argv[ i ],  "-lightmapastexcoord" ) || !strcmp( argv[ i ],  "-lightmapsastexcoord" ) ) {
 -                      lightmapsAsTexcoord = qtrue;
 -              }
 -              else if ( !strcmp( argv[ i ],  "-deluxemapastexcoord" ) || !strcmp( argv[ i ],  "-deluxemapsastexcoord" ) ) {
 -                      lightmapsAsTexcoord = qtrue;
 -                      deluxemap = qtrue;
 -              }
 -              else if ( !strcmp( argv[ i ],  "-readbsp" ) ) {
 -                      force_bsp = qtrue;
 -              }
 -              else if ( !strcmp( argv[ i ],  "-readmap" ) ) {
 -                      force_map = qtrue;
 -              }
 -              else if ( !strcmp( argv[ i ],  "-meta" ) ) {
 -                      meta = qtrue;
 -              }
 -              else if ( !strcmp( argv[ i ],  "-patchmeta" ) ) {
 -                      meta = qtrue;
 -                      patchMeta = qtrue;
 -              }
 -              else if ( !strcmp( argv[ i ],  "-fast" ) ) {
 -                      fast = qtrue;
 -              }
 -      }
 -
 -      LoadShaderInfo();
 -
 -      /* clean up map name */
 -      strcpy( source, ExpandArg( argv[i] ) );
 -      ExtractFileExtension( source, ext );
 -
 -      if ( !map_allowed && !force_map ) {
 -              force_bsp = qtrue;
 -      }
 -
 -      if ( force_map || ( !force_bsp && !Q_stricmp( ext, "map" ) && map_allowed ) ) {
 -              if ( !map_allowed ) {
 -                      Sys_Printf( "WARNING: the requested conversion should not be done from .map files. Compile a .bsp first.\n" );
 -              }
 -              StripExtension( source );
 -              DefaultExtension( source, ".map" );
 -              Sys_Printf( "Loading %s\n", source );
 -              LoadMapFile( source, qfalse, convertGame == NULL );
 -              PseudoCompileBSP( convertGame != NULL );
 -      }
 -      else
 -      {
 -              StripExtension( source );
 -              DefaultExtension( source, ".bsp" );
 -              Sys_Printf( "Loading %s\n", source );
 -              LoadBSPFile( source );
 -              ParseEntities();
 -      }
 -
 -      /* bsp format convert? */
 -      if ( convertGame != NULL ) {
 -              /* set global game */
 -              game = convertGame;
 -
 -              /* write bsp */
 -              StripExtension( source );
 -              DefaultExtension( source, "_c.bsp" );
 -              Sys_Printf( "Writing %s\n", source );
 -              WriteBSPFile( source );
 -
 -              /* return to sender */
 -              return 0;
 -      }
 -
 -      /* normal convert */
 -      return convertFunc( source );
 -}
 -
 -
 -
  /*
     main()
     q3map mojo...
  int main( int argc, char **argv ){
        int i, r;
        double start, end;
 +      extern qboolean werror;
  
  
        /* we want consistent 'randomness' */
        /* read general options first */
        for ( i = 1; i < argc; i++ )
        {
 +              /* -help */
 +              if ( !strcmp( argv[ i ], "-h" ) || !strcmp( argv[ i ], "--help" )
 +                      || !strcmp( argv[ i ], "-help" ) ) {
 +                      HelpMain(argv[i+1]);
 +                      return 0;
 +              }
 +
                /* -connect */
                if ( !strcmp( argv[ i ], "-connect" ) ) {
                        argv[ i ] = NULL;
                        argv[ i ] = NULL;
                }
  
 +              /* make all warnings into errors */
 +              else if ( !strcmp( argv[ i ], "-werror" ) ) {
 +                      werror = qtrue;
 +                      argv[ i ] = NULL;
 +              }
 +
                /* patch subdivisions */
                else if ( !strcmp( argv[ i ], "-subdivisions" ) ) {
                        argv[ i ] = NULL;
  
        /* fixaas */
        if ( !strcmp( argv[ 1 ], "-fixaas" ) ) {
 -              r = FixAAS( argc - 1, argv + 1 );
 +              r = FixAASMain( argc - 1, argv + 1 );
        }
  
        /* analyze */
        else if ( !strcmp( argv[ 1 ], "-analyze" ) ) {
 -              r = AnalyzeBSP( argc - 1, argv + 1 );
 +              r = AnalyzeBSPMain( argc - 1, argv + 1 );
        }
  
        /* info */
        else if ( !strcmp( argv[ 1 ], "-info" ) ) {
 -              r = BSPInfo( argc - 2, argv + 2 );
 +              r = BSPInfoMain( argc - 2, argv + 2 );
        }
  
        /* vis */
  
        /* vlight */
        else if ( !strcmp( argv[ 1 ], "-vlight" ) ) {
 -              Sys_Printf( "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" );
 +              Sys_FPrintf( SYS_WRN, "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" );
                argv[ 1 ] = "-fast";    /* eek a hack */
                r = LightMain( argc, argv );
        }
  
 +      /* QBall: export entities */
 +      else if ( !strcmp( argv[ 1 ], "-exportents" ) ) {
 +              r = ExportEntitiesMain( argc - 1, argv + 1 );
 +      }
 +
        /* ydnar: lightmap export */
        else if ( !strcmp( argv[ 1 ], "-export" ) ) {
                r = ExportLightmapsMain( argc - 1, argv + 1 );
index ff97ba02eb6a6d59cbdc8f9b6d1ab5d6edb003ed,0629d442b8af8231eb40388c9bb089dae838b477..f6296f1b72aae3412f8dcd4c90c175d1503195a8
@@@ -32,7 -32,7 +32,7 @@@
  #ifndef Q3MAP2_H
  #define Q3MAP2_H
  
 -
 +#include "globaldefs.h"
  
  /* version */
  #ifndef Q3MAP_VERSION
@@@ -50,7 -50,7 +50,7 @@@
     ------------------------------------------------------------------------------- */
  
  /* platform-specific */
 -#if defined( __linux__ ) || defined( __APPLE__ )
 +#if GDEF_OS_LINUX || GDEF_OS_MACOS
        #define Q_UNIX
  #endif
  
@@@ -60,7 -60,7 +60,7 @@@
        #include <limits.h>
  #endif
  
 -#ifdef WIN32
 +#if GDEF_OS_WINDOWS
        #include <windows.h>
  #endif
  
@@@ -72,9 -72,6 +72,9 @@@
  #include "mathlib.h"
  #include "md5lib.h"
  #include "ddslib.h"
 +#ifdef BUILD_CRUNCH
 +#include "crn_rgba.h"
 +#endif // BUILD_CRUNCH
  
  #include "picomodel.h"
  
     ------------------------------------------------------------------------------- */
  
  #define MAC_STATIC_HACK         0
 -#if defined( __APPLE__ ) && MAC_STATIC_HACK
 +#if GDEF_OS_MACOS && MAC_STATIC_HACK
        #define MAC_STATIC          static
  #else
        #define MAC_STATIC
  #endif
  
  #if 1
 -      #ifdef WIN32
 +      #if GDEF_OS_WINDOWS
                #define Q_stricmp           stricmp
                #define Q_strncasecmp       strnicmp
        #else
  
  /* ok to increase these at the expense of more memory */
  #define MAX_MAP_AREAS           0x100       /* MAX_MAP_AREA_BYTES in q_shared must match! */
 -#define       MAX_MAP_FOGS                    0x100                   //& 0x100       /* RBSP (32 - world fog - goggles) */
 +#define MAX_MAP_FOGS            30          //& 0x100 /* RBSP (32 - world fog - goggles) */
  #define MAX_MAP_LEAFS           0x20000
  #define MAX_MAP_PORTALS         0x20000
  #define MAX_MAP_LIGHTING        0x800000
  #define MAX_MAP_VISCLUSTERS     0x4000 // <= MAX_MAP_LEAFS
  #define MAX_MAP_VISIBILITY      ( VIS_HEADER_SIZE + MAX_MAP_VISCLUSTERS * ( ( ( MAX_MAP_VISCLUSTERS + 63 ) & ~63 ) >> 3 ) )
  
 -#define       MAX_MAP_DRAW_SURFS              0x20000
 +#define MAX_MAP_DRAW_SURFS      0x20000
  
  #define MAX_MAP_ADVERTISEMENTS  30
  
@@@ -962,9 -959,8 +962,9 @@@ typedef struct parseMesh_
        shaderInfo_t        *shaderInfo;
        shaderInfo_t        *celShader;             /* :) */
  
 +      /* jal : entity based _lightmapsamplesize */
 +      int lightmapSampleSize;
        /* ydnar: gs mods */
 -      int lightmapSampleSize;                     /* jal : entity based _lightmapsamplesize */
        float lightmapScale;
        vec3_t eMins, eMaxs;
        indexMap_t          *im;
@@@ -1520,51 -1516,33 +1520,51 @@@ vec_t                       Random( voi
  char                        *Q_strncpyz( char *dst, const char *src, size_t len );
  char                        *Q_strcat( char *dst, size_t dlen, const char *src );
  char                        *Q_strncat( char *dst, size_t dlen, const char *src, size_t slen );
 -int                         BSPInfo( int count, char **fileNames );
 -int                         ScaleBSPMain( int argc, char **argv );
  int                         ShiftBSPMain( int argc, char **argv );
 -int                         ConvertMain( int argc, char **argv );
  
 +/* help.c */
 +void                        HelpMain(const char* arg);
  
  /* path_init.c */
  game_t                      *GetGame( char *arg );
  void                        InitPaths( int *argc, char **argv );
  
  
 +/* fixaas.c */
 +int                         FixAASMain( int argc, char **argv );
 +
 +
  /* bsp.c */
  int                         BSPMain( int argc, char **argv );
  
  
 +/* bsp_analyze.c */
 +int                         AnalyzeBSPMain( int argc, char **argv );
 +
 +
 +/* bsp_info.c */
 +int                         BSPInfoMain( int count, char **fileNames );
 +
 +/* bsp_scale.c */
 +int                         ScaleBSPMain( int argc, char **argv );
 +
 +/* minimap.c */
 +int                         MiniMapBSPMain( int argc, char **argv );
 +
 +/* convert_bsp.c */
 +int                         ConvertBSPMain( int argc, char **argv );
 +
 +
  /* convert_map.c */
  int                         ConvertBSPToMap( char *bspName );
  int                         ConvertBSPToMap_BP( char *bspName );
  
 -
  /* convert_ase.c */
  int                         ConvertBSPToASE( char *bspName );
  
  /* convert_obj.c */
  int                         ConvertBSPToOBJ( char *bspName );
  
 -
  /* brush.c */
  sideRef_t                   *AllocSideRef( side_t *side, sideRef_t *next );
  int                         CountBrushList( brush_t *brushes );
@@@ -1638,12 -1616,12 +1638,12 @@@ void                        MakeTreePor
  
  
  /* leakfile.c */
 -xmlNodePtr                  LeakFile( tree_t *tree );
 +xmlNodePtr                  LeakFile( tree_t *tree, const char *lineFilePath );
  
  
  /* prtfile.c */
  void                        NumberClusters( tree_t *tree );
 -void                        WritePortalFile( tree_t *tree );
 +void                        WritePortalFile( tree_t *tree, const char *portalFilePath );
  
  
  /* writebsp.c */
@@@ -1653,7 -1631,7 +1653,7 @@@ void                        SetLightSty
  int                         EmitShader( const char *shader, int *contentFlags, int *surfaceFlags );
  
  void                        BeginBSPFile( void );
 -void                        EndBSPFile( qboolean do_write );
 +void                        EndBSPFile( qboolean do_write, const char *BSPFilePath, const char *surfaceFilePath );
  void                        EmitBrushes( brush_t *brushes, int *firstBrush, int *numBrushes );
  void                        EmitFogs( void );
  
@@@ -1765,8 -1743,8 +1765,8 @@@ int                         GetSurfaceE
  float                       GetSurfaceExtraLongestCurve( int num );
  void                        GetSurfaceExtraLightmapAxis( int num, vec3_t lightmapAxis );
  
 -void                        WriteSurfaceExtraFile( const char *path );
 -void                        LoadSurfaceExtraFile( const char *path );
 +void                        WriteSurfaceExtraFile( const char *surfaceFilePath );
 +void                        LoadSurfaceExtraFile( const char *surfaceFilePath );
  
  
  /* decals.c */
@@@ -1837,7 -1815,7 +1837,7 @@@ void                        FloodLightR
  void                        IlluminateRawLightmap( int num );
  void                        IlluminateVertexes( int num );
  
 -void                        SetupBrushesFlags( int mask_any, int test_any, int mask_all, int test_all );
 +void                        SetupBrushesFlags( unsigned int mask_any, unsigned int test_any, unsigned int mask_all, unsigned int test_all );
  void                        SetupBrushes( void );
  void                        SetupClusters( void );
  qboolean                    ClusterVisible( int a, int b );
@@@ -1860,12 -1838,7 +1860,12 @@@ int                         ImportLight
  
  void                        SetupSurfaceLightmaps( void );
  void                        StitchSurfaceLightmaps( void );
 -void                        StoreSurfaceLightmaps( void );
 +void                        StoreSurfaceLightmaps( qboolean fastAllocate );
 +
 +
 +/* exportents.c */
 +void                        ExportEntities( void );
 +int                         ExportEntitiesMain( int argc, char **argv );
  
  
  /* image.c */
@@@ -1926,7 -1899,7 +1926,7 @@@ qboolean                    KeyExists( 
  const char                  *ValueForKey( const entity_t *ent, const char *key );
  int                         IntForKey( const entity_t *ent, const char *key );
  vec_t                       FloatForKey( const entity_t *ent, const char *key );
 -void                        GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec );
 +qboolean                    GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec );
  entity_t                    *FindTargetEntity( const char *target );
  void                        GetEntityShadowFlags( const entity_t *ent, const entity_t *ent2, int *castShadows, int *recvShadows );
  void InjectCommandLine( char **argv, int beginArgs, int endArgs );
@@@ -1969,21 -1942,19 +1969,21 @@@ Q_EXTERN game_t games[
        {
                                                                #include "game_quake3.h"
        ,
 -                                                              #include "game_quakelive.h" /* most be after game_quake3.h as they share defines! */
 +                                                              #include "game_quakelive.h" /* must be after game_quake3.h as they share defines! */
        ,
 -                                                              #include "game_nexuiz.h" /* most be after game_quake3.h as they share defines! */
 +                                                              #include "game_nexuiz.h" /* must be after game_quake3.h as they share defines! */
        ,
 -                                                              #include "game_xonotic.h" /* most be after game_quake3.h as they share defines! */
 +                                                              #include "game_xonotic.h" /* must be after game_quake3.h as they share defines! */
        ,
                                                                #include "game_tremulous.h" /*LinuxManMikeC: must be after game_quake3.h, depends on #define's set in it */
 +      ,
 +                                                              #include "game_unvanquished.h" /* must be after game_tremulous.h as they share defines! */
        ,
                                                                #include "game_tenebrae.h"
        ,
                                                                #include "game_wolf.h"
        ,
 -                                                              #include "game_wolfet.h" /* most be after game_wolf.h as they share defines! */
 +                                                              #include "game_wolfet.h" /* must be after game_wolf.h as they share defines! */
        ,
                                                                #include "game_etut.h"
        ,
        ,
                                                                #include "game_sof2.h"
        ,
 -                                                              #include "game_jk2.h"   /* most be after game_sof2.h as they share defines! */
 +                                                              #include "game_jk2.h"   /* must be after game_sof2.h as they share defines! */
        ,
 -                                                              #include "game_ja.h"    /* most be after game_jk2.h as they share defines! */
 +                                                              #include "game_ja.h"    /* must be after game_jk2.h as they share defines! */
        ,
                                                                #include "game_qfusion.h"   /* qfusion game */
        ,
@@@ -2032,11 -2003,10 +2032,10 @@@ Q_EXTERN qboolean warnImage Q_ASSIGN( q
  /* ydnar: sinusoid samples */
  Q_EXTERN float jitters[ MAX_JITTERS ];
  
- /*can't code*/
+ /* can't code */
  Q_EXTERN qboolean doingBSP Q_ASSIGN( qfalse );
  
  /* commandline arguments */
- Q_EXTERN qboolean nocmdline Q_ASSIGN( qfalse );
  Q_EXTERN qboolean verbose;
  Q_EXTERN qboolean verboseEntities Q_ASSIGN( qfalse );
  Q_EXTERN qboolean force Q_ASSIGN( qfalse );
@@@ -2059,6 -2029,7 +2058,7 @@@ Q_EXTERN qboolean skyFixHack Q_ASSIGN( 
  Q_EXTERN qboolean bspAlternateSplitWeights Q_ASSIGN( qfalse );                      /* 27 */
  Q_EXTERN qboolean deepBSP Q_ASSIGN( qfalse );                   /* div0 */
  Q_EXTERN qboolean maxAreaFaceSurface Q_ASSIGN( qfalse );                    /* divVerent */
+ Q_EXTERN qboolean nocmdline Q_ASSIGN( qfalse );
  
  Q_EXTERN int patchSubdivisions Q_ASSIGN( 8 );                       /* ydnar: -patchmeta subdivisions */
  
@@@ -2261,7 -2232,7 +2261,7 @@@ Q_EXTERN qboolean keepLights Q_ASSIGN( 
  
  Q_EXTERN int sampleSize Q_ASSIGN( DEFAULT_LIGHTMAP_SAMPLE_SIZE );
  Q_EXTERN int minSampleSize Q_ASSIGN( DEFAULT_LIGHTMAP_MIN_SAMPLE_SIZE );
 -Q_EXTERN float noVertexLighting Q_ASSIGN( 0.0f );
 +Q_EXTERN qboolean noVertexLighting Q_ASSIGN( qfalse );
  Q_EXTERN qboolean nolm Q_ASSIGN( qfalse );
  Q_EXTERN qboolean noGridLighting Q_ASSIGN( qfalse );
  
index 0f8b56b47834a08321a46ee1db280433a934179f,3d5249ef1f41f9c305acc20dddf79af8096152b1..5a015f42f631758bfcf4b257807cf31b6cdb06ae
@@@ -383,7 -383,7 +383,7 @@@ void WriteMapShaderFile( void )
        /* open shader file */
        file = fopen( mapShaderFile, "w" );
        if ( file == NULL ) {
 -              Sys_Printf( "WARNING: Unable to open map shader file %s for writing\n", mapShaderFile );
 +              Sys_FPrintf( SYS_WRN, "WARNING: Unable to open map shader file %s for writing\n", mapShaderFile );
                return;
        }
  
@@@ -776,7 -776,7 +776,7 @@@ static void LoadShaderImages( shaderInf
                if ( si->shaderImage == NULL ) {
                        si->shaderImage = ImageLoad( DEFAULT_IMAGE );
                        if ( warnImage && strcmp( si->shader, "noshader" ) ) {
 -                              Sys_Printf( "WARNING: Couldn't find image for shader %s\n", si->shader );
 +                              Sys_FPrintf( SYS_WRN, "WARNING: Couldn't find image for shader %s\n", si->shader );
                        }
                }
  
@@@ -844,7 -844,7 +844,7 @@@ shaderInfo_t *ShaderInfoForShader( cons
  
        /* dummy check */
        if ( shaderName == NULL || shaderName[ 0 ] == '\0' ) {
 -              Sys_Printf( "WARNING: Null or empty shader name\n" );
 +              Sys_FPrintf( SYS_WRN, "WARNING: Null or empty shader name\n" );
                shaderName = "missing";
        }
  
                                /* increase deprecation depth */
                                deprecationDepth++;
                                if ( deprecationDepth == MAX_SHADER_DEPRECATION_DEPTH ) {
 -                                      Sys_Printf( "WARNING: Max deprecation depth of %i is reached on shader '%s'\n", MAX_SHADER_DEPRECATION_DEPTH, shader );
 +                                      Sys_FPrintf( SYS_WRN, "WARNING: Max deprecation depth of %i is reached on shader '%s'\n", MAX_SHADER_DEPRECATION_DEPTH, shader );
                                }
                                /* search again from beginning */
                                i = -1;
@@@ -1092,7 -1092,7 +1092,7 @@@ static void ParseShaderFile( const cha
                        else if ( !Q_stricmp( token, "surfaceparm" ) ) {
                                GetTokenAppend( shaderText, qfalse );
                                if ( ApplySurfaceParm( token, &si->contentFlags, &si->surfaceFlags, &si->compileFlags ) == qfalse ) {
 -                                      Sys_Printf( "WARNING: Unknown surfaceparm: \"%s\"\n", token );
 +                                      Sys_FPrintf( SYS_WRN, "WARNING: Unknown surfaceparm: \"%s\"\n", token );
                                }
                        }
  
                        else if ( !Q_stricmp( token, "sun" ) /* sof2 */ || !Q_stricmp( token, "q3map_sun" ) || !Q_stricmp( token, "q3map_sunExt" ) ) {
                                float a, b;
                                sun_t       *sun;
-                               qboolean ext;
+                               qboolean ext = qfalse;
  
  
                                /* ydnar: extended sun directive? */
                                        }
                                        else
                                        {
 -                                              Sys_Printf( "WARNING: Unknown value for lightmap axis: %s\n", token );
 +                                              Sys_FPrintf( SYS_WRN, "WARNING: Unknown value for lightmap axis: %s\n", token );
                                                VectorClear( si->lightmapAxis );
                                        }
                                }
                                        /* must be a power of 2 */
                                        if ( ( ( si->lmCustomWidth - 1 ) & si->lmCustomWidth ) ||
                                                 ( ( si->lmCustomHeight - 1 ) & si->lmCustomHeight ) ) {
 -                                              Sys_Printf( "WARNING: Non power-of-two lightmap size specified (%d, %d)\n",
 +                                              Sys_FPrintf( SYS_WRN, "WARNING: Non power-of-two lightmap size specified (%d, %d)\n",
                                                                        si->lmCustomWidth, si->lmCustomHeight );
                                                si->lmCustomWidth = lmCustomSize;
                                                si->lmCustomHeight = lmCustomSize;
                                        }
                                        else
                                        {
 -                                              Sys_Printf( "WARNING: Unknown q3map_tcGen method: %s\n", token );
 +                                              Sys_FPrintf( SYS_WRN, "WARNING: Unknown q3map_tcGen method: %s\n", token );
                                                VectorClear( si->vecs[ 0 ] );
                                                VectorClear( si->vecs[ 1 ] );
                                        }
  
                                        /* unknown */
                                        else{
 -                                              Sys_Printf( "WARNING: Unknown colorMod method: %s\n", token );
 +                                              Sys_FPrintf( SYS_WRN, "WARNING: Unknown colorMod method: %s\n", token );
                                        }
                                }
  
                                                TCModRotate( si->mod, a );
                                        }
                                        else{
 -                                              Sys_Printf( "WARNING: Unknown q3map_tcMod method: %s\n", token );
 +                                              Sys_FPrintf( SYS_WRN, "WARNING: Unknown q3map_tcMod method: %s\n", token );
                                        }
                                }
  
                                        GetTokenAppend( shaderText, qfalse );
                                        sprintf( temp, "*mat_%s", token );
                                        if ( ApplySurfaceParm( temp, &si->contentFlags, &si->surfaceFlags, &si->compileFlags ) == qfalse ) {
 -                                              Sys_Printf( "WARNING: Unknown material \"%s\"\n", token );
 +                                              Sys_FPrintf( SYS_WRN, "WARNING: Unknown material \"%s\"\n", token );
                                        }
                                }
  
                                {
                                        Sys_FPrintf( SYS_VRB, "Attempting to match %s with a known surfaceparm\n", token );
                                        if ( ApplySurfaceParm( &token[ 6 ], &si->contentFlags, &si->surfaceFlags, &si->compileFlags ) == qfalse ) {
 -                                              Sys_Printf( "WARNING: Unknown q3map_* directive \"%s\"\n", token );
 +                                              Sys_FPrintf( SYS_WRN, "WARNING: Unknown q3map_* directive \"%s\"\n", token );
                                        }
                                }
  #endif
@@@ -2043,13 -2043,13 +2043,13 @@@ static void ParseCustomInfoParms( void 
                custSurfaceParms[ numCustSurfaceParms ].name = safe_malloc( MAX_OS_PATH );
                strcpy( custSurfaceParms[ numCustSurfaceParms ].name, token );
                GetToken( qfalse );
 -              sscanf( token, "%x", &custSurfaceParms[ numCustSurfaceParms ].contentFlags );
 +              sscanf( token, "%x", (unsigned int *) &custSurfaceParms[ numCustSurfaceParms ].contentFlags );
                numCustSurfaceParms++;
        }
  
        /* any content? */
        if ( !parsedContent ) {
 -              Sys_Printf( "WARNING: Couldn't find valid custom contentsflag section\n" );
 +              Sys_FPrintf( SYS_WRN, "WARNING: Couldn't find valid custom contentsflag section\n" );
                return;
        }
  
                custSurfaceParms[ numCustSurfaceParms ].name = safe_malloc( MAX_OS_PATH );
                strcpy( custSurfaceParms[ numCustSurfaceParms ].name, token );
                GetToken( qfalse );
 -              sscanf( token, "%x", &custSurfaceParms[ numCustSurfaceParms ].surfaceFlags );
 +              sscanf( token, "%x", (unsigned int *) &custSurfaceParms[ numCustSurfaceParms ].surfaceFlags );
                numCustSurfaceParms++;
        }
  
        /* any content? */
        if ( !parsedContent ) {
 -              Sys_Printf( "WARNING: Couldn't find valid custom surfaceflag section\n" );
 +              Sys_FPrintf( SYS_WRN, "WARNING: Couldn't find valid custom surfaceflag section\n" );
        }
  }