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