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