3 Copyright (C) 2010-2013 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>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
31 #include "guiPauseMenu.h"
32 #include "guiPasswordChange.h"
33 #include "guiVolumeChange.h"
34 #include "guiFormSpecMenu.h"
35 #include "guiTextInputMenu.h"
36 #include "guiDeathScreen.h"
38 #include "guiChatConsole.h"
41 #include "particles.h"
47 #include "mainmenumanager.h"
51 // Needed for determining pointing to nodes
53 #include "nodemetadata.h"
54 #include "main.h" // For g_settings
56 #include "tile.h" // For TextureSource
57 #include "shader.h" // For ShaderSource
58 #include "logoutputbuffer.h"
60 #include "quicktune_shortcutter.h"
61 #include "clientmap.h"
66 #include "sound_openal.h"
68 #include "event_manager.h"
70 #include "util/directiontables.h"
76 struct TextDestChat : public TextDest
78 TextDestChat(Client *client)
82 void gotText(std::wstring text)
84 m_client->typeChatMessage(text);
86 void gotText(std::map<std::string, std::string> fields)
88 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
94 struct TextDestNodeMetadata : public TextDest
96 TextDestNodeMetadata(v3s16 p, Client *client)
101 // This is deprecated I guess? -celeron55
102 void gotText(std::wstring text)
104 std::string ntext = wide_to_narrow(text);
105 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
106 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
107 std::map<std::string, std::string> fields;
108 fields["text"] = ntext;
109 m_client->sendNodemetaFields(m_p, "", fields);
111 void gotText(std::map<std::string, std::string> fields)
113 m_client->sendNodemetaFields(m_p, "", fields);
120 struct TextDestPlayerInventory : public TextDest
122 TextDestPlayerInventory(Client *client)
127 TextDestPlayerInventory(Client *client, std::string formname)
130 m_formname = formname;
132 void gotText(std::map<std::string, std::string> fields)
134 m_client->sendInventoryFields(m_formname, fields);
138 std::string m_formname;
141 /* Respawn menu callback */
143 class MainRespawnInitiator: public IRespawnInitiator
146 MainRespawnInitiator(bool *active, Client *client):
147 m_active(active), m_client(client)
154 m_client->sendRespawn();
161 /* Form update callback */
163 class NodeMetadataFormSource: public IFormSource
166 NodeMetadataFormSource(ClientMap *map, v3s16 p):
171 std::string getForm()
173 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
176 return meta->getString("formspec");
178 std::string resolveText(std::string str)
180 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
183 return meta->resolveString(str);
190 class PlayerInventoryFormSource: public IFormSource
193 PlayerInventoryFormSource(Client *client):
197 std::string getForm()
199 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
200 return player->inventory_formspec;
206 class FormspecFormSource: public IFormSource
209 FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
211 m_formspec = formspec;
212 m_game_formspec = game_formspec;
215 ~FormspecFormSource()
217 *m_game_formspec = 0;
220 void setForm(std::string formspec) {
221 m_formspec = formspec;
224 std::string getForm()
229 std::string m_formspec;
230 FormspecFormSource** m_game_formspec;
234 Check if a node is pointable
236 inline bool isPointableNode(const MapNode& n,
237 Client *client, bool liquids_pointable)
239 const ContentFeatures &features = client->getNodeDefManager()->get(n);
240 return features.pointable ||
241 (liquids_pointable && features.isLiquid());
245 Find what the player is pointing at
247 PointedThing getPointedThing(Client *client, v3f player_position,
248 v3f camera_direction, v3f camera_position,
249 core::line3d<f32> shootline, f32 d,
250 bool liquids_pointable,
251 bool look_for_object,
252 std::vector<aabb3f> &hilightboxes,
253 ClientActiveObject *&selected_object)
257 hilightboxes.clear();
258 selected_object = NULL;
260 INodeDefManager *nodedef = client->getNodeDefManager();
261 ClientMap &map = client->getEnv().getClientMap();
263 // First try to find a pointed at active object
266 selected_object = client->getSelectedActiveObject(d*BS,
267 camera_position, shootline);
269 if(selected_object != NULL)
271 if(selected_object->doShowSelectionBox())
273 aabb3f *selection_box = selected_object->getSelectionBox();
274 // Box should exist because object was
275 // returned in the first place
276 assert(selection_box);
278 v3f pos = selected_object->getPosition();
279 hilightboxes.push_back(aabb3f(
280 selection_box->MinEdge + pos,
281 selection_box->MaxEdge + pos));
285 result.type = POINTEDTHING_OBJECT;
286 result.object_id = selected_object->getId();
291 // That didn't work, try to find a pointed at node
293 f32 mindistance = BS * 1001;
295 v3s16 pos_i = floatToInt(player_position, BS);
297 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
301 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
302 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
303 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
304 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
305 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
306 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
308 // Prevent signed number overflow
316 for(s16 y = ystart; y <= yend; y++)
317 for(s16 z = zstart; z <= zend; z++)
318 for(s16 x = xstart; x <= xend; x++)
323 n = map.getNode(v3s16(x,y,z));
325 catch(InvalidPositionException &e)
329 if(!isPointableNode(n, client, liquids_pointable))
332 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
335 v3f npf = intToFloat(np, BS);
337 for(std::vector<aabb3f>::const_iterator
339 i != boxes.end(); i++)
345 for(u16 j=0; j<6; j++)
347 v3s16 facedir = g_6dirs[j];
348 aabb3f facebox = box;
352 facebox.MinEdge.X = facebox.MaxEdge.X-d;
353 else if(facedir.X < 0)
354 facebox.MaxEdge.X = facebox.MinEdge.X+d;
355 else if(facedir.Y > 0)
356 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
357 else if(facedir.Y < 0)
358 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
359 else if(facedir.Z > 0)
360 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
361 else if(facedir.Z < 0)
362 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
364 v3f centerpoint = facebox.getCenter();
365 f32 distance = (centerpoint - camera_position).getLength();
366 if(distance >= mindistance)
368 if(!facebox.intersectsWithLine(shootline))
371 v3s16 np_above = np + facedir;
373 result.type = POINTEDTHING_NODE;
374 result.node_undersurface = np;
375 result.node_abovesurface = np_above;
376 mindistance = distance;
378 hilightboxes.clear();
379 for(std::vector<aabb3f>::const_iterator
381 i2 != boxes.end(); i2++)
384 box.MinEdge += npf + v3f(-d,-d,-d);
385 box.MaxEdge += npf + v3f(d,d,d);
386 hilightboxes.push_back(box);
396 Draws a screen with a single text on it.
397 Text will be removed when the screen is drawn the next time.
399 /*gui::IGUIStaticText **/
400 void draw_load_screen(const std::wstring &text,
401 video::IVideoDriver* driver, gui::IGUIFont* font)
403 v2u32 screensize = driver->getScreenSize();
404 const wchar_t *loadingtext = text.c_str();
405 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
406 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
407 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
408 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
410 gui::IGUIStaticText *guitext = guienv->addStaticText(
411 loadingtext, textrect, false, false);
412 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
414 driver->beginScene(true, true, video::SColor(255,0,0,0));
423 /* Profiler display */
425 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
426 gui::IGUIFont *font, u32 text_height,
427 u32 show_profiler, u32 show_profiler_max)
429 if(show_profiler == 0)
431 guitext_profiler->setVisible(false);
436 std::ostringstream os(std::ios_base::binary);
437 g_profiler->printPage(os, show_profiler, show_profiler_max);
438 std::wstring text = narrow_to_wide(os.str());
439 guitext_profiler->setText(text.c_str());
440 guitext_profiler->setVisible(true);
442 s32 w = font->getDimension(text.c_str()).Width;
445 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
446 8+(text_height+5)*2 +
447 font->getDimension(text.c_str()).Height);
448 guitext_profiler->setRelativePosition(rect);
449 guitext_profiler->setVisible(true);
457 Profiler::GraphValues values;
463 Meta(float initial=0, video::SColor color=
464 video::SColor(255,255,255,255)):
470 std::list<Piece> m_log;
478 void put(const Profiler::GraphValues &values)
481 piece.values = values;
482 m_log.push_back(piece);
483 while(m_log.size() > m_log_max_size)
484 m_log.erase(m_log.begin());
487 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
488 gui::IGUIFont* font) const
490 std::map<std::string, Meta> m_meta;
491 for(std::list<Piece>::const_iterator k = m_log.begin();
492 k != m_log.end(); k++)
494 const Piece &piece = *k;
495 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
496 i != piece.values.end(); i++){
497 const std::string &id = i->first;
498 const float &value = i->second;
499 std::map<std::string, Meta>::iterator j =
501 if(j == m_meta.end()){
502 m_meta[id] = Meta(value);
505 if(value < j->second.min)
506 j->second.min = value;
507 if(value > j->second.max)
508 j->second.max = value;
513 static const video::SColor usable_colors[] = {
514 video::SColor(255,255,100,100),
515 video::SColor(255,90,225,90),
516 video::SColor(255,100,100,255),
517 video::SColor(255,255,150,50),
518 video::SColor(255,220,220,100)
520 static const u32 usable_colors_count =
521 sizeof(usable_colors) / sizeof(*usable_colors);
522 u32 next_color_i = 0;
523 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
524 i != m_meta.end(); i++){
525 Meta &meta = i->second;
526 video::SColor color(255,200,200,200);
527 if(next_color_i < usable_colors_count)
528 color = usable_colors[next_color_i++];
533 s32 textx = x_left + m_log_max_size + 15;
534 s32 textx2 = textx + 200 - 15;
538 u32 num_graphs = m_meta.size();
539 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
541 video::SColor bgcolor(120,0,0,0);
542 driver->draw2DRectangle(bgcolor, rect, NULL);
546 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
547 i != m_meta.end(); i++){
548 const std::string &id = i->first;
549 const Meta &meta = i->second;
551 s32 y = y_bottom - meta_i * 50;
552 float show_min = meta.min;
553 float show_max = meta.max;
554 if(show_min >= -0.0001 && show_max >= -0.0001){
555 if(show_min <= show_max * 0.5)
560 snprintf(buf, 10, "%.3g", show_max);
561 font->draw(narrow_to_wide(buf).c_str(),
562 core::rect<s32>(textx, y - graphh,
563 textx2, y - graphh + texth),
565 snprintf(buf, 10, "%.3g", show_min);
566 font->draw(narrow_to_wide(buf).c_str(),
567 core::rect<s32>(textx, y - texth,
570 font->draw(narrow_to_wide(id).c_str(),
571 core::rect<s32>(textx, y - graphh/2 - texth/2,
572 textx2, y - graphh/2 + texth/2),
575 s32 graph1h = graphh;
576 bool relativegraph = (show_min != 0 && show_min != show_max);
577 float lastscaledvalue = 0.0;
578 bool lastscaledvalue_exists = false;
579 for(std::list<Piece>::const_iterator j = m_log.begin();
580 j != m_log.end(); j++)
582 const Piece &piece = *j;
584 bool value_exists = false;
585 Profiler::GraphValues::const_iterator k =
586 piece.values.find(id);
587 if(k != piece.values.end()){
593 lastscaledvalue_exists = false;
596 float scaledvalue = 1.0;
597 if(show_max != show_min)
598 scaledvalue = (value - show_min) / (show_max - show_min);
599 if(scaledvalue == 1.0 && value == 0){
601 lastscaledvalue_exists = false;
605 if(lastscaledvalue_exists){
606 s32 ivalue1 = lastscaledvalue * graph1h;
607 s32 ivalue2 = scaledvalue * graph1h;
608 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
609 v2s32(x, graph1y - ivalue2), meta.color);
611 lastscaledvalue = scaledvalue;
612 lastscaledvalue_exists = true;
614 s32 ivalue = scaledvalue * graph1h;
615 driver->draw2DLine(v2s32(x, graph1y),
616 v2s32(x, graph1y - ivalue), meta.color);
625 class NodeDugEvent: public MtEvent
631 NodeDugEvent(v3s16 p, MapNode n):
635 const char* getType() const
641 ISoundManager *m_sound;
642 INodeDefManager *m_ndef;
644 float m_player_step_timer;
646 SimpleSoundSpec m_player_step_sound;
647 SimpleSoundSpec m_player_leftpunch_sound;
648 SimpleSoundSpec m_player_rightpunch_sound;
650 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
653 m_player_step_timer(0)
657 void playPlayerStep()
659 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
660 m_player_step_timer = 0.03;
661 m_sound->playSound(m_player_step_sound, false);
665 static void viewBobbingStep(MtEvent *e, void *data)
667 SoundMaker *sm = (SoundMaker*)data;
668 sm->playPlayerStep();
671 static void playerRegainGround(MtEvent *e, void *data)
673 SoundMaker *sm = (SoundMaker*)data;
674 sm->playPlayerStep();
677 static void playerJump(MtEvent *e, void *data)
679 //SoundMaker *sm = (SoundMaker*)data;
682 static void cameraPunchLeft(MtEvent *e, void *data)
684 SoundMaker *sm = (SoundMaker*)data;
685 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
688 static void cameraPunchRight(MtEvent *e, void *data)
690 SoundMaker *sm = (SoundMaker*)data;
691 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
694 static void nodeDug(MtEvent *e, void *data)
696 SoundMaker *sm = (SoundMaker*)data;
697 NodeDugEvent *nde = (NodeDugEvent*)e;
698 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
701 void registerReceiver(MtEventManager *mgr)
703 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
704 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
705 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
706 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
707 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
708 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
711 void step(float dtime)
713 m_player_step_timer -= dtime;
717 // Locally stored sounds don't need to be preloaded because of this
718 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
720 std::set<std::string> m_fetched;
723 void fetchSounds(const std::string &name,
724 std::set<std::string> &dst_paths,
725 std::set<std::string> &dst_datas)
727 if(m_fetched.count(name))
729 m_fetched.insert(name);
730 std::string base = porting::path_share + DIR_DELIM + "testsounds";
731 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
732 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
733 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
734 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
735 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
736 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
737 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
738 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
739 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
740 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
741 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
745 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
748 bool *m_force_fog_off;
753 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
754 f32 *fog_range, Client *client):
756 m_force_fog_off(force_fog_off),
757 m_fog_range(fog_range),
760 ~GameGlobalShaderConstantSetter() {}
762 virtual void onSetConstants(video::IMaterialRendererServices *services,
769 video::SColor bgcolor = m_sky->getBgColor();
770 video::SColorf bgcolorf(bgcolor);
771 float bgcolorfa[4] = {
777 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
780 float fog_distance = *m_fog_range;
782 fog_distance = 10000*BS;
783 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
786 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
787 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
788 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
796 IrrlichtDevice *device,
799 std::string playername,
800 std::string password,
801 std::string address, // If "", local server is used
803 std::wstring &error_message,
804 std::string configpath,
805 ChatBackend &chat_backend,
806 const SubgameSpec &gamespec, // Used for local game,
807 bool simple_singleplayer_mode
810 FormspecFormSource* current_formspec = 0;
811 video::IVideoDriver* driver = device->getVideoDriver();
812 scene::ISceneManager* smgr = device->getSceneManager();
814 // Calculate text height using the font
815 u32 text_height = font->getDimension(L"Random test string").Height;
817 v2u32 last_screensize(0,0);
818 v2u32 screensize = driver->getScreenSize();
821 Draw "Loading" screen
824 draw_load_screen(L"Loading...", driver, font);
826 // Create texture source
827 IWritableTextureSource *tsrc = createTextureSource(device);
829 // Create shader source
830 IWritableShaderSource *shsrc = createShaderSource(device);
832 // These will be filled by data received from the server
833 // Create item definition manager
834 IWritableItemDefManager *itemdef = createItemDefManager();
835 // Create node definition manager
836 IWritableNodeDefManager *nodedef = createNodeDefManager();
838 // Sound fetcher (useful when testing)
839 GameOnDemandSoundFetcher soundfetcher;
842 ISoundManager *sound = NULL;
843 bool sound_is_dummy = false;
845 if(g_settings->getBool("enable_sound")){
846 infostream<<"Attempting to use OpenAL audio"<<std::endl;
847 sound = createOpenALSoundManager(&soundfetcher);
849 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
851 infostream<<"Sound disabled."<<std::endl;
855 infostream<<"Using dummy audio."<<std::endl;
856 sound = &dummySoundManager;
857 sound_is_dummy = true;
860 Server *server = NULL;
864 EventManager eventmgr;
867 SoundMaker soundmaker(sound, nodedef);
868 soundmaker.registerReceiver(&eventmgr);
870 // Add chat log output for errors to be shown in chat
871 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
873 // Create UI for modifying quicktune values
874 QuicktuneShortcutter quicktune;
881 draw_load_screen(L"Creating server...", driver, font);
882 infostream<<"Creating server"<<std::endl;
883 server = new Server(map_dir, configpath, gamespec,
884 simple_singleplayer_mode);
888 do{ // Client scope (breakable do-while(0))
894 draw_load_screen(L"Creating client...", driver, font);
895 infostream<<"Creating client"<<std::endl;
897 MapDrawControl draw_control;
899 Client client(device, playername.c_str(), password, draw_control,
900 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
902 // Client acts as our GameDef
903 IGameDef *gamedef = &client;
905 draw_load_screen(L"Resolving address...", driver, font);
906 Address connect_address(0,0,0,0, port);
909 //connect_address.Resolve("localhost");
910 connect_address.setAddress(127,0,0,1);
912 connect_address.Resolve(address.c_str());
914 catch(ResolveError &e)
916 error_message = L"Couldn't resolve address";
917 errorstream<<wide_to_narrow(error_message)<<std::endl;
918 // Break out of client scope
923 Attempt to connect to the server
926 infostream<<"Connecting to server at ";
927 connect_address.print(&infostream);
928 infostream<<std::endl;
929 client.connect(connect_address);
932 Wait for server to accept connection
934 bool could_connect = false;
935 bool connect_aborted = false;
937 float frametime = 0.033;
938 float time_counter = 0.0;
942 // Update client and server
943 client.step(frametime);
945 server->step(frametime);
948 if(client.connectedAndInitialized()){
949 could_connect = true;
953 if(client.accessDenied()){
954 error_message = L"Access denied. Reason: "
955 +client.accessDeniedReason();
956 errorstream<<wide_to_narrow(error_message)<<std::endl;
959 if(input->wasKeyDown(EscapeKey)){
960 connect_aborted = true;
961 infostream<<"Connect aborted [Escape]"<<std::endl;
966 std::wostringstream ss;
967 ss<<L"Connecting to server... (press Escape to cancel)\n";
968 std::wstring animation = L"/-\\|";
969 ss<<animation[(int)(time_counter/0.2)%4];
970 draw_load_screen(ss.str(), driver, font);
973 sleep_ms(1000*frametime);
974 time_counter += frametime;
977 catch(con::PeerNotFoundException &e)
981 Handle failure to connect
984 if(error_message == L"" && !connect_aborted){
985 error_message = L"Connection failed";
986 errorstream<<wide_to_narrow(error_message)<<std::endl;
988 // Break out of client scope
993 Wait until content has been received
995 bool got_content = false;
996 bool content_aborted = false;
998 float frametime = 0.033;
999 float time_counter = 0.0;
1001 while(device->run())
1003 // Update client and server
1004 client.step(frametime);
1006 server->step(frametime);
1009 if(client.texturesReceived() &&
1010 client.itemdefReceived() &&
1011 client.nodedefReceived()){
1016 if(!client.connectedAndInitialized()){
1017 error_message = L"Client disconnected";
1018 errorstream<<wide_to_narrow(error_message)<<std::endl;
1021 if(input->wasKeyDown(EscapeKey)){
1022 content_aborted = true;
1023 infostream<<"Connect aborted [Escape]"<<std::endl;
1028 std::wostringstream ss;
1029 ss<<L"Waiting content... (press Escape to cancel)\n";
1031 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1032 ss<<L" Item definitions\n";
1033 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1034 ss<<L" Node definitions\n";
1035 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1038 draw_load_screen(ss.str(), driver, font);
1041 sleep_ms(1000*frametime);
1042 time_counter += frametime;
1047 if(error_message == L"" && !content_aborted){
1048 error_message = L"Something failed";
1049 errorstream<<wide_to_narrow(error_message)<<std::endl;
1051 // Break out of client scope
1056 After all content has been received:
1057 Update cached textures, meshes and materials
1059 client.afterContentReceived();
1062 Create the camera node
1064 Camera camera(smgr, draw_control, gamedef);
1065 if (!camera.successfullyCreated(error_message))
1068 f32 camera_yaw = 0; // "right/left"
1069 f32 camera_pitch = 0; // "up/down"
1075 Clouds *clouds = NULL;
1076 if(g_settings->getBool("enable_clouds"))
1078 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1086 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1092 FarMesh *farmesh = NULL;
1093 if(g_settings->getBool("enable_farmesh"))
1095 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1099 A copy of the local inventory
1101 Inventory local_inventory(itemdef);
1104 Find out size of crack animation
1106 int crack_animation_length = 5;
1108 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1109 v2u32 size = t->getOriginalSize();
1110 crack_animation_length = size.Y / size.X;
1117 // First line of debug text
1118 gui::IGUIStaticText *guitext = guienv->addStaticText(
1120 core::rect<s32>(5, 5, 795, 5+text_height),
1122 // Second line of debug text
1123 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1125 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1127 // At the middle of the screen
1128 // Object infos are shown in this
1129 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1131 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1134 // Status text (displays info when showing and hiding GUI stuff, etc.)
1135 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1137 core::rect<s32>(0,0,0,0),
1139 guitext_status->setVisible(false);
1141 std::wstring statustext;
1142 float statustext_time = 0;
1145 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1147 core::rect<s32>(0,0,0,0),
1148 //false, false); // Disable word wrap as of now
1150 // Remove stale "recent" chat messages from previous connections
1151 chat_backend.clearRecentChat();
1152 // Chat backend and console
1153 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1155 // Profiler text (size is updated when text is updated)
1156 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1158 core::rect<s32>(0,0,0,0),
1160 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1161 guitext_profiler->setVisible(false);
1164 Some statistics are collected in these
1167 u32 beginscenetime = 0;
1169 u32 endscenetime = 0;
1171 float recent_turn_speed = 0.0;
1173 ProfilerGraph graph;
1174 // Initially clear the profiler
1175 Profiler::GraphValues dummyvalues;
1176 g_profiler->graphGet(dummyvalues);
1178 float nodig_delay_timer = 0.0;
1179 float dig_time = 0.0;
1181 PointedThing pointed_old;
1182 bool digging = false;
1183 bool ldown_for_dig = false;
1185 float damage_flash = 0;
1186 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1188 float jump_timer = 0;
1189 bool reset_jump_timer = false;
1191 const float object_hit_delay = 0.2;
1192 float object_hit_delay_timer = 0.0;
1193 float time_from_last_punch = 10;
1195 float update_draw_list_timer = 0.0;
1196 v3f update_draw_list_last_cam_dir;
1198 bool invert_mouse = g_settings->getBool("invert_mouse");
1200 bool respawn_menu_active = false;
1201 bool update_wielded_item_trigger = false;
1203 bool show_hud = true;
1204 bool show_chat = true;
1205 bool force_fog_off = false;
1206 f32 fog_range = 100*BS;
1207 bool disable_camera_update = false;
1208 bool show_debug = g_settings->getBool("show_debug");
1209 bool show_profiler_graph = false;
1210 u32 show_profiler = 0;
1211 u32 show_profiler_max = 3; // Number of pages
1213 float time_of_day = 0;
1214 float time_of_day_smooth = 0;
1216 float repeat_rightclick_timer = 0;
1221 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1222 sky, &force_fog_off, &fog_range, &client));
1228 bool first_loop_after_window_activation = true;
1230 // TODO: Convert the static interval timers to these
1231 // Interval limiter for profiler
1232 IntervalLimiter m_profiler_interval;
1234 // Time is in milliseconds
1235 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1236 // NOTE: So we have to use getTime() and call run()s between them
1237 u32 lasttime = device->getTimer()->getTime();
1239 LocalPlayer* player = client.getEnv().getLocalPlayer();
1240 player->hurt_tilt_timer = 0;
1241 player->hurt_tilt_strength = 0;
1246 Hud hud(driver, guienv, font, text_height,
1247 gamedef, player, &local_inventory);
1251 if(device->run() == false || kill == true)
1254 // Time of frame without fps limit
1258 // not using getRealTime is necessary for wine
1259 u32 time = device->getTimer()->getTime();
1261 busytime_u32 = time - lasttime;
1264 busytime = busytime_u32 / 1000.0;
1267 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1269 // Necessary for device->getTimer()->getTime()
1277 float fps_max = g_settings->getFloat("fps_max");
1278 u32 frametime_min = 1000./fps_max;
1280 if(busytime_u32 < frametime_min)
1282 u32 sleeptime = frametime_min - busytime_u32;
1283 device->sleep(sleeptime);
1284 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1288 // Necessary for device->getTimer()->getTime()
1292 Time difference calculation
1294 f32 dtime; // in seconds
1296 u32 time = device->getTimer()->getTime();
1298 dtime = (time - lasttime) / 1000.0;
1303 g_profiler->graphAdd("mainloop_dtime", dtime);
1307 if(nodig_delay_timer >= 0)
1308 nodig_delay_timer -= dtime;
1309 if(object_hit_delay_timer >= 0)
1310 object_hit_delay_timer -= dtime;
1311 time_from_last_punch += dtime;
1313 g_profiler->add("Elapsed time", dtime);
1314 g_profiler->avg("FPS", 1./dtime);
1317 Time average and jitter calculation
1320 static f32 dtime_avg1 = 0.0;
1321 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1322 f32 dtime_jitter1 = dtime - dtime_avg1;
1324 static f32 dtime_jitter1_max_sample = 0.0;
1325 static f32 dtime_jitter1_max_fraction = 0.0;
1327 static f32 jitter1_max = 0.0;
1328 static f32 counter = 0.0;
1329 if(dtime_jitter1 > jitter1_max)
1330 jitter1_max = dtime_jitter1;
1335 dtime_jitter1_max_sample = jitter1_max;
1336 dtime_jitter1_max_fraction
1337 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1343 Busytime average and jitter calculation
1346 static f32 busytime_avg1 = 0.0;
1347 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1348 f32 busytime_jitter1 = busytime - busytime_avg1;
1350 static f32 busytime_jitter1_max_sample = 0.0;
1351 static f32 busytime_jitter1_min_sample = 0.0;
1353 static f32 jitter1_max = 0.0;
1354 static f32 jitter1_min = 0.0;
1355 static f32 counter = 0.0;
1356 if(busytime_jitter1 > jitter1_max)
1357 jitter1_max = busytime_jitter1;
1358 if(busytime_jitter1 < jitter1_min)
1359 jitter1_min = busytime_jitter1;
1363 busytime_jitter1_max_sample = jitter1_max;
1364 busytime_jitter1_min_sample = jitter1_min;
1371 Handle miscellaneous stuff
1374 if(client.accessDenied())
1376 error_message = L"Access denied. Reason: "
1377 +client.accessDeniedReason();
1378 errorstream<<wide_to_narrow(error_message)<<std::endl;
1382 if(g_gamecallback->disconnect_requested)
1384 g_gamecallback->disconnect_requested = false;
1388 if(g_gamecallback->changepassword_requested)
1390 (new GUIPasswordChange(guienv, guiroot, -1,
1391 &g_menumgr, &client))->drop();
1392 g_gamecallback->changepassword_requested = false;
1395 if(g_gamecallback->changevolume_requested)
1397 (new GUIVolumeChange(guienv, guiroot, -1,
1398 &g_menumgr, &client))->drop();
1399 g_gamecallback->changevolume_requested = false;
1402 /* Process TextureSource's queue */
1403 tsrc->processQueue();
1405 /* Process ItemDefManager's queue */
1406 itemdef->processQueue(gamedef);
1409 Process ShaderSource's queue
1411 shsrc->processQueue();
1416 last_screensize = screensize;
1417 screensize = driver->getScreenSize();
1418 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1419 //bool screensize_changed = screensize != last_screensize;
1422 // Update HUD values
1423 hud.screensize = screensize;
1424 hud.displaycenter = displaycenter;
1427 // Hilight boxes collected during the loop and displayed
1428 std::vector<aabb3f> hilightboxes;
1431 std::wstring infotext;
1434 Debug info for client
1437 static float counter = 0.0;
1442 client.printDebugInfo(infostream);
1449 float profiler_print_interval =
1450 g_settings->getFloat("profiler_print_interval");
1451 bool print_to_log = true;
1452 if(profiler_print_interval == 0){
1453 print_to_log = false;
1454 profiler_print_interval = 5;
1456 if(m_profiler_interval.step(dtime, profiler_print_interval))
1459 infostream<<"Profiler:"<<std::endl;
1460 g_profiler->print(infostream);
1463 update_profiler_gui(guitext_profiler, font, text_height,
1464 show_profiler, show_profiler_max);
1466 g_profiler->clear();
1470 Direct handling of user input
1473 // Reset input if window not active or some menu is active
1474 if(device->isWindowActive() == false
1475 || noMenuActive() == false
1476 || guienv->hasFocus(gui_chat_console))
1481 // Input handler step() (used by the random input generator)
1484 // Increase timer for doubleclick of "jump"
1485 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1486 jump_timer += dtime;
1489 Launch menus and trigger stuff according to keys
1491 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1493 // drop selected item
1494 IDropAction *a = new IDropAction();
1496 a->from_inv.setCurrentPlayer();
1497 a->from_list = "main";
1498 a->from_i = client.getPlayerItem();
1499 client.inventoryAction(a);
1501 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1503 infostream<<"the_game: "
1504 <<"Launching inventory"<<std::endl;
1506 GUIFormSpecMenu *menu =
1507 new GUIFormSpecMenu(device, guiroot, -1,
1511 InventoryLocation inventoryloc;
1512 inventoryloc.setCurrentPlayer();
1514 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1516 menu->setFormSpec(src->getForm(), inventoryloc);
1517 menu->setFormSource(src);
1518 menu->setTextDest(new TextDestPlayerInventory(&client));
1521 else if(input->wasKeyDown(EscapeKey))
1523 infostream<<"the_game: "
1524 <<"Launching pause menu"<<std::endl;
1525 // It will delete itself by itself
1526 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1527 &g_menumgr, simple_singleplayer_mode))->drop();
1529 // Move mouse cursor on top of the disconnect button
1530 if(simple_singleplayer_mode)
1531 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1533 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1535 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1537 TextDest *dest = new TextDestChat(&client);
1539 (new GUITextInputMenu(guienv, guiroot, -1,
1543 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1545 TextDest *dest = new TextDestChat(&client);
1547 (new GUITextInputMenu(guienv, guiroot, -1,
1551 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1553 if (!gui_chat_console->isOpenInhibited())
1555 // Open up to over half of the screen
1556 gui_chat_console->openConsole(0.6);
1557 guienv->setFocus(gui_chat_console);
1560 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1562 if(g_settings->getBool("free_move"))
1564 g_settings->set("free_move","false");
1565 statustext = L"free_move disabled";
1566 statustext_time = 0;
1570 g_settings->set("free_move","true");
1571 statustext = L"free_move enabled";
1572 statustext_time = 0;
1573 if(!client.checkPrivilege("fly"))
1574 statustext += L" (note: no 'fly' privilege)";
1577 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1579 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1581 if(g_settings->getBool("free_move"))
1583 g_settings->set("free_move","false");
1584 statustext = L"free_move disabled";
1585 statustext_time = 0;
1589 g_settings->set("free_move","true");
1590 statustext = L"free_move enabled";
1591 statustext_time = 0;
1592 if(!client.checkPrivilege("fly"))
1593 statustext += L" (note: no 'fly' privilege)";
1596 reset_jump_timer = true;
1598 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1600 if(g_settings->getBool("fast_move"))
1602 g_settings->set("fast_move","false");
1603 statustext = L"fast_move disabled";
1604 statustext_time = 0;
1608 g_settings->set("fast_move","true");
1609 statustext = L"fast_move enabled";
1610 statustext_time = 0;
1611 if(!client.checkPrivilege("fast"))
1612 statustext += L" (note: no 'fast' privilege)";
1615 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1617 if(g_settings->getBool("noclip"))
1619 g_settings->set("noclip","false");
1620 statustext = L"noclip disabled";
1621 statustext_time = 0;
1625 g_settings->set("noclip","true");
1626 statustext = L"noclip enabled";
1627 statustext_time = 0;
1628 if(!client.checkPrivilege("noclip"))
1629 statustext += L" (note: no 'noclip' privilege)";
1632 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1634 irr::video::IImage* const image = driver->createScreenShot();
1636 irr::c8 filename[256];
1637 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1638 g_settings->get("screenshot_path").c_str(),
1639 device->getTimer()->getRealTime());
1640 if (driver->writeImageToFile(image, filename)) {
1641 std::wstringstream sstr;
1642 sstr<<"Saved screenshot to '"<<filename<<"'";
1643 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1644 statustext = sstr.str();
1645 statustext_time = 0;
1647 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1652 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1654 show_hud = !show_hud;
1656 statustext = L"HUD shown";
1658 statustext = L"HUD hidden";
1659 statustext_time = 0;
1661 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1663 show_chat = !show_chat;
1665 statustext = L"Chat shown";
1667 statustext = L"Chat hidden";
1668 statustext_time = 0;
1670 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1672 force_fog_off = !force_fog_off;
1674 statustext = L"Fog disabled";
1676 statustext = L"Fog enabled";
1677 statustext_time = 0;
1679 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1681 disable_camera_update = !disable_camera_update;
1682 if(disable_camera_update)
1683 statustext = L"Camera update disabled";
1685 statustext = L"Camera update enabled";
1686 statustext_time = 0;
1688 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1690 // Initial / 3x toggle: Chat only
1691 // 1x toggle: Debug text with chat
1692 // 2x toggle: Debug text with profiler graph
1696 show_profiler_graph = false;
1697 statustext = L"Debug info shown";
1698 statustext_time = 0;
1700 else if(show_profiler_graph)
1703 show_profiler_graph = false;
1704 statustext = L"Debug info and profiler graph hidden";
1705 statustext_time = 0;
1709 show_profiler_graph = true;
1710 statustext = L"Profiler graph shown";
1711 statustext_time = 0;
1714 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1716 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1718 // FIXME: This updates the profiler with incomplete values
1719 update_profiler_gui(guitext_profiler, font, text_height,
1720 show_profiler, show_profiler_max);
1722 if(show_profiler != 0)
1724 std::wstringstream sstr;
1725 sstr<<"Profiler shown (page "<<show_profiler
1726 <<" of "<<show_profiler_max<<")";
1727 statustext = sstr.str();
1728 statustext_time = 0;
1732 statustext = L"Profiler hidden";
1733 statustext_time = 0;
1736 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1738 s16 range = g_settings->getS16("viewing_range_nodes_min");
1739 s16 range_new = range + 10;
1740 g_settings->set("viewing_range_nodes_min", itos(range_new));
1741 statustext = narrow_to_wide(
1742 "Minimum viewing range changed to "
1744 statustext_time = 0;
1746 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1748 s16 range = g_settings->getS16("viewing_range_nodes_min");
1749 s16 range_new = range - 10;
1752 g_settings->set("viewing_range_nodes_min",
1754 statustext = narrow_to_wide(
1755 "Minimum viewing range changed to "
1757 statustext_time = 0;
1761 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1763 reset_jump_timer = false;
1767 // Handle QuicktuneShortcutter
1768 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1770 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1772 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1774 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1777 std::string msg = quicktune.getMessage();
1779 statustext = narrow_to_wide(msg);
1780 statustext_time = 0;
1784 // Item selection with mouse wheel
1785 u16 new_playeritem = client.getPlayerItem();
1787 s32 wheel = input->getMouseWheel();
1788 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1789 hud.hotbar_itemcount-1);
1793 if(new_playeritem < max_item)
1800 if(new_playeritem > 0)
1803 new_playeritem = max_item;
1808 for(u16 i=0; i<10; i++)
1810 const KeyPress *kp = NumberKey + (i + 1) % 10;
1811 if(input->wasKeyDown(*kp))
1813 if(i < PLAYER_INVENTORY_SIZE && i < hud.hotbar_itemcount)
1817 infostream<<"Selected item: "
1818 <<new_playeritem<<std::endl;
1823 // Viewing range selection
1824 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1826 draw_control.range_all = !draw_control.range_all;
1827 if(draw_control.range_all)
1829 infostream<<"Enabled full viewing range"<<std::endl;
1830 statustext = L"Enabled full viewing range";
1831 statustext_time = 0;
1835 infostream<<"Disabled full viewing range"<<std::endl;
1836 statustext = L"Disabled full viewing range";
1837 statustext_time = 0;
1841 // Print debug stacks
1842 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1844 dstream<<"-----------------------------------------"
1846 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1847 dstream<<"-----------------------------------------"
1849 debug_stacks_print();
1853 Mouse and camera control
1854 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1857 float turn_amount = 0;
1858 if((device->isWindowActive() && noMenuActive()) || random_input)
1862 // Mac OSX gets upset if this is set every frame
1863 if(device->getCursorControl()->isVisible())
1864 device->getCursorControl()->setVisible(false);
1867 if(first_loop_after_window_activation){
1868 //infostream<<"window active, first loop"<<std::endl;
1869 first_loop_after_window_activation = false;
1872 s32 dx = input->getMousePos().X - displaycenter.X;
1873 s32 dy = input->getMousePos().Y - displaycenter.Y;
1876 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1878 /*const float keyspeed = 500;
1879 if(input->isKeyDown(irr::KEY_UP))
1880 dy -= dtime * keyspeed;
1881 if(input->isKeyDown(irr::KEY_DOWN))
1882 dy += dtime * keyspeed;
1883 if(input->isKeyDown(irr::KEY_LEFT))
1884 dx -= dtime * keyspeed;
1885 if(input->isKeyDown(irr::KEY_RIGHT))
1886 dx += dtime * keyspeed;*/
1890 camera_pitch += dy*d;
1891 if(camera_pitch < -89.5) camera_pitch = -89.5;
1892 if(camera_pitch > 89.5) camera_pitch = 89.5;
1894 turn_amount = v2f(dx, dy).getLength() * d;
1896 input->setMousePos(displaycenter.X, displaycenter.Y);
1899 // Mac OSX gets upset if this is set every frame
1900 if(device->getCursorControl()->isVisible() == false)
1901 device->getCursorControl()->setVisible(true);
1903 //infostream<<"window inactive"<<std::endl;
1904 first_loop_after_window_activation = true;
1906 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1907 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1910 Player speed control
1924 PlayerControl control(
1925 input->isKeyDown(getKeySetting("keymap_forward")),
1926 input->isKeyDown(getKeySetting("keymap_backward")),
1927 input->isKeyDown(getKeySetting("keymap_left")),
1928 input->isKeyDown(getKeySetting("keymap_right")),
1929 input->isKeyDown(getKeySetting("keymap_jump")),
1930 input->isKeyDown(getKeySetting("keymap_special1")),
1931 input->isKeyDown(getKeySetting("keymap_sneak")),
1932 input->getLeftState(),
1933 input->getRightState(),
1937 client.setPlayerControl(control);
1939 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
1940 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
1941 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
1942 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
1943 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
1944 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
1945 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
1946 128*(int)input->getLeftState()+
1947 256*(int)input->getRightState();
1948 LocalPlayer* player = client.getEnv().getLocalPlayer();
1949 player->keyPressed=keyPressed;
1958 //TimeTaker timer("server->step(dtime)");
1959 server->step(dtime);
1967 //TimeTaker timer("client.step(dtime)");
1969 //client.step(dtime_avg1);
1973 // Read client events
1976 ClientEvent event = client.getClientEvent();
1977 if(event.type == CE_NONE)
1981 else if(event.type == CE_PLAYER_DAMAGE &&
1982 client.getHP() != 0)
1984 //u16 damage = event.player_damage.amount;
1985 //infostream<<"Player damage: "<<damage<<std::endl;
1987 damage_flash += 100.0;
1988 damage_flash += 8.0 * event.player_damage.amount;
1990 player->hurt_tilt_timer = 1.5;
1991 player->hurt_tilt_strength = event.player_damage.amount/2;
1992 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
1994 else if(event.type == CE_PLAYER_FORCE_MOVE)
1996 camera_yaw = event.player_force_move.yaw;
1997 camera_pitch = event.player_force_move.pitch;
1999 else if(event.type == CE_DEATHSCREEN)
2001 if(respawn_menu_active)
2004 /*bool set_camera_point_target =
2005 event.deathscreen.set_camera_point_target;
2006 v3f camera_point_target;
2007 camera_point_target.X = event.deathscreen.camera_point_target_x;
2008 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2009 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2010 MainRespawnInitiator *respawner =
2011 new MainRespawnInitiator(
2012 &respawn_menu_active, &client);
2013 GUIDeathScreen *menu =
2014 new GUIDeathScreen(guienv, guiroot, -1,
2015 &g_menumgr, respawner);
2018 chat_backend.addMessage(L"", L"You died.");
2020 /* Handle visualization */
2024 LocalPlayer* player = client.getEnv().getLocalPlayer();
2025 player->hurt_tilt_timer = 0;
2026 player->hurt_tilt_strength = 0;
2028 /*LocalPlayer* player = client.getLocalPlayer();
2029 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2030 camera.update(player, busytime, screensize);*/
2032 else if (event.type == CE_SHOW_FORMSPEC)
2034 if (current_formspec == 0)
2037 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2039 GUIFormSpecMenu *menu =
2040 new GUIFormSpecMenu(device, guiroot, -1,
2043 menu->setFormSource(current_formspec);
2044 menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
2050 current_formspec->setForm(*(event.show_formspec.formspec));
2052 delete(event.show_formspec.formspec);
2053 delete(event.show_formspec.formname);
2055 else if(event.type == CE_TEXTURES_UPDATED)
2057 update_wielded_item_trigger = true;
2059 else if(event.type == CE_SPAWN_PARTICLE)
2061 LocalPlayer* player = client.getEnv().getLocalPlayer();
2063 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2065 new Particle(gamedef, smgr, player, client.getEnv(),
2066 *event.spawn_particle.pos,
2067 *event.spawn_particle.vel,
2068 *event.spawn_particle.acc,
2069 event.spawn_particle.expirationtime,
2070 event.spawn_particle.size,
2071 event.spawn_particle.collisiondetection, ap);
2073 else if(event.type == CE_ADD_PARTICLESPAWNER)
2075 LocalPlayer* player = client.getEnv().getLocalPlayer();
2077 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2079 new ParticleSpawner(gamedef, smgr, player,
2080 event.add_particlespawner.amount,
2081 event.add_particlespawner.spawntime,
2082 *event.add_particlespawner.minpos,
2083 *event.add_particlespawner.maxpos,
2084 *event.add_particlespawner.minvel,
2085 *event.add_particlespawner.maxvel,
2086 *event.add_particlespawner.minacc,
2087 *event.add_particlespawner.maxacc,
2088 event.add_particlespawner.minexptime,
2089 event.add_particlespawner.maxexptime,
2090 event.add_particlespawner.minsize,
2091 event.add_particlespawner.maxsize,
2092 event.add_particlespawner.collisiondetection,
2094 event.add_particlespawner.id);
2096 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2098 delete_particlespawner (event.delete_particlespawner.id);
2100 else if (event.type == CE_HUDADD)
2102 u32 id = event.hudadd.id;
2103 size_t nhudelem = player->hud.size();
2104 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2105 delete event.hudadd.pos;
2106 delete event.hudadd.name;
2107 delete event.hudadd.scale;
2108 delete event.hudadd.text;
2112 HudElement *e = new HudElement;
2113 e->type = (HudElementType)event.hudadd.type;
2114 e->pos = *event.hudadd.pos;
2115 e->name = *event.hudadd.name;
2116 e->scale = *event.hudadd.scale;
2117 e->text = *event.hudadd.text;
2118 e->number = event.hudadd.number;
2119 e->item = event.hudadd.item;
2120 e->dir = event.hudadd.dir;
2123 player->hud.push_back(e);
2125 player->hud[id] = e;
2127 delete event.hudadd.pos;
2128 delete event.hudadd.name;
2129 delete event.hudadd.scale;
2130 delete event.hudadd.text;
2132 else if (event.type == CE_HUDRM)
2134 u32 id = event.hudrm.id;
2135 if (id < player->hud.size() && player->hud[id]) {
2136 delete player->hud[id];
2137 player->hud[id] = NULL;
2140 else if (event.type == CE_HUDCHANGE)
2142 u32 id = event.hudchange.id;
2143 if (id >= player->hud.size() || !player->hud[id]) {
2144 delete event.hudchange.v2fdata;
2145 delete event.hudchange.sdata;
2149 HudElement* e = player->hud[id];
2150 switch (event.hudchange.stat) {
2152 e->pos = *event.hudchange.v2fdata;
2155 e->name = *event.hudchange.sdata;
2157 case HUD_STAT_SCALE:
2158 e->scale = *event.hudchange.v2fdata;
2161 e->text = *event.hudchange.sdata;
2163 case HUD_STAT_NUMBER:
2164 e->number = event.hudchange.data;
2167 e->item = event.hudchange.data;
2170 e->dir = event.hudchange.data;
2174 delete event.hudchange.v2fdata;
2175 delete event.hudchange.sdata;
2180 //TimeTaker //timer2("//timer2");
2183 For interaction purposes, get info about the held item
2185 - Is it a usable item?
2186 - Can it point to liquids?
2188 ItemStack playeritem;
2189 bool playeritem_usable = false;
2190 bool playeritem_liquids_pointable = false;
2192 InventoryList *mlist = local_inventory.getList("main");
2195 playeritem = mlist->getItem(client.getPlayerItem());
2196 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2197 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2200 ToolCapabilities playeritem_toolcap =
2201 playeritem.getToolCapabilities(itemdef);
2207 LocalPlayer* player = client.getEnv().getLocalPlayer();
2208 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2209 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2210 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2211 camera.update(player, busytime, screensize, tool_reload_ratio);
2214 v3f player_position = player->getPosition();
2215 v3f camera_position = camera.getPosition();
2216 v3f camera_direction = camera.getDirection();
2217 f32 camera_fov = camera.getFovMax();
2219 if(!disable_camera_update){
2220 client.getEnv().getClientMap().updateCamera(camera_position,
2221 camera_direction, camera_fov);
2224 // Update sound listener
2225 sound->updateListener(camera.getCameraNode()->getPosition(),
2226 v3f(0,0,0), // velocity
2227 camera.getDirection(),
2228 camera.getCameraNode()->getUpVector());
2229 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2235 soundmaker.step(dtime);
2237 ClientMap &map = client.getEnv().getClientMap();
2238 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2239 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2243 Calculate what block is the crosshair pointing to
2246 //u32 t1 = device->getTimer()->getRealTime();
2248 f32 d = 4; // max. distance
2249 core::line3d<f32> shootline(camera_position,
2250 camera_position + camera_direction * BS * (d+1));
2252 ClientActiveObject *selected_object = NULL;
2254 PointedThing pointed = getPointedThing(
2256 &client, player_position, camera_direction,
2257 camera_position, shootline, d,
2258 playeritem_liquids_pointable, !ldown_for_dig,
2263 if(pointed != pointed_old)
2265 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2266 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2271 - releasing left mouse button
2272 - pointing away from node
2276 if(input->getLeftReleased())
2278 infostream<<"Left button released"
2279 <<" (stopped digging)"<<std::endl;
2282 else if(pointed != pointed_old)
2284 if (pointed.type == POINTEDTHING_NODE
2285 && pointed_old.type == POINTEDTHING_NODE
2286 && pointed.node_undersurface == pointed_old.node_undersurface)
2288 // Still pointing to the same node,
2289 // but a different face. Don't reset.
2293 infostream<<"Pointing away from node"
2294 <<" (stopped digging)"<<std::endl;
2300 client.interact(1, pointed_old);
2301 client.setCrack(-1, v3s16(0,0,0));
2305 if(!digging && ldown_for_dig && !input->getLeftState())
2307 ldown_for_dig = false;
2310 bool left_punch = false;
2311 soundmaker.m_player_leftpunch_sound.name = "";
2313 if(input->getRightState())
2314 repeat_rightclick_timer += dtime;
2316 repeat_rightclick_timer = 0;
2318 if(playeritem_usable && input->getLeftState())
2320 if(input->getLeftClicked())
2321 client.interact(4, pointed);
2323 else if(pointed.type == POINTEDTHING_NODE)
2325 v3s16 nodepos = pointed.node_undersurface;
2326 v3s16 neighbourpos = pointed.node_abovesurface;
2329 Check information text of node
2332 ClientMap &map = client.getEnv().getClientMap();
2333 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2335 infotext = narrow_to_wide(meta->getString("infotext"));
2337 MapNode n = map.getNode(nodepos);
2338 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2339 infotext = L"Unknown node: ";
2340 infotext += narrow_to_wide(nodedef->get(n).name);
2348 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2352 infostream<<"Started digging"<<std::endl;
2353 client.interact(0, pointed);
2355 ldown_for_dig = true;
2357 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2359 // NOTE: Similar piece of code exists on the server side for
2361 // Get digging parameters
2362 DigParams params = getDigParams(nodedef->get(n).groups,
2363 &playeritem_toolcap);
2364 // If can't dig, try hand
2365 if(!params.diggable){
2366 const ItemDefinition &hand = itemdef->get("");
2367 const ToolCapabilities *tp = hand.tool_capabilities;
2369 params = getDigParams(nodedef->get(n).groups, tp);
2372 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2373 if(sound_dig.exists()){
2374 if(sound_dig.name == "__group"){
2375 if(params.main_group != ""){
2376 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2377 soundmaker.m_player_leftpunch_sound.name =
2378 std::string("default_dig_") +
2382 soundmaker.m_player_leftpunch_sound = sound_dig;
2386 float dig_time_complete = 0.0;
2388 if(params.diggable == false)
2390 // I guess nobody will wait for this long
2391 dig_time_complete = 10000000.0;
2395 dig_time_complete = params.time;
2396 if (g_settings->getBool("enable_particles"))
2398 const ContentFeatures &features =
2399 client.getNodeDefManager()->get(n);
2400 addPunchingParticles
2401 (gamedef, smgr, player, client.getEnv(),
2402 nodepos, features.tiles);
2406 if(dig_time_complete >= 0.001)
2408 dig_index = (u16)((float)crack_animation_length
2409 * dig_time/dig_time_complete);
2411 // This is for torches
2414 dig_index = crack_animation_length;
2417 // Don't show cracks if not diggable
2418 if(dig_time_complete >= 100000.0)
2421 else if(dig_index < crack_animation_length)
2423 //TimeTaker timer("client.setTempMod");
2424 //infostream<<"dig_index="<<dig_index<<std::endl;
2425 client.setCrack(dig_index, nodepos);
2429 infostream<<"Digging completed"<<std::endl;
2430 client.interact(2, pointed);
2431 client.setCrack(-1, v3s16(0,0,0));
2432 MapNode wasnode = map.getNode(nodepos);
2433 client.removeNode(nodepos);
2435 if (g_settings->getBool("enable_particles"))
2437 const ContentFeatures &features =
2438 client.getNodeDefManager()->get(wasnode);
2440 (gamedef, smgr, player, client.getEnv(),
2441 nodepos, features.tiles);
2447 nodig_delay_timer = dig_time_complete
2448 / (float)crack_animation_length;
2450 // We don't want a corresponding delay to
2451 // very time consuming nodes
2452 if(nodig_delay_timer > 0.3)
2453 nodig_delay_timer = 0.3;
2454 // We want a slight delay to very little
2455 // time consuming nodes
2456 float mindelay = 0.15;
2457 if(nodig_delay_timer < mindelay)
2458 nodig_delay_timer = mindelay;
2460 // Send event to trigger sound
2461 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2462 gamedef->event()->put(e);
2467 camera.setDigging(0); // left click animation
2470 if(input->getRightClicked() ||
2471 repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2473 repeat_rightclick_timer = 0;
2474 infostream<<"Ground right-clicked"<<std::endl;
2476 // Sign special case, at least until formspec is properly implemented.
2478 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2480 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2482 infostream<<"Launching metadata text input"<<std::endl;
2484 // Get a new text for it
2486 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2488 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2490 (new GUITextInputMenu(guienv, guiroot, -1,
2494 // If metadata provides an inventory view, activate it
2495 else if(meta && meta->getString("formspec") != "" && !random_input
2496 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2498 infostream<<"Launching custom inventory view"<<std::endl;
2500 InventoryLocation inventoryloc;
2501 inventoryloc.setNodeMeta(nodepos);
2505 GUIFormSpecMenu *menu =
2506 new GUIFormSpecMenu(device, guiroot, -1,
2509 menu->setFormSpec(meta->getString("formspec"),
2511 menu->setFormSource(new NodeMetadataFormSource(
2512 &client.getEnv().getClientMap(), nodepos));
2513 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2516 // Otherwise report right click to server
2520 client.interact(3, pointed);
2521 camera.setDigging(1); // right click animation
2523 // If the wielded item has node placement prediction,
2525 const ItemDefinition &def =
2526 playeritem.getDefinition(itemdef);
2527 if(def.node_placement_prediction != ""
2528 && !nodedef->get(map.getNode(nodepos)).rightclickable)
2530 verbosestream<<"Node placement prediction for "
2531 <<playeritem.name<<" is "
2532 <<def.node_placement_prediction<<std::endl;
2533 v3s16 p = neighbourpos;
2534 // Place inside node itself if buildable_to
2536 MapNode n_under = map.getNode(nodepos);
2537 if(nodedef->get(n_under).buildable_to)
2539 }catch(InvalidPositionException &e){}
2540 // Find id of predicted node
2543 nodedef->getId(def.node_placement_prediction, id);
2545 errorstream<<"Node placement prediction failed for "
2546 <<playeritem.name<<" (places "
2547 <<def.node_placement_prediction
2548 <<") - Name not known"<<std::endl;
2553 // This triggers the required mesh update too
2554 client.addNode(p, n);
2555 }catch(InvalidPositionException &e){
2556 errorstream<<"Node placement prediction failed for "
2557 <<playeritem.name<<" (places "
2558 <<def.node_placement_prediction
2559 <<") - Position not loaded"<<std::endl;
2564 soundmaker.m_player_rightpunch_sound = def.sound_place;
2568 else if(pointed.type == POINTEDTHING_OBJECT)
2570 infotext = narrow_to_wide(selected_object->infoText());
2572 if(infotext == L"" && show_debug){
2573 infotext = narrow_to_wide(selected_object->debugInfoText());
2576 //if(input->getLeftClicked())
2577 if(input->getLeftState())
2579 bool do_punch = false;
2580 bool do_punch_damage = false;
2581 if(object_hit_delay_timer <= 0.0){
2583 do_punch_damage = true;
2584 object_hit_delay_timer = object_hit_delay;
2586 if(input->getLeftClicked()){
2590 infostream<<"Left-clicked object"<<std::endl;
2593 if(do_punch_damage){
2594 // Report direct punch
2595 v3f objpos = selected_object->getPosition();
2596 v3f dir = (objpos - player_position).normalize();
2598 bool disable_send = selected_object->directReportPunch(
2599 dir, &playeritem, time_from_last_punch);
2600 time_from_last_punch = 0;
2602 client.interact(0, pointed);
2605 else if(input->getRightClicked())
2607 infostream<<"Right-clicked object"<<std::endl;
2608 client.interact(3, pointed); // place
2611 else if(input->getLeftState())
2613 // When button is held down in air, show continuous animation
2617 pointed_old = pointed;
2619 if(left_punch || input->getLeftClicked())
2621 camera.setDigging(0); // left click animation
2624 input->resetLeftClicked();
2625 input->resetRightClicked();
2627 input->resetLeftReleased();
2628 input->resetRightReleased();
2631 Calculate stuff for drawing
2640 fog_range = BS*farmesh_range;
2644 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2646 if(draw_control.range_all)
2647 fog_range = 100000*BS;
2651 Calculate general brightness
2653 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2654 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2655 float direct_brightness = 0;
2656 bool sunlight_seen = false;
2657 if(g_settings->getBool("free_move")){
2658 direct_brightness = time_brightness;
2659 sunlight_seen = true;
2661 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2662 float old_brightness = sky->getBrightness();
2663 direct_brightness = (float)client.getEnv().getClientMap()
2664 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2665 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2669 time_of_day = client.getEnv().getTimeOfDayF();
2671 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2672 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2673 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2674 time_of_day_smooth = time_of_day;
2676 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2677 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2678 + (time_of_day+1.0) * todsm;
2680 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2681 + time_of_day * todsm;
2683 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2686 float brightness = sky->getBrightness();
2687 video::SColor bgcolor = sky->getBgColor();
2688 video::SColor skycolor = sky->getSkyColor();
2694 if(sky->getCloudsVisible()){
2695 clouds->setVisible(true);
2696 clouds->step(dtime);
2697 clouds->update(v2f(player_position.X, player_position.Z),
2698 sky->getCloudColor());
2700 clouds->setVisible(false);
2709 farmesh_range = draw_control.wanted_range * 10;
2710 if(draw_control.range_all && farmesh_range < 500)
2711 farmesh_range = 500;
2712 if(farmesh_range > 1000)
2713 farmesh_range = 1000;
2715 farmesh->step(dtime);
2716 farmesh->update(v2f(player_position.X, player_position.Z),
2717 brightness, farmesh_range);
2724 allparticles_step(dtime, client.getEnv());
2725 allparticlespawners_step(dtime, client.getEnv());
2731 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2735 video::EFT_FOG_LINEAR,
2747 video::EFT_FOG_LINEAR,
2757 Update gui stuff (0ms)
2760 //TimeTaker guiupdatetimer("Gui updating");
2762 const char program_name_and_version[] =
2763 "Minetest " VERSION_STRING;
2767 static float drawtime_avg = 0;
2768 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2769 /*static float beginscenetime_avg = 0;
2770 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2771 static float scenetime_avg = 0;
2772 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2773 static float endscenetime_avg = 0;
2774 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2777 snprintf(temptext, 300, "%s ("
2780 " drawtime=%.0f, dtime_jitter = % .1f %%"
2781 ", v_range = %.1f, RTT = %.3f",
2782 program_name_and_version,
2783 draw_control.range_all,
2785 dtime_jitter1_max_fraction * 100.0,
2786 draw_control.wanted_range,
2790 guitext->setText(narrow_to_wide(temptext).c_str());
2791 guitext->setVisible(true);
2793 else if(show_hud || show_chat)
2795 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2796 guitext->setVisible(true);
2800 guitext->setVisible(false);
2806 snprintf(temptext, 300,
2807 "(% .1f, % .1f, % .1f)"
2808 " (yaw = %.1f) (seed = %llu)",
2809 player_position.X/BS,
2810 player_position.Y/BS,
2811 player_position.Z/BS,
2812 wrapDegrees_0_360(camera_yaw),
2813 (unsigned long long)client.getMapSeed());
2815 guitext2->setText(narrow_to_wide(temptext).c_str());
2816 guitext2->setVisible(true);
2820 guitext2->setVisible(false);
2824 guitext_info->setText(infotext.c_str());
2825 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2829 float statustext_time_max = 1.5;
2830 if(!statustext.empty())
2832 statustext_time += dtime;
2833 if(statustext_time >= statustext_time_max)
2836 statustext_time = 0;
2839 guitext_status->setText(statustext.c_str());
2840 guitext_status->setVisible(!statustext.empty());
2842 if(!statustext.empty())
2844 s32 status_y = screensize.Y - 130;
2845 core::rect<s32> rect(
2847 status_y - guitext_status->getTextHeight(),
2851 guitext_status->setRelativePosition(rect);
2854 video::SColor initial_color(255,0,0,0);
2855 if(guienv->getSkin())
2856 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2857 video::SColor final_color = initial_color;
2858 final_color.setAlpha(0);
2859 video::SColor fade_color =
2860 initial_color.getInterpolated_quadratic(
2863 pow(statustext_time / (float)statustext_time_max, 2.0f));
2864 guitext_status->setOverrideColor(fade_color);
2865 guitext_status->enableOverrideColor(true);
2870 Get chat messages from client
2873 // Get new messages from error log buffer
2874 while(!chat_log_error_buf.empty())
2876 chat_backend.addMessage(L"", narrow_to_wide(
2877 chat_log_error_buf.get()));
2879 // Get new messages from client
2880 std::wstring message;
2881 while(client.getChatMessage(message))
2883 chat_backend.addUnparsedMessage(message);
2885 // Remove old messages
2886 chat_backend.step(dtime);
2888 // Display all messages in a static text element
2889 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2890 std::wstring recent_chat = chat_backend.getRecentChat();
2891 guitext_chat->setText(recent_chat.c_str());
2893 // Update gui element size and position
2894 s32 chat_y = 5+(text_height+5);
2896 chat_y += (text_height+5);
2897 core::rect<s32> rect(
2901 chat_y + guitext_chat->getTextHeight()
2903 guitext_chat->setRelativePosition(rect);
2905 // Don't show chat if disabled or empty or profiler is enabled
2906 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2914 if(client.getPlayerItem() != new_playeritem)
2916 client.selectPlayerItem(new_playeritem);
2918 if(client.getLocalInventoryUpdated())
2920 //infostream<<"Updating local inventory"<<std::endl;
2921 client.getLocalInventory(local_inventory);
2923 update_wielded_item_trigger = true;
2925 if(update_wielded_item_trigger)
2927 update_wielded_item_trigger = false;
2928 // Update wielded tool
2929 InventoryList *mlist = local_inventory.getList("main");
2932 item = mlist->getItem(client.getPlayerItem());
2937 Update block draw list every 200ms or when camera direction has
2940 update_draw_list_timer += dtime;
2941 if(update_draw_list_timer >= 0.2 ||
2942 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2943 update_draw_list_timer = 0;
2944 client.getEnv().getClientMap().updateDrawList(driver);
2945 update_draw_list_last_cam_dir = camera_direction;
2952 TimeTaker tt_draw("mainloop: draw");
2955 TimeTaker timer("beginScene");
2956 //driver->beginScene(false, true, bgcolor);
2957 //driver->beginScene(true, true, bgcolor);
2958 driver->beginScene(true, true, skycolor);
2959 beginscenetime = timer.stop(true);
2964 //infostream<<"smgr->drawAll()"<<std::endl;
2966 TimeTaker timer("smgr");
2969 if(g_settings->getBool("anaglyph"))
2971 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
2972 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
2974 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
2976 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
2977 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
2978 camera.getCameraNode()->getAbsolutePosition() ;
2981 irr::core::vector3df leftEye;
2982 irr::core::matrix4 leftMove;
2984 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2985 leftEye=(startMatrix*leftMove).getTranslation();
2987 //clear the depth buffer, and color
2988 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
2990 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
2991 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
2992 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2993 irr::scene::ESNRP_SOLID +
2994 irr::scene::ESNRP_TRANSPARENT +
2995 irr::scene::ESNRP_TRANSPARENT_EFFECT +
2996 irr::scene::ESNRP_SHADOW;
2998 camera.getCameraNode()->setPosition( leftEye );
2999 camera.getCameraNode()->setTarget( focusPoint );
3001 smgr->drawAll(); // 'smgr->drawAll();' may go here
3005 irr::core::vector3df rightEye;
3006 irr::core::matrix4 rightMove;
3008 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3009 rightEye=(startMatrix*rightMove).getTranslation();
3011 //clear the depth buffer
3012 driver->clearZBuffer();
3014 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3015 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3016 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3017 irr::scene::ESNRP_SOLID +
3018 irr::scene::ESNRP_TRANSPARENT +
3019 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3020 irr::scene::ESNRP_SHADOW;
3022 camera.getCameraNode()->setPosition( rightEye );
3023 camera.getCameraNode()->setTarget( focusPoint );
3025 smgr->drawAll(); // 'smgr->drawAll();' may go here
3028 //driver->endScene();
3030 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3031 driver->getOverrideMaterial().EnableFlags=0;
3032 driver->getOverrideMaterial().EnablePasses=0;
3034 camera.getCameraNode()->setPosition( oldPosition );
3035 camera.getCameraNode()->setTarget( oldTarget );
3038 scenetime = timer.stop(true);
3042 //TimeTaker timer9("auxiliary drawings");
3046 //TimeTaker //timer10("//timer10");
3052 driver->setMaterial(m);
3054 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3057 hud.drawSelectionBoxes(hilightboxes);
3063 // Warning: This clears the Z buffer.
3064 camera.drawWieldedTool();
3071 client.getEnv().getClientMap().renderPostFx();
3077 if(show_profiler_graph)
3079 graph.draw(10, screensize.Y - 10, driver, font);
3086 hud.drawCrosshair();
3091 //TimeTaker //timer11("//timer11");
3099 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3100 client.getHP(), client.getPlayerItem());
3106 if(damage_flash > 0.0)
3108 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3109 driver->draw2DRectangle(color,
3110 core::rect<s32>(0,0,screensize.X,screensize.Y),
3113 damage_flash -= 100.0*dtime;
3119 if(player->hurt_tilt_timer > 0.0)
3121 player->hurt_tilt_timer -= dtime*5;
3122 if(player->hurt_tilt_timer < 0)
3123 player->hurt_tilt_strength = 0;
3130 hud.drawLuaElements();
3142 TimeTaker timer("endScene");
3144 endscenetime = timer.stop(true);
3147 drawtime = tt_draw.stop(true);
3148 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3154 static s16 lastFPS = 0;
3155 //u16 fps = driver->getFPS();
3156 u16 fps = (1.0/dtime_avg1);
3160 core::stringw str = L"Minetest [";
3161 str += driver->getName();
3165 device->setWindowCaption(str.c_str());
3170 Log times and stuff for visualization
3172 Profiler::GraphValues values;
3173 g_profiler->graphGet(values);
3182 if (gui_chat_console)
3183 gui_chat_console->drop();
3187 Draw a "shutting down" screen, which will be shown while the map
3188 generator and other stuff quits
3191 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3192 draw_load_screen(L"Shutting down stuff...", driver, font);
3193 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3196 gui_shuttingdowntext->remove();*/
3199 chat_backend.addMessage(L"", L"# Disconnected.");
3200 chat_backend.addMessage(L"", L"");
3202 // Client scope (client is destructed before destructing *def and tsrc)
3205 catch(SerializationError &e)
3207 error_message = L"A serialization error occurred:\n"
3208 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3209 L" running a different version of Minetest.";
3210 errorstream<<wide_to_narrow(error_message)<<std::endl;
3212 catch(ServerError &e)
3214 error_message = narrow_to_wide(e.what());
3215 errorstream<<wide_to_narrow(error_message)<<std::endl;
3219 errorstream<<e.what()<<std::endl;
3220 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3228 //has to be deleted first to stop all server threads
3236 //extended resource accounting
3237 infostream << "Irrlicht resources after cleanup:" << std::endl;
3238 infostream << "\tRemaining meshes : "
3239 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3240 infostream << "\tRemaining textures : "
3241 << driver->getTextureCount() << std::endl;
3242 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3243 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3244 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3247 infostream << "\tRemaining materials: "
3248 << driver-> getMaterialRendererCount ()
3249 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;