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