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
52 #include "logoutputbuffer.h"
55 Setting this to 1 enables a special camera mode that forces
56 the renderers to think that the camera statically points from
57 the starting place to a static direction.
59 This allows one to move around with the player and see what
60 is actually drawn behind solid things and behind the player.
62 #define FIELD_OF_VIEW_TEST 0
72 ChatLine(const std::wstring &a_text):
85 struct TextDestChat : public TextDest
87 TextDestChat(Client *client)
91 void gotText(std::wstring text)
98 m_client->sendChatMessage(text);
100 m_client->addChatMessage(text);
106 struct TextDestNodeMetadata : public TextDest
108 TextDestNodeMetadata(v3s16 p, Client *client)
113 void gotText(std::wstring text)
115 std::string ntext = wide_to_narrow(text);
116 infostream<<"Changing text of a sign node: "
118 m_client->sendSignNodeText(m_p, ntext);
125 /* Respawn menu callback */
127 class MainRespawnInitiator: public IRespawnInitiator
130 MainRespawnInitiator(bool *active, Client *client):
131 m_active(active), m_client(client)
138 m_client->sendRespawn();
148 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
150 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
151 Inventory *inventory, s32 halfheartcount, u16 playeritem)
153 InventoryList *mainlist = inventory->getList("main");
156 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
160 s32 padding = imgsize/12;
161 //s32 height = imgsize + padding*2;
162 s32 width = itemcount*(imgsize+padding*2);
164 // Position of upper left corner of bar
165 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
167 // Draw background color
168 /*core::rect<s32> barrect(0,0,width,height);
170 video::SColor bgcolor(255,128,128,128);
171 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
173 core::rect<s32> imgrect(0,0,imgsize,imgsize);
175 for(s32 i=0; i<itemcount; i++)
177 const ItemStack &item = mainlist->getItem(i);
179 core::rect<s32> rect = imgrect + pos
180 + v2s32(padding+i*(imgsize+padding*2), padding);
184 video::SColor c_outside(255,255,0,0);
185 //video::SColor c_outside(255,0,0,0);
186 //video::SColor c_inside(255,192,192,192);
187 s32 x1 = rect.UpperLeftCorner.X;
188 s32 y1 = rect.UpperLeftCorner.Y;
189 s32 x2 = rect.LowerRightCorner.X;
190 s32 y2 = rect.LowerRightCorner.Y;
191 // Black base borders
192 driver->draw2DRectangle(c_outside,
194 v2s32(x1 - padding, y1 - padding),
195 v2s32(x2 + padding, y1)
197 driver->draw2DRectangle(c_outside,
199 v2s32(x1 - padding, y2),
200 v2s32(x2 + padding, y2 + padding)
202 driver->draw2DRectangle(c_outside,
204 v2s32(x1 - padding, y1),
207 driver->draw2DRectangle(c_outside,
210 v2s32(x2 + padding, y2)
212 /*// Light inside borders
213 driver->draw2DRectangle(c_inside,
215 v2s32(x1 - padding/2, y1 - padding/2),
216 v2s32(x2 + padding/2, y1)
218 driver->draw2DRectangle(c_inside,
220 v2s32(x1 - padding/2, y2),
221 v2s32(x2 + padding/2, y2 + padding/2)
223 driver->draw2DRectangle(c_inside,
225 v2s32(x1 - padding/2, y1),
228 driver->draw2DRectangle(c_inside,
231 v2s32(x2 + padding/2, y2)
236 video::SColor bgcolor2(128,0,0,0);
237 driver->draw2DRectangle(bgcolor2, rect, NULL);
238 drawItemStack(driver, font, item, rect, NULL, gamedef);
244 video::ITexture *heart_texture =
245 gamedef->getTextureSource()->getTextureRaw("heart.png");
248 v2s32 p = pos + v2s32(0, -20);
249 for(s32 i=0; i<halfheartcount/2; i++)
251 const video::SColor color(255,255,255,255);
252 const video::SColor colors[] = {color,color,color,color};
253 core::rect<s32> rect(0,0,16,16);
255 driver->draw2DImage(heart_texture, rect,
256 core::rect<s32>(core::position2d<s32>(0,0),
257 core::dimension2di(heart_texture->getOriginalSize())),
261 if(halfheartcount % 2 == 1)
263 const video::SColor color(255,255,255,255);
264 const video::SColor colors[] = {color,color,color,color};
265 core::rect<s32> rect(0,0,16/2,16);
267 core::dimension2di srcd(heart_texture->getOriginalSize());
269 driver->draw2DImage(heart_texture, rect,
270 core::rect<s32>(core::position2d<s32>(0,0), srcd),
278 Check if a node is pointable
280 inline bool isPointableNode(const MapNode& n,
281 Client *client, bool liquids_pointable)
283 const ContentFeatures &features = client->getNodeDefManager()->get(n);
284 return features.pointable ||
285 (liquids_pointable && features.isLiquid());
289 Find what the player is pointing at
291 PointedThing getPointedThing(Client *client, v3f player_position,
292 v3f camera_direction, v3f camera_position,
293 core::line3d<f32> shootline, f32 d,
294 bool liquids_pointable,
295 bool look_for_object,
296 core::aabbox3d<f32> &hilightbox,
297 bool &should_show_hilightbox,
298 ClientActiveObject *&selected_object)
302 hilightbox = core::aabbox3d<f32>(0,0,0,0,0,0);
303 should_show_hilightbox = false;
304 selected_object = NULL;
306 INodeDefManager *nodedef = client->getNodeDefManager();
308 // First try to find a pointed at active object
311 selected_object = client->getSelectedActiveObject(d*BS,
312 camera_position, shootline);
314 if(selected_object != NULL)
316 core::aabbox3d<f32> *selection_box
317 = selected_object->getSelectionBox();
318 // Box should exist because object was returned in the
320 assert(selection_box);
322 v3f pos = selected_object->getPosition();
324 hilightbox = core::aabbox3d<f32>(
325 selection_box->MinEdge + pos,
326 selection_box->MaxEdge + pos
329 should_show_hilightbox = selected_object->doShowSelectionBox();
331 result.type = POINTEDTHING_OBJECT;
332 result.object_id = selected_object->getId();
336 // That didn't work, try to find a pointed at node
338 f32 mindistance = BS * 1001;
340 v3s16 pos_i = floatToInt(player_position, BS);
342 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
346 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
347 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
348 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
349 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
350 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
351 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
353 for(s16 y = ystart; y <= yend; y++)
354 for(s16 z = zstart; z <= zend; z++)
355 for(s16 x = xstart; x <= xend; x++)
360 n = client->getNode(v3s16(x,y,z));
362 catch(InvalidPositionException &e)
366 if(!isPointableNode(n, client, liquids_pointable))
370 v3f npf = intToFloat(np, BS);
375 v3s16(0,0,1), // back
377 v3s16(1,0,0), // right
378 v3s16(0,0,-1), // front
379 v3s16(0,-1,0), // bottom
380 v3s16(-1,0,0), // left
383 const ContentFeatures &f = nodedef->get(n);
385 if(f.selection_box.type == NODEBOX_FIXED)
387 core::aabbox3d<f32> box = f.selection_box.fixed;
391 v3s16 facedirs[6] = {
400 core::aabbox3d<f32> faceboxes[6] = {
403 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
404 box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
408 box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
409 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
413 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
414 box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
418 box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
419 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
423 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
424 box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
428 box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
429 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
433 for(u16 i=0; i<6; i++)
435 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
436 v3f centerpoint = npf + facedir_f * BS/2;
437 f32 distance = (centerpoint - camera_position).getLength();
438 if(distance >= mindistance)
440 if(!faceboxes[i].intersectsWithLine(shootline))
442 result.type = POINTEDTHING_NODE;
443 result.node_undersurface = np;
444 result.node_abovesurface = np+facedirs[i];
445 mindistance = distance;
447 should_show_hilightbox = true;
450 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
452 v3s16 dir = n.getWallMountedDir(nodedef);
453 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
454 dir_f *= BS/2 - BS/6 - BS/20;
455 v3f cpf = npf + dir_f;
456 f32 distance = (cpf - camera_position).getLength();
458 core::aabbox3d<f32> box;
461 if(dir == v3s16(0,1,0)){
462 box = f.selection_box.wall_top;
465 else if(dir == v3s16(0,-1,0)){
466 box = f.selection_box.wall_bottom;
472 f.selection_box.wall_side.MinEdge,
473 f.selection_box.wall_side.MaxEdge
476 for(s32 i=0; i<2; i++)
478 if(dir == v3s16(-1,0,0))
479 vertices[i].rotateXZBy(0);
480 if(dir == v3s16(1,0,0))
481 vertices[i].rotateXZBy(180);
482 if(dir == v3s16(0,0,-1))
483 vertices[i].rotateXZBy(90);
484 if(dir == v3s16(0,0,1))
485 vertices[i].rotateXZBy(-90);
488 box = core::aabbox3d<f32>(vertices[0]);
489 box.addInternalPoint(vertices[1]);
495 if(distance < mindistance)
497 if(box.intersectsWithLine(shootline))
499 result.type = POINTEDTHING_NODE;
500 result.node_undersurface = np;
501 result.node_abovesurface = np;
502 mindistance = distance;
504 should_show_hilightbox = true;
508 else // NODEBOX_REGULAR
510 for(u16 i=0; i<6; i++)
512 v3f dir_f = v3f(dirs[i].X,
513 dirs[i].Y, dirs[i].Z);
514 v3f centerpoint = npf + dir_f * BS/2;
516 (centerpoint - camera_position).getLength();
518 if(distance < mindistance)
520 core::CMatrix4<f32> m;
521 m.buildRotateFromTo(v3f(0,0,1), dir_f);
523 // This is the back face
525 v3f(BS/2, BS/2, BS/2),
526 v3f(-BS/2, -BS/2, BS/2+d)
529 for(u16 j=0; j<2; j++)
531 m.rotateVect(corners[j]);
535 core::aabbox3d<f32> facebox(corners[0]);
536 facebox.addInternalPoint(corners[1]);
538 if(facebox.intersectsWithLine(shootline))
540 result.type = POINTEDTHING_NODE;
541 result.node_undersurface = np;
542 result.node_abovesurface = np + dirs[i];
543 mindistance = distance;
545 //hilightbox = facebox;
547 const float d = 0.502;
548 core::aabbox3d<f32> nodebox
549 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
550 v3f nodepos_f = intToFloat(np, BS);
551 nodebox.MinEdge += nodepos_f;
552 nodebox.MaxEdge += nodepos_f;
553 hilightbox = nodebox;
554 should_show_hilightbox = true;
556 } // if distance < mindistance
564 void update_skybox(video::IVideoDriver* driver, ITextureSource *tsrc,
565 scene::ISceneManager* smgr, scene::ISceneNode* &skybox,
573 /*// Disable skybox if FarMesh is enabled
574 if(g_settings->getBool("enable_farmesh"))
577 if(brightness >= 0.5)
579 skybox = smgr->addSkyBoxSceneNode(
580 tsrc->getTextureRaw("skybox2.png"),
581 tsrc->getTextureRaw("skybox3.png"),
582 tsrc->getTextureRaw("skybox1.png"),
583 tsrc->getTextureRaw("skybox1.png"),
584 tsrc->getTextureRaw("skybox1.png"),
585 tsrc->getTextureRaw("skybox1.png"));
587 else if(brightness >= 0.2)
589 skybox = smgr->addSkyBoxSceneNode(
590 tsrc->getTextureRaw("skybox2_dawn.png"),
591 tsrc->getTextureRaw("skybox3_dawn.png"),
592 tsrc->getTextureRaw("skybox1_dawn.png"),
593 tsrc->getTextureRaw("skybox1_dawn.png"),
594 tsrc->getTextureRaw("skybox1_dawn.png"),
595 tsrc->getTextureRaw("skybox1_dawn.png"));
599 skybox = smgr->addSkyBoxSceneNode(
600 tsrc->getTextureRaw("skybox2_night.png"),
601 tsrc->getTextureRaw("skybox3_night.png"),
602 tsrc->getTextureRaw("skybox1_night.png"),
603 tsrc->getTextureRaw("skybox1_night.png"),
604 tsrc->getTextureRaw("skybox1_night.png"),
605 tsrc->getTextureRaw("skybox1_night.png"));
610 Draws a screen with a single text on it.
611 Text will be removed when the screen is drawn the next time.
613 /*gui::IGUIStaticText **/
614 void draw_load_screen(const std::wstring &text,
615 video::IVideoDriver* driver, gui::IGUIFont* font)
617 v2u32 screensize = driver->getScreenSize();
618 const wchar_t *loadingtext = text.c_str();
619 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
620 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
621 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
622 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
624 gui::IGUIStaticText *guitext = guienv->addStaticText(
625 loadingtext, textrect, false, false);
626 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
628 driver->beginScene(true, true, video::SColor(255,0,0,0));
637 /* Profiler display */
639 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
640 gui::IGUIFont *font, u32 text_height,
641 u32 show_profiler, u32 show_profiler_max)
643 if(show_profiler == 0)
645 guitext_profiler->setVisible(false);
650 std::ostringstream os(std::ios_base::binary);
651 g_profiler->printPage(os, show_profiler, show_profiler_max);
652 std::wstring text = narrow_to_wide(os.str());
653 guitext_profiler->setText(text.c_str());
654 guitext_profiler->setVisible(true);
656 s32 w = font->getDimension(text.c_str()).Width;
659 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
660 8+(text_height+5)*2 +
661 font->getDimension(text.c_str()).Height);
662 guitext_profiler->setRelativePosition(rect);
663 guitext_profiler->setVisible(true);
671 IrrlichtDevice *device,
674 std::string playername,
675 std::string password,
678 std::wstring &error_message,
679 std::string configpath
682 video::IVideoDriver* driver = device->getVideoDriver();
683 scene::ISceneManager* smgr = device->getSceneManager();
685 // Calculate text height using the font
686 u32 text_height = font->getDimension(L"Random test string").Height;
688 v2u32 screensize(0,0);
689 v2u32 last_screensize(0,0);
690 screensize = driver->getScreenSize();
692 const s32 hotbar_itemcount = 8;
693 //const s32 hotbar_imagesize = 36;
694 //const s32 hotbar_imagesize = 64;
695 s32 hotbar_imagesize = 48;
697 // The color of the sky
699 //video::SColor skycolor = video::SColor(255,140,186,250);
701 video::SColor bgcolor_bright = video::SColor(255,170,200,230);
704 Draw "Loading" screen
707 draw_load_screen(L"Loading...", driver, font);
709 // Create texture source
710 IWritableTextureSource *tsrc = createTextureSource(device);
712 // These will be filled by data received from the server
713 // Create item definition manager
714 IWritableItemDefManager *itemdef = createItemDefManager();
715 // Create node definition manager
716 IWritableNodeDefManager *nodedef = createNodeDefManager();
718 // Add chat log output for errors to be shown in chat
719 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
723 SharedPtr will delete it when it goes out of scope.
725 SharedPtr<Server> server;
727 draw_load_screen(L"Creating server...", driver, font);
728 infostream<<"Creating server"<<std::endl;
729 server = new Server(map_dir, configpath);
739 draw_load_screen(L"Creating client...", driver, font);
740 infostream<<"Creating client"<<std::endl;
742 MapDrawControl draw_control;
744 Client client(device, playername.c_str(), password, draw_control,
745 tsrc, itemdef, nodedef);
747 // Client acts as our GameDef
748 IGameDef *gamedef = &client;
750 draw_load_screen(L"Resolving address...", driver, font);
751 Address connect_address(0,0,0,0, port);
754 //connect_address.Resolve("localhost");
755 connect_address.setAddress(127,0,0,1);
757 connect_address.Resolve(address.c_str());
759 catch(ResolveError &e)
761 errorstream<<"Couldn't resolve address"<<std::endl;
763 error_message = L"Couldn't resolve address";
764 //gui_loadingtext->remove();
769 Attempt to connect to the server
772 infostream<<"Connecting to server at ";
773 connect_address.print(&infostream);
774 infostream<<std::endl;
775 client.connect(connect_address);
778 Wait for server to accept connection
780 bool could_connect = false;
782 float frametime = 0.033;
783 const float timeout = 10.0;
784 float time_counter = 0.0;
787 // Update client and server
788 client.step(frametime);
790 server->step(frametime);
793 if(client.connectedAndInitialized()){
794 could_connect = true;
798 if(client.accessDenied())
800 if(time_counter >= timeout)
804 std::wostringstream ss;
805 ss<<L"Connecting to server... (timeout in ";
806 ss<<(int)(timeout - time_counter + 1.0);
808 draw_load_screen(ss.str(), driver, font);
811 sleep_ms(1000*frametime);
812 time_counter += frametime;
815 catch(con::PeerNotFoundException &e)
819 Handle failure to connect
821 if(could_connect == false)
823 if(client.accessDenied())
825 error_message = L"Access denied. Reason: "
826 +client.accessDeniedReason();
827 errorstream<<wide_to_narrow(error_message)<<std::endl;
831 error_message = L"Connection timed out.";
832 errorstream<<"Timed out."<<std::endl;
834 //gui_loadingtext->remove();
839 Wait until content has been received
841 bool got_content = false;
843 float frametime = 0.033;
844 const float timeout = 30.0;
845 float time_counter = 0.0;
848 // Update client and server
849 client.step(frametime);
851 server->step(frametime);
854 if(client.texturesReceived() &&
855 client.itemdefReceived() &&
856 client.nodedefReceived()){
861 if(!client.connectedAndInitialized())
863 if(time_counter >= timeout)
867 std::wostringstream ss;
868 ss<<L"Waiting content... (continuing anyway in ";
869 ss<<(int)(timeout - time_counter + 1.0);
872 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
873 ss<<L" Item definitions\n";
874 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
875 ss<<L" Node definitions\n";
876 //ss<<(client.texturesReceived()?L"[X]":L"[ ]");
877 ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
880 draw_load_screen(ss.str(), driver, font);
883 sleep_ms(1000*frametime);
884 time_counter += frametime;
889 After all content has been received:
890 Update cached textures, meshes and materials
892 client.afterContentReceived();
897 float old_brightness = 1.0;
898 scene::ISceneNode* skybox = NULL;
899 update_skybox(driver, tsrc, smgr, skybox, 1.0);
902 Create the camera node
904 Camera camera(smgr, draw_control);
905 if (!camera.successfullyCreated(error_message))
908 f32 camera_yaw = 0; // "right/left"
909 f32 camera_pitch = 0; // "up/down"
915 float cloud_height = BS*100;
916 Clouds *clouds = NULL;
917 if(g_settings->getBool("enable_clouds"))
919 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1,
920 cloud_height, time(0));
927 FarMesh *farmesh = NULL;
928 if(g_settings->getBool("enable_farmesh"))
930 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
934 A copy of the local inventory
936 Inventory local_inventory(itemdef);
942 //gui_loadingtext->remove();
948 // First line of debug text
949 gui::IGUIStaticText *guitext = guienv->addStaticText(
951 core::rect<s32>(5, 5, 795, 5+text_height),
953 // Second line of debug text
954 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
956 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
958 // At the middle of the screen
959 // Object infos are shown in this
960 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
962 core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
965 // Status text (displays info when showing and hiding GUI stuff, etc.)
966 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
968 core::rect<s32>(0,0,0,0),
970 guitext_status->setVisible(false);
972 std::wstring statustext;
973 float statustext_time = 0;
976 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
978 core::rect<s32>(0,0,0,0),
979 //false, false); // Disable word wrap as of now
981 //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
982 core::list<ChatLine> chat_lines;
984 // Profiler text (size is updated when text is updated)
985 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
987 core::rect<s32>(0,0,0,0),
989 guitext_profiler->setBackgroundColor(video::SColor(80,0,0,0));
990 guitext_profiler->setVisible(false);
992 /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
993 (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
994 /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
995 (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
997 // Test the text input system
998 /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
1000 /*GUIMessageMenu *menu =
1001 new GUIMessageMenu(guienv, guiroot, -1,
1006 // Launch pause menu
1007 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1008 &g_menumgr))->drop();
1010 //s32 guitext_chat_pad_bottom = 70;
1013 Some statistics are collected in these
1016 u32 beginscenetime = 0;
1018 u32 endscenetime = 0;
1021 //throw con::PeerNotFoundException("lol");
1023 float brightness = 1.0;
1025 core::list<float> frametime_log;
1027 float nodig_delay_timer = 0.0;
1028 float dig_time = 0.0;
1030 PointedThing pointed_old;
1031 bool digging = false;
1032 bool ldown_for_dig = false;
1034 float damage_flash_timer = 0;
1035 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1037 const float object_hit_delay = 0.2;
1038 float object_hit_delay_timer = 0.0;
1040 bool invert_mouse = g_settings->getBool("invert_mouse");
1042 bool respawn_menu_active = false;
1043 bool update_wielded_item_trigger = false;
1045 bool show_hud = true;
1046 bool show_chat = true;
1047 bool force_fog_off = false;
1048 bool disable_camera_update = false;
1049 bool show_debug = g_settings->getBool("show_debug");
1050 bool show_debug_frametime = false;
1051 u32 show_profiler = 0;
1052 u32 show_profiler_max = 3; // Number of pages
1058 bool first_loop_after_window_activation = true;
1060 // TODO: Convert the static interval timers to these
1061 // Interval limiter for profiler
1062 IntervalLimiter m_profiler_interval;
1064 // Time is in milliseconds
1065 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1066 // NOTE: So we have to use getTime() and call run()s between them
1067 u32 lasttime = device->getTimer()->getTime();
1069 while(device->run() && kill == false)
1071 //std::cerr<<"frame"<<std::endl;
1073 if(client.accessDenied())
1075 error_message = L"Access denied. Reason: "
1076 +client.accessDeniedReason();
1077 errorstream<<wide_to_narrow(error_message)<<std::endl;
1081 if(g_gamecallback->disconnect_requested)
1083 g_gamecallback->disconnect_requested = false;
1087 if(g_gamecallback->changepassword_requested)
1089 (new GUIPasswordChange(guienv, guiroot, -1,
1090 &g_menumgr, &client))->drop();
1091 g_gamecallback->changepassword_requested = false;
1095 Process TextureSource's queue
1097 tsrc->processQueue();
1102 last_screensize = screensize;
1103 screensize = driver->getScreenSize();
1104 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1105 //bool screensize_changed = screensize != last_screensize;
1108 if(screensize.Y <= 800)
1109 hotbar_imagesize = 32;
1110 else if(screensize.Y <= 1280)
1111 hotbar_imagesize = 48;
1113 hotbar_imagesize = 64;
1115 // Hilight boxes collected during the loop and displayed
1116 core::list< core::aabbox3d<f32> > hilightboxes;
1119 std::wstring infotext;
1121 // When screen size changes, update positions and sizes of stuff
1122 /*if(screensize_changed)
1124 v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
1125 quick_inventory->updatePosition(pos);
1128 //TimeTaker //timer1("//timer1");
1130 // Time of frame without fps limit
1134 // not using getRealTime is necessary for wine
1135 u32 time = device->getTimer()->getTime();
1137 busytime_u32 = time - lasttime;
1140 busytime = busytime_u32 / 1000.0;
1143 //infostream<<"busytime_u32="<<busytime_u32<<std::endl;
1145 // Necessary for device->getTimer()->getTime()
1153 float fps_max = g_settings->getFloat("fps_max");
1154 u32 frametime_min = 1000./fps_max;
1156 if(busytime_u32 < frametime_min)
1158 u32 sleeptime = frametime_min - busytime_u32;
1159 device->sleep(sleeptime);
1163 // Necessary for device->getTimer()->getTime()
1167 Time difference calculation
1169 f32 dtime; // in seconds
1171 u32 time = device->getTimer()->getTime();
1173 dtime = (time - lasttime) / 1000.0;
1180 if(nodig_delay_timer >= 0)
1181 nodig_delay_timer -= dtime;
1182 if(object_hit_delay_timer >= 0)
1183 object_hit_delay_timer -= dtime;
1185 g_profiler->add("Elapsed time", dtime);
1186 g_profiler->avg("FPS", 1./dtime);
1189 Log frametime for visualization
1191 frametime_log.push_back(dtime);
1192 if(frametime_log.size() > 100)
1194 core::list<float>::Iterator i = frametime_log.begin();
1195 frametime_log.erase(i);
1199 Visualize frametime in terminal
1201 /*for(u32 i=0; i<dtime*400; i++)
1203 infostream<<std::endl;*/
1206 Time average and jitter calculation
1209 static f32 dtime_avg1 = 0.0;
1210 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1211 f32 dtime_jitter1 = dtime - dtime_avg1;
1213 static f32 dtime_jitter1_max_sample = 0.0;
1214 static f32 dtime_jitter1_max_fraction = 0.0;
1216 static f32 jitter1_max = 0.0;
1217 static f32 counter = 0.0;
1218 if(dtime_jitter1 > jitter1_max)
1219 jitter1_max = dtime_jitter1;
1224 dtime_jitter1_max_sample = jitter1_max;
1225 dtime_jitter1_max_fraction
1226 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1232 Busytime average and jitter calculation
1235 static f32 busytime_avg1 = 0.0;
1236 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1237 f32 busytime_jitter1 = busytime - busytime_avg1;
1239 static f32 busytime_jitter1_max_sample = 0.0;
1240 static f32 busytime_jitter1_min_sample = 0.0;
1242 static f32 jitter1_max = 0.0;
1243 static f32 jitter1_min = 0.0;
1244 static f32 counter = 0.0;
1245 if(busytime_jitter1 > jitter1_max)
1246 jitter1_max = busytime_jitter1;
1247 if(busytime_jitter1 < jitter1_min)
1248 jitter1_min = busytime_jitter1;
1252 busytime_jitter1_max_sample = jitter1_max;
1253 busytime_jitter1_min_sample = jitter1_min;
1260 Debug info for client
1263 static float counter = 0.0;
1268 client.printDebugInfo(infostream);
1275 float profiler_print_interval =
1276 g_settings->getFloat("profiler_print_interval");
1277 bool print_to_log = true;
1278 if(profiler_print_interval == 0){
1279 print_to_log = false;
1280 profiler_print_interval = 5;
1282 if(m_profiler_interval.step(dtime, profiler_print_interval))
1285 infostream<<"Profiler:"<<std::endl;
1286 g_profiler->print(infostream);
1289 update_profiler_gui(guitext_profiler, font, text_height,
1290 show_profiler, show_profiler_max);
1292 g_profiler->clear();
1296 Direct handling of user input
1299 // Reset input if window not active or some menu is active
1300 if(device->isWindowActive() == false || noMenuActive() == false)
1305 // Input handler step() (used by the random input generator)
1309 Launch menus and trigger stuff according to keys
1311 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1313 // drop selected item
1314 IDropAction *a = new IDropAction();
1316 a->from_inv.setCurrentPlayer();
1317 a->from_list = "main";
1318 a->from_i = client.getPlayerItem();
1319 client.inventoryAction(a);
1321 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1323 infostream<<"the_game: "
1324 <<"Launching inventory"<<std::endl;
1326 GUIInventoryMenu *menu =
1327 new GUIInventoryMenu(guienv, guiroot, -1,
1328 &g_menumgr, v2s16(8,7),
1331 InventoryLocation inventoryloc;
1332 inventoryloc.setCurrentPlayer();
1334 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1335 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1336 "list", inventoryloc, "main",
1337 v2s32(0, 3), v2s32(8, 4)));
1338 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1339 "list", inventoryloc, "craft",
1340 v2s32(3, 0), v2s32(3, 3)));
1341 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1342 "list", inventoryloc, "craftpreview",
1343 v2s32(7, 1), v2s32(1, 1)));
1345 menu->setDrawSpec(draw_spec);
1349 else if(input->wasKeyDown(EscapeKey))
1351 infostream<<"the_game: "
1352 <<"Launching pause menu"<<std::endl;
1353 // It will delete itself by itself
1354 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1355 &g_menumgr))->drop();
1357 // Move mouse cursor on top of the disconnect button
1358 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1360 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1362 TextDest *dest = new TextDestChat(&client);
1364 (new GUITextInputMenu(guienv, guiroot, -1,
1368 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1370 TextDest *dest = new TextDestChat(&client);
1372 (new GUITextInputMenu(guienv, guiroot, -1,
1376 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1378 if(g_settings->getBool("free_move"))
1380 g_settings->set("free_move","false");
1381 statustext = L"free_move disabled";
1382 statustext_time = 0;
1386 g_settings->set("free_move","true");
1387 statustext = L"free_move enabled";
1388 statustext_time = 0;
1391 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1393 if(g_settings->getBool("fast_move"))
1395 g_settings->set("fast_move","false");
1396 statustext = L"fast_move disabled";
1397 statustext_time = 0;
1401 g_settings->set("fast_move","true");
1402 statustext = L"fast_move enabled";
1403 statustext_time = 0;
1406 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1408 irr::video::IImage* const image = driver->createScreenShot();
1410 irr::c8 filename[256];
1411 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1412 g_settings->get("screenshot_path").c_str(),
1413 device->getTimer()->getRealTime());
1414 if (driver->writeImageToFile(image, filename)) {
1415 std::wstringstream sstr;
1416 sstr<<"Saved screenshot to '"<<filename<<"'";
1417 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1418 statustext = sstr.str();
1419 statustext_time = 0;
1421 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1426 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1428 show_hud = !show_hud;
1430 statustext = L"HUD shown";
1432 statustext = L"HUD hidden";
1433 statustext_time = 0;
1435 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1437 show_chat = !show_chat;
1439 statustext = L"Chat shown";
1441 statustext = L"Chat hidden";
1442 statustext_time = 0;
1444 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1446 force_fog_off = !force_fog_off;
1448 statustext = L"Fog disabled";
1450 statustext = L"Fog enabled";
1451 statustext_time = 0;
1453 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1455 disable_camera_update = !disable_camera_update;
1456 if(disable_camera_update)
1457 statustext = L"Camera update disabled";
1459 statustext = L"Camera update enabled";
1460 statustext_time = 0;
1462 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1464 // Initial / 3x toggle: Chat only
1465 // 1x toggle: Debug text with chat
1466 // 2x toggle: Debug text with frametime
1470 show_debug_frametime = false;
1471 statustext = L"Debug info shown";
1472 statustext_time = 0;
1474 else if(show_debug_frametime)
1477 show_debug_frametime = false;
1478 statustext = L"Debug info and frametime graph hidden";
1479 statustext_time = 0;
1483 show_debug_frametime = true;
1484 statustext = L"Frametime graph shown";
1485 statustext_time = 0;
1488 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1490 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1492 // FIXME: This updates the profiler with incomplete values
1493 update_profiler_gui(guitext_profiler, font, text_height,
1494 show_profiler, show_profiler_max);
1496 if(show_profiler != 0)
1498 std::wstringstream sstr;
1499 sstr<<"Profiler shown (page "<<show_profiler
1500 <<" of "<<show_profiler_max<<")";
1501 statustext = sstr.str();
1502 statustext_time = 0;
1506 statustext = L"Profiler hidden";
1507 statustext_time = 0;
1511 // Item selection with mouse wheel
1512 u16 new_playeritem = client.getPlayerItem();
1514 s32 wheel = input->getMouseWheel();
1515 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1516 hotbar_itemcount-1);
1520 if(new_playeritem < max_item)
1527 if(new_playeritem > 0)
1530 new_playeritem = max_item;
1535 for(u16 i=0; i<10; i++)
1537 const KeyPress *kp = NumberKey + (i + 1) % 10;
1538 if(input->wasKeyDown(*kp))
1540 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1544 infostream<<"Selected item: "
1545 <<new_playeritem<<std::endl;
1550 // Viewing range selection
1551 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1553 draw_control.range_all = !draw_control.range_all;
1554 if(draw_control.range_all)
1556 infostream<<"Enabled full viewing range"<<std::endl;
1557 statustext = L"Enabled full viewing range";
1558 statustext_time = 0;
1562 infostream<<"Disabled full viewing range"<<std::endl;
1563 statustext = L"Disabled full viewing range";
1564 statustext_time = 0;
1568 // Print debug stacks
1569 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1571 dstream<<"-----------------------------------------"
1573 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1574 dstream<<"-----------------------------------------"
1576 debug_stacks_print();
1580 Mouse and camera control
1581 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1584 if((device->isWindowActive() && noMenuActive()) || random_input)
1588 // Mac OSX gets upset if this is set every frame
1589 if(device->getCursorControl()->isVisible())
1590 device->getCursorControl()->setVisible(false);
1593 if(first_loop_after_window_activation){
1594 //infostream<<"window active, first loop"<<std::endl;
1595 first_loop_after_window_activation = false;
1598 s32 dx = input->getMousePos().X - displaycenter.X;
1599 s32 dy = input->getMousePos().Y - displaycenter.Y;
1602 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1604 /*const float keyspeed = 500;
1605 if(input->isKeyDown(irr::KEY_UP))
1606 dy -= dtime * keyspeed;
1607 if(input->isKeyDown(irr::KEY_DOWN))
1608 dy += dtime * keyspeed;
1609 if(input->isKeyDown(irr::KEY_LEFT))
1610 dx -= dtime * keyspeed;
1611 if(input->isKeyDown(irr::KEY_RIGHT))
1612 dx += dtime * keyspeed;*/
1614 camera_yaw -= dx*0.2;
1615 camera_pitch += dy*0.2;
1616 if(camera_pitch < -89.5) camera_pitch = -89.5;
1617 if(camera_pitch > 89.5) camera_pitch = 89.5;
1619 input->setMousePos(displaycenter.X, displaycenter.Y);
1622 // Mac OSX gets upset if this is set every frame
1623 if(device->getCursorControl()->isVisible() == false)
1624 device->getCursorControl()->setVisible(true);
1626 //infostream<<"window inactive"<<std::endl;
1627 first_loop_after_window_activation = true;
1631 Player speed control
1634 if(!noMenuActive() || !device->isWindowActive())
1636 PlayerControl control(
1647 client.setPlayerControl(control);
1660 PlayerControl control(
1661 input->isKeyDown(getKeySetting("keymap_forward")),
1662 input->isKeyDown(getKeySetting("keymap_backward")),
1663 input->isKeyDown(getKeySetting("keymap_left")),
1664 input->isKeyDown(getKeySetting("keymap_right")),
1665 input->isKeyDown(getKeySetting("keymap_jump")),
1666 input->isKeyDown(getKeySetting("keymap_special1")),
1667 input->isKeyDown(getKeySetting("keymap_sneak")),
1671 client.setPlayerControl(control);
1680 //TimeTaker timer("server->step(dtime)");
1681 server->step(dtime);
1689 //TimeTaker timer("client.step(dtime)");
1691 //client.step(dtime_avg1);
1695 // Read client events
1698 ClientEvent event = client.getClientEvent();
1699 if(event.type == CE_NONE)
1703 else if(event.type == CE_PLAYER_DAMAGE)
1705 //u16 damage = event.player_damage.amount;
1706 //infostream<<"Player damage: "<<damage<<std::endl;
1707 damage_flash_timer = 0.05;
1708 if(event.player_damage.amount >= 2){
1709 damage_flash_timer += 0.05 * event.player_damage.amount;
1712 else if(event.type == CE_PLAYER_FORCE_MOVE)
1714 camera_yaw = event.player_force_move.yaw;
1715 camera_pitch = event.player_force_move.pitch;
1717 else if(event.type == CE_DEATHSCREEN)
1719 if(respawn_menu_active)
1722 /*bool set_camera_point_target =
1723 event.deathscreen.set_camera_point_target;
1724 v3f camera_point_target;
1725 camera_point_target.X = event.deathscreen.camera_point_target_x;
1726 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1727 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1728 MainRespawnInitiator *respawner =
1729 new MainRespawnInitiator(
1730 &respawn_menu_active, &client);
1731 GUIDeathScreen *menu =
1732 new GUIDeathScreen(guienv, guiroot, -1,
1733 &g_menumgr, respawner);
1736 /* Handle visualization */
1738 damage_flash_timer = 0;
1740 /*LocalPlayer* player = client.getLocalPlayer();
1741 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1742 camera.update(player, busytime, screensize);*/
1744 else if(event.type == CE_TEXTURES_UPDATED)
1746 update_skybox(driver, tsrc, smgr, skybox, brightness);
1748 update_wielded_item_trigger = true;
1753 //TimeTaker //timer2("//timer2");
1755 LocalPlayer* player = client.getLocalPlayer();
1756 camera.update(player, busytime, screensize);
1759 v3f player_position = player->getPosition();
1760 v3f camera_position = camera.getPosition();
1761 v3f camera_direction = camera.getDirection();
1762 f32 camera_fov = camera.getFovMax();
1764 if(!disable_camera_update){
1765 client.updateCamera(camera_position,
1766 camera_direction, camera_fov);
1770 //TimeTaker //timer3("//timer3");
1773 For interaction purposes, get info about the held item
1775 - Is it a usable item?
1776 - Can it point to liquids?
1778 ItemStack playeritem;
1779 bool playeritem_usable = false;
1780 bool playeritem_liquids_pointable = false;
1782 InventoryList *mlist = local_inventory.getList("main");
1785 playeritem = mlist->getItem(client.getPlayerItem());
1786 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1787 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1792 Calculate what block is the crosshair pointing to
1795 //u32 t1 = device->getTimer()->getRealTime();
1797 f32 d = 4; // max. distance
1798 core::line3d<f32> shootline(camera_position,
1799 camera_position + camera_direction * BS * (d+1));
1801 core::aabbox3d<f32> hilightbox;
1802 bool should_show_hilightbox = false;
1803 ClientActiveObject *selected_object = NULL;
1805 PointedThing pointed = getPointedThing(
1807 &client, player_position, camera_direction,
1808 camera_position, shootline, d,
1809 playeritem_liquids_pointable, !ldown_for_dig,
1811 hilightbox, should_show_hilightbox,
1814 if(pointed != pointed_old)
1816 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1817 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1823 if(should_show_hilightbox)
1824 hilightboxes.push_back(hilightbox);
1828 - releasing left mouse button
1829 - pointing away from node
1833 if(input->getLeftReleased())
1835 infostream<<"Left button released"
1836 <<" (stopped digging)"<<std::endl;
1839 else if(pointed != pointed_old)
1841 if (pointed.type == POINTEDTHING_NODE
1842 && pointed_old.type == POINTEDTHING_NODE
1843 && pointed.node_undersurface == pointed_old.node_undersurface)
1845 // Still pointing to the same node,
1846 // but a different face. Don't reset.
1850 infostream<<"Pointing away from node"
1851 <<" (stopped digging)"<<std::endl;
1857 client.interact(1, pointed_old);
1858 client.clearTempMod(pointed_old.node_undersurface);
1862 if(!digging && ldown_for_dig && !input->getLeftState())
1864 ldown_for_dig = false;
1867 bool left_punch = false;
1868 bool left_punch_muted = false;
1870 if(playeritem_usable && input->getLeftState())
1872 if(input->getLeftClicked())
1873 client.interact(4, pointed);
1875 else if(pointed.type == POINTEDTHING_NODE)
1877 v3s16 nodepos = pointed.node_undersurface;
1878 v3s16 neighbourpos = pointed.node_abovesurface;
1881 Check information text of node
1884 NodeMetadata *meta = client.getNodeMetadata(nodepos);
1887 infotext = narrow_to_wide(meta->infoText());
1891 MapNode n = client.getNode(nodepos);
1892 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
1893 infotext = L"Unknown node: ";
1894 infotext += narrow_to_wide(nodedef->get(n).name);
1903 if(nodig_delay_timer <= 0.0 && input->getLeftState())
1907 infostream<<"Started digging"<<std::endl;
1908 client.interact(0, pointed);
1910 ldown_for_dig = true;
1912 MapNode n = client.getNode(nodepos);
1914 // Get digging properties for material and tool
1915 MaterialProperties mp = nodedef->get(n.getContent()).material;
1916 ToolDiggingProperties tp =
1917 playeritem.getToolDiggingProperties(itemdef);
1918 DiggingProperties prop = getDiggingProperties(&mp, &tp);
1920 float dig_time_complete = 0.0;
1922 if(prop.diggable == false)
1924 // I guess nobody will wait for this long
1925 dig_time_complete = 10000000.0;
1929 dig_time_complete = prop.time;
1932 if(dig_time_complete >= 0.001)
1934 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1935 * dig_time/dig_time_complete);
1937 // This is for torches
1940 dig_index = CRACK_ANIMATION_LENGTH;
1943 if(dig_index < CRACK_ANIMATION_LENGTH)
1945 //TimeTaker timer("client.setTempMod");
1946 //infostream<<"dig_index="<<dig_index<<std::endl;
1947 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1951 infostream<<"Digging completed"<<std::endl;
1952 client.interact(2, pointed);
1953 client.clearTempMod(nodepos);
1954 client.removeNode(nodepos);
1959 nodig_delay_timer = dig_time_complete
1960 / (float)CRACK_ANIMATION_LENGTH;
1962 // We don't want a corresponding delay to
1963 // very time consuming nodes
1964 if(nodig_delay_timer > 0.5)
1966 nodig_delay_timer = 0.5;
1968 // We want a slight delay to very little
1969 // time consuming nodes
1970 float mindelay = 0.15;
1971 if(nodig_delay_timer < mindelay)
1973 nodig_delay_timer = mindelay;
1979 camera.setDigging(0); // left click animation
1982 if(input->getRightClicked())
1984 infostream<<"Ground right-clicked"<<std::endl;
1986 // If metadata provides an inventory view, activate it
1987 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
1989 infostream<<"Launching custom inventory view"<<std::endl;
1991 InventoryLocation inventoryloc;
1992 inventoryloc.setNodeMeta(nodepos);
1999 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2001 GUIInventoryMenu::makeDrawSpecArrayFromString(
2003 meta->getInventoryDrawSpecString(),
2006 GUIInventoryMenu *menu =
2007 new GUIInventoryMenu(guienv, guiroot, -1,
2008 &g_menumgr, invsize,
2010 menu->setDrawSpec(draw_spec);
2013 // If metadata provides text input, activate text input
2014 else if(meta && meta->allowsTextInput() && !random_input)
2016 infostream<<"Launching metadata text input"<<std::endl;
2018 // Get a new text for it
2020 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2022 std::wstring wtext = narrow_to_wide(meta->getText());
2024 (new GUITextInputMenu(guienv, guiroot, -1,
2028 // Otherwise report right click to server
2031 client.interact(3, pointed);
2032 camera.setDigging(1); // right click animation
2036 else if(pointed.type == POINTEDTHING_OBJECT)
2038 infotext = narrow_to_wide(selected_object->infoText());
2040 //if(input->getLeftClicked())
2041 if(input->getLeftState())
2043 bool do_punch = false;
2044 bool do_punch_damage = false;
2045 if(object_hit_delay_timer <= 0.0){
2047 do_punch_damage = true;
2048 object_hit_delay_timer = object_hit_delay;
2050 if(input->getLeftClicked()){
2054 infostream<<"Left-clicked object"<<std::endl;
2057 if(do_punch_damage){
2058 // Report direct punch
2059 v3f objpos = selected_object->getPosition();
2060 v3f dir = (objpos - player_position).normalize();
2062 bool disable_send = selected_object->directReportPunch(playeritem.name, dir);
2064 client.interact(0, pointed);
2067 else if(input->getRightClicked())
2069 infostream<<"Right-clicked object"<<std::endl;
2070 client.interact(3, pointed); // place
2074 pointed_old = pointed;
2076 if(left_punch || (input->getLeftClicked() && !left_punch_muted))
2078 camera.setDigging(0); // left click animation
2081 input->resetLeftClicked();
2082 input->resetRightClicked();
2084 input->resetLeftReleased();
2085 input->resetRightReleased();
2088 Calculate stuff for drawing
2092 Calculate general brightness
2094 u32 daynight_ratio = client.getDayNightRatio();
2095 u8 light8 = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
2096 brightness = (float)light8/255.0;
2097 video::SColor bgcolor = video::SColor(
2099 bgcolor_bright.getRed() * brightness,
2100 bgcolor_bright.getGreen() * brightness,
2101 bgcolor_bright.getBlue() * brightness);
2102 /*skycolor.getRed() * brightness,
2103 skycolor.getGreen() * brightness,
2104 skycolor.getBlue() * brightness);*/
2109 if(fabs(brightness - old_brightness) > 0.01)
2110 update_skybox(driver, tsrc, smgr, skybox, brightness);
2117 clouds->step(dtime);
2118 clouds->update(v2f(player_position.X, player_position.Z),
2119 0.05+brightness*0.95);
2127 farmesh_range = draw_control.wanted_range * 10;
2128 if(draw_control.range_all && farmesh_range < 500)
2129 farmesh_range = 500;
2130 if(farmesh_range > 1000)
2131 farmesh_range = 1000;
2133 farmesh->step(dtime);
2134 farmesh->update(v2f(player_position.X, player_position.Z),
2135 0.05+brightness*0.95, farmesh_range);
2138 // Store brightness value
2139 old_brightness = brightness;
2145 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2150 range = BS*farmesh_range;
2154 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
2156 if(draw_control.range_all)
2159 range = range * 0.5 + 25*BS;*/
2164 video::EFT_FOG_LINEAR,
2176 video::EFT_FOG_LINEAR,
2186 Update gui stuff (0ms)
2189 //TimeTaker guiupdatetimer("Gui updating");
2191 const char program_name_and_version[] =
2192 "Minetest-c55 " VERSION_STRING;
2196 static float drawtime_avg = 0;
2197 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2198 /*static float beginscenetime_avg = 0;
2199 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2200 static float scenetime_avg = 0;
2201 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2202 static float endscenetime_avg = 0;
2203 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2206 snprintf(temptext, 300, "%s ("
2209 " drawtime=%.0f, dtime_jitter = % .1f %%"
2210 ", v_range = %.1f, RTT = %.3f",
2211 program_name_and_version,
2212 draw_control.range_all,
2214 dtime_jitter1_max_fraction * 100.0,
2215 draw_control.wanted_range,
2219 guitext->setText(narrow_to_wide(temptext).c_str());
2220 guitext->setVisible(true);
2222 else if(show_hud || show_chat)
2224 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2225 guitext->setVisible(true);
2229 guitext->setVisible(false);
2235 snprintf(temptext, 300,
2236 "(% .1f, % .1f, % .1f)"
2238 player_position.X/BS,
2239 player_position.Y/BS,
2240 player_position.Z/BS,
2241 wrapDegrees_0_360(camera_yaw));
2243 guitext2->setText(narrow_to_wide(temptext).c_str());
2244 guitext2->setVisible(true);
2248 guitext2->setVisible(false);
2252 guitext_info->setText(infotext.c_str());
2253 guitext_info->setVisible(show_hud);
2257 float statustext_time_max = 3.0;
2258 if(!statustext.empty())
2260 statustext_time += dtime;
2261 if(statustext_time >= statustext_time_max)
2264 statustext_time = 0;
2267 guitext_status->setText(statustext.c_str());
2268 guitext_status->setVisible(!statustext.empty());
2270 if(!statustext.empty())
2272 s32 status_y = screensize.Y - 130;
2273 core::rect<s32> rect(
2275 status_y - guitext_status->getTextHeight(),
2279 guitext_status->setRelativePosition(rect);
2282 video::SColor initial_color(255,0,0,0);
2283 if(guienv->getSkin())
2284 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2285 video::SColor final_color = initial_color;
2286 final_color.setAlpha(0);
2287 video::SColor fade_color =
2288 initial_color.getInterpolated_quadratic(
2291 statustext_time / (float) statustext_time_max);
2292 guitext_status->setOverrideColor(fade_color);
2293 guitext_status->enableOverrideColor(true);
2298 Get chat messages from client
2301 // Get new messages from error log buffer
2302 while(!chat_log_error_buf.empty())
2304 chat_lines.push_back(ChatLine(narrow_to_wide(
2305 chat_log_error_buf.get())));
2307 // Get new messages from client
2308 std::wstring message;
2309 while(client.getChatMessage(message))
2311 chat_lines.push_back(ChatLine(message));
2312 /*if(chat_lines.size() > 6)
2314 core::list<ChatLine>::Iterator
2315 i = chat_lines.begin();
2316 chat_lines.erase(i);
2319 // Append them to form the whole static text and throw
2320 // it to the gui element
2322 // This will correspond to the line number counted from
2323 // top to bottom, from size-1 to 0
2324 s16 line_number = chat_lines.size();
2325 // Count of messages to be removed from the top
2326 u16 to_be_removed_count = 0;
2327 for(core::list<ChatLine>::Iterator
2328 i = chat_lines.begin();
2329 i != chat_lines.end(); i++)
2331 // After this, line number is valid for this loop
2336 This results in a maximum age of 60*6 to the
2337 lowermost line and a maximum of 6 lines
2339 float allowed_age = (6-line_number) * 60.0;
2341 if((*i).age > allowed_age)
2343 to_be_removed_count++;
2346 whole += (*i).text + L'\n';
2348 for(u16 i=0; i<to_be_removed_count; i++)
2350 core::list<ChatLine>::Iterator
2351 it = chat_lines.begin();
2352 chat_lines.erase(it);
2354 guitext_chat->setText(whole.c_str());
2356 // Update gui element size and position
2358 /*core::rect<s32> rect(
2360 screensize.Y - guitext_chat_pad_bottom
2361 - text_height*chat_lines.size(),
2363 screensize.Y - guitext_chat_pad_bottom
2366 s32 chat_y = 5+(text_height+5);
2368 chat_y += (text_height+5);
2369 core::rect<s32> rect(
2373 chat_y + guitext_chat->getTextHeight()
2376 guitext_chat->setRelativePosition(rect);
2378 // Don't show chat if empty or profiler or debug is enabled
2379 guitext_chat->setVisible(chat_lines.size() != 0
2380 && show_chat && show_profiler == 0);
2387 if(client.getPlayerItem() != new_playeritem)
2389 client.selectPlayerItem(new_playeritem);
2391 if(client.getLocalInventoryUpdated())
2393 //infostream<<"Updating local inventory"<<std::endl;
2394 client.getLocalInventory(local_inventory);
2396 update_wielded_item_trigger = true;
2398 if(update_wielded_item_trigger)
2400 update_wielded_item_trigger = false;
2401 // Update wielded tool
2402 InventoryList *mlist = local_inventory.getList("main");
2405 item = mlist->getItem(client.getPlayerItem());
2406 camera.wield(item, gamedef);
2413 TimeTaker drawtimer("Drawing");
2417 TimeTaker timer("beginScene");
2418 driver->beginScene(false, true, bgcolor);
2419 //driver->beginScene(false, true, bgcolor);
2420 beginscenetime = timer.stop(true);
2425 //infostream<<"smgr->drawAll()"<<std::endl;
2428 TimeTaker timer("smgr");
2430 scenetime = timer.stop(true);
2434 //TimeTaker timer9("auxiliary drawings");
2438 //TimeTaker //timer10("//timer10");
2444 driver->setMaterial(m);
2446 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2450 for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2451 i != hilightboxes.end(); i++)
2453 /*infostream<<"hilightbox min="
2454 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2456 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2458 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2467 // Warning: This clears the Z buffer.
2468 camera.drawWieldedTool();
2475 client.renderPostFx();
2481 if(show_debug_frametime)
2484 s32 y = screensize.Y - 10;
2485 for(core::list<float>::Iterator
2486 i = frametime_log.begin();
2487 i != frametime_log.end();
2490 driver->draw2DLine(v2s32(x,y),
2491 v2s32(x,y-(*i)*1000),
2492 video::SColor(255,255,255,255));
2502 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2503 displaycenter + core::vector2d<s32>(10,0),
2504 video::SColor(255,255,255,255));
2505 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2506 displaycenter + core::vector2d<s32>(0,10),
2507 video::SColor(255,255,255,255));
2513 //TimeTaker //timer11("//timer11");
2526 draw_hotbar(driver, font, gamedef,
2527 v2s32(displaycenter.X, screensize.Y),
2528 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2529 client.getHP(), client.getPlayerItem());
2535 if(damage_flash_timer > 0.0)
2537 damage_flash_timer -= dtime;
2539 video::SColor color(128,255,0,0);
2540 driver->draw2DRectangle(color,
2541 core::rect<s32>(0,0,screensize.X,screensize.Y),
2549 TimeTaker timer("endScene");
2551 endscenetime = timer.stop(true);
2554 drawtime = drawtimer.stop(true);
2560 static s16 lastFPS = 0;
2561 //u16 fps = driver->getFPS();
2562 u16 fps = (1.0/dtime_avg1);
2566 core::stringw str = L"Minetest [";
2567 str += driver->getName();
2571 device->setWindowCaption(str.c_str());
2583 Draw a "shutting down" screen, which will be shown while the map
2584 generator and other stuff quits
2587 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2588 draw_load_screen(L"Shutting down stuff...", driver, font);
2589 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2592 gui_shuttingdowntext->remove();*/
2595 } // Client scope (must be destructed before destructing *def and tsrc