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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "irrlichttypes_extrabloated.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"
62 #include "event_manager.h"
64 #include "util/directiontables.h"
70 struct TextDestChat : public TextDest
72 TextDestChat(Client *client)
76 void gotText(std::wstring text)
78 m_client->typeChatMessage(text);
84 struct TextDestNodeMetadata : public TextDest
86 TextDestNodeMetadata(v3s16 p, Client *client)
91 void gotText(std::wstring text)
93 std::string ntext = wide_to_narrow(text);
94 infostream<<"Changing text of a sign node: "
96 std::map<std::string, std::string> fields;
97 fields["text"] = ntext;
98 m_client->sendNodemetaFields(m_p, "", fields);
105 /* Respawn menu callback */
107 class MainRespawnInitiator: public IRespawnInitiator
110 MainRespawnInitiator(bool *active, Client *client):
111 m_active(active), m_client(client)
118 m_client->sendRespawn();
125 /* Form update callback */
127 class NodeMetadataFormSource: public IFormSource
130 NodeMetadataFormSource(ClientMap *map, v3s16 p):
135 std::string getForm()
137 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
140 return meta->getString("formspec");
150 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
152 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
153 Inventory *inventory, s32 halfheartcount, u16 playeritem)
155 InventoryList *mainlist = inventory->getList("main");
158 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
162 s32 padding = imgsize/12;
163 //s32 height = imgsize + padding*2;
164 s32 width = itemcount*(imgsize+padding*2);
166 // Position of upper left corner of bar
167 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
169 // Draw background color
170 /*core::rect<s32> barrect(0,0,width,height);
172 video::SColor bgcolor(255,128,128,128);
173 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
175 core::rect<s32> imgrect(0,0,imgsize,imgsize);
177 for(s32 i=0; i<itemcount; i++)
179 const ItemStack &item = mainlist->getItem(i);
181 core::rect<s32> rect = imgrect + pos
182 + v2s32(padding+i*(imgsize+padding*2), padding);
186 video::SColor c_outside(255,255,0,0);
187 //video::SColor c_outside(255,0,0,0);
188 //video::SColor c_inside(255,192,192,192);
189 s32 x1 = rect.UpperLeftCorner.X;
190 s32 y1 = rect.UpperLeftCorner.Y;
191 s32 x2 = rect.LowerRightCorner.X;
192 s32 y2 = rect.LowerRightCorner.Y;
193 // Black base borders
194 driver->draw2DRectangle(c_outside,
196 v2s32(x1 - padding, y1 - padding),
197 v2s32(x2 + padding, y1)
199 driver->draw2DRectangle(c_outside,
201 v2s32(x1 - padding, y2),
202 v2s32(x2 + padding, y2 + padding)
204 driver->draw2DRectangle(c_outside,
206 v2s32(x1 - padding, y1),
209 driver->draw2DRectangle(c_outside,
212 v2s32(x2 + padding, y2)
214 /*// Light inside borders
215 driver->draw2DRectangle(c_inside,
217 v2s32(x1 - padding/2, y1 - padding/2),
218 v2s32(x2 + padding/2, y1)
220 driver->draw2DRectangle(c_inside,
222 v2s32(x1 - padding/2, y2),
223 v2s32(x2 + padding/2, y2 + padding/2)
225 driver->draw2DRectangle(c_inside,
227 v2s32(x1 - padding/2, y1),
230 driver->draw2DRectangle(c_inside,
233 v2s32(x2 + padding/2, y2)
238 video::SColor bgcolor2(128,0,0,0);
239 driver->draw2DRectangle(bgcolor2, rect, NULL);
240 drawItemStack(driver, font, item, rect, NULL, gamedef);
246 video::ITexture *heart_texture =
247 gamedef->getTextureSource()->getTextureRaw("heart.png");
250 v2s32 p = pos + v2s32(0, -20);
251 for(s32 i=0; i<halfheartcount/2; i++)
253 const video::SColor color(255,255,255,255);
254 const video::SColor colors[] = {color,color,color,color};
255 core::rect<s32> rect(0,0,16,16);
257 driver->draw2DImage(heart_texture, rect,
258 core::rect<s32>(core::position2d<s32>(0,0),
259 core::dimension2di(heart_texture->getOriginalSize())),
263 if(halfheartcount % 2 == 1)
265 const video::SColor color(255,255,255,255);
266 const video::SColor colors[] = {color,color,color,color};
267 core::rect<s32> rect(0,0,16/2,16);
269 core::dimension2di srcd(heart_texture->getOriginalSize());
271 driver->draw2DImage(heart_texture, rect,
272 core::rect<s32>(core::position2d<s32>(0,0), srcd),
280 Check if a node is pointable
282 inline bool isPointableNode(const MapNode& n,
283 Client *client, bool liquids_pointable)
285 const ContentFeatures &features = client->getNodeDefManager()->get(n);
286 return features.pointable ||
287 (liquids_pointable && features.isLiquid());
291 Find what the player is pointing at
293 PointedThing getPointedThing(Client *client, v3f player_position,
294 v3f camera_direction, v3f camera_position,
295 core::line3d<f32> shootline, f32 d,
296 bool liquids_pointable,
297 bool look_for_object,
298 std::vector<aabb3f> &hilightboxes,
299 ClientActiveObject *&selected_object)
303 hilightboxes.clear();
304 selected_object = NULL;
306 INodeDefManager *nodedef = client->getNodeDefManager();
307 ClientMap &map = client->getEnv().getClientMap();
309 // First try to find a pointed at active object
312 selected_object = client->getSelectedActiveObject(d*BS,
313 camera_position, shootline);
315 if(selected_object != NULL)
317 if(selected_object->doShowSelectionBox())
319 aabb3f *selection_box = selected_object->getSelectionBox();
320 // Box should exist because object was
321 // returned in the first place
322 assert(selection_box);
324 v3f pos = selected_object->getPosition();
325 hilightboxes.push_back(aabb3f(
326 selection_box->MinEdge + pos,
327 selection_box->MaxEdge + pos));
331 result.type = POINTEDTHING_OBJECT;
332 result.object_id = selected_object->getId();
337 // That didn't work, try to find a pointed at node
339 f32 mindistance = BS * 1001;
341 v3s16 pos_i = floatToInt(player_position, BS);
343 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
347 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
348 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
349 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
350 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
351 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
352 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
354 for(s16 y = ystart; y <= yend; y++)
355 for(s16 z = zstart; z <= zend; z++)
356 for(s16 x = xstart; x <= xend; x++)
361 n = map.getNode(v3s16(x,y,z));
363 catch(InvalidPositionException &e)
367 if(!isPointableNode(n, client, liquids_pointable))
370 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
373 v3f npf = intToFloat(np, BS);
375 for(std::vector<aabb3f>::const_iterator
377 i != boxes.end(); i++)
383 for(u16 j=0; j<6; j++)
385 v3s16 facedir = g_6dirs[j];
386 aabb3f facebox = box;
390 facebox.MinEdge.X = facebox.MaxEdge.X-d;
391 else if(facedir.X < 0)
392 facebox.MaxEdge.X = facebox.MinEdge.X+d;
393 else if(facedir.Y > 0)
394 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
395 else if(facedir.Y < 0)
396 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
397 else if(facedir.Z > 0)
398 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
399 else if(facedir.Z < 0)
400 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
402 v3f centerpoint = facebox.getCenter();
403 f32 distance = (centerpoint - camera_position).getLength();
404 if(distance >= mindistance)
406 if(!facebox.intersectsWithLine(shootline))
409 v3s16 np_above = np + facedir;
411 result.type = POINTEDTHING_NODE;
412 result.node_undersurface = np;
413 result.node_abovesurface = np_above;
414 mindistance = distance;
416 hilightboxes.clear();
417 for(std::vector<aabb3f>::const_iterator
419 i2 != boxes.end(); i2++)
422 box.MinEdge += npf + v3f(-d,-d,-d);
423 box.MaxEdge += npf + v3f(d,d,d);
424 hilightboxes.push_back(box);
434 Draws a screen with a single text on it.
435 Text will be removed when the screen is drawn the next time.
437 /*gui::IGUIStaticText **/
438 void draw_load_screen(const std::wstring &text,
439 video::IVideoDriver* driver, gui::IGUIFont* font)
441 v2u32 screensize = driver->getScreenSize();
442 const wchar_t *loadingtext = text.c_str();
443 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
444 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
445 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
446 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
448 gui::IGUIStaticText *guitext = guienv->addStaticText(
449 loadingtext, textrect, false, false);
450 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
452 driver->beginScene(true, true, video::SColor(255,0,0,0));
461 /* Profiler display */
463 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
464 gui::IGUIFont *font, u32 text_height,
465 u32 show_profiler, u32 show_profiler_max)
467 if(show_profiler == 0)
469 guitext_profiler->setVisible(false);
474 std::ostringstream os(std::ios_base::binary);
475 g_profiler->printPage(os, show_profiler, show_profiler_max);
476 std::wstring text = narrow_to_wide(os.str());
477 guitext_profiler->setText(text.c_str());
478 guitext_profiler->setVisible(true);
480 s32 w = font->getDimension(text.c_str()).Width;
483 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
484 8+(text_height+5)*2 +
485 font->getDimension(text.c_str()).Height);
486 guitext_profiler->setRelativePosition(rect);
487 guitext_profiler->setVisible(true);
495 Profiler::GraphValues values;
501 Meta(float initial=0, video::SColor color=
502 video::SColor(255,255,255,255)):
508 std::list<Piece> m_log;
516 void put(const Profiler::GraphValues &values)
519 piece.values = values;
520 m_log.push_back(piece);
521 while(m_log.size() > m_log_max_size)
522 m_log.erase(m_log.begin());
525 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
526 gui::IGUIFont* font) const
528 std::map<std::string, Meta> m_meta;
529 for(std::list<Piece>::const_iterator k = m_log.begin();
530 k != m_log.end(); k++)
532 const Piece &piece = *k;
533 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
534 i != piece.values.end(); i++){
535 const std::string &id = i->first;
536 const float &value = i->second;
537 std::map<std::string, Meta>::iterator j =
539 if(j == m_meta.end()){
540 m_meta[id] = Meta(value);
543 if(value < j->second.min)
544 j->second.min = value;
545 if(value > j->second.max)
546 j->second.max = value;
551 static const video::SColor usable_colors[] = {
552 video::SColor(255,255,100,100),
553 video::SColor(255,90,225,90),
554 video::SColor(255,100,100,255),
555 video::SColor(255,255,150,50),
556 video::SColor(255,220,220,100)
558 static const u32 usable_colors_count =
559 sizeof(usable_colors) / sizeof(*usable_colors);
560 u32 next_color_i = 0;
561 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
562 i != m_meta.end(); i++){
563 Meta &meta = i->second;
564 video::SColor color(255,200,200,200);
565 if(next_color_i < usable_colors_count)
566 color = usable_colors[next_color_i++];
571 s32 textx = x_left + m_log_max_size + 15;
572 s32 textx2 = textx + 200 - 15;
576 u32 num_graphs = m_meta.size();
577 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
579 video::SColor bgcolor(120,0,0,0);
580 driver->draw2DRectangle(bgcolor, rect, NULL);
584 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
585 i != m_meta.end(); i++){
586 const std::string &id = i->first;
587 const Meta &meta = i->second;
589 s32 y = y_bottom - meta_i * 50;
590 float show_min = meta.min;
591 float show_max = meta.max;
592 if(show_min >= -0.0001 && show_max >= -0.0001){
593 if(show_min <= show_max * 0.5)
598 snprintf(buf, 10, "%.3g", show_max);
599 font->draw(narrow_to_wide(buf).c_str(),
600 core::rect<s32>(textx, y - graphh,
601 textx2, y - graphh + texth),
603 snprintf(buf, 10, "%.3g", show_min);
604 font->draw(narrow_to_wide(buf).c_str(),
605 core::rect<s32>(textx, y - texth,
608 font->draw(narrow_to_wide(id).c_str(),
609 core::rect<s32>(textx, y - graphh/2 - texth/2,
610 textx2, y - graphh/2 + texth/2),
613 s32 graph1h = graphh;
614 bool relativegraph = (show_min != 0 && show_min != show_max);
615 float lastscaledvalue = 0.0;
616 bool lastscaledvalue_exists = false;
617 for(std::list<Piece>::const_iterator j = m_log.begin();
618 j != m_log.end(); j++)
620 const Piece &piece = *j;
622 bool value_exists = false;
623 Profiler::GraphValues::const_iterator k =
624 piece.values.find(id);
625 if(k != piece.values.end()){
631 lastscaledvalue_exists = false;
634 float scaledvalue = 1.0;
635 if(show_max != show_min)
636 scaledvalue = (value - show_min) / (show_max - show_min);
637 if(scaledvalue == 1.0 && value == 0){
639 lastscaledvalue_exists = false;
643 if(lastscaledvalue_exists){
644 s32 ivalue1 = lastscaledvalue * graph1h;
645 s32 ivalue2 = scaledvalue * graph1h;
646 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
647 v2s32(x, graph1y - ivalue2), meta.color);
649 lastscaledvalue = scaledvalue;
650 lastscaledvalue_exists = true;
652 s32 ivalue = scaledvalue * graph1h;
653 driver->draw2DLine(v2s32(x, graph1y),
654 v2s32(x, graph1y - ivalue), meta.color);
663 class NodeDugEvent: public MtEvent
669 NodeDugEvent(v3s16 p, MapNode n):
673 const char* getType() const
679 ISoundManager *m_sound;
680 INodeDefManager *m_ndef;
682 float m_player_step_timer;
684 SimpleSoundSpec m_player_step_sound;
685 SimpleSoundSpec m_player_leftpunch_sound;
686 SimpleSoundSpec m_player_rightpunch_sound;
688 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
691 m_player_step_timer(0)
695 void playPlayerStep()
697 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
698 m_player_step_timer = 0.03;
699 m_sound->playSound(m_player_step_sound, false);
703 static void viewBobbingStep(MtEvent *e, void *data)
705 SoundMaker *sm = (SoundMaker*)data;
706 sm->playPlayerStep();
709 static void playerRegainGround(MtEvent *e, void *data)
711 SoundMaker *sm = (SoundMaker*)data;
712 sm->playPlayerStep();
715 static void playerJump(MtEvent *e, void *data)
717 //SoundMaker *sm = (SoundMaker*)data;
720 static void cameraPunchLeft(MtEvent *e, void *data)
722 SoundMaker *sm = (SoundMaker*)data;
723 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
726 static void cameraPunchRight(MtEvent *e, void *data)
728 SoundMaker *sm = (SoundMaker*)data;
729 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
732 static void nodeDug(MtEvent *e, void *data)
734 SoundMaker *sm = (SoundMaker*)data;
735 NodeDugEvent *nde = (NodeDugEvent*)e;
736 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
739 void registerReceiver(MtEventManager *mgr)
741 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
742 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
743 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
744 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
745 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
746 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
749 void step(float dtime)
751 m_player_step_timer -= dtime;
755 // Locally stored sounds don't need to be preloaded because of this
756 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
758 std::set<std::string> m_fetched;
761 void fetchSounds(const std::string &name,
762 std::set<std::string> &dst_paths,
763 std::set<std::string> &dst_datas)
765 if(m_fetched.count(name))
767 m_fetched.insert(name);
768 std::string base = porting::path_share + DIR_DELIM + "testsounds";
769 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
770 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
771 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
772 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
773 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
774 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
775 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
776 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
777 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
778 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
779 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
787 IrrlichtDevice *device,
790 std::string playername,
791 std::string password,
792 std::string address, // If "", local server is used
794 std::wstring &error_message,
795 std::string configpath,
796 ChatBackend &chat_backend,
797 const SubgameSpec &gamespec, // Used for local game,
798 bool simple_singleplayer_mode
801 video::IVideoDriver* driver = device->getVideoDriver();
802 scene::ISceneManager* smgr = device->getSceneManager();
804 // Calculate text height using the font
805 u32 text_height = font->getDimension(L"Random test string").Height;
807 v2u32 screensize(0,0);
808 v2u32 last_screensize(0,0);
809 screensize = driver->getScreenSize();
811 const s32 hotbar_itemcount = 8;
812 //const s32 hotbar_imagesize = 36;
813 //const s32 hotbar_imagesize = 64;
814 s32 hotbar_imagesize = 48;
817 Draw "Loading" screen
820 draw_load_screen(L"Loading...", driver, font);
822 // Create texture source
823 IWritableTextureSource *tsrc = createTextureSource(device);
825 // These will be filled by data received from the server
826 // Create item definition manager
827 IWritableItemDefManager *itemdef = createItemDefManager();
828 // Create node definition manager
829 IWritableNodeDefManager *nodedef = createNodeDefManager();
831 // Sound fetcher (useful when testing)
832 GameOnDemandSoundFetcher soundfetcher;
835 ISoundManager *sound = NULL;
836 bool sound_is_dummy = false;
838 if(g_settings->getBool("enable_sound")){
839 infostream<<"Attempting to use OpenAL audio"<<std::endl;
840 sound = createOpenALSoundManager(&soundfetcher);
842 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
844 infostream<<"Sound disabled."<<std::endl;
848 infostream<<"Using dummy audio."<<std::endl;
849 sound = &dummySoundManager;
850 sound_is_dummy = true;
854 EventManager eventmgr;
857 SoundMaker soundmaker(sound, nodedef);
858 soundmaker.registerReceiver(&eventmgr);
860 // Add chat log output for errors to be shown in chat
861 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
863 // Create UI for modifying quicktune values
864 QuicktuneShortcutter quicktune;
868 SharedPtr will delete it when it goes out of scope.
870 SharedPtr<Server> server;
872 draw_load_screen(L"Creating server...", driver, font);
873 infostream<<"Creating server"<<std::endl;
874 server = new Server(map_dir, configpath, gamespec,
875 simple_singleplayer_mode);
880 do{ // Client scope (breakable do-while(0))
886 draw_load_screen(L"Creating client...", driver, font);
887 infostream<<"Creating client"<<std::endl;
889 MapDrawControl draw_control;
891 Client client(device, playername.c_str(), password, draw_control,
892 tsrc, itemdef, nodedef, sound, &eventmgr);
894 // Client acts as our GameDef
895 IGameDef *gamedef = &client;
897 draw_load_screen(L"Resolving address...", driver, font);
898 Address connect_address(0,0,0,0, port);
901 //connect_address.Resolve("localhost");
902 connect_address.setAddress(127,0,0,1);
904 connect_address.Resolve(address.c_str());
906 catch(ResolveError &e)
908 error_message = L"Couldn't resolve address";
909 errorstream<<wide_to_narrow(error_message)<<std::endl;
910 // Break out of client scope
915 Attempt to connect to the server
918 infostream<<"Connecting to server at ";
919 connect_address.print(&infostream);
920 infostream<<std::endl;
921 client.connect(connect_address);
924 Wait for server to accept connection
926 bool could_connect = false;
927 bool connect_aborted = false;
929 float frametime = 0.033;
930 float time_counter = 0.0;
934 // Update client and server
935 client.step(frametime);
937 server->step(frametime);
940 if(client.connectedAndInitialized()){
941 could_connect = true;
945 if(client.accessDenied()){
946 error_message = L"Access denied. Reason: "
947 +client.accessDeniedReason();
948 errorstream<<wide_to_narrow(error_message)<<std::endl;
951 if(input->wasKeyDown(EscapeKey)){
952 connect_aborted = true;
953 infostream<<"Connect aborted [Escape]"<<std::endl;
958 std::wostringstream ss;
959 ss<<L"Connecting to server... (press Escape to cancel)\n";
960 std::wstring animation = L"/-\\|";
961 ss<<animation[(int)(time_counter/0.2)%4];
962 draw_load_screen(ss.str(), driver, font);
965 sleep_ms(1000*frametime);
966 time_counter += frametime;
969 catch(con::PeerNotFoundException &e)
973 Handle failure to connect
976 if(error_message == L"" && !connect_aborted){
977 error_message = L"Connection failed";
978 errorstream<<wide_to_narrow(error_message)<<std::endl;
980 // Break out of client scope
985 Wait until content has been received
987 bool got_content = false;
988 bool content_aborted = false;
990 float frametime = 0.033;
991 float time_counter = 0.0;
995 // Update client and server
996 client.step(frametime);
998 server->step(frametime);
1001 if(client.texturesReceived() &&
1002 client.itemdefReceived() &&
1003 client.nodedefReceived()){
1008 if(!client.connectedAndInitialized()){
1009 error_message = L"Client disconnected";
1010 errorstream<<wide_to_narrow(error_message)<<std::endl;
1013 if(input->wasKeyDown(EscapeKey)){
1014 content_aborted = true;
1015 infostream<<"Connect aborted [Escape]"<<std::endl;
1020 std::wostringstream ss;
1021 ss<<L"Waiting content... (press Escape to cancel)\n";
1023 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1024 ss<<L" Item definitions\n";
1025 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1026 ss<<L" Node definitions\n";
1027 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1030 draw_load_screen(ss.str(), driver, font);
1033 sleep_ms(1000*frametime);
1034 time_counter += frametime;
1039 if(error_message == L"" && !content_aborted){
1040 error_message = L"Something failed";
1041 errorstream<<wide_to_narrow(error_message)<<std::endl;
1043 // Break out of client scope
1048 After all content has been received:
1049 Update cached textures, meshes and materials
1051 client.afterContentReceived();
1054 Create the camera node
1056 Camera camera(smgr, draw_control, gamedef);
1057 if (!camera.successfullyCreated(error_message))
1060 f32 camera_yaw = 0; // "right/left"
1061 f32 camera_pitch = 0; // "up/down"
1067 Clouds *clouds = NULL;
1068 if(g_settings->getBool("enable_clouds"))
1070 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1078 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1084 FarMesh *farmesh = NULL;
1085 if(g_settings->getBool("enable_farmesh"))
1087 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1091 A copy of the local inventory
1093 Inventory local_inventory(itemdef);
1096 Find out size of crack animation
1098 int crack_animation_length = 5;
1100 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1101 v2u32 size = t->getOriginalSize();
1102 crack_animation_length = size.Y / size.X;
1109 // First line of debug text
1110 gui::IGUIStaticText *guitext = guienv->addStaticText(
1112 core::rect<s32>(5, 5, 795, 5+text_height),
1114 // Second line of debug text
1115 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1117 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1119 // At the middle of the screen
1120 // Object infos are shown in this
1121 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1123 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1126 // Status text (displays info when showing and hiding GUI stuff, etc.)
1127 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1129 core::rect<s32>(0,0,0,0),
1131 guitext_status->setVisible(false);
1133 std::wstring statustext;
1134 float statustext_time = 0;
1137 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1139 core::rect<s32>(0,0,0,0),
1140 //false, false); // Disable word wrap as of now
1142 // Remove stale "recent" chat messages from previous connections
1143 chat_backend.clearRecentChat();
1144 // Chat backend and console
1145 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1147 // Profiler text (size is updated when text is updated)
1148 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1150 core::rect<s32>(0,0,0,0),
1152 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1153 guitext_profiler->setVisible(false);
1156 Some statistics are collected in these
1159 u32 beginscenetime = 0;
1161 u32 endscenetime = 0;
1163 float recent_turn_speed = 0.0;
1165 ProfilerGraph graph;
1166 // Initially clear the profiler
1167 Profiler::GraphValues dummyvalues;
1168 g_profiler->graphGet(dummyvalues);
1170 float nodig_delay_timer = 0.0;
1171 float dig_time = 0.0;
1173 PointedThing pointed_old;
1174 bool digging = false;
1175 bool ldown_for_dig = false;
1177 float damage_flash_timer = 0;
1178 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1180 const float object_hit_delay = 0.2;
1181 float object_hit_delay_timer = 0.0;
1182 float time_from_last_punch = 10;
1184 bool invert_mouse = g_settings->getBool("invert_mouse");
1186 bool respawn_menu_active = false;
1187 bool update_wielded_item_trigger = false;
1189 bool show_hud = true;
1190 bool show_chat = true;
1191 bool force_fog_off = false;
1192 bool disable_camera_update = false;
1193 bool show_debug = g_settings->getBool("show_debug");
1194 bool show_profiler_graph = false;
1195 u32 show_profiler = 0;
1196 u32 show_profiler_max = 3; // Number of pages
1198 float time_of_day = 0;
1199 float time_of_day_smooth = 0;
1205 bool first_loop_after_window_activation = true;
1207 // TODO: Convert the static interval timers to these
1208 // Interval limiter for profiler
1209 IntervalLimiter m_profiler_interval;
1211 // Time is in milliseconds
1212 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1213 // NOTE: So we have to use getTime() and call run()s between them
1214 u32 lasttime = device->getTimer()->getTime();
1218 if(device->run() == false || kill == true)
1221 // Time of frame without fps limit
1225 // not using getRealTime is necessary for wine
1226 u32 time = device->getTimer()->getTime();
1228 busytime_u32 = time - lasttime;
1231 busytime = busytime_u32 / 1000.0;
1234 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1236 // Necessary for device->getTimer()->getTime()
1244 float fps_max = g_settings->getFloat("fps_max");
1245 u32 frametime_min = 1000./fps_max;
1247 if(busytime_u32 < frametime_min)
1249 u32 sleeptime = frametime_min - busytime_u32;
1250 device->sleep(sleeptime);
1251 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1255 // Necessary for device->getTimer()->getTime()
1259 Time difference calculation
1261 f32 dtime; // in seconds
1263 u32 time = device->getTimer()->getTime();
1265 dtime = (time - lasttime) / 1000.0;
1270 g_profiler->graphAdd("mainloop_dtime", dtime);
1274 if(nodig_delay_timer >= 0)
1275 nodig_delay_timer -= dtime;
1276 if(object_hit_delay_timer >= 0)
1277 object_hit_delay_timer -= dtime;
1278 time_from_last_punch += dtime;
1280 g_profiler->add("Elapsed time", dtime);
1281 g_profiler->avg("FPS", 1./dtime);
1284 Time average and jitter calculation
1287 static f32 dtime_avg1 = 0.0;
1288 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1289 f32 dtime_jitter1 = dtime - dtime_avg1;
1291 static f32 dtime_jitter1_max_sample = 0.0;
1292 static f32 dtime_jitter1_max_fraction = 0.0;
1294 static f32 jitter1_max = 0.0;
1295 static f32 counter = 0.0;
1296 if(dtime_jitter1 > jitter1_max)
1297 jitter1_max = dtime_jitter1;
1302 dtime_jitter1_max_sample = jitter1_max;
1303 dtime_jitter1_max_fraction
1304 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1310 Busytime average and jitter calculation
1313 static f32 busytime_avg1 = 0.0;
1314 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1315 f32 busytime_jitter1 = busytime - busytime_avg1;
1317 static f32 busytime_jitter1_max_sample = 0.0;
1318 static f32 busytime_jitter1_min_sample = 0.0;
1320 static f32 jitter1_max = 0.0;
1321 static f32 jitter1_min = 0.0;
1322 static f32 counter = 0.0;
1323 if(busytime_jitter1 > jitter1_max)
1324 jitter1_max = busytime_jitter1;
1325 if(busytime_jitter1 < jitter1_min)
1326 jitter1_min = busytime_jitter1;
1330 busytime_jitter1_max_sample = jitter1_max;
1331 busytime_jitter1_min_sample = jitter1_min;
1338 Handle miscellaneous stuff
1341 if(client.accessDenied())
1343 error_message = L"Access denied. Reason: "
1344 +client.accessDeniedReason();
1345 errorstream<<wide_to_narrow(error_message)<<std::endl;
1349 if(g_gamecallback->disconnect_requested)
1351 g_gamecallback->disconnect_requested = false;
1355 if(g_gamecallback->changepassword_requested)
1357 (new GUIPasswordChange(guienv, guiroot, -1,
1358 &g_menumgr, &client))->drop();
1359 g_gamecallback->changepassword_requested = false;
1363 Process TextureSource's queue
1365 tsrc->processQueue();
1370 last_screensize = screensize;
1371 screensize = driver->getScreenSize();
1372 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1373 //bool screensize_changed = screensize != last_screensize;
1376 if(screensize.Y <= 800)
1377 hotbar_imagesize = 32;
1378 else if(screensize.Y <= 1280)
1379 hotbar_imagesize = 48;
1381 hotbar_imagesize = 64;
1383 // Hilight boxes collected during the loop and displayed
1384 std::vector<aabb3f> hilightboxes;
1387 std::wstring infotext;
1390 Debug info for client
1393 static float counter = 0.0;
1398 client.printDebugInfo(infostream);
1405 float profiler_print_interval =
1406 g_settings->getFloat("profiler_print_interval");
1407 bool print_to_log = true;
1408 if(profiler_print_interval == 0){
1409 print_to_log = false;
1410 profiler_print_interval = 5;
1412 if(m_profiler_interval.step(dtime, profiler_print_interval))
1415 infostream<<"Profiler:"<<std::endl;
1416 g_profiler->print(infostream);
1419 update_profiler_gui(guitext_profiler, font, text_height,
1420 show_profiler, show_profiler_max);
1422 g_profiler->clear();
1426 Direct handling of user input
1429 // Reset input if window not active or some menu is active
1430 if(device->isWindowActive() == false
1431 || noMenuActive() == false
1432 || guienv->hasFocus(gui_chat_console))
1437 // Input handler step() (used by the random input generator)
1441 Launch menus and trigger stuff according to keys
1443 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1445 // drop selected item
1446 IDropAction *a = new IDropAction();
1448 a->from_inv.setCurrentPlayer();
1449 a->from_list = "main";
1450 a->from_i = client.getPlayerItem();
1451 client.inventoryAction(a);
1453 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1455 infostream<<"the_game: "
1456 <<"Launching inventory"<<std::endl;
1458 GUIInventoryMenu *menu =
1459 new GUIInventoryMenu(guienv, guiroot, -1,
1463 InventoryLocation inventoryloc;
1464 inventoryloc.setCurrentPlayer();
1468 //"image[1,0.6;1,2;player.png]"
1469 "list[current_player;main;0,3.5;8,4;]"
1470 "list[current_player;craft;3,0;3,3;]"
1471 "list[current_player;craftpreview;7,1;1,1;]"
1476 else if(input->wasKeyDown(EscapeKey))
1478 infostream<<"the_game: "
1479 <<"Launching pause menu"<<std::endl;
1480 // It will delete itself by itself
1481 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1482 &g_menumgr, simple_singleplayer_mode))->drop();
1484 // Move mouse cursor on top of the disconnect button
1485 if(simple_singleplayer_mode)
1486 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1488 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1490 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1492 TextDest *dest = new TextDestChat(&client);
1494 (new GUITextInputMenu(guienv, guiroot, -1,
1498 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1500 TextDest *dest = new TextDestChat(&client);
1502 (new GUITextInputMenu(guienv, guiroot, -1,
1506 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1508 if (!gui_chat_console->isOpenInhibited())
1510 // Open up to over half of the screen
1511 gui_chat_console->openConsole(0.6);
1512 guienv->setFocus(gui_chat_console);
1515 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1517 if(g_settings->getBool("free_move"))
1519 g_settings->set("free_move","false");
1520 statustext = L"free_move disabled";
1521 statustext_time = 0;
1525 g_settings->set("free_move","true");
1526 statustext = L"free_move enabled";
1527 statustext_time = 0;
1528 if(!client.checkPrivilege("fly"))
1529 statustext += L" (note: no 'fly' privilege)";
1532 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1534 if(g_settings->getBool("fast_move"))
1536 g_settings->set("fast_move","false");
1537 statustext = L"fast_move disabled";
1538 statustext_time = 0;
1542 g_settings->set("fast_move","true");
1543 statustext = L"fast_move enabled";
1544 statustext_time = 0;
1545 if(!client.checkPrivilege("fast"))
1546 statustext += L" (note: no 'fast' privilege)";
1549 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1551 irr::video::IImage* const image = driver->createScreenShot();
1553 irr::c8 filename[256];
1554 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1555 g_settings->get("screenshot_path").c_str(),
1556 device->getTimer()->getRealTime());
1557 if (driver->writeImageToFile(image, filename)) {
1558 std::wstringstream sstr;
1559 sstr<<"Saved screenshot to '"<<filename<<"'";
1560 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1561 statustext = sstr.str();
1562 statustext_time = 0;
1564 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1569 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1571 show_hud = !show_hud;
1573 statustext = L"HUD shown";
1575 statustext = L"HUD hidden";
1576 statustext_time = 0;
1578 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1580 show_chat = !show_chat;
1582 statustext = L"Chat shown";
1584 statustext = L"Chat hidden";
1585 statustext_time = 0;
1587 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1589 force_fog_off = !force_fog_off;
1591 statustext = L"Fog disabled";
1593 statustext = L"Fog enabled";
1594 statustext_time = 0;
1596 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1598 disable_camera_update = !disable_camera_update;
1599 if(disable_camera_update)
1600 statustext = L"Camera update disabled";
1602 statustext = L"Camera update enabled";
1603 statustext_time = 0;
1605 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1607 // Initial / 3x toggle: Chat only
1608 // 1x toggle: Debug text with chat
1609 // 2x toggle: Debug text with profiler graph
1613 show_profiler_graph = false;
1614 statustext = L"Debug info shown";
1615 statustext_time = 0;
1617 else if(show_profiler_graph)
1620 show_profiler_graph = false;
1621 statustext = L"Debug info and profiler graph hidden";
1622 statustext_time = 0;
1626 show_profiler_graph = true;
1627 statustext = L"Profiler graph shown";
1628 statustext_time = 0;
1631 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1633 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1635 // FIXME: This updates the profiler with incomplete values
1636 update_profiler_gui(guitext_profiler, font, text_height,
1637 show_profiler, show_profiler_max);
1639 if(show_profiler != 0)
1641 std::wstringstream sstr;
1642 sstr<<"Profiler shown (page "<<show_profiler
1643 <<" of "<<show_profiler_max<<")";
1644 statustext = sstr.str();
1645 statustext_time = 0;
1649 statustext = L"Profiler hidden";
1650 statustext_time = 0;
1653 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1655 s16 range = g_settings->getS16("viewing_range_nodes_min");
1656 s16 range_new = range + 10;
1657 g_settings->set("viewing_range_nodes_min", itos(range_new));
1658 statustext = narrow_to_wide(
1659 "Minimum viewing range changed to "
1661 statustext_time = 0;
1663 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1665 s16 range = g_settings->getS16("viewing_range_nodes_min");
1666 s16 range_new = range - 10;
1669 g_settings->set("viewing_range_nodes_min",
1671 statustext = narrow_to_wide(
1672 "Minimum viewing range changed to "
1674 statustext_time = 0;
1677 // Handle QuicktuneShortcutter
1678 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1680 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1682 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1684 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1687 std::string msg = quicktune.getMessage();
1689 statustext = narrow_to_wide(msg);
1690 statustext_time = 0;
1694 // Item selection with mouse wheel
1695 u16 new_playeritem = client.getPlayerItem();
1697 s32 wheel = input->getMouseWheel();
1698 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1699 hotbar_itemcount-1);
1703 if(new_playeritem < max_item)
1710 if(new_playeritem > 0)
1713 new_playeritem = max_item;
1718 for(u16 i=0; i<10; i++)
1720 const KeyPress *kp = NumberKey + (i + 1) % 10;
1721 if(input->wasKeyDown(*kp))
1723 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1727 infostream<<"Selected item: "
1728 <<new_playeritem<<std::endl;
1733 // Viewing range selection
1734 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1736 draw_control.range_all = !draw_control.range_all;
1737 if(draw_control.range_all)
1739 infostream<<"Enabled full viewing range"<<std::endl;
1740 statustext = L"Enabled full viewing range";
1741 statustext_time = 0;
1745 infostream<<"Disabled full viewing range"<<std::endl;
1746 statustext = L"Disabled full viewing range";
1747 statustext_time = 0;
1751 // Print debug stacks
1752 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1754 dstream<<"-----------------------------------------"
1756 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1757 dstream<<"-----------------------------------------"
1759 debug_stacks_print();
1763 Mouse and camera control
1764 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1767 float turn_amount = 0;
1768 if((device->isWindowActive() && noMenuActive()) || random_input)
1772 // Mac OSX gets upset if this is set every frame
1773 if(device->getCursorControl()->isVisible())
1774 device->getCursorControl()->setVisible(false);
1777 if(first_loop_after_window_activation){
1778 //infostream<<"window active, first loop"<<std::endl;
1779 first_loop_after_window_activation = false;
1782 s32 dx = input->getMousePos().X - displaycenter.X;
1783 s32 dy = input->getMousePos().Y - displaycenter.Y;
1786 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1788 /*const float keyspeed = 500;
1789 if(input->isKeyDown(irr::KEY_UP))
1790 dy -= dtime * keyspeed;
1791 if(input->isKeyDown(irr::KEY_DOWN))
1792 dy += dtime * keyspeed;
1793 if(input->isKeyDown(irr::KEY_LEFT))
1794 dx -= dtime * keyspeed;
1795 if(input->isKeyDown(irr::KEY_RIGHT))
1796 dx += dtime * keyspeed;*/
1800 camera_pitch += dy*d;
1801 if(camera_pitch < -89.5) camera_pitch = -89.5;
1802 if(camera_pitch > 89.5) camera_pitch = 89.5;
1804 turn_amount = v2f(dx, dy).getLength() * d;
1806 input->setMousePos(displaycenter.X, displaycenter.Y);
1809 // Mac OSX gets upset if this is set every frame
1810 if(device->getCursorControl()->isVisible() == false)
1811 device->getCursorControl()->setVisible(true);
1813 //infostream<<"window inactive"<<std::endl;
1814 first_loop_after_window_activation = true;
1816 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1817 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1820 Player speed control
1832 PlayerControl control(
1833 input->isKeyDown(getKeySetting("keymap_forward")),
1834 input->isKeyDown(getKeySetting("keymap_backward")),
1835 input->isKeyDown(getKeySetting("keymap_left")),
1836 input->isKeyDown(getKeySetting("keymap_right")),
1837 input->isKeyDown(getKeySetting("keymap_jump")),
1838 input->isKeyDown(getKeySetting("keymap_special1")),
1839 input->isKeyDown(getKeySetting("keymap_sneak")),
1843 client.setPlayerControl(control);
1852 //TimeTaker timer("server->step(dtime)");
1853 server->step(dtime);
1861 //TimeTaker timer("client.step(dtime)");
1863 //client.step(dtime_avg1);
1867 // Read client events
1870 ClientEvent event = client.getClientEvent();
1871 if(event.type == CE_NONE)
1875 else if(event.type == CE_PLAYER_DAMAGE)
1877 //u16 damage = event.player_damage.amount;
1878 //infostream<<"Player damage: "<<damage<<std::endl;
1879 damage_flash_timer = 0.05;
1880 if(event.player_damage.amount >= 2){
1881 damage_flash_timer += 0.05 * event.player_damage.amount;
1884 else if(event.type == CE_PLAYER_FORCE_MOVE)
1886 camera_yaw = event.player_force_move.yaw;
1887 camera_pitch = event.player_force_move.pitch;
1889 else if(event.type == CE_DEATHSCREEN)
1891 if(respawn_menu_active)
1894 /*bool set_camera_point_target =
1895 event.deathscreen.set_camera_point_target;
1896 v3f camera_point_target;
1897 camera_point_target.X = event.deathscreen.camera_point_target_x;
1898 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1899 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1900 MainRespawnInitiator *respawner =
1901 new MainRespawnInitiator(
1902 &respawn_menu_active, &client);
1903 GUIDeathScreen *menu =
1904 new GUIDeathScreen(guienv, guiroot, -1,
1905 &g_menumgr, respawner);
1908 chat_backend.addMessage(L"", L"You died.");
1910 /* Handle visualization */
1912 damage_flash_timer = 0;
1914 /*LocalPlayer* player = client.getLocalPlayer();
1915 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1916 camera.update(player, busytime, screensize);*/
1918 else if(event.type == CE_TEXTURES_UPDATED)
1920 update_wielded_item_trigger = true;
1925 //TimeTaker //timer2("//timer2");
1928 For interaction purposes, get info about the held item
1930 - Is it a usable item?
1931 - Can it point to liquids?
1933 ItemStack playeritem;
1934 bool playeritem_usable = false;
1935 bool playeritem_liquids_pointable = false;
1937 InventoryList *mlist = local_inventory.getList("main");
1940 playeritem = mlist->getItem(client.getPlayerItem());
1941 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1942 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1945 ToolCapabilities playeritem_toolcap =
1946 playeritem.getToolCapabilities(itemdef);
1952 LocalPlayer* player = client.getEnv().getLocalPlayer();
1953 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1954 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1955 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1956 camera.update(player, busytime, screensize, tool_reload_ratio);
1959 v3f player_position = player->getPosition();
1960 v3f camera_position = camera.getPosition();
1961 v3f camera_direction = camera.getDirection();
1962 f32 camera_fov = camera.getFovMax();
1964 if(!disable_camera_update){
1965 client.getEnv().getClientMap().updateCamera(camera_position,
1966 camera_direction, camera_fov);
1969 // Update sound listener
1970 sound->updateListener(camera.getCameraNode()->getPosition(),
1971 v3f(0,0,0), // velocity
1972 camera.getDirection(),
1973 camera.getCameraNode()->getUpVector());
1974 sound->setListenerGain(g_settings->getFloat("sound_volume"));
1980 soundmaker.step(dtime);
1982 ClientMap &map = client.getEnv().getClientMap();
1983 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
1984 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
1988 Calculate what block is the crosshair pointing to
1991 //u32 t1 = device->getTimer()->getRealTime();
1993 f32 d = 4; // max. distance
1994 core::line3d<f32> shootline(camera_position,
1995 camera_position + camera_direction * BS * (d+1));
1997 ClientActiveObject *selected_object = NULL;
1999 PointedThing pointed = getPointedThing(
2001 &client, player_position, camera_direction,
2002 camera_position, shootline, d,
2003 playeritem_liquids_pointable, !ldown_for_dig,
2008 if(pointed != pointed_old)
2010 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2011 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2016 - releasing left mouse button
2017 - pointing away from node
2021 if(input->getLeftReleased())
2023 infostream<<"Left button released"
2024 <<" (stopped digging)"<<std::endl;
2027 else if(pointed != pointed_old)
2029 if (pointed.type == POINTEDTHING_NODE
2030 && pointed_old.type == POINTEDTHING_NODE
2031 && pointed.node_undersurface == pointed_old.node_undersurface)
2033 // Still pointing to the same node,
2034 // but a different face. Don't reset.
2038 infostream<<"Pointing away from node"
2039 <<" (stopped digging)"<<std::endl;
2045 client.interact(1, pointed_old);
2046 client.setCrack(-1, v3s16(0,0,0));
2050 if(!digging && ldown_for_dig && !input->getLeftState())
2052 ldown_for_dig = false;
2055 bool left_punch = false;
2056 soundmaker.m_player_leftpunch_sound.name = "";
2058 if(playeritem_usable && input->getLeftState())
2060 if(input->getLeftClicked())
2061 client.interact(4, pointed);
2063 else if(pointed.type == POINTEDTHING_NODE)
2065 v3s16 nodepos = pointed.node_undersurface;
2066 v3s16 neighbourpos = pointed.node_abovesurface;
2069 Check information text of node
2072 ClientMap &map = client.getEnv().getClientMap();
2073 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2075 infotext = narrow_to_wide(meta->getString("infotext"));
2077 MapNode n = map.getNode(nodepos);
2078 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2079 infotext = L"Unknown node: ";
2080 infotext += narrow_to_wide(nodedef->get(n).name);
2084 // We can't actually know, but assume the sound of right-clicking
2085 // to be the sound of placing a node
2086 soundmaker.m_player_rightpunch_sound.gain = 0.5;
2087 soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2093 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2097 infostream<<"Started digging"<<std::endl;
2098 client.interact(0, pointed);
2100 ldown_for_dig = true;
2102 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2104 // Get digging parameters
2105 DigParams params = getDigParams(nodedef->get(n).groups,
2106 &playeritem_toolcap);
2107 // If can't dig, try hand
2108 if(!params.diggable){
2109 const ItemDefinition &hand = itemdef->get("");
2110 const ToolCapabilities *tp = hand.tool_capabilities;
2112 params = getDigParams(nodedef->get(n).groups, tp);
2115 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2116 if(sound_dig.exists()){
2117 if(sound_dig.name == "__group"){
2118 if(params.main_group != ""){
2119 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2120 soundmaker.m_player_leftpunch_sound.name =
2121 std::string("default_dig_") +
2125 soundmaker.m_player_leftpunch_sound = sound_dig;
2129 float dig_time_complete = 0.0;
2131 if(params.diggable == false)
2133 // I guess nobody will wait for this long
2134 dig_time_complete = 10000000.0;
2138 dig_time_complete = params.time;
2141 if(dig_time_complete >= 0.001)
2143 dig_index = (u16)((float)crack_animation_length
2144 * dig_time/dig_time_complete);
2146 // This is for torches
2149 dig_index = crack_animation_length;
2152 // Don't show cracks if not diggable
2153 if(dig_time_complete >= 100000.0)
2156 else if(dig_index < crack_animation_length)
2158 //TimeTaker timer("client.setTempMod");
2159 //infostream<<"dig_index="<<dig_index<<std::endl;
2160 client.setCrack(dig_index, nodepos);
2164 infostream<<"Digging completed"<<std::endl;
2165 client.interact(2, pointed);
2166 client.setCrack(-1, v3s16(0,0,0));
2167 MapNode wasnode = map.getNode(nodepos);
2168 client.removeNode(nodepos);
2173 nodig_delay_timer = dig_time_complete
2174 / (float)crack_animation_length;
2176 // We don't want a corresponding delay to
2177 // very time consuming nodes
2178 if(nodig_delay_timer > 0.3)
2179 nodig_delay_timer = 0.3;
2180 // We want a slight delay to very little
2181 // time consuming nodes
2182 float mindelay = 0.15;
2183 if(nodig_delay_timer < mindelay)
2184 nodig_delay_timer = mindelay;
2186 // Send event to trigger sound
2187 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2188 gamedef->event()->put(e);
2193 camera.setDigging(0); // left click animation
2196 if(input->getRightClicked())
2198 infostream<<"Ground right-clicked"<<std::endl;
2200 // sign special case, at least until formspec is properly implemented
2201 if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
2203 infostream<<"Launching metadata text input"<<std::endl;
2205 // Get a new text for it
2207 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2209 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2211 (new GUITextInputMenu(guienv, guiroot, -1,
2215 // If metadata provides an inventory view, activate it
2216 else if(meta && meta->getString("formspec") != "" && !random_input)
2218 infostream<<"Launching custom inventory view"<<std::endl;
2220 InventoryLocation inventoryloc;
2221 inventoryloc.setNodeMeta(nodepos);
2225 GUIInventoryMenu *menu =
2226 new GUIInventoryMenu(guienv, guiroot, -1,
2229 menu->setFormSpec(meta->getString("formspec"),
2231 menu->setFormSource(new NodeMetadataFormSource(
2232 &client.getEnv().getClientMap(), nodepos));
2235 // Otherwise report right click to server
2239 client.interact(3, pointed);
2240 camera.setDigging(1); // right click animation
2242 // If the wielded item has node placement prediction,
2244 const ItemDefinition &def =
2245 playeritem.getDefinition(itemdef);
2246 if(def.node_placement_prediction != "")
2248 verbosestream<<"Node placement prediction for "
2249 <<playeritem.name<<" is "
2250 <<def.node_placement_prediction<<std::endl;
2251 v3s16 p = neighbourpos;
2254 nodedef->getId(def.node_placement_prediction, id);
2256 errorstream<<"Node placement prediction failed for "
2257 <<playeritem.name<<" (places "
2258 <<def.node_placement_prediction
2259 <<") - Name not known"<<std::endl;
2264 // This triggers the required mesh update too
2265 client.addNode(p, n);
2266 }catch(InvalidPositionException &e){
2267 errorstream<<"Node placement prediction failed for "
2268 <<playeritem.name<<" (places "
2269 <<def.node_placement_prediction
2270 <<") - Position not loaded"<<std::endl;
2276 else if(pointed.type == POINTEDTHING_OBJECT)
2278 infotext = narrow_to_wide(selected_object->infoText());
2280 if(infotext == L"" && show_debug){
2281 infotext = narrow_to_wide(selected_object->debugInfoText());
2284 //if(input->getLeftClicked())
2285 if(input->getLeftState())
2287 bool do_punch = false;
2288 bool do_punch_damage = false;
2289 if(object_hit_delay_timer <= 0.0){
2291 do_punch_damage = true;
2292 object_hit_delay_timer = object_hit_delay;
2294 if(input->getLeftClicked()){
2298 infostream<<"Left-clicked object"<<std::endl;
2301 if(do_punch_damage){
2302 // Report direct punch
2303 v3f objpos = selected_object->getPosition();
2304 v3f dir = (objpos - player_position).normalize();
2306 bool disable_send = selected_object->directReportPunch(
2307 dir, &playeritem, time_from_last_punch);
2308 time_from_last_punch = 0;
2310 client.interact(0, pointed);
2313 else if(input->getRightClicked())
2315 infostream<<"Right-clicked object"<<std::endl;
2316 client.interact(3, pointed); // place
2319 else if(input->getLeftState())
2321 // When button is held down in air, show continuous animation
2325 pointed_old = pointed;
2327 if(left_punch || input->getLeftClicked())
2329 camera.setDigging(0); // left click animation
2332 input->resetLeftClicked();
2333 input->resetRightClicked();
2335 input->resetLeftReleased();
2336 input->resetRightReleased();
2339 Calculate stuff for drawing
2349 fog_range = BS*farmesh_range;
2353 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2355 if(draw_control.range_all)
2356 fog_range = 100000*BS;
2360 Calculate general brightness
2362 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2363 float time_brightness = (float)decode_light(
2364 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2365 float direct_brightness = 0;
2366 bool sunlight_seen = false;
2367 if(g_settings->getBool("free_move")){
2368 direct_brightness = time_brightness;
2369 sunlight_seen = true;
2371 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2372 float old_brightness = sky->getBrightness();
2373 direct_brightness = (float)client.getEnv().getClientMap()
2374 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2375 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2379 time_of_day = client.getEnv().getTimeOfDayF();
2381 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2382 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2383 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2384 time_of_day_smooth = time_of_day;
2386 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2387 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2388 + (time_of_day+1.0) * todsm;
2390 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2391 + time_of_day * todsm;
2393 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2396 float brightness = sky->getBrightness();
2397 video::SColor bgcolor = sky->getBgColor();
2398 video::SColor skycolor = sky->getSkyColor();
2404 if(sky->getCloudsVisible()){
2405 clouds->setVisible(true);
2406 clouds->step(dtime);
2407 clouds->update(v2f(player_position.X, player_position.Z),
2408 sky->getCloudColor());
2410 clouds->setVisible(false);
2419 farmesh_range = draw_control.wanted_range * 10;
2420 if(draw_control.range_all && farmesh_range < 500)
2421 farmesh_range = 500;
2422 if(farmesh_range > 1000)
2423 farmesh_range = 1000;
2425 farmesh->step(dtime);
2426 farmesh->update(v2f(player_position.X, player_position.Z),
2427 brightness, farmesh_range);
2434 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2438 video::EFT_FOG_LINEAR,
2450 video::EFT_FOG_LINEAR,
2460 Update gui stuff (0ms)
2463 //TimeTaker guiupdatetimer("Gui updating");
2465 const char program_name_and_version[] =
2466 "Minetest-c55 " VERSION_STRING;
2470 static float drawtime_avg = 0;
2471 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2472 /*static float beginscenetime_avg = 0;
2473 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2474 static float scenetime_avg = 0;
2475 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2476 static float endscenetime_avg = 0;
2477 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2480 snprintf(temptext, 300, "%s ("
2483 " drawtime=%.0f, dtime_jitter = % .1f %%"
2484 ", v_range = %.1f, RTT = %.3f",
2485 program_name_and_version,
2486 draw_control.range_all,
2488 dtime_jitter1_max_fraction * 100.0,
2489 draw_control.wanted_range,
2493 guitext->setText(narrow_to_wide(temptext).c_str());
2494 guitext->setVisible(true);
2496 else if(show_hud || show_chat)
2498 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2499 guitext->setVisible(true);
2503 guitext->setVisible(false);
2509 snprintf(temptext, 300,
2510 "(% .1f, % .1f, % .1f)"
2511 " (yaw = %.1f) (seed = %lli)",
2512 player_position.X/BS,
2513 player_position.Y/BS,
2514 player_position.Z/BS,
2515 wrapDegrees_0_360(camera_yaw),
2516 client.getMapSeed());
2518 guitext2->setText(narrow_to_wide(temptext).c_str());
2519 guitext2->setVisible(true);
2523 guitext2->setVisible(false);
2527 guitext_info->setText(infotext.c_str());
2528 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2532 float statustext_time_max = 1.5;
2533 if(!statustext.empty())
2535 statustext_time += dtime;
2536 if(statustext_time >= statustext_time_max)
2539 statustext_time = 0;
2542 guitext_status->setText(statustext.c_str());
2543 guitext_status->setVisible(!statustext.empty());
2545 if(!statustext.empty())
2547 s32 status_y = screensize.Y - 130;
2548 core::rect<s32> rect(
2550 status_y - guitext_status->getTextHeight(),
2554 guitext_status->setRelativePosition(rect);
2557 video::SColor initial_color(255,0,0,0);
2558 if(guienv->getSkin())
2559 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2560 video::SColor final_color = initial_color;
2561 final_color.setAlpha(0);
2562 video::SColor fade_color =
2563 initial_color.getInterpolated_quadratic(
2566 pow(statustext_time / (float)statustext_time_max, 2.0f));
2567 guitext_status->setOverrideColor(fade_color);
2568 guitext_status->enableOverrideColor(true);
2573 Get chat messages from client
2576 // Get new messages from error log buffer
2577 while(!chat_log_error_buf.empty())
2579 chat_backend.addMessage(L"", narrow_to_wide(
2580 chat_log_error_buf.get()));
2582 // Get new messages from client
2583 std::wstring message;
2584 while(client.getChatMessage(message))
2586 chat_backend.addUnparsedMessage(message);
2588 // Remove old messages
2589 chat_backend.step(dtime);
2591 // Display all messages in a static text element
2592 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2593 std::wstring recent_chat = chat_backend.getRecentChat();
2594 guitext_chat->setText(recent_chat.c_str());
2596 // Update gui element size and position
2597 s32 chat_y = 5+(text_height+5);
2599 chat_y += (text_height+5);
2600 core::rect<s32> rect(
2604 chat_y + guitext_chat->getTextHeight()
2606 guitext_chat->setRelativePosition(rect);
2608 // Don't show chat if disabled or empty or profiler is enabled
2609 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2617 if(client.getPlayerItem() != new_playeritem)
2619 client.selectPlayerItem(new_playeritem);
2621 if(client.getLocalInventoryUpdated())
2623 //infostream<<"Updating local inventory"<<std::endl;
2624 client.getLocalInventory(local_inventory);
2626 update_wielded_item_trigger = true;
2628 if(update_wielded_item_trigger)
2630 update_wielded_item_trigger = false;
2631 // Update wielded tool
2632 InventoryList *mlist = local_inventory.getList("main");
2635 item = mlist->getItem(client.getPlayerItem());
2643 TimeTaker tt_draw("mainloop: draw");
2647 TimeTaker timer("beginScene");
2648 //driver->beginScene(false, true, bgcolor);
2649 //driver->beginScene(true, true, bgcolor);
2650 driver->beginScene(true, true, skycolor);
2651 beginscenetime = timer.stop(true);
2656 //infostream<<"smgr->drawAll()"<<std::endl;
2658 TimeTaker timer("smgr");
2660 scenetime = timer.stop(true);
2664 //TimeTaker timer9("auxiliary drawings");
2668 //TimeTaker //timer10("//timer10");
2674 driver->setMaterial(m);
2676 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2680 for(std::vector<aabb3f>::const_iterator
2681 i = hilightboxes.begin();
2682 i != hilightboxes.end(); i++)
2684 /*infostream<<"hilightbox min="
2685 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2687 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2689 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2698 // Warning: This clears the Z buffer.
2699 camera.drawWieldedTool();
2706 client.getEnv().getClientMap().renderPostFx();
2712 if(show_profiler_graph)
2714 graph.draw(10, screensize.Y - 10, driver, font);
2722 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2723 displaycenter + core::vector2d<s32>(10,0),
2724 video::SColor(255,255,255,255));
2725 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2726 displaycenter + core::vector2d<s32>(0,10),
2727 video::SColor(255,255,255,255));
2733 //TimeTaker //timer11("//timer11");
2746 draw_hotbar(driver, font, gamedef,
2747 v2s32(displaycenter.X, screensize.Y),
2748 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2749 client.getHP(), client.getPlayerItem());
2755 if(damage_flash_timer > 0.0)
2757 damage_flash_timer -= dtime;
2759 video::SColor color(128,255,0,0);
2760 driver->draw2DRectangle(color,
2761 core::rect<s32>(0,0,screensize.X,screensize.Y),
2769 TimeTaker timer("endScene");
2771 endscenetime = timer.stop(true);
2774 drawtime = tt_draw.stop(true);
2775 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2781 static s16 lastFPS = 0;
2782 //u16 fps = driver->getFPS();
2783 u16 fps = (1.0/dtime_avg1);
2787 core::stringw str = L"Minetest [";
2788 str += driver->getName();
2792 device->setWindowCaption(str.c_str());
2797 Log times and stuff for visualization
2799 Profiler::GraphValues values;
2800 g_profiler->graphGet(values);
2809 if(gui_chat_console)
2810 gui_chat_console->drop();
2813 Draw a "shutting down" screen, which will be shown while the map
2814 generator and other stuff quits
2817 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2818 draw_load_screen(L"Shutting down stuff...", driver, font);
2819 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2822 gui_shuttingdowntext->remove();*/
2825 chat_backend.addMessage(L"", L"# Disconnected.");
2826 chat_backend.addMessage(L"", L"");
2828 // Client scope (client is destructed before destructing *def and tsrc)
2831 catch(SerializationError &e)
2833 error_message = L"A serialization error occurred:\n"
2834 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
2835 L" running a different version of Minetest.";
2836 errorstream<<wide_to_narrow(error_message)<<std::endl;