]> git.lizzy.rs Git - dragonfireclient.git/blob - src/game.cpp
Remove #include <content_mapnode.h> from game.cpp
[dragonfireclient.git] / src / game.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "game.h"
21 #include "common_irrlicht.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
26 #include <IGUIFont.h>
27 #include "client.h"
28 #include "server.h"
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiInventoryMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
34 #include "materials.h"
35 #include "config.h"
36 #include "clouds.h"
37 #include "camera.h"
38 #include "farmesh.h"
39 #include "mapblock.h"
40 #include "settings.h"
41 #include "profiler.h"
42 #include "mainmenumanager.h"
43 #include "gettext.h"
44 #include "log.h"
45 #include "filesys.h"
46 // Needed for determining pointing to nodes
47 #include "nodedef.h"
48 #include "nodemetadata.h"
49 #include "main.h" // For g_settings
50 #include "tooldef.h"
51 #include "tile.h" // For TextureSource
52
53 /*
54         Setting this to 1 enables a special camera mode that forces
55         the renderers to think that the camera statically points from
56         the starting place to a static direction.
57
58         This allows one to move around with the player and see what
59         is actually drawn behind solid things and behind the player.
60 */
61 #define FIELD_OF_VIEW_TEST 0
62
63
64 // Chat data
65 struct ChatLine
66 {
67         ChatLine():
68                 age(0.0)
69         {
70         }
71         ChatLine(const std::wstring &a_text):
72                 age(0.0),
73                 text(a_text)
74         {
75         }
76         float age;
77         std::wstring text;
78 };
79
80 /*
81         Inventory stuff
82 */
83
84 // Inventory actions from the menu are buffered here before sending
85 Queue<InventoryAction*> inventory_action_queue;
86 // This is a copy of the inventory that the client's environment has
87 Inventory local_inventory;
88
89 u16 g_selected_item = 0;
90
91 /*
92         Text input system
93 */
94
95 struct TextDestChat : public TextDest
96 {
97         TextDestChat(Client *client)
98         {
99                 m_client = client;
100         }
101         void gotText(std::wstring text)
102         {
103                 // Discard empty line
104                 if(text == L"")
105                         return;
106
107                 // Send to others
108                 m_client->sendChatMessage(text);
109                 // Show locally
110                 m_client->addChatMessage(text);
111         }
112
113         Client *m_client;
114 };
115
116 struct TextDestNodeMetadata : public TextDest
117 {
118         TextDestNodeMetadata(v3s16 p, Client *client)
119         {
120                 m_p = p;
121                 m_client = client;
122         }
123         void gotText(std::wstring text)
124         {
125                 std::string ntext = wide_to_narrow(text);
126                 infostream<<"Changing text of a sign node: "
127                                 <<ntext<<std::endl;
128                 m_client->sendSignNodeText(m_p, ntext);
129         }
130
131         v3s16 m_p;
132         Client *m_client;
133 };
134
135 /* Respawn menu callback */
136
137 class MainRespawnInitiator: public IRespawnInitiator
138 {
139 public:
140         MainRespawnInitiator(bool *active, Client *client):
141                 m_active(active), m_client(client)
142         {
143                 *m_active = true;
144         }
145         void respawn()
146         {
147                 *m_active = false;
148                 m_client->sendRespawn();
149         }
150 private:
151         bool *m_active;
152         Client *m_client;
153 };
154
155 /*
156         Hotbar draw routine
157 */
158 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
159                 ITextureSource *tsrc,
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, tsrc);
252                 }
253         }
254         
255         /*
256                 Draw hearts
257         */
258         video::ITexture *heart_texture = tsrc->getTextureRaw("heart.png");
259         if(heart_texture)
260         {
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(client->getNodeDefManager()->get(n).pointable == 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                 const ContentFeatures &f = client->getNodeDefManager()->get(n);
346                 
347                 if(f.selection_box.type == NODEBOX_FIXED)
348                 {
349                         core::aabbox3d<f32> box = f.selection_box.fixed;
350                         box.MinEdge += npf;
351                         box.MaxEdge += npf;
352
353                         v3s16 facedirs[6] = {
354                                 v3s16(-1,0,0),
355                                 v3s16(1,0,0),
356                                 v3s16(0,-1,0),
357                                 v3s16(0,1,0),
358                                 v3s16(0,0,-1),
359                                 v3s16(0,0,1),
360                         };
361
362                         core::aabbox3d<f32> faceboxes[6] = {
363                                 // X-
364                                 core::aabbox3d<f32>(
365                                         box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
366                                         box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
367                                 ),
368                                 // X+
369                                 core::aabbox3d<f32>(
370                                         box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
371                                         box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
372                                 ),
373                                 // Y-
374                                 core::aabbox3d<f32>(
375                                         box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
376                                         box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
377                                 ),
378                                 // Y+
379                                 core::aabbox3d<f32>(
380                                         box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
381                                         box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
382                                 ),
383                                 // Z-
384                                 core::aabbox3d<f32>(
385                                         box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
386                                         box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
387                                 ),
388                                 // Z+
389                                 core::aabbox3d<f32>(
390                                         box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
391                                         box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
392                                 ),
393                         };
394
395                         for(u16 i=0; i<6; i++)
396                         {
397                                 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
398                                 v3f centerpoint = npf + facedir_f * BS/2;
399                                 f32 distance = (centerpoint - camera_position).getLength();
400                                 if(distance >= mindistance)
401                                         continue;
402                                 if(!faceboxes[i].intersectsWithLine(shootline))
403                                         continue;
404                                 nodefound = true;
405                                 nodepos = np;
406                                 neighbourpos = np+facedirs[i];
407                                 mindistance = distance;
408                                 nodehilightbox = box;
409                         }
410                 }
411                 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
412                 {
413                         v3s16 dir = unpackDir(n.param2);
414                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
415                         dir_f *= BS/2 - BS/6 - BS/20;
416                         v3f cpf = npf + dir_f;
417                         f32 distance = (cpf - camera_position).getLength();
418
419                         core::aabbox3d<f32> box;
420                         
421                         // top
422                         if(dir == v3s16(0,1,0)){
423                                 box = f.selection_box.wall_top;
424                         }
425                         // bottom
426                         else if(dir == v3s16(0,-1,0)){
427                                 box = f.selection_box.wall_bottom;
428                         }
429                         // side
430                         else{
431                                 v3f vertices[2] =
432                                 {
433                                         f.selection_box.wall_side.MinEdge,
434                                         f.selection_box.wall_side.MaxEdge
435                                 };
436
437                                 for(s32 i=0; i<2; i++)
438                                 {
439                                         if(dir == v3s16(-1,0,0))
440                                                 vertices[i].rotateXZBy(0);
441                                         if(dir == v3s16(1,0,0))
442                                                 vertices[i].rotateXZBy(180);
443                                         if(dir == v3s16(0,0,-1))
444                                                 vertices[i].rotateXZBy(90);
445                                         if(dir == v3s16(0,0,1))
446                                                 vertices[i].rotateXZBy(-90);
447                                 }
448
449                                 box = core::aabbox3d<f32>(vertices[0]);
450                                 box.addInternalPoint(vertices[1]);
451                         }
452
453                         box.MinEdge += npf;
454                         box.MaxEdge += npf;
455                         
456                         if(distance < mindistance)
457                         {
458                                 if(box.intersectsWithLine(shootline))
459                                 {
460                                         nodefound = true;
461                                         nodepos = np;
462                                         neighbourpos = np;
463                                         mindistance = distance;
464                                         nodehilightbox = box;
465                                 }
466                         }
467                 }
468                 else // NODEBOX_REGULAR
469                 {
470                         for(u16 i=0; i<6; i++)
471                         {
472                                 v3f dir_f = v3f(dirs[i].X,
473                                                 dirs[i].Y, dirs[i].Z);
474                                 v3f centerpoint = npf + dir_f * BS/2;
475                                 f32 distance =
476                                                 (centerpoint - camera_position).getLength();
477                                 
478                                 if(distance < mindistance)
479                                 {
480                                         core::CMatrix4<f32> m;
481                                         m.buildRotateFromTo(v3f(0,0,1), dir_f);
482
483                                         // This is the back face
484                                         v3f corners[2] = {
485                                                 v3f(BS/2, BS/2, BS/2),
486                                                 v3f(-BS/2, -BS/2, BS/2+d)
487                                         };
488                                         
489                                         for(u16 j=0; j<2; j++)
490                                         {
491                                                 m.rotateVect(corners[j]);
492                                                 corners[j] += npf;
493                                         }
494
495                                         core::aabbox3d<f32> facebox(corners[0]);
496                                         facebox.addInternalPoint(corners[1]);
497
498                                         if(facebox.intersectsWithLine(shootline))
499                                         {
500                                                 nodefound = true;
501                                                 nodepos = np;
502                                                 neighbourpos = np + dirs[i];
503                                                 mindistance = distance;
504
505                                                 //nodehilightbox = facebox;
506
507                                                 const float d = 0.502;
508                                                 core::aabbox3d<f32> nodebox
509                                                                 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
510                                                 v3f nodepos_f = intToFloat(nodepos, BS);
511                                                 nodebox.MinEdge += nodepos_f;
512                                                 nodebox.MaxEdge += nodepos_f;
513                                                 nodehilightbox = nodebox;
514                                         }
515                                 } // if distance < mindistance
516                         } // for dirs
517                 } // regular block
518         } // for coords
519 }
520
521 void update_skybox(video::IVideoDriver* driver, ITextureSource *tsrc,
522                 scene::ISceneManager* smgr, scene::ISceneNode* &skybox,
523                 float brightness)
524 {
525         if(skybox)
526         {
527                 skybox->remove();
528         }
529         
530         /*// Disable skybox if FarMesh is enabled
531         if(g_settings->getBool("enable_farmesh"))
532                 return;*/
533         
534         if(brightness >= 0.5)
535         {
536                 skybox = smgr->addSkyBoxSceneNode(
537                         tsrc->getTextureRaw("skybox2.png"),
538                         tsrc->getTextureRaw("skybox3.png"),
539                         tsrc->getTextureRaw("skybox1.png"),
540                         tsrc->getTextureRaw("skybox1.png"),
541                         tsrc->getTextureRaw("skybox1.png"),
542                         tsrc->getTextureRaw("skybox1.png"));
543         }
544         else if(brightness >= 0.2)
545         {
546                 skybox = smgr->addSkyBoxSceneNode(
547                         tsrc->getTextureRaw("skybox2_dawn.png"),
548                         tsrc->getTextureRaw("skybox3_dawn.png"),
549                         tsrc->getTextureRaw("skybox1_dawn.png"),
550                         tsrc->getTextureRaw("skybox1_dawn.png"),
551                         tsrc->getTextureRaw("skybox1_dawn.png"),
552                         tsrc->getTextureRaw("skybox1_dawn.png"));
553         }
554         else
555         {
556                 skybox = smgr->addSkyBoxSceneNode(
557                         tsrc->getTextureRaw("skybox2_night.png"),
558                         tsrc->getTextureRaw("skybox3_night.png"),
559                         tsrc->getTextureRaw("skybox1_night.png"),
560                         tsrc->getTextureRaw("skybox1_night.png"),
561                         tsrc->getTextureRaw("skybox1_night.png"),
562                         tsrc->getTextureRaw("skybox1_night.png"));
563         }
564 }
565
566 /*
567         Draws a screen with a single text on it.
568         Text will be removed when the screen is drawn the next time.
569 */
570 /*gui::IGUIStaticText **/
571 void draw_load_screen(const std::wstring &text,
572                 video::IVideoDriver* driver, gui::IGUIFont* font)
573 {
574         v2u32 screensize = driver->getScreenSize();
575         const wchar_t *loadingtext = text.c_str();
576         core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
577         core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
578         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
579         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
580
581         gui::IGUIStaticText *guitext = guienv->addStaticText(
582                         loadingtext, textrect, false, false);
583         guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
584
585         driver->beginScene(true, true, video::SColor(255,0,0,0));
586         guienv->drawAll();
587         driver->endScene();
588         
589         guitext->remove();
590         
591         //return guitext;
592 }
593
594 void the_game(
595         bool &kill,
596         bool random_input,
597         InputHandler *input,
598         IrrlichtDevice *device,
599         gui::IGUIFont* font,
600         std::string map_dir,
601         std::string playername,
602         std::string password,
603         std::string address,
604         u16 port,
605         std::wstring &error_message,
606     std::string configpath
607 )
608 {
609         video::IVideoDriver* driver = device->getVideoDriver();
610         scene::ISceneManager* smgr = device->getSceneManager();
611         
612         // Calculate text height using the font
613         u32 text_height = font->getDimension(L"Random test string").Height;
614
615         v2u32 screensize(0,0);
616         v2u32 last_screensize(0,0);
617         screensize = driver->getScreenSize();
618
619         const s32 hotbar_itemcount = 8;
620         //const s32 hotbar_imagesize = 36;
621         //const s32 hotbar_imagesize = 64;
622         s32 hotbar_imagesize = 48;
623         
624         // The color of the sky
625
626         //video::SColor skycolor = video::SColor(255,140,186,250);
627
628         video::SColor bgcolor_bright = video::SColor(255,170,200,230);
629
630         /*
631                 Draw "Loading" screen
632         */
633
634         draw_load_screen(L"Loading...", driver, font);
635         
636         // Create texture source
637         IWritableTextureSource *tsrc = createTextureSource(device);
638         
639         // These will be filled by data received from the server
640         // Create tool definition manager
641         IWritableToolDefManager *tooldef = createToolDefManager();
642         // Create node definition manager
643         IWritableNodeDefManager *nodedef = createNodeDefManager();
644
645         /*
646                 Create server.
647                 SharedPtr will delete it when it goes out of scope.
648         */
649         SharedPtr<Server> server;
650         if(address == ""){
651                 draw_load_screen(L"Creating server...", driver, font);
652                 infostream<<"Creating server"<<std::endl;
653                 server = new Server(map_dir, configpath);
654                 server->start(port);
655         }
656
657         { // Client scope
658         
659         /*
660                 Create client
661         */
662
663         draw_load_screen(L"Creating client...", driver, font);
664         infostream<<"Creating client"<<std::endl;
665         
666         MapDrawControl draw_control;
667
668         Client client(device, playername.c_str(), password, draw_control,
669                         tsrc, tooldef, nodedef);
670         
671         // Client acts as our GameDef
672         IGameDef *gamedef = &client;
673                         
674         draw_load_screen(L"Resolving address...", driver, font);
675         Address connect_address(0,0,0,0, port);
676         try{
677                 if(address == "")
678                         //connect_address.Resolve("localhost");
679                         connect_address.setAddress(127,0,0,1);
680                 else
681                         connect_address.Resolve(address.c_str());
682         }
683         catch(ResolveError &e)
684         {
685                 errorstream<<"Couldn't resolve address"<<std::endl;
686                 //return 0;
687                 error_message = L"Couldn't resolve address";
688                 //gui_loadingtext->remove();
689                 return;
690         }
691
692         /*
693                 Attempt to connect to the server
694         */
695         
696         infostream<<"Connecting to server at ";
697         connect_address.print(&infostream);
698         infostream<<std::endl;
699         client.connect(connect_address);
700         
701         /*
702                 Wait for server to accept connection
703         */
704         bool could_connect = false;
705         try{
706                 float frametime = 0.033;
707                 const float timeout = 10.0;
708                 float time_counter = 0.0;
709                 for(;;)
710                 {
711                         // Update client and server
712                         client.step(frametime);
713                         if(server != NULL)
714                                 server->step(frametime);
715                         
716                         // End condition
717                         if(client.connectedAndInitialized()){
718                                 could_connect = true;
719                                 break;
720                         }
721                         // Break conditions
722                         if(client.accessDenied())
723                                 break;
724                         if(time_counter >= timeout)
725                                 break;
726                         
727                         // Display status
728                         std::wostringstream ss;
729                         ss<<L"Connecting to server... (timeout in ";
730                         ss<<(int)(timeout - time_counter + 1.0);
731                         ss<<L" seconds)";
732                         draw_load_screen(ss.str(), driver, font);
733                         
734                         // Delay a bit
735                         sleep_ms(1000*frametime);
736                         time_counter += frametime;
737                 }
738         }
739         catch(con::PeerNotFoundException &e)
740         {}
741         
742         /*
743                 Handle failure to connect
744         */
745         if(could_connect == false)
746         {
747                 if(client.accessDenied())
748                 {
749                         error_message = L"Access denied. Reason: "
750                                         +client.accessDeniedReason();
751                         errorstream<<wide_to_narrow(error_message)<<std::endl;
752                 }
753                 else
754                 {
755                         error_message = L"Connection timed out.";
756                         errorstream<<"Timed out."<<std::endl;
757                 }
758                 //gui_loadingtext->remove();
759                 return;
760         }
761         
762         /*
763                 Wait until content has been received
764         */
765         bool got_content = false;
766         {
767                 float frametime = 0.033;
768                 const float timeout = 5.0;
769                 float time_counter = 0.0;
770                 for(;;)
771                 {
772                         // Update client and server
773                         client.step(frametime);
774                         if(server != NULL)
775                                 server->step(frametime);
776                         
777                         // End condition
778                         if(client.texturesReceived() &&
779                                         client.tooldefReceived() &&
780                                         client.nodedefReceived()){
781                                 got_content = true;
782                                 break;
783                         }
784                         // Break conditions
785                         if(!client.connectedAndInitialized())
786                                 break;
787                         if(time_counter >= timeout)
788                                 break;
789                         
790                         // Display status
791                         std::wostringstream ss;
792                         ss<<L"Waiting content... (continuing anyway in ";
793                         ss<<(int)(timeout - time_counter + 1.0);
794                         ss<<L" seconds)\n";
795
796                         ss<<(client.tooldefReceived()?L"[X]":L"[  ]");
797                         ss<<L" Tool definitions\n";
798                         ss<<(client.nodedefReceived()?L"[X]":L"[  ]");
799                         ss<<L" Node definitions\n";
800                         //ss<<(client.texturesReceived()?L"[X]":L"[  ]");
801                         ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
802                         ss<<L" Textures\n";
803
804                         draw_load_screen(ss.str(), driver, font);
805                         
806                         // Delay a bit
807                         sleep_ms(1000*frametime);
808                         time_counter += frametime;
809                 }
810         }
811
812         /*
813                 Create skybox
814         */
815         float old_brightness = 1.0;
816         scene::ISceneNode* skybox = NULL;
817         update_skybox(driver, tsrc, smgr, skybox, 1.0);
818         
819         /*
820                 Create the camera node
821         */
822         Camera camera(smgr, draw_control);
823         if (!camera.successfullyCreated(error_message))
824                 return;
825
826         f32 camera_yaw = 0; // "right/left"
827         f32 camera_pitch = 0; // "up/down"
828
829         /*
830                 Clouds
831         */
832         
833         float cloud_height = BS*100;
834         Clouds *clouds = NULL;
835         if(g_settings->getBool("enable_clouds"))
836         {
837                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1,
838                                 cloud_height, time(0));
839         }
840         
841         /*
842                 FarMesh
843         */
844
845         FarMesh *farmesh = NULL;
846         if(g_settings->getBool("enable_farmesh"))
847         {
848                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
849         }
850
851         /*
852                 Move into game
853         */
854         
855         //gui_loadingtext->remove();
856
857         /*
858                 Add some gui stuff
859         */
860
861         // First line of debug text
862         gui::IGUIStaticText *guitext = guienv->addStaticText(
863                         L"Minetest-c55",
864                         core::rect<s32>(5, 5, 795, 5+text_height),
865                         false, false);
866         // Second line of debug text
867         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
868                         L"",
869                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
870                         false, false);
871         // At the middle of the screen
872         // Object infos are shown in this
873         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
874                         L"",
875                         core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
876                         false, false);
877         
878         // Chat text
879         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
880                         L"",
881                         core::rect<s32>(0,0,0,0),
882                         //false, false); // Disable word wrap as of now
883                         false, true);
884         //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
885         core::list<ChatLine> chat_lines;
886         
887         // Profiler text (size is updated when text is updated)
888         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
889                         L"<Profiler>",
890                         core::rect<s32>(6, 4+(text_height+5)*2, 400,
891                         (text_height+5)*2 + text_height*35),
892                         false, false);
893         guitext_profiler->setBackgroundColor(video::SColor(80,0,0,0));
894         guitext_profiler->setVisible(false);
895         
896         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
897                         (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
898         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
899                         (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
900         
901         // Test the text input system
902         /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
903                         NULL))->drop();*/
904         /*GUIMessageMenu *menu =
905                         new GUIMessageMenu(guienv, guiroot, -1, 
906                                 &g_menumgr,
907                                 L"Asd");
908         menu->drop();*/
909         
910         // Launch pause menu
911         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
912                         &g_menumgr))->drop();
913         
914         // Enable texts
915         /*guitext2->setVisible(true);
916         guitext_info->setVisible(true);
917         guitext_chat->setVisible(true);*/
918
919         //s32 guitext_chat_pad_bottom = 70;
920
921         /*
922                 Some statistics are collected in these
923         */
924         u32 drawtime = 0;
925         u32 beginscenetime = 0;
926         u32 scenetime = 0;
927         u32 endscenetime = 0;
928         
929         // A test
930         //throw con::PeerNotFoundException("lol");
931
932         float brightness = 1.0;
933
934         core::list<float> frametime_log;
935
936         float nodig_delay_counter = 0.0;
937         float dig_time = 0.0;
938         u16 dig_index = 0;
939         v3s16 nodepos_old(-32768,-32768,-32768);
940
941         float damage_flash_timer = 0;
942         s16 farmesh_range = 20*MAP_BLOCKSIZE;
943
944         const float object_hit_delay = 0.5;
945         float object_hit_delay_timer = 0.0;
946         
947         bool invert_mouse = g_settings->getBool("invert_mouse");
948
949         bool respawn_menu_active = false;
950
951         bool show_profiler = false;
952         bool force_fog_off = false;
953         bool disable_camera_update = 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                 tsrc->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                         std::wstring text = narrow_to_wide(os.str());
1190                         guitext_profiler->setText(text.c_str());
1191
1192                         g_profiler->clear();
1193                         
1194                         s32 w = font->getDimension(text.c_str()).Width;
1195                         if(w < 400)
1196                                 w = 400;
1197                         core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
1198                                         8+(text_height+5)*2 +
1199                                         font->getDimension(text.c_str()).Height);
1200                         guitext_profiler->setRelativePosition(rect);
1201                 }
1202
1203                 /*
1204                         Direct handling of user input
1205                 */
1206                 
1207                 // Reset input if window not active or some menu is active
1208                 if(device->isWindowActive() == false || noMenuActive() == false)
1209                 {
1210                         input->clear();
1211                 }
1212
1213                 // Input handler step() (used by the random input generator)
1214                 input->step(dtime);
1215
1216                 /*
1217                         Launch menus according to keys
1218                 */
1219                 if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1220                 {
1221                         infostream<<"the_game: "
1222                                         <<"Launching inventory"<<std::endl;
1223                         
1224                         GUIInventoryMenu *menu =
1225                                 new GUIInventoryMenu(guienv, guiroot, -1,
1226                                         &g_menumgr, v2s16(8,7),
1227                                         client.getInventoryContext(),
1228                                         &client, tsrc);
1229
1230                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1231                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1232                                         "list", "current_player", "main",
1233                                         v2s32(0, 3), v2s32(8, 4)));
1234                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1235                                         "list", "current_player", "craft",
1236                                         v2s32(3, 0), v2s32(3, 3)));
1237                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1238                                         "list", "current_player", "craftresult",
1239                                         v2s32(7, 1), v2s32(1, 1)));
1240
1241                         menu->setDrawSpec(draw_spec);
1242
1243                         menu->drop();
1244                 }
1245                 else if(input->wasKeyDown(EscapeKey))
1246                 {
1247                         infostream<<"the_game: "
1248                                         <<"Launching pause menu"<<std::endl;
1249                         // It will delete itself by itself
1250                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1251                                         &g_menumgr))->drop();
1252
1253                         // Move mouse cursor on top of the disconnect button
1254                         input->setMousePos(displaycenter.X, displaycenter.Y+25);
1255                 }
1256                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1257                 {
1258                         TextDest *dest = new TextDestChat(&client);
1259
1260                         (new GUITextInputMenu(guienv, guiroot, -1,
1261                                         &g_menumgr, dest,
1262                                         L""))->drop();
1263                 }
1264                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1265                 {
1266                         TextDest *dest = new TextDestChat(&client);
1267
1268                         (new GUITextInputMenu(guienv, guiroot, -1,
1269                                         &g_menumgr, dest,
1270                                         L"/"))->drop();
1271                 }
1272                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1273                 {
1274                         if(g_settings->getBool("free_move"))
1275                         {
1276                                 g_settings->set("free_move","false");
1277                                 chat_lines.push_back(ChatLine(L"free_move disabled"));
1278                         }
1279                         else
1280                         {
1281                                 g_settings->set("free_move","true");
1282                                 chat_lines.push_back(ChatLine(L"free_move enabled"));
1283                         }
1284                 }
1285                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1286                 {
1287                         if(g_settings->getBool("fast_move"))
1288                         {
1289                                 g_settings->set("fast_move","false");
1290                                 chat_lines.push_back(ChatLine(L"fast_move disabled"));
1291                         }
1292                         else
1293                         {
1294                                 g_settings->set("fast_move","true");
1295                                 chat_lines.push_back(ChatLine(L"fast_move enabled"));
1296                         }
1297                 }
1298                 else if(input->wasKeyDown(getKeySetting("keymap_frametime_graph")))
1299                 {
1300                         if(g_settings->getBool("frametime_graph"))
1301                         {
1302                                 g_settings->set("frametime_graph","false");
1303                                 chat_lines.push_back(ChatLine(L"frametime_graph disabled"));
1304                         }
1305                         else
1306                         {
1307                                 g_settings->set("frametime_graph","true");
1308                                 chat_lines.push_back(ChatLine(L"frametime_graph enabled"));
1309                         }
1310                 }
1311                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1312                 {
1313                         irr::video::IImage* const image = driver->createScreenShot(); 
1314                         if (image) { 
1315                                 irr::c8 filename[256]; 
1316                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1317                                                  g_settings->get("screenshot_path").c_str(),
1318                                                  device->getTimer()->getRealTime()); 
1319                                 if (driver->writeImageToFile(image, filename)) {
1320                                         std::wstringstream sstr;
1321                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1322                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1323                                         chat_lines.push_back(ChatLine(sstr.str()));
1324                                 } else{
1325                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1326                                 }
1327                                 image->drop(); 
1328                         }                        
1329                 }
1330                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1331                 {
1332                         show_profiler = !show_profiler;
1333                         guitext_profiler->setVisible(show_profiler);
1334                         if(show_profiler)
1335                                 chat_lines.push_back(ChatLine(L"Profiler disabled"));
1336                         else
1337                                 chat_lines.push_back(ChatLine(L"Profiler enabled"));
1338                 }
1339                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1340                 {
1341                         force_fog_off = !force_fog_off;
1342                         if(force_fog_off)
1343                                 chat_lines.push_back(ChatLine(L"Fog disabled"));
1344                         else
1345                                 chat_lines.push_back(ChatLine(L"Fog enabled"));
1346                 }
1347                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1348                 {
1349                         disable_camera_update = !disable_camera_update;
1350                         if(disable_camera_update)
1351                                 chat_lines.push_back(ChatLine(L"Camera update disabled"));
1352                         else
1353                                 chat_lines.push_back(ChatLine(L"Camera update enabled"));
1354                 }
1355
1356                 // Item selection with mouse wheel
1357                 {
1358                         s32 wheel = input->getMouseWheel();
1359                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1360                                         hotbar_itemcount-1);
1361
1362                         if(wheel < 0)
1363                         {
1364                                 if(g_selected_item < max_item)
1365                                         g_selected_item++;
1366                                 else
1367                                         g_selected_item = 0;
1368                         }
1369                         else if(wheel > 0)
1370                         {
1371                                 if(g_selected_item > 0)
1372                                         g_selected_item--;
1373                                 else
1374                                         g_selected_item = max_item;
1375                         }
1376                 }
1377                 
1378                 // Item selection
1379                 for(u16 i=0; i<10; i++)
1380                 {
1381                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1382                         if(input->wasKeyDown(*kp))
1383                         {
1384                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1385                                 {
1386                                         g_selected_item = i;
1387
1388                                         infostream<<"Selected item: "
1389                                                         <<g_selected_item<<std::endl;
1390                                 }
1391                         }
1392                 }
1393
1394                 // Viewing range selection
1395                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1396                 {
1397                         if(draw_control.range_all)
1398                         {
1399                                 draw_control.range_all = false;
1400                                 infostream<<"Disabled full viewing range"<<std::endl;
1401                         }
1402                         else
1403                         {
1404                                 draw_control.range_all = true;
1405                                 infostream<<"Enabled full viewing range"<<std::endl;
1406                         }
1407                 }
1408
1409                 // Print debug stacks
1410                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1411                 {
1412                         dstream<<"-----------------------------------------"
1413                                         <<std::endl;
1414                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1415                         dstream<<"-----------------------------------------"
1416                                         <<std::endl;
1417                         debug_stacks_print();
1418                 }
1419
1420                 /*
1421                         Mouse and camera control
1422                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1423                 */
1424                 
1425                 if((device->isWindowActive() && noMenuActive()) || random_input)
1426                 {
1427                         if(!random_input)
1428                         {
1429                                 // Mac OSX gets upset if this is set every frame
1430                                 if(device->getCursorControl()->isVisible())
1431                                         device->getCursorControl()->setVisible(false);
1432                         }
1433
1434                         if(first_loop_after_window_activation){
1435                                 //infostream<<"window active, first loop"<<std::endl;
1436                                 first_loop_after_window_activation = false;
1437                         }
1438                         else{
1439                                 s32 dx = input->getMousePos().X - displaycenter.X;
1440                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1441                                 if(invert_mouse)
1442                                         dy = -dy;
1443                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1444                                 
1445                                 /*const float keyspeed = 500;
1446                                 if(input->isKeyDown(irr::KEY_UP))
1447                                         dy -= dtime * keyspeed;
1448                                 if(input->isKeyDown(irr::KEY_DOWN))
1449                                         dy += dtime * keyspeed;
1450                                 if(input->isKeyDown(irr::KEY_LEFT))
1451                                         dx -= dtime * keyspeed;
1452                                 if(input->isKeyDown(irr::KEY_RIGHT))
1453                                         dx += dtime * keyspeed;*/
1454
1455                                 camera_yaw -= dx*0.2;
1456                                 camera_pitch += dy*0.2;
1457                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1458                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1459                         }
1460                         input->setMousePos(displaycenter.X, displaycenter.Y);
1461                 }
1462                 else{
1463                         // Mac OSX gets upset if this is set every frame
1464                         if(device->getCursorControl()->isVisible() == false)
1465                                 device->getCursorControl()->setVisible(true);
1466
1467                         //infostream<<"window inactive"<<std::endl;
1468                         first_loop_after_window_activation = true;
1469                 }
1470
1471                 /*
1472                         Player speed control
1473                 */
1474                 
1475                 if(!noMenuActive() || !device->isWindowActive())
1476                 {
1477                         PlayerControl control(
1478                                 false,
1479                                 false,
1480                                 false,
1481                                 false,
1482                                 false,
1483                                 false,
1484                                 false,
1485                                 camera_pitch,
1486                                 camera_yaw
1487                         );
1488                         client.setPlayerControl(control);
1489                 }
1490                 else
1491                 {
1492                         /*bool a_up,
1493                         bool a_down,
1494                         bool a_left,
1495                         bool a_right,
1496                         bool a_jump,
1497                         bool a_superspeed,
1498                         bool a_sneak,
1499                         float a_pitch,
1500                         float a_yaw*/
1501                         PlayerControl control(
1502                                 input->isKeyDown(getKeySetting("keymap_forward")),
1503                                 input->isKeyDown(getKeySetting("keymap_backward")),
1504                                 input->isKeyDown(getKeySetting("keymap_left")),
1505                                 input->isKeyDown(getKeySetting("keymap_right")),
1506                                 input->isKeyDown(getKeySetting("keymap_jump")),
1507                                 input->isKeyDown(getKeySetting("keymap_special1")),
1508                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1509                                 camera_pitch,
1510                                 camera_yaw
1511                         );
1512                         client.setPlayerControl(control);
1513                 }
1514                 
1515                 /*
1516                         Run server
1517                 */
1518
1519                 if(server != NULL)
1520                 {
1521                         //TimeTaker timer("server->step(dtime)");
1522                         server->step(dtime);
1523                 }
1524
1525                 /*
1526                         Process environment
1527                 */
1528                 
1529                 {
1530                         //TimeTaker timer("client.step(dtime)");
1531                         client.step(dtime);
1532                         //client.step(dtime_avg1);
1533                 }
1534
1535                 {
1536                         // Read client events
1537                         for(;;)
1538                         {
1539                                 ClientEvent event = client.getClientEvent();
1540                                 if(event.type == CE_NONE)
1541                                 {
1542                                         break;
1543                                 }
1544                                 else if(event.type == CE_PLAYER_DAMAGE)
1545                                 {
1546                                         //u16 damage = event.player_damage.amount;
1547                                         //infostream<<"Player damage: "<<damage<<std::endl;
1548                                         damage_flash_timer = 0.05;
1549                                         if(event.player_damage.amount >= 2){
1550                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1551                                         }
1552                                 }
1553                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1554                                 {
1555                                         camera_yaw = event.player_force_move.yaw;
1556                                         camera_pitch = event.player_force_move.pitch;
1557                                 }
1558                                 else if(event.type == CE_DEATHSCREEN)
1559                                 {
1560                                         if(respawn_menu_active)
1561                                                 continue;
1562
1563                                         /*bool set_camera_point_target =
1564                                                         event.deathscreen.set_camera_point_target;
1565                                         v3f camera_point_target;
1566                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1567                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1568                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1569                                         MainRespawnInitiator *respawner =
1570                                                         new MainRespawnInitiator(
1571                                                                         &respawn_menu_active, &client);
1572                                         GUIDeathScreen *menu =
1573                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1574                                                                 &g_menumgr, respawner);
1575                                         menu->drop();
1576                                         
1577                                         /* Handle visualization */
1578
1579                                         damage_flash_timer = 0;
1580
1581                                         /*LocalPlayer* player = client.getLocalPlayer();
1582                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1583                                         camera.update(player, busytime, screensize);*/
1584                                 }
1585                                 else if(event.type == CE_TEXTURES_UPDATED)
1586                                 {
1587                                         update_skybox(driver, tsrc, smgr, skybox, brightness);
1588                                 }
1589                         }
1590                 }
1591                 
1592                 //TimeTaker //timer2("//timer2");
1593
1594                 LocalPlayer* player = client.getLocalPlayer();
1595                 camera.update(player, busytime, screensize);
1596                 camera.step(dtime);
1597
1598                 v3f player_position = player->getPosition();
1599                 v3f camera_position = camera.getPosition();
1600                 v3f camera_direction = camera.getDirection();
1601                 f32 camera_fov = camera.getFovMax();
1602                 
1603                 if(!disable_camera_update){
1604                         client.updateCamera(camera_position,
1605                                 camera_direction, camera_fov);
1606                 }
1607
1608                 //timer2.stop();
1609                 //TimeTaker //timer3("//timer3");
1610
1611                 /*
1612                         Calculate what block is the crosshair pointing to
1613                 */
1614                 
1615                 //u32 t1 = device->getTimer()->getRealTime();
1616                 
1617                 //f32 d = 4; // max. distance
1618                 f32 d = 4; // max. distance
1619                 core::line3d<f32> shootline(camera_position,
1620                                 camera_position + camera_direction * BS * (d+1));
1621
1622                 ClientActiveObject *selected_active_object
1623                                 = client.getSelectedActiveObject
1624                                         (d*BS, camera_position, shootline);
1625                 
1626                 bool left_punch = false;
1627                 bool left_punch_muted = false;
1628
1629                 if(selected_active_object != NULL)
1630                 {
1631                         /* Clear possible cracking animation */
1632                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1633                         {
1634                                 client.clearTempMod(nodepos_old);
1635                                 dig_time = 0.0;
1636                                 nodepos_old = v3s16(-32768,-32768,-32768);
1637                         }
1638
1639                         //infostream<<"Client returned selected_active_object != NULL"<<std::endl;
1640                         
1641                         core::aabbox3d<f32> *selection_box
1642                                         = selected_active_object->getSelectionBox();
1643                         // Box should exist because object was returned in the
1644                         // first place
1645                         assert(selection_box);
1646
1647                         v3f pos = selected_active_object->getPosition();
1648
1649                         core::aabbox3d<f32> box_on_map(
1650                                         selection_box->MinEdge + pos,
1651                                         selection_box->MaxEdge + pos
1652                         );
1653                         
1654                         if(selected_active_object->doShowSelectionBox())
1655                                 hilightboxes.push_back(box_on_map);
1656
1657                         //infotext = narrow_to_wide("A ClientActiveObject");
1658                         infotext = narrow_to_wide(selected_active_object->infoText());
1659
1660                         //if(input->getLeftClicked())
1661                         if(input->getLeftState())
1662                         {
1663                                 bool do_punch = false;
1664                                 bool do_punch_damage = false;
1665                                 if(object_hit_delay_timer <= 0.0){
1666                                         do_punch = true;
1667                                         do_punch_damage = true;
1668                                         object_hit_delay_timer = object_hit_delay;
1669                                 }
1670                                 if(input->getLeftClicked()){
1671                                         do_punch = true;
1672                                 }
1673                                 if(do_punch){
1674                                         infostream<<"Left-clicked object"<<std::endl;
1675                                         left_punch = true;
1676                                 }
1677                                 if(do_punch_damage){
1678                                         client.clickActiveObject(0,
1679                                                         selected_active_object->getId(), g_selected_item);
1680                                 }
1681                         }
1682                         else if(input->getRightClicked())
1683                         {
1684                                 infostream<<"Right-clicked object"<<std::endl;
1685                                 client.clickActiveObject(1,
1686                                                 selected_active_object->getId(), g_selected_item);
1687                         }
1688                 }
1689                 else // selected_object == NULL
1690                 {
1691
1692                 /*
1693                         Find out which node we are pointing at
1694                 */
1695                 
1696                 bool nodefound = false;
1697                 v3s16 nodepos;
1698                 v3s16 neighbourpos;
1699                 core::aabbox3d<f32> nodehilightbox;
1700
1701                 getPointedNode(&client, player_position,
1702                                 camera_direction, camera_position,
1703                                 nodefound, shootline,
1704                                 nodepos, neighbourpos,
1705                                 nodehilightbox, d);
1706         
1707                 if(!nodefound){
1708                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1709                         {
1710                                 client.clearTempMod(nodepos_old);
1711                                 dig_time = 0.0;
1712                                 nodepos_old = v3s16(-32768,-32768,-32768);
1713                         }
1714                 } else {
1715                         /*
1716                                 Visualize selection
1717                         */
1718
1719                         hilightboxes.push_back(nodehilightbox);
1720
1721                         /*
1722                                 Check information text of node
1723                         */
1724
1725                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1726                         if(meta)
1727                         {
1728                                 infotext = narrow_to_wide(meta->infoText());
1729                         }
1730                         
1731                         //MapNode node = client.getNode(nodepos);
1732
1733                         /*
1734                                 Handle digging
1735                         */
1736                         
1737                         if(input->getLeftReleased())
1738                         {
1739                                 client.clearTempMod(nodepos);
1740                                 dig_time = 0.0;
1741                         }
1742                         
1743                         if(nodig_delay_counter > 0.0)
1744                         {
1745                                 nodig_delay_counter -= dtime;
1746                         }
1747                         else
1748                         {
1749                                 if(nodepos != nodepos_old)
1750                                 {
1751                                         infostream<<"Pointing at ("<<nodepos.X<<","
1752                                                         <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1753
1754                                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1755                                         {
1756                                                 client.clearTempMod(nodepos_old);
1757                                                 dig_time = 0.0;
1758                                                 nodepos_old = v3s16(-32768,-32768,-32768);
1759                                         }
1760                                 }
1761
1762                                 if(input->getLeftClicked() ||
1763                                                 (input->getLeftState() && nodepos != nodepos_old))
1764                                 {
1765                                         infostream<<"Started digging"<<std::endl;
1766                                         client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1767                                 }
1768                                 if(input->getLeftClicked())
1769                                 {
1770                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1771                                 }
1772                                 if(input->getLeftState())
1773                                 {
1774                                         MapNode n = client.getNode(nodepos);
1775                                 
1776                                         // Get tool name. Default is "" = bare hands
1777                                         std::string toolname = "";
1778                                         InventoryList *mlist = local_inventory.getList("main");
1779                                         if(mlist != NULL)
1780                                         {
1781                                                 InventoryItem *item = mlist->getItem(g_selected_item);
1782                                                 if(item && (std::string)item->getName() == "ToolItem")
1783                                                 {
1784                                                         ToolItem *titem = (ToolItem*)item;
1785                                                         toolname = titem->getToolName();
1786                                                 }
1787                                         }
1788
1789                                         // Get digging properties for material and tool
1790                                         content_t material = n.getContent();
1791                                         ToolDiggingProperties tp =
1792                                                         tooldef->getDiggingProperties(toolname);
1793                                         DiggingProperties prop =
1794                                                         getDiggingProperties(material, &tp, nodedef);
1795                                         
1796                                         float dig_time_complete = 0.0;
1797
1798                                         if(prop.diggable == false)
1799                                         {
1800                                                 /*infostream<<"Material "<<(int)material
1801                                                                 <<" not diggable with \""
1802                                                                 <<toolname<<"\""<<std::endl;*/
1803                                                 // I guess nobody will wait for this long
1804                                                 dig_time_complete = 10000000.0;
1805                                         }
1806                                         else
1807                                         {
1808                                                 dig_time_complete = prop.time;
1809                                         }
1810                                         
1811                                         if(dig_time_complete >= 0.001)
1812                                         {
1813                                                 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1814                                                                 * dig_time/dig_time_complete);
1815                                         }
1816                                         // This is for torches
1817                                         else
1818                                         {
1819                                                 dig_index = CRACK_ANIMATION_LENGTH;
1820                                         }
1821
1822                                         if(dig_index < CRACK_ANIMATION_LENGTH)
1823                                         {
1824                                                 //TimeTaker timer("client.setTempMod");
1825                                                 //infostream<<"dig_index="<<dig_index<<std::endl;
1826                                                 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1827                                         }
1828                                         else
1829                                         {
1830                                                 infostream<<"Digging completed"<<std::endl;
1831                                                 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1832                                                 client.clearTempMod(nodepos);
1833                                                 client.removeNode(nodepos);
1834
1835                                                 dig_time = 0;
1836
1837                                                 nodig_delay_counter = dig_time_complete
1838                                                                 / (float)CRACK_ANIMATION_LENGTH;
1839
1840                                                 // We don't want a corresponding delay to
1841                                                 // very time consuming nodes
1842                                                 if(nodig_delay_counter > 0.5)
1843                                                 {
1844                                                         nodig_delay_counter = 0.5;
1845                                                 }
1846                                                 // We want a slight delay to very little
1847                                                 // time consuming nodes
1848                                                 float mindelay = 0.15;
1849                                                 if(nodig_delay_counter < mindelay)
1850                                                 {
1851                                                         nodig_delay_counter = mindelay;
1852                                                 }
1853                                         }
1854
1855                                         dig_time += dtime;
1856
1857                                         camera.setDigging(0);  // left click animation
1858                                 }
1859                         }
1860                         
1861                         
1862                         if(input->getRightClicked())
1863                         {
1864                                 infostream<<"Ground right-clicked"<<std::endl;
1865                                 
1866                                 // If metadata provides an inventory view, activate it
1867                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
1868                                 {
1869                                         infostream<<"Launching custom inventory view"<<std::endl;
1870                                         /*
1871                                                 Construct the unique identification string of the node
1872                                         */
1873                                         std::string current_name;
1874                                         current_name += "nodemeta:";
1875                                         current_name += itos(nodepos.X);
1876                                         current_name += ",";
1877                                         current_name += itos(nodepos.Y);
1878                                         current_name += ",";
1879                                         current_name += itos(nodepos.Z);
1880                                         
1881                                         /*
1882                                                 Create menu
1883                                         */
1884
1885                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1886                                         v2s16 invsize =
1887                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
1888                                                         draw_spec,
1889                                                         meta->getInventoryDrawSpecString(),
1890                                                         current_name);
1891
1892                                         GUIInventoryMenu *menu =
1893                                                 new GUIInventoryMenu(guienv, guiroot, -1,
1894                                                         &g_menumgr, invsize,
1895                                                         client.getInventoryContext(),
1896                                                         &client, tsrc);
1897                                         menu->setDrawSpec(draw_spec);
1898                                         menu->drop();
1899                                 }
1900                                 // If metadata provides text input, activate text input
1901                                 else if(meta && meta->allowsTextInput() && !random_input)
1902                                 {
1903                                         infostream<<"Launching metadata text input"<<std::endl;
1904                                         
1905                                         // Get a new text for it
1906
1907                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
1908
1909                                         std::wstring wtext = narrow_to_wide(meta->getText());
1910
1911                                         (new GUITextInputMenu(guienv, guiroot, -1,
1912                                                         &g_menumgr, dest,
1913                                                         wtext))->drop();
1914                                 }
1915                                 // Otherwise report right click to server
1916                                 else
1917                                 {
1918                                         client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1919                                         camera.setDigging(1);  // right click animation
1920                                 }
1921                         }
1922                         
1923                         nodepos_old = nodepos;
1924                 }
1925
1926                 } // selected_object == NULL
1927                 
1928                 if(left_punch || (input->getLeftClicked() && !left_punch_muted))
1929                 {
1930                         camera.setDigging(0); // left click animation
1931                 }
1932
1933                 input->resetLeftClicked();
1934                 input->resetRightClicked();
1935                 
1936                 if(input->getLeftReleased())
1937                 {
1938                         infostream<<"Left button released (stopped digging)"
1939                                         <<std::endl;
1940                         client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1941                 }
1942                 if(input->getRightReleased())
1943                 {
1944                         //inostream<<DTIME<<"Right released"<<std::endl;
1945                         // Nothing here
1946                 }
1947                 
1948                 input->resetLeftReleased();
1949                 input->resetRightReleased();
1950                 
1951                 /*
1952                         Calculate stuff for drawing
1953                 */
1954                 
1955                 /*
1956                         Calculate general brightness
1957                 */
1958                 u32 daynight_ratio = client.getDayNightRatio();
1959                 u8 light8 = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1960                 brightness = (float)light8/255.0;
1961                 video::SColor bgcolor = video::SColor(
1962                                 255,
1963                                 bgcolor_bright.getRed() * brightness,
1964                                 bgcolor_bright.getGreen() * brightness,
1965                                 bgcolor_bright.getBlue() * brightness);
1966                                 /*skycolor.getRed() * brightness,
1967                                 skycolor.getGreen() * brightness,
1968                                 skycolor.getBlue() * brightness);*/
1969
1970                 /*
1971                         Update skybox
1972                 */
1973                 if(fabs(brightness - old_brightness) > 0.01)
1974                         update_skybox(driver, tsrc, smgr, skybox, brightness);
1975
1976                 /*
1977                         Update clouds
1978                 */
1979                 if(clouds)
1980                 {
1981                         clouds->step(dtime);
1982                         clouds->update(v2f(player_position.X, player_position.Z),
1983                                         0.05+brightness*0.95);
1984                 }
1985                 
1986                 /*
1987                         Update farmesh
1988                 */
1989                 if(farmesh)
1990                 {
1991                         farmesh_range = draw_control.wanted_range * 10;
1992                         if(draw_control.range_all && farmesh_range < 500)
1993                                 farmesh_range = 500;
1994                         if(farmesh_range > 1000)
1995                                 farmesh_range = 1000;
1996
1997                         farmesh->step(dtime);
1998                         farmesh->update(v2f(player_position.X, player_position.Z),
1999                                         0.05+brightness*0.95, farmesh_range);
2000                 }
2001                 
2002                 // Store brightness value
2003                 old_brightness = brightness;
2004
2005                 /*
2006                         Fog
2007                 */
2008                 
2009                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2010                 {
2011                         f32 range;
2012                         if(farmesh)
2013                         {
2014                                 range = BS*farmesh_range;
2015                         }
2016                         else
2017                         {
2018                                 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
2019                                 range *= 0.9;
2020                                 if(draw_control.range_all)
2021                                         range = 100000*BS;
2022                                 /*if(range < 50*BS)
2023                                         range = range * 0.5 + 25*BS;*/
2024                         }
2025
2026                         driver->setFog(
2027                                 bgcolor,
2028                                 video::EFT_FOG_LINEAR,
2029                                 range*0.4,
2030                                 range*1.0,
2031                                 0.01,
2032                                 false, // pixel fog
2033                                 false // range fog
2034                         );
2035                 }
2036                 else
2037                 {
2038                         driver->setFog(
2039                                 bgcolor,
2040                                 video::EFT_FOG_LINEAR,
2041                                 100000*BS,
2042                                 110000*BS,
2043                                 0.01,
2044                                 false, // pixel fog
2045                                 false // range fog
2046                         );
2047                 }
2048
2049                 /*
2050                         Update gui stuff (0ms)
2051                 */
2052
2053                 //TimeTaker guiupdatetimer("Gui updating");
2054                 
2055                 {
2056                         static float drawtime_avg = 0;
2057                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2058                         static float beginscenetime_avg = 0;
2059                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2060                         static float scenetime_avg = 0;
2061                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2062                         static float endscenetime_avg = 0;
2063                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
2064                         
2065                         char temptext[300];
2066                         snprintf(temptext, 300, "Minetest-c55 %s ("
2067                                         "R: range_all=%i"
2068                                         ")"
2069                                         " drawtime=%.0f, beginscenetime=%.0f"
2070                                         ", scenetime=%.0f, endscenetime=%.0f",
2071                                         VERSION_STRING,
2072                                         draw_control.range_all,
2073                                         drawtime_avg,
2074                                         beginscenetime_avg,
2075                                         scenetime_avg,
2076                                         endscenetime_avg
2077                                         );
2078                         
2079                         guitext->setText(narrow_to_wide(temptext).c_str());
2080                 }
2081                 
2082                 {
2083                         char temptext[300];
2084                         snprintf(temptext, 300,
2085                                         "(% .1f, % .1f, % .1f)"
2086                                         " (% .3f < btime_jitter < % .3f"
2087                                         ", dtime_jitter = % .1f %%"
2088                                         ", v_range = %.1f, RTT = %.3f)",
2089                                         player_position.X/BS,
2090                                         player_position.Y/BS,
2091                                         player_position.Z/BS,
2092                                         busytime_jitter1_min_sample,
2093                                         busytime_jitter1_max_sample,
2094                                         dtime_jitter1_max_fraction * 100.0,
2095                                         draw_control.wanted_range,
2096                                         client.getRTT()
2097                                         );
2098
2099                         guitext2->setText(narrow_to_wide(temptext).c_str());
2100                 }
2101                 
2102                 {
2103                         guitext_info->setText(infotext.c_str());
2104                 }
2105                 
2106                 /*
2107                         Get chat messages from client
2108                 */
2109                 {
2110                         // Get new messages
2111                         std::wstring message;
2112                         while(client.getChatMessage(message))
2113                         {
2114                                 chat_lines.push_back(ChatLine(message));
2115                                 /*if(chat_lines.size() > 6)
2116                                 {
2117                                         core::list<ChatLine>::Iterator
2118                                                         i = chat_lines.begin();
2119                                         chat_lines.erase(i);
2120                                 }*/
2121                         }
2122                         // Append them to form the whole static text and throw
2123                         // it to the gui element
2124                         std::wstring whole;
2125                         // This will correspond to the line number counted from
2126                         // top to bottom, from size-1 to 0
2127                         s16 line_number = chat_lines.size();
2128                         // Count of messages to be removed from the top
2129                         u16 to_be_removed_count = 0;
2130                         for(core::list<ChatLine>::Iterator
2131                                         i = chat_lines.begin();
2132                                         i != chat_lines.end(); i++)
2133                         {
2134                                 // After this, line number is valid for this loop
2135                                 line_number--;
2136                                 // Increment age
2137                                 (*i).age += dtime;
2138                                 /*
2139                                         This results in a maximum age of 60*6 to the
2140                                         lowermost line and a maximum of 6 lines
2141                                 */
2142                                 float allowed_age = (6-line_number) * 60.0;
2143
2144                                 if((*i).age > allowed_age)
2145                                 {
2146                                         to_be_removed_count++;
2147                                         continue;
2148                                 }
2149                                 whole += (*i).text + L'\n';
2150                         }
2151                         for(u16 i=0; i<to_be_removed_count; i++)
2152                         {
2153                                 core::list<ChatLine>::Iterator
2154                                                 it = chat_lines.begin();
2155                                 chat_lines.erase(it);
2156                         }
2157                         guitext_chat->setText(whole.c_str());
2158
2159                         // Update gui element size and position
2160
2161                         /*core::rect<s32> rect(
2162                                         10,
2163                                         screensize.Y - guitext_chat_pad_bottom
2164                                                         - text_height*chat_lines.size(),
2165                                         screensize.X - 10,
2166                                         screensize.Y - guitext_chat_pad_bottom
2167                         );*/
2168                         core::rect<s32> rect(
2169                                         10,
2170                                         50,
2171                                         screensize.X - 10,
2172                                         50 + guitext_chat->getTextHeight()
2173                         );
2174
2175                         guitext_chat->setRelativePosition(rect);
2176
2177                         // Don't show chat if empty or profiler is enabled
2178                         if(chat_lines.size() == 0 || show_profiler)
2179                                 guitext_chat->setVisible(false);
2180                         else
2181                                 guitext_chat->setVisible(true);
2182                 }
2183
2184                 /*
2185                         Inventory
2186                 */
2187                 
2188                 static u16 old_selected_item = 65535;
2189                 if(client.getLocalInventoryUpdated()
2190                                 || g_selected_item != old_selected_item)
2191                 {
2192                         client.selectPlayerItem(g_selected_item);
2193                         old_selected_item = g_selected_item;
2194                         //infostream<<"Updating local inventory"<<std::endl;
2195                         client.getLocalInventory(local_inventory);
2196
2197                         // Update wielded tool
2198                         InventoryList *mlist = local_inventory.getList("main");
2199                         InventoryItem *item = NULL;
2200                         if(mlist != NULL)
2201                                 item = mlist->getItem(g_selected_item);
2202                         camera.wield(item, gamedef);
2203                 }
2204                 
2205                 /*
2206                         Send actions returned by the inventory menu
2207                 */
2208                 while(inventory_action_queue.size() != 0)
2209                 {
2210                         InventoryAction *a = inventory_action_queue.pop_front();
2211
2212                         client.sendInventoryAction(a);
2213                         // Eat it
2214                         delete a;
2215                 }
2216
2217                 /*
2218                         Drawing begins
2219                 */
2220
2221                 TimeTaker drawtimer("Drawing");
2222
2223                 
2224                 {
2225                         TimeTaker timer("beginScene");
2226                         driver->beginScene(true, true, bgcolor);
2227                         //driver->beginScene(false, true, bgcolor);
2228                         beginscenetime = timer.stop(true);
2229                 }
2230                 
2231                 //timer3.stop();
2232                 
2233                 //infostream<<"smgr->drawAll()"<<std::endl;
2234                 
2235                 {
2236                         TimeTaker timer("smgr");
2237                         smgr->drawAll();
2238                         scenetime = timer.stop(true);
2239                 }
2240                 
2241                 {
2242                 //TimeTaker timer9("auxiliary drawings");
2243                 // 0ms
2244                 
2245                 //timer9.stop();
2246                 //TimeTaker //timer10("//timer10");
2247                 
2248                 video::SMaterial m;
2249                 //m.Thickness = 10;
2250                 m.Thickness = 3;
2251                 m.Lighting = false;
2252                 driver->setMaterial(m);
2253
2254                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2255
2256                 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
2257                                 i != hilightboxes.end(); i++)
2258                 {
2259                         /*infostream<<"hilightbox min="
2260                                         <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2261                                         <<" max="
2262                                         <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2263                                         <<std::endl;*/
2264                         driver->draw3DBox(*i, video::SColor(255,0,0,0));
2265                 }
2266
2267                 /*
2268                         Wielded tool
2269                 */
2270                 {
2271                         // Warning: This clears the Z buffer.
2272                         camera.drawWieldedTool();
2273                 }
2274
2275                 /*
2276                         Post effects
2277                 */
2278                 {
2279                         client.renderPostFx();
2280                 }
2281
2282                 /*
2283                         Frametime log
2284                 */
2285                 if(g_settings->getBool("frametime_graph") == true)
2286                 {
2287                         s32 x = 10;
2288                         for(core::list<float>::Iterator
2289                                         i = frametime_log.begin();
2290                                         i != frametime_log.end();
2291                                         i++)
2292                         {
2293                                 driver->draw2DLine(v2s32(x,50),
2294                                                 v2s32(x,50+(*i)*1000),
2295                                                 video::SColor(255,255,255,255));
2296                                 x++;
2297                         }
2298                 }
2299
2300                 /*
2301                         Draw crosshair
2302                 */
2303                 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2304                                 displaycenter + core::vector2d<s32>(10,0),
2305                                 video::SColor(255,255,255,255));
2306                 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2307                                 displaycenter + core::vector2d<s32>(0,10),
2308                                 video::SColor(255,255,255,255));
2309
2310                 } // timer
2311
2312                 //timer10.stop();
2313                 //TimeTaker //timer11("//timer11");
2314
2315                 /*
2316                         Draw gui
2317                 */
2318                 // 0-1ms
2319                 guienv->drawAll();
2320
2321                 /*
2322                         Draw hotbar
2323                 */
2324                 {
2325                         draw_hotbar(driver, font, tsrc,
2326                                         v2s32(displaycenter.X, screensize.Y),
2327                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2328                                         client.getHP());
2329                 }
2330
2331                 /*
2332                         Damage flash
2333                 */
2334                 if(damage_flash_timer > 0.0)
2335                 {
2336                         damage_flash_timer -= dtime;
2337                         
2338                         video::SColor color(128,255,0,0);
2339                         driver->draw2DRectangle(color,
2340                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2341                                         NULL);
2342                 }
2343
2344                 /*
2345                         End scene
2346                 */
2347                 {
2348                         TimeTaker timer("endScene");
2349                         endSceneX(driver);
2350                         endscenetime = timer.stop(true);
2351                 }
2352
2353                 drawtime = drawtimer.stop(true);
2354
2355                 /*
2356                         End of drawing
2357                 */
2358
2359                 static s16 lastFPS = 0;
2360                 //u16 fps = driver->getFPS();
2361                 u16 fps = (1.0/dtime_avg1);
2362
2363                 if (lastFPS != fps)
2364                 {
2365                         core::stringw str = L"Minetest [";
2366                         str += driver->getName();
2367                         str += "] FPS=";
2368                         str += fps;
2369
2370                         device->setWindowCaption(str.c_str());
2371                         lastFPS = fps;
2372                 }
2373         }
2374
2375         /*
2376                 Drop stuff
2377         */
2378         if(clouds)
2379                 clouds->drop();
2380         
2381         /*
2382                 Draw a "shutting down" screen, which will be shown while the map
2383                 generator and other stuff quits
2384         */
2385         {
2386                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2387                 draw_load_screen(L"Shutting down stuff...", driver, font);
2388                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2389                 guienv->drawAll();
2390                 driver->endScene();
2391                 gui_shuttingdowntext->remove();*/
2392         }
2393
2394         } // Client scope (must be destructed before destructing *def and tsrc
2395
2396         delete tooldef;
2397         delete tsrc;
2398         delete nodedef;
2399 }
2400
2401