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 "client/keys.h"
27 #include "client/joystick_controller.h"
28 #include "clientmap.h"
31 #include "content_cao.h"
32 #include "drawscene.h"
33 #include "event_manager.h"
34 #include "fontengine.h"
39 #include "guiChatConsole.h"
40 #include "guiFormSpecMenu.h"
41 #include "guiKeyChangeMenu.h"
42 #include "guiPasswordChange.h"
43 #include "guiVolumeChange.h"
45 #include "mainmenumanager.h"
47 #include "nodedef.h" // Needed for determining pointing to nodes
48 #include "nodemetadata.h"
49 #include "particles.h"
51 #include "quicktune_shortcutter.h"
54 #include "shader.h" // For ShaderSource
58 #include "util/directiontables.h"
59 #include "util/pointedthing.h"
60 #include "irrlicht_changes/static_text.h"
63 #include "mapblock_mesh.h"
68 #include "sound_openal.h"
71 #ifdef HAVE_TOUCHSCREENGUI
72 #include "touchscreengui.h"
75 extern Settings *g_settings;
76 extern Profiler *g_profiler;
82 struct TextDestNodeMetadata : public TextDest {
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(std::wstring text)
91 std::string ntext = wide_to_utf8(text);
92 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
93 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(const StringMap &fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest {
108 TextDestPlayerInventory(Client *client)
113 TextDestPlayerInventory(Client *client, std::string formname)
116 m_formname = formname;
118 void gotText(const StringMap &fields)
120 m_client->sendInventoryFields(m_formname, fields);
126 struct LocalFormspecHandler : public TextDest {
127 LocalFormspecHandler();
128 LocalFormspecHandler(std::string formname) :
131 m_formname = formname;
134 LocalFormspecHandler(std::string formname, Client *client) :
137 m_formname = formname;
140 void gotText(std::wstring message)
142 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
145 void gotText(const StringMap &fields)
147 if (m_formname == "MT_PAUSE_MENU") {
148 if (fields.find("btn_sound") != fields.end()) {
149 g_gamecallback->changeVolume();
153 if (fields.find("btn_key_config") != fields.end()) {
154 g_gamecallback->keyConfig();
158 if (fields.find("btn_exit_menu") != fields.end()) {
159 g_gamecallback->disconnect();
163 if (fields.find("btn_exit_os") != fields.end()) {
164 g_gamecallback->exitToOS();
168 if (fields.find("btn_change_password") != fields.end()) {
169 g_gamecallback->changePassword();
173 if (fields.find("quit") != fields.end()) {
177 if (fields.find("btn_continue") != fields.end()) {
182 if (m_formname == "MT_DEATH_SCREEN") {
183 assert(m_client != 0);
185 if ((fields.find("btn_respawn") != fields.end())) {
186 m_client->sendRespawn();
190 if (fields.find("quit") != fields.end()) {
191 m_client->sendRespawn();
196 // don't show error message for unhandled cursor keys
197 if ((fields.find("key_up") != fields.end()) ||
198 (fields.find("key_down") != fields.end()) ||
199 (fields.find("key_left") != fields.end()) ||
200 (fields.find("key_right") != fields.end())) {
204 errorstream << "LocalFormspecHandler::gotText unhandled >"
205 << m_formname << "< event" << std::endl;
208 StringMap::const_iterator it;
209 for (it = fields.begin(); it != fields.end(); ++it) {
210 errorstream << "\t" << i << ": " << it->first
211 << "=" << it->second << std::endl;
219 /* Form update callback */
221 class NodeMetadataFormSource: public IFormSource
224 NodeMetadataFormSource(ClientMap *map, v3s16 p):
229 std::string getForm()
231 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
236 return meta->getString("formspec");
238 std::string resolveText(std::string str)
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
245 return meta->resolveString(str);
252 class PlayerInventoryFormSource: public IFormSource
255 PlayerInventoryFormSource(Client *client):
259 std::string getForm()
261 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
262 return player->inventory_formspec;
269 Check if a node is pointable
271 inline bool isPointableNode(const MapNode &n,
272 Client *client, bool liquids_pointable)
274 const ContentFeatures &features = client->getNodeDefManager()->get(n);
275 return features.pointable ||
276 (liquids_pointable && features.isLiquid());
279 static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef,
280 ClientMap *map, MapNode n, u8 bitmask, u8 *neighbors)
282 MapNode n2 = map->getNodeNoEx(p);
283 if (nodedef->nodeboxConnects(n, n2, bitmask))
284 *neighbors |= bitmask;
287 static inline u8 getNeighbors(v3s16 p, INodeDefManager *nodedef, ClientMap *map, MapNode n)
290 const ContentFeatures &f = nodedef->get(n);
291 // locate possible neighboring nodes to connect to
292 if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
296 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
300 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
304 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
308 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
312 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
316 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
323 Find what the player is pointing at
325 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
326 const v3f &camera_direction, const v3f &camera_position,
327 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
328 bool look_for_object, const v3s16 &camera_offset,
329 ClientActiveObject *&selected_object)
333 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
334 selectionboxes->clear();
335 static const bool show_entity_selectionbox = g_settings->getBool("show_entity_selectionbox");
337 selected_object = NULL;
339 INodeDefManager *nodedef = client->getNodeDefManager();
340 ClientMap &map = client->getEnv().getClientMap();
342 f32 min_distance = BS * 1001;
344 // First try to find a pointed at active object
345 if (look_for_object) {
346 selected_object = client->getSelectedActiveObject(d * BS,
347 camera_position, shootline);
349 if (selected_object != NULL) {
350 if (show_entity_selectionbox &&
351 selected_object->doShowSelectionBox()) {
352 aabb3f *selection_box = selected_object->getSelectionBox();
353 // Box should exist because object was
354 // returned in the first place
355 assert(selection_box);
357 v3f pos = selected_object->getPosition();
358 selectionboxes->push_back(aabb3f(
359 selection_box->MinEdge, selection_box->MaxEdge));
360 hud->setSelectionPos(pos, camera_offset);
363 min_distance = (selected_object->getPosition() - camera_position).getLength();
365 hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
366 result.type = POINTEDTHING_OBJECT;
367 result.object_id = selected_object->getId();
371 // That didn't work, try to find a pointed at node
373 v3s16 pos_i = floatToInt(player_position, BS);
375 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
379 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
380 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
381 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
382 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
383 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
384 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
386 // Prevent signed number overflow
396 v3s16 pointed_pos(0, 0, 0);
398 for (s16 y = ystart; y <= yend; y++) {
399 for (s16 z = zstart; z <= zend; z++) {
400 for (s16 x = xstart; x <= xend; x++) {
402 bool is_valid_position;
405 n = map.getNodeNoEx(p, &is_valid_position);
406 if (!is_valid_position) {
409 if (!isPointableNode(n, client, liquids_pointable)) {
413 std::vector<aabb3f> boxes;
414 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n));
417 v3f npf = intToFloat(np, BS);
418 for (std::vector<aabb3f>::const_iterator
420 i != boxes.end(); ++i) {
425 v3f centerpoint = box.getCenter();
426 f32 distance = (centerpoint - camera_position).getLength();
427 if (distance >= min_distance) {
430 if (!box.intersectsWithLine(shootline)) {
433 result.type = POINTEDTHING_NODE;
434 min_distance = distance;
441 if (result.type == POINTEDTHING_NODE) {
443 MapNode n = map.getNodeNoEx(pointed_pos);
444 v3f npf = intToFloat(pointed_pos, BS);
445 std::vector<aabb3f> boxes;
446 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n));
447 f32 face_min_distance = 1000 * BS;
448 for (std::vector<aabb3f>::const_iterator
450 i != boxes.end(); ++i) {
454 for (u16 j = 0; j < 6; j++) {
455 v3s16 facedir = g_6dirs[j];
456 aabb3f facebox = box;
458 facebox.MinEdge.X = facebox.MaxEdge.X - d;
459 } else if (facedir.X < 0) {
460 facebox.MaxEdge.X = facebox.MinEdge.X + d;
461 } else if (facedir.Y > 0) {
462 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
463 } else if (facedir.Y < 0) {
464 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
465 } else if (facedir.Z > 0) {
466 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
467 } else if (facedir.Z < 0) {
468 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
470 v3f centerpoint = facebox.getCenter();
471 f32 distance = (centerpoint - camera_position).getLength();
472 if (distance >= face_min_distance)
474 if (!facebox.intersectsWithLine(shootline))
476 result.node_abovesurface = pointed_pos + facedir;
477 hud->setSelectedFaceNormal(v3f(facedir.X, facedir.Y, facedir.Z));
478 face_min_distance = distance;
481 selectionboxes->clear();
482 for (std::vector<aabb3f>::const_iterator
484 i != boxes.end(); ++i) {
486 box.MinEdge += v3f(-d, -d, -d);
487 box.MaxEdge += v3f(d, d, d);
488 selectionboxes->push_back(box);
490 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
491 result.node_undersurface = pointed_pos;
494 // Update selection mesh light level and vertex colors
495 if (selectionboxes->size() > 0) {
496 v3f pf = hud->getSelectionPos();
497 v3s16 p = floatToInt(pf, BS);
499 // Get selection mesh light level
500 MapNode n = map.getNodeNoEx(p);
501 u16 node_light = getInteriorLight(n, -1, nodedef);
502 u16 light_level = node_light;
504 for (u8 i = 0; i < 6; i++) {
505 n = map.getNodeNoEx(p + g_6dirs[i]);
506 node_light = getInteriorLight(n, -1, nodedef);
507 if (node_light > light_level)
508 light_level = node_light;
511 video::SColor c = MapBlock_LightColor(255, light_level, 0);
513 u8 night = c.getGreen();
514 u32 daynight_ratio = client->getEnv().getDayNightRatio();
515 finalColorBlend(c, day, night, daynight_ratio);
517 // Modify final color a bit with time
518 u32 timer = porting::getTimeMs() % 5000;
519 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
520 float sin_r = 0.08 * sin(timerf);
521 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
522 float sin_b = 0.08 * sin(timerf + irr::core::PI);
523 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
524 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
525 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
527 // Set mesh final color
528 hud->setSelectionMeshColor(c);
533 /* Profiler display */
535 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
536 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
538 if (show_profiler == 0) {
539 guitext_profiler->setVisible(false);
542 std::ostringstream os(std::ios_base::binary);
543 g_profiler->printPage(os, show_profiler, show_profiler_max);
544 std::wstring text = utf8_to_wide(os.str());
545 setStaticText(guitext_profiler, text.c_str());
546 guitext_profiler->setVisible(true);
548 s32 w = fe->getTextWidth(text.c_str());
553 unsigned text_height = fe->getTextHeight();
555 core::position2di upper_left, lower_right;
558 upper_left.Y = (text_height + 5) * 2;
559 lower_right.X = 12 + w;
560 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
562 if (lower_right.Y > screen_height * 2 / 3)
563 lower_right.Y = screen_height * 2 / 3;
565 core::rect<s32> rect(upper_left, lower_right);
567 guitext_profiler->setRelativePosition(rect);
568 guitext_profiler->setVisible(true);
576 Profiler::GraphValues values;
582 Meta(float initial = 0,
583 video::SColor color = video::SColor(255, 255, 255, 255)):
589 std::deque<Piece> m_log;
597 void put(const Profiler::GraphValues &values)
600 piece.values = values;
601 m_log.push_back(piece);
603 while (m_log.size() > m_log_max_size)
604 m_log.erase(m_log.begin());
607 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
608 gui::IGUIFont *font) const
610 // Do *not* use UNORDERED_MAP here as the order needs
611 // to be the same for each call to prevent flickering
612 std::map<std::string, Meta> m_meta;
614 for (std::deque<Piece>::const_iterator k = m_log.begin();
615 k != m_log.end(); ++k) {
616 const Piece &piece = *k;
618 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
619 i != piece.values.end(); ++i) {
620 const std::string &id = i->first;
621 const float &value = i->second;
622 std::map<std::string, Meta>::iterator j = m_meta.find(id);
624 if (j == m_meta.end()) {
625 m_meta[id] = Meta(value);
629 if (value < j->second.min)
630 j->second.min = value;
632 if (value > j->second.max)
633 j->second.max = value;
638 static const video::SColor usable_colors[] = {
639 video::SColor(255, 255, 100, 100),
640 video::SColor(255, 90, 225, 90),
641 video::SColor(255, 100, 100, 255),
642 video::SColor(255, 255, 150, 50),
643 video::SColor(255, 220, 220, 100)
645 static const u32 usable_colors_count =
646 sizeof(usable_colors) / sizeof(*usable_colors);
647 u32 next_color_i = 0;
649 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
650 i != m_meta.end(); ++i) {
651 Meta &meta = i->second;
652 video::SColor color(255, 200, 200, 200);
654 if (next_color_i < usable_colors_count)
655 color = usable_colors[next_color_i++];
661 s32 textx = x_left + m_log_max_size + 15;
662 s32 textx2 = textx + 200 - 15;
665 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
666 i != m_meta.end(); ++i) {
667 const std::string &id = i->first;
668 const Meta &meta = i->second;
670 s32 y = y_bottom - meta_i * 50;
671 float show_min = meta.min;
672 float show_max = meta.max;
674 if (show_min >= -0.0001 && show_max >= -0.0001) {
675 if (show_min <= show_max * 0.5)
681 snprintf(buf, 10, "%.3g", show_max);
682 font->draw(utf8_to_wide(buf).c_str(),
683 core::rect<s32>(textx, y - graphh,
684 textx2, y - graphh + texth),
686 snprintf(buf, 10, "%.3g", show_min);
687 font->draw(utf8_to_wide(buf).c_str(),
688 core::rect<s32>(textx, y - texth,
691 font->draw(utf8_to_wide(id).c_str(),
692 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
693 textx2, y - graphh / 2 + texth / 2),
696 s32 graph1h = graphh;
697 bool relativegraph = (show_min != 0 && show_min != show_max);
698 float lastscaledvalue = 0.0;
699 bool lastscaledvalue_exists = false;
701 for (std::deque<Piece>::const_iterator j = m_log.begin();
702 j != m_log.end(); ++j) {
703 const Piece &piece = *j;
705 bool value_exists = false;
706 Profiler::GraphValues::const_iterator k =
707 piece.values.find(id);
709 if (k != piece.values.end()) {
716 lastscaledvalue_exists = false;
720 float scaledvalue = 1.0;
722 if (show_max != show_min)
723 scaledvalue = (value - show_min) / (show_max - show_min);
725 if (scaledvalue == 1.0 && value == 0) {
727 lastscaledvalue_exists = false;
732 if (lastscaledvalue_exists) {
733 s32 ivalue1 = lastscaledvalue * graph1h;
734 s32 ivalue2 = scaledvalue * graph1h;
735 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
736 v2s32(x, graph1y - ivalue2), meta.color);
739 lastscaledvalue = scaledvalue;
740 lastscaledvalue_exists = true;
742 s32 ivalue = scaledvalue * graph1h;
743 driver->draw2DLine(v2s32(x, graph1y),
744 v2s32(x, graph1y - ivalue), meta.color);
755 class NodeDugEvent: public MtEvent
761 NodeDugEvent(v3s16 p, MapNode n):
765 const char *getType() const
773 ISoundManager *m_sound;
774 INodeDefManager *m_ndef;
776 float m_player_step_timer;
778 SimpleSoundSpec m_player_step_sound;
779 SimpleSoundSpec m_player_leftpunch_sound;
780 SimpleSoundSpec m_player_rightpunch_sound;
782 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
785 m_player_step_timer(0)
789 void playPlayerStep()
791 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
792 m_player_step_timer = 0.03;
793 m_sound->playSound(m_player_step_sound, false);
797 static void viewBobbingStep(MtEvent *e, void *data)
799 SoundMaker *sm = (SoundMaker *)data;
800 sm->playPlayerStep();
803 static void playerRegainGround(MtEvent *e, void *data)
805 SoundMaker *sm = (SoundMaker *)data;
806 sm->playPlayerStep();
809 static void playerJump(MtEvent *e, void *data)
811 //SoundMaker *sm = (SoundMaker*)data;
814 static void cameraPunchLeft(MtEvent *e, void *data)
816 SoundMaker *sm = (SoundMaker *)data;
817 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
820 static void cameraPunchRight(MtEvent *e, void *data)
822 SoundMaker *sm = (SoundMaker *)data;
823 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
826 static void nodeDug(MtEvent *e, void *data)
828 SoundMaker *sm = (SoundMaker *)data;
829 NodeDugEvent *nde = (NodeDugEvent *)e;
830 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
833 static void playerDamage(MtEvent *e, void *data)
835 SoundMaker *sm = (SoundMaker *)data;
836 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
839 static void playerFallingDamage(MtEvent *e, void *data)
841 SoundMaker *sm = (SoundMaker *)data;
842 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
845 void registerReceiver(MtEventManager *mgr)
847 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
848 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
849 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
850 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
851 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
852 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
853 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
854 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
857 void step(float dtime)
859 m_player_step_timer -= dtime;
863 // Locally stored sounds don't need to be preloaded because of this
864 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
866 std::set<std::string> m_fetched;
868 void fetchSounds(const std::string &name,
869 std::set<std::string> &dst_paths,
870 std::set<std::string> &dst_datas)
872 if (m_fetched.count(name))
875 m_fetched.insert(name);
876 std::string base = porting::path_share + DIR_DELIM + "sounds";
877 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
878 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
879 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
880 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
881 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
882 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
883 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
884 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
885 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
886 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
887 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
892 // before 1.8 there isn't a "integer interface", only float
893 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
894 typedef f32 SamplerLayer_t;
896 typedef s32 SamplerLayer_t;
900 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
903 bool *m_force_fog_off;
906 CachedPixelShaderSetting<float, 4> m_sky_bg_color;
907 CachedPixelShaderSetting<float> m_fog_distance;
908 CachedVertexShaderSetting<float> m_animation_timer_vertex;
909 CachedPixelShaderSetting<float> m_animation_timer_pixel;
910 CachedPixelShaderSetting<float> m_day_night_ratio;
911 CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
912 CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
913 CachedPixelShaderSetting<float, 3> m_minimap_yaw;
914 CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
915 CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
916 CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
920 void onSettingsChange(const std::string &name)
922 if (name == "enable_fog")
923 m_fog_enabled = g_settings->getBool("enable_fog");
926 static void settingsCallback(const std::string &name, void *userdata)
928 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
931 void setSky(Sky *sky) { m_sky = sky; }
933 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
934 f32 *fog_range, Client *client) :
936 m_force_fog_off(force_fog_off),
937 m_fog_range(fog_range),
938 m_sky_bg_color("skyBgColor"),
939 m_fog_distance("fogDistance"),
940 m_animation_timer_vertex("animationTimer"),
941 m_animation_timer_pixel("animationTimer"),
942 m_day_night_ratio("dayNightRatio"),
943 m_eye_position_pixel("eyePosition"),
944 m_eye_position_vertex("eyePosition"),
945 m_minimap_yaw("yawVec"),
946 m_base_texture("baseTexture"),
947 m_normal_texture("normalTexture"),
948 m_texture_flags("textureFlags"),
951 g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
952 m_fog_enabled = g_settings->getBool("enable_fog");
955 ~GameGlobalShaderConstantSetter()
957 g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
960 virtual void onSetConstants(video::IMaterialRendererServices *services,
967 video::SColor bgcolor = m_sky->getBgColor();
968 video::SColorf bgcolorf(bgcolor);
969 float bgcolorfa[4] = {
975 m_sky_bg_color.set(bgcolorfa, services);
978 float fog_distance = 10000 * BS;
980 if (m_fog_enabled && !*m_force_fog_off)
981 fog_distance = *m_fog_range;
983 m_fog_distance.set(&fog_distance, services);
985 float daynight_ratio = (float)m_client->getEnv().getDayNightRatio() / 1000.f;
986 m_day_night_ratio.set(&daynight_ratio, services);
988 u32 animation_timer = porting::getTimeMs() % 100000;
989 float animation_timer_f = (float)animation_timer / 100000.f;
990 m_animation_timer_vertex.set(&animation_timer_f, services);
991 m_animation_timer_pixel.set(&animation_timer_f, services);
993 float eye_position_array[3];
994 v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
995 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
996 eye_position_array[0] = epos.X;
997 eye_position_array[1] = epos.Y;
998 eye_position_array[2] = epos.Z;
1000 epos.getAs3Values(eye_position_array);
1002 m_eye_position_pixel.set(eye_position_array, services);
1003 m_eye_position_vertex.set(eye_position_array, services);
1005 float minimap_yaw_array[3];
1006 v3f minimap_yaw = m_client->getMapper()->getYawVec();
1007 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
1008 minimap_yaw_array[0] = minimap_yaw.X;
1009 minimap_yaw_array[1] = minimap_yaw.Y;
1010 minimap_yaw_array[2] = minimap_yaw.Z;
1012 minimap_yaw.getAs3Values(minimap_yaw_array);
1014 m_minimap_yaw.set(minimap_yaw_array, services);
1016 SamplerLayer_t base_tex = 0,
1019 m_base_texture.set(&base_tex, services);
1020 m_normal_texture.set(&normal_tex, services);
1021 m_texture_flags.set(&flags_tex, services);
1026 class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
1029 bool *m_force_fog_off;
1032 std::vector<GameGlobalShaderConstantSetter *> created_nosky;
1034 GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
1035 f32 *fog_range, Client *client) :
1037 m_force_fog_off(force_fog_off),
1038 m_fog_range(fog_range),
1042 void setSky(Sky *sky) {
1044 for (size_t i = 0; i < created_nosky.size(); ++i) {
1045 created_nosky[i]->setSky(m_sky);
1047 created_nosky.clear();
1050 virtual IShaderConstantSetter* create()
1052 GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
1053 m_sky, m_force_fog_off, m_fog_range, m_client);
1055 created_nosky.push_back(scs);
1061 bool nodePlacementPrediction(Client &client,
1062 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
1064 std::string prediction = playeritem_def.node_placement_prediction;
1065 INodeDefManager *nodedef = client.ndef();
1066 ClientMap &map = client.getEnv().getClientMap();
1068 bool is_valid_position;
1070 node = map.getNodeNoEx(nodepos, &is_valid_position);
1071 if (!is_valid_position)
1074 if (prediction != "" && !nodedef->get(node).rightclickable) {
1075 verbosestream << "Node placement prediction for "
1076 << playeritem_def.name << " is "
1077 << prediction << std::endl;
1078 v3s16 p = neighbourpos;
1080 // Place inside node itself if buildable_to
1081 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
1082 if (is_valid_position)
1084 if (nodedef->get(n_under).buildable_to)
1087 node = map.getNodeNoEx(p, &is_valid_position);
1088 if (is_valid_position &&!nodedef->get(node).buildable_to)
1093 // Find id of predicted node
1095 bool found = nodedef->getId(prediction, id);
1098 errorstream << "Node placement prediction failed for "
1099 << playeritem_def.name << " (places "
1101 << ") - Name not known" << std::endl;
1105 // Predict param2 for facedir and wallmounted nodes
1108 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
1109 v3s16 dir = nodepos - neighbourpos;
1111 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
1112 param2 = dir.Y < 0 ? 1 : 0;
1113 } else if (abs(dir.X) > abs(dir.Z)) {
1114 param2 = dir.X < 0 ? 3 : 2;
1116 param2 = dir.Z < 0 ? 5 : 4;
1120 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
1121 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
1123 if (abs(dir.X) > abs(dir.Z)) {
1124 param2 = dir.X < 0 ? 3 : 1;
1126 param2 = dir.Z < 0 ? 2 : 0;
1130 assert(param2 <= 5);
1132 //Check attachment if node is in group attached_node
1133 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1134 static v3s16 wallmounted_dirs[8] = {
1144 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1145 pp = p + wallmounted_dirs[param2];
1147 pp = p + v3s16(0, -1, 0);
1149 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1153 // Add node to client map
1154 MapNode n(id, 0, param2);
1157 LocalPlayer *player = client.getEnv().getLocalPlayer();
1159 // Dont place node when player would be inside new node
1160 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1161 if (!nodedef->get(n).walkable ||
1162 g_settings->getBool("enable_build_where_you_stand") ||
1163 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1164 (nodedef->get(n).walkable &&
1165 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1166 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1168 // This triggers the required mesh update too
1169 client.addNode(p, n);
1172 } catch (InvalidPositionException &e) {
1173 errorstream << "Node placement prediction failed for "
1174 << playeritem_def.name << " (places "
1176 << ") - Position not loaded" << std::endl;
1183 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1184 InventoryManager *invmgr, IGameDef *gamedef,
1185 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1186 JoystickController *joystick,
1187 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1190 if (*cur_formspec == 0) {
1191 *cur_formspec = new GUIFormSpecMenu(device, joystick,
1192 guiroot, -1, &g_menumgr, invmgr, gamedef, tsrc,
1193 fs_src, txt_dest, client);
1194 (*cur_formspec)->doPause = false;
1197 Caution: do not call (*cur_formspec)->drop() here --
1198 the reference might outlive the menu, so we will
1199 periodically check if *cur_formspec is the only
1200 remaining reference (i.e. the menu was removed)
1201 and delete it in that case.
1205 (*cur_formspec)->setFormSource(fs_src);
1206 (*cur_formspec)->setTextDest(txt_dest);
1211 #define SIZE_TAG "size[11,5.5]"
1213 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1216 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1217 InventoryManager *invmgr, IGameDef *gamedef,
1218 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1219 JoystickController *joystick, Client *client)
1221 std::string formspec =
1222 std::string(FORMSPEC_VERSION_STRING) +
1224 "bgcolor[#320000b4;true]"
1225 "label[4.85,1.35;" + gettext("You died.") + "]"
1226 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1230 /* Note: FormspecFormSource and LocalFormspecHandler
1231 * are deleted by guiFormSpecMenu */
1232 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1233 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1235 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
1236 joystick, fs_src, txt_dst, NULL);
1239 /******************************************************************************/
1240 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1241 InventoryManager *invmgr, IGameDef *gamedef,
1242 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1243 JoystickController *joystick, bool singleplayermode)
1246 std::string control_text = strgettext("Default Controls:\n"
1247 "No menu visible:\n"
1248 "- single tap: button activate\n"
1249 "- double tap: place/use\n"
1250 "- slide finger: look around\n"
1251 "Menu/Inventory visible:\n"
1252 "- double tap (outside):\n"
1254 "- touch stack, touch slot:\n"
1256 "- touch&drag, tap 2nd finger\n"
1257 " --> place single item to slot\n"
1260 std::string control_text = strgettext("Default Controls:\n"
1262 "- Space: jump/climb\n"
1263 "- Shift: sneak/go down\n"
1266 "- Mouse: turn/look\n"
1267 "- Mouse left: dig/punch\n"
1268 "- Mouse right: place/use\n"
1269 "- Mouse wheel: select item\n"
1274 float ypos = singleplayermode ? 0.5 : 0.1;
1275 std::ostringstream os;
1277 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1278 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1279 << strgettext("Continue") << "]";
1281 if (!singleplayermode) {
1282 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1283 << strgettext("Change Password") << "]";
1287 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1288 << strgettext("Sound Volume") << "]";
1289 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1290 << strgettext("Change Keys") << "]";
1292 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1293 << strgettext("Exit to Menu") << "]";
1294 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1295 << strgettext("Exit to OS") << "]"
1296 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1297 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1298 << g_build_info << "\n"
1299 << "path_user = " << wrap_rows(porting::path_user, 20)
1303 /* Note: FormspecFormSource and LocalFormspecHandler *
1304 * are deleted by guiFormSpecMenu */
1305 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1306 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1308 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
1309 joystick, fs_src, txt_dst, NULL);
1310 std::string con("btn_continue");
1311 (*cur_formspec)->setFocus(con);
1312 (*cur_formspec)->doPause = true;
1315 /******************************************************************************/
1316 static void updateChat(Client &client, f32 dtime, bool show_debug,
1317 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1318 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1320 // Add chat log output for errors to be shown in chat
1321 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1323 // Get new messages from error log buffer
1324 while (!chat_log_error_buf.empty()) {
1325 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
1326 if (!g_settings->getBool("disable_escape_sequences")) {
1327 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
1329 chat_backend.addMessage(L"", error_message);
1332 // Get new messages from client
1333 std::wstring message;
1335 while (client.getChatMessage(message)) {
1336 chat_backend.addUnparsedMessage(message);
1339 // Remove old messages
1340 chat_backend.step(dtime);
1342 // Display all messages in a static text element
1343 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1344 EnrichedString recent_chat = chat_backend.getRecentChat();
1345 unsigned int line_height = g_fontengine->getLineHeight();
1347 setStaticText(guitext_chat, recent_chat);
1349 // Update gui element size and position
1353 chat_y += 2 * line_height;
1355 // first pass to calculate height of text to be set
1356 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1357 porting::getWindowSize().X - 20);
1358 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1359 guitext_chat->setRelativePosition(rect);
1361 //now use real height of text and adjust rect according to this size
1362 rect = core::rect<s32>(10, chat_y, width,
1363 chat_y + guitext_chat->getTextHeight());
1366 guitext_chat->setRelativePosition(rect);
1367 // Don't show chat if disabled or empty or profiler is enabled
1368 guitext_chat->setVisible(
1369 show_chat && recent_chat_count != 0 && !show_profiler);
1373 /****************************************************************************
1374 Fast key cache for main game loop
1375 ****************************************************************************/
1377 /* This is faster than using getKeySetting with the tradeoff that functions
1378 * using it must make sure that it's initialised before using it and there is
1379 * no error handling (for example bounds checking). This is really intended for
1380 * use only in the main running loop of the client (the_game()) where the faster
1381 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1382 * (e.g. formspecs) should continue using getKeySetting().
1390 populate_nonchanging();
1395 // Keys that are not settings dependent
1396 void populate_nonchanging();
1398 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1399 InputHandler *handler;
1402 void KeyCache::populate_nonchanging()
1404 key[KeyType::ESC] = EscapeKey;
1407 void KeyCache::populate()
1409 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1410 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1411 key[KeyType::LEFT] = getKeySetting("keymap_left");
1412 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1413 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1414 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1415 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1417 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1419 key[KeyType::DROP] = getKeySetting("keymap_drop");
1420 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1421 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1422 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1423 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1424 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1425 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1426 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1427 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1428 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1429 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1430 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1431 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1432 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1433 = getKeySetting("keymap_toggle_force_fog_off");
1434 key[KeyType::TOGGLE_UPDATE_CAMERA]
1435 = getKeySetting("keymap_toggle_update_camera");
1436 key[KeyType::TOGGLE_DEBUG]
1437 = getKeySetting("keymap_toggle_debug");
1438 key[KeyType::TOGGLE_PROFILER]
1439 = getKeySetting("keymap_toggle_profiler");
1440 key[KeyType::CAMERA_MODE]
1441 = getKeySetting("keymap_camera_mode");
1442 key[KeyType::INCREASE_VIEWING_RANGE]
1443 = getKeySetting("keymap_increase_viewing_range_min");
1444 key[KeyType::DECREASE_VIEWING_RANGE]
1445 = getKeySetting("keymap_decrease_viewing_range_min");
1446 key[KeyType::RANGESELECT]
1447 = getKeySetting("keymap_rangeselect");
1448 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1450 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1451 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1452 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1453 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1455 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1458 // First clear all keys, then re-add the ones we listen for
1459 handler->dontListenForKeys();
1460 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1461 handler->listenForKey(key[i]);
1463 handler->listenForKey(EscapeKey);
1464 handler->listenForKey(CancelKey);
1465 for (size_t i = 0; i < 10; i++) {
1466 handler->listenForKey(NumberKey[i]);
1472 /****************************************************************************
1474 ****************************************************************************/
1476 const float object_hit_delay = 0.2;
1479 u32 last_time, busy_time, sleep_time;
1483 /* The reason the following structs are not anonymous structs within the
1484 * class is that they are not used by the majority of member functions and
1485 * many functions that do require objects of thse types do not modify them
1486 * (so they can be passed as a const qualified parameter)
1488 struct CameraOrientation {
1489 f32 camera_yaw; // "right/left"
1490 f32 camera_pitch; // "up/down"
1493 struct GameRunData {
1496 PointedThing pointed_old;
1500 bool update_wielded_item_trigger;
1501 bool reset_jump_timer;
1502 float nodig_delay_timer;
1504 float dig_time_complete;
1505 float repeat_rightclick_timer;
1506 float object_hit_delay_timer;
1507 float time_from_last_punch;
1508 ClientActiveObject *selected_object;
1512 float update_draw_list_timer;
1513 float statustext_time;
1517 v3f update_draw_list_last_cam_dir;
1519 u32 profiler_current_page;
1520 u32 profiler_max_page; // Number of pages
1523 float time_of_day_smooth;
1527 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1535 Jitter dtime_jitter, busy_time_jitter;
1538 /* Flags that can, or may, change during main game loop
1540 struct VolatileRunFlags {
1547 bool show_profiler_graph;
1548 bool disable_camera_update;
1549 bool first_loop_after_window_activation;
1550 bool camera_offset_changed;
1554 /****************************************************************************
1556 ****************************************************************************/
1558 /* This is not intended to be a public class. If a public class becomes
1559 * desirable then it may be better to create another 'wrapper' class that
1560 * hides most of the stuff in this class (nothing in this class is required
1561 * by any other file) but exposes the public methods/data only.
1568 bool startup(bool *kill,
1570 InputHandler *input,
1571 IrrlichtDevice *device,
1572 const std::string &map_dir,
1573 const std::string &playername,
1574 const std::string &password,
1575 // If address is "", local server is used and address is updated
1576 std::string *address,
1578 std::string &error_message,
1580 ChatBackend *chat_backend,
1581 const SubgameSpec &gamespec, // Used for local game
1582 bool simple_singleplayer_mode);
1589 void extendedResourceCleanup();
1591 // Basic initialisation
1592 bool init(const std::string &map_dir, std::string *address,
1594 const SubgameSpec &gamespec);
1596 bool createSingleplayerServer(const std::string map_dir,
1597 const SubgameSpec &gamespec, u16 port, std::string *address);
1600 bool createClient(const std::string &playername,
1601 const std::string &password, std::string *address, u16 port);
1604 // Client connection
1605 bool connectToServer(const std::string &playername,
1606 const std::string &password, std::string *address, u16 port,
1607 bool *connect_ok, bool *aborted);
1608 bool getServerContent(bool *aborted);
1612 void updateInteractTimers(GameRunData *runData, f32 dtime);
1613 bool checkConnection();
1614 bool handleCallbacks();
1615 void processQueues();
1616 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1617 const FpsControl &draw_times, f32 dtime);
1618 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1620 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1623 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1625 void processKeyInput(VolatileRunFlags *flags,
1626 float *statustext_time,
1628 bool *reset_jump_timer,
1629 u32 *profiler_current_page,
1630 u32 profiler_max_page);
1631 void processItemSelection(u16 *new_playeritem);
1633 void dropSelectedItem();
1634 void openInventory();
1635 void openConsole(float height, const wchar_t *line=NULL);
1636 void toggleFreeMove(float *statustext_time);
1637 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1638 void toggleFast(float *statustext_time);
1639 void toggleNoClip(float *statustext_time);
1640 void toggleCinematic(float *statustext_time);
1641 void toggleAutorun(float *statustext_time);
1643 void toggleChat(float *statustext_time, bool *flag);
1644 void toggleHud(float *statustext_time, bool *flag);
1645 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1646 bool shift_pressed);
1647 void toggleFog(float *statustext_time, bool *flag);
1648 void toggleDebug(float *statustext_time, bool *show_debug,
1649 bool *show_profiler_graph, bool *show_wireframe);
1650 void toggleUpdateCamera(float *statustext_time, bool *flag);
1651 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1652 u32 profiler_max_page);
1654 void increaseViewRange(float *statustext_time);
1655 void decreaseViewRange(float *statustext_time);
1656 void toggleFullViewRange(float *statustext_time);
1658 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags,
1660 void updateCameraOrientation(CameraOrientation *cam,
1661 const VolatileRunFlags &flags, float dtime);
1662 void updatePlayerControl(const CameraOrientation &cam);
1663 void step(f32 *dtime);
1664 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1665 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1666 float time_from_last_punch);
1667 void updateSound(f32 dtime);
1668 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1670 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1671 void handlePointingAtNode(GameRunData *runData,
1672 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1673 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1674 void handlePointingAtObject(GameRunData *runData,
1675 const PointedThing &pointed, const ItemStack &playeritem,
1676 const v3f &player_position, bool show_debug);
1677 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1678 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1680 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1681 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1682 void updateGui(float *statustext_time, const RunStats &stats,
1683 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1684 const CameraOrientation &cam);
1685 void updateProfilerGraphs(ProfilerGraph *graph);
1688 void limitFps(FpsControl *fps_timings, f32 *dtime);
1690 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1691 bool draw_clouds = true);
1693 static void settingChangedCallback(const std::string &setting_name, void *data);
1694 void readSettings();
1696 inline bool getLeftClicked()
1698 return input->getLeftClicked() ||
1699 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1701 inline bool getRightClicked()
1703 return input->getRightClicked() ||
1704 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1706 inline bool isLeftPressed()
1708 return input->getLeftState() ||
1709 input->joystick.isKeyDown(KeyType::MOUSE_L);
1711 inline bool isRightPressed()
1713 return input->getRightState() ||
1714 input->joystick.isKeyDown(KeyType::MOUSE_R);
1716 inline bool getLeftReleased()
1718 return input->getLeftReleased() ||
1719 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1722 inline bool isKeyDown(GameKeyType k)
1724 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1726 inline bool wasKeyDown(GameKeyType k)
1728 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1732 void handleAndroidChatInput();
1736 InputHandler *input;
1741 IWritableTextureSource *texture_src;
1742 IWritableShaderSource *shader_src;
1744 // When created, these will be filled with data received from the server
1745 IWritableItemDefManager *itemdef_manager;
1746 IWritableNodeDefManager *nodedef_manager;
1748 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1749 ISoundManager *sound;
1750 bool sound_is_dummy;
1751 SoundMaker *soundmaker;
1753 ChatBackend *chat_backend;
1755 GUIFormSpecMenu *current_formspec;
1757 EventManager *eventmgr;
1758 QuicktuneShortcutter *quicktune;
1760 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1761 MapDrawControl *draw_control;
1763 Clouds *clouds; // Free using ->Drop()
1764 Sky *sky; // Free using ->Drop()
1765 Inventory *local_inventory;
1769 GameRunData runData;
1770 VolatileRunFlags flags;
1773 This class does take ownership/responsibily for cleaning up etc of any of
1774 these items (e.g. device)
1776 IrrlichtDevice *device;
1777 video::IVideoDriver *driver;
1778 scene::ISceneManager *smgr;
1780 std::string *error_message;
1781 bool *reconnect_requested;
1782 IGameDef *gamedef; // Convenience (same as *client)
1783 scene::ISceneNode *skybox;
1786 bool simple_singleplayer_mode;
1789 /* Pre-calculated values
1791 int crack_animation_length;
1795 gui::IGUIStaticText *guitext; // First line of debug text
1796 gui::IGUIStaticText *guitext2; // Second line of debug text
1797 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1798 gui::IGUIStaticText *guitext_status;
1799 gui::IGUIStaticText *guitext_chat; // Chat text
1800 gui::IGUIStaticText *guitext_profiler; // Profiler text
1802 std::wstring infotext;
1803 std::wstring statustext;
1807 IntervalLimiter profiler_interval;
1810 * TODO: Local caching of settings is not optimal and should at some stage
1811 * be updated to use a global settings object for getting thse values
1812 * (as opposed to the this local caching). This can be addressed in
1815 bool m_cache_doubletap_jump;
1816 bool m_cache_enable_clouds;
1817 bool m_cache_enable_joysticks;
1818 bool m_cache_enable_particles;
1819 bool m_cache_enable_fog;
1820 bool m_cache_enable_noclip;
1821 bool m_cache_enable_free_move;
1822 f32 m_cache_mouse_sensitivity;
1823 f32 m_cache_joystick_frustum_sensitivity;
1824 f32 m_repeat_right_click_time;
1827 bool m_cache_hold_aux1;
1828 bool m_android_chat_open;
1837 itemdef_manager(NULL),
1838 nodedef_manager(NULL),
1840 sound_is_dummy(false),
1843 current_formspec(NULL),
1846 gui_chat_console(NULL),
1851 local_inventory(NULL),
1855 g_settings->registerChangedCallback("doubletap_jump",
1856 &settingChangedCallback, this);
1857 g_settings->registerChangedCallback("enable_clouds",
1858 &settingChangedCallback, this);
1859 g_settings->registerChangedCallback("doubletap_joysticks",
1860 &settingChangedCallback, this);
1861 g_settings->registerChangedCallback("enable_particles",
1862 &settingChangedCallback, this);
1863 g_settings->registerChangedCallback("enable_fog",
1864 &settingChangedCallback, this);
1865 g_settings->registerChangedCallback("mouse_sensitivity",
1866 &settingChangedCallback, this);
1867 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1868 &settingChangedCallback, this);
1869 g_settings->registerChangedCallback("repeat_rightclick_time",
1870 &settingChangedCallback, this);
1871 g_settings->registerChangedCallback("noclip",
1872 &settingChangedCallback, this);
1873 g_settings->registerChangedCallback("free_move",
1874 &settingChangedCallback, this);
1879 m_cache_hold_aux1 = false; // This is initialised properly later
1886 /****************************************************************************
1888 ****************************************************************************/
1894 if (!sound_is_dummy)
1897 delete server; // deleted first to stop all server threads
1900 delete local_inventory;
1906 delete nodedef_manager;
1907 delete itemdef_manager;
1908 delete draw_control;
1910 extendedResourceCleanup();
1912 g_settings->deregisterChangedCallback("doubletap_jump",
1913 &settingChangedCallback, this);
1914 g_settings->deregisterChangedCallback("enable_clouds",
1915 &settingChangedCallback, this);
1916 g_settings->deregisterChangedCallback("enable_particles",
1917 &settingChangedCallback, this);
1918 g_settings->deregisterChangedCallback("enable_fog",
1919 &settingChangedCallback, this);
1920 g_settings->deregisterChangedCallback("mouse_sensitivity",
1921 &settingChangedCallback, this);
1922 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1923 &settingChangedCallback, this);
1924 g_settings->deregisterChangedCallback("noclip",
1925 &settingChangedCallback, this);
1926 g_settings->deregisterChangedCallback("free_move",
1927 &settingChangedCallback, this);
1930 bool Game::startup(bool *kill,
1932 InputHandler *input,
1933 IrrlichtDevice *device,
1934 const std::string &map_dir,
1935 const std::string &playername,
1936 const std::string &password,
1937 std::string *address, // can change if simple_singleplayer_mode
1939 std::string &error_message,
1941 ChatBackend *chat_backend,
1942 const SubgameSpec &gamespec,
1943 bool simple_singleplayer_mode)
1946 this->device = device;
1948 this->error_message = &error_message;
1949 this->reconnect_requested = reconnect;
1950 this->random_input = random_input;
1951 this->input = input;
1952 this->chat_backend = chat_backend;
1953 this->simple_singleplayer_mode = simple_singleplayer_mode;
1955 keycache.handler = input;
1956 keycache.populate();
1958 driver = device->getVideoDriver();
1959 smgr = device->getSceneManager();
1961 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1963 memset(&runData, 0, sizeof(runData));
1964 runData.time_from_last_punch = 10.0;
1965 runData.profiler_max_page = 3;
1966 runData.update_wielded_item_trigger = true;
1968 memset(&flags, 0, sizeof(flags));
1969 flags.show_chat = true;
1970 flags.show_hud = true;
1971 flags.show_debug = g_settings->getBool("show_debug");
1972 flags.invert_mouse = g_settings->getBool("invert_mouse");
1973 flags.first_loop_after_window_activation = true;
1975 if (!init(map_dir, address, port, gamespec))
1978 if (!createClient(playername, password, address, port))
1987 ProfilerGraph graph;
1988 RunStats stats = { 0 };
1989 CameraOrientation cam_view_target = { 0 };
1990 CameraOrientation cam_view = { 0 };
1991 FpsControl draw_times = { 0 };
1992 f32 dtime; // in seconds
1994 /* Clear the profiler */
1995 Profiler::GraphValues dummyvalues;
1996 g_profiler->graphGet(dummyvalues);
1998 draw_times.last_time = device->getTimer()->getTime();
2000 set_light_table(g_settings->getFloat("display_gamma"));
2003 m_cache_hold_aux1 = g_settings->getBool("fast_move")
2004 && client->checkPrivilege("fast");
2007 while (device->run()
2008 && !(*kill || g_gamecallback->shutdown_requested
2009 || (server && server->getShutdownRequested()))) {
2011 /* Must be called immediately after a device->run() call because it
2012 * uses device->getTimer()->getTime()
2014 limitFps(&draw_times, &dtime);
2016 updateStats(&stats, draw_times, dtime);
2017 updateInteractTimers(&runData, dtime);
2019 if (!checkConnection())
2021 if (!handleCallbacks())
2027 hud->resizeHotbar();
2029 updateProfilers(runData, stats, draw_times, dtime);
2030 processUserInput(&flags, &runData, dtime);
2031 // Update camera before player movement to avoid camera lag of one frame
2032 updateCameraDirection(&cam_view_target, &flags, dtime);
2033 float cam_smoothing = 0;
2034 if (g_settings->getBool("cinematic"))
2035 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
2037 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
2038 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
2039 cam_view.camera_yaw += (cam_view_target.camera_yaw -
2040 cam_view.camera_yaw) * cam_smoothing;
2041 cam_view.camera_pitch += (cam_view_target.camera_pitch -
2042 cam_view.camera_pitch) * cam_smoothing;
2043 updatePlayerControl(cam_view);
2045 processClientEvents(&cam_view_target, &runData.damage_flash);
2046 updateCamera(&flags, draw_times.busy_time, dtime,
2047 runData.time_from_last_punch);
2049 processPlayerInteraction(&runData, dtime, flags.show_hud,
2051 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
2052 updateProfilerGraphs(&graph);
2054 // Update if minimap has been disabled by the server
2055 flags.show_minimap &= !client->isMinimapDisabledByServer();
2060 void Game::shutdown()
2062 if (g_settings->get("3d_mode") == "pageflip") {
2063 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
2066 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
2071 if (gui_chat_console)
2072 gui_chat_console->drop();
2078 while (g_menumgr.menuCount() > 0) {
2079 g_menumgr.m_stack.front()->setVisible(false);
2080 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
2083 if (current_formspec) {
2084 current_formspec->drop();
2085 current_formspec = NULL;
2088 chat_backend->addMessage(L"", L"# Disconnected.");
2089 chat_backend->addMessage(L"", L"");
2093 while (!client->isShutdown()) {
2094 assert(texture_src != NULL);
2095 assert(shader_src != NULL);
2096 texture_src->processQueue();
2097 shader_src->processQueue();
2104 /****************************************************************************/
2105 /****************************************************************************
2107 ****************************************************************************/
2108 /****************************************************************************/
2111 const std::string &map_dir,
2112 std::string *address,
2114 const SubgameSpec &gamespec)
2116 showOverlayMessage(wgettext("Loading..."), 0, 0);
2118 texture_src = createTextureSource(device);
2119 shader_src = createShaderSource(device);
2121 itemdef_manager = createItemDefManager();
2122 nodedef_manager = createNodeDefManager();
2124 eventmgr = new EventManager();
2125 quicktune = new QuicktuneShortcutter();
2127 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2128 && eventmgr && quicktune))
2134 // Create a server if not connecting to an existing one
2135 if (*address == "") {
2136 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2143 bool Game::initSound()
2146 if (g_settings->getBool("enable_sound")) {
2147 infostream << "Attempting to use OpenAL audio" << std::endl;
2148 sound = createOpenALSoundManager(&soundfetcher);
2150 infostream << "Failed to initialize OpenAL audio" << std::endl;
2152 infostream << "Sound disabled." << std::endl;
2156 infostream << "Using dummy audio." << std::endl;
2157 sound = &dummySoundManager;
2158 sound_is_dummy = true;
2161 soundmaker = new SoundMaker(sound, nodedef_manager);
2165 soundmaker->registerReceiver(eventmgr);
2170 bool Game::createSingleplayerServer(const std::string map_dir,
2171 const SubgameSpec &gamespec, u16 port, std::string *address)
2173 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2175 std::string bind_str = g_settings->get("bind_address");
2176 Address bind_addr(0, 0, 0, 0, port);
2178 if (g_settings->getBool("ipv6_server")) {
2179 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2183 bind_addr.Resolve(bind_str.c_str());
2184 } catch (ResolveError &e) {
2185 infostream << "Resolving bind address \"" << bind_str
2186 << "\" failed: " << e.what()
2187 << " -- Listening on all addresses." << std::endl;
2190 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2191 *error_message = "Unable to listen on " +
2192 bind_addr.serializeString() +
2193 " because IPv6 is disabled";
2194 errorstream << *error_message << std::endl;
2198 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2199 bind_addr.isIPv6());
2201 server->start(bind_addr);
2206 bool Game::createClient(const std::string &playername,
2207 const std::string &password, std::string *address, u16 port)
2209 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2211 draw_control = new MapDrawControl;
2215 bool could_connect, connect_aborted;
2217 if (!connectToServer(playername, password, address, port,
2218 &could_connect, &connect_aborted))
2221 if (!could_connect) {
2222 if (error_message->empty() && !connect_aborted) {
2223 // Should not happen if error messages are set properly
2224 *error_message = "Connection failed for unknown reason";
2225 errorstream << *error_message << std::endl;
2230 if (!getServerContent(&connect_aborted)) {
2231 if (error_message->empty() && !connect_aborted) {
2232 // Should not happen if error messages are set properly
2233 *error_message = "Connection failed for unknown reason";
2234 errorstream << *error_message << std::endl;
2239 GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
2240 &flags.force_fog_off, &runData.fog_range, client);
2241 shader_src->addShaderConstantSetterFactory(scsf);
2243 // Update cached textures, meshes and materials
2244 client->afterContentReceived(device);
2248 camera = new Camera(smgr, *draw_control, gamedef);
2249 if (!camera || !camera->successfullyCreated(*error_message))
2251 client->setCamera(camera);
2255 if (m_cache_enable_clouds) {
2256 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2258 *error_message = "Memory allocation error (clouds)";
2259 errorstream << *error_message << std::endl;
2266 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2268 skybox = NULL; // This is used/set later on in the main run loop
2270 local_inventory = new Inventory(itemdef_manager);
2272 if (!(sky && local_inventory)) {
2273 *error_message = "Memory allocation error (sky or local inventory)";
2274 errorstream << *error_message << std::endl;
2278 /* Pre-calculated values
2280 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2282 v2u32 size = t->getOriginalSize();
2283 crack_animation_length = size.Y / size.X;
2285 crack_animation_length = 5;
2291 /* Set window caption
2293 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2295 str += utf8_to_wide(g_version_hash);
2297 str += driver->getName();
2299 device->setWindowCaption(str.c_str());
2301 LocalPlayer *player = client->getEnv().getLocalPlayer();
2302 player->hurt_tilt_timer = 0;
2303 player->hurt_tilt_strength = 0;
2305 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2308 *error_message = "Memory error: could not create HUD";
2309 errorstream << *error_message << std::endl;
2313 mapper = client->getMapper();
2314 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2319 bool Game::initGui()
2321 // First line of debug text
2322 guitext = addStaticText(guienv,
2323 utf8_to_wide(PROJECT_NAME_C).c_str(),
2324 core::rect<s32>(0, 0, 0, 0),
2325 false, false, guiroot);
2327 // Second line of debug text
2328 guitext2 = addStaticText(guienv,
2330 core::rect<s32>(0, 0, 0, 0),
2331 false, false, guiroot);
2333 // At the middle of the screen
2334 // Object infos are shown in this
2335 guitext_info = addStaticText(guienv,
2337 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2338 false, true, guiroot);
2340 // Status text (displays info when showing and hiding GUI stuff, etc.)
2341 guitext_status = addStaticText(guienv,
2343 core::rect<s32>(0, 0, 0, 0),
2344 false, false, guiroot);
2345 guitext_status->setVisible(false);
2348 guitext_chat = addStaticText(
2351 core::rect<s32>(0, 0, 0, 0),
2352 //false, false); // Disable word wrap as of now
2353 false, true, guiroot);
2355 // Remove stale "recent" chat messages from previous connections
2356 chat_backend->clearRecentChat();
2358 // Chat backend and console
2359 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2360 -1, chat_backend, client, &g_menumgr);
2361 if (!gui_chat_console) {
2362 *error_message = "Could not allocate memory for chat console";
2363 errorstream << *error_message << std::endl;
2367 // Profiler text (size is updated when text is updated)
2368 guitext_profiler = addStaticText(guienv,
2370 core::rect<s32>(0, 0, 0, 0),
2371 false, false, guiroot);
2372 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2373 guitext_profiler->setVisible(false);
2374 guitext_profiler->setWordWrap(true);
2376 #ifdef HAVE_TOUCHSCREENGUI
2378 if (g_touchscreengui)
2379 g_touchscreengui->init(texture_src);
2386 bool Game::connectToServer(const std::string &playername,
2387 const std::string &password, std::string *address, u16 port,
2388 bool *connect_ok, bool *aborted)
2390 *connect_ok = false; // Let's not be overly optimistic
2392 bool local_server_mode = false;
2394 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2396 Address connect_address(0, 0, 0, 0, port);
2399 connect_address.Resolve(address->c_str());
2401 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2402 //connect_address.Resolve("localhost");
2403 if (connect_address.isIPv6()) {
2404 IPv6AddressBytes addr_bytes;
2405 addr_bytes.bytes[15] = 1;
2406 connect_address.setAddress(&addr_bytes);
2408 connect_address.setAddress(127, 0, 0, 1);
2410 local_server_mode = true;
2412 } catch (ResolveError &e) {
2413 *error_message = std::string("Couldn't resolve address: ") + e.what();
2414 errorstream << *error_message << std::endl;
2418 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2419 *error_message = "Unable to connect to " +
2420 connect_address.serializeString() +
2421 " because IPv6 is disabled";
2422 errorstream << *error_message << std::endl;
2426 client = new Client(device,
2427 playername.c_str(), password,
2428 *draw_control, texture_src, shader_src,
2429 itemdef_manager, nodedef_manager, sound, eventmgr,
2430 connect_address.isIPv6());
2435 gamedef = client; // Client acts as our GameDef
2437 infostream << "Connecting to server at ";
2438 connect_address.print(&infostream);
2439 infostream << std::endl;
2441 client->connect(connect_address, *address,
2442 simple_singleplayer_mode || local_server_mode);
2445 Wait for server to accept connection
2451 FpsControl fps_control = { 0 };
2453 f32 wait_time = 0; // in seconds
2455 fps_control.last_time = device->getTimer()->getTime();
2457 while (device->run()) {
2459 limitFps(&fps_control, &dtime);
2461 // Update client and server
2462 client->step(dtime);
2465 server->step(dtime);
2468 if (client->getState() == LC_Init) {
2474 if (client->accessDenied()) {
2475 *error_message = "Access denied. Reason: "
2476 + client->accessDeniedReason();
2477 *reconnect_requested = client->reconnectRequested();
2478 errorstream << *error_message << std::endl;
2482 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2484 infostream << "Connect aborted [Escape]" << std::endl;
2489 // Only time out if we aren't waiting for the server we started
2490 if ((*address != "") && (wait_time > 10)) {
2491 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2492 // If no pre v25 init was sent, and no answer was received,
2493 // but the low level connection could be established
2494 // (meaning that we have a peer id), then we probably wanted
2495 // to connect to a legacy server. In this case, tell the user
2496 // to enable the option to be able to connect.
2497 if (!sent_old_init &&
2498 (client->getProtoVersion() == 0) &&
2499 client->connectedToServer()) {
2500 *error_message = "Connection failure: init packet not "
2501 "recognized by server.\n"
2502 "Most likely the server uses an old protocol version (<v25).\n"
2503 "Please ask the server owner to update to 0.4.13 or later.\n"
2504 "To still connect to the server in the meantime,\n"
2505 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2506 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2507 "entry in the advanced settings menu.";
2509 *error_message = "Connection timed out.";
2511 errorstream << *error_message << std::endl;
2516 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2518 } catch (con::PeerNotFoundException &e) {
2519 // TODO: Should something be done here? At least an info/error
2527 bool Game::getServerContent(bool *aborted)
2531 FpsControl fps_control = { 0 };
2532 f32 dtime; // in seconds
2534 fps_control.last_time = device->getTimer()->getTime();
2536 while (device->run()) {
2538 limitFps(&fps_control, &dtime);
2540 // Update client and server
2541 client->step(dtime);
2544 server->step(dtime);
2547 if (client->mediaReceived() && client->itemdefReceived() &&
2548 client->nodedefReceived()) {
2553 if (!checkConnection())
2556 if (client->getState() < LC_Init) {
2557 *error_message = "Client disconnected";
2558 errorstream << *error_message << std::endl;
2562 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2564 infostream << "Connect aborted [Escape]" << std::endl;
2571 if (!client->itemdefReceived()) {
2572 const wchar_t *text = wgettext("Item definitions...");
2574 draw_load_screen(text, device, guienv, dtime, progress);
2576 } else if (!client->nodedefReceived()) {
2577 const wchar_t *text = wgettext("Node definitions...");
2579 draw_load_screen(text, device, guienv, dtime, progress);
2582 std::stringstream message;
2583 message.precision(3);
2584 message << gettext("Media...");
2586 if ((USE_CURL == 0) ||
2587 (!g_settings->getBool("enable_remote_media_server"))) {
2588 float cur = client->getCurRate();
2589 std::string cur_unit = gettext("KiB/s");
2593 cur_unit = gettext("MiB/s");
2596 message << " (" << cur << ' ' << cur_unit << ")";
2599 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2600 draw_load_screen(utf8_to_wide(message.str()), device,
2601 guienv, dtime, progress);
2609 /****************************************************************************/
2610 /****************************************************************************
2612 ****************************************************************************/
2613 /****************************************************************************/
2615 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2617 if (runData->nodig_delay_timer >= 0)
2618 runData->nodig_delay_timer -= dtime;
2620 if (runData->object_hit_delay_timer >= 0)
2621 runData->object_hit_delay_timer -= dtime;
2623 runData->time_from_last_punch += dtime;
2627 /* returns false if game should exit, otherwise true
2629 inline bool Game::checkConnection()
2631 if (client->accessDenied()) {
2632 *error_message = "Access denied. Reason: "
2633 + client->accessDeniedReason();
2634 *reconnect_requested = client->reconnectRequested();
2635 errorstream << *error_message << std::endl;
2643 /* returns false if game should exit, otherwise true
2645 inline bool Game::handleCallbacks()
2647 if (g_gamecallback->disconnect_requested) {
2648 g_gamecallback->disconnect_requested = false;
2652 if (g_gamecallback->changepassword_requested) {
2653 (new GUIPasswordChange(guienv, guiroot, -1,
2654 &g_menumgr, client))->drop();
2655 g_gamecallback->changepassword_requested = false;
2658 if (g_gamecallback->changevolume_requested) {
2659 (new GUIVolumeChange(guienv, guiroot, -1,
2660 &g_menumgr))->drop();
2661 g_gamecallback->changevolume_requested = false;
2664 if (g_gamecallback->keyconfig_requested) {
2665 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2666 &g_menumgr))->drop();
2667 g_gamecallback->keyconfig_requested = false;
2670 if (g_gamecallback->keyconfig_changed) {
2671 keycache.populate(); // update the cache with new settings
2672 g_gamecallback->keyconfig_changed = false;
2679 void Game::processQueues()
2681 texture_src->processQueue();
2682 itemdef_manager->processQueue(gamedef);
2683 shader_src->processQueue();
2687 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2688 const FpsControl &draw_times, f32 dtime)
2690 float profiler_print_interval =
2691 g_settings->getFloat("profiler_print_interval");
2692 bool print_to_log = true;
2694 if (profiler_print_interval == 0) {
2695 print_to_log = false;
2696 profiler_print_interval = 5;
2699 if (profiler_interval.step(dtime, profiler_print_interval)) {
2701 infostream << "Profiler:" << std::endl;
2702 g_profiler->print(infostream);
2705 update_profiler_gui(guitext_profiler, g_fontengine,
2706 runData.profiler_current_page, runData.profiler_max_page,
2707 driver->getScreenSize().Height);
2709 g_profiler->clear();
2712 addProfilerGraphs(stats, draw_times, dtime);
2716 void Game::addProfilerGraphs(const RunStats &stats,
2717 const FpsControl &draw_times, f32 dtime)
2719 g_profiler->graphAdd("mainloop_other",
2720 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2722 if (draw_times.sleep_time != 0)
2723 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2724 g_profiler->graphAdd("mainloop_dtime", dtime);
2726 g_profiler->add("Elapsed time", dtime);
2727 g_profiler->avg("FPS", 1. / dtime);
2731 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2738 /* Time average and jitter calculation
2740 jp = &stats->dtime_jitter;
2741 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2743 jitter = dtime - jp->avg;
2745 if (jitter > jp->max)
2748 jp->counter += dtime;
2750 if (jp->counter > 0.0) {
2752 jp->max_sample = jp->max;
2753 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2757 /* Busytime average and jitter calculation
2759 jp = &stats->busy_time_jitter;
2760 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2762 jitter = draw_times.busy_time - jp->avg;
2764 if (jitter > jp->max)
2766 if (jitter < jp->min)
2769 jp->counter += dtime;
2771 if (jp->counter > 0.0) {
2773 jp->max_sample = jp->max;
2774 jp->min_sample = jp->min;
2782 /****************************************************************************
2784 ****************************************************************************/
2786 void Game::processUserInput(VolatileRunFlags *flags,
2787 GameRunData *runData, f32 dtime)
2789 // Reset input if window not active or some menu is active
2790 if (device->isWindowActive() == false
2791 || noMenuActive() == false
2792 || guienv->hasFocus(gui_chat_console)) {
2794 #ifdef HAVE_TOUCHSCREENGUI
2795 g_touchscreengui->hide();
2798 #ifdef HAVE_TOUCHSCREENGUI
2799 else if (g_touchscreengui) {
2800 /* on touchscreengui step may generate own input events which ain't
2801 * what we want in case we just did clear them */
2802 g_touchscreengui->step(dtime);
2806 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2807 gui_chat_console->closeConsoleAtOnce();
2810 // Input handler step() (used by the random input generator)
2814 if (current_formspec != NULL)
2815 current_formspec->getAndroidUIInput();
2817 handleAndroidChatInput();
2820 // Increase timer for double tap of "keymap_jump"
2821 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2822 runData->jump_timer += dtime;
2826 &runData->statustext_time,
2827 &runData->jump_timer,
2828 &runData->reset_jump_timer,
2829 &runData->profiler_current_page,
2830 runData->profiler_max_page);
2832 processItemSelection(&runData->new_playeritem);
2836 void Game::processKeyInput(VolatileRunFlags *flags,
2837 float *statustext_time,
2839 bool *reset_jump_timer,
2840 u32 *profiler_current_page,
2841 u32 profiler_max_page)
2844 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2846 if (wasKeyDown(KeyType::DROP)) {
2848 } else if (wasKeyDown(KeyType::AUTORUN)) {
2849 toggleAutorun(statustext_time);
2850 } else if (wasKeyDown(KeyType::INVENTORY)) {
2852 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2853 if (!gui_chat_console->isOpenInhibited()) {
2854 show_pause_menu(¤t_formspec, client, gamedef,
2855 texture_src, device, &input->joystick,
2856 simple_singleplayer_mode);
2858 } else if (wasKeyDown(KeyType::CHAT)) {
2859 openConsole(0.2, L"");
2860 } else if (wasKeyDown(KeyType::CMD)) {
2861 openConsole(0.2, L"/");
2862 } else if (wasKeyDown(KeyType::CONSOLE)) {
2864 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2865 toggleFreeMove(statustext_time);
2866 } else if (wasKeyDown(KeyType::JUMP)) {
2867 toggleFreeMoveAlt(statustext_time, jump_timer);
2868 *reset_jump_timer = true;
2869 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2870 toggleFast(statustext_time);
2871 } else if (wasKeyDown(KeyType::NOCLIP)) {
2872 toggleNoClip(statustext_time);
2873 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2874 toggleCinematic(statustext_time);
2875 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2876 client->makeScreenshot(device);
2877 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2878 toggleHud(statustext_time, &flags->show_hud);
2879 } else if (wasKeyDown(KeyType::MINIMAP)) {
2880 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2881 isKeyDown(KeyType::SNEAK));
2882 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2883 toggleChat(statustext_time, &flags->show_chat);
2884 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2885 toggleFog(statustext_time, &flags->force_fog_off);
2886 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2887 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2888 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2889 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph,
2890 &draw_control->show_wireframe);
2891 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2892 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2893 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2894 increaseViewRange(statustext_time);
2895 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2896 decreaseViewRange(statustext_time);
2897 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2898 toggleFullViewRange(statustext_time);
2899 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2901 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2903 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2905 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2907 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2908 // Print debug stacks
2909 dstream << "-----------------------------------------"
2911 dstream << "Printing debug stacks:" << std::endl;
2912 dstream << "-----------------------------------------"
2914 debug_stacks_print();
2917 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2918 *reset_jump_timer = false;
2924 if (quicktune->hasMessage()) {
2925 std::string msg = quicktune->getMessage();
2926 statustext = utf8_to_wide(msg);
2927 *statustext_time = 0;
2931 void Game::processItemSelection(u16 *new_playeritem)
2933 LocalPlayer *player = client->getEnv().getLocalPlayer();
2935 /* Item selection using mouse wheel
2937 *new_playeritem = client->getPlayerItem();
2939 s32 wheel = input->getMouseWheel();
2940 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2941 player->hud_hotbar_itemcount - 1);
2945 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2949 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2954 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2956 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2959 /* Item selection using keyboard
2961 for (u16 i = 0; i < 10; i++) {
2962 static const KeyPress *item_keys[10] = {
2963 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2964 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2965 NumberKey + 9, NumberKey + 0,
2968 if (input->wasKeyDown(*item_keys[i])) {
2969 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2970 *new_playeritem = i;
2971 infostream << "Selected item: " << new_playeritem << std::endl;
2979 void Game::dropSelectedItem()
2981 IDropAction *a = new IDropAction();
2983 a->from_inv.setCurrentPlayer();
2984 a->from_list = "main";
2985 a->from_i = client->getPlayerItem();
2986 client->inventoryAction(a);
2990 void Game::openInventory()
2993 * Don't permit to open inventory is CAO or player doesn't exists.
2994 * This prevent showing an empty inventory at player load
2997 LocalPlayer *player = client->getEnv().getLocalPlayer();
2998 if (player == NULL || player->getCAO() == NULL)
3001 infostream << "the_game: " << "Launching inventory" << std::endl;
3003 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
3004 TextDest *txt_dst = new TextDestPlayerInventory(client);
3006 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
3007 device, &input->joystick, fs_src, txt_dst, client);
3009 InventoryLocation inventoryloc;
3010 inventoryloc.setCurrentPlayer();
3011 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
3015 void Game::openConsole(float height, const wchar_t *line)
3018 porting::showInputDialog(gettext("ok"), "", "", 2);
3019 m_android_chat_open = true;
3021 if (gui_chat_console->isOpenInhibited())
3023 gui_chat_console->openConsole(height);
3025 gui_chat_console->setCloseOnEnter(true);
3026 gui_chat_console->replaceAndAddToHistory(line);
3032 void Game::handleAndroidChatInput()
3034 if (m_android_chat_open && porting::getInputDialogState() == 0) {
3035 std::string text = porting::getInputDialogValue();
3036 client->typeChatMessage(utf8_to_wide(text));
3042 void Game::toggleFreeMove(float *statustext_time)
3044 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
3046 bool free_move = !g_settings->getBool("free_move");
3047 g_settings->set("free_move", bool_to_cstr(free_move));
3049 *statustext_time = 0;
3050 statustext = msg[free_move];
3051 if (free_move && !client->checkPrivilege("fly"))
3052 statustext += L" (note: no 'fly' privilege)";
3056 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
3058 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
3059 toggleFreeMove(statustext_time);
3063 void Game::toggleFast(float *statustext_time)
3065 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
3066 bool fast_move = !g_settings->getBool("fast_move");
3067 g_settings->set("fast_move", bool_to_cstr(fast_move));
3069 *statustext_time = 0;
3070 statustext = msg[fast_move];
3072 bool has_fast_privs = client->checkPrivilege("fast");
3074 if (fast_move && !has_fast_privs)
3075 statustext += L" (note: no 'fast' privilege)";
3078 m_cache_hold_aux1 = fast_move && has_fast_privs;
3083 void Game::toggleNoClip(float *statustext_time)
3085 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
3086 bool noclip = !g_settings->getBool("noclip");
3087 g_settings->set("noclip", bool_to_cstr(noclip));
3089 *statustext_time = 0;
3090 statustext = msg[noclip];
3092 if (noclip && !client->checkPrivilege("noclip"))
3093 statustext += L" (note: no 'noclip' privilege)";
3096 void Game::toggleCinematic(float *statustext_time)
3098 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
3099 bool cinematic = !g_settings->getBool("cinematic");
3100 g_settings->set("cinematic", bool_to_cstr(cinematic));
3102 *statustext_time = 0;
3103 statustext = msg[cinematic];
3106 // Add WoW-style autorun by toggling continuous forward.
3107 void Game::toggleAutorun(float *statustext_time)
3109 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
3110 bool autorun_enabled = !g_settings->getBool("continuous_forward");
3111 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
3113 *statustext_time = 0;
3114 statustext = msg[autorun_enabled ? 1 : 0];
3117 void Game::toggleChat(float *statustext_time, bool *flag)
3119 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
3122 *statustext_time = 0;
3123 statustext = msg[*flag];
3127 void Game::toggleHud(float *statustext_time, bool *flag)
3129 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
3132 *statustext_time = 0;
3133 statustext = msg[*flag];
3136 void Game::toggleMinimap(float *statustext_time, bool *flag,
3137 bool show_hud, bool shift_pressed)
3139 if (!show_hud || !g_settings->getBool("enable_minimap"))
3142 if (shift_pressed) {
3143 mapper->toggleMinimapShape();
3147 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
3149 MinimapMode mode = MINIMAP_MODE_OFF;
3150 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
3151 mode = mapper->getMinimapMode();
3152 mode = (MinimapMode)((int)mode + 1);
3157 case MINIMAP_MODE_SURFACEx1:
3158 statustext = L"Minimap in surface mode, Zoom x1";
3160 case MINIMAP_MODE_SURFACEx2:
3161 statustext = L"Minimap in surface mode, Zoom x2";
3163 case MINIMAP_MODE_SURFACEx4:
3164 statustext = L"Minimap in surface mode, Zoom x4";
3166 case MINIMAP_MODE_RADARx1:
3167 statustext = L"Minimap in radar mode, Zoom x1";
3169 case MINIMAP_MODE_RADARx2:
3170 statustext = L"Minimap in radar mode, Zoom x2";
3172 case MINIMAP_MODE_RADARx4:
3173 statustext = L"Minimap in radar mode, Zoom x4";
3176 mode = MINIMAP_MODE_OFF;
3178 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3179 L"Minimap hidden" : L"Minimap disabled by server";
3182 *statustext_time = 0;
3183 mapper->setMinimapMode(mode);
3186 void Game::toggleFog(float *statustext_time, bool *flag)
3188 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3191 *statustext_time = 0;
3192 statustext = msg[*flag];
3196 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3197 bool *show_profiler_graph, bool *show_wireframe)
3199 // Initial / 4x toggle: Chat only
3200 // 1x toggle: Debug text with chat
3201 // 2x toggle: Debug text with profiler graph
3202 // 3x toggle: Debug text and wireframe
3205 *show_profiler_graph = false;
3206 *show_wireframe = false;
3207 statustext = L"Debug info shown";
3208 } else if (!*show_profiler_graph && !*show_wireframe) {
3209 *show_profiler_graph = true;
3210 statustext = L"Profiler graph shown";
3211 } else if (!*show_wireframe && client->checkPrivilege("debug")) {
3212 *show_profiler_graph = false;
3213 *show_wireframe = true;
3214 statustext = L"Wireframe shown";
3216 *show_debug = false;
3217 *show_profiler_graph = false;
3218 *show_wireframe = false;
3219 if (client->checkPrivilege("debug")) {
3220 statustext = L"Debug info, profiler graph, and wireframe hidden";
3222 statustext = L"Debug info and profiler graph hidden";
3225 *statustext_time = 0;
3229 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3231 static const wchar_t *msg[] = {
3232 L"Camera update enabled",
3233 L"Camera update disabled"
3237 *statustext_time = 0;
3238 statustext = msg[*flag];
3242 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3243 u32 profiler_max_page)
3245 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3247 // FIXME: This updates the profiler with incomplete values
3248 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3249 profiler_max_page, driver->getScreenSize().Height);
3251 if (*profiler_current_page != 0) {
3252 std::wstringstream sstr;
3253 sstr << "Profiler shown (page " << *profiler_current_page
3254 << " of " << profiler_max_page << ")";
3255 statustext = sstr.str();
3257 statustext = L"Profiler hidden";
3259 *statustext_time = 0;
3263 void Game::increaseViewRange(float *statustext_time)
3265 s16 range = g_settings->getS16("viewing_range");
3266 s16 range_new = range + 10;
3267 g_settings->set("viewing_range", itos(range_new));
3268 statustext = utf8_to_wide("Viewing range changed to "
3270 *statustext_time = 0;
3274 void Game::decreaseViewRange(float *statustext_time)
3276 s16 range = g_settings->getS16("viewing_range");
3277 s16 range_new = range - 10;
3282 g_settings->set("viewing_range", itos(range_new));
3283 statustext = utf8_to_wide("Viewing range changed to "
3285 *statustext_time = 0;
3289 void Game::toggleFullViewRange(float *statustext_time)
3291 static const wchar_t *msg[] = {
3292 L"Disabled full viewing range",
3293 L"Enabled full viewing range"
3296 draw_control->range_all = !draw_control->range_all;
3297 infostream << msg[draw_control->range_all] << std::endl;
3298 statustext = msg[draw_control->range_all];
3299 *statustext_time = 0;
3303 void Game::updateCameraDirection(CameraOrientation *cam,
3304 VolatileRunFlags *flags, float dtime)
3306 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3309 if (!random_input) {
3310 // Mac OSX gets upset if this is set every frame
3311 if (device->getCursorControl()->isVisible())
3312 device->getCursorControl()->setVisible(false);
3316 if (flags->first_loop_after_window_activation)
3317 flags->first_loop_after_window_activation = false;
3319 updateCameraOrientation(cam, *flags, dtime);
3321 input->setMousePos((driver->getScreenSize().Width / 2),
3322 (driver->getScreenSize().Height / 2));
3326 // Mac OSX gets upset if this is set every frame
3327 if (device->getCursorControl()->isVisible() == false)
3328 device->getCursorControl()->setVisible(true);
3331 if (!flags->first_loop_after_window_activation)
3332 flags->first_loop_after_window_activation = true;
3337 void Game::updateCameraOrientation(CameraOrientation *cam,
3338 const VolatileRunFlags &flags, float dtime)
3340 #ifdef HAVE_TOUCHSCREENGUI
3341 if (g_touchscreengui) {
3342 cam->camera_yaw = g_touchscreengui->getYaw();
3343 cam->camera_pitch = g_touchscreengui->getPitch();
3347 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3348 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3350 if (flags.invert_mouse
3351 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3355 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3356 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3358 #ifdef HAVE_TOUCHSCREENGUI
3362 if (m_cache_enable_joysticks) {
3363 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3364 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3366 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3370 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3374 void Game::updatePlayerControl(const CameraOrientation &cam)
3376 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3378 // DO NOT use the isKeyDown method for the forward, backward, left, right
3379 // buttons, as the code that uses the controls needs to be able to
3380 // distinguish between the two in order to know when to use joysticks.
3382 PlayerControl control(
3383 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3384 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3385 input->isKeyDown(keycache.key[KeyType::LEFT]),
3386 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3387 isKeyDown(KeyType::JUMP),
3388 isKeyDown(KeyType::SPECIAL1),
3389 isKeyDown(KeyType::SNEAK),
3390 isKeyDown(KeyType::ZOOM),
3395 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3396 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3400 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3401 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3402 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3403 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3404 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3405 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3406 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3407 ( (u32)(isLeftPressed() & 0x1) << 7) |
3408 ( (u32)(isRightPressed() & 0x1) << 8
3412 /* For Android, simulate holding down AUX1 (fast move) if the user has
3413 * the fast_move setting toggled on. If there is an aux1 key defined for
3414 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3417 if (m_cache_hold_aux1) {
3418 control.aux1 = control.aux1 ^ true;
3419 keypress_bits ^= ((u32)(1U << 5));
3423 client->setPlayerControl(control);
3424 LocalPlayer *player = client->getEnv().getLocalPlayer();
3425 player->keyPressed = keypress_bits;
3431 inline void Game::step(f32 *dtime)
3433 bool can_be_and_is_paused =
3434 (simple_singleplayer_mode && g_menumgr.pausesGame());
3436 if (can_be_and_is_paused) { // This is for a singleplayer server
3437 *dtime = 0; // No time passes
3439 if (server != NULL) {
3440 //TimeTaker timer("server->step(dtime)");
3441 server->step(*dtime);
3444 //TimeTaker timer("client.step(dtime)");
3445 client->step(*dtime);
3450 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3452 ClientEvent event = client->getClientEvent();
3454 LocalPlayer *player = client->getEnv().getLocalPlayer();
3456 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3458 if (event.type == CE_PLAYER_DAMAGE &&
3459 client->getHP() != 0) {
3460 //u16 damage = event.player_damage.amount;
3461 //infostream<<"Player damage: "<<damage<<std::endl;
3463 *damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3464 *damage_flash = MYMIN(*damage_flash, 127.0);
3466 player->hurt_tilt_timer = 1.5;
3467 player->hurt_tilt_strength =
3468 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3470 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3471 gamedef->event()->put(e);
3472 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3473 cam->camera_yaw = event.player_force_move.yaw;
3474 cam->camera_pitch = event.player_force_move.pitch;
3475 } else if (event.type == CE_DEATHSCREEN) {
3476 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3477 device, &input->joystick, client);
3479 chat_backend->addMessage(L"", L"You died.");
3481 /* Handle visualization */
3483 player->hurt_tilt_timer = 0;
3484 player->hurt_tilt_strength = 0;
3486 } else if (event.type == CE_SHOW_FORMSPEC) {
3487 FormspecFormSource *fs_src =
3488 new FormspecFormSource(*(event.show_formspec.formspec));
3489 TextDestPlayerInventory *txt_dst =
3490 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3492 create_formspec_menu(¤t_formspec, client, gamedef,
3493 texture_src, device, &input->joystick,
3494 fs_src, txt_dst, client);
3496 delete(event.show_formspec.formspec);
3497 delete(event.show_formspec.formname);
3498 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3499 (event.type == CE_ADD_PARTICLESPAWNER) ||
3500 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3501 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3503 } else if (event.type == CE_HUDADD) {
3504 u32 id = event.hudadd.id;
3506 LocalPlayer *player = client->getEnv().getLocalPlayer();
3507 HudElement *e = player->getHud(id);
3510 delete event.hudadd.pos;
3511 delete event.hudadd.name;
3512 delete event.hudadd.scale;
3513 delete event.hudadd.text;
3514 delete event.hudadd.align;
3515 delete event.hudadd.offset;
3516 delete event.hudadd.world_pos;
3517 delete event.hudadd.size;
3522 e->type = (HudElementType)event.hudadd.type;
3523 e->pos = *event.hudadd.pos;
3524 e->name = *event.hudadd.name;
3525 e->scale = *event.hudadd.scale;
3526 e->text = *event.hudadd.text;
3527 e->number = event.hudadd.number;
3528 e->item = event.hudadd.item;
3529 e->dir = event.hudadd.dir;
3530 e->align = *event.hudadd.align;
3531 e->offset = *event.hudadd.offset;
3532 e->world_pos = *event.hudadd.world_pos;
3533 e->size = *event.hudadd.size;
3535 u32 new_id = player->addHud(e);
3536 //if this isn't true our huds aren't consistent
3537 sanity_check(new_id == id);
3539 delete event.hudadd.pos;
3540 delete event.hudadd.name;
3541 delete event.hudadd.scale;
3542 delete event.hudadd.text;
3543 delete event.hudadd.align;
3544 delete event.hudadd.offset;
3545 delete event.hudadd.world_pos;
3546 delete event.hudadd.size;
3547 } else if (event.type == CE_HUDRM) {
3548 HudElement *e = player->removeHud(event.hudrm.id);
3552 } else if (event.type == CE_HUDCHANGE) {
3553 u32 id = event.hudchange.id;
3554 HudElement *e = player->getHud(id);
3557 delete event.hudchange.v3fdata;
3558 delete event.hudchange.v2fdata;
3559 delete event.hudchange.sdata;
3560 delete event.hudchange.v2s32data;
3564 switch (event.hudchange.stat) {
3566 e->pos = *event.hudchange.v2fdata;
3570 e->name = *event.hudchange.sdata;
3573 case HUD_STAT_SCALE:
3574 e->scale = *event.hudchange.v2fdata;
3578 e->text = *event.hudchange.sdata;
3581 case HUD_STAT_NUMBER:
3582 e->number = event.hudchange.data;
3586 e->item = event.hudchange.data;
3590 e->dir = event.hudchange.data;
3593 case HUD_STAT_ALIGN:
3594 e->align = *event.hudchange.v2fdata;
3597 case HUD_STAT_OFFSET:
3598 e->offset = *event.hudchange.v2fdata;
3601 case HUD_STAT_WORLD_POS:
3602 e->world_pos = *event.hudchange.v3fdata;
3606 e->size = *event.hudchange.v2s32data;
3610 delete event.hudchange.v3fdata;
3611 delete event.hudchange.v2fdata;
3612 delete event.hudchange.sdata;
3613 delete event.hudchange.v2s32data;
3614 } else if (event.type == CE_SET_SKY) {
3615 sky->setVisible(false);
3622 // Handle according to type
3623 if (*event.set_sky.type == "regular") {
3624 sky->setVisible(true);
3625 } else if (*event.set_sky.type == "skybox" &&
3626 event.set_sky.params->size() == 6) {
3627 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3628 skybox = smgr->addSkyBoxSceneNode(
3629 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3630 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3631 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3632 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3633 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3634 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3636 // Handle everything else as plain color
3638 if (*event.set_sky.type != "plain")
3639 infostream << "Unknown sky type: "
3640 << (*event.set_sky.type) << std::endl;
3642 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3645 delete event.set_sky.bgcolor;
3646 delete event.set_sky.type;
3647 delete event.set_sky.params;
3648 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3649 bool enable = event.override_day_night_ratio.do_override;
3650 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3651 client->getEnv().setDayNightRatioOverride(enable, value);
3657 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3658 f32 dtime, float time_from_last_punch)
3660 LocalPlayer *player = client->getEnv().getLocalPlayer();
3663 For interaction purposes, get info about the held item
3665 - Is it a usable item?
3666 - Can it point to liquids?
3668 ItemStack playeritem;
3670 InventoryList *mlist = local_inventory->getList("main");
3672 if (mlist && client->getPlayerItem() < mlist->getSize())
3673 playeritem = mlist->getItem(client->getPlayerItem());
3676 ToolCapabilities playeritem_toolcap =
3677 playeritem.getToolCapabilities(itemdef_manager);
3679 v3s16 old_camera_offset = camera->getOffset();
3681 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3682 GenericCAO *playercao = player->getCAO();
3684 // If playercao not loaded, don't change camera
3685 if (playercao == NULL)
3688 camera->toggleCameraMode();
3690 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3691 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3694 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3695 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3697 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3698 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3700 camera->step(dtime);
3702 v3f camera_position = camera->getPosition();
3703 v3f camera_direction = camera->getDirection();
3704 f32 camera_fov = camera->getFovMax();
3705 v3s16 camera_offset = camera->getOffset();
3707 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3709 if (!flags->disable_camera_update) {
3710 client->getEnv().getClientMap().updateCamera(camera_position,
3711 camera_direction, camera_fov, camera_offset);
3713 if (flags->camera_offset_changed) {
3714 client->updateCameraOffset(camera_offset);
3715 client->getEnv().updateCameraOffset(camera_offset);
3718 clouds->updateCameraOffset(camera_offset);
3724 void Game::updateSound(f32 dtime)
3726 // Update sound listener
3727 v3s16 camera_offset = camera->getOffset();
3728 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3729 v3f(0, 0, 0), // velocity
3730 camera->getDirection(),
3731 camera->getCameraNode()->getUpVector());
3732 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3735 // Update sound maker
3736 soundmaker->step(dtime);
3738 LocalPlayer *player = client->getEnv().getLocalPlayer();
3740 ClientMap &map = client->getEnv().getClientMap();
3741 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3742 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3746 void Game::processPlayerInteraction(GameRunData *runData,
3747 f32 dtime, bool show_hud, bool show_debug)
3749 LocalPlayer *player = client->getEnv().getLocalPlayer();
3751 ItemStack playeritem;
3753 InventoryList *mlist = local_inventory->getList("main");
3755 if (mlist && client->getPlayerItem() < mlist->getSize())
3756 playeritem = mlist->getItem(client->getPlayerItem());
3759 const ItemDefinition &playeritem_def =
3760 playeritem.getDefinition(itemdef_manager);
3762 v3f player_position = player->getPosition();
3763 v3f camera_position = camera->getPosition();
3764 v3f camera_direction = camera->getDirection();
3765 v3s16 camera_offset = camera->getOffset();
3769 Calculate what block is the crosshair pointing to
3772 f32 d = playeritem_def.range; // max. distance
3773 f32 d_hand = itemdef_manager->get("").range;
3775 if (d < 0 && d_hand >= 0)
3780 core::line3d<f32> shootline;
3782 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3784 shootline = core::line3d<f32>(camera_position,
3785 camera_position + camera_direction * BS * (d + 1));
3788 // prevent player pointing anything in front-view
3789 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3790 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3793 #ifdef HAVE_TOUCHSCREENGUI
3795 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3796 shootline = g_touchscreengui->getShootline();
3797 shootline.start += intToFloat(camera_offset, BS);
3798 shootline.end += intToFloat(camera_offset, BS);
3803 PointedThing pointed = getPointedThing(
3805 client, hud, player_position, camera_direction,
3806 camera_position, shootline, d,
3807 playeritem_def.liquids_pointable,
3808 !runData->ldown_for_dig,
3811 runData->selected_object);
3813 if (pointed != runData->pointed_old) {
3814 infostream << "Pointing at " << pointed.dump() << std::endl;
3815 hud->updateSelectionMesh(camera_offset);
3820 - releasing left mouse button
3821 - pointing away from node
3823 if (runData->digging) {
3824 if (getLeftReleased()) {
3825 infostream << "Left button released"
3826 << " (stopped digging)" << std::endl;
3827 runData->digging = false;
3828 } else if (pointed != runData->pointed_old) {
3829 if (pointed.type == POINTEDTHING_NODE
3830 && runData->pointed_old.type == POINTEDTHING_NODE
3831 && pointed.node_undersurface
3832 == runData->pointed_old.node_undersurface) {
3833 // Still pointing to the same node, but a different face.
3836 infostream << "Pointing away from node"
3837 << " (stopped digging)" << std::endl;
3838 runData->digging = false;
3839 hud->updateSelectionMesh(camera_offset);
3843 if (!runData->digging) {
3844 client->interact(1, runData->pointed_old);
3845 client->setCrack(-1, v3s16(0, 0, 0));
3846 runData->dig_time = 0.0;
3850 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3851 runData->ldown_for_dig = false;
3854 runData->left_punch = false;
3856 soundmaker->m_player_leftpunch_sound.name = "";
3858 if (isRightPressed())
3859 runData->repeat_rightclick_timer += dtime;
3861 runData->repeat_rightclick_timer = 0;
3863 if (playeritem_def.usable && isLeftPressed()) {
3864 if (getLeftClicked())
3865 client->interact(4, pointed);
3866 } else if (pointed.type == POINTEDTHING_NODE) {
3867 ToolCapabilities playeritem_toolcap =
3868 playeritem.getToolCapabilities(itemdef_manager);
3869 handlePointingAtNode(runData, pointed, playeritem_def,
3870 playeritem_toolcap, dtime);
3871 } else if (pointed.type == POINTEDTHING_OBJECT) {
3872 handlePointingAtObject(runData, pointed, playeritem,
3873 player_position, show_debug);
3874 } else if (isLeftPressed()) {
3875 // When button is held down in air, show continuous animation
3876 runData->left_punch = true;
3877 } else if (getRightClicked()) {
3878 handlePointingAtNothing(runData, playeritem);
3881 runData->pointed_old = pointed;
3883 if (runData->left_punch || getLeftClicked())
3884 camera->setDigging(0); // left click animation
3886 input->resetLeftClicked();
3887 input->resetRightClicked();
3889 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3890 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3892 input->resetLeftReleased();
3893 input->resetRightReleased();
3895 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3896 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3900 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3902 infostream << "Right Clicked in Air" << std::endl;
3903 PointedThing fauxPointed;
3904 fauxPointed.type = POINTEDTHING_NOTHING;
3905 client->interact(5, fauxPointed);
3909 void Game::handlePointingAtNode(GameRunData *runData,
3910 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3911 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3913 v3s16 nodepos = pointed.node_undersurface;
3914 v3s16 neighbourpos = pointed.node_abovesurface;
3917 Check information text of node
3920 ClientMap &map = client->getEnv().getClientMap();
3921 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3924 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3926 MapNode n = map.getNodeNoEx(nodepos);
3928 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3929 infotext = L"Unknown node: ";
3930 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3934 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3935 && client->checkPrivilege("interact")) {
3936 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3939 if ((getRightClicked() ||
3940 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3941 client->checkPrivilege("interact")) {
3942 runData->repeat_rightclick_timer = 0;
3943 infostream << "Ground right-clicked" << std::endl;
3945 if (meta && meta->getString("formspec") != "" && !random_input
3946 && !isKeyDown(KeyType::SNEAK)) {
3947 infostream << "Launching custom inventory view" << std::endl;
3949 InventoryLocation inventoryloc;
3950 inventoryloc.setNodeMeta(nodepos);
3952 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3953 &client->getEnv().getClientMap(), nodepos);
3954 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3956 create_formspec_menu(¤t_formspec, client, gamedef,
3957 texture_src, device, &input->joystick, fs_src, txt_dst, client);
3959 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3961 // Report right click to server
3963 camera->setDigging(1); // right click animation (always shown for feedback)
3965 // If the wielded item has node placement prediction,
3967 bool placed = nodePlacementPrediction(*client,
3969 nodepos, neighbourpos);
3973 client->interact(3, pointed);
3975 soundmaker->m_player_rightpunch_sound =
3976 playeritem_def.sound_place;
3978 soundmaker->m_player_rightpunch_sound =
3981 if (playeritem_def.node_placement_prediction == "" ||
3982 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3983 client->interact(3, pointed); // Report to server
3985 soundmaker->m_player_rightpunch_sound =
3986 playeritem_def.sound_place_failed;
3994 void Game::handlePointingAtObject(GameRunData *runData,
3995 const PointedThing &pointed,
3996 const ItemStack &playeritem,
3997 const v3f &player_position,
4000 infotext = unescape_enriched(
4001 utf8_to_wide(runData->selected_object->infoText()));
4004 if (infotext != L"") {
4007 infotext += unescape_enriched(utf8_to_wide(
4008 runData->selected_object->debugInfoText()));
4011 if (isLeftPressed()) {
4012 bool do_punch = false;
4013 bool do_punch_damage = false;
4015 if (runData->object_hit_delay_timer <= 0.0) {
4017 do_punch_damage = true;
4018 runData->object_hit_delay_timer = object_hit_delay;
4021 if (getLeftClicked())
4025 infostream << "Left-clicked object" << std::endl;
4026 runData->left_punch = true;
4029 if (do_punch_damage) {
4030 // Report direct punch
4031 v3f objpos = runData->selected_object->getPosition();
4032 v3f dir = (objpos - player_position).normalize();
4034 bool disable_send = runData->selected_object->directReportPunch(
4035 dir, &playeritem, runData->time_from_last_punch);
4036 runData->time_from_last_punch = 0;
4039 client->interact(0, pointed);
4041 } else if (getRightClicked()) {
4042 infostream << "Right-clicked object" << std::endl;
4043 client->interact(3, pointed); // place
4048 void Game::handleDigging(GameRunData *runData,
4049 const PointedThing &pointed, const v3s16 &nodepos,
4050 const ToolCapabilities &playeritem_toolcap, f32 dtime)
4052 if (!runData->digging) {
4053 infostream << "Started digging" << std::endl;
4054 client->interact(0, pointed);
4055 runData->digging = true;
4056 runData->ldown_for_dig = true;
4059 LocalPlayer *player = client->getEnv().getLocalPlayer();
4060 ClientMap &map = client->getEnv().getClientMap();
4061 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
4063 // NOTE: Similar piece of code exists on the server side for
4065 // Get digging parameters
4066 DigParams params = getDigParams(nodedef_manager->get(n).groups,
4067 &playeritem_toolcap);
4069 // If can't dig, try hand
4070 if (!params.diggable) {
4071 const ItemDefinition &hand = itemdef_manager->get("");
4072 const ToolCapabilities *tp = hand.tool_capabilities;
4075 params = getDigParams(nodedef_manager->get(n).groups, tp);
4078 if (params.diggable == false) {
4079 // I guess nobody will wait for this long
4080 runData->dig_time_complete = 10000000.0;
4082 runData->dig_time_complete = params.time;
4084 if (m_cache_enable_particles) {
4085 const ContentFeatures &features =
4086 client->getNodeDefManager()->get(n);
4087 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
4088 player, nodepos, features.tiles);
4092 if (runData->dig_time_complete >= 0.001) {
4093 runData->dig_index = (float)crack_animation_length
4095 / runData->dig_time_complete;
4097 // This is for torches
4098 runData->dig_index = crack_animation_length;
4101 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
4103 if (sound_dig.exists() && params.diggable) {
4104 if (sound_dig.name == "__group") {
4105 if (params.main_group != "") {
4106 soundmaker->m_player_leftpunch_sound.gain = 0.5;
4107 soundmaker->m_player_leftpunch_sound.name =
4108 std::string("default_dig_") +
4112 soundmaker->m_player_leftpunch_sound = sound_dig;
4116 // Don't show cracks if not diggable
4117 if (runData->dig_time_complete >= 100000.0) {
4118 } else if (runData->dig_index < crack_animation_length) {
4119 //TimeTaker timer("client.setTempMod");
4120 //infostream<<"dig_index="<<dig_index<<std::endl;
4121 client->setCrack(runData->dig_index, nodepos);
4123 infostream << "Digging completed" << std::endl;
4124 client->interact(2, pointed);
4125 client->setCrack(-1, v3s16(0, 0, 0));
4126 bool is_valid_position;
4127 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4128 if (is_valid_position)
4129 client->removeNode(nodepos);
4131 if (m_cache_enable_particles) {
4132 const ContentFeatures &features =
4133 client->getNodeDefManager()->get(wasnode);
4134 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
4135 player, nodepos, features.tiles);
4138 runData->dig_time = 0;
4139 runData->digging = false;
4141 runData->nodig_delay_timer =
4142 runData->dig_time_complete / (float)crack_animation_length;
4144 // We don't want a corresponding delay to
4145 // very time consuming nodes
4146 if (runData->nodig_delay_timer > 0.3)
4147 runData->nodig_delay_timer = 0.3;
4149 // We want a slight delay to very little
4150 // time consuming nodes
4151 const float mindelay = 0.15;
4153 if (runData->nodig_delay_timer < mindelay)
4154 runData->nodig_delay_timer = mindelay;
4156 // Send event to trigger sound
4157 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4158 gamedef->event()->put(e);
4161 if (runData->dig_time_complete < 100000.0) {
4162 runData->dig_time += dtime;
4164 runData->dig_time = 0;
4165 client->setCrack(-1, nodepos);
4168 camera->setDigging(0); // left click animation
4172 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4173 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4174 const CameraOrientation &cam)
4176 LocalPlayer *player = client->getEnv().getLocalPlayer();
4182 if (draw_control->range_all) {
4183 runData->fog_range = 100000 * BS;
4185 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
4189 Calculate general brightness
4191 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4192 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4193 float direct_brightness;
4196 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4197 direct_brightness = time_brightness;
4198 sunlight_seen = true;
4200 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4201 float old_brightness = sky->getBrightness();
4202 direct_brightness = client->getEnv().getClientMap()
4203 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4204 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4208 float time_of_day = runData->time_of_day;
4209 float time_of_day_smooth = runData->time_of_day_smooth;
4211 time_of_day = client->getEnv().getTimeOfDayF();
4213 const float maxsm = 0.05;
4214 const float todsm = 0.05;
4216 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4217 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4218 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4219 time_of_day_smooth = time_of_day;
4221 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4222 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4223 + (time_of_day + 1.0) * todsm;
4225 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4226 + time_of_day * todsm;
4228 runData->time_of_day = time_of_day;
4229 runData->time_of_day_smooth = time_of_day_smooth;
4231 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4232 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4233 player->getPitch());
4239 v3f player_position = player->getPosition();
4240 if (sky->getCloudsVisible()) {
4241 clouds->setVisible(true);
4242 clouds->step(dtime);
4243 clouds->update(v2f(player_position.X, player_position.Z),
4244 sky->getCloudColor());
4246 clouds->setVisible(false);
4253 client->getParticleManager()->step(dtime);
4259 if (m_cache_enable_fog && !flags.force_fog_off) {
4262 video::EFT_FOG_LINEAR,
4263 runData->fog_range * 0.4,
4264 runData->fog_range * 1.0,
4272 video::EFT_FOG_LINEAR,
4282 Get chat messages from client
4285 v2u32 screensize = driver->getScreenSize();
4287 updateChat(*client, dtime, flags.show_debug, screensize,
4288 flags.show_chat, runData->profiler_current_page,
4289 *chat_backend, guitext_chat);
4295 if (client->getPlayerItem() != runData->new_playeritem)
4296 client->selectPlayerItem(runData->new_playeritem);
4298 // Update local inventory if it has changed
4299 if (client->getLocalInventoryUpdated()) {
4300 //infostream<<"Updating local inventory"<<std::endl;
4301 client->getLocalInventory(*local_inventory);
4302 runData->update_wielded_item_trigger = true;
4305 if (runData->update_wielded_item_trigger) {
4306 // Update wielded tool
4307 InventoryList *mlist = local_inventory->getList("main");
4309 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4310 ItemStack item = mlist->getItem(client->getPlayerItem());
4311 camera->wield(item);
4313 runData->update_wielded_item_trigger = false;
4317 Update block draw list every 200ms or when camera direction has
4320 runData->update_draw_list_timer += dtime;
4322 v3f camera_direction = camera->getDirection();
4323 if (runData->update_draw_list_timer >= 0.2
4324 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4325 || flags.camera_offset_changed) {
4326 runData->update_draw_list_timer = 0;
4327 client->getEnv().getClientMap().updateDrawList(driver);
4328 runData->update_draw_list_last_cam_dir = camera_direction;
4331 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4334 make sure menu is on top
4335 1. Delete formspec menu reference if menu was removed
4336 2. Else, make sure formspec menu is on top
4338 if (current_formspec) {
4339 if (current_formspec->getReferenceCount() == 1) {
4340 current_formspec->drop();
4341 current_formspec = NULL;
4342 } else if (!noMenuActive()) {
4343 guiroot->bringToFront(current_formspec);
4351 video::SColor skycolor = sky->getSkyColor();
4353 TimeTaker tt_draw("mainloop: draw");
4355 TimeTaker timer("beginScene");
4356 driver->beginScene(true, true, skycolor);
4357 stats->beginscenetime = timer.stop(true);
4360 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4361 guienv, screensize, skycolor, flags.show_hud,
4362 flags.show_minimap);
4367 if (flags.show_profiler_graph)
4368 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4373 if (runData->damage_flash > 0.0) {
4374 video::SColor color(runData->damage_flash, 180, 0, 0);
4375 driver->draw2DRectangle(color,
4376 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4379 runData->damage_flash -= 100.0 * dtime;
4385 if (player->hurt_tilt_timer > 0.0) {
4386 player->hurt_tilt_timer -= dtime * 5;
4388 if (player->hurt_tilt_timer < 0)
4389 player->hurt_tilt_strength = 0;
4393 Update minimap pos and rotation
4395 if (flags.show_minimap && flags.show_hud) {
4396 mapper->setPos(floatToInt(player->getPosition(), BS));
4397 mapper->setAngle(player->getYaw());
4404 TimeTaker timer("endScene");
4406 stats->endscenetime = timer.stop(true);
4409 stats->drawtime = tt_draw.stop(true);
4410 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4414 inline static const char *yawToDirectionString(int yaw)
4416 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4418 yaw = wrapDegrees_0_360(yaw);
4419 yaw = (yaw + 45) % 360 / 90;
4421 return direction[yaw];
4425 void Game::updateGui(float *statustext_time, const RunStats &stats,
4426 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4427 const CameraOrientation &cam)
4429 v2u32 screensize = driver->getScreenSize();
4430 LocalPlayer *player = client->getEnv().getLocalPlayer();
4431 v3f player_position = player->getPosition();
4433 if (flags.show_debug) {
4434 static float drawtime_avg = 0;
4435 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4437 u16 fps = 1.0 / stats.dtime_jitter.avg;
4438 //s32 fps = driver->getFPS();
4440 std::ostringstream os(std::ios_base::binary);
4442 << PROJECT_NAME_C " " << g_version_hash
4444 << " (R: range_all=" << draw_control->range_all << ")"
4445 << std::setprecision(0)
4446 << " drawtime = " << drawtime_avg
4447 << std::setprecision(1)
4448 << ", dtime_jitter = "
4449 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4450 << std::setprecision(1)
4451 << ", v_range = " << draw_control->wanted_range
4452 << std::setprecision(3)
4453 << ", RTT = " << client->getRTT();
4454 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4455 guitext->setVisible(true);
4457 guitext->setVisible(false);
4460 if (guitext->isVisible()) {
4461 core::rect<s32> rect(
4463 screensize.X, 5 + g_fontengine->getTextHeight()
4465 guitext->setRelativePosition(rect);
4468 if (flags.show_debug) {
4469 std::ostringstream os(std::ios_base::binary);
4470 os << std::setprecision(1) << std::fixed
4471 << "(" << (player_position.X / BS)
4472 << ", " << (player_position.Y / BS)
4473 << ", " << (player_position.Z / BS)
4474 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4475 << " " << yawToDirectionString(cam.camera_yaw)
4476 << ") (seed = " << ((u64)client->getMapSeed())
4479 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4480 ClientMap &map = client->getEnv().getClientMap();
4481 const INodeDefManager *nodedef = client->getNodeDefManager();
4482 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4483 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4484 const ContentFeatures &features = nodedef->get(n);
4485 os << " (pointing_at = " << nodedef->get(n).name
4486 << " - " << features.tiledef[0].name.c_str()
4491 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4492 guitext2->setVisible(true);
4494 core::rect<s32> rect(
4495 5, 5 + g_fontengine->getTextHeight(),
4496 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4498 guitext2->setRelativePosition(rect);
4500 guitext2->setVisible(false);
4503 setStaticText(guitext_info, infotext.c_str());
4504 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4506 float statustext_time_max = 1.5;
4508 if (!statustext.empty()) {
4509 *statustext_time += dtime;
4511 if (*statustext_time >= statustext_time_max) {
4513 *statustext_time = 0;
4517 setStaticText(guitext_status, statustext.c_str());
4518 guitext_status->setVisible(!statustext.empty());
4520 if (!statustext.empty()) {
4521 s32 status_width = guitext_status->getTextWidth();
4522 s32 status_height = guitext_status->getTextHeight();
4523 s32 status_y = screensize.Y - 150;
4524 s32 status_x = (screensize.X - status_width) / 2;
4525 core::rect<s32> rect(
4526 status_x , status_y - status_height,
4527 status_x + status_width, status_y
4529 guitext_status->setRelativePosition(rect);
4532 video::SColor initial_color(255, 0, 0, 0);
4534 if (guienv->getSkin())
4535 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4537 video::SColor final_color = initial_color;
4538 final_color.setAlpha(0);
4539 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4540 initial_color, final_color,
4541 pow(*statustext_time / statustext_time_max, 2.0f));
4542 guitext_status->setOverrideColor(fade_color);
4543 guitext_status->enableOverrideColor(true);
4548 /* Log times and stuff for visualization */
4549 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4551 Profiler::GraphValues values;
4552 g_profiler->graphGet(values);
4558 /****************************************************************************
4560 ****************************************************************************/
4562 /* On some computers framerate doesn't seem to be automatically limited
4564 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4566 // not using getRealTime is necessary for wine
4567 device->getTimer()->tick(); // Maker sure device time is up-to-date
4568 u32 time = device->getTimer()->getTime();
4569 u32 last_time = fps_timings->last_time;
4571 if (time > last_time) // Make sure time hasn't overflowed
4572 fps_timings->busy_time = time - last_time;
4574 fps_timings->busy_time = 0;
4576 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4577 ? g_settings->getFloat("pause_fps_max")
4578 : g_settings->getFloat("fps_max"));
4580 if (fps_timings->busy_time < frametime_min) {
4581 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4582 device->sleep(fps_timings->sleep_time);
4584 fps_timings->sleep_time = 0;
4587 /* Get the new value of the device timer. Note that device->sleep() may
4588 * not sleep for the entire requested time as sleep may be interrupted and
4589 * therefore it is arguably more accurate to get the new time from the
4590 * device rather than calculating it by adding sleep_time to time.
4593 device->getTimer()->tick(); // Update device timer
4594 time = device->getTimer()->getTime();
4596 if (time > last_time) // Make sure last_time hasn't overflowed
4597 *dtime = (time - last_time) / 1000.0;
4601 fps_timings->last_time = time;
4604 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4605 // pass a copy of it to this function
4606 // Note: \p msg must be allocated using new (not malloc())
4607 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4608 int percent, bool draw_clouds)
4610 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4614 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4616 ((Game *)data)->readSettings();
4619 void Game::readSettings()
4621 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4622 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4623 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4624 m_cache_enable_particles = g_settings->getBool("enable_particles");
4625 m_cache_enable_fog = g_settings->getBool("enable_fog");
4626 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4627 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4628 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4630 m_cache_enable_noclip = g_settings->getBool("noclip");
4631 m_cache_enable_free_move = g_settings->getBool("free_move");
4633 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4636 /****************************************************************************/
4637 /****************************************************************************
4639 ****************************************************************************/
4640 /****************************************************************************/
4642 void Game::extendedResourceCleanup()
4644 // Extended resource accounting
4645 infostream << "Irrlicht resources after cleanup:" << std::endl;
4646 infostream << "\tRemaining meshes : "
4647 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4648 infostream << "\tRemaining textures : "
4649 << driver->getTextureCount() << std::endl;
4651 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4652 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4653 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4657 clearTextureNameCache();
4658 infostream << "\tRemaining materials: "
4659 << driver-> getMaterialRendererCount()
4660 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4664 /****************************************************************************/
4665 /****************************************************************************
4666 extern function for launching the game
4667 ****************************************************************************/
4668 /****************************************************************************/
4670 void the_game(bool *kill,
4672 InputHandler *input,
4673 IrrlichtDevice *device,
4675 const std::string &map_dir,
4676 const std::string &playername,
4677 const std::string &password,
4678 const std::string &address, // If empty local server is created
4681 std::string &error_message,
4682 ChatBackend &chat_backend,
4683 bool *reconnect_requested,
4684 const SubgameSpec &gamespec, // Used for local game
4685 bool simple_singleplayer_mode)
4689 /* Make a copy of the server address because if a local singleplayer server
4690 * is created then this is updated and we don't want to change the value
4691 * passed to us by the calling function
4693 std::string server_address = address;
4697 if (game.startup(kill, random_input, input, device, map_dir,
4698 playername, password, &server_address, port, error_message,
4699 reconnect_requested, &chat_backend, gamespec,
4700 simple_singleplayer_mode)) {
4705 } catch (SerializationError &e) {
4706 error_message = std::string("A serialization error occurred:\n")
4707 + e.what() + "\n\nThe server is probably "
4708 " running a different version of " PROJECT_NAME_C ".";
4709 errorstream << error_message << std::endl;
4710 } catch (ServerError &e) {
4711 error_message = e.what();
4712 errorstream << "ServerError: " << error_message << std::endl;
4713 } catch (ModError &e) {
4714 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4715 errorstream << "ModError: " << error_message << std::endl;