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