f35b85cb6f7e7f4fd0645097468462bf21587806
[oweals/minetest.git] / src / game.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "game.h"
21 #include "common_irrlicht.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
26 #include <IGUIFont.h>
27 #include "client.h"
28 #include "server.h"
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiInventoryMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
34 #include "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                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1511                 {
1512                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1513                         s16 range_new = range + 10;
1514                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1515                         statustext = narrow_to_wide(
1516                                         "Minimum viewing range changed from "
1517                                         + itos(range) + " to " + itos(range_new));
1518                         statustext_time = 0;
1519                 }
1520                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1521                 {
1522                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1523                         s16 range_new = range - 10;
1524                         if(range_new >= 0)
1525                         {
1526                                 g_settings->set("viewing_range_nodes_min",
1527                                                 itos(range_new));
1528                                 statustext = narrow_to_wide(
1529                                                 "Minimum viewing range changed from "
1530                                                 + itos(range) + " to "
1531                                                 + itos(range_new));
1532                                 statustext_time = 0;
1533                         }
1534                         else
1535                         {
1536                                 statustext = L"Minimum viewing range already at minimum";
1537                                 statustext_time = 0;
1538                         }
1539                 }
1540
1541                 // Item selection with mouse wheel
1542                 u16 new_playeritem = client.getPlayerItem();
1543                 {
1544                         s32 wheel = input->getMouseWheel();
1545                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1546                                         hotbar_itemcount-1);
1547
1548                         if(wheel < 0)
1549                         {
1550                                 if(new_playeritem < max_item)
1551                                         new_playeritem++;
1552                                 else
1553                                         new_playeritem = 0;
1554                         }
1555                         else if(wheel > 0)
1556                         {
1557                                 if(new_playeritem > 0)
1558                                         new_playeritem--;
1559                                 else
1560                                         new_playeritem = max_item;
1561                         }
1562                 }
1563                 
1564                 // Item selection
1565                 for(u16 i=0; i<10; i++)
1566                 {
1567                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1568                         if(input->wasKeyDown(*kp))
1569                         {
1570                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1571                                 {
1572                                         new_playeritem = i;
1573
1574                                         infostream<<"Selected item: "
1575                                                         <<new_playeritem<<std::endl;
1576                                 }
1577                         }
1578                 }
1579
1580                 // Viewing range selection
1581                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1582                 {
1583                         draw_control.range_all = !draw_control.range_all;
1584                         if(draw_control.range_all)
1585                         {
1586                                 infostream<<"Enabled full viewing range"<<std::endl;
1587                                 statustext = L"Enabled full viewing range";
1588                                 statustext_time = 0;
1589                         }
1590                         else
1591                         {
1592                                 infostream<<"Disabled full viewing range"<<std::endl;
1593                                 statustext = L"Disabled full viewing range";
1594                                 statustext_time = 0;
1595                         }
1596                 }
1597
1598                 // Print debug stacks
1599                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1600                 {
1601                         dstream<<"-----------------------------------------"
1602                                         <<std::endl;
1603                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1604                         dstream<<"-----------------------------------------"
1605                                         <<std::endl;
1606                         debug_stacks_print();
1607                 }
1608
1609                 /*
1610                         Mouse and camera control
1611                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1612                 */
1613                 
1614                 if((device->isWindowActive() && noMenuActive()) || random_input)
1615                 {
1616                         if(!random_input)
1617                         {
1618                                 // Mac OSX gets upset if this is set every frame
1619                                 if(device->getCursorControl()->isVisible())
1620                                         device->getCursorControl()->setVisible(false);
1621                         }
1622
1623                         if(first_loop_after_window_activation){
1624                                 //infostream<<"window active, first loop"<<std::endl;
1625                                 first_loop_after_window_activation = false;
1626                         }
1627                         else{
1628                                 s32 dx = input->getMousePos().X - displaycenter.X;
1629                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1630                                 if(invert_mouse)
1631                                         dy = -dy;
1632                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1633                                 
1634                                 /*const float keyspeed = 500;
1635                                 if(input->isKeyDown(irr::KEY_UP))
1636                                         dy -= dtime * keyspeed;
1637                                 if(input->isKeyDown(irr::KEY_DOWN))
1638                                         dy += dtime * keyspeed;
1639                                 if(input->isKeyDown(irr::KEY_LEFT))
1640                                         dx -= dtime * keyspeed;
1641                                 if(input->isKeyDown(irr::KEY_RIGHT))
1642                                         dx += dtime * keyspeed;*/
1643
1644                                 camera_yaw -= dx*0.2;
1645                                 camera_pitch += dy*0.2;
1646                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1647                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1648                         }
1649                         input->setMousePos(displaycenter.X, displaycenter.Y);
1650                 }
1651                 else{
1652                         // Mac OSX gets upset if this is set every frame
1653                         if(device->getCursorControl()->isVisible() == false)
1654                                 device->getCursorControl()->setVisible(true);
1655
1656                         //infostream<<"window inactive"<<std::endl;
1657                         first_loop_after_window_activation = true;
1658                 }
1659
1660                 /*
1661                         Player speed control
1662                 */
1663                 
1664                 if(!noMenuActive() || !device->isWindowActive())
1665                 {
1666                         PlayerControl control(
1667                                 false,
1668                                 false,
1669                                 false,
1670                                 false,
1671                                 false,
1672                                 false,
1673                                 false,
1674                                 camera_pitch,
1675                                 camera_yaw
1676                         );
1677                         client.setPlayerControl(control);
1678                 }
1679                 else
1680                 {
1681                         /*bool a_up,
1682                         bool a_down,
1683                         bool a_left,
1684                         bool a_right,
1685                         bool a_jump,
1686                         bool a_superspeed,
1687                         bool a_sneak,
1688                         float a_pitch,
1689                         float a_yaw*/
1690                         PlayerControl control(
1691                                 input->isKeyDown(getKeySetting("keymap_forward")),
1692                                 input->isKeyDown(getKeySetting("keymap_backward")),
1693                                 input->isKeyDown(getKeySetting("keymap_left")),
1694                                 input->isKeyDown(getKeySetting("keymap_right")),
1695                                 input->isKeyDown(getKeySetting("keymap_jump")),
1696                                 input->isKeyDown(getKeySetting("keymap_special1")),
1697                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1698                                 camera_pitch,
1699                                 camera_yaw
1700                         );
1701                         client.setPlayerControl(control);
1702                 }
1703                 
1704                 /*
1705                         Run server
1706                 */
1707
1708                 if(server != NULL)
1709                 {
1710                         //TimeTaker timer("server->step(dtime)");
1711                         server->step(dtime);
1712                 }
1713
1714                 /*
1715                         Process environment
1716                 */
1717                 
1718                 {
1719                         //TimeTaker timer("client.step(dtime)");
1720                         client.step(dtime);
1721                         //client.step(dtime_avg1);
1722                 }
1723
1724                 {
1725                         // Read client events
1726                         for(;;)
1727                         {
1728                                 ClientEvent event = client.getClientEvent();
1729                                 if(event.type == CE_NONE)
1730                                 {
1731                                         break;
1732                                 }
1733                                 else if(event.type == CE_PLAYER_DAMAGE)
1734                                 {
1735                                         //u16 damage = event.player_damage.amount;
1736                                         //infostream<<"Player damage: "<<damage<<std::endl;
1737                                         damage_flash_timer = 0.05;
1738                                         if(event.player_damage.amount >= 2){
1739                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1740                                         }
1741                                 }
1742                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1743                                 {
1744                                         camera_yaw = event.player_force_move.yaw;
1745                                         camera_pitch = event.player_force_move.pitch;
1746                                 }
1747                                 else if(event.type == CE_DEATHSCREEN)
1748                                 {
1749                                         if(respawn_menu_active)
1750                                                 continue;
1751
1752                                         /*bool set_camera_point_target =
1753                                                         event.deathscreen.set_camera_point_target;
1754                                         v3f camera_point_target;
1755                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1756                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1757                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1758                                         MainRespawnInitiator *respawner =
1759                                                         new MainRespawnInitiator(
1760                                                                         &respawn_menu_active, &client);
1761                                         GUIDeathScreen *menu =
1762                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1763                                                                 &g_menumgr, respawner);
1764                                         menu->drop();
1765                                         
1766                                         /* Handle visualization */
1767
1768                                         damage_flash_timer = 0;
1769
1770                                         /*LocalPlayer* player = client.getLocalPlayer();
1771                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1772                                         camera.update(player, busytime, screensize);*/
1773                                 }
1774                                 else if(event.type == CE_TEXTURES_UPDATED)
1775                                 {
1776                                         update_skybox(driver, tsrc, smgr, skybox, brightness);
1777                                         
1778                                         update_wielded_item_trigger = true;
1779                                 }
1780                         }
1781                 }
1782                 
1783                 //TimeTaker //timer2("//timer2");
1784
1785                 LocalPlayer* player = client.getLocalPlayer();
1786                 camera.update(player, busytime, screensize);
1787                 camera.step(dtime);
1788
1789                 v3f player_position = player->getPosition();
1790                 v3f camera_position = camera.getPosition();
1791                 v3f camera_direction = camera.getDirection();
1792                 f32 camera_fov = camera.getFovMax();
1793                 
1794                 if(!disable_camera_update){
1795                         client.updateCamera(camera_position,
1796                                 camera_direction, camera_fov);
1797                 }
1798
1799                 //timer2.stop();
1800                 //TimeTaker //timer3("//timer3");
1801
1802                 /*
1803                         For interaction purposes, get info about the held item
1804                         - What item is it?
1805                         - Is it a usable item?
1806                         - Can it point to liquids?
1807                 */
1808                 ItemStack playeritem;
1809                 bool playeritem_usable = false;
1810                 bool playeritem_liquids_pointable = false;
1811                 {
1812                         InventoryList *mlist = local_inventory.getList("main");
1813                         if(mlist != NULL)
1814                         {
1815                                 playeritem = mlist->getItem(client.getPlayerItem());
1816                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1817                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1818                         }
1819                 }
1820
1821                 /*
1822                         Calculate what block is the crosshair pointing to
1823                 */
1824                 
1825                 //u32 t1 = device->getTimer()->getRealTime();
1826                 
1827                 f32 d = 4; // max. distance
1828                 core::line3d<f32> shootline(camera_position,
1829                                 camera_position + camera_direction * BS * (d+1));
1830
1831                 core::aabbox3d<f32> hilightbox;
1832                 bool should_show_hilightbox = false;
1833                 ClientActiveObject *selected_object = NULL;
1834
1835                 PointedThing pointed = getPointedThing(
1836                                 // input
1837                                 &client, player_position, camera_direction,
1838                                 camera_position, shootline, d,
1839                                 playeritem_liquids_pointable, !ldown_for_dig,
1840                                 // output
1841                                 hilightbox, should_show_hilightbox,
1842                                 selected_object);
1843
1844                 if(pointed != pointed_old)
1845                 {
1846                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1847                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1848                 }
1849
1850                 /*
1851                         Visualize selection
1852                 */
1853                 if(should_show_hilightbox)
1854                         hilightboxes.push_back(hilightbox);
1855
1856                 /*
1857                         Stop digging when
1858                         - releasing left mouse button
1859                         - pointing away from node
1860                 */
1861                 if(digging)
1862                 {
1863                         if(input->getLeftReleased())
1864                         {
1865                                 infostream<<"Left button released"
1866                                         <<" (stopped digging)"<<std::endl;
1867                                 digging = false;
1868                         }
1869                         else if(pointed != pointed_old)
1870                         {
1871                                 if (pointed.type == POINTEDTHING_NODE
1872                                         && pointed_old.type == POINTEDTHING_NODE
1873                                         && pointed.node_undersurface == pointed_old.node_undersurface)
1874                                 {
1875                                         // Still pointing to the same node,
1876                                         // but a different face. Don't reset.
1877                                 }
1878                                 else
1879                                 {
1880                                         infostream<<"Pointing away from node"
1881                                                 <<" (stopped digging)"<<std::endl;
1882                                         digging = false;
1883                                 }
1884                         }
1885                         if(!digging)
1886                         {
1887                                 client.interact(1, pointed_old);
1888                                 client.clearTempMod(pointed_old.node_undersurface);
1889                                 dig_time = 0.0;
1890                         }
1891                 }
1892                 if(!digging && ldown_for_dig && !input->getLeftState())
1893                 {
1894                         ldown_for_dig = false;
1895                 }
1896
1897                 bool left_punch = false;
1898                 bool left_punch_muted = false;
1899
1900                 if(playeritem_usable && input->getLeftState())
1901                 {
1902                         if(input->getLeftClicked())
1903                                 client.interact(4, pointed);
1904                 }
1905                 else if(pointed.type == POINTEDTHING_NODE)
1906                 {
1907                         v3s16 nodepos = pointed.node_undersurface;
1908                         v3s16 neighbourpos = pointed.node_abovesurface;
1909
1910                         /*
1911                                 Check information text of node
1912                         */
1913
1914                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1915                         if(meta)
1916                         {
1917                                 infotext = narrow_to_wide(meta->infoText());
1918                         }
1919                         else
1920                         {
1921                                 MapNode n = client.getNode(nodepos);
1922                                 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
1923                                         infotext = L"Unknown node: ";
1924                                         infotext += narrow_to_wide(nodedef->get(n).name);
1925                                 }
1926                         }
1927                         
1928                         /*
1929                                 Handle digging
1930                         */
1931                         
1932                         
1933                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
1934                         {
1935                                 if(!digging)
1936                                 {
1937                                         infostream<<"Started digging"<<std::endl;
1938                                         client.interact(0, pointed);
1939                                         digging = true;
1940                                         ldown_for_dig = true;
1941                                 }
1942                                 MapNode n = client.getNode(nodepos);
1943
1944                                 // Get digging properties for material and tool
1945                                 MaterialProperties mp = nodedef->get(n.getContent()).material;
1946                                 ToolDiggingProperties tp =
1947                                                 playeritem.getToolDiggingProperties(itemdef);
1948                                 DiggingProperties prop = getDiggingProperties(&mp, &tp);
1949
1950                                 float dig_time_complete = 0.0;
1951
1952                                 if(prop.diggable == false)
1953                                 {
1954                                         // I guess nobody will wait for this long
1955                                         dig_time_complete = 10000000.0;
1956                                 }
1957                                 else
1958                                 {
1959                                         dig_time_complete = prop.time;
1960                                 }
1961
1962                                 if(dig_time_complete >= 0.001)
1963                                 {
1964                                         dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1965                                                         * dig_time/dig_time_complete);
1966                                 }
1967                                 // This is for torches
1968                                 else
1969                                 {
1970                                         dig_index = CRACK_ANIMATION_LENGTH;
1971                                 }
1972
1973                                 if(dig_index < CRACK_ANIMATION_LENGTH)
1974                                 {
1975                                         //TimeTaker timer("client.setTempMod");
1976                                         //infostream<<"dig_index="<<dig_index<<std::endl;
1977                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1978                                 }
1979                                 else
1980                                 {
1981                                         infostream<<"Digging completed"<<std::endl;
1982                                         client.interact(2, pointed);
1983                                         client.clearTempMod(nodepos);
1984                                         client.removeNode(nodepos);
1985
1986                                         dig_time = 0;
1987                                         digging = false;
1988
1989                                         nodig_delay_timer = dig_time_complete
1990                                                         / (float)CRACK_ANIMATION_LENGTH;
1991
1992                                         // We don't want a corresponding delay to
1993                                         // very time consuming nodes
1994                                         if(nodig_delay_timer > 0.5)
1995                                         {
1996                                                 nodig_delay_timer = 0.5;
1997                                         }
1998                                         // We want a slight delay to very little
1999                                         // time consuming nodes
2000                                         float mindelay = 0.15;
2001                                         if(nodig_delay_timer < mindelay)
2002                                         {
2003                                                 nodig_delay_timer = mindelay;
2004                                         }
2005                                 }
2006
2007                                 dig_time += dtime;
2008
2009                                 camera.setDigging(0);  // left click animation
2010                         }
2011
2012                         if(input->getRightClicked())
2013                         {
2014                                 infostream<<"Ground right-clicked"<<std::endl;
2015                                 
2016                                 // If metadata provides an inventory view, activate it
2017                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2018                                 {
2019                                         infostream<<"Launching custom inventory view"<<std::endl;
2020
2021                                         InventoryLocation inventoryloc;
2022                                         inventoryloc.setNodeMeta(nodepos);
2023                                         
2024
2025                                         /*
2026                                                 Create menu
2027                                         */
2028
2029                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2030                                         v2s16 invsize =
2031                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
2032                                                         draw_spec,
2033                                                         meta->getInventoryDrawSpecString(),
2034                                                         inventoryloc);
2035
2036                                         GUIInventoryMenu *menu =
2037                                                 new GUIInventoryMenu(guienv, guiroot, -1,
2038                                                         &g_menumgr, invsize,
2039                                                         &client, gamedef);
2040                                         menu->setDrawSpec(draw_spec);
2041                                         menu->drop();
2042                                 }
2043                                 // If metadata provides text input, activate text input
2044                                 else if(meta && meta->allowsTextInput() && !random_input)
2045                                 {
2046                                         infostream<<"Launching metadata text input"<<std::endl;
2047                                         
2048                                         // Get a new text for it
2049
2050                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2051
2052                                         std::wstring wtext = narrow_to_wide(meta->getText());
2053
2054                                         (new GUITextInputMenu(guienv, guiroot, -1,
2055                                                         &g_menumgr, dest,
2056                                                         wtext))->drop();
2057                                 }
2058                                 // Otherwise report right click to server
2059                                 else
2060                                 {
2061                                         client.interact(3, pointed);
2062                                         camera.setDigging(1);  // right click animation
2063                                 }
2064                         }
2065                 }
2066                 else if(pointed.type == POINTEDTHING_OBJECT)
2067                 {
2068                         infotext = narrow_to_wide(selected_object->infoText());
2069
2070                         //if(input->getLeftClicked())
2071                         if(input->getLeftState())
2072                         {
2073                                 bool do_punch = false;
2074                                 bool do_punch_damage = false;
2075                                 if(object_hit_delay_timer <= 0.0){
2076                                         do_punch = true;
2077                                         do_punch_damage = true;
2078                                         object_hit_delay_timer = object_hit_delay;
2079                                 }
2080                                 if(input->getLeftClicked()){
2081                                         do_punch = true;
2082                                 }
2083                                 if(do_punch){
2084                                         infostream<<"Left-clicked object"<<std::endl;
2085                                         left_punch = true;
2086                                 }
2087                                 if(do_punch_damage){
2088                                         // Report direct punch
2089                                         v3f objpos = selected_object->getPosition();
2090                                         v3f dir = (objpos - player_position).normalize();
2091
2092                                         bool disable_send = selected_object->directReportPunch(playeritem.name, dir);
2093                                         if(!disable_send)
2094                                                 client.interact(0, pointed);
2095                                 }
2096                         }
2097                         else if(input->getRightClicked())
2098                         {
2099                                 infostream<<"Right-clicked object"<<std::endl;
2100                                 client.interact(3, pointed);  // place
2101                         }
2102                 }
2103
2104                 pointed_old = pointed;
2105                 
2106                 if(left_punch || (input->getLeftClicked() && !left_punch_muted))
2107                 {
2108                         camera.setDigging(0); // left click animation
2109                 }
2110
2111                 input->resetLeftClicked();
2112                 input->resetRightClicked();
2113
2114                 input->resetLeftReleased();
2115                 input->resetRightReleased();
2116                 
2117                 /*
2118                         Calculate stuff for drawing
2119                 */
2120                 
2121                 /*
2122                         Calculate general brightness
2123                 */
2124                 u32 daynight_ratio = client.getDayNightRatio();
2125                 u8 light8 = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
2126                 brightness = (float)light8/255.0;
2127                 video::SColor bgcolor = video::SColor(
2128                                 255,
2129                                 bgcolor_bright.getRed() * brightness,
2130                                 bgcolor_bright.getGreen() * brightness,
2131                                 bgcolor_bright.getBlue() * brightness);
2132                                 /*skycolor.getRed() * brightness,
2133                                 skycolor.getGreen() * brightness,
2134                                 skycolor.getBlue() * brightness);*/
2135
2136                 /*
2137                         Update skybox
2138                 */
2139                 if(fabs(brightness - old_brightness) > 0.01)
2140                         update_skybox(driver, tsrc, smgr, skybox, brightness);
2141
2142                 /*
2143                         Update clouds
2144                 */
2145                 if(clouds)
2146                 {
2147                         clouds->step(dtime);
2148                         clouds->update(v2f(player_position.X, player_position.Z),
2149                                         0.05+brightness*0.95);
2150                 }
2151                 
2152                 /*
2153                         Update farmesh
2154                 */
2155                 if(farmesh)
2156                 {
2157                         farmesh_range = draw_control.wanted_range * 10;
2158                         if(draw_control.range_all && farmesh_range < 500)
2159                                 farmesh_range = 500;
2160                         if(farmesh_range > 1000)
2161                                 farmesh_range = 1000;
2162
2163                         farmesh->step(dtime);
2164                         farmesh->update(v2f(player_position.X, player_position.Z),
2165                                         0.05+brightness*0.95, farmesh_range);
2166                 }
2167                 
2168                 // Store brightness value
2169                 old_brightness = brightness;
2170
2171                 /*
2172                         Fog
2173                 */
2174                 
2175                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2176                 {
2177                         f32 range;
2178                         if(farmesh)
2179                         {
2180                                 range = BS*farmesh_range;
2181                         }
2182                         else
2183                         {
2184                                 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
2185                                 range *= 0.9;
2186                                 if(draw_control.range_all)
2187                                         range = 100000*BS;
2188                                 /*if(range < 50*BS)
2189                                         range = range * 0.5 + 25*BS;*/
2190                         }
2191
2192                         driver->setFog(
2193                                 bgcolor,
2194                                 video::EFT_FOG_LINEAR,
2195                                 range*0.4,
2196                                 range*1.0,
2197                                 0.01,
2198                                 false, // pixel fog
2199                                 false // range fog
2200                         );
2201                 }
2202                 else
2203                 {
2204                         driver->setFog(
2205                                 bgcolor,
2206                                 video::EFT_FOG_LINEAR,
2207                                 100000*BS,
2208                                 110000*BS,
2209                                 0.01,
2210                                 false, // pixel fog
2211                                 false // range fog
2212                         );
2213                 }
2214
2215                 /*
2216                         Update gui stuff (0ms)
2217                 */
2218
2219                 //TimeTaker guiupdatetimer("Gui updating");
2220                 
2221                 const char program_name_and_version[] =
2222                         "Minetest-c55 " VERSION_STRING;
2223
2224                 if(show_debug)
2225                 {
2226                         static float drawtime_avg = 0;
2227                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2228                         /*static float beginscenetime_avg = 0;
2229                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2230                         static float scenetime_avg = 0;
2231                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2232                         static float endscenetime_avg = 0;
2233                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2234                         
2235                         char temptext[300];
2236                         snprintf(temptext, 300, "%s ("
2237                                         "R: range_all=%i"
2238                                         ")"
2239                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2240                                         ", v_range = %.1f, RTT = %.3f",
2241                                         program_name_and_version,
2242                                         draw_control.range_all,
2243                                         drawtime_avg,
2244                                         dtime_jitter1_max_fraction * 100.0,
2245                                         draw_control.wanted_range,
2246                                         client.getRTT()
2247                                         );
2248                         
2249                         guitext->setText(narrow_to_wide(temptext).c_str());
2250                         guitext->setVisible(true);
2251                 }
2252                 else if(show_hud || show_chat)
2253                 {
2254                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2255                         guitext->setVisible(true);
2256                 }
2257                 else
2258                 {
2259                         guitext->setVisible(false);
2260                 }
2261                 
2262                 if(show_debug)
2263                 {
2264                         char temptext[300];
2265                         snprintf(temptext, 300,
2266                                         "(% .1f, % .1f, % .1f)"
2267                                         " (yaw = %.1f)",
2268                                         player_position.X/BS,
2269                                         player_position.Y/BS,
2270                                         player_position.Z/BS,
2271                                         wrapDegrees_0_360(camera_yaw));
2272
2273                         guitext2->setText(narrow_to_wide(temptext).c_str());
2274                         guitext2->setVisible(true);
2275                 }
2276                 else
2277                 {
2278                         guitext2->setVisible(false);
2279                 }
2280                 
2281                 {
2282                         guitext_info->setText(infotext.c_str());
2283                         guitext_info->setVisible(show_hud);
2284                 }
2285
2286                 {
2287                         float statustext_time_max = 3.0;
2288                         if(!statustext.empty())
2289                         {
2290                                 statustext_time += dtime;
2291                                 if(statustext_time >= statustext_time_max)
2292                                 {
2293                                         statustext = L"";
2294                                         statustext_time = 0;
2295                                 }
2296                         }
2297                         guitext_status->setText(statustext.c_str());
2298                         guitext_status->setVisible(!statustext.empty());
2299
2300                         if(!statustext.empty())
2301                         {
2302                                 s32 status_y = screensize.Y - 130;
2303                                 core::rect<s32> rect(
2304                                                 10,
2305                                                 status_y - guitext_status->getTextHeight(),
2306                                                 screensize.X - 10,
2307                                                 status_y
2308                                 );
2309                                 guitext_status->setRelativePosition(rect);
2310
2311                                 // Fade out
2312                                 video::SColor initial_color(255,0,0,0);
2313                                 if(guienv->getSkin())
2314                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2315                                 video::SColor final_color = initial_color;
2316                                 final_color.setAlpha(0);
2317                                 video::SColor fade_color =
2318                                         initial_color.getInterpolated_quadratic(
2319                                                 initial_color,
2320                                                 final_color,
2321                                                 statustext_time / (float) statustext_time_max);
2322                                 guitext_status->setOverrideColor(fade_color);
2323                                 guitext_status->enableOverrideColor(true);
2324                         }
2325                 }
2326                 
2327                 /*
2328                         Get chat messages from client
2329                 */
2330                 {
2331                         // Get new messages from error log buffer
2332                         while(!chat_log_error_buf.empty())
2333                         {
2334                                 chat_lines.push_back(ChatLine(narrow_to_wide(
2335                                                 chat_log_error_buf.get())));
2336                         }
2337                         // Get new messages from client
2338                         std::wstring message;
2339                         while(client.getChatMessage(message))
2340                         {
2341                                 chat_lines.push_back(ChatLine(message));
2342                                 /*if(chat_lines.size() > 6)
2343                                 {
2344                                         core::list<ChatLine>::Iterator
2345                                                         i = chat_lines.begin();
2346                                         chat_lines.erase(i);
2347                                 }*/
2348                         }
2349                         // Append them to form the whole static text and throw
2350                         // it to the gui element
2351                         std::wstring whole;
2352                         // This will correspond to the line number counted from
2353                         // top to bottom, from size-1 to 0
2354                         s16 line_number = chat_lines.size();
2355                         // Count of messages to be removed from the top
2356                         u16 to_be_removed_count = 0;
2357                         for(core::list<ChatLine>::Iterator
2358                                         i = chat_lines.begin();
2359                                         i != chat_lines.end(); i++)
2360                         {
2361                                 // After this, line number is valid for this loop
2362                                 line_number--;
2363                                 // Increment age
2364                                 (*i).age += dtime;
2365                                 /*
2366                                         This results in a maximum age of 60*6 to the
2367                                         lowermost line and a maximum of 6 lines
2368                                 */
2369                                 float allowed_age = (6-line_number) * 60.0;
2370
2371                                 if((*i).age > allowed_age)
2372                                 {
2373                                         to_be_removed_count++;
2374                                         continue;
2375                                 }
2376                                 whole += (*i).text + L'\n';
2377                         }
2378                         for(u16 i=0; i<to_be_removed_count; i++)
2379                         {
2380                                 core::list<ChatLine>::Iterator
2381                                                 it = chat_lines.begin();
2382                                 chat_lines.erase(it);
2383                         }
2384                         guitext_chat->setText(whole.c_str());
2385
2386                         // Update gui element size and position
2387
2388                         /*core::rect<s32> rect(
2389                                         10,
2390                                         screensize.Y - guitext_chat_pad_bottom
2391                                                         - text_height*chat_lines.size(),
2392                                         screensize.X - 10,
2393                                         screensize.Y - guitext_chat_pad_bottom
2394                         );*/
2395
2396                         s32 chat_y = 5+(text_height+5);
2397                         if(show_debug)
2398                                 chat_y += (text_height+5);
2399                         core::rect<s32> rect(
2400                                         10,
2401                                         chat_y,
2402                                         screensize.X - 10,
2403                                         chat_y + guitext_chat->getTextHeight()
2404                         );
2405
2406                         guitext_chat->setRelativePosition(rect);
2407
2408                         // Don't show chat if empty or profiler or debug is enabled
2409                         guitext_chat->setVisible(chat_lines.size() != 0
2410                                         && show_chat && show_profiler == 0);
2411                 }
2412
2413                 /*
2414                         Inventory
2415                 */
2416                 
2417                 if(client.getPlayerItem() != new_playeritem)
2418                 {
2419                         client.selectPlayerItem(new_playeritem);
2420                 }
2421                 if(client.getLocalInventoryUpdated())
2422                 {
2423                         //infostream<<"Updating local inventory"<<std::endl;
2424                         client.getLocalInventory(local_inventory);
2425                         
2426                         update_wielded_item_trigger = true;
2427                 }
2428                 if(update_wielded_item_trigger)
2429                 {
2430                         update_wielded_item_trigger = false;
2431                         // Update wielded tool
2432                         InventoryList *mlist = local_inventory.getList("main");
2433                         ItemStack item;
2434                         if(mlist != NULL)
2435                                 item = mlist->getItem(client.getPlayerItem());
2436                         camera.wield(item, gamedef);
2437                 }
2438                 
2439                 /*
2440                         Drawing begins
2441                 */
2442
2443                 TimeTaker drawtimer("Drawing");
2444
2445                 
2446                 {
2447                         TimeTaker timer("beginScene");
2448                         driver->beginScene(false, true, bgcolor);
2449                         //driver->beginScene(false, true, bgcolor);
2450                         beginscenetime = timer.stop(true);
2451                 }
2452                 
2453                 //timer3.stop();
2454                 
2455                 //infostream<<"smgr->drawAll()"<<std::endl;
2456                 
2457                 {
2458                         TimeTaker timer("smgr");
2459                         smgr->drawAll();
2460                         scenetime = timer.stop(true);
2461                 }
2462                 
2463                 {
2464                 //TimeTaker timer9("auxiliary drawings");
2465                 // 0ms
2466                 
2467                 //timer9.stop();
2468                 //TimeTaker //timer10("//timer10");
2469                 
2470                 video::SMaterial m;
2471                 //m.Thickness = 10;
2472                 m.Thickness = 3;
2473                 m.Lighting = false;
2474                 driver->setMaterial(m);
2475
2476                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2477
2478                 if(show_hud)
2479                 {
2480                         for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2481                                         i != hilightboxes.end(); i++)
2482                         {
2483                                 /*infostream<<"hilightbox min="
2484                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2485                                                 <<" max="
2486                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2487                                                 <<std::endl;*/
2488                                 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2489                         }
2490                 }
2491
2492                 /*
2493                         Wielded tool
2494                 */
2495                 if(show_hud)
2496                 {
2497                         // Warning: This clears the Z buffer.
2498                         camera.drawWieldedTool();
2499                 }
2500
2501                 /*
2502                         Post effects
2503                 */
2504                 {
2505                         client.renderPostFx();
2506                 }
2507
2508                 /*
2509                         Frametime log
2510                 */
2511                 if(show_debug_frametime)
2512                 {
2513                         s32 x = 10;
2514                         s32 y = screensize.Y - 10;
2515                         for(core::list<float>::Iterator
2516                                         i = frametime_log.begin();
2517                                         i != frametime_log.end();
2518                                         i++)
2519                         {
2520                                 driver->draw2DLine(v2s32(x,y),
2521                                                 v2s32(x,y-(*i)*1000),
2522                                                 video::SColor(255,255,255,255));
2523                                 x++;
2524                         }
2525                 }
2526
2527                 /*
2528                         Draw crosshair
2529                 */
2530                 if(show_hud)
2531                 {
2532                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2533                                         displaycenter + core::vector2d<s32>(10,0),
2534                                         video::SColor(255,255,255,255));
2535                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2536                                         displaycenter + core::vector2d<s32>(0,10),
2537                                         video::SColor(255,255,255,255));
2538                 }
2539
2540                 } // timer
2541
2542                 //timer10.stop();
2543                 //TimeTaker //timer11("//timer11");
2544
2545                 /*
2546                         Draw gui
2547                 */
2548                 // 0-1ms
2549                 guienv->drawAll();
2550
2551                 /*
2552                         Draw hotbar
2553                 */
2554                 if(show_hud)
2555                 {
2556                         draw_hotbar(driver, font, gamedef,
2557                                         v2s32(displaycenter.X, screensize.Y),
2558                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2559                                         client.getHP(), client.getPlayerItem());
2560                 }
2561
2562                 /*
2563                         Damage flash
2564                 */
2565                 if(damage_flash_timer > 0.0)
2566                 {
2567                         damage_flash_timer -= dtime;
2568                         
2569                         video::SColor color(128,255,0,0);
2570                         driver->draw2DRectangle(color,
2571                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2572                                         NULL);
2573                 }
2574
2575                 /*
2576                         End scene
2577                 */
2578                 {
2579                         TimeTaker timer("endScene");
2580                         endSceneX(driver);
2581                         endscenetime = timer.stop(true);
2582                 }
2583
2584                 drawtime = drawtimer.stop(true);
2585
2586                 /*
2587                         End of drawing
2588                 */
2589
2590                 static s16 lastFPS = 0;
2591                 //u16 fps = driver->getFPS();
2592                 u16 fps = (1.0/dtime_avg1);
2593
2594                 if (lastFPS != fps)
2595                 {
2596                         core::stringw str = L"Minetest [";
2597                         str += driver->getName();
2598                         str += "] FPS=";
2599                         str += fps;
2600
2601                         device->setWindowCaption(str.c_str());
2602                         lastFPS = fps;
2603                 }
2604         }
2605
2606         /*
2607                 Drop stuff
2608         */
2609         if(clouds)
2610                 clouds->drop();
2611         
2612         /*
2613                 Draw a "shutting down" screen, which will be shown while the map
2614                 generator and other stuff quits
2615         */
2616         {
2617                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2618                 draw_load_screen(L"Shutting down stuff...", driver, font);
2619                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2620                 guienv->drawAll();
2621                 driver->endScene();
2622                 gui_shuttingdowntext->remove();*/
2623         }
2624
2625         } // Client scope (must be destructed before destructing *def and tsrc
2626
2627         delete tsrc;
2628         delete nodedef;
2629         delete itemdef;
2630 }
2631
2632