]> git.lizzy.rs Git - minetest.git/blob - src/game.cpp
Add mouse_sensitivity option
[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
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                 // TODO: Facedir prediction
863                 // TODO: If predicted node is in attached_node group, check attachment
864                 // Add node to client map
865                 MapNode n(id, 0, param2);
866                 try{
867                         // This triggers the required mesh update too
868                         client.addNode(p, n);
869                 }catch(InvalidPositionException &e){
870                         errorstream<<"Node placement prediction failed for "
871                                         <<playeritem_def.name<<" (places "
872                                         <<prediction
873                                         <<") - Position not loaded"<<std::endl;
874                 }
875         }
876 }
877
878
879 void the_game(
880         bool &kill,
881         bool random_input,
882         InputHandler *input,
883         IrrlichtDevice *device,
884         gui::IGUIFont* font,
885         std::string map_dir,
886         std::string playername,
887         std::string password,
888         std::string address, // If "", local server is used
889         u16 port,
890         std::wstring &error_message,
891         std::string configpath,
892         ChatBackend &chat_backend,
893         const SubgameSpec &gamespec, // Used for local game,
894         bool simple_singleplayer_mode
895 )
896 {
897         FormspecFormSource* current_formspec = 0;
898         video::IVideoDriver* driver = device->getVideoDriver();
899         scene::ISceneManager* smgr = device->getSceneManager();
900         
901         // Calculate text height using the font
902         u32 text_height = font->getDimension(L"Random test string").Height;
903
904         v2u32 last_screensize(0,0);
905         v2u32 screensize = driver->getScreenSize();
906         
907         /*
908                 Draw "Loading" screen
909         */
910
911         {
912                 wchar_t* text = wgettext("Loading...");
913                 draw_load_screen(text, device, font,0,0);
914                 delete[] text;
915         }
916         
917         // Create texture source
918         IWritableTextureSource *tsrc = createTextureSource(device);
919         
920         // Create shader source
921         IWritableShaderSource *shsrc = createShaderSource(device);
922         
923         // These will be filled by data received from the server
924         // Create item definition manager
925         IWritableItemDefManager *itemdef = createItemDefManager();
926         // Create node definition manager
927         IWritableNodeDefManager *nodedef = createNodeDefManager();
928         
929         // Sound fetcher (useful when testing)
930         GameOnDemandSoundFetcher soundfetcher;
931
932         // Sound manager
933         ISoundManager *sound = NULL;
934         bool sound_is_dummy = false;
935 #if USE_SOUND
936         if(g_settings->getBool("enable_sound")){
937                 infostream<<"Attempting to use OpenAL audio"<<std::endl;
938                 sound = createOpenALSoundManager(&soundfetcher);
939                 if(!sound)
940                         infostream<<"Failed to initialize OpenAL audio"<<std::endl;
941         } else {
942                 infostream<<"Sound disabled."<<std::endl;
943         }
944 #endif
945         if(!sound){
946                 infostream<<"Using dummy audio."<<std::endl;
947                 sound = &dummySoundManager;
948                 sound_is_dummy = true;
949         }
950
951         Server *server = NULL;
952
953         try{
954         // Event manager
955         EventManager eventmgr;
956
957         // Sound maker
958         SoundMaker soundmaker(sound, nodedef);
959         soundmaker.registerReceiver(&eventmgr);
960         
961         // Add chat log output for errors to be shown in chat
962         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
963
964         // Create UI for modifying quicktune values
965         QuicktuneShortcutter quicktune;
966
967         /*
968                 Create server.
969         */
970
971         if(address == ""){
972                 wchar_t* text = wgettext("Creating server....");
973                 draw_load_screen(text, device, font,0,25);
974                 delete[] text;
975                 infostream<<"Creating server"<<std::endl;
976                 server = new Server(map_dir, configpath, gamespec,
977                                 simple_singleplayer_mode);
978                 server->start(port);
979         }
980
981         do{ // Client scope (breakable do-while(0))
982         
983         /*
984                 Create client
985         */
986
987         {
988                 wchar_t* text = wgettext("Creating client...");
989                 draw_load_screen(text, device, font,0,50);
990                 delete[] text;
991         }
992         infostream<<"Creating client"<<std::endl;
993         
994         MapDrawControl draw_control;
995
996         Client client(device, playername.c_str(), password, draw_control,
997                         tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
998         
999         // Client acts as our GameDef
1000         IGameDef *gamedef = &client;
1001         
1002         {
1003                 wchar_t* text = wgettext("Resolving address...");
1004                 draw_load_screen(text, device, font,0,75);
1005                 delete[] text;
1006         }
1007         Address connect_address(0,0,0,0, port);
1008         try{
1009                 if(address == "")
1010                         //connect_address.Resolve("localhost");
1011                         connect_address.setAddress(127,0,0,1);
1012                 else
1013                         connect_address.Resolve(address.c_str());
1014         }
1015         catch(ResolveError &e)
1016         {
1017                 error_message = L"Couldn't resolve address";
1018                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1019                 // Break out of client scope
1020                 break;
1021         }
1022
1023         /*
1024                 Attempt to connect to the server
1025         */
1026         
1027         infostream<<"Connecting to server at ";
1028         connect_address.print(&infostream);
1029         infostream<<std::endl;
1030         client.connect(connect_address);
1031         
1032         /*
1033                 Wait for server to accept connection
1034         */
1035         bool could_connect = false;
1036         bool connect_aborted = false;
1037         try{
1038                 float time_counter = 0.0;
1039                 input->clear();
1040                 float fps_max = g_settings->getFloat("fps_max");
1041                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1042                 u32 lasttime = device->getTimer()->getTime();
1043                 while(device->run())
1044                 {
1045                         f32 dtime=0; // in seconds
1046                         if (cloud_menu_background) {
1047                                 u32 time = device->getTimer()->getTime();
1048                                 if(time > lasttime)
1049                                         dtime = (time - lasttime) / 1000.0;
1050                                 else
1051                                         dtime = 0;
1052                                 lasttime = time;
1053                         }
1054                         // Update client and server
1055                         client.step(dtime);
1056                         if(server != NULL)
1057                                 server->step(dtime);
1058                         
1059                         // End condition
1060                         if(client.connectedAndInitialized()){
1061                                 could_connect = true;
1062                                 break;
1063                         }
1064                         // Break conditions
1065                         if(client.accessDenied()){
1066                                 error_message = L"Access denied. Reason: "
1067                                                 +client.accessDeniedReason();
1068                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1069                                 break;
1070                         }
1071                         if(input->wasKeyDown(EscapeKey)){
1072                                 connect_aborted = true;
1073                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1074                                 break;
1075                         }
1076                         
1077                         // Display status
1078                         {
1079                                 wchar_t* text = wgettext("Connecting to server...");
1080                                 draw_load_screen(text, device, font, dtime, 100);
1081                                 delete[] text;
1082                         }
1083                         
1084                         // On some computers framerate doesn't seem to be
1085                         // automatically limited
1086                         if (cloud_menu_background) {
1087                                 // Time of frame without fps limit
1088                                 float busytime;
1089                                 u32 busytime_u32;
1090                                 // not using getRealTime is necessary for wine
1091                                 u32 time = device->getTimer()->getTime();
1092                                 if(time > lasttime)
1093                                         busytime_u32 = time - lasttime;
1094                                 else
1095                                         busytime_u32 = 0;
1096                                 busytime = busytime_u32 / 1000.0;
1097
1098                                 // FPS limiter
1099                                 u32 frametime_min = 1000./fps_max;
1100
1101                                 if(busytime_u32 < frametime_min) {
1102                                         u32 sleeptime = frametime_min - busytime_u32;
1103                                         device->sleep(sleeptime);
1104                                 }
1105                         } else {
1106                                 sleep_ms(25);
1107                         }
1108                         time_counter += dtime;
1109                 }
1110         }
1111         catch(con::PeerNotFoundException &e)
1112         {}
1113         
1114         /*
1115                 Handle failure to connect
1116         */
1117         if(!could_connect){
1118                 if(error_message == L"" && !connect_aborted){
1119                         error_message = L"Connection failed";
1120                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1121                 }
1122                 // Break out of client scope
1123                 break;
1124         }
1125         
1126         /*
1127                 Wait until content has been received
1128         */
1129         bool got_content = false;
1130         bool content_aborted = false;
1131         {
1132                 float time_counter = 0.0;
1133                 input->clear();
1134                 float fps_max = g_settings->getFloat("fps_max");
1135                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1136                 u32 lasttime = device->getTimer()->getTime();
1137                 while(device->run())
1138                 {
1139                         f32 dtime=0; // in seconds
1140                         if (cloud_menu_background) {
1141                                 u32 time = device->getTimer()->getTime();
1142                                 if(time > lasttime)
1143                                         dtime = (time - lasttime) / 1000.0;
1144                                 else
1145                                         dtime = 0;
1146                                 lasttime = time;
1147                         }
1148                         // Update client and server
1149                         client.step(dtime);
1150                         if(server != NULL)
1151                                 server->step(dtime);
1152                         
1153                         // End condition
1154                         if(client.texturesReceived() &&
1155                                         client.itemdefReceived() &&
1156                                         client.nodedefReceived()){
1157                                 got_content = true;
1158                                 break;
1159                         }
1160                         // Break conditions
1161                         if(!client.connectedAndInitialized()){
1162                                 error_message = L"Client disconnected";
1163                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1164                                 break;
1165                         }
1166                         if(input->wasKeyDown(EscapeKey)){
1167                                 content_aborted = true;
1168                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1169                                 break;
1170                         }
1171                         
1172                         // Display status
1173                         std::ostringstream ss;
1174                         int progress=0;
1175                         if (!client.itemdefReceived())
1176                         {
1177                                 ss << "Item definitions...";
1178                                 progress = 0;
1179                         }
1180                         else if (!client.nodedefReceived())
1181                         {
1182                                 ss << "Node definitions...";
1183                                 progress = 25;
1184                         }
1185                         else
1186                         {
1187                                 ss << "Media...";
1188                                 progress = 50+client.mediaReceiveProgress()*50+0.5;
1189                         }
1190                         wchar_t* text = wgettext(ss.str().c_str());
1191                         draw_load_screen(text, device, font, dtime, progress);
1192                         delete[] text;
1193                         
1194                         // On some computers framerate doesn't seem to be
1195                         // automatically limited
1196                         if (cloud_menu_background) {
1197                                 // Time of frame without fps limit
1198                                 float busytime;
1199                                 u32 busytime_u32;
1200                                 // not using getRealTime is necessary for wine
1201                                 u32 time = device->getTimer()->getTime();
1202                                 if(time > lasttime)
1203                                         busytime_u32 = time - lasttime;
1204                                 else
1205                                         busytime_u32 = 0;
1206                                 busytime = busytime_u32 / 1000.0;
1207
1208                                 // FPS limiter
1209                                 u32 frametime_min = 1000./fps_max;
1210
1211                                 if(busytime_u32 < frametime_min) {
1212                                         u32 sleeptime = frametime_min - busytime_u32;
1213                                         device->sleep(sleeptime);
1214                                 }
1215                         } else {
1216                                 sleep_ms(25);
1217                         }
1218                         time_counter += dtime;
1219                 }
1220         }
1221
1222         if(!got_content){
1223                 if(error_message == L"" && !content_aborted){
1224                         error_message = L"Something failed";
1225                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1226                 }
1227                 // Break out of client scope
1228                 break;
1229         }
1230
1231         /*
1232                 After all content has been received:
1233                 Update cached textures, meshes and materials
1234         */
1235         client.afterContentReceived(device,font);
1236
1237         /*
1238                 Create the camera node
1239         */
1240         Camera camera(smgr, draw_control, gamedef);
1241         if (!camera.successfullyCreated(error_message))
1242                 return;
1243
1244         f32 camera_yaw = 0; // "right/left"
1245         f32 camera_pitch = 0; // "up/down"
1246
1247         /*
1248                 Clouds
1249         */
1250         
1251         Clouds *clouds = NULL;
1252         if(g_settings->getBool("enable_clouds"))
1253         {
1254                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1255         }
1256
1257         /*
1258                 Skybox thingy
1259         */
1260
1261         Sky *sky = NULL;
1262         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1263         
1264         /*
1265                 FarMesh
1266         */
1267
1268         FarMesh *farmesh = NULL;
1269         if(g_settings->getBool("enable_farmesh"))
1270         {
1271                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1272         }
1273
1274         /*
1275                 A copy of the local inventory
1276         */
1277         Inventory local_inventory(itemdef);
1278
1279         /*
1280                 Find out size of crack animation
1281         */
1282         int crack_animation_length = 5;
1283         {
1284                 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1285                 v2u32 size = t->getOriginalSize();
1286                 crack_animation_length = size.Y / size.X;
1287         }
1288
1289         /*
1290                 Add some gui stuff
1291         */
1292
1293         // First line of debug text
1294         gui::IGUIStaticText *guitext = guienv->addStaticText(
1295                         L"Minetest",
1296                         core::rect<s32>(5, 5, 795, 5+text_height),
1297                         false, false);
1298         // Second line of debug text
1299         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1300                         L"",
1301                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1302                         false, false);
1303         // At the middle of the screen
1304         // Object infos are shown in this
1305         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1306                         L"",
1307                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1308                         false, true);
1309         
1310         // Status text (displays info when showing and hiding GUI stuff, etc.)
1311         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1312                         L"<Status>",
1313                         core::rect<s32>(0,0,0,0),
1314                         false, false);
1315         guitext_status->setVisible(false);
1316         
1317         std::wstring statustext;
1318         float statustext_time = 0;
1319         
1320         // Chat text
1321         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1322                         L"",
1323                         core::rect<s32>(0,0,0,0),
1324                         //false, false); // Disable word wrap as of now
1325                         false, true);
1326         // Remove stale "recent" chat messages from previous connections
1327         chat_backend.clearRecentChat();
1328         // Chat backend and console
1329         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1330         
1331         // Profiler text (size is updated when text is updated)
1332         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1333                         L"<Profiler>",
1334                         core::rect<s32>(0,0,0,0),
1335                         false, false);
1336         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1337         guitext_profiler->setVisible(false);
1338         
1339         /*
1340                 Some statistics are collected in these
1341         */
1342         u32 drawtime = 0;
1343         u32 beginscenetime = 0;
1344         u32 scenetime = 0;
1345         u32 endscenetime = 0;
1346         
1347         float recent_turn_speed = 0.0;
1348         
1349         ProfilerGraph graph;
1350         // Initially clear the profiler
1351         Profiler::GraphValues dummyvalues;
1352         g_profiler->graphGet(dummyvalues);
1353
1354         float nodig_delay_timer = 0.0;
1355         float dig_time = 0.0;
1356         u16 dig_index = 0;
1357         PointedThing pointed_old;
1358         bool digging = false;
1359         bool ldown_for_dig = false;
1360
1361         float damage_flash = 0;
1362         s16 farmesh_range = 20*MAP_BLOCKSIZE;
1363
1364         float jump_timer = 0;
1365         bool reset_jump_timer = false;
1366
1367         const float object_hit_delay = 0.2;
1368         float object_hit_delay_timer = 0.0;
1369         float time_from_last_punch = 10;
1370
1371         float update_draw_list_timer = 0.0;
1372         v3f update_draw_list_last_cam_dir;
1373
1374         bool invert_mouse = g_settings->getBool("invert_mouse");
1375
1376         bool respawn_menu_active = false;
1377         bool update_wielded_item_trigger = false;
1378
1379         bool show_hud = true;
1380         bool show_chat = true;
1381         bool force_fog_off = false;
1382         f32 fog_range = 100*BS;
1383         bool disable_camera_update = false;
1384         bool show_debug = g_settings->getBool("show_debug");
1385         bool show_profiler_graph = false;
1386         u32 show_profiler = 0;
1387         u32 show_profiler_max = 3;  // Number of pages
1388
1389         float time_of_day = 0;
1390         float time_of_day_smooth = 0;
1391
1392         float repeat_rightclick_timer = 0;
1393
1394         /*
1395                 Shader constants
1396         */
1397         shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1398                         sky, &force_fog_off, &fog_range, &client));
1399
1400         /*
1401                 Main loop
1402         */
1403
1404         bool first_loop_after_window_activation = true;
1405
1406         // TODO: Convert the static interval timers to these
1407         // Interval limiter for profiler
1408         IntervalLimiter m_profiler_interval;
1409
1410         // Time is in milliseconds
1411         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1412         // NOTE: So we have to use getTime() and call run()s between them
1413         u32 lasttime = device->getTimer()->getTime();
1414
1415         LocalPlayer* player = client.getEnv().getLocalPlayer();
1416         player->hurt_tilt_timer = 0;
1417         player->hurt_tilt_strength = 0;
1418         
1419         /*
1420                 HUD object
1421         */
1422         Hud hud(driver, guienv, font, text_height,
1423                         gamedef, player, &local_inventory);
1424
1425         for(;;)
1426         {
1427                 if(device->run() == false || kill == true)
1428                         break;
1429
1430                 // Time of frame without fps limit
1431                 float busytime;
1432                 u32 busytime_u32;
1433                 {
1434                         // not using getRealTime is necessary for wine
1435                         u32 time = device->getTimer()->getTime();
1436                         if(time > lasttime)
1437                                 busytime_u32 = time - lasttime;
1438                         else
1439                                 busytime_u32 = 0;
1440                         busytime = busytime_u32 / 1000.0;
1441                 }
1442                 
1443                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1444
1445                 // Necessary for device->getTimer()->getTime()
1446                 device->run();
1447
1448                 /*
1449                         FPS limiter
1450                 */
1451
1452                 {
1453                         float fps_max = g_settings->getFloat("fps_max");
1454                         u32 frametime_min = 1000./fps_max;
1455                         
1456                         if(busytime_u32 < frametime_min)
1457                         {
1458                                 u32 sleeptime = frametime_min - busytime_u32;
1459                                 device->sleep(sleeptime);
1460                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1461                         }
1462                 }
1463
1464                 // Necessary for device->getTimer()->getTime()
1465                 device->run();
1466
1467                 /*
1468                         Time difference calculation
1469                 */
1470                 f32 dtime; // in seconds
1471                 
1472                 u32 time = device->getTimer()->getTime();
1473                 if(time > lasttime)
1474                         dtime = (time - lasttime) / 1000.0;
1475                 else
1476                         dtime = 0;
1477                 lasttime = time;
1478
1479                 g_profiler->graphAdd("mainloop_dtime", dtime);
1480
1481                 /* Run timers */
1482
1483                 if(nodig_delay_timer >= 0)
1484                         nodig_delay_timer -= dtime;
1485                 if(object_hit_delay_timer >= 0)
1486                         object_hit_delay_timer -= dtime;
1487                 time_from_last_punch += dtime;
1488                 
1489                 g_profiler->add("Elapsed time", dtime);
1490                 g_profiler->avg("FPS", 1./dtime);
1491
1492                 /*
1493                         Time average and jitter calculation
1494                 */
1495
1496                 static f32 dtime_avg1 = 0.0;
1497                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1498                 f32 dtime_jitter1 = dtime - dtime_avg1;
1499
1500                 static f32 dtime_jitter1_max_sample = 0.0;
1501                 static f32 dtime_jitter1_max_fraction = 0.0;
1502                 {
1503                         static f32 jitter1_max = 0.0;
1504                         static f32 counter = 0.0;
1505                         if(dtime_jitter1 > jitter1_max)
1506                                 jitter1_max = dtime_jitter1;
1507                         counter += dtime;
1508                         if(counter > 0.0)
1509                         {
1510                                 counter -= 3.0;
1511                                 dtime_jitter1_max_sample = jitter1_max;
1512                                 dtime_jitter1_max_fraction
1513                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1514                                 jitter1_max = 0.0;
1515                         }
1516                 }
1517                 
1518                 /*
1519                         Busytime average and jitter calculation
1520                 */
1521
1522                 static f32 busytime_avg1 = 0.0;
1523                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1524                 f32 busytime_jitter1 = busytime - busytime_avg1;
1525                 
1526                 static f32 busytime_jitter1_max_sample = 0.0;
1527                 static f32 busytime_jitter1_min_sample = 0.0;
1528                 {
1529                         static f32 jitter1_max = 0.0;
1530                         static f32 jitter1_min = 0.0;
1531                         static f32 counter = 0.0;
1532                         if(busytime_jitter1 > jitter1_max)
1533                                 jitter1_max = busytime_jitter1;
1534                         if(busytime_jitter1 < jitter1_min)
1535                                 jitter1_min = busytime_jitter1;
1536                         counter += dtime;
1537                         if(counter > 0.0){
1538                                 counter -= 3.0;
1539                                 busytime_jitter1_max_sample = jitter1_max;
1540                                 busytime_jitter1_min_sample = jitter1_min;
1541                                 jitter1_max = 0.0;
1542                                 jitter1_min = 0.0;
1543                         }
1544                 }
1545
1546                 /*
1547                         Handle miscellaneous stuff
1548                 */
1549                 
1550                 if(client.accessDenied())
1551                 {
1552                         error_message = L"Access denied. Reason: "
1553                                         +client.accessDeniedReason();
1554                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1555                         break;
1556                 }
1557
1558                 if(g_gamecallback->disconnect_requested)
1559                 {
1560                         g_gamecallback->disconnect_requested = false;
1561                         break;
1562                 }
1563
1564                 if(g_gamecallback->changepassword_requested)
1565                 {
1566                         (new GUIPasswordChange(guienv, guiroot, -1,
1567                                 &g_menumgr, &client))->drop();
1568                         g_gamecallback->changepassword_requested = false;
1569                 }
1570
1571                 if(g_gamecallback->changevolume_requested)
1572                 {
1573                         (new GUIVolumeChange(guienv, guiroot, -1,
1574                                 &g_menumgr, &client))->drop();
1575                         g_gamecallback->changevolume_requested = false;
1576                 }
1577
1578                 /* Process TextureSource's queue */
1579                 tsrc->processQueue();
1580
1581                 /* Process ItemDefManager's queue */
1582                 itemdef->processQueue(gamedef);
1583
1584                 /*
1585                         Process ShaderSource's queue
1586                 */
1587                 shsrc->processQueue();
1588
1589                 /*
1590                         Random calculations
1591                 */
1592                 last_screensize = screensize;
1593                 screensize = driver->getScreenSize();
1594                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1595                 //bool screensize_changed = screensize != last_screensize;
1596
1597                         
1598                 // Update HUD values
1599                 hud.screensize    = screensize;
1600                 hud.displaycenter = displaycenter;
1601                 hud.resizeHotbar();
1602                 
1603                 // Hilight boxes collected during the loop and displayed
1604                 std::vector<aabb3f> hilightboxes;
1605                 
1606                 // Info text
1607                 std::wstring infotext;
1608
1609                 /*
1610                         Debug info for client
1611                 */
1612                 {
1613                         static float counter = 0.0;
1614                         counter -= dtime;
1615                         if(counter < 0)
1616                         {
1617                                 counter = 30.0;
1618                                 client.printDebugInfo(infostream);
1619                         }
1620                 }
1621
1622                 /*
1623                         Profiler
1624                 */
1625                 float profiler_print_interval =
1626                                 g_settings->getFloat("profiler_print_interval");
1627                 bool print_to_log = true;
1628                 if(profiler_print_interval == 0){
1629                         print_to_log = false;
1630                         profiler_print_interval = 5;
1631                 }
1632                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1633                 {
1634                         if(print_to_log){
1635                                 infostream<<"Profiler:"<<std::endl;
1636                                 g_profiler->print(infostream);
1637                         }
1638
1639                         update_profiler_gui(guitext_profiler, font, text_height,
1640                                         show_profiler, show_profiler_max);
1641
1642                         g_profiler->clear();
1643                 }
1644
1645                 /*
1646                         Direct handling of user input
1647                 */
1648                 
1649                 // Reset input if window not active or some menu is active
1650                 if(device->isWindowActive() == false
1651                                 || noMenuActive() == false
1652                                 || guienv->hasFocus(gui_chat_console))
1653                 {
1654                         input->clear();
1655                 }
1656
1657                 // Input handler step() (used by the random input generator)
1658                 input->step(dtime);
1659
1660                 // Increase timer for doubleclick of "jump"
1661                 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1662                         jump_timer += dtime;
1663
1664                 /*
1665                         Launch menus and trigger stuff according to keys
1666                 */
1667                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1668                 {
1669                         // drop selected item
1670                         IDropAction *a = new IDropAction();
1671                         a->count = 0;
1672                         a->from_inv.setCurrentPlayer();
1673                         a->from_list = "main";
1674                         a->from_i = client.getPlayerItem();
1675                         client.inventoryAction(a);
1676                 }
1677                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1678                 {
1679                         infostream<<"the_game: "
1680                                         <<"Launching inventory"<<std::endl;
1681                         
1682                         GUIFormSpecMenu *menu =
1683                                 new GUIFormSpecMenu(device, guiroot, -1,
1684                                         &g_menumgr,
1685                                         &client, gamedef);
1686
1687                         InventoryLocation inventoryloc;
1688                         inventoryloc.setCurrentPlayer();
1689
1690                         PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1691                         assert(src);
1692                         menu->setFormSpec(src->getForm(), inventoryloc);
1693                         menu->setFormSource(src);
1694                         menu->setTextDest(new TextDestPlayerInventory(&client));
1695                         menu->drop();
1696                 }
1697                 else if(input->wasKeyDown(EscapeKey))
1698                 {
1699                         infostream<<"the_game: "
1700                                         <<"Launching pause menu"<<std::endl;
1701                         // It will delete itself by itself
1702                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1703                                         &g_menumgr, simple_singleplayer_mode))->drop();
1704
1705                         // Move mouse cursor on top of the disconnect button
1706                         if(simple_singleplayer_mode)
1707                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1708                         else
1709                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1710                 }
1711                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1712                 {
1713                         TextDest *dest = new TextDestChat(&client);
1714
1715                         (new GUITextInputMenu(guienv, guiroot, -1,
1716                                         &g_menumgr, dest,
1717                                         L""))->drop();
1718                 }
1719                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1720                 {
1721                         TextDest *dest = new TextDestChat(&client);
1722
1723                         (new GUITextInputMenu(guienv, guiroot, -1,
1724                                         &g_menumgr, dest,
1725                                         L"/"))->drop();
1726                 }
1727                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1728                 {
1729                         if (!gui_chat_console->isOpenInhibited())
1730                         {
1731                                 // Open up to over half of the screen
1732                                 gui_chat_console->openConsole(0.6);
1733                                 guienv->setFocus(gui_chat_console);
1734                         }
1735                 }
1736                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1737                 {
1738                         if(g_settings->getBool("free_move"))
1739                         {
1740                                 g_settings->set("free_move","false");
1741                                 statustext = L"free_move disabled";
1742                                 statustext_time = 0;
1743                         }
1744                         else
1745                         {
1746                                 g_settings->set("free_move","true");
1747                                 statustext = L"free_move enabled";
1748                                 statustext_time = 0;
1749                                 if(!client.checkPrivilege("fly"))
1750                                         statustext += L" (note: no 'fly' privilege)";
1751                         }
1752                 }
1753                 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1754                 {
1755                         if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1756                         {
1757                                 if(g_settings->getBool("free_move"))
1758                                 {
1759                                         g_settings->set("free_move","false");
1760                                         statustext = L"free_move disabled";
1761                                         statustext_time = 0;
1762                                 }
1763                                 else
1764                                 {
1765                                         g_settings->set("free_move","true");
1766                                         statustext = L"free_move enabled";
1767                                         statustext_time = 0;
1768                                         if(!client.checkPrivilege("fly"))
1769                                                 statustext += L" (note: no 'fly' privilege)";
1770                                 }
1771                         }
1772                         reset_jump_timer = true;
1773                 }
1774                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1775                 {
1776                         if(g_settings->getBool("fast_move"))
1777                         {
1778                                 g_settings->set("fast_move","false");
1779                                 statustext = L"fast_move disabled";
1780                                 statustext_time = 0;
1781                         }
1782                         else
1783                         {
1784                                 g_settings->set("fast_move","true");
1785                                 statustext = L"fast_move enabled";
1786                                 statustext_time = 0;
1787                                 if(!client.checkPrivilege("fast"))
1788                                         statustext += L" (note: no 'fast' privilege)";
1789                         }
1790                 }
1791                 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1792                 {
1793                         if(g_settings->getBool("noclip"))
1794                         {
1795                                 g_settings->set("noclip","false");
1796                                 statustext = L"noclip disabled";
1797                                 statustext_time = 0;
1798                         }
1799                         else
1800                         {
1801                                 g_settings->set("noclip","true");
1802                                 statustext = L"noclip enabled";
1803                                 statustext_time = 0;
1804                                 if(!client.checkPrivilege("noclip"))
1805                                         statustext += L" (note: no 'noclip' privilege)";
1806                         }
1807                 }
1808                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1809                 {
1810                         irr::video::IImage* const image = driver->createScreenShot(); 
1811                         if (image) { 
1812                                 irr::c8 filename[256]; 
1813                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1814                                                  g_settings->get("screenshot_path").c_str(),
1815                                                  device->getTimer()->getRealTime()); 
1816                                 if (driver->writeImageToFile(image, filename)) {
1817                                         std::wstringstream sstr;
1818                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1819                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1820                                         statustext = sstr.str();
1821                                         statustext_time = 0;
1822                                 } else{
1823                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1824                                 }
1825                                 image->drop(); 
1826                         }                        
1827                 }
1828                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1829                 {
1830                         show_hud = !show_hud;
1831                         if(show_hud)
1832                                 statustext = L"HUD shown";
1833                         else
1834                                 statustext = L"HUD hidden";
1835                         statustext_time = 0;
1836                 }
1837                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1838                 {
1839                         show_chat = !show_chat;
1840                         if(show_chat)
1841                                 statustext = L"Chat shown";
1842                         else
1843                                 statustext = L"Chat hidden";
1844                         statustext_time = 0;
1845                 }
1846                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1847                 {
1848                         force_fog_off = !force_fog_off;
1849                         if(force_fog_off)
1850                                 statustext = L"Fog disabled";
1851                         else
1852                                 statustext = L"Fog enabled";
1853                         statustext_time = 0;
1854                 }
1855                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1856                 {
1857                         disable_camera_update = !disable_camera_update;
1858                         if(disable_camera_update)
1859                                 statustext = L"Camera update disabled";
1860                         else
1861                                 statustext = L"Camera update enabled";
1862                         statustext_time = 0;
1863                 }
1864                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1865                 {
1866                         // Initial / 3x toggle: Chat only
1867                         // 1x toggle: Debug text with chat
1868                         // 2x toggle: Debug text with profiler graph
1869                         if(!show_debug)
1870                         {
1871                                 show_debug = true;
1872                                 show_profiler_graph = false;
1873                                 statustext = L"Debug info shown";
1874                                 statustext_time = 0;
1875                         }
1876                         else if(show_profiler_graph)
1877                         {
1878                                 show_debug = false;
1879                                 show_profiler_graph = false;
1880                                 statustext = L"Debug info and profiler graph hidden";
1881                                 statustext_time = 0;
1882                         }
1883                         else
1884                         {
1885                                 show_profiler_graph = true;
1886                                 statustext = L"Profiler graph shown";
1887                                 statustext_time = 0;
1888                         }
1889                 }
1890                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1891                 {
1892                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1893
1894                         // FIXME: This updates the profiler with incomplete values
1895                         update_profiler_gui(guitext_profiler, font, text_height,
1896                                         show_profiler, show_profiler_max);
1897
1898                         if(show_profiler != 0)
1899                         {
1900                                 std::wstringstream sstr;
1901                                 sstr<<"Profiler shown (page "<<show_profiler
1902                                         <<" of "<<show_profiler_max<<")";
1903                                 statustext = sstr.str();
1904                                 statustext_time = 0;
1905                         }
1906                         else
1907                         {
1908                                 statustext = L"Profiler hidden";
1909                                 statustext_time = 0;
1910                         }
1911                 }
1912                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1913                 {
1914                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1915                         s16 range_new = range + 10;
1916                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1917                         statustext = narrow_to_wide(
1918                                         "Minimum viewing range changed to "
1919                                         + itos(range_new));
1920                         statustext_time = 0;
1921                 }
1922                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1923                 {
1924                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1925                         s16 range_new = range - 10;
1926                         if(range_new < 0)
1927                                 range_new = range;
1928                         g_settings->set("viewing_range_nodes_min",
1929                                         itos(range_new));
1930                         statustext = narrow_to_wide(
1931                                         "Minimum viewing range changed to "
1932                                         + itos(range_new));
1933                         statustext_time = 0;
1934                 }
1935                 
1936                 // Reset jump_timer
1937                 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1938                 {
1939                         reset_jump_timer = false;
1940                         jump_timer = 0.0;
1941                 }
1942
1943                 // Handle QuicktuneShortcutter
1944                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1945                         quicktune.next();
1946                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1947                         quicktune.prev();
1948                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1949                         quicktune.inc();
1950                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1951                         quicktune.dec();
1952                 {
1953                         std::string msg = quicktune.getMessage();
1954                         if(msg != ""){
1955                                 statustext = narrow_to_wide(msg);
1956                                 statustext_time = 0;
1957                         }
1958                 }
1959
1960                 // Item selection with mouse wheel
1961                 u16 new_playeritem = client.getPlayerItem();
1962                 {
1963                         s32 wheel = input->getMouseWheel();
1964                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1965                                         hud.hotbar_itemcount-1);
1966
1967                         if(wheel < 0)
1968                         {
1969                                 if(new_playeritem < max_item)
1970                                         new_playeritem++;
1971                                 else
1972                                         new_playeritem = 0;
1973                         }
1974                         else if(wheel > 0)
1975                         {
1976                                 if(new_playeritem > 0)
1977                                         new_playeritem--;
1978                                 else
1979                                         new_playeritem = max_item;
1980                         }
1981                 }
1982                 
1983                 // Item selection
1984                 for(u16 i=0; i<10; i++)
1985                 {
1986                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1987                         if(input->wasKeyDown(*kp))
1988                         {
1989                                 if(i < PLAYER_INVENTORY_SIZE && i < hud.hotbar_itemcount)
1990                                 {
1991                                         new_playeritem = i;
1992
1993                                         infostream<<"Selected item: "
1994                                                         <<new_playeritem<<std::endl;
1995                                 }
1996                         }
1997                 }
1998
1999                 // Viewing range selection
2000                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2001                 {
2002                         draw_control.range_all = !draw_control.range_all;
2003                         if(draw_control.range_all)
2004                         {
2005                                 infostream<<"Enabled full viewing range"<<std::endl;
2006                                 statustext = L"Enabled full viewing range";
2007                                 statustext_time = 0;
2008                         }
2009                         else
2010                         {
2011                                 infostream<<"Disabled full viewing range"<<std::endl;
2012                                 statustext = L"Disabled full viewing range";
2013                                 statustext_time = 0;
2014                         }
2015                 }
2016
2017                 // Print debug stacks
2018                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2019                 {
2020                         dstream<<"-----------------------------------------"
2021                                         <<std::endl;
2022                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2023                         dstream<<"-----------------------------------------"
2024                                         <<std::endl;
2025                         debug_stacks_print();
2026                 }
2027
2028                 /*
2029                         Mouse and camera control
2030                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2031                 */
2032                 
2033                 float turn_amount = 0;
2034                 if((device->isWindowActive() && noMenuActive()) || random_input)
2035                 {
2036                         if(!random_input)
2037                         {
2038                                 // Mac OSX gets upset if this is set every frame
2039                                 if(device->getCursorControl()->isVisible())
2040                                         device->getCursorControl()->setVisible(false);
2041                         }
2042
2043                         if(first_loop_after_window_activation){
2044                                 //infostream<<"window active, first loop"<<std::endl;
2045                                 first_loop_after_window_activation = false;
2046                         }
2047                         else{
2048                                 s32 dx = input->getMousePos().X - displaycenter.X;
2049                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
2050                                 if(invert_mouse)
2051                                         dy = -dy;
2052                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2053                                 
2054                                 /*const float keyspeed = 500;
2055                                 if(input->isKeyDown(irr::KEY_UP))
2056                                         dy -= dtime * keyspeed;
2057                                 if(input->isKeyDown(irr::KEY_DOWN))
2058                                         dy += dtime * keyspeed;
2059                                 if(input->isKeyDown(irr::KEY_LEFT))
2060                                         dx -= dtime * keyspeed;
2061                                 if(input->isKeyDown(irr::KEY_RIGHT))
2062                                         dx += dtime * keyspeed;*/
2063                                 
2064                                 float d = g_settings->getFloat("mouse_sensitivity");
2065                                 d = rangelim(d, 0.01, 100.0);
2066                                 camera_yaw -= dx*d;
2067                                 camera_pitch += dy*d;
2068                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
2069                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
2070                                 
2071                                 turn_amount = v2f(dx, dy).getLength() * d;
2072                         }
2073                         input->setMousePos(displaycenter.X, displaycenter.Y);
2074                 }
2075                 else{
2076                         // Mac OSX gets upset if this is set every frame
2077                         if(device->getCursorControl()->isVisible() == false)
2078                                 device->getCursorControl()->setVisible(true);
2079
2080                         //infostream<<"window inactive"<<std::endl;
2081                         first_loop_after_window_activation = true;
2082                 }
2083                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2084                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2085
2086                 /*
2087                         Player speed control
2088                 */
2089                 {
2090                         /*bool a_up,
2091                         bool a_down,
2092                         bool a_left,
2093                         bool a_right,
2094                         bool a_jump,
2095                         bool a_superspeed,
2096                         bool a_sneak,
2097                         bool a_LMB,
2098                         bool a_RMB,
2099                         float a_pitch,
2100                         float a_yaw*/
2101                         PlayerControl control(
2102                                 input->isKeyDown(getKeySetting("keymap_forward")),
2103                                 input->isKeyDown(getKeySetting("keymap_backward")),
2104                                 input->isKeyDown(getKeySetting("keymap_left")),
2105                                 input->isKeyDown(getKeySetting("keymap_right")),
2106                                 input->isKeyDown(getKeySetting("keymap_jump")),
2107                                 input->isKeyDown(getKeySetting("keymap_special1")),
2108                                 input->isKeyDown(getKeySetting("keymap_sneak")),
2109                                 input->getLeftState(),
2110                                 input->getRightState(),
2111                                 camera_pitch,
2112                                 camera_yaw
2113                         );
2114                         client.setPlayerControl(control);
2115                         u32 keyPressed=
2116                         1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2117                         2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2118                         4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2119                         8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2120                         16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2121                         32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2122                         64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2123                         128*(int)input->getLeftState()+
2124                         256*(int)input->getRightState();
2125                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2126                         player->keyPressed=keyPressed;
2127                 }
2128                 
2129                 /*
2130                         Run server
2131                 */
2132
2133                 if(server != NULL)
2134                 {
2135                         //TimeTaker timer("server->step(dtime)");
2136                         server->step(dtime);
2137                 }
2138
2139                 /*
2140                         Process environment
2141                 */
2142                 
2143                 {
2144                         //TimeTaker timer("client.step(dtime)");
2145                         client.step(dtime);
2146                         //client.step(dtime_avg1);
2147                 }
2148
2149                 {
2150                         // Read client events
2151                         for(;;)
2152                         {
2153                                 ClientEvent event = client.getClientEvent();
2154                                 if(event.type == CE_NONE)
2155                                 {
2156                                         break;
2157                                 }
2158                                 else if(event.type == CE_PLAYER_DAMAGE &&
2159                                                 client.getHP() != 0)
2160                                 {
2161                                         //u16 damage = event.player_damage.amount;
2162                                         //infostream<<"Player damage: "<<damage<<std::endl;
2163
2164                                         damage_flash += 100.0;
2165                                         damage_flash += 8.0 * event.player_damage.amount;
2166
2167                                         player->hurt_tilt_timer = 1.5;
2168                                         player->hurt_tilt_strength = event.player_damage.amount/2;
2169                                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2170                                 }
2171                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
2172                                 {
2173                                         camera_yaw = event.player_force_move.yaw;
2174                                         camera_pitch = event.player_force_move.pitch;
2175                                 }
2176                                 else if(event.type == CE_DEATHSCREEN)
2177                                 {
2178                                         if(respawn_menu_active)
2179                                                 continue;
2180
2181                                         /*bool set_camera_point_target =
2182                                                         event.deathscreen.set_camera_point_target;
2183                                         v3f camera_point_target;
2184                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
2185                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
2186                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2187                                         MainRespawnInitiator *respawner =
2188                                                         new MainRespawnInitiator(
2189                                                                         &respawn_menu_active, &client);
2190                                         GUIDeathScreen *menu =
2191                                                         new GUIDeathScreen(guienv, guiroot, -1, 
2192                                                                 &g_menumgr, respawner);
2193                                         menu->drop();
2194                                         
2195                                         chat_backend.addMessage(L"", L"You died.");
2196
2197                                         /* Handle visualization */
2198
2199                                         damage_flash = 0;
2200
2201                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2202                                         player->hurt_tilt_timer = 0;
2203                                         player->hurt_tilt_strength = 0;
2204
2205                                         /*LocalPlayer* player = client.getLocalPlayer();
2206                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
2207                                         camera.update(player, busytime, screensize);*/
2208                                 }
2209                                 else if (event.type == CE_SHOW_FORMSPEC)
2210                                 {
2211                                         if (current_formspec == 0)
2212                                         {
2213                                                 /* Create menu */
2214                                                 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),&current_formspec);
2215
2216                                                 GUIFormSpecMenu *menu =
2217                                                                 new GUIFormSpecMenu(device, guiroot, -1,
2218                                                                                 &g_menumgr,
2219                                                                                 &client, gamedef);
2220                                                 menu->setFormSource(current_formspec);
2221                                                 menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
2222                                                 menu->drop();
2223                                         }
2224                                         else
2225                                         {
2226                                                 /* update menu */
2227                                                 current_formspec->setForm(*(event.show_formspec.formspec));
2228                                         }
2229                                         delete(event.show_formspec.formspec);
2230                                         delete(event.show_formspec.formname);
2231                                 }
2232                                 else if(event.type == CE_TEXTURES_UPDATED)
2233                                 {
2234                                         update_wielded_item_trigger = true;
2235                                 }
2236                                 else if(event.type == CE_SPAWN_PARTICLE)
2237                                 {
2238                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2239                                         AtlasPointer ap =
2240                                                 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2241
2242                                         new Particle(gamedef, smgr, player, client.getEnv(),
2243                                                 *event.spawn_particle.pos,
2244                                                 *event.spawn_particle.vel,
2245                                                 *event.spawn_particle.acc,
2246                                                  event.spawn_particle.expirationtime,
2247                                                  event.spawn_particle.size,
2248                                                  event.spawn_particle.collisiondetection, ap);
2249                                 }
2250                                 else if(event.type == CE_ADD_PARTICLESPAWNER)
2251                                 {
2252                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2253                                         AtlasPointer ap =
2254                                                 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2255
2256                                         new ParticleSpawner(gamedef, smgr, player,
2257                                                  event.add_particlespawner.amount,
2258                                                  event.add_particlespawner.spawntime,
2259                                                 *event.add_particlespawner.minpos,
2260                                                 *event.add_particlespawner.maxpos,
2261                                                 *event.add_particlespawner.minvel,
2262                                                 *event.add_particlespawner.maxvel,
2263                                                 *event.add_particlespawner.minacc,
2264                                                 *event.add_particlespawner.maxacc,
2265                                                  event.add_particlespawner.minexptime,
2266                                                  event.add_particlespawner.maxexptime,
2267                                                  event.add_particlespawner.minsize,
2268                                                  event.add_particlespawner.maxsize,
2269                                                  event.add_particlespawner.collisiondetection,
2270                                                  ap,
2271                                                  event.add_particlespawner.id);
2272                                 }
2273                                 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2274                                 {
2275                                         delete_particlespawner (event.delete_particlespawner.id);
2276                                 }
2277                                 else if (event.type == CE_HUDADD)
2278                                 {
2279                                         u32 id = event.hudadd.id;
2280                                         size_t nhudelem = player->hud.size();
2281                                         if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2282                                                 delete event.hudadd.pos;
2283                                                 delete event.hudadd.name;
2284                                                 delete event.hudadd.scale;
2285                                                 delete event.hudadd.text;
2286                                                 delete event.hudadd.align;
2287                                                 delete event.hudadd.offset;
2288                                                 continue;
2289                                         }
2290                                         
2291                                         HudElement *e = new HudElement;
2292                                         e->type   = (HudElementType)event.hudadd.type;
2293                                         e->pos    = *event.hudadd.pos;
2294                                         e->name   = *event.hudadd.name;
2295                                         e->scale  = *event.hudadd.scale;
2296                                         e->text   = *event.hudadd.text;
2297                                         e->number = event.hudadd.number;
2298                                         e->item   = event.hudadd.item;
2299                                         e->dir    = event.hudadd.dir;
2300                                         e->align  = *event.hudadd.align;
2301                                         e->offset = *event.hudadd.offset;
2302                                         
2303                                         if (id == nhudelem)
2304                                                 player->hud.push_back(e);
2305                                         else
2306                                                 player->hud[id] = e;
2307
2308                                         delete event.hudadd.pos;
2309                                         delete event.hudadd.name;
2310                                         delete event.hudadd.scale;
2311                                         delete event.hudadd.text;
2312                                         delete event.hudadd.align;
2313                                         delete event.hudadd.offset;
2314                                 }
2315                                 else if (event.type == CE_HUDRM)
2316                                 {
2317                                         u32 id = event.hudrm.id;
2318                                         if (id < player->hud.size() && player->hud[id]) {
2319                                                 delete player->hud[id];
2320                                                 player->hud[id] = NULL;
2321                                         }
2322                                 }
2323                                 else if (event.type == CE_HUDCHANGE)
2324                                 {
2325                                         u32 id = event.hudchange.id;
2326                                         if (id >= player->hud.size() || !player->hud[id]) {
2327                                                 delete event.hudchange.v2fdata;
2328                                                 delete event.hudchange.sdata;
2329                                                 continue;
2330                                         }
2331                                                 
2332                                         HudElement* e = player->hud[id];
2333                                         switch (event.hudchange.stat) {
2334                                                 case HUD_STAT_POS:
2335                                                         e->pos = *event.hudchange.v2fdata;
2336                                                         break;
2337                                                 case HUD_STAT_NAME:
2338                                                         e->name = *event.hudchange.sdata;
2339                                                         break;
2340                                                 case HUD_STAT_SCALE:
2341                                                         e->scale = *event.hudchange.v2fdata;
2342                                                         break;
2343                                                 case HUD_STAT_TEXT:
2344                                                         e->text = *event.hudchange.sdata;
2345                                                         break;
2346                                                 case HUD_STAT_NUMBER:
2347                                                         e->number = event.hudchange.data;
2348                                                         break;
2349                                                 case HUD_STAT_ITEM:
2350                                                         e->item = event.hudchange.data;
2351                                                         break;
2352                                                 case HUD_STAT_DIR:
2353                                                         e->dir = event.hudchange.data;
2354                                                         break;
2355                                                 case HUD_STAT_ALIGN:
2356                                                         e->align = *event.hudchange.v2fdata;
2357                                                         break;
2358                                                 case HUD_STAT_OFFSET:
2359                                                         e->offset = *event.hudchange.v2fdata;
2360                                                         break;
2361                                         }
2362                                         
2363                                         delete event.hudchange.v2fdata;
2364                                         delete event.hudchange.sdata;
2365                                 }
2366                         }
2367                 }
2368                 
2369                 //TimeTaker //timer2("//timer2");
2370
2371                 /*
2372                         For interaction purposes, get info about the held item
2373                         - What item is it?
2374                         - Is it a usable item?
2375                         - Can it point to liquids?
2376                 */
2377                 ItemStack playeritem;
2378                 {
2379                         InventoryList *mlist = local_inventory.getList("main");
2380                         if(mlist != NULL)
2381                         {
2382                                 playeritem = mlist->getItem(client.getPlayerItem());
2383                         }
2384                 }
2385                 const ItemDefinition &playeritem_def =
2386                                 playeritem.getDefinition(itemdef);
2387                 ToolCapabilities playeritem_toolcap =
2388                                 playeritem.getToolCapabilities(itemdef);
2389                 
2390                 /*
2391                         Update camera
2392                 */
2393
2394                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2395                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2396                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2397                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2398                 camera.update(player, busytime, screensize, tool_reload_ratio);
2399                 camera.step(dtime);
2400
2401                 v3f player_position = player->getPosition();
2402                 v3f camera_position = camera.getPosition();
2403                 v3f camera_direction = camera.getDirection();
2404                 f32 camera_fov = camera.getFovMax();
2405                 
2406                 if(!disable_camera_update){
2407                         client.getEnv().getClientMap().updateCamera(camera_position,
2408                                 camera_direction, camera_fov);
2409                 }
2410                 
2411                 // Update sound listener
2412                 sound->updateListener(camera.getCameraNode()->getPosition(),
2413                                 v3f(0,0,0), // velocity
2414                                 camera.getDirection(),
2415                                 camera.getCameraNode()->getUpVector());
2416                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2417
2418                 /*
2419                         Update sound maker
2420                 */
2421                 {
2422                         soundmaker.step(dtime);
2423                         
2424                         ClientMap &map = client.getEnv().getClientMap();
2425                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2426                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2427                 }
2428
2429                 /*
2430                         Calculate what block is the crosshair pointing to
2431                 */
2432                 
2433                 //u32 t1 = device->getTimer()->getRealTime();
2434                 
2435                 f32 d = 4; // max. distance
2436                 core::line3d<f32> shootline(camera_position,
2437                                 camera_position + camera_direction * BS * (d+1));
2438
2439                 ClientActiveObject *selected_object = NULL;
2440
2441                 PointedThing pointed = getPointedThing(
2442                                 // input
2443                                 &client, player_position, camera_direction,
2444                                 camera_position, shootline, d,
2445                                 playeritem_def.liquids_pointable, !ldown_for_dig,
2446                                 // output
2447                                 hilightboxes,
2448                                 selected_object);
2449
2450                 if(pointed != pointed_old)
2451                 {
2452                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2453                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2454                 }
2455
2456                 /*
2457                         Stop digging when
2458                         - releasing left mouse button
2459                         - pointing away from node
2460                 */
2461                 if(digging)
2462                 {
2463                         if(input->getLeftReleased())
2464                         {
2465                                 infostream<<"Left button released"
2466                                         <<" (stopped digging)"<<std::endl;
2467                                 digging = false;
2468                         }
2469                         else if(pointed != pointed_old)
2470                         {
2471                                 if (pointed.type == POINTEDTHING_NODE
2472                                         && pointed_old.type == POINTEDTHING_NODE
2473                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2474                                 {
2475                                         // Still pointing to the same node,
2476                                         // but a different face. Don't reset.
2477                                 }
2478                                 else
2479                                 {
2480                                         infostream<<"Pointing away from node"
2481                                                 <<" (stopped digging)"<<std::endl;
2482                                         digging = false;
2483                                 }
2484                         }
2485                         if(!digging)
2486                         {
2487                                 client.interact(1, pointed_old);
2488                                 client.setCrack(-1, v3s16(0,0,0));
2489                                 dig_time = 0.0;
2490                         }
2491                 }
2492                 if(!digging && ldown_for_dig && !input->getLeftState())
2493                 {
2494                         ldown_for_dig = false;
2495                 }
2496
2497                 bool left_punch = false;
2498                 soundmaker.m_player_leftpunch_sound.name = "";
2499
2500                 if(input->getRightState())
2501                         repeat_rightclick_timer += dtime;
2502                 else
2503                         repeat_rightclick_timer = 0;
2504
2505                 if(playeritem_def.usable && input->getLeftState())
2506                 {
2507                         if(input->getLeftClicked())
2508                                 client.interact(4, pointed);
2509                 }
2510                 else if(pointed.type == POINTEDTHING_NODE)
2511                 {
2512                         v3s16 nodepos = pointed.node_undersurface;
2513                         v3s16 neighbourpos = pointed.node_abovesurface;
2514
2515                         /*
2516                                 Check information text of node
2517                         */
2518                         
2519                         ClientMap &map = client.getEnv().getClientMap();
2520                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2521                         if(meta){
2522                                 infotext = narrow_to_wide(meta->getString("infotext"));
2523                         } else {
2524                                 MapNode n = map.getNode(nodepos);
2525                                 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2526                                         infotext = L"Unknown node: ";
2527                                         infotext += narrow_to_wide(nodedef->get(n).name);
2528                                 }
2529                         }
2530                         
2531                         /*
2532                                 Handle digging
2533                         */
2534                         
2535                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
2536                         {
2537                                 if(!digging)
2538                                 {
2539                                         infostream<<"Started digging"<<std::endl;
2540                                         client.interact(0, pointed);
2541                                         digging = true;
2542                                         ldown_for_dig = true;
2543                                 }
2544                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2545                                 
2546                                 // NOTE: Similar piece of code exists on the server side for
2547                                 // cheat detection.
2548                                 // Get digging parameters
2549                                 DigParams params = getDigParams(nodedef->get(n).groups,
2550                                                 &playeritem_toolcap);
2551                                 // If can't dig, try hand
2552                                 if(!params.diggable){
2553                                         const ItemDefinition &hand = itemdef->get("");
2554                                         const ToolCapabilities *tp = hand.tool_capabilities;
2555                                         if(tp)
2556                                                 params = getDigParams(nodedef->get(n).groups, tp);
2557                                 }
2558                                 
2559                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2560                                 if(sound_dig.exists()){
2561                                         if(sound_dig.name == "__group"){
2562                                                 if(params.main_group != ""){
2563                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2564                                                         soundmaker.m_player_leftpunch_sound.name =
2565                                                                         std::string("default_dig_") +
2566                                                                                         params.main_group;
2567                                                 }
2568                                         } else{
2569                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2570                                         }
2571                                 }
2572
2573                                 float dig_time_complete = 0.0;
2574
2575                                 if(params.diggable == false)
2576                                 {
2577                                         // I guess nobody will wait for this long
2578                                         dig_time_complete = 10000000.0;
2579                                 }
2580                                 else
2581                                 {
2582                                         dig_time_complete = params.time;
2583                                         if (g_settings->getBool("enable_particles"))
2584                                         {
2585                                                 const ContentFeatures &features =
2586                                                         client.getNodeDefManager()->get(n);
2587                                                 addPunchingParticles
2588                                                         (gamedef, smgr, player, client.getEnv(),
2589                                                          nodepos, features.tiles);
2590                                         }
2591                                 }
2592
2593                                 if(dig_time_complete >= 0.001)
2594                                 {
2595                                         dig_index = (u16)((float)crack_animation_length
2596                                                         * dig_time/dig_time_complete);
2597                                 }
2598                                 // This is for torches
2599                                 else
2600                                 {
2601                                         dig_index = crack_animation_length;
2602                                 }
2603
2604                                 // Don't show cracks if not diggable
2605                                 if(dig_time_complete >= 100000.0)
2606                                 {
2607                                 }
2608                                 else if(dig_index < crack_animation_length)
2609                                 {
2610                                         //TimeTaker timer("client.setTempMod");
2611                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2612                                         client.setCrack(dig_index, nodepos);
2613                                 }
2614                                 else
2615                                 {
2616                                         infostream<<"Digging completed"<<std::endl;
2617                                         client.interact(2, pointed);
2618                                         client.setCrack(-1, v3s16(0,0,0));
2619                                         MapNode wasnode = map.getNode(nodepos);
2620                                         client.removeNode(nodepos);
2621
2622                                         if (g_settings->getBool("enable_particles"))
2623                                         {
2624                                                 const ContentFeatures &features =
2625                                                         client.getNodeDefManager()->get(wasnode);
2626                                                 addDiggingParticles
2627                                                         (gamedef, smgr, player, client.getEnv(),
2628                                                          nodepos, features.tiles);
2629                                         }
2630
2631                                         dig_time = 0;
2632                                         digging = false;
2633
2634                                         nodig_delay_timer = dig_time_complete
2635                                                         / (float)crack_animation_length;
2636
2637                                         // We don't want a corresponding delay to
2638                                         // very time consuming nodes
2639                                         if(nodig_delay_timer > 0.3)
2640                                                 nodig_delay_timer = 0.3;
2641                                         // We want a slight delay to very little
2642                                         // time consuming nodes
2643                                         float mindelay = 0.15;
2644                                         if(nodig_delay_timer < mindelay)
2645                                                 nodig_delay_timer = mindelay;
2646                                         
2647                                         // Send event to trigger sound
2648                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2649                                         gamedef->event()->put(e);
2650                                 }
2651
2652                                 dig_time += dtime;
2653
2654                                 camera.setDigging(0);  // left click animation
2655                         }
2656
2657                         if(input->getRightClicked() ||
2658                                         repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2659                         {
2660                                 repeat_rightclick_timer = 0;
2661                                 infostream<<"Ground right-clicked"<<std::endl;
2662                                 
2663                                 // Sign special case, at least until formspec is properly implemented.
2664                                 // Deprecated?
2665                                 if(meta && meta->getString("formspec") == "hack:sign_text_input" 
2666                                                 && !random_input
2667                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2668                                 {
2669                                         infostream<<"Launching metadata text input"<<std::endl;
2670                                         
2671                                         // Get a new text for it
2672
2673                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2674
2675                                         std::wstring wtext = narrow_to_wide(meta->getString("text"));
2676
2677                                         (new GUITextInputMenu(guienv, guiroot, -1,
2678                                                         &g_menumgr, dest,
2679                                                         wtext))->drop();
2680                                 }
2681                                 // If metadata provides an inventory view, activate it
2682                                 else if(meta && meta->getString("formspec") != "" && !random_input
2683                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2684                                 {
2685                                         infostream<<"Launching custom inventory view"<<std::endl;
2686
2687                                         InventoryLocation inventoryloc;
2688                                         inventoryloc.setNodeMeta(nodepos);
2689                                         
2690                                         /* Create menu */
2691
2692                                         GUIFormSpecMenu *menu =
2693                                                 new GUIFormSpecMenu(device, guiroot, -1,
2694                                                         &g_menumgr,
2695                                                         &client, gamedef);
2696                                         menu->setFormSpec(meta->getString("formspec"),
2697                                                         inventoryloc);
2698                                         menu->setFormSource(new NodeMetadataFormSource(
2699                                                         &client.getEnv().getClientMap(), nodepos));
2700                                         menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2701                                         menu->drop();
2702                                 }
2703                                 // Otherwise report right click to server
2704                                 else
2705                                 {
2706                                         // Report to server
2707                                         client.interact(3, pointed);
2708                                         camera.setDigging(1);  // right click animation
2709                                         
2710                                         // If the wielded item has node placement prediction,
2711                                         // make that happen
2712                                         nodePlacementPrediction(client,
2713                                                         playeritem_def,
2714                                                         nodepos, neighbourpos);
2715                                         
2716                                         // Read the sound
2717                                         soundmaker.m_player_rightpunch_sound =
2718                                                         playeritem_def.sound_place;
2719                                 }
2720                         }
2721                 }
2722                 else if(pointed.type == POINTEDTHING_OBJECT)
2723                 {
2724                         infotext = narrow_to_wide(selected_object->infoText());
2725
2726                         if(infotext == L"" && show_debug){
2727                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2728                         }
2729
2730                         //if(input->getLeftClicked())
2731                         if(input->getLeftState())
2732                         {
2733                                 bool do_punch = false;
2734                                 bool do_punch_damage = false;
2735                                 if(object_hit_delay_timer <= 0.0){
2736                                         do_punch = true;
2737                                         do_punch_damage = true;
2738                                         object_hit_delay_timer = object_hit_delay;
2739                                 }
2740                                 if(input->getLeftClicked()){
2741                                         do_punch = true;
2742                                 }
2743                                 if(do_punch){
2744                                         infostream<<"Left-clicked object"<<std::endl;
2745                                         left_punch = true;
2746                                 }
2747                                 if(do_punch_damage){
2748                                         // Report direct punch
2749                                         v3f objpos = selected_object->getPosition();
2750                                         v3f dir = (objpos - player_position).normalize();
2751                                         
2752                                         bool disable_send = selected_object->directReportPunch(
2753                                                         dir, &playeritem, time_from_last_punch);
2754                                         time_from_last_punch = 0;
2755                                         if(!disable_send)
2756                                                 client.interact(0, pointed);
2757                                 }
2758                         }
2759                         else if(input->getRightClicked())
2760                         {
2761                                 infostream<<"Right-clicked object"<<std::endl;
2762                                 client.interact(3, pointed);  // place
2763                         }
2764                 }
2765                 else if(input->getLeftState())
2766                 {
2767                         // When button is held down in air, show continuous animation
2768                         left_punch = true;
2769                 }
2770
2771                 pointed_old = pointed;
2772                 
2773                 if(left_punch || input->getLeftClicked())
2774                 {
2775                         camera.setDigging(0); // left click animation
2776                 }
2777
2778                 input->resetLeftClicked();
2779                 input->resetRightClicked();
2780
2781                 input->resetLeftReleased();
2782                 input->resetRightReleased();
2783                 
2784                 /*
2785                         Calculate stuff for drawing
2786                 */
2787
2788                 /*
2789                         Fog range
2790                 */
2791         
2792                 if(farmesh)
2793                 {
2794                         fog_range = BS*farmesh_range;
2795                 }
2796                 else
2797                 {
2798                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2799                         fog_range *= 0.9;
2800                         if(draw_control.range_all)
2801                                 fog_range = 100000*BS;
2802                 }
2803
2804                 /*
2805                         Calculate general brightness
2806                 */
2807                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2808                 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2809                 float direct_brightness = 0;
2810                 bool sunlight_seen = false;
2811                 if(g_settings->getBool("free_move")){
2812                         direct_brightness = time_brightness;
2813                         sunlight_seen = true;
2814                 } else {
2815                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2816                         float old_brightness = sky->getBrightness();
2817                         direct_brightness = (float)client.getEnv().getClientMap()
2818                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2819                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2820                                         / 255.0;
2821                 }
2822                 
2823                 time_of_day = client.getEnv().getTimeOfDayF();
2824                 float maxsm = 0.05;
2825                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2826                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2827                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2828                         time_of_day_smooth = time_of_day;
2829                 float todsm = 0.05;
2830                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2831                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2832                                         + (time_of_day+1.0) * todsm;
2833                 else
2834                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2835                                         + time_of_day * todsm;
2836                         
2837                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2838                                 sunlight_seen);
2839                 
2840                 float brightness = sky->getBrightness();
2841                 video::SColor bgcolor = sky->getBgColor();
2842                 video::SColor skycolor = sky->getSkyColor();
2843
2844                 /*
2845                         Update clouds
2846                 */
2847                 if(clouds){
2848                         if(sky->getCloudsVisible()){
2849                                 clouds->setVisible(true);
2850                                 clouds->step(dtime);
2851                                 clouds->update(v2f(player_position.X, player_position.Z),
2852                                                 sky->getCloudColor());
2853                         } else{
2854                                 clouds->setVisible(false);
2855                         }
2856                 }
2857                 
2858                 /*
2859                         Update farmesh
2860                 */
2861                 if(farmesh)
2862                 {
2863                         farmesh_range = draw_control.wanted_range * 10;
2864                         if(draw_control.range_all && farmesh_range < 500)
2865                                 farmesh_range = 500;
2866                         if(farmesh_range > 1000)
2867                                 farmesh_range = 1000;
2868
2869                         farmesh->step(dtime);
2870                         farmesh->update(v2f(player_position.X, player_position.Z),
2871                                         brightness, farmesh_range);
2872                 }
2873
2874                 /*
2875                         Update particles
2876                 */
2877
2878                 allparticles_step(dtime, client.getEnv());
2879                 allparticlespawners_step(dtime, client.getEnv());
2880                 
2881                 /*
2882                         Fog
2883                 */
2884                 
2885                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2886                 {
2887                         driver->setFog(
2888                                 bgcolor,
2889                                 video::EFT_FOG_LINEAR,
2890                                 fog_range*0.4,
2891                                 fog_range*1.0,
2892                                 0.01,
2893                                 false, // pixel fog
2894                                 false // range fog
2895                         );
2896                 }
2897                 else
2898                 {
2899                         driver->setFog(
2900                                 bgcolor,
2901                                 video::EFT_FOG_LINEAR,
2902                                 100000*BS,
2903                                 110000*BS,
2904                                 0.01,
2905                                 false, // pixel fog
2906                                 false // range fog
2907                         );
2908                 }
2909
2910                 /*
2911                         Update gui stuff (0ms)
2912                 */
2913
2914                 //TimeTaker guiupdatetimer("Gui updating");
2915                 
2916                 const char program_name_and_version[] =
2917                         "Minetest " VERSION_STRING;
2918
2919                 if(show_debug)
2920                 {
2921                         static float drawtime_avg = 0;
2922                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2923                         /*static float beginscenetime_avg = 0;
2924                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2925                         static float scenetime_avg = 0;
2926                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2927                         static float endscenetime_avg = 0;
2928                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2929                         
2930                         char temptext[300];
2931                         snprintf(temptext, 300, "%s ("
2932                                         "R: range_all=%i"
2933                                         ")"
2934                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2935                                         ", v_range = %.1f, RTT = %.3f",
2936                                         program_name_and_version,
2937                                         draw_control.range_all,
2938                                         drawtime_avg,
2939                                         dtime_jitter1_max_fraction * 100.0,
2940                                         draw_control.wanted_range,
2941                                         client.getRTT()
2942                                         );
2943                         
2944                         guitext->setText(narrow_to_wide(temptext).c_str());
2945                         guitext->setVisible(true);
2946                 }
2947                 else if(show_hud || show_chat)
2948                 {
2949                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2950                         guitext->setVisible(true);
2951                 }
2952                 else
2953                 {
2954                         guitext->setVisible(false);
2955                 }
2956                 
2957                 if(show_debug)
2958                 {
2959                         char temptext[300];
2960                         snprintf(temptext, 300,
2961                                         "(% .1f, % .1f, % .1f)"
2962                                         " (yaw = %.1f) (seed = %llu)",
2963                                         player_position.X/BS,
2964                                         player_position.Y/BS,
2965                                         player_position.Z/BS,
2966                                         wrapDegrees_0_360(camera_yaw),
2967                                         (unsigned long long)client.getMapSeed());
2968
2969                         guitext2->setText(narrow_to_wide(temptext).c_str());
2970                         guitext2->setVisible(true);
2971                 }
2972                 else
2973                 {
2974                         guitext2->setVisible(false);
2975                 }
2976                 
2977                 {
2978                         guitext_info->setText(infotext.c_str());
2979                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2980                 }
2981
2982                 {
2983                         float statustext_time_max = 1.5;
2984                         if(!statustext.empty())
2985                         {
2986                                 statustext_time += dtime;
2987                                 if(statustext_time >= statustext_time_max)
2988                                 {
2989                                         statustext = L"";
2990                                         statustext_time = 0;
2991                                 }
2992                         }
2993                         guitext_status->setText(statustext.c_str());
2994                         guitext_status->setVisible(!statustext.empty());
2995
2996                         if(!statustext.empty())
2997                         {
2998                                 s32 status_y = screensize.Y - 130;
2999                                 core::rect<s32> rect(
3000                                                 10,
3001                                                 status_y - guitext_status->getTextHeight(),
3002                                                 screensize.X - 10,
3003                                                 status_y
3004                                 );
3005                                 guitext_status->setRelativePosition(rect);
3006
3007                                 // Fade out
3008                                 video::SColor initial_color(255,0,0,0);
3009                                 if(guienv->getSkin())
3010                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3011                                 video::SColor final_color = initial_color;
3012                                 final_color.setAlpha(0);
3013                                 video::SColor fade_color =
3014                                         initial_color.getInterpolated_quadratic(
3015                                                 initial_color,
3016                                                 final_color,
3017                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
3018                                 guitext_status->setOverrideColor(fade_color);
3019                                 guitext_status->enableOverrideColor(true);
3020                         }
3021                 }
3022                 
3023                 /*
3024                         Get chat messages from client
3025                 */
3026                 {
3027                         // Get new messages from error log buffer
3028                         while(!chat_log_error_buf.empty())
3029                         {
3030                                 chat_backend.addMessage(L"", narrow_to_wide(
3031                                                 chat_log_error_buf.get()));
3032                         }
3033                         // Get new messages from client
3034                         std::wstring message;
3035                         while(client.getChatMessage(message))
3036                         {
3037                                 chat_backend.addUnparsedMessage(message);
3038                         }
3039                         // Remove old messages
3040                         chat_backend.step(dtime);
3041
3042                         // Display all messages in a static text element
3043                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3044                         std::wstring recent_chat = chat_backend.getRecentChat();
3045                         guitext_chat->setText(recent_chat.c_str());
3046
3047                         // Update gui element size and position
3048                         s32 chat_y = 5+(text_height+5);
3049                         if(show_debug)
3050                                 chat_y += (text_height+5);
3051                         core::rect<s32> rect(
3052                                 10,
3053                                 chat_y,
3054                                 screensize.X - 10,
3055                                 chat_y + guitext_chat->getTextHeight()
3056                         );
3057                         guitext_chat->setRelativePosition(rect);
3058
3059                         // Don't show chat if disabled or empty or profiler is enabled
3060                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
3061                                         && !show_profiler);
3062                 }
3063
3064                 /*
3065                         Inventory
3066                 */
3067                 
3068                 if(client.getPlayerItem() != new_playeritem)
3069                 {
3070                         client.selectPlayerItem(new_playeritem);
3071                 }
3072                 if(client.getLocalInventoryUpdated())
3073                 {
3074                         //infostream<<"Updating local inventory"<<std::endl;
3075                         client.getLocalInventory(local_inventory);
3076                         
3077                         update_wielded_item_trigger = true;
3078                 }
3079                 if(update_wielded_item_trigger)
3080                 {
3081                         update_wielded_item_trigger = false;
3082                         // Update wielded tool
3083                         InventoryList *mlist = local_inventory.getList("main");
3084                         ItemStack item;
3085                         if(mlist != NULL)
3086                                 item = mlist->getItem(client.getPlayerItem());
3087                         camera.wield(item);
3088                 }
3089
3090                 /*
3091                         Update block draw list every 200ms or when camera direction has
3092                         changed much
3093                 */
3094                 update_draw_list_timer += dtime;
3095                 if(update_draw_list_timer >= 0.2 ||
3096                                 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3097                         update_draw_list_timer = 0;
3098                         client.getEnv().getClientMap().updateDrawList(driver);
3099                         update_draw_list_last_cam_dir = camera_direction;
3100                 }
3101
3102                 /*
3103                         Drawing begins
3104                 */
3105
3106                 TimeTaker tt_draw("mainloop: draw");
3107                 
3108                 {
3109                         TimeTaker timer("beginScene");
3110                         //driver->beginScene(false, true, bgcolor);
3111                         //driver->beginScene(true, true, bgcolor);
3112                         driver->beginScene(true, true, skycolor);
3113                         beginscenetime = timer.stop(true);
3114                 }
3115                 
3116                 //timer3.stop();
3117         
3118                 //infostream<<"smgr->drawAll()"<<std::endl;
3119                 {
3120                         TimeTaker timer("smgr");
3121                         smgr->drawAll();
3122                         
3123                         if(g_settings->getBool("anaglyph"))
3124                         {
3125                                 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3126                                 irr::core::vector3df oldTarget   = camera.getCameraNode()->getTarget();
3127
3128                                 irr::core::matrix4 startMatrix   = camera.getCameraNode()->getAbsoluteTransformation();
3129
3130                                 irr::core::vector3df focusPoint  = (camera.getCameraNode()->getTarget() -
3131                                                                                  camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3132                                                                                  camera.getCameraNode()->getAbsolutePosition() ;
3133
3134                                 //Left eye...
3135                                 irr::core::vector3df leftEye;
3136                                 irr::core::matrix4   leftMove;
3137
3138                                 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3139                                 leftEye=(startMatrix*leftMove).getTranslation();
3140
3141                                 //clear the depth buffer, and color
3142                                 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3143
3144                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3145                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
3146                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX + 
3147                                                                                                                          irr::scene::ESNRP_SOLID +
3148                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
3149                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
3150                                                                                                                          irr::scene::ESNRP_SHADOW;
3151
3152                                 camera.getCameraNode()->setPosition( leftEye );
3153                                 camera.getCameraNode()->setTarget( focusPoint );
3154
3155                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
3156
3157
3158                                 //Right eye...
3159                                 irr::core::vector3df rightEye;
3160                                 irr::core::matrix4   rightMove;
3161
3162                                 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3163                                 rightEye=(startMatrix*rightMove).getTranslation();
3164
3165                                 //clear the depth buffer
3166                                 driver->clearZBuffer();
3167
3168                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3169                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
3170                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3171                                                                                                                          irr::scene::ESNRP_SOLID +
3172                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
3173                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
3174                                                                                                                          irr::scene::ESNRP_SHADOW;
3175
3176                                 camera.getCameraNode()->setPosition( rightEye );
3177                                 camera.getCameraNode()->setTarget( focusPoint );
3178
3179                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
3180
3181
3182                                 //driver->endScene();
3183
3184                                 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3185                                 driver->getOverrideMaterial().EnableFlags=0;
3186                                 driver->getOverrideMaterial().EnablePasses=0;
3187
3188                                 camera.getCameraNode()->setPosition( oldPosition );
3189                                 camera.getCameraNode()->setTarget( oldTarget );
3190                         }
3191
3192                         scenetime = timer.stop(true);
3193                 }
3194                 
3195                 {
3196                 //TimeTaker timer9("auxiliary drawings");
3197                 // 0ms
3198                 
3199                 //timer9.stop();
3200                 //TimeTaker //timer10("//timer10");
3201                 
3202                 video::SMaterial m;
3203                 //m.Thickness = 10;
3204                 m.Thickness = 3;
3205                 m.Lighting = false;
3206                 driver->setMaterial(m);
3207
3208                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3209
3210                 if (show_hud)
3211                         hud.drawSelectionBoxes(hilightboxes);
3212                 /*
3213                         Wielded tool
3214                 */
3215                 if(show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE))
3216                 {
3217                         // Warning: This clears the Z buffer.
3218                         camera.drawWieldedTool();
3219                 }
3220
3221                 /*
3222                         Post effects
3223                 */
3224                 {
3225                         client.getEnv().getClientMap().renderPostFx();
3226                 }
3227
3228                 /*
3229                         Profiler graph
3230                 */
3231                 if(show_profiler_graph)
3232                 {
3233                         graph.draw(10, screensize.Y - 10, driver, font);
3234                 }
3235
3236                 /*
3237                         Draw crosshair
3238                 */
3239                 if (show_hud)
3240                         hud.drawCrosshair();
3241                         
3242                 } // timer
3243
3244                 //timer10.stop();
3245                 //TimeTaker //timer11("//timer11");
3246
3247
3248                 /*
3249                         Draw hotbar
3250                 */
3251                 if (show_hud)
3252                 {
3253                         hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3254                                         client.getHP(), client.getPlayerItem());
3255                 }
3256
3257                 /*
3258                         Damage flash
3259                 */
3260                 if(damage_flash > 0.0)
3261                 {
3262                         video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3263                         driver->draw2DRectangle(color,
3264                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
3265                                         NULL);
3266                         
3267                         damage_flash -= 100.0*dtime;
3268                 }
3269
3270                 /*
3271                         Damage camera tilt
3272                 */
3273                 if(player->hurt_tilt_timer > 0.0)
3274                 {
3275                         player->hurt_tilt_timer -= dtime*5;
3276                         if(player->hurt_tilt_timer < 0)
3277                                 player->hurt_tilt_strength = 0;
3278                 }
3279
3280                 /*
3281                         Draw lua hud items
3282                 */
3283                 if (show_hud)
3284                         hud.drawLuaElements();
3285
3286                 /*
3287                         Draw gui
3288                 */
3289                 // 0-1ms
3290                 guienv->drawAll();
3291
3292                 /*
3293                         End scene
3294                 */
3295                 {
3296                         TimeTaker timer("endScene");
3297                         endSceneX(driver);
3298                         endscenetime = timer.stop(true);
3299                 }
3300
3301                 drawtime = tt_draw.stop(true);
3302                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3303
3304                 /*
3305                         End of drawing
3306                 */
3307
3308                 static s16 lastFPS = 0;
3309                 //u16 fps = driver->getFPS();
3310                 u16 fps = (1.0/dtime_avg1);
3311
3312                 if (lastFPS != fps)
3313                 {
3314                         core::stringw str = L"Minetest [";
3315                         str += driver->getName();
3316                         str += "] FPS=";
3317                         str += fps;
3318
3319                         device->setWindowCaption(str.c_str());
3320                         lastFPS = fps;
3321                 }
3322
3323                 /*
3324                         Log times and stuff for visualization
3325                 */
3326                 Profiler::GraphValues values;
3327                 g_profiler->graphGet(values);
3328                 graph.put(values);
3329         }
3330
3331         /*
3332                 Drop stuff
3333         */
3334         if (clouds)
3335                 clouds->drop();
3336         if (gui_chat_console)
3337                 gui_chat_console->drop();
3338         if (sky)
3339                 sky->drop();
3340         clear_particles();
3341         
3342         /*
3343                 Draw a "shutting down" screen, which will be shown while the map
3344                 generator and other stuff quits
3345         */
3346         {
3347                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3348                 wchar_t* text = wgettext("Shutting down stuff...");
3349                 draw_load_screen(text, device, font, 0, -1, false);
3350                 delete[] text;
3351                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3352                 guienv->drawAll();
3353                 driver->endScene();
3354                 gui_shuttingdowntext->remove();*/
3355         }
3356
3357         chat_backend.addMessage(L"", L"# Disconnected.");
3358         chat_backend.addMessage(L"", L"");
3359
3360         // Client scope (client is destructed before destructing *def and tsrc)
3361         }while(0);
3362         } // try-catch
3363         catch(SerializationError &e)
3364         {
3365                 error_message = L"A serialization error occurred:\n"
3366                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3367                                 L" running a different version of Minetest.";
3368                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3369         }
3370         catch(ServerError &e)
3371         {
3372                 error_message = narrow_to_wide(e.what());
3373                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3374         }
3375         catch(ModError &e)
3376         {
3377                 errorstream<<e.what()<<std::endl;
3378                 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3379         }
3380
3381
3382         
3383         if(!sound_is_dummy)
3384                 delete sound;
3385
3386         //has to be deleted first to stop all server threads
3387         delete server;
3388
3389         delete tsrc;
3390         delete shsrc;
3391         delete nodedef;
3392         delete itemdef;
3393
3394         //extended resource accounting
3395         infostream << "Irrlicht resources after cleanup:" << std::endl;
3396         infostream << "\tRemaining meshes   : "
3397                 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3398         infostream << "\tRemaining textures : "
3399                 << driver->getTextureCount() << std::endl;
3400         for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3401                 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3402                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3403                                 << std::endl;
3404         }
3405         infostream << "\tRemaining materials: "
3406                 << driver-> getMaterialRendererCount ()
3407                 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;
3408 }
3409
3410