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 "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiFormSpecMenu.h"
35 #include "guiChatConsole.h"
39 #include "particles.h"
44 #include "mainmenumanager.h"
48 // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "main.h" // For g_settings
53 #include "tile.h" // For TextureSource
54 #include "shader.h" // For ShaderSource
55 #include "logoutputbuffer.h"
57 #include "quicktune_shortcutter.h"
58 #include "clientmap.h"
63 #include "sound_openal.h"
65 #include "event_manager.h"
68 #include "util/directiontables.h"
69 #include "util/pointedthing.h"
70 #include "drawscene.h"
71 #include "content_cao.h"
73 #ifdef HAVE_TOUCHSCREENGUI
74 #include "touchscreengui.h"
81 struct TextDestNodeMetadata : public TextDest
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(std::wstring text)
91 std::string ntext = wide_to_narrow(text);
92 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
93 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
94 std::map<std::string, std::string> fields;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(std::map<std::string, std::string> fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest
109 TextDestPlayerInventory(Client *client)
114 TextDestPlayerInventory(Client *client, std::string formname)
117 m_formname = formname;
119 void gotText(std::map<std::string, std::string> fields)
121 m_client->sendInventoryFields(m_formname, fields);
127 struct LocalFormspecHandler : public TextDest
129 LocalFormspecHandler();
130 LocalFormspecHandler(std::string formname) :
133 m_formname = formname;
136 LocalFormspecHandler(std::string formname, Client *client) :
139 m_formname = formname;
142 void gotText(std::wstring message) {
143 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
146 void gotText(std::map<std::string, std::string> fields)
148 if (m_formname == "MT_PAUSE_MENU") {
149 if (fields.find("btn_sound") != fields.end()) {
150 g_gamecallback->changeVolume();
154 if (fields.find("btn_exit_menu") != fields.end()) {
155 g_gamecallback->disconnect();
159 if (fields.find("btn_exit_os") != fields.end()) {
160 g_gamecallback->exitToOS();
164 if (fields.find("btn_change_password") != fields.end()) {
165 g_gamecallback->changePassword();
169 if (fields.find("quit") != fields.end()) {
173 if (fields.find("btn_continue") != fields.end()) {
177 if (m_formname == "MT_CHAT_MENU") {
178 assert(m_client != 0);
179 if ((fields.find("btn_send") != fields.end()) ||
180 (fields.find("quit") != fields.end())) {
181 if (fields.find("f_text") != fields.end()) {
182 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
188 if (m_formname == "MT_DEATH_SCREEN") {
189 assert(m_client != 0);
190 if ((fields.find("btn_respawn") != fields.end())) {
191 m_client->sendRespawn();
195 if (fields.find("quit") != fields.end()) {
196 m_client->sendRespawn();
201 // don't show error message for unhandled cursor keys
202 if ( (fields.find("key_up") != fields.end()) ||
203 (fields.find("key_down") != fields.end()) ||
204 (fields.find("key_left") != fields.end()) ||
205 (fields.find("key_right") != fields.end())) {
209 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
211 for (std::map<std::string,std::string>::iterator iter = fields.begin();
212 iter != fields.end(); iter++) {
213 errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
221 /* Form update callback */
223 class NodeMetadataFormSource: public IFormSource
226 NodeMetadataFormSource(ClientMap *map, v3s16 p):
231 std::string getForm()
233 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
236 return meta->getString("formspec");
238 std::string resolveText(std::string str)
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
243 return meta->resolveString(str);
250 class PlayerInventoryFormSource: public IFormSource
253 PlayerInventoryFormSource(Client *client):
257 std::string getForm()
259 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
260 return player->inventory_formspec;
267 Check if a node is pointable
269 inline bool isPointableNode(const MapNode& n,
270 Client *client, bool liquids_pointable)
272 const ContentFeatures &features = client->getNodeDefManager()->get(n);
273 return features.pointable ||
274 (liquids_pointable && features.isLiquid());
278 Find what the player is pointing at
280 PointedThing getPointedThing(Client *client, v3f player_position,
281 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
282 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
283 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
287 hilightboxes.clear();
288 selected_object = NULL;
290 INodeDefManager *nodedef = client->getNodeDefManager();
291 ClientMap &map = client->getEnv().getClientMap();
293 f32 mindistance = BS * 1001;
295 // First try to find a pointed at active object
298 selected_object = client->getSelectedActiveObject(d*BS,
299 camera_position, shootline);
301 if(selected_object != NULL)
303 if(selected_object->doShowSelectionBox())
305 aabb3f *selection_box = selected_object->getSelectionBox();
306 // Box should exist because object was
307 // returned in the first place
308 assert(selection_box);
310 v3f pos = selected_object->getPosition();
311 hilightboxes.push_back(aabb3f(
312 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
313 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
316 mindistance = (selected_object->getPosition() - camera_position).getLength();
318 result.type = POINTEDTHING_OBJECT;
319 result.object_id = selected_object->getId();
323 // That didn't work, try to find a pointed at node
326 v3s16 pos_i = floatToInt(player_position, BS);
328 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
332 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
333 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
334 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
335 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
336 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
337 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
339 // Prevent signed number overflow
347 for(s16 y = ystart; y <= yend; y++)
348 for(s16 z = zstart; z <= zend; z++)
349 for(s16 x = xstart; x <= xend; x++)
354 n = map.getNode(v3s16(x,y,z));
356 catch(InvalidPositionException &e)
360 if(!isPointableNode(n, client, liquids_pointable))
363 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
366 v3f npf = intToFloat(np, BS);
368 for(std::vector<aabb3f>::const_iterator
370 i != boxes.end(); i++)
376 for(u16 j=0; j<6; j++)
378 v3s16 facedir = g_6dirs[j];
379 aabb3f facebox = box;
383 facebox.MinEdge.X = facebox.MaxEdge.X-d;
384 else if(facedir.X < 0)
385 facebox.MaxEdge.X = facebox.MinEdge.X+d;
386 else if(facedir.Y > 0)
387 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
388 else if(facedir.Y < 0)
389 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
390 else if(facedir.Z > 0)
391 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
392 else if(facedir.Z < 0)
393 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
395 v3f centerpoint = facebox.getCenter();
396 f32 distance = (centerpoint - camera_position).getLength();
397 if(distance >= mindistance)
399 if(!facebox.intersectsWithLine(shootline))
402 v3s16 np_above = np + facedir;
404 result.type = POINTEDTHING_NODE;
405 result.node_undersurface = np;
406 result.node_abovesurface = np_above;
407 mindistance = distance;
409 hilightboxes.clear();
410 for(std::vector<aabb3f>::const_iterator
412 i2 != boxes.end(); i2++)
415 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
416 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
417 hilightboxes.push_back(box);
426 /* Profiler display */
428 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
429 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
430 u32 show_profiler_max)
432 if(show_profiler == 0)
434 guitext_profiler->setVisible(false);
439 std::ostringstream os(std::ios_base::binary);
440 g_profiler->printPage(os, show_profiler, show_profiler_max);
441 std::wstring text = narrow_to_wide(os.str());
442 guitext_profiler->setText(text.c_str());
443 guitext_profiler->setVisible(true);
445 s32 w = font->getDimension(text.c_str()).Width;
448 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
449 8+(text_height+5)*2 +
450 font->getDimension(text.c_str()).Height);
451 guitext_profiler->setRelativePosition(rect);
452 guitext_profiler->setVisible(true);
460 Profiler::GraphValues values;
466 Meta(float initial=0, video::SColor color=
467 video::SColor(255,255,255,255)):
473 std::list<Piece> m_log;
481 void put(const Profiler::GraphValues &values)
484 piece.values = values;
485 m_log.push_back(piece);
486 while(m_log.size() > m_log_max_size)
487 m_log.erase(m_log.begin());
490 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
491 gui::IGUIFont* font) const
493 std::map<std::string, Meta> m_meta;
494 for(std::list<Piece>::const_iterator k = m_log.begin();
495 k != m_log.end(); k++)
497 const Piece &piece = *k;
498 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
499 i != piece.values.end(); i++){
500 const std::string &id = i->first;
501 const float &value = i->second;
502 std::map<std::string, Meta>::iterator j =
504 if(j == m_meta.end()){
505 m_meta[id] = Meta(value);
508 if(value < j->second.min)
509 j->second.min = value;
510 if(value > j->second.max)
511 j->second.max = value;
516 static const video::SColor usable_colors[] = {
517 video::SColor(255,255,100,100),
518 video::SColor(255,90,225,90),
519 video::SColor(255,100,100,255),
520 video::SColor(255,255,150,50),
521 video::SColor(255,220,220,100)
523 static const u32 usable_colors_count =
524 sizeof(usable_colors) / sizeof(*usable_colors);
525 u32 next_color_i = 0;
526 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
527 i != m_meta.end(); i++){
528 Meta &meta = i->second;
529 video::SColor color(255,200,200,200);
530 if(next_color_i < usable_colors_count)
531 color = usable_colors[next_color_i++];
536 s32 textx = x_left + m_log_max_size + 15;
537 s32 textx2 = textx + 200 - 15;
541 u32 num_graphs = m_meta.size();
542 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
544 video::SColor bgcolor(120,0,0,0);
545 driver->draw2DRectangle(bgcolor, rect, NULL);
549 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
550 i != m_meta.end(); i++){
551 const std::string &id = i->first;
552 const Meta &meta = i->second;
554 s32 y = y_bottom - meta_i * 50;
555 float show_min = meta.min;
556 float show_max = meta.max;
557 if(show_min >= -0.0001 && show_max >= -0.0001){
558 if(show_min <= show_max * 0.5)
563 snprintf(buf, 10, "%.3g", show_max);
564 font->draw(narrow_to_wide(buf).c_str(),
565 core::rect<s32>(textx, y - graphh,
566 textx2, y - graphh + texth),
568 snprintf(buf, 10, "%.3g", show_min);
569 font->draw(narrow_to_wide(buf).c_str(),
570 core::rect<s32>(textx, y - texth,
573 font->draw(narrow_to_wide(id).c_str(),
574 core::rect<s32>(textx, y - graphh/2 - texth/2,
575 textx2, y - graphh/2 + texth/2),
578 s32 graph1h = graphh;
579 bool relativegraph = (show_min != 0 && show_min != show_max);
580 float lastscaledvalue = 0.0;
581 bool lastscaledvalue_exists = false;
582 for(std::list<Piece>::const_iterator j = m_log.begin();
583 j != m_log.end(); j++)
585 const Piece &piece = *j;
587 bool value_exists = false;
588 Profiler::GraphValues::const_iterator k =
589 piece.values.find(id);
590 if(k != piece.values.end()){
596 lastscaledvalue_exists = false;
599 float scaledvalue = 1.0;
600 if(show_max != show_min)
601 scaledvalue = (value - show_min) / (show_max - show_min);
602 if(scaledvalue == 1.0 && value == 0){
604 lastscaledvalue_exists = false;
608 if(lastscaledvalue_exists){
609 s32 ivalue1 = lastscaledvalue * graph1h;
610 s32 ivalue2 = scaledvalue * graph1h;
611 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
612 v2s32(x, graph1y - ivalue2), meta.color);
614 lastscaledvalue = scaledvalue;
615 lastscaledvalue_exists = true;
617 s32 ivalue = scaledvalue * graph1h;
618 driver->draw2DLine(v2s32(x, graph1y),
619 v2s32(x, graph1y - ivalue), meta.color);
628 class NodeDugEvent: public MtEvent
634 NodeDugEvent(v3s16 p, MapNode n):
638 const char* getType() const
644 ISoundManager *m_sound;
645 INodeDefManager *m_ndef;
647 float m_player_step_timer;
649 SimpleSoundSpec m_player_step_sound;
650 SimpleSoundSpec m_player_leftpunch_sound;
651 SimpleSoundSpec m_player_rightpunch_sound;
653 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
656 m_player_step_timer(0)
660 void playPlayerStep()
662 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
663 m_player_step_timer = 0.03;
664 m_sound->playSound(m_player_step_sound, false);
668 static void viewBobbingStep(MtEvent *e, void *data)
670 SoundMaker *sm = (SoundMaker*)data;
671 sm->playPlayerStep();
674 static void playerRegainGround(MtEvent *e, void *data)
676 SoundMaker *sm = (SoundMaker*)data;
677 sm->playPlayerStep();
680 static void playerJump(MtEvent *e, void *data)
682 //SoundMaker *sm = (SoundMaker*)data;
685 static void cameraPunchLeft(MtEvent *e, void *data)
687 SoundMaker *sm = (SoundMaker*)data;
688 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
691 static void cameraPunchRight(MtEvent *e, void *data)
693 SoundMaker *sm = (SoundMaker*)data;
694 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
697 static void nodeDug(MtEvent *e, void *data)
699 SoundMaker *sm = (SoundMaker*)data;
700 NodeDugEvent *nde = (NodeDugEvent*)e;
701 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
704 static void playerDamage(MtEvent *e, void *data)
706 SoundMaker *sm = (SoundMaker*)data;
707 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
710 static void playerFallingDamage(MtEvent *e, void *data)
712 SoundMaker *sm = (SoundMaker*)data;
713 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
716 void registerReceiver(MtEventManager *mgr)
718 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
719 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
720 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
721 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
722 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
723 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
724 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
725 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
728 void step(float dtime)
730 m_player_step_timer -= dtime;
734 // Locally stored sounds don't need to be preloaded because of this
735 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
737 std::set<std::string> m_fetched;
740 void fetchSounds(const std::string &name,
741 std::set<std::string> &dst_paths,
742 std::set<std::string> &dst_datas)
744 if(m_fetched.count(name))
746 m_fetched.insert(name);
747 std::string base = porting::path_share + DIR_DELIM + "testsounds";
748 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
749 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
750 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
751 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
752 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
753 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
754 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
755 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
756 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
757 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
758 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
762 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
765 bool *m_force_fog_off;
770 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
771 f32 *fog_range, Client *client):
773 m_force_fog_off(force_fog_off),
774 m_fog_range(fog_range),
777 ~GameGlobalShaderConstantSetter() {}
779 virtual void onSetConstants(video::IMaterialRendererServices *services,
786 video::SColor bgcolor = m_sky->getBgColor();
787 video::SColorf bgcolorf(bgcolor);
788 float bgcolorfa[4] = {
794 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
797 float fog_distance = 10000*BS;
798 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
799 fog_distance = *m_fog_range;
800 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
803 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
804 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
805 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
807 u32 animation_timer = porting::getTimeMs() % 100000;
808 float animation_timer_f = (float)animation_timer / 100000.0;
809 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
810 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
812 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
813 v3f eye_position = player->getEyePosition();
814 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
815 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
817 // Uniform sampler layers
821 // before 1.8 there isn't a "integer interface", only float
822 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
823 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
824 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
825 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
827 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
828 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
829 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
834 bool nodePlacementPrediction(Client &client,
835 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
837 std::string prediction = playeritem_def.node_placement_prediction;
838 INodeDefManager *nodedef = client.ndef();
839 ClientMap &map = client.getEnv().getClientMap();
841 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
843 verbosestream<<"Node placement prediction for "
844 <<playeritem_def.name<<" is "
845 <<prediction<<std::endl;
846 v3s16 p = neighbourpos;
847 // Place inside node itself if buildable_to
849 MapNode n_under = map.getNode(nodepos);
850 if(nodedef->get(n_under).buildable_to)
852 else if (!nodedef->get(map.getNode(p)).buildable_to)
854 }catch(InvalidPositionException &e){}
855 // Find id of predicted node
857 bool found = nodedef->getId(prediction, id);
859 errorstream<<"Node placement prediction failed for "
860 <<playeritem_def.name<<" (places "
862 <<") - Name not known"<<std::endl;
865 // Predict param2 for facedir and wallmounted nodes
867 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
868 v3s16 dir = nodepos - neighbourpos;
869 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
870 param2 = dir.Y < 0 ? 1 : 0;
871 } else if(abs(dir.X) > abs(dir.Z)){
872 param2 = dir.X < 0 ? 3 : 2;
874 param2 = dir.Z < 0 ? 5 : 4;
877 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
878 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
879 if(abs(dir.X) > abs(dir.Z)){
880 param2 = dir.X < 0 ? 3 : 1;
882 param2 = dir.Z < 0 ? 2 : 0;
885 assert(param2 >= 0 && param2 <= 5);
886 //Check attachment if node is in group attached_node
887 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
888 static v3s16 wallmounted_dirs[8] = {
897 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
898 pp = p + wallmounted_dirs[param2];
900 pp = p + v3s16(0,-1,0);
901 if(!nodedef->get(map.getNode(pp)).walkable)
904 // Add node to client map
905 MapNode n(id, 0, param2);
907 LocalPlayer* player = client.getEnv().getLocalPlayer();
909 // Dont place node when player would be inside new node
910 // NOTE: This is to be eventually implemented by a mod as client-side Lua
911 if (!nodedef->get(n).walkable ||
912 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
913 (nodedef->get(n).walkable &&
914 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
915 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
917 // This triggers the required mesh update too
918 client.addNode(p, n);
921 }catch(InvalidPositionException &e){
922 errorstream<<"Node placement prediction failed for "
923 <<playeritem_def.name<<" (places "
925 <<") - Position not loaded"<<std::endl;
931 static inline void create_formspec_menu(GUIFormSpecMenu** cur_formspec,
932 InventoryManager *invmgr, IGameDef *gamedef,
933 IWritableTextureSource* tsrc, IrrlichtDevice * device,
934 IFormSource* fs_src, TextDest* txt_dest
937 if (*cur_formspec == 0) {
938 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
939 invmgr, gamedef, tsrc, fs_src, txt_dest, cur_formspec );
940 (*cur_formspec)->doPause = false;
941 (*cur_formspec)->drop();
944 (*cur_formspec)->setFormSource(fs_src);
945 (*cur_formspec)->setTextDest(txt_dest);
950 #define SIZE_TAG "size[11,5.5]"
952 #define SIZE_TAG "size[11,5.5,true]"
955 static void show_chat_menu(GUIFormSpecMenu** cur_formspec,
956 InventoryManager *invmgr, IGameDef *gamedef,
957 IWritableTextureSource* tsrc, IrrlichtDevice * device,
958 Client* client, std::string text)
960 std::string formspec =
961 FORMSPEC_VERSION_STRING
963 "field[3,2.35;6,0.5;f_text;;" + text + "]"
964 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
968 /* Note: FormspecFormSource and LocalFormspecHandler
969 * are deleted by guiFormSpecMenu */
970 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
971 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
973 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
976 static void show_deathscreen(GUIFormSpecMenu** cur_formspec,
977 InventoryManager *invmgr, IGameDef *gamedef,
978 IWritableTextureSource* tsrc, IrrlichtDevice * device, Client* client)
980 std::string formspec =
981 std::string(FORMSPEC_VERSION_STRING) +
983 "bgcolor[#320000b4;true]"
984 "label[4.85,1.35;You died.]"
985 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
989 /* Note: FormspecFormSource and LocalFormspecHandler
990 * are deleted by guiFormSpecMenu */
991 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
992 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
994 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
997 /******************************************************************************/
998 static void show_pause_menu(GUIFormSpecMenu** cur_formspec,
999 InventoryManager *invmgr, IGameDef *gamedef,
1000 IWritableTextureSource* tsrc, IrrlichtDevice * device,
1001 bool singleplayermode)
1004 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1005 "No menu visible:\n"
1006 "- single tap: button activate\n"
1007 "- double tap: place/use\n"
1008 "- slide finger: look around\n"
1009 "Menu/Inventory visible:\n"
1010 "- double tap (outside):\n"
1012 "- touch stack, touch slot:\n"
1014 "- touch&drag, tap 2nd finger\n"
1015 " --> place single item to slot\n"
1018 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1020 "- Space: jump/climb\n"
1021 "- Shift: sneak/go down\n"
1024 "- Mouse: turn/look\n"
1025 "- Mouse left: dig/punch\n"
1026 "- Mouse right: place/use\n"
1027 "- Mouse wheel: select item\n"
1031 float ypos = singleplayermode ? 1.0 : 0.5;
1032 std::ostringstream os;
1034 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1035 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1036 << wide_to_narrow(wstrgettext("Continue")) << "]";
1038 if (!singleplayermode) {
1039 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1040 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1043 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1044 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1045 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1046 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1047 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1048 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1049 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1050 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1051 << minetest_build_info << "\n"
1052 << "path_user = " << wrap_rows(porting::path_user, 20)
1056 /* Note: FormspecFormSource and LocalFormspecHandler *
1057 * are deleted by guiFormSpecMenu */
1058 FormspecFormSource* fs_src = new FormspecFormSource(os.str());
1059 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1061 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
1063 (*cur_formspec)->doPause = true;
1066 /******************************************************************************/
1067 static void updateChat(Client& client, f32 dtime, bool show_debug,
1068 const v2u32& screensize, bool show_chat, u32 show_profiler,
1069 ChatBackend& chat_backend, gui::IGUIStaticText* guitext_chat,
1070 gui::IGUIFont* font)
1072 // Add chat log output for errors to be shown in chat
1073 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1075 // Get new messages from error log buffer
1076 while(!chat_log_error_buf.empty()) {
1077 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1080 // Get new messages from client
1081 std::wstring message;
1082 while (client.getChatMessage(message)) {
1083 chat_backend.addUnparsedMessage(message);
1086 // Remove old messages
1087 chat_backend.step(dtime);
1089 // Display all messages in a static text element
1090 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1091 std::wstring recent_chat = chat_backend.getRecentChat();
1093 // TODO replace by fontengine fcts
1094 unsigned int line_height = font->getDimension(L"Ay").Height + font->getKerningHeight();
1096 guitext_chat->setText(recent_chat.c_str());
1098 // Update gui element size and position
1099 s32 chat_y = 5 + line_height;
1101 chat_y += line_height;
1103 core::rect<s32> rect(10, chat_y, font->getDimension(recent_chat.c_str()).Width +10,
1104 chat_y + (recent_chat_count * line_height));
1106 guitext_chat->setRelativePosition(rect);
1107 // Don't show chat if disabled or empty or profiler is enabled
1108 guitext_chat->setVisible(
1109 show_chat && recent_chat_count != 0 && !show_profiler);
1112 /******************************************************************************/
1113 void the_game(bool &kill, bool random_input, InputHandler *input,
1114 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1115 std::string playername, std::string password,
1116 std::string address /* If "", local server is used */,
1117 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1118 const SubgameSpec &gamespec /* Used for local game */,
1119 bool simple_singleplayer_mode)
1121 GUIFormSpecMenu* current_formspec = 0;
1122 video::IVideoDriver* driver = device->getVideoDriver();
1123 scene::ISceneManager* smgr = device->getSceneManager();
1125 // Calculate text height using the font
1126 u32 text_height = font->getDimension(L"Random test string").Height;
1129 Draw "Loading" screen
1133 wchar_t* text = wgettext("Loading...");
1134 draw_load_screen(text, device, guienv, font, 0, 0);
1138 // Create texture source
1139 IWritableTextureSource *tsrc = createTextureSource(device);
1141 // Create shader source
1142 IWritableShaderSource *shsrc = createShaderSource(device);
1144 // These will be filled by data received from the server
1145 // Create item definition manager
1146 IWritableItemDefManager *itemdef = createItemDefManager();
1147 // Create node definition manager
1148 IWritableNodeDefManager *nodedef = createNodeDefManager();
1150 // Sound fetcher (useful when testing)
1151 GameOnDemandSoundFetcher soundfetcher;
1154 ISoundManager *sound = NULL;
1155 bool sound_is_dummy = false;
1157 if(g_settings->getBool("enable_sound")){
1158 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1159 sound = createOpenALSoundManager(&soundfetcher);
1161 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1163 infostream<<"Sound disabled."<<std::endl;
1167 infostream<<"Using dummy audio."<<std::endl;
1168 sound = &dummySoundManager;
1169 sound_is_dummy = true;
1172 Server *server = NULL;
1176 EventManager eventmgr;
1179 SoundMaker soundmaker(sound, nodedef);
1180 soundmaker.registerReceiver(&eventmgr);
1182 // Create UI for modifying quicktune values
1183 QuicktuneShortcutter quicktune;
1190 wchar_t* text = wgettext("Creating server....");
1191 draw_load_screen(text, device, guienv, font, 0, 25);
1193 infostream<<"Creating server"<<std::endl;
1195 std::string bind_str = g_settings->get("bind_address");
1196 Address bind_addr(0,0,0,0, port);
1198 if (g_settings->getBool("ipv6_server")) {
1199 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1202 bind_addr.Resolve(bind_str.c_str());
1204 } catch (ResolveError &e) {
1205 infostream << "Resolving bind address \"" << bind_str
1206 << "\" failed: " << e.what()
1207 << " -- Listening on all addresses." << std::endl;
1210 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1211 error_message = L"Unable to listen on " +
1212 narrow_to_wide(bind_addr.serializeString()) +
1213 L" because IPv6 is disabled";
1214 errorstream<<wide_to_narrow(error_message)<<std::endl;
1215 // Break out of client scope
1219 server = new Server(map_dir, gamespec,
1220 simple_singleplayer_mode,
1221 bind_addr.isIPv6());
1223 server->start(bind_addr);
1226 do{ // Client scope (breakable do-while(0))
1233 wchar_t* text = wgettext("Creating client...");
1234 draw_load_screen(text, device, guienv, font, 0, 50);
1237 infostream<<"Creating client"<<std::endl;
1239 MapDrawControl draw_control;
1242 wchar_t* text = wgettext("Resolving address...");
1243 draw_load_screen(text, device, guienv, font, 0, 75);
1246 Address connect_address(0,0,0,0, port);
1248 connect_address.Resolve(address.c_str());
1249 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1250 //connect_address.Resolve("localhost");
1251 if (connect_address.isIPv6()) {
1252 IPv6AddressBytes addr_bytes;
1253 addr_bytes.bytes[15] = 1;
1254 connect_address.setAddress(&addr_bytes);
1256 connect_address.setAddress(127,0,0,1);
1260 catch(ResolveError &e) {
1261 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1262 errorstream<<wide_to_narrow(error_message)<<std::endl;
1263 // Break out of client scope
1266 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1267 error_message = L"Unable to connect to " +
1268 narrow_to_wide(connect_address.serializeString()) +
1269 L" because IPv6 is disabled";
1270 errorstream<<wide_to_narrow(error_message)<<std::endl;
1271 // Break out of client scope
1278 Client client(device, playername.c_str(), password, draw_control,
1279 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1280 connect_address.isIPv6());
1282 // Client acts as our GameDef
1283 IGameDef *gamedef = &client;
1286 Attempt to connect to the server
1289 infostream<<"Connecting to server at ";
1290 connect_address.print(&infostream);
1291 infostream<<std::endl;
1292 client.connect(connect_address);
1295 Wait for server to accept connection
1297 bool could_connect = false;
1298 bool connect_aborted = false;
1300 float time_counter = 0.0;
1302 float fps_max = g_settings->getFloat("fps_max");
1303 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1304 u32 lasttime = device->getTimer()->getTime();
1305 while(device->run())
1307 f32 dtime = 0.033; // in seconds
1308 if (cloud_menu_background) {
1309 u32 time = device->getTimer()->getTime();
1311 dtime = (time - lasttime) / 1000.0;
1316 // Update client and server
1319 server->step(dtime);
1322 if(client.getState() == LC_Init) {
1323 could_connect = true;
1327 if(client.accessDenied()) {
1328 error_message = L"Access denied. Reason: "
1329 +client.accessDeniedReason();
1330 errorstream<<wide_to_narrow(error_message)<<std::endl;
1333 if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1334 connect_aborted = true;
1335 infostream<<"Connect aborted [Escape]"<<std::endl;
1341 wchar_t* text = wgettext("Connecting to server...");
1342 draw_load_screen(text, device, guienv, font, dtime, 100);
1346 // On some computers framerate doesn't seem to be
1347 // automatically limited
1348 if (cloud_menu_background) {
1349 // Time of frame without fps limit
1352 // not using getRealTime is necessary for wine
1353 u32 time = device->getTimer()->getTime();
1355 busytime_u32 = time - lasttime;
1358 busytime = busytime_u32 / 1000.0;
1361 u32 frametime_min = 1000./fps_max;
1363 if(busytime_u32 < frametime_min) {
1364 u32 sleeptime = frametime_min - busytime_u32;
1365 device->sleep(sleeptime);
1370 time_counter += dtime;
1373 catch(con::PeerNotFoundException &e)
1377 Handle failure to connect
1379 if(!could_connect) {
1380 if(error_message == L"" && !connect_aborted) {
1381 error_message = L"Connection failed";
1382 errorstream<<wide_to_narrow(error_message)<<std::endl;
1384 // Break out of client scope
1389 Wait until content has been received
1391 bool got_content = false;
1392 bool content_aborted = false;
1394 float time_counter = 0.0;
1396 float fps_max = g_settings->getFloat("fps_max");
1397 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1398 u32 lasttime = device->getTimer()->getTime();
1399 while (device->run()) {
1400 f32 dtime = 0.033; // in seconds
1401 if (cloud_menu_background) {
1402 u32 time = device->getTimer()->getTime();
1404 dtime = (time - lasttime) / 1000.0;
1409 // Update client and server
1412 server->step(dtime);
1415 if (client.mediaReceived() &&
1416 client.itemdefReceived() &&
1417 client.nodedefReceived()) {
1422 if (client.accessDenied()) {
1423 error_message = L"Access denied. Reason: "
1424 +client.accessDeniedReason();
1425 errorstream<<wide_to_narrow(error_message)<<std::endl;
1428 if (client.getState() < LC_Init) {
1429 error_message = L"Client disconnected";
1430 errorstream<<wide_to_narrow(error_message)<<std::endl;
1433 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1434 content_aborted = true;
1435 infostream<<"Connect aborted [Escape]"<<std::endl;
1441 if (!client.itemdefReceived())
1443 wchar_t* text = wgettext("Item definitions...");
1445 draw_load_screen(text, device, guienv, font, dtime, progress);
1448 else if (!client.nodedefReceived())
1450 wchar_t* text = wgettext("Node definitions...");
1452 draw_load_screen(text, device, guienv, font, dtime, progress);
1458 std::stringstream message;
1459 message.precision(3);
1460 message << gettext("Media...");
1462 if ( ( USE_CURL == 0) ||
1463 (!g_settings->getBool("enable_remote_media_server"))) {
1464 float cur = client.getCurRate();
1465 std::string cur_unit = gettext(" KB/s");
1469 cur_unit = gettext(" MB/s");
1471 message << " ( " << cur << cur_unit << " )";
1473 progress = 50+client.mediaReceiveProgress()*50+0.5;
1474 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
1475 guienv, font, dtime, progress);
1478 // On some computers framerate doesn't seem to be
1479 // automatically limited
1480 if (cloud_menu_background) {
1481 // Time of frame without fps limit
1484 // not using getRealTime is necessary for wine
1485 u32 time = device->getTimer()->getTime();
1487 busytime_u32 = time - lasttime;
1490 busytime = busytime_u32 / 1000.0;
1493 u32 frametime_min = 1000./fps_max;
1495 if(busytime_u32 < frametime_min) {
1496 u32 sleeptime = frametime_min - busytime_u32;
1497 device->sleep(sleeptime);
1502 time_counter += dtime;
1507 if(error_message == L"" && !content_aborted){
1508 error_message = L"Something failed";
1509 errorstream<<wide_to_narrow(error_message)<<std::endl;
1511 // Break out of client scope
1516 After all content has been received:
1517 Update cached textures, meshes and materials
1519 client.afterContentReceived(device,font);
1522 Create the camera node
1524 Camera camera(smgr, draw_control, gamedef);
1525 if (!camera.successfullyCreated(error_message))
1528 f32 camera_yaw = 0; // "right/left"
1529 f32 camera_pitch = 0; // "up/down"
1535 Clouds *clouds = NULL;
1536 if(g_settings->getBool("enable_clouds"))
1538 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1546 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1548 scene::ISceneNode* skybox = NULL;
1551 A copy of the local inventory
1553 Inventory local_inventory(itemdef);
1556 Find out size of crack animation
1558 int crack_animation_length = 5;
1560 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1561 v2u32 size = t->getOriginalSize();
1562 crack_animation_length = size.Y / size.X;
1569 // First line of debug text
1570 gui::IGUIStaticText *guitext = guienv->addStaticText(
1572 core::rect<s32>(0, 0, 0, 0),
1573 false, false, guiroot);
1574 // Second line of debug text
1575 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1577 core::rect<s32>(0, 0, 0, 0),
1578 false, false, guiroot);
1579 // At the middle of the screen
1580 // Object infos are shown in this
1581 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1583 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1584 false, true, guiroot);
1586 // Status text (displays info when showing and hiding GUI stuff, etc.)
1587 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1589 core::rect<s32>(0,0,0,0),
1590 false, false, guiroot);
1591 guitext_status->setVisible(false);
1593 std::wstring statustext;
1594 float statustext_time = 0;
1597 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1599 core::rect<s32>(0,0,0,0),
1600 //false, false); // Disable word wrap as of now
1601 false, true, guiroot);
1602 // Remove stale "recent" chat messages from previous connections
1603 chat_backend.clearRecentChat();
1604 // Chat backend and console
1605 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1607 // Profiler text (size is updated when text is updated)
1608 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1610 core::rect<s32>(0,0,0,0),
1611 false, false, guiroot);
1612 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1613 guitext_profiler->setVisible(false);
1614 guitext_profiler->setWordWrap(true);
1616 #ifdef HAVE_TOUCHSCREENGUI
1617 if (g_touchscreengui)
1618 g_touchscreengui->init(tsrc,porting::getDisplayDensity());
1622 Some statistics are collected in these
1625 u32 beginscenetime = 0;
1626 u32 endscenetime = 0;
1628 float recent_turn_speed = 0.0;
1630 ProfilerGraph graph;
1631 // Initially clear the profiler
1632 Profiler::GraphValues dummyvalues;
1633 g_profiler->graphGet(dummyvalues);
1635 float nodig_delay_timer = 0.0;
1636 float dig_time = 0.0;
1638 PointedThing pointed_old;
1639 bool digging = false;
1640 bool ldown_for_dig = false;
1642 float damage_flash = 0;
1644 float jump_timer = 0;
1645 bool reset_jump_timer = false;
1647 const float object_hit_delay = 0.2;
1648 float object_hit_delay_timer = 0.0;
1649 float time_from_last_punch = 10;
1651 float update_draw_list_timer = 0.0;
1652 v3f update_draw_list_last_cam_dir;
1654 bool invert_mouse = g_settings->getBool("invert_mouse");
1656 bool update_wielded_item_trigger = true;
1658 bool show_hud = true;
1659 bool show_chat = true;
1660 bool force_fog_off = false;
1661 f32 fog_range = 100*BS;
1662 bool disable_camera_update = false;
1663 bool show_debug = g_settings->getBool("show_debug");
1664 bool show_profiler_graph = false;
1665 u32 show_profiler = 0;
1666 u32 show_profiler_max = 3; // Number of pages
1668 float time_of_day = 0;
1669 float time_of_day_smooth = 0;
1671 float repeat_rightclick_timer = 0;
1676 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1677 sky, &force_fog_off, &fog_range, &client));
1683 bool first_loop_after_window_activation = true;
1685 // TODO: Convert the static interval timers to these
1686 // Interval limiter for profiler
1687 IntervalLimiter m_profiler_interval;
1689 // Time is in milliseconds
1690 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1691 // NOTE: So we have to use getTime() and call run()s between them
1692 u32 lasttime = device->getTimer()->getTime();
1694 LocalPlayer* player = client.getEnv().getLocalPlayer();
1695 player->hurt_tilt_timer = 0;
1696 player->hurt_tilt_strength = 0;
1701 Hud hud(driver, smgr, guienv, font, text_height,
1702 gamedef, player, &local_inventory);
1704 core::stringw str = L"Minetest [";
1705 str += driver->getName();
1707 device->setWindowCaption(str.c_str());
1710 std::wstring infotext;
1714 if(device->run() == false || kill == true ||
1715 g_gamecallback->shutdown_requested)
1718 v2u32 screensize = driver->getScreenSize();
1720 // Time of frame without fps limit
1724 // not using getRealTime is necessary for wine
1725 u32 time = device->getTimer()->getTime();
1727 busytime_u32 = time - lasttime;
1730 busytime = busytime_u32 / 1000.0;
1733 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1735 // Necessary for device->getTimer()->getTime()
1743 float fps_max = g_menumgr.pausesGame() ?
1744 g_settings->getFloat("pause_fps_max") :
1745 g_settings->getFloat("fps_max");
1746 u32 frametime_min = 1000./fps_max;
1748 if(busytime_u32 < frametime_min)
1750 u32 sleeptime = frametime_min - busytime_u32;
1751 device->sleep(sleeptime);
1752 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1756 // Necessary for device->getTimer()->getTime()
1760 Time difference calculation
1762 f32 dtime; // in seconds
1764 u32 time = device->getTimer()->getTime();
1766 dtime = (time - lasttime) / 1000.0;
1771 g_profiler->graphAdd("mainloop_dtime", dtime);
1775 if(nodig_delay_timer >= 0)
1776 nodig_delay_timer -= dtime;
1777 if(object_hit_delay_timer >= 0)
1778 object_hit_delay_timer -= dtime;
1779 time_from_last_punch += dtime;
1781 g_profiler->add("Elapsed time", dtime);
1782 g_profiler->avg("FPS", 1./dtime);
1785 Time average and jitter calculation
1788 static f32 dtime_avg1 = 0.0;
1789 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1790 f32 dtime_jitter1 = dtime - dtime_avg1;
1792 static f32 dtime_jitter1_max_sample = 0.0;
1793 static f32 dtime_jitter1_max_fraction = 0.0;
1795 static f32 jitter1_max = 0.0;
1796 static f32 counter = 0.0;
1797 if(dtime_jitter1 > jitter1_max)
1798 jitter1_max = dtime_jitter1;
1803 dtime_jitter1_max_sample = jitter1_max;
1804 dtime_jitter1_max_fraction
1805 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1811 Busytime average and jitter calculation
1814 static f32 busytime_avg1 = 0.0;
1815 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1816 f32 busytime_jitter1 = busytime - busytime_avg1;
1818 static f32 busytime_jitter1_max_sample = 0.0;
1819 static f32 busytime_jitter1_min_sample = 0.0;
1821 static f32 jitter1_max = 0.0;
1822 static f32 jitter1_min = 0.0;
1823 static f32 counter = 0.0;
1824 if(busytime_jitter1 > jitter1_max)
1825 jitter1_max = busytime_jitter1;
1826 if(busytime_jitter1 < jitter1_min)
1827 jitter1_min = busytime_jitter1;
1831 busytime_jitter1_max_sample = jitter1_max;
1832 busytime_jitter1_min_sample = jitter1_min;
1839 Handle miscellaneous stuff
1842 if(client.accessDenied())
1844 error_message = L"Access denied. Reason: "
1845 +client.accessDeniedReason();
1846 errorstream<<wide_to_narrow(error_message)<<std::endl;
1850 if(g_gamecallback->disconnect_requested)
1852 g_gamecallback->disconnect_requested = false;
1856 if(g_gamecallback->changepassword_requested)
1858 (new GUIPasswordChange(guienv, guiroot, -1,
1859 &g_menumgr, &client))->drop();
1860 g_gamecallback->changepassword_requested = false;
1863 if(g_gamecallback->changevolume_requested)
1865 (new GUIVolumeChange(guienv, guiroot, -1,
1866 &g_menumgr, &client))->drop();
1867 g_gamecallback->changevolume_requested = false;
1870 /* Process TextureSource's queue */
1871 tsrc->processQueue();
1873 /* Process ItemDefManager's queue */
1874 itemdef->processQueue(gamedef);
1877 Process ShaderSource's queue
1879 shsrc->processQueue();
1886 // Hilight boxes collected during the loop and displayed
1887 std::vector<aabb3f> hilightboxes;
1889 /* reset infotext */
1894 float profiler_print_interval =
1895 g_settings->getFloat("profiler_print_interval");
1896 bool print_to_log = true;
1897 if(profiler_print_interval == 0){
1898 print_to_log = false;
1899 profiler_print_interval = 5;
1901 if(m_profiler_interval.step(dtime, profiler_print_interval))
1904 infostream<<"Profiler:"<<std::endl;
1905 g_profiler->print(infostream);
1908 update_profiler_gui(guitext_profiler, font, text_height,
1909 show_profiler, show_profiler_max);
1911 g_profiler->clear();
1915 Direct handling of user input
1918 // Reset input if window not active or some menu is active
1919 if(device->isWindowActive() == false
1920 || noMenuActive() == false
1921 || guienv->hasFocus(gui_chat_console))
1925 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1927 gui_chat_console->closeConsoleAtOnce();
1930 // Input handler step() (used by the random input generator)
1932 #ifdef HAVE_TOUCHSCREENGUI
1933 if (g_touchscreengui) {
1934 g_touchscreengui->step(dtime);
1938 if (current_formspec != 0)
1939 current_formspec->getAndroidUIInput();
1942 // Increase timer for doubleclick of "jump"
1943 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1944 jump_timer += dtime;
1947 Launch menus and trigger stuff according to keys
1949 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1951 // drop selected item
1952 IDropAction *a = new IDropAction();
1954 a->from_inv.setCurrentPlayer();
1955 a->from_list = "main";
1956 a->from_i = client.getPlayerItem();
1957 client.inventoryAction(a);
1959 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1961 infostream<<"the_game: "
1962 <<"Launching inventory"<<std::endl;
1964 PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1965 TextDest* txt_dst = new TextDestPlayerInventory(&client);
1967 create_formspec_menu(¤t_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst);
1969 InventoryLocation inventoryloc;
1970 inventoryloc.setCurrentPlayer();
1971 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1973 else if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey))
1975 show_pause_menu(¤t_formspec, &client, gamedef, tsrc, device,
1976 simple_singleplayer_mode);
1978 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1980 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1983 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1985 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1988 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1990 if (!gui_chat_console->isOpenInhibited())
1992 // Open up to over half of the screen
1993 gui_chat_console->openConsole(0.6);
1994 guienv->setFocus(gui_chat_console);
1997 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1999 if(g_settings->getBool("free_move"))
2001 g_settings->set("free_move","false");
2002 statustext = L"free_move disabled";
2003 statustext_time = 0;
2007 g_settings->set("free_move","true");
2008 statustext = L"free_move enabled";
2009 statustext_time = 0;
2010 if(!client.checkPrivilege("fly"))
2011 statustext += L" (note: no 'fly' privilege)";
2014 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
2016 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
2018 if(g_settings->getBool("free_move"))
2020 g_settings->set("free_move","false");
2021 statustext = L"free_move disabled";
2022 statustext_time = 0;
2026 g_settings->set("free_move","true");
2027 statustext = L"free_move enabled";
2028 statustext_time = 0;
2029 if(!client.checkPrivilege("fly"))
2030 statustext += L" (note: no 'fly' privilege)";
2033 reset_jump_timer = true;
2035 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
2037 if(g_settings->getBool("fast_move"))
2039 g_settings->set("fast_move","false");
2040 statustext = L"fast_move disabled";
2041 statustext_time = 0;
2045 g_settings->set("fast_move","true");
2046 statustext = L"fast_move enabled";
2047 statustext_time = 0;
2048 if(!client.checkPrivilege("fast"))
2049 statustext += L" (note: no 'fast' privilege)";
2052 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2054 if(g_settings->getBool("noclip"))
2056 g_settings->set("noclip","false");
2057 statustext = L"noclip disabled";
2058 statustext_time = 0;
2062 g_settings->set("noclip","true");
2063 statustext = L"noclip enabled";
2064 statustext_time = 0;
2065 if(!client.checkPrivilege("noclip"))
2066 statustext += L" (note: no 'noclip' privilege)";
2069 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2071 irr::video::IImage* const image = driver->createScreenShot();
2073 irr::c8 filename[256];
2074 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
2075 g_settings->get("screenshot_path").c_str(),
2076 device->getTimer()->getRealTime());
2077 if (driver->writeImageToFile(image, filename)) {
2078 std::wstringstream sstr;
2079 sstr<<"Saved screenshot to '"<<filename<<"'";
2080 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
2081 statustext = sstr.str();
2082 statustext_time = 0;
2084 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
2089 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2091 show_hud = !show_hud;
2093 statustext = L"HUD shown";
2095 statustext = L"HUD hidden";
2096 statustext_time = 0;
2098 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2100 show_chat = !show_chat;
2102 statustext = L"Chat shown";
2104 statustext = L"Chat hidden";
2105 statustext_time = 0;
2107 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2109 force_fog_off = !force_fog_off;
2111 statustext = L"Fog disabled";
2113 statustext = L"Fog enabled";
2114 statustext_time = 0;
2116 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2118 disable_camera_update = !disable_camera_update;
2119 if(disable_camera_update)
2120 statustext = L"Camera update disabled";
2122 statustext = L"Camera update enabled";
2123 statustext_time = 0;
2125 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2127 // Initial / 3x toggle: Chat only
2128 // 1x toggle: Debug text with chat
2129 // 2x toggle: Debug text with profiler graph
2133 show_profiler_graph = false;
2134 statustext = L"Debug info shown";
2135 statustext_time = 0;
2137 else if(show_profiler_graph)
2140 show_profiler_graph = false;
2141 statustext = L"Debug info and profiler graph hidden";
2142 statustext_time = 0;
2146 show_profiler_graph = true;
2147 statustext = L"Profiler graph shown";
2148 statustext_time = 0;
2151 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2153 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2155 // FIXME: This updates the profiler with incomplete values
2156 update_profiler_gui(guitext_profiler, font, text_height,
2157 show_profiler, show_profiler_max);
2159 if(show_profiler != 0)
2161 std::wstringstream sstr;
2162 sstr<<"Profiler shown (page "<<show_profiler
2163 <<" of "<<show_profiler_max<<")";
2164 statustext = sstr.str();
2165 statustext_time = 0;
2169 statustext = L"Profiler hidden";
2170 statustext_time = 0;
2173 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2175 s16 range = g_settings->getS16("viewing_range_nodes_min");
2176 s16 range_new = range + 10;
2177 g_settings->set("viewing_range_nodes_min", itos(range_new));
2178 statustext = narrow_to_wide(
2179 "Minimum viewing range changed to "
2181 statustext_time = 0;
2183 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2185 s16 range = g_settings->getS16("viewing_range_nodes_min");
2186 s16 range_new = range - 10;
2189 g_settings->set("viewing_range_nodes_min",
2191 statustext = narrow_to_wide(
2192 "Minimum viewing range changed to "
2194 statustext_time = 0;
2198 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2200 reset_jump_timer = false;
2204 // Handle QuicktuneShortcutter
2205 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2207 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2209 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2211 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2214 std::string msg = quicktune.getMessage();
2216 statustext = narrow_to_wide(msg);
2217 statustext_time = 0;
2221 // Item selection with mouse wheel
2222 u16 new_playeritem = client.getPlayerItem();
2224 s32 wheel = input->getMouseWheel();
2225 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2226 player->hud_hotbar_itemcount-1);
2230 if(new_playeritem < max_item)
2237 if(new_playeritem > 0)
2240 new_playeritem = max_item;
2245 for(u16 i=0; i<10; i++)
2247 const KeyPress *kp = NumberKey + (i + 1) % 10;
2248 if(input->wasKeyDown(*kp))
2250 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2254 infostream<<"Selected item: "
2255 <<new_playeritem<<std::endl;
2260 // Viewing range selection
2261 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2263 draw_control.range_all = !draw_control.range_all;
2264 if(draw_control.range_all)
2266 infostream<<"Enabled full viewing range"<<std::endl;
2267 statustext = L"Enabled full viewing range";
2268 statustext_time = 0;
2272 infostream<<"Disabled full viewing range"<<std::endl;
2273 statustext = L"Disabled full viewing range";
2274 statustext_time = 0;
2278 // Print debug stacks
2279 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2281 dstream<<"-----------------------------------------"
2283 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2284 dstream<<"-----------------------------------------"
2286 debug_stacks_print();
2290 Mouse and camera control
2291 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2294 float turn_amount = 0;
2295 if((device->isWindowActive() && noMenuActive()) || random_input)
2300 // Mac OSX gets upset if this is set every frame
2301 if(device->getCursorControl()->isVisible())
2302 device->getCursorControl()->setVisible(false);
2306 if(first_loop_after_window_activation){
2307 //infostream<<"window active, first loop"<<std::endl;
2308 first_loop_after_window_activation = false;
2310 #ifdef HAVE_TOUCHSCREENGUI
2311 if (g_touchscreengui) {
2312 camera_yaw = g_touchscreengui->getYaw();
2313 camera_pitch = g_touchscreengui->getPitch();
2316 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2317 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2319 || (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2322 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2324 /*const float keyspeed = 500;
2325 if(input->isKeyDown(irr::KEY_UP))
2326 dy -= dtime * keyspeed;
2327 if(input->isKeyDown(irr::KEY_DOWN))
2328 dy += dtime * keyspeed;
2329 if(input->isKeyDown(irr::KEY_LEFT))
2330 dx -= dtime * keyspeed;
2331 if(input->isKeyDown(irr::KEY_RIGHT))
2332 dx += dtime * keyspeed;*/
2334 float d = g_settings->getFloat("mouse_sensitivity");
2335 d = rangelim(d, 0.01, 100.0);
2337 camera_pitch += dy*d;
2338 turn_amount = v2f(dx, dy).getLength() * d;
2340 #ifdef HAVE_TOUCHSCREENGUI
2343 if(camera_pitch < -89.5) camera_pitch = -89.5;
2344 if(camera_pitch > 89.5) camera_pitch = 89.5;
2346 input->setMousePos((driver->getScreenSize().Width/2),
2347 (driver->getScreenSize().Height/2));
2351 // Mac OSX gets upset if this is set every frame
2352 if(device->getCursorControl()->isVisible() == false)
2353 device->getCursorControl()->setVisible(true);
2356 //infostream<<"window inactive"<<std::endl;
2357 first_loop_after_window_activation = true;
2359 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2360 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2363 Player speed control
2377 PlayerControl control(
2378 input->isKeyDown(getKeySetting("keymap_forward")),
2379 input->isKeyDown(getKeySetting("keymap_backward")),
2380 input->isKeyDown(getKeySetting("keymap_left")),
2381 input->isKeyDown(getKeySetting("keymap_right")),
2382 input->isKeyDown(getKeySetting("keymap_jump")),
2383 input->isKeyDown(getKeySetting("keymap_special1")),
2384 input->isKeyDown(getKeySetting("keymap_sneak")),
2385 input->getLeftState(),
2386 input->getRightState(),
2390 client.setPlayerControl(control);
2391 LocalPlayer* player = client.getEnv().getLocalPlayer();
2393 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2394 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2395 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2396 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2397 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2398 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2399 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2400 (((int)input->getLeftState() & 0x1) << 7) |
2401 (((int)input->getRightState() & 0x1) << 8);
2405 Run server, client (and process environments)
2407 bool can_be_and_is_paused =
2408 (simple_singleplayer_mode && g_menumgr.pausesGame());
2409 if(can_be_and_is_paused)
2418 //TimeTaker timer("server->step(dtime)");
2419 server->step(dtime);
2422 //TimeTaker timer("client.step(dtime)");
2428 // Read client events
2430 ClientEvent event = client.getClientEvent();
2431 if(event.type == CE_NONE) {
2434 else if(event.type == CE_PLAYER_DAMAGE &&
2435 client.getHP() != 0) {
2436 //u16 damage = event.player_damage.amount;
2437 //infostream<<"Player damage: "<<damage<<std::endl;
2439 damage_flash += 100.0;
2440 damage_flash += 8.0 * event.player_damage.amount;
2442 player->hurt_tilt_timer = 1.5;
2443 player->hurt_tilt_strength = event.player_damage.amount/4;
2444 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2446 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2447 gamedef->event()->put(e);
2449 else if(event.type == CE_PLAYER_FORCE_MOVE) {
2450 camera_yaw = event.player_force_move.yaw;
2451 camera_pitch = event.player_force_move.pitch;
2453 else if(event.type == CE_DEATHSCREEN) {
2454 show_deathscreen(¤t_formspec, &client, gamedef, tsrc,
2457 chat_backend.addMessage(L"", L"You died.");
2459 /* Handle visualization */
2462 LocalPlayer* player = client.getEnv().getLocalPlayer();
2463 player->hurt_tilt_timer = 0;
2464 player->hurt_tilt_strength = 0;
2467 else if (event.type == CE_SHOW_FORMSPEC) {
2468 FormspecFormSource* fs_src =
2469 new FormspecFormSource(*(event.show_formspec.formspec));
2470 TextDestPlayerInventory* txt_dst =
2471 new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2473 create_formspec_menu(¤t_formspec, &client, gamedef,
2474 tsrc, device, fs_src, txt_dst);
2476 delete(event.show_formspec.formspec);
2477 delete(event.show_formspec.formname);
2479 else if(event.type == CE_SPAWN_PARTICLE) {
2480 LocalPlayer* player = client.getEnv().getLocalPlayer();
2481 video::ITexture *texture =
2482 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2484 new Particle(gamedef, smgr, player, client.getEnv(),
2485 *event.spawn_particle.pos,
2486 *event.spawn_particle.vel,
2487 *event.spawn_particle.acc,
2488 event.spawn_particle.expirationtime,
2489 event.spawn_particle.size,
2490 event.spawn_particle.collisiondetection,
2491 event.spawn_particle.vertical,
2496 else if(event.type == CE_ADD_PARTICLESPAWNER) {
2497 LocalPlayer* player = client.getEnv().getLocalPlayer();
2498 video::ITexture *texture =
2499 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2501 new ParticleSpawner(gamedef, smgr, player,
2502 event.add_particlespawner.amount,
2503 event.add_particlespawner.spawntime,
2504 *event.add_particlespawner.minpos,
2505 *event.add_particlespawner.maxpos,
2506 *event.add_particlespawner.minvel,
2507 *event.add_particlespawner.maxvel,
2508 *event.add_particlespawner.minacc,
2509 *event.add_particlespawner.maxacc,
2510 event.add_particlespawner.minexptime,
2511 event.add_particlespawner.maxexptime,
2512 event.add_particlespawner.minsize,
2513 event.add_particlespawner.maxsize,
2514 event.add_particlespawner.collisiondetection,
2515 event.add_particlespawner.vertical,
2517 event.add_particlespawner.id);
2519 else if(event.type == CE_DELETE_PARTICLESPAWNER) {
2520 delete_particlespawner (event.delete_particlespawner.id);
2522 else if (event.type == CE_HUDADD) {
2523 u32 id = event.hudadd.id;
2525 HudElement *e = player->getHud(id);
2528 delete event.hudadd.pos;
2529 delete event.hudadd.name;
2530 delete event.hudadd.scale;
2531 delete event.hudadd.text;
2532 delete event.hudadd.align;
2533 delete event.hudadd.offset;
2534 delete event.hudadd.world_pos;
2535 delete event.hudadd.size;
2540 e->type = (HudElementType)event.hudadd.type;
2541 e->pos = *event.hudadd.pos;
2542 e->name = *event.hudadd.name;
2543 e->scale = *event.hudadd.scale;
2544 e->text = *event.hudadd.text;
2545 e->number = event.hudadd.number;
2546 e->item = event.hudadd.item;
2547 e->dir = event.hudadd.dir;
2548 e->align = *event.hudadd.align;
2549 e->offset = *event.hudadd.offset;
2550 e->world_pos = *event.hudadd.world_pos;
2551 e->size = *event.hudadd.size;
2553 u32 new_id = player->addHud(e);
2554 //if this isn't true our huds aren't consistent
2555 assert(new_id == id);
2557 delete event.hudadd.pos;
2558 delete event.hudadd.name;
2559 delete event.hudadd.scale;
2560 delete event.hudadd.text;
2561 delete event.hudadd.align;
2562 delete event.hudadd.offset;
2563 delete event.hudadd.world_pos;
2564 delete event.hudadd.size;
2566 else if (event.type == CE_HUDRM) {
2567 HudElement* e = player->removeHud(event.hudrm.id);
2572 else if (event.type == CE_HUDCHANGE) {
2573 u32 id = event.hudchange.id;
2574 HudElement* e = player->getHud(id);
2577 delete event.hudchange.v3fdata;
2578 delete event.hudchange.v2fdata;
2579 delete event.hudchange.sdata;
2580 delete event.hudchange.v2s32data;
2584 switch (event.hudchange.stat) {
2586 e->pos = *event.hudchange.v2fdata;
2589 e->name = *event.hudchange.sdata;
2591 case HUD_STAT_SCALE:
2592 e->scale = *event.hudchange.v2fdata;
2595 e->text = *event.hudchange.sdata;
2597 case HUD_STAT_NUMBER:
2598 e->number = event.hudchange.data;
2601 e->item = event.hudchange.data;
2604 e->dir = event.hudchange.data;
2606 case HUD_STAT_ALIGN:
2607 e->align = *event.hudchange.v2fdata;
2609 case HUD_STAT_OFFSET:
2610 e->offset = *event.hudchange.v2fdata;
2612 case HUD_STAT_WORLD_POS:
2613 e->world_pos = *event.hudchange.v3fdata;
2616 e->size = *event.hudchange.v2s32data;
2620 delete event.hudchange.v3fdata;
2621 delete event.hudchange.v2fdata;
2622 delete event.hudchange.sdata;
2623 delete event.hudchange.v2s32data;
2625 else if (event.type == CE_SET_SKY) {
2626 sky->setVisible(false);
2631 // Handle according to type
2632 if(*event.set_sky.type == "regular") {
2633 sky->setVisible(true);
2635 else if(*event.set_sky.type == "skybox" &&
2636 event.set_sky.params->size() == 6) {
2637 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2638 skybox = smgr->addSkyBoxSceneNode(
2639 tsrc->getTexture((*event.set_sky.params)[0]),
2640 tsrc->getTexture((*event.set_sky.params)[1]),
2641 tsrc->getTexture((*event.set_sky.params)[2]),
2642 tsrc->getTexture((*event.set_sky.params)[3]),
2643 tsrc->getTexture((*event.set_sky.params)[4]),
2644 tsrc->getTexture((*event.set_sky.params)[5]));
2646 // Handle everything else as plain color
2648 if(*event.set_sky.type != "plain")
2649 infostream<<"Unknown sky type: "
2650 <<(*event.set_sky.type)<<std::endl;
2651 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2654 delete event.set_sky.bgcolor;
2655 delete event.set_sky.type;
2656 delete event.set_sky.params;
2658 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
2659 bool enable = event.override_day_night_ratio.do_override;
2660 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2661 client.getEnv().setDayNightRatioOverride(enable, value);
2666 //TimeTaker //timer2("//timer2");
2669 For interaction purposes, get info about the held item
2671 - Is it a usable item?
2672 - Can it point to liquids?
2674 ItemStack playeritem;
2676 InventoryList *mlist = local_inventory.getList("main");
2677 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
2678 playeritem = mlist->getItem(client.getPlayerItem());
2680 const ItemDefinition &playeritem_def =
2681 playeritem.getDefinition(itemdef);
2682 ToolCapabilities playeritem_toolcap =
2683 playeritem.getToolCapabilities(itemdef);
2689 v3s16 old_camera_offset = camera.getOffset();
2691 LocalPlayer* player = client.getEnv().getLocalPlayer();
2692 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2693 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2695 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2696 camera.toggleCameraMode();
2697 GenericCAO* playercao = player->getCAO();
2699 assert( playercao != NULL );
2700 if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2701 playercao->setVisible(true);
2704 playercao->setVisible(false);
2707 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2708 camera.update(player, dtime, busytime, tool_reload_ratio,
2712 v3f player_position = player->getPosition();
2713 v3f camera_position = camera.getPosition();
2714 v3f camera_direction = camera.getDirection();
2715 f32 camera_fov = camera.getFovMax();
2716 v3s16 camera_offset = camera.getOffset();
2718 bool camera_offset_changed = (camera_offset != old_camera_offset);
2720 if(!disable_camera_update){
2721 client.getEnv().getClientMap().updateCamera(camera_position,
2722 camera_direction, camera_fov, camera_offset);
2723 if (camera_offset_changed){
2724 client.updateCameraOffset(camera_offset);
2725 client.getEnv().updateCameraOffset(camera_offset);
2727 clouds->updateCameraOffset(camera_offset);
2731 // Update sound listener
2732 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2733 v3f(0,0,0), // velocity
2734 camera.getDirection(),
2735 camera.getCameraNode()->getUpVector());
2736 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2742 soundmaker.step(dtime);
2744 ClientMap &map = client.getEnv().getClientMap();
2745 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2746 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2750 Calculate what block is the crosshair pointing to
2753 //u32 t1 = device->getTimer()->getRealTime();
2755 f32 d = playeritem_def.range; // max. distance
2756 f32 d_hand = itemdef->get("").range;
2757 if(d < 0 && d_hand >= 0)
2761 core::line3d<f32> shootline(camera_position,
2762 camera_position + camera_direction * BS * (d+1));
2765 // prevent player pointing anything in front-view
2766 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2767 shootline = core::line3d<f32>(0,0,0,0,0,0);
2769 #ifdef HAVE_TOUCHSCREENGUI
2770 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2771 shootline = g_touchscreengui->getShootline();
2772 shootline.start += intToFloat(camera_offset,BS);
2773 shootline.end += intToFloat(camera_offset,BS);
2777 ClientActiveObject *selected_object = NULL;
2779 PointedThing pointed = getPointedThing(
2781 &client, player_position, camera_direction,
2782 camera_position, shootline, d,
2783 playeritem_def.liquids_pointable, !ldown_for_dig,
2789 if(pointed != pointed_old)
2791 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2792 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2797 - releasing left mouse button
2798 - pointing away from node
2802 if(input->getLeftReleased())
2804 infostream<<"Left button released"
2805 <<" (stopped digging)"<<std::endl;
2808 else if(pointed != pointed_old)
2810 if (pointed.type == POINTEDTHING_NODE
2811 && pointed_old.type == POINTEDTHING_NODE
2812 && pointed.node_undersurface == pointed_old.node_undersurface)
2814 // Still pointing to the same node,
2815 // but a different face. Don't reset.
2819 infostream<<"Pointing away from node"
2820 <<" (stopped digging)"<<std::endl;
2826 client.interact(1, pointed_old);
2827 client.setCrack(-1, v3s16(0,0,0));
2831 if(!digging && ldown_for_dig && !input->getLeftState())
2833 ldown_for_dig = false;
2836 bool left_punch = false;
2837 soundmaker.m_player_leftpunch_sound.name = "";
2839 if(input->getRightState())
2840 repeat_rightclick_timer += dtime;
2842 repeat_rightclick_timer = 0;
2844 if(playeritem_def.usable && input->getLeftState())
2846 if(input->getLeftClicked())
2847 client.interact(4, pointed);
2849 else if(pointed.type == POINTEDTHING_NODE)
2851 v3s16 nodepos = pointed.node_undersurface;
2852 v3s16 neighbourpos = pointed.node_abovesurface;
2855 Check information text of node
2858 ClientMap &map = client.getEnv().getClientMap();
2859 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2861 infotext = narrow_to_wide(meta->getString("infotext"));
2863 MapNode n = map.getNode(nodepos);
2864 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2865 infotext = L"Unknown node: ";
2866 infotext += narrow_to_wide(nodedef->get(n).name);
2874 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2875 && client.checkPrivilege("interact"))
2879 infostream<<"Started digging"<<std::endl;
2880 client.interact(0, pointed);
2882 ldown_for_dig = true;
2884 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2886 // NOTE: Similar piece of code exists on the server side for
2888 // Get digging parameters
2889 DigParams params = getDigParams(nodedef->get(n).groups,
2890 &playeritem_toolcap);
2891 // If can't dig, try hand
2892 if(!params.diggable){
2893 const ItemDefinition &hand = itemdef->get("");
2894 const ToolCapabilities *tp = hand.tool_capabilities;
2896 params = getDigParams(nodedef->get(n).groups, tp);
2899 float dig_time_complete = 0.0;
2901 if(params.diggable == false)
2903 // I guess nobody will wait for this long
2904 dig_time_complete = 10000000.0;
2908 dig_time_complete = params.time;
2909 if (g_settings->getBool("enable_particles"))
2911 const ContentFeatures &features =
2912 client.getNodeDefManager()->get(n);
2913 addPunchingParticles
2914 (gamedef, smgr, player, client.getEnv(),
2915 nodepos, features.tiles);
2919 if(dig_time_complete >= 0.001)
2921 dig_index = (u16)((float)crack_animation_length
2922 * dig_time/dig_time_complete);
2924 // This is for torches
2927 dig_index = crack_animation_length;
2930 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2931 if(sound_dig.exists() && params.diggable){
2932 if(sound_dig.name == "__group"){
2933 if(params.main_group != ""){
2934 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2935 soundmaker.m_player_leftpunch_sound.name =
2936 std::string("default_dig_") +
2940 soundmaker.m_player_leftpunch_sound = sound_dig;
2944 // Don't show cracks if not diggable
2945 if(dig_time_complete >= 100000.0)
2948 else if(dig_index < crack_animation_length)
2950 //TimeTaker timer("client.setTempMod");
2951 //infostream<<"dig_index="<<dig_index<<std::endl;
2952 client.setCrack(dig_index, nodepos);
2956 infostream<<"Digging completed"<<std::endl;
2957 client.interact(2, pointed);
2958 client.setCrack(-1, v3s16(0,0,0));
2959 MapNode wasnode = map.getNode(nodepos);
2960 client.removeNode(nodepos);
2962 if (g_settings->getBool("enable_particles"))
2964 const ContentFeatures &features =
2965 client.getNodeDefManager()->get(wasnode);
2967 (gamedef, smgr, player, client.getEnv(),
2968 nodepos, features.tiles);
2974 nodig_delay_timer = dig_time_complete
2975 / (float)crack_animation_length;
2977 // We don't want a corresponding delay to
2978 // very time consuming nodes
2979 if(nodig_delay_timer > 0.3)
2980 nodig_delay_timer = 0.3;
2981 // We want a slight delay to very little
2982 // time consuming nodes
2983 float mindelay = 0.15;
2984 if(nodig_delay_timer < mindelay)
2985 nodig_delay_timer = mindelay;
2987 // Send event to trigger sound
2988 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2989 gamedef->event()->put(e);
2992 if(dig_time_complete < 100000.0)
2996 client.setCrack(-1, nodepos);
2999 camera.setDigging(0); // left click animation
3002 if((input->getRightClicked() ||
3003 repeat_rightclick_timer >=
3004 g_settings->getFloat("repeat_rightclick_time")) &&
3005 client.checkPrivilege("interact"))
3007 repeat_rightclick_timer = 0;
3008 infostream<<"Ground right-clicked"<<std::endl;
3010 if(meta && meta->getString("formspec") != "" && !random_input
3011 && !input->isKeyDown(getKeySetting("keymap_sneak")))
3013 infostream<<"Launching custom inventory view"<<std::endl;
3015 InventoryLocation inventoryloc;
3016 inventoryloc.setNodeMeta(nodepos);
3018 NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
3019 &client.getEnv().getClientMap(), nodepos);
3020 TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
3022 create_formspec_menu(¤t_formspec, &client, gamedef,
3023 tsrc, device, fs_src, txt_dst);
3025 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3027 // Otherwise report right click to server
3030 camera.setDigging(1); // right click animation (always shown for feedback)
3032 // If the wielded item has node placement prediction,
3034 bool placed = nodePlacementPrediction(client,
3036 nodepos, neighbourpos);
3040 client.interact(3, pointed);
3042 soundmaker.m_player_rightpunch_sound =
3043 playeritem_def.sound_place;
3045 soundmaker.m_player_rightpunch_sound =
3049 if (playeritem_def.node_placement_prediction == "" ||
3050 nodedef->get(map.getNode(nodepos)).rightclickable)
3051 client.interact(3, pointed); // Report to server
3055 else if(pointed.type == POINTEDTHING_OBJECT)
3057 infotext = narrow_to_wide(selected_object->infoText());
3059 if(infotext == L"" && show_debug){
3060 infotext = narrow_to_wide(selected_object->debugInfoText());
3063 //if(input->getLeftClicked())
3064 if(input->getLeftState())
3066 bool do_punch = false;
3067 bool do_punch_damage = false;
3068 if(object_hit_delay_timer <= 0.0){
3070 do_punch_damage = true;
3071 object_hit_delay_timer = object_hit_delay;
3073 if(input->getLeftClicked()){
3077 infostream<<"Left-clicked object"<<std::endl;
3080 if(do_punch_damage){
3081 // Report direct punch
3082 v3f objpos = selected_object->getPosition();
3083 v3f dir = (objpos - player_position).normalize();
3085 bool disable_send = selected_object->directReportPunch(
3086 dir, &playeritem, time_from_last_punch);
3087 time_from_last_punch = 0;
3089 client.interact(0, pointed);
3092 else if(input->getRightClicked())
3094 infostream<<"Right-clicked object"<<std::endl;
3095 client.interact(3, pointed); // place
3098 else if(input->getLeftState())
3100 // When button is held down in air, show continuous animation
3104 pointed_old = pointed;
3106 if(left_punch || input->getLeftClicked())
3108 camera.setDigging(0); // left click animation
3111 input->resetLeftClicked();
3112 input->resetRightClicked();
3114 input->resetLeftReleased();
3115 input->resetRightReleased();
3118 Calculate stuff for drawing
3125 if(draw_control.range_all)
3126 fog_range = 100000*BS;
3128 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3129 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3134 Calculate general brightness
3136 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3137 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3138 float direct_brightness = 0;
3139 bool sunlight_seen = false;
3140 if(g_settings->getBool("free_move")){
3141 direct_brightness = time_brightness;
3142 sunlight_seen = true;
3144 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3145 float old_brightness = sky->getBrightness();
3146 direct_brightness = (float)client.getEnv().getClientMap()
3147 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3148 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3152 time_of_day = client.getEnv().getTimeOfDayF();
3154 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3155 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3156 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3157 time_of_day_smooth = time_of_day;
3159 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3160 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3161 + (time_of_day+1.0) * todsm;
3163 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3164 + time_of_day * todsm;
3166 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3167 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3168 player->getPitch());
3170 video::SColor bgcolor = sky->getBgColor();
3171 video::SColor skycolor = sky->getSkyColor();
3177 if(sky->getCloudsVisible()){
3178 clouds->setVisible(true);
3179 clouds->step(dtime);
3180 clouds->update(v2f(player_position.X, player_position.Z),
3181 sky->getCloudColor());
3183 clouds->setVisible(false);
3191 allparticles_step(dtime);
3192 allparticlespawners_step(dtime, client.getEnv());
3198 if(g_settings->getBool("enable_fog") && !force_fog_off)
3202 video::EFT_FOG_LINEAR,
3214 video::EFT_FOG_LINEAR,
3224 Update gui stuff (0ms)
3227 //TimeTaker guiupdatetimer("Gui updating");
3231 static float drawtime_avg = 0;
3232 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3233 /*static float beginscenetime_avg = 0;
3234 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3235 static float scenetime_avg = 0;
3236 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3237 static float endscenetime_avg = 0;
3238 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3240 u16 fps = (1.0/dtime_avg1);
3242 std::ostringstream os(std::ios_base::binary);
3244 <<"Minetest "<<minetest_version_hash
3246 <<" (R: range_all="<<draw_control.range_all<<")"
3247 <<std::setprecision(0)
3248 <<" drawtime = "<<drawtime_avg
3249 <<std::setprecision(1)
3250 <<", dtime_jitter = "
3251 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3252 <<std::setprecision(1)
3253 <<", v_range = "<<draw_control.wanted_range
3254 <<std::setprecision(3)
3255 <<", RTT = "<<client.getRTT();
3256 guitext->setText(narrow_to_wide(os.str()).c_str());
3257 guitext->setVisible(true);
3259 else if(show_hud || show_chat)
3261 std::ostringstream os(std::ios_base::binary);
3262 os<<"Minetest "<<minetest_version_hash;
3263 guitext->setText(narrow_to_wide(os.str()).c_str());
3264 guitext->setVisible(true);
3268 guitext->setVisible(false);
3271 if (guitext->isVisible())
3273 core::rect<s32> rect(
3279 guitext->setRelativePosition(rect);
3284 std::ostringstream os(std::ios_base::binary);
3285 os<<std::setprecision(1)<<std::fixed
3286 <<"(" <<(player_position.X/BS)
3287 <<", "<<(player_position.Y/BS)
3288 <<", "<<(player_position.Z/BS)
3289 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3290 <<") (seed = "<<((u64)client.getMapSeed())
3292 guitext2->setText(narrow_to_wide(os.str()).c_str());
3293 guitext2->setVisible(true);
3295 core::rect<s32> rect(
3299 5 + (text_height * 2)
3301 guitext2->setRelativePosition(rect);
3305 guitext2->setVisible(false);
3309 guitext_info->setText(infotext.c_str());
3310 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3314 float statustext_time_max = 1.5;
3315 if(!statustext.empty())
3317 statustext_time += dtime;
3318 if(statustext_time >= statustext_time_max)
3321 statustext_time = 0;
3324 guitext_status->setText(statustext.c_str());
3325 guitext_status->setVisible(!statustext.empty());
3327 if(!statustext.empty())
3329 s32 status_y = screensize.Y - 130;
3330 core::rect<s32> rect(
3332 status_y - guitext_status->getTextHeight(),
3333 10 + guitext_status->getTextWidth(),
3336 guitext_status->setRelativePosition(rect);
3339 video::SColor initial_color(255,0,0,0);
3340 if(guienv->getSkin())
3341 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3342 video::SColor final_color = initial_color;
3343 final_color.setAlpha(0);
3344 video::SColor fade_color =
3345 initial_color.getInterpolated_quadratic(
3348 pow(statustext_time / (float)statustext_time_max, 2.0f));
3349 guitext_status->setOverrideColor(fade_color);
3350 guitext_status->enableOverrideColor(true);
3355 Get chat messages from client
3357 updateChat(client, dtime, show_debug, screensize, show_chat,
3358 show_profiler, chat_backend, guitext_chat, font);
3364 if(client.getPlayerItem() != new_playeritem)
3366 client.selectPlayerItem(new_playeritem);
3368 if(client.getLocalInventoryUpdated())
3370 //infostream<<"Updating local inventory"<<std::endl;
3371 client.getLocalInventory(local_inventory);
3373 update_wielded_item_trigger = true;
3375 if(update_wielded_item_trigger)
3377 update_wielded_item_trigger = false;
3378 // Update wielded tool
3379 InventoryList *mlist = local_inventory.getList("main");
3381 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
3382 item = mlist->getItem(client.getPlayerItem());
3383 camera.wield(item, client.getPlayerItem());
3387 Update block draw list every 200ms or when camera direction has
3390 update_draw_list_timer += dtime;
3391 if(update_draw_list_timer >= 0.2 ||
3392 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3393 camera_offset_changed){
3394 update_draw_list_timer = 0;
3395 client.getEnv().getClientMap().updateDrawList(driver);
3396 update_draw_list_last_cam_dir = camera_direction;
3400 make sure menu is on top
3402 if ((!noMenuActive()) && (current_formspec)) {
3403 guiroot->bringToFront(current_formspec);
3409 TimeTaker tt_draw("mainloop: draw");
3411 TimeTaker timer("beginScene");
3412 driver->beginScene(true, true, skycolor);
3413 beginscenetime = timer.stop(true);
3417 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3418 hilightboxes, screensize, skycolor, show_hud);
3423 if(show_profiler_graph)
3425 graph.draw(10, screensize.Y - 10, driver, font);
3431 if(damage_flash > 0.0)
3433 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3434 driver->draw2DRectangle(color,
3435 core::rect<s32>(0,0,screensize.X,screensize.Y),
3438 damage_flash -= 100.0*dtime;
3444 if(player->hurt_tilt_timer > 0.0)
3446 player->hurt_tilt_timer -= dtime*5;
3447 if(player->hurt_tilt_timer < 0)
3448 player->hurt_tilt_strength = 0;
3455 TimeTaker timer("endScene");
3457 endscenetime = timer.stop(true);
3460 drawtime = tt_draw.stop(true);
3461 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3468 Log times and stuff for visualization
3470 Profiler::GraphValues values;
3471 g_profiler->graphGet(values);
3480 if (gui_chat_console)
3481 gui_chat_console->drop();
3487 while (g_menumgr.menuCount() > 0)
3489 g_menumgr.m_stack.front()->setVisible(false);
3490 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3493 Draw a "shutting down" screen, which will be shown while the map
3494 generator and other stuff quits
3497 wchar_t* text = wgettext("Shutting down stuff...");
3498 draw_load_screen(text, device, guienv, font, 0, -1, false);
3502 chat_backend.addMessage(L"", L"# Disconnected.");
3503 chat_backend.addMessage(L"", L"");
3507 //force answer all texture and shader jobs (TODO return empty values)
3509 while(!client.isShutdown()) {
3510 tsrc->processQueue();
3511 shsrc->processQueue();
3515 // Client scope (client is destructed before destructing *def and tsrc)
3518 catch(SerializationError &e)
3520 error_message = L"A serialization error occurred:\n"
3521 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3522 L" running a different version of Minetest.";
3523 errorstream<<wide_to_narrow(error_message)<<std::endl;
3525 catch(ServerError &e) {
3526 error_message = narrow_to_wide(e.what());
3527 errorstream << "ServerError: " << e.what() << std::endl;
3529 catch(ModError &e) {
3530 errorstream << "ModError: " << e.what() << std::endl;
3531 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3539 //has to be deleted first to stop all server threads
3547 //extended resource accounting
3548 infostream << "Irrlicht resources after cleanup:" << std::endl;
3549 infostream << "\tRemaining meshes : "
3550 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3551 infostream << "\tRemaining textures : "
3552 << driver->getTextureCount() << std::endl;
3553 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3554 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3555 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3558 clearTextureNameCache();
3559 infostream << "\tRemaining materials: "
3560 << driver-> getMaterialRendererCount ()
3561 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;