]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - src/main.cpp
CMake stuff works now on linux and windows... and should be possible to make to work...
[dragonfireclient.git] / src / main.cpp
index a2185450f0922a1b548359f11b8c7848050ec12c..a0da103c94aa06974495ea867aa1b80f99b188bb 100644 (file)
@@ -27,50 +27,7 @@ NOTE: VBO cannot be turned on for fast-changing stuff because there
 NOTE: iostream.imbue(std::locale("C")) is very slow\r
 NOTE: Global locale is now set at initialization\r
 \r
-SUGGESTION: add a second lighting value to the MS nibble of param of\r
-       air to tell how bright the air node is when there is no sunlight.\r
-       When day changes to night, these two values can be interpolated.\r
-\r
-TODO: Fix address to be ipv6 compatible\r
-\r
-TODO: ESC Pause mode in which the cursor is not kept at the center of window.\r
-TODO: Stop player if focus of window is taken away (go to pause mode)\r
-TODO: Optimize and fix makeFastFace or whatever it's called\r
-      - Face calculation is the source of CPU usage on the client\r
-SUGGESTION: The client will calculate and send lighting changes and\r
-  the server will randomly check some of them and kick the client out\r
-  if it fails to calculate them right.\r
-  - Actually, it could just start ignoring them and calculate them\r
-    itself.\r
-SUGGESTION: Combine MapBlock's face caches to so big pieces that VBO\r
-            gets used\r
-            - That is >500 vertices\r
-\r
-TODO: Better dungeons\r
-TODO: There should be very slight natural caves also, starting from\r
-      only a straightened-up cliff\r
-\r
-TODO: Changing of block with mouse wheel or something\r
-TODO: Menus\r
-\r
-TODO: Mobs\r
-      - Server:\r
-        - One single map container with ids as keys\r
-      - Client:\r
-           - ?\r
-TODO: - Keep track of the place of the mob in the last few hundreth's\r
-        of a second - then, if a player hits it, take the value that is\r
-               avg_rtt/2 before the moment the packet is received.\r
-TODO: - Scripting\r
-\r
-SUGGESTION: Modify client to calculate single changes asynchronously\r
-\r
-TODO: Moving players more smoothly. Calculate moving animation\r
-      in a way that doesn't make the player jump to the right place\r
-         immediately when the server sends a new position\r
-\r
-TODO: There are some lighting-related todos and fixmes in\r
-      ServerMap::emergeBlock\r
+SUGG: Fix address to be ipv6 compatible\r
 \r
 FIXME: When a new sector is generated, it may change the ground level\r
        of it's and it's neighbors border that two blocks that are\r
@@ -81,12 +38,7 @@ SUGGESTION: Use same technique for sector heightmaps as what we're
             using for UnlimitedHeightmap? (getting all neighbors\r
                        when generating)\r
 \r
-SUGG: Set server to automatically find a good spawning place in some\r
-      place where there is water and land.\r
-         - Map to have a getWalkableNear(p)\r
-         - Is this a good idea? It's part of the game to find a good place.\r
-\r
-TODO: Transfer more blocks in a single packet\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
@@ -97,80 +49,155 @@ SUGG: Expose Connection's seqnums and ACKs to server and client.
       - 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
-TODO: Add a sane bandwidth throttling system to Connection\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
-TODO: Make the amount of blocks sending to client and the total\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: Implement lighting using VoxelManipulator\r
+      - Would it be significantly faster?\r
+\r
+FIXME: Rats somehow go underground sometimes (you can see it in water)\r
+       - Does their position get saved to a border value or something?\r
+          - Does this happen anymore?\r
+\r
+SUGG: MovingObject::move and Player::move are basically the same.\r
+      combine them.\r
+\r
+SUGG: Implement a "Fast check queue" (a queue with a map for checking\r
+      if something is already in it)\r
+      - Use it in active block queue in water flowing\r
+\r
+SUGG: Precalculate lighting translation table at runtime (at startup)\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
-TODO: Server to load starting inventory from disk\r
+SUGG: Meshes of blocks could be split into 6 meshes facing into\r
+      different directions and then only those drawn that need to be\r
+         - Also an 1-dimensional tile map would be nice probably\r
+\r
+TODO: Untie client network operations from framerate\r
+      - Needs some input queues or something\r
+         - Not really necessary?\r
 \r
-TODO: PLayers to only be hidden when the client quits.\r
+TODO: Combine MapBlock's face caches to so big pieces that VBO\r
+      gets used\r
+      - That is >500 vertices\r
+\r
+TODO: Startup and configuration menu\r
+\r
+TODO: There are some lighting-related todos and fixmes in\r
+      ServerMap::emergeBlock\r
+\r
+TODO: Proper handling of spawning place (try to find something that\r
+      is not in the middle of an ocean (some land to stand on at\r
+         least) and save it in map config.\r
+\r
+TODO: Players to only be hidden when the client quits.\r
 TODO: - Players to be saved on disk, with inventory\r
 TODO: Players to be saved as text in map/players/<name>\r
-\r
-SUGG: A map editing mode (similar to dedicated server mode)\r
+TODO: Player inventory to be saved on disk\r
 \r
 TODO: Make fetching sector's blocks more efficient when rendering\r
       sectors that have very large amounts of blocks (on client)\r
 \r
 TODO: Make the video backend selectable\r
 \r
+TODO: Copy the text of the last picked sign to inventory in creative\r
+      mode\r
+\r
+TODO: Get rid of GotSplitPacketException\r
+\r
+TODO: Check what goes wrong with caching map to disk (Kray)\r
+      - Nothing?\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, the time difference is calculated and\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
-TODO: A timestamp to blocks\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
+TODO: Better handling of objects and mobs\r
+      - Scripting?\r
+      - There has to be some way to do it with less spaghetti 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: Add config parameters for server's sending and generating distance\r
+TODO: Draw big amounts of torches better (that is, throw them in the\r
+      same meshbuffer (can the meshcollector class be used?))\r
 \r
-TODO: Copy the text of the last picked sign to inventory in creative\r
-      mode\r
+TODO: Make an option to the server to disable building and digging near\r
+      the starting position\r
 \r
-TODO: Untie client network operations from framerate\r
-      - Needs some input queues or something\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
+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
 \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
+TODO: When server sees that client is removing an inexistent block or\r
+      adding a block to an existent position, resend the MapBlock.\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
+TODO: When player dies, throw items on map\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
+TODO: Use porting::path_userdata for configuration file\r
 \r
-TODO: Get rid of GotSplitPacketException\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
 \r
-SUGG: Implement lighting using VoxelManipulator\r
-      - Would it be significantly faster?\r
-\r
-TODO: Check what goes wrong with caching map to disk (Kray)\r
+TODO: Map generator version 2\r
+       - Create surface areas based on central points; a given point's\r
+         area type is given by the nearest central point\r
+         - Separate points for heightmap, caves, plants and minerals?\r
+         - Flat land, mountains, forest, jungle\r
+    - Cliffs, arcs\r
 \r
-TODO: Remove LazyMeshUpdater. It is not used as supposed.\r
+TODO: Add gui option to remove map\r
 \r
 Doing now:\r
 ======================================================================\r
 \r
-\r
 ======================================================================\r
 \r
 */\r
@@ -185,7 +212,7 @@ Doing now:
 */\r
 #define FIELD_OF_VIEW_TEST 0\r
 \r
-#ifdef UNITTEST_DISABLE\r
+#ifdef NDEBUG\r
        #ifdef _WIN32\r
                #pragma message ("Disabling unit tests")\r
        #else\r
@@ -201,23 +228,15 @@ Doing now:
 #ifdef _MSC_VER\r
 #pragma comment(lib, "Irrlicht.lib")\r
 #pragma comment(lib, "jthread.lib")\r
+#pragma comment(lib, "zlibwapi.lib")\r
 // This would get rid of the console window\r
 //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")\r
 #endif\r
 \r
-#ifdef _WIN32\r
-       #define WIN32_LEAN_AND_MEAN\r
-       #include <windows.h>\r
-       #define sleep_ms(x) Sleep(x)\r
-#else\r
-       #include <unistd.h>\r
-       #define sleep_ms(x) usleep(x*1000)\r
-#endif\r
-\r
 #include <iostream>\r
 #include <fstream>\r
-#include <time.h>\r
 #include <jmutexautolock.h>\r
+#include <locale.h>\r
 #include "common_irrlicht.h"\r
 #include "debug.h"\r
 #include "map.h"\r
@@ -231,45 +250,20 @@ Doing now:
 #include "constants.h"\r
 #include "strfnd.h"\r
 #include "porting.h"\r
-#include <locale.h>\r
-\r
-IrrlichtDevice *g_device = NULL;\r
-\r
-const char *g_material_filenames[MATERIALS_COUNT] =\r
-{\r
-       "../data/stone.png",\r
-       "../data/grass.png",\r
-       "../data/water.png",\r
-       "../data/light.png",\r
-       "../data/tree.png",\r
-       "../data/leaves.png",\r
-       "../data/grass_footsteps.png",\r
-       "../data/mese.png",\r
-       "../data/mud.png"\r
-};\r
-\r
-video::SMaterial g_materials[MATERIALS_COUNT];\r
-//video::SMaterial g_mesh_materials[3];\r
-\r
-// All range-related stuff below is locked behind this\r
-JMutex g_range_mutex;\r
-\r
-// Blocks are viewed in this range from the player\r
-s16 g_viewing_range_nodes = 60;\r
-\r
-// This is updated by the client's fetchBlocks routine\r
-//s16 g_actual_viewing_range_nodes = VIEWING_RANGE_NODES_DEFAULT;\r
-\r
-// If true, the preceding value has no meaning and all blocks\r
-// already existing in memory are drawn\r
-bool g_viewing_range_all = false;\r
+#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
 \r
-// This is the freetime ratio imposed by the dynamic viewing\r
-// range changing code.\r
-// It is controlled by the main loop to the smallest value that\r
-// inhibits glitches (dtime jitter) in the main loop.\r
-//float g_freetime_ratio = FREETIME_RATIO_MAX;\r
+IrrlichtWrapper *g_irrlicht;\r
 \r
+MapDrawControl draw_control;\r
 \r
 /*\r
        Settings.\r
@@ -278,53 +272,33 @@ bool g_viewing_range_all = false;
 \r
 Settings g_settings;\r
 \r
-// Sets default settings\r
-void set_default_settings()\r
-{\r
-       g_settings.set("dedicated_server", "");\r
-\r
-       // Client stuff\r
-       g_settings.set("wanted_fps", "30");\r
-       g_settings.set("fps_max", "60");\r
-       g_settings.set("viewing_range_nodes_max", "300");\r
-       g_settings.set("viewing_range_nodes_min", "20");\r
-       g_settings.set("screenW", "");\r
-       g_settings.set("screenH", "");\r
-       g_settings.set("host_game", "");\r
-       g_settings.set("port", "");\r
-       g_settings.set("address", "");\r
-       g_settings.set("name", "");\r
-       g_settings.set("random_input", "false");\r
-       g_settings.set("client_delete_unused_sectors_timeout", "1200");\r
-\r
-       // Server stuff\r
-       g_settings.set("creative_mode", "false");\r
-       g_settings.set("heightmap_blocksize", "128");\r
-       g_settings.set("height_randmax", "constant 70.0");\r
-       g_settings.set("height_randfactor", "constant 0.6");\r
-       g_settings.set("height_base", "linear 0 35 0");\r
-       g_settings.set("plants_amount", "1.0");\r
-       g_settings.set("ravines_amount", "1.0");\r
-       g_settings.set("objectdata_interval", "0.2");\r
-       g_settings.set("active_object_range", "2");\r
-       g_settings.set("max_simultaneous_block_sends_per_client", "1");\r
-       g_settings.set("max_simultaneous_block_sends_server_total", "4");\r
-}\r
+extern void set_default_settings();\r
 \r
 /*\r
        Random stuff\r
 */\r
 \r
-//u16 g_selected_material = 0;\r
-u16 g_selected_item = 0;\r
+IrrlichtDevice *g_device = NULL;\r
+Client *g_client = NULL;\r
+\r
+/*\r
+       GUI Stuff\r
+*/\r
+gui::IGUIEnvironment* guienv = NULL;\r
+gui::IGUIStaticText *guiroot = NULL;\r
+int g_active_menu_count = 0;\r
 \r
-bool g_esc_pressed = false;\r
+bool noMenuActive()\r
+{\r
+       return (g_active_menu_count == 0);\r
+}\r
 \r
-std::wstring g_text_buffer;\r
-bool g_text_buffer_accepted = false;\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
-// When true, the mouse and keyboard are grabbed\r
-bool g_game_focused = true;\r
+u16 g_selected_item = 0;\r
 \r
 /*\r
        Debug streams\r
@@ -346,26 +320,60 @@ std::ostream *derr_server_ptr = &dstream;
 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
-       Timestamp stuff\r
+       Text input system\r
 */\r
 \r
-JMutex g_timestamp_mutex;\r
-//std::string g_timestamp;\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
-std::string getTimestamp()\r
+       v3s16 m_blockpos;\r
+       s16 m_id;\r
+       Client *m_client;\r
+};\r
+\r
+struct TextDestChat : public TextDest\r
 {\r
-       if(g_timestamp_mutex.IsInitialized()==false)\r
-               return "";\r
-       JMutexAutoLock lock(g_timestamp_mutex);\r
-       //return g_timestamp;\r
-       time_t t = time(NULL);\r
-       struct tm *tm = localtime(&t);\r
-       char cs[20];\r
-       strftime(cs, 20, "%H:%M:%S", tm);\r
-       return cs;\r
-}\r
+       TextDestChat(Client *client)\r
+       {\r
+               m_client = client;\r
+       }\r
+       void gotText(std::wstring text)\r
+       {\r
+               m_client->sendChatMessage(text);\r
+               m_client->addChatMessage(text);\r
+       }\r
+\r
+       Client *m_client;\r
+};\r
 \r
 class MyEventReceiver : public IEventReceiver\r
 {\r
@@ -373,6 +381,15 @@ class MyEventReceiver : public IEventReceiver
        // This is the one method that we have to implement\r
        virtual bool OnEvent(const SEvent& event)\r
        {\r
+               /*\r
+                       React to nothing here if a menu is active\r
+               */\r
+               if(noMenuActive() == false)\r
+               {\r
+                       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
@@ -381,70 +398,69 @@ class MyEventReceiver : public IEventReceiver
                        if(event.KeyInput.PressedDown)\r
                        {\r
                                //dstream<<"Pressed key: "<<(char)event.KeyInput.Key<<std::endl;\r
-                               if(g_game_focused == false)\r
+                               \r
+                               /*\r
+                                       Launch menus\r
+                               */\r
+\r
+                               if(guienv != NULL && guiroot != NULL && g_device != NULL)\r
                                {\r
-                                       s16 key = event.KeyInput.Key;\r
-                                       if(key == irr::KEY_RETURN || key == irr::KEY_ESCAPE)\r
+                                       if(event.KeyInput.Key == irr::KEY_ESCAPE)\r
                                        {\r
-                                               g_text_buffer_accepted = true;\r
+                                               dstream<<DTIME<<"MyEventReceiver: "\r
+                                                               <<"Launching pause menu"<<std::endl;\r
+                                               // It will delete itself by itself\r
+                                               (new GUIPauseMenu(guienv, guiroot, -1, g_device,\r
+                                                               &g_active_menu_count))->drop();\r
+                                               return true;\r
                                        }\r
-                                       else if(key == irr::KEY_BACK)\r
-                                       {\r
-                                               if(g_text_buffer.size() > 0)\r
-                                                       g_text_buffer = g_text_buffer.substr\r
-                                                                       (0, g_text_buffer.size()-1);\r
-                                       }\r
-                                       else\r
+                                       if(event.KeyInput.Key == irr::KEY_KEY_I)\r
                                        {\r
-                                               wchar_t wc = event.KeyInput.Char;\r
-                                               if(wc != 0)\r
-                                                       g_text_buffer += wc;\r
+                                               dstream<<DTIME<<"MyEventReceiver: "\r
+                                                               <<"Launching inventory"<<std::endl;\r
+                                               (new GUIInventoryMenu(guienv, guiroot, -1,\r
+                                                               &local_inventory, &inventory_action_queue,\r
+                                                               &g_active_menu_count))->drop();\r
+                                               return true;\r
                                        }\r
-                               }\r
-                               \r
-                               if(event.KeyInput.Key == irr::KEY_ESCAPE)\r
-                               {\r
-                                       if(g_game_focused == true)\r
+                                       if(event.KeyInput.Key == irr::KEY_KEY_T)\r
                                        {\r
-                                               dstream<<DTIME<<"ESC pressed"<<std::endl;\r
-                                               g_esc_pressed = true;\r
+                                               TextDest *dest = new TextDestChat(g_client);\r
+\r
+                                               (new GUITextInputMenu(guienv, guiroot, -1,\r
+                                                               &g_active_menu_count, dest,\r
+                                                               L""))->drop();\r
                                        }\r
                                }\r
 \r
                                // Material selection\r
                                if(event.KeyInput.Key == irr::KEY_KEY_F)\r
                                {\r
-                                       if(g_game_focused == true)\r
-                                       {\r
-                                               if(g_selected_item < PLAYER_INVENTORY_SIZE-1)\r
-                                                       g_selected_item++;\r
-                                               else\r
-                                                       g_selected_item = 0;\r
-                                               dstream<<DTIME<<"Selected item: "\r
-                                                               <<g_selected_item<<std::endl;\r
-                                       }\r
+                                       if(g_selected_item < PLAYER_INVENTORY_SIZE-1)\r
+                                               g_selected_item++;\r
+                                       else\r
+                                               g_selected_item = 0;\r
+                                       dstream<<DTIME<<"Selected item: "\r
+                                                       <<g_selected_item<<std::endl;\r
                                }\r
 \r
                                // Viewing range selection\r
-                               if(event.KeyInput.Key == irr::KEY_KEY_R\r
-                                               && g_game_focused)\r
+                               if(event.KeyInput.Key == irr::KEY_KEY_R)\r
                                {\r
-                                       JMutexAutoLock lock(g_range_mutex);\r
-                                       if(g_viewing_range_all)\r
+                                       if(draw_control.range_all)\r
                                        {\r
-                                               g_viewing_range_all = false;\r
+                                               draw_control.range_all = false;\r
                                                dstream<<DTIME<<"Disabled full viewing range"<<std::endl;\r
                                        }\r
                                        else\r
                                        {\r
-                                               g_viewing_range_all = true;\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
-                                               && g_game_focused)\r
+                               if(event.KeyInput.Key == irr::KEY_KEY_P)\r
                                {\r
                                        dstream<<"-----------------------------------------"\r
                                                        <<std::endl;\r
@@ -458,31 +474,53 @@ class MyEventReceiver : public IEventReceiver
 \r
                if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)\r
                {\r
-                       if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)\r
-                       {\r
-                               leftclicked = true;\r
-                       }\r
-                       if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)\r
+                       if(noMenuActive() == false)\r
                        {\r
-                               rightclicked = true;\r
+                               left_active = false;\r
+                               middle_active = false;\r
+                               right_active = false;\r
                        }\r
-                       if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)\r
+                       else\r
                        {\r
-                               /*dstream<<"event.MouseInput.Wheel="\r
-                                               <<event.MouseInput.Wheel<<std::endl;*/\r
-                               if(event.MouseInput.Wheel < 0)\r
+                               //dstream<<"MyEventReceiver: mouse input"<<std::endl;\r
+                               left_active = event.MouseInput.isLeftPressed();\r
+                               middle_active = event.MouseInput.isMiddlePressed();\r
+                               right_active = event.MouseInput.isRightPressed();\r
+\r
+                               if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)\r
                                {\r
-                                       if(g_selected_item < PLAYER_INVENTORY_SIZE-1)\r
-                                               g_selected_item++;\r
-                                       else\r
-                                               g_selected_item = 0;\r
+                                       leftclicked = true;\r
                                }\r
-                               else if(event.MouseInput.Wheel > 0)\r
+                               if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)\r
                                {\r
-                                       if(g_selected_item > 0)\r
-                                               g_selected_item--;\r
-                                       else\r
-                                               g_selected_item = PLAYER_INVENTORY_SIZE-1;\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
+                                       if(event.MouseInput.Wheel < 0)\r
+                                       {\r
+                                               if(g_selected_item < PLAYER_INVENTORY_SIZE-1)\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 = PLAYER_INVENTORY_SIZE-1;\r
+                                       }\r
                                }\r
                        }\r
                }\r
@@ -496,21 +534,41 @@ class MyEventReceiver : public IEventReceiver
                return keyIsDown[keyCode];\r
        }\r
 \r
-       MyEventReceiver()\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
@@ -522,13 +580,24 @@ class InputHandler
        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
@@ -537,17 +606,6 @@ class InputHandler
 \r
 InputHandler *g_input = NULL;\r
 \r
-void focusGame()\r
-{\r
-       g_input->clear();\r
-       g_game_focused = true;\r
-}\r
-\r
-void unFocusGame()\r
-{\r
-       g_game_focused = false;\r
-}\r
-\r
 class RealInputHandler : public InputHandler\r
 {\r
 public:\r
@@ -569,16 +627,21 @@ class RealInputHandler : public InputHandler
                m_device->getCursorControl()->setPosition(x, y);\r
        }\r
 \r
+       virtual bool getLeftState()\r
+       {\r
+               return m_receiver->left_active;\r
+       }\r
+       virtual bool getRightState()\r
+       {\r
+               return m_receiver->right_active;\r
+       }\r
+       \r
        virtual bool getLeftClicked()\r
        {\r
-               if(g_game_focused == false)\r
-                       return false;\r
                return m_receiver->leftclicked;\r
        }\r
        virtual bool getRightClicked()\r
        {\r
-               if(g_game_focused == false)\r
-                       return false;\r
                return m_receiver->rightclicked;\r
        }\r
        virtual void resetLeftClicked()\r
@@ -590,6 +653,23 @@ class RealInputHandler : public InputHandler
                m_receiver->rightclicked = false;\r
        }\r
 \r
+       virtual bool getLeftReleased()\r
+       {\r
+               return m_receiver->leftreleased;\r
+       }\r
+       virtual bool getRightReleased()\r
+       {\r
+               return m_receiver->rightreleased;\r
+       }\r
+       virtual void resetLeftReleased()\r
+       {\r
+               m_receiver->leftreleased = false;\r
+       }\r
+       virtual void resetRightReleased()\r
+       {\r
+               m_receiver->rightreleased = false;\r
+       }\r
+\r
        void clear()\r
        {\r
                resetRightClicked();\r
@@ -623,6 +703,15 @@ class RandomInputHandler : public InputHandler
                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
@@ -640,6 +729,21 @@ class RandomInputHandler : public InputHandler
                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
@@ -648,7 +752,7 @@ class RandomInputHandler : public InputHandler
                        if(counter1 < 0.0)\r
                        {\r
                                counter1 = 0.1*Rand(1,10);\r
-                               /*if(g_selected_material < USEFUL_MATERIAL_COUNT-1)\r
+                               /*if(g_selected_material < USEFUL_CONTENT_COUNT-1)\r
                                        g_selected_material++;\r
                                else\r
                                        g_selected_material = 0;*/\r
@@ -726,7 +830,7 @@ class RandomInputHandler : public InputHandler
 \r
        s32 Rand(s32 min, s32 max)\r
        {\r
-               return (rand()%(max-min+1))+min;\r
+               return (myrand()%(max-min+1))+min;\r
        }\r
 private:\r
        bool keydown[KEY_KEY_CODES_COUNT];\r
@@ -736,82 +840,135 @@ class RandomInputHandler : public InputHandler
        bool rightclicked;\r
 };\r
 \r
-void updateViewingRange(f32 frametime, Client *client)\r
+void updateViewingRange(f32 frametime_in, Client *client)\r
 {\r
-       // Range_all messes up frametime_avg\r
-       if(g_viewing_range_all == true)\r
+       if(draw_control.range_all == true)\r
                return;\r
-\r
-       float wanted_fps = g_settings.getFloat("wanted_fps");\r
        \r
-       // Initialize to the target value\r
-       static float frametime_avg = 1.0/wanted_fps;\r
-       frametime_avg = frametime_avg * 0.9 + frametime * 0.1;\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
-       if(counter > 0){\r
-               counter -= frametime;\r
+       counter -= frametime_in;\r
+       if(counter > 0)\r
                return;\r
-       }\r
-       //counter = 1.0; //seconds\r
-       counter = 0.5; //seconds\r
+       //counter = 0.1;\r
+       counter = 0.2;\r
 \r
-       //float freetime_ratio = 0.2;\r
-       //float freetime_ratio = 0.4;\r
-       float freetime_ratio = FREETIME_RATIO;\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
-       float frametime_wanted = (1.0/(wanted_fps/(1.0-freetime_ratio)));\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 fraction = sqrt(frametime_avg / frametime_wanted);\r
+       float range = draw_control.wanted_range;\r
+       float new_range = range;\r
 \r
-       static bool fraction_is_good = false;\r
+       static s16 range_old = 0;\r
+       static f32 frametime_old = 0;\r
        \r
-       float fraction_good_threshold = 0.1;\r
-       float fraction_bad_threshold = 0.25;\r
-       float fraction_limit;\r
-       // Use high limit if fraction is good AND the fraction would\r
-       // lower the range. We want to keep the range fairly high.\r
-       if(fraction_is_good && fraction > 1.0)\r
-               fraction_limit = fraction_bad_threshold;\r
-       else\r
-               fraction_limit = fraction_good_threshold;\r
-\r
-       if(fabs(fraction - 1.0) < fraction_limit)\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
-               fraction_is_good = true;\r
-               return;\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
-               fraction_is_good = false;\r
+               //dstream<<"time_per_range="<<time_per_range<<std::endl;\r
        }\r
 \r
-       //dstream<<"frametime_avg="<<frametime_avg<<std::endl;\r
-       //dstream<<"frametime_wanted="<<frametime_wanted<<std::endl;\r
-       /*dstream<<"fetching="<<client->isFetchingBlocks()\r
-                       <<" faction = "<<fraction<<std::endl;*/\r
+       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
-       JMutexAutoLock lock(g_range_mutex);\r
-       \r
-       s16 viewing_range_nodes_min = g_settings.getS16("viewing_range_nodes_min");\r
-       s16 viewing_range_nodes_max = g_settings.getS16("viewing_range_nodes_max");\r
-\r
-       s16 n = (float)g_viewing_range_nodes / fraction;\r
-       if(n < viewing_range_nodes_min)\r
-               n = viewing_range_nodes_min;\r
-       if(n > viewing_range_nodes_max)\r
-               n = viewing_range_nodes_max;\r
-\r
-       bool can_change = true;\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
-       if(client->isFetchingBlocks() == true && n > g_viewing_range_nodes)\r
-               can_change = false;\r
+       new_range += wanted_range_change;\r
+       //dstream<<"new_range="<<new_range/*<<std::endl*/;\r
        \r
-       if(can_change)\r
-               g_viewing_range_nodes = n;\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
-       /*dstream<<"g_viewing_range_nodes = "\r
-                       <<g_viewing_range_nodes<<std::endl;*/\r
+       range_old = new_range;\r
+       frametime_old = frametime;\r
 }\r
 \r
 class GUIQuickInventory : public IEventReceiver\r
@@ -864,16 +1021,18 @@ class GUIQuickInventory : public IEventReceiver
 \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)m_inventory->getSize() - 1)\r
-                               j -= m_inventory->getSize();\r
+                       if(j > (s32)mainlist->getSize() - 1)\r
+                               j -= mainlist->getSize();\r
                        if(j < 0)\r
-                               j += m_inventory->getSize();\r
+                               j += mainlist->getSize();\r
                        \r
-                       InventoryItem *item = m_inventory->getItem(j);\r
+                       InventoryItem *item = mainlist->getItem(j);\r
                        // Null items\r
                        if(item == NULL)\r
                        {\r
@@ -910,6 +1069,22 @@ class GUIQuickInventory : public IEventReceiver
        s32 m_selection;\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
 int main(int argc, char *argv[])\r
 {\r
        /*\r
@@ -928,9 +1103,73 @@ int main(int argc, char *argv[])
 \r
        DSTACK(__FUNCTION_NAME);\r
 \r
+       porting::initializePaths();\r
+       // Create user data directory\r
+       fs::CreateDir(porting::path_userdata);\r
+\r
+       initializeMaterialProperties();\r
+\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
        try\r
        {\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
+\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
        /*\r
                Basic initialization\r
        */\r
@@ -938,12 +1177,6 @@ int main(int argc, char *argv[])
        // Initialize default settings\r
        set_default_settings();\r
        \r
-       // Print startup message\r
-       dstream<<DTIME<<"minetest-c55"\r
-                       " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST\r
-                       <<", ENABLE_TESTS="<<ENABLE_TESTS\r
-                       <<std::endl;\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
@@ -953,49 +1186,60 @@ int main(int argc, char *argv[])
        sockets_init();\r
        atexit(sockets_cleanup);\r
        \r
-       // Initialize timestamp mutex\r
-       g_timestamp_mutex.Init();\r
-\r
-       /*\r
-               Run unit tests\r
-       */\r
-       if(ENABLE_TESTS)\r
-       {\r
-               run_tests();\r
-       }\r
-       \r
        /*\r
                Initialization\r
        */\r
 \r
-       // Read config file\r
+       /*\r
+               Read config file\r
+       */\r
        \r
-       if(argc >= 2)\r
+       // Path of configuration file in use\r
+       std::string configpath = "";\r
+       \r
+       if(cmd_args.exists("config"))\r
        {\r
-               g_settings.readConfigFile(argv[1]);\r
+               bool r = g_settings.readConfigFile(cmd_args.get("config").c_str());\r
+               if(r == false)\r
+               {\r
+                       dstream<<"Could not read configuration from \""\r
+                                       <<cmd_args.get("config")<<"\""<<std::endl;\r
+                       return 1;\r
+               }\r
+               configpath = cmd_args.get("config");\r
        }\r
        else\r
        {\r
-               const char *filenames[2] =\r
-               {\r
-                       "../minetest.conf",\r
-                       "../../minetest.conf"\r
-               };\r
+               core::array<std::string> filenames;\r
+               filenames.push_back(porting::path_userdata + "/minetest.conf");\r
+#ifdef RUN_IN_PLACE\r
+               filenames.push_back(porting::path_userdata + "/../minetest.conf");\r
+#endif\r
 \r
-               for(u32 i=0; i<2; i++)\r
+               for(u32 i=0; i<filenames.size(); i++)\r
                {\r
-                       bool r = g_settings.readConfigFile(filenames[i]);\r
+                       bool r = g_settings.readConfigFile(filenames[i].c_str());\r
                        if(r)\r
+                       {\r
+                               configpath = filenames[i];\r
                                break;\r
+                       }\r
                }\r
        }\r
 \r
        // Initialize random seed\r
        srand(time(0));\r
+       mysrand(time(0));\r
 \r
-       g_range_mutex.Init();\r
-       assert(g_range_mutex.IsInitialized());\r
-\r
+       /*\r
+               Run unit tests\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
        // Read map parameters from settings\r
 \r
        HMParams hm_params;\r
@@ -1013,18 +1257,39 @@ int main(int argc, char *argv[])
        */\r
 \r
        std::cout<<std::endl<<std::endl;\r
-       char templine[100];\r
        \r
-       // Dedicated?\r
-       bool dedicated = g_settings.getBoolAsk\r
-                       ("dedicated_server", "Dedicated server?", false);\r
-       std::cout<<"dedicated = "<<dedicated<<std::endl;\r
+       std::cout\r
+       <<"        .__               __                   __   "<<std::endl\r
+       <<"  _____ |__| ____   _____/  |_  ____   _______/  |_ "<<std::endl\r
+       <<" /     \\|  |/    \\_/ __ \\   __\\/ __ \\ /  ___/\\   __\\"<<std::endl\r
+       <<"|  Y Y  \\  |   |  \\  ___/|  | \\  ___/ \\___ \\  |  |  "<<std::endl\r
+       <<"|__|_|  /__|___|  /\\___  >__|  \\___  >____  > |__|  "<<std::endl\r
+       <<"      \\/        \\/     \\/          \\/     \\/        "<<std::endl\r
+       <<std::endl;\r
+\r
+       std::cout<<std::endl;\r
+       //char templine[100];\r
        \r
        // Port?\r
-       u16 port = g_settings.getU16Ask("port", "Port", 30000);\r
-       std::cout<<"-> "<<port<<std::endl;\r
+       u16 port = 30000;\r
+       if(cmd_args.exists("port"))\r
+       {\r
+               port = cmd_args.getU16("port");\r
+       }\r
+       else\r
+       {\r
+               port = g_settings.getU16Ask("port", "Port", 30000);\r
+               std::cout<<"-> "<<port<<std::endl;\r
+       }\r
        \r
-       if(dedicated)\r
+       //Map directory\r
+       std::string map_dir = porting::path_userdata+"/map";\r
+       if(cmd_args.exists("map-dir"))\r
+               map_dir = cmd_args.get("map-dir");\r
+       else if(g_settings.exists("map-dir"))\r
+               map_dir = g_settings.get("map-dir");\r
+       \r
+       if(cmd_args.getFlag("server"))\r
        {\r
                DSTACK("Dedicated server branch");\r
                \r
@@ -1034,7 +1299,7 @@ int main(int argc, char *argv[])
                std::cout<<"========================"<<std::endl;\r
                std::cout<<std::endl;\r
 \r
-               Server server("../map", hm_params, map_params);\r
+               Server server(map_dir, hm_params, map_params);\r
                server.start(port);\r
        \r
                for(;;)\r
@@ -1072,15 +1337,22 @@ int main(int argc, char *argv[])
        bool hosting = false;\r
        char connect_name[100] = "";\r
 \r
-       std::cout<<"Address to connect to [empty = host a game]: ";\r
-       if(g_settings.get("address") != "" && is_yes(g_settings.get("host_game")) == false)\r
+       if(cmd_args.exists("address"))\r
        {\r
-               std::cout<<g_settings.get("address")<<std::endl;\r
-               snprintf(connect_name, 100, "%s", g_settings.get("address").c_str());\r
+               snprintf(connect_name, 100, "%s", cmd_args.get("address").c_str());\r
        }\r
-       else\r
+       else if(is_yes(g_settings.get("host_game")) == false)\r
        {\r
-               std::cin.getline(connect_name, 100);\r
+               if(g_settings.get("address") != "")\r
+               {\r
+                       std::cout<<g_settings.get("address")<<std::endl;\r
+                       snprintf(connect_name, 100, "%s", g_settings.get("address").c_str());\r
+               }\r
+               else\r
+               {\r
+                       std::cout<<"Address to connect to [empty = host a game]: ";\r
+                       std::cin.getline(connect_name, 100);\r
+               }\r
        }\r
        \r
        if(connect_name[0] == 0){\r
@@ -1089,9 +1361,9 @@ int main(int argc, char *argv[])
        }\r
        \r
        if(hosting)\r
-               std::cout<<"-> hosting"<<std::endl;\r
+               std::cout<<"> Hosting game"<<std::endl;\r
        else\r
-               std::cout<<"-> "<<connect_name<<std::endl;\r
+               std::cout<<"> Connecting to "<<connect_name<<std::endl;\r
        \r
        char playername[PLAYERNAME_SIZE] = "";\r
        if(g_settings.get("name") != "")\r
@@ -1108,68 +1380,10 @@ int main(int argc, char *argv[])
        /*\r
                Resolution selection\r
        */\r
-\r
-       u16 screenW;\r
-       u16 screenH;\r
-       bool fullscreen = false;\r
        \r
-       if(g_settings.get("screenW") != "" && g_settings.get("screenH") != "")\r
-       {\r
-               screenW = atoi(g_settings.get("screenW").c_str());\r
-               screenH = atoi(g_settings.get("screenH").c_str());\r
-       }\r
-       else\r
-       {\r
-               u16 resolutions[][3] = {\r
-                       //W, H, fullscreen\r
-                       {640,480, 0},\r
-                       {800,600, 0},\r
-                       {1024,768, 0},\r
-                       {1280,1024, 0},\r
-                       /*{640,480, 1},\r
-                       {800,600, 1},\r
-                       {1024,768, 1},\r
-                       {1280,1024, 1},*/\r
-               };\r
-\r
-               u16 res_count = sizeof(resolutions)/sizeof(resolutions[0]);\r
-               \r
-               for(u16 i=0; i<res_count; i++)\r
-               {\r
-                       std::cout<<(i+1)<<": "<<resolutions[i][0]<<"x"\r
-                                       <<resolutions[i][1];\r
-                       if(resolutions[i][2])\r
-                               std::cout<<" fullscreen"<<std::endl;\r
-                       else\r
-                               std::cout<<" windowed"<<std::endl;\r
-               }\r
-               std::cout<<"Select a window resolution number [empty = 2]: ";\r
-               std::cin.getline(templine, 100);\r
-\r
-               u16 r0;\r
-               if(templine[0] == 0)\r
-                       r0 = 2;\r
-               else\r
-                       r0 = atoi(templine);\r
-\r
-               if(r0 > res_count || r0 == 0)\r
-                       r0 = 2;\r
-               \r
-               {\r
-                       u16 i = r0-1;\r
-                       std::cout<<"-> ";\r
-                       std::cout<<(i+1)<<": "<<resolutions[i][0]<<"x"\r
-                                       <<resolutions[i][1];\r
-                       if(resolutions[i][2])\r
-                               std::cout<<" fullscreen"<<std::endl;\r
-                       else\r
-                               std::cout<<" windowed"<<std::endl;\r
-               }\r
-\r
-               screenW = resolutions[r0-1][0];\r
-               screenH = resolutions[r0-1][1];\r
-               fullscreen = resolutions[r0-1][2];\r
-       }\r
+       bool fullscreen = false;\r
+       u16 screenW = atoi(g_settings.get("screenW").c_str());\r
+       u16 screenH = atoi(g_settings.get("screenH").c_str());\r
 \r
        //\r
 \r
@@ -1190,19 +1404,20 @@ int main(int argc, char *argv[])
        device = createDevice(driverType,\r
                        core::dimension2d<u32>(screenW, screenH),\r
                        16, fullscreen, false, false, &receiver);\r
-       // With vsync\r
-       /*device = createDevice(driverType,\r
-                       core::dimension2d<u32>(screenW, screenH),\r
-                       16, fullscreen, false, true, &receiver);*/\r
 \r
        if (device == 0)\r
                return 1; // could not create selected driver.\r
-\r
+       \r
        g_device = device;\r
+       g_irrlicht = new IrrlichtWrapper(device);\r
+\r
+       //g_device = device;\r
        \r
        device->setResizable(true);\r
 \r
-       if(g_settings.getBool("random_input"))\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
@@ -1212,19 +1427,23 @@ int main(int argc, char *argv[])
        */\r
 \r
        video::IVideoDriver* driver = device->getVideoDriver();\r
-       // These make the textures not to show at all\r
-       //driver->setTextureCreationFlag(video::ETCF_ALWAYS_16_BIT);\r
-       //driver->setTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED );\r
 \r
-       //driver->setMinHardwareBufferVertexCount(1);\r
+       /*\r
+               This changes the minimum allowed number of vertices in a VBO\r
+       */\r
+       //driver->setMinHardwareBufferVertexCount(50);\r
 \r
        scene::ISceneManager* smgr = device->getSceneManager();\r
-\r
-       gui::IGUIEnvironment* guienv = device->getGUIEnvironment();\r
+       \r
+       guienv = device->getGUIEnvironment();\r
        gui::IGUISkin* skin = guienv->getSkin();\r
-       gui::IGUIFont* font = guienv->getFont("../data/fontlucida.png");\r
+       gui::IGUIFont* font = guienv->getFont(porting::getDataPath("fontlucida.png").c_str());\r
        if(font)\r
                skin->setFont(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
@@ -1234,11 +1453,7 @@ int main(int argc, char *argv[])
        \r
        const wchar_t *text = L"Loading and connecting...";\r
        core::vector2d<s32> center(screenW/2, screenH/2);\r
-       core::dimension2d<u32> textd = font->getDimension(text);\r
-       std::cout<<DTIME<<"Text w="<<textd.Width<<" h="<<textd.Height<<std::endl;\r
-       // Have to add a bit to disable the text from word wrapping\r
-       //core::vector2d<s32> textsize(textd.Width+4, textd.Height);\r
-       core::vector2d<s32> textsize(300, textd.Height);\r
+       core::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
@@ -1250,49 +1465,17 @@ int main(int argc, char *argv[])
        driver->endScene();\r
 \r
        /*\r
-               Initialize material array\r
+               Preload some textures\r
        */\r
 \r
-       //video::SMaterial g_materials[MATERIALS_COUNT];\r
-       for(u16 i=0; i<MATERIALS_COUNT; i++)\r
-       {\r
-               g_materials[i].Lighting = false;\r
-               g_materials[i].BackfaceCulling = false;\r
-\r
-               const char *filename = g_material_filenames[i];\r
-               if(filename != NULL){\r
-                       video::ITexture *t = driver->getTexture(filename);\r
-                       if(t == NULL){\r
-                               std::cout<<DTIME<<"Texture could not be loaded: \""\r
-                                               <<filename<<"\""<<std::endl;\r
-                               return 1;\r
-                       }\r
-                       g_materials[i].setTexture(0, driver->getTexture(filename));\r
-               }\r
-               //g_materials[i].setFlag(video::EMF_TEXTURE_WRAP, video::ETC_REPEAT);\r
-               g_materials[i].setFlag(video::EMF_BILINEAR_FILTER, false);\r
-               //g_materials[i].setFlag(video::EMF_ANISOTROPIC_FILTER, false);\r
-               //g_materials[i].setFlag(video::EMF_FOG_ENABLE, true);\r
-               if(i == MATERIAL_WATER)\r
-               {\r
-                       g_materials[i].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;\r
-                       //g_materials[i].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;\r
-               }\r
-       }\r
-\r
-       /*g_mesh_materials[0].setTexture(0, driver->getTexture("../data/water.png"));\r
-       g_mesh_materials[1].setTexture(0, driver->getTexture("../data/grass.png"));\r
-       g_mesh_materials[2].setTexture(0, driver->getTexture("../data/stone.png"));\r
-       for(u32 i=0; i<3; i++)\r
-       {\r
-               g_mesh_materials[i].Lighting = false;\r
-               g_mesh_materials[i].BackfaceCulling = false;\r
-               g_mesh_materials[i].setFlag(video::EMF_BILINEAR_FILTER, false);\r
-               g_mesh_materials[i].setFlag(video::EMF_FOG_ENABLE, true);\r
-       }*/\r
+       init_content_inventory_texture_paths();\r
+       init_tile_texture_paths();\r
+       tile_materials_preload(g_irrlicht);\r
 \r
-       // Make a scope here for the client so that it gets removed\r
-       // before the irrlicht device\r
+       /*\r
+               Make a scope here for the client so that it gets removed\r
+               before the irrlicht device\r
+       */\r
        {\r
 \r
        std::cout<<DTIME<<"Creating server and client"<<std::endl;\r
@@ -1302,7 +1485,7 @@ int main(int argc, char *argv[])
        */\r
        SharedPtr<Server> server;\r
        if(hosting){\r
-               server = new Server("../map", hm_params, map_params);\r
+               server = new Server(map_dir, hm_params, map_params);\r
                server->start(port);\r
        }\r
        \r
@@ -1310,10 +1493,9 @@ int main(int argc, char *argv[])
                Create client\r
        */\r
 \r
-       // TODO: Get rid of the g_materials parameter or it's globalness\r
-       Client client(device, g_materials,\r
-                       g_settings.getFloat("client_delete_unused_sectors_timeout"),\r
-                       playername);\r
+       Client client(device, playername, draw_control);\r
+                       \r
+       g_client = &client;\r
        \r
        Address connect_address(0,0,0,0, port);\r
        try{\r
@@ -1343,6 +1525,18 @@ int main(int argc, char *argv[])
                std::cout<<DTIME<<"Timed out."<<std::endl;\r
                return 0;\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
@@ -1365,39 +1559,52 @@ int main(int argc, char *argv[])
        // Just so big a value that everything rendered is visible\r
        camera->setFarValue(100000*BS);\r
 \r
-       /*//f32 range = BS*HEIGHTMAP_RANGE_NODES*0.9;\r
-       f32 range = BS*HEIGHTMAP_RANGE_NODES*0.9;\r
-       \r
-       camera->setFarValue(range);\r
-       \r
-       driver->setFog(\r
-               skycolor,\r
-               video::EFT_FOG_LINEAR,\r
-               range*0.8,\r
-               range,\r
-               0.01,\r
-               false,\r
-               false\r
-               );*/\r
-       \r
        f32 camera_yaw = 0; // "right/left"\r
        f32 camera_pitch = 0; // "up/down"\r
+\r
+       /*\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
+       \r
+       /*\r
+               We need some kind of a root node to be able to add\r
+               custom 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
+       // Test the text input system\r
+       /*(new GUITextInputMenu(guienv, guiroot, -1, &g_active_menu_count,\r
+                       NULL))->drop();*/\r
+       /*GUIMessageMenu *menu =\r
+                       new GUIMessageMenu(guienv, guiroot, -1, \r
+                               &g_active_menu_count,\r
+                               L"Asd");\r
+       menu->drop();*/\r
+       \r
+       // Launch pause menu\r
+       (new GUIPauseMenu(guienv, guiroot, -1, g_device,\r
+                       &g_active_menu_count))->drop();\r
+\r
        // First line of debug text\r
        gui::IGUIStaticText *guitext = guienv->addStaticText(\r
                        L"Minetest-c55",\r
-                       core::rect<s32>(5, 5, 5+600, 5+textsize.Y),\r
+                       core::rect<s32>(5, 5, 795, 5+textsize.Y),\r
                        false, false);\r
        // Second line of debug text\r
        gui::IGUIStaticText *guitext2 = guienv->addStaticText(\r
                        L"",\r
-                       core::rect<s32>(5, 5+(textsize.Y+5)*1, 5+600, (5+textsize.Y)*2),\r
+                       core::rect<s32>(5, 5+(textsize.Y+5)*1, 795, (5+textsize.Y)*2),\r
                        false, false);\r
        \r
        // At the middle of the screen\r
@@ -1407,52 +1614,24 @@ int main(int argc, char *argv[])
                        core::rect<s32>(100, 70, 100+400, 70+(textsize.Y+5)),\r
                        false, false);\r
        \r
-       // This is a copy of the inventory that the client's environment has\r
-       Inventory local_inventory(PLAYER_INVENTORY_SIZE);\r
-       \r
-       GUIQuickInventory *quick_inventory = new GUIQuickInventory\r
-                       (guienv, NULL, v2s32(10, 70), 5, &local_inventory);\r
+       // Chat text\r
+       gui::IGUIStaticText *chat_guitext = guienv->addStaticText(\r
+                       L"Chat here\nOther line\nOther line\nOther line\nOther line",\r
+                       core::rect<s32>(70, 60, 795, 150),\r
+                       false, true);\r
+       chat_guitext->setBackgroundColor(video::SColor(96,0,0,0));\r
+       core::list<ChatLine> chat_lines;\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
-       /*\r
-               Text input system\r
-       */\r
-       \r
-       struct TextDest\r
-       {\r
-               virtual void sendText(std::string text) = 0;\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 sendText(std::string text)\r
-               {\r
-                       dstream<<"Changing text of a sign object: "\r
-                                       <<text<<std::endl;\r
-                       m_client->sendSignText(m_blockpos, m_id, text);\r
-               }\r
-\r
-               v3s16 m_blockpos;\r
-               s16 m_id;\r
-               Client *m_client;\r
-       };\r
-\r
-       TextDest *textbuf_dest = NULL;\r
-       \r
-       //gui::IGUIWindow* input_window = NULL;\r
-       gui::IGUIStaticText* input_guitext = NULL;\r
+       // A test\r
+       //throw con::PeerNotFoundException("lol");\r
 \r
        /*\r
                Main loop\r
@@ -1461,19 +1640,30 @@ int main(int argc, char *argv[])
        bool first_loop_after_window_activation = true;\r
 \r
        // Time is in milliseconds\r
-       // NOTE: getRealTime() without run()s causes strange problems in wine\r
-       // NOTE: Have to call run() between calls of this to update the timer\r
+       // 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())\r
        {\r
+               /*\r
+                       Run global IrrlichtWrapper's main thread processing stuff\r
+               */\r
+               g_irrlicht->Run();\r
+\r
+               /*\r
+                       Random calculations\r
+               */\r
+               v2u32 screensize = driver->getScreenSize();\r
+               core::vector2d<s32> displaycenter(screensize.X/2,screensize.Y/2);\r
+               \r
                // Hilight boxes collected during the loop and displayed\r
                core::list< core::aabbox3d<f32> > hilightboxes;\r
                \r
                // Info text\r
                std::wstring infotext;\r
 \r
-               //TimeTaker //timer1("//timer1", device);\r
+               //TimeTaker //timer1("//timer1");\r
                \r
                // Time of frame without fps limit\r
                float busytime;\r
@@ -1497,7 +1687,6 @@ int main(int argc, char *argv[])
                        Viewing range\r
                */\r
                \r
-               //updateViewingRange(dtime, &client);\r
                updateViewingRange(busytime, &client);\r
                \r
                /*\r
@@ -1616,19 +1805,10 @@ int main(int argc, char *argv[])
                */\r
                g_input->step(dtime);\r
 \r
-               /*\r
-                       Special keys\r
-               */\r
-               if(g_esc_pressed)\r
-               {\r
-                       break;\r
-               }\r
-\r
                /*\r
                        Player speed control\r
                */\r
                \r
-               if(g_game_focused)\r
                {\r
                        /*bool a_up,\r
                        bool a_down,\r
@@ -1650,56 +1830,50 @@ int main(int argc, char *argv[])
                        );\r
                        client.setPlayerControl(control);\r
                }\r
-               else\r
-               {\r
-                       // Set every key to inactive\r
-                       PlayerControl control;\r
-                       client.setPlayerControl(control);\r
-               }\r
 \r
-               //timer1.stop();\r
                /*\r
                        Process environment\r
                */\r
                \r
                {\r
-                       //TimeTaker timer("client.step(dtime)", device);\r
+                       //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)", device);\r
+                       //TimeTaker timer("server->step(dtime)");\r
                        server->step(dtime);\r
                }\r
 \r
                v3f player_position = client.getPlayerPosition();\r
                \r
-               //TimeTaker //timer2("//timer2", device);\r
+               //TimeTaker //timer2("//timer2");\r
 \r
                /*\r
                        Mouse and camera control\r
                */\r
                \r
-               if(device->isWindowActive() && g_game_focused)\r
+               if((device->isWindowActive() && noMenuActive()) || random_input)\r
                {\r
-                       device->getCursorControl()->setVisible(false);\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 - 320;\r
-                               s32 dy = g_input->getMousePos().Y - 240;\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(320, 240);\r
+                       g_input->setMousePos(displaycenter.X, displaycenter.Y);\r
                }\r
                else{\r
                        device->getCursorControl()->setVisible(true);\r
@@ -1714,9 +1888,13 @@ int main(int argc, char *argv[])
                v3f camera_direction = v3f(0,0,1);\r
                camera_direction.rotateYZBy(camera_pitch);\r
                camera_direction.rotateXZBy(camera_yaw);\r
-\r
+               \r
+               // This is at the height of the eyes of the current figure\r
                v3f camera_position =\r
                                player_position + v3f(0, BS+BS/2, 0);\r
+               // This is more like in minecraft\r
+               /*v3f camera_position =\r
+                               player_position + v3f(0, BS+BS*0.65, 0);*/\r
 \r
                camera->setPosition(camera_position);\r
                // *100.0 helps in large map coordinates\r
@@ -1728,12 +1906,12 @@ int main(int argc, char *argv[])
                }\r
                else{\r
                        //client.m_env.getMap().updateCamera(camera_position, camera_direction);\r
-                       //TimeTaker timer("client.updateCamera", device);\r
+                       //TimeTaker timer("client.updateCamera");\r
                        client.updateCamera(camera_position, camera_direction);\r
                }\r
                \r
                //timer2.stop();\r
-               //TimeTaker //timer3("//timer3", device);\r
+               //TimeTaker //timer3("//timer3");\r
 \r
                /*\r
                        Calculate what block is the crosshair pointing to\r
@@ -1749,6 +1927,10 @@ int main(int argc, char *argv[])
                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
@@ -1775,23 +1957,25 @@ int main(int argc, char *argv[])
                                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
-                                       unFocusGame();\r
+                                               TextDest *dest = new TextDestSign(\r
+                                                               selected_object->getBlock()->getPos(),\r
+                                                               selected_object->getId(),\r
+                                                               &client);\r
 \r
-                                       input_guitext = guienv->addStaticText(L"",\r
-                                                       core::rect<s32>(150,100,350,120),\r
-                                                       true, // border?\r
-                                                       false, // wordwrap?\r
-                                                       NULL);\r
+                                               SignObject *sign_object = (SignObject*)selected_object;\r
 \r
-                                       input_guitext->setDrawBackground(true);\r
+                                               std::wstring wtext =\r
+                                                               narrow_to_wide(sign_object->getText());\r
 \r
-                                       g_text_buffer = L"";\r
-                                       g_text_buffer_accepted = false;\r
-                                       textbuf_dest = new TextDestSign(\r
-                                                       selected_object->getBlock()->getPos(),\r
-                                                       selected_object->getId(),\r
-                                                       &client);\r
+                                               (new GUITextInputMenu(guienv, guiroot, -1,\r
+                                                               &g_active_menu_count, dest,\r
+                                                               wtext))->drop();\r
+                                       }\r
                                }\r
                                /*\r
                                        Otherwise pass the event to the server as-is\r
@@ -1805,6 +1989,10 @@ int main(int argc, char *argv[])
                }\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
@@ -1825,15 +2013,19 @@ int main(int argc, char *argv[])
                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 y = ystart; y <= yend; y++)\r
+               for(s16 z = zstart; z <= zend; z++)\r
                for(s16 x = xstart; x <= xend; x++)\r
                {\r
-                       try{\r
-                               if(client.getNode(v3s16(x,y,z)).d == MATERIAL_AIR){\r
+                       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
+                       catch(InvalidPositionException &e)\r
+                       {\r
                                continue;\r
                        }\r
 \r
@@ -1842,94 +2034,250 @@ int main(int argc, char *argv[])
                        \r
                        f32 d = 0.01;\r
                        \r
-                       v3s16 directions[6] = {\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),\r
-                               v3s16(0,-1,0),\r
-                               v3s16(-1,0,0),\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
-                       for(u16 i=0; i<6; i++){\r
-                       //{u16 i=3;\r
-                               v3f dir_f = v3f(directions[i].X,\r
-                                               directions[i].Y, directions[i].Z);\r
-                               v3f centerpoint = npf + dir_f * BS/2;\r
-                               f32 distance =\r
-                                               (centerpoint - camera_position).getLength();\r
+                               core::aabbox3d<f32> box;\r
                                \r
-                               if(distance < mindistance){\r
-                                       //std::cout<<DTIME<<"for centerpoint=("<<centerpoint.X<<","<<centerpoint.Y<<","<<centerpoint.Z<<"): distance < mindistance"<<std::endl;\r
-                                       //std::cout<<DTIME<<"npf=("<<npf.X<<","<<npf.Y<<","<<npf.Z<<")"<<std::endl;\r
-                                       core::CMatrix4<f32> m;\r
-                                       m.buildRotateFromTo(v3f(0,0,1), dir_f);\r
-\r
-                                       // This is the back face\r
-                                       v3f corners[2] = {\r
-                                               v3f(BS/2, BS/2, BS/2),\r
-                                               v3f(-BS/2, -BS/2, BS/2+d)\r
-                                       };\r
-                                       \r
-                                       for(u16 j=0; j<2; j++){\r
-                                               m.rotateVect(corners[j]);\r
-                                               corners[j] += npf;\r
-                                               //std::cout<<DTIME<<"box corners["<<j<<"]: ("<<corners[j].X<<","<<corners[j].Y<<","<<corners[j].Z<<")"<<std::endl;\r
-                                       }\r
-\r
-                                       //core::aabbox3d<f32> facebox(corners[0],corners[1]);\r
-                                       core::aabbox3d<f32> facebox(corners[0]);\r
-                                       facebox.addInternalPoint(corners[1]);\r
+                               // 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(facebox.intersectsWithLine(shootline)){\r
+                               if(distance < mindistance)\r
+                               {\r
+                                       if(box.intersectsWithLine(shootline))\r
+                                       {\r
                                                nodefound = true;\r
                                                nodepos = np;\r
-                                               neighbourpos = np + directions[i];\r
+                                               neighbourpos = np;\r
                                                mindistance = distance;\r
-                                               nodefacebox = facebox;\r
+                                               nodefacebox = box;\r
                                        }\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
+                                                       nodefacebox = facebox;\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
-                       //std::cout<<DTIME<<"nodefound == true"<<std::endl;\r
-                       //std::cout<<DTIME<<"nodepos=("<<nodepos.X<<","<<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;\r
-                       //std::cout<<DTIME<<"neighbourpos=("<<neighbourpos.X<<","<<neighbourpos.Y<<","<<neighbourpos.Z<<")"<<std::endl;\r
-\r
-                       static v3s16 nodepos_old(-1,-1,-1);\r
-                       if(nodepos != nodepos_old){\r
-                               std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","\r
-                                               <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;\r
-                               nodepos_old = nodepos;\r
-\r
-                               /*wchar_t positiontext[20];\r
-                               swprintf(positiontext, 20, L"(%i,%i,%i)",\r
-                                               nodepos.X, nodepos.Y, nodepos.Z);\r
-                               positiontextgui->setText(positiontext);*/\r
-                       }\r
+                       static v3s16 nodepos_old(-32768,-32768,-32768);\r
+\r
+                       static float dig_time = 0.0;\r
+                       static u16 dig_index = 0;\r
 \r
                        hilightboxes.push_back(nodefacebox);\r
                        \r
-                       if(g_input->getLeftClicked())\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
-                               //std::cout<<DTIME<<"Removing node"<<std::endl;\r
-                               //client.removeNode(nodepos);\r
-                               std::cout<<DTIME<<"Ground left-clicked"<<std::endl;\r
-                               client.clickGround(0, nodepos, neighbourpos, g_selected_item);\r
+                               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
+                                               //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
+                                               float mindelay = 0.20;\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<<"Placing node"<<std::endl;\r
-                               //client.addNodeFromInventory(neighbourpos, g_selected_item);\r
                                std::cout<<DTIME<<"Ground right-clicked"<<std::endl;\r
-                               client.clickGround(1, nodepos, neighbourpos, g_selected_item);\r
+                               client.groundAction(1, nodepos, neighbourpos, g_selected_item);\r
                        }\r
+                       \r
+                       nodepos_old = nodepos;\r
                }\r
                else{\r
-                       //std::cout<<DTIME<<"nodefound == false"<<std::endl;\r
-                       //positiontextgui->setText(L"");\r
                }\r
 \r
                } // selected_object == NULL\r
@@ -1937,39 +2285,90 @@ int main(int argc, char *argv[])
                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
-               v2u32 screensize = driver->getScreenSize();\r
-               core::vector2d<s32> displaycenter(screensize.X/2,screensize.Y/2);\r
-\r
                camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);\r
+               \r
+               u32 daynight_ratio = client.getDayNightRatio();\r
+               /*video::SColor bgcolor = video::SColor(\r
+                               255,\r
+                               skycolor.getRed() * daynight_ratio / 1000,\r
+                               skycolor.getGreen() * daynight_ratio / 1000,\r
+                               skycolor.getBlue() * daynight_ratio / 1000);*/\r
+\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;\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,\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", device);\r
+               //TimeTaker guiupdatetimer("Gui updating");\r
                \r
                {\r
-                       wchar_t temptext[100];\r
+                       wchar_t temptext[150];\r
 \r
                        static float drawtime_avg = 0;\r
-                       drawtime_avg = drawtime_avg * 0.98 + (float)drawtime*0.02;\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.98 + (float)scenetime*0.02;\r
+                       scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;\r
                        static float endscenetime_avg = 0;\r
-                       endscenetime_avg = endscenetime_avg * 0.98 + (float)endscenetime*0.02;\r
+                       endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;\r
                        \r
-                       swprintf(temptext, 100, L"Minetest-c55 ("\r
+                       swprintf(temptext, 150, L"Minetest-c55 ("\r
                                        L"F: item=%i"\r
                                        L", R: range_all=%i"\r
                                        L")"\r
-                                       L" drawtime=%.0f, scenetime=%.0f, endscenetime=%.0f",\r
+                                       L" drawtime=%.0f, beginscenetime=%.0f, scenetime=%.0f, endscenetime=%.0f",\r
                                        g_selected_item,\r
-                                       g_viewing_range_all,\r
+                                       draw_control.range_all,\r
                                        drawtime_avg,\r
+                                       beginscenetime_avg,\r
                                        scenetime_avg,\r
                                        endscenetime_avg\r
                                        );\r
@@ -1978,43 +2377,93 @@ int main(int argc, char *argv[])
                }\r
                \r
                {\r
-                       wchar_t temptext[100];\r
-                       /*swprintf(temptext, 100,\r
-                                       L"("\r
-                                       L"% .3f < btime_jitter < % .3f"\r
-                                       L", dtime_jitter = % .1f %%"\r
-                                       //L", ftime_ratio = % .3f"\r
-                                       L")",\r
-                                       busytime_jitter1_min_sample,\r
-                                       busytime_jitter1_max_sample,\r
-                                       dtime_jitter1_max_fraction * 100.0\r
-                                       //g_freetime_ratio\r
-                                       );*/\r
-                       swprintf(temptext, 100,\r
+                       wchar_t temptext[150];\r
+                       swprintf(temptext, 150,\r
                                        L"(% .1f, % .1f, % .1f)"\r
                                        L" (% .3f < btime_jitter < % .3f"\r
-                                       L", dtime_jitter = % .1f %%)",\r
+                                       L", dtime_jitter = % .1f %%"\r
+                                       L", 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
+                                       dtime_jitter1_max_fraction * 100.0,\r
+                                       draw_control.wanted_range\r
                                        );\r
 \r
                        guitext2->setText(temptext);\r
                }\r
                \r
                {\r
-                       /*wchar_t temptext[100];\r
-                       swprintf(temptext, 100,\r
-                                       SWPRINTF_CHARSTRING,\r
-                                       infotext.substr(0,99).c_str()\r
-                                       );\r
+                       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
-                       guitext_info->setText(temptext);*/\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
+                       chat_guitext->setText(whole.c_str());\r
+                       // Update gui element size and position\r
+                       core::rect<s32> rect(\r
+                                       10,\r
+                                       screensize.Y - 10 - text_height*chat_lines.size(),\r
+                                       screensize.X - 10,\r
+                                       screensize.Y - 10\r
+                       );\r
+                       chat_guitext->setRelativePosition(rect);\r
 \r
-                       guitext_info->setText(infotext.c_str());\r
+                       if(chat_lines.size() == 0)\r
+                               chat_guitext->setVisible(false);\r
+                       else\r
+                               chat_guitext->setVisible(true);\r
                }\r
 \r
                /*\r
@@ -2031,90 +2480,49 @@ int main(int argc, char *argv[])
                        quick_inventory->setSelection(g_selected_item);\r
                        quick_inventory->update();\r
                }\r
-\r
-               if(input_guitext != NULL)\r
-               {\r
-                       /*wchar_t temptext[100];\r
-                       swprintf(temptext, 100,\r
-                                       SWPRINTF_CHARSTRING,\r
-                                       g_text_buffer.substr(0,99).c_str()\r
-                                       );*/\r
-                       input_guitext->setText(g_text_buffer.c_str());\r
-               }\r
-\r
+               \r
                /*\r
-                       Text input stuff\r
+                       Send actions returned by the inventory menu\r
                */\r
-               if(input_guitext != NULL && g_text_buffer_accepted)\r
+               while(inventory_action_queue.size() != 0)\r
                {\r
-                       input_guitext->remove();\r
-                       input_guitext = NULL;\r
-                       \r
-                       if(textbuf_dest != NULL)\r
-                       {\r
-                               std::string text = wide_to_narrow(g_text_buffer);\r
-                               dstream<<"Sending text: "<<text<<std::endl;\r
-                               textbuf_dest->sendText(text);\r
-                               delete textbuf_dest;\r
-                               textbuf_dest = NULL;\r
-                       }\r
+                       InventoryAction *a = inventory_action_queue.pop_front();\r
 \r
-                       focusGame();\r
+                       client.sendInventoryAction(a);\r
+                       // Eat it\r
+                       delete a;\r
                }\r
 \r
-               //guiupdatetimer.stop();\r
-\r
                /*\r
                        Drawing begins\r
                */\r
 \r
-               TimeTaker drawtimer("Drawing", device);\r
+               TimeTaker drawtimer("Drawing");\r
 \r
-               /*\r
-                       Background color is choosen based on whether the player is\r
-                       much beyond the initial ground level\r
-               */\r
-               /*video::SColor bgcolor;\r
-               v3s16 p0 = Map::floatToInt(player_position);\r
-               // Does this make short random delays?\r
-               // NOTE: no need for this, sky doesn't show underground with\r
-               // enough range\r
-               bool is_underground = client.isNodeUnderground(p0);\r
-               //bool is_underground = false;\r
-               if(is_underground == false)\r
-                       bgcolor = video::SColor(255,90,140,200);\r
-               else\r
-                       bgcolor = video::SColor(255,0,0,0);*/\r
-                       \r
-               //video::SColor bgcolor = video::SColor(255,90,140,200);\r
-               video::SColor bgcolor = skycolor;\r
                \r
-               // 0ms\r
-               driver->beginScene(true, true, bgcolor);\r
+               {\r
+                       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", device);\r
-               smgr->drawAll();\r
-               scenetime = timer.stop(true);\r
+                       TimeTaker timer("smgr");\r
+                       smgr->drawAll();\r
+                       scenetime = timer.stop(true);\r
                }\r
                \r
                {\r
-               //TimeTaker timer9("auxiliary drawings", device);\r
+               //TimeTaker timer9("auxiliary drawings");\r
                // 0ms\r
-\r
-               driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),\r
-                               displaycenter + core::vector2d<s32>(10,0),\r
-                               video::SColor(255,255,255,255));\r
-               driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),\r
-                               displaycenter + core::vector2d<s32>(0,10),\r
-                               video::SColor(255,255,255,255));\r
-\r
+               \r
                //timer9.stop();\r
-               //TimeTaker //timer10("//timer10", device);\r
+               //TimeTaker //timer10("//timer10");\r
                \r
                video::SMaterial m;\r
                m.Thickness = 10;\r
@@ -2134,10 +2542,20 @@ int main(int argc, char *argv[])
                        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
 \r
                //timer10.stop();\r
-               //TimeTaker //timer11("//timer11", device);\r
+               //TimeTaker //timer11("//timer11");\r
 \r
                /*\r
                        Draw gui\r
@@ -2147,9 +2565,9 @@ int main(int argc, char *argv[])
                \r
                // End drawing\r
                {\r
-               TimeTaker timer("endScene", device);\r
-               driver->endScene();\r
-               endscenetime = timer.stop(true);\r
+                       TimeTaker timer("endScene");\r
+                       driver->endScene();\r
+                       endscenetime = timer.stop(true);\r
                }\r
 \r
                drawtime = drawtimer.stop(true);\r
@@ -2178,6 +2596,8 @@ int main(int argc, char *argv[])
                        device->yield();*/\r
        }\r
 \r
+       delete quick_inventory;\r
+\r
        } // client is deleted at this point\r
        \r
        delete g_input;\r
@@ -2186,24 +2606,46 @@ int main(int argc, char *argv[])
                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
        } //try\r
        catch(con::PeerNotFoundException &e)\r
        {\r
                dstream<<DTIME<<"Connection timed out."<<std::endl;\r
+               \r
+               /*if(g_device)\r
+               {\r
+                       GUIMessageMenu *menu =\r
+                                       new GUIMessageMenu(guienv, guiroot, -1, \r
+                                               &g_active_menu_count,\r
+                                               L"Connection timed out");\r
+\r
+                       video::IVideoDriver* driver = g_device->getVideoDriver();\r
+                       \r
+                       dstream<<"Created menu"<<std::endl;\r
+\r
+                       while(g_device->run() && menu->getStatus() == false)\r
+                       {\r
+                               driver->beginScene(true, true, video::SColor(255,0,0,0));\r
+                               guienv->drawAll();\r
+                               driver->endScene();\r
+                       }\r
+                       \r
+                       dstream<<"Dropping menu"<<std::endl;\r
+\r
+                       menu->drop();\r
+               }*/\r
        }\r
-#if CATCH_UNHANDLED_EXCEPTIONS\r
-       /*\r
-               This is what has to be done in every thread to get suitable debug info\r
-       */\r
-       catch(std::exception &e)\r
-       {\r
-               dstream<<std::endl<<DTIME<<"An unhandled exception occurred: "\r
-                               <<e.what()<<std::endl;\r
-               assert(0);\r
-       }\r
-#endif\r
 \r
+       END_DEBUG_EXCEPTION_HANDLER\r
+       \r
        debugstreams_deinit();\r
        \r
        return 0;\r