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