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