]> git.lizzy.rs Git - minetest.git/blob - src/game.cpp
Dynamic sky, fog and cloud colors; sun and moon
[minetest.git] / src / game.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "game.h"
21 #include "common_irrlicht.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
26 #include <IGUIFont.h>
27 #include "client.h"
28 #include "server.h"
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiInventoryMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
34 #include "tool.h"
35 #include "guiChatConsole.h"
36 #include "config.h"
37 #include "clouds.h"
38 #include "camera.h"
39 #include "farmesh.h"
40 #include "mapblock.h"
41 #include "settings.h"
42 #include "profiler.h"
43 #include "mainmenumanager.h"
44 #include "gettext.h"
45 #include "log.h"
46 #include "filesys.h"
47 // Needed for determining pointing to nodes
48 #include "nodedef.h"
49 #include "nodemetadata.h"
50 #include "main.h" // For g_settings
51 #include "itemdef.h"
52 #include "tile.h" // For TextureSource
53 #include "logoutputbuffer.h"
54 #include "subgame.h"
55 #include "quicktune_shortcutter.h"
56 #include "clientmap.h"
57 #include "sky.h"
58
59 /*
60         Setting this to 1 enables a special camera mode that forces
61         the renderers to think that the camera statically points from
62         the starting place to a static direction.
63
64         This allows one to move around with the player and see what
65         is actually drawn behind solid things and behind the player.
66 */
67 #define FIELD_OF_VIEW_TEST 0
68
69
70 /*
71         Text input system
72 */
73
74 struct TextDestChat : public TextDest
75 {
76         TextDestChat(Client *client)
77         {
78                 m_client = client;
79         }
80         void gotText(std::wstring text)
81         {
82                 m_client->typeChatMessage(text);
83         }
84
85         Client *m_client;
86 };
87
88 struct TextDestNodeMetadata : public TextDest
89 {
90         TextDestNodeMetadata(v3s16 p, Client *client)
91         {
92                 m_p = p;
93                 m_client = client;
94         }
95         void gotText(std::wstring text)
96         {
97                 std::string ntext = wide_to_narrow(text);
98                 infostream<<"Changing text of a sign node: "
99                                 <<ntext<<std::endl;
100                 m_client->sendSignNodeText(m_p, ntext);
101         }
102
103         v3s16 m_p;
104         Client *m_client;
105 };
106
107 /* Respawn menu callback */
108
109 class MainRespawnInitiator: public IRespawnInitiator
110 {
111 public:
112         MainRespawnInitiator(bool *active, Client *client):
113                 m_active(active), m_client(client)
114         {
115                 *m_active = true;
116         }
117         void respawn()
118         {
119                 *m_active = false;
120                 m_client->sendRespawn();
121         }
122 private:
123         bool *m_active;
124         Client *m_client;
125 };
126
127 /*
128         Hotbar draw routine
129 */
130 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
131                 IGameDef *gamedef,
132                 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
133                 Inventory *inventory, s32 halfheartcount, u16 playeritem)
134 {
135         InventoryList *mainlist = inventory->getList("main");
136         if(mainlist == NULL)
137         {
138                 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
139                 return;
140         }
141         
142         s32 padding = imgsize/12;
143         //s32 height = imgsize + padding*2;
144         s32 width = itemcount*(imgsize+padding*2);
145         
146         // Position of upper left corner of bar
147         v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
148         
149         // Draw background color
150         /*core::rect<s32> barrect(0,0,width,height);
151         barrect += pos;
152         video::SColor bgcolor(255,128,128,128);
153         driver->draw2DRectangle(bgcolor, barrect, NULL);*/
154
155         core::rect<s32> imgrect(0,0,imgsize,imgsize);
156
157         for(s32 i=0; i<itemcount; i++)
158         {
159                 const ItemStack &item = mainlist->getItem(i);
160                 
161                 core::rect<s32> rect = imgrect + pos
162                                 + v2s32(padding+i*(imgsize+padding*2), padding);
163                 
164                 if(playeritem == i)
165                 {
166                         video::SColor c_outside(255,255,0,0);
167                         //video::SColor c_outside(255,0,0,0);
168                         //video::SColor c_inside(255,192,192,192);
169                         s32 x1 = rect.UpperLeftCorner.X;
170                         s32 y1 = rect.UpperLeftCorner.Y;
171                         s32 x2 = rect.LowerRightCorner.X;
172                         s32 y2 = rect.LowerRightCorner.Y;
173                         // Black base borders
174                         driver->draw2DRectangle(c_outside,
175                                         core::rect<s32>(
176                                                 v2s32(x1 - padding, y1 - padding),
177                                                 v2s32(x2 + padding, y1)
178                                         ), NULL);
179                         driver->draw2DRectangle(c_outside,
180                                         core::rect<s32>(
181                                                 v2s32(x1 - padding, y2),
182                                                 v2s32(x2 + padding, y2 + padding)
183                                         ), NULL);
184                         driver->draw2DRectangle(c_outside,
185                                         core::rect<s32>(
186                                                 v2s32(x1 - padding, y1),
187                                                 v2s32(x1, y2)
188                                         ), NULL);
189                         driver->draw2DRectangle(c_outside,
190                                         core::rect<s32>(
191                                                 v2s32(x2, y1),
192                                                 v2s32(x2 + padding, y2)
193                                         ), NULL);
194                         /*// Light inside borders
195                         driver->draw2DRectangle(c_inside,
196                                         core::rect<s32>(
197                                                 v2s32(x1 - padding/2, y1 - padding/2),
198                                                 v2s32(x2 + padding/2, y1)
199                                         ), NULL);
200                         driver->draw2DRectangle(c_inside,
201                                         core::rect<s32>(
202                                                 v2s32(x1 - padding/2, y2),
203                                                 v2s32(x2 + padding/2, y2 + padding/2)
204                                         ), NULL);
205                         driver->draw2DRectangle(c_inside,
206                                         core::rect<s32>(
207                                                 v2s32(x1 - padding/2, y1),
208                                                 v2s32(x1, y2)
209                                         ), NULL);
210                         driver->draw2DRectangle(c_inside,
211                                         core::rect<s32>(
212                                                 v2s32(x2, y1),
213                                                 v2s32(x2 + padding/2, y2)
214                                         ), NULL);
215                         */
216                 }
217
218                 video::SColor bgcolor2(128,0,0,0);
219                 driver->draw2DRectangle(bgcolor2, rect, NULL);
220                 drawItemStack(driver, font, item, rect, NULL, gamedef);
221         }
222         
223         /*
224                 Draw hearts
225         */
226         video::ITexture *heart_texture =
227                 gamedef->getTextureSource()->getTextureRaw("heart.png");
228         if(heart_texture)
229         {
230                 v2s32 p = pos + v2s32(0, -20);
231                 for(s32 i=0; i<halfheartcount/2; i++)
232                 {
233                         const video::SColor color(255,255,255,255);
234                         const video::SColor colors[] = {color,color,color,color};
235                         core::rect<s32> rect(0,0,16,16);
236                         rect += p;
237                         driver->draw2DImage(heart_texture, rect,
238                                 core::rect<s32>(core::position2d<s32>(0,0),
239                                 core::dimension2di(heart_texture->getOriginalSize())),
240                                 NULL, colors, true);
241                         p += v2s32(16,0);
242                 }
243                 if(halfheartcount % 2 == 1)
244                 {
245                         const video::SColor color(255,255,255,255);
246                         const video::SColor colors[] = {color,color,color,color};
247                         core::rect<s32> rect(0,0,16/2,16);
248                         rect += p;
249                         core::dimension2di srcd(heart_texture->getOriginalSize());
250                         srcd.Width /= 2;
251                         driver->draw2DImage(heart_texture, rect,
252                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
253                                 NULL, colors, true);
254                         p += v2s32(16,0);
255                 }
256         }
257 }
258
259 /*
260         Check if a node is pointable
261 */
262 inline bool isPointableNode(const MapNode& n,
263                 Client *client, bool liquids_pointable)
264 {
265         const ContentFeatures &features = client->getNodeDefManager()->get(n);
266         return features.pointable ||
267                 (liquids_pointable && features.isLiquid());
268 }
269
270 /*
271         Find what the player is pointing at
272 */
273 PointedThing getPointedThing(Client *client, v3f player_position,
274                 v3f camera_direction, v3f camera_position,
275                 core::line3d<f32> shootline, f32 d,
276                 bool liquids_pointable,
277                 bool look_for_object,
278                 core::aabbox3d<f32> &hilightbox,
279                 bool &should_show_hilightbox,
280                 ClientActiveObject *&selected_object)
281 {
282         PointedThing result;
283
284         hilightbox = core::aabbox3d<f32>(0,0,0,0,0,0);
285         should_show_hilightbox = false;
286         selected_object = NULL;
287
288         INodeDefManager *nodedef = client->getNodeDefManager();
289         ClientMap &map = client->getEnv().getClientMap();
290
291         // First try to find a pointed at active object
292         if(look_for_object)
293         {
294                 selected_object = client->getSelectedActiveObject(d*BS,
295                                 camera_position, shootline);
296         }
297         if(selected_object != NULL)
298         {
299                 core::aabbox3d<f32> *selection_box
300                         = selected_object->getSelectionBox();
301                 // Box should exist because object was returned in the
302                 // first place
303                 assert(selection_box);
304
305                 v3f pos = selected_object->getPosition();
306
307                 hilightbox = core::aabbox3d<f32>(
308                                 selection_box->MinEdge + pos,
309                                 selection_box->MaxEdge + pos
310                 );
311
312                 should_show_hilightbox = selected_object->doShowSelectionBox();
313
314                 result.type = POINTEDTHING_OBJECT;
315                 result.object_id = selected_object->getId();
316                 return result;
317         }
318
319         // That didn't work, try to find a pointed at node
320
321         f32 mindistance = BS * 1001;
322         
323         v3s16 pos_i = floatToInt(player_position, BS);
324
325         /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
326                         <<std::endl;*/
327
328         s16 a = d;
329         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
330         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
331         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
332         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
333         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
334         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
335         
336         for(s16 y = ystart; y <= yend; y++)
337         for(s16 z = zstart; z <= zend; z++)
338         for(s16 x = xstart; x <= xend; x++)
339         {
340                 MapNode n;
341                 try
342                 {
343                         n = map.getNode(v3s16(x,y,z));
344                 }
345                 catch(InvalidPositionException &e)
346                 {
347                         continue;
348                 }
349                 if(!isPointableNode(n, client, liquids_pointable))
350                         continue;
351
352                 v3s16 np(x,y,z);
353                 v3f npf = intToFloat(np, BS);
354                 
355                 f32 d = 0.01;
356                 
357                 v3s16 dirs[6] = {
358                         v3s16(0,0,1), // back
359                         v3s16(0,1,0), // top
360                         v3s16(1,0,0), // right
361                         v3s16(0,0,-1), // front
362                         v3s16(0,-1,0), // bottom
363                         v3s16(-1,0,0), // left
364                 };
365                 
366                 const ContentFeatures &f = nodedef->get(n);
367                 
368                 if(f.selection_box.type == NODEBOX_FIXED)
369                 {
370                         core::aabbox3d<f32> box = f.selection_box.fixed;
371                         box.MinEdge += npf;
372                         box.MaxEdge += npf;
373
374                         v3s16 facedirs[6] = {
375                                 v3s16(-1,0,0),
376                                 v3s16(1,0,0),
377                                 v3s16(0,-1,0),
378                                 v3s16(0,1,0),
379                                 v3s16(0,0,-1),
380                                 v3s16(0,0,1),
381                         };
382
383                         core::aabbox3d<f32> faceboxes[6] = {
384                                 // X-
385                                 core::aabbox3d<f32>(
386                                         box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
387                                         box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
388                                 ),
389                                 // X+
390                                 core::aabbox3d<f32>(
391                                         box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
392                                         box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
393                                 ),
394                                 // Y-
395                                 core::aabbox3d<f32>(
396                                         box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
397                                         box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
398                                 ),
399                                 // Y+
400                                 core::aabbox3d<f32>(
401                                         box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
402                                         box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
403                                 ),
404                                 // Z-
405                                 core::aabbox3d<f32>(
406                                         box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
407                                         box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
408                                 ),
409                                 // Z+
410                                 core::aabbox3d<f32>(
411                                         box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
412                                         box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
413                                 ),
414                         };
415
416                         for(u16 i=0; i<6; i++)
417                         {
418                                 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
419                                 v3f centerpoint = npf + facedir_f * BS/2;
420                                 f32 distance = (centerpoint - camera_position).getLength();
421                                 if(distance >= mindistance)
422                                         continue;
423                                 if(!faceboxes[i].intersectsWithLine(shootline))
424                                         continue;
425                                 result.type = POINTEDTHING_NODE;
426                                 result.node_undersurface = np;
427                                 result.node_abovesurface = np+facedirs[i];
428                                 mindistance = distance;
429                                 hilightbox = box;
430                                 should_show_hilightbox = true;
431                         }
432                 }
433                 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
434                 {
435                         v3s16 dir = n.getWallMountedDir(nodedef);
436                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
437                         dir_f *= BS/2 - BS/6 - BS/20;
438                         v3f cpf = npf + dir_f;
439                         f32 distance = (cpf - camera_position).getLength();
440
441                         core::aabbox3d<f32> box;
442                         
443                         // top
444                         if(dir == v3s16(0,1,0)){
445                                 box = f.selection_box.wall_top;
446                         }
447                         // bottom
448                         else if(dir == v3s16(0,-1,0)){
449                                 box = f.selection_box.wall_bottom;
450                         }
451                         // side
452                         else{
453                                 v3f vertices[2] =
454                                 {
455                                         f.selection_box.wall_side.MinEdge,
456                                         f.selection_box.wall_side.MaxEdge
457                                 };
458
459                                 for(s32 i=0; i<2; i++)
460                                 {
461                                         if(dir == v3s16(-1,0,0))
462                                                 vertices[i].rotateXZBy(0);
463                                         if(dir == v3s16(1,0,0))
464                                                 vertices[i].rotateXZBy(180);
465                                         if(dir == v3s16(0,0,-1))
466                                                 vertices[i].rotateXZBy(90);
467                                         if(dir == v3s16(0,0,1))
468                                                 vertices[i].rotateXZBy(-90);
469                                 }
470
471                                 box = core::aabbox3d<f32>(vertices[0]);
472                                 box.addInternalPoint(vertices[1]);
473                         }
474
475                         box.MinEdge += npf;
476                         box.MaxEdge += npf;
477                         
478                         if(distance < mindistance)
479                         {
480                                 if(box.intersectsWithLine(shootline))
481                                 {
482                                         result.type = POINTEDTHING_NODE;
483                                         result.node_undersurface = np;
484                                         result.node_abovesurface = np;
485                                         mindistance = distance;
486                                         hilightbox = box;
487                                         should_show_hilightbox = true;
488                                 }
489                         }
490                 }
491                 else // NODEBOX_REGULAR
492                 {
493                         for(u16 i=0; i<6; i++)
494                         {
495                                 v3f dir_f = v3f(dirs[i].X,
496                                                 dirs[i].Y, dirs[i].Z);
497                                 v3f centerpoint = npf + dir_f * BS/2;
498                                 f32 distance =
499                                                 (centerpoint - camera_position).getLength();
500                                 
501                                 if(distance < mindistance)
502                                 {
503                                         core::CMatrix4<f32> m;
504                                         m.buildRotateFromTo(v3f(0,0,1), dir_f);
505
506                                         // This is the back face
507                                         v3f corners[2] = {
508                                                 v3f(BS/2, BS/2, BS/2),
509                                                 v3f(-BS/2, -BS/2, BS/2+d)
510                                         };
511                                         
512                                         for(u16 j=0; j<2; j++)
513                                         {
514                                                 m.rotateVect(corners[j]);
515                                                 corners[j] += npf;
516                                         }
517
518                                         core::aabbox3d<f32> facebox(corners[0]);
519                                         facebox.addInternalPoint(corners[1]);
520
521                                         if(facebox.intersectsWithLine(shootline))
522                                         {
523                                                 result.type = POINTEDTHING_NODE;
524                                                 result.node_undersurface = np;
525                                                 result.node_abovesurface = np + dirs[i];
526                                                 mindistance = distance;
527
528                                                 //hilightbox = facebox;
529
530                                                 const float d = 0.502;
531                                                 core::aabbox3d<f32> nodebox
532                                                                 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
533                                                 v3f nodepos_f = intToFloat(np, BS);
534                                                 nodebox.MinEdge += nodepos_f;
535                                                 nodebox.MaxEdge += nodepos_f;
536                                                 hilightbox = nodebox;
537                                                 should_show_hilightbox = true;
538                                         }
539                                 } // if distance < mindistance
540                         } // for dirs
541                 } // regular block
542         } // for coords
543
544         return result;
545 }
546
547 /*
548         Draws a screen with a single text on it.
549         Text will be removed when the screen is drawn the next time.
550 */
551 /*gui::IGUIStaticText **/
552 void draw_load_screen(const std::wstring &text,
553                 video::IVideoDriver* driver, gui::IGUIFont* font)
554 {
555         v2u32 screensize = driver->getScreenSize();
556         const wchar_t *loadingtext = text.c_str();
557         core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
558         core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
559         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
560         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
561
562         gui::IGUIStaticText *guitext = guienv->addStaticText(
563                         loadingtext, textrect, false, false);
564         guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
565
566         driver->beginScene(true, true, video::SColor(255,0,0,0));
567         guienv->drawAll();
568         driver->endScene();
569         
570         guitext->remove();
571         
572         //return guitext;
573 }
574
575 /* Profiler display */
576
577 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
578                 gui::IGUIFont *font, u32 text_height,
579                 u32 show_profiler, u32 show_profiler_max)
580 {
581         if(show_profiler == 0)
582         {
583                 guitext_profiler->setVisible(false);
584         }
585         else
586         {
587
588                 std::ostringstream os(std::ios_base::binary);
589                 g_profiler->printPage(os, show_profiler, show_profiler_max);
590                 std::wstring text = narrow_to_wide(os.str());
591                 guitext_profiler->setText(text.c_str());
592                 guitext_profiler->setVisible(true);
593
594                 s32 w = font->getDimension(text.c_str()).Width;
595                 if(w < 400)
596                         w = 400;
597                 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
598                                 8+(text_height+5)*2 +
599                                 font->getDimension(text.c_str()).Height);
600                 guitext_profiler->setRelativePosition(rect);
601                 guitext_profiler->setVisible(true);
602         }
603 }
604
605 void the_game(
606         bool &kill,
607         bool random_input,
608         InputHandler *input,
609         IrrlichtDevice *device,
610         gui::IGUIFont* font,
611         std::string map_dir,
612         std::string playername,
613         std::string password,
614         std::string address, // If "", local server is used
615         u16 port,
616         std::wstring &error_message,
617         std::string configpath,
618         ChatBackend &chat_backend,
619         const SubgameSpec &gamespec, // Used for local game,
620         bool simple_singleplayer_mode
621 )
622 {
623         video::IVideoDriver* driver = device->getVideoDriver();
624         scene::ISceneManager* smgr = device->getSceneManager();
625         
626         // Calculate text height using the font
627         u32 text_height = font->getDimension(L"Random test string").Height;
628
629         v2u32 screensize(0,0);
630         v2u32 last_screensize(0,0);
631         screensize = driver->getScreenSize();
632
633         const s32 hotbar_itemcount = 8;
634         //const s32 hotbar_imagesize = 36;
635         //const s32 hotbar_imagesize = 64;
636         s32 hotbar_imagesize = 48;
637         
638         /*
639                 Draw "Loading" screen
640         */
641
642         draw_load_screen(L"Loading...", driver, font);
643         
644         // Create texture source
645         IWritableTextureSource *tsrc = createTextureSource(device);
646         
647         // These will be filled by data received from the server
648         // Create item definition manager
649         IWritableItemDefManager *itemdef = createItemDefManager();
650         // Create node definition manager
651         IWritableNodeDefManager *nodedef = createNodeDefManager();
652
653         // Add chat log output for errors to be shown in chat
654         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
655
656         // Create UI for modifying quicktune values
657         QuicktuneShortcutter quicktune;
658
659         /*
660                 Create server.
661                 SharedPtr will delete it when it goes out of scope.
662         */
663         SharedPtr<Server> server;
664         if(address == ""){
665                 draw_load_screen(L"Creating server...", driver, font);
666                 infostream<<"Creating server"<<std::endl;
667                 server = new Server(map_dir, configpath, gamespec,
668                                 simple_singleplayer_mode);
669                 server->start(port);
670         }
671
672         do{ // Client scope (breakable do-while(0))
673         
674         /*
675                 Create client
676         */
677
678         draw_load_screen(L"Creating client...", driver, font);
679         infostream<<"Creating client"<<std::endl;
680         
681         MapDrawControl draw_control;
682
683         Client client(device, playername.c_str(), password, draw_control,
684                         tsrc, itemdef, nodedef);
685         
686         // Client acts as our GameDef
687         IGameDef *gamedef = &client;
688                         
689         draw_load_screen(L"Resolving address...", driver, font);
690         Address connect_address(0,0,0,0, port);
691         try{
692                 if(address == "")
693                         //connect_address.Resolve("localhost");
694                         connect_address.setAddress(127,0,0,1);
695                 else
696                         connect_address.Resolve(address.c_str());
697         }
698         catch(ResolveError &e)
699         {
700                 error_message = L"Couldn't resolve address";
701                 errorstream<<wide_to_narrow(error_message)<<std::endl;
702                 // Break out of client scope
703                 break;
704         }
705
706         /*
707                 Attempt to connect to the server
708         */
709         
710         infostream<<"Connecting to server at ";
711         connect_address.print(&infostream);
712         infostream<<std::endl;
713         client.connect(connect_address);
714         
715         /*
716                 Wait for server to accept connection
717         */
718         bool could_connect = false;
719         bool connect_aborted = false;
720         try{
721                 float frametime = 0.033;
722                 float time_counter = 0.0;
723                 input->clear();
724                 while(device->run())
725                 {
726                         // Update client and server
727                         client.step(frametime);
728                         if(server != NULL)
729                                 server->step(frametime);
730                         
731                         // End condition
732                         if(client.connectedAndInitialized()){
733                                 could_connect = true;
734                                 break;
735                         }
736                         // Break conditions
737                         if(client.accessDenied()){
738                                 error_message = L"Access denied. Reason: "
739                                                 +client.accessDeniedReason();
740                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
741                                 break;
742                         }
743                         if(input->wasKeyDown(EscapeKey)){
744                                 connect_aborted = true;
745                                 infostream<<"Connect aborted [Escape]"<<std::endl;
746                                 break;
747                         }
748                         
749                         // Display status
750                         std::wostringstream ss;
751                         ss<<L"Connecting to server... (press Escape to cancel)\n";
752                         std::wstring animation = L"/-\\|";
753                         ss<<animation[(int)(time_counter/0.2)%4];
754                         draw_load_screen(ss.str(), driver, font);
755                         
756                         // Delay a bit
757                         sleep_ms(1000*frametime);
758                         time_counter += frametime;
759                 }
760         }
761         catch(con::PeerNotFoundException &e)
762         {}
763         
764         /*
765                 Handle failure to connect
766         */
767         if(!could_connect){
768                 if(error_message == L"" && !connect_aborted){
769                         error_message = L"Connection failed";
770                         errorstream<<wide_to_narrow(error_message)<<std::endl;
771                 }
772                 // Break out of client scope
773                 break;
774         }
775         
776         /*
777                 Wait until content has been received
778         */
779         bool got_content = false;
780         bool content_aborted = false;
781         {
782                 float frametime = 0.033;
783                 float time_counter = 0.0;
784                 input->clear();
785                 while(device->run())
786                 {
787                         // Update client and server
788                         client.step(frametime);
789                         if(server != NULL)
790                                 server->step(frametime);
791                         
792                         // End condition
793                         if(client.texturesReceived() &&
794                                         client.itemdefReceived() &&
795                                         client.nodedefReceived()){
796                                 got_content = true;
797                                 break;
798                         }
799                         // Break conditions
800                         if(!client.connectedAndInitialized()){
801                                 error_message = L"Client disconnected";
802                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
803                                 break;
804                         }
805                         if(input->wasKeyDown(EscapeKey)){
806                                 content_aborted = true;
807                                 infostream<<"Connect aborted [Escape]"<<std::endl;
808                                 break;
809                         }
810                         
811                         // Display status
812                         std::wostringstream ss;
813                         ss<<L"Waiting content... (press Escape to cancel)\n";
814
815                         ss<<(client.itemdefReceived()?L"[X]":L"[  ]");
816                         ss<<L" Item definitions\n";
817                         ss<<(client.nodedefReceived()?L"[X]":L"[  ]");
818                         ss<<L" Node definitions\n";
819                         //ss<<(client.texturesReceived()?L"[X]":L"[  ]");
820                         ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
821                         ss<<L" Textures\n";
822
823                         draw_load_screen(ss.str(), driver, font);
824                         
825                         // Delay a bit
826                         sleep_ms(1000*frametime);
827                         time_counter += frametime;
828                 }
829         }
830
831         if(!got_content){
832                 if(error_message == L"" && !content_aborted){
833                         error_message = L"Something failed";
834                         errorstream<<wide_to_narrow(error_message)<<std::endl;
835                 }
836                 // Break out of client scope
837                 break;
838         }
839
840         /*
841                 After all content has been received:
842                 Update cached textures, meshes and materials
843         */
844         client.afterContentReceived();
845
846         /*
847                 Create the camera node
848         */
849         Camera camera(smgr, draw_control);
850         if (!camera.successfullyCreated(error_message))
851                 return;
852
853         f32 camera_yaw = 0; // "right/left"
854         f32 camera_pitch = 0; // "up/down"
855
856         /*
857                 Clouds
858         */
859         
860         Clouds *clouds = NULL;
861         if(g_settings->getBool("enable_clouds"))
862         {
863                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
864         }
865
866         /*
867                 Skybox thingy
868         */
869
870         Sky *sky = NULL;
871         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
872         
873         /*
874                 FarMesh
875         */
876
877         FarMesh *farmesh = NULL;
878         if(g_settings->getBool("enable_farmesh"))
879         {
880                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
881         }
882
883         /*
884                 A copy of the local inventory
885         */
886         Inventory local_inventory(itemdef);
887
888         /*
889                 Move into game
890         */
891         
892         //gui_loadingtext->remove();
893
894         /*
895                 Add some gui stuff
896         */
897
898         // First line of debug text
899         gui::IGUIStaticText *guitext = guienv->addStaticText(
900                         L"Minetest-c55",
901                         core::rect<s32>(5, 5, 795, 5+text_height),
902                         false, false);
903         // Second line of debug text
904         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
905                         L"",
906                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
907                         false, false);
908         // At the middle of the screen
909         // Object infos are shown in this
910         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
911                         L"",
912                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
913                         false, false);
914         
915         // Status text (displays info when showing and hiding GUI stuff, etc.)
916         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
917                         L"<Status>",
918                         core::rect<s32>(0,0,0,0),
919                         false, false);
920         guitext_status->setVisible(false);
921         
922         std::wstring statustext;
923         float statustext_time = 0;
924         
925         // Chat text
926         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
927                         L"",
928                         core::rect<s32>(0,0,0,0),
929                         //false, false); // Disable word wrap as of now
930                         false, true);
931         // Remove stale "recent" chat messages from previous connections
932         chat_backend.clearRecentChat();
933         // Chat backend and console
934         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
935         
936         // Profiler text (size is updated when text is updated)
937         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
938                         L"<Profiler>",
939                         core::rect<s32>(0,0,0,0),
940                         false, false);
941         guitext_profiler->setBackgroundColor(video::SColor(80,0,0,0));
942         guitext_profiler->setVisible(false);
943         
944         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
945                         (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
946         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
947                         (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
948         
949         // Test the text input system
950         /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
951                         NULL))->drop();*/
952         /*GUIMessageMenu *menu =
953                         new GUIMessageMenu(guienv, guiroot, -1, 
954                                 &g_menumgr,
955                                 L"Asd");
956         menu->drop();*/
957         
958         // Launch pause menu
959         /*(new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
960                         &g_menumgr))->drop();*/
961         
962         //s32 guitext_chat_pad_bottom = 70;
963
964         /*
965                 Some statistics are collected in these
966         */
967         u32 drawtime = 0;
968         u32 beginscenetime = 0;
969         u32 scenetime = 0;
970         u32 endscenetime = 0;
971         
972         // A test
973         //throw con::PeerNotFoundException("lol");
974
975         float recent_turn_speed = 0.0;
976
977         core::list<float> frametime_log;
978
979         float nodig_delay_timer = 0.0;
980         float dig_time = 0.0;
981         u16 dig_index = 0;
982         PointedThing pointed_old;
983         bool digging = false;
984         bool ldown_for_dig = false;
985
986         float damage_flash_timer = 0;
987         s16 farmesh_range = 20*MAP_BLOCKSIZE;
988
989         const float object_hit_delay = 0.2;
990         float object_hit_delay_timer = 0.0;
991         float time_from_last_punch = 10;
992
993         bool invert_mouse = g_settings->getBool("invert_mouse");
994
995         bool respawn_menu_active = false;
996         bool update_wielded_item_trigger = false;
997
998         bool show_hud = true;
999         bool show_chat = true;
1000         bool force_fog_off = false;
1001         bool disable_camera_update = false;
1002         bool show_debug = g_settings->getBool("show_debug");
1003         bool show_debug_frametime = false;
1004         u32 show_profiler = 0;
1005         u32 show_profiler_max = 3;  // Number of pages
1006
1007         float time_of_day = 0;
1008         float time_of_day_smooth = 0;
1009
1010         /*
1011                 Main loop
1012         */
1013
1014         bool first_loop_after_window_activation = true;
1015
1016         // TODO: Convert the static interval timers to these
1017         // Interval limiter for profiler
1018         IntervalLimiter m_profiler_interval;
1019
1020         // Time is in milliseconds
1021         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1022         // NOTE: So we have to use getTime() and call run()s between them
1023         u32 lasttime = device->getTimer()->getTime();
1024
1025         while(device->run() && kill == false)
1026         {
1027                 //std::cerr<<"frame"<<std::endl;
1028
1029                 if(client.accessDenied())
1030                 {
1031                         error_message = L"Access denied. Reason: "
1032                                         +client.accessDeniedReason();
1033                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1034                         break;
1035                 }
1036
1037                 if(g_gamecallback->disconnect_requested)
1038                 {
1039                         g_gamecallback->disconnect_requested = false;
1040                         break;
1041                 }
1042
1043                 if(g_gamecallback->changepassword_requested)
1044                 {
1045                         (new GUIPasswordChange(guienv, guiroot, -1,
1046                                 &g_menumgr, &client))->drop();
1047                         g_gamecallback->changepassword_requested = false;
1048                 }
1049
1050                 /*
1051                         Process TextureSource's queue
1052                 */
1053                 tsrc->processQueue();
1054
1055                 /*
1056                         Random calculations
1057                 */
1058                 last_screensize = screensize;
1059                 screensize = driver->getScreenSize();
1060                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1061                 //bool screensize_changed = screensize != last_screensize;
1062
1063                 // Resize hotbar
1064                 if(screensize.Y <= 800)
1065                         hotbar_imagesize = 32;
1066                 else if(screensize.Y <= 1280)
1067                         hotbar_imagesize = 48;
1068                 else
1069                         hotbar_imagesize = 64;
1070                 
1071                 // Hilight boxes collected during the loop and displayed
1072                 core::list< core::aabbox3d<f32> > hilightboxes;
1073                 
1074                 // Info text
1075                 std::wstring infotext;
1076
1077                 // When screen size changes, update positions and sizes of stuff
1078                 /*if(screensize_changed)
1079                 {
1080                         v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
1081                         quick_inventory->updatePosition(pos);
1082                 }*/
1083
1084                 //TimeTaker //timer1("//timer1");
1085                 
1086                 // Time of frame without fps limit
1087                 float busytime;
1088                 u32 busytime_u32;
1089                 {
1090                         // not using getRealTime is necessary for wine
1091                         u32 time = device->getTimer()->getTime();
1092                         if(time > lasttime)
1093                                 busytime_u32 = time - lasttime;
1094                         else
1095                                 busytime_u32 = 0;
1096                         busytime = busytime_u32 / 1000.0;
1097                 }
1098
1099                 //infostream<<"busytime_u32="<<busytime_u32<<std::endl;
1100         
1101                 // Necessary for device->getTimer()->getTime()
1102                 device->run();
1103
1104                 /*
1105                         FPS limiter
1106                 */
1107
1108                 {
1109                         float fps_max = g_settings->getFloat("fps_max");
1110                         u32 frametime_min = 1000./fps_max;
1111                         
1112                         if(busytime_u32 < frametime_min)
1113                         {
1114                                 u32 sleeptime = frametime_min - busytime_u32;
1115                                 device->sleep(sleeptime);
1116                         }
1117                 }
1118
1119                 // Necessary for device->getTimer()->getTime()
1120                 device->run();
1121
1122                 /*
1123                         Time difference calculation
1124                 */
1125                 f32 dtime; // in seconds
1126                 
1127                 u32 time = device->getTimer()->getTime();
1128                 if(time > lasttime)
1129                         dtime = (time - lasttime) / 1000.0;
1130                 else
1131                         dtime = 0;
1132                 lasttime = time;
1133
1134                 /* Run timers */
1135
1136                 if(nodig_delay_timer >= 0)
1137                         nodig_delay_timer -= dtime;
1138                 if(object_hit_delay_timer >= 0)
1139                         object_hit_delay_timer -= dtime;
1140                 time_from_last_punch += dtime;
1141
1142                 g_profiler->add("Elapsed time", dtime);
1143                 g_profiler->avg("FPS", 1./dtime);
1144
1145                 /*
1146                         Log frametime for visualization
1147                 */
1148                 frametime_log.push_back(dtime);
1149                 if(frametime_log.size() > 100)
1150                 {
1151                         core::list<float>::Iterator i = frametime_log.begin();
1152                         frametime_log.erase(i);
1153                 }
1154
1155                 /*
1156                         Visualize frametime in terminal
1157                 */
1158                 /*for(u32 i=0; i<dtime*400; i++)
1159                         infostream<<"X";
1160                 infostream<<std::endl;*/
1161
1162                 /*
1163                         Time average and jitter calculation
1164                 */
1165
1166                 static f32 dtime_avg1 = 0.0;
1167                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1168                 f32 dtime_jitter1 = dtime - dtime_avg1;
1169
1170                 static f32 dtime_jitter1_max_sample = 0.0;
1171                 static f32 dtime_jitter1_max_fraction = 0.0;
1172                 {
1173                         static f32 jitter1_max = 0.0;
1174                         static f32 counter = 0.0;
1175                         if(dtime_jitter1 > jitter1_max)
1176                                 jitter1_max = dtime_jitter1;
1177                         counter += dtime;
1178                         if(counter > 0.0)
1179                         {
1180                                 counter -= 3.0;
1181                                 dtime_jitter1_max_sample = jitter1_max;
1182                                 dtime_jitter1_max_fraction
1183                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1184                                 jitter1_max = 0.0;
1185                         }
1186                 }
1187                 
1188                 /*
1189                         Busytime average and jitter calculation
1190                 */
1191
1192                 static f32 busytime_avg1 = 0.0;
1193                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1194                 f32 busytime_jitter1 = busytime - busytime_avg1;
1195                 
1196                 static f32 busytime_jitter1_max_sample = 0.0;
1197                 static f32 busytime_jitter1_min_sample = 0.0;
1198                 {
1199                         static f32 jitter1_max = 0.0;
1200                         static f32 jitter1_min = 0.0;
1201                         static f32 counter = 0.0;
1202                         if(busytime_jitter1 > jitter1_max)
1203                                 jitter1_max = busytime_jitter1;
1204                         if(busytime_jitter1 < jitter1_min)
1205                                 jitter1_min = busytime_jitter1;
1206                         counter += dtime;
1207                         if(counter > 0.0){
1208                                 counter -= 3.0;
1209                                 busytime_jitter1_max_sample = jitter1_max;
1210                                 busytime_jitter1_min_sample = jitter1_min;
1211                                 jitter1_max = 0.0;
1212                                 jitter1_min = 0.0;
1213                         }
1214                 }
1215                 
1216                 /*
1217                         Debug info for client
1218                 */
1219                 {
1220                         static float counter = 0.0;
1221                         counter -= dtime;
1222                         if(counter < 0)
1223                         {
1224                                 counter = 30.0;
1225                                 client.printDebugInfo(infostream);
1226                         }
1227                 }
1228
1229                 /*
1230                         Profiler
1231                 */
1232                 float profiler_print_interval =
1233                                 g_settings->getFloat("profiler_print_interval");
1234                 bool print_to_log = true;
1235                 if(profiler_print_interval == 0){
1236                         print_to_log = false;
1237                         profiler_print_interval = 5;
1238                 }
1239                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1240                 {
1241                         if(print_to_log){
1242                                 infostream<<"Profiler:"<<std::endl;
1243                                 g_profiler->print(infostream);
1244                         }
1245
1246                         update_profiler_gui(guitext_profiler, font, text_height,
1247                                         show_profiler, show_profiler_max);
1248
1249                         g_profiler->clear();
1250                 }
1251
1252                 /*
1253                         Direct handling of user input
1254                 */
1255                 
1256                 // Reset input if window not active or some menu is active
1257                 if(device->isWindowActive() == false
1258                                 || noMenuActive() == false
1259                                 || guienv->hasFocus(gui_chat_console))
1260                 {
1261                         input->clear();
1262                 }
1263
1264                 // Input handler step() (used by the random input generator)
1265                 input->step(dtime);
1266
1267                 /*
1268                         Launch menus and trigger stuff according to keys
1269                 */
1270                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1271                 {
1272                         // drop selected item
1273                         IDropAction *a = new IDropAction();
1274                         a->count = 0;
1275                         a->from_inv.setCurrentPlayer();
1276                         a->from_list = "main";
1277                         a->from_i = client.getPlayerItem();
1278                         client.inventoryAction(a);
1279                 }
1280                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1281                 {
1282                         infostream<<"the_game: "
1283                                         <<"Launching inventory"<<std::endl;
1284                         
1285                         GUIInventoryMenu *menu =
1286                                 new GUIInventoryMenu(guienv, guiroot, -1,
1287                                         &g_menumgr, v2s16(8,7),
1288                                         &client, gamedef);
1289
1290                         InventoryLocation inventoryloc;
1291                         inventoryloc.setCurrentPlayer();
1292
1293                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1294                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1295                                         "list", inventoryloc, "main",
1296                                         v2s32(0, 3), v2s32(8, 4)));
1297                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1298                                         "list", inventoryloc, "craft",
1299                                         v2s32(3, 0), v2s32(3, 3)));
1300                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1301                                         "list", inventoryloc, "craftpreview",
1302                                         v2s32(7, 1), v2s32(1, 1)));
1303
1304                         menu->setDrawSpec(draw_spec);
1305
1306                         menu->drop();
1307                 }
1308                 else if(input->wasKeyDown(EscapeKey))
1309                 {
1310                         infostream<<"the_game: "
1311                                         <<"Launching pause menu"<<std::endl;
1312                         // It will delete itself by itself
1313                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1314                                         &g_menumgr, simple_singleplayer_mode))->drop();
1315
1316                         // Move mouse cursor on top of the disconnect button
1317                         if(simple_singleplayer_mode)
1318                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1319                         else
1320                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1321                 }
1322                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1323                 {
1324                         TextDest *dest = new TextDestChat(&client);
1325
1326                         (new GUITextInputMenu(guienv, guiroot, -1,
1327                                         &g_menumgr, dest,
1328                                         L""))->drop();
1329                 }
1330                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1331                 {
1332                         TextDest *dest = new TextDestChat(&client);
1333
1334                         (new GUITextInputMenu(guienv, guiroot, -1,
1335                                         &g_menumgr, dest,
1336                                         L"/"))->drop();
1337                 }
1338                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1339                 {
1340                         if (!gui_chat_console->isOpenInhibited())
1341                         {
1342                                 // Open up to over half of the screen
1343                                 gui_chat_console->openConsole(0.6);
1344                                 guienv->setFocus(gui_chat_console);
1345                         }
1346                 }
1347                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1348                 {
1349                         if(g_settings->getBool("free_move"))
1350                         {
1351                                 g_settings->set("free_move","false");
1352                                 statustext = L"free_move disabled";
1353                                 statustext_time = 0;
1354                         }
1355                         else
1356                         {
1357                                 g_settings->set("free_move","true");
1358                                 statustext = L"free_move enabled";
1359                                 statustext_time = 0;
1360                         }
1361                 }
1362                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1363                 {
1364                         if(g_settings->getBool("fast_move"))
1365                         {
1366                                 g_settings->set("fast_move","false");
1367                                 statustext = L"fast_move disabled";
1368                                 statustext_time = 0;
1369                         }
1370                         else
1371                         {
1372                                 g_settings->set("fast_move","true");
1373                                 statustext = L"fast_move enabled";
1374                                 statustext_time = 0;
1375                         }
1376                 }
1377                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1378                 {
1379                         irr::video::IImage* const image = driver->createScreenShot(); 
1380                         if (image) { 
1381                                 irr::c8 filename[256]; 
1382                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1383                                                  g_settings->get("screenshot_path").c_str(),
1384                                                  device->getTimer()->getRealTime()); 
1385                                 if (driver->writeImageToFile(image, filename)) {
1386                                         std::wstringstream sstr;
1387                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1388                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1389                                         statustext = sstr.str();
1390                                         statustext_time = 0;
1391                                 } else{
1392                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1393                                 }
1394                                 image->drop(); 
1395                         }                        
1396                 }
1397                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1398                 {
1399                         show_hud = !show_hud;
1400                         if(show_hud)
1401                                 statustext = L"HUD shown";
1402                         else
1403                                 statustext = L"HUD hidden";
1404                         statustext_time = 0;
1405                 }
1406                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1407                 {
1408                         show_chat = !show_chat;
1409                         if(show_chat)
1410                                 statustext = L"Chat shown";
1411                         else
1412                                 statustext = L"Chat hidden";
1413                         statustext_time = 0;
1414                 }
1415                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1416                 {
1417                         force_fog_off = !force_fog_off;
1418                         if(force_fog_off)
1419                                 statustext = L"Fog disabled";
1420                         else
1421                                 statustext = L"Fog enabled";
1422                         statustext_time = 0;
1423                 }
1424                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1425                 {
1426                         disable_camera_update = !disable_camera_update;
1427                         if(disable_camera_update)
1428                                 statustext = L"Camera update disabled";
1429                         else
1430                                 statustext = L"Camera update enabled";
1431                         statustext_time = 0;
1432                 }
1433                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1434                 {
1435                         // Initial / 3x toggle: Chat only
1436                         // 1x toggle: Debug text with chat
1437                         // 2x toggle: Debug text with frametime
1438                         if(!show_debug)
1439                         {
1440                                 show_debug = true;
1441                                 show_debug_frametime = false;
1442                                 statustext = L"Debug info shown";
1443                                 statustext_time = 0;
1444                         }
1445                         else if(show_debug_frametime)
1446                         {
1447                                 show_debug = false;
1448                                 show_debug_frametime = false;
1449                                 statustext = L"Debug info and frametime graph hidden";
1450                                 statustext_time = 0;
1451                         }
1452                         else
1453                         {
1454                                 show_debug_frametime = true;
1455                                 statustext = L"Frametime graph shown";
1456                                 statustext_time = 0;
1457                         }
1458                 }
1459                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1460                 {
1461                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1462
1463                         // FIXME: This updates the profiler with incomplete values
1464                         update_profiler_gui(guitext_profiler, font, text_height,
1465                                         show_profiler, show_profiler_max);
1466
1467                         if(show_profiler != 0)
1468                         {
1469                                 std::wstringstream sstr;
1470                                 sstr<<"Profiler shown (page "<<show_profiler
1471                                         <<" of "<<show_profiler_max<<")";
1472                                 statustext = sstr.str();
1473                                 statustext_time = 0;
1474                         }
1475                         else
1476                         {
1477                                 statustext = L"Profiler hidden";
1478                                 statustext_time = 0;
1479                         }
1480                 }
1481                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1482                 {
1483                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1484                         s16 range_new = range + 10;
1485                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1486                         statustext = narrow_to_wide(
1487                                         "Minimum viewing range changed to "
1488                                         + itos(range_new));
1489                         statustext_time = 0;
1490                 }
1491                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1492                 {
1493                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1494                         s16 range_new = range - 10;
1495                         if(range_new < 0)
1496                                 range_new = range;
1497                         g_settings->set("viewing_range_nodes_min",
1498                                         itos(range_new));
1499                         statustext = narrow_to_wide(
1500                                         "Minimum viewing range changed to "
1501                                         + itos(range_new));
1502                         statustext_time = 0;
1503                 }
1504                 
1505                 // Handle QuicktuneShortcutter
1506                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1507                         quicktune.next();
1508                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1509                         quicktune.prev();
1510                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1511                         quicktune.inc();
1512                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1513                         quicktune.dec();
1514                 {
1515                         std::string msg = quicktune.getMessage();
1516                         if(msg != ""){
1517                                 statustext = narrow_to_wide(msg);
1518                                 statustext_time = 0;
1519                         }
1520                 }
1521
1522                 // Item selection with mouse wheel
1523                 u16 new_playeritem = client.getPlayerItem();
1524                 {
1525                         s32 wheel = input->getMouseWheel();
1526                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1527                                         hotbar_itemcount-1);
1528
1529                         if(wheel < 0)
1530                         {
1531                                 if(new_playeritem < max_item)
1532                                         new_playeritem++;
1533                                 else
1534                                         new_playeritem = 0;
1535                         }
1536                         else if(wheel > 0)
1537                         {
1538                                 if(new_playeritem > 0)
1539                                         new_playeritem--;
1540                                 else
1541                                         new_playeritem = max_item;
1542                         }
1543                 }
1544                 
1545                 // Item selection
1546                 for(u16 i=0; i<10; i++)
1547                 {
1548                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1549                         if(input->wasKeyDown(*kp))
1550                         {
1551                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1552                                 {
1553                                         new_playeritem = i;
1554
1555                                         infostream<<"Selected item: "
1556                                                         <<new_playeritem<<std::endl;
1557                                 }
1558                         }
1559                 }
1560
1561                 // Viewing range selection
1562                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1563                 {
1564                         draw_control.range_all = !draw_control.range_all;
1565                         if(draw_control.range_all)
1566                         {
1567                                 infostream<<"Enabled full viewing range"<<std::endl;
1568                                 statustext = L"Enabled full viewing range";
1569                                 statustext_time = 0;
1570                         }
1571                         else
1572                         {
1573                                 infostream<<"Disabled full viewing range"<<std::endl;
1574                                 statustext = L"Disabled full viewing range";
1575                                 statustext_time = 0;
1576                         }
1577                 }
1578
1579                 // Print debug stacks
1580                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1581                 {
1582                         dstream<<"-----------------------------------------"
1583                                         <<std::endl;
1584                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1585                         dstream<<"-----------------------------------------"
1586                                         <<std::endl;
1587                         debug_stacks_print();
1588                 }
1589
1590                 /*
1591                         Mouse and camera control
1592                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1593                 */
1594                 
1595                 float turn_amount = 0;
1596                 if((device->isWindowActive() && noMenuActive()) || random_input)
1597                 {
1598                         if(!random_input)
1599                         {
1600                                 // Mac OSX gets upset if this is set every frame
1601                                 if(device->getCursorControl()->isVisible())
1602                                         device->getCursorControl()->setVisible(false);
1603                         }
1604
1605                         if(first_loop_after_window_activation){
1606                                 //infostream<<"window active, first loop"<<std::endl;
1607                                 first_loop_after_window_activation = false;
1608                         }
1609                         else{
1610                                 s32 dx = input->getMousePos().X - displaycenter.X;
1611                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1612                                 if(invert_mouse)
1613                                         dy = -dy;
1614                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1615                                 
1616                                 /*const float keyspeed = 500;
1617                                 if(input->isKeyDown(irr::KEY_UP))
1618                                         dy -= dtime * keyspeed;
1619                                 if(input->isKeyDown(irr::KEY_DOWN))
1620                                         dy += dtime * keyspeed;
1621                                 if(input->isKeyDown(irr::KEY_LEFT))
1622                                         dx -= dtime * keyspeed;
1623                                 if(input->isKeyDown(irr::KEY_RIGHT))
1624                                         dx += dtime * keyspeed;*/
1625                                 
1626                                 float d = 0.2;
1627                                 camera_yaw -= dx*d;
1628                                 camera_pitch += dy*d;
1629                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1630                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1631                                 
1632                                 turn_amount = v2f(dx, dy).getLength() * d;
1633                         }
1634                         input->setMousePos(displaycenter.X, displaycenter.Y);
1635                 }
1636                 else{
1637                         // Mac OSX gets upset if this is set every frame
1638                         if(device->getCursorControl()->isVisible() == false)
1639                                 device->getCursorControl()->setVisible(true);
1640
1641                         //infostream<<"window inactive"<<std::endl;
1642                         first_loop_after_window_activation = true;
1643                 }
1644                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1645                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1646
1647                 /*
1648                         Player speed control
1649                 */
1650                 {
1651                         /*bool a_up,
1652                         bool a_down,
1653                         bool a_left,
1654                         bool a_right,
1655                         bool a_jump,
1656                         bool a_superspeed,
1657                         bool a_sneak,
1658                         float a_pitch,
1659                         float a_yaw*/
1660                         PlayerControl control(
1661                                 input->isKeyDown(getKeySetting("keymap_forward")),
1662                                 input->isKeyDown(getKeySetting("keymap_backward")),
1663                                 input->isKeyDown(getKeySetting("keymap_left")),
1664                                 input->isKeyDown(getKeySetting("keymap_right")),
1665                                 input->isKeyDown(getKeySetting("keymap_jump")),
1666                                 input->isKeyDown(getKeySetting("keymap_special1")),
1667                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1668                                 camera_pitch,
1669                                 camera_yaw
1670                         );
1671                         client.setPlayerControl(control);
1672                 }
1673                 
1674                 /*
1675                         Run server
1676                 */
1677
1678                 if(server != NULL)
1679                 {
1680                         //TimeTaker timer("server->step(dtime)");
1681                         server->step(dtime);
1682                 }
1683
1684                 /*
1685                         Process environment
1686                 */
1687                 
1688                 {
1689                         //TimeTaker timer("client.step(dtime)");
1690                         client.step(dtime);
1691                         //client.step(dtime_avg1);
1692                 }
1693
1694                 {
1695                         // Read client events
1696                         for(;;)
1697                         {
1698                                 ClientEvent event = client.getClientEvent();
1699                                 if(event.type == CE_NONE)
1700                                 {
1701                                         break;
1702                                 }
1703                                 else if(event.type == CE_PLAYER_DAMAGE)
1704                                 {
1705                                         //u16 damage = event.player_damage.amount;
1706                                         //infostream<<"Player damage: "<<damage<<std::endl;
1707                                         damage_flash_timer = 0.05;
1708                                         if(event.player_damage.amount >= 2){
1709                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1710                                         }
1711                                 }
1712                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1713                                 {
1714                                         camera_yaw = event.player_force_move.yaw;
1715                                         camera_pitch = event.player_force_move.pitch;
1716                                 }
1717                                 else if(event.type == CE_DEATHSCREEN)
1718                                 {
1719                                         if(respawn_menu_active)
1720                                                 continue;
1721
1722                                         /*bool set_camera_point_target =
1723                                                         event.deathscreen.set_camera_point_target;
1724                                         v3f camera_point_target;
1725                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1726                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1727                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1728                                         MainRespawnInitiator *respawner =
1729                                                         new MainRespawnInitiator(
1730                                                                         &respawn_menu_active, &client);
1731                                         GUIDeathScreen *menu =
1732                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1733                                                                 &g_menumgr, respawner);
1734                                         menu->drop();
1735                                         
1736                                         chat_backend.addMessage(L"", L"You died.");
1737
1738                                         /* Handle visualization */
1739
1740                                         damage_flash_timer = 0;
1741
1742                                         /*LocalPlayer* player = client.getLocalPlayer();
1743                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1744                                         camera.update(player, busytime, screensize);*/
1745                                 }
1746                                 else if(event.type == CE_TEXTURES_UPDATED)
1747                                 {
1748                                         update_wielded_item_trigger = true;
1749                                 }
1750                         }
1751                 }
1752                 
1753                 //TimeTaker //timer2("//timer2");
1754
1755                 /*
1756                         For interaction purposes, get info about the held item
1757                         - What item is it?
1758                         - Is it a usable item?
1759                         - Can it point to liquids?
1760                 */
1761                 ItemStack playeritem;
1762                 bool playeritem_usable = false;
1763                 bool playeritem_liquids_pointable = false;
1764                 {
1765                         InventoryList *mlist = local_inventory.getList("main");
1766                         if(mlist != NULL)
1767                         {
1768                                 playeritem = mlist->getItem(client.getPlayerItem());
1769                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1770                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1771                         }
1772                 }
1773                 ToolCapabilities playeritem_toolcap =
1774                                 playeritem.getToolCapabilities(itemdef);
1775                 
1776                 /*
1777                         Update camera
1778                 */
1779
1780                 LocalPlayer* player = client.getEnv().getLocalPlayer();
1781                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1782                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1783                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1784                 camera.update(player, busytime, screensize, tool_reload_ratio);
1785                 camera.step(dtime);
1786
1787                 v3f player_position = player->getPosition();
1788                 v3f camera_position = camera.getPosition();
1789                 v3f camera_direction = camera.getDirection();
1790                 f32 camera_fov = camera.getFovMax();
1791                 
1792                 if(!disable_camera_update){
1793                         client.getEnv().getClientMap().updateCamera(camera_position,
1794                                 camera_direction, camera_fov);
1795                 }
1796
1797                 //timer2.stop();
1798                 //TimeTaker //timer3("//timer3");
1799
1800                 /*
1801                         Calculate what block is the crosshair pointing to
1802                 */
1803                 
1804                 //u32 t1 = device->getTimer()->getRealTime();
1805                 
1806                 f32 d = 4; // max. distance
1807                 core::line3d<f32> shootline(camera_position,
1808                                 camera_position + camera_direction * BS * (d+1));
1809
1810                 core::aabbox3d<f32> hilightbox;
1811                 bool should_show_hilightbox = false;
1812                 ClientActiveObject *selected_object = NULL;
1813
1814                 PointedThing pointed = getPointedThing(
1815                                 // input
1816                                 &client, player_position, camera_direction,
1817                                 camera_position, shootline, d,
1818                                 playeritem_liquids_pointable, !ldown_for_dig,
1819                                 // output
1820                                 hilightbox, should_show_hilightbox,
1821                                 selected_object);
1822
1823                 if(pointed != pointed_old)
1824                 {
1825                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1826                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1827                 }
1828
1829                 /*
1830                         Visualize selection
1831                 */
1832                 if(should_show_hilightbox)
1833                         hilightboxes.push_back(hilightbox);
1834
1835                 /*
1836                         Stop digging when
1837                         - releasing left mouse button
1838                         - pointing away from node
1839                 */
1840                 if(digging)
1841                 {
1842                         if(input->getLeftReleased())
1843                         {
1844                                 infostream<<"Left button released"
1845                                         <<" (stopped digging)"<<std::endl;
1846                                 digging = false;
1847                         }
1848                         else if(pointed != pointed_old)
1849                         {
1850                                 if (pointed.type == POINTEDTHING_NODE
1851                                         && pointed_old.type == POINTEDTHING_NODE
1852                                         && pointed.node_undersurface == pointed_old.node_undersurface)
1853                                 {
1854                                         // Still pointing to the same node,
1855                                         // but a different face. Don't reset.
1856                                 }
1857                                 else
1858                                 {
1859                                         infostream<<"Pointing away from node"
1860                                                 <<" (stopped digging)"<<std::endl;
1861                                         digging = false;
1862                                 }
1863                         }
1864                         if(!digging)
1865                         {
1866                                 client.interact(1, pointed_old);
1867                                 client.setCrack(-1, v3s16(0,0,0));
1868                                 dig_time = 0.0;
1869                         }
1870                 }
1871                 if(!digging && ldown_for_dig && !input->getLeftState())
1872                 {
1873                         ldown_for_dig = false;
1874                 }
1875
1876                 bool left_punch = false;
1877
1878                 if(playeritem_usable && input->getLeftState())
1879                 {
1880                         if(input->getLeftClicked())
1881                                 client.interact(4, pointed);
1882                 }
1883                 else if(pointed.type == POINTEDTHING_NODE)
1884                 {
1885                         v3s16 nodepos = pointed.node_undersurface;
1886                         v3s16 neighbourpos = pointed.node_abovesurface;
1887
1888                         /*
1889                                 Check information text of node
1890                         */
1891                         
1892                         ClientMap &map = client.getEnv().getClientMap();
1893                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
1894                         if(meta){
1895                                 infotext = narrow_to_wide(meta->infoText());
1896                         } else {
1897                                 MapNode n = map.getNode(nodepos);
1898                                 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
1899                                         infotext = L"Unknown node: ";
1900                                         infotext += narrow_to_wide(nodedef->get(n).name);
1901                                 }
1902                         }
1903                         
1904                         /*
1905                                 Handle digging
1906                         */
1907                         
1908                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
1909                         {
1910                                 if(!digging)
1911                                 {
1912                                         infostream<<"Started digging"<<std::endl;
1913                                         client.interact(0, pointed);
1914                                         digging = true;
1915                                         ldown_for_dig = true;
1916                                 }
1917                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
1918
1919                                 // Get digging parameters
1920                                 DigParams params = getDigParams(nodedef->get(n).groups,
1921                                                 &playeritem_toolcap);
1922                                 // If can't dig, try hand
1923                                 if(!params.diggable){
1924                                         const ItemDefinition &hand = itemdef->get("");
1925                                         const ToolCapabilities *tp = hand.tool_capabilities;
1926                                         if(tp)
1927                                                 params = getDigParams(nodedef->get(n).groups, tp);
1928                                 }
1929
1930                                 float dig_time_complete = 0.0;
1931
1932                                 if(params.diggable == false)
1933                                 {
1934                                         // I guess nobody will wait for this long
1935                                         dig_time_complete = 10000000.0;
1936                                 }
1937                                 else
1938                                 {
1939                                         dig_time_complete = params.time;
1940                                 }
1941
1942                                 if(dig_time_complete >= 0.001)
1943                                 {
1944                                         dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1945                                                         * dig_time/dig_time_complete);
1946                                 }
1947                                 // This is for torches
1948                                 else
1949                                 {
1950                                         dig_index = CRACK_ANIMATION_LENGTH;
1951                                 }
1952                                 
1953                                 // Don't show cracks if not diggable
1954                                 if(dig_time_complete >= 100000.0)
1955                                 {
1956                                 }
1957                                 else if(dig_index < CRACK_ANIMATION_LENGTH)
1958                                 {
1959                                         //TimeTaker timer("client.setTempMod");
1960                                         //infostream<<"dig_index="<<dig_index<<std::endl;
1961                                         client.setCrack(dig_index, nodepos);
1962                                 }
1963                                 else
1964                                 {
1965                                         infostream<<"Digging completed"<<std::endl;
1966                                         client.interact(2, pointed);
1967                                         client.setCrack(-1, v3s16(0,0,0));
1968                                         client.removeNode(nodepos);
1969
1970                                         dig_time = 0;
1971                                         digging = false;
1972
1973                                         nodig_delay_timer = dig_time_complete
1974                                                         / (float)CRACK_ANIMATION_LENGTH;
1975
1976                                         // We don't want a corresponding delay to
1977                                         // very time consuming nodes
1978                                         if(nodig_delay_timer > 0.5)
1979                                         {
1980                                                 nodig_delay_timer = 0.5;
1981                                         }
1982                                         // We want a slight delay to very little
1983                                         // time consuming nodes
1984                                         float mindelay = 0.15;
1985                                         if(nodig_delay_timer < mindelay)
1986                                         {
1987                                                 nodig_delay_timer = mindelay;
1988                                         }
1989                                 }
1990
1991                                 dig_time += dtime;
1992
1993                                 camera.setDigging(0);  // left click animation
1994                         }
1995
1996                         if(input->getRightClicked())
1997                         {
1998                                 infostream<<"Ground right-clicked"<<std::endl;
1999                                 
2000                                 // If metadata provides an inventory view, activate it
2001                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2002                                 {
2003                                         infostream<<"Launching custom inventory view"<<std::endl;
2004
2005                                         InventoryLocation inventoryloc;
2006                                         inventoryloc.setNodeMeta(nodepos);
2007                                         
2008
2009                                         /*
2010                                                 Create menu
2011                                         */
2012
2013                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2014                                         v2s16 invsize =
2015                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
2016                                                         draw_spec,
2017                                                         meta->getInventoryDrawSpecString(),
2018                                                         inventoryloc);
2019
2020                                         GUIInventoryMenu *menu =
2021                                                 new GUIInventoryMenu(guienv, guiroot, -1,
2022                                                         &g_menumgr, invsize,
2023                                                         &client, gamedef);
2024                                         menu->setDrawSpec(draw_spec);
2025                                         menu->drop();
2026                                 }
2027                                 // If metadata provides text input, activate text input
2028                                 else if(meta && meta->allowsTextInput() && !random_input)
2029                                 {
2030                                         infostream<<"Launching metadata text input"<<std::endl;
2031                                         
2032                                         // Get a new text for it
2033
2034                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2035
2036                                         std::wstring wtext = narrow_to_wide(meta->getText());
2037
2038                                         (new GUITextInputMenu(guienv, guiroot, -1,
2039                                                         &g_menumgr, dest,
2040                                                         wtext))->drop();
2041                                 }
2042                                 // Otherwise report right click to server
2043                                 else
2044                                 {
2045                                         client.interact(3, pointed);
2046                                         camera.setDigging(1);  // right click animation
2047                                 }
2048                         }
2049                 }
2050                 else if(pointed.type == POINTEDTHING_OBJECT)
2051                 {
2052                         infotext = narrow_to_wide(selected_object->infoText());
2053
2054                         if(infotext == L"" && show_debug){
2055                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2056                         }
2057
2058                         //if(input->getLeftClicked())
2059                         if(input->getLeftState())
2060                         {
2061                                 bool do_punch = false;
2062                                 bool do_punch_damage = false;
2063                                 if(object_hit_delay_timer <= 0.0){
2064                                         do_punch = true;
2065                                         do_punch_damage = true;
2066                                         object_hit_delay_timer = object_hit_delay;
2067                                 }
2068                                 if(input->getLeftClicked()){
2069                                         do_punch = true;
2070                                 }
2071                                 if(do_punch){
2072                                         infostream<<"Left-clicked object"<<std::endl;
2073                                         left_punch = true;
2074                                 }
2075                                 if(do_punch_damage){
2076                                         // Report direct punch
2077                                         v3f objpos = selected_object->getPosition();
2078                                         v3f dir = (objpos - player_position).normalize();
2079                                         
2080                                         bool disable_send = selected_object->directReportPunch(
2081                                                         dir, &playeritem, time_from_last_punch);
2082                                         time_from_last_punch = 0;
2083                                         if(!disable_send)
2084                                                 client.interact(0, pointed);
2085                                 }
2086                         }
2087                         else if(input->getRightClicked())
2088                         {
2089                                 infostream<<"Right-clicked object"<<std::endl;
2090                                 client.interact(3, pointed);  // place
2091                         }
2092                 }
2093                 else if(input->getLeftState())
2094                 {
2095                         // When button is held down in air, show continuous animation
2096                         left_punch = true;
2097                 }
2098
2099                 pointed_old = pointed;
2100                 
2101                 if(left_punch || input->getLeftClicked())
2102                 {
2103                         camera.setDigging(0); // left click animation
2104                 }
2105
2106                 input->resetLeftClicked();
2107                 input->resetRightClicked();
2108
2109                 input->resetLeftReleased();
2110                 input->resetRightReleased();
2111                 
2112                 /*
2113                         Calculate stuff for drawing
2114                 */
2115
2116                 /*
2117                         Fog range
2118                 */
2119         
2120                 f32 fog_range;
2121                 if(farmesh)
2122                 {
2123                         fog_range = BS*farmesh_range;
2124                 }
2125                 else
2126                 {
2127                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2128                         fog_range *= 0.9;
2129                         if(draw_control.range_all)
2130                                 fog_range = 100000*BS;
2131                 }
2132
2133                 /*
2134                         Calculate general brightness
2135                 */
2136                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2137                 float time_brightness = (float)decode_light(
2138                                 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2139                 float direct_brightness = 0;
2140                 bool sunlight_seen = false;
2141                 if(g_settings->getBool("free_move")){
2142                         direct_brightness = time_brightness;
2143                         sunlight_seen = true;
2144                 } else {
2145                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2146                         float old_brightness = sky->getBrightness();
2147                         direct_brightness = (float)client.getEnv().getClientMap()
2148                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2149                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2150                                         / 255.0;
2151                 }
2152                 
2153                 time_of_day = client.getEnv().getTimeOfDayF();
2154                 float maxsm = 0.05;
2155                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2156                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2157                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2158                         time_of_day_smooth = time_of_day;
2159                 float todsm = 0.05;
2160                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2161                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2162                                         + (time_of_day+1.0) * todsm;
2163                 else
2164                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2165                                         + time_of_day * todsm;
2166                         
2167                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2168                                 sunlight_seen);
2169                 
2170                 float brightness = sky->getBrightness();
2171                 video::SColor bgcolor = sky->getBgColor();
2172                 video::SColor skycolor = sky->getSkyColor();
2173
2174                 /*
2175                         Update clouds
2176                 */
2177                 if(clouds){
2178                         if(sky->getCloudsVisible()){
2179                                 clouds->setVisible(true);
2180                                 clouds->step(dtime);
2181                                 clouds->update(v2f(player_position.X, player_position.Z),
2182                                                 sky->getCloudColor());
2183                         } else{
2184                                 clouds->setVisible(false);
2185                         }
2186                 }
2187                 
2188                 /*
2189                         Update farmesh
2190                 */
2191                 if(farmesh)
2192                 {
2193                         farmesh_range = draw_control.wanted_range * 10;
2194                         if(draw_control.range_all && farmesh_range < 500)
2195                                 farmesh_range = 500;
2196                         if(farmesh_range > 1000)
2197                                 farmesh_range = 1000;
2198
2199                         farmesh->step(dtime);
2200                         farmesh->update(v2f(player_position.X, player_position.Z),
2201                                         brightness, farmesh_range);
2202                 }
2203                 
2204                 /*
2205                         Fog
2206                 */
2207                 
2208                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2209                 {
2210                         driver->setFog(
2211                                 bgcolor,
2212                                 video::EFT_FOG_LINEAR,
2213                                 fog_range*0.4,
2214                                 fog_range*1.0,
2215                                 0.01,
2216                                 false, // pixel fog
2217                                 false // range fog
2218                         );
2219                 }
2220                 else
2221                 {
2222                         driver->setFog(
2223                                 bgcolor,
2224                                 video::EFT_FOG_LINEAR,
2225                                 100000*BS,
2226                                 110000*BS,
2227                                 0.01,
2228                                 false, // pixel fog
2229                                 false // range fog
2230                         );
2231                 }
2232
2233                 /*
2234                         Update gui stuff (0ms)
2235                 */
2236
2237                 //TimeTaker guiupdatetimer("Gui updating");
2238                 
2239                 const char program_name_and_version[] =
2240                         "Minetest-c55 " VERSION_STRING;
2241
2242                 if(show_debug)
2243                 {
2244                         static float drawtime_avg = 0;
2245                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2246                         /*static float beginscenetime_avg = 0;
2247                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2248                         static float scenetime_avg = 0;
2249                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2250                         static float endscenetime_avg = 0;
2251                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2252                         
2253                         char temptext[300];
2254                         snprintf(temptext, 300, "%s ("
2255                                         "R: range_all=%i"
2256                                         ")"
2257                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2258                                         ", v_range = %.1f, RTT = %.3f",
2259                                         program_name_and_version,
2260                                         draw_control.range_all,
2261                                         drawtime_avg,
2262                                         dtime_jitter1_max_fraction * 100.0,
2263                                         draw_control.wanted_range,
2264                                         client.getRTT()
2265                                         );
2266                         
2267                         guitext->setText(narrow_to_wide(temptext).c_str());
2268                         guitext->setVisible(true);
2269                 }
2270                 else if(show_hud || show_chat)
2271                 {
2272                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2273                         guitext->setVisible(true);
2274                 }
2275                 else
2276                 {
2277                         guitext->setVisible(false);
2278                 }
2279                 
2280                 if(show_debug)
2281                 {
2282                         char temptext[300];
2283                         snprintf(temptext, 300,
2284                                         "(% .1f, % .1f, % .1f)"
2285                                         " (yaw = %.1f)",
2286                                         player_position.X/BS,
2287                                         player_position.Y/BS,
2288                                         player_position.Z/BS,
2289                                         wrapDegrees_0_360(camera_yaw));
2290
2291                         guitext2->setText(narrow_to_wide(temptext).c_str());
2292                         guitext2->setVisible(true);
2293                 }
2294                 else
2295                 {
2296                         guitext2->setVisible(false);
2297                 }
2298                 
2299                 {
2300                         guitext_info->setText(infotext.c_str());
2301                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2302                 }
2303
2304                 {
2305                         float statustext_time_max = 3.0;
2306                         if(!statustext.empty())
2307                         {
2308                                 statustext_time += dtime;
2309                                 if(statustext_time >= statustext_time_max)
2310                                 {
2311                                         statustext = L"";
2312                                         statustext_time = 0;
2313                                 }
2314                         }
2315                         guitext_status->setText(statustext.c_str());
2316                         guitext_status->setVisible(!statustext.empty());
2317
2318                         if(!statustext.empty())
2319                         {
2320                                 s32 status_y = screensize.Y - 130;
2321                                 core::rect<s32> rect(
2322                                                 10,
2323                                                 status_y - guitext_status->getTextHeight(),
2324                                                 screensize.X - 10,
2325                                                 status_y
2326                                 );
2327                                 guitext_status->setRelativePosition(rect);
2328
2329                                 // Fade out
2330                                 video::SColor initial_color(255,0,0,0);
2331                                 if(guienv->getSkin())
2332                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2333                                 video::SColor final_color = initial_color;
2334                                 final_color.setAlpha(0);
2335                                 video::SColor fade_color =
2336                                         initial_color.getInterpolated_quadratic(
2337                                                 initial_color,
2338                                                 final_color,
2339                                                 statustext_time / (float) statustext_time_max);
2340                                 guitext_status->setOverrideColor(fade_color);
2341                                 guitext_status->enableOverrideColor(true);
2342                         }
2343                 }
2344                 
2345                 /*
2346                         Get chat messages from client
2347                 */
2348                 {
2349                         // Get new messages from error log buffer
2350                         while(!chat_log_error_buf.empty())
2351                         {
2352                                 chat_backend.addMessage(L"", narrow_to_wide(
2353                                                 chat_log_error_buf.get()));
2354                         }
2355                         // Get new messages from client
2356                         std::wstring message;
2357                         while(client.getChatMessage(message))
2358                         {
2359                                 chat_backend.addUnparsedMessage(message);
2360                         }
2361                         // Remove old messages
2362                         chat_backend.step(dtime);
2363
2364                         // Display all messages in a static text element
2365                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2366                         std::wstring recent_chat = chat_backend.getRecentChat();
2367                         guitext_chat->setText(recent_chat.c_str());
2368
2369                         // Update gui element size and position
2370                         s32 chat_y = 5+(text_height+5);
2371                         if(show_debug)
2372                                 chat_y += (text_height+5);
2373                         core::rect<s32> rect(
2374                                 10,
2375                                 chat_y,
2376                                 screensize.X - 10,
2377                                 chat_y + guitext_chat->getTextHeight()
2378                         );
2379                         guitext_chat->setRelativePosition(rect);
2380
2381                         // Don't show chat if disabled or empty or profiler is enabled
2382                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
2383                                         && !show_profiler);
2384                 }
2385
2386                 /*
2387                         Inventory
2388                 */
2389                 
2390                 if(client.getPlayerItem() != new_playeritem)
2391                 {
2392                         client.selectPlayerItem(new_playeritem);
2393                 }
2394                 if(client.getLocalInventoryUpdated())
2395                 {
2396                         //infostream<<"Updating local inventory"<<std::endl;
2397                         client.getLocalInventory(local_inventory);
2398                         
2399                         update_wielded_item_trigger = true;
2400                 }
2401                 if(update_wielded_item_trigger)
2402                 {
2403                         update_wielded_item_trigger = false;
2404                         // Update wielded tool
2405                         InventoryList *mlist = local_inventory.getList("main");
2406                         ItemStack item;
2407                         if(mlist != NULL)
2408                                 item = mlist->getItem(client.getPlayerItem());
2409                         camera.wield(item, gamedef);
2410                 }
2411                 
2412                 /*
2413                         Drawing begins
2414                 */
2415
2416                 TimeTaker drawtimer("Drawing");
2417
2418                 
2419                 {
2420                         TimeTaker timer("beginScene");
2421                         //driver->beginScene(false, true, bgcolor);
2422                         //driver->beginScene(true, true, bgcolor);
2423                         driver->beginScene(true, true, skycolor);
2424                         beginscenetime = timer.stop(true);
2425                 }
2426                 
2427                 //timer3.stop();
2428         
2429                 //infostream<<"smgr->drawAll()"<<std::endl;
2430                 {
2431                         TimeTaker timer("smgr");
2432                         smgr->drawAll();
2433                         scenetime = timer.stop(true);
2434                 }
2435                 
2436                 {
2437                 //TimeTaker timer9("auxiliary drawings");
2438                 // 0ms
2439                 
2440                 //timer9.stop();
2441                 //TimeTaker //timer10("//timer10");
2442                 
2443                 video::SMaterial m;
2444                 //m.Thickness = 10;
2445                 m.Thickness = 3;
2446                 m.Lighting = false;
2447                 driver->setMaterial(m);
2448
2449                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2450
2451                 if(show_hud)
2452                 {
2453                         for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2454                                         i != hilightboxes.end(); i++)
2455                         {
2456                                 /*infostream<<"hilightbox min="
2457                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2458                                                 <<" max="
2459                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2460                                                 <<std::endl;*/
2461                                 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2462                         }
2463                 }
2464
2465                 /*
2466                         Wielded tool
2467                 */
2468                 if(show_hud)
2469                 {
2470                         // Warning: This clears the Z buffer.
2471                         camera.drawWieldedTool();
2472                 }
2473
2474                 /*
2475                         Post effects
2476                 */
2477                 {
2478                         client.getEnv().getClientMap().renderPostFx();
2479                 }
2480
2481                 /*
2482                         Frametime log
2483                 */
2484                 if(show_debug_frametime)
2485                 {
2486                         s32 x = 10;
2487                         s32 y = screensize.Y - 10;
2488                         for(core::list<float>::Iterator
2489                                         i = frametime_log.begin();
2490                                         i != frametime_log.end();
2491                                         i++)
2492                         {
2493                                 driver->draw2DLine(v2s32(x,y),
2494                                                 v2s32(x,y-(*i)*1000),
2495                                                 video::SColor(255,255,255,255));
2496                                 x++;
2497                         }
2498                 }
2499
2500                 /*
2501                         Draw crosshair
2502                 */
2503                 if(show_hud)
2504                 {
2505                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2506                                         displaycenter + core::vector2d<s32>(10,0),
2507                                         video::SColor(255,255,255,255));
2508                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2509                                         displaycenter + core::vector2d<s32>(0,10),
2510                                         video::SColor(255,255,255,255));
2511                 }
2512
2513                 } // timer
2514
2515                 //timer10.stop();
2516                 //TimeTaker //timer11("//timer11");
2517
2518                 /*
2519                         Draw gui
2520                 */
2521                 // 0-1ms
2522                 guienv->drawAll();
2523
2524                 /*
2525                         Draw hotbar
2526                 */
2527                 if(show_hud)
2528                 {
2529                         draw_hotbar(driver, font, gamedef,
2530                                         v2s32(displaycenter.X, screensize.Y),
2531                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2532                                         client.getHP(), client.getPlayerItem());
2533                 }
2534
2535                 /*
2536                         Damage flash
2537                 */
2538                 if(damage_flash_timer > 0.0)
2539                 {
2540                         damage_flash_timer -= dtime;
2541                         
2542                         video::SColor color(128,255,0,0);
2543                         driver->draw2DRectangle(color,
2544                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2545                                         NULL);
2546                 }
2547
2548                 // Clear Z buffer
2549                 driver->clearZBuffer();
2550                 // Draw some sky things
2551                 //draw_horizon(driver, camera.getCameraNode());
2552                 
2553                 /*
2554                         End scene
2555                 */
2556                 {
2557                         TimeTaker timer("endScene");
2558                         endSceneX(driver);
2559                         endscenetime = timer.stop(true);
2560                 }
2561
2562                 drawtime = drawtimer.stop(true);
2563
2564                 /*
2565                         End of drawing
2566                 */
2567
2568                 static s16 lastFPS = 0;
2569                 //u16 fps = driver->getFPS();
2570                 u16 fps = (1.0/dtime_avg1);
2571
2572                 if (lastFPS != fps)
2573                 {
2574                         core::stringw str = L"Minetest [";
2575                         str += driver->getName();
2576                         str += "] FPS=";
2577                         str += fps;
2578
2579                         device->setWindowCaption(str.c_str());
2580                         lastFPS = fps;
2581                 }
2582         }
2583
2584         /*
2585                 Drop stuff
2586         */
2587         if(clouds)
2588                 clouds->drop();
2589         if(gui_chat_console)
2590                 gui_chat_console->drop();
2591         
2592         /*
2593                 Draw a "shutting down" screen, which will be shown while the map
2594                 generator and other stuff quits
2595         */
2596         {
2597                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2598                 draw_load_screen(L"Shutting down stuff...", driver, font);
2599                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2600                 guienv->drawAll();
2601                 driver->endScene();
2602                 gui_shuttingdowntext->remove();*/
2603         }
2604
2605         chat_backend.addMessage(L"", L"# Disconnected.");
2606         chat_backend.addMessage(L"", L"");
2607
2608         // Client scope (client is destructed before destructing *def and tsrc)
2609         }while(0);
2610
2611         delete tsrc;
2612         delete nodedef;
2613         delete itemdef;
2614 }
2615
2616