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