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