]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - src/main.cpp
+ paper, book, bookshelf
[dragonfireclient.git] / src / main.cpp
index 258119c4a233d5963b3a08f2d087502350e4e93f..f67d53475ad234fbc5105dc07a7bca343c471849 100644 (file)
@@ -1,6 +1,6 @@
 /*\r
 Minetest-c55\r
-Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>\r
+Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>\r
 \r
 This program is free software; you can redistribute it and/or modify\r
 it under the terms of the GNU General Public License as published by\r
@@ -19,194 +19,305 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 \r
 /*\r
 =============================== NOTES ==============================\r
+NOTE: Things starting with TODO are sometimes only suggestions.\r
 \r
-NOTE: VBO cannot be turned on for fast-changing stuff because there\r
-      is an apparanet memory leak in irrlicht when using it\r
-\r
-SUGGESTION: add a second lighting value to the MS nibble of param of\r
-       air to tell how bright the air node is when there is no sunlight.\r
-       When day changes to night, these two values can be interpolated.\r
-TODO: Fix address to be ipv6 compatible\r
-\r
-TODO: ESC Pause mode in which the cursor is not kept at the center of window.\r
-TODO: Stop player if focus of window is taken away (go to pause mode)\r
-TODO: Optimize and fix makeFastFace or whatever it's called\r
-      - Face calculation is the source of CPU usage on the client\r
-SUGGESTION: The client will calculate and send lighting changes and\r
-  the server will randomly check some of them and kick the client out\r
-  if it fails to calculate them right.\r
-  - Actually, it could just start ignoring them and calculate them\r
-    itself.\r
-SUGGESTION: Combine MapBlock's face caches to so big pieces that VBO\r
-            gets used\r
-            - That is >500 vertices\r
-\r
-TODO: Better dungeons\r
-TODO: There should be very slight natural caves also, starting from\r
-      only a straightened-up cliff\r
-\r
-TODO: Changing of block with mouse wheel or something\r
-TODO: Menus\r
-\r
-TODO: Mobs\r
-      - Server:\r
-        - One single map container with ids as keys\r
-      - Client:\r
-           - ?\r
-TODO: - Keep track of the place of the mob in the last few hundreth's\r
-        of a second - then, if a player hits it, take the value that is\r
-               avg_rtt/2 before the moment the packet is received.\r
-TODO: - Scripting\r
-\r
-SUGGESTION: Modify client to calculate single changes asynchronously\r
-\r
-TODO: Moving players more smoothly. Calculate moving animation from\r
-      data sent by server.\r
-\r
-TODO: There are some lighting-related todos and fixmes in\r
-      ServerMap::emergeBlock\r
-\r
-TODO: Make a dirt node and use it under water\r
-\r
-FIXME: When a new sector is generated, it may change the ground level\r
-       of it's and it's neighbors border that two blocks that are\r
-          above and below each other and that are generated before and\r
-          after the sector heightmap generation (order doesn't matter),\r
-          can have a small gap between each other at the border.\r
-SUGGESTION: Use same technique for sector heightmaps as what we're\r
-            using for UnlimitedHeightmap? (getting all neighbors\r
-                       when generating)\r
-\r
-TODO: Set server to automatically find a good spawning place in some\r
-      place where there is water and land.\r
-         - Map to have a getWalkableNear(p)\r
-\r
-TODO: Transfer more blocks in a single packet\r
-SUGG: A blockdata combiner class, to which blocks are added and at\r
-      destruction it sends all the stuff in as few packets as possible.\r
+NOTE: iostream.imbue(std::locale("C")) is very slow\r
+NOTE: Global locale is now set at initialization\r
 \r
-TODO: If player is on ground, mainly fetch ground-level blocks\r
-TODO: Fetch stuff mainly from the viewing direction\r
+NOTE: If VBO (EHM_STATIC) is used, remember to explicitly free the\r
+      hardware buffer (it is not freed automatically)\r
 \r
-TODO: Expose Connection's seqnums and ACKs to server and client.\r
+Old, wild and random suggestions that probably won't be done:\r
+-------------------------------------------------------------\r
+\r
+SUGG: If player is on ground, mainly fetch ground-level blocks\r
+\r
+SUGG: Expose Connection's seqnums and ACKs to server and client.\r
       - This enables saving many packets and making a faster connection\r
          - This also enables server to check if client has received the\r
            most recent block sent, for example.\r
+SUGG: Add a sane bandwidth throttling system to Connection\r
 \r
-SUGG: Add a time value to the param of footstepped grass and check it\r
-      against a global timer when a block is accessed, to make old\r
-         steps fade away.\r
+SUGG: More fine-grained control of client's dumping of blocks from\r
+      memory\r
+         - ...What does this mean in the first place?\r
 \r
-FIXME: There still are *some* tiny glitches in lighting as seen from\r
-       the client side. The server calculates them right but sometimes\r
-          they don't get transferred properly.\r
-          - Server probably checks that a block is not sent, then continues\r
-          to sending it, then the emerge thread marks it as unsent and then\r
-          the sender sends the block as it was before emerging?\r
-TODO: How about adding a "revision" field to MapBlocks?\r
+SUGG: A map editing mode (similar to dedicated server mode)\r
 \r
-TODO: More fine-grained control of client's dumping of blocks from\r
-      memory\r
+SUGG: Transfer more blocks in a single packet\r
+SUGG: A blockdata combiner class, to which blocks are added and at\r
+      destruction it sends all the stuff in as few packets as possible.\r
+SUGG: Make a PACKET_COMBINED which contains many subpackets. Utilize\r
+      it by sending more stuff in a single packet.\r
+         - Add a packet queue to RemoteClient, from which packets will be\r
+           combined with object data packets\r
+               - This is not exactly trivial: the object data packets are\r
+                 sometimes very big by themselves\r
+         - This might not give much network performance gain though.\r
 \r
-TODO: Somehow prioritize the sending of blocks and combine the block\r
-      send queue lengths\r
-         - Take two blocks to be sent next from each client and assign\r
-           a priority value to them\r
-         - Priority is the same as distance from player\r
-         - Take the highest priority ones and send them. Send as many as\r
-           fits in the global send queue maximum length (sum of lengths\r
-               of client queues)\r
-TODO: Make the amount of blocks sending to client and the total\r
+SUGG: Precalculate lighting translation table at runtime (at startup)\r
+      - This is not doable because it is currently hand-made and not\r
+           based on some mathematical function.\r
+               - Note: This has been changing lately\r
+\r
+SUGG: A version number to blocks, which increments when the block is\r
+      modified (node add/remove, water update, lighting update)\r
+         - This can then be used to make sure the most recent version of\r
+           a block has been sent to client, for example\r
+\r
+SUGG: Make the amount of blocks sending to client and the total\r
          amount of blocks dynamically limited. Transferring blocks is the\r
          main network eater of this system, so it is the one that has\r
          to be throttled so that RTTs stay low.\r
-FIXME: There is a bug that sometimes the EmergeThread bumps to\r
-       the client's emerge counter being already 0, and also the\r
-          sending queue size of the client can float to 1 or 2, which\r
-          stops the map from loading at all.\r
-          - A quick hack could be applied to ignore the error of\r
-            being at 0 and timing out old entries\r
-SUGG: Make client send GOTBLOCKS before updating meshes\r
 \r
-TODO: Server to load starting inventory from disk\r
+SUGG: Meshes of blocks could be split into 6 meshes facing into\r
+      different directions and then only those drawn that need to be\r
 \r
-NOTE: iostream.imbue(std::locale("C")) is very slow\r
-NOTE: Global locale is now set at initialization\r
+SUGG: Calculate lighting per vertex to get a lighting effect like in\r
+      bartwe's game\r
 \r
-TODO: PLayers to only be hidden when the client quits.\r
-TODO: - Players to be saved on disk, with inventory\r
-TODO: Players to be saved as text in map/players/<name>\r
+SUGG: Background music based on cellular automata?\r
+      http://www.earslap.com/projectslab/otomata\r
 \r
-SUGGESTION: A map editing mode (similar to dedicated server mode)\r
+SUGG: Simple light color information to air\r
 \r
-TODO: Maybe: Create a face calculation queue on the client that is\r
-      processed in a separate thread\r
-TODO: Make client's mesh updates to happen in a thread similar to\r
-      server's EmergeThread.\r
-         - This is not really needed, mesh update is really fast\r
-         - Instead, the lighting update can be slow\r
-         - So, this todo is not really a todo. It is a not-todo.\r
-SUGG: Make server to send all modified blocks after a node change\r
-      after all the stuff including lighting have been updated\r
+SUGG: Server-side objects could be moved based on nodes to enable very\r
+      lightweight operation and simple AI\r
+       - Not practical; client would still need to show smooth movement.\r
 \r
-TODO: Make fetching sector's blocks more efficient when rendering\r
-      sectors that have very large amounts of blocks (on client)\r
+SUGG: Make a system for pregenerating quick information for mapblocks, so\r
+         that the client can show them as cubes before they are actually sent\r
+         or even generated.\r
 \r
-TODO: Make the video backend selectable\r
+Gaming ideas:\r
+-------------\r
 \r
-Block object server side:\r
-      - A "near blocks" buffer, in which some nearby blocks are stored.\r
-         - For all blocks in the buffer, objects are stepped(). This\r
-           means they are active.\r
-      - TODO All blocks going in and out of the buffer are recorded.\r
-           - TODO For outgoing blocks, a timestamp is written.\r
-           - TODO For incoming blocks, the time difference is calculated and\r
-             objects are stepped according to it.\r
-TODO: A timestamp to blocks\r
+- Aim for something like controlling a single dwarf in Dwarf Fortress\r
+- The player could go faster by a crafting a boat, or riding an animal\r
+- Random NPC traders. what else?\r
 \r
-TODO: Add config parameters for server's sending and generating distance\r
+Game content:\r
+-------------\r
 \r
-TODO: Copy the text of the last picked sign to inventory in creative\r
-      mode\r
+- When furnace is destroyed, move items to player's inventory\r
+- Add lots of stuff\r
+- Glass blocks\r
+- Growing grass, decaying leaves\r
+       - This can be done in the active blocks I guess.\r
+       - Lots of stuff can be done in the active blocks.\r
+       - Uh, is there an active block list somewhere? I think not. Add it.\r
+- Breaking weak structures\r
+       - This can probably be accomplished in the same way as grass\r
+- Player health points\r
+       - When player dies, throw items on map (needs better item-on-map\r
+         implementation)\r
+- Cobble to get mossy if near water\r
+- More slots in furnace source list, so that multiple ingredients\r
+  are possible.\r
+- Keys to chests?\r
 \r
-TODO: Untie client network operations from framerate\r
+- The Treasure Guard; a big monster with a hammer\r
+       - The hammer does great damage, shakes the ground and removes a block\r
+       - You can drop on top of it, and have some time to attack there\r
+         before he shakes you off\r
 \r
-SUGG: Make a copy of close-range environment on client for showing\r
-      on screen, with minimal mutexes to slow the main loop down\r
+- Maybe the difficulty could come from monsters getting tougher in\r
+  far-away places, and the player starting to need something from\r
+  there when time goes by.\r
+  - The player would have some of that stuff at the beginning, and\r
+    would need new supplies of it when it runs out\r
 \r
-SUGG: Make a PACKET_COMBINED which contains many subpackets. Utilize\r
-      it by sending more stuff in a single packet.\r
-         - Add a packet queue to RemoteClient, from which packets will be\r
-           combined with object data packets\r
-               - This is not exactly trivial: the object data packets are\r
-                 sometimes very big by themselves\r
+- A bomb\r
+- A spread-items-on-map routine for the bomb, and for dying players\r
 \r
-SUGG: Split MapBlockObject serialization to to-client and to-disk\r
-      - This will allow saving ages of rats on disk but not sending\r
-           them to clients\r
+- Fighting:\r
+  - Proper sword swing simulation\r
+  - Player should get damage from colliding to a wall at high speed\r
 \r
-TODO: Fix the long-lived Server Block Emerge Jam bug\r
-      - Is it related to the client deleting blocks?\r
+Documentation:\r
+--------------\r
 \r
-Doing now:\r
-======================================================================\r
+Build system / running:\r
+-----------------------\r
 \r
+Networking and serialization:\r
+-----------------------------\r
 \r
-======================================================================\r
+SUGG: Fix address to be ipv6 compatible\r
 \r
-*/\r
+User Interface:\r
+---------------\r
 \r
-/*\r
-       Setting this to 1 enables a special camera mode that forces\r
-       the renderers to think that the camera statically points from\r
-       the starting place to a static direction.\r
+Graphics:\r
+---------\r
+\r
+SUGG: Combine MapBlock's face caches to so big pieces that VBO\r
+      can be used\r
+      - That is >500 vertices\r
+         - This is not easy; all the MapBlocks close to the player would\r
+           still need to be drawn separately and combining the blocks\r
+               would have to happen in a background thread\r
+\r
+SUGG: Make fetching sector's blocks more efficient when rendering\r
+      sectors that have very large amounts of blocks (on client)\r
+         - Is this necessary at all?\r
+\r
+TODO: Flowing water animation\r
+\r
+SUGG: Draw cubes in inventory directly with 3D drawing commands, so that\r
+      animating them is easier.\r
+\r
+SUGG: Option for enabling proper alpha channel for textures\r
+TODO: A setting for enabling bilinear filtering for textures\r
+\r
+TODO: Better control of draw_control.wanted_max_blocks\r
+\r
+TODO: Block mesh generator to tile properly on smooth lighting\r
+\r
+Configuration:\r
+--------------\r
+\r
+Client:\r
+-------\r
+\r
+TODO: Untie client network operations from framerate\r
+      - Needs some input queues or something\r
+         - This won't give much performance boost because calculating block\r
+           meshes takes so long\r
+\r
+SUGG: Make morning and evening transition more smooth and maybe shorter\r
+\r
+TODO: Don't update all meshes always on single node changes, but\r
+      check which ones should be updated\r
+         - implement Map::updateNodeMeshes() and the usage of it\r
+         - It will give almost always a 4x boost in mesh update performance.\r
+\r
+- A weapon engine\r
+\r
+- Tool/weapon visualization\r
+\r
+FIXME: When disconnected to the menu, memory is not freed properly\r
+\r
+Server:\r
+-------\r
+\r
+SUGG: Make an option to the server to disable building and digging near\r
+      the starting position\r
+\r
+FIXME: Server sometimes goes into some infinite PeerNotFoundException loop\r
+\r
+* Fix the problem with the server constantly saving one or a few\r
+  blocks? List the first saved block, maybe it explains.\r
+  - It is probably caused by oscillating water\r
+* Make a small history check to transformLiquids to detect and log\r
+  continuous oscillations, in such detail that they can be fixed.\r
+\r
+FIXME: The new optimized map sending doesn't sometimes send enough blocks\r
+       from big caves and such\r
+\r
+Environment:\r
+------------\r
+\r
+TODO: A list of "active blocks" in which stuff happens.\r
+       + Add a never-resetted game timer to the server\r
+       + Add a timestamp value to blocks\r
+       + The simple rule: All blocks near some player are "active"\r
+       - Do stuff in real time in active blocks\r
+               + Handle objects\r
+               TODO: Make proper hooks in here\r
+               - Grow grass, delete leaves without a tree\r
+               - Spawn some mobs based on some rules\r
+               - Transform cobble to mossy cobble near water\r
+               - Run a custom script\r
+               - ...And all kinds of other dynamic stuff\r
+       + Keep track of when a block becomes active and becomes inactive\r
+       + When a block goes inactive:\r
+               + Store objects statically to block\r
+               + Store timer value as the timestamp\r
+       + When a block goes active:\r
+               + Create active objects out of static objects\r
+               TODO: Make proper hooks in here\r
+               - Simulate the results of what would have happened if it would have\r
+                 been active for all the time\r
+                       - Grow a lot of grass and so on\r
+       + Initially it is fine to send information about every active object\r
+         to every player. Eventually it should be modified to only send info\r
+         about the nearest ones.\r
+               + This was left to be done by the old system and it sends only the\r
+                 nearest ones.\r
+\r
+Objects:\r
+--------\r
+\r
+TODO: Get rid of MapBlockObjects and use only ActiveObjects\r
+       - Skipping the MapBlockObject data is nasty - there is no "total\r
+         length" stored; have to make a SkipMBOs function which contains\r
+         enough of the current code to skip them properly.\r
+\r
+SUGG: MovingObject::move and Player::move are basically the same.\r
+      combine them.\r
+       - NOTE: Player::move is more up-to-date.\r
+       - NOTE: There is a simple move implementation now in collision.{h,cpp}\r
+       - NOTE: MovingObject will be deleted (MapBlockObject)\r
+\r
+Map:\r
+----\r
+\r
+TODO: Mineral and ground material properties\r
+      - This way mineral ground toughness can be calculated with just\r
+           some formula, as well as tool strengths\r
+\r
+TODO: Flowing water to actually contain flow direction information\r
+      - There is a space for this - it just has to be implemented.\r
+\r
+SUGG: Erosion simulation at map generation time\r
+       - Simulate water flows, which would carve out dirt fast and\r
+         then turn stone into gravel and sand and relocate it.\r
+       - How about relocating minerals, too? Coal and gold in\r
+         downstream sand and gravel would be kind of cool\r
+         - This would need a better way of handling minerals, mainly\r
+               to have mineral content as a separate field. the first\r
+               parameter field is free for this.\r
+       - Simulate rock falling from cliffs when water has removed\r
+         enough solid rock from the bottom\r
+\r
+SUGG: Try out the notch way of generating maps, that is, make bunches\r
+      of low-res 3d noise and interpolate linearly.\r
+\r
+Mapgen v2:\r
+* Possibly add some kind of erosion and other stuff\r
+* Better water generation (spread it to underwater caverns but don't\r
+  fill dungeons that don't touch big water masses)\r
+* When generating a chunk and the neighboring chunk doesn't have mud\r
+  and stuff yet and the ground is fairly flat, the mud will flow to\r
+  the other chunk making nasty straight walls when the other chunk\r
+  is generated. Fix it. Maybe just a special case if the ground is\r
+  flat?\r
+\r
+Misc. stuff:\r
+------------\r
+* Move digging property stuff from material.{h,cpp} to mapnode.cpp\r
+  - ...Or maybe move content_features to material.{h,cpp}?\r
+\r
+Making it more portable:\r
+------------------------\r
\r
+Stuff to do before release:\r
+---------------------------\r
+- Player default privileges and default password\r
+- Chat privilege\r
+- Some simple block-based dynamic stuff in the world (finish the\r
+  ActiveBlockModifier stuff)\r
+- Protocol version field\r
+- Consider getting some textures from cisoun's texture pack\r
+- Add a long step function to objects that is called with the time\r
+  difference when block activates\r
+\r
+======================================================================\r
 \r
-       This allows one to move around with the player and see what\r
-       is actually drawn behind solid things etc.\r
 */\r
-#define FIELD_OF_VIEW_TEST 0\r
 \r
-#ifdef UNITTEST_DISABLE\r
+#ifdef NDEBUG\r
        #ifdef _WIN32\r
                #pragma message ("Disabling unit tests")\r
        #else\r
@@ -220,119 +331,73 @@ Doing now:
 #endif\r
 \r
 #ifdef _MSC_VER\r
-#pragma comment(lib, "Irrlicht.lib")\r
-#pragma comment(lib, "jthread.lib")\r
-// This would get rid of the console window\r
-//#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")\r
-#endif\r
-\r
-#ifdef _WIN32\r
-       #define WIN32_LEAN_AND_MEAN\r
-       #include <windows.h>\r
-       #define sleep_ms(x) Sleep(x)\r
-#else\r
-       #include <unistd.h>\r
-       #define sleep_ms(x) usleep(x*1000)\r
+       #pragma comment(lib, "Irrlicht.lib")\r
+       //#pragma comment(lib, "jthread.lib")\r
+       #pragma comment(lib, "zlibwapi.lib")\r
+       #pragma comment(lib, "Shell32.lib")\r
+       // This would get rid of the console window\r
+       //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")\r
 #endif\r
 \r
 #include <iostream>\r
 #include <fstream>\r
-#include <time.h>\r
-#include <jmutexautolock.h>\r
+//#include <jmutexautolock.h>\r
+#include <locale.h>\r
+#include "main.h"\r
 #include "common_irrlicht.h"\r
 #include "debug.h"\r
-#include "map.h"\r
-#include "player.h"\r
-#include "main.h"\r
+//#include "map.h"\r
+//#include "player.h"\r
 #include "test.h"\r
-#include "environment.h"\r
 #include "server.h"\r
-#include "client.h"\r
-#include "serialization.h"\r
+//#include "client.h"\r
 #include "constants.h"\r
-#include "strfnd.h"\r
 #include "porting.h"\r
-#include <locale.h>\r
-\r
-IrrlichtDevice *g_device = NULL;\r
-\r
-const char *g_material_filenames[MATERIALS_COUNT] =\r
-{\r
-       "../data/stone.png",\r
-       "../data/grass.png",\r
-       "../data/water.png",\r
-       "../data/light.png",\r
-       "../data/tree.png",\r
-       "../data/leaves.png",\r
-       "../data/grass_footsteps.png",\r
-       "../data/mese.png"\r
-};\r
-\r
-video::SMaterial g_materials[MATERIALS_COUNT];\r
-//video::SMaterial g_mesh_materials[3];\r
-\r
-// All range-related stuff below is locked behind this\r
-JMutex g_range_mutex;\r
-\r
-// Blocks are viewed in this range from the player\r
-s16 g_viewing_range_nodes = 60;\r
-\r
-// This is updated by the client's fetchBlocks routine\r
-//s16 g_actual_viewing_range_nodes = VIEWING_RANGE_NODES_DEFAULT;\r
-\r
-// If true, the preceding value has no meaning and all blocks\r
-// already existing in memory are drawn\r
-bool g_viewing_range_all = false;\r
-\r
-// This is the freetime ratio imposed by the dynamic viewing\r
-// range changing code.\r
-// It is controlled by the main loop to the smallest value that\r
-// inhibits glitches (dtime jitter) in the main loop.\r
-//float g_freetime_ratio = FREETIME_RATIO_MAX;\r
-\r
+#include "gettime.h"\r
+#include "guiMessageMenu.h"\r
+#include "filesys.h"\r
+#include "config.h"\r
+#include "guiMainMenu.h"\r
+#include "mineral.h"\r
+//#include "noise.h"\r
+//#include "tile.h"\r
+#include "materials.h"\r
+#include "game.h"\r
+#include "keycode.h"\r
+\r
+// This makes textures\r
+ITextureSource *g_texturesource = NULL;\r
 \r
 /*\r
        Settings.\r
        These are loaded from the config file.\r
 */\r
 \r
-std::string g_dedicated_server;\r
-\r
-// Client stuff\r
-float g_wanted_fps = FPS_DEFAULT_WANTED;\r
-float g_fps_max = FPS_DEFAULT_MAX;\r
-s16 g_viewing_range_nodes_max = 300;\r
-s16 g_viewing_range_nodes_min = 20;\r
-std::string g_screenW;\r
-std::string g_screenH;\r
-std::string g_host_game;\r
-std::string g_port;\r
-std::string g_address;\r
-std::string g_name;\r
-bool g_random_input = false;\r
-float g_client_delete_unused_sectors_timeout = 1200;\r
-\r
-// Server stuff\r
-bool g_creative_mode = false;\r
-HMParams g_hm_params;\r
-MapParams g_map_params;\r
-float g_objectdata_interval = 0.2;\r
-u16 g_active_object_range = 2;\r
+Settings g_settings;\r
+// This is located in defaultsettings.cpp\r
+extern void set_default_settings();\r
 \r
 /*\r
        Random stuff\r
 */\r
 \r
-//u16 g_selected_material = 0;\r
-u16 g_selected_item = 0;\r
+/*\r
+       GUI Stuff\r
+*/\r
+\r
+gui::IGUIEnvironment* guienv = NULL;\r
+gui::IGUIStaticText *guiroot = NULL;\r
 \r
-bool g_esc_pressed = false;\r
+MainMenuManager g_menumgr;\r
 \r
-std::wstring g_text_buffer;\r
-bool g_text_buffer_accepted = false;\r
+bool noMenuActive()\r
+{\r
+       return (g_menumgr.menuCount() == 0);\r
+}\r
 \r
-// When true, the mouse and keyboard are grabbed\r
-bool g_game_focused = true;\r
+// Passed to menus to allow disconnecting and exiting\r
+\r
+MainGameCallback *g_gamecallback = NULL;\r
 \r
 /*\r
        Debug streams\r
@@ -355,163 +420,42 @@ std::ostream *dout_client_ptr = &dstream;
 std::ostream *derr_client_ptr = &dstream;\r
 \r
 /*\r
-       Config stuff\r
+       gettime.h implementation\r
 */\r
 \r
-// Returns false on EOF\r
-bool parseConfigObject(std::istream &is)\r
+// A small helper class\r
+class TimeGetter\r
 {\r
-       // float g_wanted_fps\r
-       // s16 g_viewing_range_nodes_max\r
-\r
-       if(is.eof())\r
-               return false;\r
-       \r
-       std::string line;\r
-       std::getline(is, line);\r
-       //dstream<<"got line: \""<<line<<"\""<<std::endl;\r
-\r
-       std::string trimmedline = trim(line);\r
-       \r
-       // Ignore comments\r
-       if(trimmedline[0] == '#')\r
-               return true;\r
-\r
-       //dstream<<"trimmedline=\""<<trimmedline<<"\""<<std::endl;\r
-\r
-       Strfnd sf(trim(line));\r
-\r
-       std::string name = sf.next("=");\r
-       name = trim(name);\r
-\r
-       if(name == "")\r
-               return true;\r
-       \r
-       std::string value = sf.next("\n");\r
-       value = trim(value);\r
-\r
-       dstream<<"Config name=\""<<name<<"\" value=\""\r
-                       <<value<<"\""<<std::endl;\r
-       \r
-       if(name == "dedicated_server")\r
-               g_dedicated_server = value;\r
-       \r
-       // Client stuff\r
-       else if(name == "wanted_fps")\r
-       {\r
-               g_wanted_fps = atof(value.c_str());\r
-       }\r
-       else if(name == "fps_max")\r
-       {\r
-               g_fps_max = atof(value.c_str());\r
-       }\r
-       else if(name == "viewing_range_nodes_max")\r
-       {\r
-               g_viewing_range_nodes_max = stoi(value, 0, 32767);\r
-       }\r
-       else if(name == "viewing_range_nodes_min")\r
-       {\r
-               g_viewing_range_nodes_min = stoi(value, 0, 32767);\r
-       }\r
-       else if(name=="screenW")\r
-               g_screenW = value;\r
-       else if(name=="screenH")\r
-               g_screenH = value;\r
-       else if(name == "host_game")\r
-               g_host_game = value;\r
-       else if(name == "port")\r
-               g_port = value;\r
-       else if(name == "address")\r
-               g_address = value;\r
-       else if(name == "name")\r
-               g_name = value;\r
-       else if(name == "random_input")\r
-               g_random_input = is_yes(value);\r
-       else if(name == "client_delete_unused_sectors_timeout")\r
-       {\r
-               std::istringstream vis(value);\r
-               //vis.imbue(std::locale("C"));\r
-               vis>>g_client_delete_unused_sectors_timeout;\r
-       }\r
-       \r
-       // Server stuff\r
-       else if(name == "creative_mode")\r
-               g_creative_mode = is_yes(value);\r
-       else if(name == "mapgen_heightmap_blocksize")\r
-       {\r
-               s32 d = atoi(value.c_str());\r
-               if(d > 0 && (d & (d-1)) == 0)\r
-                       g_hm_params.heightmap_blocksize = d;\r
-               else\r
-                       dstream<<"Invalid value in config file: \""\r
-                                       <<line<<"\""<<std::endl;\r
-       }\r
-       else if(name == "mapgen_height_randmax")\r
-               g_hm_params.height_randmax = value;\r
-       else if(name == "mapgen_height_randfactor")\r
-               g_hm_params.height_randfactor = value;\r
-       else if(name == "mapgen_height_base")\r
-               g_hm_params.height_base = value;\r
-       else if(name == "mapgen_plants_amount")\r
-       {\r
-               std::istringstream vis(value);\r
-               vis>>g_map_params.plants_amount;\r
-       }\r
-       else if(name == "objectdata_inverval")\r
-       {\r
-               std::istringstream vis(value);\r
-               vis>>g_objectdata_interval;\r
-       }\r
-       else if(name == "active_object_range")\r
-               g_active_object_range = stoi(value, 0, 65535);\r
-       \r
-       else\r
+public:\r
+       TimeGetter(IrrlichtDevice *device):\r
+               m_device(device)\r
+       {}\r
+       u32 getTime()\r
        {\r
-               dstream<<"Unknown option in config file: \""\r
-                               <<line<<"\""<<std::endl;\r
+               if(m_device == NULL)\r
+                       return 0;\r
+               return m_device->getTimer()->getRealTime();\r
        }\r
+private:\r
+       IrrlichtDevice *m_device;\r
+};\r
 \r
-       return true;\r
-}\r
+// A pointer to a global instance of the time getter\r
+TimeGetter *g_timegetter = NULL;\r
 \r
-// Returns true on success\r
-bool readConfigFile(const char *filename)\r
+u32 getTimeMs()\r
 {\r
-       std::ifstream is(filename);\r
-       if(is.good() == false)\r
-       {\r
-               dstream<<DTIME<<"Error opening configuration file: "\r
-                               <<filename<<std::endl;\r
-               return false;\r
-       }\r
-\r
-       dstream<<DTIME<<"Parsing configuration file: "\r
-                       <<filename<<std::endl;\r
-                       \r
-       while(parseConfigObject(is));\r
-       \r
-       return true;\r
+       if(g_timegetter == NULL)\r
+               return 0;\r
+       return g_timegetter->getTime();\r
 }\r
 \r
 /*\r
-       Timestamp stuff\r
-*/\r
+       Event handler for Irrlicht\r
 \r
-JMutex g_timestamp_mutex;\r
-//std::string g_timestamp;\r
-\r
-std::string getTimestamp()\r
-{\r
-       if(g_timestamp_mutex.IsInitialized()==false)\r
-               return "";\r
-       JMutexAutoLock lock(g_timestamp_mutex);\r
-       //return g_timestamp;\r
-       time_t t = time(NULL);\r
-       struct tm *tm = localtime(&t);\r
-       char cs[20];\r
-       strftime(cs, 20, "%H:%M:%S", tm);\r
-       return cs;\r
-}\r
+       NOTE: Everything possible should be moved out from here,\r
+             probably to InputHandler and the_game\r
+*/\r
 \r
 class MyEventReceiver : public IEventReceiver\r
 {\r
@@ -519,104 +463,57 @@ class MyEventReceiver : public IEventReceiver
        // This is the one method that we have to implement\r
        virtual bool OnEvent(const SEvent& event)\r
        {\r
+               /*\r
+                       React to nothing here if a menu is active\r
+               */\r
+               if(noMenuActive() == false)\r
+               {\r
+                       return false;\r
+               }\r
+\r
                // Remember whether each key is down or up\r
                if(event.EventType == irr::EET_KEY_INPUT_EVENT)\r
                {\r
                        keyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;\r
 \r
                        if(event.KeyInput.PressedDown)\r
-                       {\r
-                               //dstream<<"Pressed key: "<<(char)event.KeyInput.Key<<std::endl;\r
-                               if(g_game_focused == false)\r
-                               {\r
-                                       s16 key = event.KeyInput.Key;\r
-                                       if(key == irr::KEY_RETURN || key == irr::KEY_ESCAPE)\r
-                                       {\r
-                                               g_text_buffer_accepted = true;\r
-                                       }\r
-                                       else if(key == irr::KEY_BACK)\r
-                                       {\r
-                                               if(g_text_buffer.size() > 0)\r
-                                                       g_text_buffer = g_text_buffer.substr\r
-                                                                       (0, g_text_buffer.size()-1);\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               wchar_t wc = event.KeyInput.Char;\r
-                                               if(wc != 0)\r
-                                                       g_text_buffer += wc;\r
-                                       }\r
-                               }\r
-                               \r
-                               if(event.KeyInput.Key == irr::KEY_ESCAPE)\r
-                               {\r
-                                       if(g_game_focused == true)\r
-                                       {\r
-                                               dstream<<DTIME<<"ESC pressed"<<std::endl;\r
-                                               g_esc_pressed = true;\r
-                                       }\r
-                               }\r
-\r
-                               // Material selection\r
-                               if(event.KeyInput.Key == irr::KEY_KEY_F)\r
-                               {\r
-                                       if(g_game_focused == true)\r
-                                       {\r
-                                               if(g_selected_item < PLAYER_INVENTORY_SIZE-1)\r
-                                                       g_selected_item++;\r
-                                               else\r
-                                                       g_selected_item = 0;\r
-                                               dstream<<DTIME<<"Selected item: "\r
-                                                               <<g_selected_item<<std::endl;\r
-                                       }\r
-                               }\r
-\r
-                               // Viewing range selection\r
-                               if(event.KeyInput.Key == irr::KEY_KEY_R\r
-                                               && g_game_focused)\r
-                               {\r
-                                       JMutexAutoLock lock(g_range_mutex);\r
-                                       if(g_viewing_range_all)\r
-                                       {\r
-                                               g_viewing_range_all = false;\r
-                                               dstream<<DTIME<<"Disabled full viewing range"<<std::endl;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               g_viewing_range_all = true;\r
-                                               dstream<<DTIME<<"Enabled full viewing range"<<std::endl;\r
-                                       }\r
-                               }\r
-                       }\r
+                               keyWasDown[event.KeyInput.Key] = true;\r
                }\r
 \r
                if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)\r
                {\r
-                       if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)\r
-                       {\r
-                               leftclicked = true;\r
-                       }\r
-                       if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)\r
+                       if(noMenuActive() == false)\r
                        {\r
-                               rightclicked = true;\r
+                               left_active = false;\r
+                               middle_active = false;\r
+                               right_active = false;\r
                        }\r
-                       if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)\r
+                       else\r
                        {\r
-                               /*dstream<<"event.MouseInput.Wheel="\r
-                                               <<event.MouseInput.Wheel<<std::endl;*/\r
-                               if(event.MouseInput.Wheel < 0)\r
+                               //dstream<<"MyEventReceiver: mouse input"<<std::endl;\r
+                               left_active = event.MouseInput.isLeftPressed();\r
+                               middle_active = event.MouseInput.isMiddlePressed();\r
+                               right_active = event.MouseInput.isRightPressed();\r
+\r
+                               if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)\r
+                               {\r
+                                       leftclicked = true;\r
+                               }\r
+                               if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)\r
+                               {\r
+                                       rightclicked = true;\r
+                               }\r
+                               if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)\r
+                               {\r
+                                       leftreleased = true;\r
+                               }\r
+                               if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)\r
                                {\r
-                                       if(g_selected_item < PLAYER_INVENTORY_SIZE-1)\r
-                                               g_selected_item++;\r
-                                       else\r
-                                               g_selected_item = 0;\r
+                                       rightreleased = true;\r
                                }\r
-                               else if(event.MouseInput.Wheel > 0)\r
+                               if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)\r
                                {\r
-                                       if(g_selected_item > 0)\r
-                                               g_selected_item--;\r
-                                       else\r
-                                               g_selected_item = PLAYER_INVENTORY_SIZE-1;\r
+                                       mouse_wheel += event.MouseInput.Wheel;\r
                                }\r
                        }\r
                }\r
@@ -624,63 +521,74 @@ class MyEventReceiver : public IEventReceiver
                return false;\r
        }\r
 \r
-       // This is used to check whether a key is being held down\r
-       virtual bool IsKeyDown(EKEY_CODE keyCode) const\r
+       bool IsKeyDown(EKEY_CODE keyCode) const\r
        {\r
                return keyIsDown[keyCode];\r
        }\r
+       \r
+       // Checks whether a key was down and resets the state\r
+       bool WasKeyDown(EKEY_CODE keyCode)\r
+       {\r
+               bool b = keyWasDown[keyCode];\r
+               keyWasDown[keyCode] = false;\r
+               return b;\r
+       }\r
 \r
-       MyEventReceiver()\r
+       s32 getMouseWheel()\r
+       {\r
+               s32 a = mouse_wheel;\r
+               mouse_wheel = 0;\r
+               return a;\r
+       }\r
+\r
+       void clearInput()\r
        {\r
-               for (u32 i=0; i<KEY_KEY_CODES_COUNT; ++i)\r
-                               keyIsDown[i] = false;\r
+               for(u32 i=0; i<KEY_KEY_CODES_COUNT; i++)\r
+               {\r
+                       keyIsDown[i] = false;\r
+                       keyWasDown[i] = false;\r
+               }\r
+               \r
                leftclicked = false;\r
                rightclicked = false;\r
-       }\r
+               leftreleased = false;\r
+               rightreleased = false;\r
 \r
-       bool leftclicked;\r
-       bool rightclicked;\r
-private:\r
-       // We use this array to store the current state of each key\r
-       bool keyIsDown[KEY_KEY_CODES_COUNT];\r
-       //s32 mouseX;\r
-       //s32 mouseY;\r
-};\r
+               left_active = false;\r
+               middle_active = false;\r
+               right_active = false;\r
 \r
-class InputHandler\r
-{\r
-public:\r
-       InputHandler()\r
-       {\r
+               mouse_wheel = 0;\r
        }\r
-       virtual ~InputHandler()\r
+\r
+       MyEventReceiver()\r
        {\r
+               clearInput();\r
        }\r
-       virtual bool isKeyDown(EKEY_CODE keyCode) = 0;\r
-       virtual v2s32 getMousePos() = 0;\r
-       virtual void setMousePos(s32 x, s32 y) = 0;\r
-       virtual bool getLeftClicked() = 0;\r
-       virtual bool getRightClicked() = 0;\r
-       virtual void resetLeftClicked() = 0;\r
-       virtual void resetRightClicked() = 0;\r
-       \r
-       virtual void step(float dtime) {};\r
 \r
-       virtual void clear() {};\r
-};\r
+       bool leftclicked;\r
+       bool rightclicked;\r
+       bool leftreleased;\r
+       bool rightreleased;\r
 \r
-InputHandler *g_input = NULL;\r
+       bool left_active;\r
+       bool middle_active;\r
+       bool right_active;\r
 \r
-void focusGame()\r
-{\r
-       g_input->clear();\r
-       g_game_focused = true;\r
-}\r
+       s32 mouse_wheel;\r
 \r
-void unFocusGame()\r
-{\r
-       g_game_focused = false;\r
-}\r
+private:\r
+       IrrlichtDevice *m_device;\r
+       \r
+       // The current state of keys\r
+       bool keyIsDown[KEY_KEY_CODES_COUNT];\r
+       // Whether a key has been pressed or not\r
+       bool keyWasDown[KEY_KEY_CODES_COUNT];\r
+};\r
+\r
+/*\r
+       Separated input handler\r
+*/\r
 \r
 class RealInputHandler : public InputHandler\r
 {\r
@@ -694,6 +602,10 @@ class RealInputHandler : public InputHandler
        {\r
                return m_receiver->IsKeyDown(keyCode);\r
        }\r
+       virtual bool wasKeyDown(EKEY_CODE keyCode)\r
+       {\r
+               return m_receiver->WasKeyDown(keyCode);\r
+       }\r
        virtual v2s32 getMousePos()\r
        {\r
                return m_device->getCursorControl()->getPosition();\r
@@ -703,16 +615,21 @@ class RealInputHandler : public InputHandler
                m_device->getCursorControl()->setPosition(x, y);\r
        }\r
 \r
+       virtual bool getLeftState()\r
+       {\r
+               return m_receiver->left_active;\r
+       }\r
+       virtual bool getRightState()\r
+       {\r
+               return m_receiver->right_active;\r
+       }\r
+       \r
        virtual bool getLeftClicked()\r
        {\r
-               if(g_game_focused == false)\r
-                       return false;\r
                return m_receiver->leftclicked;\r
        }\r
        virtual bool getRightClicked()\r
        {\r
-               if(g_game_focused == false)\r
-                       return false;\r
                return m_receiver->rightclicked;\r
        }\r
        virtual void resetLeftClicked()\r
@@ -724,10 +641,31 @@ class RealInputHandler : public InputHandler
                m_receiver->rightclicked = false;\r
        }\r
 \r
+       virtual bool getLeftReleased()\r
+       {\r
+               return m_receiver->leftreleased;\r
+       }\r
+       virtual bool getRightReleased()\r
+       {\r
+               return m_receiver->rightreleased;\r
+       }\r
+       virtual void resetLeftReleased()\r
+       {\r
+               m_receiver->leftreleased = false;\r
+       }\r
+       virtual void resetRightReleased()\r
+       {\r
+               m_receiver->rightreleased = false;\r
+       }\r
+\r
+       virtual s32 getMouseWheel()\r
+       {\r
+               return m_receiver->getMouseWheel();\r
+       }\r
+\r
        void clear()\r
        {\r
-               resetRightClicked();\r
-               resetLeftClicked();\r
+               m_receiver->clearInput();\r
        }\r
 private:\r
        IrrlichtDevice *m_device;\r
@@ -739,8 +677,12 @@ class RandomInputHandler : public InputHandler
 public:\r
        RandomInputHandler()\r
        {\r
+               leftdown = false;\r
+               rightdown = false;\r
                leftclicked = false;\r
                rightclicked = false;\r
+               leftreleased = false;\r
+               rightreleased = false;\r
                for(u32 i=0; i<KEY_KEY_CODES_COUNT; ++i)\r
                        keydown[i] = false;\r
        }\r
@@ -748,6 +690,10 @@ class RandomInputHandler : public InputHandler
        {\r
                return keydown[keyCode];\r
        }\r
+       virtual bool wasKeyDown(EKEY_CODE keyCode)\r
+       {\r
+               return false;\r
+       }\r
        virtual v2s32 getMousePos()\r
        {\r
                return mousepos;\r
@@ -757,6 +703,15 @@ class RandomInputHandler : public InputHandler
                mousepos = v2s32(x,y);\r
        }\r
 \r
+       virtual bool getLeftState()\r
+       {\r
+               return leftdown;\r
+       }\r
+       virtual bool getRightState()\r
+       {\r
+               return rightdown;\r
+       }\r
+\r
        virtual bool getLeftClicked()\r
        {\r
                return leftclicked;\r
@@ -774,31 +729,38 @@ class RandomInputHandler : public InputHandler
                rightclicked = false;\r
        }\r
 \r
+       virtual bool getLeftReleased()\r
+       {\r
+               return leftreleased;\r
+       }\r
+       virtual bool getRightReleased()\r
+       {\r
+               return rightreleased;\r
+       }\r
+       virtual void resetLeftReleased()\r
+       {\r
+               leftreleased = false;\r
+       }\r
+       virtual void resetRightReleased()\r
+       {\r
+               rightreleased = false;\r
+       }\r
+\r
+       virtual s32 getMouseWheel()\r
+       {\r
+               return 0;\r
+       }\r
+\r
        virtual void step(float dtime)\r
        {\r
-               {\r
-                       static float counter1 = 0;\r
-                       counter1 -= dtime;\r
-                       if(counter1 < 0.0)\r
-                       {\r
-                               counter1 = 0.1*Rand(1,10);\r
-                               /*if(g_selected_material < USEFUL_MATERIAL_COUNT-1)\r
-                                       g_selected_material++;\r
-                               else\r
-                                       g_selected_material = 0;*/\r
-                               if(g_selected_item < PLAYER_INVENTORY_SIZE-1)\r
-                                       g_selected_item++;\r
-                               else\r
-                                       g_selected_item = 0;\r
-                       }\r
-               }\r
                {\r
                        static float counter1 = 0;\r
                        counter1 -= dtime;\r
                        if(counter1 < 0.0)\r
                        {\r
                                counter1 = 0.1*Rand(1, 40);\r
-                               keydown[irr::KEY_SPACE] = !keydown[irr::KEY_SPACE];\r
+                               keydown[getKeySetting("keymap_jump")] =\r
+                                               !keydown[getKeySetting("keymap_jump")];\r
                        }\r
                }\r
                {\r
@@ -807,7 +769,8 @@ class RandomInputHandler : public InputHandler
                        if(counter1 < 0.0)\r
                        {\r
                                counter1 = 0.1*Rand(1, 40);\r
-                               keydown[irr::KEY_KEY_2] = !keydown[irr::KEY_KEY_2];\r
+                               keydown[getKeySetting("keymap_special1")] =\r
+                                               !keydown[getKeySetting("keymap_special1")];\r
                        }\r
                }\r
                {\r
@@ -816,7 +779,8 @@ class RandomInputHandler : public InputHandler
                        if(counter1 < 0.0)\r
                        {\r
                                counter1 = 0.1*Rand(1, 40);\r
-                               keydown[irr::KEY_KEY_W] = !keydown[irr::KEY_KEY_W];\r
+                               keydown[getKeySetting("keymap_forward")] =\r
+                                               !keydown[getKeySetting("keymap_forward")];\r
                        }\r
                }\r
                {\r
@@ -825,7 +789,8 @@ class RandomInputHandler : public InputHandler
                        if(counter1 < 0.0)\r
                        {\r
                                counter1 = 0.1*Rand(1, 40);\r
-                               keydown[irr::KEY_KEY_A] = !keydown[irr::KEY_KEY_A];\r
+                               keydown[getKeySetting("keymap_left")] =\r
+                                               !keydown[getKeySetting("keymap_left")];\r
                        }\r
                }\r
                {\r
@@ -843,7 +808,11 @@ class RandomInputHandler : public InputHandler
                        if(counter1 < 0.0)\r
                        {\r
                                counter1 = 0.1*Rand(1, 30);\r
-                               leftclicked = true;\r
+                               leftdown = !leftdown;\r
+                               if(leftdown)\r
+                                       leftclicked = true;\r
+                               if(!leftdown)\r
+                                       leftreleased = true;\r
                        }\r
                }\r
                {\r
@@ -851,8 +820,12 @@ class RandomInputHandler : public InputHandler
                        counter1 -= dtime;\r
                        if(counter1 < 0.0)\r
                        {\r
-                               counter1 = 0.1*Rand(1, 20);\r
-                               rightclicked = true;\r
+                               counter1 = 0.1*Rand(1, 15);\r
+                               rightdown = !rightdown;\r
+                               if(rightdown)\r
+                                       rightclicked = true;\r
+                               if(!rightdown)\r
+                                       rightreleased = true;\r
                        }\r
                }\r
                mousepos += mousespeed;\r
@@ -860,214 +833,263 @@ class RandomInputHandler : public InputHandler
 \r
        s32 Rand(s32 min, s32 max)\r
        {\r
-               return (rand()%(max-min+1))+min;\r
+               return (myrand()%(max-min+1))+min;\r
        }\r
 private:\r
        bool keydown[KEY_KEY_CODES_COUNT];\r
        v2s32 mousepos;\r
        v2s32 mousespeed;\r
+       bool leftdown;\r
+       bool rightdown;\r
        bool leftclicked;\r
        bool rightclicked;\r
+       bool leftreleased;\r
+       bool rightreleased;\r
 };\r
 \r
-void updateViewingRange(f32 frametime, Client *client)\r
+// These are defined global so that they're not optimized too much.\r
+// Can't change them to volatile.\r
+s16 temp16;\r
+f32 tempf;\r
+v3f tempv3f1;\r
+v3f tempv3f2;\r
+std::string tempstring;\r
+std::string tempstring2;\r
+\r
+void SpeedTests()\r
 {\r
-       // Range_all messes up frametime_avg\r
-       if(g_viewing_range_all == true)\r
-               return;\r
-       \r
-       // Initialize to the target value\r
-       static float frametime_avg = 1.0/g_wanted_fps;\r
-       frametime_avg = frametime_avg * 0.9 + frametime * 0.1;\r
-\r
-       static f32 counter = 0;\r
-       if(counter > 0){\r
-               counter -= frametime;\r
-               return;\r
+       {\r
+               dstream<<"The following test should take around 20ms."<<std::endl;\r
+               TimeTaker timer("Testing std::string speed");\r
+               const u32 jj = 10000;\r
+               for(u32 j=0; j<jj; j++)\r
+               {\r
+                       tempstring = "";\r
+                       tempstring2 = "";\r
+                       const u32 ii = 10;\r
+                       for(u32 i=0; i<ii; i++){\r
+                               tempstring2 += "asd";\r
+                       }\r
+                       for(u32 i=0; i<ii+1; i++){\r
+                               tempstring += "asd";\r
+                               if(tempstring == tempstring2)\r
+                                       break;\r
+                       }\r
+               }\r
        }\r
-       //counter = 1.0; //seconds\r
-       counter = 0.5; //seconds\r
-\r
-       //float freetime_ratio = 0.2;\r
-       //float freetime_ratio = 0.4;\r
-       float freetime_ratio = FREETIME_RATIO;\r
-\r
-       float frametime_wanted = (1.0/(g_wanted_fps/(1.0-freetime_ratio)));\r
-\r
-       float fraction = sqrt(frametime_avg / frametime_wanted);\r
-\r
-       static bool fraction_is_good = false;\r
        \r
-       float fraction_good_threshold = 0.1;\r
-       float fraction_bad_threshold = 0.25;\r
-       float fraction_limit;\r
-       // Use high limit if fraction is good AND the fraction would\r
-       // lower the range. We want to keep the range fairly high.\r
-       if(fraction_is_good && fraction > 1.0)\r
-               fraction_limit = fraction_bad_threshold;\r
-       else\r
-               fraction_limit = fraction_good_threshold;\r
+       dstream<<"All of the following tests should take around 100ms each."\r
+                       <<std::endl;\r
 \r
-       if(fabs(fraction - 1.0) < fraction_limit)\r
        {\r
-               fraction_is_good = true;\r
-               return;\r
+               TimeTaker timer("Testing floating-point conversion speed");\r
+               tempf = 0.001;\r
+               for(u32 i=0; i<4000000; i++){\r
+                       temp16 += tempf;\r
+                       tempf += 0.001;\r
+               }\r
        }\r
-       else\r
+       \r
        {\r
-               fraction_is_good = false;\r
-       }\r
+               TimeTaker timer("Testing floating-point vector speed");\r
 \r
-       //dstream<<"frametime_avg="<<frametime_avg<<std::endl;\r
-       //dstream<<"frametime_wanted="<<frametime_wanted<<std::endl;\r
-       /*dstream<<"fetching="<<client->isFetchingBlocks()\r
-                       <<" faction = "<<fraction<<std::endl;*/\r
+               tempv3f1 = v3f(1,2,3);\r
+               tempv3f2 = v3f(4,5,6);\r
+               for(u32 i=0; i<10000000; i++){\r
+                       tempf += tempv3f1.dotProduct(tempv3f2);\r
+                       tempv3f2 += v3f(7,8,9);\r
+               }\r
+       }\r
 \r
-       JMutexAutoLock lock(g_range_mutex);\r
-       \r
-       s16 n = (float)g_viewing_range_nodes / fraction;\r
-       if(n < g_viewing_range_nodes_min)\r
-               n = g_viewing_range_nodes_min;\r
-       if(n > g_viewing_range_nodes_max)\r
-               n = g_viewing_range_nodes_max;\r
-\r
-       bool can_change = true;\r
+       {\r
+               TimeTaker timer("Testing core::map speed");\r
+               \r
+               core::map<v2s16, f32> map1;\r
+               tempf = -324;\r
+               const s16 ii=300;\r
+               for(s16 y=0; y<ii; y++){\r
+                       for(s16 x=0; x<ii; x++){\r
+                               map1.insert(v2s16(x,y), tempf);\r
+                               tempf += 1;\r
+                       }\r
+               }\r
+               for(s16 y=ii-1; y>=0; y--){\r
+                       for(s16 x=0; x<ii; x++){\r
+                               tempf = map1[v2s16(x,y)];\r
+                       }\r
+               }\r
+       }\r
 \r
-       if(client->isFetchingBlocks() == true && n > g_viewing_range_nodes)\r
-               can_change = false;\r
-       \r
-       if(can_change)\r
-               g_viewing_range_nodes = n;\r
+       {\r
+               dstream<<"Around 5000/ms should do well here."<<std::endl;\r
+               TimeTaker timer("Testing mutex speed");\r
+               \r
+               JMutex m;\r
+               m.Init();\r
+               u32 n = 0;\r
+               u32 i = 0;\r
+               do{\r
+                       n += 10000;\r
+                       for(; i<n; i++){\r
+                               m.Lock();\r
+                               m.Unlock();\r
+                       }\r
+               }\r
+               // Do at least 10ms\r
+               while(timer.getTime() < 10);\r
 \r
-       /*dstream<<"g_viewing_range_nodes = "\r
-                       <<g_viewing_range_nodes<<std::endl;*/\r
+               u32 dtime = timer.stop();\r
+               u32 per_ms = n / dtime;\r
+               std::cout<<"Done. "<<dtime<<"ms, "\r
+                               <<per_ms<<"/ms"<<std::endl;\r
+       }\r
 }\r
 \r
-class GUIQuickInventory : public IEventReceiver\r
+void drawMenuBackground(video::IVideoDriver* driver)\r
 {\r
-public:\r
-       GUIQuickInventory(\r
-                       gui::IGUIEnvironment* env,\r
-                       gui::IGUIElement* parent,\r
-                       v2s32 pos,\r
-                       s32 itemcount,\r
-                       Inventory *inventory):\r
-               m_itemcount(itemcount),\r
-               m_inventory(inventory)\r
+       core::dimension2d<u32> screensize = driver->getScreenSize();\r
+               \r
+       video::ITexture *bgtexture =\r
+                       driver->getTexture(getTexturePath("mud.png").c_str());\r
+       if(bgtexture)\r
        {\r
-               core::rect<s32> imgsize(0,0,48,48);\r
-               core::rect<s32> textsize(0,0,48,16);\r
-               v2s32 spacing(0, 64);\r
-               for(s32 i=0; i<m_itemcount; i++)\r
+               s32 texturesize = 128;\r
+               s32 tiled_y = screensize.Height / texturesize + 1;\r
+               s32 tiled_x = screensize.Width / texturesize + 1;\r
+               \r
+               for(s32 y=0; y<tiled_y; y++)\r
+               for(s32 x=0; x<tiled_x; x++)\r
                {\r
-                       m_images.push_back(env->addImage(\r
-                               imgsize + pos + spacing*i\r
-                       ));\r
-                       m_images[i]->setScaleImage(true);\r
-                       m_texts.push_back(env->addStaticText(\r
-                               L"",\r
-                               textsize + pos + spacing*i,\r
-                               false, false\r
-                       ));\r
-                       m_texts[i]->setBackgroundColor(\r
-                                       video::SColor(128,0,0,0));\r
-                       m_texts[i]->setTextAlignment(\r
-                                       gui::EGUIA_CENTER,\r
-                                       gui::EGUIA_UPPERLEFT);\r
+                       core::rect<s32> rect(0,0,texturesize,texturesize);\r
+                       rect += v2s32(x*texturesize, y*texturesize);\r
+                       driver->draw2DImage(bgtexture, rect,\r
+                               core::rect<s32>(core::position2d<s32>(0,0),\r
+                               core::dimension2di(bgtexture->getSize())),\r
+                               NULL, NULL, true);\r
                }\r
        }\r
-\r
-       virtual bool OnEvent(const SEvent& event)\r
-       {\r
-               return false;\r
-       }\r
-\r
-       void setSelection(s32 i)\r
-       {\r
-               m_selection = i;\r
+       \r
+       video::ITexture *logotexture =\r
+                       driver->getTexture(getTexturePath("menulogo.png").c_str());\r
+       if(logotexture)\r
+       {\r
+               v2s32 logosize(logotexture->getOriginalSize().Width,\r
+                               logotexture->getOriginalSize().Height);\r
+               logosize *= 4;\r
+\r
+               video::SColor bgcolor(255,50,50,50);\r
+               core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,\r
+                               screensize.Width, screensize.Height);\r
+               driver->draw2DRectangle(bgcolor, bgrect, NULL);\r
+\r
+               core::rect<s32> rect(0,0,logosize.X,logosize.Y);\r
+               rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);\r
+               rect -= v2s32(logosize.X/2, 0);\r
+               driver->draw2DImage(logotexture, rect,\r
+                       core::rect<s32>(core::position2d<s32>(0,0),\r
+                       core::dimension2di(logotexture->getSize())),\r
+                       NULL, NULL, true);\r
        }\r
+}\r
 \r
-       void update()\r
-       {\r
-               s32 start = 0;\r
+int main(int argc, char *argv[])\r
+{\r
+       /*\r
+               Parse command line\r
+       */\r
+       \r
+       // List all allowed options\r
+       core::map<std::string, ValueSpec> allowed_options;\r
+       allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG));\r
+       allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,\r
+                       "Run server directly"));\r
+       allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,\r
+                       "Load configuration from specified file"));\r
+       allowed_options.insert("port", ValueSpec(VALUETYPE_STRING));\r
+       allowed_options.insert("address", ValueSpec(VALUETYPE_STRING));\r
+       allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG));\r
+       allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG));\r
+       allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG));\r
+       allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING));\r
+#ifdef _WIN32\r
+       allowed_options.insert("dstream-on-stderr", ValueSpec(VALUETYPE_FLAG));\r
+#endif\r
+       allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG));\r
 \r
-               start = m_selection - m_itemcount / 2;\r
+       Settings cmd_args;\r
+       \r
+       bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);\r
 \r
-               for(s32 i=0; i<m_itemcount; i++)\r
+       if(ret == false || cmd_args.getFlag("help"))\r
+       {\r
+               dstream<<"Allowed options:"<<std::endl;\r
+               for(core::map<std::string, ValueSpec>::Iterator\r
+                               i = allowed_options.getIterator();\r
+                               i.atEnd() == false; i++)\r
                {\r
-                       s32 j = i + start;\r
-\r
-                       if(j > (s32)m_inventory->getSize() - 1)\r
-                               j -= m_inventory->getSize();\r
-                       if(j < 0)\r
-                               j += m_inventory->getSize();\r
-                       \r
-                       InventoryItem *item = m_inventory->getItem(j);\r
-                       // Null items\r
-                       if(item == NULL)\r
+                       dstream<<"  --"<<i.getNode()->getKey();\r
+                       if(i.getNode()->getValue().type == VALUETYPE_FLAG)\r
                        {\r
-                               m_images[i]->setImage(NULL);\r
-\r
-                               wchar_t t[10];\r
-                               if(m_selection == j)\r
-                                       swprintf(t, 10, L"<-");\r
-                               else\r
-                                       swprintf(t, 10, L"");\r
-                               m_texts[i]->setText(t);\r
-\r
-                               // The next ifs will segfault with a NULL pointer\r
-                               continue;\r
                        }\r
-                       \r
-                       \r
-                       m_images[i]->setImage(item->getImage());\r
-                       \r
-                       wchar_t t[10];\r
-                       if(m_selection == j)\r
-                               swprintf(t, 10, SWPRINTF_CHARSTRING L" <-", item->getText().c_str());\r
                        else\r
-                               swprintf(t, 10, SWPRINTF_CHARSTRING, item->getText().c_str());\r
-                       m_texts[i]->setText(t);\r
-               }\r
-       }\r
+                       {\r
+                               dstream<<" <value>";\r
+                       }\r
+                       dstream<<std::endl;\r
 \r
-private:\r
-       s32 m_itemcount;\r
-       core::array<gui::IGUIStaticText*> m_texts;\r
-       core::array<gui::IGUIImage*> m_images;\r
-       Inventory *m_inventory;\r
-       s32 m_selection;\r
-};\r
+                       if(i.getNode()->getValue().help != NULL)\r
+                       {\r
+                               dstream<<"      "<<i.getNode()->getValue().help\r
+                                               <<std::endl;\r
+                       }\r
+               }\r
 \r
-int main(int argc, char *argv[])\r
-{\r
+               return cmd_args.getFlag("help") ? 0 : 1;\r
+       }\r
+       \r
        /*\r
                Low-level initialization\r
        */\r
 \r
        bool disable_stderr = false;\r
 #ifdef _WIN32\r
-       disable_stderr = true;\r
+       if(cmd_args.getFlag("dstream-on-stderr") == false)\r
+               disable_stderr = true;\r
 #endif\r
 \r
+       // Initialize debug streams\r
        debugstreams_init(disable_stderr, DEBUGFILE);\r
+       // Initialize debug stacks\r
        debug_stacks_init();\r
 \r
-\r
        DSTACK(__FUNCTION_NAME);\r
 \r
-       try\r
-       {\r
+       porting::signal_handler_init();\r
+       bool &kill = *porting::signal_handler_killstatus();\r
        \r
-       /*\r
-               Basic initialization\r
-       */\r
+       porting::initializePaths();\r
+       // Create user data directory\r
+       fs::CreateDir(porting::path_userdata);\r
+       \r
+       // C-style stuff initialization\r
+       initializeMaterialProperties();\r
+\r
+       // Debug handler\r
+       BEGIN_DEBUG_EXCEPTION_HANDLER\r
 \r
+       // Print startup message\r
        dstream<<DTIME<<"minetest-c55"\r
                        " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST\r
-                       <<", ENABLE_TESTS="<<ENABLE_TESTS\r
+                       <<", "<<BUILD_INFO\r
                        <<std::endl;\r
        \r
+       /*\r
+               Basic initialization\r
+       */\r
+\r
+       // Initialize default settings\r
+       set_default_settings();\r
+       \r
        // Set locale. This is for forcing '.' as the decimal point.\r
        std::locale::global(std::locale("C"));\r
        // This enables printing all characters in bitmap font\r
@@ -1077,295 +1099,245 @@ int main(int argc, char *argv[])
        sockets_init();\r
        atexit(sockets_cleanup);\r
        \r
-       // Initialize timestamp mutex\r
-       g_timestamp_mutex.Init();\r
-\r
-       /*\r
-               Run unit tests\r
-       */\r
-       if(ENABLE_TESTS)\r
-       {\r
-               run_tests();\r
-       }\r
-       \r
        /*\r
                Initialization\r
        */\r
 \r
-       // Read config file\r
+       /*\r
+               Read config file\r
+       */\r
        \r
-       if(argc >= 2)\r
+       // Path of configuration file in use\r
+       std::string configpath = "";\r
+       \r
+       if(cmd_args.exists("config"))\r
        {\r
-               readConfigFile(argv[1]);\r
+               bool r = g_settings.readConfigFile(cmd_args.get("config").c_str());\r
+               if(r == false)\r
+               {\r
+                       dstream<<"Could not read configuration from \""\r
+                                       <<cmd_args.get("config")<<"\""<<std::endl;\r
+                       return 1;\r
+               }\r
+               configpath = cmd_args.get("config");\r
        }\r
        else\r
        {\r
-               const char *filenames[2] =\r
-               {\r
-                       "../minetest.conf",\r
-                       "../../minetest.conf"\r
-               };\r
+               core::array<std::string> filenames;\r
+               filenames.push_back(porting::path_userdata + "/minetest.conf");\r
+#ifdef RUN_IN_PLACE\r
+               filenames.push_back(porting::path_userdata + "/../minetest.conf");\r
+#endif\r
 \r
-               for(u32 i=0; i<2; i++)\r
+               for(u32 i=0; i<filenames.size(); i++)\r
                {\r
-                       bool r = readConfigFile(filenames[i]);\r
+                       bool r = g_settings.readConfigFile(filenames[i].c_str());\r
                        if(r)\r
+                       {\r
+                               configpath = filenames[i];\r
                                break;\r
+                       }\r
                }\r
+               \r
+               // If no path found, use the first one (menu creates the file)\r
+               if(configpath == "")\r
+                       configpath = filenames[0];\r
        }\r
 \r
        // Initialize random seed\r
        srand(time(0));\r
+       mysrand(time(0));\r
+\r
+       /*\r
+               Pre-initialize some stuff with a dummy irrlicht wrapper.\r
 \r
-       g_range_mutex.Init();\r
-       assert(g_range_mutex.IsInitialized());\r
+               These are needed for unit tests at least.\r
+       */\r
+       \r
+       // Initial call with g_texturesource not set.\r
+       init_mapnode();\r
 \r
        /*\r
-               Ask some stuff\r
+               Run unit tests\r
        */\r
 \r
-       std::cout<<std::endl<<std::endl;\r
-       char templine[100];\r
-       \r
-       std::cout<<"Dedicated server? [y = yes]: ";\r
-       if(g_dedicated_server != "")\r
+       if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)\r
+                       || cmd_args.getFlag("enable-unittests") == true)\r
        {\r
-               std::cout<<g_dedicated_server<<std::endl;\r
-               snprintf(templine, 100, "%s", g_dedicated_server.c_str());\r
-       }\r
-       else\r
-       {\r
-               std::cin.getline(templine, 100);\r
+               run_tests();\r
        }\r
-\r
-       bool dedicated = false;\r
-       if(templine[0] == 'y')\r
-               dedicated = true;\r
-       if(dedicated)\r
-               std::cout<<"-> yes"<<std::endl;\r
-       else\r
-               std::cout<<"-> no"<<std::endl;\r
        \r
-       std::cout<<"Port [empty=30000]: ";\r
-       if(g_port != "")\r
+       /*for(s16 y=-100; y<100; y++)\r
+       for(s16 x=-100; x<100; x++)\r
        {\r
-               std::cout<<g_port<<std::endl;\r
-               snprintf(templine, 100, "%s", g_port.c_str());\r
+               std::cout<<noise2d_gradient((double)x/10,(double)y/10, 32415)<<std::endl;\r
        }\r
-       else\r
-       {\r
-               std::cin.getline(templine, 100);\r
-       }\r
-       unsigned short port;\r
-       if(templine[0] == 0)\r
+       return 0;*/\r
+       \r
+       /*\r
+               Game parameters\r
+       */\r
+\r
+       // Port\r
+       u16 port = 30000;\r
+       if(cmd_args.exists("port"))\r
+               port = cmd_args.getU16("port");\r
+       else if(g_settings.exists("port"))\r
+               port = g_settings.getU16("port");\r
+       if(port == 0)\r
                port = 30000;\r
-       else\r
-               port = atoi(templine);\r
-       std::cout<<"-> "<<port<<std::endl;\r
        \r
-       if(dedicated)\r
+       // Map directory\r
+       std::string map_dir = porting::path_userdata+"/map";\r
+       if(cmd_args.exists("map-dir"))\r
+               map_dir = cmd_args.get("map-dir");\r
+       else if(g_settings.exists("map-dir"))\r
+               map_dir = g_settings.get("map-dir");\r
+       \r
+       // Run dedicated server if asked to\r
+       if(cmd_args.getFlag("server"))\r
        {\r
                DSTACK("Dedicated server branch");\r
-               \r
-               std::cout<<std::endl;\r
-               std::cout<<"========================"<<std::endl;\r
-               std::cout<<"Running dedicated server"<<std::endl;\r
-               std::cout<<"========================"<<std::endl;\r
-               std::cout<<std::endl;\r
-\r
-               Server server("../map", g_creative_mode, g_hm_params,\r
-                               g_map_params, g_objectdata_interval,\r
-                               g_active_object_range);\r
-               server.start(port);\r
-       \r
-               for(;;)\r
-               {\r
-                       // This is kind of a hack but can be done like this\r
-                       // because server.step() is very light\r
-                       sleep_ms(100);\r
-                       server.step(0.1);\r
-\r
-                       static int counter = 0;\r
-                       counter--;\r
-                       if(counter <= 0)\r
-                       {\r
-                               counter = 10;\r
 \r
-                               core::list<PlayerInfo> list = server.getPlayerInfo();\r
-                               core::list<PlayerInfo>::Iterator i;\r
-                               static u32 sum_old = 0;\r
-                               u32 sum = PIChecksum(list);\r
-                               if(sum != sum_old)\r
-                               {\r
-                                       std::cout<<DTIME<<"Player info:"<<std::endl;\r
-                                       for(i=list.begin(); i!=list.end(); i++)\r
-                                       {\r
-                                               i->PrintLine(&std::cout);\r
-                                       }\r
-                               }\r
-                               sum_old = sum;\r
-                       }\r
-               }\r
+               // Create server\r
+               Server server(map_dir.c_str());\r
+               server.start(port);\r
+               \r
+               // Run server\r
+               dedicated_server_loop(server, kill);\r
 \r
                return 0;\r
        }\r
 \r
-       bool hosting = false;\r
-       char connect_name[100] = "";\r
 \r
-       std::cout<<"Address to connect to [empty = host a game]: ";\r
-       if(g_address != "" && is_yes(g_host_game) == false)\r
-       {\r
-               std::cout<<g_address<<std::endl;\r
-               snprintf(connect_name, 100, "%s", g_address.c_str());\r
-       }\r
-       else\r
-       {\r
-               std::cin.getline(connect_name, 100);\r
-       }\r
-       \r
-       if(connect_name[0] == 0){\r
-               snprintf(connect_name, 100, "127.0.0.1");\r
-               hosting = true;\r
-       }\r
+       /*\r
+               More parameters\r
+       */\r
        \r
-       if(hosting)\r
-               std::cout<<"-> hosting"<<std::endl;\r
-       else\r
-               std::cout<<"-> "<<connect_name<<std::endl;\r
+       // Address to connect to\r
+       std::string address = "";\r
        \r
-       char playername[PLAYERNAME_SIZE] = "";\r
-       if(g_name != "")\r
+       if(cmd_args.exists("address"))\r
        {\r
-               snprintf(playername, PLAYERNAME_SIZE, "%s", g_name.c_str());\r
+               address = cmd_args.get("address");\r
        }\r
        else\r
        {\r
-               std::cout<<"Name of player: ";\r
-               std::cin.getline(playername, PLAYERNAME_SIZE);\r
+               address = g_settings.get("address");\r
        }\r
-       std::cout<<"-> \""<<playername<<"\""<<std::endl;\r
+       \r
+       std::string playername = g_settings.get("name");\r
 \r
        /*\r
-               Resolution selection\r
+               Device initialization\r
        */\r
 \r
-       u16 screenW;\r
-       u16 screenH;\r
+       // Resolution selection\r
+       \r
        bool fullscreen = false;\r
+       u16 screenW = g_settings.getU16("screenW");\r
+       u16 screenH = g_settings.getU16("screenH");\r
+\r
+       // Determine driver\r
+\r
+       video::E_DRIVER_TYPE driverType;\r
        \r
-       if(g_screenW != "" && g_screenH != "")\r
-       {\r
-               screenW = atoi(g_screenW.c_str());\r
-               screenH = atoi(g_screenH.c_str());\r
-       }\r
+       std::string driverstring = g_settings.get("video_driver");\r
+\r
+       if(driverstring == "null")\r
+               driverType = video::EDT_NULL;\r
+       else if(driverstring == "software")\r
+               driverType = video::EDT_SOFTWARE;\r
+       else if(driverstring == "burningsvideo")\r
+               driverType = video::EDT_BURNINGSVIDEO;\r
+       else if(driverstring == "direct3d8")\r
+               driverType = video::EDT_DIRECT3D8;\r
+       else if(driverstring == "direct3d9")\r
+               driverType = video::EDT_DIRECT3D9;\r
+       else if(driverstring == "opengl")\r
+               driverType = video::EDT_OPENGL;\r
        else\r
        {\r
-               u16 resolutions[][3] = {\r
-                       //W, H, fullscreen\r
-                       {640,480, 0},\r
-                       {800,600, 0},\r
-                       {1024,768, 0},\r
-                       {1280,1024, 0},\r
-                       /*{640,480, 1},\r
-                       {800,600, 1},\r
-                       {1024,768, 1},\r
-                       {1280,1024, 1},*/\r
-               };\r
-\r
-               u16 res_count = sizeof(resolutions)/sizeof(resolutions[0]);\r
-               \r
-               for(u16 i=0; i<res_count; i++)\r
-               {\r
-                       std::cout<<(i+1)<<": "<<resolutions[i][0]<<"x"\r
-                                       <<resolutions[i][1];\r
-                       if(resolutions[i][2])\r
-                               std::cout<<" fullscreen"<<std::endl;\r
-                       else\r
-                               std::cout<<" windowed"<<std::endl;\r
-               }\r
-               std::cout<<"Select a window resolution number [empty = 2]: ";\r
-               std::cin.getline(templine, 100);\r
-\r
-               u16 r0;\r
-               if(templine[0] == 0)\r
-                       r0 = 2;\r
-               else\r
-                       r0 = atoi(templine);\r
-\r
-               if(r0 > res_count || r0 == 0)\r
-                       r0 = 2;\r
-               \r
-               {\r
-                       u16 i = r0-1;\r
-                       std::cout<<"-> ";\r
-                       std::cout<<(i+1)<<": "<<resolutions[i][0]<<"x"\r
-                                       <<resolutions[i][1];\r
-                       if(resolutions[i][2])\r
-                               std::cout<<" fullscreen"<<std::endl;\r
-                       else\r
-                               std::cout<<" windowed"<<std::endl;\r
-               }\r
-\r
-               screenW = resolutions[r0-1][0];\r
-               screenH = resolutions[r0-1][1];\r
-               fullscreen = resolutions[r0-1][2];\r
+               dstream<<"WARNING: Invalid video_driver specified; defaulting "\r
+                               "to opengl"<<std::endl;\r
+               driverType = video::EDT_OPENGL;\r
        }\r
 \r
-       //\r
+       /*\r
+               Create device and exit if creation failed\r
+       */\r
 \r
        MyEventReceiver receiver;\r
 \r
-       video::E_DRIVER_TYPE driverType;\r
-\r
-#ifdef _WIN32\r
-       //driverType = video::EDT_DIRECT3D9; // Doesn't seem to work\r
-       driverType = video::EDT_OPENGL;\r
-#else\r
-       driverType = video::EDT_OPENGL;\r
-#endif\r
-\r
-       // create device and exit if creation failed\r
-\r
        IrrlichtDevice *device;\r
        device = createDevice(driverType,\r
                        core::dimension2d<u32>(screenW, screenH),\r
                        16, fullscreen, false, false, &receiver);\r
-       // With vsync\r
-       /*device = createDevice(driverType,\r
-                       core::dimension2d<u32>(screenW, screenH),\r
-                       16, fullscreen, false, true, &receiver);*/\r
 \r
        if (device == 0)\r
                return 1; // could not create selected driver.\r
+       \r
+       // Set device in game parameters\r
+       device = device;\r
+       \r
+       // Create time getter\r
+       g_timegetter = new TimeGetter(device);\r
+       \r
+       // Create game callback for menus\r
+       g_gamecallback = new MainGameCallback(device);\r
+       \r
+       // Create texture source\r
+       g_texturesource = new TextureSource(device);\r
 \r
-       g_device = device;\r
+       /*\r
+               Speed tests (done after irrlicht is loaded to get timer)\r
+       */\r
+       if(cmd_args.getFlag("speedtests"))\r
+       {\r
+               dstream<<"Running speed tests"<<std::endl;\r
+               SpeedTests();\r
+               return 0;\r
+       }\r
        \r
        device->setResizable(true);\r
 \r
-       if(g_random_input)\r
-               g_input = new RandomInputHandler();\r
+       bool random_input = g_settings.getBool("random_input")\r
+                       || cmd_args.getFlag("random-input");\r
+       InputHandler *input = NULL;\r
+       if(random_input)\r
+               input = new RandomInputHandler();\r
        else\r
-               g_input = new RealInputHandler(device, &receiver);\r
+               input = new RealInputHandler(device, &receiver);\r
        \r
        /*\r
                Continue initialization\r
        */\r
 \r
-       video::IVideoDriver* driver = device->getVideoDriver();\r
-       // These make the textures not to show at all\r
-       //driver->setTextureCreationFlag(video::ETCF_ALWAYS_16_BIT);\r
-       //driver->setTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED );\r
+       //video::IVideoDriver* driver = device->getVideoDriver();\r
 \r
-       //driver->setMinHardwareBufferVertexCount(1);\r
+       /*\r
+               This changes the minimum allowed number of vertices in a VBO.\r
+               Default is 500.\r
+       */\r
+       //driver->setMinHardwareBufferVertexCount(50);\r
 \r
        scene::ISceneManager* smgr = device->getSceneManager();\r
 \r
-       gui::IGUIEnvironment* guienv = device->getGUIEnvironment();\r
+       guienv = device->getGUIEnvironment();\r
        gui::IGUISkin* skin = guienv->getSkin();\r
-       gui::IGUIFont* font = guienv->getFont("../data/fontlucida.png");\r
+       gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());\r
        if(font)\r
                skin->setFont(font);\r
+       else\r
+               dstream<<"WARNING: Font file was not found."\r
+                               " Using default font."<<std::endl;\r
+       // If font was not found, this will get us one\r
+       font = skin->getFont();\r
+       assert(font);\r
+       \r
+       u32 text_height = font->getDimension(L"Hello, world!").Height;\r
+       dstream<<"text_height="<<text_height<<std::endl;\r
+\r
        //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));\r
        skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));\r
        //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));\r
@@ -1373,980 +1345,225 @@ int main(int argc, char *argv[])
        skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));\r
        skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));\r
        \r
-       const wchar_t *text = L"Loading and connecting...";\r
-       core::vector2d<s32> center(screenW/2, screenH/2);\r
-       core::dimension2d<u32> textd = font->getDimension(text);\r
-       std::cout<<DTIME<<"Text w="<<textd.Width<<" h="<<textd.Height<<std::endl;\r
-       // Have to add a bit to disable the text from word wrapping\r
-       //core::vector2d<s32> textsize(textd.Width+4, textd.Height);\r
-       core::vector2d<s32> textsize(300, textd.Height);\r
-       core::rect<s32> textrect(center - textsize/2, center + textsize/2);\r
-\r
-       gui::IGUIStaticText *gui_loadingtext = guienv->addStaticText(\r
-                       text, textrect, false, false);\r
-       gui_loadingtext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);\r
-\r
-       driver->beginScene(true, true, video::SColor(255,0,0,0));\r
-       guienv->drawAll();\r
-       driver->endScene();\r
-\r
        /*\r
-               Initialize material array\r
+               Preload some textures and stuff\r
        */\r
 \r
-       //video::SMaterial g_materials[MATERIALS_COUNT];\r
-       for(u16 i=0; i<MATERIALS_COUNT; i++)\r
-       {\r
-               g_materials[i].Lighting = false;\r
-               g_materials[i].BackfaceCulling = false;\r
-\r
-               const char *filename = g_material_filenames[i];\r
-               if(filename != NULL){\r
-                       video::ITexture *t = driver->getTexture(filename);\r
-                       if(t == NULL){\r
-                               std::cout<<DTIME<<"Texture could not be loaded: \""\r
-                                               <<filename<<"\""<<std::endl;\r
-                               return 1;\r
-                       }\r
-                       g_materials[i].setTexture(0, driver->getTexture(filename));\r
-               }\r
-               //g_materials[i].setFlag(video::EMF_TEXTURE_WRAP, video::ETC_REPEAT);\r
-               g_materials[i].setFlag(video::EMF_BILINEAR_FILTER, false);\r
-               //g_materials[i].setFlag(video::EMF_ANISOTROPIC_FILTER, false);\r
-               //g_materials[i].setFlag(video::EMF_FOG_ENABLE, true);\r
-               if(i == MATERIAL_WATER)\r
-               {\r
-                       g_materials[i].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;\r
-                       //g_materials[i].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;\r
-               }\r
-       }\r
-\r
-       /*g_mesh_materials[0].setTexture(0, driver->getTexture("../data/water.png"));\r
-       g_mesh_materials[1].setTexture(0, driver->getTexture("../data/grass.png"));\r
-       g_mesh_materials[2].setTexture(0, driver->getTexture("../data/stone.png"));\r
-       for(u32 i=0; i<3; i++)\r
-       {\r
-               g_mesh_materials[i].Lighting = false;\r
-               g_mesh_materials[i].BackfaceCulling = false;\r
-               g_mesh_materials[i].setFlag(video::EMF_BILINEAR_FILTER, false);\r
-               g_mesh_materials[i].setFlag(video::EMF_FOG_ENABLE, true);\r
-       }*/\r
-\r
-       // Make a scope here for the client so that it gets removed\r
-       // before the irrlicht device\r
-       {\r
+       init_content_inventory_texture_paths();\r
+       init_mapnode(); // Second call with g_texturesource set\r
+       init_mineral();\r
 \r
-       std::cout<<DTIME<<"Creating server and client"<<std::endl;\r
-       \r
        /*\r
-               Create server\r
-       */\r
-       SharedPtr<Server> server;\r
-       if(hosting){\r
-               server = new Server("../map", g_creative_mode, g_hm_params,\r
-                               g_map_params, g_objectdata_interval,\r
-                               g_active_object_range);\r
-               server->start(port);\r
-       }\r
-       \r
-       /*\r
-               Create client\r
+               GUI stuff\r
        */\r
 \r
-       // TODO: Get rid of the g_materials parameter or it's globalness\r
-       Client client(device, g_materials,\r
-                       g_client_delete_unused_sectors_timeout,\r
-                       playername);\r
-       \r
-       Address connect_address(0,0,0,0, port);\r
-       try{\r
-               connect_address.Resolve(connect_name);\r
-       }\r
-       catch(ResolveError &e)\r
-       {\r
-               std::cout<<DTIME<<"Couldn't resolve address"<<std::endl;\r
-               return 0;\r
-       }\r
-       \r
-       std::cout<<DTIME<<"Connecting to server..."<<std::endl;\r
-       client.connect(connect_address);\r
-       \r
-       try{\r
-               while(client.connectedAndInitialized() == false)\r
-               {\r
-                       client.step(0.1);\r
-                       if(server != NULL){\r
-                               server->step(0.1);\r
-                       }\r
-                       sleep_ms(100);\r
-               }\r
-       }\r
-       catch(con::PeerNotFoundException &e)\r
-       {\r
-               std::cout<<DTIME<<"Timed out."<<std::endl;\r
-               return 0;\r
-       }\r
-       \r
        /*\r
-               Create the camera node\r
+               If an error occurs, this is set to something and the\r
+               menu-game loop is restarted. It is then displayed before\r
+               the menu.\r
        */\r
+       std::wstring error_message = L"";\r
 \r
-       scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(\r
-               0, // Camera parent\r
-               v3f(BS*100, BS*2, BS*100), // Look from\r
-               v3f(BS*100+1, BS*2, BS*100), // Look to\r
-               -1 // Camera ID\r
-       );\r
-\r
-       if(camera == NULL)\r
-               return 1;\r
-       \r
-       video::SColor skycolor = video::SColor(255,90,140,200);\r
-\r
-       camera->setFOV(FOV_ANGLE);\r
-\r
-       // Just so big a value that everything rendered is visible\r
-       camera->setFarValue(100000*BS);\r
-\r
-       /*//f32 range = BS*HEIGHTMAP_RANGE_NODES*0.9;\r
-       f32 range = BS*HEIGHTMAP_RANGE_NODES*0.9;\r
-       \r
-       camera->setFarValue(range);\r
-       \r
-       driver->setFog(\r
-               skycolor,\r
-               video::EFT_FOG_LINEAR,\r
-               range*0.8,\r
-               range,\r
-               0.01,\r
-               false,\r
-               false\r
-               );*/\r
-       \r
-       f32 camera_yaw = 0; // "right/left"\r
-       f32 camera_pitch = 0; // "up/down"\r
-       \r
-       gui_loadingtext->remove();\r
-\r
-       /*\r
-               Add some gui stuff\r
-       */\r
-       \r
-       // First line of debug text\r
-       gui::IGUIStaticText *guitext = guienv->addStaticText(\r
-                       L"Minetest-c55",\r
-                       core::rect<s32>(5, 5, 5+600, 5+textsize.Y),\r
-                       false, false);\r
-       // Second line of debug text\r
-       gui::IGUIStaticText *guitext2 = guienv->addStaticText(\r
-                       L"",\r
-                       core::rect<s32>(5, 5+(textsize.Y+5)*1, 5+600, (5+textsize.Y)*2),\r
-                       false, false);\r
-       \r
-       // At the middle of the screen\r
-       // Object infos are shown in this\r
-       gui::IGUIStaticText *guitext_info = guienv->addStaticText(\r
-                       L"test",\r
-                       core::rect<s32>(100, 70, 100+400, 70+(textsize.Y+5)),\r
-                       false, false);\r
-       \r
-       // This is a copy of the inventory that the client's environment has\r
-       Inventory local_inventory(PLAYER_INVENTORY_SIZE);\r
-       \r
-       GUIQuickInventory *quick_inventory = new GUIQuickInventory\r
-                       (guienv, NULL, v2s32(10, 70), 5, &local_inventory);\r
-       \r
-       /*\r
-               Some statistics are collected in these\r
-       */\r
-       u32 drawtime = 0;\r
-       u32 scenetime = 0;\r
-       u32 endscenetime = 0;\r
+       // The password entered during the menu screen,\r
+       std::string password;\r
 \r
        /*\r
-               Text input system\r
+               Menu-game loop\r
        */\r
-       \r
-       struct TextDest\r
-       {\r
-               virtual void sendText(std::string text) = 0;\r
-       };\r
-       \r
-       struct TextDestSign : public TextDest\r
+       while(device->run() && kill == false)\r
        {\r
-               TextDestSign(v3s16 blockpos, s16 id, Client *client)\r
-               {\r
-                       m_blockpos = blockpos;\r
-                       m_id = id;\r
-                       m_client = client;\r
-               }\r
-               void sendText(std::string text)\r
-               {\r
-                       dstream<<"Changing text of a sign object: "\r
-                                       <<text<<std::endl;\r
-                       m_client->sendSignText(m_blockpos, m_id, text);\r
-               }\r
-\r
-               v3s16 m_blockpos;\r
-               s16 m_id;\r
-               Client *m_client;\r
-       };\r
-\r
-       TextDest *textbuf_dest = NULL;\r
-       \r
-       //gui::IGUIWindow* input_window = NULL;\r
-       gui::IGUIStaticText* input_guitext = NULL;\r
-\r
-       /*\r
-               Main loop\r
-       */\r
-\r
-       bool first_loop_after_window_activation = true;\r
 \r
-       // Time is in milliseconds\r
-       // NOTE: getRealTime() without run()s causes strange problems in wine\r
-       // NOTE: Have to call run() between calls of this to update the timer\r
-       u32 lasttime = device->getTimer()->getTime();\r
-\r
-       while(device->run())\r
-       {\r
-               // Hilight boxes collected during the loop and displayed\r
-               core::list< core::aabbox3d<f32> > hilightboxes;\r
-               \r
-               // Info text\r
-               std::wstring infotext;\r
-\r
-               //TimeTaker //timer1("//timer1", device);\r
-               \r
-               // Time of frame without fps limit\r
-               float busytime;\r
-               u32 busytime_u32;\r
+               // This is used for catching disconnects\r
+               try\r
                {\r
-                       // not using getRealTime is necessary for wine\r
-                       u32 time = device->getTimer()->getTime();\r
-                       if(time > lasttime)\r
-                               busytime_u32 = time - lasttime;\r
-                       else\r
-                               busytime_u32 = 0;\r
-                       busytime = busytime_u32 / 1000.0;\r
-               }\r
 \r
-               //std::cout<<"busytime_u32="<<busytime_u32<<std::endl;\r
-       \r
-               // Absolutelu necessary for wine!\r
-               device->run();\r
-\r
-               /*\r
-                       Viewing range\r
-               */\r
-               \r
-               //updateViewingRange(dtime, &client);\r
-               updateViewingRange(busytime, &client);\r
-               \r
-               /*\r
-                       FPS limiter\r
-               */\r
-\r
-               {\r
-                       float fps_max = g_fps_max;\r
-                       u32 frametime_min = 1000./fps_max;\r
+                       /*\r
+                               Clear everything from the GUIEnvironment\r
+                       */\r
+                       guienv->clear();\r
                        \r
-                       if(busytime_u32 < frametime_min)\r
-                       {\r
-                               u32 sleeptime = frametime_min - busytime_u32;\r
-                               device->sleep(sleeptime);\r
-                       }\r
-               }\r
-\r
-               // Absolutelu necessary for wine!\r
-               device->run();\r
-\r
-               /*\r
-                       Time difference calculation\r
-               */\r
-               f32 dtime; // in seconds\r
-               \r
-               u32 time = device->getTimer()->getTime();\r
-               if(time > lasttime)\r
-                       dtime = (time - lasttime) / 1000.0;\r
-               else\r
-                       dtime = 0;\r
-               lasttime = time;\r
-\r
-               /*\r
-                       Time average and jitter calculation\r
-               */\r
-\r
-               static f32 dtime_avg1 = 0.0;\r
-               dtime_avg1 = dtime_avg1 * 0.98 + dtime * 0.02;\r
-               f32 dtime_jitter1 = dtime - dtime_avg1;\r
+                       /*\r
+                               We need some kind of a root node to be able to add\r
+                               custom gui elements directly on the screen.\r
+                               Otherwise they won't be automatically drawn.\r
+                       */\r
+                       guiroot = guienv->addStaticText(L"",\r
+                                       core::rect<s32>(0, 0, 10000, 10000));\r
+                       \r
+                       /*\r
+                               Out-of-game menu loop.\r
 \r
-               static f32 dtime_jitter1_max_sample = 0.0;\r
-               static f32 dtime_jitter1_max_fraction = 0.0;\r
-               {\r
-                       static f32 jitter1_max = 0.0;\r
-                       static f32 counter = 0.0;\r
-                       if(dtime_jitter1 > jitter1_max)\r
-                               jitter1_max = dtime_jitter1;\r
-                       counter += dtime;\r
-                       if(counter > 0.0)\r
+                               Loop quits when menu returns proper parameters.\r
+                       */\r
+                       while(kill == false)\r
                        {\r
-                               counter -= 3.0;\r
-                               dtime_jitter1_max_sample = jitter1_max;\r
-                               dtime_jitter1_max_fraction\r
-                                               = dtime_jitter1_max_sample / (dtime_avg1+0.001);\r
-                               jitter1_max = 0.0;\r
+                               // Cursor can be non-visible when coming from the game\r
+                               device->getCursorControl()->setVisible(true);\r
+                               // Some stuff are left to scene manager when coming from the game\r
+                               // (map at least?)\r
+                               smgr->clear();\r
+                               // Reset or hide the debug gui texts\r
+                               /*guitext->setText(L"Minetest-c55");\r
+                               guitext2->setVisible(false);\r
+                               guitext_info->setVisible(false);\r
+                               guitext_chat->setVisible(false);*/\r
                                \r
-                               /*\r
-                                       Control freetime ratio\r
-                               */\r
-                               /*if(dtime_jitter1_max_fraction > DTIME_JITTER_MAX_FRACTION)\r
+                               // Initialize menu data\r
+                               MainMenuData menudata;\r
+                               menudata.address = narrow_to_wide(address);\r
+                               menudata.name = narrow_to_wide(playername);\r
+                               menudata.port = narrow_to_wide(itos(port));\r
+                               menudata.fancy_trees = g_settings.getBool("new_style_leaves");\r
+                               menudata.smooth_lighting = g_settings.getBool("smooth_lighting");\r
+                               menudata.creative_mode = g_settings.getBool("creative_mode");\r
+                               menudata.enable_damage = g_settings.getBool("enable_damage");\r
+\r
+                               GUIMainMenu *menu =\r
+                                               new GUIMainMenu(guienv, guiroot, -1, \r
+                                                       &g_menumgr, &menudata, g_gamecallback);\r
+                               menu->allowFocusRemoval(true);\r
+\r
+                               if(error_message != L"")\r
                                {\r
-                                       if(g_freetime_ratio < FREETIME_RATIO_MAX)\r
-                                               g_freetime_ratio += 0.01;\r
+                                       dstream<<"WARNING: error_message = "\r
+                                                       <<wide_to_narrow(error_message)<<std::endl;\r
+\r
+                                       GUIMessageMenu *menu2 =\r
+                                                       new GUIMessageMenu(guienv, guiroot, -1, \r
+                                                               &g_menumgr, error_message.c_str());\r
+                                       menu2->drop();\r
+                                       error_message = L"";\r
                                }\r
-                               else\r
-                               {\r
-                                       if(g_freetime_ratio > FREETIME_RATIO_MIN)\r
-                                               g_freetime_ratio -= 0.01;\r
-                               }*/\r
-                       }\r
-               }\r
-               \r
-               /*\r
-                       Busytime average and jitter calculation\r
-               */\r
-\r
-               static f32 busytime_avg1 = 0.0;\r
-               busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;\r
-               f32 busytime_jitter1 = busytime - busytime_avg1;\r
-               \r
-               static f32 busytime_jitter1_max_sample = 0.0;\r
-               static f32 busytime_jitter1_min_sample = 0.0;\r
-               {\r
-                       static f32 jitter1_max = 0.0;\r
-                       static f32 jitter1_min = 0.0;\r
-                       static f32 counter = 0.0;\r
-                       if(busytime_jitter1 > jitter1_max)\r
-                               jitter1_max = busytime_jitter1;\r
-                       if(busytime_jitter1 < jitter1_min)\r
-                               jitter1_min = busytime_jitter1;\r
-                       counter += dtime;\r
-                       if(counter > 0.0){\r
-                               counter -= 3.0;\r
-                               busytime_jitter1_max_sample = jitter1_max;\r
-                               busytime_jitter1_min_sample = jitter1_min;\r
-                               jitter1_max = 0.0;\r
-                               jitter1_min = 0.0;\r
-                       }\r
-               }\r
-               \r
-               /*\r
-                       Debug info for client\r
-               */\r
-               {\r
-                       static float counter = 0.0;\r
-                       counter -= dtime;\r
-                       if(counter < 0)\r
-                       {\r
-                               counter = 30.0;\r
-                               client.printDebugInfo(std::cout);\r
-                       }\r
-               }\r
-\r
-               /*\r
-                       Input handler step()\r
-               */\r
-               g_input->step(dtime);\r
-\r
-               /*\r
-                       Special keys\r
-               */\r
-               if(g_esc_pressed)\r
-               {\r
-                       break;\r
-               }\r
-\r
-               /*\r
-                       Player speed control\r
-               */\r
-               \r
-               if(g_game_focused)\r
-               {\r
-                       /*bool a_up,\r
-                       bool a_down,\r
-                       bool a_left,\r
-                       bool a_right,\r
-                       bool a_jump,\r
-                       bool a_superspeed,\r
-                       float a_pitch,\r
-                       float a_yaw*/\r
-                       PlayerControl control(\r
-                               g_input->isKeyDown(irr::KEY_KEY_W),\r
-                               g_input->isKeyDown(irr::KEY_KEY_S),\r
-                               g_input->isKeyDown(irr::KEY_KEY_A),\r
-                               g_input->isKeyDown(irr::KEY_KEY_D),\r
-                               g_input->isKeyDown(irr::KEY_SPACE),\r
-                               g_input->isKeyDown(irr::KEY_KEY_2),\r
-                               camera_pitch,\r
-                               camera_yaw\r
-                       );\r
-                       client.setPlayerControl(control);\r
-               }\r
-               else\r
-               {\r
-                       // Set every key to inactive\r
-                       PlayerControl control;\r
-                       client.setPlayerControl(control);\r
-               }\r
-\r
-               //timer1.stop();\r
-               /*\r
-                       Process environment\r
-               */\r
-               \r
-               {\r
-                       //TimeTaker timer("client.step(dtime)", device);\r
-                       client.step(dtime);\r
-                       //client.step(dtime_avg1);\r
-               }\r
-\r
-               if(server != NULL)\r
-               {\r
-                       //TimeTaker timer("server->step(dtime)", device);\r
-                       server->step(dtime);\r
-               }\r
-\r
-               v3f player_position = client.getPlayerPosition();\r
-               \r
-               //TimeTaker //timer2("//timer2", device);\r
-\r
-               /*\r
-                       Mouse and camera control\r
-               */\r
-               \r
-               if(device->isWindowActive() && g_game_focused)\r
-               {\r
-                       device->getCursorControl()->setVisible(false);\r
-\r
-                       if(first_loop_after_window_activation){\r
-                               //std::cout<<"window active, first loop"<<std::endl;\r
-                               first_loop_after_window_activation = false;\r
-                       }\r
-                       else{\r
-                               s32 dx = g_input->getMousePos().X - 320;\r
-                               s32 dy = g_input->getMousePos().Y - 240;\r
-                               //std::cout<<"window active, pos difference "<<dx<<","<<dy<<std::endl;\r
-                               camera_yaw -= dx*0.2;\r
-                               camera_pitch += dy*0.2;\r
-                               if(camera_pitch < -89.5) camera_pitch = -89.5;\r
-                               if(camera_pitch > 89.5) camera_pitch = 89.5;\r
-                       }\r
-                       g_input->setMousePos(320, 240);\r
-               }\r
-               else{\r
-                       device->getCursorControl()->setVisible(true);\r
-\r
-                       //std::cout<<"window inactive"<<std::endl;\r
-                       first_loop_after_window_activation = true;\r
-               }\r
-\r
-               camera_yaw = wrapDegrees(camera_yaw);\r
-               camera_pitch = wrapDegrees(camera_pitch);\r
-               \r
-               v3f camera_direction = v3f(0,0,1);\r
-               camera_direction.rotateYZBy(camera_pitch);\r
-               camera_direction.rotateXZBy(camera_yaw);\r
-\r
-               v3f camera_position =\r
-                               player_position + v3f(0, BS+BS/2, 0);\r
 \r
-               camera->setPosition(camera_position);\r
-               // *100.0 helps in large map coordinates\r
-               camera->setTarget(camera_position + camera_direction * 100.0);\r
-\r
-               if(FIELD_OF_VIEW_TEST){\r
-                       //client.m_env.getMap().updateCamera(v3f(0,0,0), v3f(0,0,1));\r
-                       client.updateCamera(v3f(0,0,0), v3f(0,0,1));\r
-               }\r
-               else{\r
-                       //client.m_env.getMap().updateCamera(camera_position, camera_direction);\r
-                       //TimeTaker timer("client.updateCamera", device);\r
-                       client.updateCamera(camera_position, camera_direction);\r
-               }\r
-               \r
-               //timer2.stop();\r
-               //TimeTaker //timer3("//timer3", device);\r
-\r
-               /*\r
-                       Calculate what block is the crosshair pointing to\r
-               */\r
-               \r
-               //u32 t1 = device->getTimer()->getRealTime();\r
-               \r
-               //f32 d = 4; // max. distance\r
-               f32 d = 4; // max. distance\r
-               core::line3d<f32> shootline(camera_position,\r
-                               camera_position + camera_direction * BS * (d+1));\r
-\r
-               MapBlockObject *selected_object = client.getSelectedObject\r
-                               (d*BS, camera_position, shootline);\r
+                               video::IVideoDriver* driver = device->getVideoDriver();\r
+                               \r
+                               dstream<<"Created main menu"<<std::endl;\r
 \r
-               if(selected_object != NULL)\r
-               {\r
-                       //dstream<<"Client returned selected_object != NULL"<<std::endl;\r
+                               while(device->run() && kill == false)\r
+                               {\r
+                                       if(menu->getStatus() == true)\r
+                                               break;\r
 \r
-                       core::aabbox3d<f32> box_on_map\r
-                                       = selected_object->getSelectionBoxOnMap();\r
+                                       //driver->beginScene(true, true, video::SColor(255,0,0,0));\r
+                                       driver->beginScene(true, true, video::SColor(255,128,128,128));\r
 \r
-                       hilightboxes.push_back(box_on_map);\r
+                                       drawMenuBackground(driver);\r
 \r
-                       infotext = narrow_to_wide(selected_object->infoText());\r
+                                       guienv->drawAll();\r
+                                       \r
+                                       driver->endScene();\r
+                                       \r
+                                       // On some computers framerate doesn't seem to be\r
+                                       // automatically limited\r
+                                       sleep_ms(25);\r
+                               }\r
+                               \r
+                               // Break out of menu-game loop to shut down cleanly\r
+                               if(device->run() == false || kill == true)\r
+                                       break;\r
+                               \r
+                               dstream<<"Dropping main menu"<<std::endl;\r
 \r
-                       if(g_input->getLeftClicked())\r
-                       {\r
-                               std::cout<<DTIME<<"Left-clicked object"<<std::endl;\r
-                               client.clickObject(0, selected_object->getBlock()->getPos(),\r
-                                               selected_object->getId(), g_selected_item);\r
-                       }\r
-                       else if(g_input->getRightClicked())\r
-                       {\r
-                               std::cout<<DTIME<<"Right-clicked object"<<std::endl;\r
-                               /*\r
-                                       Check if we want to modify the object ourselves\r
-                               */\r
-                               if(selected_object->getTypeId() == MAPBLOCKOBJECT_TYPE_SIGN)\r
+                               menu->drop();\r
+                               \r
+                               // Delete map if requested\r
+                               if(menudata.delete_map)\r
                                {\r
-                                       dstream<<"Sign object right-clicked"<<std::endl;\r
-\r
-                                       unFocusGame();\r
+                                       bool r = fs::RecursiveDeleteContent(map_dir);\r
+                                       if(r == false)\r
+                                               error_message = L"Delete failed";\r
+                                       continue;\r
+                               }\r
 \r
-                                       input_guitext = guienv->addStaticText(L"",\r
-                                                       core::rect<s32>(150,100,350,120),\r
-                                                       true, // border?\r
-                                                       false, // wordwrap?\r
-                                                       NULL);\r
+                               playername = wide_to_narrow(menudata.name);\r
 \r
-                                       input_guitext->setDrawBackground(true);\r
+                               password = translatePassword(playername, menudata.password);\r
 \r
-                                       g_text_buffer = L"";\r
-                                       g_text_buffer_accepted = false;\r
-                                       textbuf_dest = new TextDestSign(\r
-                                                       selected_object->getBlock()->getPos(),\r
-                                                       selected_object->getId(),\r
-                                                       &client);\r
-                               }\r
-                               /*\r
-                                       Otherwise pass the event to the server as-is\r
-                               */\r
-                               else\r
+                               address = wide_to_narrow(menudata.address);\r
+                               int newport = stoi(wide_to_narrow(menudata.port));\r
+                               if(newport != 0)\r
+                                       port = newport;\r
+                               g_settings.set("new_style_leaves", itos(menudata.fancy_trees));\r
+                               g_settings.set("smooth_lighting", itos(menudata.smooth_lighting));\r
+                               g_settings.set("creative_mode", itos(menudata.creative_mode));\r
+                               g_settings.set("enable_damage", itos(menudata.enable_damage));\r
+                               \r
+                               // Check for valid parameters, restart menu if invalid.\r
+                               if(playername == "")\r
                                {\r
-                                       client.clickObject(1, selected_object->getBlock()->getPos(),\r
-                                                       selected_object->getId(), g_selected_item);\r
-                               }\r
-                       }\r
-               }\r
-               else // selected_object == NULL\r
-               {\r
-               \r
-               bool nodefound = false;\r
-               v3s16 nodepos;\r
-               v3s16 neighbourpos;\r
-               core::aabbox3d<f32> nodefacebox;\r
-               f32 mindistance = BS * 1001;\r
-               \r
-               v3s16 pos_i = floatToInt(player_position);\r
-\r
-               /*std::cout<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"\r
-                               <<std::endl;*/\r
-\r
-               s16 a = d;\r
-               s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);\r
-               s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);\r
-               s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);\r
-               s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);\r
-               s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);\r
-               s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);\r
-               \r
-               for(s16 y = ystart; y <= yend; y++){\r
-               for(s16 z = zstart; z <= zend; z++){\r
-               for(s16 x = xstart; x <= xend; x++)\r
-               {\r
-                       try{\r
-                               if(client.getNode(v3s16(x,y,z)).d == MATERIAL_AIR){\r
+                                       error_message = L"Name required.";\r
                                        continue;\r
                                }\r
-                       }catch(InvalidPositionException &e){\r
-                               continue;\r
-                       }\r
-\r
-                       v3s16 np(x,y,z);\r
-                       v3f npf = intToFloat(np);\r
-                       \r
-                       f32 d = 0.01;\r
-                       \r
-                       v3s16 directions[6] = {\r
-                               v3s16(0,0,1), // back\r
-                               v3s16(0,1,0), // top\r
-                               v3s16(1,0,0), // right\r
-                               v3s16(0,0,-1),\r
-                               v3s16(0,-1,0),\r
-                               v3s16(-1,0,0),\r
-                       };\r
-\r
-                       for(u16 i=0; i<6; i++){\r
-                       //{u16 i=3;\r
-                               v3f dir_f = v3f(directions[i].X,\r
-                                               directions[i].Y, directions[i].Z);\r
-                               v3f centerpoint = npf + dir_f * BS/2;\r
-                               f32 distance =\r
-                                               (centerpoint - camera_position).getLength();\r
                                \r
-                               if(distance < mindistance){\r
-                                       //std::cout<<DTIME<<"for centerpoint=("<<centerpoint.X<<","<<centerpoint.Y<<","<<centerpoint.Z<<"): distance < mindistance"<<std::endl;\r
-                                       //std::cout<<DTIME<<"npf=("<<npf.X<<","<<npf.Y<<","<<npf.Z<<")"<<std::endl;\r
-                                       core::CMatrix4<f32> m;\r
-                                       m.buildRotateFromTo(v3f(0,0,1), dir_f);\r
-\r
-                                       // This is the back face\r
-                                       v3f corners[2] = {\r
-                                               v3f(BS/2, BS/2, BS/2),\r
-                                               v3f(-BS/2, -BS/2, BS/2+d)\r
-                                       };\r
-                                       \r
-                                       for(u16 j=0; j<2; j++){\r
-                                               m.rotateVect(corners[j]);\r
-                                               corners[j] += npf;\r
-                                               //std::cout<<DTIME<<"box corners["<<j<<"]: ("<<corners[j].X<<","<<corners[j].Y<<","<<corners[j].Z<<")"<<std::endl;\r
-                                       }\r
-\r
-                                       //core::aabbox3d<f32> facebox(corners[0],corners[1]);\r
-                                       core::aabbox3d<f32> facebox(corners[0]);\r
-                                       facebox.addInternalPoint(corners[1]);\r
-\r
-                                       if(facebox.intersectsWithLine(shootline)){\r
-                                               nodefound = true;\r
-                                               nodepos = np;\r
-                                               neighbourpos = np + directions[i];\r
-                                               mindistance = distance;\r
-                                               nodefacebox = facebox;\r
-                                       }\r
-                               }\r
-                       }\r
-               }}}\r
-\r
-               if(nodefound)\r
-               {\r
-                       //std::cout<<DTIME<<"nodefound == true"<<std::endl;\r
-                       //std::cout<<DTIME<<"nodepos=("<<nodepos.X<<","<<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;\r
-                       //std::cout<<DTIME<<"neighbourpos=("<<neighbourpos.X<<","<<neighbourpos.Y<<","<<neighbourpos.Z<<")"<<std::endl;\r
-\r
-                       static v3s16 nodepos_old(-1,-1,-1);\r
-                       if(nodepos != nodepos_old){\r
-                               std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","\r
-                                               <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;\r
-                               nodepos_old = nodepos;\r
-\r
-                               /*wchar_t positiontext[20];\r
-                               swprintf(positiontext, 20, L"(%i,%i,%i)",\r
-                                               nodepos.X, nodepos.Y, nodepos.Z);\r
-                               positiontextgui->setText(positiontext);*/\r
-                       }\r
-\r
-                       hilightboxes.push_back(nodefacebox);\r
+                               // Save settings\r
+                               g_settings.set("name", playername);\r
+                               g_settings.set("address", address);\r
+                               g_settings.set("port", itos(port));\r
+                               // Update configuration file\r
+                               if(configpath != "")\r
+                                       g_settings.updateConfigFile(configpath.c_str());\r
                        \r
-                       if(g_input->getLeftClicked())\r
-                       {\r
-                               //std::cout<<DTIME<<"Removing node"<<std::endl;\r
-                               //client.removeNode(nodepos);\r
-                               std::cout<<DTIME<<"Ground left-clicked"<<std::endl;\r
-                               client.clickGround(0, nodepos, neighbourpos, g_selected_item);\r
-                       }\r
-                       if(g_input->getRightClicked())\r
-                       {\r
-                               //std::cout<<DTIME<<"Placing node"<<std::endl;\r
-                               //client.addNodeFromInventory(neighbourpos, g_selected_item);\r
-                               std::cout<<DTIME<<"Ground right-clicked"<<std::endl;\r
-                               client.clickGround(1, nodepos, neighbourpos, g_selected_item);\r
+                               // Continue to game\r
+                               break;\r
                        }\r
-               }\r
-               else{\r
-                       //std::cout<<DTIME<<"nodefound == false"<<std::endl;\r
-                       //positiontextgui->setText(L"");\r
-               }\r
-\r
-               } // selected_object == NULL\r
-               \r
-               g_input->resetLeftClicked();\r
-               g_input->resetRightClicked();\r
-               \r
-               /*\r
-                       Calculate stuff for drawing\r
-               */\r
-\r
-               v2u32 screensize = driver->getScreenSize();\r
-               core::vector2d<s32> displaycenter(screensize.X/2,screensize.Y/2);\r
-\r
-               camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);\r
-\r
-               /*\r
-                       Update gui stuff (0ms)\r
-               */\r
-\r
-               //TimeTaker guiupdatetimer("Gui updating", device);\r
-               \r
-               {\r
-                       wchar_t temptext[100];\r
-\r
-                       static float drawtime_avg = 0;\r
-                       drawtime_avg = drawtime_avg * 0.98 + (float)drawtime*0.02;\r
-                       static float scenetime_avg = 0;\r
-                       scenetime_avg = scenetime_avg * 0.98 + (float)scenetime*0.02;\r
-                       static float endscenetime_avg = 0;\r
-                       endscenetime_avg = endscenetime_avg * 0.98 + (float)endscenetime*0.02;\r
-                       \r
-                       swprintf(temptext, 100, L"Minetest-c55 ("\r
-                                       L"F: item=%i"\r
-                                       L", R: range_all=%i"\r
-                                       L")"\r
-                                       L" drawtime=%.0f, scenetime=%.0f, endscenetime=%.0f",\r
-                                       g_selected_item,\r
-                                       g_viewing_range_all,\r
-                                       drawtime_avg,\r
-                                       scenetime_avg,\r
-                                       endscenetime_avg\r
-                                       );\r
-                       \r
-                       guitext->setText(temptext);\r
-               }\r
-               \r
-               {\r
-                       wchar_t temptext[100];\r
-                       /*swprintf(temptext, 100,\r
-                                       L"("\r
-                                       L"% .3f < btime_jitter < % .3f"\r
-                                       L", dtime_jitter = % .1f %%"\r
-                                       //L", ftime_ratio = % .3f"\r
-                                       L")",\r
-                                       busytime_jitter1_min_sample,\r
-                                       busytime_jitter1_max_sample,\r
-                                       dtime_jitter1_max_fraction * 100.0\r
-                                       //g_freetime_ratio\r
-                                       );*/\r
-                       swprintf(temptext, 100,\r
-                                       L"(% .1f, % .1f, % .1f)"\r
-                                       L" (% .3f < btime_jitter < % .3f"\r
-                                       L", dtime_jitter = % .1f %%)",\r
-                                       player_position.X/BS,\r
-                                       player_position.Y/BS,\r
-                                       player_position.Z/BS,\r
-                                       busytime_jitter1_min_sample,\r
-                                       busytime_jitter1_max_sample,\r
-                                       dtime_jitter1_max_fraction * 100.0\r
-                                       );\r
-\r
-                       guitext2->setText(temptext);\r
-               }\r
-               \r
-               {\r
-                       /*wchar_t temptext[100];\r
-                       swprintf(temptext, 100,\r
-                                       SWPRINTF_CHARSTRING,\r
-                                       infotext.substr(0,99).c_str()\r
-                                       );\r
-\r
-                       guitext_info->setText(temptext);*/\r
-\r
-                       guitext_info->setText(infotext.c_str());\r
-               }\r
-\r
-               /*\r
-                       Inventory\r
-               */\r
-               \r
-               static u16 old_selected_item = 65535;\r
-               if(client.getLocalInventoryUpdated()\r
-                               || g_selected_item != old_selected_item)\r
-               {\r
-                       old_selected_item = g_selected_item;\r
-                       //std::cout<<"Updating local inventory"<<std::endl;\r
-                       client.getLocalInventory(local_inventory);\r
-                       quick_inventory->setSelection(g_selected_item);\r
-                       quick_inventory->update();\r
-               }\r
-\r
-               if(input_guitext != NULL)\r
-               {\r
-                       /*wchar_t temptext[100];\r
-                       swprintf(temptext, 100,\r
-                                       SWPRINTF_CHARSTRING,\r
-                                       g_text_buffer.substr(0,99).c_str()\r
-                                       );*/\r
-                       input_guitext->setText(g_text_buffer.c_str());\r
-               }\r
-\r
-               /*\r
-                       Text input stuff\r
-               */\r
-               if(input_guitext != NULL && g_text_buffer_accepted)\r
-               {\r
-                       input_guitext->remove();\r
-                       input_guitext = NULL;\r
                        \r
-                       if(textbuf_dest != NULL)\r
-                       {\r
-                               std::string text = wide_to_narrow(g_text_buffer);\r
-                               dstream<<"Sending text: "<<text<<std::endl;\r
-                               textbuf_dest->sendText(text);\r
-                               delete textbuf_dest;\r
-                               textbuf_dest = NULL;\r
-                       }\r
-\r
-                       focusGame();\r
-               }\r
-\r
-               //guiupdatetimer.stop();\r
-\r
-               /*\r
-                       Drawing begins\r
-               */\r
-\r
-               TimeTaker drawtimer("Drawing", device);\r
-\r
-               /*\r
-                       Background color is choosen based on whether the player is\r
-                       much beyond the initial ground level\r
-               */\r
-               /*video::SColor bgcolor;\r
-               v3s16 p0 = Map::floatToInt(player_position);\r
-               // Does this make short random delays?\r
-               // NOTE: no need for this, sky doesn't show underground with\r
-               // enough range\r
-               bool is_underground = client.isNodeUnderground(p0);\r
-               //bool is_underground = false;\r
-               if(is_underground == false)\r
-                       bgcolor = video::SColor(255,90,140,200);\r
-               else\r
-                       bgcolor = video::SColor(255,0,0,0);*/\r
+                       // Break out of menu-game loop to shut down cleanly\r
+                       if(device->run() == false)\r
+                               break;\r
                        \r
-               //video::SColor bgcolor = video::SColor(255,90,140,200);\r
-               video::SColor bgcolor = skycolor;\r
-               \r
-               // 0ms\r
-               driver->beginScene(true, true, bgcolor);\r
-\r
-               //timer3.stop();\r
-               \r
-               //std::cout<<DTIME<<"smgr->drawAll()"<<std::endl;\r
-               \r
-               {\r
-               TimeTaker timer("smgr", device);\r
-               smgr->drawAll();\r
-               scenetime = timer.stop(true);\r
-               }\r
-               \r
-               {\r
-               //TimeTaker timer9("auxiliary drawings", device);\r
-               // 0ms\r
-\r
-               driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),\r
-                               displaycenter + core::vector2d<s32>(10,0),\r
-                               video::SColor(255,255,255,255));\r
-               driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),\r
-                               displaycenter + core::vector2d<s32>(0,10),\r
-                               video::SColor(255,255,255,255));\r
-\r
-               //timer9.stop();\r
-               //TimeTaker //timer10("//timer10", device);\r
-               \r
-               video::SMaterial m;\r
-               m.Thickness = 10;\r
-               m.Lighting = false;\r
-               driver->setMaterial(m);\r
-\r
-               driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);\r
+                       // Initialize mapnode again to enable changed graphics settings\r
+                       init_mapnode();\r
+\r
+                       /*\r
+                               Run game\r
+                       */\r
+                       the_game(\r
+                               kill,\r
+                               random_input,\r
+                               input,\r
+                               device,\r
+                               font,\r
+                               map_dir,\r
+                               playername,\r
+                               password,\r
+                               address,\r
+                               port,\r
+                               error_message\r
+                       );\r
 \r
-               for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();\r
-                               i != hilightboxes.end(); i++)\r
+               } //try\r
+               catch(con::PeerNotFoundException &e)\r
                {\r
-                       /*std::cout<<"hilightbox min="\r
-                                       <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"\r
-                                       <<" max="\r
-                                       <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"\r
-                                       <<std::endl;*/\r
-                       driver->draw3DBox(*i, video::SColor(255,0,0,0));\r
-               }\r
-\r
+                       dstream<<DTIME<<"Connection error (timed out?)"<<std::endl;\r
+                       error_message = L"Connection error (timed out?)";\r
                }\r
-\r
-               //timer10.stop();\r
-               //TimeTaker //timer11("//timer11", device);\r
-\r
-               /*\r
-                       Draw gui\r
-               */\r
-               // 0-1ms\r
-               guienv->drawAll();\r
-               \r
-               // End drawing\r
+               catch(SocketException &e)\r
                {\r
-               TimeTaker timer("endScene", device);\r
-               driver->endScene();\r
-               endscenetime = timer.stop(true);\r
+                       dstream<<DTIME<<"Socket error (port already in use?)"<<std::endl;\r
+                       error_message = L"Socket error (port already in use?)";\r
                }\r
-\r
-               drawtime = drawtimer.stop(true);\r
-\r
-               /*\r
-                       Drawing ends\r
-               */\r
-               \r
-               static s16 lastFPS = 0;\r
-               //u16 fps = driver->getFPS();\r
-               u16 fps = (1.0/dtime_avg1);\r
-\r
-               if (lastFPS != fps)\r
+#ifdef NDEBUG\r
+               catch(std::exception &e)\r
                {\r
-                       core::stringw str = L"Minetest [";\r
-                       str += driver->getName();\r
-                       str += "] FPS:";\r
-                       str += fps;\r
-\r
-                       device->setWindowCaption(str.c_str());\r
-                       lastFPS = fps;\r
+                       std::string narrow_message = "Some exception, what()=\"";\r
+                       narrow_message += e.what();\r
+                       narrow_message += "\"";\r
+                       dstream<<DTIME<<narrow_message<<std::endl;\r
+                       error_message = narrow_to_wide(narrow_message);\r
                }\r
-               \r
-               /*}\r
-               else\r
-                       device->yield();*/\r
-       }\r
+#endif\r
 \r
-       } // client is deleted at this point\r
+       } // Menu-game loop\r
        \r
-       delete g_input;\r
+       delete input;\r
 \r
        /*\r
-       In the end, delete the Irrlicht device.\r
+               In the end, delete the Irrlicht device.\r
        */\r
        device->drop();\r
-\r
-       } //try\r
-       catch(con::PeerNotFoundException &e)\r
-       {\r
-               dstream<<DTIME<<"Connection timed out."<<std::endl;\r
-       }\r
-#if CATCH_EXCEPTIONS\r
-       /*\r
-               This is what has to be done in every thread to get suitable debug info\r
-       */\r
-       catch(std::exception &e)\r
-       {\r
-               dstream<<std::endl<<DTIME<<"An unhandled exception occurred: "\r
-                               <<e.what()<<std::endl;\r
-               assert(0);\r
-       }\r
-#endif\r
-\r
+       \r
+       END_DEBUG_EXCEPTION_HANDLER\r
+       \r
        debugstreams_deinit();\r
        \r
        return 0;\r