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