Fixed viewing range stuff a bit (now it works better with very low ranges)
[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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "common_irrlicht.h"
21 #include "game.h"
22 #include "client.h"
23 #include "server.h"
24 #include "guiPauseMenu.h"
25 #include "guiInventoryMenu.h"
26 #include "guiTextInputMenu.h"
27 #include "guiFurnaceMenu.h"
28 #include "materials.h"
29 #include "config.h"
30 #include "clouds.h"
31
32 /*
33         Setting this to 1 enables a special camera mode that forces
34         the renderers to think that the camera statically points from
35         the starting place to a static direction.
36
37         This allows one to move around with the player and see what
38         is actually drawn behind solid things and behind the player.
39 */
40 #define FIELD_OF_VIEW_TEST 0
41
42
43 MapDrawControl draw_control;
44
45 // Chat data
46 struct ChatLine
47 {
48         ChatLine():
49                 age(0.0)
50         {
51         }
52         ChatLine(const std::wstring &a_text):
53                 age(0.0),
54                 text(a_text)
55         {
56         }
57         float age;
58         std::wstring text;
59 };
60
61 /*
62         Inventory stuff
63 */
64
65 // Inventory actions from the menu are buffered here before sending
66 Queue<InventoryAction*> inventory_action_queue;
67 // This is a copy of the inventory that the client's environment has
68 Inventory local_inventory;
69
70 u16 g_selected_item = 0;
71
72 /*
73         Text input system
74 */
75
76 struct TextDestSign : public TextDest
77 {
78         TextDestSign(v3s16 blockpos, s16 id, Client *client)
79         {
80                 m_blockpos = blockpos;
81                 m_id = id;
82                 m_client = client;
83         }
84         void gotText(std::wstring text)
85         {
86                 std::string ntext = wide_to_narrow(text);
87                 dstream<<"Changing text of a sign object: "
88                                 <<ntext<<std::endl;
89                 m_client->sendSignText(m_blockpos, m_id, ntext);
90         }
91
92         v3s16 m_blockpos;
93         s16 m_id;
94         Client *m_client;
95 };
96
97 struct TextDestChat : public TextDest
98 {
99         TextDestChat(Client *client)
100         {
101                 m_client = client;
102         }
103         void gotText(std::wstring text)
104         {
105                 // Discard empty line
106                 if(text == L"")
107                         return;
108                 
109                 // Parse command (server command starts with "/#")
110                 if(text[0] == L'/' && text[1] != L'#')
111                 {
112                         std::wstring reply = L"Local: ";
113
114                         reply += L"Local commands not yet supported. "
115                                         L"Server prefix is \"/#\".";
116                         
117                         m_client->addChatMessage(reply);
118                         return;
119                 }
120
121                 // Send to others
122                 m_client->sendChatMessage(text);
123                 // Show locally
124                 m_client->addChatMessage(text);
125         }
126
127         Client *m_client;
128 };
129
130 struct TextDestSignNode : public TextDest
131 {
132         TextDestSignNode(v3s16 p, Client *client)
133         {
134                 m_p = p;
135                 m_client = client;
136         }
137         void gotText(std::wstring text)
138         {
139                 std::string ntext = wide_to_narrow(text);
140                 dstream<<"Changing text of a sign node: "
141                                 <<ntext<<std::endl;
142                 m_client->sendSignNodeText(m_p, ntext);
143         }
144
145         v3s16 m_p;
146         Client *m_client;
147 };
148
149 /*
150         Render distance feedback loop
151 */
152 void updateViewingRange(f32 frametime_in, Client *client)
153 {
154         if(draw_control.range_all == true)
155                 return;
156         
157         static f32 added_frametime = 0;
158         static s16 added_frames = 0;
159
160         added_frametime += frametime_in;
161         added_frames += 1;
162
163         // Actually this counter kind of sucks because frametime is busytime
164         static f32 counter = 0;
165         counter -= frametime_in;
166         if(counter > 0)
167                 return;
168         //counter = 0.1;
169         counter = 0.2;
170
171         /*dstream<<__FUNCTION_NAME
172                         <<": Collected "<<added_frames<<" frames, total of "
173                         <<added_frametime<<"s."<<std::endl;*/
174         
175         /*dstream<<"draw_control.blocks_drawn="
176                         <<draw_control.blocks_drawn
177                         <<", draw_control.blocks_would_have_drawn="
178                         <<draw_control.blocks_would_have_drawn
179                         <<std::endl;*/
180         
181         float range_min = g_settings.getS16("viewing_range_nodes_min");
182         float range_max = g_settings.getS16("viewing_range_nodes_max");
183         
184         // Limit minimum to keep the feedback loop stable
185         if(range_min < 5)
186                 range_min = 5;
187         
188         draw_control.wanted_min_range = range_min;
189         //draw_control.wanted_max_blocks = (1.5*draw_control.blocks_drawn)+1;
190         draw_control.wanted_max_blocks = (1.5*draw_control.blocks_would_have_drawn)+1;
191         if(draw_control.wanted_max_blocks < 10)
192                 draw_control.wanted_max_blocks = 10;
193         
194         float block_draw_ratio = 1.0;
195         if(draw_control.blocks_would_have_drawn != 0)
196         {
197                 block_draw_ratio = (float)draw_control.blocks_drawn
198                         / (float)draw_control.blocks_would_have_drawn;
199         }
200
201         // Calculate the average frametime in the case that all wanted
202         // blocks had been drawn
203         f32 frametime = added_frametime / added_frames / block_draw_ratio;
204         
205         added_frametime = 0.0;
206         added_frames = 0;
207         
208         float wanted_fps = g_settings.getFloat("wanted_fps");
209         float wanted_frametime = 1.0 / wanted_fps;
210         
211         f32 wanted_frametime_change = wanted_frametime - frametime;
212         //dstream<<"wanted_frametime_change="<<wanted_frametime_change<<std::endl;
213         
214         // If needed frametime change is small, just return
215         if(fabs(wanted_frametime_change) < wanted_frametime*0.4)
216         {
217                 //dstream<<"ignoring small wanted_frametime_change"<<std::endl;
218                 return;
219         }
220
221         float range = draw_control.wanted_range;
222         float new_range = range;
223
224         static s16 range_old = 0;
225         static f32 frametime_old = 0;
226         
227         float d_range = range - range_old;
228         f32 d_frametime = frametime - frametime_old;
229         // A sane default of 30ms per 50 nodes of range
230         static f32 time_per_range = 30. / 50;
231         if(d_range != 0)
232         {
233                 time_per_range = d_frametime / d_range;
234         }
235         
236         // The minimum allowed calculated frametime-range derivative:
237         // Practically this sets the maximum speed of changing the range.
238         // The lower this value, the higher the maximum changing speed.
239         // A low value here results in wobbly range (0.001)
240         // A high value here results in slow changing range (0.0025)
241         // SUGG: This could be dynamically adjusted so that when
242         //       the camera is turning, this is lower
243         //float min_time_per_range = 0.0015;
244         float min_time_per_range = 0.0010;
245         //float min_time_per_range = 0.05 / range;
246         if(time_per_range < min_time_per_range)
247         {
248                 time_per_range = min_time_per_range;
249                 //dstream<<"time_per_range="<<time_per_range<<" (min)"<<std::endl;
250         }
251         else
252         {
253                 //dstream<<"time_per_range="<<time_per_range<<std::endl;
254         }
255
256         f32 wanted_range_change = wanted_frametime_change / time_per_range;
257         // Dampen the change a bit to kill oscillations
258         //wanted_range_change *= 0.9;
259         //wanted_range_change *= 0.75;
260         wanted_range_change *= 0.5;
261         //dstream<<"wanted_range_change="<<wanted_range_change<<std::endl;
262
263         // If needed range change is very small, just return
264         if(fabs(wanted_range_change) < 0.001)
265         {
266                 //dstream<<"ignoring small wanted_range_change"<<std::endl;
267                 return;
268         }
269
270         new_range += wanted_range_change;
271         
272         float new_range_unclamped = new_range;
273         if(new_range < range_min)
274                 new_range = range_min;
275         if(new_range > range_max)
276                 new_range = range_max;
277         
278         dstream<<"new_range="<<new_range_unclamped
279                         <<", clamped to "<<new_range<<std::endl;
280
281         draw_control.wanted_range = new_range;
282
283         range_old = new_range;
284         frametime_old = frametime;
285 }
286
287 /*
288         Hotbar draw routine
289 */
290 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
291                 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
292                 Inventory *inventory, s32 halfheartcount)
293 {
294         InventoryList *mainlist = inventory->getList("main");
295         if(mainlist == NULL)
296         {
297                 dstream<<"WARNING: draw_hotbar(): mainlist == NULL"<<std::endl;
298                 return;
299         }
300         
301         s32 padding = imgsize/12;
302         //s32 height = imgsize + padding*2;
303         s32 width = itemcount*(imgsize+padding*2);
304         
305         // Position of upper left corner of bar
306         v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
307         
308         // Draw background color
309         /*core::rect<s32> barrect(0,0,width,height);
310         barrect += pos;
311         video::SColor bgcolor(255,128,128,128);
312         driver->draw2DRectangle(bgcolor, barrect, NULL);*/
313
314         core::rect<s32> imgrect(0,0,imgsize,imgsize);
315
316         for(s32 i=0; i<itemcount; i++)
317         {
318                 InventoryItem *item = mainlist->getItem(i);
319                 
320                 core::rect<s32> rect = imgrect + pos
321                                 + v2s32(padding+i*(imgsize+padding*2), padding);
322                 
323                 if(g_selected_item == i)
324                 {
325                         driver->draw2DRectangle(video::SColor(255,255,0,0),
326                                         core::rect<s32>(rect.UpperLeftCorner - v2s32(1,1)*padding,
327                                                         rect.LowerRightCorner + v2s32(1,1)*padding),
328                                         NULL);
329                 }
330                 else
331                 {
332                         video::SColor bgcolor2(128,0,0,0);
333                         driver->draw2DRectangle(bgcolor2, rect, NULL);
334                 }
335
336                 if(item != NULL)
337                 {
338                         drawInventoryItem(driver, font, item, rect, NULL);
339                 }
340         }
341         
342         /*
343                 Draw hearts
344         */
345         {
346                 video::ITexture *heart_texture =
347                                 driver->getTexture(porting::getDataPath("heart.png").c_str());
348                 v2s32 p = pos + v2s32(0, -20);
349                 for(s32 i=0; i<halfheartcount/2; i++)
350                 {
351                         const video::SColor color(255,255,255,255);
352                         const video::SColor colors[] = {color,color,color,color};
353                         core::rect<s32> rect(0,0,16,16);
354                         rect += p;
355                         driver->draw2DImage(heart_texture, rect,
356                                 core::rect<s32>(core::position2d<s32>(0,0),
357                                 core::dimension2di(heart_texture->getOriginalSize())),
358                                 NULL, colors, true);
359                         p += v2s32(20,0);
360                 }
361                 if(halfheartcount % 2 == 1)
362                 {
363                         const video::SColor color(255,255,255,255);
364                         const video::SColor colors[] = {color,color,color,color};
365                         core::rect<s32> rect(0,0,16/2,16);
366                         rect += p;
367                         core::dimension2di srcd(heart_texture->getOriginalSize());
368                         srcd.Width /= 2;
369                         driver->draw2DImage(heart_texture, rect,
370                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
371                                 NULL, colors, true);
372                         p += v2s32(20,0);
373                 }
374         }
375 }
376
377 /*
378         Find what the player is pointing at
379 */
380 void getPointedNode(Client *client, v3f player_position,
381                 v3f camera_direction, v3f camera_position,
382                 bool &nodefound, core::line3d<f32> shootline,
383                 v3s16 &nodepos, v3s16 &neighbourpos,
384                 core::aabbox3d<f32> &nodehilightbox,
385                 f32 d)
386 {
387         f32 mindistance = BS * 1001;
388         
389         v3s16 pos_i = floatToInt(player_position, BS);
390
391         /*std::cout<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
392                         <<std::endl;*/
393
394         s16 a = d;
395         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
396         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
397         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
398         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
399         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
400         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
401         
402         for(s16 y = ystart; y <= yend; y++)
403         for(s16 z = zstart; z <= zend; z++)
404         for(s16 x = xstart; x <= xend; x++)
405         {
406                 MapNode n;
407                 try
408                 {
409                         n = client->getNode(v3s16(x,y,z));
410                         if(content_pointable(n.d) == false)
411                                 continue;
412                 }
413                 catch(InvalidPositionException &e)
414                 {
415                         continue;
416                 }
417
418                 v3s16 np(x,y,z);
419                 v3f npf = intToFloat(np, BS);
420                 
421                 f32 d = 0.01;
422                 
423                 v3s16 dirs[6] = {
424                         v3s16(0,0,1), // back
425                         v3s16(0,1,0), // top
426                         v3s16(1,0,0), // right
427                         v3s16(0,0,-1), // front
428                         v3s16(0,-1,0), // bottom
429                         v3s16(-1,0,0), // left
430                 };
431                 
432                 /*
433                         Meta-objects
434                 */
435                 if(n.d == CONTENT_TORCH)
436                 {
437                         v3s16 dir = unpackDir(n.dir);
438                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
439                         dir_f *= BS/2 - BS/6 - BS/20;
440                         v3f cpf = npf + dir_f;
441                         f32 distance = (cpf - camera_position).getLength();
442
443                         core::aabbox3d<f32> box;
444                         
445                         // bottom
446                         if(dir == v3s16(0,-1,0))
447                         {
448                                 box = core::aabbox3d<f32>(
449                                         npf - v3f(BS/6, BS/2, BS/6),
450                                         npf + v3f(BS/6, -BS/2+BS/3*2, BS/6)
451                                 );
452                         }
453                         // top
454                         else if(dir == v3s16(0,1,0))
455                         {
456                                 box = core::aabbox3d<f32>(
457                                         npf - v3f(BS/6, -BS/2+BS/3*2, BS/6),
458                                         npf + v3f(BS/6, BS/2, BS/6)
459                                 );
460                         }
461                         // side
462                         else
463                         {
464                                 box = core::aabbox3d<f32>(
465                                         cpf - v3f(BS/6, BS/3, BS/6),
466                                         cpf + v3f(BS/6, BS/3, BS/6)
467                                 );
468                         }
469
470                         if(distance < mindistance)
471                         {
472                                 if(box.intersectsWithLine(shootline))
473                                 {
474                                         nodefound = true;
475                                         nodepos = np;
476                                         neighbourpos = np;
477                                         mindistance = distance;
478                                         nodehilightbox = box;
479                                 }
480                         }
481                 }
482                 else if(n.d == CONTENT_SIGN_WALL)
483                 {
484                         v3s16 dir = unpackDir(n.dir);
485                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
486                         dir_f *= BS/2 - BS/6 - BS/20;
487                         v3f cpf = npf + dir_f;
488                         f32 distance = (cpf - camera_position).getLength();
489
490                         v3f vertices[4] =
491                         {
492                                 v3f(BS*0.42,-BS*0.35,-BS*0.4),
493                                 v3f(BS*0.49, BS*0.35, BS*0.4),
494                         };
495
496                         for(s32 i=0; i<2; i++)
497                         {
498                                 if(dir == v3s16(1,0,0))
499                                         vertices[i].rotateXZBy(0);
500                                 if(dir == v3s16(-1,0,0))
501                                         vertices[i].rotateXZBy(180);
502                                 if(dir == v3s16(0,0,1))
503                                         vertices[i].rotateXZBy(90);
504                                 if(dir == v3s16(0,0,-1))
505                                         vertices[i].rotateXZBy(-90);
506                                 if(dir == v3s16(0,-1,0))
507                                         vertices[i].rotateXYBy(-90);
508                                 if(dir == v3s16(0,1,0))
509                                         vertices[i].rotateXYBy(90);
510
511                                 vertices[i] += npf;
512                         }
513
514                         core::aabbox3d<f32> box;
515
516                         box = core::aabbox3d<f32>(vertices[0]);
517                         box.addInternalPoint(vertices[1]);
518
519                         if(distance < mindistance)
520                         {
521                                 if(box.intersectsWithLine(shootline))
522                                 {
523                                         nodefound = true;
524                                         nodepos = np;
525                                         neighbourpos = np;
526                                         mindistance = distance;
527                                         nodehilightbox = box;
528                                 }
529                         }
530                 }
531                 /*
532                         Regular blocks
533                 */
534                 else
535                 {
536                         for(u16 i=0; i<6; i++)
537                         {
538                                 v3f dir_f = v3f(dirs[i].X,
539                                                 dirs[i].Y, dirs[i].Z);
540                                 v3f centerpoint = npf + dir_f * BS/2;
541                                 f32 distance =
542                                                 (centerpoint - camera_position).getLength();
543                                 
544                                 if(distance < mindistance)
545                                 {
546                                         core::CMatrix4<f32> m;
547                                         m.buildRotateFromTo(v3f(0,0,1), dir_f);
548
549                                         // This is the back face
550                                         v3f corners[2] = {
551                                                 v3f(BS/2, BS/2, BS/2),
552                                                 v3f(-BS/2, -BS/2, BS/2+d)
553                                         };
554                                         
555                                         for(u16 j=0; j<2; j++)
556                                         {
557                                                 m.rotateVect(corners[j]);
558                                                 corners[j] += npf;
559                                         }
560
561                                         core::aabbox3d<f32> facebox(corners[0]);
562                                         facebox.addInternalPoint(corners[1]);
563
564                                         if(facebox.intersectsWithLine(shootline))
565                                         {
566                                                 nodefound = true;
567                                                 nodepos = np;
568                                                 neighbourpos = np + dirs[i];
569                                                 mindistance = distance;
570
571                                                 //nodehilightbox = facebox;
572
573                                                 const float d = 0.502;
574                                                 core::aabbox3d<f32> nodebox
575                                                                 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
576                                                 v3f nodepos_f = intToFloat(nodepos, BS);
577                                                 nodebox.MinEdge += nodepos_f;
578                                                 nodebox.MaxEdge += nodepos_f;
579                                                 nodehilightbox = nodebox;
580                                         }
581                                 } // if distance < mindistance
582                         } // for dirs
583                 } // regular block
584         } // for coords
585 }
586
587 void update_skybox(video::IVideoDriver* driver,
588                 scene::ISceneManager* smgr, scene::ISceneNode* &skybox,
589                 float brightness)
590 {
591         if(skybox)
592         {
593                 skybox->remove();
594         }
595         
596         if(brightness >= 0.5)
597         {
598                 skybox = smgr->addSkyBoxSceneNode(
599                         driver->getTexture(porting::getDataPath("skybox2.png").c_str()),
600                         driver->getTexture(porting::getDataPath("skybox3.png").c_str()),
601                         driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
602                         driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
603                         driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
604                         driver->getTexture(porting::getDataPath("skybox1.png").c_str()));
605         }
606         else if(brightness >= 0.2)
607         {
608                 skybox = smgr->addSkyBoxSceneNode(
609                         driver->getTexture(porting::getDataPath("skybox2_dawn.png").c_str()),
610                         driver->getTexture(porting::getDataPath("skybox3_dawn.png").c_str()),
611                         driver->getTexture(porting::getDataPath("skybox1_dawn.png").c_str()),
612                         driver->getTexture(porting::getDataPath("skybox1_dawn.png").c_str()),
613                         driver->getTexture(porting::getDataPath("skybox1_dawn.png").c_str()),
614                         driver->getTexture(porting::getDataPath("skybox1_dawn.png").c_str()));
615         }
616         else
617         {
618                 skybox = smgr->addSkyBoxSceneNode(
619                         driver->getTexture(porting::getDataPath("skybox2_night.png").c_str()),
620                         driver->getTexture(porting::getDataPath("skybox3_night.png").c_str()),
621                         driver->getTexture(porting::getDataPath("skybox1_night.png").c_str()),
622                         driver->getTexture(porting::getDataPath("skybox1_night.png").c_str()),
623                         driver->getTexture(porting::getDataPath("skybox1_night.png").c_str()),
624                         driver->getTexture(porting::getDataPath("skybox1_night.png").c_str()));
625         }
626 }
627
628 void the_game(
629         bool &kill,
630         bool random_input,
631         InputHandler *input,
632         IrrlichtDevice *device,
633         gui::IGUIFont* font,
634         std::string map_dir,
635         std::string playername,
636         std::string address,
637         u16 port,
638         std::wstring &error_message
639 )
640 {
641         video::IVideoDriver* driver = device->getVideoDriver();
642         scene::ISceneManager* smgr = device->getSceneManager();
643
644         v2u32 screensize(0,0);
645         v2u32 last_screensize(0,0);
646         screensize = driver->getScreenSize();
647
648         const s32 hotbar_itemcount = 8;
649         const s32 hotbar_imagesize = 36;
650         
651         // The color of the sky
652
653         //video::SColor skycolor = video::SColor(255,140,186,250);
654
655         video::SColor bgcolor_bright = video::SColor(255,170,200,230);
656
657         /*
658                 Draw "Loading" screen
659         */
660         const wchar_t *loadingtext = L"Loading and connecting...";
661         u32 text_height = font->getDimension(loadingtext).Height;
662         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
663         core::vector2d<s32> textsize(300, text_height);
664         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
665
666         gui::IGUIStaticText *gui_loadingtext = guienv->addStaticText(
667                         loadingtext, textrect, false, false);
668         gui_loadingtext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
669
670         driver->beginScene(true, true, video::SColor(255,0,0,0));
671         guienv->drawAll();
672         driver->endScene();
673
674         std::cout<<DTIME<<"Creating server and client"<<std::endl;
675         
676         /*
677                 Create server.
678                 SharedPtr will delete it when it goes out of scope.
679         */
680         SharedPtr<Server> server;
681         if(address == ""){
682                 server = new Server(map_dir);
683                 server->start(port);
684         }
685         
686         /*
687                 Create client
688         */
689
690         Client client(device, playername.c_str(), draw_control);
691                         
692         Address connect_address(0,0,0,0, port);
693         try{
694                 if(address == "")
695                         //connect_address.Resolve("localhost");
696                         connect_address.setAddress(127,0,0,1);
697                 else
698                         connect_address.Resolve(address.c_str());
699         }
700         catch(ResolveError &e)
701         {
702                 std::cout<<DTIME<<"Couldn't resolve address"<<std::endl;
703                 //return 0;
704                 error_message = L"Couldn't resolve address";
705                 gui_loadingtext->remove();
706                 return;
707         }
708
709         /*
710                 Attempt to connect to the server
711         */
712         
713         dstream<<DTIME<<"Connecting to server at ";
714         connect_address.print(&dstream);
715         dstream<<std::endl;
716         client.connect(connect_address);
717
718         bool could_connect = false;
719         
720         try{
721                 float time_counter = 0.0;
722                 for(;;)
723                 {
724                         if(client.connectedAndInitialized())
725                         {
726                                 could_connect = true;
727                                 break;
728                         }
729                         // Wait for 10 seconds
730                         if(time_counter >= 10.0)
731                         {
732                                 break;
733                         }
734
735                         // Update screen
736                         driver->beginScene(true, true, video::SColor(255,0,0,0));
737                         guienv->drawAll();
738                         driver->endScene();
739
740                         // Update client and server
741
742                         client.step(0.1);
743
744                         if(server != NULL)
745                                 server->step(0.1);
746                         
747                         // Delay a bit
748                         sleep_ms(100);
749                         time_counter += 0.1;
750                 }
751         }
752         catch(con::PeerNotFoundException &e)
753         {}
754
755         if(could_connect == false)
756         {
757                 std::cout<<DTIME<<"Timed out."<<std::endl;
758                 error_message = L"Connection timed out.";
759                 gui_loadingtext->remove();
760                 return;
761         }
762
763         /*
764                 Create skybox
765         */
766         float old_brightness = 1.0;
767         scene::ISceneNode* skybox = NULL;
768         update_skybox(driver, smgr, skybox, 1.0);
769         
770         /*
771                 Create the camera node
772         */
773
774         scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(
775                 0, // Camera parent
776                 v3f(BS*100, BS*2, BS*100), // Look from
777                 v3f(BS*100+1, BS*2, BS*100), // Look to
778                 -1 // Camera ID
779         );
780
781         if(camera == NULL)
782         {
783                 error_message = L"Failed to create the camera node";
784                 return;
785         }
786
787         camera->setFOV(FOV_ANGLE);
788
789         // Just so big a value that everything rendered is visible
790         camera->setFarValue(100000*BS);
791         
792         f32 camera_yaw = 0; // "right/left"
793         f32 camera_pitch = 0; // "up/down"
794
795         /*
796                 Clouds
797         */
798         
799         float cloud_height = BS*100;
800         Clouds *clouds = NULL;
801         clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1,
802                         cloud_height, time(0));
803
804         /*
805                 Move into game
806         */
807         
808         gui_loadingtext->remove();
809
810         /*
811                 Add some gui stuff
812         */
813
814         // First line of debug text
815         gui::IGUIStaticText *guitext = guienv->addStaticText(
816                         L"Minetest-c55",
817                         core::rect<s32>(5, 5, 795, 5+text_height),
818                         false, false);
819         // Second line of debug text
820         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
821                         L"",
822                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
823                         false, false);
824         
825         // At the middle of the screen
826         // Object infos are shown in this
827         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
828                         L"",
829                         core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
830                         false, false);
831         
832         // Chat text
833         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
834                         L"",
835                         core::rect<s32>(0,0,0,0),
836                         false, false); // Disable word wrap as of now
837                         //false, true);
838         //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
839         core::list<ChatLine> chat_lines;
840         
841         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
842                         (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
843         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
844                         (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
845         
846         // Test the text input system
847         /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
848                         NULL))->drop();*/
849         /*GUIMessageMenu *menu =
850                         new GUIMessageMenu(guienv, guiroot, -1, 
851                                 &g_menumgr,
852                                 L"Asd");
853         menu->drop();*/
854         
855         // Launch pause menu
856         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
857                         &g_menumgr))->drop();
858         
859         // Enable texts
860         /*guitext2->setVisible(true);
861         guitext_info->setVisible(true);
862         guitext_chat->setVisible(true);*/
863
864         //s32 guitext_chat_pad_bottom = 70;
865
866         /*
867                 Some statistics are collected in these
868         */
869         u32 drawtime = 0;
870         u32 beginscenetime = 0;
871         u32 scenetime = 0;
872         u32 endscenetime = 0;
873         
874         // A test
875         //throw con::PeerNotFoundException("lol");
876
877         core::list<float> frametime_log;
878
879         float damage_flash_timer = 0;
880
881         /*
882                 Main loop
883         */
884
885         bool first_loop_after_window_activation = true;
886
887         // Time is in milliseconds
888         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
889         // NOTE: So we have to use getTime() and call run()s between them
890         u32 lasttime = device->getTimer()->getTime();
891
892         while(device->run() && kill == false)
893         {
894                 if(g_gamecallback->disconnect_requested)
895                 {
896                         g_gamecallback->disconnect_requested = false;
897                         break;
898                 }
899
900                 /*
901                         Process TextureSource's queue
902                 */
903                 ((TextureSource*)g_texturesource)->processQueue();
904
905                 /*
906                         Random calculations
907                 */
908                 last_screensize = screensize;
909                 screensize = driver->getScreenSize();
910                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
911                 //bool screensize_changed = screensize != last_screensize;
912                 
913                 // Hilight boxes collected during the loop and displayed
914                 core::list< core::aabbox3d<f32> > hilightboxes;
915                 
916                 // Info text
917                 std::wstring infotext;
918
919                 // When screen size changes, update positions and sizes of stuff
920                 /*if(screensize_changed)
921                 {
922                         v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
923                         quick_inventory->updatePosition(pos);
924                 }*/
925
926                 //TimeTaker //timer1("//timer1");
927                 
928                 // Time of frame without fps limit
929                 float busytime;
930                 u32 busytime_u32;
931                 {
932                         // not using getRealTime is necessary for wine
933                         u32 time = device->getTimer()->getTime();
934                         if(time > lasttime)
935                                 busytime_u32 = time - lasttime;
936                         else
937                                 busytime_u32 = 0;
938                         busytime = busytime_u32 / 1000.0;
939                 }
940
941                 //std::cout<<"busytime_u32="<<busytime_u32<<std::endl;
942         
943                 // Necessary for device->getTimer()->getTime()
944                 device->run();
945
946                 /*
947                         Viewing range
948                 */
949                 
950                 updateViewingRange(busytime, &client);
951                 
952                 /*
953                         FPS limiter
954                 */
955
956                 {
957                         float fps_max = g_settings.getFloat("fps_max");
958                         u32 frametime_min = 1000./fps_max;
959                         
960                         if(busytime_u32 < frametime_min)
961                         {
962                                 u32 sleeptime = frametime_min - busytime_u32;
963                                 device->sleep(sleeptime);
964                         }
965                 }
966
967                 // Necessary for device->getTimer()->getTime()
968                 device->run();
969
970                 /*
971                         Time difference calculation
972                 */
973                 f32 dtime; // in seconds
974                 
975                 u32 time = device->getTimer()->getTime();
976                 if(time > lasttime)
977                         dtime = (time - lasttime) / 1000.0;
978                 else
979                         dtime = 0;
980                 lasttime = time;
981
982                 /*
983                         Log frametime for visualization
984                 */
985                 frametime_log.push_back(dtime);
986                 if(frametime_log.size() > 100)
987                 {
988                         core::list<float>::Iterator i = frametime_log.begin();
989                         frametime_log.erase(i);
990                 }
991
992                 /*
993                         Visualize frametime in terminal
994                 */
995                 /*for(u32 i=0; i<dtime*400; i++)
996                         std::cout<<"X";
997                 std::cout<<std::endl;*/
998
999                 /*
1000                         Time average and jitter calculation
1001                 */
1002
1003                 static f32 dtime_avg1 = 0.0;
1004                 dtime_avg1 = dtime_avg1 * 0.98 + dtime * 0.02;
1005                 f32 dtime_jitter1 = dtime - dtime_avg1;
1006
1007                 static f32 dtime_jitter1_max_sample = 0.0;
1008                 static f32 dtime_jitter1_max_fraction = 0.0;
1009                 {
1010                         static f32 jitter1_max = 0.0;
1011                         static f32 counter = 0.0;
1012                         if(dtime_jitter1 > jitter1_max)
1013                                 jitter1_max = dtime_jitter1;
1014                         counter += dtime;
1015                         if(counter > 0.0)
1016                         {
1017                                 counter -= 3.0;
1018                                 dtime_jitter1_max_sample = jitter1_max;
1019                                 dtime_jitter1_max_fraction
1020                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1021                                 jitter1_max = 0.0;
1022                         }
1023                 }
1024                 
1025                 /*
1026                         Busytime average and jitter calculation
1027                 */
1028
1029                 static f32 busytime_avg1 = 0.0;
1030                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1031                 f32 busytime_jitter1 = busytime - busytime_avg1;
1032                 
1033                 static f32 busytime_jitter1_max_sample = 0.0;
1034                 static f32 busytime_jitter1_min_sample = 0.0;
1035                 {
1036                         static f32 jitter1_max = 0.0;
1037                         static f32 jitter1_min = 0.0;
1038                         static f32 counter = 0.0;
1039                         if(busytime_jitter1 > jitter1_max)
1040                                 jitter1_max = busytime_jitter1;
1041                         if(busytime_jitter1 < jitter1_min)
1042                                 jitter1_min = busytime_jitter1;
1043                         counter += dtime;
1044                         if(counter > 0.0){
1045                                 counter -= 3.0;
1046                                 busytime_jitter1_max_sample = jitter1_max;
1047                                 busytime_jitter1_min_sample = jitter1_min;
1048                                 jitter1_max = 0.0;
1049                                 jitter1_min = 0.0;
1050                         }
1051                 }
1052                 
1053                 /*
1054                         Debug info for client
1055                 */
1056                 {
1057                         static float counter = 0.0;
1058                         counter -= dtime;
1059                         if(counter < 0)
1060                         {
1061                                 counter = 30.0;
1062                                 client.printDebugInfo(std::cout);
1063                         }
1064                 }
1065
1066                 /*
1067                         Direct handling of user input
1068                 */
1069                 
1070                 // Reset input if window not active or some menu is active
1071                 if(device->isWindowActive() == false || noMenuActive() == false)
1072                 {
1073                         input->clear();
1074                 }
1075
1076                 // Input handler step() (used by the random input generator)
1077                 input->step(dtime);
1078
1079                 /*
1080                         Launch menus according to keys
1081                 */
1082                 if(input->wasKeyDown(irr::KEY_KEY_I))
1083                 {
1084                         dstream<<DTIME<<"the_game: "
1085                                         <<"Launching inventory"<<std::endl;
1086                         
1087                         GUIInventoryMenu *menu =
1088                                 new GUIInventoryMenu(guienv, guiroot, -1,
1089                                         &g_menumgr, v2s16(8,7),
1090                                         client.getInventoryContext(),
1091                                         &client);
1092
1093                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1094                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1095                                         "list", "current_player", "main",
1096                                         v2s32(0, 3), v2s32(8, 4)));
1097                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1098                                         "list", "current_player", "craft",
1099                                         v2s32(3, 0), v2s32(3, 3)));
1100                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1101                                         "list", "current_player", "craftresult",
1102                                         v2s32(7, 1), v2s32(1, 1)));
1103
1104                         menu->setDrawSpec(draw_spec);
1105
1106                         menu->drop();
1107                 }
1108                 else if(input->wasKeyDown(irr::KEY_ESCAPE))
1109                 {
1110                         dstream<<DTIME<<"the_game: "
1111                                         <<"Launching pause menu"<<std::endl;
1112                         // It will delete itself by itself
1113                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1114                                         &g_menumgr))->drop();
1115                 }
1116                 else if(input->wasKeyDown(irr::KEY_KEY_T))
1117                 {
1118                         TextDest *dest = new TextDestChat(&client);
1119
1120                         (new GUITextInputMenu(guienv, guiroot, -1,
1121                                         &g_menumgr, dest,
1122                                         L""))->drop();
1123                 }
1124
1125                 // Item selection with mouse wheel
1126                 {
1127                         s32 wheel = input->getMouseWheel();
1128                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1129                                         hotbar_itemcount-1);
1130
1131                         if(wheel < 0)
1132                         {
1133                                 if(g_selected_item < max_item)
1134                                         g_selected_item++;
1135                                 else
1136                                         g_selected_item = 0;
1137                         }
1138                         else if(wheel > 0)
1139                         {
1140                                 if(g_selected_item > 0)
1141                                         g_selected_item--;
1142                                 else
1143                                         g_selected_item = max_item;
1144                         }
1145                 }
1146                 
1147                 // Item selection
1148                 for(u16 i=0; i<10; i++)
1149                 {
1150                         s32 keycode = irr::KEY_KEY_1 + i;
1151                         if(i == 9)
1152                                 keycode = irr::KEY_KEY_0;
1153                         if(input->wasKeyDown((irr::EKEY_CODE)keycode))
1154                         {
1155                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1156                                 {
1157                                         g_selected_item = i;
1158
1159                                         dstream<<DTIME<<"Selected item: "
1160                                                         <<g_selected_item<<std::endl;
1161                                 }
1162                         }
1163                 }
1164
1165                 // Viewing range selection
1166                 if(input->wasKeyDown(irr::KEY_KEY_R))
1167                 {
1168                         if(draw_control.range_all)
1169                         {
1170                                 draw_control.range_all = false;
1171                                 dstream<<DTIME<<"Disabled full viewing range"<<std::endl;
1172                         }
1173                         else
1174                         {
1175                                 draw_control.range_all = true;
1176                                 dstream<<DTIME<<"Enabled full viewing range"<<std::endl;
1177                         }
1178                 }
1179
1180                 // Print debug stacks
1181                 if(input->wasKeyDown(irr::KEY_KEY_P))
1182                 {
1183                         dstream<<"-----------------------------------------"
1184                                         <<std::endl;
1185                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1186                         dstream<<"-----------------------------------------"
1187                                         <<std::endl;
1188                         debug_stacks_print();
1189                 }
1190
1191                 /*
1192                         Player speed control
1193                 */
1194                 
1195                 {
1196                         /*bool a_up,
1197                         bool a_down,
1198                         bool a_left,
1199                         bool a_right,
1200                         bool a_jump,
1201                         bool a_superspeed,
1202                         bool a_sneak,
1203                         float a_pitch,
1204                         float a_yaw*/
1205                         PlayerControl control(
1206                                 input->isKeyDown(irr::KEY_KEY_W),
1207                                 input->isKeyDown(irr::KEY_KEY_S),
1208                                 input->isKeyDown(irr::KEY_KEY_A),
1209                                 input->isKeyDown(irr::KEY_KEY_D),
1210                                 input->isKeyDown(irr::KEY_SPACE),
1211                                 input->isKeyDown(irr::KEY_KEY_E),
1212                                 input->isKeyDown(irr::KEY_LSHIFT)
1213                                                 || input->isKeyDown(irr::KEY_RSHIFT),
1214                                 camera_pitch,
1215                                 camera_yaw
1216                         );
1217                         client.setPlayerControl(control);
1218                 }
1219                 
1220                 /*
1221                         Run server
1222                 */
1223
1224                 if(server != NULL)
1225                 {
1226                         //TimeTaker timer("server->step(dtime)");
1227                         server->step(dtime);
1228                 }
1229
1230                 /*
1231                         Process environment
1232                 */
1233                 
1234                 {
1235                         //TimeTaker timer("client.step(dtime)");
1236                         client.step(dtime);
1237                         //client.step(dtime_avg1);
1238                 }
1239
1240                 // Read client events
1241                 for(;;)
1242                 {
1243                         ClientEvent event = client.getClientEvent();
1244                         if(event.type == CE_NONE)
1245                         {
1246                                 break;
1247                         }
1248                         else if(event.type == CE_PLAYER_DAMAGE)
1249                         {
1250                                 //u16 damage = event.player_damage.amount;
1251                                 //dstream<<"Player damage: "<<damage<<std::endl;
1252                                 damage_flash_timer = 0.05;
1253                         }
1254                         else if(event.type == CE_PLAYER_FORCE_MOVE)
1255                         {
1256                                 camera_yaw = event.player_force_move.yaw;
1257                                 camera_pitch = event.player_force_move.pitch;
1258                         }
1259                 }
1260                 
1261                 // Get player position
1262                 v3f player_position = client.getPlayerPosition();
1263
1264                 //TimeTaker //timer2("//timer2");
1265
1266                 /*
1267                         Mouse and camera control
1268                 */
1269                 
1270                 if((device->isWindowActive() && noMenuActive()) || random_input)
1271                 {
1272                         if(!random_input)
1273                                 device->getCursorControl()->setVisible(false);
1274
1275                         if(first_loop_after_window_activation){
1276                                 //std::cout<<"window active, first loop"<<std::endl;
1277                                 first_loop_after_window_activation = false;
1278                         }
1279                         else{
1280                                 s32 dx = input->getMousePos().X - displaycenter.X;
1281                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1282                                 //std::cout<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1283                                 
1284                                 const float keyspeed = 500;
1285                                 if(input->isKeyDown(irr::KEY_UP))
1286                                         dy -= dtime * keyspeed;
1287                                 if(input->isKeyDown(irr::KEY_DOWN))
1288                                         dy += dtime * keyspeed;
1289                                 if(input->isKeyDown(irr::KEY_LEFT))
1290                                         dx -= dtime * keyspeed;
1291                                 if(input->isKeyDown(irr::KEY_RIGHT))
1292                                         dx += dtime * keyspeed;
1293
1294                                 camera_yaw -= dx*0.2;
1295                                 camera_pitch += dy*0.2;
1296                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1297                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1298                         }
1299                         input->setMousePos(displaycenter.X, displaycenter.Y);
1300                 }
1301                 else{
1302                         device->getCursorControl()->setVisible(true);
1303
1304                         //std::cout<<"window inactive"<<std::endl;
1305                         first_loop_after_window_activation = true;
1306                 }
1307
1308                 camera_yaw = wrapDegrees(camera_yaw);
1309                 camera_pitch = wrapDegrees(camera_pitch);
1310                 
1311                 v3f camera_direction = v3f(0,0,1);
1312                 camera_direction.rotateYZBy(camera_pitch);
1313                 camera_direction.rotateXZBy(camera_yaw);
1314                 
1315                 // This is at the height of the eyes of the current figure
1316                 //v3f camera_position = player_position + v3f(0, BS+BS/2, 0);
1317                 // This is more like in minecraft
1318                 v3f camera_position = player_position + v3f(0, BS+BS*0.625, 0);
1319
1320                 camera->setPosition(camera_position);
1321                 // *100.0 helps in large map coordinates
1322                 camera->setTarget(camera_position + camera_direction * 100.0);
1323
1324                 if(FIELD_OF_VIEW_TEST){
1325                         client.updateCamera(v3f(0,0,0), v3f(0,0,1));
1326                 }
1327                 else{
1328                         //TimeTaker timer("client.updateCamera");
1329                         client.updateCamera(camera_position, camera_direction);
1330                 }
1331                 
1332                 //timer2.stop();
1333                 //TimeTaker //timer3("//timer3");
1334
1335                 /*
1336                         Calculate what block is the crosshair pointing to
1337                 */
1338                 
1339                 //u32 t1 = device->getTimer()->getRealTime();
1340                 
1341                 //f32 d = 4; // max. distance
1342                 f32 d = 4; // max. distance
1343                 core::line3d<f32> shootline(camera_position,
1344                                 camera_position + camera_direction * BS * (d+1));
1345
1346                 MapBlockObject *selected_object = client.getSelectedObject
1347                                 (d*BS, camera_position, shootline);
1348
1349                 ClientActiveObject *selected_active_object
1350                                 = client.getSelectedActiveObject
1351                                         (d*BS, camera_position, shootline);
1352
1353                 if(selected_object != NULL)
1354                 {
1355                         //dstream<<"Client returned selected_object != NULL"<<std::endl;
1356
1357                         core::aabbox3d<f32> box_on_map
1358                                         = selected_object->getSelectionBoxOnMap();
1359
1360                         hilightboxes.push_back(box_on_map);
1361
1362                         infotext = narrow_to_wide(selected_object->infoText());
1363
1364                         if(input->getLeftClicked())
1365                         {
1366                                 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1367                                 client.clickObject(0, selected_object->getBlock()->getPos(),
1368                                                 selected_object->getId(), g_selected_item);
1369                         }
1370                         else if(input->getRightClicked())
1371                         {
1372                                 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1373                                 /*
1374                                         Check if we want to modify the object ourselves
1375                                 */
1376                                 if(selected_object->getTypeId() == MAPBLOCKOBJECT_TYPE_SIGN)
1377                                 {
1378                                         dstream<<"Sign object right-clicked"<<std::endl;
1379                                         
1380                                         if(random_input == false)
1381                                         {
1382                                                 // Get a new text for it
1383
1384                                                 TextDest *dest = new TextDestSign(
1385                                                                 selected_object->getBlock()->getPos(),
1386                                                                 selected_object->getId(),
1387                                                                 &client);
1388
1389                                                 SignObject *sign_object = (SignObject*)selected_object;
1390
1391                                                 std::wstring wtext =
1392                                                                 narrow_to_wide(sign_object->getText());
1393
1394                                                 (new GUITextInputMenu(guienv, guiroot, -1,
1395                                                                 &g_menumgr, dest,
1396                                                                 wtext))->drop();
1397                                         }
1398                                 }
1399                                 /*
1400                                         Otherwise pass the event to the server as-is
1401                                 */
1402                                 else
1403                                 {
1404                                         client.clickObject(1, selected_object->getBlock()->getPos(),
1405                                                         selected_object->getId(), g_selected_item);
1406                                 }
1407                         }
1408                 }
1409                 else if(selected_active_object != NULL)
1410                 {
1411                         //dstream<<"Client returned selected_active_object != NULL"<<std::endl;
1412                         
1413                         core::aabbox3d<f32> *selection_box
1414                                         = selected_active_object->getSelectionBox();
1415                         // Box should exist because object was returned in the
1416                         // first place
1417                         assert(selection_box);
1418
1419                         v3f pos = selected_active_object->getPosition();
1420
1421                         core::aabbox3d<f32> box_on_map(
1422                                         selection_box->MinEdge + pos,
1423                                         selection_box->MaxEdge + pos
1424                         );
1425
1426                         hilightboxes.push_back(box_on_map);
1427
1428                         //infotext = narrow_to_wide("A ClientActiveObject");
1429                         infotext = narrow_to_wide(selected_active_object->infoText());
1430
1431                         if(input->getLeftClicked())
1432                         {
1433                                 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1434                                 client.clickActiveObject(0,
1435                                                 selected_active_object->getId(), g_selected_item);
1436                         }
1437                         else if(input->getRightClicked())
1438                         {
1439                                 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1440                         }
1441                 }
1442                 else // selected_object == NULL
1443                 {
1444
1445                 /*
1446                         Find out which node we are pointing at
1447                 */
1448                 
1449                 bool nodefound = false;
1450                 v3s16 nodepos;
1451                 v3s16 neighbourpos;
1452                 core::aabbox3d<f32> nodehilightbox;
1453
1454                 getPointedNode(&client, player_position,
1455                                 camera_direction, camera_position,
1456                                 nodefound, shootline,
1457                                 nodepos, neighbourpos,
1458                                 nodehilightbox, d);
1459         
1460                 static float nodig_delay_counter = 0.0;
1461
1462                 if(nodefound)
1463                 {
1464                         static v3s16 nodepos_old(-32768,-32768,-32768);
1465
1466                         static float dig_time = 0.0;
1467                         static u16 dig_index = 0;
1468                         
1469                         /*
1470                                 Visualize selection
1471                         */
1472
1473                         hilightboxes.push_back(nodehilightbox);
1474
1475                         /*
1476                                 Check information text of node
1477                         */
1478
1479                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1480                         if(meta)
1481                         {
1482                                 infotext = narrow_to_wide(meta->infoText());
1483                         }
1484                         
1485                         //MapNode node = client.getNode(nodepos);
1486
1487                         /*
1488                                 Handle digging
1489                         */
1490                         
1491                         if(input->getLeftReleased())
1492                         {
1493                                 client.clearTempMod(nodepos);
1494                                 dig_time = 0.0;
1495                         }
1496                         
1497                         if(nodig_delay_counter > 0.0)
1498                         {
1499                                 nodig_delay_counter -= dtime;
1500                         }
1501                         else
1502                         {
1503                                 if(nodepos != nodepos_old)
1504                                 {
1505                                         std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","
1506                                                         <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1507
1508                                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1509                                         {
1510                                                 client.clearTempMod(nodepos_old);
1511                                                 dig_time = 0.0;
1512                                         }
1513                                 }
1514
1515                                 if(input->getLeftClicked() ||
1516                                                 (input->getLeftState() && nodepos != nodepos_old))
1517                                 {
1518                                         dstream<<DTIME<<"Started digging"<<std::endl;
1519                                         client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1520                                 }
1521                                 if(input->getLeftClicked())
1522                                 {
1523                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1524                                 }
1525                                 if(input->getLeftState())
1526                                 {
1527                                         MapNode n = client.getNode(nodepos);
1528                                 
1529                                         // Get tool name. Default is "" = bare hands
1530                                         std::string toolname = "";
1531                                         InventoryList *mlist = local_inventory.getList("main");
1532                                         if(mlist != NULL)
1533                                         {
1534                                                 InventoryItem *item = mlist->getItem(g_selected_item);
1535                                                 if(item && (std::string)item->getName() == "ToolItem")
1536                                                 {
1537                                                         ToolItem *titem = (ToolItem*)item;
1538                                                         toolname = titem->getToolName();
1539                                                 }
1540                                         }
1541
1542                                         // Get digging properties for material and tool
1543                                         u8 material = n.d;
1544                                         DiggingProperties prop =
1545                                                         getDiggingProperties(material, toolname);
1546                                         
1547                                         float dig_time_complete = 0.0;
1548
1549                                         if(prop.diggable == false)
1550                                         {
1551                                                 /*dstream<<"Material "<<(int)material
1552                                                                 <<" not diggable with \""
1553                                                                 <<toolname<<"\""<<std::endl;*/
1554                                                 // I guess nobody will wait for this long
1555                                                 dig_time_complete = 10000000.0;
1556                                         }
1557                                         else
1558                                         {
1559                                                 dig_time_complete = prop.time;
1560                                         }
1561                                         
1562                                         if(dig_time_complete >= 0.001)
1563                                         {
1564                                                 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1565                                                                 * dig_time/dig_time_complete);
1566                                         }
1567                                         // This is for torches
1568                                         else
1569                                         {
1570                                                 dig_index = CRACK_ANIMATION_LENGTH;
1571                                         }
1572
1573                                         if(dig_index < CRACK_ANIMATION_LENGTH)
1574                                         {
1575                                                 //TimeTaker timer("client.setTempMod");
1576                                                 //dstream<<"dig_index="<<dig_index<<std::endl;
1577                                                 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1578                                         }
1579                                         else
1580                                         {
1581                                                 dstream<<DTIME<<"Digging completed"<<std::endl;
1582                                                 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1583                                                 client.clearTempMod(nodepos);
1584                                                 client.removeNode(nodepos);
1585
1586                                                 dig_time = 0;
1587
1588                                                 nodig_delay_counter = dig_time_complete
1589                                                                 / (float)CRACK_ANIMATION_LENGTH;
1590
1591                                                 // We don't want a corresponding delay to
1592                                                 // very time consuming nodes
1593                                                 if(nodig_delay_counter > 0.5)
1594                                                 {
1595                                                         nodig_delay_counter = 0.5;
1596                                                 }
1597                                                 // We want a slight delay to very little
1598                                                 // time consuming nodes
1599                                                 float mindelay = 0.15;
1600                                                 if(nodig_delay_counter < mindelay)
1601                                                 {
1602                                                         nodig_delay_counter = mindelay;
1603                                                 }
1604                                         }
1605
1606                                         dig_time += dtime;
1607                                 }
1608                         }
1609                         
1610                         if(input->getRightClicked())
1611                         {
1612                                 std::cout<<DTIME<<"Ground right-clicked"<<std::endl;
1613                                 
1614                                 if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1615                                 {
1616                                         dstream<<"Sign node right-clicked"<<std::endl;
1617                                         
1618                                         SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1619                                         
1620                                         // Get a new text for it
1621
1622                                         TextDest *dest = new TextDestSignNode(nodepos, &client);
1623
1624                                         std::wstring wtext =
1625                                                         narrow_to_wide(signmeta->getText());
1626
1627                                         (new GUITextInputMenu(guienv, guiroot, -1,
1628                                                         &g_menumgr, dest,
1629                                                         wtext))->drop();
1630                                 }
1631                                 else if(meta && meta->typeId() == CONTENT_CHEST && !random_input)
1632                                 {
1633                                         dstream<<"Chest node right-clicked"<<std::endl;
1634                                         
1635                                         //ChestNodeMetadata *chestmeta = (ChestNodeMetadata*)meta;
1636
1637                                         std::string chest_inv_id;
1638                                         chest_inv_id += "nodemeta:";
1639                                         chest_inv_id += itos(nodepos.X);
1640                                         chest_inv_id += ",";
1641                                         chest_inv_id += itos(nodepos.Y);
1642                                         chest_inv_id += ",";
1643                                         chest_inv_id += itos(nodepos.Z);
1644                                         
1645                                         GUIInventoryMenu *menu =
1646                                                 new GUIInventoryMenu(guienv, guiroot, -1,
1647                                                         &g_menumgr, v2s16(8,9),
1648                                                         client.getInventoryContext(),
1649                                                         &client);
1650
1651                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1652                                         
1653                                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1654                                                         "list", chest_inv_id, "0",
1655                                                         v2s32(0, 0), v2s32(8, 4)));
1656                                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1657                                                         "list", "current_player", "main",
1658                                                         v2s32(0, 5), v2s32(8, 4)));
1659
1660                                         menu->setDrawSpec(draw_spec);
1661
1662                                         menu->drop();
1663
1664                                 }
1665                                 else if(meta && meta->typeId() == CONTENT_FURNACE && !random_input)
1666                                 {
1667                                         dstream<<"Furnace node right-clicked"<<std::endl;
1668                                         
1669                                         GUIFurnaceMenu *menu =
1670                                                 new GUIFurnaceMenu(guienv, guiroot, -1,
1671                                                         &g_menumgr, nodepos, &client);
1672
1673                                         menu->drop();
1674
1675                                 }
1676                                 else
1677                                 {
1678                                         client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1679                                 }
1680                         }
1681                         
1682                         nodepos_old = nodepos;
1683                 }
1684                 else{
1685                 }
1686
1687                 } // selected_object == NULL
1688                 
1689                 input->resetLeftClicked();
1690                 input->resetRightClicked();
1691                 
1692                 if(input->getLeftReleased())
1693                 {
1694                         std::cout<<DTIME<<"Left button released (stopped digging)"
1695                                         <<std::endl;
1696                         client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1697                 }
1698                 if(input->getRightReleased())
1699                 {
1700                         //std::cout<<DTIME<<"Right released"<<std::endl;
1701                         // Nothing here
1702                 }
1703                 
1704                 input->resetLeftReleased();
1705                 input->resetRightReleased();
1706                 
1707                 /*
1708                         Calculate stuff for drawing
1709                 */
1710
1711                 camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);
1712                 
1713                 u32 daynight_ratio = client.getDayNightRatio();
1714                 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1715                 video::SColor bgcolor = video::SColor(
1716                                 255,
1717                                 bgcolor_bright.getRed() * l / 255,
1718                                 bgcolor_bright.getGreen() * l / 255,
1719                                 bgcolor_bright.getBlue() * l / 255);
1720                                 /*skycolor.getRed() * l / 255,
1721                                 skycolor.getGreen() * l / 255,
1722                                 skycolor.getBlue() * l / 255);*/
1723
1724                 float brightness = (float)l/255.0;
1725
1726                 /*
1727                         Update skybox
1728                 */
1729                 if(fabs(brightness - old_brightness) > 0.01)
1730                         update_skybox(driver, smgr, skybox, brightness);
1731
1732                 /*
1733                         Update coulds
1734                 */
1735                 if(clouds)
1736                 {
1737                         clouds->step(dtime);
1738                         clouds->update(v2f(player_position.X, player_position.Z),
1739                                         0.05+brightness*0.95);
1740                 }
1741                 
1742                 // Store brightness value
1743                 old_brightness = brightness;
1744
1745                 /*
1746                         Fog
1747                 */
1748                 
1749                 if(g_settings.getBool("enable_fog") == true)
1750                 {
1751                         f32 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
1752                         if(draw_control.range_all)
1753                                 range = 100000*BS;
1754                         if(range < 50*BS)
1755                                 range = range * 0.5 + 25*BS;
1756
1757                         driver->setFog(
1758                                 bgcolor,
1759                                 video::EFT_FOG_LINEAR,
1760                                 range*0.4,
1761                                 range*1.0,
1762                                 0.01,
1763                                 false, // pixel fog
1764                                 false // range fog
1765                         );
1766                 }
1767                 else
1768                 {
1769                         driver->setFog(
1770                                 bgcolor,
1771                                 video::EFT_FOG_LINEAR,
1772                                 100000*BS,
1773                                 110000*BS,
1774                                 0.01,
1775                                 false, // pixel fog
1776                                 false // range fog
1777                         );
1778                 }
1779
1780
1781                 /*
1782                         Update gui stuff (0ms)
1783                 */
1784
1785                 //TimeTaker guiupdatetimer("Gui updating");
1786                 
1787                 {
1788                         static float drawtime_avg = 0;
1789                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
1790                         static float beginscenetime_avg = 0;
1791                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
1792                         static float scenetime_avg = 0;
1793                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
1794                         static float endscenetime_avg = 0;
1795                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
1796                         
1797                         char temptext[300];
1798                         snprintf(temptext, 300, "Minetest-c55 %s ("
1799                                         "R: range_all=%i"
1800                                         ")"
1801                                         " drawtime=%.0f, beginscenetime=%.0f"
1802                                         ", scenetime=%.0f, endscenetime=%.0f",
1803                                         VERSION_STRING,
1804                                         draw_control.range_all,
1805                                         drawtime_avg,
1806                                         beginscenetime_avg,
1807                                         scenetime_avg,
1808                                         endscenetime_avg
1809                                         );
1810                         
1811                         guitext->setText(narrow_to_wide(temptext).c_str());
1812                 }
1813                 
1814                 {
1815                         char temptext[300];
1816                         snprintf(temptext, 300,
1817                                         "(% .1f, % .1f, % .1f)"
1818                                         " (% .3f < btime_jitter < % .3f"
1819                                         ", dtime_jitter = % .1f %%"
1820                                         ", v_range = %.1f)",
1821                                         player_position.X/BS,
1822                                         player_position.Y/BS,
1823                                         player_position.Z/BS,
1824                                         busytime_jitter1_min_sample,
1825                                         busytime_jitter1_max_sample,
1826                                         dtime_jitter1_max_fraction * 100.0,
1827                                         draw_control.wanted_range
1828                                         );
1829
1830                         guitext2->setText(narrow_to_wide(temptext).c_str());
1831                 }
1832                 
1833                 {
1834                         guitext_info->setText(infotext.c_str());
1835                 }
1836                 
1837                 /*
1838                         Get chat messages from client
1839                 */
1840                 {
1841                         // Get new messages
1842                         std::wstring message;
1843                         while(client.getChatMessage(message))
1844                         {
1845                                 chat_lines.push_back(ChatLine(message));
1846                                 /*if(chat_lines.size() > 6)
1847                                 {
1848                                         core::list<ChatLine>::Iterator
1849                                                         i = chat_lines.begin();
1850                                         chat_lines.erase(i);
1851                                 }*/
1852                         }
1853                         // Append them to form the whole static text and throw
1854                         // it to the gui element
1855                         std::wstring whole;
1856                         // This will correspond to the line number counted from
1857                         // top to bottom, from size-1 to 0
1858                         s16 line_number = chat_lines.size();
1859                         // Count of messages to be removed from the top
1860                         u16 to_be_removed_count = 0;
1861                         for(core::list<ChatLine>::Iterator
1862                                         i = chat_lines.begin();
1863                                         i != chat_lines.end(); i++)
1864                         {
1865                                 // After this, line number is valid for this loop
1866                                 line_number--;
1867                                 // Increment age
1868                                 (*i).age += dtime;
1869                                 /*
1870                                         This results in a maximum age of 60*6 to the
1871                                         lowermost line and a maximum of 6 lines
1872                                 */
1873                                 float allowed_age = (6-line_number) * 60.0;
1874
1875                                 if((*i).age > allowed_age)
1876                                 {
1877                                         to_be_removed_count++;
1878                                         continue;
1879                                 }
1880                                 whole += (*i).text + L'\n';
1881                         }
1882                         for(u16 i=0; i<to_be_removed_count; i++)
1883                         {
1884                                 core::list<ChatLine>::Iterator
1885                                                 it = chat_lines.begin();
1886                                 chat_lines.erase(it);
1887                         }
1888                         guitext_chat->setText(whole.c_str());
1889
1890                         // Update gui element size and position
1891
1892                         /*core::rect<s32> rect(
1893                                         10,
1894                                         screensize.Y - guitext_chat_pad_bottom
1895                                                         - text_height*chat_lines.size(),
1896                                         screensize.X - 10,
1897                                         screensize.Y - guitext_chat_pad_bottom
1898                         );*/
1899                         core::rect<s32> rect(
1900                                         10,
1901                                         50,
1902                                         screensize.X - 10,
1903                                         50 + text_height*chat_lines.size()
1904                         );
1905
1906                         guitext_chat->setRelativePosition(rect);
1907
1908                         if(chat_lines.size() == 0)
1909                                 guitext_chat->setVisible(false);
1910                         else
1911                                 guitext_chat->setVisible(true);
1912                 }
1913
1914                 /*
1915                         Inventory
1916                 */
1917                 
1918                 static u16 old_selected_item = 65535;
1919                 if(client.getLocalInventoryUpdated()
1920                                 || g_selected_item != old_selected_item)
1921                 {
1922                         old_selected_item = g_selected_item;
1923                         //std::cout<<"Updating local inventory"<<std::endl;
1924                         client.getLocalInventory(local_inventory);
1925                 }
1926                 
1927                 /*
1928                         Send actions returned by the inventory menu
1929                 */
1930                 while(inventory_action_queue.size() != 0)
1931                 {
1932                         InventoryAction *a = inventory_action_queue.pop_front();
1933
1934                         client.sendInventoryAction(a);
1935                         // Eat it
1936                         delete a;
1937                 }
1938
1939                 /*
1940                         Drawing begins
1941                 */
1942
1943                 TimeTaker drawtimer("Drawing");
1944
1945                 
1946                 {
1947                         TimeTaker timer("beginScene");
1948                         driver->beginScene(true, true, bgcolor);
1949                         //driver->beginScene(false, true, bgcolor);
1950                         beginscenetime = timer.stop(true);
1951                 }
1952
1953                 //timer3.stop();
1954                 
1955                 //std::cout<<DTIME<<"smgr->drawAll()"<<std::endl;
1956                 
1957                 {
1958                         TimeTaker timer("smgr");
1959                         smgr->drawAll();
1960                         scenetime = timer.stop(true);
1961                 }
1962                 
1963                 {
1964                 //TimeTaker timer9("auxiliary drawings");
1965                 // 0ms
1966                 
1967                 //timer9.stop();
1968                 //TimeTaker //timer10("//timer10");
1969                 
1970                 video::SMaterial m;
1971                 //m.Thickness = 10;
1972                 m.Thickness = 3;
1973                 m.Lighting = false;
1974                 driver->setMaterial(m);
1975
1976                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
1977
1978                 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
1979                                 i != hilightboxes.end(); i++)
1980                 {
1981                         /*std::cout<<"hilightbox min="
1982                                         <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
1983                                         <<" max="
1984                                         <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
1985                                         <<std::endl;*/
1986                         driver->draw3DBox(*i, video::SColor(255,0,0,0));
1987                 }
1988
1989                 /*
1990                         Frametime log
1991                 */
1992                 if(g_settings.getBool("frametime_graph") == true)
1993                 {
1994                         s32 x = 10;
1995                         for(core::list<float>::Iterator
1996                                         i = frametime_log.begin();
1997                                         i != frametime_log.end();
1998                                         i++)
1999                         {
2000                                 driver->draw2DLine(v2s32(x,50),
2001                                                 v2s32(x,50+(*i)*1000),
2002                                                 video::SColor(255,255,255,255));
2003                                 x++;
2004                         }
2005                 }
2006
2007                 /*
2008                         Draw crosshair
2009                 */
2010                 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2011                                 displaycenter + core::vector2d<s32>(10,0),
2012                                 video::SColor(255,255,255,255));
2013                 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2014                                 displaycenter + core::vector2d<s32>(0,10),
2015                                 video::SColor(255,255,255,255));
2016
2017                 } // timer
2018
2019                 //timer10.stop();
2020                 //TimeTaker //timer11("//timer11");
2021
2022                 /*
2023                         Draw gui
2024                 */
2025                 // 0-1ms
2026                 guienv->drawAll();
2027
2028                 /*
2029                         Draw hotbar
2030                 */
2031                 {
2032                         draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
2033                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2034                                         client.getHP());
2035                 }
2036
2037                 /*
2038                         Damage flash
2039                 */
2040                 if(damage_flash_timer > 0.0)
2041                 {
2042                         damage_flash_timer -= dtime;
2043                         
2044                         video::SColor color(128,255,0,0);
2045                         driver->draw2DRectangle(color,
2046                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2047                                         NULL);
2048                 }
2049                 
2050                 /*
2051                         End scene
2052                 */
2053                 {
2054                         TimeTaker timer("endScene");
2055                         endSceneX(driver);
2056                         endscenetime = timer.stop(true);
2057                 }
2058
2059                 drawtime = drawtimer.stop(true);
2060
2061                 /*
2062                         End of drawing
2063                 */
2064
2065                 static s16 lastFPS = 0;
2066                 //u16 fps = driver->getFPS();
2067                 u16 fps = (1.0/dtime_avg1);
2068
2069                 if (lastFPS != fps)
2070                 {
2071                         core::stringw str = L"Minetest [";
2072                         str += driver->getName();
2073                         str += "] FPS=";
2074                         str += fps;
2075
2076                         device->setWindowCaption(str.c_str());
2077                         lastFPS = fps;
2078                 }
2079         }
2080         
2081         /*
2082                 Draw a "shutting down" screen, which will be shown while the map
2083                 generator and other stuff quits
2084         */
2085         {
2086                 const wchar_t *shuttingdowntext = L"Shutting down stuff...";
2087                 gui::IGUIStaticText *gui_shuttingdowntext = guienv->addStaticText(
2088                                 shuttingdowntext, textrect, false, false);
2089                 gui_shuttingdowntext->setTextAlignment(gui::EGUIA_CENTER,
2090                                 gui::EGUIA_UPPERLEFT);
2091                 driver->beginScene(true, true, video::SColor(255,0,0,0));
2092                 guienv->drawAll();
2093                 driver->endScene();
2094                 gui_shuttingdowntext->remove();
2095         }
2096 }
2097
2098