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