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