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.
25 #include "client/tile.h" // For TextureSource
26 #include "clientmap.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
43 #include "logoutputbuffer.h"
44 #include "mainmenumanager.h"
46 #include "nodedef.h" // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
50 #include "quicktune_shortcutter.h"
53 #include "shader.h" // For ShaderSource
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
65 #include "sound_openal.h"
68 #ifdef HAVE_TOUCHSCREENGUI
69 #include "touchscreengui.h"
72 extern Settings *g_settings;
73 extern Profiler *g_profiler;
79 struct TextDestNodeMetadata : public TextDest {
80 TextDestNodeMetadata(v3s16 p, Client *client)
85 // This is deprecated I guess? -celeron55
86 void gotText(std::wstring text)
88 std::string ntext = wide_to_narrow(text);
89 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
90 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
92 fields["text"] = ntext;
93 m_client->sendNodemetaFields(m_p, "", fields);
95 void gotText(const StringMap &fields)
97 m_client->sendNodemetaFields(m_p, "", fields);
104 struct TextDestPlayerInventory : public TextDest {
105 TextDestPlayerInventory(Client *client)
110 TextDestPlayerInventory(Client *client, std::string formname)
113 m_formname = formname;
115 void gotText(const StringMap &fields)
117 m_client->sendInventoryFields(m_formname, fields);
123 struct LocalFormspecHandler : public TextDest {
124 LocalFormspecHandler();
125 LocalFormspecHandler(std::string formname) :
128 m_formname = formname;
131 LocalFormspecHandler(std::string formname, Client *client) :
134 m_formname = formname;
137 void gotText(std::wstring message)
139 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
142 void gotText(const StringMap &fields)
144 if (m_formname == "MT_PAUSE_MENU") {
145 if (fields.find("btn_sound") != fields.end()) {
146 g_gamecallback->changeVolume();
150 if (fields.find("btn_key_config") != fields.end()) {
151 g_gamecallback->keyConfig();
155 if (fields.find("btn_exit_menu") != fields.end()) {
156 g_gamecallback->disconnect();
160 if (fields.find("btn_exit_os") != fields.end()) {
161 g_gamecallback->exitToOS();
165 if (fields.find("btn_change_password") != fields.end()) {
166 g_gamecallback->changePassword();
170 if (fields.find("quit") != fields.end()) {
174 if (fields.find("btn_continue") != fields.end()) {
179 if (m_formname == "MT_CHAT_MENU") {
180 assert(m_client != 0);
182 if ((fields.find("btn_send") != fields.end()) ||
183 (fields.find("quit") != fields.end())) {
184 StringMap::const_iterator it = fields.find("f_text");
185 if (it != fields.end())
186 m_client->typeChatMessage(narrow_to_wide(it->second));
192 if (m_formname == "MT_DEATH_SCREEN") {
193 assert(m_client != 0);
195 if ((fields.find("btn_respawn") != fields.end())) {
196 m_client->sendRespawn();
200 if (fields.find("quit") != fields.end()) {
201 m_client->sendRespawn();
206 // don't show error message for unhandled cursor keys
207 if ((fields.find("key_up") != fields.end()) ||
208 (fields.find("key_down") != fields.end()) ||
209 (fields.find("key_left") != fields.end()) ||
210 (fields.find("key_right") != fields.end())) {
214 errorstream << "LocalFormspecHandler::gotText unhandled >"
215 << m_formname << "< event" << std::endl;
218 StringMap::const_iterator it;
219 for (it = fields.begin(); it != fields.end(); ++it) {
220 errorstream << "\t" << i << ": " << it->first
221 << "=" << it->second << std::endl;
229 /* Form update callback */
231 class NodeMetadataFormSource: public IFormSource
234 NodeMetadataFormSource(ClientMap *map, v3s16 p):
239 std::string getForm()
241 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
246 return meta->getString("formspec");
248 std::string resolveText(std::string str)
250 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
255 return meta->resolveString(str);
262 class PlayerInventoryFormSource: public IFormSource
265 PlayerInventoryFormSource(Client *client):
269 std::string getForm()
271 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
272 return player->inventory_formspec;
279 Check if a node is pointable
281 inline bool isPointableNode(const MapNode &n,
282 Client *client, bool liquids_pointable)
284 const ContentFeatures &features = client->getNodeDefManager()->get(n);
285 return features.pointable ||
286 (liquids_pointable && features.isLiquid());
290 Find what the player is pointing at
292 PointedThing getPointedThing(Client *client, v3f player_position,
293 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
294 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
295 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
299 hilightboxes.clear();
300 selected_object = NULL;
302 INodeDefManager *nodedef = client->getNodeDefManager();
303 ClientMap &map = client->getEnv().getClientMap();
305 f32 mindistance = BS * 1001;
307 // First try to find a pointed at active object
308 if (look_for_object) {
309 selected_object = client->getSelectedActiveObject(d * BS,
310 camera_position, shootline);
312 if (selected_object != NULL) {
313 if (selected_object->doShowSelectionBox()) {
314 aabb3f *selection_box = selected_object->getSelectionBox();
315 // Box should exist because object was
316 // returned in the first place
317 assert(selection_box);
319 v3f pos = selected_object->getPosition();
320 hilightboxes.push_back(aabb3f(
321 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
322 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
325 mindistance = (selected_object->getPosition() - camera_position).getLength();
327 result.type = POINTEDTHING_OBJECT;
328 result.object_id = selected_object->getId();
332 // That didn't work, try to find a pointed at node
335 v3s16 pos_i = floatToInt(player_position, BS);
337 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
341 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
342 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
343 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
344 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
345 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
346 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
348 // Prevent signed number overflow
358 for (s16 y = ystart; y <= yend; y++)
359 for (s16 z = zstart; z <= zend; z++)
360 for (s16 x = xstart; x <= xend; x++) {
362 bool is_valid_position;
364 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
365 if (!is_valid_position)
368 if (!isPointableNode(n, client, liquids_pointable))
371 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
374 v3f npf = intToFloat(np, BS);
376 for (std::vector<aabb3f>::const_iterator
378 i != boxes.end(); i++) {
383 for (u16 j = 0; j < 6; j++) {
384 v3s16 facedir = g_6dirs[j];
385 aabb3f facebox = box;
390 facebox.MinEdge.X = facebox.MaxEdge.X - d;
391 else if (facedir.X < 0)
392 facebox.MaxEdge.X = facebox.MinEdge.X + d;
393 else if (facedir.Y > 0)
394 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
395 else if (facedir.Y < 0)
396 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
397 else if (facedir.Z > 0)
398 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
399 else if (facedir.Z < 0)
400 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
402 v3f centerpoint = facebox.getCenter();
403 f32 distance = (centerpoint - camera_position).getLength();
405 if (distance >= mindistance)
408 if (!facebox.intersectsWithLine(shootline))
411 v3s16 np_above = np + facedir;
413 result.type = POINTEDTHING_NODE;
414 result.node_undersurface = np;
415 result.node_abovesurface = np_above;
416 mindistance = distance;
418 hilightboxes.clear();
420 if (!g_settings->getBool("enable_node_highlighting")) {
421 for (std::vector<aabb3f>::const_iterator
423 i2 != boxes.end(); i2++) {
425 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
426 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
427 hilightboxes.push_back(box);
437 /* Profiler display */
439 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
440 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
442 if (show_profiler == 0) {
443 guitext_profiler->setVisible(false);
446 std::ostringstream os(std::ios_base::binary);
447 g_profiler->printPage(os, show_profiler, show_profiler_max);
448 std::wstring text = narrow_to_wide(os.str());
449 guitext_profiler->setText(text.c_str());
450 guitext_profiler->setVisible(true);
452 s32 w = fe->getTextWidth(text.c_str());
457 unsigned text_height = fe->getTextHeight();
459 core::position2di upper_left, lower_right;
462 upper_left.Y = (text_height + 5) * 2;
463 lower_right.X = 12 + w;
464 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
466 if (lower_right.Y > screen_height * 2 / 3)
467 lower_right.Y = screen_height * 2 / 3;
469 core::rect<s32> rect(upper_left, lower_right);
471 guitext_profiler->setRelativePosition(rect);
472 guitext_profiler->setVisible(true);
480 Profiler::GraphValues values;
486 Meta(float initial = 0,
487 video::SColor color = video::SColor(255, 255, 255, 255)):
493 std::vector<Piece> m_log;
501 void put(const Profiler::GraphValues &values)
504 piece.values = values;
505 m_log.push_back(piece);
507 while (m_log.size() > m_log_max_size)
508 m_log.erase(m_log.begin());
511 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
512 gui::IGUIFont *font) const
514 std::map<std::string, Meta> m_meta;
516 for (std::vector<Piece>::const_iterator k = m_log.begin();
517 k != m_log.end(); k++) {
518 const Piece &piece = *k;
520 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
521 i != piece.values.end(); i++) {
522 const std::string &id = i->first;
523 const float &value = i->second;
524 std::map<std::string, Meta>::iterator j =
527 if (j == m_meta.end()) {
528 m_meta[id] = Meta(value);
532 if (value < j->second.min)
533 j->second.min = value;
535 if (value > j->second.max)
536 j->second.max = value;
541 static const video::SColor usable_colors[] = {
542 video::SColor(255, 255, 100, 100),
543 video::SColor(255, 90, 225, 90),
544 video::SColor(255, 100, 100, 255),
545 video::SColor(255, 255, 150, 50),
546 video::SColor(255, 220, 220, 100)
548 static const u32 usable_colors_count =
549 sizeof(usable_colors) / sizeof(*usable_colors);
550 u32 next_color_i = 0;
552 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
553 i != m_meta.end(); i++) {
554 Meta &meta = i->second;
555 video::SColor color(255, 200, 200, 200);
557 if (next_color_i < usable_colors_count)
558 color = usable_colors[next_color_i++];
564 s32 textx = x_left + m_log_max_size + 15;
565 s32 textx2 = textx + 200 - 15;
568 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
569 i != m_meta.end(); i++) {
570 const std::string &id = i->first;
571 const Meta &meta = i->second;
573 s32 y = y_bottom - meta_i * 50;
574 float show_min = meta.min;
575 float show_max = meta.max;
577 if (show_min >= -0.0001 && show_max >= -0.0001) {
578 if (show_min <= show_max * 0.5)
584 snprintf(buf, 10, "%.3g", show_max);
585 font->draw(narrow_to_wide(buf).c_str(),
586 core::rect<s32>(textx, y - graphh,
587 textx2, y - graphh + texth),
589 snprintf(buf, 10, "%.3g", show_min);
590 font->draw(narrow_to_wide(buf).c_str(),
591 core::rect<s32>(textx, y - texth,
594 font->draw(narrow_to_wide(id).c_str(),
595 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
596 textx2, y - graphh / 2 + texth / 2),
599 s32 graph1h = graphh;
600 bool relativegraph = (show_min != 0 && show_min != show_max);
601 float lastscaledvalue = 0.0;
602 bool lastscaledvalue_exists = false;
604 for (std::vector<Piece>::const_iterator j = m_log.begin();
605 j != m_log.end(); j++) {
606 const Piece &piece = *j;
608 bool value_exists = false;
609 Profiler::GraphValues::const_iterator k =
610 piece.values.find(id);
612 if (k != piece.values.end()) {
619 lastscaledvalue_exists = false;
623 float scaledvalue = 1.0;
625 if (show_max != show_min)
626 scaledvalue = (value - show_min) / (show_max - show_min);
628 if (scaledvalue == 1.0 && value == 0) {
630 lastscaledvalue_exists = false;
635 if (lastscaledvalue_exists) {
636 s32 ivalue1 = lastscaledvalue * graph1h;
637 s32 ivalue2 = scaledvalue * graph1h;
638 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
639 v2s32(x, graph1y - ivalue2), meta.color);
642 lastscaledvalue = scaledvalue;
643 lastscaledvalue_exists = true;
645 s32 ivalue = scaledvalue * graph1h;
646 driver->draw2DLine(v2s32(x, graph1y),
647 v2s32(x, graph1y - ivalue), meta.color);
658 class NodeDugEvent: public MtEvent
664 NodeDugEvent(v3s16 p, MapNode n):
668 const char *getType() const
676 ISoundManager *m_sound;
677 INodeDefManager *m_ndef;
679 float m_player_step_timer;
681 SimpleSoundSpec m_player_step_sound;
682 SimpleSoundSpec m_player_leftpunch_sound;
683 SimpleSoundSpec m_player_rightpunch_sound;
685 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
688 m_player_step_timer(0)
692 void playPlayerStep()
694 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
695 m_player_step_timer = 0.03;
696 m_sound->playSound(m_player_step_sound, false);
700 static void viewBobbingStep(MtEvent *e, void *data)
702 SoundMaker *sm = (SoundMaker *)data;
703 sm->playPlayerStep();
706 static void playerRegainGround(MtEvent *e, void *data)
708 SoundMaker *sm = (SoundMaker *)data;
709 sm->playPlayerStep();
712 static void playerJump(MtEvent *e, void *data)
714 //SoundMaker *sm = (SoundMaker*)data;
717 static void cameraPunchLeft(MtEvent *e, void *data)
719 SoundMaker *sm = (SoundMaker *)data;
720 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
723 static void cameraPunchRight(MtEvent *e, void *data)
725 SoundMaker *sm = (SoundMaker *)data;
726 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
729 static void nodeDug(MtEvent *e, void *data)
731 SoundMaker *sm = (SoundMaker *)data;
732 NodeDugEvent *nde = (NodeDugEvent *)e;
733 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
736 static void playerDamage(MtEvent *e, void *data)
738 SoundMaker *sm = (SoundMaker *)data;
739 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
742 static void playerFallingDamage(MtEvent *e, void *data)
744 SoundMaker *sm = (SoundMaker *)data;
745 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
748 void registerReceiver(MtEventManager *mgr)
750 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
751 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
752 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
753 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
754 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
755 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
756 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
757 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
760 void step(float dtime)
762 m_player_step_timer -= dtime;
766 // Locally stored sounds don't need to be preloaded because of this
767 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
769 std::set<std::string> m_fetched;
771 void fetchSounds(const std::string &name,
772 std::set<std::string> &dst_paths,
773 std::set<std::string> &dst_datas)
775 if (m_fetched.count(name))
778 m_fetched.insert(name);
779 std::string base = porting::path_share + DIR_DELIM + "testsounds";
780 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
781 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
782 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
783 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
784 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
785 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
786 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
787 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
788 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
789 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
790 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
794 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
797 bool *m_force_fog_off;
803 void onSettingsChange(const std::string &name)
805 if (name == "enable_fog")
806 m_fogEnabled = g_settings->getBool("enable_fog");
809 static void SettingsCallback(const std::string name, void *userdata)
811 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
814 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
815 f32 *fog_range, Client *client) :
817 m_force_fog_off(force_fog_off),
818 m_fog_range(fog_range),
821 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
822 m_fogEnabled = g_settings->getBool("enable_fog");
825 ~GameGlobalShaderConstantSetter()
827 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
830 virtual void onSetConstants(video::IMaterialRendererServices *services,
837 video::SColor bgcolor = m_sky->getBgColor();
838 video::SColorf bgcolorf(bgcolor);
839 float bgcolorfa[4] = {
845 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
848 float fog_distance = 10000 * BS;
850 if (m_fogEnabled && !*m_force_fog_off)
851 fog_distance = *m_fog_range;
853 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
856 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
857 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
858 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
860 u32 animation_timer = porting::getTimeMs() % 100000;
861 float animation_timer_f = (float)animation_timer / 100000.0;
862 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
863 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
865 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
866 v3f eye_position = player->getEyePosition();
867 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
868 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
870 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
871 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
873 // Uniform sampler layers
877 // before 1.8 there isn't a "integer interface", only float
878 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
879 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
880 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
881 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
883 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
884 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
885 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
890 bool nodePlacementPrediction(Client &client,
891 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
893 std::string prediction = playeritem_def.node_placement_prediction;
894 INodeDefManager *nodedef = client.ndef();
895 ClientMap &map = client.getEnv().getClientMap();
897 bool is_valid_position;
899 node = map.getNodeNoEx(nodepos, &is_valid_position);
900 if (!is_valid_position)
903 if (prediction != "" && !nodedef->get(node).rightclickable) {
904 verbosestream << "Node placement prediction for "
905 << playeritem_def.name << " is "
906 << prediction << std::endl;
907 v3s16 p = neighbourpos;
909 // Place inside node itself if buildable_to
910 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
911 if (is_valid_position)
913 if (nodedef->get(n_under).buildable_to)
916 node = map.getNodeNoEx(p, &is_valid_position);
917 if (is_valid_position &&!nodedef->get(node).buildable_to)
922 // Find id of predicted node
924 bool found = nodedef->getId(prediction, id);
927 errorstream << "Node placement prediction failed for "
928 << playeritem_def.name << " (places "
930 << ") - Name not known" << std::endl;
934 // Predict param2 for facedir and wallmounted nodes
937 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
938 v3s16 dir = nodepos - neighbourpos;
940 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
941 param2 = dir.Y < 0 ? 1 : 0;
942 } else if (abs(dir.X) > abs(dir.Z)) {
943 param2 = dir.X < 0 ? 3 : 2;
945 param2 = dir.Z < 0 ? 5 : 4;
949 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
950 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
952 if (abs(dir.X) > abs(dir.Z)) {
953 param2 = dir.X < 0 ? 3 : 1;
955 param2 = dir.Z < 0 ? 2 : 0;
961 //Check attachment if node is in group attached_node
962 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
963 static v3s16 wallmounted_dirs[8] = {
973 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
974 pp = p + wallmounted_dirs[param2];
976 pp = p + v3s16(0, -1, 0);
978 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
982 // Add node to client map
983 MapNode n(id, 0, param2);
986 LocalPlayer *player = client.getEnv().getLocalPlayer();
988 // Dont place node when player would be inside new node
989 // NOTE: This is to be eventually implemented by a mod as client-side Lua
990 if (!nodedef->get(n).walkable ||
991 g_settings->getBool("enable_build_where_you_stand") ||
992 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
993 (nodedef->get(n).walkable &&
994 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
995 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
997 // This triggers the required mesh update too
998 client.addNode(p, n);
1001 } catch (InvalidPositionException &e) {
1002 errorstream << "Node placement prediction failed for "
1003 << playeritem_def.name << " (places "
1005 << ") - Position not loaded" << std::endl;
1012 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1013 InventoryManager *invmgr, IGameDef *gamedef,
1014 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1015 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1018 if (*cur_formspec == 0) {
1019 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1020 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1021 (*cur_formspec)->doPause = false;
1024 Caution: do not call (*cur_formspec)->drop() here --
1025 the reference might outlive the menu, so we will
1026 periodically check if *cur_formspec is the only
1027 remaining reference (i.e. the menu was removed)
1028 and delete it in that case.
1032 (*cur_formspec)->setFormSource(fs_src);
1033 (*cur_formspec)->setTextDest(txt_dest);
1038 #define SIZE_TAG "size[11,5.5]"
1040 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1043 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1044 InventoryManager *invmgr, IGameDef *gamedef,
1045 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1046 Client *client, std::string text)
1048 std::string formspec =
1049 FORMSPEC_VERSION_STRING
1051 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1052 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1056 /* Note: FormspecFormSource and LocalFormspecHandler
1057 * are deleted by guiFormSpecMenu */
1058 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1059 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1061 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1064 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1065 InventoryManager *invmgr, IGameDef *gamedef,
1066 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1068 std::string formspec =
1069 std::string(FORMSPEC_VERSION_STRING) +
1071 "bgcolor[#320000b4;true]"
1072 "label[4.85,1.35;" + gettext("You died.") + "]"
1073 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1077 /* Note: FormspecFormSource and LocalFormspecHandler
1078 * are deleted by guiFormSpecMenu */
1079 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1080 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1082 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1085 /******************************************************************************/
1086 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1087 InventoryManager *invmgr, IGameDef *gamedef,
1088 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1089 bool singleplayermode)
1092 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1093 "No menu visible:\n"
1094 "- single tap: button activate\n"
1095 "- double tap: place/use\n"
1096 "- slide finger: look around\n"
1097 "Menu/Inventory visible:\n"
1098 "- double tap (outside):\n"
1100 "- touch stack, touch slot:\n"
1102 "- touch&drag, tap 2nd finger\n"
1103 " --> place single item to slot\n"
1106 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1108 "- Space: jump/climb\n"
1109 "- Shift: sneak/go down\n"
1112 "- Mouse: turn/look\n"
1113 "- Mouse left: dig/punch\n"
1114 "- Mouse right: place/use\n"
1115 "- Mouse wheel: select item\n"
1120 float ypos = singleplayermode ? 0.5 : 0.1;
1121 std::ostringstream os;
1123 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1124 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1125 << wide_to_narrow(wstrgettext("Continue")) << "]";
1127 if (!singleplayermode) {
1128 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1129 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1133 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1134 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1135 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1136 << wide_to_narrow(wstrgettext("Change Keys")) << "]";
1138 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1139 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1140 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1141 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1142 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1143 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1144 << g_build_info << "\n"
1145 << "path_user = " << wrap_rows(porting::path_user, 20)
1149 /* Note: FormspecFormSource and LocalFormspecHandler *
1150 * are deleted by guiFormSpecMenu */
1151 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1152 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1154 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1155 std::string con("btn_continue");
1156 (*cur_formspec)->setFocus(con);
1157 (*cur_formspec)->doPause = true;
1160 /******************************************************************************/
1161 static void updateChat(Client &client, f32 dtime, bool show_debug,
1162 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1163 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1165 // Add chat log output for errors to be shown in chat
1166 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1168 // Get new messages from error log buffer
1169 while (!chat_log_error_buf.empty()) {
1170 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1173 // Get new messages from client
1174 std::wstring message;
1176 while (client.getChatMessage(message)) {
1177 chat_backend.addUnparsedMessage(message);
1180 // Remove old messages
1181 chat_backend.step(dtime);
1183 // Display all messages in a static text element
1184 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1185 std::wstring recent_chat = chat_backend.getRecentChat();
1186 unsigned int line_height = g_fontengine->getLineHeight();
1188 guitext_chat->setText(recent_chat.c_str());
1190 // Update gui element size and position
1191 s32 chat_y = 5 + line_height;
1194 chat_y += line_height;
1196 // first pass to calculate height of text to be set
1197 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1198 porting::getWindowSize().X - 20);
1199 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1200 guitext_chat->setRelativePosition(rect);
1202 //now use real height of text and adjust rect according to this size
1203 rect = core::rect<s32>(10, chat_y, width,
1204 chat_y + guitext_chat->getTextHeight());
1207 guitext_chat->setRelativePosition(rect);
1208 // Don't show chat if disabled or empty or profiler is enabled
1209 guitext_chat->setVisible(
1210 show_chat && recent_chat_count != 0 && !show_profiler);
1214 /****************************************************************************
1215 Fast key cache for main game loop
1216 ****************************************************************************/
1218 /* This is faster than using getKeySetting with the tradeoff that functions
1219 * using it must make sure that it's initialised before using it and there is
1220 * no error handling (for example bounds checking). This is really intended for
1221 * use only in the main running loop of the client (the_game()) where the faster
1222 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1223 * (e.g. formspecs) should continue using getKeySetting().
1227 KeyCache() { populate(); }
1241 KEYMAP_ID_INVENTORY,
1249 KEYMAP_ID_CINEMATIC,
1250 KEYMAP_ID_SCREENSHOT,
1251 KEYMAP_ID_TOGGLE_HUD,
1252 KEYMAP_ID_TOGGLE_CHAT,
1253 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1254 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1255 KEYMAP_ID_TOGGLE_DEBUG,
1256 KEYMAP_ID_TOGGLE_PROFILER,
1257 KEYMAP_ID_CAMERA_MODE,
1258 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1259 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1260 KEYMAP_ID_RANGESELECT,
1262 KEYMAP_ID_QUICKTUNE_NEXT,
1263 KEYMAP_ID_QUICKTUNE_PREV,
1264 KEYMAP_ID_QUICKTUNE_INC,
1265 KEYMAP_ID_QUICKTUNE_DEC,
1267 KEYMAP_ID_DEBUG_STACKS,
1269 // Fake keycode for array size and internal checks
1270 KEYMAP_INTERNAL_ENUM_COUNT
1277 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1280 void KeyCache::populate()
1282 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1283 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1284 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1285 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1286 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1287 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1288 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1290 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1291 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1292 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1293 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1294 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1295 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1296 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1297 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1298 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1299 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1300 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1301 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1302 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1303 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1304 = getKeySetting("keymap_toggle_force_fog_off");
1305 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1306 = getKeySetting("keymap_toggle_update_camera");
1307 key[KEYMAP_ID_TOGGLE_DEBUG]
1308 = getKeySetting("keymap_toggle_debug");
1309 key[KEYMAP_ID_TOGGLE_PROFILER]
1310 = getKeySetting("keymap_toggle_profiler");
1311 key[KEYMAP_ID_CAMERA_MODE]
1312 = getKeySetting("keymap_camera_mode");
1313 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1314 = getKeySetting("keymap_increase_viewing_range_min");
1315 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1316 = getKeySetting("keymap_decrease_viewing_range_min");
1317 key[KEYMAP_ID_RANGESELECT]
1318 = getKeySetting("keymap_rangeselect");
1320 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1321 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1322 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1323 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1325 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1329 /****************************************************************************
1331 ****************************************************************************/
1333 const float object_hit_delay = 0.2;
1336 u32 last_time, busy_time, sleep_time;
1340 /* The reason the following structs are not anonymous structs within the
1341 * class is that they are not used by the majority of member functions and
1342 * many functions that do require objects of thse types do not modify them
1343 * (so they can be passed as a const qualified parameter)
1345 struct CameraOrientation {
1346 f32 camera_yaw; // "right/left"
1347 f32 camera_pitch; // "up/down"
1350 struct GameRunData {
1353 PointedThing pointed_old;
1357 bool update_wielded_item_trigger;
1358 bool reset_jump_timer;
1359 float nodig_delay_timer;
1361 float dig_time_complete;
1362 float repeat_rightclick_timer;
1363 float object_hit_delay_timer;
1364 float time_from_last_punch;
1365 ClientActiveObject *selected_object;
1369 float update_draw_list_timer;
1370 float statustext_time;
1374 v3f update_draw_list_last_cam_dir;
1376 u32 profiler_current_page;
1377 u32 profiler_max_page; // Number of pages
1380 float time_of_day_smooth;
1384 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1392 Jitter dtime_jitter, busy_time_jitter;
1395 /* Flags that can, or may, change during main game loop
1397 struct VolatileRunFlags {
1404 bool show_profiler_graph;
1405 bool disable_camera_update;
1406 bool first_loop_after_window_activation;
1407 bool camera_offset_changed;
1411 /****************************************************************************
1413 ****************************************************************************/
1415 /* This is not intended to be a public class. If a public class becomes
1416 * desirable then it may be better to create another 'wrapper' class that
1417 * hides most of the stuff in this class (nothing in this class is required
1418 * by any other file) but exposes the public methods/data only.
1426 bool startup(bool *kill,
1428 InputHandler *input,
1429 IrrlichtDevice *device,
1430 const std::string &map_dir,
1431 const std::string &playername,
1432 const std::string &password,
1433 // If address is "", local server is used and address is updated
1434 std::string *address,
1436 std::string &error_message,
1437 ChatBackend *chat_backend,
1438 const SubgameSpec &gamespec, // Used for local game
1439 bool simple_singleplayer_mode);
1446 void extendedResourceCleanup();
1448 // Basic initialisation
1449 bool init(const std::string &map_dir, std::string *address,
1451 const SubgameSpec &gamespec);
1453 bool createSingleplayerServer(const std::string map_dir,
1454 const SubgameSpec &gamespec, u16 port, std::string *address);
1457 bool createClient(const std::string &playername,
1458 const std::string &password, std::string *address, u16 port);
1461 // Client connection
1462 bool connectToServer(const std::string &playername,
1463 const std::string &password, std::string *address, u16 port,
1464 bool *connect_ok, bool *aborted);
1465 bool getServerContent(bool *aborted);
1469 void updateInteractTimers(GameRunData *runData, f32 dtime);
1470 bool checkConnection();
1471 bool handleCallbacks();
1472 void processQueues();
1473 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1474 const FpsControl &draw_times, f32 dtime);
1475 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1477 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1479 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1481 void processKeyboardInput(VolatileRunFlags *flags,
1482 float *statustext_time,
1484 bool *reset_jump_timer,
1485 u32 *profiler_current_page,
1486 u32 profiler_max_page);
1487 void processItemSelection(u16 *new_playeritem);
1489 void dropSelectedItem();
1490 void openInventory();
1492 void toggleFreeMove(float *statustext_time);
1493 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1494 void toggleFast(float *statustext_time);
1495 void toggleNoClip(float *statustext_time);
1496 void toggleCinematic(float *statustext_time);
1498 void toggleChat(float *statustext_time, bool *flag);
1499 void toggleHud(float *statustext_time, bool *flag);
1500 void toggleMinimap(float *statustext_time, bool *flag1, bool *flag2,
1501 bool shift_pressed);
1502 void toggleFog(float *statustext_time, bool *flag);
1503 void toggleDebug(float *statustext_time, bool *show_debug,
1504 bool *show_profiler_graph);
1505 void toggleUpdateCamera(float *statustext_time, bool *flag);
1506 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1507 u32 profiler_max_page);
1509 void increaseViewRange(float *statustext_time);
1510 void decreaseViewRange(float *statustext_time);
1511 void toggleFullViewRange(float *statustext_time);
1513 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1514 void updateCameraOrientation(CameraOrientation *cam,
1515 const VolatileRunFlags &flags);
1516 void updatePlayerControl(const CameraOrientation &cam);
1517 void step(f32 *dtime);
1518 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1519 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1520 float time_from_last_punch);
1521 void updateSound(f32 dtime);
1522 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1523 GameRunData *runData, f32 dtime, bool show_hud,
1525 void handlePointingAtNode(GameRunData *runData,
1526 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1527 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1528 void handlePointingAtObject(GameRunData *runData,
1529 const PointedThing &pointed, const ItemStack &playeritem,
1530 const v3f &player_position, bool show_debug);
1531 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1532 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1534 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1535 RunStats *stats, GameRunData *runData,
1536 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1537 void updateGui(float *statustext_time, const RunStats &stats,
1538 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1539 const CameraOrientation &cam);
1540 void updateProfilerGraphs(ProfilerGraph *graph);
1543 void limitFps(FpsControl *fps_timings, f32 *dtime);
1545 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1546 bool draw_clouds = true);
1549 InputHandler *input;
1554 IWritableTextureSource *texture_src;
1555 IWritableShaderSource *shader_src;
1557 // When created, these will be filled with data received from the server
1558 IWritableItemDefManager *itemdef_manager;
1559 IWritableNodeDefManager *nodedef_manager;
1561 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1562 ISoundManager *sound;
1563 bool sound_is_dummy;
1564 SoundMaker *soundmaker;
1566 ChatBackend *chat_backend;
1568 GUIFormSpecMenu *current_formspec;
1570 EventManager *eventmgr;
1571 QuicktuneShortcutter *quicktune;
1573 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1574 MapDrawControl *draw_control;
1576 Clouds *clouds; // Free using ->Drop()
1577 Sky *sky; // Free using ->Drop()
1578 Inventory *local_inventory;
1583 This class does take ownership/responsibily for cleaning up etc of any of
1584 these items (e.g. device)
1586 IrrlichtDevice *device;
1587 video::IVideoDriver *driver;
1588 scene::ISceneManager *smgr;
1590 std::string *error_message;
1591 IGameDef *gamedef; // Convenience (same as *client)
1592 scene::ISceneNode *skybox;
1595 bool simple_singleplayer_mode;
1598 /* Pre-calculated values
1600 int crack_animation_length;
1604 gui::IGUIStaticText *guitext; // First line of debug text
1605 gui::IGUIStaticText *guitext2; // Second line of debug text
1606 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1607 gui::IGUIStaticText *guitext_status;
1608 gui::IGUIStaticText *guitext_chat; // Chat text
1609 gui::IGUIStaticText *guitext_profiler; // Profiler text
1611 std::wstring infotext;
1612 std::wstring statustext;
1616 IntervalLimiter profiler_interval;
1618 /* TODO: Add a callback function so these can be updated when a setting
1619 * changes. At this point in time it doesn't matter (e.g. /set
1620 * is documented to change server settings only)
1622 * TODO: Local caching of settings is not optimal and should at some stage
1623 * be updated to use a global settings object for getting thse values
1624 * (as opposed to the this local caching). This can be addressed in
1627 bool m_cache_doubletap_jump;
1628 bool m_cache_enable_node_highlighting;
1629 bool m_cache_enable_clouds;
1630 bool m_cache_enable_particles;
1631 bool m_cache_enable_fog;
1632 f32 m_cache_mouse_sensitivity;
1633 f32 m_repeat_right_click_time;
1636 bool m_cache_hold_aux1;
1646 itemdef_manager(NULL),
1647 nodedef_manager(NULL),
1649 sound_is_dummy(false),
1652 current_formspec(NULL),
1655 gui_chat_console(NULL),
1660 local_inventory(NULL),
1664 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
1665 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
1666 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
1667 m_cache_enable_particles = g_settings->getBool("enable_particles");
1668 m_cache_enable_fog = g_settings->getBool("enable_fog");
1669 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
1670 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
1672 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1675 m_cache_hold_aux1 = false; // This is initialised properly later
1682 /****************************************************************************
1684 ****************************************************************************/
1690 if (!sound_is_dummy)
1693 delete server; // deleted first to stop all server threads
1696 delete local_inventory;
1702 delete nodedef_manager;
1703 delete itemdef_manager;
1704 delete draw_control;
1706 extendedResourceCleanup();
1709 bool Game::startup(bool *kill,
1711 InputHandler *input,
1712 IrrlichtDevice *device,
1713 const std::string &map_dir,
1714 const std::string &playername,
1715 const std::string &password,
1716 std::string *address, // can change if simple_singleplayer_mode
1718 std::string &error_message,
1719 ChatBackend *chat_backend,
1720 const SubgameSpec &gamespec,
1721 bool simple_singleplayer_mode)
1724 this->device = device;
1726 this->error_message = &error_message;
1727 this->random_input = random_input;
1728 this->input = input;
1729 this->chat_backend = chat_backend;
1730 this->simple_singleplayer_mode = simple_singleplayer_mode;
1732 driver = device->getVideoDriver();
1733 smgr = device->getSceneManager();
1735 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1737 if (!init(map_dir, address, port, gamespec))
1740 if (!createClient(playername, password, address, port))
1749 ProfilerGraph graph;
1750 RunStats stats = { 0 };
1751 CameraOrientation cam_view_target = { 0 };
1752 CameraOrientation cam_view = { 0 };
1753 GameRunData runData = { 0 };
1754 FpsControl draw_times = { 0 };
1755 VolatileRunFlags flags = { 0 };
1756 f32 dtime; // in seconds
1758 runData.time_from_last_punch = 10.0;
1759 runData.profiler_max_page = 3;
1760 runData.update_wielded_item_trigger = true;
1762 flags.show_chat = true;
1763 flags.show_hud = true;
1764 flags.show_minimap = g_settings->getBool("enable_minimap");
1765 flags.show_debug = g_settings->getBool("show_debug");
1766 flags.invert_mouse = g_settings->getBool("invert_mouse");
1767 flags.first_loop_after_window_activation = true;
1769 /* Clear the profiler */
1770 Profiler::GraphValues dummyvalues;
1771 g_profiler->graphGet(dummyvalues);
1773 draw_times.last_time = device->getTimer()->getTime();
1775 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1777 &flags.force_fog_off,
1781 std::vector<aabb3f> highlight_boxes;
1783 set_light_table(g_settings->getFloat("display_gamma"));
1786 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1787 && client->checkPrivilege("fast");
1790 while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1792 /* Must be called immediately after a device->run() call because it
1793 * uses device->getTimer()->getTime()
1795 limitFps(&draw_times, &dtime);
1797 updateStats(&stats, draw_times, dtime);
1798 updateInteractTimers(&runData, dtime);
1800 if (!checkConnection())
1802 if (!handleCallbacks())
1808 hud->resizeHotbar();
1810 updateProfilers(runData, stats, draw_times, dtime);
1811 processUserInput(&flags, &runData, dtime);
1812 // Update camera before player movement to avoid camera lag of one frame
1813 updateCameraDirection(&cam_view_target, &flags);
1814 float cam_smoothing = 0;
1815 if (g_settings->getBool("cinematic"))
1816 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1818 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1819 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1820 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1821 cam_view.camera_yaw) * cam_smoothing;
1822 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1823 cam_view.camera_pitch) * cam_smoothing;
1824 updatePlayerControl(cam_view);
1826 processClientEvents(&cam_view_target, &runData.damage_flash);
1827 updateCamera(&flags, draw_times.busy_time, dtime,
1828 runData.time_from_last_punch);
1830 processPlayerInteraction(highlight_boxes, &runData, dtime,
1831 flags.show_hud, flags.show_debug);
1832 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1834 updateProfilerGraphs(&graph);
1839 void Game::shutdown()
1841 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1846 if (gui_chat_console)
1847 gui_chat_console->drop();
1853 while (g_menumgr.menuCount() > 0) {
1854 g_menumgr.m_stack.front()->setVisible(false);
1855 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1858 if (current_formspec) {
1859 current_formspec->drop();
1860 current_formspec = NULL;
1863 chat_backend->addMessage(L"", L"# Disconnected.");
1864 chat_backend->addMessage(L"", L"");
1868 while (!client->isShutdown()) {
1869 assert(texture_src != NULL);
1870 assert(shader_src != NULL);
1871 texture_src->processQueue();
1872 shader_src->processQueue();
1879 /****************************************************************************/
1880 /****************************************************************************
1882 ****************************************************************************/
1883 /****************************************************************************/
1886 const std::string &map_dir,
1887 std::string *address,
1889 const SubgameSpec &gamespec)
1891 showOverlayMessage(wgettext("Loading..."), 0, 0);
1893 texture_src = createTextureSource(device);
1894 shader_src = createShaderSource(device);
1896 itemdef_manager = createItemDefManager();
1897 nodedef_manager = createNodeDefManager();
1899 eventmgr = new EventManager();
1900 quicktune = new QuicktuneShortcutter();
1902 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1903 && eventmgr && quicktune))
1909 // Create a server if not connecting to an existing one
1910 if (*address == "") {
1911 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1918 bool Game::initSound()
1921 if (g_settings->getBool("enable_sound")) {
1922 infostream << "Attempting to use OpenAL audio" << std::endl;
1923 sound = createOpenALSoundManager(&soundfetcher);
1925 infostream << "Failed to initialize OpenAL audio" << std::endl;
1927 infostream << "Sound disabled." << std::endl;
1931 infostream << "Using dummy audio." << std::endl;
1932 sound = &dummySoundManager;
1933 sound_is_dummy = true;
1936 soundmaker = new SoundMaker(sound, nodedef_manager);
1940 soundmaker->registerReceiver(eventmgr);
1945 bool Game::createSingleplayerServer(const std::string map_dir,
1946 const SubgameSpec &gamespec, u16 port, std::string *address)
1948 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1950 std::string bind_str = g_settings->get("bind_address");
1951 Address bind_addr(0, 0, 0, 0, port);
1953 if (g_settings->getBool("ipv6_server")) {
1954 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1958 bind_addr.Resolve(bind_str.c_str());
1959 } catch (ResolveError &e) {
1960 infostream << "Resolving bind address \"" << bind_str
1961 << "\" failed: " << e.what()
1962 << " -- Listening on all addresses." << std::endl;
1965 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1966 *error_message = "Unable to listen on " +
1967 bind_addr.serializeString() +
1968 " because IPv6 is disabled";
1969 errorstream << *error_message << std::endl;
1973 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1974 bind_addr.isIPv6());
1976 server->start(bind_addr);
1981 bool Game::createClient(const std::string &playername,
1982 const std::string &password, std::string *address, u16 port)
1984 showOverlayMessage(wgettext("Creating client..."), 0, 10);
1986 draw_control = new MapDrawControl;
1990 bool could_connect, connect_aborted;
1992 if (!connectToServer(playername, password, address, port,
1993 &could_connect, &connect_aborted))
1996 if (!could_connect) {
1997 if (error_message->empty() && !connect_aborted) {
1998 // Should not happen if error messages are set properly
1999 *error_message = "Connection failed for unknown reason";
2000 errorstream << *error_message << std::endl;
2005 if (!getServerContent(&connect_aborted)) {
2006 if (error_message->empty() && !connect_aborted) {
2007 // Should not happen if error messages are set properly
2008 *error_message = "Connection failed for unknown reason";
2009 errorstream << *error_message << std::endl;
2014 // Update cached textures, meshes and materials
2015 client->afterContentReceived(device);
2019 camera = new Camera(smgr, *draw_control, gamedef);
2020 if (!camera || !camera->successfullyCreated(*error_message))
2025 if (m_cache_enable_clouds) {
2026 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2028 *error_message = "Memory allocation error (clouds)";
2029 errorstream << *error_message << std::endl;
2036 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2037 skybox = NULL; // This is used/set later on in the main run loop
2039 local_inventory = new Inventory(itemdef_manager);
2041 if (!(sky && local_inventory)) {
2042 *error_message = "Memory allocation error (sky or local inventory)";
2043 errorstream << *error_message << std::endl;
2047 /* Pre-calculated values
2049 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2051 v2u32 size = t->getOriginalSize();
2052 crack_animation_length = size.Y / size.X;
2054 crack_animation_length = 5;
2060 /* Set window caption
2062 std::wstring str = narrow_to_wide(PROJECT_NAME_C);
2064 str += driver->getName();
2066 device->setWindowCaption(str.c_str());
2068 LocalPlayer *player = client->getEnv().getLocalPlayer();
2069 player->hurt_tilt_timer = 0;
2070 player->hurt_tilt_strength = 0;
2072 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2075 *error_message = "Memory error: could not create HUD";
2076 errorstream << *error_message << std::endl;
2080 mapper = client->getMapper();
2081 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2086 bool Game::initGui()
2088 // First line of debug text
2089 guitext = guienv->addStaticText(
2090 narrow_to_wide(PROJECT_NAME_C).c_str(),
2091 core::rect<s32>(0, 0, 0, 0),
2092 false, false, guiroot);
2094 // Second line of debug text
2095 guitext2 = guienv->addStaticText(
2097 core::rect<s32>(0, 0, 0, 0),
2098 false, false, guiroot);
2100 // At the middle of the screen
2101 // Object infos are shown in this
2102 guitext_info = guienv->addStaticText(
2104 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2105 false, true, guiroot);
2107 // Status text (displays info when showing and hiding GUI stuff, etc.)
2108 guitext_status = guienv->addStaticText(
2110 core::rect<s32>(0, 0, 0, 0),
2111 false, false, guiroot);
2112 guitext_status->setVisible(false);
2115 guitext_chat = guienv->addStaticText(
2117 core::rect<s32>(0, 0, 0, 0),
2118 //false, false); // Disable word wrap as of now
2119 false, true, guiroot);
2120 // Remove stale "recent" chat messages from previous connections
2121 chat_backend->clearRecentChat();
2123 // Chat backend and console
2124 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2125 -1, chat_backend, client);
2126 if (!gui_chat_console) {
2127 *error_message = "Could not allocate memory for chat console";
2128 errorstream << *error_message << std::endl;
2132 // Profiler text (size is updated when text is updated)
2133 guitext_profiler = guienv->addStaticText(
2135 core::rect<s32>(0, 0, 0, 0),
2136 false, false, guiroot);
2137 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2138 guitext_profiler->setVisible(false);
2139 guitext_profiler->setWordWrap(true);
2141 #ifdef HAVE_TOUCHSCREENGUI
2143 if (g_touchscreengui)
2144 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2151 bool Game::connectToServer(const std::string &playername,
2152 const std::string &password, std::string *address, u16 port,
2153 bool *connect_ok, bool *aborted)
2155 *connect_ok = false; // Let's not be overly optimistic
2157 bool local_server_mode = false;
2159 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2161 Address connect_address(0, 0, 0, 0, port);
2164 connect_address.Resolve(address->c_str());
2166 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2167 //connect_address.Resolve("localhost");
2168 if (connect_address.isIPv6()) {
2169 IPv6AddressBytes addr_bytes;
2170 addr_bytes.bytes[15] = 1;
2171 connect_address.setAddress(&addr_bytes);
2173 connect_address.setAddress(127, 0, 0, 1);
2175 local_server_mode = true;
2177 } catch (ResolveError &e) {
2178 *error_message = std::string("Couldn't resolve address: ") + e.what();
2179 errorstream << *error_message << std::endl;
2183 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2184 *error_message = "Unable to connect to " +
2185 connect_address.serializeString() +
2186 " because IPv6 is disabled";
2187 errorstream << *error_message << std::endl;
2191 client = new Client(device,
2192 playername.c_str(), password,
2193 *draw_control, texture_src, shader_src,
2194 itemdef_manager, nodedef_manager, sound, eventmgr,
2195 connect_address.isIPv6());
2200 gamedef = client; // Client acts as our GameDef
2202 infostream << "Connecting to server at ";
2203 connect_address.print(&infostream);
2204 infostream << std::endl;
2206 client->connect(connect_address, *address,
2207 simple_singleplayer_mode || local_server_mode);
2210 Wait for server to accept connection
2216 FpsControl fps_control = { 0 };
2218 f32 wait_time = 0; // in seconds
2220 fps_control.last_time = device->getTimer()->getTime();
2222 while (device->run()) {
2224 limitFps(&fps_control, &dtime);
2226 // Update client and server
2227 client->step(dtime);
2230 server->step(dtime);
2233 if (client->getState() == LC_Init) {
2239 if (client->accessDenied()) {
2240 *error_message = "Access denied. Reason: "
2241 + client->accessDeniedReason();
2242 errorstream << *error_message << std::endl;
2246 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2248 infostream << "Connect aborted [Escape]" << std::endl;
2253 // Only time out if we aren't waiting for the server we started
2254 if ((*address != "") && (wait_time > 10)) {
2255 *error_message = "Connection timed out.";
2256 errorstream << *error_message << std::endl;
2261 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2263 } catch (con::PeerNotFoundException &e) {
2264 // TODO: Should something be done here? At least an info/error
2272 bool Game::getServerContent(bool *aborted)
2276 FpsControl fps_control = { 0 };
2277 f32 dtime; // in seconds
2279 fps_control.last_time = device->getTimer()->getTime();
2281 while (device->run()) {
2283 limitFps(&fps_control, &dtime);
2285 // Update client and server
2286 client->step(dtime);
2289 server->step(dtime);
2292 if (client->mediaReceived() && client->itemdefReceived() &&
2293 client->nodedefReceived()) {
2298 if (!checkConnection())
2301 if (client->getState() < LC_Init) {
2302 *error_message = "Client disconnected";
2303 errorstream << *error_message << std::endl;
2307 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2309 infostream << "Connect aborted [Escape]" << std::endl;
2316 if (!client->itemdefReceived()) {
2317 const wchar_t *text = wgettext("Item definitions...");
2319 draw_load_screen(text, device, guienv, dtime, progress);
2321 } else if (!client->nodedefReceived()) {
2322 const wchar_t *text = wgettext("Node definitions...");
2324 draw_load_screen(text, device, guienv, dtime, progress);
2327 std::stringstream message;
2328 message.precision(3);
2329 message << gettext("Media...");
2331 if ((USE_CURL == 0) ||
2332 (!g_settings->getBool("enable_remote_media_server"))) {
2333 float cur = client->getCurRate();
2334 std::string cur_unit = gettext("KiB/s");
2338 cur_unit = gettext("MiB/s");
2341 message << " (" << cur << ' ' << cur_unit << ")";
2344 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2345 draw_load_screen(narrow_to_wide(message.str()), device,
2346 guienv, dtime, progress);
2354 /****************************************************************************/
2355 /****************************************************************************
2357 ****************************************************************************/
2358 /****************************************************************************/
2360 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2362 if (runData->nodig_delay_timer >= 0)
2363 runData->nodig_delay_timer -= dtime;
2365 if (runData->object_hit_delay_timer >= 0)
2366 runData->object_hit_delay_timer -= dtime;
2368 runData->time_from_last_punch += dtime;
2372 /* returns false if game should exit, otherwise true
2374 inline bool Game::checkConnection()
2376 if (client->accessDenied()) {
2377 *error_message = "Access denied. Reason: "
2378 + client->accessDeniedReason();
2379 errorstream << *error_message << std::endl;
2387 /* returns false if game should exit, otherwise true
2389 inline bool Game::handleCallbacks()
2391 if (g_gamecallback->disconnect_requested) {
2392 g_gamecallback->disconnect_requested = false;
2396 if (g_gamecallback->changepassword_requested) {
2397 (new GUIPasswordChange(guienv, guiroot, -1,
2398 &g_menumgr, client))->drop();
2399 g_gamecallback->changepassword_requested = false;
2402 if (g_gamecallback->changevolume_requested) {
2403 (new GUIVolumeChange(guienv, guiroot, -1,
2404 &g_menumgr, client))->drop();
2405 g_gamecallback->changevolume_requested = false;
2408 if (g_gamecallback->keyconfig_requested) {
2409 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2410 &g_menumgr))->drop();
2411 g_gamecallback->keyconfig_requested = false;
2414 if (g_gamecallback->keyconfig_changed) {
2415 keycache.populate(); // update the cache with new settings
2416 g_gamecallback->keyconfig_changed = false;
2423 void Game::processQueues()
2425 texture_src->processQueue();
2426 itemdef_manager->processQueue(gamedef);
2427 shader_src->processQueue();
2431 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2432 const FpsControl &draw_times, f32 dtime)
2434 float profiler_print_interval =
2435 g_settings->getFloat("profiler_print_interval");
2436 bool print_to_log = true;
2438 if (profiler_print_interval == 0) {
2439 print_to_log = false;
2440 profiler_print_interval = 5;
2443 if (profiler_interval.step(dtime, profiler_print_interval)) {
2445 infostream << "Profiler:" << std::endl;
2446 g_profiler->print(infostream);
2449 update_profiler_gui(guitext_profiler, g_fontengine,
2450 runData.profiler_current_page, runData.profiler_max_page,
2451 driver->getScreenSize().Height);
2453 g_profiler->clear();
2456 addProfilerGraphs(stats, draw_times, dtime);
2460 void Game::addProfilerGraphs(const RunStats &stats,
2461 const FpsControl &draw_times, f32 dtime)
2463 g_profiler->graphAdd("mainloop_other",
2464 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2466 if (draw_times.sleep_time != 0)
2467 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2468 g_profiler->graphAdd("mainloop_dtime", dtime);
2470 g_profiler->add("Elapsed time", dtime);
2471 g_profiler->avg("FPS", 1. / dtime);
2475 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2482 /* Time average and jitter calculation
2484 jp = &stats->dtime_jitter;
2485 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2487 jitter = dtime - jp->avg;
2489 if (jitter > jp->max)
2492 jp->counter += dtime;
2494 if (jp->counter > 0.0) {
2496 jp->max_sample = jp->max;
2497 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2501 /* Busytime average and jitter calculation
2503 jp = &stats->busy_time_jitter;
2504 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2506 jitter = draw_times.busy_time - jp->avg;
2508 if (jitter > jp->max)
2510 if (jitter < jp->min)
2513 jp->counter += dtime;
2515 if (jp->counter > 0.0) {
2517 jp->max_sample = jp->max;
2518 jp->min_sample = jp->min;
2526 /****************************************************************************
2528 ****************************************************************************/
2530 void Game::processUserInput(VolatileRunFlags *flags,
2531 GameRunData *runData, f32 dtime)
2533 // Reset input if window not active or some menu is active
2534 if (device->isWindowActive() == false
2535 || noMenuActive() == false
2536 || guienv->hasFocus(gui_chat_console)) {
2540 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2541 gui_chat_console->closeConsoleAtOnce();
2544 // Input handler step() (used by the random input generator)
2547 #ifdef HAVE_TOUCHSCREENGUI
2549 if (g_touchscreengui) {
2550 g_touchscreengui->step(dtime);
2556 if (current_formspec != 0)
2557 current_formspec->getAndroidUIInput();
2561 // Increase timer for double tap of "keymap_jump"
2562 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2563 runData->jump_timer += dtime;
2565 processKeyboardInput(
2567 &runData->statustext_time,
2568 &runData->jump_timer,
2569 &runData->reset_jump_timer,
2570 &runData->profiler_current_page,
2571 runData->profiler_max_page);
2573 processItemSelection(&runData->new_playeritem);
2577 void Game::processKeyboardInput(VolatileRunFlags *flags,
2578 float *statustext_time,
2580 bool *reset_jump_timer,
2581 u32 *profiler_current_page,
2582 u32 profiler_max_page)
2585 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2587 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2589 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2591 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2592 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2593 simple_singleplayer_mode);
2594 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2595 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2597 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2598 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2600 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2602 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2603 toggleFreeMove(statustext_time);
2604 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2605 toggleFreeMoveAlt(statustext_time, jump_timer);
2606 *reset_jump_timer = true;
2607 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2608 toggleFast(statustext_time);
2609 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2610 toggleNoClip(statustext_time);
2611 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2612 toggleCinematic(statustext_time);
2613 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2614 client->makeScreenshot(device);
2615 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2616 toggleHud(statustext_time, &flags->show_hud);
2617 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2618 toggleMinimap(statustext_time, &flags->show_minimap, &flags->show_hud,
2619 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2620 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2621 toggleChat(statustext_time, &flags->show_chat);
2622 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2623 toggleFog(statustext_time, &flags->force_fog_off);
2624 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2625 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2626 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2627 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2628 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2629 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2630 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2631 increaseViewRange(statustext_time);
2632 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2633 decreaseViewRange(statustext_time);
2634 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2635 toggleFullViewRange(statustext_time);
2636 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2638 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2640 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2642 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2644 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2645 // Print debug stacks
2646 dstream << "-----------------------------------------"
2648 dstream << DTIME << "Printing debug stacks:" << std::endl;
2649 dstream << "-----------------------------------------"
2651 debug_stacks_print();
2654 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2655 *reset_jump_timer = false;
2661 if (quicktune->hasMessage()) {
2662 std::string msg = quicktune->getMessage();
2663 statustext = narrow_to_wide(msg);
2664 *statustext_time = 0;
2669 void Game::processItemSelection(u16 *new_playeritem)
2671 LocalPlayer *player = client->getEnv().getLocalPlayer();
2673 /* Item selection using mouse wheel
2675 *new_playeritem = client->getPlayerItem();
2677 s32 wheel = input->getMouseWheel();
2678 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2679 player->hud_hotbar_itemcount - 1);
2682 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2684 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2688 /* Item selection using keyboard
2690 for (u16 i = 0; i < 10; i++) {
2691 static const KeyPress *item_keys[10] = {
2692 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2693 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2694 NumberKey + 9, NumberKey + 0,
2697 if (input->wasKeyDown(*item_keys[i])) {
2698 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2699 *new_playeritem = i;
2700 infostream << "Selected item: " << new_playeritem << std::endl;
2708 void Game::dropSelectedItem()
2710 IDropAction *a = new IDropAction();
2712 a->from_inv.setCurrentPlayer();
2713 a->from_list = "main";
2714 a->from_i = client->getPlayerItem();
2715 client->inventoryAction(a);
2719 void Game::openInventory()
2722 * Don't permit to open inventory is CAO or player doesn't exists.
2723 * This prevent showing an empty inventory at player load
2726 LocalPlayer *player = client->getEnv().getLocalPlayer();
2727 if (player == NULL || player->getCAO() == NULL)
2730 infostream << "the_game: " << "Launching inventory" << std::endl;
2732 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2733 TextDest *txt_dst = new TextDestPlayerInventory(client);
2735 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2736 device, fs_src, txt_dst, client);
2738 InventoryLocation inventoryloc;
2739 inventoryloc.setCurrentPlayer();
2740 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2744 void Game::openConsole()
2746 if (!gui_chat_console->isOpenInhibited()) {
2747 // Open up to over half of the screen
2748 gui_chat_console->openConsole(0.6);
2749 guienv->setFocus(gui_chat_console);
2754 void Game::toggleFreeMove(float *statustext_time)
2756 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2758 bool free_move = !g_settings->getBool("free_move");
2759 g_settings->set("free_move", bool_to_cstr(free_move));
2761 *statustext_time = 0;
2762 statustext = msg[free_move];
2763 if (free_move && !client->checkPrivilege("fly"))
2764 statustext += L" (note: no 'fly' privilege)";
2768 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2770 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2771 toggleFreeMove(statustext_time);
2775 void Game::toggleFast(float *statustext_time)
2777 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2778 bool fast_move = !g_settings->getBool("fast_move");
2779 g_settings->set("fast_move", bool_to_cstr(fast_move));
2781 *statustext_time = 0;
2782 statustext = msg[fast_move];
2784 bool has_fast_privs = client->checkPrivilege("fast");
2786 if (fast_move && !has_fast_privs)
2787 statustext += L" (note: no 'fast' privilege)";
2790 m_cache_hold_aux1 = fast_move && has_fast_privs;
2795 void Game::toggleNoClip(float *statustext_time)
2797 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2798 bool noclip = !g_settings->getBool("noclip");
2799 g_settings->set("noclip", bool_to_cstr(noclip));
2801 *statustext_time = 0;
2802 statustext = msg[noclip];
2804 if (noclip && !client->checkPrivilege("noclip"))
2805 statustext += L" (note: no 'noclip' privilege)";
2808 void Game::toggleCinematic(float *statustext_time)
2810 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2811 bool cinematic = !g_settings->getBool("cinematic");
2812 g_settings->set("cinematic", bool_to_cstr(cinematic));
2814 *statustext_time = 0;
2815 statustext = msg[cinematic];
2819 void Game::toggleChat(float *statustext_time, bool *flag)
2821 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2824 *statustext_time = 0;
2825 statustext = msg[*flag];
2829 void Game::toggleHud(float *statustext_time, bool *flag)
2831 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2834 *statustext_time = 0;
2835 statustext = msg[*flag];
2836 if (g_settings->getBool("enable_node_highlighting"))
2837 client->setHighlighted(client->getHighlighted(), *flag);
2840 void Game::toggleMinimap(float *statustext_time, bool *flag, bool *show_hud, bool shift_pressed)
2842 if (*show_hud && g_settings->getBool("enable_minimap")) {
2843 if (shift_pressed) {
2844 mapper->toggleMinimapShape();
2847 MinimapMode mode = mapper->getMinimapMode();
2848 mode = (MinimapMode)((int)(mode) + 1);
2851 case MINIMAP_MODE_SURFACEx1:
2852 statustext = L"Minimap in surface mode, Zoom x1";
2854 case MINIMAP_MODE_SURFACEx2:
2855 statustext = L"Minimap in surface mode, Zoom x2";
2857 case MINIMAP_MODE_SURFACEx4:
2858 statustext = L"Minimap in surface mode, Zoom x4";
2860 case MINIMAP_MODE_RADARx1:
2861 statustext = L"Minimap in radar mode, Zoom x1";
2863 case MINIMAP_MODE_RADARx2:
2864 statustext = L"Minimap in radar mode, Zoom x2";
2866 case MINIMAP_MODE_RADARx4:
2867 statustext = L"Minimap in radar mode, Zoom x4";
2870 mode = MINIMAP_MODE_OFF;
2872 statustext = L"Minimap hidden";
2874 *statustext_time = 0;
2875 mapper->setMinimapMode(mode);
2879 void Game::toggleFog(float *statustext_time, bool *flag)
2881 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2884 *statustext_time = 0;
2885 statustext = msg[*flag];
2889 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2890 bool *show_profiler_graph)
2892 // Initial / 3x toggle: Chat only
2893 // 1x toggle: Debug text with chat
2894 // 2x toggle: Debug text with profiler graph
2897 *show_profiler_graph = false;
2898 statustext = L"Debug info shown";
2899 } else if (*show_profiler_graph) {
2900 *show_debug = false;
2901 *show_profiler_graph = false;
2902 statustext = L"Debug info and profiler graph hidden";
2904 *show_profiler_graph = true;
2905 statustext = L"Profiler graph shown";
2907 *statustext_time = 0;
2911 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2913 static const wchar_t *msg[] = {
2914 L"Camera update enabled",
2915 L"Camera update disabled"
2919 *statustext_time = 0;
2920 statustext = msg[*flag];
2924 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2925 u32 profiler_max_page)
2927 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2929 // FIXME: This updates the profiler with incomplete values
2930 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2931 profiler_max_page, driver->getScreenSize().Height);
2933 if (*profiler_current_page != 0) {
2934 std::wstringstream sstr;
2935 sstr << "Profiler shown (page " << *profiler_current_page
2936 << " of " << profiler_max_page << ")";
2937 statustext = sstr.str();
2939 statustext = L"Profiler hidden";
2941 *statustext_time = 0;
2945 void Game::increaseViewRange(float *statustext_time)
2947 s16 range = g_settings->getS16("viewing_range_nodes_min");
2948 s16 range_new = range + 10;
2949 g_settings->set("viewing_range_nodes_min", itos(range_new));
2950 statustext = narrow_to_wide("Minimum viewing range changed to "
2952 *statustext_time = 0;
2956 void Game::decreaseViewRange(float *statustext_time)
2958 s16 range = g_settings->getS16("viewing_range_nodes_min");
2959 s16 range_new = range - 10;
2964 g_settings->set("viewing_range_nodes_min", itos(range_new));
2965 statustext = narrow_to_wide("Minimum viewing range changed to "
2967 *statustext_time = 0;
2971 void Game::toggleFullViewRange(float *statustext_time)
2973 static const wchar_t *msg[] = {
2974 L"Disabled full viewing range",
2975 L"Enabled full viewing range"
2978 draw_control->range_all = !draw_control->range_all;
2979 infostream << msg[draw_control->range_all] << std::endl;
2980 statustext = msg[draw_control->range_all];
2981 *statustext_time = 0;
2985 void Game::updateCameraDirection(CameraOrientation *cam,
2986 VolatileRunFlags *flags)
2988 if ((device->isWindowActive() && noMenuActive()) || random_input) {
2991 if (!random_input) {
2992 // Mac OSX gets upset if this is set every frame
2993 if (device->getCursorControl()->isVisible())
2994 device->getCursorControl()->setVisible(false);
2998 if (flags->first_loop_after_window_activation)
2999 flags->first_loop_after_window_activation = false;
3001 updateCameraOrientation(cam, *flags);
3003 input->setMousePos((driver->getScreenSize().Width / 2),
3004 (driver->getScreenSize().Height / 2));
3008 // Mac OSX gets upset if this is set every frame
3009 if (device->getCursorControl()->isVisible() == false)
3010 device->getCursorControl()->setVisible(true);
3013 if (!flags->first_loop_after_window_activation)
3014 flags->first_loop_after_window_activation = true;
3020 void Game::updateCameraOrientation(CameraOrientation *cam,
3021 const VolatileRunFlags &flags)
3023 #ifdef HAVE_TOUCHSCREENGUI
3024 if (g_touchscreengui) {
3025 cam->camera_yaw = g_touchscreengui->getYaw();
3026 cam->camera_pitch = g_touchscreengui->getPitch();
3029 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3030 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3032 if (flags.invert_mouse
3033 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3037 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3038 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3040 #ifdef HAVE_TOUCHSCREENGUI
3044 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3048 void Game::updatePlayerControl(const CameraOrientation &cam)
3050 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3052 PlayerControl control(
3053 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3054 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3055 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3056 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3057 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3058 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3059 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3060 input->getLeftState(),
3061 input->getRightState(),
3067 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3068 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3069 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3070 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3071 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3072 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3073 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3074 ( (u32)(input->getLeftState() & 0x1) << 7) |
3075 ( (u32)(input->getRightState() & 0x1) << 8
3079 /* For Android, simulate holding down AUX1 (fast move) if the user has
3080 * the fast_move setting toggled on. If there is an aux1 key defined for
3081 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3084 if (m_cache_hold_aux1) {
3085 control.aux1 = control.aux1 ^ true;
3086 keypress_bits ^= ((u32)(1U << 5));
3090 client->setPlayerControl(control);
3091 LocalPlayer *player = client->getEnv().getLocalPlayer();
3092 player->keyPressed = keypress_bits;
3098 inline void Game::step(f32 *dtime)
3100 bool can_be_and_is_paused =
3101 (simple_singleplayer_mode && g_menumgr.pausesGame());
3103 if (can_be_and_is_paused) { // This is for a singleplayer server
3104 *dtime = 0; // No time passes
3106 if (server != NULL) {
3107 //TimeTaker timer("server->step(dtime)");
3108 server->step(*dtime);
3111 //TimeTaker timer("client.step(dtime)");
3112 client->step(*dtime);
3117 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3119 ClientEvent event = client->getClientEvent();
3121 LocalPlayer *player = client->getEnv().getLocalPlayer();
3123 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3125 if (event.type == CE_PLAYER_DAMAGE &&
3126 client->getHP() != 0) {
3127 //u16 damage = event.player_damage.amount;
3128 //infostream<<"Player damage: "<<damage<<std::endl;
3130 *damage_flash += 100.0;
3131 *damage_flash += 8.0 * event.player_damage.amount;
3133 player->hurt_tilt_timer = 1.5;
3134 player->hurt_tilt_strength = event.player_damage.amount / 4;
3135 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3137 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3138 gamedef->event()->put(e);
3139 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3140 cam->camera_yaw = event.player_force_move.yaw;
3141 cam->camera_pitch = event.player_force_move.pitch;
3142 } else if (event.type == CE_DEATHSCREEN) {
3143 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3146 chat_backend->addMessage(L"", L"You died.");
3148 /* Handle visualization */
3150 player->hurt_tilt_timer = 0;
3151 player->hurt_tilt_strength = 0;
3153 } else if (event.type == CE_SHOW_FORMSPEC) {
3154 FormspecFormSource *fs_src =
3155 new FormspecFormSource(*(event.show_formspec.formspec));
3156 TextDestPlayerInventory *txt_dst =
3157 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3159 create_formspec_menu(¤t_formspec, client, gamedef,
3160 texture_src, device, fs_src, txt_dst, client);
3162 delete(event.show_formspec.formspec);
3163 delete(event.show_formspec.formname);
3164 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3165 (event.type == CE_ADD_PARTICLESPAWNER) ||
3166 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3167 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3169 } else if (event.type == CE_HUDADD) {
3170 u32 id = event.hudadd.id;
3172 LocalPlayer *player = client->getEnv().getLocalPlayer();
3173 HudElement *e = player->getHud(id);
3176 delete event.hudadd.pos;
3177 delete event.hudadd.name;
3178 delete event.hudadd.scale;
3179 delete event.hudadd.text;
3180 delete event.hudadd.align;
3181 delete event.hudadd.offset;
3182 delete event.hudadd.world_pos;
3183 delete event.hudadd.size;
3188 e->type = (HudElementType)event.hudadd.type;
3189 e->pos = *event.hudadd.pos;
3190 e->name = *event.hudadd.name;
3191 e->scale = *event.hudadd.scale;
3192 e->text = *event.hudadd.text;
3193 e->number = event.hudadd.number;
3194 e->item = event.hudadd.item;
3195 e->dir = event.hudadd.dir;
3196 e->align = *event.hudadd.align;
3197 e->offset = *event.hudadd.offset;
3198 e->world_pos = *event.hudadd.world_pos;
3199 e->size = *event.hudadd.size;
3201 u32 new_id = player->addHud(e);
3202 //if this isn't true our huds aren't consistent
3203 sanity_check(new_id == id);
3205 delete event.hudadd.pos;
3206 delete event.hudadd.name;
3207 delete event.hudadd.scale;
3208 delete event.hudadd.text;
3209 delete event.hudadd.align;
3210 delete event.hudadd.offset;
3211 delete event.hudadd.world_pos;
3212 delete event.hudadd.size;
3213 } else if (event.type == CE_HUDRM) {
3214 HudElement *e = player->removeHud(event.hudrm.id);
3218 } else if (event.type == CE_HUDCHANGE) {
3219 u32 id = event.hudchange.id;
3220 HudElement *e = player->getHud(id);
3223 delete event.hudchange.v3fdata;
3224 delete event.hudchange.v2fdata;
3225 delete event.hudchange.sdata;
3226 delete event.hudchange.v2s32data;
3230 switch (event.hudchange.stat) {
3232 e->pos = *event.hudchange.v2fdata;
3236 e->name = *event.hudchange.sdata;
3239 case HUD_STAT_SCALE:
3240 e->scale = *event.hudchange.v2fdata;
3244 e->text = *event.hudchange.sdata;
3247 case HUD_STAT_NUMBER:
3248 e->number = event.hudchange.data;
3252 e->item = event.hudchange.data;
3256 e->dir = event.hudchange.data;
3259 case HUD_STAT_ALIGN:
3260 e->align = *event.hudchange.v2fdata;
3263 case HUD_STAT_OFFSET:
3264 e->offset = *event.hudchange.v2fdata;
3267 case HUD_STAT_WORLD_POS:
3268 e->world_pos = *event.hudchange.v3fdata;
3272 e->size = *event.hudchange.v2s32data;
3276 delete event.hudchange.v3fdata;
3277 delete event.hudchange.v2fdata;
3278 delete event.hudchange.sdata;
3279 delete event.hudchange.v2s32data;
3280 } else if (event.type == CE_SET_SKY) {
3281 sky->setVisible(false);
3288 // Handle according to type
3289 if (*event.set_sky.type == "regular") {
3290 sky->setVisible(true);
3291 } else if (*event.set_sky.type == "skybox" &&
3292 event.set_sky.params->size() == 6) {
3293 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3294 skybox = smgr->addSkyBoxSceneNode(
3295 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3296 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3297 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3298 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3299 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3300 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3302 // Handle everything else as plain color
3304 if (*event.set_sky.type != "plain")
3305 infostream << "Unknown sky type: "
3306 << (*event.set_sky.type) << std::endl;
3308 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3311 delete event.set_sky.bgcolor;
3312 delete event.set_sky.type;
3313 delete event.set_sky.params;
3314 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3315 bool enable = event.override_day_night_ratio.do_override;
3316 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3317 client->getEnv().setDayNightRatioOverride(enable, value);
3323 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3324 f32 dtime, float time_from_last_punch)
3326 LocalPlayer *player = client->getEnv().getLocalPlayer();
3329 For interaction purposes, get info about the held item
3331 - Is it a usable item?
3332 - Can it point to liquids?
3334 ItemStack playeritem;
3336 InventoryList *mlist = local_inventory->getList("main");
3338 if (mlist && client->getPlayerItem() < mlist->getSize())
3339 playeritem = mlist->getItem(client->getPlayerItem());
3342 ToolCapabilities playeritem_toolcap =
3343 playeritem.getToolCapabilities(itemdef_manager);
3345 v3s16 old_camera_offset = camera->getOffset();
3347 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3348 GenericCAO *playercao = player->getCAO();
3350 // If playercao not loaded, don't change camera
3351 if (playercao == NULL)
3354 camera->toggleCameraMode();
3356 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3357 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3360 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3361 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3363 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3364 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3366 camera->step(dtime);
3368 v3f camera_position = camera->getPosition();
3369 v3f camera_direction = camera->getDirection();
3370 f32 camera_fov = camera->getFovMax();
3371 v3s16 camera_offset = camera->getOffset();
3373 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3375 if (!flags->disable_camera_update) {
3376 client->getEnv().getClientMap().updateCamera(camera_position,
3377 camera_direction, camera_fov, camera_offset);
3379 if (flags->camera_offset_changed) {
3380 client->updateCameraOffset(camera_offset);
3381 client->getEnv().updateCameraOffset(camera_offset);
3384 clouds->updateCameraOffset(camera_offset);
3390 void Game::updateSound(f32 dtime)
3392 // Update sound listener
3393 v3s16 camera_offset = camera->getOffset();
3394 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3395 v3f(0, 0, 0), // velocity
3396 camera->getDirection(),
3397 camera->getCameraNode()->getUpVector());
3398 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3401 // Update sound maker
3402 soundmaker->step(dtime);
3404 LocalPlayer *player = client->getEnv().getLocalPlayer();
3406 ClientMap &map = client->getEnv().getClientMap();
3407 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3408 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3412 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3413 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3415 LocalPlayer *player = client->getEnv().getLocalPlayer();
3417 ItemStack playeritem;
3419 InventoryList *mlist = local_inventory->getList("main");
3421 if (mlist && client->getPlayerItem() < mlist->getSize())
3422 playeritem = mlist->getItem(client->getPlayerItem());
3425 const ItemDefinition &playeritem_def =
3426 playeritem.getDefinition(itemdef_manager);
3428 v3f player_position = player->getPosition();
3429 v3f camera_position = camera->getPosition();
3430 v3f camera_direction = camera->getDirection();
3431 v3s16 camera_offset = camera->getOffset();
3435 Calculate what block is the crosshair pointing to
3438 f32 d = playeritem_def.range; // max. distance
3439 f32 d_hand = itemdef_manager->get("").range;
3441 if (d < 0 && d_hand >= 0)
3446 core::line3d<f32> shootline;
3448 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3450 shootline = core::line3d<f32>(camera_position,
3451 camera_position + camera_direction * BS * (d + 1));
3454 // prevent player pointing anything in front-view
3455 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3456 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3459 #ifdef HAVE_TOUCHSCREENGUI
3461 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3462 shootline = g_touchscreengui->getShootline();
3463 shootline.start += intToFloat(camera_offset, BS);
3464 shootline.end += intToFloat(camera_offset, BS);
3469 PointedThing pointed = getPointedThing(
3471 client, player_position, camera_direction,
3472 camera_position, shootline, d,
3473 playeritem_def.liquids_pointable,
3474 !runData->ldown_for_dig,
3478 runData->selected_object);
3480 if (pointed != runData->pointed_old) {
3481 infostream << "Pointing at " << pointed.dump() << std::endl;
3483 if (m_cache_enable_node_highlighting) {
3484 if (pointed.type == POINTEDTHING_NODE) {
3485 client->setHighlighted(pointed.node_undersurface, show_hud);
3487 client->setHighlighted(pointed.node_undersurface, false);
3494 - releasing left mouse button
3495 - pointing away from node
3497 if (runData->digging) {
3498 if (input->getLeftReleased()) {
3499 infostream << "Left button released"
3500 << " (stopped digging)" << std::endl;
3501 runData->digging = false;
3502 } else if (pointed != runData->pointed_old) {
3503 if (pointed.type == POINTEDTHING_NODE
3504 && runData->pointed_old.type == POINTEDTHING_NODE
3505 && pointed.node_undersurface
3506 == runData->pointed_old.node_undersurface) {
3507 // Still pointing to the same node, but a different face.
3510 infostream << "Pointing away from node"
3511 << " (stopped digging)" << std::endl;
3512 runData->digging = false;
3516 if (!runData->digging) {
3517 client->interact(1, runData->pointed_old);
3518 client->setCrack(-1, v3s16(0, 0, 0));
3519 runData->dig_time = 0.0;
3523 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3524 runData->ldown_for_dig = false;
3527 runData->left_punch = false;
3529 soundmaker->m_player_leftpunch_sound.name = "";
3531 if (input->getRightState())
3532 runData->repeat_rightclick_timer += dtime;
3534 runData->repeat_rightclick_timer = 0;
3536 if (playeritem_def.usable && input->getLeftState()) {
3537 if (input->getLeftClicked())
3538 client->interact(4, pointed);
3539 } else if (pointed.type == POINTEDTHING_NODE) {
3540 ToolCapabilities playeritem_toolcap =
3541 playeritem.getToolCapabilities(itemdef_manager);
3542 handlePointingAtNode(runData, pointed, playeritem_def,
3543 playeritem_toolcap, dtime);
3544 } else if (pointed.type == POINTEDTHING_OBJECT) {
3545 handlePointingAtObject(runData, pointed, playeritem,
3546 player_position, show_debug);
3547 } else if (input->getLeftState()) {
3548 // When button is held down in air, show continuous animation
3549 runData->left_punch = true;
3552 runData->pointed_old = pointed;
3554 if (runData->left_punch || input->getLeftClicked())
3555 camera->setDigging(0); // left click animation
3557 input->resetLeftClicked();
3558 input->resetRightClicked();
3560 input->resetLeftReleased();
3561 input->resetRightReleased();
3565 void Game::handlePointingAtNode(GameRunData *runData,
3566 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3567 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3569 v3s16 nodepos = pointed.node_undersurface;
3570 v3s16 neighbourpos = pointed.node_abovesurface;
3573 Check information text of node
3576 ClientMap &map = client->getEnv().getClientMap();
3577 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3580 infotext = narrow_to_wide(meta->getString("infotext"));
3582 MapNode n = map.getNodeNoEx(nodepos);
3584 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3585 infotext = L"Unknown node: ";
3586 infotext += narrow_to_wide(nodedef_manager->get(n).name);
3590 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3591 && client->checkPrivilege("interact")) {
3592 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3595 if ((input->getRightClicked() ||
3596 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3597 client->checkPrivilege("interact")) {
3598 runData->repeat_rightclick_timer = 0;
3599 infostream << "Ground right-clicked" << std::endl;
3601 if (meta && meta->getString("formspec") != "" && !random_input
3602 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3603 infostream << "Launching custom inventory view" << std::endl;
3605 InventoryLocation inventoryloc;
3606 inventoryloc.setNodeMeta(nodepos);
3608 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3609 &client->getEnv().getClientMap(), nodepos);
3610 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3612 create_formspec_menu(¤t_formspec, client, gamedef,
3613 texture_src, device, fs_src, txt_dst, client);
3615 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3617 // Report right click to server
3619 camera->setDigging(1); // right click animation (always shown for feedback)
3621 // If the wielded item has node placement prediction,
3623 bool placed = nodePlacementPrediction(*client,
3625 nodepos, neighbourpos);
3629 client->interact(3, pointed);
3631 soundmaker->m_player_rightpunch_sound =
3632 playeritem_def.sound_place;
3634 soundmaker->m_player_rightpunch_sound =
3638 if (playeritem_def.node_placement_prediction == "" ||
3639 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3640 client->interact(3, pointed); // Report to server
3646 void Game::handlePointingAtObject(GameRunData *runData,
3647 const PointedThing &pointed,
3648 const ItemStack &playeritem,
3649 const v3f &player_position,
3652 infotext = narrow_to_wide(runData->selected_object->infoText());
3654 if (infotext == L"" && show_debug) {
3655 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3658 if (input->getLeftState()) {
3659 bool do_punch = false;
3660 bool do_punch_damage = false;
3662 if (runData->object_hit_delay_timer <= 0.0) {
3664 do_punch_damage = true;
3665 runData->object_hit_delay_timer = object_hit_delay;
3668 if (input->getLeftClicked())
3672 infostream << "Left-clicked object" << std::endl;
3673 runData->left_punch = true;
3676 if (do_punch_damage) {
3677 // Report direct punch
3678 v3f objpos = runData->selected_object->getPosition();
3679 v3f dir = (objpos - player_position).normalize();
3681 bool disable_send = runData->selected_object->directReportPunch(
3682 dir, &playeritem, runData->time_from_last_punch);
3683 runData->time_from_last_punch = 0;
3686 client->interact(0, pointed);
3688 } else if (input->getRightClicked()) {
3689 infostream << "Right-clicked object" << std::endl;
3690 client->interact(3, pointed); // place
3695 void Game::handleDigging(GameRunData *runData,
3696 const PointedThing &pointed, const v3s16 &nodepos,
3697 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3699 if (!runData->digging) {
3700 infostream << "Started digging" << std::endl;
3701 client->interact(0, pointed);
3702 runData->digging = true;
3703 runData->ldown_for_dig = true;
3706 LocalPlayer *player = client->getEnv().getLocalPlayer();
3707 ClientMap &map = client->getEnv().getClientMap();
3708 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3710 // NOTE: Similar piece of code exists on the server side for
3712 // Get digging parameters
3713 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3714 &playeritem_toolcap);
3716 // If can't dig, try hand
3717 if (!params.diggable) {
3718 const ItemDefinition &hand = itemdef_manager->get("");
3719 const ToolCapabilities *tp = hand.tool_capabilities;
3722 params = getDigParams(nodedef_manager->get(n).groups, tp);
3725 if (params.diggable == false) {
3726 // I guess nobody will wait for this long
3727 runData->dig_time_complete = 10000000.0;
3729 runData->dig_time_complete = params.time;
3731 if (m_cache_enable_particles) {
3732 const ContentFeatures &features =
3733 client->getNodeDefManager()->get(n);
3734 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3735 player, nodepos, features.tiles);
3739 if (runData->dig_time_complete >= 0.001) {
3740 runData->dig_index = (float)crack_animation_length
3742 / runData->dig_time_complete;
3744 // This is for torches
3745 runData->dig_index = crack_animation_length;
3748 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3750 if (sound_dig.exists() && params.diggable) {
3751 if (sound_dig.name == "__group") {
3752 if (params.main_group != "") {
3753 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3754 soundmaker->m_player_leftpunch_sound.name =
3755 std::string("default_dig_") +
3759 soundmaker->m_player_leftpunch_sound = sound_dig;
3763 // Don't show cracks if not diggable
3764 if (runData->dig_time_complete >= 100000.0) {
3765 } else if (runData->dig_index < crack_animation_length) {
3766 //TimeTaker timer("client.setTempMod");
3767 //infostream<<"dig_index="<<dig_index<<std::endl;
3768 client->setCrack(runData->dig_index, nodepos);
3770 infostream << "Digging completed" << std::endl;
3771 client->interact(2, pointed);
3772 client->setCrack(-1, v3s16(0, 0, 0));
3773 bool is_valid_position;
3774 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3775 if (is_valid_position)
3776 client->removeNode(nodepos);
3778 if (m_cache_enable_particles) {
3779 const ContentFeatures &features =
3780 client->getNodeDefManager()->get(wasnode);
3781 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3782 player, nodepos, features.tiles);
3785 runData->dig_time = 0;
3786 runData->digging = false;
3788 runData->nodig_delay_timer =
3789 runData->dig_time_complete / (float)crack_animation_length;
3791 // We don't want a corresponding delay to
3792 // very time consuming nodes
3793 if (runData->nodig_delay_timer > 0.3)
3794 runData->nodig_delay_timer = 0.3;
3796 // We want a slight delay to very little
3797 // time consuming nodes
3798 const float mindelay = 0.15;
3800 if (runData->nodig_delay_timer < mindelay)
3801 runData->nodig_delay_timer = mindelay;
3803 // Send event to trigger sound
3804 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3805 gamedef->event()->put(e);
3808 if (runData->dig_time_complete < 100000.0) {
3809 runData->dig_time += dtime;
3811 runData->dig_time = 0;
3812 client->setCrack(-1, nodepos);
3815 camera->setDigging(0); // left click animation
3819 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3820 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3821 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3823 LocalPlayer *player = client->getEnv().getLocalPlayer();
3829 if (draw_control->range_all) {
3830 runData->fog_range = 100000 * BS;
3832 runData->fog_range = draw_control->wanted_range * BS
3833 + 0.0 * MAP_BLOCKSIZE * BS;
3834 runData->fog_range = MYMIN(
3836 (draw_control->farthest_drawn + 20) * BS);
3837 runData->fog_range *= 0.9;
3841 Calculate general brightness
3843 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3844 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3845 float direct_brightness;
3848 if (g_settings->getBool("free_move")) {
3849 direct_brightness = time_brightness;
3850 sunlight_seen = true;
3852 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3853 float old_brightness = sky->getBrightness();
3854 direct_brightness = client->getEnv().getClientMap()
3855 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3856 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3860 float time_of_day = runData->time_of_day;
3861 float time_of_day_smooth = runData->time_of_day_smooth;
3863 time_of_day = client->getEnv().getTimeOfDayF();
3865 const float maxsm = 0.05;
3866 const float todsm = 0.05;
3868 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3869 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3870 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3871 time_of_day_smooth = time_of_day;
3873 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3874 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3875 + (time_of_day + 1.0) * todsm;
3877 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3878 + time_of_day * todsm;
3880 runData->time_of_day = time_of_day;
3881 runData->time_of_day_smooth = time_of_day_smooth;
3883 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3884 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3885 player->getPitch());
3891 v3f player_position = player->getPosition();
3892 if (sky->getCloudsVisible()) {
3893 clouds->setVisible(true);
3894 clouds->step(dtime);
3895 clouds->update(v2f(player_position.X, player_position.Z),
3896 sky->getCloudColor());
3898 clouds->setVisible(false);
3905 client->getParticleManager()->step(dtime);
3911 if (m_cache_enable_fog && !flags.force_fog_off) {
3914 video::EFT_FOG_LINEAR,
3915 runData->fog_range * 0.4,
3916 runData->fog_range * 1.0,
3924 video::EFT_FOG_LINEAR,
3934 Get chat messages from client
3937 v2u32 screensize = driver->getScreenSize();
3939 updateChat(*client, dtime, flags.show_debug, screensize,
3940 flags.show_chat, runData->profiler_current_page,
3941 *chat_backend, guitext_chat);
3947 if (client->getPlayerItem() != runData->new_playeritem)
3948 client->selectPlayerItem(runData->new_playeritem);
3950 // Update local inventory if it has changed
3951 if (client->getLocalInventoryUpdated()) {
3952 //infostream<<"Updating local inventory"<<std::endl;
3953 client->getLocalInventory(*local_inventory);
3954 runData->update_wielded_item_trigger = true;
3957 if (runData->update_wielded_item_trigger) {
3958 // Update wielded tool
3959 InventoryList *mlist = local_inventory->getList("main");
3961 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3962 ItemStack item = mlist->getItem(client->getPlayerItem());
3963 camera->wield(item);
3965 runData->update_wielded_item_trigger = false;
3969 Update block draw list every 200ms or when camera direction has
3972 runData->update_draw_list_timer += dtime;
3974 v3f camera_direction = camera->getDirection();
3975 if (runData->update_draw_list_timer >= 0.2
3976 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3977 || flags.camera_offset_changed) {
3978 runData->update_draw_list_timer = 0;
3979 client->getEnv().getClientMap().updateDrawList(driver);
3980 runData->update_draw_list_last_cam_dir = camera_direction;
3983 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3986 make sure menu is on top
3987 1. Delete formspec menu reference if menu was removed
3988 2. Else, make sure formspec menu is on top
3990 if (current_formspec) {
3991 if (current_formspec->getReferenceCount() == 1) {
3992 current_formspec->drop();
3993 current_formspec = NULL;
3994 } else if (!noMenuActive()) {
3995 guiroot->bringToFront(current_formspec);
4003 video::SColor skycolor = sky->getSkyColor();
4005 TimeTaker tt_draw("mainloop: draw");
4007 TimeTaker timer("beginScene");
4008 driver->beginScene(true, true, skycolor);
4009 stats->beginscenetime = timer.stop(true);
4012 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4013 guienv, highlight_boxes, screensize, skycolor, flags.show_hud,
4014 flags.show_minimap);
4019 if (flags.show_profiler_graph)
4020 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4025 if (runData->damage_flash > 0.0) {
4026 video::SColor color(std::min(runData->damage_flash, 180.0f),
4030 driver->draw2DRectangle(color,
4031 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4034 runData->damage_flash -= 100.0 * dtime;
4040 if (player->hurt_tilt_timer > 0.0) {
4041 player->hurt_tilt_timer -= dtime * 5;
4043 if (player->hurt_tilt_timer < 0)
4044 player->hurt_tilt_strength = 0;
4048 Update minimap pos and rotation
4050 if (flags.show_minimap && flags.show_hud) {
4051 mapper->setPos(floatToInt(player->getPosition(), BS));
4052 mapper->setAngle(player->getYaw());
4059 TimeTaker timer("endScene");
4061 stats->endscenetime = timer.stop(true);
4064 stats->drawtime = tt_draw.stop(true);
4065 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4069 inline static const char *yawToDirectionString(int yaw)
4071 // NOTE: TODO: This can be done mathematically without the else/else-if
4074 const char *player_direction;
4076 yaw = wrapDegrees_0_360(yaw);
4078 if (yaw >= 45 && yaw < 135)
4079 player_direction = "West [-X]";
4080 else if (yaw >= 135 && yaw < 225)
4081 player_direction = "South [-Z]";
4082 else if (yaw >= 225 && yaw < 315)
4083 player_direction = "East [+X]";
4085 player_direction = "North [+Z]";
4087 return player_direction;
4091 void Game::updateGui(float *statustext_time, const RunStats &stats,
4092 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4093 const CameraOrientation &cam)
4095 v2u32 screensize = driver->getScreenSize();
4096 LocalPlayer *player = client->getEnv().getLocalPlayer();
4097 v3f player_position = player->getPosition();
4099 if (flags.show_debug) {
4100 static float drawtime_avg = 0;
4101 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4103 u16 fps = 1.0 / stats.dtime_jitter.avg;
4104 //s32 fps = driver->getFPS();
4106 std::ostringstream os(std::ios_base::binary);
4108 << PROJECT_NAME_C " " << g_version_hash
4110 << " (R: range_all=" << draw_control->range_all << ")"
4111 << std::setprecision(0)
4112 << " drawtime = " << drawtime_avg
4113 << std::setprecision(1)
4114 << ", dtime_jitter = "
4115 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4116 << std::setprecision(1)
4117 << ", v_range = " << draw_control->wanted_range
4118 << std::setprecision(3)
4119 << ", RTT = " << client->getRTT();
4120 guitext->setText(narrow_to_wide(os.str()).c_str());
4121 guitext->setVisible(true);
4122 } else if (flags.show_hud || flags.show_chat) {
4123 std::ostringstream os(std::ios_base::binary);
4124 os << PROJECT_NAME_C " " << g_version_hash;
4125 guitext->setText(narrow_to_wide(os.str()).c_str());
4126 guitext->setVisible(true);
4128 guitext->setVisible(false);
4131 if (guitext->isVisible()) {
4132 core::rect<s32> rect(
4134 screensize.X, 5 + g_fontengine->getTextHeight()
4136 guitext->setRelativePosition(rect);
4139 if (flags.show_debug) {
4140 std::ostringstream os(std::ios_base::binary);
4141 os << std::setprecision(1) << std::fixed
4142 << "(" << (player_position.X / BS)
4143 << ", " << (player_position.Y / BS)
4144 << ", " << (player_position.Z / BS)
4145 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4146 << " " << yawToDirectionString(cam.camera_yaw)
4147 << ") (seed = " << ((u64)client->getMapSeed())
4150 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4151 ClientMap &map = client->getEnv().getClientMap();
4152 const INodeDefManager *nodedef = client->getNodeDefManager();
4153 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4154 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4155 const ContentFeatures &features = nodedef->get(n);
4156 os << " (pointing_at = " << nodedef->get(n).name
4157 << " - " << features.tiledef[0].name.c_str()
4162 guitext2->setText(narrow_to_wide(os.str()).c_str());
4163 guitext2->setVisible(true);
4165 core::rect<s32> rect(
4166 5, 5 + g_fontengine->getTextHeight(),
4167 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4169 guitext2->setRelativePosition(rect);
4171 guitext2->setVisible(false);
4174 guitext_info->setText(infotext.c_str());
4175 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4177 float statustext_time_max = 1.5;
4179 if (!statustext.empty()) {
4180 *statustext_time += dtime;
4182 if (*statustext_time >= statustext_time_max) {
4184 *statustext_time = 0;
4188 guitext_status->setText(statustext.c_str());
4189 guitext_status->setVisible(!statustext.empty());
4191 if (!statustext.empty()) {
4192 s32 status_width = guitext_status->getTextWidth();
4193 s32 status_height = guitext_status->getTextHeight();
4194 s32 status_y = screensize.Y - 150;
4195 s32 status_x = (screensize.X - status_width) / 2;
4196 core::rect<s32> rect(
4197 status_x , status_y - status_height,
4198 status_x + status_width, status_y
4200 guitext_status->setRelativePosition(rect);
4203 video::SColor initial_color(255, 0, 0, 0);
4205 if (guienv->getSkin())
4206 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4208 video::SColor final_color = initial_color;
4209 final_color.setAlpha(0);
4210 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4211 initial_color, final_color,
4212 pow(*statustext_time / statustext_time_max, 2.0f));
4213 guitext_status->setOverrideColor(fade_color);
4214 guitext_status->enableOverrideColor(true);
4219 /* Log times and stuff for visualization */
4220 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4222 Profiler::GraphValues values;
4223 g_profiler->graphGet(values);
4229 /****************************************************************************
4231 ****************************************************************************/
4233 /* On some computers framerate doesn't seem to be automatically limited
4235 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4237 // not using getRealTime is necessary for wine
4238 device->getTimer()->tick(); // Maker sure device time is up-to-date
4239 u32 time = device->getTimer()->getTime();
4240 u32 last_time = fps_timings->last_time;
4242 if (time > last_time) // Make sure time hasn't overflowed
4243 fps_timings->busy_time = time - last_time;
4245 fps_timings->busy_time = 0;
4247 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4248 ? g_settings->getFloat("pause_fps_max")
4249 : g_settings->getFloat("fps_max"));
4251 if (fps_timings->busy_time < frametime_min) {
4252 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4253 device->sleep(fps_timings->sleep_time);
4255 fps_timings->sleep_time = 0;
4258 /* Get the new value of the device timer. Note that device->sleep() may
4259 * not sleep for the entire requested time as sleep may be interrupted and
4260 * therefore it is arguably more accurate to get the new time from the
4261 * device rather than calculating it by adding sleep_time to time.
4264 device->getTimer()->tick(); // Update device timer
4265 time = device->getTimer()->getTime();
4267 if (time > last_time) // Make sure last_time hasn't overflowed
4268 *dtime = (time - last_time) / 1000.0;
4272 fps_timings->last_time = time;
4275 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4276 // pass a copy of it to this function
4277 // Note: \p msg must be allocated using new (not malloc())
4278 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4279 int percent, bool draw_clouds)
4281 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4286 /****************************************************************************/
4287 /****************************************************************************
4289 ****************************************************************************/
4290 /****************************************************************************/
4292 void Game::extendedResourceCleanup()
4294 // Extended resource accounting
4295 infostream << "Irrlicht resources after cleanup:" << std::endl;
4296 infostream << "\tRemaining meshes : "
4297 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4298 infostream << "\tRemaining textures : "
4299 << driver->getTextureCount() << std::endl;
4301 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4302 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4303 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4307 clearTextureNameCache();
4308 infostream << "\tRemaining materials: "
4309 << driver-> getMaterialRendererCount()
4310 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4314 /****************************************************************************/
4315 /****************************************************************************
4316 extern function for launching the game
4317 ****************************************************************************/
4318 /****************************************************************************/
4320 void the_game(bool *kill,
4322 InputHandler *input,
4323 IrrlichtDevice *device,
4325 const std::string &map_dir,
4326 const std::string &playername,
4327 const std::string &password,
4328 const std::string &address, // If empty local server is created
4331 std::string &error_message,
4332 ChatBackend &chat_backend,
4333 const SubgameSpec &gamespec, // Used for local game
4334 bool simple_singleplayer_mode)
4338 /* Make a copy of the server address because if a local singleplayer server
4339 * is created then this is updated and we don't want to change the value
4340 * passed to us by the calling function
4342 std::string server_address = address;
4346 if (game.startup(kill, random_input, input, device, map_dir,
4347 playername, password, &server_address, port,
4348 error_message, &chat_backend, gamespec,
4349 simple_singleplayer_mode)) {
4354 } catch (SerializationError &e) {
4355 error_message = std::string("A serialization error occurred:\n")
4356 + e.what() + "\n\nThe server is probably "
4357 " running a different version of " PROJECT_NAME_C ".";
4358 errorstream << error_message << std::endl;
4359 } catch (ServerError &e) {
4360 error_message = e.what();
4361 errorstream << "ServerError: " << error_message << std::endl;
4362 } catch (ModError &e) {
4363 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4364 errorstream << "ModError: " << error_message << std::endl;