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