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 result.type = POINTEDTHING_OBJECT;
366 result.object_id = selected_object->getId();
370 // That didn't work, try to find a pointed at node
372 v3s16 pos_i = floatToInt(player_position, BS);
374 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
378 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
379 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
380 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
381 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
382 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
383 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
385 // Prevent signed number overflow
395 v3s16 pointed_pos(0, 0, 0);
397 for (s16 y = ystart; y <= yend; y++) {
398 for (s16 z = zstart; z <= zend; z++) {
399 for (s16 x = xstart; x <= xend; x++) {
401 bool is_valid_position;
404 n = map.getNodeNoEx(p, &is_valid_position);
405 if (!is_valid_position) {
408 if (!isPointableNode(n, client, liquids_pointable)) {
412 std::vector<aabb3f> boxes;
413 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n));
416 v3f npf = intToFloat(np, BS);
417 for (std::vector<aabb3f>::const_iterator
419 i != boxes.end(); ++i) {
424 v3f centerpoint = box.getCenter();
425 f32 distance = (centerpoint - camera_position).getLength();
426 if (distance >= min_distance) {
429 if (!box.intersectsWithLine(shootline)) {
432 result.type = POINTEDTHING_NODE;
433 min_distance = distance;
440 if (result.type == POINTEDTHING_NODE) {
442 MapNode n = map.getNodeNoEx(pointed_pos);
443 v3f npf = intToFloat(pointed_pos, BS);
444 std::vector<aabb3f> boxes;
445 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n));
446 f32 face_min_distance = 1000 * BS;
447 for (std::vector<aabb3f>::const_iterator
449 i != boxes.end(); ++i) {
453 for (u16 j = 0; j < 6; j++) {
454 v3s16 facedir = g_6dirs[j];
455 aabb3f facebox = box;
457 facebox.MinEdge.X = facebox.MaxEdge.X - d;
458 } else if (facedir.X < 0) {
459 facebox.MaxEdge.X = facebox.MinEdge.X + d;
460 } else if (facedir.Y > 0) {
461 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
462 } else if (facedir.Y < 0) {
463 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
464 } else if (facedir.Z > 0) {
465 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
466 } else if (facedir.Z < 0) {
467 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
469 v3f centerpoint = facebox.getCenter();
470 f32 distance = (centerpoint - camera_position).getLength();
471 if (distance >= face_min_distance)
473 if (!facebox.intersectsWithLine(shootline))
475 result.node_abovesurface = pointed_pos + facedir;
476 face_min_distance = distance;
479 selectionboxes->clear();
480 for (std::vector<aabb3f>::const_iterator
482 i != boxes.end(); ++i) {
484 box.MinEdge += v3f(-d, -d, -d);
485 box.MaxEdge += v3f(d, d, d);
486 selectionboxes->push_back(box);
488 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
489 result.node_undersurface = pointed_pos;
492 // Update selection mesh light level and vertex colors
493 if (selectionboxes->size() > 0) {
494 v3f pf = hud->getSelectionPos();
495 v3s16 p = floatToInt(pf, BS);
497 // Get selection mesh light level
498 MapNode n = map.getNodeNoEx(p);
499 u16 node_light = getInteriorLight(n, -1, nodedef);
500 u16 light_level = node_light;
502 for (u8 i = 0; i < 6; i++) {
503 n = map.getNodeNoEx(p + g_6dirs[i]);
504 node_light = getInteriorLight(n, -1, nodedef);
505 if (node_light > light_level)
506 light_level = node_light;
509 video::SColor c = MapBlock_LightColor(255, light_level, 0);
511 u8 night = c.getGreen();
512 u32 daynight_ratio = client->getEnv().getDayNightRatio();
513 finalColorBlend(c, day, night, daynight_ratio);
515 // Modify final color a bit with time
516 u32 timer = porting::getTimeMs() % 5000;
517 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
518 float sin_r = 0.08 * sin(timerf);
519 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
520 float sin_b = 0.08 * sin(timerf + irr::core::PI);
521 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
522 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
523 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
525 // Set mesh final color
526 hud->setSelectionMeshColor(c);
531 /* Profiler display */
533 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
534 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
536 if (show_profiler == 0) {
537 guitext_profiler->setVisible(false);
540 std::ostringstream os(std::ios_base::binary);
541 g_profiler->printPage(os, show_profiler, show_profiler_max);
542 std::wstring text = utf8_to_wide(os.str());
543 setStaticText(guitext_profiler, text.c_str());
544 guitext_profiler->setVisible(true);
546 s32 w = fe->getTextWidth(text.c_str());
551 unsigned text_height = fe->getTextHeight();
553 core::position2di upper_left, lower_right;
556 upper_left.Y = (text_height + 5) * 2;
557 lower_right.X = 12 + w;
558 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
560 if (lower_right.Y > screen_height * 2 / 3)
561 lower_right.Y = screen_height * 2 / 3;
563 core::rect<s32> rect(upper_left, lower_right);
565 guitext_profiler->setRelativePosition(rect);
566 guitext_profiler->setVisible(true);
574 Profiler::GraphValues values;
580 Meta(float initial = 0,
581 video::SColor color = video::SColor(255, 255, 255, 255)):
587 std::deque<Piece> m_log;
595 void put(const Profiler::GraphValues &values)
598 piece.values = values;
599 m_log.push_back(piece);
601 while (m_log.size() > m_log_max_size)
602 m_log.erase(m_log.begin());
605 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
606 gui::IGUIFont *font) const
608 UNORDERED_MAP<std::string, Meta> m_meta;
610 for (std::deque<Piece>::const_iterator k = m_log.begin();
611 k != m_log.end(); ++k) {
612 const Piece &piece = *k;
614 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
615 i != piece.values.end(); ++i) {
616 const std::string &id = i->first;
617 const float &value = i->second;
618 UNORDERED_MAP<std::string, Meta>::iterator j = m_meta.find(id);
620 if (j == m_meta.end()) {
621 m_meta[id] = Meta(value);
625 if (value < j->second.min)
626 j->second.min = value;
628 if (value > j->second.max)
629 j->second.max = value;
634 static const video::SColor usable_colors[] = {
635 video::SColor(255, 255, 100, 100),
636 video::SColor(255, 90, 225, 90),
637 video::SColor(255, 100, 100, 255),
638 video::SColor(255, 255, 150, 50),
639 video::SColor(255, 220, 220, 100)
641 static const u32 usable_colors_count =
642 sizeof(usable_colors) / sizeof(*usable_colors);
643 u32 next_color_i = 0;
645 for (UNORDERED_MAP<std::string, Meta>::iterator i = m_meta.begin();
646 i != m_meta.end(); ++i) {
647 Meta &meta = i->second;
648 video::SColor color(255, 200, 200, 200);
650 if (next_color_i < usable_colors_count)
651 color = usable_colors[next_color_i++];
657 s32 textx = x_left + m_log_max_size + 15;
658 s32 textx2 = textx + 200 - 15;
661 for (UNORDERED_MAP<std::string, Meta>::const_iterator i = m_meta.begin();
662 i != m_meta.end(); ++i) {
663 const std::string &id = i->first;
664 const Meta &meta = i->second;
666 s32 y = y_bottom - meta_i * 50;
667 float show_min = meta.min;
668 float show_max = meta.max;
670 if (show_min >= -0.0001 && show_max >= -0.0001) {
671 if (show_min <= show_max * 0.5)
677 snprintf(buf, 10, "%.3g", show_max);
678 font->draw(utf8_to_wide(buf).c_str(),
679 core::rect<s32>(textx, y - graphh,
680 textx2, y - graphh + texth),
682 snprintf(buf, 10, "%.3g", show_min);
683 font->draw(utf8_to_wide(buf).c_str(),
684 core::rect<s32>(textx, y - texth,
687 font->draw(utf8_to_wide(id).c_str(),
688 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
689 textx2, y - graphh / 2 + texth / 2),
692 s32 graph1h = graphh;
693 bool relativegraph = (show_min != 0 && show_min != show_max);
694 float lastscaledvalue = 0.0;
695 bool lastscaledvalue_exists = false;
697 for (std::deque<Piece>::const_iterator j = m_log.begin();
698 j != m_log.end(); ++j) {
699 const Piece &piece = *j;
701 bool value_exists = false;
702 Profiler::GraphValues::const_iterator k =
703 piece.values.find(id);
705 if (k != piece.values.end()) {
712 lastscaledvalue_exists = false;
716 float scaledvalue = 1.0;
718 if (show_max != show_min)
719 scaledvalue = (value - show_min) / (show_max - show_min);
721 if (scaledvalue == 1.0 && value == 0) {
723 lastscaledvalue_exists = false;
728 if (lastscaledvalue_exists) {
729 s32 ivalue1 = lastscaledvalue * graph1h;
730 s32 ivalue2 = scaledvalue * graph1h;
731 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
732 v2s32(x, graph1y - ivalue2), meta.color);
735 lastscaledvalue = scaledvalue;
736 lastscaledvalue_exists = true;
738 s32 ivalue = scaledvalue * graph1h;
739 driver->draw2DLine(v2s32(x, graph1y),
740 v2s32(x, graph1y - ivalue), meta.color);
751 class NodeDugEvent: public MtEvent
757 NodeDugEvent(v3s16 p, MapNode n):
761 const char *getType() const
769 ISoundManager *m_sound;
770 INodeDefManager *m_ndef;
772 float m_player_step_timer;
774 SimpleSoundSpec m_player_step_sound;
775 SimpleSoundSpec m_player_leftpunch_sound;
776 SimpleSoundSpec m_player_rightpunch_sound;
778 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
781 m_player_step_timer(0)
785 void playPlayerStep()
787 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
788 m_player_step_timer = 0.03;
789 m_sound->playSound(m_player_step_sound, false);
793 static void viewBobbingStep(MtEvent *e, void *data)
795 SoundMaker *sm = (SoundMaker *)data;
796 sm->playPlayerStep();
799 static void playerRegainGround(MtEvent *e, void *data)
801 SoundMaker *sm = (SoundMaker *)data;
802 sm->playPlayerStep();
805 static void playerJump(MtEvent *e, void *data)
807 //SoundMaker *sm = (SoundMaker*)data;
810 static void cameraPunchLeft(MtEvent *e, void *data)
812 SoundMaker *sm = (SoundMaker *)data;
813 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
816 static void cameraPunchRight(MtEvent *e, void *data)
818 SoundMaker *sm = (SoundMaker *)data;
819 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
822 static void nodeDug(MtEvent *e, void *data)
824 SoundMaker *sm = (SoundMaker *)data;
825 NodeDugEvent *nde = (NodeDugEvent *)e;
826 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
829 static void playerDamage(MtEvent *e, void *data)
831 SoundMaker *sm = (SoundMaker *)data;
832 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
835 static void playerFallingDamage(MtEvent *e, void *data)
837 SoundMaker *sm = (SoundMaker *)data;
838 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
841 void registerReceiver(MtEventManager *mgr)
843 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
844 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
845 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
846 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
847 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
848 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
849 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
850 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
853 void step(float dtime)
855 m_player_step_timer -= dtime;
859 // Locally stored sounds don't need to be preloaded because of this
860 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
862 std::set<std::string> m_fetched;
864 void fetchSounds(const std::string &name,
865 std::set<std::string> &dst_paths,
866 std::set<std::string> &dst_datas)
868 if (m_fetched.count(name))
871 m_fetched.insert(name);
872 std::string base = porting::path_share + DIR_DELIM + "testsounds";
873 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
874 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
875 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
876 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
877 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
878 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
879 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
880 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
881 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
882 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
883 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
887 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
890 bool *m_force_fog_off;
896 void onSettingsChange(const std::string &name)
898 if (name == "enable_fog")
899 m_fogEnabled = g_settings->getBool("enable_fog");
902 static void SettingsCallback(const std::string &name, void *userdata)
904 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
907 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
908 f32 *fog_range, Client *client) :
910 m_force_fog_off(force_fog_off),
911 m_fog_range(fog_range),
914 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
915 m_fogEnabled = g_settings->getBool("enable_fog");
918 ~GameGlobalShaderConstantSetter()
920 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
923 virtual void onSetConstants(video::IMaterialRendererServices *services,
930 video::SColor bgcolor = m_sky->getBgColor();
931 video::SColorf bgcolorf(bgcolor);
932 float bgcolorfa[4] = {
938 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
941 float fog_distance = 10000 * BS;
943 if (m_fogEnabled && !*m_force_fog_off)
944 fog_distance = *m_fog_range;
946 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
949 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
950 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
951 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
953 u32 animation_timer = porting::getTimeMs() % 100000;
954 float animation_timer_f = (float)animation_timer / 100000.0;
955 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
956 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
958 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
959 v3f eye_position = player->getEyePosition();
960 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
961 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
963 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
964 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
966 // Uniform sampler layers
967 // before 1.8 there isn't a "integer interface", only float
968 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
972 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
973 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
974 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
979 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
980 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
981 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
986 bool nodePlacementPrediction(Client &client,
987 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
989 std::string prediction = playeritem_def.node_placement_prediction;
990 INodeDefManager *nodedef = client.ndef();
991 ClientMap &map = client.getEnv().getClientMap();
993 bool is_valid_position;
995 node = map.getNodeNoEx(nodepos, &is_valid_position);
996 if (!is_valid_position)
999 if (prediction != "" && !nodedef->get(node).rightclickable) {
1000 verbosestream << "Node placement prediction for "
1001 << playeritem_def.name << " is "
1002 << prediction << std::endl;
1003 v3s16 p = neighbourpos;
1005 // Place inside node itself if buildable_to
1006 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
1007 if (is_valid_position)
1009 if (nodedef->get(n_under).buildable_to)
1012 node = map.getNodeNoEx(p, &is_valid_position);
1013 if (is_valid_position &&!nodedef->get(node).buildable_to)
1018 // Find id of predicted node
1020 bool found = nodedef->getId(prediction, id);
1023 errorstream << "Node placement prediction failed for "
1024 << playeritem_def.name << " (places "
1026 << ") - Name not known" << std::endl;
1030 // Predict param2 for facedir and wallmounted nodes
1033 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
1034 v3s16 dir = nodepos - neighbourpos;
1036 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
1037 param2 = dir.Y < 0 ? 1 : 0;
1038 } else if (abs(dir.X) > abs(dir.Z)) {
1039 param2 = dir.X < 0 ? 3 : 2;
1041 param2 = dir.Z < 0 ? 5 : 4;
1045 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
1046 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
1048 if (abs(dir.X) > abs(dir.Z)) {
1049 param2 = dir.X < 0 ? 3 : 1;
1051 param2 = dir.Z < 0 ? 2 : 0;
1055 assert(param2 <= 5);
1057 //Check attachment if node is in group attached_node
1058 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1059 static v3s16 wallmounted_dirs[8] = {
1069 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1070 pp = p + wallmounted_dirs[param2];
1072 pp = p + v3s16(0, -1, 0);
1074 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1078 // Add node to client map
1079 MapNode n(id, 0, param2);
1082 LocalPlayer *player = client.getEnv().getLocalPlayer();
1084 // Dont place node when player would be inside new node
1085 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1086 if (!nodedef->get(n).walkable ||
1087 g_settings->getBool("enable_build_where_you_stand") ||
1088 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1089 (nodedef->get(n).walkable &&
1090 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1091 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1093 // This triggers the required mesh update too
1094 client.addNode(p, n);
1097 } catch (InvalidPositionException &e) {
1098 errorstream << "Node placement prediction failed for "
1099 << playeritem_def.name << " (places "
1101 << ") - Position not loaded" << std::endl;
1108 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1109 InventoryManager *invmgr, IGameDef *gamedef,
1110 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1111 JoystickController *joystick,
1112 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1115 if (*cur_formspec == 0) {
1116 *cur_formspec = new GUIFormSpecMenu(device, joystick,
1117 guiroot, -1, &g_menumgr, invmgr, gamedef, tsrc,
1118 fs_src, txt_dest, client);
1119 (*cur_formspec)->doPause = false;
1122 Caution: do not call (*cur_formspec)->drop() here --
1123 the reference might outlive the menu, so we will
1124 periodically check if *cur_formspec is the only
1125 remaining reference (i.e. the menu was removed)
1126 and delete it in that case.
1130 (*cur_formspec)->setFormSource(fs_src);
1131 (*cur_formspec)->setTextDest(txt_dest);
1136 #define SIZE_TAG "size[11,5.5]"
1138 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1141 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1142 InventoryManager *invmgr, IGameDef *gamedef,
1143 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1144 JoystickController *joystick, Client *client)
1146 std::string formspec =
1147 std::string(FORMSPEC_VERSION_STRING) +
1149 "bgcolor[#320000b4;true]"
1150 "label[4.85,1.35;" + gettext("You died.") + "]"
1151 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1155 /* Note: FormspecFormSource and LocalFormspecHandler
1156 * are deleted by guiFormSpecMenu */
1157 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1158 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1160 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
1161 joystick, fs_src, txt_dst, NULL);
1164 /******************************************************************************/
1165 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1166 InventoryManager *invmgr, IGameDef *gamedef,
1167 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1168 JoystickController *joystick, bool singleplayermode)
1171 std::string control_text = strgettext("Default Controls:\n"
1172 "No menu visible:\n"
1173 "- single tap: button activate\n"
1174 "- double tap: place/use\n"
1175 "- slide finger: look around\n"
1176 "Menu/Inventory visible:\n"
1177 "- double tap (outside):\n"
1179 "- touch stack, touch slot:\n"
1181 "- touch&drag, tap 2nd finger\n"
1182 " --> place single item to slot\n"
1185 std::string control_text = strgettext("Default Controls:\n"
1187 "- Space: jump/climb\n"
1188 "- Shift: sneak/go down\n"
1191 "- Mouse: turn/look\n"
1192 "- Mouse left: dig/punch\n"
1193 "- Mouse right: place/use\n"
1194 "- Mouse wheel: select item\n"
1199 float ypos = singleplayermode ? 0.5 : 0.1;
1200 std::ostringstream os;
1202 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1203 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1204 << strgettext("Continue") << "]";
1206 if (!singleplayermode) {
1207 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1208 << strgettext("Change Password") << "]";
1212 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1213 << strgettext("Sound Volume") << "]";
1214 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1215 << strgettext("Change Keys") << "]";
1217 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1218 << strgettext("Exit to Menu") << "]";
1219 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1220 << strgettext("Exit to OS") << "]"
1221 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1222 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1223 << g_build_info << "\n"
1224 << "path_user = " << wrap_rows(porting::path_user, 20)
1228 /* Note: FormspecFormSource and LocalFormspecHandler *
1229 * are deleted by guiFormSpecMenu */
1230 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1231 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1233 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
1234 joystick, fs_src, txt_dst, NULL);
1235 std::string con("btn_continue");
1236 (*cur_formspec)->setFocus(con);
1237 (*cur_formspec)->doPause = true;
1240 /******************************************************************************/
1241 static void updateChat(Client &client, f32 dtime, bool show_debug,
1242 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1243 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1245 // Add chat log output for errors to be shown in chat
1246 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1248 // Get new messages from error log buffer
1249 while (!chat_log_error_buf.empty()) {
1250 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
1251 if (!g_settings->getBool("disable_escape_sequences")) {
1252 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
1254 chat_backend.addMessage(L"", error_message);
1257 // Get new messages from client
1258 std::wstring message;
1260 while (client.getChatMessage(message)) {
1261 chat_backend.addUnparsedMessage(message);
1264 // Remove old messages
1265 chat_backend.step(dtime);
1267 // Display all messages in a static text element
1268 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1269 EnrichedString recent_chat = chat_backend.getRecentChat();
1270 unsigned int line_height = g_fontengine->getLineHeight();
1272 setStaticText(guitext_chat, recent_chat);
1274 // Update gui element size and position
1278 chat_y += 2 * line_height;
1280 // first pass to calculate height of text to be set
1281 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1282 porting::getWindowSize().X - 20);
1283 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1284 guitext_chat->setRelativePosition(rect);
1286 //now use real height of text and adjust rect according to this size
1287 rect = core::rect<s32>(10, chat_y, width,
1288 chat_y + guitext_chat->getTextHeight());
1291 guitext_chat->setRelativePosition(rect);
1292 // Don't show chat if disabled or empty or profiler is enabled
1293 guitext_chat->setVisible(
1294 show_chat && recent_chat_count != 0 && !show_profiler);
1298 /****************************************************************************
1299 Fast key cache for main game loop
1300 ****************************************************************************/
1302 /* This is faster than using getKeySetting with the tradeoff that functions
1303 * using it must make sure that it's initialised before using it and there is
1304 * no error handling (for example bounds checking). This is really intended for
1305 * use only in the main running loop of the client (the_game()) where the faster
1306 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1307 * (e.g. formspecs) should continue using getKeySetting().
1315 populate_nonchanging();
1320 // Keys that are not settings dependent
1321 void populate_nonchanging();
1323 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1324 InputHandler *handler;
1327 void KeyCache::populate_nonchanging()
1329 key[KeyType::ESC] = EscapeKey;
1332 void KeyCache::populate()
1334 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1335 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1336 key[KeyType::LEFT] = getKeySetting("keymap_left");
1337 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1338 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1339 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1340 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1342 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1344 key[KeyType::DROP] = getKeySetting("keymap_drop");
1345 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1346 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1347 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1348 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1349 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1350 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1351 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1352 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1353 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1354 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1355 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1356 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1357 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1358 = getKeySetting("keymap_toggle_force_fog_off");
1359 key[KeyType::TOGGLE_UPDATE_CAMERA]
1360 = getKeySetting("keymap_toggle_update_camera");
1361 key[KeyType::TOGGLE_DEBUG]
1362 = getKeySetting("keymap_toggle_debug");
1363 key[KeyType::TOGGLE_PROFILER]
1364 = getKeySetting("keymap_toggle_profiler");
1365 key[KeyType::CAMERA_MODE]
1366 = getKeySetting("keymap_camera_mode");
1367 key[KeyType::INCREASE_VIEWING_RANGE]
1368 = getKeySetting("keymap_increase_viewing_range_min");
1369 key[KeyType::DECREASE_VIEWING_RANGE]
1370 = getKeySetting("keymap_decrease_viewing_range_min");
1371 key[KeyType::RANGESELECT]
1372 = getKeySetting("keymap_rangeselect");
1373 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1375 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1376 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1377 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1378 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1380 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1383 // First clear all keys, then re-add the ones we listen for
1384 handler->dontListenForKeys();
1385 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1386 handler->listenForKey(key[i]);
1388 handler->listenForKey(EscapeKey);
1389 handler->listenForKey(CancelKey);
1390 for (size_t i = 0; i < 10; i++) {
1391 handler->listenForKey(NumberKey[i]);
1397 /****************************************************************************
1399 ****************************************************************************/
1401 const float object_hit_delay = 0.2;
1404 u32 last_time, busy_time, sleep_time;
1408 /* The reason the following structs are not anonymous structs within the
1409 * class is that they are not used by the majority of member functions and
1410 * many functions that do require objects of thse types do not modify them
1411 * (so they can be passed as a const qualified parameter)
1413 struct CameraOrientation {
1414 f32 camera_yaw; // "right/left"
1415 f32 camera_pitch; // "up/down"
1418 struct GameRunData {
1421 PointedThing pointed_old;
1425 bool update_wielded_item_trigger;
1426 bool reset_jump_timer;
1427 float nodig_delay_timer;
1429 float dig_time_complete;
1430 float repeat_rightclick_timer;
1431 float object_hit_delay_timer;
1432 float time_from_last_punch;
1433 ClientActiveObject *selected_object;
1437 float update_draw_list_timer;
1438 float statustext_time;
1442 v3f update_draw_list_last_cam_dir;
1444 u32 profiler_current_page;
1445 u32 profiler_max_page; // Number of pages
1448 float time_of_day_smooth;
1452 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1460 Jitter dtime_jitter, busy_time_jitter;
1463 /* Flags that can, or may, change during main game loop
1465 struct VolatileRunFlags {
1472 bool show_profiler_graph;
1473 bool disable_camera_update;
1474 bool first_loop_after_window_activation;
1475 bool camera_offset_changed;
1479 /****************************************************************************
1481 ****************************************************************************/
1483 /* This is not intended to be a public class. If a public class becomes
1484 * desirable then it may be better to create another 'wrapper' class that
1485 * hides most of the stuff in this class (nothing in this class is required
1486 * by any other file) but exposes the public methods/data only.
1493 bool startup(bool *kill,
1495 InputHandler *input,
1496 IrrlichtDevice *device,
1497 const std::string &map_dir,
1498 const std::string &playername,
1499 const std::string &password,
1500 // If address is "", local server is used and address is updated
1501 std::string *address,
1503 std::string &error_message,
1505 ChatBackend *chat_backend,
1506 const SubgameSpec &gamespec, // Used for local game
1507 bool simple_singleplayer_mode);
1514 void extendedResourceCleanup();
1516 // Basic initialisation
1517 bool init(const std::string &map_dir, std::string *address,
1519 const SubgameSpec &gamespec);
1521 bool createSingleplayerServer(const std::string map_dir,
1522 const SubgameSpec &gamespec, u16 port, std::string *address);
1525 bool createClient(const std::string &playername,
1526 const std::string &password, std::string *address, u16 port);
1529 // Client connection
1530 bool connectToServer(const std::string &playername,
1531 const std::string &password, std::string *address, u16 port,
1532 bool *connect_ok, bool *aborted);
1533 bool getServerContent(bool *aborted);
1537 void updateInteractTimers(GameRunData *runData, f32 dtime);
1538 bool checkConnection();
1539 bool handleCallbacks();
1540 void processQueues();
1541 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1542 const FpsControl &draw_times, f32 dtime);
1543 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1545 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1548 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1550 void processKeyInput(VolatileRunFlags *flags,
1551 float *statustext_time,
1553 bool *reset_jump_timer,
1554 u32 *profiler_current_page,
1555 u32 profiler_max_page);
1556 void processItemSelection(u16 *new_playeritem);
1558 void dropSelectedItem();
1559 void openInventory();
1560 void openConsole(float height, const wchar_t *line=NULL);
1561 void toggleFreeMove(float *statustext_time);
1562 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1563 void toggleFast(float *statustext_time);
1564 void toggleNoClip(float *statustext_time);
1565 void toggleCinematic(float *statustext_time);
1566 void toggleAutorun(float *statustext_time);
1568 void toggleChat(float *statustext_time, bool *flag);
1569 void toggleHud(float *statustext_time, bool *flag);
1570 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1571 bool shift_pressed);
1572 void toggleFog(float *statustext_time, bool *flag);
1573 void toggleDebug(float *statustext_time, bool *show_debug,
1574 bool *show_profiler_graph);
1575 void toggleUpdateCamera(float *statustext_time, bool *flag);
1576 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1577 u32 profiler_max_page);
1579 void increaseViewRange(float *statustext_time);
1580 void decreaseViewRange(float *statustext_time);
1581 void toggleFullViewRange(float *statustext_time);
1583 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags,
1585 void updateCameraOrientation(CameraOrientation *cam,
1586 const VolatileRunFlags &flags, float dtime);
1587 void updatePlayerControl(const CameraOrientation &cam);
1588 void step(f32 *dtime);
1589 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1590 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1591 float time_from_last_punch);
1592 void updateSound(f32 dtime);
1593 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1595 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1596 void handlePointingAtNode(GameRunData *runData,
1597 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1598 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1599 void handlePointingAtObject(GameRunData *runData,
1600 const PointedThing &pointed, const ItemStack &playeritem,
1601 const v3f &player_position, bool show_debug);
1602 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1603 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1605 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1606 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1607 void updateGui(float *statustext_time, const RunStats &stats,
1608 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1609 const CameraOrientation &cam);
1610 void updateProfilerGraphs(ProfilerGraph *graph);
1613 void limitFps(FpsControl *fps_timings, f32 *dtime);
1615 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1616 bool draw_clouds = true);
1618 static void settingChangedCallback(const std::string &setting_name, void *data);
1619 void readSettings();
1621 inline bool getLeftClicked()
1623 return input->getLeftClicked() ||
1624 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1626 inline bool getRightClicked()
1628 return input->getRightClicked() ||
1629 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1631 inline bool isLeftPressed()
1633 return input->getLeftState() ||
1634 input->joystick.isKeyDown(KeyType::MOUSE_L);
1636 inline bool isRightPressed()
1638 return input->getRightState() ||
1639 input->joystick.isKeyDown(KeyType::MOUSE_R);
1641 inline bool getLeftReleased()
1643 return input->getLeftReleased() ||
1644 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1647 inline bool isKeyDown(GameKeyType k)
1649 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1651 inline bool wasKeyDown(GameKeyType k)
1653 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1657 void handleAndroidChatInput();
1661 InputHandler *input;
1666 IWritableTextureSource *texture_src;
1667 IWritableShaderSource *shader_src;
1669 // When created, these will be filled with data received from the server
1670 IWritableItemDefManager *itemdef_manager;
1671 IWritableNodeDefManager *nodedef_manager;
1673 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1674 ISoundManager *sound;
1675 bool sound_is_dummy;
1676 SoundMaker *soundmaker;
1678 ChatBackend *chat_backend;
1680 GUIFormSpecMenu *current_formspec;
1682 EventManager *eventmgr;
1683 QuicktuneShortcutter *quicktune;
1685 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1686 MapDrawControl *draw_control;
1688 Clouds *clouds; // Free using ->Drop()
1689 Sky *sky; // Free using ->Drop()
1690 Inventory *local_inventory;
1695 This class does take ownership/responsibily for cleaning up etc of any of
1696 these items (e.g. device)
1698 IrrlichtDevice *device;
1699 video::IVideoDriver *driver;
1700 scene::ISceneManager *smgr;
1702 std::string *error_message;
1703 bool *reconnect_requested;
1704 IGameDef *gamedef; // Convenience (same as *client)
1705 scene::ISceneNode *skybox;
1708 bool simple_singleplayer_mode;
1711 /* Pre-calculated values
1713 int crack_animation_length;
1717 gui::IGUIStaticText *guitext; // First line of debug text
1718 gui::IGUIStaticText *guitext2; // Second line of debug text
1719 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1720 gui::IGUIStaticText *guitext_status;
1721 gui::IGUIStaticText *guitext_chat; // Chat text
1722 gui::IGUIStaticText *guitext_profiler; // Profiler text
1724 std::wstring infotext;
1725 std::wstring statustext;
1729 IntervalLimiter profiler_interval;
1732 * TODO: Local caching of settings is not optimal and should at some stage
1733 * be updated to use a global settings object for getting thse values
1734 * (as opposed to the this local caching). This can be addressed in
1737 bool m_cache_doubletap_jump;
1738 bool m_cache_enable_clouds;
1739 bool m_cache_enable_joysticks;
1740 bool m_cache_enable_particles;
1741 bool m_cache_enable_fog;
1742 f32 m_cache_mouse_sensitivity;
1743 f32 m_cache_joystick_frustum_sensitivity;
1744 f32 m_repeat_right_click_time;
1747 bool m_cache_hold_aux1;
1748 bool m_android_chat_open;
1757 itemdef_manager(NULL),
1758 nodedef_manager(NULL),
1760 sound_is_dummy(false),
1763 current_formspec(NULL),
1766 gui_chat_console(NULL),
1771 local_inventory(NULL),
1775 g_settings->registerChangedCallback("doubletap_jump",
1776 &settingChangedCallback, this);
1777 g_settings->registerChangedCallback("enable_clouds",
1778 &settingChangedCallback, this);
1779 g_settings->registerChangedCallback("doubletap_joysticks",
1780 &settingChangedCallback, this);
1781 g_settings->registerChangedCallback("enable_particles",
1782 &settingChangedCallback, this);
1783 g_settings->registerChangedCallback("enable_fog",
1784 &settingChangedCallback, this);
1785 g_settings->registerChangedCallback("mouse_sensitivity",
1786 &settingChangedCallback, this);
1787 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1788 &settingChangedCallback, this);
1789 g_settings->registerChangedCallback("repeat_rightclick_time",
1790 &settingChangedCallback, this);
1795 m_cache_hold_aux1 = false; // This is initialised properly later
1802 /****************************************************************************
1804 ****************************************************************************/
1810 if (!sound_is_dummy)
1813 delete server; // deleted first to stop all server threads
1816 delete local_inventory;
1822 delete nodedef_manager;
1823 delete itemdef_manager;
1824 delete draw_control;
1826 extendedResourceCleanup();
1828 g_settings->deregisterChangedCallback("doubletap_jump",
1829 &settingChangedCallback, this);
1830 g_settings->deregisterChangedCallback("enable_clouds",
1831 &settingChangedCallback, this);
1832 g_settings->deregisterChangedCallback("enable_particles",
1833 &settingChangedCallback, this);
1834 g_settings->deregisterChangedCallback("enable_fog",
1835 &settingChangedCallback, this);
1836 g_settings->deregisterChangedCallback("mouse_sensitivity",
1837 &settingChangedCallback, this);
1838 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1839 &settingChangedCallback, this);
1842 bool Game::startup(bool *kill,
1844 InputHandler *input,
1845 IrrlichtDevice *device,
1846 const std::string &map_dir,
1847 const std::string &playername,
1848 const std::string &password,
1849 std::string *address, // can change if simple_singleplayer_mode
1851 std::string &error_message,
1853 ChatBackend *chat_backend,
1854 const SubgameSpec &gamespec,
1855 bool simple_singleplayer_mode)
1858 this->device = device;
1860 this->error_message = &error_message;
1861 this->reconnect_requested = reconnect;
1862 this->random_input = random_input;
1863 this->input = input;
1864 this->chat_backend = chat_backend;
1865 this->simple_singleplayer_mode = simple_singleplayer_mode;
1867 keycache.handler = input;
1868 keycache.populate();
1870 driver = device->getVideoDriver();
1871 smgr = device->getSceneManager();
1873 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1875 if (!init(map_dir, address, port, gamespec))
1878 if (!createClient(playername, password, address, port))
1887 ProfilerGraph graph;
1888 RunStats stats = { 0 };
1889 CameraOrientation cam_view_target = { 0 };
1890 CameraOrientation cam_view = { 0 };
1891 GameRunData runData = { 0 };
1892 FpsControl draw_times = { 0 };
1893 VolatileRunFlags flags = { 0 };
1894 f32 dtime; // in seconds
1896 runData.time_from_last_punch = 10.0;
1897 runData.profiler_max_page = 3;
1898 runData.update_wielded_item_trigger = true;
1900 flags.show_chat = true;
1901 flags.show_hud = true;
1902 flags.show_minimap = g_settings->getBool("enable_minimap");
1903 flags.show_debug = g_settings->getBool("show_debug");
1904 flags.invert_mouse = g_settings->getBool("invert_mouse");
1905 flags.first_loop_after_window_activation = true;
1907 /* Clear the profiler */
1908 Profiler::GraphValues dummyvalues;
1909 g_profiler->graphGet(dummyvalues);
1911 draw_times.last_time = device->getTimer()->getTime();
1913 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1915 &flags.force_fog_off,
1919 set_light_table(g_settings->getFloat("display_gamma"));
1922 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1923 && client->checkPrivilege("fast");
1926 while (device->run()
1927 && !(*kill || g_gamecallback->shutdown_requested
1928 || (server && server->getShutdownRequested()))) {
1930 /* Must be called immediately after a device->run() call because it
1931 * uses device->getTimer()->getTime()
1933 limitFps(&draw_times, &dtime);
1935 updateStats(&stats, draw_times, dtime);
1936 updateInteractTimers(&runData, dtime);
1938 if (!checkConnection())
1940 if (!handleCallbacks())
1946 hud->resizeHotbar();
1948 updateProfilers(runData, stats, draw_times, dtime);
1949 processUserInput(&flags, &runData, dtime);
1950 // Update camera before player movement to avoid camera lag of one frame
1951 updateCameraDirection(&cam_view_target, &flags, dtime);
1952 float cam_smoothing = 0;
1953 if (g_settings->getBool("cinematic"))
1954 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1956 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1957 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1958 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1959 cam_view.camera_yaw) * cam_smoothing;
1960 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1961 cam_view.camera_pitch) * cam_smoothing;
1962 updatePlayerControl(cam_view);
1964 processClientEvents(&cam_view_target, &runData.damage_flash);
1965 updateCamera(&flags, draw_times.busy_time, dtime,
1966 runData.time_from_last_punch);
1968 processPlayerInteraction(&runData, dtime, flags.show_hud,
1970 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1971 updateProfilerGraphs(&graph);
1973 // Update if minimap has been disabled by the server
1974 flags.show_minimap &= !client->isMinimapDisabledByServer();
1979 void Game::shutdown()
1981 if (g_settings->get("3d_mode") == "pageflip") {
1982 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1985 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1990 if (gui_chat_console)
1991 gui_chat_console->drop();
1997 while (g_menumgr.menuCount() > 0) {
1998 g_menumgr.m_stack.front()->setVisible(false);
1999 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
2002 if (current_formspec) {
2003 current_formspec->drop();
2004 current_formspec = NULL;
2007 chat_backend->addMessage(L"", L"# Disconnected.");
2008 chat_backend->addMessage(L"", L"");
2012 while (!client->isShutdown()) {
2013 assert(texture_src != NULL);
2014 assert(shader_src != NULL);
2015 texture_src->processQueue();
2016 shader_src->processQueue();
2023 /****************************************************************************/
2024 /****************************************************************************
2026 ****************************************************************************/
2027 /****************************************************************************/
2030 const std::string &map_dir,
2031 std::string *address,
2033 const SubgameSpec &gamespec)
2035 showOverlayMessage(wgettext("Loading..."), 0, 0);
2037 texture_src = createTextureSource(device);
2038 shader_src = createShaderSource(device);
2040 itemdef_manager = createItemDefManager();
2041 nodedef_manager = createNodeDefManager();
2043 eventmgr = new EventManager();
2044 quicktune = new QuicktuneShortcutter();
2046 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2047 && eventmgr && quicktune))
2053 // Create a server if not connecting to an existing one
2054 if (*address == "") {
2055 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2062 bool Game::initSound()
2065 if (g_settings->getBool("enable_sound")) {
2066 infostream << "Attempting to use OpenAL audio" << std::endl;
2067 sound = createOpenALSoundManager(&soundfetcher);
2069 infostream << "Failed to initialize OpenAL audio" << std::endl;
2071 infostream << "Sound disabled." << std::endl;
2075 infostream << "Using dummy audio." << std::endl;
2076 sound = &dummySoundManager;
2077 sound_is_dummy = true;
2080 soundmaker = new SoundMaker(sound, nodedef_manager);
2084 soundmaker->registerReceiver(eventmgr);
2089 bool Game::createSingleplayerServer(const std::string map_dir,
2090 const SubgameSpec &gamespec, u16 port, std::string *address)
2092 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2094 std::string bind_str = g_settings->get("bind_address");
2095 Address bind_addr(0, 0, 0, 0, port);
2097 if (g_settings->getBool("ipv6_server")) {
2098 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2102 bind_addr.Resolve(bind_str.c_str());
2103 } catch (ResolveError &e) {
2104 infostream << "Resolving bind address \"" << bind_str
2105 << "\" failed: " << e.what()
2106 << " -- Listening on all addresses." << std::endl;
2109 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2110 *error_message = "Unable to listen on " +
2111 bind_addr.serializeString() +
2112 " because IPv6 is disabled";
2113 errorstream << *error_message << std::endl;
2117 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2118 bind_addr.isIPv6());
2120 server->start(bind_addr);
2125 bool Game::createClient(const std::string &playername,
2126 const std::string &password, std::string *address, u16 port)
2128 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2130 draw_control = new MapDrawControl;
2134 bool could_connect, connect_aborted;
2136 if (!connectToServer(playername, password, address, port,
2137 &could_connect, &connect_aborted))
2140 if (!could_connect) {
2141 if (error_message->empty() && !connect_aborted) {
2142 // Should not happen if error messages are set properly
2143 *error_message = "Connection failed for unknown reason";
2144 errorstream << *error_message << std::endl;
2149 if (!getServerContent(&connect_aborted)) {
2150 if (error_message->empty() && !connect_aborted) {
2151 // Should not happen if error messages are set properly
2152 *error_message = "Connection failed for unknown reason";
2153 errorstream << *error_message << std::endl;
2158 // Update cached textures, meshes and materials
2159 client->afterContentReceived(device);
2163 camera = new Camera(smgr, *draw_control, gamedef);
2164 if (!camera || !camera->successfullyCreated(*error_message))
2166 client->setCamera(camera);
2170 if (m_cache_enable_clouds) {
2171 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2173 *error_message = "Memory allocation error (clouds)";
2174 errorstream << *error_message << std::endl;
2181 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2182 skybox = NULL; // This is used/set later on in the main run loop
2184 local_inventory = new Inventory(itemdef_manager);
2186 if (!(sky && local_inventory)) {
2187 *error_message = "Memory allocation error (sky or local inventory)";
2188 errorstream << *error_message << std::endl;
2192 /* Pre-calculated values
2194 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2196 v2u32 size = t->getOriginalSize();
2197 crack_animation_length = size.Y / size.X;
2199 crack_animation_length = 5;
2205 /* Set window caption
2207 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2209 str += utf8_to_wide(g_version_hash);
2211 str += driver->getName();
2213 device->setWindowCaption(str.c_str());
2215 LocalPlayer *player = client->getEnv().getLocalPlayer();
2216 player->hurt_tilt_timer = 0;
2217 player->hurt_tilt_strength = 0;
2219 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2222 *error_message = "Memory error: could not create HUD";
2223 errorstream << *error_message << std::endl;
2227 mapper = client->getMapper();
2228 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2233 bool Game::initGui()
2235 // First line of debug text
2236 guitext = addStaticText(guienv,
2237 utf8_to_wide(PROJECT_NAME_C).c_str(),
2238 core::rect<s32>(0, 0, 0, 0),
2239 false, false, guiroot);
2241 // Second line of debug text
2242 guitext2 = addStaticText(guienv,
2244 core::rect<s32>(0, 0, 0, 0),
2245 false, false, guiroot);
2247 // At the middle of the screen
2248 // Object infos are shown in this
2249 guitext_info = addStaticText(guienv,
2251 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2252 false, true, guiroot);
2254 // Status text (displays info when showing and hiding GUI stuff, etc.)
2255 guitext_status = addStaticText(guienv,
2257 core::rect<s32>(0, 0, 0, 0),
2258 false, false, guiroot);
2259 guitext_status->setVisible(false);
2262 guitext_chat = addStaticText(
2265 core::rect<s32>(0, 0, 0, 0),
2266 //false, false); // Disable word wrap as of now
2267 false, true, guiroot);
2269 // Remove stale "recent" chat messages from previous connections
2270 chat_backend->clearRecentChat();
2272 // Chat backend and console
2273 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2274 -1, chat_backend, client, &g_menumgr);
2275 if (!gui_chat_console) {
2276 *error_message = "Could not allocate memory for chat console";
2277 errorstream << *error_message << std::endl;
2281 // Profiler text (size is updated when text is updated)
2282 guitext_profiler = addStaticText(guienv,
2284 core::rect<s32>(0, 0, 0, 0),
2285 false, false, guiroot);
2286 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2287 guitext_profiler->setVisible(false);
2288 guitext_profiler->setWordWrap(true);
2290 #ifdef HAVE_TOUCHSCREENGUI
2292 if (g_touchscreengui)
2293 g_touchscreengui->init(texture_src);
2300 bool Game::connectToServer(const std::string &playername,
2301 const std::string &password, std::string *address, u16 port,
2302 bool *connect_ok, bool *aborted)
2304 *connect_ok = false; // Let's not be overly optimistic
2306 bool local_server_mode = false;
2308 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2310 Address connect_address(0, 0, 0, 0, port);
2313 connect_address.Resolve(address->c_str());
2315 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2316 //connect_address.Resolve("localhost");
2317 if (connect_address.isIPv6()) {
2318 IPv6AddressBytes addr_bytes;
2319 addr_bytes.bytes[15] = 1;
2320 connect_address.setAddress(&addr_bytes);
2322 connect_address.setAddress(127, 0, 0, 1);
2324 local_server_mode = true;
2326 } catch (ResolveError &e) {
2327 *error_message = std::string("Couldn't resolve address: ") + e.what();
2328 errorstream << *error_message << std::endl;
2332 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2333 *error_message = "Unable to connect to " +
2334 connect_address.serializeString() +
2335 " because IPv6 is disabled";
2336 errorstream << *error_message << std::endl;
2340 client = new Client(device,
2341 playername.c_str(), password,
2342 *draw_control, texture_src, shader_src,
2343 itemdef_manager, nodedef_manager, sound, eventmgr,
2344 connect_address.isIPv6());
2349 gamedef = client; // Client acts as our GameDef
2351 infostream << "Connecting to server at ";
2352 connect_address.print(&infostream);
2353 infostream << std::endl;
2355 client->connect(connect_address, *address,
2356 simple_singleplayer_mode || local_server_mode);
2359 Wait for server to accept connection
2365 FpsControl fps_control = { 0 };
2367 f32 wait_time = 0; // in seconds
2369 fps_control.last_time = device->getTimer()->getTime();
2371 while (device->run()) {
2373 limitFps(&fps_control, &dtime);
2375 // Update client and server
2376 client->step(dtime);
2379 server->step(dtime);
2382 if (client->getState() == LC_Init) {
2388 if (client->accessDenied()) {
2389 *error_message = "Access denied. Reason: "
2390 + client->accessDeniedReason();
2391 *reconnect_requested = client->reconnectRequested();
2392 errorstream << *error_message << std::endl;
2396 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2398 infostream << "Connect aborted [Escape]" << std::endl;
2403 // Only time out if we aren't waiting for the server we started
2404 if ((*address != "") && (wait_time > 10)) {
2405 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2406 // If no pre v25 init was sent, and no answer was received,
2407 // but the low level connection could be established
2408 // (meaning that we have a peer id), then we probably wanted
2409 // to connect to a legacy server. In this case, tell the user
2410 // to enable the option to be able to connect.
2411 if (!sent_old_init &&
2412 (client->getProtoVersion() == 0) &&
2413 client->connectedToServer()) {
2414 *error_message = "Connection failure: init packet not "
2415 "recognized by server.\n"
2416 "Most likely the server uses an old protocol version (<v25).\n"
2417 "Please ask the server owner to update to 0.4.13 or later.\n"
2418 "To still connect to the server in the meantime,\n"
2419 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2420 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2421 "entry in the advanced settings menu.";
2423 *error_message = "Connection timed out.";
2425 errorstream << *error_message << std::endl;
2430 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2432 } catch (con::PeerNotFoundException &e) {
2433 // TODO: Should something be done here? At least an info/error
2441 bool Game::getServerContent(bool *aborted)
2445 FpsControl fps_control = { 0 };
2446 f32 dtime; // in seconds
2448 fps_control.last_time = device->getTimer()->getTime();
2450 while (device->run()) {
2452 limitFps(&fps_control, &dtime);
2454 // Update client and server
2455 client->step(dtime);
2458 server->step(dtime);
2461 if (client->mediaReceived() && client->itemdefReceived() &&
2462 client->nodedefReceived()) {
2467 if (!checkConnection())
2470 if (client->getState() < LC_Init) {
2471 *error_message = "Client disconnected";
2472 errorstream << *error_message << std::endl;
2476 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2478 infostream << "Connect aborted [Escape]" << std::endl;
2485 if (!client->itemdefReceived()) {
2486 const wchar_t *text = wgettext("Item definitions...");
2488 draw_load_screen(text, device, guienv, dtime, progress);
2490 } else if (!client->nodedefReceived()) {
2491 const wchar_t *text = wgettext("Node definitions...");
2493 draw_load_screen(text, device, guienv, dtime, progress);
2496 std::stringstream message;
2497 message.precision(3);
2498 message << gettext("Media...");
2500 if ((USE_CURL == 0) ||
2501 (!g_settings->getBool("enable_remote_media_server"))) {
2502 float cur = client->getCurRate();
2503 std::string cur_unit = gettext("KiB/s");
2507 cur_unit = gettext("MiB/s");
2510 message << " (" << cur << ' ' << cur_unit << ")";
2513 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2514 draw_load_screen(utf8_to_wide(message.str()), device,
2515 guienv, dtime, progress);
2523 /****************************************************************************/
2524 /****************************************************************************
2526 ****************************************************************************/
2527 /****************************************************************************/
2529 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2531 if (runData->nodig_delay_timer >= 0)
2532 runData->nodig_delay_timer -= dtime;
2534 if (runData->object_hit_delay_timer >= 0)
2535 runData->object_hit_delay_timer -= dtime;
2537 runData->time_from_last_punch += dtime;
2541 /* returns false if game should exit, otherwise true
2543 inline bool Game::checkConnection()
2545 if (client->accessDenied()) {
2546 *error_message = "Access denied. Reason: "
2547 + client->accessDeniedReason();
2548 *reconnect_requested = client->reconnectRequested();
2549 errorstream << *error_message << std::endl;
2557 /* returns false if game should exit, otherwise true
2559 inline bool Game::handleCallbacks()
2561 if (g_gamecallback->disconnect_requested) {
2562 g_gamecallback->disconnect_requested = false;
2566 if (g_gamecallback->changepassword_requested) {
2567 (new GUIPasswordChange(guienv, guiroot, -1,
2568 &g_menumgr, client))->drop();
2569 g_gamecallback->changepassword_requested = false;
2572 if (g_gamecallback->changevolume_requested) {
2573 (new GUIVolumeChange(guienv, guiroot, -1,
2574 &g_menumgr))->drop();
2575 g_gamecallback->changevolume_requested = false;
2578 if (g_gamecallback->keyconfig_requested) {
2579 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2580 &g_menumgr))->drop();
2581 g_gamecallback->keyconfig_requested = false;
2584 if (g_gamecallback->keyconfig_changed) {
2585 keycache.populate(); // update the cache with new settings
2586 g_gamecallback->keyconfig_changed = false;
2593 void Game::processQueues()
2595 texture_src->processQueue();
2596 itemdef_manager->processQueue(gamedef);
2597 shader_src->processQueue();
2601 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2602 const FpsControl &draw_times, f32 dtime)
2604 float profiler_print_interval =
2605 g_settings->getFloat("profiler_print_interval");
2606 bool print_to_log = true;
2608 if (profiler_print_interval == 0) {
2609 print_to_log = false;
2610 profiler_print_interval = 5;
2613 if (profiler_interval.step(dtime, profiler_print_interval)) {
2615 infostream << "Profiler:" << std::endl;
2616 g_profiler->print(infostream);
2619 update_profiler_gui(guitext_profiler, g_fontengine,
2620 runData.profiler_current_page, runData.profiler_max_page,
2621 driver->getScreenSize().Height);
2623 g_profiler->clear();
2626 addProfilerGraphs(stats, draw_times, dtime);
2630 void Game::addProfilerGraphs(const RunStats &stats,
2631 const FpsControl &draw_times, f32 dtime)
2633 g_profiler->graphAdd("mainloop_other",
2634 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2636 if (draw_times.sleep_time != 0)
2637 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2638 g_profiler->graphAdd("mainloop_dtime", dtime);
2640 g_profiler->add("Elapsed time", dtime);
2641 g_profiler->avg("FPS", 1. / dtime);
2645 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2652 /* Time average and jitter calculation
2654 jp = &stats->dtime_jitter;
2655 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2657 jitter = dtime - jp->avg;
2659 if (jitter > jp->max)
2662 jp->counter += dtime;
2664 if (jp->counter > 0.0) {
2666 jp->max_sample = jp->max;
2667 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2671 /* Busytime average and jitter calculation
2673 jp = &stats->busy_time_jitter;
2674 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2676 jitter = draw_times.busy_time - jp->avg;
2678 if (jitter > jp->max)
2680 if (jitter < jp->min)
2683 jp->counter += dtime;
2685 if (jp->counter > 0.0) {
2687 jp->max_sample = jp->max;
2688 jp->min_sample = jp->min;
2696 /****************************************************************************
2698 ****************************************************************************/
2700 void Game::processUserInput(VolatileRunFlags *flags,
2701 GameRunData *runData, f32 dtime)
2703 // Reset input if window not active or some menu is active
2704 if (device->isWindowActive() == false
2705 || noMenuActive() == false
2706 || guienv->hasFocus(gui_chat_console)) {
2708 #ifdef HAVE_TOUCHSCREENGUI
2709 g_touchscreengui->hide();
2712 #ifdef HAVE_TOUCHSCREENGUI
2713 else if (g_touchscreengui) {
2714 /* on touchscreengui step may generate own input events which ain't
2715 * what we want in case we just did clear them */
2716 g_touchscreengui->step(dtime);
2720 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2721 gui_chat_console->closeConsoleAtOnce();
2724 // Input handler step() (used by the random input generator)
2728 if (current_formspec != NULL)
2729 current_formspec->getAndroidUIInput();
2731 handleAndroidChatInput();
2734 // Increase timer for double tap of "keymap_jump"
2735 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2736 runData->jump_timer += dtime;
2740 &runData->statustext_time,
2741 &runData->jump_timer,
2742 &runData->reset_jump_timer,
2743 &runData->profiler_current_page,
2744 runData->profiler_max_page);
2746 processItemSelection(&runData->new_playeritem);
2750 void Game::processKeyInput(VolatileRunFlags *flags,
2751 float *statustext_time,
2753 bool *reset_jump_timer,
2754 u32 *profiler_current_page,
2755 u32 profiler_max_page)
2758 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2760 if (wasKeyDown(KeyType::DROP)) {
2762 } else if (wasKeyDown(KeyType::AUTORUN)) {
2763 toggleAutorun(statustext_time);
2764 } else if (wasKeyDown(KeyType::INVENTORY)) {
2766 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2767 if (!gui_chat_console->isOpenInhibited()) {
2768 show_pause_menu(¤t_formspec, client, gamedef,
2769 texture_src, device, &input->joystick,
2770 simple_singleplayer_mode);
2772 } else if (wasKeyDown(KeyType::CHAT)) {
2773 openConsole(0.2, L"");
2774 } else if (wasKeyDown(KeyType::CMD)) {
2775 openConsole(0.2, L"/");
2776 } else if (wasKeyDown(KeyType::CONSOLE)) {
2778 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2779 toggleFreeMove(statustext_time);
2780 } else if (wasKeyDown(KeyType::JUMP)) {
2781 toggleFreeMoveAlt(statustext_time, jump_timer);
2782 *reset_jump_timer = true;
2783 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2784 toggleFast(statustext_time);
2785 } else if (wasKeyDown(KeyType::NOCLIP)) {
2786 toggleNoClip(statustext_time);
2787 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2788 toggleCinematic(statustext_time);
2789 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2790 client->makeScreenshot(device);
2791 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2792 toggleHud(statustext_time, &flags->show_hud);
2793 } else if (wasKeyDown(KeyType::MINIMAP)) {
2794 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2795 isKeyDown(KeyType::SNEAK));
2796 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2797 toggleChat(statustext_time, &flags->show_chat);
2798 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2799 toggleFog(statustext_time, &flags->force_fog_off);
2800 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2801 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2802 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2803 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2804 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2805 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2806 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2807 increaseViewRange(statustext_time);
2808 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2809 decreaseViewRange(statustext_time);
2810 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2811 toggleFullViewRange(statustext_time);
2812 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2814 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2816 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2818 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2820 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2821 // Print debug stacks
2822 dstream << "-----------------------------------------"
2824 dstream << "Printing debug stacks:" << std::endl;
2825 dstream << "-----------------------------------------"
2827 debug_stacks_print();
2830 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2831 *reset_jump_timer = false;
2837 if (quicktune->hasMessage()) {
2838 std::string msg = quicktune->getMessage();
2839 statustext = utf8_to_wide(msg);
2840 *statustext_time = 0;
2844 void Game::processItemSelection(u16 *new_playeritem)
2846 LocalPlayer *player = client->getEnv().getLocalPlayer();
2848 /* Item selection using mouse wheel
2850 *new_playeritem = client->getPlayerItem();
2852 s32 wheel = input->getMouseWheel();
2853 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2854 player->hud_hotbar_itemcount - 1);
2858 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2862 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2867 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2869 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2872 /* Item selection using keyboard
2874 for (u16 i = 0; i < 10; i++) {
2875 static const KeyPress *item_keys[10] = {
2876 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2877 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2878 NumberKey + 9, NumberKey + 0,
2881 if (input->wasKeyDown(*item_keys[i])) {
2882 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2883 *new_playeritem = i;
2884 infostream << "Selected item: " << new_playeritem << std::endl;
2892 void Game::dropSelectedItem()
2894 IDropAction *a = new IDropAction();
2896 a->from_inv.setCurrentPlayer();
2897 a->from_list = "main";
2898 a->from_i = client->getPlayerItem();
2899 client->inventoryAction(a);
2903 void Game::openInventory()
2906 * Don't permit to open inventory is CAO or player doesn't exists.
2907 * This prevent showing an empty inventory at player load
2910 LocalPlayer *player = client->getEnv().getLocalPlayer();
2911 if (player == NULL || player->getCAO() == NULL)
2914 infostream << "the_game: " << "Launching inventory" << std::endl;
2916 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2917 TextDest *txt_dst = new TextDestPlayerInventory(client);
2919 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2920 device, &input->joystick, fs_src, txt_dst, client);
2922 InventoryLocation inventoryloc;
2923 inventoryloc.setCurrentPlayer();
2924 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2928 void Game::openConsole(float height, const wchar_t *line)
2931 porting::showInputDialog(gettext("ok"), "", "", 2);
2932 m_android_chat_open = true;
2934 if (gui_chat_console->isOpenInhibited())
2936 gui_chat_console->openConsole(height);
2938 gui_chat_console->setCloseOnEnter(true);
2939 gui_chat_console->replaceAndAddToHistory(line);
2945 void Game::handleAndroidChatInput()
2947 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2948 std::string text = porting::getInputDialogValue();
2949 client->typeChatMessage(utf8_to_wide(text));
2955 void Game::toggleFreeMove(float *statustext_time)
2957 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2959 bool free_move = !g_settings->getBool("free_move");
2960 g_settings->set("free_move", bool_to_cstr(free_move));
2962 *statustext_time = 0;
2963 statustext = msg[free_move];
2964 if (free_move && !client->checkPrivilege("fly"))
2965 statustext += L" (note: no 'fly' privilege)";
2969 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2971 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2972 toggleFreeMove(statustext_time);
2976 void Game::toggleFast(float *statustext_time)
2978 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2979 bool fast_move = !g_settings->getBool("fast_move");
2980 g_settings->set("fast_move", bool_to_cstr(fast_move));
2982 *statustext_time = 0;
2983 statustext = msg[fast_move];
2985 bool has_fast_privs = client->checkPrivilege("fast");
2987 if (fast_move && !has_fast_privs)
2988 statustext += L" (note: no 'fast' privilege)";
2991 m_cache_hold_aux1 = fast_move && has_fast_privs;
2996 void Game::toggleNoClip(float *statustext_time)
2998 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2999 bool noclip = !g_settings->getBool("noclip");
3000 g_settings->set("noclip", bool_to_cstr(noclip));
3002 *statustext_time = 0;
3003 statustext = msg[noclip];
3005 if (noclip && !client->checkPrivilege("noclip"))
3006 statustext += L" (note: no 'noclip' privilege)";
3009 void Game::toggleCinematic(float *statustext_time)
3011 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
3012 bool cinematic = !g_settings->getBool("cinematic");
3013 g_settings->set("cinematic", bool_to_cstr(cinematic));
3015 *statustext_time = 0;
3016 statustext = msg[cinematic];
3019 // Add WoW-style autorun by toggling continuous forward.
3020 void Game::toggleAutorun(float *statustext_time)
3022 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
3023 bool autorun_enabled = !g_settings->getBool("continuous_forward");
3024 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
3026 *statustext_time = 0;
3027 statustext = msg[autorun_enabled ? 1 : 0];
3030 void Game::toggleChat(float *statustext_time, bool *flag)
3032 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
3035 *statustext_time = 0;
3036 statustext = msg[*flag];
3040 void Game::toggleHud(float *statustext_time, bool *flag)
3042 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
3045 *statustext_time = 0;
3046 statustext = msg[*flag];
3049 void Game::toggleMinimap(float *statustext_time, bool *flag,
3050 bool show_hud, bool shift_pressed)
3052 if (!show_hud || !g_settings->getBool("enable_minimap"))
3055 if (shift_pressed) {
3056 mapper->toggleMinimapShape();
3060 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
3062 MinimapMode mode = MINIMAP_MODE_OFF;
3063 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
3064 mode = mapper->getMinimapMode();
3065 mode = (MinimapMode)((int)mode + 1);
3070 case MINIMAP_MODE_SURFACEx1:
3071 statustext = L"Minimap in surface mode, Zoom x1";
3073 case MINIMAP_MODE_SURFACEx2:
3074 statustext = L"Minimap in surface mode, Zoom x2";
3076 case MINIMAP_MODE_SURFACEx4:
3077 statustext = L"Minimap in surface mode, Zoom x4";
3079 case MINIMAP_MODE_RADARx1:
3080 statustext = L"Minimap in radar mode, Zoom x1";
3082 case MINIMAP_MODE_RADARx2:
3083 statustext = L"Minimap in radar mode, Zoom x2";
3085 case MINIMAP_MODE_RADARx4:
3086 statustext = L"Minimap in radar mode, Zoom x4";
3089 mode = MINIMAP_MODE_OFF;
3091 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3092 L"Minimap hidden" : L"Minimap disabled by server";
3095 *statustext_time = 0;
3096 mapper->setMinimapMode(mode);
3099 void Game::toggleFog(float *statustext_time, bool *flag)
3101 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3104 *statustext_time = 0;
3105 statustext = msg[*flag];
3109 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3110 bool *show_profiler_graph)
3112 // Initial / 3x toggle: Chat only
3113 // 1x toggle: Debug text with chat
3114 // 2x toggle: Debug text with profiler graph
3117 *show_profiler_graph = false;
3118 statustext = L"Debug info shown";
3119 } else if (*show_profiler_graph) {
3120 *show_debug = false;
3121 *show_profiler_graph = false;
3122 statustext = L"Debug info and profiler graph hidden";
3124 *show_profiler_graph = true;
3125 statustext = L"Profiler graph shown";
3127 *statustext_time = 0;
3131 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3133 static const wchar_t *msg[] = {
3134 L"Camera update enabled",
3135 L"Camera update disabled"
3139 *statustext_time = 0;
3140 statustext = msg[*flag];
3144 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3145 u32 profiler_max_page)
3147 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3149 // FIXME: This updates the profiler with incomplete values
3150 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3151 profiler_max_page, driver->getScreenSize().Height);
3153 if (*profiler_current_page != 0) {
3154 std::wstringstream sstr;
3155 sstr << "Profiler shown (page " << *profiler_current_page
3156 << " of " << profiler_max_page << ")";
3157 statustext = sstr.str();
3159 statustext = L"Profiler hidden";
3161 *statustext_time = 0;
3165 void Game::increaseViewRange(float *statustext_time)
3167 s16 range = g_settings->getS16("viewing_range");
3168 s16 range_new = range + 10;
3169 g_settings->set("viewing_range", itos(range_new));
3170 statustext = utf8_to_wide("Viewing range changed to "
3172 *statustext_time = 0;
3176 void Game::decreaseViewRange(float *statustext_time)
3178 s16 range = g_settings->getS16("viewing_range");
3179 s16 range_new = range - 10;
3184 g_settings->set("viewing_range", itos(range_new));
3185 statustext = utf8_to_wide("Viewing range changed to "
3187 *statustext_time = 0;
3191 void Game::toggleFullViewRange(float *statustext_time)
3193 static const wchar_t *msg[] = {
3194 L"Disabled full viewing range",
3195 L"Enabled full viewing range"
3198 draw_control->range_all = !draw_control->range_all;
3199 infostream << msg[draw_control->range_all] << std::endl;
3200 statustext = msg[draw_control->range_all];
3201 *statustext_time = 0;
3205 void Game::updateCameraDirection(CameraOrientation *cam,
3206 VolatileRunFlags *flags, float dtime)
3208 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3211 if (!random_input) {
3212 // Mac OSX gets upset if this is set every frame
3213 if (device->getCursorControl()->isVisible())
3214 device->getCursorControl()->setVisible(false);
3218 if (flags->first_loop_after_window_activation)
3219 flags->first_loop_after_window_activation = false;
3221 updateCameraOrientation(cam, *flags, dtime);
3223 input->setMousePos((driver->getScreenSize().Width / 2),
3224 (driver->getScreenSize().Height / 2));
3228 // Mac OSX gets upset if this is set every frame
3229 if (device->getCursorControl()->isVisible() == false)
3230 device->getCursorControl()->setVisible(true);
3233 if (!flags->first_loop_after_window_activation)
3234 flags->first_loop_after_window_activation = true;
3239 void Game::updateCameraOrientation(CameraOrientation *cam,
3240 const VolatileRunFlags &flags, float dtime)
3242 #ifdef HAVE_TOUCHSCREENGUI
3243 if (g_touchscreengui) {
3244 cam->camera_yaw = g_touchscreengui->getYaw();
3245 cam->camera_pitch = g_touchscreengui->getPitch();
3249 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3250 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3252 if (flags.invert_mouse
3253 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3257 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3258 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3260 #ifdef HAVE_TOUCHSCREENGUI
3264 if (m_cache_enable_joysticks) {
3265 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3266 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3268 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3272 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3276 void Game::updatePlayerControl(const CameraOrientation &cam)
3278 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3280 // DO NOT use the isKeyDown method for the forward, backward, left, right
3281 // buttons, as the code that uses the controls needs to be able to
3282 // distinguish between the two in order to know when to use joysticks.
3284 PlayerControl control(
3285 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3286 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3287 input->isKeyDown(keycache.key[KeyType::LEFT]),
3288 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3289 isKeyDown(KeyType::JUMP),
3290 isKeyDown(KeyType::SPECIAL1),
3291 isKeyDown(KeyType::SNEAK),
3292 isKeyDown(KeyType::ZOOM),
3297 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3298 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3302 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3303 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3304 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3305 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3306 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3307 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3308 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3309 ( (u32)(isLeftPressed() & 0x1) << 7) |
3310 ( (u32)(isRightPressed() & 0x1) << 8
3314 /* For Android, simulate holding down AUX1 (fast move) if the user has
3315 * the fast_move setting toggled on. If there is an aux1 key defined for
3316 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3319 if (m_cache_hold_aux1) {
3320 control.aux1 = control.aux1 ^ true;
3321 keypress_bits ^= ((u32)(1U << 5));
3325 client->setPlayerControl(control);
3326 LocalPlayer *player = client->getEnv().getLocalPlayer();
3327 player->keyPressed = keypress_bits;
3333 inline void Game::step(f32 *dtime)
3335 bool can_be_and_is_paused =
3336 (simple_singleplayer_mode && g_menumgr.pausesGame());
3338 if (can_be_and_is_paused) { // This is for a singleplayer server
3339 *dtime = 0; // No time passes
3341 if (server != NULL) {
3342 //TimeTaker timer("server->step(dtime)");
3343 server->step(*dtime);
3346 //TimeTaker timer("client.step(dtime)");
3347 client->step(*dtime);
3352 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3354 ClientEvent event = client->getClientEvent();
3356 LocalPlayer *player = client->getEnv().getLocalPlayer();
3358 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3360 if (event.type == CE_PLAYER_DAMAGE &&
3361 client->getHP() != 0) {
3362 //u16 damage = event.player_damage.amount;
3363 //infostream<<"Player damage: "<<damage<<std::endl;
3365 *damage_flash += 100.0;
3366 *damage_flash += 8.0 * event.player_damage.amount;
3368 player->hurt_tilt_timer = 1.5;
3369 player->hurt_tilt_strength = event.player_damage.amount / 4;
3370 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3372 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3373 gamedef->event()->put(e);
3374 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3375 cam->camera_yaw = event.player_force_move.yaw;
3376 cam->camera_pitch = event.player_force_move.pitch;
3377 } else if (event.type == CE_DEATHSCREEN) {
3378 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3379 device, &input->joystick, client);
3381 chat_backend->addMessage(L"", L"You died.");
3383 /* Handle visualization */
3385 player->hurt_tilt_timer = 0;
3386 player->hurt_tilt_strength = 0;
3388 } else if (event.type == CE_SHOW_FORMSPEC) {
3389 FormspecFormSource *fs_src =
3390 new FormspecFormSource(*(event.show_formspec.formspec));
3391 TextDestPlayerInventory *txt_dst =
3392 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3394 create_formspec_menu(¤t_formspec, client, gamedef,
3395 texture_src, device, &input->joystick,
3396 fs_src, txt_dst, client);
3398 delete(event.show_formspec.formspec);
3399 delete(event.show_formspec.formname);
3400 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3401 (event.type == CE_ADD_PARTICLESPAWNER) ||
3402 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3403 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3405 } else if (event.type == CE_HUDADD) {
3406 u32 id = event.hudadd.id;
3408 LocalPlayer *player = client->getEnv().getLocalPlayer();
3409 HudElement *e = player->getHud(id);
3412 delete event.hudadd.pos;
3413 delete event.hudadd.name;
3414 delete event.hudadd.scale;
3415 delete event.hudadd.text;
3416 delete event.hudadd.align;
3417 delete event.hudadd.offset;
3418 delete event.hudadd.world_pos;
3419 delete event.hudadd.size;
3424 e->type = (HudElementType)event.hudadd.type;
3425 e->pos = *event.hudadd.pos;
3426 e->name = *event.hudadd.name;
3427 e->scale = *event.hudadd.scale;
3428 e->text = *event.hudadd.text;
3429 e->number = event.hudadd.number;
3430 e->item = event.hudadd.item;
3431 e->dir = event.hudadd.dir;
3432 e->align = *event.hudadd.align;
3433 e->offset = *event.hudadd.offset;
3434 e->world_pos = *event.hudadd.world_pos;
3435 e->size = *event.hudadd.size;
3437 u32 new_id = player->addHud(e);
3438 //if this isn't true our huds aren't consistent
3439 sanity_check(new_id == id);
3441 delete event.hudadd.pos;
3442 delete event.hudadd.name;
3443 delete event.hudadd.scale;
3444 delete event.hudadd.text;
3445 delete event.hudadd.align;
3446 delete event.hudadd.offset;
3447 delete event.hudadd.world_pos;
3448 delete event.hudadd.size;
3449 } else if (event.type == CE_HUDRM) {
3450 HudElement *e = player->removeHud(event.hudrm.id);
3454 } else if (event.type == CE_HUDCHANGE) {
3455 u32 id = event.hudchange.id;
3456 HudElement *e = player->getHud(id);
3459 delete event.hudchange.v3fdata;
3460 delete event.hudchange.v2fdata;
3461 delete event.hudchange.sdata;
3462 delete event.hudchange.v2s32data;
3466 switch (event.hudchange.stat) {
3468 e->pos = *event.hudchange.v2fdata;
3472 e->name = *event.hudchange.sdata;
3475 case HUD_STAT_SCALE:
3476 e->scale = *event.hudchange.v2fdata;
3480 e->text = *event.hudchange.sdata;
3483 case HUD_STAT_NUMBER:
3484 e->number = event.hudchange.data;
3488 e->item = event.hudchange.data;
3492 e->dir = event.hudchange.data;
3495 case HUD_STAT_ALIGN:
3496 e->align = *event.hudchange.v2fdata;
3499 case HUD_STAT_OFFSET:
3500 e->offset = *event.hudchange.v2fdata;
3503 case HUD_STAT_WORLD_POS:
3504 e->world_pos = *event.hudchange.v3fdata;
3508 e->size = *event.hudchange.v2s32data;
3512 delete event.hudchange.v3fdata;
3513 delete event.hudchange.v2fdata;
3514 delete event.hudchange.sdata;
3515 delete event.hudchange.v2s32data;
3516 } else if (event.type == CE_SET_SKY) {
3517 sky->setVisible(false);
3524 // Handle according to type
3525 if (*event.set_sky.type == "regular") {
3526 sky->setVisible(true);
3527 } else if (*event.set_sky.type == "skybox" &&
3528 event.set_sky.params->size() == 6) {
3529 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3530 skybox = smgr->addSkyBoxSceneNode(
3531 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3532 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3533 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3534 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3535 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3536 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3538 // Handle everything else as plain color
3540 if (*event.set_sky.type != "plain")
3541 infostream << "Unknown sky type: "
3542 << (*event.set_sky.type) << std::endl;
3544 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3547 delete event.set_sky.bgcolor;
3548 delete event.set_sky.type;
3549 delete event.set_sky.params;
3550 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3551 bool enable = event.override_day_night_ratio.do_override;
3552 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3553 client->getEnv().setDayNightRatioOverride(enable, value);
3559 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3560 f32 dtime, float time_from_last_punch)
3562 LocalPlayer *player = client->getEnv().getLocalPlayer();
3565 For interaction purposes, get info about the held item
3567 - Is it a usable item?
3568 - Can it point to liquids?
3570 ItemStack playeritem;
3572 InventoryList *mlist = local_inventory->getList("main");
3574 if (mlist && client->getPlayerItem() < mlist->getSize())
3575 playeritem = mlist->getItem(client->getPlayerItem());
3578 ToolCapabilities playeritem_toolcap =
3579 playeritem.getToolCapabilities(itemdef_manager);
3581 v3s16 old_camera_offset = camera->getOffset();
3583 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3584 GenericCAO *playercao = player->getCAO();
3586 // If playercao not loaded, don't change camera
3587 if (playercao == NULL)
3590 camera->toggleCameraMode();
3592 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3593 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3596 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3597 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3599 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3600 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3602 camera->step(dtime);
3604 v3f camera_position = camera->getPosition();
3605 v3f camera_direction = camera->getDirection();
3606 f32 camera_fov = camera->getFovMax();
3607 v3s16 camera_offset = camera->getOffset();
3609 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3611 if (!flags->disable_camera_update) {
3612 client->getEnv().getClientMap().updateCamera(camera_position,
3613 camera_direction, camera_fov, camera_offset);
3615 if (flags->camera_offset_changed) {
3616 client->updateCameraOffset(camera_offset);
3617 client->getEnv().updateCameraOffset(camera_offset);
3620 clouds->updateCameraOffset(camera_offset);
3626 void Game::updateSound(f32 dtime)
3628 // Update sound listener
3629 v3s16 camera_offset = camera->getOffset();
3630 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3631 v3f(0, 0, 0), // velocity
3632 camera->getDirection(),
3633 camera->getCameraNode()->getUpVector());
3634 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3637 // Update sound maker
3638 soundmaker->step(dtime);
3640 LocalPlayer *player = client->getEnv().getLocalPlayer();
3642 ClientMap &map = client->getEnv().getClientMap();
3643 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3644 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3648 void Game::processPlayerInteraction(GameRunData *runData,
3649 f32 dtime, bool show_hud, bool show_debug)
3651 LocalPlayer *player = client->getEnv().getLocalPlayer();
3653 ItemStack playeritem;
3655 InventoryList *mlist = local_inventory->getList("main");
3657 if (mlist && client->getPlayerItem() < mlist->getSize())
3658 playeritem = mlist->getItem(client->getPlayerItem());
3661 const ItemDefinition &playeritem_def =
3662 playeritem.getDefinition(itemdef_manager);
3664 v3f player_position = player->getPosition();
3665 v3f camera_position = camera->getPosition();
3666 v3f camera_direction = camera->getDirection();
3667 v3s16 camera_offset = camera->getOffset();
3671 Calculate what block is the crosshair pointing to
3674 f32 d = playeritem_def.range; // max. distance
3675 f32 d_hand = itemdef_manager->get("").range;
3677 if (d < 0 && d_hand >= 0)
3682 core::line3d<f32> shootline;
3684 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3686 shootline = core::line3d<f32>(camera_position,
3687 camera_position + camera_direction * BS * (d + 1));
3690 // prevent player pointing anything in front-view
3691 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3692 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3695 #ifdef HAVE_TOUCHSCREENGUI
3697 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3698 shootline = g_touchscreengui->getShootline();
3699 shootline.start += intToFloat(camera_offset, BS);
3700 shootline.end += intToFloat(camera_offset, BS);
3705 PointedThing pointed = getPointedThing(
3707 client, hud, player_position, camera_direction,
3708 camera_position, shootline, d,
3709 playeritem_def.liquids_pointable,
3710 !runData->ldown_for_dig,
3713 runData->selected_object);
3715 if (pointed != runData->pointed_old) {
3716 infostream << "Pointing at " << pointed.dump() << std::endl;
3717 hud->updateSelectionMesh(camera_offset);
3722 - releasing left mouse button
3723 - pointing away from node
3725 if (runData->digging) {
3726 if (getLeftReleased()) {
3727 infostream << "Left button released"
3728 << " (stopped digging)" << std::endl;
3729 runData->digging = false;
3730 } else if (pointed != runData->pointed_old) {
3731 if (pointed.type == POINTEDTHING_NODE
3732 && runData->pointed_old.type == POINTEDTHING_NODE
3733 && pointed.node_undersurface
3734 == runData->pointed_old.node_undersurface) {
3735 // Still pointing to the same node, but a different face.
3738 infostream << "Pointing away from node"
3739 << " (stopped digging)" << std::endl;
3740 runData->digging = false;
3741 hud->updateSelectionMesh(camera_offset);
3745 if (!runData->digging) {
3746 client->interact(1, runData->pointed_old);
3747 client->setCrack(-1, v3s16(0, 0, 0));
3748 runData->dig_time = 0.0;
3752 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3753 runData->ldown_for_dig = false;
3756 runData->left_punch = false;
3758 soundmaker->m_player_leftpunch_sound.name = "";
3760 if (isRightPressed())
3761 runData->repeat_rightclick_timer += dtime;
3763 runData->repeat_rightclick_timer = 0;
3765 if (playeritem_def.usable && isLeftPressed()) {
3766 if (getLeftClicked())
3767 client->interact(4, pointed);
3768 } else if (pointed.type == POINTEDTHING_NODE) {
3769 ToolCapabilities playeritem_toolcap =
3770 playeritem.getToolCapabilities(itemdef_manager);
3771 handlePointingAtNode(runData, pointed, playeritem_def,
3772 playeritem_toolcap, dtime);
3773 } else if (pointed.type == POINTEDTHING_OBJECT) {
3774 handlePointingAtObject(runData, pointed, playeritem,
3775 player_position, show_debug);
3776 } else if (isLeftPressed()) {
3777 // When button is held down in air, show continuous animation
3778 runData->left_punch = true;
3779 } else if (getRightClicked()) {
3780 handlePointingAtNothing(runData, playeritem);
3783 runData->pointed_old = pointed;
3785 if (runData->left_punch || getLeftClicked())
3786 camera->setDigging(0); // left click animation
3788 input->resetLeftClicked();
3789 input->resetRightClicked();
3791 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3792 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3794 input->resetLeftReleased();
3795 input->resetRightReleased();
3797 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3798 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3802 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3804 infostream << "Right Clicked in Air" << std::endl;
3805 PointedThing fauxPointed;
3806 fauxPointed.type = POINTEDTHING_NOTHING;
3807 client->interact(5, fauxPointed);
3811 void Game::handlePointingAtNode(GameRunData *runData,
3812 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3813 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3815 v3s16 nodepos = pointed.node_undersurface;
3816 v3s16 neighbourpos = pointed.node_abovesurface;
3819 Check information text of node
3822 ClientMap &map = client->getEnv().getClientMap();
3823 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3826 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3828 MapNode n = map.getNodeNoEx(nodepos);
3830 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3831 infotext = L"Unknown node: ";
3832 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3836 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3837 && client->checkPrivilege("interact")) {
3838 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3841 if ((getRightClicked() ||
3842 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3843 client->checkPrivilege("interact")) {
3844 runData->repeat_rightclick_timer = 0;
3845 infostream << "Ground right-clicked" << std::endl;
3847 if (meta && meta->getString("formspec") != "" && !random_input
3848 && !isKeyDown(KeyType::SNEAK)) {
3849 infostream << "Launching custom inventory view" << std::endl;
3851 InventoryLocation inventoryloc;
3852 inventoryloc.setNodeMeta(nodepos);
3854 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3855 &client->getEnv().getClientMap(), nodepos);
3856 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3858 create_formspec_menu(¤t_formspec, client, gamedef,
3859 texture_src, device, &input->joystick, fs_src, txt_dst, client);
3861 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3863 // Report right click to server
3865 camera->setDigging(1); // right click animation (always shown for feedback)
3867 // If the wielded item has node placement prediction,
3869 bool placed = nodePlacementPrediction(*client,
3871 nodepos, neighbourpos);
3875 client->interact(3, pointed);
3877 soundmaker->m_player_rightpunch_sound =
3878 playeritem_def.sound_place;
3880 soundmaker->m_player_rightpunch_sound =
3883 if (playeritem_def.node_placement_prediction == "" ||
3884 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3885 client->interact(3, pointed); // Report to server
3887 soundmaker->m_player_rightpunch_sound =
3888 playeritem_def.sound_place_failed;
3896 void Game::handlePointingAtObject(GameRunData *runData,
3897 const PointedThing &pointed,
3898 const ItemStack &playeritem,
3899 const v3f &player_position,
3902 infotext = unescape_enriched(
3903 utf8_to_wide(runData->selected_object->infoText()));
3906 if (infotext != L"") {
3909 infotext += unescape_enriched(utf8_to_wide(
3910 runData->selected_object->debugInfoText()));
3913 if (isLeftPressed()) {
3914 bool do_punch = false;
3915 bool do_punch_damage = false;
3917 if (runData->object_hit_delay_timer <= 0.0) {
3919 do_punch_damage = true;
3920 runData->object_hit_delay_timer = object_hit_delay;
3923 if (getLeftClicked())
3927 infostream << "Left-clicked object" << std::endl;
3928 runData->left_punch = true;
3931 if (do_punch_damage) {
3932 // Report direct punch
3933 v3f objpos = runData->selected_object->getPosition();
3934 v3f dir = (objpos - player_position).normalize();
3936 bool disable_send = runData->selected_object->directReportPunch(
3937 dir, &playeritem, runData->time_from_last_punch);
3938 runData->time_from_last_punch = 0;
3941 client->interact(0, pointed);
3943 } else if (getRightClicked()) {
3944 infostream << "Right-clicked object" << std::endl;
3945 client->interact(3, pointed); // place
3950 void Game::handleDigging(GameRunData *runData,
3951 const PointedThing &pointed, const v3s16 &nodepos,
3952 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3954 if (!runData->digging) {
3955 infostream << "Started digging" << std::endl;
3956 client->interact(0, pointed);
3957 runData->digging = true;
3958 runData->ldown_for_dig = true;
3961 LocalPlayer *player = client->getEnv().getLocalPlayer();
3962 ClientMap &map = client->getEnv().getClientMap();
3963 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3965 // NOTE: Similar piece of code exists on the server side for
3967 // Get digging parameters
3968 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3969 &playeritem_toolcap);
3971 // If can't dig, try hand
3972 if (!params.diggable) {
3973 const ItemDefinition &hand = itemdef_manager->get("");
3974 const ToolCapabilities *tp = hand.tool_capabilities;
3977 params = getDigParams(nodedef_manager->get(n).groups, tp);
3980 if (params.diggable == false) {
3981 // I guess nobody will wait for this long
3982 runData->dig_time_complete = 10000000.0;
3984 runData->dig_time_complete = params.time;
3986 if (m_cache_enable_particles) {
3987 const ContentFeatures &features =
3988 client->getNodeDefManager()->get(n);
3989 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3990 player, nodepos, features.tiles);
3994 if (runData->dig_time_complete >= 0.001) {
3995 runData->dig_index = (float)crack_animation_length
3997 / runData->dig_time_complete;
3999 // This is for torches
4000 runData->dig_index = crack_animation_length;
4003 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
4005 if (sound_dig.exists() && params.diggable) {
4006 if (sound_dig.name == "__group") {
4007 if (params.main_group != "") {
4008 soundmaker->m_player_leftpunch_sound.gain = 0.5;
4009 soundmaker->m_player_leftpunch_sound.name =
4010 std::string("default_dig_") +
4014 soundmaker->m_player_leftpunch_sound = sound_dig;
4018 // Don't show cracks if not diggable
4019 if (runData->dig_time_complete >= 100000.0) {
4020 } else if (runData->dig_index < crack_animation_length) {
4021 //TimeTaker timer("client.setTempMod");
4022 //infostream<<"dig_index="<<dig_index<<std::endl;
4023 client->setCrack(runData->dig_index, nodepos);
4025 infostream << "Digging completed" << std::endl;
4026 client->interact(2, pointed);
4027 client->setCrack(-1, v3s16(0, 0, 0));
4028 bool is_valid_position;
4029 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4030 if (is_valid_position)
4031 client->removeNode(nodepos);
4033 if (m_cache_enable_particles) {
4034 const ContentFeatures &features =
4035 client->getNodeDefManager()->get(wasnode);
4036 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
4037 player, nodepos, features.tiles);
4040 runData->dig_time = 0;
4041 runData->digging = false;
4043 runData->nodig_delay_timer =
4044 runData->dig_time_complete / (float)crack_animation_length;
4046 // We don't want a corresponding delay to
4047 // very time consuming nodes
4048 if (runData->nodig_delay_timer > 0.3)
4049 runData->nodig_delay_timer = 0.3;
4051 // We want a slight delay to very little
4052 // time consuming nodes
4053 const float mindelay = 0.15;
4055 if (runData->nodig_delay_timer < mindelay)
4056 runData->nodig_delay_timer = mindelay;
4058 // Send event to trigger sound
4059 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4060 gamedef->event()->put(e);
4063 if (runData->dig_time_complete < 100000.0) {
4064 runData->dig_time += dtime;
4066 runData->dig_time = 0;
4067 client->setCrack(-1, nodepos);
4070 camera->setDigging(0); // left click animation
4074 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4075 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4076 const CameraOrientation &cam)
4078 LocalPlayer *player = client->getEnv().getLocalPlayer();
4084 if (draw_control->range_all) {
4085 runData->fog_range = 100000 * BS;
4087 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
4091 Calculate general brightness
4093 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4094 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4095 float direct_brightness;
4098 if (g_settings->getBool("free_move")) {
4099 direct_brightness = time_brightness;
4100 sunlight_seen = true;
4102 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4103 float old_brightness = sky->getBrightness();
4104 direct_brightness = client->getEnv().getClientMap()
4105 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4106 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4110 float time_of_day = runData->time_of_day;
4111 float time_of_day_smooth = runData->time_of_day_smooth;
4113 time_of_day = client->getEnv().getTimeOfDayF();
4115 const float maxsm = 0.05;
4116 const float todsm = 0.05;
4118 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4119 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4120 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4121 time_of_day_smooth = time_of_day;
4123 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4124 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4125 + (time_of_day + 1.0) * todsm;
4127 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4128 + time_of_day * todsm;
4130 runData->time_of_day = time_of_day;
4131 runData->time_of_day_smooth = time_of_day_smooth;
4133 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4134 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4135 player->getPitch());
4141 v3f player_position = player->getPosition();
4142 if (sky->getCloudsVisible()) {
4143 clouds->setVisible(true);
4144 clouds->step(dtime);
4145 clouds->update(v2f(player_position.X, player_position.Z),
4146 sky->getCloudColor());
4148 clouds->setVisible(false);
4155 client->getParticleManager()->step(dtime);
4161 if (m_cache_enable_fog && !flags.force_fog_off) {
4164 video::EFT_FOG_LINEAR,
4165 runData->fog_range * 0.4,
4166 runData->fog_range * 1.0,
4174 video::EFT_FOG_LINEAR,
4184 Get chat messages from client
4187 v2u32 screensize = driver->getScreenSize();
4189 updateChat(*client, dtime, flags.show_debug, screensize,
4190 flags.show_chat, runData->profiler_current_page,
4191 *chat_backend, guitext_chat);
4197 if (client->getPlayerItem() != runData->new_playeritem)
4198 client->selectPlayerItem(runData->new_playeritem);
4200 // Update local inventory if it has changed
4201 if (client->getLocalInventoryUpdated()) {
4202 //infostream<<"Updating local inventory"<<std::endl;
4203 client->getLocalInventory(*local_inventory);
4204 runData->update_wielded_item_trigger = true;
4207 if (runData->update_wielded_item_trigger) {
4208 // Update wielded tool
4209 InventoryList *mlist = local_inventory->getList("main");
4211 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4212 ItemStack item = mlist->getItem(client->getPlayerItem());
4213 camera->wield(item);
4215 runData->update_wielded_item_trigger = false;
4219 Update block draw list every 200ms or when camera direction has
4222 runData->update_draw_list_timer += dtime;
4224 v3f camera_direction = camera->getDirection();
4225 if (runData->update_draw_list_timer >= 0.2
4226 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4227 || flags.camera_offset_changed) {
4228 runData->update_draw_list_timer = 0;
4229 client->getEnv().getClientMap().updateDrawList(driver);
4230 runData->update_draw_list_last_cam_dir = camera_direction;
4233 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4236 make sure menu is on top
4237 1. Delete formspec menu reference if menu was removed
4238 2. Else, make sure formspec menu is on top
4240 if (current_formspec) {
4241 if (current_formspec->getReferenceCount() == 1) {
4242 current_formspec->drop();
4243 current_formspec = NULL;
4244 } else if (!noMenuActive()) {
4245 guiroot->bringToFront(current_formspec);
4253 video::SColor skycolor = sky->getSkyColor();
4255 TimeTaker tt_draw("mainloop: draw");
4257 TimeTaker timer("beginScene");
4258 driver->beginScene(true, true, skycolor);
4259 stats->beginscenetime = timer.stop(true);
4262 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4263 guienv, screensize, skycolor, flags.show_hud,
4264 flags.show_minimap);
4269 if (flags.show_profiler_graph)
4270 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4275 if (runData->damage_flash > 0.0) {
4276 video::SColor color(std::min(runData->damage_flash, 180.0f),
4280 driver->draw2DRectangle(color,
4281 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4284 runData->damage_flash -= 100.0 * dtime;
4290 if (player->hurt_tilt_timer > 0.0) {
4291 player->hurt_tilt_timer -= dtime * 5;
4293 if (player->hurt_tilt_timer < 0)
4294 player->hurt_tilt_strength = 0;
4298 Update minimap pos and rotation
4300 if (flags.show_minimap && flags.show_hud) {
4301 mapper->setPos(floatToInt(player->getPosition(), BS));
4302 mapper->setAngle(player->getYaw());
4309 TimeTaker timer("endScene");
4311 stats->endscenetime = timer.stop(true);
4314 stats->drawtime = tt_draw.stop(true);
4315 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4319 inline static const char *yawToDirectionString(int yaw)
4321 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4323 yaw = wrapDegrees_0_360(yaw);
4324 yaw = (yaw + 45) % 360 / 90;
4326 return direction[yaw];
4330 void Game::updateGui(float *statustext_time, const RunStats &stats,
4331 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4332 const CameraOrientation &cam)
4334 v2u32 screensize = driver->getScreenSize();
4335 LocalPlayer *player = client->getEnv().getLocalPlayer();
4336 v3f player_position = player->getPosition();
4338 if (flags.show_debug) {
4339 static float drawtime_avg = 0;
4340 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4342 u16 fps = 1.0 / stats.dtime_jitter.avg;
4343 //s32 fps = driver->getFPS();
4345 std::ostringstream os(std::ios_base::binary);
4347 << PROJECT_NAME_C " " << g_version_hash
4349 << " (R: range_all=" << draw_control->range_all << ")"
4350 << std::setprecision(0)
4351 << " drawtime = " << drawtime_avg
4352 << std::setprecision(1)
4353 << ", dtime_jitter = "
4354 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4355 << std::setprecision(1)
4356 << ", v_range = " << draw_control->wanted_range
4357 << std::setprecision(3)
4358 << ", RTT = " << client->getRTT();
4359 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4360 guitext->setVisible(true);
4362 guitext->setVisible(false);
4365 if (guitext->isVisible()) {
4366 core::rect<s32> rect(
4368 screensize.X, 5 + g_fontengine->getTextHeight()
4370 guitext->setRelativePosition(rect);
4373 if (flags.show_debug) {
4374 std::ostringstream os(std::ios_base::binary);
4375 os << std::setprecision(1) << std::fixed
4376 << "(" << (player_position.X / BS)
4377 << ", " << (player_position.Y / BS)
4378 << ", " << (player_position.Z / BS)
4379 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4380 << " " << yawToDirectionString(cam.camera_yaw)
4381 << ") (seed = " << ((u64)client->getMapSeed())
4384 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4385 ClientMap &map = client->getEnv().getClientMap();
4386 const INodeDefManager *nodedef = client->getNodeDefManager();
4387 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4388 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4389 const ContentFeatures &features = nodedef->get(n);
4390 os << " (pointing_at = " << nodedef->get(n).name
4391 << " - " << features.tiledef[0].name.c_str()
4396 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4397 guitext2->setVisible(true);
4399 core::rect<s32> rect(
4400 5, 5 + g_fontengine->getTextHeight(),
4401 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4403 guitext2->setRelativePosition(rect);
4405 guitext2->setVisible(false);
4408 setStaticText(guitext_info, infotext.c_str());
4409 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4411 float statustext_time_max = 1.5;
4413 if (!statustext.empty()) {
4414 *statustext_time += dtime;
4416 if (*statustext_time >= statustext_time_max) {
4418 *statustext_time = 0;
4422 setStaticText(guitext_status, statustext.c_str());
4423 guitext_status->setVisible(!statustext.empty());
4425 if (!statustext.empty()) {
4426 s32 status_width = guitext_status->getTextWidth();
4427 s32 status_height = guitext_status->getTextHeight();
4428 s32 status_y = screensize.Y - 150;
4429 s32 status_x = (screensize.X - status_width) / 2;
4430 core::rect<s32> rect(
4431 status_x , status_y - status_height,
4432 status_x + status_width, status_y
4434 guitext_status->setRelativePosition(rect);
4437 video::SColor initial_color(255, 0, 0, 0);
4439 if (guienv->getSkin())
4440 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4442 video::SColor final_color = initial_color;
4443 final_color.setAlpha(0);
4444 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4445 initial_color, final_color,
4446 pow(*statustext_time / statustext_time_max, 2.0f));
4447 guitext_status->setOverrideColor(fade_color);
4448 guitext_status->enableOverrideColor(true);
4453 /* Log times and stuff for visualization */
4454 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4456 Profiler::GraphValues values;
4457 g_profiler->graphGet(values);
4463 /****************************************************************************
4465 ****************************************************************************/
4467 /* On some computers framerate doesn't seem to be automatically limited
4469 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4471 // not using getRealTime is necessary for wine
4472 device->getTimer()->tick(); // Maker sure device time is up-to-date
4473 u32 time = device->getTimer()->getTime();
4474 u32 last_time = fps_timings->last_time;
4476 if (time > last_time) // Make sure time hasn't overflowed
4477 fps_timings->busy_time = time - last_time;
4479 fps_timings->busy_time = 0;
4481 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4482 ? g_settings->getFloat("pause_fps_max")
4483 : g_settings->getFloat("fps_max"));
4485 if (fps_timings->busy_time < frametime_min) {
4486 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4487 device->sleep(fps_timings->sleep_time);
4489 fps_timings->sleep_time = 0;
4492 /* Get the new value of the device timer. Note that device->sleep() may
4493 * not sleep for the entire requested time as sleep may be interrupted and
4494 * therefore it is arguably more accurate to get the new time from the
4495 * device rather than calculating it by adding sleep_time to time.
4498 device->getTimer()->tick(); // Update device timer
4499 time = device->getTimer()->getTime();
4501 if (time > last_time) // Make sure last_time hasn't overflowed
4502 *dtime = (time - last_time) / 1000.0;
4506 fps_timings->last_time = time;
4509 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4510 // pass a copy of it to this function
4511 // Note: \p msg must be allocated using new (not malloc())
4512 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4513 int percent, bool draw_clouds)
4515 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4519 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4521 ((Game *)data)->readSettings();
4524 void Game::readSettings()
4526 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4527 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4528 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4529 m_cache_enable_particles = g_settings->getBool("enable_particles");
4530 m_cache_enable_fog = g_settings->getBool("enable_fog");
4531 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4532 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4533 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4535 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4538 /****************************************************************************/
4539 /****************************************************************************
4541 ****************************************************************************/
4542 /****************************************************************************/
4544 void Game::extendedResourceCleanup()
4546 // Extended resource accounting
4547 infostream << "Irrlicht resources after cleanup:" << std::endl;
4548 infostream << "\tRemaining meshes : "
4549 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4550 infostream << "\tRemaining textures : "
4551 << driver->getTextureCount() << std::endl;
4553 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4554 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4555 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4559 clearTextureNameCache();
4560 infostream << "\tRemaining materials: "
4561 << driver-> getMaterialRendererCount()
4562 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4566 /****************************************************************************/
4567 /****************************************************************************
4568 extern function for launching the game
4569 ****************************************************************************/
4570 /****************************************************************************/
4572 void the_game(bool *kill,
4574 InputHandler *input,
4575 IrrlichtDevice *device,
4577 const std::string &map_dir,
4578 const std::string &playername,
4579 const std::string &password,
4580 const std::string &address, // If empty local server is created
4583 std::string &error_message,
4584 ChatBackend &chat_backend,
4585 bool *reconnect_requested,
4586 const SubgameSpec &gamespec, // Used for local game
4587 bool simple_singleplayer_mode)
4591 /* Make a copy of the server address because if a local singleplayer server
4592 * is created then this is updated and we don't want to change the value
4593 * passed to us by the calling function
4595 std::string server_address = address;
4599 if (game.startup(kill, random_input, input, device, map_dir,
4600 playername, password, &server_address, port, error_message,
4601 reconnect_requested, &chat_backend, gamespec,
4602 simple_singleplayer_mode)) {
4607 } catch (SerializationError &e) {
4608 error_message = std::string("A serialization error occurred:\n")
4609 + e.what() + "\n\nThe server is probably "
4610 " running a different version of " PROJECT_NAME_C ".";
4611 errorstream << error_message << std::endl;
4612 } catch (ServerError &e) {
4613 error_message = e.what();
4614 errorstream << "ServerError: " << error_message << std::endl;
4615 } catch (ModError &e) {
4616 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4617 errorstream << "ModError: " << error_message << std::endl;