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