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