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