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