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