]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - src/main.cpp
Use the logger; also, default to not showing much crap in console. Use --info-on...
[dragonfireclient.git] / src / main.cpp
index 88a258dce27d5fea9869185ea0e37f11ab90bdc8..02cae0317858310073f7aed49e4186b583403ba0 100644 (file)
-/*\r
-Minetest-c55\r
-Copyright (C) 2010 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
-the Free Software Foundation; either version 2 of the License, or\r
-(at your option) any later version.\r
-\r
-This program is distributed in the hope that it will be useful,\r
-but WITHOUT ANY WARRANTY; without even the implied warranty of\r
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
-GNU General Public License for more details.\r
-\r
-You should have received a copy of the GNU General Public License along\r
-with this program; if not, write to the Free Software Foundation, Inc.,\r
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\r
-*/\r
-\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 (not sure)\r
-         - It is not a memory leak but some kind of a buffer.\r
-\r
-NOTE: iostream.imbue(std::locale("C")) is very slow\r
-NOTE: Global locale is now set at initialization\r
-\r
-SUGG: Fix address to be ipv6 compatible\r
-\r
-NOTE: 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
-SUGG: Use same technique for sector heightmaps as what we're\r
-      using for UnlimitedHeightmap? (getting all neighbors\r
-         when generating)\r
-\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
-\r
-SUGG: If player is on ground, mainly fetch ground-level blocks\r
-SUGG: Fetch stuff mainly from the viewing direction\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: More fine-grained control of client's dumping of blocks from\r
-      memory\r
-         - ...What does this mean in the first place?\r
-\r
-SUGG: A map editing mode (similar to dedicated server mode)\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
-\r
-SUGG: Make a copy of close-range environment on client for showing\r
-      on screen, with minimal mutexes to slow down the main loop\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
-\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
-\r
-SUGG: MovingObject::move and Player::move are basically the same.\r
-      combine them.\r
-         - NOTE: Player::move is more up-to-date.\r
-\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\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
-\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
-SUGG: Calculate lighting per vertex to get a lighting effect like in\r
-      bartwe's game\r
-\r
-Gaming ideas:\r
--------------\r
-\r
-- Aim for something like controlling a single dwarf in Dwarf Fortress\r
-\r
-- The player could go faster by a crafting a boat, or riding an animal\r
-\r
-- Random NPC traders. what else?\r
-\r
-Documentation:\r
---------------\r
-\r
-Build system / running:\r
------------------------\r
-\r
-FIXME: Some network errors on Windows that cause local game to not work\r
-       - See siggjen's emails.\r
-          - Is this the famous "windows 7 problem"?\r
-       - Apparently there might be other errors too\r
-\r
-Networking and serialization:\r
------------------------------\r
-\r
-TODO: Get rid of GotSplitPacketException\r
-\r
-GUI:\r
-----\r
-\r
-TODO: Add gui option to remove map\r
-\r
-TODO: Configuration menu, at least for keys\r
-\r
-Graphics:\r
----------\r
-\r
-TODO: Optimize day/night mesh updating somehow\r
-      - create copies of all textures for all lighting values and only\r
-           change texture for material?\r
-         - Umm... the collecting of the faces is the slow part\r
-           -> what about just changing the color values of the existing\r
-                  meshbuffers? It should go quite fast.\r
-                  - This is not easy; There'd need to be a buffer somewhere\r
-                    that would contain the night and day lighting values.\r
-                        - Actually if FastFaces would be stored, they could\r
-                          hold both values\r
-\r
-FEATURE: Combine MapBlock's face caches to so big pieces that VBO\r
-      gets 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
-TODO: 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
-NOTE(FIXED): A lock condition is possible:\r
-       1) MapBlock::updateMesh() is called from client asynchronously:\r
-          - AsyncProcessData() -> Map::updateMeshes()\r
-       2) Asynchronous locks m_temp_mods_mutex\r
-       3) MapBlock::updateMesh() is called from client synchronously:\r
-          - Client::step() -> Environment::step()\r
-       4) Synchronous starts waiting for m_temp_mods_mutex\r
-       5) Asynchronous calls getTexture, which starts waiting for main thread\r
-\r
-Configuration:\r
---------------\r
-\r
-TODO: Make the video backend selectable\r
-\r
-Client:\r
--------\r
-\r
-TODO: Untie client network operations from framerate\r
-      - Needs some input queues or something\r
-\r
-TODO: 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()\r
-\r
-Server:\r
--------\r
-\r
-TODO: When player dies, throw items on map\r
-\r
-TODO: Make an option to the server to disable building and digging near\r
-      the starting position\r
-\r
-TODO: Save players with inventories to disk\r
-TODO: Players to be saved as text in map/players/<name>\r
-\r
-TODO: Copy the text of the last picked sign to inventory in creative\r
-      mode\r
-\r
-TODO: Check what goes wrong with caching map to disk (Kray)\r
-      - Nothing?\r
-\r
-TODO: When server sees that client is removing an inexistent block to\r
-      an existent position, resend the MapBlock.\r
-\r
-FIXME: Server went into some infinite PeerNotFoundException loop\r
-\r
-Objects:\r
---------\r
-\r
-TODO: Better handling of objects and mobs\r
-      - Scripting?\r
-      - There has to be some way to do it with less messy code\r
-         - Make separate classes for client and server\r
-           - Client should not discriminate between blocks, server should\r
-           - Make other players utilize the same framework\r
-               - This is also needed for objects that don't get sent to client\r
-                 but are used for triggers etc\r
-\r
-TODO: There has to be some better way to handle static objects than to\r
-      send them all the time. This affects signs and item objects.\r
-SUGG: Signs could be done in the same way as torches. For this, blocks\r
-      need an additional metadata field for the texts\r
-         - This is also needed for item container chests\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: A global active buffer is needed for the server\r
-         - TODO: A timestamp to blocks\r
-      - TODO: All blocks going in and out of the buffer are recorded.\r
-           - TODO: For outgoing blocks, timestamp is written.\r
-           - TODO: For incoming blocks, time difference is calculated and\r
-             objects are stepped according to it.\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
-\r
-TODO: Remove duplicate lighting implementation from Map (leave\r
-      VoxelManipulator, which is faster)\r
-\r
-FEATURE: Create a system that allows a huge amount of different "map\r
-            generator modules/filters"\r
-\r
-FEATURE: 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
-Doing now (most important at the top):\r
---------------------------------------\r
-# maybe done\r
-* not done\r
-\r
-=== Fixmes\r
-* Make server find the spawning place from the real map data, not from\r
-  the heightmap\r
-  - But the changing borders of chunk have to be avoided, because\r
-    there is time to generate only one chunk.\r
-* Make the generator to run in background and not blocking block\r
-  placement and transfer\r
-* only_from_disk might not work anymore - check and fix it.\r
-* Check the fixmes in the list above\r
-* When sending blocks to the client, the server takes way too much\r
-  CPU time (20-30% for single player), find out what it is doing.\r
-  - Make a simple profiler\r
-\r
-=== Making it more portable\r
-* Some MSVC: std::sto* are defined without a namespace and collide\r
-  with the ones in utility.h\r
-\r
-=== Features\r
-* Make an "environment metafile" to store at least time of day\r
-* Move digging property stuff from material.{h,cpp} to mapnode.cpp...\r
-  - Or maybe move content_features to material.{h,cpp}?\r
-* Add some kind of erosion and other stuff that now is possible\r
-* Make client to fetch stuff asynchronously\r
-  - Needs method SyncProcessData\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
-* Water doesn't start flowing after map generation like it should\r
-  - Are there still problems?\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.\r
-* Make a small history check to transformLiquids to detect and log\r
-  continuous oscillations, in such detail that they can be fixed.\r
-* Combine meshes to bigger ones in ClientMap and set them EHM_STATIC\r
-\r
-======================================================================\r
-\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
-\r
-       This allows one to move around with the player and see what\r
-       is actually drawn behind solid things and behind the player.\r
-*/\r
-#define FIELD_OF_VIEW_TEST 0\r
-\r
-#ifdef NDEBUG\r
-       #ifdef _WIN32\r
-               #pragma message ("Disabling unit tests")\r
-       #else\r
-               #warning "Disabling unit tests"\r
-       #endif\r
-       // Disable unit tests\r
-       #define ENABLE_TESTS 0\r
-#else\r
-       // Enable unit tests\r
-       #define ENABLE_TESTS 1\r
-#endif\r
-\r
-#ifdef _MSC_VER\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 <jmutexautolock.h>\r
-#include <locale.h>\r
-#include "common_irrlicht.h"\r
-#include "debug.h"\r
-#include "map.h"\r
-#include "player.h"\r
-#include "main.h"\r
-#include "test.h"\r
-#include "environment.h"\r
-#include "server.h"\r
-#include "client.h"\r
-#include "serialization.h"\r
-#include "constants.h"\r
-#include "strfnd.h"\r
-#include "porting.h"\r
-#include "irrlichtwrapper.h"\r
-#include "gettime.h"\r
-#include "porting.h"\r
-#include "guiPauseMenu.h"\r
-#include "guiInventoryMenu.h"\r
-#include "guiTextInputMenu.h"\r
-#include "materials.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
-\r
-// TODO: Remove this\r
-IrrlichtWrapper *g_irrlicht = NULL;\r
-\r
-// This makes textures\r
-ITextureSource *g_texturesource = NULL;\r
-\r
-MapDrawControl draw_control;\r
-\r
-/*\r
-       Settings.\r
-       These are loaded from the config file.\r
-*/\r
-\r
-Settings g_settings;\r
-\r
-extern void set_default_settings();\r
-\r
-/*\r
-       Random stuff\r
-*/\r
-\r
-IrrlichtDevice *g_device = NULL;\r
-Client *g_client = NULL;\r
-\r
-/*const s16 quickinv_size = 40;\r
-const s16 quickinv_padding = 8;\r
-const s16 quickinv_spacing = quickinv_size + quickinv_padding;\r
-const s16 quickinv_outer_padding = 4;\r
-const s16 quickinv_itemcount = 8;*/\r
-\r
-const s32 hotbar_itemcount = 8;\r
-const s32 hotbar_imagesize = 36;\r
-\r
-/*\r
-       GUI Stuff\r
-*/\r
-\r
-gui::IGUIEnvironment* guienv = NULL;\r
-gui::IGUIStaticText *guiroot = NULL;\r
-\r
-class MainMenuManager : public IMenuManager\r
-{\r
-public:\r
-       virtual void createdMenu(GUIModalMenu *menu)\r
-       {\r
-               for(core::list<GUIModalMenu*>::Iterator\r
-                               i = m_stack.begin();\r
-                               i != m_stack.end(); i++)\r
-               {\r
-                       assert(*i != menu);\r
-               }\r
-\r
-               if(m_stack.size() != 0)\r
-                       (*m_stack.getLast())->setVisible(false);\r
-               m_stack.push_back(menu);\r
-       }\r
-\r
-       virtual void deletingMenu(GUIModalMenu *menu)\r
-       {\r
-               // Remove all entries if there are duplicates\r
-               bool removed_entry;\r
-               do{\r
-                       removed_entry = false;\r
-                       for(core::list<GUIModalMenu*>::Iterator\r
-                                       i = m_stack.begin();\r
-                                       i != m_stack.end(); i++)\r
-                       {\r
-                               if(*i == menu)\r
-                               {\r
-                                       m_stack.erase(i);\r
-                                       removed_entry = true;\r
-                                       break;\r
-                               }\r
-                       }\r
-               }while(removed_entry);\r
-\r
-               /*core::list<GUIModalMenu*>::Iterator i = m_stack.getLast();\r
-               assert(*i == menu);\r
-               m_stack.erase(i);*/\r
-               \r
-               if(m_stack.size() != 0)\r
-                       (*m_stack.getLast())->setVisible(true);\r
-       }\r
-\r
-       u32 menuCount()\r
-       {\r
-               return m_stack.size();\r
-       }\r
-\r
-       core::list<GUIModalMenu*> m_stack;\r
-};\r
-\r
-MainMenuManager g_menumgr;\r
-\r
-bool noMenuActive()\r
-{\r
-       return (g_menumgr.menuCount() == 0);\r
-}\r
-\r
-bool g_disconnect_requested = false;\r
-\r
-class MainGameCallback : public IGameCallback\r
-{\r
-public:\r
-       virtual void exitToOS()\r
-       {\r
-               g_device->closeDevice();\r
-       }\r
-\r
-       virtual void disconnect()\r
-       {\r
-               g_disconnect_requested = true;\r
-       }\r
-};\r
-\r
-MainGameCallback g_gamecallback;\r
-\r
-// Inventory actions from the menu are buffered here before sending\r
-Queue<InventoryAction*> inventory_action_queue;\r
-// This is a copy of the inventory that the client's environment has\r
-Inventory local_inventory;\r
-\r
-u16 g_selected_item = 0;\r
-\r
-/*\r
-       Debug streams\r
-*/\r
-\r
-// Connection\r
-std::ostream *dout_con_ptr = &dummyout;\r
-std::ostream *derr_con_ptr = &dstream_no_stderr;\r
-//std::ostream *dout_con_ptr = &dstream_no_stderr;\r
-//std::ostream *derr_con_ptr = &dstream_no_stderr;\r
-//std::ostream *dout_con_ptr = &dstream;\r
-//std::ostream *derr_con_ptr = &dstream;\r
-\r
-// Server\r
-std::ostream *dout_server_ptr = &dstream;\r
-std::ostream *derr_server_ptr = &dstream;\r
-\r
-// Client\r
-std::ostream *dout_client_ptr = &dstream;\r
-std::ostream *derr_client_ptr = &dstream;\r
-\r
-/*\r
-       gettime.h implementation\r
-*/\r
-\r
-u32 getTimeMs()\r
-{\r
-       /*\r
-               Use irrlicht because it is more precise than porting.h's\r
-               getTimeMs()\r
-       */\r
-       if(g_irrlicht == NULL)\r
-               return 0;\r
-       return g_irrlicht->getTime();\r
-}\r
-\r
-/*\r
-       Text input system\r
-*/\r
-\r
-struct TextDestSign : public TextDest\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 gotText(std::wstring text)\r
-       {\r
-               std::string ntext = wide_to_narrow(text);\r
-               dstream<<"Changing text of a sign object: "\r
-                               <<ntext<<std::endl;\r
-               m_client->sendSignText(m_blockpos, m_id, ntext);\r
-       }\r
-\r
-       v3s16 m_blockpos;\r
-       s16 m_id;\r
-       Client *m_client;\r
-};\r
-\r
-struct TextDestChat : public TextDest\r
-{\r
-       TextDestChat(Client *client)\r
-       {\r
-               m_client = client;\r
-       }\r
-       void gotText(std::wstring text)\r
-       {\r
-               // Discard empty line\r
-               if(text == L"")\r
-                       return;\r
-               \r
-               // Parse command (server command starts with "/#")\r
-               if(text[0] == L'/' && text[1] != L'#')\r
-               {\r
-                       std::wstring reply = L"Local: ";\r
-\r
-                       reply += L"Local commands not yet supported. "\r
-                                       L"Server prefix is \"/#\".";\r
-                       \r
-                       m_client->addChatMessage(reply);\r
-                       return;\r
-               }\r
-\r
-               // Send to others\r
-               m_client->sendChatMessage(text);\r
-               // Show locally\r
-               m_client->addChatMessage(text);\r
-       }\r
-\r
-       Client *m_client;\r
-};\r
-\r
-class MyEventReceiver : public IEventReceiver\r
-{\r
-public:\r
-       // 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
-                       clearInput();\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
-                               \r
-                               /*\r
-                                       Launch menus\r
-                               */\r
-\r
-                               if(guienv != NULL && guiroot != NULL && g_device != NULL)\r
-                               {\r
-                                       if(event.KeyInput.Key == irr::KEY_ESCAPE)\r
-                                       {\r
-                                               dstream<<DTIME<<"MyEventReceiver: "\r
-                                                               <<"Launching pause menu"<<std::endl;\r
-                                               // It will delete itself by itself\r
-                                               (new GUIPauseMenu(guienv, guiroot, -1, &g_gamecallback,\r
-                                                               &g_menumgr))->drop();\r
-                                               return true;\r
-                                       }\r
-                                       if(event.KeyInput.Key == irr::KEY_KEY_I)\r
-                                       {\r
-                                               dstream<<DTIME<<"MyEventReceiver: "\r
-                                                               <<"Launching inventory"<<std::endl;\r
-                                               (new GUIInventoryMenu(guienv, guiroot, -1,\r
-                                                               &local_inventory, &inventory_action_queue,\r
-                                                               &g_menumgr))->drop();\r
-                                               return true;\r
-                                       }\r
-                                       if(event.KeyInput.Key == irr::KEY_KEY_T)\r
-                                       {\r
-                                               TextDest *dest = new TextDestChat(g_client);\r
-\r
-                                               (new GUITextInputMenu(guienv, guiroot, -1,\r
-                                                               &g_menumgr, dest,\r
-                                                               L""))->drop();\r
-                                       }\r
-                               }\r
-\r
-                               // Item selection\r
-                               if(event.KeyInput.Key >= irr::KEY_KEY_0\r
-                                               && event.KeyInput.Key <= irr::KEY_KEY_9)\r
-                               {\r
-                                       u16 s1 = event.KeyInput.Key - irr::KEY_KEY_0;\r
-                                       if(event.KeyInput.Key == irr::KEY_KEY_0)\r
-                                               s1 = 10;\r
-                                       if(s1 < PLAYER_INVENTORY_SIZE && s1 < hotbar_itemcount)\r
-                                               g_selected_item = s1-1;\r
-                                       dstream<<DTIME<<"Selected item: "\r
-                                                       <<g_selected_item<<std::endl;\r
-                               }\r
-\r
-                               // Viewing range selection\r
-                               if(event.KeyInput.Key == irr::KEY_KEY_R)\r
-                               {\r
-                                       if(draw_control.range_all)\r
-                                       {\r
-                                               draw_control.range_all = false;\r
-                                               dstream<<DTIME<<"Disabled full viewing range"<<std::endl;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               draw_control.range_all = true;\r
-                                               dstream<<DTIME<<"Enabled full viewing range"<<std::endl;\r
-                                       }\r
-                               }\r
-\r
-                               // Print debug stacks\r
-                               if(event.KeyInput.Key == irr::KEY_KEY_P)\r
-                               {\r
-                                       dstream<<"-----------------------------------------"\r
-                                                       <<std::endl;\r
-                                       dstream<<DTIME<<"Printing debug stacks:"<<std::endl;\r
-                                       dstream<<"-----------------------------------------"\r
-                                                       <<std::endl;\r
-                                       debug_stacks_print();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)\r
-               {\r
-                       if(noMenuActive() == false)\r
-                       {\r
-                               left_active = false;\r
-                               middle_active = false;\r
-                               right_active = false;\r
-                       }\r
-                       else\r
-                       {\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
-                                       rightreleased = true;\r
-                               }\r
-                               if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)\r
-                               {\r
-                                       /*dstream<<"event.MouseInput.Wheel="\r
-                                                       <<event.MouseInput.Wheel<<std::endl;*/\r
-                                       \r
-                                       u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,\r
-                                                       hotbar_itemcount-1);\r
-                                       if(event.MouseInput.Wheel < 0)\r
-                                       {\r
-                                               if(g_selected_item < max_item)\r
-                                                       g_selected_item++;\r
-                                               else\r
-                                                       g_selected_item = 0;\r
-                                       }\r
-                                       else if(event.MouseInput.Wheel > 0)\r
-                                       {\r
-                                               if(g_selected_item > 0)\r
-                                                       g_selected_item--;\r
-                                               else\r
-                                                       g_selected_item = max_item;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               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
-       {\r
-               return keyIsDown[keyCode];\r
-       }\r
-\r
-       void clearInput()\r
-       {\r
-               for (u32 i=0; i<KEY_KEY_CODES_COUNT; ++i)\r
-                               keyIsDown[i] = false;\r
-               \r
-               leftclicked = false;\r
-               rightclicked = false;\r
-               leftreleased = false;\r
-               rightreleased = false;\r
-\r
-               left_active = false;\r
-               middle_active = false;\r
-               right_active = false;\r
-       }\r
-\r
-       MyEventReceiver()\r
-       {\r
-               clearInput();\r
-       }\r
-\r
-       bool leftclicked;\r
-       bool rightclicked;\r
-       bool leftreleased;\r
-       bool rightreleased;\r
-\r
-       bool left_active;\r
-       bool middle_active;\r
-       bool right_active;\r
-\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
-       IrrlichtDevice *m_device;\r
-};\r
-\r
-class InputHandler\r
-{\r
-public:\r
-       InputHandler()\r
-       {\r
-       }\r
-       virtual ~InputHandler()\r
-       {\r
-       }\r
-\r
-       virtual bool isKeyDown(EKEY_CODE keyCode) = 0;\r
-\r
-       virtual v2s32 getMousePos() = 0;\r
-       virtual void setMousePos(s32 x, s32 y) = 0;\r
-\r
-       virtual bool getLeftState() = 0;\r
-       virtual bool getRightState() = 0;\r
-\r
-       virtual bool getLeftClicked() = 0;\r
-       virtual bool getRightClicked() = 0;\r
-       virtual void resetLeftClicked() = 0;\r
-       virtual void resetRightClicked() = 0;\r
-\r
-       virtual bool getLeftReleased() = 0;\r
-       virtual bool getRightReleased() = 0;\r
-       virtual void resetLeftReleased() = 0;\r
-       virtual void resetRightReleased() = 0;\r
-       \r
-       virtual void step(float dtime) {};\r
-\r
-       virtual void clear() {};\r
-};\r
-\r
-InputHandler *g_input = NULL;\r
-\r
-class RealInputHandler : public InputHandler\r
-{\r
-public:\r
-       RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):\r
-               m_device(device),\r
-               m_receiver(receiver)\r
-       {\r
-       }\r
-       virtual bool isKeyDown(EKEY_CODE keyCode)\r
-       {\r
-               return m_receiver->IsKeyDown(keyCode);\r
-       }\r
-       virtual v2s32 getMousePos()\r
-       {\r
-               return m_device->getCursorControl()->getPosition();\r
-       }\r
-       virtual void setMousePos(s32 x, s32 y)\r
-       {\r
-               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
-               return m_receiver->leftclicked;\r
-       }\r
-       virtual bool getRightClicked()\r
-       {\r
-               return m_receiver->rightclicked;\r
-       }\r
-       virtual void resetLeftClicked()\r
-       {\r
-               m_receiver->leftclicked = false;\r
-       }\r
-       virtual void resetRightClicked()\r
-       {\r
-               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
-       void clear()\r
-       {\r
-               resetRightClicked();\r
-               resetLeftClicked();\r
-       }\r
-private:\r
-       IrrlichtDevice *m_device;\r
-       MyEventReceiver *m_receiver;\r
-};\r
-\r
-class RandomInputHandler : public InputHandler\r
-{\r
-public:\r
-       RandomInputHandler()\r
-       {\r
-               leftclicked = false;\r
-               rightclicked = false;\r
-               for(u32 i=0; i<KEY_KEY_CODES_COUNT; ++i)\r
-                       keydown[i] = false;\r
-       }\r
-       virtual bool isKeyDown(EKEY_CODE keyCode)\r
-       {\r
-               return keydown[keyCode];\r
-       }\r
-       virtual v2s32 getMousePos()\r
-       {\r
-               return mousepos;\r
-       }\r
-       virtual void setMousePos(s32 x, s32 y)\r
-       {\r
-               mousepos = v2s32(x,y);\r
-       }\r
-\r
-       virtual bool getLeftState()\r
-       {\r
-               return false;\r
-       }\r
-       virtual bool getRightState()\r
-       {\r
-               return false;\r
-       }\r
-\r
-       virtual bool getLeftClicked()\r
-       {\r
-               return leftclicked;\r
-       }\r
-       virtual bool getRightClicked()\r
-       {\r
-               return rightclicked;\r
-       }\r
-       virtual void resetLeftClicked()\r
-       {\r
-               leftclicked = false;\r
-       }\r
-       virtual void resetRightClicked()\r
-       {\r
-               rightclicked = false;\r
-       }\r
-\r
-       virtual bool getLeftReleased()\r
-       {\r
-               return false;\r
-       }\r
-       virtual bool getRightReleased()\r
-       {\r
-               return false;\r
-       }\r
-       virtual void resetLeftReleased()\r
-       {\r
-       }\r
-       virtual void resetRightReleased()\r
-       {\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_CONTENT_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
-                       }\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_KEY_E] = !keydown[irr::KEY_KEY_E];\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_KEY_W] = !keydown[irr::KEY_KEY_W];\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_KEY_A] = !keydown[irr::KEY_KEY_A];\r
-                       }\r
-               }\r
-               {\r
-                       static float counter1 = 0;\r
-                       counter1 -= dtime;\r
-                       if(counter1 < 0.0)\r
-                       {\r
-                               counter1 = 0.1*Rand(1, 20);\r
-                               mousespeed = v2s32(Rand(-20,20), Rand(-15,20));\r
-                       }\r
-               }\r
-               {\r
-                       static float counter1 = 0;\r
-                       counter1 -= dtime;\r
-                       if(counter1 < 0.0)\r
-                       {\r
-                               counter1 = 0.1*Rand(1, 30);\r
-                               leftclicked = true;\r
-                       }\r
-               }\r
-               {\r
-                       static float counter1 = 0;\r
-                       counter1 -= dtime;\r
-                       if(counter1 < 0.0)\r
-                       {\r
-                               counter1 = 0.1*Rand(1, 20);\r
-                               rightclicked = true;\r
-                       }\r
-               }\r
-               mousepos += mousespeed;\r
-       }\r
-\r
-       s32 Rand(s32 min, s32 max)\r
-       {\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 leftclicked;\r
-       bool rightclicked;\r
-};\r
-\r
-void updateViewingRange(f32 frametime_in, Client *client)\r
-{\r
-       if(draw_control.range_all == true)\r
-               return;\r
-       \r
-       static f32 added_frametime = 0;\r
-       static s16 added_frames = 0;\r
-\r
-       added_frametime += frametime_in;\r
-       added_frames += 1;\r
-\r
-       // Actually this counter kind of sucks because frametime is busytime\r
-       static f32 counter = 0;\r
-       counter -= frametime_in;\r
-       if(counter > 0)\r
-               return;\r
-       //counter = 0.1;\r
-       counter = 0.2;\r
-\r
-       /*dstream<<__FUNCTION_NAME\r
-                       <<": Collected "<<added_frames<<" frames, total of "\r
-                       <<added_frametime<<"s."<<std::endl;*/\r
-       \r
-       /*dstream<<"draw_control.blocks_drawn="\r
-                       <<draw_control.blocks_drawn\r
-                       <<", draw_control.blocks_would_have_drawn="\r
-                       <<draw_control.blocks_would_have_drawn\r
-                       <<std::endl;*/\r
-       \r
-       float range_min = g_settings.getS16("viewing_range_nodes_min");\r
-       float range_max = g_settings.getS16("viewing_range_nodes_max");\r
-       \r
-       draw_control.wanted_min_range = range_min;\r
-       draw_control.wanted_max_blocks = (1.2*draw_control.blocks_drawn)+1;\r
-       \r
-       float block_draw_ratio = 1.0;\r
-       if(draw_control.blocks_would_have_drawn != 0)\r
-       {\r
-               block_draw_ratio = (float)draw_control.blocks_drawn\r
-                       / (float)draw_control.blocks_would_have_drawn;\r
-       }\r
-\r
-       // Calculate the average frametime in the case that all wanted\r
-       // blocks had been drawn\r
-       f32 frametime = added_frametime / added_frames / block_draw_ratio;\r
-       \r
-       added_frametime = 0.0;\r
-       added_frames = 0;\r
-       \r
-       float wanted_fps = g_settings.getFloat("wanted_fps");\r
-       float wanted_frametime = 1.0 / wanted_fps;\r
-       \r
-       f32 wanted_frametime_change = wanted_frametime - frametime;\r
-       //dstream<<"wanted_frametime_change="<<wanted_frametime_change<<std::endl;\r
-       \r
-       // If needed frametime change is very small, just return\r
-       if(fabs(wanted_frametime_change) < wanted_frametime*0.2)\r
-       {\r
-               //dstream<<"ignoring small wanted_frametime_change"<<std::endl;\r
-               return;\r
-       }\r
-\r
-       float range = draw_control.wanted_range;\r
-       float new_range = range;\r
-\r
-       static s16 range_old = 0;\r
-       static f32 frametime_old = 0;\r
-       \r
-       float d_range = range - range_old;\r
-       f32 d_frametime = frametime - frametime_old;\r
-       // A sane default of 30ms per 50 nodes of range\r
-       static f32 time_per_range = 30. / 50;\r
-       if(d_range != 0)\r
-       {\r
-               time_per_range = d_frametime / d_range;\r
-       }\r
-       \r
-       // The minimum allowed calculated frametime-range derivative:\r
-       // Practically this sets the maximum speed of changing the range.\r
-       // The lower this value, the higher the maximum changing speed.\r
-       // A low value here results in wobbly range (0.001)\r
-       // A high value here results in slow changing range (0.0025)\r
-       // SUGG: This could be dynamically adjusted so that when\r
-       //       the camera is turning, this is lower\r
-       //float min_time_per_range = 0.0015;\r
-       float min_time_per_range = 0.0010;\r
-       //float min_time_per_range = 0.05 / range;\r
-       if(time_per_range < min_time_per_range)\r
-       {\r
-               time_per_range = min_time_per_range;\r
-               //dstream<<"time_per_range="<<time_per_range<<" (min)"<<std::endl;\r
-       }\r
-       else\r
-       {\r
-               //dstream<<"time_per_range="<<time_per_range<<std::endl;\r
-       }\r
-\r
-       f32 wanted_range_change = wanted_frametime_change / time_per_range;\r
-       // Dampen the change a bit to kill oscillations\r
-       //wanted_range_change *= 0.9;\r
-       //wanted_range_change *= 0.75;\r
-       wanted_range_change *= 0.5;\r
-       //dstream<<"wanted_range_change="<<wanted_range_change<<std::endl;\r
-\r
-       // If needed range change is very small, just return\r
-       if(fabs(wanted_range_change) < 0.001)\r
-       {\r
-               //dstream<<"ignoring small wanted_range_change"<<std::endl;\r
-               return;\r
-       }\r
-\r
-       new_range += wanted_range_change;\r
-       //dstream<<"new_range="<<new_range/*<<std::endl*/;\r
-       \r
-       //float new_range_unclamped = new_range;\r
-       if(new_range < range_min)\r
-               new_range = range_min;\r
-       if(new_range > range_max)\r
-               new_range = range_max;\r
-       \r
-       /*if(new_range != new_range_unclamped)\r
-               dstream<<", clamped to "<<new_range<<std::endl;\r
-       else\r
-               dstream<<std::endl;*/\r
-\r
-       draw_control.wanted_range = new_range;\r
-\r
-       range_old = new_range;\r
-       frametime_old = frametime;\r
-}\r
-\r
-#if 0\r
-// TODO: Remove\r
-class GUIQuickInventory\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
-       {\r
-               core::rect<s32> imgsize(0,0,quickinv_size,quickinv_size);\r
-               core::rect<s32> textsize(0,0,quickinv_size,quickinv_size);\r
-               bgtext = env->addStaticText(L"", core::rect<s32>(0,0,1,1), false, false);\r
-               bgtext->setBackgroundColor(\r
-                               video::SColor(128,0,0,0));\r
-               for(s32 i=0; i<m_itemcount; i++)\r
-               {\r
-                       m_images.push_back(env->addImage(\r
-                               imgsize\r
-                       ));\r
-                       m_images[i]->setScaleImage(true);\r
-                       m_texts.push_back(env->addStaticText(\r
-                               L"",\r
-                               textsize,\r
-                               false, false\r
-                       ));\r
-                       /*m_texts[i]->setBackgroundColor(\r
-                                       video::SColor(128,0,0,0));*/\r
-                       m_texts[i]->setTextAlignment(\r
-                                       gui::EGUIA_LOWERRIGHT,\r
-                                       gui::EGUIA_LOWERRIGHT);\r
-               }\r
-\r
-               updatePosition(pos);\r
-       }\r
-\r
-       ~GUIQuickInventory()\r
-       {\r
-               for(u32 i=0; i<m_texts.size(); i++)\r
-               {\r
-                       m_texts[i]->remove();\r
-               }\r
-               for(u32 i=0; i<m_images.size(); i++)\r
-               {\r
-                       m_images[i]->remove();\r
-               }\r
-               bgtext->remove();\r
-       }\r
-\r
-       void updatePosition(v2s32 pos)\r
-       {\r
-               v2s32 spacing(quickinv_spacing, 0);\r
-               for(s32 i=0; i<m_itemcount; i++)\r
-               {\r
-                       m_images[i]->setRelativePosition(pos + spacing*i);\r
-                       m_texts[i]->setRelativePosition(pos + spacing*i);\r
-               }\r
-               core::rect<s32> bgrect(-quickinv_outer_padding,-quickinv_outer_padding,\r
-                               (quickinv_itemcount-1)*quickinv_spacing+quickinv_size+quickinv_outer_padding,\r
-                               quickinv_size+quickinv_outer_padding);\r
-               bgtext->setRelativePosition(bgrect+pos);\r
-       }\r
-\r
-       void setSelection(s32 i)\r
-       {\r
-               m_selection = i;\r
-       }\r
-\r
-       void update()\r
-       {\r
-               s32 start = 0;\r
-\r
-               //start = m_selection - m_itemcount / 2;\r
-\r
-               InventoryList *mainlist = m_inventory->getList("main");\r
-\r
-               for(s32 i=0; i<m_itemcount; i++)\r
-               {\r
-                       s32 j = i + start;\r
-\r
-                       if(j > (s32)mainlist->getSize() - 1)\r
-                               j -= mainlist->getSize();\r
-                       if(j < 0)\r
-                               j += mainlist->getSize();\r
-                       \r
-                       InventoryItem *item = mainlist->getItem(j);\r
-                       // Null items\r
-                       if(item == NULL)\r
-                       {\r
-                               m_images[i]->setImage(NULL);\r
-\r
-                               if(m_selection == j)\r
-                                       m_texts[i]->setText(L"->");\r
-                               else\r
-                                       m_texts[i]->setText(L"");\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
-                       std::ostringstream os;\r
-                       if(m_selection == j)\r
-                               os<<"-> ";\r
-                       os<<item->getText();\r
-                       m_texts[i]->setText(narrow_to_wide(os.str()).c_str());\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
-private:\r
-       s32 m_itemcount;\r
-       gui::IGUIStaticText *bgtext;\r
-       core::array<gui::IGUIStaticText*> m_texts;\r
-       core::array<gui::IGUIImage*> m_images;\r
-       Inventory *m_inventory;\r
-       s32 m_selection;\r
-};\r
-#endif\r
-\r
-void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,\r
-               v2s32 centerlowerpos, s32 imgsize, s32 itemcount,\r
-               Inventory *inventory)\r
-{\r
-       InventoryList *mainlist = inventory->getList("main");\r
-       if(mainlist == NULL)\r
-       {\r
-               dstream<<"WARNING: draw_hotbar(): mainlist == NULL"<<std::endl;\r
-               return;\r
-       }\r
-       \r
-       s32 padding = imgsize/12;\r
-       //s32 height = imgsize + padding*2;\r
-       s32 width = itemcount*(imgsize+padding*2);\r
-       \r
-       // Position of upper left corner of bar\r
-       v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);\r
-       \r
-       // Draw background color\r
-       /*core::rect<s32> barrect(0,0,width,height);\r
-       barrect += pos;\r
-       video::SColor bgcolor(255,128,128,128);\r
-       driver->draw2DRectangle(bgcolor, barrect, NULL);*/\r
-\r
-       core::rect<s32> imgrect(0,0,imgsize,imgsize);\r
-\r
-       for(s32 i=0; i<itemcount; i++)\r
-       {\r
-               InventoryItem *item = mainlist->getItem(i);\r
-               \r
-               core::rect<s32> rect = imgrect + pos\r
-                               + v2s32(padding+i*(imgsize+padding*2), padding);\r
-               \r
-               if(g_selected_item == i)\r
-               {\r
-                       driver->draw2DRectangle(video::SColor(255,255,0,0),\r
-                                       core::rect<s32>(rect.UpperLeftCorner - v2s32(1,1)*padding,\r
-                                                       rect.LowerRightCorner + v2s32(1,1)*padding),\r
-                                       NULL);\r
-               }\r
-               else\r
-               {\r
-                       video::SColor bgcolor2(128,0,0,0);\r
-                       driver->draw2DRectangle(bgcolor2, rect, NULL);\r
-               }\r
-\r
-               if(item != NULL)\r
-               {\r
-                       drawInventoryItem(driver, font, item, rect, NULL);\r
-               }\r
-       }\r
-}\r
-\r
-// Chat data\r
-struct ChatLine\r
-{\r
-       ChatLine():\r
-               age(0.0)\r
-       {\r
-       }\r
-       ChatLine(const std::wstring &a_text):\r
-               age(0.0),\r
-               text(a_text)\r
-       {\r
-       }\r
-       float age;\r
-       std::wstring text;\r
-};\r
-\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
-       {\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
-       \r
-       dstream<<"All of the following tests should take around 100ms each."\r
-                       <<std::endl;\r
-\r
-       {\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
-       \r
-       {\r
-               TimeTaker timer("Testing floating-point vector speed");\r
-\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
-       {\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
-       {\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
-               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
-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
-       Settings cmd_args;\r
-       \r
-       bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);\r
-\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
-                       dstream<<"  --"<<i.getNode()->getKey();\r
-                       if(i.getNode()->getValue().type == VALUETYPE_FLAG)\r
-                       {\r
-                       }\r
-                       else\r
-                       {\r
-                               dstream<<" <value>";\r
-                       }\r
-                       dstream<<std::endl;\r
-\r
-                       if(i.getNode()->getValue().help != NULL)\r
-                       {\r
-                               dstream<<"      "<<i.getNode()->getValue().help\r
-                                               <<std::endl;\r
-                       }\r
-               }\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
-       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
-       DSTACK(__FUNCTION_NAME);\r
-\r
-       porting::signal_handler_init();\r
-       bool &kill = *porting::signal_handler_killstatus();\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
-                       <<", "<<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
-       setlocale(LC_CTYPE, "en_US");\r
-\r
-       // Initialize sockets\r
-       sockets_init();\r
-       atexit(sockets_cleanup);\r
-       \r
-       /*\r
-               Initialization\r
-       */\r
-\r
-       /*\r
-               Read config file\r
-       */\r
-       \r
-       // Path of configuration file in use\r
-       std::string configpath = "";\r
-       \r
-       if(cmd_args.exists("config"))\r
-       {\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
-               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<filenames.size(); i++)\r
-               {\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
-               These are needed for unit tests at least.\r
-       */\r
-       \r
-       // Initial call with g_texturesource not set.\r
-       init_mapnode();\r
-\r
-       /*\r
-               Run unit tests\r
-       */\r
-\r
-       if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)\r
-                       || cmd_args.getFlag("enable-unittests") == true)\r
-       {\r
-               run_tests();\r
-       }\r
-       \r
-       /*for(s16 y=-100; y<100; y++)\r
-       for(s16 x=-100; x<100; x++)\r
-       {\r
-               std::cout<<noise2d_gradient((double)x/10,(double)y/10, 32415)<<std::endl;\r
-       }\r
-       return 0;*/\r
-       \r
-       /*\r
-               Some parameters\r
-       */\r
-\r
-       // Port\r
-       u16 port = 30000;\r
-       if(cmd_args.exists("port"))\r
-               port = cmd_args.getU16("port");\r
-       else if(cmd_args.exists("port"))\r
-               port = g_settings.getU16("port");\r
-       \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
-               // 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
-       /*\r
-               More parameters\r
-       */\r
-       \r
-       // Address to connect to\r
-       std::string address = "";\r
-       \r
-       if(cmd_args.exists("address"))\r
-       {\r
-               address = cmd_args.get("address");\r
-       }\r
-       else\r
-       {\r
-               address = g_settings.get("address");\r
-       }\r
-       \r
-       std::string playername = g_settings.get("name");\r
-\r
-       /*\r
-               Resolution selection\r
-       */\r
-       \r
-       bool fullscreen = false;\r
-       u16 screenW = g_settings.getU16("screenW");\r
-       u16 screenH = g_settings.getU16("screenH");\r
-\r
-       //\r
-\r
-       MyEventReceiver receiver;\r
-\r
-       video::E_DRIVER_TYPE driverType;\r
-\r
-#ifdef _WIN32\r
-       //driverType = video::EDT_DIRECT3D9;\r
-       driverType = video::EDT_OPENGL;\r
-#else\r
-       driverType = video::EDT_OPENGL;\r
-       //driverType = video::EDT_BURNINGSVIDEO; // Best software renderer\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
-\r
-       if (device == 0)\r
-               return 1; // could not create selected driver.\r
-       \r
-       g_device = device;\r
-       g_irrlicht = new IrrlichtWrapper(device);\r
-       TextureSource *texturesource = new TextureSource(device);\r
-       g_texturesource = texturesource;\r
-\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
-       bool random_input = g_settings.getBool("random_input")\r
-                       || cmd_args.getFlag("random-input");\r
-       if(random_input)\r
-               g_input = new RandomInputHandler();\r
-       else\r
-               g_input = new RealInputHandler(device, &receiver);\r
-       \r
-       /*\r
-               Continue initialization\r
-       */\r
-\r
-       video::IVideoDriver* driver = device->getVideoDriver();\r
-\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
-       guienv = device->getGUIEnvironment();\r
-       gui::IGUISkin* skin = guienv->getSkin();\r
-       gui::IGUIFont* font = guienv->getFont(porting::getDataPath("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
-       //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));\r
-       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
-       /*\r
-               Preload some textures and stuff\r
-       */\r
-\r
-       init_content_inventory_texture_paths();\r
-       init_mapnode(); // Second call with g_texturesource set\r
-       init_mineral();\r
-\r
-       /*\r
-               GUI stuff\r
-       */\r
-\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
-       // First line of debug text\r
-       gui::IGUIStaticText *guitext = guienv->addStaticText(\r
-                       L"",\r
-                       core::rect<s32>(5, 5, 795, 5+text_height),\r
-                       false, false);\r
-       // Second line of debug text\r
-       gui::IGUIStaticText *guitext2 = guienv->addStaticText(\r
-                       L"",\r
-                       core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*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"",\r
-                       core::rect<s32>(100, 70, 100+400, 70+(text_height+5)),\r
-                       false, false);\r
-       \r
-       // Chat text\r
-       gui::IGUIStaticText *guitext_chat = guienv->addStaticText(\r
-                       L"",\r
-                       core::rect<s32>(0,0,0,0),\r
-                       false, false); // Disable word wrap as of now\r
-                       //false, true);\r
-       //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));\r
-       core::list<ChatLine> chat_lines;\r
-       \r
-       /*\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
-       /*\r
-               Menu-game loop\r
-       */\r
-       while(g_device->run() && kill == false)\r
-       {\r
-       \r
-       // This is used for catching disconnects\r
-       try\r
-       {\r
-       \r
-       /*\r
-               Out-of-game menu loop.\r
-\r
-               Loop quits when menu returns proper parameters.\r
-       */\r
-       while(kill == false)\r
-       {\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
-               // 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.creative_mode = g_settings.getBool("creative_mode");\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
-                       GUIMessageMenu *menu2 =\r
-                                       new GUIMessageMenu(guienv, guiroot, -1, \r
-                                               &g_menumgr, error_message.c_str());\r
-                       menu2->drop();\r
-                       error_message = L"";\r
-               }\r
-\r
-               video::IVideoDriver* driver = g_device->getVideoDriver();\r
-               \r
-               dstream<<"Created main menu"<<std::endl;\r
-\r
-               while(g_device->run())\r
-               {\r
-                       // Run global IrrlichtWrapper's main thread processing stuff\r
-                       g_irrlicht->Run();\r
-                       \r
-                       if(menu->getStatus() == true)\r
-                               break;\r
-\r
-                       //driver->beginScene(true, true, video::SColor(255,0,0,0));\r
-                       driver->beginScene(true, true, video::SColor(255,128,128,128));\r
-                       guienv->drawAll();\r
-                       driver->endScene();\r
-               }\r
-               \r
-               // Break out of menu-game loop to shut down cleanly\r
-               if(g_device->run() == false)\r
-                       break;\r
-               \r
-               dstream<<"Dropping main menu"<<std::endl;\r
-\r
-               menu->drop();\r
-               \r
-               // Delete map if requested\r
-               if(menudata.delete_map)\r
-               {\r
-                       bool r = fs::RecursiveDeleteContent(map_dir);\r
-                       if(r == false)\r
-                               error_message = L"Delete failed";\r
-                       continue;\r
-               }\r
-\r
-               playername = wide_to_narrow(menudata.name);\r
-               address = wide_to_narrow(menudata.address);\r
-               port = stoi(wide_to_narrow(menudata.port));\r
-               g_settings.set("creative_mode", itos(menudata.creative_mode));\r
-               \r
-               // Check for valid parameters, restart menu if invalid.\r
-               if(playername == "")\r
-               {\r
-                       error_message = L"Name required.";\r
-                       continue;\r
-               }\r
-               \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
-               // Continue to game\r
-               break;\r
-       }\r
-       \r
-       // Break out of menu-game loop to shut down cleanly\r
-       if(g_device->run() == false)\r
-               break;\r
-\r
-       /*\r
-               Make a scope here so that the client and the server and other\r
-               stuff gets removed when disconnected or the irrlicht device\r
-               is removed.\r
-       */\r
-       {\r
-\r
-       // This is set to true at the end of the scope\r
-       g_irrlicht->Shutdown(false);\r
-\r
-       /*\r
-               Draw "Loading" screen\r
-       */\r
-       const wchar_t *text = L"Loading and connecting...";\r
-       core::vector2d<s32> center(screenW/2, screenH/2);\r
-       core::vector2d<s32> textsize(300, text_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
-       std::cout<<DTIME<<"Creating server and client"<<std::endl;\r
-       \r
-       /*\r
-               Create server.\r
-               SharedPtr will delete it when it goes out of scope.\r
-       */\r
-       SharedPtr<Server> server;\r
-       if(address == ""){\r
-               server = new Server(map_dir);\r
-               server->start(port);\r
-       }\r
-       \r
-       /*\r
-               Create client\r
-       */\r
-\r
-       Client client(device, playername.c_str(), draw_control);\r
-                       \r
-       g_client = &client;\r
-       \r
-       Address connect_address(0,0,0,0, port);\r
-       try{\r
-               if(address == "")\r
-                       //connect_address.Resolve("localhost");\r
-                       connect_address.setAddress(127,0,0,1);\r
-               else\r
-                       connect_address.Resolve(address.c_str());\r
-       }\r
-       catch(ResolveError &e)\r
-       {\r
-               std::cout<<DTIME<<"Couldn't resolve address"<<std::endl;\r
-               //return 0;\r
-               error_message = L"Couldn't resolve address";\r
-               gui_loadingtext->remove();\r
-               continue;\r
-       }\r
-       \r
-       dstream<<DTIME<<"Connecting to server at ";\r
-       connect_address.print(&dstream);\r
-       dstream<<std::endl;\r
-       client.connect(connect_address);\r
-       \r
-       try{\r
-               while(client.connectedAndInitialized() == false)\r
-               {\r
-                       // Update screen\r
-                       driver->beginScene(true, true, video::SColor(255,0,0,0));\r
-                       guienv->drawAll();\r
-                       driver->endScene();\r
-\r
-                       // Update client and server\r
-\r
-                       client.step(0.1);\r
-\r
-                       if(server != NULL)\r
-                               server->step(0.1);\r
-                       \r
-                       // Delay a bit\r
-                       sleep_ms(100);\r
-               }\r
-       }\r
-       catch(con::PeerNotFoundException &e)\r
-       {\r
-               std::cout<<DTIME<<"Timed out."<<std::endl;\r
-               //return 0;\r
-               error_message = L"Connection timed out.";\r
-               gui_loadingtext->remove();\r
-               continue;\r
-       }\r
-\r
-       /*\r
-               Create skybox\r
-       */\r
-       /*scene::ISceneNode* skybox;\r
-       skybox = smgr->addSkyBoxSceneNode(\r
-               driver->getTexture(porting::getDataPath("skybox2.png").c_str()),\r
-               driver->getTexture(porting::getDataPath("skybox3.png").c_str()),\r
-               driver->getTexture(porting::getDataPath("skybox1.png").c_str()),\r
-               driver->getTexture(porting::getDataPath("skybox1.png").c_str()),\r
-               driver->getTexture(porting::getDataPath("skybox1.png").c_str()),\r
-               driver->getTexture(porting::getDataPath("skybox1.png").c_str()));*/\r
-       \r
-       /*\r
-               Create the camera node\r
-       */\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
-       //video::SColor skycolor = video::SColor(255,166,202,244);\r
-       video::SColor skycolor = video::SColor(255,120,185,244);\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 camera_yaw = 0; // "right/left"\r
-       f32 camera_pitch = 0; // "up/down"\r
-\r
-       /*\r
-               Move into game\r
-       */\r
-       \r
-       gui_loadingtext->remove();\r
-\r
-       /*\r
-               Add some gui stuff\r
-       */\r
-\r
-       /*GUIQuickInventory *quick_inventory = new GUIQuickInventory\r
-                       (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/\r
-       /*GUIQuickInventory *quick_inventory = new GUIQuickInventory\r
-                       (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/\r
-       \r
-       // Test the text input system\r
-       /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,\r
-                       NULL))->drop();*/\r
-       /*GUIMessageMenu *menu =\r
-                       new GUIMessageMenu(guienv, guiroot, -1, \r
-                               &g_menumgr,\r
-                               L"Asd");\r
-       menu->drop();*/\r
-       \r
-       // Launch pause menu\r
-       (new GUIPauseMenu(guienv, guiroot, -1, &g_gamecallback,\r
-                       &g_menumgr))->drop();\r
-       \r
-       // Enable texts\r
-       guitext2->setVisible(true);\r
-       guitext_info->setVisible(true);\r
-       guitext_chat->setVisible(true);\r
-\r
-       //s32 guitext_chat_pad_bottom = 70;\r
-\r
-       v2u32 screensize(0,0);\r
-       v2u32 last_screensize(0,0);\r
-       \r
-       /*\r
-               Some statistics are collected in these\r
-       */\r
-       u32 drawtime = 0;\r
-       u32 beginscenetime = 0;\r
-       u32 scenetime = 0;\r
-       u32 endscenetime = 0;\r
-       \r
-       // A test\r
-       //throw con::PeerNotFoundException("lol");\r
-\r
-       core::list<float> frametime_log;\r
-\r
-       /*\r
-               Main loop\r
-       */\r
-\r
-       bool first_loop_after_window_activation = true;\r
-\r
-       // Time is in milliseconds\r
-       // NOTE: getRealTime() causes strange problems in wine (imprecision?)\r
-       // NOTE: So we have to use getTime() and call run()s between them\r
-       u32 lasttime = device->getTimer()->getTime();\r
-\r
-       while(device->run() && kill == false)\r
-       {\r
-               if(g_disconnect_requested)\r
-               {\r
-                       g_disconnect_requested = false;\r
-                       break;\r
-               }\r
-\r
-               /*\r
-                       Run global IrrlichtWrapper's main thread processing stuff\r
-               */\r
-               g_irrlicht->Run();\r
-\r
-               /*\r
-                       Process TextureSource's queue\r
-               */\r
-               texturesource->processQueue();\r
-\r
-               /*\r
-                       Random calculations\r
-               */\r
-               last_screensize = screensize;\r
-               screensize = driver->getScreenSize();\r
-               v2s32 displaycenter(screensize.X/2,screensize.Y/2);\r
-               //bool screensize_changed = screensize != last_screensize;\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
-               // When screen size changes, update positions and sizes of stuff\r
-               /*if(screensize_changed)\r
-               {\r
-                       v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);\r
-                       quick_inventory->updatePosition(pos);\r
-               }*/\r
-\r
-               //TimeTaker //timer1("//timer1");\r
-               \r
-               // Time of frame without fps limit\r
-               float busytime;\r
-               u32 busytime_u32;\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(busytime, &client);\r
-               \r
-               /*\r
-                       FPS limiter\r
-               */\r
-\r
-               {\r
-                       float fps_max = g_settings.getFloat("fps_max");\r
-                       u32 frametime_min = 1000./fps_max;\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
-                       Log frametime for visualization\r
-               */\r
-               frametime_log.push_back(dtime);\r
-               if(frametime_log.size() > 100)\r
-               {\r
-                       core::list<float>::Iterator i = frametime_log.begin();\r
-                       frametime_log.erase(i);\r
-               }\r
-\r
-               /*\r
-                       Visualize frametime in terminal\r
-               */\r
-               /*for(u32 i=0; i<dtime*400; i++)\r
-                       std::cout<<"X";\r
-               std::cout<<std::endl;*/\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
-               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
-                       {\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
-                       }\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
-                       Player speed control\r
-               */\r
-               \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
-                       bool a_sneak,\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_E),\r
-                               g_input->isKeyDown(irr::KEY_LSHIFT)\r
-                                               || g_input->isKeyDown(irr::KEY_RSHIFT),\r
-                               camera_pitch,\r
-                               camera_yaw\r
-                       );\r
-                       client.setPlayerControl(control);\r
-               }\r
-\r
-               /*\r
-                       Process environment\r
-               */\r
-               \r
-               {\r
-                       //TimeTaker timer("client.step(dtime)");\r
-                       client.step(dtime);\r
-                       //client.step(dtime_avg1);\r
-               }\r
-\r
-               if(server != NULL)\r
-               {\r
-                       //TimeTaker timer("server->step(dtime)");\r
-                       server->step(dtime);\r
-               }\r
-\r
-               v3f player_position = client.getPlayerPosition();\r
-               \r
-               //TimeTaker //timer2("//timer2");\r
-\r
-               /*\r
-                       Mouse and camera control\r
-               */\r
-               \r
-               if((device->isWindowActive() && noMenuActive()) || random_input)\r
-               {\r
-                       if(!random_input)\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 - displaycenter.X;\r
-                               s32 dy = g_input->getMousePos().Y - displaycenter.Y;\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(displaycenter.X, displaycenter.Y);\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
-               // This is at the height of the eyes of the current figure\r
-               //v3f camera_position = player_position + v3f(0, BS+BS/2, 0);\r
-               // This is more like in minecraft\r
-               v3f camera_position = player_position + v3f(0, BS+BS*0.625, 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");\r
-                       client.updateCamera(camera_position, camera_direction);\r
-               }\r
-               \r
-               //timer2.stop();\r
-               //TimeTaker //timer3("//timer3");\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
-\r
-               /*\r
-                       If it's pointing to a MapBlockObject\r
-               */\r
-\r
-               if(selected_object != NULL)\r
-               {\r
-                       //dstream<<"Client returned selected_object != NULL"<<std::endl;\r
-\r
-                       core::aabbox3d<f32> box_on_map\r
-                                       = selected_object->getSelectionBoxOnMap();\r
-\r
-                       hilightboxes.push_back(box_on_map);\r
-\r
-                       infotext = narrow_to_wide(selected_object->infoText());\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
-                               {\r
-                                       dstream<<"Sign object right-clicked"<<std::endl;\r
-                                       \r
-                                       if(random_input == false)\r
-                                       {\r
-                                               // Get a new text for it\r
-\r
-                                               TextDest *dest = new TextDestSign(\r
-                                                               selected_object->getBlock()->getPos(),\r
-                                                               selected_object->getId(),\r
-                                                               &client);\r
-\r
-                                               SignObject *sign_object = (SignObject*)selected_object;\r
-\r
-                                               std::wstring wtext =\r
-                                                               narrow_to_wide(sign_object->getText());\r
-\r
-                                               (new GUITextInputMenu(guienv, guiroot, -1,\r
-                                                               &g_menumgr, dest,\r
-                                                               wtext))->drop();\r
-                                       }\r
-                               }\r
-                               /*\r
-                                       Otherwise pass the event to the server as-is\r
-                               */\r
-                               else\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
-               /*\r
-                       Find out which node we are pointing at\r
-               */\r
-               \r
-               bool nodefound = false;\r
-               v3s16 nodepos;\r
-               v3s16 neighbourpos;\r
-               core::aabbox3d<f32> nodehilightbox;\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
-                       MapNode n;\r
-                       try\r
-                       {\r
-                               n = client.getNode(v3s16(x,y,z));\r
-                               if(content_pointable(n.d) == false)\r
-                                       continue;\r
-                       }\r
-                       catch(InvalidPositionException &e)\r
-                       {\r
-                               continue;\r
-                       }\r
-\r
-                       v3s16 np(x,y,z);\r
-                       v3f npf = intToFloat(np);\r
-                       \r
-                       f32 d = 0.01;\r
-                       \r
-                       v3s16 dirs[6] = {\r
-                               v3s16(0,0,1), // back\r
-                               v3s16(0,1,0), // top\r
-                               v3s16(1,0,0), // right\r
-                               v3s16(0,0,-1), // front\r
-                               v3s16(0,-1,0), // bottom\r
-                               v3s16(-1,0,0), // left\r
-                       };\r
-                       \r
-                       /*\r
-                               Meta-objects\r
-                       */\r
-                       if(n.d == CONTENT_TORCH)\r
-                       {\r
-                               v3s16 dir = unpackDir(n.dir);\r
-                               v3f dir_f = v3f(dir.X, dir.Y, dir.Z);\r
-                               dir_f *= BS/2 - BS/6 - BS/20;\r
-                               v3f cpf = npf + dir_f;\r
-                               f32 distance = (cpf - camera_position).getLength();\r
-\r
-                               core::aabbox3d<f32> box;\r
-                               \r
-                               // bottom\r
-                               if(dir == v3s16(0,-1,0))\r
-                               {\r
-                                       box = core::aabbox3d<f32>(\r
-                                               npf - v3f(BS/6, BS/2, BS/6),\r
-                                               npf + v3f(BS/6, -BS/2+BS/3*2, BS/6)\r
-                                       );\r
-                               }\r
-                               // top\r
-                               else if(dir == v3s16(0,1,0))\r
-                               {\r
-                                       box = core::aabbox3d<f32>(\r
-                                               npf - v3f(BS/6, -BS/2+BS/3*2, BS/6),\r
-                                               npf + v3f(BS/6, BS/2, BS/6)\r
-                                       );\r
-                               }\r
-                               // side\r
-                               else\r
-                               {\r
-                                       box = core::aabbox3d<f32>(\r
-                                               cpf - v3f(BS/6, BS/3, BS/6),\r
-                                               cpf + v3f(BS/6, BS/3, BS/6)\r
-                                       );\r
-                               }\r
-\r
-                               if(distance < mindistance)\r
-                               {\r
-                                       if(box.intersectsWithLine(shootline))\r
-                                       {\r
-                                               nodefound = true;\r
-                                               nodepos = np;\r
-                                               neighbourpos = np;\r
-                                               mindistance = distance;\r
-                                               nodehilightbox = box;\r
-                                       }\r
-                               }\r
-                       }\r
-                       /*\r
-                               Regular blocks\r
-                       */\r
-                       else\r
-                       {\r
-                               for(u16 i=0; i<6; i++)\r
-                               {\r
-                                       v3f dir_f = v3f(dirs[i].X,\r
-                                                       dirs[i].Y, dirs[i].Z);\r
-                                       v3f centerpoint = npf + dir_f * BS/2;\r
-                                       f32 distance =\r
-                                                       (centerpoint - camera_position).getLength();\r
-                                       \r
-                                       if(distance < mindistance)\r
-                                       {\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
-                                               {\r
-                                                       m.rotateVect(corners[j]);\r
-                                                       corners[j] += npf;\r
-                                               }\r
-\r
-                                               core::aabbox3d<f32> facebox(corners[0]);\r
-                                               facebox.addInternalPoint(corners[1]);\r
-\r
-                                               if(facebox.intersectsWithLine(shootline))\r
-                                               {\r
-                                                       nodefound = true;\r
-                                                       nodepos = np;\r
-                                                       neighbourpos = np + dirs[i];\r
-                                                       mindistance = distance;\r
-\r
-                                                       //nodehilightbox = facebox;\r
-\r
-                                                       const float d = 0.502;\r
-                                                       core::aabbox3d<f32> nodebox\r
-                                                                       (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);\r
-                                                       v3f nodepos_f = intToFloat(nodepos);\r
-                                                       nodebox.MinEdge += nodepos_f;\r
-                                                       nodebox.MaxEdge += nodepos_f;\r
-                                                       nodehilightbox = nodebox;\r
-                                               }\r
-                                       } // if distance < mindistance\r
-                               } // for dirs\r
-                       } // regular block\r
-               } // for coords\r
-\r
-               static float nodig_delay_counter = 0.0;\r
-\r
-               if(nodefound)\r
-               {\r
-                       static v3s16 nodepos_old(-32768,-32768,-32768);\r
-\r
-                       static float dig_time = 0.0;\r
-                       static u16 dig_index = 0;\r
-                       \r
-                       // Visualize selection\r
-\r
-                       hilightboxes.push_back(nodehilightbox);\r
-\r
-                       // Handle digging\r
-                       \r
-                       if(g_input->getLeftReleased())\r
-                       {\r
-                               client.clearTempMod(nodepos);\r
-                               dig_time = 0.0;\r
-                       }\r
-                       \r
-                       if(nodig_delay_counter > 0.0)\r
-                       {\r
-                               nodig_delay_counter -= dtime;\r
-                       }\r
-                       else\r
-                       {\r
-                               if(nodepos != nodepos_old)\r
-                               {\r
-                                       std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","\r
-                                                       <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;\r
-\r
-                                       if(nodepos_old != v3s16(-32768,-32768,-32768))\r
-                                       {\r
-                                               client.clearTempMod(nodepos_old);\r
-                                               dig_time = 0.0;\r
-                                       }\r
-                               }\r
-\r
-                               if(g_input->getLeftClicked() ||\r
-                                               (g_input->getLeftState() && nodepos != nodepos_old))\r
-                               {\r
-                                       dstream<<DTIME<<"Started digging"<<std::endl;\r
-                                       client.groundAction(0, nodepos, neighbourpos, g_selected_item);\r
-                               }\r
-                               if(g_input->getLeftClicked())\r
-                               {\r
-                                       client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));\r
-                               }\r
-                               if(g_input->getLeftState())\r
-                               {\r
-                                       MapNode n = client.getNode(nodepos);\r
-                               \r
-                                       // Get tool name. Default is "" = bare hands\r
-                                       std::string toolname = "";\r
-                                       InventoryList *mlist = local_inventory.getList("main");\r
-                                       if(mlist != NULL)\r
-                                       {\r
-                                               InventoryItem *item = mlist->getItem(g_selected_item);\r
-                                               if(item && (std::string)item->getName() == "ToolItem")\r
-                                               {\r
-                                                       ToolItem *titem = (ToolItem*)item;\r
-                                                       toolname = titem->getToolName();\r
-                                               }\r
-                                       }\r
-\r
-                                       // Get digging properties for material and tool\r
-                                       u8 material = n.d;\r
-                                       DiggingProperties prop =\r
-                                                       getDiggingProperties(material, toolname);\r
-                                       \r
-                                       float dig_time_complete = 0.0;\r
-\r
-                                       if(prop.diggable == false)\r
-                                       {\r
-                                               /*dstream<<"Material "<<(int)material\r
-                                                               <<" not diggable with \""\r
-                                                               <<toolname<<"\""<<std::endl;*/\r
-                                               // I guess nobody will wait for this long\r
-                                               dig_time_complete = 10000000.0;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               dig_time_complete = prop.time;\r
-                                       }\r
-                                       \r
-                                       if(dig_time_complete >= 0.001)\r
-                                       {\r
-                                               dig_index = (u16)((float)CRACK_ANIMATION_LENGTH\r
-                                                               * dig_time/dig_time_complete);\r
-                                       }\r
-                                       // This is for torches\r
-                                       else\r
-                                       {\r
-                                               dig_index = CRACK_ANIMATION_LENGTH;\r
-                                       }\r
-\r
-                                       if(dig_index < CRACK_ANIMATION_LENGTH)\r
-                                       {\r
-                                               //TimeTaker timer("client.setTempMod");\r
-                                               //dstream<<"dig_index="<<dig_index<<std::endl;\r
-                                               client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               dstream<<DTIME<<"Digging completed"<<std::endl;\r
-                                               client.groundAction(3, nodepos, neighbourpos, g_selected_item);\r
-                                               client.clearTempMod(nodepos);\r
-                                               client.removeNode(nodepos);\r
-\r
-                                               dig_time = 0;\r
-\r
-                                               nodig_delay_counter = dig_time_complete\r
-                                                               / (float)CRACK_ANIMATION_LENGTH;\r
-\r
-                                               // We don't want a corresponding delay to\r
-                                               // very time consuming nodes\r
-                                               if(nodig_delay_counter > 0.5)\r
-                                               {\r
-                                                       nodig_delay_counter = 0.5;\r
-                                               }\r
-                                               // We want a slight delay to very little\r
-                                               // time consuming nodes\r
-                                               float mindelay = 0.15;\r
-                                               if(nodig_delay_counter < mindelay)\r
-                                               {\r
-                                                       nodig_delay_counter = mindelay;\r
-                                               }\r
-                                       }\r
-\r
-                                       dig_time += dtime;\r
-                               }\r
-                       }\r
-                       \r
-                       if(g_input->getRightClicked())\r
-                       {\r
-                               std::cout<<DTIME<<"Ground right-clicked"<<std::endl;\r
-                               client.groundAction(1, nodepos, neighbourpos, g_selected_item);\r
-                       }\r
-                       \r
-                       nodepos_old = nodepos;\r
-               }\r
-               else{\r
-               }\r
-\r
-               } // selected_object == NULL\r
-               \r
-               g_input->resetLeftClicked();\r
-               g_input->resetRightClicked();\r
-               \r
-               if(g_input->getLeftReleased())\r
-               {\r
-                       std::cout<<DTIME<<"Left button released (stopped digging)"\r
-                                       <<std::endl;\r
-                       client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);\r
-               }\r
-               if(g_input->getRightReleased())\r
-               {\r
-                       //std::cout<<DTIME<<"Right released"<<std::endl;\r
-                       // Nothing here\r
-               }\r
-               \r
-               g_input->resetLeftReleased();\r
-               g_input->resetRightReleased();\r
-               \r
-               /*\r
-                       Calculate stuff for drawing\r
-               */\r
-\r
-               camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);\r
-               \r
-               u32 daynight_ratio = client.getDayNightRatio();\r
-               u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);\r
-               video::SColor bgcolor = video::SColor(\r
-                               255,\r
-                               skycolor.getRed() * l / 255,\r
-                               skycolor.getGreen() * l / 255,\r
-                               skycolor.getBlue() * l / 255);\r
-\r
-               /*\r
-                       Fog\r
-               */\r
-               \r
-               if(g_settings.getBool("enable_fog") == true)\r
-               {\r
-                       //f32 range = draw_control.wanted_range * BS + MAP_BLOCKSIZE/2*BS;\r
-                       f32 range = draw_control.wanted_range * BS + 0.8*MAP_BLOCKSIZE*BS;\r
-                       //f32 range = draw_control.wanted_range * BS + 0.0*MAP_BLOCKSIZE*BS;\r
-                       if(draw_control.range_all)\r
-                               range = 100000*BS;\r
-\r
-                       driver->setFog(\r
-                               bgcolor,\r
-                               video::EFT_FOG_LINEAR,\r
-                               range*0.6,\r
-                               range*1.0,\r
-                               0.01,\r
-                               false, // pixel fog\r
-                               false // range fog\r
-                       );\r
-               }\r
-               else\r
-               {\r
-                       driver->setFog(\r
-                               bgcolor,\r
-                               video::EFT_FOG_LINEAR,\r
-                               100000*BS,\r
-                               110000*BS,\r
-                               0.01,\r
-                               false, // pixel fog\r
-                               false // range fog\r
-                       );\r
-               }\r
-\r
-\r
-               /*\r
-                       Update gui stuff (0ms)\r
-               */\r
-\r
-               //TimeTaker guiupdatetimer("Gui updating");\r
-               \r
-               {\r
-                       static float drawtime_avg = 0;\r
-                       drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;\r
-                       static float beginscenetime_avg = 0;\r
-                       beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;\r
-                       static float scenetime_avg = 0;\r
-                       scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;\r
-                       static float endscenetime_avg = 0;\r
-                       endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;\r
-                       \r
-                       char temptext[300];\r
-                       snprintf(temptext, 300, "Minetest-c55 ("\r
-                                       "F: item=%i"\r
-                                       ", R: range_all=%i"\r
-                                       ")"\r
-                                       " drawtime=%.0f, beginscenetime=%.0f"\r
-                                       ", scenetime=%.0f, endscenetime=%.0f",\r
-                                       g_selected_item,\r
-                                       draw_control.range_all,\r
-                                       drawtime_avg,\r
-                                       beginscenetime_avg,\r
-                                       scenetime_avg,\r
-                                       endscenetime_avg\r
-                                       );\r
-                       \r
-                       guitext->setText(narrow_to_wide(temptext).c_str());\r
-               }\r
-               \r
-               {\r
-                       char temptext[300];\r
-                       snprintf(temptext, 300,\r
-                                       "(% .1f, % .1f, % .1f)"\r
-                                       " (% .3f < btime_jitter < % .3f"\r
-                                       ", dtime_jitter = % .1f %%"\r
-                                       ", v_range = %.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
-                                       draw_control.wanted_range\r
-                                       );\r
-\r
-                       guitext2->setText(narrow_to_wide(temptext).c_str());\r
-               }\r
-               \r
-               {\r
-                       guitext_info->setText(infotext.c_str());\r
-               }\r
-               \r
-               /*\r
-                       Get chat messages from client\r
-               */\r
-               {\r
-                       // Get new messages\r
-                       std::wstring message;\r
-                       while(client.getChatMessage(message))\r
-                       {\r
-                               chat_lines.push_back(ChatLine(message));\r
-                               /*if(chat_lines.size() > 6)\r
-                               {\r
-                                       core::list<ChatLine>::Iterator\r
-                                                       i = chat_lines.begin();\r
-                                       chat_lines.erase(i);\r
-                               }*/\r
-                       }\r
-                       // Append them to form the whole static text and throw\r
-                       // it to the gui element\r
-                       std::wstring whole;\r
-                       // This will correspond to the line number counted from\r
-                       // top to bottom, from size-1 to 0\r
-                       s16 line_number = chat_lines.size();\r
-                       // Count of messages to be removed from the top\r
-                       u16 to_be_removed_count = 0;\r
-                       for(core::list<ChatLine>::Iterator\r
-                                       i = chat_lines.begin();\r
-                                       i != chat_lines.end(); i++)\r
-                       {\r
-                               // After this, line number is valid for this loop\r
-                               line_number--;\r
-                               // Increment age\r
-                               (*i).age += dtime;\r
-                               /*\r
-                                       This results in a maximum age of 60*6 to the\r
-                                       lowermost line and a maximum of 6 lines\r
-                               */\r
-                               float allowed_age = (6-line_number) * 60.0;\r
-\r
-                               if((*i).age > allowed_age)\r
-                               {\r
-                                       to_be_removed_count++;\r
-                                       continue;\r
-                               }\r
-                               whole += (*i).text + L'\n';\r
-                       }\r
-                       for(u16 i=0; i<to_be_removed_count; i++)\r
-                       {\r
-                               core::list<ChatLine>::Iterator\r
-                                               it = chat_lines.begin();\r
-                               chat_lines.erase(it);\r
-                       }\r
-                       guitext_chat->setText(whole.c_str());\r
-\r
-                       // Update gui element size and position\r
-\r
-                       /*core::rect<s32> rect(\r
-                                       10,\r
-                                       screensize.Y - guitext_chat_pad_bottom\r
-                                                       - text_height*chat_lines.size(),\r
-                                       screensize.X - 10,\r
-                                       screensize.Y - guitext_chat_pad_bottom\r
-                       );*/\r
-                       core::rect<s32> rect(\r
-                                       10,\r
-                                       50,\r
-                                       screensize.X - 10,\r
-                                       50 + text_height*chat_lines.size()\r
-                       );\r
-\r
-                       guitext_chat->setRelativePosition(rect);\r
-\r
-                       if(chat_lines.size() == 0)\r
-                               guitext_chat->setVisible(false);\r
-                       else\r
-                               guitext_chat->setVisible(true);\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
-               /*\r
-                       Send actions returned by the inventory menu\r
-               */\r
-               while(inventory_action_queue.size() != 0)\r
-               {\r
-                       InventoryAction *a = inventory_action_queue.pop_front();\r
-\r
-                       client.sendInventoryAction(a);\r
-                       // Eat it\r
-                       delete a;\r
-               }\r
-\r
-               /*\r
-                       Drawing begins\r
-               */\r
-\r
-               TimeTaker drawtimer("Drawing");\r
-\r
-               \r
-               {\r
-                       TimeTaker timer("beginScene");\r
-                       driver->beginScene(true, true, bgcolor);\r
-                       //driver->beginScene(false, true, bgcolor);\r
-                       beginscenetime = timer.stop(true);\r
-               }\r
-\r
-               //timer3.stop();\r
-               \r
-               //std::cout<<DTIME<<"smgr->drawAll()"<<std::endl;\r
-               \r
-               {\r
-                       TimeTaker timer("smgr");\r
-                       smgr->drawAll();\r
-                       scenetime = timer.stop(true);\r
-               }\r
-               \r
-               {\r
-               //TimeTaker timer9("auxiliary drawings");\r
-               // 0ms\r
-               \r
-               //timer9.stop();\r
-               //TimeTaker //timer10("//timer10");\r
-               \r
-               video::SMaterial m;\r
-               //m.Thickness = 10;\r
-               m.Thickness = 3;\r
-               m.Lighting = false;\r
-               driver->setMaterial(m);\r
-\r
-               driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);\r
-\r
-               for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();\r
-                               i != hilightboxes.end(); i++)\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
-               /*\r
-                       Draw crosshair\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
-               /*\r
-                       Frametime log\r
-               */\r
-               if(g_settings.getBool("frametime_graph") == true)\r
-               {\r
-                       s32 x = 10;\r
-                       for(core::list<float>::Iterator\r
-                                       i = frametime_log.begin();\r
-                                       i != frametime_log.end();\r
-                                       i++)\r
-                       {\r
-                               driver->draw2DLine(v2s32(x,50),\r
-                                               v2s32(x,50+(*i)*1000),\r
-                                               video::SColor(255,255,255,255));\r
-                               x++;\r
-                       }\r
-               }\r
-\r
-               } // timer\r
-\r
-               //timer10.stop();\r
-               //TimeTaker //timer11("//timer11");\r
-\r
-               /*\r
-                       Draw gui\r
-               */\r
-               // 0-1ms\r
-               guienv->drawAll();\r
-\r
-               /*\r
-                       Draw hotbar\r
-               */\r
-               {\r
-                       draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),\r
-                                       hotbar_imagesize, hotbar_itemcount, &local_inventory);\r
-               }\r
-               \r
-               // End drawing\r
-               {\r
-                       TimeTaker timer("endScene");\r
-                       driver->endScene();\r
-                       endscenetime = timer.stop(true);\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
-               {\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
-               }\r
-               \r
-               /*}\r
-               else\r
-                       device->yield();*/\r
-       }\r
-\r
-       //delete quick_inventory;\r
-\r
-       /*\r
-               Disable texture fetches and other stuff that is queued\r
-               to be processed by the main loop.\r
-\r
-               This has to be done before client goes out of scope.\r
-       */\r
-       g_irrlicht->Shutdown(true);\r
-\r
-       } // client and server are deleted at this point\r
-\r
-       } //try\r
-       catch(con::PeerNotFoundException &e)\r
-       {\r
-               dstream<<DTIME<<"Connection timed out."<<std::endl;\r
-               error_message = L"Connection timed out.";\r
-       }\r
-\r
-       } // Menu-game loop\r
-       \r
-       delete g_input;\r
-\r
-       /*\r
-               In the end, delete the Irrlicht device.\r
-       */\r
-       device->drop();\r
-       \r
-       /*\r
-               Update configuration file\r
-       */\r
-       /*if(configpath != "")\r
-       {\r
-               g_settings.updateConfigFile(configpath.c_str());\r
-       }*/\r
-\r
-       END_DEBUG_EXCEPTION_HANDLER\r
-       \r
-       debugstreams_deinit();\r
-       \r
-       return 0;\r
-}\r
-\r
-//END\r
+/*
+Minetest-c55
+Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License along
+with this program; if not, write to the Free Software Foundation, Inc.,
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+*/
+
+/*
+=============================== NOTES ==============================
+NOTE: Things starting with TODO are sometimes only suggestions.
+
+NOTE: iostream.imbue(std::locale("C")) is very slow
+NOTE: Global locale is now set at initialization
+
+NOTE: If VBO (EHM_STATIC) is used, remember to explicitly free the
+      hardware buffer (it is not freed automatically)
+
+NOTE: A random to-do list saved here as documentation:
+A list of "active blocks" in which stuff happens. (+=done)
+       + Add a never-resetted game timer to the server
+       + Add a timestamp value to blocks
+       + The simple rule: All blocks near some player are "active"
+       - Do stuff in real time in active blocks
+               + Handle objects
+               - Grow grass, delete leaves without a tree
+               - Spawn some mobs based on some rules
+               - Transform cobble to mossy cobble near water
+               - Run a custom script
+               - ...And all kinds of other dynamic stuff
+       + Keep track of when a block becomes active and becomes inactive
+       + When a block goes inactive:
+               + Store objects statically to block
+               + Store timer value as the timestamp
+       + When a block goes active:
+               + Create active objects out of static objects
+               - Simulate the results of what would have happened if it would have
+                 been active for all the time
+                       - Grow a lot of grass and so on
+       + Initially it is fine to send information about every active object
+         to every player. Eventually it should be modified to only send info
+         about the nearest ones.
+               + This was left to be done by the old system and it sends only the
+                 nearest ones.
+
+Vim conversion regexpes for moving to extended content type storage:
+%s/\(\.\|->\)d \([!=]=\)/\1getContent() \2/g
+%s/content_features(\([^.]*\)\.d)/content_features(\1)/g
+%s/\(\.\|->\)d = \([^;]*\);/\1setContent(\2);/g
+%s/\(getNodeNoExNoEmerge([^)]*)\)\.d/\1.getContent()/g
+%s/\(getNodeNoExNoEmerge(.*)\)\.d/\1.getContent()/g
+%s/\.d;/.getContent();/g
+%s/\(content_liquid\|content_flowing_liquid\|make_liquid_flowing\|content_pointable\)(\([^.]*\).d)/\1(\2.getContent())/g
+Other things to note:
+- node.d = node.param0 (only in raw serialization; use getContent() otherwise)
+- node.param = node.param1
+- node.dir = node.param2
+- content_walkable(node.d) etc should be changed to
+  content_features(node).walkable etc
+- Also check for lines that store the result of getContent to a 8-bit
+  variable and fix them (result of getContent() must be stored in
+  content_t, which is 16-bit)
+
+NOTE: Seeds in 1260:6c77e7dbfd29:
+5721858502589302589:
+       Spawns you on a small sand island with a surface dungeon
+2983455799928051958:
+       Enormous jungle + a surface dungeon at ~(250,0,0)
+
+Old, wild and random suggestions that probably won't be done:
+-------------------------------------------------------------
+
+SUGG: If player is on ground, mainly fetch ground-level blocks
+
+SUGG: Expose Connection's seqnums and ACKs to server and client.
+      - This enables saving many packets and making a faster connection
+         - This also enables server to check if client has received the
+           most recent block sent, for example.
+SUGG: Add a sane bandwidth throttling system to Connection
+
+SUGG: More fine-grained control of client's dumping of blocks from
+      memory
+         - ...What does this mean in the first place?
+
+SUGG: A map editing mode (similar to dedicated server mode)
+
+SUGG: Transfer more blocks in a single packet
+SUGG: A blockdata combiner class, to which blocks are added and at
+      destruction it sends all the stuff in as few packets as possible.
+SUGG: Make a PACKET_COMBINED which contains many subpackets. Utilize
+      it by sending more stuff in a single packet.
+         - Add a packet queue to RemoteClient, from which packets will be
+           combined with object data packets
+               - This is not exactly trivial: the object data packets are
+                 sometimes very big by themselves
+         - This might not give much network performance gain though.
+
+SUGG: Precalculate lighting translation table at runtime (at startup)
+      - This is not doable because it is currently hand-made and not
+           based on some mathematical function.
+               - Note: This has been changing lately
+
+SUGG: A version number to blocks, which increments when the block is
+      modified (node add/remove, water update, lighting update)
+         - This can then be used to make sure the most recent version of
+           a block has been sent to client, for example
+
+SUGG: Make the amount of blocks sending to client and the total
+         amount of blocks dynamically limited. Transferring blocks is the
+         main network eater of this system, so it is the one that has
+         to be throttled so that RTTs stay low.
+
+SUGG: Meshes of blocks could be split into 6 meshes facing into
+      different directions and then only those drawn that need to be
+
+SUGG: Background music based on cellular automata?
+      http://www.earslap.com/projectslab/otomata
+
+SUGG: Simple light color information to air
+
+SUGG: Server-side objects could be moved based on nodes to enable very
+      lightweight operation and simple AI
+       - Not practical; client would still need to show smooth movement.
+
+SUGG: Make a system for pregenerating quick information for mapblocks, so
+         that the client can show them as cubes before they are actually sent
+         or even generated.
+
+SUGG: Erosion simulation at map generation time
+    - This might be plausible if larger areas of map were pregenerated
+         without lighting (which is slow)
+       - Simulate water flows, which would carve out dirt fast and
+         then turn stone into gravel and sand and relocate it.
+       - How about relocating minerals, too? Coal and gold in
+         downstream sand and gravel would be kind of cool
+         - This would need a better way of handling minerals, mainly
+               to have mineral content as a separate field. the first
+               parameter field is free for this.
+       - Simulate rock falling from cliffs when water has removed
+         enough solid rock from the bottom
+
+SUGG: For non-mapgen FarMesh: Add a per-sector database to store surface
+      stuff as simple flags/values
+      - Light?
+         - A building?
+         And at some point make the server send this data to the client too,
+         instead of referring to the noise functions
+         - Ground height
+         - Surface ground type
+         - Trees?
+
+Gaming ideas:
+-------------
+
+- Aim for something like controlling a single dwarf in Dwarf Fortress
+- The player could go faster by a crafting a boat, or riding an animal
+- Random NPC traders. what else?
+
+Game content:
+-------------
+
+- When furnace is destroyed, move items to player's inventory
+- Add lots of stuff
+- Glass blocks
+- Growing grass, decaying leaves
+       - This can be done in the active blocks I guess.
+       - Lots of stuff can be done in the active blocks.
+       - Uh, is there an active block list somewhere? I think not. Add it.
+- Breaking weak structures
+       - This can probably be accomplished in the same way as grass
+- Player health points
+       - When player dies, throw items on map (needs better item-on-map
+         implementation)
+- Cobble to get mossy if near water
+- More slots in furnace source list, so that multiple ingredients
+  are possible.
+- Keys to chests?
+
+- The Treasure Guard; a big monster with a hammer
+       - The hammer does great damage, shakes the ground and removes a block
+       - You can drop on top of it, and have some time to attack there
+         before he shakes you off
+
+- Maybe the difficulty could come from monsters getting tougher in
+  far-away places, and the player starting to need something from
+  there when time goes by.
+  - The player would have some of that stuff at the beginning, and
+    would need new supplies of it when it runs out
+
+- A bomb
+- A spread-items-on-map routine for the bomb, and for dying players
+
+- Fighting:
+  - Proper sword swing simulation
+  - Player should get damage from colliding to a wall at high speed
+
+Documentation:
+--------------
+
+Build system / running:
+-----------------------
+
+Networking and serialization:
+-----------------------------
+
+SUGG: Fix address to be ipv6 compatible
+
+User Interface:
+---------------
+
+Graphics:
+---------
+
+SUGG: Combine MapBlock's face caches to so big pieces that VBO
+      can be used
+      - That is >500 vertices
+         - This is not easy; all the MapBlocks close to the player would
+           still need to be drawn separately and combining the blocks
+               would have to happen in a background thread
+
+SUGG: Make fetching sector's blocks more efficient when rendering
+      sectors that have very large amounts of blocks (on client)
+         - Is this necessary at all?
+
+SUGG: Draw cubes in inventory directly with 3D drawing commands, so that
+      animating them is easier.
+
+SUGG: Option for enabling proper alpha channel for textures
+
+TODO: Flowing water animation
+
+TODO: A setting for enabling bilinear filtering for textures
+
+TODO: Better control of draw_control.wanted_max_blocks
+
+TODO: Further investigate the use of GPU lighting in addition to the
+      current one
+
+TODO: Artificial (night) light could be more yellow colored than sunlight.
+      - This is technically doable.
+         - Also the actual colors of the textures could be made less colorful
+           in the dark but it's a bit more difficult.
+
+SUGG: Somehow make the night less colorful
+
+TODO: Occlusion culling
+      - At the same time, move some of the renderMap() block choosing code
+        to the same place as where the new culling happens.
+      - Shoot some rays per frame and when ready, make a new list of
+           blocks for usage of renderMap and give it a new pointer to it.
+
+Configuration:
+--------------
+
+Client:
+-------
+
+TODO: Untie client network operations from framerate
+      - Needs some input queues or something
+         - This won't give much performance boost because calculating block
+           meshes takes so long
+
+SUGG: Make morning and evening transition more smooth and maybe shorter
+
+TODO: Don't update all meshes always on single node changes, but
+      check which ones should be updated
+         - implement Map::updateNodeMeshes() and the usage of it
+         - It will give almost always a 4x boost in mesh update performance.
+
+- A weapon engine
+
+- Tool/weapon visualization
+
+FIXME: When disconnected to the menu, memory is not freed properly
+
+TODO: Investigate how much the mesh generator thread gets used when
+      transferring map data
+
+Server:
+-------
+
+SUGG: Make an option to the server to disable building and digging near
+      the starting position
+
+FIXME: Server sometimes goes into some infinite PeerNotFoundException loop
+
+* Fix the problem with the server constantly saving one or a few
+  blocks? List the first saved block, maybe it explains.
+  - It is probably caused by oscillating water
+  - TODO: Investigate if this still happens (this is a very old one)
+* Make a small history check to transformLiquids to detect and log
+  continuous oscillations, in such detail that they can be fixed.
+
+FIXME: The new optimized map sending doesn't sometimes send enough blocks
+       from big caves and such
+FIXME: Block send distance configuration does not take effect for some reason
+
+Environment:
+------------
+
+TODO: Add proper hooks to when adding and removing active blocks
+
+TODO: Finish the ActiveBlockModifier stuff and use it for something
+
+Objects:
+--------
+
+TODO: Get rid of MapBlockObjects and use only ActiveObjects
+       - Skipping the MapBlockObject data is nasty - there is no "total
+         length" stored; have to make a SkipMBOs function which contains
+         enough of the current code to skip them properly.
+
+SUGG: MovingObject::move and Player::move are basically the same.
+      combine them.
+       - NOTE: This is a bit tricky because player has the sneaking ability
+       - NOTE: Player::move is more up-to-date.
+       - NOTE: There is a simple move implementation now in collision.{h,cpp}
+       - NOTE: MovingObject will be deleted (MapBlockObject)
+
+TODO: Add a long step function to objects that is called with the time
+      difference when block activates
+
+Map:
+----
+
+TODO: Mineral and ground material properties
+      - This way mineral ground toughness can be calculated with just
+           some formula, as well as tool strengths. Sounds too.
+         - There are TODOs in appropriate files: material.h, content_mapnode.h
+
+TODO: Flowing water to actually contain flow direction information
+      - There is a space for this - it just has to be implemented.
+
+TODO: Consider smoothening cave floors after generating them
+
+TODO: Fix make_tree, make_* to use seed-position-consistent pseudorandom
+         - delta also
+
+Misc. stuff:
+------------
+TODO: Make sure server handles removing grass when a block is placed (etc)
+      - The client should not do it by itself
+         - NOTE: I think nobody does it currently...
+TODO: Block cube placement around player's head
+TODO: Protocol version field
+TODO: Think about using same bits for material for fences and doors, for
+         example
+TODO: Move mineral to param2, increment map serialization version, add
+      conversion
+
+SUGG: Restart irrlicht completely when coming back to main menu from game.
+       - This gets rid of everything that is stored in irrlicht's caches.
+       - This might be needed for texture pack selection in menu
+
+TODO: Merge bahamada's audio stuff (clean patch available)
+
+TODO: Move content_features to mapnode_content_features.{h,cpp} or so
+
+TODO: Fix item use() stuff; dropping a stack of cooked rats and eating
+      it gives 3 hearts and consumes all the rats.
+
+Making it more portable:
+------------------------
+Stuff to do before release:
+---------------------------
+
+Fixes to the current release:
+-----------------------------
+
+Stuff to do after release:
+---------------------------
+
+Doing currently:
+----------------
+
+======================================================================
+
+*/
+
+#ifdef NDEBUG
+       #ifdef _WIN32
+               #pragma message ("Disabling unit tests")
+       #else
+               #warning "Disabling unit tests"
+       #endif
+       // Disable unit tests
+       #define ENABLE_TESTS 0
+#else
+       // Enable unit tests
+       #define ENABLE_TESTS 1
+#endif
+
+#ifdef _MSC_VER
+       #pragma comment(lib, "Irrlicht.lib")
+       //#pragma comment(lib, "jthread.lib")
+       #pragma comment(lib, "zlibwapi.lib")
+       #pragma comment(lib, "Shell32.lib")
+       // This would get rid of the console window
+       //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
+#endif
+
+#include "irrlicht.h" // createDevice
+
+#include "main.h"
+#include "mainmenumanager.h"
+#include <iostream>
+#include <fstream>
+#include <locale.h>
+#include "common_irrlicht.h"
+#include "debug.h"
+#include "test.h"
+#include "server.h"
+#include "constants.h"
+#include "porting.h"
+#include "gettime.h"
+#include "guiMessageMenu.h"
+#include "filesys.h"
+#include "config.h"
+#include "guiMainMenu.h"
+#include "mineral.h"
+#include "materials.h"
+#include "game.h"
+#include "keycode.h"
+#include "tile.h"
+#include "defaultsettings.h"
+#include "gettext.h"
+#include "settings.h"
+#include "profiler.h"
+#include "log.h"
+
+// This makes textures
+ITextureSource *g_texturesource = NULL;
+
+/*
+       Settings.
+       These are loaded from the config file.
+*/
+Settings main_settings;
+Settings *g_settings = &main_settings;
+
+// Global profiler
+Profiler main_profiler;
+Profiler *g_profiler = &main_profiler;
+
+/*
+       Random stuff
+*/
+
+/*
+       mainmenumanager.h
+*/
+
+gui::IGUIEnvironment* guienv = NULL;
+gui::IGUIStaticText *guiroot = NULL;
+MainMenuManager g_menumgr;
+
+bool noMenuActive()
+{
+       return (g_menumgr.menuCount() == 0);
+}
+
+// Passed to menus to allow disconnecting and exiting
+MainGameCallback *g_gamecallback = NULL;
+
+/*
+       Debug streams
+*/
+
+// Connection
+std::ostream *dout_con_ptr = &dummyout;
+std::ostream *derr_con_ptr = &verbosestream;
+
+// Server
+std::ostream *dout_server_ptr = &infostream;
+std::ostream *derr_server_ptr = &errorstream;
+
+// Client
+std::ostream *dout_client_ptr = &infostream;
+std::ostream *derr_client_ptr = &errorstream;
+
+/*
+       gettime.h implementation
+*/
+
+// A small helper class
+class TimeGetter
+{
+public:
+       virtual u32 getTime() = 0;
+};
+
+// A precise irrlicht one
+class IrrlichtTimeGetter: public TimeGetter
+{
+public:
+       IrrlichtTimeGetter(IrrlichtDevice *device):
+               m_device(device)
+       {}
+       u32 getTime()
+       {
+               if(m_device == NULL)
+                       return 0;
+               return m_device->getTimer()->getRealTime();
+       }
+private:
+       IrrlichtDevice *m_device;
+};
+// Not so precise one which works without irrlicht
+class SimpleTimeGetter: public TimeGetter
+{
+public:
+       u32 getTime()
+       {
+               return porting::getTimeMs();
+       }
+};
+
+// A pointer to a global instance of the time getter
+// TODO: why?
+TimeGetter *g_timegetter = NULL;
+
+u32 getTimeMs()
+{
+       if(g_timegetter == NULL)
+               return 0;
+       return g_timegetter->getTime();
+}
+
+/*
+       Event handler for Irrlicht
+
+       NOTE: Everything possible should be moved out from here,
+             probably to InputHandler and the_game
+*/
+
+class MyEventReceiver : public IEventReceiver
+{
+public:
+       // This is the one method that we have to implement
+       virtual bool OnEvent(const SEvent& event)
+       {
+               /*
+                       React to nothing here if a menu is active
+               */
+               if(noMenuActive() == false)
+               {
+                       return false;
+               }
+
+               // Remember whether each key is down or up
+               if(event.EventType == irr::EET_KEY_INPUT_EVENT)
+               {
+                       if(event.KeyInput.PressedDown) {
+                               keyIsDown.set(event.KeyInput);
+                               keyWasDown.set(event.KeyInput);
+                       } else {
+                               keyIsDown.unset(event.KeyInput);
+                       }
+               }
+
+               if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
+               {
+                       if(noMenuActive() == false)
+                       {
+                               left_active = false;
+                               middle_active = false;
+                               right_active = false;
+                       }
+                       else
+                       {
+                               left_active = event.MouseInput.isLeftPressed();
+                               middle_active = event.MouseInput.isMiddlePressed();
+                               right_active = event.MouseInput.isRightPressed();
+
+                               if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
+                               {
+                                       leftclicked = true;
+                               }
+                               if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
+                               {
+                                       rightclicked = true;
+                               }
+                               if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
+                               {
+                                       leftreleased = true;
+                               }
+                               if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
+                               {
+                                       rightreleased = true;
+                               }
+                               if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
+                               {
+                                       mouse_wheel += event.MouseInput.Wheel;
+                               }
+                       }
+               }
+
+               return false;
+       }
+
+       bool IsKeyDown(const KeyPress &keyCode) const
+       {
+               return keyIsDown[keyCode];
+       }
+       
+       // Checks whether a key was down and resets the state
+       bool WasKeyDown(const KeyPress &keyCode)
+       {
+               bool b = keyWasDown[keyCode];
+               if (b)
+                       keyWasDown.unset(keyCode);
+               return b;
+       }
+
+       s32 getMouseWheel()
+       {
+               s32 a = mouse_wheel;
+               mouse_wheel = 0;
+               return a;
+       }
+
+       void clearInput()
+       {
+               keyIsDown.clear();
+               keyWasDown.clear();
+
+               leftclicked = false;
+               rightclicked = false;
+               leftreleased = false;
+               rightreleased = false;
+
+               left_active = false;
+               middle_active = false;
+               right_active = false;
+
+               mouse_wheel = 0;
+       }
+
+       MyEventReceiver()
+       {
+               clearInput();
+       }
+
+       bool leftclicked;
+       bool rightclicked;
+       bool leftreleased;
+       bool rightreleased;
+
+       bool left_active;
+       bool middle_active;
+       bool right_active;
+
+       s32 mouse_wheel;
+
+private:
+       IrrlichtDevice *m_device;
+       
+       // The current state of keys
+       KeyList keyIsDown;
+       // Whether a key has been pressed or not
+       KeyList keyWasDown;
+};
+
+/*
+       Separated input handler
+*/
+
+class RealInputHandler : public InputHandler
+{
+public:
+       RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
+               m_device(device),
+               m_receiver(receiver)
+       {
+       }
+       virtual bool isKeyDown(const KeyPress &keyCode)
+       {
+               return m_receiver->IsKeyDown(keyCode);
+       }
+       virtual bool wasKeyDown(const KeyPress &keyCode)
+       {
+               return m_receiver->WasKeyDown(keyCode);
+       }
+       virtual v2s32 getMousePos()
+       {
+               return m_device->getCursorControl()->getPosition();
+       }
+       virtual void setMousePos(s32 x, s32 y)
+       {
+               m_device->getCursorControl()->setPosition(x, y);
+       }
+
+       virtual bool getLeftState()
+       {
+               return m_receiver->left_active;
+       }
+       virtual bool getRightState()
+       {
+               return m_receiver->right_active;
+       }
+       
+       virtual bool getLeftClicked()
+       {
+               return m_receiver->leftclicked;
+       }
+       virtual bool getRightClicked()
+       {
+               return m_receiver->rightclicked;
+       }
+       virtual void resetLeftClicked()
+       {
+               m_receiver->leftclicked = false;
+       }
+       virtual void resetRightClicked()
+       {
+               m_receiver->rightclicked = false;
+       }
+
+       virtual bool getLeftReleased()
+       {
+               return m_receiver->leftreleased;
+       }
+       virtual bool getRightReleased()
+       {
+               return m_receiver->rightreleased;
+       }
+       virtual void resetLeftReleased()
+       {
+               m_receiver->leftreleased = false;
+       }
+       virtual void resetRightReleased()
+       {
+               m_receiver->rightreleased = false;
+       }
+
+       virtual s32 getMouseWheel()
+       {
+               return m_receiver->getMouseWheel();
+       }
+
+       void clear()
+       {
+               m_receiver->clearInput();
+       }
+private:
+       IrrlichtDevice *m_device;
+       MyEventReceiver *m_receiver;
+};
+
+class RandomInputHandler : public InputHandler
+{
+public:
+       RandomInputHandler()
+       {
+               leftdown = false;
+               rightdown = false;
+               leftclicked = false;
+               rightclicked = false;
+               leftreleased = false;
+               rightreleased = false;
+               keydown.clear();
+       }
+       virtual bool isKeyDown(const KeyPress &keyCode)
+       {
+               return keydown[keyCode];
+       }
+       virtual bool wasKeyDown(const KeyPress &keyCode)
+       {
+               return false;
+       }
+       virtual v2s32 getMousePos()
+       {
+               return mousepos;
+       }
+       virtual void setMousePos(s32 x, s32 y)
+       {
+               mousepos = v2s32(x,y);
+       }
+
+       virtual bool getLeftState()
+       {
+               return leftdown;
+       }
+       virtual bool getRightState()
+       {
+               return rightdown;
+       }
+
+       virtual bool getLeftClicked()
+       {
+               return leftclicked;
+       }
+       virtual bool getRightClicked()
+       {
+               return rightclicked;
+       }
+       virtual void resetLeftClicked()
+       {
+               leftclicked = false;
+       }
+       virtual void resetRightClicked()
+       {
+               rightclicked = false;
+       }
+
+       virtual bool getLeftReleased()
+       {
+               return leftreleased;
+       }
+       virtual bool getRightReleased()
+       {
+               return rightreleased;
+       }
+       virtual void resetLeftReleased()
+       {
+               leftreleased = false;
+       }
+       virtual void resetRightReleased()
+       {
+               rightreleased = false;
+       }
+
+       virtual s32 getMouseWheel()
+       {
+               return 0;
+       }
+
+       virtual void step(float dtime)
+       {
+               {
+                       static float counter1 = 0;
+                       counter1 -= dtime;
+                       if(counter1 < 0.0)
+                       {
+                               counter1 = 0.1*Rand(1, 40);
+                               keydown.toggle(getKeySetting("keymap_jump"));
+                       }
+               }
+               {
+                       static float counter1 = 0;
+                       counter1 -= dtime;
+                       if(counter1 < 0.0)
+                       {
+                               counter1 = 0.1*Rand(1, 40);
+                               keydown.toggle(getKeySetting("keymap_special1"));
+                       }
+               }
+               {
+                       static float counter1 = 0;
+                       counter1 -= dtime;
+                       if(counter1 < 0.0)
+                       {
+                               counter1 = 0.1*Rand(1, 40);
+                               keydown.toggle(getKeySetting("keymap_forward"));
+                       }
+               }
+               {
+                       static float counter1 = 0;
+                       counter1 -= dtime;
+                       if(counter1 < 0.0)
+                       {
+                               counter1 = 0.1*Rand(1, 40);
+                               keydown.toggle(getKeySetting("keymap_left"));
+                       }
+               }
+               {
+                       static float counter1 = 0;
+                       counter1 -= dtime;
+                       if(counter1 < 0.0)
+                       {
+                               counter1 = 0.1*Rand(1, 20);
+                               mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
+                       }
+               }
+               {
+                       static float counter1 = 0;
+                       counter1 -= dtime;
+                       if(counter1 < 0.0)
+                       {
+                               counter1 = 0.1*Rand(1, 30);
+                               leftdown = !leftdown;
+                               if(leftdown)
+                                       leftclicked = true;
+                               if(!leftdown)
+                                       leftreleased = true;
+                       }
+               }
+               {
+                       static float counter1 = 0;
+                       counter1 -= dtime;
+                       if(counter1 < 0.0)
+                       {
+                               counter1 = 0.1*Rand(1, 15);
+                               rightdown = !rightdown;
+                               if(rightdown)
+                                       rightclicked = true;
+                               if(!rightdown)
+                                       rightreleased = true;
+                       }
+               }
+               mousepos += mousespeed;
+       }
+
+       s32 Rand(s32 min, s32 max)
+       {
+               return (myrand()%(max-min+1))+min;
+       }
+private:
+       KeyList keydown;
+       v2s32 mousepos;
+       v2s32 mousespeed;
+       bool leftdown;
+       bool rightdown;
+       bool leftclicked;
+       bool rightclicked;
+       bool leftreleased;
+       bool rightreleased;
+};
+
+// These are defined global so that they're not optimized too much.
+// Can't change them to volatile.
+s16 temp16;
+f32 tempf;
+v3f tempv3f1;
+v3f tempv3f2;
+std::string tempstring;
+std::string tempstring2;
+
+void SpeedTests()
+{
+       {
+               dstream<<"The following test should take around 20ms."<<std::endl;
+               TimeTaker timer("Testing std::string speed");
+               const u32 jj = 10000;
+               for(u32 j=0; j<jj; j++)
+               {
+                       tempstring = "";
+                       tempstring2 = "";
+                       const u32 ii = 10;
+                       for(u32 i=0; i<ii; i++){
+                               tempstring2 += "asd";
+                       }
+                       for(u32 i=0; i<ii+1; i++){
+                               tempstring += "asd";
+                               if(tempstring == tempstring2)
+                                       break;
+                       }
+               }
+       }
+       
+       dstream<<"All of the following tests should take around 100ms each."
+                       <<std::endl;
+
+       {
+               TimeTaker timer("Testing floating-point conversion speed");
+               tempf = 0.001;
+               for(u32 i=0; i<4000000; i++){
+                       temp16 += tempf;
+                       tempf += 0.001;
+               }
+       }
+       
+       {
+               TimeTaker timer("Testing floating-point vector speed");
+
+               tempv3f1 = v3f(1,2,3);
+               tempv3f2 = v3f(4,5,6);
+               for(u32 i=0; i<10000000; i++){
+                       tempf += tempv3f1.dotProduct(tempv3f2);
+                       tempv3f2 += v3f(7,8,9);
+               }
+       }
+
+       {
+               TimeTaker timer("Testing core::map speed");
+               
+               core::map<v2s16, f32> map1;
+               tempf = -324;
+               const s16 ii=300;
+               for(s16 y=0; y<ii; y++){
+                       for(s16 x=0; x<ii; x++){
+                               map1.insert(v2s16(x,y), tempf);
+                               tempf += 1;
+                       }
+               }
+               for(s16 y=ii-1; y>=0; y--){
+                       for(s16 x=0; x<ii; x++){
+                               tempf = map1[v2s16(x,y)];
+                       }
+               }
+       }
+
+       {
+               dstream<<"Around 5000/ms should do well here."<<std::endl;
+               TimeTaker timer("Testing mutex speed");
+               
+               JMutex m;
+               m.Init();
+               u32 n = 0;
+               u32 i = 0;
+               do{
+                       n += 10000;
+                       for(; i<n; i++){
+                               m.Lock();
+                               m.Unlock();
+                       }
+               }
+               // Do at least 10ms
+               while(timer.getTime() < 10);
+
+               u32 dtime = timer.stop();
+               u32 per_ms = n / dtime;
+               dstream<<"Done. "<<dtime<<"ms, "
+                               <<per_ms<<"/ms"<<std::endl;
+       }
+}
+
+void drawMenuBackground(video::IVideoDriver* driver)
+{
+       core::dimension2d<u32> screensize = driver->getScreenSize();
+               
+       video::ITexture *bgtexture =
+                       driver->getTexture(getTexturePath("mud.png").c_str());
+       if(bgtexture)
+       {
+               s32 texturesize = 128;
+               s32 tiled_y = screensize.Height / texturesize + 1;
+               s32 tiled_x = screensize.Width / texturesize + 1;
+               
+               for(s32 y=0; y<tiled_y; y++)
+               for(s32 x=0; x<tiled_x; x++)
+               {
+                       core::rect<s32> rect(0,0,texturesize,texturesize);
+                       rect += v2s32(x*texturesize, y*texturesize);
+                       driver->draw2DImage(bgtexture, rect,
+                               core::rect<s32>(core::position2d<s32>(0,0),
+                               core::dimension2di(bgtexture->getSize())),
+                               NULL, NULL, true);
+               }
+       }
+       
+       video::ITexture *logotexture =
+                       driver->getTexture(getTexturePath("menulogo.png").c_str());
+       if(logotexture)
+       {
+               v2s32 logosize(logotexture->getOriginalSize().Width,
+                               logotexture->getOriginalSize().Height);
+               logosize *= 4;
+
+               video::SColor bgcolor(255,50,50,50);
+               core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,
+                               screensize.Width, screensize.Height);
+               driver->draw2DRectangle(bgcolor, bgrect, NULL);
+
+               core::rect<s32> rect(0,0,logosize.X,logosize.Y);
+               rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);
+               rect -= v2s32(logosize.X/2, 0);
+               driver->draw2DImage(logotexture, rect,
+                       core::rect<s32>(core::position2d<s32>(0,0),
+                       core::dimension2di(logotexture->getSize())),
+                       NULL, NULL, true);
+       }
+}
+
+class DstreamLogOutput: public ILogOutput
+{
+public:
+       /* line: Full line with timestamp, level and thread */
+       void printLog(const std::string &line)
+       {
+               dstream<<line<<std::endl;
+       }
+} main_dstream_log_out;
+
+class DstreamNoStderrLogOutput: public ILogOutput
+{
+public:
+       /* line: Full line with timestamp, level and thread */
+       void printLog(const std::string &line)
+       {
+               dstream_no_stderr<<line<<std::endl;
+       }
+} main_dstream_no_stderr_log_out;
+
+int main(int argc, char *argv[])
+{
+       /*
+               Initialization
+       */
+
+       log_add_output_maxlev(&main_dstream_log_out, LMT_ACTION);
+       log_add_output_all_levs(&main_dstream_no_stderr_log_out);
+
+       log_register_thread("main");
+
+       // Set locale. This is for forcing '.' as the decimal point.
+       std::locale::global(std::locale("C"));
+       // This enables printing all characters in bitmap font
+       setlocale(LC_CTYPE, "en_US");
+
+       /*
+               Parse command line
+       */
+       
+       // List all allowed options
+       core::map<std::string, ValueSpec> allowed_options;
+       allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG));
+       allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
+                       "Run server directly"));
+       allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
+                       "Load configuration from specified file"));
+       allowed_options.insert("port", ValueSpec(VALUETYPE_STRING));
+       allowed_options.insert("address", ValueSpec(VALUETYPE_STRING));
+       allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG));
+       allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG));
+       allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG));
+       allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING));
+#ifdef _WIN32
+       allowed_options.insert("dstream-on-stderr", ValueSpec(VALUETYPE_FLAG));
+#endif
+       allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG));
+       allowed_options.insert("info-on-stderr", ValueSpec(VALUETYPE_FLAG));
+
+       Settings cmd_args;
+       
+       bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
+
+       if(ret == false || cmd_args.getFlag("help"))
+       {
+               dstream<<"Allowed options:"<<std::endl;
+               for(core::map<std::string, ValueSpec>::Iterator
+                               i = allowed_options.getIterator();
+                               i.atEnd() == false; i++)
+               {
+                       dstream<<"  --"<<i.getNode()->getKey();
+                       if(i.getNode()->getValue().type == VALUETYPE_FLAG)
+                       {
+                       }
+                       else
+                       {
+                               dstream<<" <value>";
+                       }
+                       dstream<<std::endl;
+
+                       if(i.getNode()->getValue().help != NULL)
+                       {
+                               dstream<<"      "<<i.getNode()->getValue().help
+                                               <<std::endl;
+                       }
+               }
+
+               return cmd_args.getFlag("help") ? 0 : 1;
+       }
+       
+       /*
+               Low-level initialization
+       */
+
+       bool disable_stderr = false;
+#ifdef _WIN32
+       if(cmd_args.getFlag("dstream-on-stderr") == false)
+               disable_stderr = true;
+#endif
+       
+       if(cmd_args.getFlag("info-on-stderr"))
+               log_add_output(&main_dstream_log_out, LMT_INFO);
+
+       porting::signal_handler_init();
+       bool &kill = *porting::signal_handler_killstatus();
+       
+       // Initialize porting::path_data and porting::path_userdata
+       porting::initializePaths();
+
+       // Create user data directory
+       fs::CreateDir(porting::path_userdata);
+
+       init_gettext((porting::path_data+"/../locale").c_str());
+       
+       // Initialize debug streams
+#ifdef RUN_IN_PLACE
+       std::string debugfile = DEBUGFILE;
+#else
+       std::string debugfile = porting::path_userdata+"/"+DEBUGFILE;
+#endif
+       debugstreams_init(disable_stderr, debugfile.c_str());
+       // Initialize debug stacks
+       debug_stacks_init();
+
+       DSTACK(__FUNCTION_NAME);
+
+       // Init material properties table
+       //initializeMaterialProperties();
+
+       // Debug handler
+       BEGIN_DEBUG_EXCEPTION_HANDLER
+
+       // Print startup message
+       actionstream<<PROJECT_NAME<<
+                       " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
+                       <<", "<<BUILD_INFO
+                       <<std::endl;
+       
+       /*
+               Basic initialization
+       */
+
+       // Initialize default settings
+       set_default_settings(g_settings);
+       
+       // Initialize sockets
+       sockets_init();
+       atexit(sockets_cleanup);
+       
+       /*
+               Read config file
+       */
+       
+       // Path of configuration file in use
+       std::string configpath = "";
+       
+       if(cmd_args.exists("config"))
+       {
+               bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
+               if(r == false)
+               {
+                       errorstream<<"Could not read configuration from \""
+                                       <<cmd_args.get("config")<<"\""<<std::endl;
+                       return 1;
+               }
+               configpath = cmd_args.get("config");
+       }
+       else
+       {
+               core::array<std::string> filenames;
+               filenames.push_back(porting::path_userdata + "/minetest.conf");
+#ifdef RUN_IN_PLACE
+               filenames.push_back(porting::path_userdata + "/../minetest.conf");
+#endif
+
+               for(u32 i=0; i<filenames.size(); i++)
+               {
+                       bool r = g_settings->readConfigFile(filenames[i].c_str());
+                       if(r)
+                       {
+                               configpath = filenames[i];
+                               break;
+                       }
+               }
+               
+               // If no path found, use the first one (menu creates the file)
+               if(configpath == "")
+                       configpath = filenames[0];
+       }
+
+       // Initialize random seed
+       srand(time(0));
+       mysrand(time(0));
+
+       /*
+               Pre-initialize some stuff with a dummy irrlicht wrapper.
+
+               These are needed for unit tests at least.
+       */
+       
+       // Initial call with g_texturesource not set.
+       init_mapnode();
+
+       /*
+               Run unit tests
+       */
+
+       if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
+                       || cmd_args.getFlag("enable-unittests") == true)
+       {
+               run_tests();
+       }
+       
+       /*for(s16 y=-100; y<100; y++)
+       for(s16 x=-100; x<100; x++)
+       {
+               std::cout<<noise2d_gradient((double)x/10,(double)y/10, 32415)<<std::endl;
+       }
+       return 0;*/
+       
+       /*
+               Game parameters
+       */
+
+       // Port
+       u16 port = 30000;
+       if(cmd_args.exists("port"))
+               port = cmd_args.getU16("port");
+       else if(g_settings->exists("port"))
+               port = g_settings->getU16("port");
+       if(port == 0)
+               port = 30000;
+       
+       // Map directory
+       std::string map_dir = porting::path_userdata+"/world";
+       if(cmd_args.exists("map-dir"))
+               map_dir = cmd_args.get("map-dir");
+       else if(g_settings->exists("map-dir"))
+               map_dir = g_settings->get("map-dir");
+       
+       // Run dedicated server if asked to
+       if(cmd_args.getFlag("server"))
+       {
+               DSTACK("Dedicated server branch");
+
+               // Create time getter
+               g_timegetter = new SimpleTimeGetter();
+               
+               // Create server
+               Server server(map_dir.c_str(), configpath);
+               server.start(port);
+               
+               // Run server
+               dedicated_server_loop(server, kill);
+
+               return 0;
+       }
+
+
+       /*
+               More parameters
+       */
+       
+       // Address to connect to
+       std::string address = "";
+       
+       if(cmd_args.exists("address"))
+       {
+               address = cmd_args.get("address");
+       }
+       else
+       {
+               address = g_settings->get("address");
+       }
+       
+       std::string playername = g_settings->get("name");
+
+       /*
+               Device initialization
+       */
+
+       // Resolution selection
+       
+       bool fullscreen = false;
+       u16 screenW = g_settings->getU16("screenW");
+       u16 screenH = g_settings->getU16("screenH");
+
+       // Determine driver
+
+       video::E_DRIVER_TYPE driverType;
+       
+       std::string driverstring = g_settings->get("video_driver");
+
+       if(driverstring == "null")
+               driverType = video::EDT_NULL;
+       else if(driverstring == "software")
+               driverType = video::EDT_SOFTWARE;
+       else if(driverstring == "burningsvideo")
+               driverType = video::EDT_BURNINGSVIDEO;
+       else if(driverstring == "direct3d8")
+               driverType = video::EDT_DIRECT3D8;
+       else if(driverstring == "direct3d9")
+               driverType = video::EDT_DIRECT3D9;
+       else if(driverstring == "opengl")
+               driverType = video::EDT_OPENGL;
+       else
+       {
+               errorstream<<"WARNING: Invalid video_driver specified; defaulting "
+                               "to opengl"<<std::endl;
+               driverType = video::EDT_OPENGL;
+       }
+
+       /*
+               Create device and exit if creation failed
+       */
+
+       MyEventReceiver receiver;
+
+       IrrlichtDevice *device;
+       device = createDevice(driverType,
+                       core::dimension2d<u32>(screenW, screenH),
+                       16, fullscreen, false, false, &receiver);
+
+       if (device == 0)
+               return 1; // could not create selected driver.
+       
+       // Set the window caption
+       device->setWindowCaption(L"Minetest [Main Menu]");
+       
+       // Create time getter
+       g_timegetter = new IrrlichtTimeGetter(device);
+       
+       // Create game callback for menus
+       g_gamecallback = new MainGameCallback(device);
+       
+       // Create texture source
+       g_texturesource = new TextureSource(device);
+
+       /*
+               Speed tests (done after irrlicht is loaded to get timer)
+       */
+       if(cmd_args.getFlag("speedtests"))
+       {
+               dstream<<"Running speed tests"<<std::endl;
+               SpeedTests();
+               return 0;
+       }
+       
+       device->setResizable(true);
+
+       bool random_input = g_settings->getBool("random_input")
+                       || cmd_args.getFlag("random-input");
+       InputHandler *input = NULL;
+       if(random_input)
+               input = new RandomInputHandler();
+       else
+               input = new RealInputHandler(device, &receiver);
+       
+       /*
+               Continue initialization
+       */
+
+       //video::IVideoDriver* driver = device->getVideoDriver();
+
+       /*
+               This changes the minimum allowed number of vertices in a VBO.
+               Default is 500.
+       */
+       //driver->setMinHardwareBufferVertexCount(50);
+
+       scene::ISceneManager* smgr = device->getSceneManager();
+
+       guienv = device->getGUIEnvironment();
+       gui::IGUISkin* skin = guienv->getSkin();
+       gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
+       if(font)
+               skin->setFont(font);
+       else
+               errorstream<<"WARNING: Font file was not found."
+                               " Using default font."<<std::endl;
+       // If font was not found, this will get us one
+       font = skin->getFont();
+       assert(font);
+       
+       u32 text_height = font->getDimension(L"Hello, world!").Height;
+       infostream<<"text_height="<<text_height<<std::endl;
+
+       //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
+       skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
+       //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
+       //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
+       skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
+       skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
+       
+       /*
+               Preload some textures and stuff
+       */
+
+       init_mapnode(); // Second call with g_texturesource set
+       init_mineral();
+
+       /*
+               GUI stuff
+       */
+
+       /*
+               If an error occurs, this is set to something and the
+               menu-game loop is restarted. It is then displayed before
+               the menu.
+       */
+       std::wstring error_message = L"";
+
+       // The password entered during the menu screen,
+       std::string password;
+
+       /*
+               Menu-game loop
+       */
+       while(device->run() && kill == false)
+       {
+
+               // This is used for catching disconnects
+               try
+               {
+
+                       /*
+                               Clear everything from the GUIEnvironment
+                       */
+                       guienv->clear();
+                       
+                       /*
+                               We need some kind of a root node to be able to add
+                               custom gui elements directly on the screen.
+                               Otherwise they won't be automatically drawn.
+                       */
+                       guiroot = guienv->addStaticText(L"",
+                                       core::rect<s32>(0, 0, 10000, 10000));
+                       
+                       /*
+                               Out-of-game menu loop.
+
+                               Loop quits when menu returns proper parameters.
+                       */
+                       while(kill == false)
+                       {
+                               // Cursor can be non-visible when coming from the game
+                               device->getCursorControl()->setVisible(true);
+                               // Some stuff are left to scene manager when coming from the game
+                               // (map at least?)
+                               smgr->clear();
+                               // Reset or hide the debug gui texts
+                               /*guitext->setText(L"Minetest-c55");
+                               guitext2->setVisible(false);
+                               guitext_info->setVisible(false);
+                               guitext_chat->setVisible(false);*/
+                               
+                               // Initialize menu data
+                               MainMenuData menudata;
+                               menudata.address = narrow_to_wide(address);
+                               menudata.name = narrow_to_wide(playername);
+                               menudata.port = narrow_to_wide(itos(port));
+                               menudata.fancy_trees = g_settings->getBool("new_style_leaves");
+                               menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
+                               menudata.creative_mode = g_settings->getBool("creative_mode");
+                               menudata.enable_damage = g_settings->getBool("enable_damage");
+
+                               GUIMainMenu *menu =
+                                               new GUIMainMenu(guienv, guiroot, -1, 
+                                                       &g_menumgr, &menudata, g_gamecallback);
+                               menu->allowFocusRemoval(true);
+
+                               if(error_message != L"")
+                               {
+                                       errorstream<<"error_message = "
+                                                       <<wide_to_narrow(error_message)<<std::endl;
+
+                                       GUIMessageMenu *menu2 =
+                                                       new GUIMessageMenu(guienv, guiroot, -1, 
+                                                               &g_menumgr, error_message.c_str());
+                                       menu2->drop();
+                                       error_message = L"";
+                               }
+
+                               video::IVideoDriver* driver = device->getVideoDriver();
+                               
+                               infostream<<"Created main menu"<<std::endl;
+
+                               while(device->run() && kill == false)
+                               {
+                                       if(menu->getStatus() == true)
+                                               break;
+
+                                       //driver->beginScene(true, true, video::SColor(255,0,0,0));
+                                       driver->beginScene(true, true, video::SColor(255,128,128,128));
+
+                                       drawMenuBackground(driver);
+
+                                       guienv->drawAll();
+                                       
+                                       driver->endScene();
+                                       
+                                       // On some computers framerate doesn't seem to be
+                                       // automatically limited
+                                       sleep_ms(25);
+                               }
+                               
+                               // Break out of menu-game loop to shut down cleanly
+                               if(device->run() == false || kill == true)
+                                       break;
+                               
+                               infostream<<"Dropping main menu"<<std::endl;
+
+                               menu->drop();
+                               
+                               // Delete map if requested
+                               if(menudata.delete_map)
+                               {
+                                       bool r = fs::RecursiveDeleteContent(map_dir);
+                                       if(r == false)
+                                               error_message = L"Delete failed";
+                                       continue;
+                               }
+
+                               playername = wide_to_narrow(menudata.name);
+
+                               password = translatePassword(playername, menudata.password);
+
+                               //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
+
+                               address = wide_to_narrow(menudata.address);
+                               int newport = stoi(wide_to_narrow(menudata.port));
+                               if(newport != 0)
+                                       port = newport;
+                               g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
+                               g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
+                               g_settings->set("creative_mode", itos(menudata.creative_mode));
+                               g_settings->set("enable_damage", itos(menudata.enable_damage));
+                               
+                               // NOTE: These are now checked server side; no need to do it
+                               //       here, so let's not do it here.
+                               /*// Check for valid parameters, restart menu if invalid.
+                               if(playername == "")
+                               {
+                                       error_message = L"Name required.";
+                                       continue;
+                               }
+                               // Check that name has only valid chars
+                               if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
+                               {
+                                       error_message = L"Characters allowed: "
+                                                       +narrow_to_wide(PLAYERNAME_ALLOWED_CHARS);
+                                       continue;
+                               }*/
+
+                               // Save settings
+                               g_settings->set("name", playername);
+                               g_settings->set("address", address);
+                               g_settings->set("port", itos(port));
+                               // Update configuration file
+                               if(configpath != "")
+                                       g_settings->updateConfigFile(configpath.c_str());
+                       
+                               // Continue to game
+                               break;
+                       }
+                       
+                       // Break out of menu-game loop to shut down cleanly
+                       if(device->run() == false)
+                               break;
+                       
+                       // Initialize mapnode again to enable changed graphics settings
+                       init_mapnode();
+
+                       /*
+                               Run game
+                       */
+                       the_game(
+                               kill,
+                               random_input,
+                               input,
+                               device,
+                               font,
+                               map_dir,
+                               playername,
+                               password,
+                               address,
+                               port,
+                               error_message,
+                               configpath
+                       );
+
+               } //try
+               catch(con::PeerNotFoundException &e)
+               {
+                       errorstream<<"Connection error (timed out?)"<<std::endl;
+                       error_message = L"Connection error (timed out?)";
+               }
+               catch(SocketException &e)
+               {
+                       errorstream<<"Socket error (port already in use?)"<<std::endl;
+                       error_message = L"Socket error (port already in use?)";
+               }
+#ifdef NDEBUG
+               catch(std::exception &e)
+               {
+                       std::string narrow_message = "Some exception, what()=\"";
+                       narrow_message += e.what();
+                       narrow_message += "\"";
+                       errorstream<<narrow_message<<std::endl;
+                       error_message = narrow_to_wide(narrow_message);
+               }
+#endif
+
+       } // Menu-game loop
+       
+       delete input;
+
+       /*
+               In the end, delete the Irrlicht device.
+       */
+       device->drop();
+       
+       END_DEBUG_EXCEPTION_HANDLER(errorstream)
+       
+       debugstreams_deinit();
+       
+       return 0;
+}
+
+//END
+