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"
35 #include "guiChatConsole.h"
43 #include "mainmenumanager.h"
47 // Needed for determining pointing to nodes
49 #include "nodemetadata.h"
50 #include "main.h" // For g_settings
52 #include "tile.h" // For TextureSource
53 #include "logoutputbuffer.h"
55 #include "quicktune_shortcutter.h"
56 #include "clientmap.h"
60 #include "sound_openal.h"
65 Setting this to 1 enables a special camera mode that forces
66 the renderers to think that the camera statically points from
67 the starting place to a static direction.
69 This allows one to move around with the player and see what
70 is actually drawn behind solid things and behind the player.
72 #define FIELD_OF_VIEW_TEST 0
79 struct TextDestChat : public TextDest
81 TextDestChat(Client *client)
85 void gotText(std::wstring text)
87 m_client->typeChatMessage(text);
93 struct TextDestNodeMetadata : public TextDest
95 TextDestNodeMetadata(v3s16 p, Client *client)
100 void gotText(std::wstring text)
102 std::string ntext = wide_to_narrow(text);
103 infostream<<"Changing text of a sign node: "
105 m_client->sendSignNodeText(m_p, ntext);
112 /* Respawn menu callback */
114 class MainRespawnInitiator: public IRespawnInitiator
117 MainRespawnInitiator(bool *active, Client *client):
118 m_active(active), m_client(client)
125 m_client->sendRespawn();
135 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
137 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
138 Inventory *inventory, s32 halfheartcount, u16 playeritem)
140 InventoryList *mainlist = inventory->getList("main");
143 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
147 s32 padding = imgsize/12;
148 //s32 height = imgsize + padding*2;
149 s32 width = itemcount*(imgsize+padding*2);
151 // Position of upper left corner of bar
152 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
154 // Draw background color
155 /*core::rect<s32> barrect(0,0,width,height);
157 video::SColor bgcolor(255,128,128,128);
158 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
160 core::rect<s32> imgrect(0,0,imgsize,imgsize);
162 for(s32 i=0; i<itemcount; i++)
164 const ItemStack &item = mainlist->getItem(i);
166 core::rect<s32> rect = imgrect + pos
167 + v2s32(padding+i*(imgsize+padding*2), padding);
171 video::SColor c_outside(255,255,0,0);
172 //video::SColor c_outside(255,0,0,0);
173 //video::SColor c_inside(255,192,192,192);
174 s32 x1 = rect.UpperLeftCorner.X;
175 s32 y1 = rect.UpperLeftCorner.Y;
176 s32 x2 = rect.LowerRightCorner.X;
177 s32 y2 = rect.LowerRightCorner.Y;
178 // Black base borders
179 driver->draw2DRectangle(c_outside,
181 v2s32(x1 - padding, y1 - padding),
182 v2s32(x2 + padding, y1)
184 driver->draw2DRectangle(c_outside,
186 v2s32(x1 - padding, y2),
187 v2s32(x2 + padding, y2 + padding)
189 driver->draw2DRectangle(c_outside,
191 v2s32(x1 - padding, y1),
194 driver->draw2DRectangle(c_outside,
197 v2s32(x2 + padding, y2)
199 /*// Light inside borders
200 driver->draw2DRectangle(c_inside,
202 v2s32(x1 - padding/2, y1 - padding/2),
203 v2s32(x2 + padding/2, y1)
205 driver->draw2DRectangle(c_inside,
207 v2s32(x1 - padding/2, y2),
208 v2s32(x2 + padding/2, y2 + padding/2)
210 driver->draw2DRectangle(c_inside,
212 v2s32(x1 - padding/2, y1),
215 driver->draw2DRectangle(c_inside,
218 v2s32(x2 + padding/2, y2)
223 video::SColor bgcolor2(128,0,0,0);
224 driver->draw2DRectangle(bgcolor2, rect, NULL);
225 drawItemStack(driver, font, item, rect, NULL, gamedef);
231 video::ITexture *heart_texture =
232 gamedef->getTextureSource()->getTextureRaw("heart.png");
235 v2s32 p = pos + v2s32(0, -20);
236 for(s32 i=0; i<halfheartcount/2; i++)
238 const video::SColor color(255,255,255,255);
239 const video::SColor colors[] = {color,color,color,color};
240 core::rect<s32> rect(0,0,16,16);
242 driver->draw2DImage(heart_texture, rect,
243 core::rect<s32>(core::position2d<s32>(0,0),
244 core::dimension2di(heart_texture->getOriginalSize())),
248 if(halfheartcount % 2 == 1)
250 const video::SColor color(255,255,255,255);
251 const video::SColor colors[] = {color,color,color,color};
252 core::rect<s32> rect(0,0,16/2,16);
254 core::dimension2di srcd(heart_texture->getOriginalSize());
256 driver->draw2DImage(heart_texture, rect,
257 core::rect<s32>(core::position2d<s32>(0,0), srcd),
265 Check if a node is pointable
267 inline bool isPointableNode(const MapNode& n,
268 Client *client, bool liquids_pointable)
270 const ContentFeatures &features = client->getNodeDefManager()->get(n);
271 return features.pointable ||
272 (liquids_pointable && features.isLiquid());
276 Find what the player is pointing at
278 PointedThing getPointedThing(Client *client, v3f player_position,
279 v3f camera_direction, v3f camera_position,
280 core::line3d<f32> shootline, f32 d,
281 bool liquids_pointable,
282 bool look_for_object,
283 core::aabbox3d<f32> &hilightbox,
284 bool &should_show_hilightbox,
285 ClientActiveObject *&selected_object)
289 hilightbox = core::aabbox3d<f32>(0,0,0,0,0,0);
290 should_show_hilightbox = false;
291 selected_object = NULL;
293 INodeDefManager *nodedef = client->getNodeDefManager();
294 ClientMap &map = client->getEnv().getClientMap();
296 // First try to find a pointed at active object
299 selected_object = client->getSelectedActiveObject(d*BS,
300 camera_position, shootline);
302 if(selected_object != NULL)
304 core::aabbox3d<f32> *selection_box
305 = selected_object->getSelectionBox();
306 // Box should exist because object was returned in the
308 assert(selection_box);
310 v3f pos = selected_object->getPosition();
312 hilightbox = core::aabbox3d<f32>(
313 selection_box->MinEdge + pos,
314 selection_box->MaxEdge + pos
317 should_show_hilightbox = selected_object->doShowSelectionBox();
319 result.type = POINTEDTHING_OBJECT;
320 result.object_id = selected_object->getId();
324 // That didn't work, try to find a pointed at node
326 f32 mindistance = BS * 1001;
328 v3s16 pos_i = floatToInt(player_position, BS);
330 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
334 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
335 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
336 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
337 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
338 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
339 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
341 for(s16 y = ystart; y <= yend; y++)
342 for(s16 z = zstart; z <= zend; z++)
343 for(s16 x = xstart; x <= xend; x++)
348 n = map.getNode(v3s16(x,y,z));
350 catch(InvalidPositionException &e)
354 if(!isPointableNode(n, client, liquids_pointable))
358 v3f npf = intToFloat(np, BS);
363 v3s16(0,0,1), // back
365 v3s16(1,0,0), // right
366 v3s16(0,0,-1), // front
367 v3s16(0,-1,0), // bottom
368 v3s16(-1,0,0), // left
371 const ContentFeatures &f = nodedef->get(n);
373 if(f.selection_box.type == NODEBOX_FIXED)
375 core::aabbox3d<f32> box = f.selection_box.fixed;
379 v3s16 facedirs[6] = {
388 core::aabbox3d<f32> faceboxes[6] = {
391 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
392 box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
396 box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
397 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
401 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
402 box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
406 box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
407 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
411 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
412 box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
416 box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
417 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
421 for(u16 i=0; i<6; i++)
423 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
424 v3f centerpoint = npf + facedir_f * BS/2;
425 f32 distance = (centerpoint - camera_position).getLength();
426 if(distance >= mindistance)
428 if(!faceboxes[i].intersectsWithLine(shootline))
430 result.type = POINTEDTHING_NODE;
431 result.node_undersurface = np;
432 result.node_abovesurface = np+facedirs[i];
433 mindistance = distance;
435 should_show_hilightbox = true;
438 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
440 v3s16 dir = n.getWallMountedDir(nodedef);
441 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
442 dir_f *= BS/2 - BS/6 - BS/20;
443 v3f cpf = npf + dir_f;
444 f32 distance = (cpf - camera_position).getLength();
446 core::aabbox3d<f32> box;
449 if(dir == v3s16(0,1,0)){
450 box = f.selection_box.wall_top;
453 else if(dir == v3s16(0,-1,0)){
454 box = f.selection_box.wall_bottom;
460 f.selection_box.wall_side.MinEdge,
461 f.selection_box.wall_side.MaxEdge
464 for(s32 i=0; i<2; i++)
466 if(dir == v3s16(-1,0,0))
467 vertices[i].rotateXZBy(0);
468 if(dir == v3s16(1,0,0))
469 vertices[i].rotateXZBy(180);
470 if(dir == v3s16(0,0,-1))
471 vertices[i].rotateXZBy(90);
472 if(dir == v3s16(0,0,1))
473 vertices[i].rotateXZBy(-90);
476 box = core::aabbox3d<f32>(vertices[0]);
477 box.addInternalPoint(vertices[1]);
483 if(distance < mindistance)
485 if(box.intersectsWithLine(shootline))
487 result.type = POINTEDTHING_NODE;
488 result.node_undersurface = np;
489 result.node_abovesurface = np;
490 mindistance = distance;
492 should_show_hilightbox = true;
496 else // NODEBOX_REGULAR
498 for(u16 i=0; i<6; i++)
500 v3f dir_f = v3f(dirs[i].X,
501 dirs[i].Y, dirs[i].Z);
502 v3f centerpoint = npf + dir_f * BS/2;
504 (centerpoint - camera_position).getLength();
506 if(distance < mindistance)
508 core::CMatrix4<f32> m;
509 m.buildRotateFromTo(v3f(0,0,1), dir_f);
511 // This is the back face
513 v3f(BS/2, BS/2, BS/2),
514 v3f(-BS/2, -BS/2, BS/2+d)
517 for(u16 j=0; j<2; j++)
519 m.rotateVect(corners[j]);
523 core::aabbox3d<f32> facebox(corners[0]);
524 facebox.addInternalPoint(corners[1]);
526 if(facebox.intersectsWithLine(shootline))
528 result.type = POINTEDTHING_NODE;
529 result.node_undersurface = np;
530 result.node_abovesurface = np + dirs[i];
531 mindistance = distance;
533 //hilightbox = facebox;
535 const float d = 0.502;
536 core::aabbox3d<f32> nodebox
537 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
538 v3f nodepos_f = intToFloat(np, BS);
539 nodebox.MinEdge += nodepos_f;
540 nodebox.MaxEdge += nodepos_f;
541 hilightbox = nodebox;
542 should_show_hilightbox = true;
544 } // if distance < mindistance
553 Draws a screen with a single text on it.
554 Text will be removed when the screen is drawn the next time.
556 /*gui::IGUIStaticText **/
557 void draw_load_screen(const std::wstring &text,
558 video::IVideoDriver* driver, gui::IGUIFont* font)
560 v2u32 screensize = driver->getScreenSize();
561 const wchar_t *loadingtext = text.c_str();
562 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
563 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
564 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
565 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
567 gui::IGUIStaticText *guitext = guienv->addStaticText(
568 loadingtext, textrect, false, false);
569 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
571 driver->beginScene(true, true, video::SColor(255,0,0,0));
580 /* Profiler display */
582 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
583 gui::IGUIFont *font, u32 text_height,
584 u32 show_profiler, u32 show_profiler_max)
586 if(show_profiler == 0)
588 guitext_profiler->setVisible(false);
593 std::ostringstream os(std::ios_base::binary);
594 g_profiler->printPage(os, show_profiler, show_profiler_max);
595 std::wstring text = narrow_to_wide(os.str());
596 guitext_profiler->setText(text.c_str());
597 guitext_profiler->setVisible(true);
599 s32 w = font->getDimension(text.c_str()).Width;
602 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
603 8+(text_height+5)*2 +
604 font->getDimension(text.c_str()).Height);
605 guitext_profiler->setRelativePosition(rect);
606 guitext_profiler->setVisible(true);
614 Profiler::GraphValues values;
620 Meta(float initial=0, video::SColor color=
621 video::SColor(255,255,255,255)):
627 std::list<Piece> m_log;
635 void put(const Profiler::GraphValues &values)
638 piece.values = values;
639 m_log.push_back(piece);
640 while(m_log.size() > m_log_max_size)
641 m_log.erase(m_log.begin());
644 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
645 gui::IGUIFont* font) const
647 std::map<std::string, Meta> m_meta;
648 for(std::list<Piece>::const_iterator k = m_log.begin();
649 k != m_log.end(); k++)
651 const Piece &piece = *k;
652 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
653 i != piece.values.end(); i++){
654 const std::string &id = i->first;
655 const float &value = i->second;
656 std::map<std::string, Meta>::iterator j =
658 if(j == m_meta.end()){
659 m_meta[id] = Meta(value);
662 if(value < j->second.min)
663 j->second.min = value;
664 if(value > j->second.max)
665 j->second.max = value;
670 static const video::SColor usable_colors[] = {
671 video::SColor(255,255,100,100),
672 video::SColor(255,90,225,90),
673 video::SColor(255,100,100,255),
674 video::SColor(255,255,150,50),
675 video::SColor(255,220,220,100)
677 static const u32 usable_colors_count =
678 sizeof(usable_colors) / sizeof(*usable_colors);
679 u32 next_color_i = 0;
680 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
681 i != m_meta.end(); i++){
682 Meta &meta = i->second;
683 video::SColor color(255,200,200,200);
684 if(next_color_i < usable_colors_count)
685 color = usable_colors[next_color_i++];
690 s32 textx = x_left + m_log_max_size + 15;
691 s32 textx2 = textx + 200 - 15;
695 u32 num_graphs = m_meta.size();
696 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
698 video::SColor bgcolor(120,0,0,0);
699 driver->draw2DRectangle(bgcolor, rect, NULL);
703 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
704 i != m_meta.end(); i++){
705 const std::string &id = i->first;
706 const Meta &meta = i->second;
708 s32 y = y_bottom - meta_i * 50;
709 float show_min = meta.min;
710 float show_max = meta.max;
711 if(show_min >= -0.0001 && show_max >= -0.0001){
712 if(show_min <= show_max * 0.5)
717 snprintf(buf, 10, "%.3g", show_max);
718 font->draw(narrow_to_wide(buf).c_str(),
719 core::rect<s32>(textx, y - graphh,
720 textx2, y - graphh + texth),
722 snprintf(buf, 10, "%.3g", show_min);
723 font->draw(narrow_to_wide(buf).c_str(),
724 core::rect<s32>(textx, y - texth,
727 font->draw(narrow_to_wide(id).c_str(),
728 core::rect<s32>(textx, y - graphh/2 - texth/2,
729 textx2, y - graphh/2 + texth/2),
732 s32 graph1h = graphh;
733 bool relativegraph = (show_min != 0 && show_min != show_max);
734 float lastscaledvalue = 0.0;
735 bool lastscaledvalue_exists = false;
736 for(std::list<Piece>::const_iterator j = m_log.begin();
737 j != m_log.end(); j++)
739 const Piece &piece = *j;
741 bool value_exists = false;
742 Profiler::GraphValues::const_iterator k =
743 piece.values.find(id);
744 if(k != piece.values.end()){
750 lastscaledvalue_exists = false;
753 float scaledvalue = 1.0;
754 if(show_max != show_min)
755 scaledvalue = (value - show_min) / (show_max - show_min);
756 if(scaledvalue == 1.0 && value == 0){
758 lastscaledvalue_exists = false;
762 if(lastscaledvalue_exists){
763 s32 ivalue1 = lastscaledvalue * graph1h;
764 s32 ivalue2 = scaledvalue * graph1h;
765 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
766 v2s32(x, graph1y - ivalue2), meta.color);
768 lastscaledvalue = scaledvalue;
769 lastscaledvalue_exists = true;
771 s32 ivalue = scaledvalue * graph1h;
772 driver->draw2DLine(v2s32(x, graph1y),
773 v2s32(x, graph1y - ivalue), meta.color);
786 IrrlichtDevice *device,
789 std::string playername,
790 std::string password,
791 std::string address, // If "", local server is used
793 std::wstring &error_message,
794 std::string configpath,
795 ChatBackend &chat_backend,
796 const SubgameSpec &gamespec, // Used for local game,
797 bool simple_singleplayer_mode
800 video::IVideoDriver* driver = device->getVideoDriver();
801 scene::ISceneManager* smgr = device->getSceneManager();
803 // Calculate text height using the font
804 u32 text_height = font->getDimension(L"Random test string").Height;
806 v2u32 screensize(0,0);
807 v2u32 last_screensize(0,0);
808 screensize = driver->getScreenSize();
810 const s32 hotbar_itemcount = 8;
811 //const s32 hotbar_imagesize = 36;
812 //const s32 hotbar_imagesize = 64;
813 s32 hotbar_imagesize = 48;
816 Draw "Loading" screen
819 draw_load_screen(L"Loading...", driver, font);
821 // Create texture source
822 IWritableTextureSource *tsrc = createTextureSource(device);
824 // These will be filled by data received from the server
825 // Create item definition manager
826 IWritableItemDefManager *itemdef = createItemDefManager();
827 // Create node definition manager
828 IWritableNodeDefManager *nodedef = createNodeDefManager();
831 ISoundManager *sound = NULL;
832 bool sound_is_dummy = false;
834 infostream<<"Attempting to use OpenAL audio"<<std::endl;
835 sound = createOpenALSoundManager(NULL);
837 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
840 infostream<<"Using dummy audio."<<std::endl;
841 sound = &dummySoundManager;
842 sound_is_dummy = true;
846 sound->loadSound("default_grass_walk", porting::path_share + DIR_DELIM
847 + "sounds" + DIR_DELIM + "default_grass_walk3_mono.ogg");
848 //sound->playSound("default_grass_walk", false, 1.0);
849 //sound->playSoundAt("default_grass_walk", true, 1.0, v3f(0,10,0)*BS);
851 // Add chat log output for errors to be shown in chat
852 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
854 // Create UI for modifying quicktune values
855 QuicktuneShortcutter quicktune;
859 SharedPtr will delete it when it goes out of scope.
861 SharedPtr<Server> server;
863 draw_load_screen(L"Creating server...", driver, font);
864 infostream<<"Creating server"<<std::endl;
865 server = new Server(map_dir, configpath, gamespec,
866 simple_singleplayer_mode);
870 do{ // Client scope (breakable do-while(0))
876 draw_load_screen(L"Creating client...", driver, font);
877 infostream<<"Creating client"<<std::endl;
879 MapDrawControl draw_control;
881 Client client(device, playername.c_str(), password, draw_control,
882 tsrc, itemdef, nodedef, sound);
884 // Client acts as our GameDef
885 IGameDef *gamedef = &client;
887 draw_load_screen(L"Resolving address...", driver, font);
888 Address connect_address(0,0,0,0, port);
891 //connect_address.Resolve("localhost");
892 connect_address.setAddress(127,0,0,1);
894 connect_address.Resolve(address.c_str());
896 catch(ResolveError &e)
898 error_message = L"Couldn't resolve address";
899 errorstream<<wide_to_narrow(error_message)<<std::endl;
900 // Break out of client scope
905 Attempt to connect to the server
908 infostream<<"Connecting to server at ";
909 connect_address.print(&infostream);
910 infostream<<std::endl;
911 client.connect(connect_address);
914 Wait for server to accept connection
916 bool could_connect = false;
917 bool connect_aborted = false;
919 float frametime = 0.033;
920 float time_counter = 0.0;
924 // Update client and server
925 client.step(frametime);
927 server->step(frametime);
930 if(client.connectedAndInitialized()){
931 could_connect = true;
935 if(client.accessDenied()){
936 error_message = L"Access denied. Reason: "
937 +client.accessDeniedReason();
938 errorstream<<wide_to_narrow(error_message)<<std::endl;
941 if(input->wasKeyDown(EscapeKey)){
942 connect_aborted = true;
943 infostream<<"Connect aborted [Escape]"<<std::endl;
948 std::wostringstream ss;
949 ss<<L"Connecting to server... (press Escape to cancel)\n";
950 std::wstring animation = L"/-\\|";
951 ss<<animation[(int)(time_counter/0.2)%4];
952 draw_load_screen(ss.str(), driver, font);
955 sleep_ms(1000*frametime);
956 time_counter += frametime;
959 catch(con::PeerNotFoundException &e)
963 Handle failure to connect
966 if(error_message == L"" && !connect_aborted){
967 error_message = L"Connection failed";
968 errorstream<<wide_to_narrow(error_message)<<std::endl;
970 // Break out of client scope
975 Wait until content has been received
977 bool got_content = false;
978 bool content_aborted = false;
980 float frametime = 0.033;
981 float time_counter = 0.0;
985 // Update client and server
986 client.step(frametime);
988 server->step(frametime);
991 if(client.texturesReceived() &&
992 client.itemdefReceived() &&
993 client.nodedefReceived()){
998 if(!client.connectedAndInitialized()){
999 error_message = L"Client disconnected";
1000 errorstream<<wide_to_narrow(error_message)<<std::endl;
1003 if(input->wasKeyDown(EscapeKey)){
1004 content_aborted = true;
1005 infostream<<"Connect aborted [Escape]"<<std::endl;
1010 std::wostringstream ss;
1011 ss<<L"Waiting content... (press Escape to cancel)\n";
1013 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1014 ss<<L" Item definitions\n";
1015 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1016 ss<<L" Node definitions\n";
1017 //ss<<(client.texturesReceived()?L"[X]":L"[ ]");
1018 ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
1021 draw_load_screen(ss.str(), driver, font);
1024 sleep_ms(1000*frametime);
1025 time_counter += frametime;
1030 if(error_message == L"" && !content_aborted){
1031 error_message = L"Something failed";
1032 errorstream<<wide_to_narrow(error_message)<<std::endl;
1034 // Break out of client scope
1039 After all content has been received:
1040 Update cached textures, meshes and materials
1042 client.afterContentReceived();
1045 Create the camera node
1047 Camera camera(smgr, draw_control, gamedef);
1048 if (!camera.successfullyCreated(error_message))
1051 f32 camera_yaw = 0; // "right/left"
1052 f32 camera_pitch = 0; // "up/down"
1058 Clouds *clouds = NULL;
1059 if(g_settings->getBool("enable_clouds"))
1061 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1069 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1075 FarMesh *farmesh = NULL;
1076 if(g_settings->getBool("enable_farmesh"))
1078 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1082 A copy of the local inventory
1084 Inventory local_inventory(itemdef);
1090 // First line of debug text
1091 gui::IGUIStaticText *guitext = guienv->addStaticText(
1093 core::rect<s32>(5, 5, 795, 5+text_height),
1095 // Second line of debug text
1096 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1098 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1100 // At the middle of the screen
1101 // Object infos are shown in this
1102 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1104 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1107 // Status text (displays info when showing and hiding GUI stuff, etc.)
1108 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1110 core::rect<s32>(0,0,0,0),
1112 guitext_status->setVisible(false);
1114 std::wstring statustext;
1115 float statustext_time = 0;
1118 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1120 core::rect<s32>(0,0,0,0),
1121 //false, false); // Disable word wrap as of now
1123 // Remove stale "recent" chat messages from previous connections
1124 chat_backend.clearRecentChat();
1125 // Chat backend and console
1126 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1128 // Profiler text (size is updated when text is updated)
1129 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1131 core::rect<s32>(0,0,0,0),
1133 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1134 guitext_profiler->setVisible(false);
1137 Some statistics are collected in these
1140 u32 beginscenetime = 0;
1142 u32 endscenetime = 0;
1144 float recent_turn_speed = 0.0;
1146 ProfilerGraph graph;
1147 // Initially clear the profiler
1148 Profiler::GraphValues dummyvalues;
1149 g_profiler->graphGet(dummyvalues);
1151 float nodig_delay_timer = 0.0;
1152 float dig_time = 0.0;
1154 PointedThing pointed_old;
1155 bool digging = false;
1156 bool ldown_for_dig = false;
1158 float damage_flash_timer = 0;
1159 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1161 const float object_hit_delay = 0.2;
1162 float object_hit_delay_timer = 0.0;
1163 float time_from_last_punch = 10;
1165 bool invert_mouse = g_settings->getBool("invert_mouse");
1167 bool respawn_menu_active = false;
1168 bool update_wielded_item_trigger = false;
1170 bool show_hud = true;
1171 bool show_chat = true;
1172 bool force_fog_off = false;
1173 bool disable_camera_update = false;
1174 bool show_debug = g_settings->getBool("show_debug");
1175 bool show_profiler_graph = false;
1176 u32 show_profiler = 0;
1177 u32 show_profiler_max = 3; // Number of pages
1179 float time_of_day = 0;
1180 float time_of_day_smooth = 0;
1186 bool first_loop_after_window_activation = true;
1188 // TODO: Convert the static interval timers to these
1189 // Interval limiter for profiler
1190 IntervalLimiter m_profiler_interval;
1192 // Time is in milliseconds
1193 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1194 // NOTE: So we have to use getTime() and call run()s between them
1195 u32 lasttime = device->getTimer()->getTime();
1199 if(device->run() == false || kill == true)
1202 // Time of frame without fps limit
1206 // not using getRealTime is necessary for wine
1207 u32 time = device->getTimer()->getTime();
1209 busytime_u32 = time - lasttime;
1212 busytime = busytime_u32 / 1000.0;
1215 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1217 // Necessary for device->getTimer()->getTime()
1225 float fps_max = g_settings->getFloat("fps_max");
1226 u32 frametime_min = 1000./fps_max;
1228 if(busytime_u32 < frametime_min)
1230 u32 sleeptime = frametime_min - busytime_u32;
1231 device->sleep(sleeptime);
1232 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1236 // Necessary for device->getTimer()->getTime()
1240 Time difference calculation
1242 f32 dtime; // in seconds
1244 u32 time = device->getTimer()->getTime();
1246 dtime = (time - lasttime) / 1000.0;
1251 g_profiler->graphAdd("mainloop_dtime", dtime);
1255 if(nodig_delay_timer >= 0)
1256 nodig_delay_timer -= dtime;
1257 if(object_hit_delay_timer >= 0)
1258 object_hit_delay_timer -= dtime;
1259 time_from_last_punch += dtime;
1261 g_profiler->add("Elapsed time", dtime);
1262 g_profiler->avg("FPS", 1./dtime);
1265 Time average and jitter calculation
1268 static f32 dtime_avg1 = 0.0;
1269 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1270 f32 dtime_jitter1 = dtime - dtime_avg1;
1272 static f32 dtime_jitter1_max_sample = 0.0;
1273 static f32 dtime_jitter1_max_fraction = 0.0;
1275 static f32 jitter1_max = 0.0;
1276 static f32 counter = 0.0;
1277 if(dtime_jitter1 > jitter1_max)
1278 jitter1_max = dtime_jitter1;
1283 dtime_jitter1_max_sample = jitter1_max;
1284 dtime_jitter1_max_fraction
1285 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1291 Busytime average and jitter calculation
1294 static f32 busytime_avg1 = 0.0;
1295 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1296 f32 busytime_jitter1 = busytime - busytime_avg1;
1298 static f32 busytime_jitter1_max_sample = 0.0;
1299 static f32 busytime_jitter1_min_sample = 0.0;
1301 static f32 jitter1_max = 0.0;
1302 static f32 jitter1_min = 0.0;
1303 static f32 counter = 0.0;
1304 if(busytime_jitter1 > jitter1_max)
1305 jitter1_max = busytime_jitter1;
1306 if(busytime_jitter1 < jitter1_min)
1307 jitter1_min = busytime_jitter1;
1311 busytime_jitter1_max_sample = jitter1_max;
1312 busytime_jitter1_min_sample = jitter1_min;
1319 Handle miscellaneous stuff
1322 if(client.accessDenied())
1324 error_message = L"Access denied. Reason: "
1325 +client.accessDeniedReason();
1326 errorstream<<wide_to_narrow(error_message)<<std::endl;
1330 if(g_gamecallback->disconnect_requested)
1332 g_gamecallback->disconnect_requested = false;
1336 if(g_gamecallback->changepassword_requested)
1338 (new GUIPasswordChange(guienv, guiroot, -1,
1339 &g_menumgr, &client))->drop();
1340 g_gamecallback->changepassword_requested = false;
1344 Process TextureSource's queue
1346 tsrc->processQueue();
1351 last_screensize = screensize;
1352 screensize = driver->getScreenSize();
1353 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1354 //bool screensize_changed = screensize != last_screensize;
1357 if(screensize.Y <= 800)
1358 hotbar_imagesize = 32;
1359 else if(screensize.Y <= 1280)
1360 hotbar_imagesize = 48;
1362 hotbar_imagesize = 64;
1364 // Hilight boxes collected during the loop and displayed
1365 core::list< core::aabbox3d<f32> > hilightboxes;
1368 std::wstring infotext;
1371 Debug info for client
1374 static float counter = 0.0;
1379 client.printDebugInfo(infostream);
1386 float profiler_print_interval =
1387 g_settings->getFloat("profiler_print_interval");
1388 bool print_to_log = true;
1389 if(profiler_print_interval == 0){
1390 print_to_log = false;
1391 profiler_print_interval = 5;
1393 if(m_profiler_interval.step(dtime, profiler_print_interval))
1396 infostream<<"Profiler:"<<std::endl;
1397 g_profiler->print(infostream);
1400 update_profiler_gui(guitext_profiler, font, text_height,
1401 show_profiler, show_profiler_max);
1403 g_profiler->clear();
1407 Direct handling of user input
1410 // Reset input if window not active or some menu is active
1411 if(device->isWindowActive() == false
1412 || noMenuActive() == false
1413 || guienv->hasFocus(gui_chat_console))
1418 // Input handler step() (used by the random input generator)
1422 Launch menus and trigger stuff according to keys
1424 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1426 // drop selected item
1427 IDropAction *a = new IDropAction();
1429 a->from_inv.setCurrentPlayer();
1430 a->from_list = "main";
1431 a->from_i = client.getPlayerItem();
1432 client.inventoryAction(a);
1434 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1436 infostream<<"the_game: "
1437 <<"Launching inventory"<<std::endl;
1439 GUIInventoryMenu *menu =
1440 new GUIInventoryMenu(guienv, guiroot, -1,
1441 &g_menumgr, v2s16(8,7),
1444 InventoryLocation inventoryloc;
1445 inventoryloc.setCurrentPlayer();
1447 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1448 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1449 "list", inventoryloc, "main",
1450 v2s32(0, 3), v2s32(8, 4)));
1451 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1452 "list", inventoryloc, "craft",
1453 v2s32(3, 0), v2s32(3, 3)));
1454 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1455 "list", inventoryloc, "craftpreview",
1456 v2s32(7, 1), v2s32(1, 1)));
1458 menu->setDrawSpec(draw_spec);
1462 else if(input->wasKeyDown(EscapeKey))
1464 infostream<<"the_game: "
1465 <<"Launching pause menu"<<std::endl;
1466 // It will delete itself by itself
1467 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1468 &g_menumgr, simple_singleplayer_mode))->drop();
1470 // Move mouse cursor on top of the disconnect button
1471 if(simple_singleplayer_mode)
1472 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1474 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1476 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1478 TextDest *dest = new TextDestChat(&client);
1480 (new GUITextInputMenu(guienv, guiroot, -1,
1484 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1486 TextDest *dest = new TextDestChat(&client);
1488 (new GUITextInputMenu(guienv, guiroot, -1,
1492 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1494 if (!gui_chat_console->isOpenInhibited())
1496 // Open up to over half of the screen
1497 gui_chat_console->openConsole(0.6);
1498 guienv->setFocus(gui_chat_console);
1501 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1503 if(g_settings->getBool("free_move"))
1505 g_settings->set("free_move","false");
1506 statustext = L"free_move disabled";
1507 statustext_time = 0;
1511 g_settings->set("free_move","true");
1512 statustext = L"free_move enabled";
1513 statustext_time = 0;
1516 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1518 if(g_settings->getBool("fast_move"))
1520 g_settings->set("fast_move","false");
1521 statustext = L"fast_move disabled";
1522 statustext_time = 0;
1526 g_settings->set("fast_move","true");
1527 statustext = L"fast_move enabled";
1528 statustext_time = 0;
1531 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1533 irr::video::IImage* const image = driver->createScreenShot();
1535 irr::c8 filename[256];
1536 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1537 g_settings->get("screenshot_path").c_str(),
1538 device->getTimer()->getRealTime());
1539 if (driver->writeImageToFile(image, filename)) {
1540 std::wstringstream sstr;
1541 sstr<<"Saved screenshot to '"<<filename<<"'";
1542 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1543 statustext = sstr.str();
1544 statustext_time = 0;
1546 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1551 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1553 show_hud = !show_hud;
1555 statustext = L"HUD shown";
1557 statustext = L"HUD hidden";
1558 statustext_time = 0;
1560 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1562 show_chat = !show_chat;
1564 statustext = L"Chat shown";
1566 statustext = L"Chat hidden";
1567 statustext_time = 0;
1569 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1571 force_fog_off = !force_fog_off;
1573 statustext = L"Fog disabled";
1575 statustext = L"Fog enabled";
1576 statustext_time = 0;
1578 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1580 disable_camera_update = !disable_camera_update;
1581 if(disable_camera_update)
1582 statustext = L"Camera update disabled";
1584 statustext = L"Camera update enabled";
1585 statustext_time = 0;
1587 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1589 // Initial / 3x toggle: Chat only
1590 // 1x toggle: Debug text with chat
1591 // 2x toggle: Debug text with profiler graph
1595 show_profiler_graph = false;
1596 statustext = L"Debug info shown";
1597 statustext_time = 0;
1599 else if(show_profiler_graph)
1602 show_profiler_graph = false;
1603 statustext = L"Debug info and profiler graph hidden";
1604 statustext_time = 0;
1608 show_profiler_graph = true;
1609 statustext = L"Profiler graph shown";
1610 statustext_time = 0;
1613 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1615 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1617 // FIXME: This updates the profiler with incomplete values
1618 update_profiler_gui(guitext_profiler, font, text_height,
1619 show_profiler, show_profiler_max);
1621 if(show_profiler != 0)
1623 std::wstringstream sstr;
1624 sstr<<"Profiler shown (page "<<show_profiler
1625 <<" of "<<show_profiler_max<<")";
1626 statustext = sstr.str();
1627 statustext_time = 0;
1631 statustext = L"Profiler hidden";
1632 statustext_time = 0;
1635 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1637 s16 range = g_settings->getS16("viewing_range_nodes_min");
1638 s16 range_new = range + 10;
1639 g_settings->set("viewing_range_nodes_min", itos(range_new));
1640 statustext = narrow_to_wide(
1641 "Minimum viewing range changed to "
1643 statustext_time = 0;
1645 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1647 s16 range = g_settings->getS16("viewing_range_nodes_min");
1648 s16 range_new = range - 10;
1651 g_settings->set("viewing_range_nodes_min",
1653 statustext = narrow_to_wide(
1654 "Minimum viewing range changed to "
1656 statustext_time = 0;
1659 // Handle QuicktuneShortcutter
1660 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1662 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1664 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1666 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1669 std::string msg = quicktune.getMessage();
1671 statustext = narrow_to_wide(msg);
1672 statustext_time = 0;
1676 // Item selection with mouse wheel
1677 u16 new_playeritem = client.getPlayerItem();
1679 s32 wheel = input->getMouseWheel();
1680 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1681 hotbar_itemcount-1);
1685 if(new_playeritem < max_item)
1692 if(new_playeritem > 0)
1695 new_playeritem = max_item;
1700 for(u16 i=0; i<10; i++)
1702 const KeyPress *kp = NumberKey + (i + 1) % 10;
1703 if(input->wasKeyDown(*kp))
1705 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1709 infostream<<"Selected item: "
1710 <<new_playeritem<<std::endl;
1715 // Viewing range selection
1716 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1718 draw_control.range_all = !draw_control.range_all;
1719 if(draw_control.range_all)
1721 infostream<<"Enabled full viewing range"<<std::endl;
1722 statustext = L"Enabled full viewing range";
1723 statustext_time = 0;
1727 infostream<<"Disabled full viewing range"<<std::endl;
1728 statustext = L"Disabled full viewing range";
1729 statustext_time = 0;
1733 // Print debug stacks
1734 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1736 dstream<<"-----------------------------------------"
1738 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1739 dstream<<"-----------------------------------------"
1741 debug_stacks_print();
1745 Mouse and camera control
1746 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1749 float turn_amount = 0;
1750 if((device->isWindowActive() && noMenuActive()) || random_input)
1754 // Mac OSX gets upset if this is set every frame
1755 if(device->getCursorControl()->isVisible())
1756 device->getCursorControl()->setVisible(false);
1759 if(first_loop_after_window_activation){
1760 //infostream<<"window active, first loop"<<std::endl;
1761 first_loop_after_window_activation = false;
1764 s32 dx = input->getMousePos().X - displaycenter.X;
1765 s32 dy = input->getMousePos().Y - displaycenter.Y;
1768 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1770 /*const float keyspeed = 500;
1771 if(input->isKeyDown(irr::KEY_UP))
1772 dy -= dtime * keyspeed;
1773 if(input->isKeyDown(irr::KEY_DOWN))
1774 dy += dtime * keyspeed;
1775 if(input->isKeyDown(irr::KEY_LEFT))
1776 dx -= dtime * keyspeed;
1777 if(input->isKeyDown(irr::KEY_RIGHT))
1778 dx += dtime * keyspeed;*/
1782 camera_pitch += dy*d;
1783 if(camera_pitch < -89.5) camera_pitch = -89.5;
1784 if(camera_pitch > 89.5) camera_pitch = 89.5;
1786 turn_amount = v2f(dx, dy).getLength() * d;
1788 input->setMousePos(displaycenter.X, displaycenter.Y);
1791 // Mac OSX gets upset if this is set every frame
1792 if(device->getCursorControl()->isVisible() == false)
1793 device->getCursorControl()->setVisible(true);
1795 //infostream<<"window inactive"<<std::endl;
1796 first_loop_after_window_activation = true;
1798 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1799 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1802 Player speed control
1814 PlayerControl control(
1815 input->isKeyDown(getKeySetting("keymap_forward")),
1816 input->isKeyDown(getKeySetting("keymap_backward")),
1817 input->isKeyDown(getKeySetting("keymap_left")),
1818 input->isKeyDown(getKeySetting("keymap_right")),
1819 input->isKeyDown(getKeySetting("keymap_jump")),
1820 input->isKeyDown(getKeySetting("keymap_special1")),
1821 input->isKeyDown(getKeySetting("keymap_sneak")),
1825 client.setPlayerControl(control);
1834 //TimeTaker timer("server->step(dtime)");
1835 server->step(dtime);
1843 //TimeTaker timer("client.step(dtime)");
1845 //client.step(dtime_avg1);
1849 // Read client events
1852 ClientEvent event = client.getClientEvent();
1853 if(event.type == CE_NONE)
1857 else if(event.type == CE_PLAYER_DAMAGE)
1859 //u16 damage = event.player_damage.amount;
1860 //infostream<<"Player damage: "<<damage<<std::endl;
1861 damage_flash_timer = 0.05;
1862 if(event.player_damage.amount >= 2){
1863 damage_flash_timer += 0.05 * event.player_damage.amount;
1866 else if(event.type == CE_PLAYER_FORCE_MOVE)
1868 camera_yaw = event.player_force_move.yaw;
1869 camera_pitch = event.player_force_move.pitch;
1871 else if(event.type == CE_DEATHSCREEN)
1873 if(respawn_menu_active)
1876 /*bool set_camera_point_target =
1877 event.deathscreen.set_camera_point_target;
1878 v3f camera_point_target;
1879 camera_point_target.X = event.deathscreen.camera_point_target_x;
1880 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1881 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1882 MainRespawnInitiator *respawner =
1883 new MainRespawnInitiator(
1884 &respawn_menu_active, &client);
1885 GUIDeathScreen *menu =
1886 new GUIDeathScreen(guienv, guiroot, -1,
1887 &g_menumgr, respawner);
1890 chat_backend.addMessage(L"", L"You died.");
1892 /* Handle visualization */
1894 damage_flash_timer = 0;
1896 /*LocalPlayer* player = client.getLocalPlayer();
1897 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1898 camera.update(player, busytime, screensize);*/
1900 else if(event.type == CE_TEXTURES_UPDATED)
1902 update_wielded_item_trigger = true;
1907 //TimeTaker //timer2("//timer2");
1910 For interaction purposes, get info about the held item
1912 - Is it a usable item?
1913 - Can it point to liquids?
1915 ItemStack playeritem;
1916 bool playeritem_usable = false;
1917 bool playeritem_liquids_pointable = false;
1919 InventoryList *mlist = local_inventory.getList("main");
1922 playeritem = mlist->getItem(client.getPlayerItem());
1923 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1924 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1927 ToolCapabilities playeritem_toolcap =
1928 playeritem.getToolCapabilities(itemdef);
1934 LocalPlayer* player = client.getEnv().getLocalPlayer();
1935 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1936 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1937 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1938 camera.update(player, busytime, screensize, tool_reload_ratio);
1941 v3f player_position = player->getPosition();
1942 v3f camera_position = camera.getPosition();
1943 v3f camera_direction = camera.getDirection();
1944 f32 camera_fov = camera.getFovMax();
1946 if(!disable_camera_update){
1947 client.getEnv().getClientMap().updateCamera(camera_position,
1948 camera_direction, camera_fov);
1951 // Update sound listener
1952 sound->updateListener(camera.getCameraNode()->getPosition(),
1953 v3f(0,0,0), // velocity
1954 camera.getCameraNode()->getTarget(),
1955 camera.getCameraNode()->getUpVector());
1958 Calculate what block is the crosshair pointing to
1961 //u32 t1 = device->getTimer()->getRealTime();
1963 f32 d = 4; // max. distance
1964 core::line3d<f32> shootline(camera_position,
1965 camera_position + camera_direction * BS * (d+1));
1967 core::aabbox3d<f32> hilightbox;
1968 bool should_show_hilightbox = false;
1969 ClientActiveObject *selected_object = NULL;
1971 PointedThing pointed = getPointedThing(
1973 &client, player_position, camera_direction,
1974 camera_position, shootline, d,
1975 playeritem_liquids_pointable, !ldown_for_dig,
1977 hilightbox, should_show_hilightbox,
1980 if(pointed != pointed_old)
1982 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1983 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1989 if(should_show_hilightbox)
1990 hilightboxes.push_back(hilightbox);
1994 - releasing left mouse button
1995 - pointing away from node
1999 if(input->getLeftReleased())
2001 infostream<<"Left button released"
2002 <<" (stopped digging)"<<std::endl;
2005 else if(pointed != pointed_old)
2007 if (pointed.type == POINTEDTHING_NODE
2008 && pointed_old.type == POINTEDTHING_NODE
2009 && pointed.node_undersurface == pointed_old.node_undersurface)
2011 // Still pointing to the same node,
2012 // but a different face. Don't reset.
2016 infostream<<"Pointing away from node"
2017 <<" (stopped digging)"<<std::endl;
2023 client.interact(1, pointed_old);
2024 client.setCrack(-1, v3s16(0,0,0));
2028 if(!digging && ldown_for_dig && !input->getLeftState())
2030 ldown_for_dig = false;
2033 bool left_punch = false;
2035 if(playeritem_usable && input->getLeftState())
2037 if(input->getLeftClicked())
2038 client.interact(4, pointed);
2040 else if(pointed.type == POINTEDTHING_NODE)
2042 v3s16 nodepos = pointed.node_undersurface;
2043 v3s16 neighbourpos = pointed.node_abovesurface;
2046 Check information text of node
2049 ClientMap &map = client.getEnv().getClientMap();
2050 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2052 infotext = narrow_to_wide(meta->infoText());
2054 MapNode n = map.getNode(nodepos);
2055 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2056 infotext = L"Unknown node: ";
2057 infotext += narrow_to_wide(nodedef->get(n).name);
2065 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2069 infostream<<"Started digging"<<std::endl;
2070 client.interact(0, pointed);
2072 ldown_for_dig = true;
2074 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2076 // Get digging parameters
2077 DigParams params = getDigParams(nodedef->get(n).groups,
2078 &playeritem_toolcap);
2079 // If can't dig, try hand
2080 if(!params.diggable){
2081 const ItemDefinition &hand = itemdef->get("");
2082 const ToolCapabilities *tp = hand.tool_capabilities;
2084 params = getDigParams(nodedef->get(n).groups, tp);
2087 float dig_time_complete = 0.0;
2089 if(params.diggable == false)
2091 // I guess nobody will wait for this long
2092 dig_time_complete = 10000000.0;
2096 dig_time_complete = params.time;
2099 if(dig_time_complete >= 0.001)
2101 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2102 * dig_time/dig_time_complete);
2104 // This is for torches
2107 dig_index = CRACK_ANIMATION_LENGTH;
2110 // Don't show cracks if not diggable
2111 if(dig_time_complete >= 100000.0)
2114 else if(dig_index < CRACK_ANIMATION_LENGTH)
2116 //TimeTaker timer("client.setTempMod");
2117 //infostream<<"dig_index="<<dig_index<<std::endl;
2118 client.setCrack(dig_index, nodepos);
2122 infostream<<"Digging completed"<<std::endl;
2123 client.interact(2, pointed);
2124 client.setCrack(-1, v3s16(0,0,0));
2125 client.removeNode(nodepos);
2130 nodig_delay_timer = dig_time_complete
2131 / (float)CRACK_ANIMATION_LENGTH;
2133 // We don't want a corresponding delay to
2134 // very time consuming nodes
2135 if(nodig_delay_timer > 0.5)
2137 nodig_delay_timer = 0.5;
2139 // We want a slight delay to very little
2140 // time consuming nodes
2141 float mindelay = 0.15;
2142 if(nodig_delay_timer < mindelay)
2144 nodig_delay_timer = mindelay;
2150 camera.setDigging(0); // left click animation
2153 if(input->getRightClicked())
2155 infostream<<"Ground right-clicked"<<std::endl;
2157 // If metadata provides an inventory view, activate it
2158 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2160 infostream<<"Launching custom inventory view"<<std::endl;
2162 InventoryLocation inventoryloc;
2163 inventoryloc.setNodeMeta(nodepos);
2170 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2172 GUIInventoryMenu::makeDrawSpecArrayFromString(
2174 meta->getInventoryDrawSpecString(),
2177 GUIInventoryMenu *menu =
2178 new GUIInventoryMenu(guienv, guiroot, -1,
2179 &g_menumgr, invsize,
2181 menu->setDrawSpec(draw_spec);
2184 // If metadata provides text input, activate text input
2185 else if(meta && meta->allowsTextInput() && !random_input)
2187 infostream<<"Launching metadata text input"<<std::endl;
2189 // Get a new text for it
2191 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2193 std::wstring wtext = narrow_to_wide(meta->getText());
2195 (new GUITextInputMenu(guienv, guiroot, -1,
2199 // Otherwise report right click to server
2202 client.interact(3, pointed);
2203 camera.setDigging(1); // right click animation
2207 else if(pointed.type == POINTEDTHING_OBJECT)
2209 infotext = narrow_to_wide(selected_object->infoText());
2211 if(infotext == L"" && show_debug){
2212 infotext = narrow_to_wide(selected_object->debugInfoText());
2215 //if(input->getLeftClicked())
2216 if(input->getLeftState())
2218 bool do_punch = false;
2219 bool do_punch_damage = false;
2220 if(object_hit_delay_timer <= 0.0){
2222 do_punch_damage = true;
2223 object_hit_delay_timer = object_hit_delay;
2225 if(input->getLeftClicked()){
2229 infostream<<"Left-clicked object"<<std::endl;
2232 if(do_punch_damage){
2233 // Report direct punch
2234 v3f objpos = selected_object->getPosition();
2235 v3f dir = (objpos - player_position).normalize();
2237 bool disable_send = selected_object->directReportPunch(
2238 dir, &playeritem, time_from_last_punch);
2239 time_from_last_punch = 0;
2241 client.interact(0, pointed);
2244 else if(input->getRightClicked())
2246 infostream<<"Right-clicked object"<<std::endl;
2247 client.interact(3, pointed); // place
2250 else if(input->getLeftState())
2252 // When button is held down in air, show continuous animation
2256 pointed_old = pointed;
2258 if(left_punch || input->getLeftClicked())
2260 camera.setDigging(0); // left click animation
2263 input->resetLeftClicked();
2264 input->resetRightClicked();
2266 input->resetLeftReleased();
2267 input->resetRightReleased();
2270 Calculate stuff for drawing
2280 fog_range = BS*farmesh_range;
2284 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2286 if(draw_control.range_all)
2287 fog_range = 100000*BS;
2291 Calculate general brightness
2293 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2294 float time_brightness = (float)decode_light(
2295 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2296 float direct_brightness = 0;
2297 bool sunlight_seen = false;
2298 if(g_settings->getBool("free_move")){
2299 direct_brightness = time_brightness;
2300 sunlight_seen = true;
2302 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2303 float old_brightness = sky->getBrightness();
2304 direct_brightness = (float)client.getEnv().getClientMap()
2305 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2306 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2310 time_of_day = client.getEnv().getTimeOfDayF();
2312 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2313 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2314 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2315 time_of_day_smooth = time_of_day;
2317 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2318 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2319 + (time_of_day+1.0) * todsm;
2321 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2322 + time_of_day * todsm;
2324 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2327 float brightness = sky->getBrightness();
2328 video::SColor bgcolor = sky->getBgColor();
2329 video::SColor skycolor = sky->getSkyColor();
2335 if(sky->getCloudsVisible()){
2336 clouds->setVisible(true);
2337 clouds->step(dtime);
2338 clouds->update(v2f(player_position.X, player_position.Z),
2339 sky->getCloudColor());
2341 clouds->setVisible(false);
2350 farmesh_range = draw_control.wanted_range * 10;
2351 if(draw_control.range_all && farmesh_range < 500)
2352 farmesh_range = 500;
2353 if(farmesh_range > 1000)
2354 farmesh_range = 1000;
2356 farmesh->step(dtime);
2357 farmesh->update(v2f(player_position.X, player_position.Z),
2358 brightness, farmesh_range);
2365 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2369 video::EFT_FOG_LINEAR,
2381 video::EFT_FOG_LINEAR,
2391 Update gui stuff (0ms)
2394 //TimeTaker guiupdatetimer("Gui updating");
2396 const char program_name_and_version[] =
2397 "Minetest-c55 " VERSION_STRING;
2401 static float drawtime_avg = 0;
2402 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2403 /*static float beginscenetime_avg = 0;
2404 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2405 static float scenetime_avg = 0;
2406 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2407 static float endscenetime_avg = 0;
2408 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2411 snprintf(temptext, 300, "%s ("
2414 " drawtime=%.0f, dtime_jitter = % .1f %%"
2415 ", v_range = %.1f, RTT = %.3f",
2416 program_name_and_version,
2417 draw_control.range_all,
2419 dtime_jitter1_max_fraction * 100.0,
2420 draw_control.wanted_range,
2424 guitext->setText(narrow_to_wide(temptext).c_str());
2425 guitext->setVisible(true);
2427 else if(show_hud || show_chat)
2429 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2430 guitext->setVisible(true);
2434 guitext->setVisible(false);
2440 snprintf(temptext, 300,
2441 "(% .1f, % .1f, % .1f)"
2443 player_position.X/BS,
2444 player_position.Y/BS,
2445 player_position.Z/BS,
2446 wrapDegrees_0_360(camera_yaw));
2448 guitext2->setText(narrow_to_wide(temptext).c_str());
2449 guitext2->setVisible(true);
2453 guitext2->setVisible(false);
2457 guitext_info->setText(infotext.c_str());
2458 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2462 float statustext_time_max = 1.5;
2463 if(!statustext.empty())
2465 statustext_time += dtime;
2466 if(statustext_time >= statustext_time_max)
2469 statustext_time = 0;
2472 guitext_status->setText(statustext.c_str());
2473 guitext_status->setVisible(!statustext.empty());
2475 if(!statustext.empty())
2477 s32 status_y = screensize.Y - 130;
2478 core::rect<s32> rect(
2480 status_y - guitext_status->getTextHeight(),
2484 guitext_status->setRelativePosition(rect);
2487 video::SColor initial_color(255,0,0,0);
2488 if(guienv->getSkin())
2489 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2490 video::SColor final_color = initial_color;
2491 final_color.setAlpha(0);
2492 video::SColor fade_color =
2493 initial_color.getInterpolated_quadratic(
2496 pow(statustext_time / (float)statustext_time_max, 2.0f));
2497 guitext_status->setOverrideColor(fade_color);
2498 guitext_status->enableOverrideColor(true);
2503 Get chat messages from client
2506 // Get new messages from error log buffer
2507 while(!chat_log_error_buf.empty())
2509 chat_backend.addMessage(L"", narrow_to_wide(
2510 chat_log_error_buf.get()));
2512 // Get new messages from client
2513 std::wstring message;
2514 while(client.getChatMessage(message))
2516 chat_backend.addUnparsedMessage(message);
2518 // Remove old messages
2519 chat_backend.step(dtime);
2521 // Display all messages in a static text element
2522 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2523 std::wstring recent_chat = chat_backend.getRecentChat();
2524 guitext_chat->setText(recent_chat.c_str());
2526 // Update gui element size and position
2527 s32 chat_y = 5+(text_height+5);
2529 chat_y += (text_height+5);
2530 core::rect<s32> rect(
2534 chat_y + guitext_chat->getTextHeight()
2536 guitext_chat->setRelativePosition(rect);
2538 // Don't show chat if disabled or empty or profiler is enabled
2539 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2547 if(client.getPlayerItem() != new_playeritem)
2549 client.selectPlayerItem(new_playeritem);
2551 if(client.getLocalInventoryUpdated())
2553 //infostream<<"Updating local inventory"<<std::endl;
2554 client.getLocalInventory(local_inventory);
2556 update_wielded_item_trigger = true;
2558 if(update_wielded_item_trigger)
2560 update_wielded_item_trigger = false;
2561 // Update wielded tool
2562 InventoryList *mlist = local_inventory.getList("main");
2565 item = mlist->getItem(client.getPlayerItem());
2573 TimeTaker tt_draw("mainloop: draw");
2577 TimeTaker timer("beginScene");
2578 //driver->beginScene(false, true, bgcolor);
2579 //driver->beginScene(true, true, bgcolor);
2580 driver->beginScene(true, true, skycolor);
2581 beginscenetime = timer.stop(true);
2586 //infostream<<"smgr->drawAll()"<<std::endl;
2588 TimeTaker timer("smgr");
2590 scenetime = timer.stop(true);
2594 //TimeTaker timer9("auxiliary drawings");
2598 //TimeTaker //timer10("//timer10");
2604 driver->setMaterial(m);
2606 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2610 for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2611 i != hilightboxes.end(); i++)
2613 /*infostream<<"hilightbox min="
2614 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2616 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2618 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2627 // Warning: This clears the Z buffer.
2628 camera.drawWieldedTool();
2635 client.getEnv().getClientMap().renderPostFx();
2641 if(show_profiler_graph)
2643 graph.draw(10, screensize.Y - 10, driver, font);
2651 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2652 displaycenter + core::vector2d<s32>(10,0),
2653 video::SColor(255,255,255,255));
2654 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2655 displaycenter + core::vector2d<s32>(0,10),
2656 video::SColor(255,255,255,255));
2662 //TimeTaker //timer11("//timer11");
2675 draw_hotbar(driver, font, gamedef,
2676 v2s32(displaycenter.X, screensize.Y),
2677 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2678 client.getHP(), client.getPlayerItem());
2684 if(damage_flash_timer > 0.0)
2686 damage_flash_timer -= dtime;
2688 video::SColor color(128,255,0,0);
2689 driver->draw2DRectangle(color,
2690 core::rect<s32>(0,0,screensize.X,screensize.Y),
2698 TimeTaker timer("endScene");
2700 endscenetime = timer.stop(true);
2703 drawtime = tt_draw.stop(true);
2704 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2710 static s16 lastFPS = 0;
2711 //u16 fps = driver->getFPS();
2712 u16 fps = (1.0/dtime_avg1);
2716 core::stringw str = L"Minetest [";
2717 str += driver->getName();
2721 device->setWindowCaption(str.c_str());
2726 Log times and stuff for visualization
2728 Profiler::GraphValues values;
2729 g_profiler->graphGet(values);
2738 if(gui_chat_console)
2739 gui_chat_console->drop();
2742 Draw a "shutting down" screen, which will be shown while the map
2743 generator and other stuff quits
2746 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2747 draw_load_screen(L"Shutting down stuff...", driver, font);
2748 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2751 gui_shuttingdowntext->remove();*/
2754 chat_backend.addMessage(L"", L"# Disconnected.");
2755 chat_backend.addMessage(L"", L"");
2757 // Client scope (client is destructed before destructing *def and tsrc)