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