3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
21 #include "common_irrlicht.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiInventoryMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
34 #include "materials.h"
42 #include "mainmenumanager.h"
46 // Needed for determining pointing to nodes
48 #include "nodemetadata.h"
49 #include "main.h" // For g_settings
51 #include "tile.h" // For TextureSource
54 Setting this to 1 enables a special camera mode that forces
55 the renderers to think that the camera statically points from
56 the starting place to a static direction.
58 This allows one to move around with the player and see what
59 is actually drawn behind solid things and behind the player.
61 #define FIELD_OF_VIEW_TEST 0
71 ChatLine(const std::wstring &a_text):
84 // Inventory actions from the menu are buffered here before sending
85 Queue<InventoryAction*> inventory_action_queue;
86 // This is a copy of the inventory that the client's environment has
87 Inventory local_inventory;
89 u16 g_selected_item = 0;
95 struct TextDestChat : public TextDest
97 TextDestChat(Client *client)
101 void gotText(std::wstring text)
103 // Discard empty line
108 m_client->sendChatMessage(text);
110 m_client->addChatMessage(text);
116 struct TextDestNodeMetadata : public TextDest
118 TextDestNodeMetadata(v3s16 p, Client *client)
123 void gotText(std::wstring text)
125 std::string ntext = wide_to_narrow(text);
126 infostream<<"Changing text of a sign node: "
128 m_client->sendSignNodeText(m_p, ntext);
135 /* Respawn menu callback */
137 class MainRespawnInitiator: public IRespawnInitiator
140 MainRespawnInitiator(bool *active, Client *client):
141 m_active(active), m_client(client)
148 m_client->sendRespawn();
158 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
159 ITextureSource *tsrc,
160 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
161 Inventory *inventory, s32 halfheartcount)
163 InventoryList *mainlist = inventory->getList("main");
166 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
170 s32 padding = imgsize/12;
171 //s32 height = imgsize + padding*2;
172 s32 width = itemcount*(imgsize+padding*2);
174 // Position of upper left corner of bar
175 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
177 // Draw background color
178 /*core::rect<s32> barrect(0,0,width,height);
180 video::SColor bgcolor(255,128,128,128);
181 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
183 core::rect<s32> imgrect(0,0,imgsize,imgsize);
185 for(s32 i=0; i<itemcount; i++)
187 InventoryItem *item = mainlist->getItem(i);
189 core::rect<s32> rect = imgrect + pos
190 + v2s32(padding+i*(imgsize+padding*2), padding);
192 if(g_selected_item == i)
194 video::SColor c_outside(255,255,0,0);
195 //video::SColor c_outside(255,0,0,0);
196 //video::SColor c_inside(255,192,192,192);
197 s32 x1 = rect.UpperLeftCorner.X;
198 s32 y1 = rect.UpperLeftCorner.Y;
199 s32 x2 = rect.LowerRightCorner.X;
200 s32 y2 = rect.LowerRightCorner.Y;
201 // Black base borders
202 driver->draw2DRectangle(c_outside,
204 v2s32(x1 - padding, y1 - padding),
205 v2s32(x2 + padding, y1)
207 driver->draw2DRectangle(c_outside,
209 v2s32(x1 - padding, y2),
210 v2s32(x2 + padding, y2 + padding)
212 driver->draw2DRectangle(c_outside,
214 v2s32(x1 - padding, y1),
217 driver->draw2DRectangle(c_outside,
220 v2s32(x2 + padding, y2)
222 /*// Light inside borders
223 driver->draw2DRectangle(c_inside,
225 v2s32(x1 - padding/2, y1 - padding/2),
226 v2s32(x2 + padding/2, y1)
228 driver->draw2DRectangle(c_inside,
230 v2s32(x1 - padding/2, y2),
231 v2s32(x2 + padding/2, y2 + padding/2)
233 driver->draw2DRectangle(c_inside,
235 v2s32(x1 - padding/2, y1),
238 driver->draw2DRectangle(c_inside,
241 v2s32(x2 + padding/2, y2)
246 video::SColor bgcolor2(128,0,0,0);
247 driver->draw2DRectangle(bgcolor2, rect, NULL);
251 drawInventoryItem(driver, font, item, rect, NULL, tsrc);
258 video::ITexture *heart_texture = tsrc->getTextureRaw("heart.png");
261 v2s32 p = pos + v2s32(0, -20);
262 for(s32 i=0; i<halfheartcount/2; i++)
264 const video::SColor color(255,255,255,255);
265 const video::SColor colors[] = {color,color,color,color};
266 core::rect<s32> rect(0,0,16,16);
268 driver->draw2DImage(heart_texture, rect,
269 core::rect<s32>(core::position2d<s32>(0,0),
270 core::dimension2di(heart_texture->getOriginalSize())),
274 if(halfheartcount % 2 == 1)
276 const video::SColor color(255,255,255,255);
277 const video::SColor colors[] = {color,color,color,color};
278 core::rect<s32> rect(0,0,16/2,16);
280 core::dimension2di srcd(heart_texture->getOriginalSize());
282 driver->draw2DImage(heart_texture, rect,
283 core::rect<s32>(core::position2d<s32>(0,0), srcd),
291 Find what the player is pointing at
293 void getPointedNode(Client *client, v3f player_position,
294 v3f camera_direction, v3f camera_position,
295 bool &nodefound, core::line3d<f32> shootline,
296 v3s16 &nodepos, v3s16 &neighbourpos,
297 core::aabbox3d<f32> &nodehilightbox,
300 f32 mindistance = BS * 1001;
302 v3s16 pos_i = floatToInt(player_position, BS);
304 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
308 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
309 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
310 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
311 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
312 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
313 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
315 for(s16 y = ystart; y <= yend; y++)
316 for(s16 z = zstart; z <= zend; z++)
317 for(s16 x = xstart; x <= xend; x++)
322 n = client->getNode(v3s16(x,y,z));
323 if(client->getNodeDefManager()->get(n).pointable == false)
326 catch(InvalidPositionException &e)
332 v3f npf = intToFloat(np, BS);
337 v3s16(0,0,1), // back
339 v3s16(1,0,0), // right
340 v3s16(0,0,-1), // front
341 v3s16(0,-1,0), // bottom
342 v3s16(-1,0,0), // left
345 const ContentFeatures &f = client->getNodeDefManager()->get(n);
347 if(f.selection_box.type == NODEBOX_FIXED)
349 core::aabbox3d<f32> box = f.selection_box.fixed;
353 v3s16 facedirs[6] = {
362 core::aabbox3d<f32> faceboxes[6] = {
365 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
366 box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
370 box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
371 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
375 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
376 box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
380 box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
381 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
385 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
386 box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
390 box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
391 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
395 for(u16 i=0; i<6; i++)
397 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
398 v3f centerpoint = npf + facedir_f * BS/2;
399 f32 distance = (centerpoint - camera_position).getLength();
400 if(distance >= mindistance)
402 if(!faceboxes[i].intersectsWithLine(shootline))
406 neighbourpos = np+facedirs[i];
407 mindistance = distance;
408 nodehilightbox = box;
411 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
413 v3s16 dir = unpackDir(n.param2);
414 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
415 dir_f *= BS/2 - BS/6 - BS/20;
416 v3f cpf = npf + dir_f;
417 f32 distance = (cpf - camera_position).getLength();
419 core::aabbox3d<f32> box;
422 if(dir == v3s16(0,1,0)){
423 box = f.selection_box.wall_top;
426 else if(dir == v3s16(0,-1,0)){
427 box = f.selection_box.wall_bottom;
433 f.selection_box.wall_side.MinEdge,
434 f.selection_box.wall_side.MaxEdge
437 for(s32 i=0; i<2; i++)
439 if(dir == v3s16(-1,0,0))
440 vertices[i].rotateXZBy(0);
441 if(dir == v3s16(1,0,0))
442 vertices[i].rotateXZBy(180);
443 if(dir == v3s16(0,0,-1))
444 vertices[i].rotateXZBy(90);
445 if(dir == v3s16(0,0,1))
446 vertices[i].rotateXZBy(-90);
449 box = core::aabbox3d<f32>(vertices[0]);
450 box.addInternalPoint(vertices[1]);
456 if(distance < mindistance)
458 if(box.intersectsWithLine(shootline))
463 mindistance = distance;
464 nodehilightbox = box;
468 else // NODEBOX_REGULAR
470 for(u16 i=0; i<6; i++)
472 v3f dir_f = v3f(dirs[i].X,
473 dirs[i].Y, dirs[i].Z);
474 v3f centerpoint = npf + dir_f * BS/2;
476 (centerpoint - camera_position).getLength();
478 if(distance < mindistance)
480 core::CMatrix4<f32> m;
481 m.buildRotateFromTo(v3f(0,0,1), dir_f);
483 // This is the back face
485 v3f(BS/2, BS/2, BS/2),
486 v3f(-BS/2, -BS/2, BS/2+d)
489 for(u16 j=0; j<2; j++)
491 m.rotateVect(corners[j]);
495 core::aabbox3d<f32> facebox(corners[0]);
496 facebox.addInternalPoint(corners[1]);
498 if(facebox.intersectsWithLine(shootline))
502 neighbourpos = np + dirs[i];
503 mindistance = distance;
505 //nodehilightbox = facebox;
507 const float d = 0.502;
508 core::aabbox3d<f32> nodebox
509 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
510 v3f nodepos_f = intToFloat(nodepos, BS);
511 nodebox.MinEdge += nodepos_f;
512 nodebox.MaxEdge += nodepos_f;
513 nodehilightbox = nodebox;
515 } // if distance < mindistance
521 void update_skybox(video::IVideoDriver* driver, ITextureSource *tsrc,
522 scene::ISceneManager* smgr, scene::ISceneNode* &skybox,
530 /*// Disable skybox if FarMesh is enabled
531 if(g_settings->getBool("enable_farmesh"))
534 if(brightness >= 0.5)
536 skybox = smgr->addSkyBoxSceneNode(
537 tsrc->getTextureRaw("skybox2.png"),
538 tsrc->getTextureRaw("skybox3.png"),
539 tsrc->getTextureRaw("skybox1.png"),
540 tsrc->getTextureRaw("skybox1.png"),
541 tsrc->getTextureRaw("skybox1.png"),
542 tsrc->getTextureRaw("skybox1.png"));
544 else if(brightness >= 0.2)
546 skybox = smgr->addSkyBoxSceneNode(
547 tsrc->getTextureRaw("skybox2_dawn.png"),
548 tsrc->getTextureRaw("skybox3_dawn.png"),
549 tsrc->getTextureRaw("skybox1_dawn.png"),
550 tsrc->getTextureRaw("skybox1_dawn.png"),
551 tsrc->getTextureRaw("skybox1_dawn.png"),
552 tsrc->getTextureRaw("skybox1_dawn.png"));
556 skybox = smgr->addSkyBoxSceneNode(
557 tsrc->getTextureRaw("skybox2_night.png"),
558 tsrc->getTextureRaw("skybox3_night.png"),
559 tsrc->getTextureRaw("skybox1_night.png"),
560 tsrc->getTextureRaw("skybox1_night.png"),
561 tsrc->getTextureRaw("skybox1_night.png"),
562 tsrc->getTextureRaw("skybox1_night.png"));
567 Draws a screen with a single text on it.
568 Text will be removed when the screen is drawn the next time.
570 /*gui::IGUIStaticText **/
571 void draw_load_screen(const std::wstring &text,
572 video::IVideoDriver* driver, gui::IGUIFont* font)
574 v2u32 screensize = driver->getScreenSize();
575 const wchar_t *loadingtext = text.c_str();
576 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
577 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
578 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
579 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
581 gui::IGUIStaticText *guitext = guienv->addStaticText(
582 loadingtext, textrect, false, false);
583 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
585 driver->beginScene(true, true, video::SColor(255,0,0,0));
598 IrrlichtDevice *device,
601 std::string playername,
602 std::string password,
605 std::wstring &error_message,
606 std::string configpath
609 video::IVideoDriver* driver = device->getVideoDriver();
610 scene::ISceneManager* smgr = device->getSceneManager();
612 // Calculate text height using the font
613 u32 text_height = font->getDimension(L"Random test string").Height;
615 v2u32 screensize(0,0);
616 v2u32 last_screensize(0,0);
617 screensize = driver->getScreenSize();
619 const s32 hotbar_itemcount = 8;
620 //const s32 hotbar_imagesize = 36;
621 //const s32 hotbar_imagesize = 64;
622 s32 hotbar_imagesize = 48;
624 // The color of the sky
626 //video::SColor skycolor = video::SColor(255,140,186,250);
628 video::SColor bgcolor_bright = video::SColor(255,170,200,230);
631 Draw "Loading" screen
634 draw_load_screen(L"Loading...", driver, font);
636 // Create texture source
637 IWritableTextureSource *tsrc = createTextureSource(device);
639 // These will be filled by data received from the server
640 // Create tool definition manager
641 IWritableToolDefManager *tooldef = createToolDefManager();
642 // Create node definition manager
643 IWritableNodeDefManager *nodedef = createNodeDefManager();
647 SharedPtr will delete it when it goes out of scope.
649 SharedPtr<Server> server;
651 draw_load_screen(L"Creating server...", driver, font);
652 infostream<<"Creating server"<<std::endl;
653 server = new Server(map_dir, configpath);
663 draw_load_screen(L"Creating client...", driver, font);
664 infostream<<"Creating client"<<std::endl;
666 MapDrawControl draw_control;
668 Client client(device, playername.c_str(), password, draw_control,
669 tsrc, tooldef, nodedef);
671 // Client acts as our GameDef
672 IGameDef *gamedef = &client;
674 draw_load_screen(L"Resolving address...", driver, font);
675 Address connect_address(0,0,0,0, port);
678 //connect_address.Resolve("localhost");
679 connect_address.setAddress(127,0,0,1);
681 connect_address.Resolve(address.c_str());
683 catch(ResolveError &e)
685 errorstream<<"Couldn't resolve address"<<std::endl;
687 error_message = L"Couldn't resolve address";
688 //gui_loadingtext->remove();
693 Attempt to connect to the server
696 infostream<<"Connecting to server at ";
697 connect_address.print(&infostream);
698 infostream<<std::endl;
699 client.connect(connect_address);
702 Wait for server to accept connection
704 bool could_connect = false;
706 float frametime = 0.033;
707 const float timeout = 10.0;
708 float time_counter = 0.0;
711 // Update client and server
712 client.step(frametime);
714 server->step(frametime);
717 if(client.connectedAndInitialized()){
718 could_connect = true;
722 if(client.accessDenied())
724 if(time_counter >= timeout)
728 std::wostringstream ss;
729 ss<<L"Connecting to server... (timeout in ";
730 ss<<(int)(timeout - time_counter + 1.0);
732 draw_load_screen(ss.str(), driver, font);
735 sleep_ms(1000*frametime);
736 time_counter += frametime;
739 catch(con::PeerNotFoundException &e)
743 Handle failure to connect
745 if(could_connect == false)
747 if(client.accessDenied())
749 error_message = L"Access denied. Reason: "
750 +client.accessDeniedReason();
751 errorstream<<wide_to_narrow(error_message)<<std::endl;
755 error_message = L"Connection timed out.";
756 errorstream<<"Timed out."<<std::endl;
758 //gui_loadingtext->remove();
763 Wait until content has been received
765 bool got_content = false;
767 float frametime = 0.033;
768 const float timeout = 5.0;
769 float time_counter = 0.0;
772 // Update client and server
773 client.step(frametime);
775 server->step(frametime);
778 if(client.texturesReceived() &&
779 client.tooldefReceived() &&
780 client.nodedefReceived()){
785 if(!client.connectedAndInitialized())
787 if(time_counter >= timeout)
791 std::wostringstream ss;
792 ss<<L"Waiting content... (continuing anyway in ";
793 ss<<(int)(timeout - time_counter + 1.0);
796 ss<<(client.tooldefReceived()?L"[X]":L"[ ]");
797 ss<<L" Tool definitions\n";
798 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
799 ss<<L" Node definitions\n";
800 //ss<<(client.texturesReceived()?L"[X]":L"[ ]");
801 ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
804 draw_load_screen(ss.str(), driver, font);
807 sleep_ms(1000*frametime);
808 time_counter += frametime;
815 float old_brightness = 1.0;
816 scene::ISceneNode* skybox = NULL;
817 update_skybox(driver, tsrc, smgr, skybox, 1.0);
820 Create the camera node
822 Camera camera(smgr, draw_control);
823 if (!camera.successfullyCreated(error_message))
826 f32 camera_yaw = 0; // "right/left"
827 f32 camera_pitch = 0; // "up/down"
833 float cloud_height = BS*100;
834 Clouds *clouds = NULL;
835 if(g_settings->getBool("enable_clouds"))
837 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1,
838 cloud_height, time(0));
845 FarMesh *farmesh = NULL;
846 if(g_settings->getBool("enable_farmesh"))
848 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
855 //gui_loadingtext->remove();
861 // First line of debug text
862 gui::IGUIStaticText *guitext = guienv->addStaticText(
864 core::rect<s32>(5, 5, 795, 5+text_height),
866 // Second line of debug text
867 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
869 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
871 // At the middle of the screen
872 // Object infos are shown in this
873 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
875 core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
879 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
881 core::rect<s32>(0,0,0,0),
882 //false, false); // Disable word wrap as of now
884 //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
885 core::list<ChatLine> chat_lines;
887 // Profiler text (size is updated when text is updated)
888 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
890 core::rect<s32>(6, 4+(text_height+5)*2, 400,
891 (text_height+5)*2 + text_height*35),
893 guitext_profiler->setBackgroundColor(video::SColor(80,0,0,0));
894 guitext_profiler->setVisible(false);
896 /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
897 (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
898 /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
899 (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
901 // Test the text input system
902 /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
904 /*GUIMessageMenu *menu =
905 new GUIMessageMenu(guienv, guiroot, -1,
911 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
912 &g_menumgr))->drop();
915 /*guitext2->setVisible(true);
916 guitext_info->setVisible(true);
917 guitext_chat->setVisible(true);*/
919 //s32 guitext_chat_pad_bottom = 70;
922 Some statistics are collected in these
925 u32 beginscenetime = 0;
927 u32 endscenetime = 0;
930 //throw con::PeerNotFoundException("lol");
932 float brightness = 1.0;
934 core::list<float> frametime_log;
936 float nodig_delay_counter = 0.0;
937 float dig_time = 0.0;
939 v3s16 nodepos_old(-32768,-32768,-32768);
941 float damage_flash_timer = 0;
942 s16 farmesh_range = 20*MAP_BLOCKSIZE;
944 const float object_hit_delay = 0.5;
945 float object_hit_delay_timer = 0.0;
947 bool invert_mouse = g_settings->getBool("invert_mouse");
949 bool respawn_menu_active = false;
951 bool show_profiler = false;
952 bool force_fog_off = false;
953 bool disable_camera_update = false;
959 bool first_loop_after_window_activation = true;
961 // TODO: Convert the static interval timers to these
962 // Interval limiter for profiler
963 IntervalLimiter m_profiler_interval;
965 // Time is in milliseconds
966 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
967 // NOTE: So we have to use getTime() and call run()s between them
968 u32 lasttime = device->getTimer()->getTime();
970 while(device->run() && kill == false)
972 //std::cerr<<"frame"<<std::endl;
974 if(client.accessDenied())
976 error_message = L"Access denied. Reason: "
977 +client.accessDeniedReason();
978 errorstream<<wide_to_narrow(error_message)<<std::endl;
982 if(g_gamecallback->disconnect_requested)
984 g_gamecallback->disconnect_requested = false;
988 if(g_gamecallback->changepassword_requested)
990 (new GUIPasswordChange(guienv, guiroot, -1,
991 &g_menumgr, &client))->drop();
992 g_gamecallback->changepassword_requested = false;
996 Process TextureSource's queue
998 tsrc->processQueue();
1003 last_screensize = screensize;
1004 screensize = driver->getScreenSize();
1005 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1006 //bool screensize_changed = screensize != last_screensize;
1009 if(screensize.Y <= 800)
1010 hotbar_imagesize = 32;
1011 else if(screensize.Y <= 1280)
1012 hotbar_imagesize = 48;
1014 hotbar_imagesize = 64;
1016 // Hilight boxes collected during the loop and displayed
1017 core::list< core::aabbox3d<f32> > hilightboxes;
1020 std::wstring infotext;
1022 // When screen size changes, update positions and sizes of stuff
1023 /*if(screensize_changed)
1025 v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
1026 quick_inventory->updatePosition(pos);
1029 //TimeTaker //timer1("//timer1");
1031 // Time of frame without fps limit
1035 // not using getRealTime is necessary for wine
1036 u32 time = device->getTimer()->getTime();
1038 busytime_u32 = time - lasttime;
1041 busytime = busytime_u32 / 1000.0;
1044 //infostream<<"busytime_u32="<<busytime_u32<<std::endl;
1046 // Necessary for device->getTimer()->getTime()
1054 float fps_max = g_settings->getFloat("fps_max");
1055 u32 frametime_min = 1000./fps_max;
1057 if(busytime_u32 < frametime_min)
1059 u32 sleeptime = frametime_min - busytime_u32;
1060 device->sleep(sleeptime);
1064 // Necessary for device->getTimer()->getTime()
1068 Time difference calculation
1070 f32 dtime; // in seconds
1072 u32 time = device->getTimer()->getTime();
1074 dtime = (time - lasttime) / 1000.0;
1081 object_hit_delay_timer -= dtime;
1083 g_profiler->add("Elapsed time", dtime);
1084 g_profiler->avg("FPS", 1./dtime);
1087 Log frametime for visualization
1089 frametime_log.push_back(dtime);
1090 if(frametime_log.size() > 100)
1092 core::list<float>::Iterator i = frametime_log.begin();
1093 frametime_log.erase(i);
1097 Visualize frametime in terminal
1099 /*for(u32 i=0; i<dtime*400; i++)
1101 infostream<<std::endl;*/
1104 Time average and jitter calculation
1107 static f32 dtime_avg1 = 0.0;
1108 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1109 f32 dtime_jitter1 = dtime - dtime_avg1;
1111 static f32 dtime_jitter1_max_sample = 0.0;
1112 static f32 dtime_jitter1_max_fraction = 0.0;
1114 static f32 jitter1_max = 0.0;
1115 static f32 counter = 0.0;
1116 if(dtime_jitter1 > jitter1_max)
1117 jitter1_max = dtime_jitter1;
1122 dtime_jitter1_max_sample = jitter1_max;
1123 dtime_jitter1_max_fraction
1124 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1130 Busytime average and jitter calculation
1133 static f32 busytime_avg1 = 0.0;
1134 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1135 f32 busytime_jitter1 = busytime - busytime_avg1;
1137 static f32 busytime_jitter1_max_sample = 0.0;
1138 static f32 busytime_jitter1_min_sample = 0.0;
1140 static f32 jitter1_max = 0.0;
1141 static f32 jitter1_min = 0.0;
1142 static f32 counter = 0.0;
1143 if(busytime_jitter1 > jitter1_max)
1144 jitter1_max = busytime_jitter1;
1145 if(busytime_jitter1 < jitter1_min)
1146 jitter1_min = busytime_jitter1;
1150 busytime_jitter1_max_sample = jitter1_max;
1151 busytime_jitter1_min_sample = jitter1_min;
1158 Debug info for client
1161 static float counter = 0.0;
1166 client.printDebugInfo(infostream);
1173 float profiler_print_interval =
1174 g_settings->getFloat("profiler_print_interval");
1175 bool print_to_log = true;
1176 if(profiler_print_interval == 0){
1177 print_to_log = false;
1178 profiler_print_interval = 5;
1180 if(m_profiler_interval.step(dtime, profiler_print_interval))
1183 infostream<<"Profiler:"<<std::endl;
1184 g_profiler->print(infostream);
1187 std::ostringstream os(std::ios_base::binary);
1188 g_profiler->print(os);
1189 std::wstring text = narrow_to_wide(os.str());
1190 guitext_profiler->setText(text.c_str());
1192 g_profiler->clear();
1194 s32 w = font->getDimension(text.c_str()).Width;
1197 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
1198 8+(text_height+5)*2 +
1199 font->getDimension(text.c_str()).Height);
1200 guitext_profiler->setRelativePosition(rect);
1204 Direct handling of user input
1207 // Reset input if window not active or some menu is active
1208 if(device->isWindowActive() == false || noMenuActive() == false)
1213 // Input handler step() (used by the random input generator)
1217 Launch menus according to keys
1219 if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1221 infostream<<"the_game: "
1222 <<"Launching inventory"<<std::endl;
1224 GUIInventoryMenu *menu =
1225 new GUIInventoryMenu(guienv, guiroot, -1,
1226 &g_menumgr, v2s16(8,7),
1227 client.getInventoryContext(),
1230 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1231 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1232 "list", "current_player", "main",
1233 v2s32(0, 3), v2s32(8, 4)));
1234 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1235 "list", "current_player", "craft",
1236 v2s32(3, 0), v2s32(3, 3)));
1237 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1238 "list", "current_player", "craftresult",
1239 v2s32(7, 1), v2s32(1, 1)));
1241 menu->setDrawSpec(draw_spec);
1245 else if(input->wasKeyDown(EscapeKey))
1247 infostream<<"the_game: "
1248 <<"Launching pause menu"<<std::endl;
1249 // It will delete itself by itself
1250 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1251 &g_menumgr))->drop();
1253 // Move mouse cursor on top of the disconnect button
1254 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1256 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1258 TextDest *dest = new TextDestChat(&client);
1260 (new GUITextInputMenu(guienv, guiroot, -1,
1264 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1266 TextDest *dest = new TextDestChat(&client);
1268 (new GUITextInputMenu(guienv, guiroot, -1,
1272 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1274 if(g_settings->getBool("free_move"))
1276 g_settings->set("free_move","false");
1277 chat_lines.push_back(ChatLine(L"free_move disabled"));
1281 g_settings->set("free_move","true");
1282 chat_lines.push_back(ChatLine(L"free_move enabled"));
1285 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1287 if(g_settings->getBool("fast_move"))
1289 g_settings->set("fast_move","false");
1290 chat_lines.push_back(ChatLine(L"fast_move disabled"));
1294 g_settings->set("fast_move","true");
1295 chat_lines.push_back(ChatLine(L"fast_move enabled"));
1298 else if(input->wasKeyDown(getKeySetting("keymap_frametime_graph")))
1300 if(g_settings->getBool("frametime_graph"))
1302 g_settings->set("frametime_graph","false");
1303 chat_lines.push_back(ChatLine(L"frametime_graph disabled"));
1307 g_settings->set("frametime_graph","true");
1308 chat_lines.push_back(ChatLine(L"frametime_graph enabled"));
1311 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1313 irr::video::IImage* const image = driver->createScreenShot();
1315 irr::c8 filename[256];
1316 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1317 g_settings->get("screenshot_path").c_str(),
1318 device->getTimer()->getRealTime());
1319 if (driver->writeImageToFile(image, filename)) {
1320 std::wstringstream sstr;
1321 sstr<<"Saved screenshot to '"<<filename<<"'";
1322 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1323 chat_lines.push_back(ChatLine(sstr.str()));
1325 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1330 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1332 show_profiler = !show_profiler;
1333 guitext_profiler->setVisible(show_profiler);
1335 chat_lines.push_back(ChatLine(L"Profiler disabled"));
1337 chat_lines.push_back(ChatLine(L"Profiler enabled"));
1339 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1341 force_fog_off = !force_fog_off;
1343 chat_lines.push_back(ChatLine(L"Fog disabled"));
1345 chat_lines.push_back(ChatLine(L"Fog enabled"));
1347 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1349 disable_camera_update = !disable_camera_update;
1350 if(disable_camera_update)
1351 chat_lines.push_back(ChatLine(L"Camera update disabled"));
1353 chat_lines.push_back(ChatLine(L"Camera update enabled"));
1356 // Item selection with mouse wheel
1358 s32 wheel = input->getMouseWheel();
1359 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1360 hotbar_itemcount-1);
1364 if(g_selected_item < max_item)
1367 g_selected_item = 0;
1371 if(g_selected_item > 0)
1374 g_selected_item = max_item;
1379 for(u16 i=0; i<10; i++)
1381 const KeyPress *kp = NumberKey + (i + 1) % 10;
1382 if(input->wasKeyDown(*kp))
1384 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1386 g_selected_item = i;
1388 infostream<<"Selected item: "
1389 <<g_selected_item<<std::endl;
1394 // Viewing range selection
1395 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1397 if(draw_control.range_all)
1399 draw_control.range_all = false;
1400 infostream<<"Disabled full viewing range"<<std::endl;
1404 draw_control.range_all = true;
1405 infostream<<"Enabled full viewing range"<<std::endl;
1409 // Print debug stacks
1410 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1412 dstream<<"-----------------------------------------"
1414 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1415 dstream<<"-----------------------------------------"
1417 debug_stacks_print();
1421 Mouse and camera control
1422 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1425 if((device->isWindowActive() && noMenuActive()) || random_input)
1429 // Mac OSX gets upset if this is set every frame
1430 if(device->getCursorControl()->isVisible())
1431 device->getCursorControl()->setVisible(false);
1434 if(first_loop_after_window_activation){
1435 //infostream<<"window active, first loop"<<std::endl;
1436 first_loop_after_window_activation = false;
1439 s32 dx = input->getMousePos().X - displaycenter.X;
1440 s32 dy = input->getMousePos().Y - displaycenter.Y;
1443 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1445 /*const float keyspeed = 500;
1446 if(input->isKeyDown(irr::KEY_UP))
1447 dy -= dtime * keyspeed;
1448 if(input->isKeyDown(irr::KEY_DOWN))
1449 dy += dtime * keyspeed;
1450 if(input->isKeyDown(irr::KEY_LEFT))
1451 dx -= dtime * keyspeed;
1452 if(input->isKeyDown(irr::KEY_RIGHT))
1453 dx += dtime * keyspeed;*/
1455 camera_yaw -= dx*0.2;
1456 camera_pitch += dy*0.2;
1457 if(camera_pitch < -89.5) camera_pitch = -89.5;
1458 if(camera_pitch > 89.5) camera_pitch = 89.5;
1460 input->setMousePos(displaycenter.X, displaycenter.Y);
1463 // Mac OSX gets upset if this is set every frame
1464 if(device->getCursorControl()->isVisible() == false)
1465 device->getCursorControl()->setVisible(true);
1467 //infostream<<"window inactive"<<std::endl;
1468 first_loop_after_window_activation = true;
1472 Player speed control
1475 if(!noMenuActive() || !device->isWindowActive())
1477 PlayerControl control(
1488 client.setPlayerControl(control);
1501 PlayerControl control(
1502 input->isKeyDown(getKeySetting("keymap_forward")),
1503 input->isKeyDown(getKeySetting("keymap_backward")),
1504 input->isKeyDown(getKeySetting("keymap_left")),
1505 input->isKeyDown(getKeySetting("keymap_right")),
1506 input->isKeyDown(getKeySetting("keymap_jump")),
1507 input->isKeyDown(getKeySetting("keymap_special1")),
1508 input->isKeyDown(getKeySetting("keymap_sneak")),
1512 client.setPlayerControl(control);
1521 //TimeTaker timer("server->step(dtime)");
1522 server->step(dtime);
1530 //TimeTaker timer("client.step(dtime)");
1532 //client.step(dtime_avg1);
1536 // Read client events
1539 ClientEvent event = client.getClientEvent();
1540 if(event.type == CE_NONE)
1544 else if(event.type == CE_PLAYER_DAMAGE)
1546 //u16 damage = event.player_damage.amount;
1547 //infostream<<"Player damage: "<<damage<<std::endl;
1548 damage_flash_timer = 0.05;
1549 if(event.player_damage.amount >= 2){
1550 damage_flash_timer += 0.05 * event.player_damage.amount;
1553 else if(event.type == CE_PLAYER_FORCE_MOVE)
1555 camera_yaw = event.player_force_move.yaw;
1556 camera_pitch = event.player_force_move.pitch;
1558 else if(event.type == CE_DEATHSCREEN)
1560 if(respawn_menu_active)
1563 /*bool set_camera_point_target =
1564 event.deathscreen.set_camera_point_target;
1565 v3f camera_point_target;
1566 camera_point_target.X = event.deathscreen.camera_point_target_x;
1567 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1568 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1569 MainRespawnInitiator *respawner =
1570 new MainRespawnInitiator(
1571 &respawn_menu_active, &client);
1572 GUIDeathScreen *menu =
1573 new GUIDeathScreen(guienv, guiroot, -1,
1574 &g_menumgr, respawner);
1577 /* Handle visualization */
1579 damage_flash_timer = 0;
1581 /*LocalPlayer* player = client.getLocalPlayer();
1582 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1583 camera.update(player, busytime, screensize);*/
1585 else if(event.type == CE_TEXTURES_UPDATED)
1587 update_skybox(driver, tsrc, smgr, skybox, brightness);
1592 //TimeTaker //timer2("//timer2");
1594 LocalPlayer* player = client.getLocalPlayer();
1595 camera.update(player, busytime, screensize);
1598 v3f player_position = player->getPosition();
1599 v3f camera_position = camera.getPosition();
1600 v3f camera_direction = camera.getDirection();
1601 f32 camera_fov = camera.getFovMax();
1603 if(!disable_camera_update){
1604 client.updateCamera(camera_position,
1605 camera_direction, camera_fov);
1609 //TimeTaker //timer3("//timer3");
1612 Calculate what block is the crosshair pointing to
1615 //u32 t1 = device->getTimer()->getRealTime();
1617 //f32 d = 4; // max. distance
1618 f32 d = 4; // max. distance
1619 core::line3d<f32> shootline(camera_position,
1620 camera_position + camera_direction * BS * (d+1));
1622 ClientActiveObject *selected_active_object
1623 = client.getSelectedActiveObject
1624 (d*BS, camera_position, shootline);
1626 bool left_punch = false;
1627 bool left_punch_muted = false;
1629 if(selected_active_object != NULL)
1631 /* Clear possible cracking animation */
1632 if(nodepos_old != v3s16(-32768,-32768,-32768))
1634 client.clearTempMod(nodepos_old);
1636 nodepos_old = v3s16(-32768,-32768,-32768);
1639 //infostream<<"Client returned selected_active_object != NULL"<<std::endl;
1641 core::aabbox3d<f32> *selection_box
1642 = selected_active_object->getSelectionBox();
1643 // Box should exist because object was returned in the
1645 assert(selection_box);
1647 v3f pos = selected_active_object->getPosition();
1649 core::aabbox3d<f32> box_on_map(
1650 selection_box->MinEdge + pos,
1651 selection_box->MaxEdge + pos
1654 if(selected_active_object->doShowSelectionBox())
1655 hilightboxes.push_back(box_on_map);
1657 //infotext = narrow_to_wide("A ClientActiveObject");
1658 infotext = narrow_to_wide(selected_active_object->infoText());
1660 //if(input->getLeftClicked())
1661 if(input->getLeftState())
1663 bool do_punch = false;
1664 bool do_punch_damage = false;
1665 if(object_hit_delay_timer <= 0.0){
1667 do_punch_damage = true;
1668 object_hit_delay_timer = object_hit_delay;
1670 if(input->getLeftClicked()){
1674 infostream<<"Left-clicked object"<<std::endl;
1677 if(do_punch_damage){
1678 client.clickActiveObject(0,
1679 selected_active_object->getId(), g_selected_item);
1682 else if(input->getRightClicked())
1684 infostream<<"Right-clicked object"<<std::endl;
1685 client.clickActiveObject(1,
1686 selected_active_object->getId(), g_selected_item);
1689 else // selected_object == NULL
1693 Find out which node we are pointing at
1696 bool nodefound = false;
1699 core::aabbox3d<f32> nodehilightbox;
1701 getPointedNode(&client, player_position,
1702 camera_direction, camera_position,
1703 nodefound, shootline,
1704 nodepos, neighbourpos,
1708 if(nodepos_old != v3s16(-32768,-32768,-32768))
1710 client.clearTempMod(nodepos_old);
1712 nodepos_old = v3s16(-32768,-32768,-32768);
1719 hilightboxes.push_back(nodehilightbox);
1722 Check information text of node
1725 NodeMetadata *meta = client.getNodeMetadata(nodepos);
1728 infotext = narrow_to_wide(meta->infoText());
1731 //MapNode node = client.getNode(nodepos);
1737 if(input->getLeftReleased())
1739 client.clearTempMod(nodepos);
1743 if(nodig_delay_counter > 0.0)
1745 nodig_delay_counter -= dtime;
1749 if(nodepos != nodepos_old)
1751 infostream<<"Pointing at ("<<nodepos.X<<","
1752 <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1754 if(nodepos_old != v3s16(-32768,-32768,-32768))
1756 client.clearTempMod(nodepos_old);
1758 nodepos_old = v3s16(-32768,-32768,-32768);
1762 if(input->getLeftClicked() ||
1763 (input->getLeftState() && nodepos != nodepos_old))
1765 infostream<<"Started digging"<<std::endl;
1766 client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1768 if(input->getLeftClicked())
1770 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1772 if(input->getLeftState())
1774 MapNode n = client.getNode(nodepos);
1776 // Get tool name. Default is "" = bare hands
1777 std::string toolname = "";
1778 InventoryList *mlist = local_inventory.getList("main");
1781 InventoryItem *item = mlist->getItem(g_selected_item);
1782 if(item && (std::string)item->getName() == "ToolItem")
1784 ToolItem *titem = (ToolItem*)item;
1785 toolname = titem->getToolName();
1789 // Get digging properties for material and tool
1790 content_t material = n.getContent();
1791 ToolDiggingProperties tp =
1792 tooldef->getDiggingProperties(toolname);
1793 DiggingProperties prop =
1794 getDiggingProperties(material, &tp, nodedef);
1796 float dig_time_complete = 0.0;
1798 if(prop.diggable == false)
1800 /*infostream<<"Material "<<(int)material
1801 <<" not diggable with \""
1802 <<toolname<<"\""<<std::endl;*/
1803 // I guess nobody will wait for this long
1804 dig_time_complete = 10000000.0;
1808 dig_time_complete = prop.time;
1811 if(dig_time_complete >= 0.001)
1813 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1814 * dig_time/dig_time_complete);
1816 // This is for torches
1819 dig_index = CRACK_ANIMATION_LENGTH;
1822 if(dig_index < CRACK_ANIMATION_LENGTH)
1824 //TimeTaker timer("client.setTempMod");
1825 //infostream<<"dig_index="<<dig_index<<std::endl;
1826 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1830 infostream<<"Digging completed"<<std::endl;
1831 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1832 client.clearTempMod(nodepos);
1833 client.removeNode(nodepos);
1837 nodig_delay_counter = dig_time_complete
1838 / (float)CRACK_ANIMATION_LENGTH;
1840 // We don't want a corresponding delay to
1841 // very time consuming nodes
1842 if(nodig_delay_counter > 0.5)
1844 nodig_delay_counter = 0.5;
1846 // We want a slight delay to very little
1847 // time consuming nodes
1848 float mindelay = 0.15;
1849 if(nodig_delay_counter < mindelay)
1851 nodig_delay_counter = mindelay;
1857 camera.setDigging(0); // left click animation
1862 if(input->getRightClicked())
1864 infostream<<"Ground right-clicked"<<std::endl;
1866 // If metadata provides an inventory view, activate it
1867 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
1869 infostream<<"Launching custom inventory view"<<std::endl;
1871 Construct the unique identification string of the node
1873 std::string current_name;
1874 current_name += "nodemeta:";
1875 current_name += itos(nodepos.X);
1876 current_name += ",";
1877 current_name += itos(nodepos.Y);
1878 current_name += ",";
1879 current_name += itos(nodepos.Z);
1885 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1887 GUIInventoryMenu::makeDrawSpecArrayFromString(
1889 meta->getInventoryDrawSpecString(),
1892 GUIInventoryMenu *menu =
1893 new GUIInventoryMenu(guienv, guiroot, -1,
1894 &g_menumgr, invsize,
1895 client.getInventoryContext(),
1897 menu->setDrawSpec(draw_spec);
1900 // If metadata provides text input, activate text input
1901 else if(meta && meta->allowsTextInput() && !random_input)
1903 infostream<<"Launching metadata text input"<<std::endl;
1905 // Get a new text for it
1907 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
1909 std::wstring wtext = narrow_to_wide(meta->getText());
1911 (new GUITextInputMenu(guienv, guiroot, -1,
1915 // Otherwise report right click to server
1918 client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1919 camera.setDigging(1); // right click animation
1923 nodepos_old = nodepos;
1926 } // selected_object == NULL
1928 if(left_punch || (input->getLeftClicked() && !left_punch_muted))
1930 camera.setDigging(0); // left click animation
1933 input->resetLeftClicked();
1934 input->resetRightClicked();
1936 if(input->getLeftReleased())
1938 infostream<<"Left button released (stopped digging)"
1940 client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1942 if(input->getRightReleased())
1944 //inostream<<DTIME<<"Right released"<<std::endl;
1948 input->resetLeftReleased();
1949 input->resetRightReleased();
1952 Calculate stuff for drawing
1956 Calculate general brightness
1958 u32 daynight_ratio = client.getDayNightRatio();
1959 u8 light8 = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1960 brightness = (float)light8/255.0;
1961 video::SColor bgcolor = video::SColor(
1963 bgcolor_bright.getRed() * brightness,
1964 bgcolor_bright.getGreen() * brightness,
1965 bgcolor_bright.getBlue() * brightness);
1966 /*skycolor.getRed() * brightness,
1967 skycolor.getGreen() * brightness,
1968 skycolor.getBlue() * brightness);*/
1973 if(fabs(brightness - old_brightness) > 0.01)
1974 update_skybox(driver, tsrc, smgr, skybox, brightness);
1981 clouds->step(dtime);
1982 clouds->update(v2f(player_position.X, player_position.Z),
1983 0.05+brightness*0.95);
1991 farmesh_range = draw_control.wanted_range * 10;
1992 if(draw_control.range_all && farmesh_range < 500)
1993 farmesh_range = 500;
1994 if(farmesh_range > 1000)
1995 farmesh_range = 1000;
1997 farmesh->step(dtime);
1998 farmesh->update(v2f(player_position.X, player_position.Z),
1999 0.05+brightness*0.95, farmesh_range);
2002 // Store brightness value
2003 old_brightness = brightness;
2009 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2014 range = BS*farmesh_range;
2018 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
2020 if(draw_control.range_all)
2023 range = range * 0.5 + 25*BS;*/
2028 video::EFT_FOG_LINEAR,
2040 video::EFT_FOG_LINEAR,
2050 Update gui stuff (0ms)
2053 //TimeTaker guiupdatetimer("Gui updating");
2056 static float drawtime_avg = 0;
2057 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2058 static float beginscenetime_avg = 0;
2059 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2060 static float scenetime_avg = 0;
2061 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2062 static float endscenetime_avg = 0;
2063 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
2066 snprintf(temptext, 300, "Minetest-c55 %s ("
2069 " drawtime=%.0f, beginscenetime=%.0f"
2070 ", scenetime=%.0f, endscenetime=%.0f",
2072 draw_control.range_all,
2079 guitext->setText(narrow_to_wide(temptext).c_str());
2084 snprintf(temptext, 300,
2085 "(% .1f, % .1f, % .1f)"
2086 " (% .3f < btime_jitter < % .3f"
2087 ", dtime_jitter = % .1f %%"
2088 ", v_range = %.1f, RTT = %.3f)",
2089 player_position.X/BS,
2090 player_position.Y/BS,
2091 player_position.Z/BS,
2092 busytime_jitter1_min_sample,
2093 busytime_jitter1_max_sample,
2094 dtime_jitter1_max_fraction * 100.0,
2095 draw_control.wanted_range,
2099 guitext2->setText(narrow_to_wide(temptext).c_str());
2103 guitext_info->setText(infotext.c_str());
2107 Get chat messages from client
2111 std::wstring message;
2112 while(client.getChatMessage(message))
2114 chat_lines.push_back(ChatLine(message));
2115 /*if(chat_lines.size() > 6)
2117 core::list<ChatLine>::Iterator
2118 i = chat_lines.begin();
2119 chat_lines.erase(i);
2122 // Append them to form the whole static text and throw
2123 // it to the gui element
2125 // This will correspond to the line number counted from
2126 // top to bottom, from size-1 to 0
2127 s16 line_number = chat_lines.size();
2128 // Count of messages to be removed from the top
2129 u16 to_be_removed_count = 0;
2130 for(core::list<ChatLine>::Iterator
2131 i = chat_lines.begin();
2132 i != chat_lines.end(); i++)
2134 // After this, line number is valid for this loop
2139 This results in a maximum age of 60*6 to the
2140 lowermost line and a maximum of 6 lines
2142 float allowed_age = (6-line_number) * 60.0;
2144 if((*i).age > allowed_age)
2146 to_be_removed_count++;
2149 whole += (*i).text + L'\n';
2151 for(u16 i=0; i<to_be_removed_count; i++)
2153 core::list<ChatLine>::Iterator
2154 it = chat_lines.begin();
2155 chat_lines.erase(it);
2157 guitext_chat->setText(whole.c_str());
2159 // Update gui element size and position
2161 /*core::rect<s32> rect(
2163 screensize.Y - guitext_chat_pad_bottom
2164 - text_height*chat_lines.size(),
2166 screensize.Y - guitext_chat_pad_bottom
2168 core::rect<s32> rect(
2172 50 + guitext_chat->getTextHeight()
2175 guitext_chat->setRelativePosition(rect);
2177 // Don't show chat if empty or profiler is enabled
2178 if(chat_lines.size() == 0 || show_profiler)
2179 guitext_chat->setVisible(false);
2181 guitext_chat->setVisible(true);
2188 static u16 old_selected_item = 65535;
2189 if(client.getLocalInventoryUpdated()
2190 || g_selected_item != old_selected_item)
2192 client.selectPlayerItem(g_selected_item);
2193 old_selected_item = g_selected_item;
2194 //infostream<<"Updating local inventory"<<std::endl;
2195 client.getLocalInventory(local_inventory);
2197 // Update wielded tool
2198 InventoryList *mlist = local_inventory.getList("main");
2199 InventoryItem *item = NULL;
2201 item = mlist->getItem(g_selected_item);
2202 camera.wield(item, gamedef);
2206 Send actions returned by the inventory menu
2208 while(inventory_action_queue.size() != 0)
2210 InventoryAction *a = inventory_action_queue.pop_front();
2212 client.sendInventoryAction(a);
2221 TimeTaker drawtimer("Drawing");
2225 TimeTaker timer("beginScene");
2226 driver->beginScene(true, true, bgcolor);
2227 //driver->beginScene(false, true, bgcolor);
2228 beginscenetime = timer.stop(true);
2233 //infostream<<"smgr->drawAll()"<<std::endl;
2236 TimeTaker timer("smgr");
2238 scenetime = timer.stop(true);
2242 //TimeTaker timer9("auxiliary drawings");
2246 //TimeTaker //timer10("//timer10");
2252 driver->setMaterial(m);
2254 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2256 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
2257 i != hilightboxes.end(); i++)
2259 /*infostream<<"hilightbox min="
2260 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2262 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2264 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2271 // Warning: This clears the Z buffer.
2272 camera.drawWieldedTool();
2279 client.renderPostFx();
2285 if(g_settings->getBool("frametime_graph") == true)
2288 for(core::list<float>::Iterator
2289 i = frametime_log.begin();
2290 i != frametime_log.end();
2293 driver->draw2DLine(v2s32(x,50),
2294 v2s32(x,50+(*i)*1000),
2295 video::SColor(255,255,255,255));
2303 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2304 displaycenter + core::vector2d<s32>(10,0),
2305 video::SColor(255,255,255,255));
2306 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2307 displaycenter + core::vector2d<s32>(0,10),
2308 video::SColor(255,255,255,255));
2313 //TimeTaker //timer11("//timer11");
2325 draw_hotbar(driver, font, tsrc,
2326 v2s32(displaycenter.X, screensize.Y),
2327 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2334 if(damage_flash_timer > 0.0)
2336 damage_flash_timer -= dtime;
2338 video::SColor color(128,255,0,0);
2339 driver->draw2DRectangle(color,
2340 core::rect<s32>(0,0,screensize.X,screensize.Y),
2348 TimeTaker timer("endScene");
2350 endscenetime = timer.stop(true);
2353 drawtime = drawtimer.stop(true);
2359 static s16 lastFPS = 0;
2360 //u16 fps = driver->getFPS();
2361 u16 fps = (1.0/dtime_avg1);
2365 core::stringw str = L"Minetest [";
2366 str += driver->getName();
2370 device->setWindowCaption(str.c_str());
2382 Draw a "shutting down" screen, which will be shown while the map
2383 generator and other stuff quits
2386 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2387 draw_load_screen(L"Shutting down stuff...", driver, font);
2388 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2391 gui_shuttingdowntext->remove();*/
2394 } // Client scope (must be destructed before destructing *def and tsrc