]> git.lizzy.rs Git - dragonfireclient.git/blob - src/game.cpp
Lua HUD
[dragonfireclient.git] / src / game.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
26 #include <IGUIFont.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
29 #include "client.h"
30 #include "server.h"
31 #include "guiPauseMenu.h"
32 #include "guiPasswordChange.h"
33 #include "guiVolumeChange.h"
34 #include "guiFormSpecMenu.h"
35 #include "guiTextInputMenu.h"
36 #include "guiDeathScreen.h"
37 #include "tool.h"
38 #include "guiChatConsole.h"
39 #include "config.h"
40 #include "clouds.h"
41 #include "particles.h"
42 #include "camera.h"
43 #include "farmesh.h"
44 #include "mapblock.h"
45 #include "settings.h"
46 #include "profiler.h"
47 #include "mainmenumanager.h"
48 #include "gettext.h"
49 #include "log.h"
50 #include "filesys.h"
51 // Needed for determining pointing to nodes
52 #include "nodedef.h"
53 #include "nodemetadata.h"
54 #include "main.h" // For g_settings
55 #include "itemdef.h"
56 #include "tile.h" // For TextureSource
57 #include "shader.h" // For ShaderSource
58 #include "logoutputbuffer.h"
59 #include "subgame.h"
60 #include "quicktune_shortcutter.h"
61 #include "clientmap.h"
62 #include "sky.h"
63 #include "sound.h"
64 #if USE_SOUND
65         #include "sound_openal.h"
66 #endif
67 #include "event_manager.h"
68 #include <list>
69 #include "util/directiontables.h"
70
71 /*
72         Text input system
73 */
74
75 struct TextDestChat : public TextDest
76 {
77         TextDestChat(Client *client)
78         {
79                 m_client = client;
80         }
81         void gotText(std::wstring text)
82         {
83                 m_client->typeChatMessage(text);
84         }
85         void gotText(std::map<std::string, std::string> fields)
86         {
87                 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
88         }
89
90         Client *m_client;
91 };
92
93 struct TextDestNodeMetadata : public TextDest
94 {
95         TextDestNodeMetadata(v3s16 p, Client *client)
96         {
97                 m_p = p;
98                 m_client = client;
99         }
100         // This is deprecated I guess? -celeron55
101         void gotText(std::wstring text)
102         {
103                 std::string ntext = wide_to_narrow(text);
104                 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
105                                 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
106                 std::map<std::string, std::string> fields;
107                 fields["text"] = ntext;
108                 m_client->sendNodemetaFields(m_p, "", fields);
109         }
110         void gotText(std::map<std::string, std::string> fields)
111         {
112                 m_client->sendNodemetaFields(m_p, "", fields);
113         }
114
115         v3s16 m_p;
116         Client *m_client;
117 };
118
119 struct TextDestPlayerInventory : public TextDest
120 {
121         TextDestPlayerInventory(Client *client)
122         {
123                 m_client = client;
124                 m_formname = "";
125         }
126         TextDestPlayerInventory(Client *client, std::string formname)
127         {
128                 m_client = client;
129                 m_formname = formname;
130         }
131         void gotText(std::map<std::string, std::string> fields)
132         {
133                 m_client->sendInventoryFields(m_formname, fields);
134         }
135
136         Client *m_client;
137         std::string m_formname;
138 };
139
140 /* Respawn menu callback */
141
142 class MainRespawnInitiator: public IRespawnInitiator
143 {
144 public:
145         MainRespawnInitiator(bool *active, Client *client):
146                 m_active(active), m_client(client)
147         {
148                 *m_active = true;
149         }
150         void respawn()
151         {
152                 *m_active = false;
153                 m_client->sendRespawn();
154         }
155 private:
156         bool *m_active;
157         Client *m_client;
158 };
159
160 /* Form update callback */
161
162 class NodeMetadataFormSource: public IFormSource
163 {
164 public:
165         NodeMetadataFormSource(ClientMap *map, v3s16 p):
166                 m_map(map),
167                 m_p(p)
168         {
169         }
170         std::string getForm()
171         {
172                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
173                 if(!meta)
174                         return "";
175                 return meta->getString("formspec");
176         }
177         std::string resolveText(std::string str)
178         {
179                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
180                 if(!meta)
181                         return str;
182                 return meta->resolveString(str);
183         }
184
185         ClientMap *m_map;
186         v3s16 m_p;
187 };
188
189 class PlayerInventoryFormSource: public IFormSource
190 {
191 public:
192         PlayerInventoryFormSource(Client *client):
193                 m_client(client)
194         {
195         }
196         std::string getForm()
197         {
198                 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
199                 return player->inventory_formspec;
200         }
201
202         Client *m_client;
203 };
204
205 class FormspecFormSource: public IFormSource
206 {
207 public:
208         FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
209         {
210                 m_formspec = formspec;
211                 m_game_formspec = game_formspec;
212         }
213
214         ~FormspecFormSource()
215         {
216                 *m_game_formspec = 0;
217         }
218
219         void setForm(std::string formspec) {
220                 m_formspec = formspec;
221         }
222
223         std::string getForm()
224         {
225                 return m_formspec;
226         }
227
228         std::string m_formspec;
229         FormspecFormSource** m_game_formspec;
230 };
231
232 /*
233         Item draw routine
234 */
235 void draw_item(video::IVideoDriver *driver, gui::IGUIFont *font, IGameDef *gamedef,
236                 v2s32 upperleftpos, s32 imgsize, s32 itemcount,
237                 InventoryList *mainlist, u16 selectitem, unsigned short int direction)
238                 //NOTE: selectitem = 0 -> no selected; selectitem 1-based
239                 //NOTE: direction: 0-> left-right, 1-> right-left, 2->top-bottom, 3->bottom-top
240 {
241         s32 padding = imgsize/12;
242         s32 height = imgsize + padding*2;
243         s32 width = itemcount*(imgsize+padding*2);
244         if(direction == 2 or direction == 3){
245                 width = imgsize + padding*2;
246                 height = itemcount*(imgsize+padding*2);
247         }
248         s32 fullimglen = imgsize + padding*2;
249
250         // Position of upper left corner of bar
251         v2s32 pos = upperleftpos;
252
253         // Draw background color
254         /*core::rect<s32> barrect(0,0,width,height);
255         barrect += pos;
256         video::SColor bgcolor(255,128,128,128);
257         driver->draw2DRectangle(bgcolor, barrect, NULL);*/
258
259         core::rect<s32> imgrect(0,0,imgsize,imgsize);
260
261         for(s32 i=0; i<itemcount; i++)
262         {
263                 const ItemStack &item = mainlist->getItem(i);
264
265                 v2s32 steppos;
266                 if(direction == 1){
267                         steppos = v2s32(-(padding+i*fullimglen), padding);
268                 } else if(direction == 2) {
269                         steppos = v2s32(padding, padding+i*fullimglen);
270                 } else if(direction == 3) {
271                         steppos = v2s32(padding, -(padding+i*fullimglen));
272                 } else {
273                         steppos = v2s32(padding+i*fullimglen, padding);
274                 }
275                 core::rect<s32> rect = imgrect + pos
276                                 + steppos;
277
278                 if(selectitem == (i+1))
279                 {
280                         video::SColor c_outside(255,255,0,0);
281                         //video::SColor c_outside(255,0,0,0);
282                         //video::SColor c_inside(255,192,192,192);
283                         s32 x1 = rect.UpperLeftCorner.X;
284                         s32 y1 = rect.UpperLeftCorner.Y;
285                         s32 x2 = rect.LowerRightCorner.X;
286                         s32 y2 = rect.LowerRightCorner.Y;
287                         // Black base borders
288                         driver->draw2DRectangle(c_outside,
289                                         core::rect<s32>(
290                                                 v2s32(x1 - padding, y1 - padding),
291                                                 v2s32(x2 + padding, y1)
292                                         ), NULL);
293                         driver->draw2DRectangle(c_outside,
294                                         core::rect<s32>(
295                                                 v2s32(x1 - padding, y2),
296                                                 v2s32(x2 + padding, y2 + padding)
297                                         ), NULL);
298                         driver->draw2DRectangle(c_outside,
299                                         core::rect<s32>(
300                                                 v2s32(x1 - padding, y1),
301                                                 v2s32(x1, y2)
302                                         ), NULL);
303                         driver->draw2DRectangle(c_outside,
304                                         core::rect<s32>(
305                                                 v2s32(x2, y1),
306                                                 v2s32(x2 + padding, y2)
307                                         ), NULL);
308                         /*// Light inside borders
309                         driver->draw2DRectangle(c_inside,
310                                         core::rect<s32>(
311                                                 v2s32(x1 - padding/2, y1 - padding/2),
312                                                 v2s32(x2 + padding/2, y1)
313                                         ), NULL);
314                         driver->draw2DRectangle(c_inside,
315                                         core::rect<s32>(
316                                                 v2s32(x1 - padding/2, y2),
317                                                 v2s32(x2 + padding/2, y2 + padding/2)
318                                         ), NULL);
319                         driver->draw2DRectangle(c_inside,
320                                         core::rect<s32>(
321                                                 v2s32(x1 - padding/2, y1),
322                                                 v2s32(x1, y2)
323                                         ), NULL);
324                         driver->draw2DRectangle(c_inside,
325                                         core::rect<s32>(
326                                                 v2s32(x2, y1),
327                                                 v2s32(x2 + padding/2, y2)
328                                         ), NULL);
329                         */
330                 }
331
332                 video::SColor bgcolor2(128,0,0,0);
333                 driver->draw2DRectangle(bgcolor2, rect, NULL);
334                 drawItemStack(driver, font, item, rect, NULL, gamedef);
335         }
336 }
337
338 /*
339         Statbar draw routine
340 */
341 void draw_statbar(video::IVideoDriver *driver, gui::IGUIFont *font, IGameDef *gamedef,
342                 v2s32 upperleftpos, std::string texture, s32 count)
343                 //NOTE: selectitem = 0 -> no selected; selectitem 1-based
344                 //NOTE: direction: 0-> left-right, 1-> right-left, 2->top-bottom, 3->bottom-top
345 {
346         video::ITexture *stat_texture =
347                 gamedef->getTextureSource()->getTextureRaw(texture);
348         if(stat_texture)
349         {
350                 v2s32 p = upperleftpos;
351                 for(s32 i=0; i<count/2; i++)
352                 {
353                         core::dimension2di srcd(stat_texture->getOriginalSize());
354                         const video::SColor color(255,255,255,255);
355                         const video::SColor colors[] = {color,color,color,color};
356                         core::rect<s32> rect(0,0,srcd.Width,srcd.Height);
357                         rect += p;
358                         driver->draw2DImage(stat_texture, rect,
359                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
360                                 NULL, colors, true);
361                         p += v2s32(srcd.Width,0);
362                 }
363                 if(count % 2 == 1)
364                 {
365                         core::dimension2di srcd(stat_texture->getOriginalSize());
366                         const video::SColor color(255,255,255,255);
367                         const video::SColor colors[] = {color,color,color,color};
368                         core::rect<s32> rect(0,0,srcd.Width/2,srcd.Height);
369                         rect += p;
370                         srcd.Width /= 2;
371                         driver->draw2DImage(stat_texture, rect,
372                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
373                                 NULL, colors, true);
374                         p += v2s32(srcd.Width*2,0);
375                 }
376         }
377 }
378
379 /*
380         Hotbar draw routine
381 */
382 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
383                 IGameDef *gamedef,
384                 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
385                 Inventory *inventory, s32 halfheartcount, u16 playeritem)
386 {
387         InventoryList *mainlist = inventory->getList("main");
388         if(mainlist == NULL)
389         {
390                 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
391                 return;
392         }
393 #if 0
394         s32 padding = imgsize/12;
395         //s32 height = imgsize + padding*2;
396         s32 width = itemcount*(imgsize+padding*2);
397         
398         // Position of upper left corner of bar
399         v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
400         
401         // Draw background color
402         /*core::rect<s32> barrect(0,0,width,height);
403         barrect += pos;
404         video::SColor bgcolor(255,128,128,128);
405         driver->draw2DRectangle(bgcolor, barrect, NULL);*/
406
407         core::rect<s32> imgrect(0,0,imgsize,imgsize);
408
409         for(s32 i=0; i<itemcount; i++)
410         {
411                 const ItemStack &item = mainlist->getItem(i);
412                 
413                 core::rect<s32> rect = imgrect + pos
414                                 + v2s32(padding+i*(imgsize+padding*2), padding);
415                 
416                 if(playeritem == i)
417                 {
418                         video::SColor c_outside(255,255,0,0);
419                         //video::SColor c_outside(255,0,0,0);
420                         //video::SColor c_inside(255,192,192,192);
421                         s32 x1 = rect.UpperLeftCorner.X;
422                         s32 y1 = rect.UpperLeftCorner.Y;
423                         s32 x2 = rect.LowerRightCorner.X;
424                         s32 y2 = rect.LowerRightCorner.Y;
425                         // Black base borders
426                         driver->draw2DRectangle(c_outside,
427                                         core::rect<s32>(
428                                                 v2s32(x1 - padding, y1 - padding),
429                                                 v2s32(x2 + padding, y1)
430                                         ), NULL);
431                         driver->draw2DRectangle(c_outside,
432                                         core::rect<s32>(
433                                                 v2s32(x1 - padding, y2),
434                                                 v2s32(x2 + padding, y2 + padding)
435                                         ), NULL);
436                         driver->draw2DRectangle(c_outside,
437                                         core::rect<s32>(
438                                                 v2s32(x1 - padding, y1),
439                                                 v2s32(x1, y2)
440                                         ), NULL);
441                         driver->draw2DRectangle(c_outside,
442                                         core::rect<s32>(
443                                                 v2s32(x2, y1),
444                                                 v2s32(x2 + padding, y2)
445                                         ), NULL);
446                         /*// Light inside borders
447                         driver->draw2DRectangle(c_inside,
448                                         core::rect<s32>(
449                                                 v2s32(x1 - padding/2, y1 - padding/2),
450                                                 v2s32(x2 + padding/2, y1)
451                                         ), NULL);
452                         driver->draw2DRectangle(c_inside,
453                                         core::rect<s32>(
454                                                 v2s32(x1 - padding/2, y2),
455                                                 v2s32(x2 + padding/2, y2 + padding/2)
456                                         ), NULL);
457                         driver->draw2DRectangle(c_inside,
458                                         core::rect<s32>(
459                                                 v2s32(x1 - padding/2, y1),
460                                                 v2s32(x1, y2)
461                                         ), NULL);
462                         driver->draw2DRectangle(c_inside,
463                                         core::rect<s32>(
464                                                 v2s32(x2, y1),
465                                                 v2s32(x2 + padding/2, y2)
466                                         ), NULL);
467                         */
468                 }
469
470                 video::SColor bgcolor2(128,0,0,0);
471                 driver->draw2DRectangle(bgcolor2, rect, NULL);
472                 drawItemStack(driver, font, item, rect, NULL, gamedef);
473         }
474 #else
475         s32 padding = imgsize/12;
476         s32 width = itemcount*(imgsize+padding*2);
477         v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
478         draw_item(driver, font, gamedef, pos, imgsize, itemcount,
479                                 mainlist, playeritem + 1, 0);
480 #endif
481 #if 0
482         /*
483                 Draw hearts
484         */
485         video::ITexture *heart_texture =
486                 gamedef->getTextureSource()->getTextureRaw("heart.png");
487         if(heart_texture)
488         {
489                 v2s32 p = pos + v2s32(0, -20);
490                 for(s32 i=0; i<halfheartcount/2; i++)
491                 {
492                         const video::SColor color(255,255,255,255);
493                         const video::SColor colors[] = {color,color,color,color};
494                         core::rect<s32> rect(0,0,16,16);
495                         rect += p;
496                         driver->draw2DImage(heart_texture, rect,
497                                 core::rect<s32>(core::position2d<s32>(0,0),
498                                 core::dimension2di(heart_texture->getOriginalSize())),
499                                 NULL, colors, true);
500                         p += v2s32(16,0);
501                 }
502                 if(halfheartcount % 2 == 1)
503                 {
504                         const video::SColor color(255,255,255,255);
505                         const video::SColor colors[] = {color,color,color,color};
506                         core::rect<s32> rect(0,0,16/2,16);
507                         rect += p;
508                         core::dimension2di srcd(heart_texture->getOriginalSize());
509                         srcd.Width /= 2;
510                         driver->draw2DImage(heart_texture, rect,
511                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
512                                 NULL, colors, true);
513                         p += v2s32(16,0);
514                 }
515         }
516 #else
517         draw_statbar(driver, font, gamedef, pos + v2s32(0, -20),
518                 "heart.png", halfheartcount);
519 #endif
520 }
521
522 /*
523         Check if a node is pointable
524 */
525 inline bool isPointableNode(const MapNode& n,
526                 Client *client, bool liquids_pointable)
527 {
528         const ContentFeatures &features = client->getNodeDefManager()->get(n);
529         return features.pointable ||
530                 (liquids_pointable && features.isLiquid());
531 }
532
533 /*
534         Find what the player is pointing at
535 */
536 PointedThing getPointedThing(Client *client, v3f player_position,
537                 v3f camera_direction, v3f camera_position,
538                 core::line3d<f32> shootline, f32 d,
539                 bool liquids_pointable,
540                 bool look_for_object,
541                 std::vector<aabb3f> &hilightboxes,
542                 ClientActiveObject *&selected_object)
543 {
544         PointedThing result;
545
546         hilightboxes.clear();
547         selected_object = NULL;
548
549         INodeDefManager *nodedef = client->getNodeDefManager();
550         ClientMap &map = client->getEnv().getClientMap();
551
552         // First try to find a pointed at active object
553         if(look_for_object)
554         {
555                 selected_object = client->getSelectedActiveObject(d*BS,
556                                 camera_position, shootline);
557
558                 if(selected_object != NULL)
559                 {
560                         if(selected_object->doShowSelectionBox())
561                         {
562                                 aabb3f *selection_box = selected_object->getSelectionBox();
563                                 // Box should exist because object was
564                                 // returned in the first place
565                                 assert(selection_box);
566
567                                 v3f pos = selected_object->getPosition();
568                                 hilightboxes.push_back(aabb3f(
569                                                 selection_box->MinEdge + pos,
570                                                 selection_box->MaxEdge + pos));
571                         }
572
573
574                         result.type = POINTEDTHING_OBJECT;
575                         result.object_id = selected_object->getId();
576                         return result;
577                 }
578         }
579
580         // That didn't work, try to find a pointed at node
581
582         f32 mindistance = BS * 1001;
583         
584         v3s16 pos_i = floatToInt(player_position, BS);
585
586         /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
587                         <<std::endl;*/
588
589         s16 a = d;
590         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
591         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
592         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
593         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
594         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
595         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
596         
597         // Prevent signed number overflow
598         if(yend==32767)
599                 yend=32766;
600         if(zend==32767)
601                 zend=32766;
602         if(xend==32767)
603                 xend=32766;
604
605         for(s16 y = ystart; y <= yend; y++)
606         for(s16 z = zstart; z <= zend; z++)
607         for(s16 x = xstart; x <= xend; x++)
608         {
609                 MapNode n;
610                 try
611                 {
612                         n = map.getNode(v3s16(x,y,z));
613                 }
614                 catch(InvalidPositionException &e)
615                 {
616                         continue;
617                 }
618                 if(!isPointableNode(n, client, liquids_pointable))
619                         continue;
620
621                 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
622
623                 v3s16 np(x,y,z);
624                 v3f npf = intToFloat(np, BS);
625
626                 for(std::vector<aabb3f>::const_iterator
627                                 i = boxes.begin();
628                                 i != boxes.end(); i++)
629                 {
630                         aabb3f box = *i;
631                         box.MinEdge += npf;
632                         box.MaxEdge += npf;
633
634                         for(u16 j=0; j<6; j++)
635                         {
636                                 v3s16 facedir = g_6dirs[j];
637                                 aabb3f facebox = box;
638
639                                 f32 d = 0.001*BS;
640                                 if(facedir.X > 0)
641                                         facebox.MinEdge.X = facebox.MaxEdge.X-d;
642                                 else if(facedir.X < 0)
643                                         facebox.MaxEdge.X = facebox.MinEdge.X+d;
644                                 else if(facedir.Y > 0)
645                                         facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
646                                 else if(facedir.Y < 0)
647                                         facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
648                                 else if(facedir.Z > 0)
649                                         facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
650                                 else if(facedir.Z < 0)
651                                         facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
652
653                                 v3f centerpoint = facebox.getCenter();
654                                 f32 distance = (centerpoint - camera_position).getLength();
655                                 if(distance >= mindistance)
656                                         continue;
657                                 if(!facebox.intersectsWithLine(shootline))
658                                         continue;
659
660                                 v3s16 np_above = np + facedir;
661
662                                 result.type = POINTEDTHING_NODE;
663                                 result.node_undersurface = np;
664                                 result.node_abovesurface = np_above;
665                                 mindistance = distance;
666
667                                 hilightboxes.clear();
668                                 for(std::vector<aabb3f>::const_iterator
669                                                 i2 = boxes.begin();
670                                                 i2 != boxes.end(); i2++)
671                                 {
672                                         aabb3f box = *i2;
673                                         box.MinEdge += npf + v3f(-d,-d,-d);
674                                         box.MaxEdge += npf + v3f(d,d,d);
675                                         hilightboxes.push_back(box);
676                                 }
677                         }
678                 }
679         } // for coords
680
681         return result;
682 }
683
684 /*
685         Draws a screen with a single text on it.
686         Text will be removed when the screen is drawn the next time.
687 */
688 /*gui::IGUIStaticText **/
689 void draw_load_screen(const std::wstring &text,
690                 video::IVideoDriver* driver, gui::IGUIFont* font)
691 {
692         v2u32 screensize = driver->getScreenSize();
693         const wchar_t *loadingtext = text.c_str();
694         core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
695         core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
696         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
697         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
698
699         gui::IGUIStaticText *guitext = guienv->addStaticText(
700                         loadingtext, textrect, false, false);
701         guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
702
703         driver->beginScene(true, true, video::SColor(255,0,0,0));
704         guienv->drawAll();
705         driver->endScene();
706         
707         guitext->remove();
708         
709         //return guitext;
710 }
711
712 /* Profiler display */
713
714 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
715                 gui::IGUIFont *font, u32 text_height,
716                 u32 show_profiler, u32 show_profiler_max)
717 {
718         if(show_profiler == 0)
719         {
720                 guitext_profiler->setVisible(false);
721         }
722         else
723         {
724
725                 std::ostringstream os(std::ios_base::binary);
726                 g_profiler->printPage(os, show_profiler, show_profiler_max);
727                 std::wstring text = narrow_to_wide(os.str());
728                 guitext_profiler->setText(text.c_str());
729                 guitext_profiler->setVisible(true);
730
731                 s32 w = font->getDimension(text.c_str()).Width;
732                 if(w < 400)
733                         w = 400;
734                 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
735                                 8+(text_height+5)*2 +
736                                 font->getDimension(text.c_str()).Height);
737                 guitext_profiler->setRelativePosition(rect);
738                 guitext_profiler->setVisible(true);
739         }
740 }
741
742 class ProfilerGraph
743 {
744 private:
745         struct Piece{
746                 Profiler::GraphValues values;
747         };
748         struct Meta{
749                 float min;
750                 float max;
751                 video::SColor color;
752                 Meta(float initial=0, video::SColor color=
753                                 video::SColor(255,255,255,255)):
754                         min(initial),
755                         max(initial),
756                         color(color)
757                 {}
758         };
759         std::list<Piece> m_log;
760 public:
761         u32 m_log_max_size;
762
763         ProfilerGraph():
764                 m_log_max_size(200)
765         {}
766
767         void put(const Profiler::GraphValues &values)
768         {
769                 Piece piece;
770                 piece.values = values;
771                 m_log.push_back(piece);
772                 while(m_log.size() > m_log_max_size)
773                         m_log.erase(m_log.begin());
774         }
775         
776         void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
777                         gui::IGUIFont* font) const
778         {
779                 std::map<std::string, Meta> m_meta;
780                 for(std::list<Piece>::const_iterator k = m_log.begin();
781                                 k != m_log.end(); k++)
782                 {
783                         const Piece &piece = *k;
784                         for(Profiler::GraphValues::const_iterator i = piece.values.begin();
785                                         i != piece.values.end(); i++){
786                                 const std::string &id = i->first;
787                                 const float &value = i->second;
788                                 std::map<std::string, Meta>::iterator j =
789                                                 m_meta.find(id);
790                                 if(j == m_meta.end()){
791                                         m_meta[id] = Meta(value);
792                                         continue;
793                                 }
794                                 if(value < j->second.min)
795                                         j->second.min = value;
796                                 if(value > j->second.max)
797                                         j->second.max = value;
798                         }
799                 }
800
801                 // Assign colors
802                 static const video::SColor usable_colors[] = {
803                         video::SColor(255,255,100,100),
804                         video::SColor(255,90,225,90),
805                         video::SColor(255,100,100,255),
806                         video::SColor(255,255,150,50),
807                         video::SColor(255,220,220,100)
808                 };
809                 static const u32 usable_colors_count =
810                                 sizeof(usable_colors) / sizeof(*usable_colors);
811                 u32 next_color_i = 0;
812                 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
813                                 i != m_meta.end(); i++){
814                         Meta &meta = i->second;
815                         video::SColor color(255,200,200,200);
816                         if(next_color_i < usable_colors_count)
817                                 color = usable_colors[next_color_i++];
818                         meta.color = color;
819                 }
820
821                 s32 graphh = 50;
822                 s32 textx = x_left + m_log_max_size + 15;
823                 s32 textx2 = textx + 200 - 15;
824                 
825                 // Draw background
826                 /*{
827                         u32 num_graphs = m_meta.size();
828                         core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
829                                         textx2, y_bottom);
830                         video::SColor bgcolor(120,0,0,0);
831                         driver->draw2DRectangle(bgcolor, rect, NULL);
832                 }*/
833                 
834                 s32 meta_i = 0;
835                 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
836                                 i != m_meta.end(); i++){
837                         const std::string &id = i->first;
838                         const Meta &meta = i->second;
839                         s32 x = x_left;
840                         s32 y = y_bottom - meta_i * 50;
841                         float show_min = meta.min;
842                         float show_max = meta.max;
843                         if(show_min >= -0.0001 && show_max >= -0.0001){
844                                 if(show_min <= show_max * 0.5)
845                                         show_min = 0;
846                         }
847                         s32 texth = 15;
848                         char buf[10];
849                         snprintf(buf, 10, "%.3g", show_max);
850                         font->draw(narrow_to_wide(buf).c_str(),
851                                         core::rect<s32>(textx, y - graphh,
852                                         textx2, y - graphh + texth),
853                                         meta.color);
854                         snprintf(buf, 10, "%.3g", show_min);
855                         font->draw(narrow_to_wide(buf).c_str(),
856                                         core::rect<s32>(textx, y - texth,
857                                         textx2, y),
858                                         meta.color);
859                         font->draw(narrow_to_wide(id).c_str(),
860                                         core::rect<s32>(textx, y - graphh/2 - texth/2,
861                                         textx2, y - graphh/2 + texth/2),
862                                         meta.color);
863                         s32 graph1y = y;
864                         s32 graph1h = graphh;
865                         bool relativegraph = (show_min != 0 && show_min != show_max);
866                         float lastscaledvalue = 0.0;
867                         bool lastscaledvalue_exists = false;
868                         for(std::list<Piece>::const_iterator j = m_log.begin();
869                                         j != m_log.end(); j++)
870                         {
871                                 const Piece &piece = *j;
872                                 float value = 0;
873                                 bool value_exists = false;
874                                 Profiler::GraphValues::const_iterator k =
875                                                 piece.values.find(id);
876                                 if(k != piece.values.end()){
877                                         value = k->second;
878                                         value_exists = true;
879                                 }
880                                 if(!value_exists){
881                                         x++;
882                                         lastscaledvalue_exists = false;
883                                         continue;
884                                 }
885                                 float scaledvalue = 1.0;
886                                 if(show_max != show_min)
887                                         scaledvalue = (value - show_min) / (show_max - show_min);
888                                 if(scaledvalue == 1.0 && value == 0){
889                                         x++;
890                                         lastscaledvalue_exists = false;
891                                         continue;
892                                 }
893                                 if(relativegraph){
894                                         if(lastscaledvalue_exists){
895                                                 s32 ivalue1 = lastscaledvalue * graph1h;
896                                                 s32 ivalue2 = scaledvalue * graph1h;
897                                                 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
898                                                                 v2s32(x, graph1y - ivalue2), meta.color);
899                                         }
900                                         lastscaledvalue = scaledvalue;
901                                         lastscaledvalue_exists = true;
902                                 } else{
903                                         s32 ivalue = scaledvalue * graph1h;
904                                         driver->draw2DLine(v2s32(x, graph1y),
905                                                         v2s32(x, graph1y - ivalue), meta.color);
906                                 }
907                                 x++;
908                         }
909                         meta_i++;
910                 }
911         }
912 };
913
914 class NodeDugEvent: public MtEvent
915 {
916 public:
917         v3s16 p;
918         MapNode n;
919         
920         NodeDugEvent(v3s16 p, MapNode n):
921                 p(p),
922                 n(n)
923         {}
924         const char* getType() const
925         {return "NodeDug";}
926 };
927
928 class SoundMaker
929 {
930         ISoundManager *m_sound;
931         INodeDefManager *m_ndef;
932 public:
933         float m_player_step_timer;
934
935         SimpleSoundSpec m_player_step_sound;
936         SimpleSoundSpec m_player_leftpunch_sound;
937         SimpleSoundSpec m_player_rightpunch_sound;
938
939         SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
940                 m_sound(sound),
941                 m_ndef(ndef),
942                 m_player_step_timer(0)
943         {
944         }
945
946         void playPlayerStep()
947         {
948                 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
949                         m_player_step_timer = 0.03;
950                         m_sound->playSound(m_player_step_sound, false);
951                 }
952         }
953
954         static void viewBobbingStep(MtEvent *e, void *data)
955         {
956                 SoundMaker *sm = (SoundMaker*)data;
957                 sm->playPlayerStep();
958         }
959
960         static void playerRegainGround(MtEvent *e, void *data)
961         {
962                 SoundMaker *sm = (SoundMaker*)data;
963                 sm->playPlayerStep();
964         }
965
966         static void playerJump(MtEvent *e, void *data)
967         {
968                 //SoundMaker *sm = (SoundMaker*)data;
969         }
970
971         static void cameraPunchLeft(MtEvent *e, void *data)
972         {
973                 SoundMaker *sm = (SoundMaker*)data;
974                 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
975         }
976
977         static void cameraPunchRight(MtEvent *e, void *data)
978         {
979                 SoundMaker *sm = (SoundMaker*)data;
980                 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
981         }
982
983         static void nodeDug(MtEvent *e, void *data)
984         {
985                 SoundMaker *sm = (SoundMaker*)data;
986                 NodeDugEvent *nde = (NodeDugEvent*)e;
987                 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
988         }
989
990         void registerReceiver(MtEventManager *mgr)
991         {
992                 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
993                 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
994                 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
995                 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
996                 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
997                 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
998         }
999
1000         void step(float dtime)
1001         {
1002                 m_player_step_timer -= dtime;
1003         }
1004 };
1005
1006 // Locally stored sounds don't need to be preloaded because of this
1007 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
1008 {
1009         std::set<std::string> m_fetched;
1010 public:
1011
1012         void fetchSounds(const std::string &name,
1013                         std::set<std::string> &dst_paths,
1014                         std::set<std::string> &dst_datas)
1015         {
1016                 if(m_fetched.count(name))
1017                         return;
1018                 m_fetched.insert(name);
1019                 std::string base = porting::path_share + DIR_DELIM + "testsounds";
1020                 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
1021                 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
1022                 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
1023                 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
1024                 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
1025                 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
1026                 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
1027                 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
1028                 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
1029                 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
1030                 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
1031         }
1032 };
1033
1034 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
1035 {
1036         Sky *m_sky;
1037         bool *m_force_fog_off;
1038         f32 *m_fog_range;
1039         Client *m_client;
1040
1041 public:
1042         GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
1043                         f32 *fog_range, Client *client):
1044                 m_sky(sky),
1045                 m_force_fog_off(force_fog_off),
1046                 m_fog_range(fog_range),
1047                 m_client(client)
1048         {}
1049         ~GameGlobalShaderConstantSetter() {}
1050
1051         virtual void onSetConstants(video::IMaterialRendererServices *services,
1052                         bool is_highlevel)
1053         {
1054                 if(!is_highlevel)
1055                         return;
1056
1057                 // Background color
1058                 video::SColor bgcolor = m_sky->getBgColor();
1059                 video::SColorf bgcolorf(bgcolor);
1060                 float bgcolorfa[4] = {
1061                         bgcolorf.r,
1062                         bgcolorf.g,
1063                         bgcolorf.b,
1064                         bgcolorf.a,
1065                 };
1066                 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
1067
1068                 // Fog distance
1069                 float fog_distance = *m_fog_range;
1070                 if(*m_force_fog_off)
1071                         fog_distance = 10000*BS;
1072                 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
1073
1074                 // Day-night ratio
1075                 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
1076                 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
1077                 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
1078         }
1079 };
1080
1081 void the_game(
1082         bool &kill,
1083         bool random_input,
1084         InputHandler *input,
1085         IrrlichtDevice *device,
1086         gui::IGUIFont* font,
1087         std::string map_dir,
1088         std::string playername,
1089         std::string password,
1090         std::string address, // If "", local server is used
1091         u16 port,
1092         std::wstring &error_message,
1093         std::string configpath,
1094         ChatBackend &chat_backend,
1095         const SubgameSpec &gamespec, // Used for local game,
1096         bool simple_singleplayer_mode
1097 )
1098 {
1099         FormspecFormSource* current_formspec = 0;
1100         video::IVideoDriver* driver = device->getVideoDriver();
1101         scene::ISceneManager* smgr = device->getSceneManager();
1102         
1103         // Calculate text height using the font
1104         u32 text_height = font->getDimension(L"Random test string").Height;
1105
1106         v2u32 screensize(0,0);
1107         v2u32 last_screensize(0,0);
1108         screensize = driver->getScreenSize();
1109
1110         const s32 hotbar_itemcount = 8;
1111         //const s32 hotbar_imagesize = 36;
1112         //const s32 hotbar_imagesize = 64;
1113         s32 hotbar_imagesize = 48;
1114         
1115         /*
1116                 Draw "Loading" screen
1117         */
1118
1119         draw_load_screen(L"Loading...", driver, font);
1120         
1121         // Create texture source
1122         IWritableTextureSource *tsrc = createTextureSource(device);
1123         
1124         // Create shader source
1125         IWritableShaderSource *shsrc = createShaderSource(device);
1126         
1127         // These will be filled by data received from the server
1128         // Create item definition manager
1129         IWritableItemDefManager *itemdef = createItemDefManager();
1130         // Create node definition manager
1131         IWritableNodeDefManager *nodedef = createNodeDefManager();
1132         
1133         // Sound fetcher (useful when testing)
1134         GameOnDemandSoundFetcher soundfetcher;
1135
1136         // Sound manager
1137         ISoundManager *sound = NULL;
1138         bool sound_is_dummy = false;
1139 #if USE_SOUND
1140         if(g_settings->getBool("enable_sound")){
1141                 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1142                 sound = createOpenALSoundManager(&soundfetcher);
1143                 if(!sound)
1144                         infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1145         } else {
1146                 infostream<<"Sound disabled."<<std::endl;
1147         }
1148 #endif
1149         if(!sound){
1150                 infostream<<"Using dummy audio."<<std::endl;
1151                 sound = &dummySoundManager;
1152                 sound_is_dummy = true;
1153         }
1154
1155         Server *server = NULL;
1156
1157         try{
1158         // Event manager
1159         EventManager eventmgr;
1160
1161         // Sound maker
1162         SoundMaker soundmaker(sound, nodedef);
1163         soundmaker.registerReceiver(&eventmgr);
1164         
1165         // Add chat log output for errors to be shown in chat
1166         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1167
1168         // Create UI for modifying quicktune values
1169         QuicktuneShortcutter quicktune;
1170
1171         /*
1172                 Create server.
1173         */
1174
1175         if(address == ""){
1176                 draw_load_screen(L"Creating server...", driver, font);
1177                 infostream<<"Creating server"<<std::endl;
1178                 server = new Server(map_dir, configpath, gamespec,
1179                                 simple_singleplayer_mode);
1180                 server->start(port);
1181         }
1182
1183         do{ // Client scope (breakable do-while(0))
1184         
1185         /*
1186                 Create client
1187         */
1188
1189         draw_load_screen(L"Creating client...", driver, font);
1190         infostream<<"Creating client"<<std::endl;
1191         
1192         MapDrawControl draw_control;
1193
1194         Client client(device, playername.c_str(), password, draw_control,
1195                         tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
1196         
1197         // Client acts as our GameDef
1198         IGameDef *gamedef = &client;
1199                         
1200         draw_load_screen(L"Resolving address...", driver, font);
1201         Address connect_address(0,0,0,0, port);
1202         try{
1203                 if(address == "")
1204                         //connect_address.Resolve("localhost");
1205                         connect_address.setAddress(127,0,0,1);
1206                 else
1207                         connect_address.Resolve(address.c_str());
1208         }
1209         catch(ResolveError &e)
1210         {
1211                 error_message = L"Couldn't resolve address";
1212                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1213                 // Break out of client scope
1214                 break;
1215         }
1216
1217         /*
1218                 Attempt to connect to the server
1219         */
1220         
1221         infostream<<"Connecting to server at ";
1222         connect_address.print(&infostream);
1223         infostream<<std::endl;
1224         client.connect(connect_address);
1225         
1226         /*
1227                 Wait for server to accept connection
1228         */
1229         bool could_connect = false;
1230         bool connect_aborted = false;
1231         try{
1232                 float frametime = 0.033;
1233                 float time_counter = 0.0;
1234                 input->clear();
1235                 while(device->run())
1236                 {
1237                         // Update client and server
1238                         client.step(frametime);
1239                         if(server != NULL)
1240                                 server->step(frametime);
1241                         
1242                         // End condition
1243                         if(client.connectedAndInitialized()){
1244                                 could_connect = true;
1245                                 break;
1246                         }
1247                         // Break conditions
1248                         if(client.accessDenied()){
1249                                 error_message = L"Access denied. Reason: "
1250                                                 +client.accessDeniedReason();
1251                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1252                                 break;
1253                         }
1254                         if(input->wasKeyDown(EscapeKey)){
1255                                 connect_aborted = true;
1256                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1257                                 break;
1258                         }
1259                         
1260                         // Display status
1261                         std::wostringstream ss;
1262                         ss<<L"Connecting to server... (press Escape to cancel)\n";
1263                         std::wstring animation = L"/-\\|";
1264                         ss<<animation[(int)(time_counter/0.2)%4];
1265                         draw_load_screen(ss.str(), driver, font);
1266                         
1267                         // Delay a bit
1268                         sleep_ms(1000*frametime);
1269                         time_counter += frametime;
1270                 }
1271         }
1272         catch(con::PeerNotFoundException &e)
1273         {}
1274         
1275         /*
1276                 Handle failure to connect
1277         */
1278         if(!could_connect){
1279                 if(error_message == L"" && !connect_aborted){
1280                         error_message = L"Connection failed";
1281                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1282                 }
1283                 // Break out of client scope
1284                 break;
1285         }
1286         
1287         /*
1288                 Wait until content has been received
1289         */
1290         bool got_content = false;
1291         bool content_aborted = false;
1292         {
1293                 float frametime = 0.033;
1294                 float time_counter = 0.0;
1295                 input->clear();
1296                 while(device->run())
1297                 {
1298                         // Update client and server
1299                         client.step(frametime);
1300                         if(server != NULL)
1301                                 server->step(frametime);
1302                         
1303                         // End condition
1304                         if(client.texturesReceived() &&
1305                                         client.itemdefReceived() &&
1306                                         client.nodedefReceived()){
1307                                 got_content = true;
1308                                 break;
1309                         }
1310                         // Break conditions
1311                         if(!client.connectedAndInitialized()){
1312                                 error_message = L"Client disconnected";
1313                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1314                                 break;
1315                         }
1316                         if(input->wasKeyDown(EscapeKey)){
1317                                 content_aborted = true;
1318                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1319                                 break;
1320                         }
1321                         
1322                         // Display status
1323                         std::wostringstream ss;
1324                         ss<<L"Waiting content... (press Escape to cancel)\n";
1325
1326                         ss<<(client.itemdefReceived()?L"[X]":L"[  ]");
1327                         ss<<L" Item definitions\n";
1328                         ss<<(client.nodedefReceived()?L"[X]":L"[  ]");
1329                         ss<<L" Node definitions\n";
1330                         ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1331                         ss<<L" Media\n";
1332
1333                         draw_load_screen(ss.str(), driver, font);
1334                         
1335                         // Delay a bit
1336                         sleep_ms(1000*frametime);
1337                         time_counter += frametime;
1338                 }
1339         }
1340
1341         if(!got_content){
1342                 if(error_message == L"" && !content_aborted){
1343                         error_message = L"Something failed";
1344                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1345                 }
1346                 // Break out of client scope
1347                 break;
1348         }
1349
1350         /*
1351                 After all content has been received:
1352                 Update cached textures, meshes and materials
1353         */
1354         client.afterContentReceived();
1355
1356         /*
1357                 Create the camera node
1358         */
1359         Camera camera(smgr, draw_control, gamedef);
1360         if (!camera.successfullyCreated(error_message))
1361                 return;
1362
1363         f32 camera_yaw = 0; // "right/left"
1364         f32 camera_pitch = 0; // "up/down"
1365
1366         /*
1367                 Clouds
1368         */
1369         
1370         Clouds *clouds = NULL;
1371         if(g_settings->getBool("enable_clouds"))
1372         {
1373                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1374         }
1375
1376         /*
1377                 Skybox thingy
1378         */
1379
1380         Sky *sky = NULL;
1381         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1382         
1383         /*
1384                 FarMesh
1385         */
1386
1387         FarMesh *farmesh = NULL;
1388         if(g_settings->getBool("enable_farmesh"))
1389         {
1390                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1391         }
1392
1393         /*
1394                 A copy of the local inventory
1395         */
1396         Inventory local_inventory(itemdef);
1397
1398         /*
1399                 Find out size of crack animation
1400         */
1401         int crack_animation_length = 5;
1402         {
1403                 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1404                 v2u32 size = t->getOriginalSize();
1405                 crack_animation_length = size.Y / size.X;
1406         }
1407
1408         /*
1409                 Add some gui stuff
1410         */
1411
1412         // First line of debug text
1413         gui::IGUIStaticText *guitext = guienv->addStaticText(
1414                         L"Minetest",
1415                         core::rect<s32>(5, 5, 795, 5+text_height),
1416                         false, false);
1417         // Second line of debug text
1418         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1419                         L"",
1420                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1421                         false, false);
1422         // At the middle of the screen
1423         // Object infos are shown in this
1424         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1425                         L"",
1426                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1427                         false, true);
1428         
1429         // Status text (displays info when showing and hiding GUI stuff, etc.)
1430         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1431                         L"<Status>",
1432                         core::rect<s32>(0,0,0,0),
1433                         false, false);
1434         guitext_status->setVisible(false);
1435         
1436         std::wstring statustext;
1437         float statustext_time = 0;
1438         
1439         // Chat text
1440         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1441                         L"",
1442                         core::rect<s32>(0,0,0,0),
1443                         //false, false); // Disable word wrap as of now
1444                         false, true);
1445         // Remove stale "recent" chat messages from previous connections
1446         chat_backend.clearRecentChat();
1447         // Chat backend and console
1448         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1449         
1450         // Profiler text (size is updated when text is updated)
1451         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1452                         L"<Profiler>",
1453                         core::rect<s32>(0,0,0,0),
1454                         false, false);
1455         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1456         guitext_profiler->setVisible(false);
1457         
1458         /*
1459                 Some statistics are collected in these
1460         */
1461         u32 drawtime = 0;
1462         u32 beginscenetime = 0;
1463         u32 scenetime = 0;
1464         u32 endscenetime = 0;
1465         
1466         float recent_turn_speed = 0.0;
1467         
1468         ProfilerGraph graph;
1469         // Initially clear the profiler
1470         Profiler::GraphValues dummyvalues;
1471         g_profiler->graphGet(dummyvalues);
1472
1473         float nodig_delay_timer = 0.0;
1474         float dig_time = 0.0;
1475         u16 dig_index = 0;
1476         PointedThing pointed_old;
1477         bool digging = false;
1478         bool ldown_for_dig = false;
1479
1480         float damage_flash = 0;
1481         s16 farmesh_range = 20*MAP_BLOCKSIZE;
1482
1483         float jump_timer = 0;
1484         bool reset_jump_timer = false;
1485
1486         const float object_hit_delay = 0.2;
1487         float object_hit_delay_timer = 0.0;
1488         float time_from_last_punch = 10;
1489
1490         float update_draw_list_timer = 0.0;
1491         v3f update_draw_list_last_cam_dir;
1492
1493         bool invert_mouse = g_settings->getBool("invert_mouse");
1494
1495         bool respawn_menu_active = false;
1496         bool update_wielded_item_trigger = false;
1497
1498         bool show_hud = true;
1499         bool show_chat = true;
1500         bool force_fog_off = false;
1501         f32 fog_range = 100*BS;
1502         bool disable_camera_update = false;
1503         bool show_debug = g_settings->getBool("show_debug");
1504         bool show_profiler_graph = false;
1505         u32 show_profiler = 0;
1506         u32 show_profiler_max = 3;  // Number of pages
1507
1508         float time_of_day = 0;
1509         float time_of_day_smooth = 0;
1510
1511         float repeat_rightclick_timer = 0;
1512
1513         /*
1514                 Shader constants
1515         */
1516         shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1517                         sky, &force_fog_off, &fog_range, &client));
1518
1519         /*
1520                 Main loop
1521         */
1522
1523         bool first_loop_after_window_activation = true;
1524
1525         // TODO: Convert the static interval timers to these
1526         // Interval limiter for profiler
1527         IntervalLimiter m_profiler_interval;
1528
1529         // Time is in milliseconds
1530         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1531         // NOTE: So we have to use getTime() and call run()s between them
1532         u32 lasttime = device->getTimer()->getTime();
1533
1534         LocalPlayer* player = client.getEnv().getLocalPlayer();
1535         player->hurt_tilt_timer = 0;
1536         player->hurt_tilt_strength = 0;
1537
1538         for(;;)
1539         {
1540                 if(device->run() == false || kill == true)
1541                         break;
1542
1543                 // Time of frame without fps limit
1544                 float busytime;
1545                 u32 busytime_u32;
1546                 {
1547                         // not using getRealTime is necessary for wine
1548                         u32 time = device->getTimer()->getTime();
1549                         if(time > lasttime)
1550                                 busytime_u32 = time - lasttime;
1551                         else
1552                                 busytime_u32 = 0;
1553                         busytime = busytime_u32 / 1000.0;
1554                 }
1555                 
1556                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1557
1558                 // Necessary for device->getTimer()->getTime()
1559                 device->run();
1560
1561                 /*
1562                         FPS limiter
1563                 */
1564
1565                 {
1566                         float fps_max = g_settings->getFloat("fps_max");
1567                         u32 frametime_min = 1000./fps_max;
1568                         
1569                         if(busytime_u32 < frametime_min)
1570                         {
1571                                 u32 sleeptime = frametime_min - busytime_u32;
1572                                 device->sleep(sleeptime);
1573                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1574                         }
1575                 }
1576
1577                 // Necessary for device->getTimer()->getTime()
1578                 device->run();
1579
1580                 /*
1581                         Time difference calculation
1582                 */
1583                 f32 dtime; // in seconds
1584                 
1585                 u32 time = device->getTimer()->getTime();
1586                 if(time > lasttime)
1587                         dtime = (time - lasttime) / 1000.0;
1588                 else
1589                         dtime = 0;
1590                 lasttime = time;
1591
1592                 g_profiler->graphAdd("mainloop_dtime", dtime);
1593
1594                 /* Run timers */
1595
1596                 if(nodig_delay_timer >= 0)
1597                         nodig_delay_timer -= dtime;
1598                 if(object_hit_delay_timer >= 0)
1599                         object_hit_delay_timer -= dtime;
1600                 time_from_last_punch += dtime;
1601                 
1602                 g_profiler->add("Elapsed time", dtime);
1603                 g_profiler->avg("FPS", 1./dtime);
1604
1605                 /*
1606                         Time average and jitter calculation
1607                 */
1608
1609                 static f32 dtime_avg1 = 0.0;
1610                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1611                 f32 dtime_jitter1 = dtime - dtime_avg1;
1612
1613                 static f32 dtime_jitter1_max_sample = 0.0;
1614                 static f32 dtime_jitter1_max_fraction = 0.0;
1615                 {
1616                         static f32 jitter1_max = 0.0;
1617                         static f32 counter = 0.0;
1618                         if(dtime_jitter1 > jitter1_max)
1619                                 jitter1_max = dtime_jitter1;
1620                         counter += dtime;
1621                         if(counter > 0.0)
1622                         {
1623                                 counter -= 3.0;
1624                                 dtime_jitter1_max_sample = jitter1_max;
1625                                 dtime_jitter1_max_fraction
1626                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1627                                 jitter1_max = 0.0;
1628                         }
1629                 }
1630                 
1631                 /*
1632                         Busytime average and jitter calculation
1633                 */
1634
1635                 static f32 busytime_avg1 = 0.0;
1636                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1637                 f32 busytime_jitter1 = busytime - busytime_avg1;
1638                 
1639                 static f32 busytime_jitter1_max_sample = 0.0;
1640                 static f32 busytime_jitter1_min_sample = 0.0;
1641                 {
1642                         static f32 jitter1_max = 0.0;
1643                         static f32 jitter1_min = 0.0;
1644                         static f32 counter = 0.0;
1645                         if(busytime_jitter1 > jitter1_max)
1646                                 jitter1_max = busytime_jitter1;
1647                         if(busytime_jitter1 < jitter1_min)
1648                                 jitter1_min = busytime_jitter1;
1649                         counter += dtime;
1650                         if(counter > 0.0){
1651                                 counter -= 3.0;
1652                                 busytime_jitter1_max_sample = jitter1_max;
1653                                 busytime_jitter1_min_sample = jitter1_min;
1654                                 jitter1_max = 0.0;
1655                                 jitter1_min = 0.0;
1656                         }
1657                 }
1658
1659                 /*
1660                         Handle miscellaneous stuff
1661                 */
1662                 
1663                 if(client.accessDenied())
1664                 {
1665                         error_message = L"Access denied. Reason: "
1666                                         +client.accessDeniedReason();
1667                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1668                         break;
1669                 }
1670
1671                 if(g_gamecallback->disconnect_requested)
1672                 {
1673                         g_gamecallback->disconnect_requested = false;
1674                         break;
1675                 }
1676
1677                 if(g_gamecallback->changepassword_requested)
1678                 {
1679                         (new GUIPasswordChange(guienv, guiroot, -1,
1680                                 &g_menumgr, &client))->drop();
1681                         g_gamecallback->changepassword_requested = false;
1682                 }
1683
1684                 if(g_gamecallback->changevolume_requested)
1685                 {
1686                         (new GUIVolumeChange(guienv, guiroot, -1,
1687                                 &g_menumgr, &client))->drop();
1688                         g_gamecallback->changevolume_requested = false;
1689                 }
1690
1691                 /* Process TextureSource's queue */
1692                 tsrc->processQueue();
1693
1694                 /* Process ItemDefManager's queue */
1695                 itemdef->processQueue(gamedef);
1696
1697                 /*
1698                         Process ShaderSource's queue
1699                 */
1700                 shsrc->processQueue();
1701
1702                 /*
1703                         Random calculations
1704                 */
1705                 last_screensize = screensize;
1706                 screensize = driver->getScreenSize();
1707                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1708                 //bool screensize_changed = screensize != last_screensize;
1709
1710                 // Resize hotbar
1711                 if(screensize.Y <= 800)
1712                         hotbar_imagesize = 32;
1713                 else if(screensize.Y <= 1280)
1714                         hotbar_imagesize = 48;
1715                 else
1716                         hotbar_imagesize = 64;
1717                 
1718                 // Hilight boxes collected during the loop and displayed
1719                 std::vector<aabb3f> hilightboxes;
1720                 
1721                 // Info text
1722                 std::wstring infotext;
1723
1724                 /*
1725                         Debug info for client
1726                 */
1727                 {
1728                         static float counter = 0.0;
1729                         counter -= dtime;
1730                         if(counter < 0)
1731                         {
1732                                 counter = 30.0;
1733                                 client.printDebugInfo(infostream);
1734                         }
1735                 }
1736
1737                 /*
1738                         Profiler
1739                 */
1740                 float profiler_print_interval =
1741                                 g_settings->getFloat("profiler_print_interval");
1742                 bool print_to_log = true;
1743                 if(profiler_print_interval == 0){
1744                         print_to_log = false;
1745                         profiler_print_interval = 5;
1746                 }
1747                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1748                 {
1749                         if(print_to_log){
1750                                 infostream<<"Profiler:"<<std::endl;
1751                                 g_profiler->print(infostream);
1752                         }
1753
1754                         update_profiler_gui(guitext_profiler, font, text_height,
1755                                         show_profiler, show_profiler_max);
1756
1757                         g_profiler->clear();
1758                 }
1759
1760                 /*
1761                         Direct handling of user input
1762                 */
1763                 
1764                 // Reset input if window not active or some menu is active
1765                 if(device->isWindowActive() == false
1766                                 || noMenuActive() == false
1767                                 || guienv->hasFocus(gui_chat_console))
1768                 {
1769                         input->clear();
1770                 }
1771
1772                 // Input handler step() (used by the random input generator)
1773                 input->step(dtime);
1774
1775                 // Increase timer for doubleclick of "jump"
1776                 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1777                         jump_timer += dtime;
1778
1779                 /*
1780                         Launch menus and trigger stuff according to keys
1781                 */
1782                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1783                 {
1784                         // drop selected item
1785                         IDropAction *a = new IDropAction();
1786                         a->count = 0;
1787                         a->from_inv.setCurrentPlayer();
1788                         a->from_list = "main";
1789                         a->from_i = client.getPlayerItem();
1790                         client.inventoryAction(a);
1791                 }
1792                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1793                 {
1794                         infostream<<"the_game: "
1795                                         <<"Launching inventory"<<std::endl;
1796                         
1797                         GUIFormSpecMenu *menu =
1798                                 new GUIFormSpecMenu(device, guiroot, -1,
1799                                         &g_menumgr,
1800                                         &client, gamedef);
1801
1802                         InventoryLocation inventoryloc;
1803                         inventoryloc.setCurrentPlayer();
1804
1805                         PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1806                         assert(src);
1807                         menu->setFormSpec(src->getForm(), inventoryloc);
1808                         menu->setFormSource(src);
1809                         menu->setTextDest(new TextDestPlayerInventory(&client));
1810                         menu->drop();
1811                 }
1812                 else if(input->wasKeyDown(EscapeKey))
1813                 {
1814                         infostream<<"the_game: "
1815                                         <<"Launching pause menu"<<std::endl;
1816                         // It will delete itself by itself
1817                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1818                                         &g_menumgr, simple_singleplayer_mode))->drop();
1819
1820                         // Move mouse cursor on top of the disconnect button
1821                         if(simple_singleplayer_mode)
1822                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1823                         else
1824                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1825                 }
1826                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1827                 {
1828                         TextDest *dest = new TextDestChat(&client);
1829
1830                         (new GUITextInputMenu(guienv, guiroot, -1,
1831                                         &g_menumgr, dest,
1832                                         L""))->drop();
1833                 }
1834                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1835                 {
1836                         TextDest *dest = new TextDestChat(&client);
1837
1838                         (new GUITextInputMenu(guienv, guiroot, -1,
1839                                         &g_menumgr, dest,
1840                                         L"/"))->drop();
1841                 }
1842                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1843                 {
1844                         if (!gui_chat_console->isOpenInhibited())
1845                         {
1846                                 // Open up to over half of the screen
1847                                 gui_chat_console->openConsole(0.6);
1848                                 guienv->setFocus(gui_chat_console);
1849                         }
1850                 }
1851                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1852                 {
1853                         if(g_settings->getBool("free_move"))
1854                         {
1855                                 g_settings->set("free_move","false");
1856                                 statustext = L"free_move disabled";
1857                                 statustext_time = 0;
1858                         }
1859                         else
1860                         {
1861                                 g_settings->set("free_move","true");
1862                                 statustext = L"free_move enabled";
1863                                 statustext_time = 0;
1864                                 if(!client.checkPrivilege("fly"))
1865                                         statustext += L" (note: no 'fly' privilege)";
1866                         }
1867                 }
1868                 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1869                 {
1870                         if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1871                         {
1872                                 if(g_settings->getBool("free_move"))
1873                                 {
1874                                         g_settings->set("free_move","false");
1875                                         statustext = L"free_move disabled";
1876                                         statustext_time = 0;
1877                                 }
1878                                 else
1879                                 {
1880                                         g_settings->set("free_move","true");
1881                                         statustext = L"free_move enabled";
1882                                         statustext_time = 0;
1883                                         if(!client.checkPrivilege("fly"))
1884                                                 statustext += L" (note: no 'fly' privilege)";
1885                                 }
1886                         }
1887                         reset_jump_timer = true;
1888                 }
1889                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1890                 {
1891                         if(g_settings->getBool("fast_move"))
1892                         {
1893                                 g_settings->set("fast_move","false");
1894                                 statustext = L"fast_move disabled";
1895                                 statustext_time = 0;
1896                         }
1897                         else
1898                         {
1899                                 g_settings->set("fast_move","true");
1900                                 statustext = L"fast_move enabled";
1901                                 statustext_time = 0;
1902                                 if(!client.checkPrivilege("fast"))
1903                                         statustext += L" (note: no 'fast' privilege)";
1904                         }
1905                 }
1906                 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1907                 {
1908                         if(g_settings->getBool("noclip"))
1909                         {
1910                                 g_settings->set("noclip","false");
1911                                 statustext = L"noclip disabled";
1912                                 statustext_time = 0;
1913                         }
1914                         else
1915                         {
1916                                 g_settings->set("noclip","true");
1917                                 statustext = L"noclip enabled";
1918                                 statustext_time = 0;
1919                                 if(!client.checkPrivilege("noclip"))
1920                                         statustext += L" (note: no 'noclip' privilege)";
1921                         }
1922                 }
1923                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1924                 {
1925                         irr::video::IImage* const image = driver->createScreenShot(); 
1926                         if (image) { 
1927                                 irr::c8 filename[256]; 
1928                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1929                                                  g_settings->get("screenshot_path").c_str(),
1930                                                  device->getTimer()->getRealTime()); 
1931                                 if (driver->writeImageToFile(image, filename)) {
1932                                         std::wstringstream sstr;
1933                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1934                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1935                                         statustext = sstr.str();
1936                                         statustext_time = 0;
1937                                 } else{
1938                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1939                                 }
1940                                 image->drop(); 
1941                         }                        
1942                 }
1943                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1944                 {
1945                         show_hud = !show_hud;
1946                         if(show_hud)
1947                                 statustext = L"HUD shown";
1948                         else
1949                                 statustext = L"HUD hidden";
1950                         statustext_time = 0;
1951                 }
1952                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1953                 {
1954                         show_chat = !show_chat;
1955                         if(show_chat)
1956                                 statustext = L"Chat shown";
1957                         else
1958                                 statustext = L"Chat hidden";
1959                         statustext_time = 0;
1960                 }
1961                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1962                 {
1963                         force_fog_off = !force_fog_off;
1964                         if(force_fog_off)
1965                                 statustext = L"Fog disabled";
1966                         else
1967                                 statustext = L"Fog enabled";
1968                         statustext_time = 0;
1969                 }
1970                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1971                 {
1972                         disable_camera_update = !disable_camera_update;
1973                         if(disable_camera_update)
1974                                 statustext = L"Camera update disabled";
1975                         else
1976                                 statustext = L"Camera update enabled";
1977                         statustext_time = 0;
1978                 }
1979                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1980                 {
1981                         // Initial / 3x toggle: Chat only
1982                         // 1x toggle: Debug text with chat
1983                         // 2x toggle: Debug text with profiler graph
1984                         if(!show_debug)
1985                         {
1986                                 show_debug = true;
1987                                 show_profiler_graph = false;
1988                                 statustext = L"Debug info shown";
1989                                 statustext_time = 0;
1990                         }
1991                         else if(show_profiler_graph)
1992                         {
1993                                 show_debug = false;
1994                                 show_profiler_graph = false;
1995                                 statustext = L"Debug info and profiler graph hidden";
1996                                 statustext_time = 0;
1997                         }
1998                         else
1999                         {
2000                                 show_profiler_graph = true;
2001                                 statustext = L"Profiler graph shown";
2002                                 statustext_time = 0;
2003                         }
2004                 }
2005                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2006                 {
2007                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2008
2009                         // FIXME: This updates the profiler with incomplete values
2010                         update_profiler_gui(guitext_profiler, font, text_height,
2011                                         show_profiler, show_profiler_max);
2012
2013                         if(show_profiler != 0)
2014                         {
2015                                 std::wstringstream sstr;
2016                                 sstr<<"Profiler shown (page "<<show_profiler
2017                                         <<" of "<<show_profiler_max<<")";
2018                                 statustext = sstr.str();
2019                                 statustext_time = 0;
2020                         }
2021                         else
2022                         {
2023                                 statustext = L"Profiler hidden";
2024                                 statustext_time = 0;
2025                         }
2026                 }
2027                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2028                 {
2029                         s16 range = g_settings->getS16("viewing_range_nodes_min");
2030                         s16 range_new = range + 10;
2031                         g_settings->set("viewing_range_nodes_min", itos(range_new));
2032                         statustext = narrow_to_wide(
2033                                         "Minimum viewing range changed to "
2034                                         + itos(range_new));
2035                         statustext_time = 0;
2036                 }
2037                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2038                 {
2039                         s16 range = g_settings->getS16("viewing_range_nodes_min");
2040                         s16 range_new = range - 10;
2041                         if(range_new < 0)
2042                                 range_new = range;
2043                         g_settings->set("viewing_range_nodes_min",
2044                                         itos(range_new));
2045                         statustext = narrow_to_wide(
2046                                         "Minimum viewing range changed to "
2047                                         + itos(range_new));
2048                         statustext_time = 0;
2049                 }
2050                 
2051                 // Reset jump_timer
2052                 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2053                 {
2054                         reset_jump_timer = false;
2055                         jump_timer = 0.0;
2056                 }
2057
2058                 // Handle QuicktuneShortcutter
2059                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2060                         quicktune.next();
2061                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2062                         quicktune.prev();
2063                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2064                         quicktune.inc();
2065                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2066                         quicktune.dec();
2067                 {
2068                         std::string msg = quicktune.getMessage();
2069                         if(msg != ""){
2070                                 statustext = narrow_to_wide(msg);
2071                                 statustext_time = 0;
2072                         }
2073                 }
2074
2075                 // Item selection with mouse wheel
2076                 u16 new_playeritem = client.getPlayerItem();
2077                 {
2078                         s32 wheel = input->getMouseWheel();
2079                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2080                                         hotbar_itemcount-1);
2081
2082                         if(wheel < 0)
2083                         {
2084                                 if(new_playeritem < max_item)
2085                                         new_playeritem++;
2086                                 else
2087                                         new_playeritem = 0;
2088                         }
2089                         else if(wheel > 0)
2090                         {
2091                                 if(new_playeritem > 0)
2092                                         new_playeritem--;
2093                                 else
2094                                         new_playeritem = max_item;
2095                         }
2096                 }
2097                 
2098                 // Item selection
2099                 for(u16 i=0; i<10; i++)
2100                 {
2101                         const KeyPress *kp = NumberKey + (i + 1) % 10;
2102                         if(input->wasKeyDown(*kp))
2103                         {
2104                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
2105                                 {
2106                                         new_playeritem = i;
2107
2108                                         infostream<<"Selected item: "
2109                                                         <<new_playeritem<<std::endl;
2110                                 }
2111                         }
2112                 }
2113
2114                 // Viewing range selection
2115                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2116                 {
2117                         draw_control.range_all = !draw_control.range_all;
2118                         if(draw_control.range_all)
2119                         {
2120                                 infostream<<"Enabled full viewing range"<<std::endl;
2121                                 statustext = L"Enabled full viewing range";
2122                                 statustext_time = 0;
2123                         }
2124                         else
2125                         {
2126                                 infostream<<"Disabled full viewing range"<<std::endl;
2127                                 statustext = L"Disabled full viewing range";
2128                                 statustext_time = 0;
2129                         }
2130                 }
2131
2132                 // Print debug stacks
2133                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2134                 {
2135                         dstream<<"-----------------------------------------"
2136                                         <<std::endl;
2137                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2138                         dstream<<"-----------------------------------------"
2139                                         <<std::endl;
2140                         debug_stacks_print();
2141                 }
2142
2143                 /*
2144                         Mouse and camera control
2145                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2146                 */
2147                 
2148                 float turn_amount = 0;
2149                 if((device->isWindowActive() && noMenuActive()) || random_input)
2150                 {
2151                         if(!random_input)
2152                         {
2153                                 // Mac OSX gets upset if this is set every frame
2154                                 if(device->getCursorControl()->isVisible())
2155                                         device->getCursorControl()->setVisible(false);
2156                         }
2157
2158                         if(first_loop_after_window_activation){
2159                                 //infostream<<"window active, first loop"<<std::endl;
2160                                 first_loop_after_window_activation = false;
2161                         }
2162                         else{
2163                                 s32 dx = input->getMousePos().X - displaycenter.X;
2164                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
2165                                 if(invert_mouse)
2166                                         dy = -dy;
2167                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2168                                 
2169                                 /*const float keyspeed = 500;
2170                                 if(input->isKeyDown(irr::KEY_UP))
2171                                         dy -= dtime * keyspeed;
2172                                 if(input->isKeyDown(irr::KEY_DOWN))
2173                                         dy += dtime * keyspeed;
2174                                 if(input->isKeyDown(irr::KEY_LEFT))
2175                                         dx -= dtime * keyspeed;
2176                                 if(input->isKeyDown(irr::KEY_RIGHT))
2177                                         dx += dtime * keyspeed;*/
2178                                 
2179                                 float d = 0.2;
2180                                 camera_yaw -= dx*d;
2181                                 camera_pitch += dy*d;
2182                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
2183                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
2184                                 
2185                                 turn_amount = v2f(dx, dy).getLength() * d;
2186                         }
2187                         input->setMousePos(displaycenter.X, displaycenter.Y);
2188                 }
2189                 else{
2190                         // Mac OSX gets upset if this is set every frame
2191                         if(device->getCursorControl()->isVisible() == false)
2192                                 device->getCursorControl()->setVisible(true);
2193
2194                         //infostream<<"window inactive"<<std::endl;
2195                         first_loop_after_window_activation = true;
2196                 }
2197                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2198                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2199
2200                 /*
2201                         Player speed control
2202                 */
2203                 {
2204                         /*bool a_up,
2205                         bool a_down,
2206                         bool a_left,
2207                         bool a_right,
2208                         bool a_jump,
2209                         bool a_superspeed,
2210                         bool a_sneak,
2211                         bool a_LMB,
2212                         bool a_RMB,
2213                         float a_pitch,
2214                         float a_yaw*/
2215                         PlayerControl control(
2216                                 input->isKeyDown(getKeySetting("keymap_forward")),
2217                                 input->isKeyDown(getKeySetting("keymap_backward")),
2218                                 input->isKeyDown(getKeySetting("keymap_left")),
2219                                 input->isKeyDown(getKeySetting("keymap_right")),
2220                                 input->isKeyDown(getKeySetting("keymap_jump")),
2221                                 input->isKeyDown(getKeySetting("keymap_special1")),
2222                                 input->isKeyDown(getKeySetting("keymap_sneak")),
2223                                 input->getLeftState(),
2224                                 input->getRightState(),
2225                                 camera_pitch,
2226                                 camera_yaw
2227                         );
2228                         client.setPlayerControl(control);
2229                         u32 keyPressed=
2230                         1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2231                         2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2232                         4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2233                         8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2234                         16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2235                         32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2236                         64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2237                         128*(int)input->getLeftState()+
2238                         256*(int)input->getRightState();
2239                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2240                         player->keyPressed=keyPressed;
2241                 }
2242                 
2243                 /*
2244                         Run server
2245                 */
2246
2247                 if(server != NULL)
2248                 {
2249                         //TimeTaker timer("server->step(dtime)");
2250                         server->step(dtime);
2251                 }
2252
2253                 /*
2254                         Process environment
2255                 */
2256                 
2257                 {
2258                         //TimeTaker timer("client.step(dtime)");
2259                         client.step(dtime);
2260                         //client.step(dtime_avg1);
2261                 }
2262
2263                 {
2264                         // Read client events
2265                         for(;;)
2266                         {
2267                                 ClientEvent event = client.getClientEvent();
2268                                 if(event.type == CE_NONE)
2269                                 {
2270                                         break;
2271                                 }
2272                                 else if(event.type == CE_PLAYER_DAMAGE &&
2273                                                 client.getHP() != 0)
2274                                 {
2275                                         //u16 damage = event.player_damage.amount;
2276                                         //infostream<<"Player damage: "<<damage<<std::endl;
2277
2278                                         damage_flash += 100.0;
2279                                         damage_flash += 8.0 * event.player_damage.amount;
2280
2281                                         player->hurt_tilt_timer = 1.5;
2282                                         player->hurt_tilt_strength = event.player_damage.amount/2;
2283                                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2284                                 }
2285                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
2286                                 {
2287                                         camera_yaw = event.player_force_move.yaw;
2288                                         camera_pitch = event.player_force_move.pitch;
2289                                 }
2290                                 else if(event.type == CE_DEATHSCREEN)
2291                                 {
2292                                         if(respawn_menu_active)
2293                                                 continue;
2294
2295                                         /*bool set_camera_point_target =
2296                                                         event.deathscreen.set_camera_point_target;
2297                                         v3f camera_point_target;
2298                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
2299                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
2300                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2301                                         MainRespawnInitiator *respawner =
2302                                                         new MainRespawnInitiator(
2303                                                                         &respawn_menu_active, &client);
2304                                         GUIDeathScreen *menu =
2305                                                         new GUIDeathScreen(guienv, guiroot, -1, 
2306                                                                 &g_menumgr, respawner);
2307                                         menu->drop();
2308                                         
2309                                         chat_backend.addMessage(L"", L"You died.");
2310
2311                                         /* Handle visualization */
2312
2313                                         damage_flash = 0;
2314
2315                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2316                                         player->hurt_tilt_timer = 0;
2317                                         player->hurt_tilt_strength = 0;
2318
2319                                         /*LocalPlayer* player = client.getLocalPlayer();
2320                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
2321                                         camera.update(player, busytime, screensize);*/
2322                                 }
2323                                 else if (event.type == CE_SHOW_FORMSPEC)
2324                                 {
2325                                         if (current_formspec == 0)
2326                                         {
2327                                                 /* Create menu */
2328                                                 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),&current_formspec);
2329
2330                                                 GUIFormSpecMenu *menu =
2331                                                                 new GUIFormSpecMenu(device, guiroot, -1,
2332                                                                                 &g_menumgr,
2333                                                                                 &client, gamedef);
2334                                                 menu->setFormSource(current_formspec);
2335                                                 menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
2336                                                 menu->drop();
2337                                         }
2338                                         else
2339                                         {
2340                                                 /* update menu */
2341                                                 current_formspec->setForm(*(event.show_formspec.formspec));
2342                                         }
2343                                         delete(event.show_formspec.formspec);
2344                                         delete(event.show_formspec.formname);
2345                                 }
2346                                 else if(event.type == CE_TEXTURES_UPDATED)
2347                                 {
2348                                         update_wielded_item_trigger = true;
2349                                 }
2350                                 else if(event.type == CE_SPAWN_PARTICLE)
2351                                 {
2352                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2353                                         AtlasPointer ap =
2354                                                 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2355
2356                                         new Particle(gamedef, smgr, player, client.getEnv(),
2357                                                 *event.spawn_particle.pos,
2358                                                 *event.spawn_particle.vel,
2359                                                 *event.spawn_particle.acc,
2360                                                  event.spawn_particle.expirationtime,
2361                                                  event.spawn_particle.size,
2362                                                  event.spawn_particle.collisiondetection, ap);
2363                                 }
2364                                 else if(event.type == CE_ADD_PARTICLESPAWNER)
2365                                 {
2366                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2367                                         AtlasPointer ap =
2368                                                 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2369
2370                                         new ParticleSpawner(gamedef, smgr, player,
2371                                                  event.add_particlespawner.amount,
2372                                                  event.add_particlespawner.spawntime,
2373                                                 *event.add_particlespawner.minpos,
2374                                                 *event.add_particlespawner.maxpos,
2375                                                 *event.add_particlespawner.minvel,
2376                                                 *event.add_particlespawner.maxvel,
2377                                                 *event.add_particlespawner.minacc,
2378                                                 *event.add_particlespawner.maxacc,
2379                                                  event.add_particlespawner.minexptime,
2380                                                  event.add_particlespawner.maxexptime,
2381                                                  event.add_particlespawner.minsize,
2382                                                  event.add_particlespawner.maxsize,
2383                                                  event.add_particlespawner.collisiondetection,
2384                                                  ap,
2385                                                  event.add_particlespawner.id);
2386                                 }
2387                                 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2388                                 {
2389                                         delete_particlespawner (event.delete_particlespawner.id);
2390                                 }
2391                                 else if (event.type == CE_HUDADD)
2392                                 {
2393                                         HudElement* e = new HudElement;
2394                                         e->type   = event.hudadd.type;
2395                                         e->pos    = *event.hudadd.pos;
2396                                         e->name   = *event.hudadd.name;
2397                                         e->scale  = *event.hudadd.scale;
2398                                         e->text   = *event.hudadd.text;
2399                                         e->number = event.hudadd.number;
2400                                         e->item   = event.hudadd.item;
2401                                         e->dir    = event.hudadd.dir;
2402                                         player->hud[event.hudadd.id] = e;
2403                                         delete(event.hudadd.pos);
2404                                         delete(event.hudadd.name);
2405                                         delete(event.hudadd.scale);
2406                                         delete(event.hudadd.text);
2407                                 }
2408                                 else if (event.type == CE_HUDRM)
2409                                 {
2410                                         player->hud.erase(event.hudrm.id);
2411                                 }
2412                                 else if (event.type == CE_HUDCHANGE)
2413                                 {
2414                                         HudElement* e = player->hud[event.hudchange.id];
2415                                         if(event.hudchange.stat == 0)
2416                                                 e->pos = *event.hudchange.v2fdata;
2417                                         else if(event.hudchange.stat == 1)
2418                                                 e->name = *event.hudchange.sdata;
2419                                         else if(event.hudchange.stat == 2)
2420                                                 e->scale = *event.hudchange.v2fdata;
2421                                         else if(event.hudchange.stat == 3)
2422                                                 e->text = *event.hudchange.sdata;
2423                                         else if(event.hudchange.stat == 4)
2424                                                 e->number = event.hudchange.data;
2425                                         else if(event.hudchange.stat == 5)
2426                                                 e->item = event.hudchange.data;
2427                                         else if(event.hudchange.stat == 6)
2428                                                 e->dir = event.hudchange.data;
2429                                 }
2430                         }
2431                 }
2432                 
2433                 //TimeTaker //timer2("//timer2");
2434
2435                 /*
2436                         For interaction purposes, get info about the held item
2437                         - What item is it?
2438                         - Is it a usable item?
2439                         - Can it point to liquids?
2440                 */
2441                 ItemStack playeritem;
2442                 bool playeritem_usable = false;
2443                 bool playeritem_liquids_pointable = false;
2444                 {
2445                         InventoryList *mlist = local_inventory.getList("main");
2446                         if(mlist != NULL)
2447                         {
2448                                 playeritem = mlist->getItem(client.getPlayerItem());
2449                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2450                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2451                         }
2452                 }
2453                 ToolCapabilities playeritem_toolcap =
2454                                 playeritem.getToolCapabilities(itemdef);
2455                 
2456                 /*
2457                         Update camera
2458                 */
2459
2460                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2461                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2462                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2463                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2464                 camera.update(player, busytime, screensize, tool_reload_ratio);
2465                 camera.step(dtime);
2466
2467                 v3f player_position = player->getPosition();
2468                 v3f camera_position = camera.getPosition();
2469                 v3f camera_direction = camera.getDirection();
2470                 f32 camera_fov = camera.getFovMax();
2471                 
2472                 if(!disable_camera_update){
2473                         client.getEnv().getClientMap().updateCamera(camera_position,
2474                                 camera_direction, camera_fov);
2475                 }
2476                 
2477                 // Update sound listener
2478                 sound->updateListener(camera.getCameraNode()->getPosition(),
2479                                 v3f(0,0,0), // velocity
2480                                 camera.getDirection(),
2481                                 camera.getCameraNode()->getUpVector());
2482                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2483
2484                 /*
2485                         Update sound maker
2486                 */
2487                 {
2488                         soundmaker.step(dtime);
2489                         
2490                         ClientMap &map = client.getEnv().getClientMap();
2491                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2492                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2493                 }
2494
2495                 /*
2496                         Calculate what block is the crosshair pointing to
2497                 */
2498                 
2499                 //u32 t1 = device->getTimer()->getRealTime();
2500                 
2501                 f32 d = 4; // max. distance
2502                 core::line3d<f32> shootline(camera_position,
2503                                 camera_position + camera_direction * BS * (d+1));
2504
2505                 ClientActiveObject *selected_object = NULL;
2506
2507                 PointedThing pointed = getPointedThing(
2508                                 // input
2509                                 &client, player_position, camera_direction,
2510                                 camera_position, shootline, d,
2511                                 playeritem_liquids_pointable, !ldown_for_dig,
2512                                 // output
2513                                 hilightboxes,
2514                                 selected_object);
2515
2516                 if(pointed != pointed_old)
2517                 {
2518                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2519                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2520                 }
2521
2522                 /*
2523                         Stop digging when
2524                         - releasing left mouse button
2525                         - pointing away from node
2526                 */
2527                 if(digging)
2528                 {
2529                         if(input->getLeftReleased())
2530                         {
2531                                 infostream<<"Left button released"
2532                                         <<" (stopped digging)"<<std::endl;
2533                                 digging = false;
2534                         }
2535                         else if(pointed != pointed_old)
2536                         {
2537                                 if (pointed.type == POINTEDTHING_NODE
2538                                         && pointed_old.type == POINTEDTHING_NODE
2539                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2540                                 {
2541                                         // Still pointing to the same node,
2542                                         // but a different face. Don't reset.
2543                                 }
2544                                 else
2545                                 {
2546                                         infostream<<"Pointing away from node"
2547                                                 <<" (stopped digging)"<<std::endl;
2548                                         digging = false;
2549                                 }
2550                         }
2551                         if(!digging)
2552                         {
2553                                 client.interact(1, pointed_old);
2554                                 client.setCrack(-1, v3s16(0,0,0));
2555                                 dig_time = 0.0;
2556                         }
2557                 }
2558                 if(!digging && ldown_for_dig && !input->getLeftState())
2559                 {
2560                         ldown_for_dig = false;
2561                 }
2562
2563                 bool left_punch = false;
2564                 soundmaker.m_player_leftpunch_sound.name = "";
2565
2566                 if(input->getRightState())
2567                         repeat_rightclick_timer += dtime;
2568                 else
2569                         repeat_rightclick_timer = 0;
2570
2571                 if(playeritem_usable && input->getLeftState())
2572                 {
2573                         if(input->getLeftClicked())
2574                                 client.interact(4, pointed);
2575                 }
2576                 else if(pointed.type == POINTEDTHING_NODE)
2577                 {
2578                         v3s16 nodepos = pointed.node_undersurface;
2579                         v3s16 neighbourpos = pointed.node_abovesurface;
2580
2581                         /*
2582                                 Check information text of node
2583                         */
2584                         
2585                         ClientMap &map = client.getEnv().getClientMap();
2586                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2587                         if(meta){
2588                                 infotext = narrow_to_wide(meta->getString("infotext"));
2589                         } else {
2590                                 MapNode n = map.getNode(nodepos);
2591                                 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2592                                         infotext = L"Unknown node: ";
2593                                         infotext += narrow_to_wide(nodedef->get(n).name);
2594                                 }
2595                         }
2596                         
2597                         /*
2598                                 Handle digging
2599                         */
2600                         
2601                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
2602                         {
2603                                 if(!digging)
2604                                 {
2605                                         infostream<<"Started digging"<<std::endl;
2606                                         client.interact(0, pointed);
2607                                         digging = true;
2608                                         ldown_for_dig = true;
2609                                 }
2610                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2611                                 
2612                                 // NOTE: Similar piece of code exists on the server side for
2613                                 // cheat detection.
2614                                 // Get digging parameters
2615                                 DigParams params = getDigParams(nodedef->get(n).groups,
2616                                                 &playeritem_toolcap);
2617                                 // If can't dig, try hand
2618                                 if(!params.diggable){
2619                                         const ItemDefinition &hand = itemdef->get("");
2620                                         const ToolCapabilities *tp = hand.tool_capabilities;
2621                                         if(tp)
2622                                                 params = getDigParams(nodedef->get(n).groups, tp);
2623                                 }
2624                                 
2625                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2626                                 if(sound_dig.exists()){
2627                                         if(sound_dig.name == "__group"){
2628                                                 if(params.main_group != ""){
2629                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2630                                                         soundmaker.m_player_leftpunch_sound.name =
2631                                                                         std::string("default_dig_") +
2632                                                                                         params.main_group;
2633                                                 }
2634                                         } else{
2635                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2636                                         }
2637                                 }
2638
2639                                 float dig_time_complete = 0.0;
2640
2641                                 if(params.diggable == false)
2642                                 {
2643                                         // I guess nobody will wait for this long
2644                                         dig_time_complete = 10000000.0;
2645                                 }
2646                                 else
2647                                 {
2648                                         dig_time_complete = params.time;
2649                                         if (g_settings->getBool("enable_particles"))
2650                                         {
2651                                                 const ContentFeatures &features =
2652                                                         client.getNodeDefManager()->get(n);
2653                                                 addPunchingParticles
2654                                                         (gamedef, smgr, player, client.getEnv(),
2655                                                          nodepos, features.tiles);
2656                                         }
2657                                 }
2658
2659                                 if(dig_time_complete >= 0.001)
2660                                 {
2661                                         dig_index = (u16)((float)crack_animation_length
2662                                                         * dig_time/dig_time_complete);
2663                                 }
2664                                 // This is for torches
2665                                 else
2666                                 {
2667                                         dig_index = crack_animation_length;
2668                                 }
2669
2670                                 // Don't show cracks if not diggable
2671                                 if(dig_time_complete >= 100000.0)
2672                                 {
2673                                 }
2674                                 else if(dig_index < crack_animation_length)
2675                                 {
2676                                         //TimeTaker timer("client.setTempMod");
2677                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2678                                         client.setCrack(dig_index, nodepos);
2679                                 }
2680                                 else
2681                                 {
2682                                         infostream<<"Digging completed"<<std::endl;
2683                                         client.interact(2, pointed);
2684                                         client.setCrack(-1, v3s16(0,0,0));
2685                                         MapNode wasnode = map.getNode(nodepos);
2686                                         client.removeNode(nodepos);
2687
2688                                         if (g_settings->getBool("enable_particles"))
2689                                         {
2690                                                 const ContentFeatures &features =
2691                                                         client.getNodeDefManager()->get(wasnode);
2692                                                 addDiggingParticles
2693                                                         (gamedef, smgr, player, client.getEnv(),
2694                                                          nodepos, features.tiles);
2695                                         }
2696
2697                                         dig_time = 0;
2698                                         digging = false;
2699
2700                                         nodig_delay_timer = dig_time_complete
2701                                                         / (float)crack_animation_length;
2702
2703                                         // We don't want a corresponding delay to
2704                                         // very time consuming nodes
2705                                         if(nodig_delay_timer > 0.3)
2706                                                 nodig_delay_timer = 0.3;
2707                                         // We want a slight delay to very little
2708                                         // time consuming nodes
2709                                         float mindelay = 0.15;
2710                                         if(nodig_delay_timer < mindelay)
2711                                                 nodig_delay_timer = mindelay;
2712                                         
2713                                         // Send event to trigger sound
2714                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2715                                         gamedef->event()->put(e);
2716                                 }
2717
2718                                 dig_time += dtime;
2719
2720                                 camera.setDigging(0);  // left click animation
2721                         }
2722
2723                         if(input->getRightClicked() ||
2724                                         repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2725                         {
2726                                 repeat_rightclick_timer = 0;
2727                                 infostream<<"Ground right-clicked"<<std::endl;
2728                                 
2729                                 // Sign special case, at least until formspec is properly implemented.
2730                                 // Deprecated?
2731                                 if(meta && meta->getString("formspec") == "hack:sign_text_input" 
2732                                                 && !random_input
2733                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2734                                 {
2735                                         infostream<<"Launching metadata text input"<<std::endl;
2736                                         
2737                                         // Get a new text for it
2738
2739                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2740
2741                                         std::wstring wtext = narrow_to_wide(meta->getString("text"));
2742
2743                                         (new GUITextInputMenu(guienv, guiroot, -1,
2744                                                         &g_menumgr, dest,
2745                                                         wtext))->drop();
2746                                 }
2747                                 // If metadata provides an inventory view, activate it
2748                                 else if(meta && meta->getString("formspec") != "" && !random_input
2749                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2750                                 {
2751                                         infostream<<"Launching custom inventory view"<<std::endl;
2752
2753                                         InventoryLocation inventoryloc;
2754                                         inventoryloc.setNodeMeta(nodepos);
2755                                         
2756                                         /* Create menu */
2757
2758                                         GUIFormSpecMenu *menu =
2759                                                 new GUIFormSpecMenu(device, guiroot, -1,
2760                                                         &g_menumgr,
2761                                                         &client, gamedef);
2762                                         menu->setFormSpec(meta->getString("formspec"),
2763                                                         inventoryloc);
2764                                         menu->setFormSource(new NodeMetadataFormSource(
2765                                                         &client.getEnv().getClientMap(), nodepos));
2766                                         menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2767                                         menu->drop();
2768                                 }
2769                                 // Otherwise report right click to server
2770                                 else
2771                                 {
2772                                         // Report to server
2773                                         client.interact(3, pointed);
2774                                         camera.setDigging(1);  // right click animation
2775                                         
2776                                         // If the wielded item has node placement prediction,
2777                                         // make that happen
2778                                         const ItemDefinition &def =
2779                                                         playeritem.getDefinition(itemdef);
2780                                         if(def.node_placement_prediction != ""
2781                                                         && !nodedef->get(map.getNode(nodepos)).rightclickable)
2782                                         do{ // breakable
2783                                                 verbosestream<<"Node placement prediction for "
2784                                                                 <<playeritem.name<<" is "
2785                                                                 <<def.node_placement_prediction<<std::endl;
2786                                                 v3s16 p = neighbourpos;
2787                                                 // Place inside node itself if buildable_to
2788                                                 try{
2789                                                         MapNode n_under = map.getNode(nodepos);
2790                                                         if(nodedef->get(n_under).buildable_to)
2791                                                                 p = nodepos;
2792                                                 }catch(InvalidPositionException &e){}
2793                                                 // Find id of predicted node
2794                                                 content_t id;
2795                                                 bool found =
2796                                                         nodedef->getId(def.node_placement_prediction, id);
2797                                                 if(!found){
2798                                                         errorstream<<"Node placement prediction failed for "
2799                                                                         <<playeritem.name<<" (places "
2800                                                                         <<def.node_placement_prediction
2801                                                                         <<") - Name not known"<<std::endl;
2802                                                         break;
2803                                                 }
2804                                                 MapNode n(id);
2805                                                 try{
2806                                                         // This triggers the required mesh update too
2807                                                         client.addNode(p, n);
2808                                                 }catch(InvalidPositionException &e){
2809                                                         errorstream<<"Node placement prediction failed for "
2810                                                                         <<playeritem.name<<" (places "
2811                                                                         <<def.node_placement_prediction
2812                                                                         <<") - Position not loaded"<<std::endl;
2813                                                 }
2814                                         }while(0);
2815                                         
2816                                         // Read the sound
2817                                         soundmaker.m_player_rightpunch_sound = def.sound_place;
2818                                 }
2819                         }
2820                 }
2821                 else if(pointed.type == POINTEDTHING_OBJECT)
2822                 {
2823                         infotext = narrow_to_wide(selected_object->infoText());
2824
2825                         if(infotext == L"" && show_debug){
2826                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2827                         }
2828
2829                         //if(input->getLeftClicked())
2830                         if(input->getLeftState())
2831                         {
2832                                 bool do_punch = false;
2833                                 bool do_punch_damage = false;
2834                                 if(object_hit_delay_timer <= 0.0){
2835                                         do_punch = true;
2836                                         do_punch_damage = true;
2837                                         object_hit_delay_timer = object_hit_delay;
2838                                 }
2839                                 if(input->getLeftClicked()){
2840                                         do_punch = true;
2841                                 }
2842                                 if(do_punch){
2843                                         infostream<<"Left-clicked object"<<std::endl;
2844                                         left_punch = true;
2845                                 }
2846                                 if(do_punch_damage){
2847                                         // Report direct punch
2848                                         v3f objpos = selected_object->getPosition();
2849                                         v3f dir = (objpos - player_position).normalize();
2850                                         
2851                                         bool disable_send = selected_object->directReportPunch(
2852                                                         dir, &playeritem, time_from_last_punch);
2853                                         time_from_last_punch = 0;
2854                                         if(!disable_send)
2855                                                 client.interact(0, pointed);
2856                                 }
2857                         }
2858                         else if(input->getRightClicked())
2859                         {
2860                                 infostream<<"Right-clicked object"<<std::endl;
2861                                 client.interact(3, pointed);  // place
2862                         }
2863                 }
2864                 else if(input->getLeftState())
2865                 {
2866                         // When button is held down in air, show continuous animation
2867                         left_punch = true;
2868                 }
2869
2870                 pointed_old = pointed;
2871                 
2872                 if(left_punch || input->getLeftClicked())
2873                 {
2874                         camera.setDigging(0); // left click animation
2875                 }
2876
2877                 input->resetLeftClicked();
2878                 input->resetRightClicked();
2879
2880                 input->resetLeftReleased();
2881                 input->resetRightReleased();
2882                 
2883                 /*
2884                         Calculate stuff for drawing
2885                 */
2886
2887                 /*
2888                         Fog range
2889                 */
2890         
2891                 if(farmesh)
2892                 {
2893                         fog_range = BS*farmesh_range;
2894                 }
2895                 else
2896                 {
2897                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2898                         fog_range *= 0.9;
2899                         if(draw_control.range_all)
2900                                 fog_range = 100000*BS;
2901                 }
2902
2903                 /*
2904                         Calculate general brightness
2905                 */
2906                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2907                 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2908                 float direct_brightness = 0;
2909                 bool sunlight_seen = false;
2910                 if(g_settings->getBool("free_move")){
2911                         direct_brightness = time_brightness;
2912                         sunlight_seen = true;
2913                 } else {
2914                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2915                         float old_brightness = sky->getBrightness();
2916                         direct_brightness = (float)client.getEnv().getClientMap()
2917                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2918                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2919                                         / 255.0;
2920                 }
2921                 
2922                 time_of_day = client.getEnv().getTimeOfDayF();
2923                 float maxsm = 0.05;
2924                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2925                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2926                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2927                         time_of_day_smooth = time_of_day;
2928                 float todsm = 0.05;
2929                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2930                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2931                                         + (time_of_day+1.0) * todsm;
2932                 else
2933                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2934                                         + time_of_day * todsm;
2935                         
2936                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2937                                 sunlight_seen);
2938                 
2939                 float brightness = sky->getBrightness();
2940                 video::SColor bgcolor = sky->getBgColor();
2941                 video::SColor skycolor = sky->getSkyColor();
2942
2943                 /*
2944                         Update clouds
2945                 */
2946                 if(clouds){
2947                         if(sky->getCloudsVisible()){
2948                                 clouds->setVisible(true);
2949                                 clouds->step(dtime);
2950                                 clouds->update(v2f(player_position.X, player_position.Z),
2951                                                 sky->getCloudColor());
2952                         } else{
2953                                 clouds->setVisible(false);
2954                         }
2955                 }
2956                 
2957                 /*
2958                         Update farmesh
2959                 */
2960                 if(farmesh)
2961                 {
2962                         farmesh_range = draw_control.wanted_range * 10;
2963                         if(draw_control.range_all && farmesh_range < 500)
2964                                 farmesh_range = 500;
2965                         if(farmesh_range > 1000)
2966                                 farmesh_range = 1000;
2967
2968                         farmesh->step(dtime);
2969                         farmesh->update(v2f(player_position.X, player_position.Z),
2970                                         brightness, farmesh_range);
2971                 }
2972
2973                 /*
2974                         Update particles
2975                 */
2976
2977                 allparticles_step(dtime, client.getEnv());
2978                 allparticlespawners_step(dtime, client.getEnv());
2979                 
2980                 /*
2981                         Fog
2982                 */
2983                 
2984                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2985                 {
2986                         driver->setFog(
2987                                 bgcolor,
2988                                 video::EFT_FOG_LINEAR,
2989                                 fog_range*0.4,
2990                                 fog_range*1.0,
2991                                 0.01,
2992                                 false, // pixel fog
2993                                 false // range fog
2994                         );
2995                 }
2996                 else
2997                 {
2998                         driver->setFog(
2999                                 bgcolor,
3000                                 video::EFT_FOG_LINEAR,
3001                                 100000*BS,
3002                                 110000*BS,
3003                                 0.01,
3004                                 false, // pixel fog
3005                                 false // range fog
3006                         );
3007                 }
3008
3009                 /*
3010                         Update gui stuff (0ms)
3011                 */
3012
3013                 //TimeTaker guiupdatetimer("Gui updating");
3014                 
3015                 const char program_name_and_version[] =
3016                         "Minetest " VERSION_STRING;
3017
3018                 if(show_debug)
3019                 {
3020                         static float drawtime_avg = 0;
3021                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3022                         /*static float beginscenetime_avg = 0;
3023                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3024                         static float scenetime_avg = 0;
3025                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3026                         static float endscenetime_avg = 0;
3027                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3028                         
3029                         char temptext[300];
3030                         snprintf(temptext, 300, "%s ("
3031                                         "R: range_all=%i"
3032                                         ")"
3033                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
3034                                         ", v_range = %.1f, RTT = %.3f",
3035                                         program_name_and_version,
3036                                         draw_control.range_all,
3037                                         drawtime_avg,
3038                                         dtime_jitter1_max_fraction * 100.0,
3039                                         draw_control.wanted_range,
3040                                         client.getRTT()
3041                                         );
3042                         
3043                         guitext->setText(narrow_to_wide(temptext).c_str());
3044                         guitext->setVisible(true);
3045                 }
3046                 else if(show_hud || show_chat)
3047                 {
3048                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
3049                         guitext->setVisible(true);
3050                 }
3051                 else
3052                 {
3053                         guitext->setVisible(false);
3054                 }
3055                 
3056                 if(show_debug)
3057                 {
3058                         char temptext[300];
3059                         snprintf(temptext, 300,
3060                                         "(% .1f, % .1f, % .1f)"
3061                                         " (yaw = %.1f) (seed = %llu)",
3062                                         player_position.X/BS,
3063                                         player_position.Y/BS,
3064                                         player_position.Z/BS,
3065                                         wrapDegrees_0_360(camera_yaw),
3066                                         (unsigned long long)client.getMapSeed());
3067
3068                         guitext2->setText(narrow_to_wide(temptext).c_str());
3069                         guitext2->setVisible(true);
3070                 }
3071                 else
3072                 {
3073                         guitext2->setVisible(false);
3074                 }
3075                 
3076                 {
3077                         guitext_info->setText(infotext.c_str());
3078                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3079                 }
3080
3081                 {
3082                         float statustext_time_max = 1.5;
3083                         if(!statustext.empty())
3084                         {
3085                                 statustext_time += dtime;
3086                                 if(statustext_time >= statustext_time_max)
3087                                 {
3088                                         statustext = L"";
3089                                         statustext_time = 0;
3090                                 }
3091                         }
3092                         guitext_status->setText(statustext.c_str());
3093                         guitext_status->setVisible(!statustext.empty());
3094
3095                         if(!statustext.empty())
3096                         {
3097                                 s32 status_y = screensize.Y - 130;
3098                                 core::rect<s32> rect(
3099                                                 10,
3100                                                 status_y - guitext_status->getTextHeight(),
3101                                                 screensize.X - 10,
3102                                                 status_y
3103                                 );
3104                                 guitext_status->setRelativePosition(rect);
3105
3106                                 // Fade out
3107                                 video::SColor initial_color(255,0,0,0);
3108                                 if(guienv->getSkin())
3109                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3110                                 video::SColor final_color = initial_color;
3111                                 final_color.setAlpha(0);
3112                                 video::SColor fade_color =
3113                                         initial_color.getInterpolated_quadratic(
3114                                                 initial_color,
3115                                                 final_color,
3116                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
3117                                 guitext_status->setOverrideColor(fade_color);
3118                                 guitext_status->enableOverrideColor(true);
3119                         }
3120                 }
3121                 
3122                 /*
3123                         Get chat messages from client
3124                 */
3125                 {
3126                         // Get new messages from error log buffer
3127                         while(!chat_log_error_buf.empty())
3128                         {
3129                                 chat_backend.addMessage(L"", narrow_to_wide(
3130                                                 chat_log_error_buf.get()));
3131                         }
3132                         // Get new messages from client
3133                         std::wstring message;
3134                         while(client.getChatMessage(message))
3135                         {
3136                                 chat_backend.addUnparsedMessage(message);
3137                         }
3138                         // Remove old messages
3139                         chat_backend.step(dtime);
3140
3141                         // Display all messages in a static text element
3142                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3143                         std::wstring recent_chat = chat_backend.getRecentChat();
3144                         guitext_chat->setText(recent_chat.c_str());
3145
3146                         // Update gui element size and position
3147                         s32 chat_y = 5+(text_height+5);
3148                         if(show_debug)
3149                                 chat_y += (text_height+5);
3150                         core::rect<s32> rect(
3151                                 10,
3152                                 chat_y,
3153                                 screensize.X - 10,
3154                                 chat_y + guitext_chat->getTextHeight()
3155                         );
3156                         guitext_chat->setRelativePosition(rect);
3157
3158                         // Don't show chat if disabled or empty or profiler is enabled
3159                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
3160                                         && !show_profiler);
3161                 }
3162
3163                 /*
3164                         Inventory
3165                 */
3166                 
3167                 if(client.getPlayerItem() != new_playeritem)
3168                 {
3169                         client.selectPlayerItem(new_playeritem);
3170                 }
3171                 if(client.getLocalInventoryUpdated())
3172                 {
3173                         //infostream<<"Updating local inventory"<<std::endl;
3174                         client.getLocalInventory(local_inventory);
3175                         
3176                         update_wielded_item_trigger = true;
3177                 }
3178                 if(update_wielded_item_trigger)
3179                 {
3180                         update_wielded_item_trigger = false;
3181                         // Update wielded tool
3182                         InventoryList *mlist = local_inventory.getList("main");
3183                         ItemStack item;
3184                         if(mlist != NULL)
3185                                 item = mlist->getItem(client.getPlayerItem());
3186                         camera.wield(item);
3187                 }
3188
3189                 /*
3190                         Update block draw list every 200ms or when camera direction has
3191                         changed much
3192                 */
3193                 update_draw_list_timer += dtime;
3194                 if(update_draw_list_timer >= 0.2 ||
3195                                 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3196                         update_draw_list_timer = 0;
3197                         client.getEnv().getClientMap().updateDrawList(driver);
3198                         update_draw_list_last_cam_dir = camera_direction;
3199                 }
3200
3201                 /*
3202                         Drawing begins
3203                 */
3204
3205                 TimeTaker tt_draw("mainloop: draw");
3206
3207                 
3208                 {
3209                         TimeTaker timer("beginScene");
3210                         //driver->beginScene(false, true, bgcolor);
3211                         //driver->beginScene(true, true, bgcolor);
3212                         driver->beginScene(true, true, skycolor);
3213                         beginscenetime = timer.stop(true);
3214                 }
3215                 
3216                 //timer3.stop();
3217         
3218                 //infostream<<"smgr->drawAll()"<<std::endl;
3219                 {
3220                         TimeTaker timer("smgr");
3221                         smgr->drawAll();
3222                         
3223                         if(g_settings->getBool("anaglyph"))
3224                         {
3225                                 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3226                                 irr::core::vector3df oldTarget   = camera.getCameraNode()->getTarget();
3227
3228                                 irr::core::matrix4 startMatrix   = camera.getCameraNode()->getAbsoluteTransformation();
3229
3230                                 irr::core::vector3df focusPoint  = (camera.getCameraNode()->getTarget() -
3231                                                                                  camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3232                                                                                  camera.getCameraNode()->getAbsolutePosition() ;
3233
3234                                 //Left eye...
3235                                 irr::core::vector3df leftEye;
3236                                 irr::core::matrix4   leftMove;
3237
3238                                 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3239                                 leftEye=(startMatrix*leftMove).getTranslation();
3240
3241                                 //clear the depth buffer, and color
3242                                 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3243
3244                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3245                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
3246                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX + 
3247                                                                                                                          irr::scene::ESNRP_SOLID +
3248                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
3249                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
3250                                                                                                                          irr::scene::ESNRP_SHADOW;
3251
3252                                 camera.getCameraNode()->setPosition( leftEye );
3253                                 camera.getCameraNode()->setTarget( focusPoint );
3254
3255                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
3256
3257
3258                                 //Right eye...
3259                                 irr::core::vector3df rightEye;
3260                                 irr::core::matrix4   rightMove;
3261
3262                                 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3263                                 rightEye=(startMatrix*rightMove).getTranslation();
3264
3265                                 //clear the depth buffer
3266                                 driver->clearZBuffer();
3267
3268                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3269                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
3270                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3271                                                                                                                          irr::scene::ESNRP_SOLID +
3272                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
3273                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
3274                                                                                                                          irr::scene::ESNRP_SHADOW;
3275
3276                                 camera.getCameraNode()->setPosition( rightEye );
3277                                 camera.getCameraNode()->setTarget( focusPoint );
3278
3279                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
3280
3281
3282                                 //driver->endScene();
3283
3284                                 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3285                                 driver->getOverrideMaterial().EnableFlags=0;
3286                                 driver->getOverrideMaterial().EnablePasses=0;
3287
3288                                 camera.getCameraNode()->setPosition( oldPosition );
3289                                 camera.getCameraNode()->setTarget( oldTarget );
3290                         }
3291
3292                         scenetime = timer.stop(true);
3293                 }
3294                 
3295                 {
3296                 //TimeTaker timer9("auxiliary drawings");
3297                 // 0ms
3298                 
3299                 //timer9.stop();
3300                 //TimeTaker //timer10("//timer10");
3301                 
3302                 video::SMaterial m;
3303                 //m.Thickness = 10;
3304                 m.Thickness = 3;
3305                 m.Lighting = false;
3306                 driver->setMaterial(m);
3307
3308                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3309
3310                 if(show_hud)
3311                 {
3312                         v3f selectionbox_color = g_settings->getV3F("selectionbox_color");
3313                         u32 selectionbox_color_r = rangelim(myround(selectionbox_color.X), 0, 255);
3314                         u32 selectionbox_color_g = rangelim(myround(selectionbox_color.Y), 0, 255);
3315                         u32 selectionbox_color_b = rangelim(myround(selectionbox_color.Z), 0, 255);
3316
3317                         for(std::vector<aabb3f>::const_iterator
3318                                         i = hilightboxes.begin();
3319                                         i != hilightboxes.end(); i++)
3320                         {
3321                                 /*infostream<<"hilightbox min="
3322                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
3323                                                 <<" max="
3324                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
3325                                                 <<std::endl;*/
3326                                 driver->draw3DBox(*i, video::SColor(255,selectionbox_color_r,selectionbox_color_g,selectionbox_color_b));
3327                         }
3328                 }
3329
3330                 /*
3331                         Wielded tool
3332                 */
3333                 if(show_hud)
3334                 {
3335                         // Warning: This clears the Z buffer.
3336                         camera.drawWieldedTool();
3337                 }
3338
3339                 /*
3340                         Post effects
3341                 */
3342                 {
3343                         client.getEnv().getClientMap().renderPostFx();
3344                 }
3345
3346                 /*
3347                         Profiler graph
3348                 */
3349                 if(show_profiler_graph)
3350                 {
3351                         graph.draw(10, screensize.Y - 10, driver, font);
3352                 }
3353
3354                 /*
3355                         Draw crosshair
3356                 */
3357                 if(show_hud)
3358                 {
3359                         v3f crosshair_color = g_settings->getV3F("crosshair_color");
3360                         u32 crosshair_color_r = rangelim(myround(crosshair_color.X), 0, 255);
3361                         u32 crosshair_color_g = rangelim(myround(crosshair_color.Y), 0, 255);
3362                         u32 crosshair_color_b = rangelim(myround(crosshair_color.Z), 0, 255);
3363                         u32 crosshair_alpha = rangelim(g_settings->getS32("crosshair_alpha"), 0, 255);
3364
3365                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
3366                                         displaycenter + core::vector2d<s32>(10,0),
3367                                         video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3368                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
3369                                         displaycenter + core::vector2d<s32>(0,10),
3370                                         video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3371                 }
3372
3373                 } // timer
3374
3375                 //timer10.stop();
3376                 //TimeTaker //timer11("//timer11");
3377
3378
3379                 /*
3380                         Draw hotbar
3381                 */
3382                 if(show_hud)
3383                 {
3384                         draw_hotbar(driver, font, gamedef,
3385                                         v2s32(displaycenter.X, screensize.Y),
3386                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
3387                                         client.getHP(), client.getPlayerItem());
3388                 }
3389
3390                 /*
3391                         Damage flash
3392                 */
3393                 if(damage_flash > 0.0)
3394                 {
3395                         video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3396                         driver->draw2DRectangle(color,
3397                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
3398                                         NULL);
3399                         
3400                         damage_flash -= 100.0*dtime;
3401                 }
3402
3403                 /*
3404                         Damage camera tilt
3405                 */
3406                 if(player->hurt_tilt_timer > 0.0)
3407                 {
3408                         player->hurt_tilt_timer -= dtime*5;
3409                         if(player->hurt_tilt_timer < 0)
3410                                 player->hurt_tilt_strength = 0;
3411                 }
3412
3413                 /*
3414                         Draw lua hud items
3415                 */
3416                 std::deque<gui::IGUIStaticText *> luaguitexts;
3417                 if(show_hud)
3418                 {
3419                         for(std::map<u32, HudElement*>::iterator it = player->hud.begin();
3420                                 it != player->hud.end(); ++it)
3421                         {
3422                                 HudElement* e = it->second;
3423                                 v2f posp(e->pos * v2f(screensize.X, screensize.Y));
3424                                 core::vector2d<s32> pos(posp.X, posp.Y);
3425                                 if(e->type == 'I'){         //Img
3426                                         video::ITexture *texture =
3427                                                 gamedef->getTextureSource()->getTextureRaw(e->text);
3428                                         const video::SColor color(255,255,255,255);
3429                                         const video::SColor colors[] = {color,color,color,color};
3430                                         core::dimension2di imgsize(texture->getOriginalSize());
3431                                         core::rect<s32> rect(0, 0, imgsize.Width*e->scale.X,
3432                                                                                                 imgsize.Height*e->scale.X);
3433                                         rect += pos;
3434                                         driver->draw2DImage(texture, rect,
3435                                                 core::rect<s32>(core::position2d<s32>(0,0), imgsize),
3436                                                 NULL, colors, true);
3437                                 } else if(e->type == 'T') { //Text
3438                                         std::wstring t;
3439                                         t.assign(e->text.begin(), e->text.end());
3440                                         gui::IGUIStaticText *luaguitext = guienv->addStaticText(
3441                                                         t.c_str(),
3442                                                         core::rect<s32>(0, 0, e->scale.X, text_height*(e->scale.Y))+pos,
3443                                                         false, false);
3444                                         luaguitexts.push_back(luaguitext);
3445                                 } else if(e->type == 'S') { //Statbar
3446                                         draw_statbar(driver, font, gamedef, pos, e->text, e->number);
3447                                 } else if(e->type == 's') { //Non-conflict Statbar
3448                                         v2s32 p(displaycenter.X - 143, screensize.Y - 76);
3449                                         p.X += e->pos.X*173;
3450                                         p.Y += e->pos.X*20;
3451                                         p.Y -= e->pos.Y*20;
3452                                         draw_statbar(driver, font, gamedef, p, e->text, e->number);
3453                                 } else if(e->type == 'i') { //Inv
3454                                         InventoryList* inv = local_inventory.getList(e->text);
3455                                         draw_item(driver, font, gamedef, pos, hotbar_imagesize,
3456                                                                 e->number, inv, e->item, e->dir);
3457                                 } else {
3458                                         actionstream<<"luadraw: ignoring drawform "<<it->second<<
3459                                                 "of key "<<it->first<<" due to incorrect command."<<std::endl;
3460                                         continue;
3461                                 }
3462                         }
3463                 }
3464
3465                 /*
3466                         Draw gui
3467                 */
3468                 // 0-1ms
3469                 guienv->drawAll();
3470
3471                 /*
3472                         Remove lua-texts
3473                 */
3474                 for(std::deque<gui::IGUIStaticText *>::iterator it = luaguitexts.begin();
3475                         it != luaguitexts.end(); ++it)
3476                         (*it)->remove();
3477
3478                 /*
3479                         End scene
3480                 */
3481                 {
3482                         TimeTaker timer("endScene");
3483                         endSceneX(driver);
3484                         endscenetime = timer.stop(true);
3485                 }
3486
3487                 drawtime = tt_draw.stop(true);
3488                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3489
3490                 /*
3491                         End of drawing
3492                 */
3493
3494                 static s16 lastFPS = 0;
3495                 //u16 fps = driver->getFPS();
3496                 u16 fps = (1.0/dtime_avg1);
3497
3498                 if (lastFPS != fps)
3499                 {
3500                         core::stringw str = L"Minetest [";
3501                         str += driver->getName();
3502                         str += "] FPS=";
3503                         str += fps;
3504
3505                         device->setWindowCaption(str.c_str());
3506                         lastFPS = fps;
3507                 }
3508
3509                 /*
3510                         Log times and stuff for visualization
3511                 */
3512                 Profiler::GraphValues values;
3513                 g_profiler->graphGet(values);
3514                 graph.put(values);
3515         }
3516
3517         /*
3518                 Drop stuff
3519         */
3520         if(clouds)
3521                 clouds->drop();
3522         if(gui_chat_console)
3523                 gui_chat_console->drop();
3524         clear_particles ();
3525         
3526         /*
3527                 Draw a "shutting down" screen, which will be shown while the map
3528                 generator and other stuff quits
3529         */
3530         {
3531                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3532                 draw_load_screen(L"Shutting down stuff...", driver, font);
3533                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3534                 guienv->drawAll();
3535                 driver->endScene();
3536                 gui_shuttingdowntext->remove();*/
3537         }
3538
3539         chat_backend.addMessage(L"", L"# Disconnected.");
3540         chat_backend.addMessage(L"", L"");
3541
3542         // Client scope (client is destructed before destructing *def and tsrc)
3543         }while(0);
3544         } // try-catch
3545         catch(SerializationError &e)
3546         {
3547                 error_message = L"A serialization error occurred:\n"
3548                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3549                                 L" running a different version of Minetest.";
3550                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3551         }
3552         catch(ServerError &e)
3553         {
3554                 error_message = narrow_to_wide(e.what());
3555                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3556         }
3557         catch(ModError &e)
3558         {
3559                 errorstream<<e.what()<<std::endl;
3560                 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3561         }
3562
3563
3564         
3565         if(!sound_is_dummy)
3566                 delete sound;
3567
3568         //has to be deleted first to stop all server threads
3569         delete server;
3570
3571         delete tsrc;
3572         delete shsrc;
3573         delete nodedef;
3574         delete itemdef;
3575
3576         //extended resource accounting
3577         infostream << "Irrlicht resources after cleanup:" << std::endl;
3578         infostream << "\tRemaining meshes   : "
3579                 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3580         infostream << "\tRemaining textures : "
3581                 << driver->getTextureCount() << std::endl;
3582         for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3583                 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3584                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3585                                 << std::endl;
3586         }
3587         infostream << "\tRemaining materials: "
3588                 << driver-> getMaterialRendererCount ()
3589                 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;
3590 }
3591
3592