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