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