3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/tile.h" // For TextureSource
26 #include "clientmap.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
43 #include "mainmenumanager.h"
45 #include "nodedef.h" // Needed for determining pointing to nodes
46 #include "nodemetadata.h"
47 #include "particles.h"
49 #include "quicktune_shortcutter.h"
52 #include "shader.h" // For ShaderSource
56 #include "util/directiontables.h"
57 #include "util/pointedthing.h"
60 #include "mapblock_mesh.h"
65 #include "sound_openal.h"
68 #ifdef HAVE_TOUCHSCREENGUI
69 #include "touchscreengui.h"
72 extern Settings *g_settings;
73 extern Profiler *g_profiler;
79 struct TextDestNodeMetadata : public TextDest {
80 TextDestNodeMetadata(v3s16 p, Client *client)
85 // This is deprecated I guess? -celeron55
86 void gotText(std::wstring text)
88 std::string ntext = wide_to_utf8(text);
89 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
90 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
92 fields["text"] = ntext;
93 m_client->sendNodemetaFields(m_p, "", fields);
95 void gotText(const StringMap &fields)
97 m_client->sendNodemetaFields(m_p, "", fields);
104 struct TextDestPlayerInventory : public TextDest {
105 TextDestPlayerInventory(Client *client)
110 TextDestPlayerInventory(Client *client, std::string formname)
113 m_formname = formname;
115 void gotText(const StringMap &fields)
117 m_client->sendInventoryFields(m_formname, fields);
123 struct LocalFormspecHandler : public TextDest {
124 LocalFormspecHandler();
125 LocalFormspecHandler(std::string formname) :
128 m_formname = formname;
131 LocalFormspecHandler(std::string formname, Client *client) :
134 m_formname = formname;
137 void gotText(std::wstring message)
139 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
142 void gotText(const StringMap &fields)
144 if (m_formname == "MT_PAUSE_MENU") {
145 if (fields.find("btn_sound") != fields.end()) {
146 g_gamecallback->changeVolume();
150 if (fields.find("btn_key_config") != fields.end()) {
151 g_gamecallback->keyConfig();
155 if (fields.find("btn_exit_menu") != fields.end()) {
156 g_gamecallback->disconnect();
160 if (fields.find("btn_exit_os") != fields.end()) {
161 g_gamecallback->exitToOS();
165 if (fields.find("btn_change_password") != fields.end()) {
166 g_gamecallback->changePassword();
170 if (fields.find("quit") != fields.end()) {
174 if (fields.find("btn_continue") != fields.end()) {
179 if (m_formname == "MT_CHAT_MENU") {
180 assert(m_client != 0);
182 if ((fields.find("btn_send") != fields.end()) ||
183 (fields.find("quit") != fields.end())) {
184 StringMap::const_iterator it = fields.find("f_text");
185 if (it != fields.end())
186 m_client->typeChatMessage(utf8_to_wide(it->second));
192 if (m_formname == "MT_DEATH_SCREEN") {
193 assert(m_client != 0);
195 if ((fields.find("btn_respawn") != fields.end())) {
196 m_client->sendRespawn();
200 if (fields.find("quit") != fields.end()) {
201 m_client->sendRespawn();
206 // don't show error message for unhandled cursor keys
207 if ((fields.find("key_up") != fields.end()) ||
208 (fields.find("key_down") != fields.end()) ||
209 (fields.find("key_left") != fields.end()) ||
210 (fields.find("key_right") != fields.end())) {
214 errorstream << "LocalFormspecHandler::gotText unhandled >"
215 << m_formname << "< event" << std::endl;
218 StringMap::const_iterator it;
219 for (it = fields.begin(); it != fields.end(); ++it) {
220 errorstream << "\t" << i << ": " << it->first
221 << "=" << it->second << std::endl;
229 /* Form update callback */
231 class NodeMetadataFormSource: public IFormSource
234 NodeMetadataFormSource(ClientMap *map, v3s16 p):
239 std::string getForm()
241 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
246 return meta->getString("formspec");
248 std::string resolveText(std::string str)
250 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
255 return meta->resolveString(str);
262 class PlayerInventoryFormSource: public IFormSource
265 PlayerInventoryFormSource(Client *client):
269 std::string getForm()
271 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
272 return player->inventory_formspec;
279 Check if a node is pointable
281 inline bool isPointableNode(const MapNode &n,
282 Client *client, bool liquids_pointable)
284 const ContentFeatures &features = client->getNodeDefManager()->get(n);
285 return features.pointable ||
286 (liquids_pointable && features.isLiquid());
290 Find what the player is pointing at
292 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
293 const v3f &camera_direction, const v3f &camera_position,
294 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
295 bool look_for_object, const v3s16 &camera_offset,
296 ClientActiveObject *&selected_object)
300 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
301 selectionboxes->clear();
302 selected_object = NULL;
304 INodeDefManager *nodedef = client->getNodeDefManager();
305 ClientMap &map = client->getEnv().getClientMap();
307 f32 mindistance = BS * 1001;
309 // First try to find a pointed at active object
310 if (look_for_object) {
311 selected_object = client->getSelectedActiveObject(d * BS,
312 camera_position, shootline);
314 if (selected_object != NULL) {
315 if (selected_object->doShowSelectionBox()) {
316 aabb3f *selection_box = selected_object->getSelectionBox();
317 // Box should exist because object was
318 // returned in the first place
319 assert(selection_box);
321 v3f pos = selected_object->getPosition();
322 selectionboxes->push_back(aabb3f(
323 selection_box->MinEdge, selection_box->MaxEdge));
324 hud->setSelectionPos(pos, camera_offset);
327 mindistance = (selected_object->getPosition() - camera_position).getLength();
329 result.type = POINTEDTHING_OBJECT;
330 result.object_id = selected_object->getId();
334 // That didn't work, try to find a pointed at node
337 v3s16 pos_i = floatToInt(player_position, BS);
339 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
343 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
344 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
345 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
346 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
347 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
348 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
350 // Prevent signed number overflow
360 for (s16 y = ystart; y <= yend; y++)
361 for (s16 z = zstart; z <= zend; z++)
362 for (s16 x = xstart; x <= xend; x++) {
364 bool is_valid_position;
366 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
367 if (!is_valid_position)
370 if (!isPointableNode(n, client, liquids_pointable))
373 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
376 v3f npf = intToFloat(np, BS);
378 for (std::vector<aabb3f>::const_iterator
380 i != boxes.end(); ++i) {
385 for (u16 j = 0; j < 6; j++) {
386 v3s16 facedir = g_6dirs[j];
387 aabb3f facebox = box;
392 facebox.MinEdge.X = facebox.MaxEdge.X - d;
393 else if (facedir.X < 0)
394 facebox.MaxEdge.X = facebox.MinEdge.X + d;
395 else if (facedir.Y > 0)
396 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
397 else if (facedir.Y < 0)
398 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
399 else if (facedir.Z > 0)
400 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
401 else if (facedir.Z < 0)
402 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
404 v3f centerpoint = facebox.getCenter();
405 f32 distance = (centerpoint - camera_position).getLength();
407 if (distance >= mindistance)
410 if (!facebox.intersectsWithLine(shootline))
413 v3s16 np_above = np + facedir;
415 result.type = POINTEDTHING_NODE;
416 result.node_undersurface = np;
417 result.node_abovesurface = np_above;
418 mindistance = distance;
420 selectionboxes->clear();
421 for (std::vector<aabb3f>::const_iterator
423 i2 != boxes.end(); ++i2) {
425 box.MinEdge += v3f(-d, -d, -d);
426 box.MaxEdge += v3f(d, d, d);
427 selectionboxes->push_back(box);
429 hud->setSelectionPos(npf, camera_offset);
434 // Update selection mesh light level and vertex colors
435 if (selectionboxes->size() > 0) {
436 v3f pf = hud->getSelectionPos();
437 v3s16 p = floatToInt(pf, BS);
439 // Get selection mesh light level
440 MapNode n = map.getNodeNoEx(p);
441 u16 node_light = getInteriorLight(n, -1, nodedef);
442 u16 light_level = node_light;
444 for (u8 i = 0; i < 6; i++) {
445 n = map.getNodeNoEx(p + g_6dirs[i]);
446 node_light = getInteriorLight(n, -1, nodedef);
447 if (node_light > light_level)
448 light_level = node_light;
451 video::SColor c = MapBlock_LightColor(255, light_level, 0);
453 u8 night = c.getGreen();
454 u32 daynight_ratio = client->getEnv().getDayNightRatio();
455 finalColorBlend(c, day, night, daynight_ratio);
457 // Modify final color a bit with time
458 u32 timer = porting::getTimeMs() % 5000;
459 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
460 float sin_r = 0.08 * sin(timerf);
461 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
462 float sin_b = 0.08 * sin(timerf + irr::core::PI);
463 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
464 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
465 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
467 // Set mesh final color
468 hud->setSelectionMeshColor(c);
473 /* Profiler display */
475 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
476 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
478 if (show_profiler == 0) {
479 guitext_profiler->setVisible(false);
482 std::ostringstream os(std::ios_base::binary);
483 g_profiler->printPage(os, show_profiler, show_profiler_max);
484 std::wstring text = utf8_to_wide(os.str());
485 guitext_profiler->setText(text.c_str());
486 guitext_profiler->setVisible(true);
488 s32 w = fe->getTextWidth(text.c_str());
493 unsigned text_height = fe->getTextHeight();
495 core::position2di upper_left, lower_right;
498 upper_left.Y = (text_height + 5) * 2;
499 lower_right.X = 12 + w;
500 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
502 if (lower_right.Y > screen_height * 2 / 3)
503 lower_right.Y = screen_height * 2 / 3;
505 core::rect<s32> rect(upper_left, lower_right);
507 guitext_profiler->setRelativePosition(rect);
508 guitext_profiler->setVisible(true);
516 Profiler::GraphValues values;
522 Meta(float initial = 0,
523 video::SColor color = video::SColor(255, 255, 255, 255)):
529 std::deque<Piece> m_log;
537 void put(const Profiler::GraphValues &values)
540 piece.values = values;
541 m_log.push_back(piece);
543 while (m_log.size() > m_log_max_size)
544 m_log.erase(m_log.begin());
547 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
548 gui::IGUIFont *font) const
550 std::map<std::string, Meta> m_meta;
552 for (std::deque<Piece>::const_iterator k = m_log.begin();
553 k != m_log.end(); ++k) {
554 const Piece &piece = *k;
556 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
557 i != piece.values.end(); ++i) {
558 const std::string &id = i->first;
559 const float &value = i->second;
560 std::map<std::string, Meta>::iterator j =
563 if (j == m_meta.end()) {
564 m_meta[id] = Meta(value);
568 if (value < j->second.min)
569 j->second.min = value;
571 if (value > j->second.max)
572 j->second.max = value;
577 static const video::SColor usable_colors[] = {
578 video::SColor(255, 255, 100, 100),
579 video::SColor(255, 90, 225, 90),
580 video::SColor(255, 100, 100, 255),
581 video::SColor(255, 255, 150, 50),
582 video::SColor(255, 220, 220, 100)
584 static const u32 usable_colors_count =
585 sizeof(usable_colors) / sizeof(*usable_colors);
586 u32 next_color_i = 0;
588 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
589 i != m_meta.end(); ++i) {
590 Meta &meta = i->second;
591 video::SColor color(255, 200, 200, 200);
593 if (next_color_i < usable_colors_count)
594 color = usable_colors[next_color_i++];
600 s32 textx = x_left + m_log_max_size + 15;
601 s32 textx2 = textx + 200 - 15;
604 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
605 i != m_meta.end(); ++i) {
606 const std::string &id = i->first;
607 const Meta &meta = i->second;
609 s32 y = y_bottom - meta_i * 50;
610 float show_min = meta.min;
611 float show_max = meta.max;
613 if (show_min >= -0.0001 && show_max >= -0.0001) {
614 if (show_min <= show_max * 0.5)
620 snprintf(buf, 10, "%.3g", show_max);
621 font->draw(utf8_to_wide(buf).c_str(),
622 core::rect<s32>(textx, y - graphh,
623 textx2, y - graphh + texth),
625 snprintf(buf, 10, "%.3g", show_min);
626 font->draw(utf8_to_wide(buf).c_str(),
627 core::rect<s32>(textx, y - texth,
630 font->draw(utf8_to_wide(id).c_str(),
631 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
632 textx2, y - graphh / 2 + texth / 2),
635 s32 graph1h = graphh;
636 bool relativegraph = (show_min != 0 && show_min != show_max);
637 float lastscaledvalue = 0.0;
638 bool lastscaledvalue_exists = false;
640 for (std::deque<Piece>::const_iterator j = m_log.begin();
641 j != m_log.end(); ++j) {
642 const Piece &piece = *j;
644 bool value_exists = false;
645 Profiler::GraphValues::const_iterator k =
646 piece.values.find(id);
648 if (k != piece.values.end()) {
655 lastscaledvalue_exists = false;
659 float scaledvalue = 1.0;
661 if (show_max != show_min)
662 scaledvalue = (value - show_min) / (show_max - show_min);
664 if (scaledvalue == 1.0 && value == 0) {
666 lastscaledvalue_exists = false;
671 if (lastscaledvalue_exists) {
672 s32 ivalue1 = lastscaledvalue * graph1h;
673 s32 ivalue2 = scaledvalue * graph1h;
674 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
675 v2s32(x, graph1y - ivalue2), meta.color);
678 lastscaledvalue = scaledvalue;
679 lastscaledvalue_exists = true;
681 s32 ivalue = scaledvalue * graph1h;
682 driver->draw2DLine(v2s32(x, graph1y),
683 v2s32(x, graph1y - ivalue), meta.color);
694 class NodeDugEvent: public MtEvent
700 NodeDugEvent(v3s16 p, MapNode n):
704 const char *getType() const
712 ISoundManager *m_sound;
713 INodeDefManager *m_ndef;
715 float m_player_step_timer;
717 SimpleSoundSpec m_player_step_sound;
718 SimpleSoundSpec m_player_leftpunch_sound;
719 SimpleSoundSpec m_player_rightpunch_sound;
721 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
724 m_player_step_timer(0)
728 void playPlayerStep()
730 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
731 m_player_step_timer = 0.03;
732 m_sound->playSound(m_player_step_sound, false);
736 static void viewBobbingStep(MtEvent *e, void *data)
738 SoundMaker *sm = (SoundMaker *)data;
739 sm->playPlayerStep();
742 static void playerRegainGround(MtEvent *e, void *data)
744 SoundMaker *sm = (SoundMaker *)data;
745 sm->playPlayerStep();
748 static void playerJump(MtEvent *e, void *data)
750 //SoundMaker *sm = (SoundMaker*)data;
753 static void cameraPunchLeft(MtEvent *e, void *data)
755 SoundMaker *sm = (SoundMaker *)data;
756 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
759 static void cameraPunchRight(MtEvent *e, void *data)
761 SoundMaker *sm = (SoundMaker *)data;
762 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
765 static void nodeDug(MtEvent *e, void *data)
767 SoundMaker *sm = (SoundMaker *)data;
768 NodeDugEvent *nde = (NodeDugEvent *)e;
769 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
772 static void playerDamage(MtEvent *e, void *data)
774 SoundMaker *sm = (SoundMaker *)data;
775 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
778 static void playerFallingDamage(MtEvent *e, void *data)
780 SoundMaker *sm = (SoundMaker *)data;
781 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
784 void registerReceiver(MtEventManager *mgr)
786 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
787 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
788 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
789 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
790 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
791 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
792 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
793 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
796 void step(float dtime)
798 m_player_step_timer -= dtime;
802 // Locally stored sounds don't need to be preloaded because of this
803 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
805 std::set<std::string> m_fetched;
807 void fetchSounds(const std::string &name,
808 std::set<std::string> &dst_paths,
809 std::set<std::string> &dst_datas)
811 if (m_fetched.count(name))
814 m_fetched.insert(name);
815 std::string base = porting::path_share + DIR_DELIM + "testsounds";
816 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
817 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
818 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
819 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
820 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
821 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
822 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
823 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
824 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
825 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
826 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
830 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
833 bool *m_force_fog_off;
839 void onSettingsChange(const std::string &name)
841 if (name == "enable_fog")
842 m_fogEnabled = g_settings->getBool("enable_fog");
845 static void SettingsCallback(const std::string &name, void *userdata)
847 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
850 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
851 f32 *fog_range, Client *client) :
853 m_force_fog_off(force_fog_off),
854 m_fog_range(fog_range),
857 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
858 m_fogEnabled = g_settings->getBool("enable_fog");
861 ~GameGlobalShaderConstantSetter()
863 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
866 virtual void onSetConstants(video::IMaterialRendererServices *services,
873 video::SColor bgcolor = m_sky->getBgColor();
874 video::SColorf bgcolorf(bgcolor);
875 float bgcolorfa[4] = {
881 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
884 float fog_distance = 10000 * BS;
886 if (m_fogEnabled && !*m_force_fog_off)
887 fog_distance = *m_fog_range;
889 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
892 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
893 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
894 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
896 u32 animation_timer = porting::getTimeMs() % 100000;
897 float animation_timer_f = (float)animation_timer / 100000.0;
898 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
899 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
901 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
902 v3f eye_position = player->getEyePosition();
903 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
904 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
906 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
907 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
909 // Uniform sampler layers
910 // before 1.8 there isn't a "integer interface", only float
911 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
915 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
916 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
917 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
922 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
923 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
924 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
929 bool nodePlacementPrediction(Client &client,
930 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
932 std::string prediction = playeritem_def.node_placement_prediction;
933 INodeDefManager *nodedef = client.ndef();
934 ClientMap &map = client.getEnv().getClientMap();
936 bool is_valid_position;
938 node = map.getNodeNoEx(nodepos, &is_valid_position);
939 if (!is_valid_position)
942 if (prediction != "" && !nodedef->get(node).rightclickable) {
943 verbosestream << "Node placement prediction for "
944 << playeritem_def.name << " is "
945 << prediction << std::endl;
946 v3s16 p = neighbourpos;
948 // Place inside node itself if buildable_to
949 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
950 if (is_valid_position)
952 if (nodedef->get(n_under).buildable_to)
955 node = map.getNodeNoEx(p, &is_valid_position);
956 if (is_valid_position &&!nodedef->get(node).buildable_to)
961 // Find id of predicted node
963 bool found = nodedef->getId(prediction, id);
966 errorstream << "Node placement prediction failed for "
967 << playeritem_def.name << " (places "
969 << ") - Name not known" << std::endl;
973 // Predict param2 for facedir and wallmounted nodes
976 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
977 v3s16 dir = nodepos - neighbourpos;
979 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
980 param2 = dir.Y < 0 ? 1 : 0;
981 } else if (abs(dir.X) > abs(dir.Z)) {
982 param2 = dir.X < 0 ? 3 : 2;
984 param2 = dir.Z < 0 ? 5 : 4;
988 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
989 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
991 if (abs(dir.X) > abs(dir.Z)) {
992 param2 = dir.X < 0 ? 3 : 1;
994 param2 = dir.Z < 0 ? 2 : 0;
1000 //Check attachment if node is in group attached_node
1001 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1002 static v3s16 wallmounted_dirs[8] = {
1012 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1013 pp = p + wallmounted_dirs[param2];
1015 pp = p + v3s16(0, -1, 0);
1017 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1021 // Add node to client map
1022 MapNode n(id, 0, param2);
1025 LocalPlayer *player = client.getEnv().getLocalPlayer();
1027 // Dont place node when player would be inside new node
1028 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1029 if (!nodedef->get(n).walkable ||
1030 g_settings->getBool("enable_build_where_you_stand") ||
1031 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1032 (nodedef->get(n).walkable &&
1033 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1034 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1036 // This triggers the required mesh update too
1037 client.addNode(p, n);
1040 } catch (InvalidPositionException &e) {
1041 errorstream << "Node placement prediction failed for "
1042 << playeritem_def.name << " (places "
1044 << ") - Position not loaded" << std::endl;
1051 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1052 InventoryManager *invmgr, IGameDef *gamedef,
1053 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1054 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1057 if (*cur_formspec == 0) {
1058 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1059 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1060 (*cur_formspec)->doPause = false;
1063 Caution: do not call (*cur_formspec)->drop() here --
1064 the reference might outlive the menu, so we will
1065 periodically check if *cur_formspec is the only
1066 remaining reference (i.e. the menu was removed)
1067 and delete it in that case.
1071 (*cur_formspec)->setFormSource(fs_src);
1072 (*cur_formspec)->setTextDest(txt_dest);
1077 #define SIZE_TAG "size[11,5.5]"
1079 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1082 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1083 InventoryManager *invmgr, IGameDef *gamedef,
1084 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1085 Client *client, std::string text)
1087 std::string formspec =
1088 FORMSPEC_VERSION_STRING
1090 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1091 "button_exit[4,3;3,0.5;btn_send;" + strgettext("Proceed") + "]"
1095 /* Note: FormspecFormSource and LocalFormspecHandler
1096 * are deleted by guiFormSpecMenu */
1097 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1098 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1100 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1103 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1104 InventoryManager *invmgr, IGameDef *gamedef,
1105 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1107 std::string formspec =
1108 std::string(FORMSPEC_VERSION_STRING) +
1110 "bgcolor[#320000b4;true]"
1111 "label[4.85,1.35;" + gettext("You died.") + "]"
1112 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1116 /* Note: FormspecFormSource and LocalFormspecHandler
1117 * are deleted by guiFormSpecMenu */
1118 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1119 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1121 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1124 /******************************************************************************/
1125 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1126 InventoryManager *invmgr, IGameDef *gamedef,
1127 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1128 bool singleplayermode)
1131 std::string control_text = strgettext("Default Controls:\n"
1132 "No menu visible:\n"
1133 "- single tap: button activate\n"
1134 "- double tap: place/use\n"
1135 "- slide finger: look around\n"
1136 "Menu/Inventory visible:\n"
1137 "- double tap (outside):\n"
1139 "- touch stack, touch slot:\n"
1141 "- touch&drag, tap 2nd finger\n"
1142 " --> place single item to slot\n"
1145 std::string control_text = strgettext("Default Controls:\n"
1147 "- Space: jump/climb\n"
1148 "- Shift: sneak/go down\n"
1151 "- Mouse: turn/look\n"
1152 "- Mouse left: dig/punch\n"
1153 "- Mouse right: place/use\n"
1154 "- Mouse wheel: select item\n"
1159 float ypos = singleplayermode ? 0.5 : 0.1;
1160 std::ostringstream os;
1162 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1163 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1164 << strgettext("Continue") << "]";
1166 if (!singleplayermode) {
1167 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1168 << strgettext("Change Password") << "]";
1172 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1173 << strgettext("Sound Volume") << "]";
1174 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1175 << strgettext("Change Keys") << "]";
1177 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1178 << strgettext("Exit to Menu") << "]";
1179 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1180 << strgettext("Exit to OS") << "]"
1181 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1182 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1183 << g_build_info << "\n"
1184 << "path_user = " << wrap_rows(porting::path_user, 20)
1188 /* Note: FormspecFormSource and LocalFormspecHandler *
1189 * are deleted by guiFormSpecMenu */
1190 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1191 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1193 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1194 std::string con("btn_continue");
1195 (*cur_formspec)->setFocus(con);
1196 (*cur_formspec)->doPause = true;
1199 /******************************************************************************/
1200 static void updateChat(Client &client, f32 dtime, bool show_debug,
1201 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1202 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1204 // Add chat log output for errors to be shown in chat
1205 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1207 // Get new messages from error log buffer
1208 while (!chat_log_error_buf.empty()) {
1209 chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get()));
1212 // Get new messages from client
1213 std::wstring message;
1215 while (client.getChatMessage(message)) {
1216 chat_backend.addUnparsedMessage(message);
1219 // Remove old messages
1220 chat_backend.step(dtime);
1222 // Display all messages in a static text element
1223 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1224 std::wstring recent_chat = chat_backend.getRecentChat();
1225 unsigned int line_height = g_fontengine->getLineHeight();
1227 guitext_chat->setText(recent_chat.c_str());
1229 // Update gui element size and position
1230 s32 chat_y = 5 + line_height;
1233 chat_y += line_height;
1235 // first pass to calculate height of text to be set
1236 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1237 porting::getWindowSize().X - 20);
1238 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1239 guitext_chat->setRelativePosition(rect);
1241 //now use real height of text and adjust rect according to this size
1242 rect = core::rect<s32>(10, chat_y, width,
1243 chat_y + guitext_chat->getTextHeight());
1246 guitext_chat->setRelativePosition(rect);
1247 // Don't show chat if disabled or empty or profiler is enabled
1248 guitext_chat->setVisible(
1249 show_chat && recent_chat_count != 0 && !show_profiler);
1253 /****************************************************************************
1254 Fast key cache for main game loop
1255 ****************************************************************************/
1257 /* This is faster than using getKeySetting with the tradeoff that functions
1258 * using it must make sure that it's initialised before using it and there is
1259 * no error handling (for example bounds checking). This is really intended for
1260 * use only in the main running loop of the client (the_game()) where the faster
1261 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1262 * (e.g. formspecs) should continue using getKeySetting().
1266 KeyCache() { populate(); }
1281 KEYMAP_ID_INVENTORY,
1289 KEYMAP_ID_CINEMATIC,
1290 KEYMAP_ID_SCREENSHOT,
1291 KEYMAP_ID_TOGGLE_HUD,
1292 KEYMAP_ID_TOGGLE_CHAT,
1293 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1294 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1295 KEYMAP_ID_TOGGLE_DEBUG,
1296 KEYMAP_ID_TOGGLE_PROFILER,
1297 KEYMAP_ID_CAMERA_MODE,
1298 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1299 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1300 KEYMAP_ID_RANGESELECT,
1302 KEYMAP_ID_QUICKTUNE_NEXT,
1303 KEYMAP_ID_QUICKTUNE_PREV,
1304 KEYMAP_ID_QUICKTUNE_INC,
1305 KEYMAP_ID_QUICKTUNE_DEC,
1307 KEYMAP_ID_DEBUG_STACKS,
1309 // Fake keycode for array size and internal checks
1310 KEYMAP_INTERNAL_ENUM_COUNT
1317 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1320 void KeyCache::populate()
1322 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1323 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1324 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1325 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1326 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1327 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1328 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1330 key[KEYMAP_ID_AUTORUN] = getKeySetting("keymap_autorun");
1332 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1333 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1334 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1335 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1336 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1337 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1338 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1339 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1340 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1341 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1342 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1343 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1344 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1345 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1346 = getKeySetting("keymap_toggle_force_fog_off");
1347 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1348 = getKeySetting("keymap_toggle_update_camera");
1349 key[KEYMAP_ID_TOGGLE_DEBUG]
1350 = getKeySetting("keymap_toggle_debug");
1351 key[KEYMAP_ID_TOGGLE_PROFILER]
1352 = getKeySetting("keymap_toggle_profiler");
1353 key[KEYMAP_ID_CAMERA_MODE]
1354 = getKeySetting("keymap_camera_mode");
1355 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1356 = getKeySetting("keymap_increase_viewing_range_min");
1357 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1358 = getKeySetting("keymap_decrease_viewing_range_min");
1359 key[KEYMAP_ID_RANGESELECT]
1360 = getKeySetting("keymap_rangeselect");
1362 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1363 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1364 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1365 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1367 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1371 /****************************************************************************
1373 ****************************************************************************/
1375 const float object_hit_delay = 0.2;
1378 u32 last_time, busy_time, sleep_time;
1382 /* The reason the following structs are not anonymous structs within the
1383 * class is that they are not used by the majority of member functions and
1384 * many functions that do require objects of thse types do not modify them
1385 * (so they can be passed as a const qualified parameter)
1387 struct CameraOrientation {
1388 f32 camera_yaw; // "right/left"
1389 f32 camera_pitch; // "up/down"
1392 struct GameRunData {
1395 PointedThing pointed_old;
1399 bool update_wielded_item_trigger;
1400 bool reset_jump_timer;
1401 float nodig_delay_timer;
1403 float dig_time_complete;
1404 float repeat_rightclick_timer;
1405 float object_hit_delay_timer;
1406 float time_from_last_punch;
1407 ClientActiveObject *selected_object;
1411 float update_draw_list_timer;
1412 float statustext_time;
1416 v3f update_draw_list_last_cam_dir;
1418 u32 profiler_current_page;
1419 u32 profiler_max_page; // Number of pages
1422 float time_of_day_smooth;
1426 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1434 Jitter dtime_jitter, busy_time_jitter;
1437 /* Flags that can, or may, change during main game loop
1439 struct VolatileRunFlags {
1446 bool show_profiler_graph;
1447 bool disable_camera_update;
1448 bool first_loop_after_window_activation;
1449 bool camera_offset_changed;
1453 /****************************************************************************
1455 ****************************************************************************/
1457 /* This is not intended to be a public class. If a public class becomes
1458 * desirable then it may be better to create another 'wrapper' class that
1459 * hides most of the stuff in this class (nothing in this class is required
1460 * by any other file) but exposes the public methods/data only.
1467 bool startup(bool *kill,
1469 InputHandler *input,
1470 IrrlichtDevice *device,
1471 const std::string &map_dir,
1472 const std::string &playername,
1473 const std::string &password,
1474 // If address is "", local server is used and address is updated
1475 std::string *address,
1477 std::string &error_message,
1479 ChatBackend *chat_backend,
1480 const SubgameSpec &gamespec, // Used for local game
1481 bool simple_singleplayer_mode);
1488 void extendedResourceCleanup();
1490 // Basic initialisation
1491 bool init(const std::string &map_dir, std::string *address,
1493 const SubgameSpec &gamespec);
1495 bool createSingleplayerServer(const std::string map_dir,
1496 const SubgameSpec &gamespec, u16 port, std::string *address);
1499 bool createClient(const std::string &playername,
1500 const std::string &password, std::string *address, u16 port);
1503 // Client connection
1504 bool connectToServer(const std::string &playername,
1505 const std::string &password, std::string *address, u16 port,
1506 bool *connect_ok, bool *aborted);
1507 bool getServerContent(bool *aborted);
1511 void updateInteractTimers(GameRunData *runData, f32 dtime);
1512 bool checkConnection();
1513 bool handleCallbacks();
1514 void processQueues();
1515 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1516 const FpsControl &draw_times, f32 dtime);
1517 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1519 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1521 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1523 void processKeyboardInput(VolatileRunFlags *flags,
1524 float *statustext_time,
1526 bool *reset_jump_timer,
1527 u32 *profiler_current_page,
1528 u32 profiler_max_page);
1529 void processItemSelection(u16 *new_playeritem);
1531 void dropSelectedItem();
1532 void openInventory();
1534 void toggleFreeMove(float *statustext_time);
1535 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1536 void toggleFast(float *statustext_time);
1537 void toggleNoClip(float *statustext_time);
1538 void toggleCinematic(float *statustext_time);
1539 void toggleAutorun(float *statustext_time);
1541 void toggleChat(float *statustext_time, bool *flag);
1542 void toggleHud(float *statustext_time, bool *flag);
1543 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1544 bool shift_pressed);
1545 void toggleFog(float *statustext_time, bool *flag);
1546 void toggleDebug(float *statustext_time, bool *show_debug,
1547 bool *show_profiler_graph);
1548 void toggleUpdateCamera(float *statustext_time, bool *flag);
1549 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1550 u32 profiler_max_page);
1552 void increaseViewRange(float *statustext_time);
1553 void decreaseViewRange(float *statustext_time);
1554 void toggleFullViewRange(float *statustext_time);
1556 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1557 void updateCameraOrientation(CameraOrientation *cam,
1558 const VolatileRunFlags &flags);
1559 void updatePlayerControl(const CameraOrientation &cam);
1560 void step(f32 *dtime);
1561 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1562 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1563 float time_from_last_punch);
1564 void updateSound(f32 dtime);
1565 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1567 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1568 void handlePointingAtNode(GameRunData *runData,
1569 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1570 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1571 void handlePointingAtObject(GameRunData *runData,
1572 const PointedThing &pointed, const ItemStack &playeritem,
1573 const v3f &player_position, bool show_debug);
1574 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1575 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1577 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1578 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1579 void updateGui(float *statustext_time, const RunStats &stats,
1580 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1581 const CameraOrientation &cam);
1582 void updateProfilerGraphs(ProfilerGraph *graph);
1585 void limitFps(FpsControl *fps_timings, f32 *dtime);
1587 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1588 bool draw_clouds = true);
1590 static void settingChangedCallback(const std::string &setting_name, void *data);
1591 void readSettings();
1594 InputHandler *input;
1599 IWritableTextureSource *texture_src;
1600 IWritableShaderSource *shader_src;
1602 // When created, these will be filled with data received from the server
1603 IWritableItemDefManager *itemdef_manager;
1604 IWritableNodeDefManager *nodedef_manager;
1606 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1607 ISoundManager *sound;
1608 bool sound_is_dummy;
1609 SoundMaker *soundmaker;
1611 ChatBackend *chat_backend;
1613 GUIFormSpecMenu *current_formspec;
1615 EventManager *eventmgr;
1616 QuicktuneShortcutter *quicktune;
1618 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1619 MapDrawControl *draw_control;
1621 Clouds *clouds; // Free using ->Drop()
1622 Sky *sky; // Free using ->Drop()
1623 Inventory *local_inventory;
1628 This class does take ownership/responsibily for cleaning up etc of any of
1629 these items (e.g. device)
1631 IrrlichtDevice *device;
1632 video::IVideoDriver *driver;
1633 scene::ISceneManager *smgr;
1635 std::string *error_message;
1636 bool *reconnect_requested;
1637 IGameDef *gamedef; // Convenience (same as *client)
1638 scene::ISceneNode *skybox;
1641 bool simple_singleplayer_mode;
1644 /* Pre-calculated values
1646 int crack_animation_length;
1650 gui::IGUIStaticText *guitext; // First line of debug text
1651 gui::IGUIStaticText *guitext2; // Second line of debug text
1652 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1653 gui::IGUIStaticText *guitext_status;
1654 gui::IGUIStaticText *guitext_chat; // Chat text
1655 gui::IGUIStaticText *guitext_profiler; // Profiler text
1657 std::wstring infotext;
1658 std::wstring statustext;
1662 IntervalLimiter profiler_interval;
1665 * TODO: Local caching of settings is not optimal and should at some stage
1666 * be updated to use a global settings object for getting thse values
1667 * (as opposed to the this local caching). This can be addressed in
1670 bool m_cache_doubletap_jump;
1671 bool m_cache_enable_clouds;
1672 bool m_cache_enable_particles;
1673 bool m_cache_enable_fog;
1674 f32 m_cache_mouse_sensitivity;
1675 f32 m_repeat_right_click_time;
1678 bool m_cache_hold_aux1;
1688 itemdef_manager(NULL),
1689 nodedef_manager(NULL),
1691 sound_is_dummy(false),
1694 current_formspec(NULL),
1697 gui_chat_console(NULL),
1702 local_inventory(NULL),
1706 g_settings->registerChangedCallback("doubletap_jump",
1707 &settingChangedCallback, this);
1708 g_settings->registerChangedCallback("enable_clouds",
1709 &settingChangedCallback, this);
1710 g_settings->registerChangedCallback("enable_particles",
1711 &settingChangedCallback, this);
1712 g_settings->registerChangedCallback("enable_fog",
1713 &settingChangedCallback, this);
1714 g_settings->registerChangedCallback("mouse_sensitivity",
1715 &settingChangedCallback, this);
1716 g_settings->registerChangedCallback("repeat_rightclick_time",
1717 &settingChangedCallback, this);
1722 m_cache_hold_aux1 = false; // This is initialised properly later
1729 /****************************************************************************
1731 ****************************************************************************/
1737 if (!sound_is_dummy)
1740 delete server; // deleted first to stop all server threads
1743 delete local_inventory;
1749 delete nodedef_manager;
1750 delete itemdef_manager;
1751 delete draw_control;
1753 extendedResourceCleanup();
1755 g_settings->deregisterChangedCallback("doubletap_jump",
1756 &settingChangedCallback, this);
1757 g_settings->deregisterChangedCallback("enable_clouds",
1758 &settingChangedCallback, this);
1759 g_settings->deregisterChangedCallback("enable_particles",
1760 &settingChangedCallback, this);
1761 g_settings->deregisterChangedCallback("enable_fog",
1762 &settingChangedCallback, this);
1763 g_settings->deregisterChangedCallback("mouse_sensitivity",
1764 &settingChangedCallback, this);
1765 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1766 &settingChangedCallback, this);
1769 bool Game::startup(bool *kill,
1771 InputHandler *input,
1772 IrrlichtDevice *device,
1773 const std::string &map_dir,
1774 const std::string &playername,
1775 const std::string &password,
1776 std::string *address, // can change if simple_singleplayer_mode
1778 std::string &error_message,
1780 ChatBackend *chat_backend,
1781 const SubgameSpec &gamespec,
1782 bool simple_singleplayer_mode)
1785 this->device = device;
1787 this->error_message = &error_message;
1788 this->reconnect_requested = reconnect;
1789 this->random_input = random_input;
1790 this->input = input;
1791 this->chat_backend = chat_backend;
1792 this->simple_singleplayer_mode = simple_singleplayer_mode;
1794 driver = device->getVideoDriver();
1795 smgr = device->getSceneManager();
1797 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1799 if (!init(map_dir, address, port, gamespec))
1802 if (!createClient(playername, password, address, port))
1811 ProfilerGraph graph;
1812 RunStats stats = { 0 };
1813 CameraOrientation cam_view_target = { 0 };
1814 CameraOrientation cam_view = { 0 };
1815 GameRunData runData = { 0 };
1816 FpsControl draw_times = { 0 };
1817 VolatileRunFlags flags = { 0 };
1818 f32 dtime; // in seconds
1820 runData.time_from_last_punch = 10.0;
1821 runData.profiler_max_page = 3;
1822 runData.update_wielded_item_trigger = true;
1824 flags.show_chat = true;
1825 flags.show_hud = true;
1826 flags.show_minimap = g_settings->getBool("enable_minimap");
1827 flags.show_debug = g_settings->getBool("show_debug");
1828 flags.invert_mouse = g_settings->getBool("invert_mouse");
1829 flags.first_loop_after_window_activation = true;
1831 /* Clear the profiler */
1832 Profiler::GraphValues dummyvalues;
1833 g_profiler->graphGet(dummyvalues);
1835 draw_times.last_time = device->getTimer()->getTime();
1837 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1839 &flags.force_fog_off,
1843 set_light_table(g_settings->getFloat("display_gamma"));
1846 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1847 && client->checkPrivilege("fast");
1850 while (device->run()
1851 && !(*kill || g_gamecallback->shutdown_requested
1852 || (server && server->getShutdownRequested()))) {
1854 /* Must be called immediately after a device->run() call because it
1855 * uses device->getTimer()->getTime()
1857 limitFps(&draw_times, &dtime);
1859 updateStats(&stats, draw_times, dtime);
1860 updateInteractTimers(&runData, dtime);
1862 if (!checkConnection())
1864 if (!handleCallbacks())
1870 hud->resizeHotbar();
1872 updateProfilers(runData, stats, draw_times, dtime);
1873 processUserInput(&flags, &runData, dtime);
1874 // Update camera before player movement to avoid camera lag of one frame
1875 updateCameraDirection(&cam_view_target, &flags);
1876 float cam_smoothing = 0;
1877 if (g_settings->getBool("cinematic"))
1878 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1880 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1881 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1882 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1883 cam_view.camera_yaw) * cam_smoothing;
1884 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1885 cam_view.camera_pitch) * cam_smoothing;
1886 updatePlayerControl(cam_view);
1888 processClientEvents(&cam_view_target, &runData.damage_flash);
1889 updateCamera(&flags, draw_times.busy_time, dtime,
1890 runData.time_from_last_punch);
1892 processPlayerInteraction(&runData, dtime, flags.show_hud,
1894 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1895 updateProfilerGraphs(&graph);
1897 // Update if minimap has been disabled by the server
1898 flags.show_minimap &= !client->isMinimapDisabledByServer();
1903 void Game::shutdown()
1905 if (g_settings->get("3d_mode") == "pageflip") {
1906 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1909 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1914 if (gui_chat_console)
1915 gui_chat_console->drop();
1921 while (g_menumgr.menuCount() > 0) {
1922 g_menumgr.m_stack.front()->setVisible(false);
1923 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1926 if (current_formspec) {
1927 current_formspec->drop();
1928 current_formspec = NULL;
1931 chat_backend->addMessage(L"", L"# Disconnected.");
1932 chat_backend->addMessage(L"", L"");
1936 while (!client->isShutdown()) {
1937 assert(texture_src != NULL);
1938 assert(shader_src != NULL);
1939 texture_src->processQueue();
1940 shader_src->processQueue();
1947 /****************************************************************************/
1948 /****************************************************************************
1950 ****************************************************************************/
1951 /****************************************************************************/
1954 const std::string &map_dir,
1955 std::string *address,
1957 const SubgameSpec &gamespec)
1959 showOverlayMessage(wgettext("Loading..."), 0, 0);
1961 texture_src = createTextureSource(device);
1962 shader_src = createShaderSource(device);
1964 itemdef_manager = createItemDefManager();
1965 nodedef_manager = createNodeDefManager();
1967 eventmgr = new EventManager();
1968 quicktune = new QuicktuneShortcutter();
1970 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1971 && eventmgr && quicktune))
1977 // Create a server if not connecting to an existing one
1978 if (*address == "") {
1979 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1986 bool Game::initSound()
1989 if (g_settings->getBool("enable_sound")) {
1990 infostream << "Attempting to use OpenAL audio" << std::endl;
1991 sound = createOpenALSoundManager(&soundfetcher);
1993 infostream << "Failed to initialize OpenAL audio" << std::endl;
1995 infostream << "Sound disabled." << std::endl;
1999 infostream << "Using dummy audio." << std::endl;
2000 sound = &dummySoundManager;
2001 sound_is_dummy = true;
2004 soundmaker = new SoundMaker(sound, nodedef_manager);
2008 soundmaker->registerReceiver(eventmgr);
2013 bool Game::createSingleplayerServer(const std::string map_dir,
2014 const SubgameSpec &gamespec, u16 port, std::string *address)
2016 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2018 std::string bind_str = g_settings->get("bind_address");
2019 Address bind_addr(0, 0, 0, 0, port);
2021 if (g_settings->getBool("ipv6_server")) {
2022 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2026 bind_addr.Resolve(bind_str.c_str());
2027 } catch (ResolveError &e) {
2028 infostream << "Resolving bind address \"" << bind_str
2029 << "\" failed: " << e.what()
2030 << " -- Listening on all addresses." << std::endl;
2033 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2034 *error_message = "Unable to listen on " +
2035 bind_addr.serializeString() +
2036 " because IPv6 is disabled";
2037 errorstream << *error_message << std::endl;
2041 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2042 bind_addr.isIPv6());
2044 server->start(bind_addr);
2049 bool Game::createClient(const std::string &playername,
2050 const std::string &password, std::string *address, u16 port)
2052 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2054 draw_control = new MapDrawControl;
2058 bool could_connect, connect_aborted;
2060 if (!connectToServer(playername, password, address, port,
2061 &could_connect, &connect_aborted))
2064 if (!could_connect) {
2065 if (error_message->empty() && !connect_aborted) {
2066 // Should not happen if error messages are set properly
2067 *error_message = "Connection failed for unknown reason";
2068 errorstream << *error_message << std::endl;
2073 if (!getServerContent(&connect_aborted)) {
2074 if (error_message->empty() && !connect_aborted) {
2075 // Should not happen if error messages are set properly
2076 *error_message = "Connection failed for unknown reason";
2077 errorstream << *error_message << std::endl;
2082 // Update cached textures, meshes and materials
2083 client->afterContentReceived(device);
2087 camera = new Camera(smgr, *draw_control, gamedef);
2088 if (!camera || !camera->successfullyCreated(*error_message))
2090 client->setCamera(camera);
2094 if (m_cache_enable_clouds) {
2095 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2097 *error_message = "Memory allocation error (clouds)";
2098 errorstream << *error_message << std::endl;
2105 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2106 skybox = NULL; // This is used/set later on in the main run loop
2108 local_inventory = new Inventory(itemdef_manager);
2110 if (!(sky && local_inventory)) {
2111 *error_message = "Memory allocation error (sky or local inventory)";
2112 errorstream << *error_message << std::endl;
2116 /* Pre-calculated values
2118 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2120 v2u32 size = t->getOriginalSize();
2121 crack_animation_length = size.Y / size.X;
2123 crack_animation_length = 5;
2129 /* Set window caption
2131 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2133 str += driver->getName();
2135 device->setWindowCaption(str.c_str());
2137 LocalPlayer *player = client->getEnv().getLocalPlayer();
2138 player->hurt_tilt_timer = 0;
2139 player->hurt_tilt_strength = 0;
2141 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2144 *error_message = "Memory error: could not create HUD";
2145 errorstream << *error_message << std::endl;
2149 mapper = client->getMapper();
2150 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2155 bool Game::initGui()
2157 // First line of debug text
2158 guitext = guienv->addStaticText(
2159 utf8_to_wide(PROJECT_NAME_C).c_str(),
2160 core::rect<s32>(0, 0, 0, 0),
2161 false, false, guiroot);
2163 // Second line of debug text
2164 guitext2 = guienv->addStaticText(
2166 core::rect<s32>(0, 0, 0, 0),
2167 false, false, guiroot);
2169 // At the middle of the screen
2170 // Object infos are shown in this
2171 guitext_info = guienv->addStaticText(
2173 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2174 false, true, guiroot);
2176 // Status text (displays info when showing and hiding GUI stuff, etc.)
2177 guitext_status = guienv->addStaticText(
2179 core::rect<s32>(0, 0, 0, 0),
2180 false, false, guiroot);
2181 guitext_status->setVisible(false);
2184 guitext_chat = guienv->addStaticText(
2186 core::rect<s32>(0, 0, 0, 0),
2187 //false, false); // Disable word wrap as of now
2188 false, true, guiroot);
2189 // Remove stale "recent" chat messages from previous connections
2190 chat_backend->clearRecentChat();
2192 // Chat backend and console
2193 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2194 -1, chat_backend, client);
2195 if (!gui_chat_console) {
2196 *error_message = "Could not allocate memory for chat console";
2197 errorstream << *error_message << std::endl;
2201 // Profiler text (size is updated when text is updated)
2202 guitext_profiler = guienv->addStaticText(
2204 core::rect<s32>(0, 0, 0, 0),
2205 false, false, guiroot);
2206 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2207 guitext_profiler->setVisible(false);
2208 guitext_profiler->setWordWrap(true);
2210 #ifdef HAVE_TOUCHSCREENGUI
2212 if (g_touchscreengui)
2213 g_touchscreengui->init(texture_src);
2220 bool Game::connectToServer(const std::string &playername,
2221 const std::string &password, std::string *address, u16 port,
2222 bool *connect_ok, bool *aborted)
2224 *connect_ok = false; // Let's not be overly optimistic
2226 bool local_server_mode = false;
2228 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2230 Address connect_address(0, 0, 0, 0, port);
2233 connect_address.Resolve(address->c_str());
2235 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2236 //connect_address.Resolve("localhost");
2237 if (connect_address.isIPv6()) {
2238 IPv6AddressBytes addr_bytes;
2239 addr_bytes.bytes[15] = 1;
2240 connect_address.setAddress(&addr_bytes);
2242 connect_address.setAddress(127, 0, 0, 1);
2244 local_server_mode = true;
2246 } catch (ResolveError &e) {
2247 *error_message = std::string("Couldn't resolve address: ") + e.what();
2248 errorstream << *error_message << std::endl;
2252 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2253 *error_message = "Unable to connect to " +
2254 connect_address.serializeString() +
2255 " because IPv6 is disabled";
2256 errorstream << *error_message << std::endl;
2260 client = new Client(device,
2261 playername.c_str(), password,
2262 *draw_control, texture_src, shader_src,
2263 itemdef_manager, nodedef_manager, sound, eventmgr,
2264 connect_address.isIPv6());
2269 gamedef = client; // Client acts as our GameDef
2271 infostream << "Connecting to server at ";
2272 connect_address.print(&infostream);
2273 infostream << std::endl;
2275 client->connect(connect_address, *address,
2276 simple_singleplayer_mode || local_server_mode);
2279 Wait for server to accept connection
2285 FpsControl fps_control = { 0 };
2287 f32 wait_time = 0; // in seconds
2289 fps_control.last_time = device->getTimer()->getTime();
2291 while (device->run()) {
2293 limitFps(&fps_control, &dtime);
2295 // Update client and server
2296 client->step(dtime);
2299 server->step(dtime);
2302 if (client->getState() == LC_Init) {
2308 if (client->accessDenied()) {
2309 *error_message = "Access denied. Reason: "
2310 + client->accessDeniedReason();
2311 *reconnect_requested = client->reconnectRequested();
2312 errorstream << *error_message << std::endl;
2316 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2318 infostream << "Connect aborted [Escape]" << std::endl;
2323 // Only time out if we aren't waiting for the server we started
2324 if ((*address != "") && (wait_time > 10)) {
2325 *error_message = "Connection timed out.";
2326 errorstream << *error_message << std::endl;
2331 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2333 } catch (con::PeerNotFoundException &e) {
2334 // TODO: Should something be done here? At least an info/error
2342 bool Game::getServerContent(bool *aborted)
2346 FpsControl fps_control = { 0 };
2347 f32 dtime; // in seconds
2349 fps_control.last_time = device->getTimer()->getTime();
2351 while (device->run()) {
2353 limitFps(&fps_control, &dtime);
2355 // Update client and server
2356 client->step(dtime);
2359 server->step(dtime);
2362 if (client->mediaReceived() && client->itemdefReceived() &&
2363 client->nodedefReceived()) {
2368 if (!checkConnection())
2371 if (client->getState() < LC_Init) {
2372 *error_message = "Client disconnected";
2373 errorstream << *error_message << std::endl;
2377 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2379 infostream << "Connect aborted [Escape]" << std::endl;
2386 if (!client->itemdefReceived()) {
2387 const wchar_t *text = wgettext("Item definitions...");
2389 draw_load_screen(text, device, guienv, dtime, progress);
2391 } else if (!client->nodedefReceived()) {
2392 const wchar_t *text = wgettext("Node definitions...");
2394 draw_load_screen(text, device, guienv, dtime, progress);
2397 std::stringstream message;
2398 message.precision(3);
2399 message << gettext("Media...");
2401 if ((USE_CURL == 0) ||
2402 (!g_settings->getBool("enable_remote_media_server"))) {
2403 float cur = client->getCurRate();
2404 std::string cur_unit = gettext("KiB/s");
2408 cur_unit = gettext("MiB/s");
2411 message << " (" << cur << ' ' << cur_unit << ")";
2414 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2415 draw_load_screen(utf8_to_wide(message.str()), device,
2416 guienv, dtime, progress);
2424 /****************************************************************************/
2425 /****************************************************************************
2427 ****************************************************************************/
2428 /****************************************************************************/
2430 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2432 if (runData->nodig_delay_timer >= 0)
2433 runData->nodig_delay_timer -= dtime;
2435 if (runData->object_hit_delay_timer >= 0)
2436 runData->object_hit_delay_timer -= dtime;
2438 runData->time_from_last_punch += dtime;
2442 /* returns false if game should exit, otherwise true
2444 inline bool Game::checkConnection()
2446 if (client->accessDenied()) {
2447 *error_message = "Access denied. Reason: "
2448 + client->accessDeniedReason();
2449 *reconnect_requested = client->reconnectRequested();
2450 errorstream << *error_message << std::endl;
2458 /* returns false if game should exit, otherwise true
2460 inline bool Game::handleCallbacks()
2462 if (g_gamecallback->disconnect_requested) {
2463 g_gamecallback->disconnect_requested = false;
2467 if (g_gamecallback->changepassword_requested) {
2468 (new GUIPasswordChange(guienv, guiroot, -1,
2469 &g_menumgr, client))->drop();
2470 g_gamecallback->changepassword_requested = false;
2473 if (g_gamecallback->changevolume_requested) {
2474 (new GUIVolumeChange(guienv, guiroot, -1,
2475 &g_menumgr, client))->drop();
2476 g_gamecallback->changevolume_requested = false;
2479 if (g_gamecallback->keyconfig_requested) {
2480 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2481 &g_menumgr))->drop();
2482 g_gamecallback->keyconfig_requested = false;
2485 if (g_gamecallback->keyconfig_changed) {
2486 keycache.populate(); // update the cache with new settings
2487 g_gamecallback->keyconfig_changed = false;
2494 void Game::processQueues()
2496 texture_src->processQueue();
2497 itemdef_manager->processQueue(gamedef);
2498 shader_src->processQueue();
2502 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2503 const FpsControl &draw_times, f32 dtime)
2505 float profiler_print_interval =
2506 g_settings->getFloat("profiler_print_interval");
2507 bool print_to_log = true;
2509 if (profiler_print_interval == 0) {
2510 print_to_log = false;
2511 profiler_print_interval = 5;
2514 if (profiler_interval.step(dtime, profiler_print_interval)) {
2516 infostream << "Profiler:" << std::endl;
2517 g_profiler->print(infostream);
2520 update_profiler_gui(guitext_profiler, g_fontengine,
2521 runData.profiler_current_page, runData.profiler_max_page,
2522 driver->getScreenSize().Height);
2524 g_profiler->clear();
2527 addProfilerGraphs(stats, draw_times, dtime);
2531 void Game::addProfilerGraphs(const RunStats &stats,
2532 const FpsControl &draw_times, f32 dtime)
2534 g_profiler->graphAdd("mainloop_other",
2535 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2537 if (draw_times.sleep_time != 0)
2538 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2539 g_profiler->graphAdd("mainloop_dtime", dtime);
2541 g_profiler->add("Elapsed time", dtime);
2542 g_profiler->avg("FPS", 1. / dtime);
2546 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2553 /* Time average and jitter calculation
2555 jp = &stats->dtime_jitter;
2556 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2558 jitter = dtime - jp->avg;
2560 if (jitter > jp->max)
2563 jp->counter += dtime;
2565 if (jp->counter > 0.0) {
2567 jp->max_sample = jp->max;
2568 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2572 /* Busytime average and jitter calculation
2574 jp = &stats->busy_time_jitter;
2575 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2577 jitter = draw_times.busy_time - jp->avg;
2579 if (jitter > jp->max)
2581 if (jitter < jp->min)
2584 jp->counter += dtime;
2586 if (jp->counter > 0.0) {
2588 jp->max_sample = jp->max;
2589 jp->min_sample = jp->min;
2597 /****************************************************************************
2599 ****************************************************************************/
2601 void Game::processUserInput(VolatileRunFlags *flags,
2602 GameRunData *runData, f32 dtime)
2604 // Reset input if window not active or some menu is active
2605 if (device->isWindowActive() == false
2606 || noMenuActive() == false
2607 || guienv->hasFocus(gui_chat_console)) {
2609 #ifdef HAVE_TOUCHSCREENGUI
2610 g_touchscreengui->hide();
2613 #ifdef HAVE_TOUCHSCREENGUI
2614 else if (g_touchscreengui) {
2615 /* on touchscreengui step may generate own input events which ain't
2616 * what we want in case we just did clear them */
2617 g_touchscreengui->step(dtime);
2621 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2622 gui_chat_console->closeConsoleAtOnce();
2625 // Input handler step() (used by the random input generator)
2630 if (current_formspec != 0)
2631 current_formspec->getAndroidUIInput();
2635 // Increase timer for double tap of "keymap_jump"
2636 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2637 runData->jump_timer += dtime;
2639 processKeyboardInput(
2641 &runData->statustext_time,
2642 &runData->jump_timer,
2643 &runData->reset_jump_timer,
2644 &runData->profiler_current_page,
2645 runData->profiler_max_page);
2647 processItemSelection(&runData->new_playeritem);
2651 void Game::processKeyboardInput(VolatileRunFlags *flags,
2652 float *statustext_time,
2654 bool *reset_jump_timer,
2655 u32 *profiler_current_page,
2656 u32 profiler_max_page)
2659 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2661 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2663 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_AUTORUN])) {
2664 toggleAutorun(statustext_time);
2665 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2667 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2668 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2669 simple_singleplayer_mode);
2670 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2671 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2673 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2674 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2676 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2678 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2679 toggleFreeMove(statustext_time);
2680 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2681 toggleFreeMoveAlt(statustext_time, jump_timer);
2682 *reset_jump_timer = true;
2683 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2684 toggleFast(statustext_time);
2685 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2686 toggleNoClip(statustext_time);
2687 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2688 toggleCinematic(statustext_time);
2689 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2690 client->makeScreenshot(device);
2691 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2692 toggleHud(statustext_time, &flags->show_hud);
2693 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2694 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2695 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2696 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2697 toggleChat(statustext_time, &flags->show_chat);
2698 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2699 toggleFog(statustext_time, &flags->force_fog_off);
2700 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2701 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2702 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2703 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2704 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2705 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2706 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2707 increaseViewRange(statustext_time);
2708 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2709 decreaseViewRange(statustext_time);
2710 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2711 toggleFullViewRange(statustext_time);
2712 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2714 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2716 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2718 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2720 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2721 // Print debug stacks
2722 dstream << "-----------------------------------------"
2724 dstream << "Printing debug stacks:" << std::endl;
2725 dstream << "-----------------------------------------"
2727 debug_stacks_print();
2730 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2731 *reset_jump_timer = false;
2737 if (quicktune->hasMessage()) {
2738 std::string msg = quicktune->getMessage();
2739 statustext = utf8_to_wide(msg);
2740 *statustext_time = 0;
2745 void Game::processItemSelection(u16 *new_playeritem)
2747 LocalPlayer *player = client->getEnv().getLocalPlayer();
2749 /* Item selection using mouse wheel
2751 *new_playeritem = client->getPlayerItem();
2753 s32 wheel = input->getMouseWheel();
2754 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2755 player->hud_hotbar_itemcount - 1);
2758 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2760 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2764 /* Item selection using keyboard
2766 for (u16 i = 0; i < 10; i++) {
2767 static const KeyPress *item_keys[10] = {
2768 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2769 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2770 NumberKey + 9, NumberKey + 0,
2773 if (input->wasKeyDown(*item_keys[i])) {
2774 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2775 *new_playeritem = i;
2776 infostream << "Selected item: " << new_playeritem << std::endl;
2784 void Game::dropSelectedItem()
2786 IDropAction *a = new IDropAction();
2788 a->from_inv.setCurrentPlayer();
2789 a->from_list = "main";
2790 a->from_i = client->getPlayerItem();
2791 client->inventoryAction(a);
2795 void Game::openInventory()
2798 * Don't permit to open inventory is CAO or player doesn't exists.
2799 * This prevent showing an empty inventory at player load
2802 LocalPlayer *player = client->getEnv().getLocalPlayer();
2803 if (player == NULL || player->getCAO() == NULL)
2806 infostream << "the_game: " << "Launching inventory" << std::endl;
2808 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2809 TextDest *txt_dst = new TextDestPlayerInventory(client);
2811 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2812 device, fs_src, txt_dst, client);
2814 InventoryLocation inventoryloc;
2815 inventoryloc.setCurrentPlayer();
2816 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2820 void Game::openConsole()
2822 if (!gui_chat_console->isOpenInhibited()) {
2823 // Open up to over half of the screen
2824 gui_chat_console->openConsole(0.6);
2825 guienv->setFocus(gui_chat_console);
2830 void Game::toggleFreeMove(float *statustext_time)
2832 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2834 bool free_move = !g_settings->getBool("free_move");
2835 g_settings->set("free_move", bool_to_cstr(free_move));
2837 *statustext_time = 0;
2838 statustext = msg[free_move];
2839 if (free_move && !client->checkPrivilege("fly"))
2840 statustext += L" (note: no 'fly' privilege)";
2844 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2846 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2847 toggleFreeMove(statustext_time);
2851 void Game::toggleFast(float *statustext_time)
2853 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2854 bool fast_move = !g_settings->getBool("fast_move");
2855 g_settings->set("fast_move", bool_to_cstr(fast_move));
2857 *statustext_time = 0;
2858 statustext = msg[fast_move];
2860 bool has_fast_privs = client->checkPrivilege("fast");
2862 if (fast_move && !has_fast_privs)
2863 statustext += L" (note: no 'fast' privilege)";
2866 m_cache_hold_aux1 = fast_move && has_fast_privs;
2871 void Game::toggleNoClip(float *statustext_time)
2873 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2874 bool noclip = !g_settings->getBool("noclip");
2875 g_settings->set("noclip", bool_to_cstr(noclip));
2877 *statustext_time = 0;
2878 statustext = msg[noclip];
2880 if (noclip && !client->checkPrivilege("noclip"))
2881 statustext += L" (note: no 'noclip' privilege)";
2884 void Game::toggleCinematic(float *statustext_time)
2886 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2887 bool cinematic = !g_settings->getBool("cinematic");
2888 g_settings->set("cinematic", bool_to_cstr(cinematic));
2890 *statustext_time = 0;
2891 statustext = msg[cinematic];
2894 // Add WoW-style autorun by toggling continuous forward.
2895 void Game::toggleAutorun(float *statustext_time)
2897 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2898 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2899 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2901 *statustext_time = 0;
2902 statustext = msg[autorun_enabled ? 1 : 0];
2905 void Game::toggleChat(float *statustext_time, bool *flag)
2907 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2910 *statustext_time = 0;
2911 statustext = msg[*flag];
2915 void Game::toggleHud(float *statustext_time, bool *flag)
2917 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2920 *statustext_time = 0;
2921 statustext = msg[*flag];
2924 void Game::toggleMinimap(float *statustext_time, bool *flag,
2925 bool show_hud, bool shift_pressed)
2927 if (!show_hud || !g_settings->getBool("enable_minimap"))
2930 if (shift_pressed) {
2931 mapper->toggleMinimapShape();
2935 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2937 MinimapMode mode = MINIMAP_MODE_OFF;
2938 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2939 mode = mapper->getMinimapMode();
2940 mode = (MinimapMode)((int)mode + 1);
2945 case MINIMAP_MODE_SURFACEx1:
2946 statustext = L"Minimap in surface mode, Zoom x1";
2948 case MINIMAP_MODE_SURFACEx2:
2949 statustext = L"Minimap in surface mode, Zoom x2";
2951 case MINIMAP_MODE_SURFACEx4:
2952 statustext = L"Minimap in surface mode, Zoom x4";
2954 case MINIMAP_MODE_RADARx1:
2955 statustext = L"Minimap in radar mode, Zoom x1";
2957 case MINIMAP_MODE_RADARx2:
2958 statustext = L"Minimap in radar mode, Zoom x2";
2960 case MINIMAP_MODE_RADARx4:
2961 statustext = L"Minimap in radar mode, Zoom x4";
2964 mode = MINIMAP_MODE_OFF;
2966 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2967 L"Minimap hidden" : L"Minimap disabled by server";
2970 *statustext_time = 0;
2971 mapper->setMinimapMode(mode);
2974 void Game::toggleFog(float *statustext_time, bool *flag)
2976 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2979 *statustext_time = 0;
2980 statustext = msg[*flag];
2984 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2985 bool *show_profiler_graph)
2987 // Initial / 3x toggle: Chat only
2988 // 1x toggle: Debug text with chat
2989 // 2x toggle: Debug text with profiler graph
2992 *show_profiler_graph = false;
2993 statustext = L"Debug info shown";
2994 } else if (*show_profiler_graph) {
2995 *show_debug = false;
2996 *show_profiler_graph = false;
2997 statustext = L"Debug info and profiler graph hidden";
2999 *show_profiler_graph = true;
3000 statustext = L"Profiler graph shown";
3002 *statustext_time = 0;
3006 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3008 static const wchar_t *msg[] = {
3009 L"Camera update enabled",
3010 L"Camera update disabled"
3014 *statustext_time = 0;
3015 statustext = msg[*flag];
3019 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3020 u32 profiler_max_page)
3022 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3024 // FIXME: This updates the profiler with incomplete values
3025 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3026 profiler_max_page, driver->getScreenSize().Height);
3028 if (*profiler_current_page != 0) {
3029 std::wstringstream sstr;
3030 sstr << "Profiler shown (page " << *profiler_current_page
3031 << " of " << profiler_max_page << ")";
3032 statustext = sstr.str();
3034 statustext = L"Profiler hidden";
3036 *statustext_time = 0;
3040 void Game::increaseViewRange(float *statustext_time)
3042 s16 range = g_settings->getS16("viewing_range");
3043 s16 range_new = range + 10;
3044 g_settings->set("viewing_range", itos(range_new));
3045 statustext = utf8_to_wide("Viewing range changed to "
3047 *statustext_time = 0;
3051 void Game::decreaseViewRange(float *statustext_time)
3053 s16 range = g_settings->getS16("viewing_range");
3054 s16 range_new = range - 10;
3059 g_settings->set("viewing_range", itos(range_new));
3060 statustext = utf8_to_wide("Viewing range changed to "
3062 *statustext_time = 0;
3066 void Game::toggleFullViewRange(float *statustext_time)
3068 static const wchar_t *msg[] = {
3069 L"Disabled full viewing range",
3070 L"Enabled full viewing range"
3073 draw_control->range_all = !draw_control->range_all;
3074 infostream << msg[draw_control->range_all] << std::endl;
3075 statustext = msg[draw_control->range_all];
3076 *statustext_time = 0;
3080 void Game::updateCameraDirection(CameraOrientation *cam,
3081 VolatileRunFlags *flags)
3083 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3086 if (!random_input) {
3087 // Mac OSX gets upset if this is set every frame
3088 if (device->getCursorControl()->isVisible())
3089 device->getCursorControl()->setVisible(false);
3093 if (flags->first_loop_after_window_activation)
3094 flags->first_loop_after_window_activation = false;
3096 updateCameraOrientation(cam, *flags);
3098 input->setMousePos((driver->getScreenSize().Width / 2),
3099 (driver->getScreenSize().Height / 2));
3103 // Mac OSX gets upset if this is set every frame
3104 if (device->getCursorControl()->isVisible() == false)
3105 device->getCursorControl()->setVisible(true);
3108 if (!flags->first_loop_after_window_activation)
3109 flags->first_loop_after_window_activation = true;
3115 void Game::updateCameraOrientation(CameraOrientation *cam,
3116 const VolatileRunFlags &flags)
3118 #ifdef HAVE_TOUCHSCREENGUI
3119 if (g_touchscreengui) {
3120 cam->camera_yaw = g_touchscreengui->getYaw();
3121 cam->camera_pitch = g_touchscreengui->getPitch();
3124 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3125 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3127 if (flags.invert_mouse
3128 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3132 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3133 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3135 #ifdef HAVE_TOUCHSCREENGUI
3139 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3143 void Game::updatePlayerControl(const CameraOrientation &cam)
3145 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3147 PlayerControl control(
3148 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3149 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3150 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3151 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3152 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3153 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3154 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3155 input->getLeftState(),
3156 input->getRightState(),
3162 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3163 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3164 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3165 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3166 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3167 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3168 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3169 ( (u32)(input->getLeftState() & 0x1) << 7) |
3170 ( (u32)(input->getRightState() & 0x1) << 8
3174 /* For Android, simulate holding down AUX1 (fast move) if the user has
3175 * the fast_move setting toggled on. If there is an aux1 key defined for
3176 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3179 if (m_cache_hold_aux1) {
3180 control.aux1 = control.aux1 ^ true;
3181 keypress_bits ^= ((u32)(1U << 5));
3185 client->setPlayerControl(control);
3186 LocalPlayer *player = client->getEnv().getLocalPlayer();
3187 player->keyPressed = keypress_bits;
3193 inline void Game::step(f32 *dtime)
3195 bool can_be_and_is_paused =
3196 (simple_singleplayer_mode && g_menumgr.pausesGame());
3198 if (can_be_and_is_paused) { // This is for a singleplayer server
3199 *dtime = 0; // No time passes
3201 if (server != NULL) {
3202 //TimeTaker timer("server->step(dtime)");
3203 server->step(*dtime);
3206 //TimeTaker timer("client.step(dtime)");
3207 client->step(*dtime);
3212 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3214 ClientEvent event = client->getClientEvent();
3216 LocalPlayer *player = client->getEnv().getLocalPlayer();
3218 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3220 if (event.type == CE_PLAYER_DAMAGE &&
3221 client->getHP() != 0) {
3222 //u16 damage = event.player_damage.amount;
3223 //infostream<<"Player damage: "<<damage<<std::endl;
3225 *damage_flash += 100.0;
3226 *damage_flash += 8.0 * event.player_damage.amount;
3228 player->hurt_tilt_timer = 1.5;
3229 player->hurt_tilt_strength = event.player_damage.amount / 4;
3230 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3232 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3233 gamedef->event()->put(e);
3234 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3235 cam->camera_yaw = event.player_force_move.yaw;
3236 cam->camera_pitch = event.player_force_move.pitch;
3237 } else if (event.type == CE_DEATHSCREEN) {
3238 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3241 chat_backend->addMessage(L"", L"You died.");
3243 /* Handle visualization */
3245 player->hurt_tilt_timer = 0;
3246 player->hurt_tilt_strength = 0;
3248 } else if (event.type == CE_SHOW_FORMSPEC) {
3249 FormspecFormSource *fs_src =
3250 new FormspecFormSource(*(event.show_formspec.formspec));
3251 TextDestPlayerInventory *txt_dst =
3252 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3254 create_formspec_menu(¤t_formspec, client, gamedef,
3255 texture_src, device, fs_src, txt_dst, client);
3257 delete(event.show_formspec.formspec);
3258 delete(event.show_formspec.formname);
3259 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3260 (event.type == CE_ADD_PARTICLESPAWNER) ||
3261 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3262 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3264 } else if (event.type == CE_HUDADD) {
3265 u32 id = event.hudadd.id;
3267 LocalPlayer *player = client->getEnv().getLocalPlayer();
3268 HudElement *e = player->getHud(id);
3271 delete event.hudadd.pos;
3272 delete event.hudadd.name;
3273 delete event.hudadd.scale;
3274 delete event.hudadd.text;
3275 delete event.hudadd.align;
3276 delete event.hudadd.offset;
3277 delete event.hudadd.world_pos;
3278 delete event.hudadd.size;
3283 e->type = (HudElementType)event.hudadd.type;
3284 e->pos = *event.hudadd.pos;
3285 e->name = *event.hudadd.name;
3286 e->scale = *event.hudadd.scale;
3287 e->text = *event.hudadd.text;
3288 e->number = event.hudadd.number;
3289 e->item = event.hudadd.item;
3290 e->dir = event.hudadd.dir;
3291 e->align = *event.hudadd.align;
3292 e->offset = *event.hudadd.offset;
3293 e->world_pos = *event.hudadd.world_pos;
3294 e->size = *event.hudadd.size;
3296 u32 new_id = player->addHud(e);
3297 //if this isn't true our huds aren't consistent
3298 sanity_check(new_id == id);
3300 delete event.hudadd.pos;
3301 delete event.hudadd.name;
3302 delete event.hudadd.scale;
3303 delete event.hudadd.text;
3304 delete event.hudadd.align;
3305 delete event.hudadd.offset;
3306 delete event.hudadd.world_pos;
3307 delete event.hudadd.size;
3308 } else if (event.type == CE_HUDRM) {
3309 HudElement *e = player->removeHud(event.hudrm.id);
3313 } else if (event.type == CE_HUDCHANGE) {
3314 u32 id = event.hudchange.id;
3315 HudElement *e = player->getHud(id);
3318 delete event.hudchange.v3fdata;
3319 delete event.hudchange.v2fdata;
3320 delete event.hudchange.sdata;
3321 delete event.hudchange.v2s32data;
3325 switch (event.hudchange.stat) {
3327 e->pos = *event.hudchange.v2fdata;
3331 e->name = *event.hudchange.sdata;
3334 case HUD_STAT_SCALE:
3335 e->scale = *event.hudchange.v2fdata;
3339 e->text = *event.hudchange.sdata;
3342 case HUD_STAT_NUMBER:
3343 e->number = event.hudchange.data;
3347 e->item = event.hudchange.data;
3351 e->dir = event.hudchange.data;
3354 case HUD_STAT_ALIGN:
3355 e->align = *event.hudchange.v2fdata;
3358 case HUD_STAT_OFFSET:
3359 e->offset = *event.hudchange.v2fdata;
3362 case HUD_STAT_WORLD_POS:
3363 e->world_pos = *event.hudchange.v3fdata;
3367 e->size = *event.hudchange.v2s32data;
3371 delete event.hudchange.v3fdata;
3372 delete event.hudchange.v2fdata;
3373 delete event.hudchange.sdata;
3374 delete event.hudchange.v2s32data;
3375 } else if (event.type == CE_SET_SKY) {
3376 sky->setVisible(false);
3383 // Handle according to type
3384 if (*event.set_sky.type == "regular") {
3385 sky->setVisible(true);
3386 } else if (*event.set_sky.type == "skybox" &&
3387 event.set_sky.params->size() == 6) {
3388 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3389 skybox = smgr->addSkyBoxSceneNode(
3390 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3391 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3392 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3393 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3394 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3395 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3397 // Handle everything else as plain color
3399 if (*event.set_sky.type != "plain")
3400 infostream << "Unknown sky type: "
3401 << (*event.set_sky.type) << std::endl;
3403 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3406 delete event.set_sky.bgcolor;
3407 delete event.set_sky.type;
3408 delete event.set_sky.params;
3409 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3410 bool enable = event.override_day_night_ratio.do_override;
3411 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3412 client->getEnv().setDayNightRatioOverride(enable, value);
3418 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3419 f32 dtime, float time_from_last_punch)
3421 LocalPlayer *player = client->getEnv().getLocalPlayer();
3424 For interaction purposes, get info about the held item
3426 - Is it a usable item?
3427 - Can it point to liquids?
3429 ItemStack playeritem;
3431 InventoryList *mlist = local_inventory->getList("main");
3433 if (mlist && client->getPlayerItem() < mlist->getSize())
3434 playeritem = mlist->getItem(client->getPlayerItem());
3437 ToolCapabilities playeritem_toolcap =
3438 playeritem.getToolCapabilities(itemdef_manager);
3440 v3s16 old_camera_offset = camera->getOffset();
3442 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3443 GenericCAO *playercao = player->getCAO();
3445 // If playercao not loaded, don't change camera
3446 if (playercao == NULL)
3449 camera->toggleCameraMode();
3451 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3452 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3455 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3456 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3458 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3459 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3461 camera->step(dtime);
3463 v3f camera_position = camera->getPosition();
3464 v3f camera_direction = camera->getDirection();
3465 f32 camera_fov = camera->getFovMax();
3466 v3s16 camera_offset = camera->getOffset();
3468 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3470 if (!flags->disable_camera_update) {
3471 client->getEnv().getClientMap().updateCamera(camera_position,
3472 camera_direction, camera_fov, camera_offset);
3474 if (flags->camera_offset_changed) {
3475 client->updateCameraOffset(camera_offset);
3476 client->getEnv().updateCameraOffset(camera_offset);
3479 clouds->updateCameraOffset(camera_offset);
3485 void Game::updateSound(f32 dtime)
3487 // Update sound listener
3488 v3s16 camera_offset = camera->getOffset();
3489 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3490 v3f(0, 0, 0), // velocity
3491 camera->getDirection(),
3492 camera->getCameraNode()->getUpVector());
3493 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3496 // Update sound maker
3497 soundmaker->step(dtime);
3499 LocalPlayer *player = client->getEnv().getLocalPlayer();
3501 ClientMap &map = client->getEnv().getClientMap();
3502 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3503 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3507 void Game::processPlayerInteraction(GameRunData *runData,
3508 f32 dtime, bool show_hud, bool show_debug)
3510 LocalPlayer *player = client->getEnv().getLocalPlayer();
3512 ItemStack playeritem;
3514 InventoryList *mlist = local_inventory->getList("main");
3516 if (mlist && client->getPlayerItem() < mlist->getSize())
3517 playeritem = mlist->getItem(client->getPlayerItem());
3520 const ItemDefinition &playeritem_def =
3521 playeritem.getDefinition(itemdef_manager);
3523 v3f player_position = player->getPosition();
3524 v3f camera_position = camera->getPosition();
3525 v3f camera_direction = camera->getDirection();
3526 v3s16 camera_offset = camera->getOffset();
3530 Calculate what block is the crosshair pointing to
3533 f32 d = playeritem_def.range; // max. distance
3534 f32 d_hand = itemdef_manager->get("").range;
3536 if (d < 0 && d_hand >= 0)
3541 core::line3d<f32> shootline;
3543 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3545 shootline = core::line3d<f32>(camera_position,
3546 camera_position + camera_direction * BS * (d + 1));
3549 // prevent player pointing anything in front-view
3550 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3551 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3554 #ifdef HAVE_TOUCHSCREENGUI
3556 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3557 shootline = g_touchscreengui->getShootline();
3558 shootline.start += intToFloat(camera_offset, BS);
3559 shootline.end += intToFloat(camera_offset, BS);
3564 PointedThing pointed = getPointedThing(
3566 client, hud, player_position, camera_direction,
3567 camera_position, shootline, d,
3568 playeritem_def.liquids_pointable,
3569 !runData->ldown_for_dig,
3572 runData->selected_object);
3574 if (pointed != runData->pointed_old) {
3575 infostream << "Pointing at " << pointed.dump() << std::endl;
3576 hud->updateSelectionMesh(camera_offset);
3581 - releasing left mouse button
3582 - pointing away from node
3584 if (runData->digging) {
3585 if (input->getLeftReleased()) {
3586 infostream << "Left button released"
3587 << " (stopped digging)" << std::endl;
3588 runData->digging = false;
3589 } else if (pointed != runData->pointed_old) {
3590 if (pointed.type == POINTEDTHING_NODE
3591 && runData->pointed_old.type == POINTEDTHING_NODE
3592 && pointed.node_undersurface
3593 == runData->pointed_old.node_undersurface) {
3594 // Still pointing to the same node, but a different face.
3597 infostream << "Pointing away from node"
3598 << " (stopped digging)" << std::endl;
3599 runData->digging = false;
3600 hud->updateSelectionMesh(camera_offset);
3604 if (!runData->digging) {
3605 client->interact(1, runData->pointed_old);
3606 client->setCrack(-1, v3s16(0, 0, 0));
3607 runData->dig_time = 0.0;
3611 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3612 runData->ldown_for_dig = false;
3615 runData->left_punch = false;
3617 soundmaker->m_player_leftpunch_sound.name = "";
3619 if (input->getRightState())
3620 runData->repeat_rightclick_timer += dtime;
3622 runData->repeat_rightclick_timer = 0;
3624 if (playeritem_def.usable && input->getLeftState()) {
3625 if (input->getLeftClicked())
3626 client->interact(4, pointed);
3627 } else if (pointed.type == POINTEDTHING_NODE) {
3628 ToolCapabilities playeritem_toolcap =
3629 playeritem.getToolCapabilities(itemdef_manager);
3630 handlePointingAtNode(runData, pointed, playeritem_def,
3631 playeritem_toolcap, dtime);
3632 } else if (pointed.type == POINTEDTHING_OBJECT) {
3633 handlePointingAtObject(runData, pointed, playeritem,
3634 player_position, show_debug);
3635 } else if (input->getLeftState()) {
3636 // When button is held down in air, show continuous animation
3637 runData->left_punch = true;
3638 } else if (input->getRightClicked()) {
3639 handlePointingAtNothing(runData, playeritem);
3642 runData->pointed_old = pointed;
3644 if (runData->left_punch || input->getLeftClicked())
3645 camera->setDigging(0); // left click animation
3647 input->resetLeftClicked();
3648 input->resetRightClicked();
3650 input->resetLeftReleased();
3651 input->resetRightReleased();
3655 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3657 infostream << "Right Clicked in Air" << std::endl;
3658 PointedThing fauxPointed;
3659 fauxPointed.type = POINTEDTHING_NOTHING;
3660 client->interact(5, fauxPointed);
3664 void Game::handlePointingAtNode(GameRunData *runData,
3665 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3666 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3668 v3s16 nodepos = pointed.node_undersurface;
3669 v3s16 neighbourpos = pointed.node_abovesurface;
3672 Check information text of node
3675 ClientMap &map = client->getEnv().getClientMap();
3676 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3679 infotext = utf8_to_wide(meta->getString("infotext"));
3681 MapNode n = map.getNodeNoEx(nodepos);
3683 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3684 infotext = L"Unknown node: ";
3685 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3689 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3690 && client->checkPrivilege("interact")) {
3691 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3694 if ((input->getRightClicked() ||
3695 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3696 client->checkPrivilege("interact")) {
3697 runData->repeat_rightclick_timer = 0;
3698 infostream << "Ground right-clicked" << std::endl;
3700 if (meta && meta->getString("formspec") != "" && !random_input
3701 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3702 infostream << "Launching custom inventory view" << std::endl;
3704 InventoryLocation inventoryloc;
3705 inventoryloc.setNodeMeta(nodepos);
3707 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3708 &client->getEnv().getClientMap(), nodepos);
3709 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3711 create_formspec_menu(¤t_formspec, client, gamedef,
3712 texture_src, device, fs_src, txt_dst, client);
3714 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3716 // Report right click to server
3718 camera->setDigging(1); // right click animation (always shown for feedback)
3720 // If the wielded item has node placement prediction,
3722 bool placed = nodePlacementPrediction(*client,
3724 nodepos, neighbourpos);
3728 client->interact(3, pointed);
3730 soundmaker->m_player_rightpunch_sound =
3731 playeritem_def.sound_place;
3733 soundmaker->m_player_rightpunch_sound =
3736 if (playeritem_def.node_placement_prediction == "" ||
3737 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3738 client->interact(3, pointed); // Report to server
3740 soundmaker->m_player_rightpunch_sound =
3741 playeritem_def.sound_place_failed;
3749 void Game::handlePointingAtObject(GameRunData *runData,
3750 const PointedThing &pointed,
3751 const ItemStack &playeritem,
3752 const v3f &player_position,
3755 infotext = utf8_to_wide(runData->selected_object->infoText());
3758 if (infotext != L"") {
3761 infotext += utf8_to_wide(runData->selected_object->debugInfoText());
3764 if (input->getLeftState()) {
3765 bool do_punch = false;
3766 bool do_punch_damage = false;
3768 if (runData->object_hit_delay_timer <= 0.0) {
3770 do_punch_damage = true;
3771 runData->object_hit_delay_timer = object_hit_delay;
3774 if (input->getLeftClicked())
3778 infostream << "Left-clicked object" << std::endl;
3779 runData->left_punch = true;
3782 if (do_punch_damage) {
3783 // Report direct punch
3784 v3f objpos = runData->selected_object->getPosition();
3785 v3f dir = (objpos - player_position).normalize();
3787 bool disable_send = runData->selected_object->directReportPunch(
3788 dir, &playeritem, runData->time_from_last_punch);
3789 runData->time_from_last_punch = 0;
3792 client->interact(0, pointed);
3794 } else if (input->getRightClicked()) {
3795 infostream << "Right-clicked object" << std::endl;
3796 client->interact(3, pointed); // place
3801 void Game::handleDigging(GameRunData *runData,
3802 const PointedThing &pointed, const v3s16 &nodepos,
3803 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3805 if (!runData->digging) {
3806 infostream << "Started digging" << std::endl;
3807 client->interact(0, pointed);
3808 runData->digging = true;
3809 runData->ldown_for_dig = true;
3812 LocalPlayer *player = client->getEnv().getLocalPlayer();
3813 ClientMap &map = client->getEnv().getClientMap();
3814 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3816 // NOTE: Similar piece of code exists on the server side for
3818 // Get digging parameters
3819 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3820 &playeritem_toolcap);
3822 // If can't dig, try hand
3823 if (!params.diggable) {
3824 const ItemDefinition &hand = itemdef_manager->get("");
3825 const ToolCapabilities *tp = hand.tool_capabilities;
3828 params = getDigParams(nodedef_manager->get(n).groups, tp);
3831 if (params.diggable == false) {
3832 // I guess nobody will wait for this long
3833 runData->dig_time_complete = 10000000.0;
3835 runData->dig_time_complete = params.time;
3837 if (m_cache_enable_particles) {
3838 const ContentFeatures &features =
3839 client->getNodeDefManager()->get(n);
3840 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3841 player, nodepos, features.tiles);
3845 if (runData->dig_time_complete >= 0.001) {
3846 runData->dig_index = (float)crack_animation_length
3848 / runData->dig_time_complete;
3850 // This is for torches
3851 runData->dig_index = crack_animation_length;
3854 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3856 if (sound_dig.exists() && params.diggable) {
3857 if (sound_dig.name == "__group") {
3858 if (params.main_group != "") {
3859 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3860 soundmaker->m_player_leftpunch_sound.name =
3861 std::string("default_dig_") +
3865 soundmaker->m_player_leftpunch_sound = sound_dig;
3869 // Don't show cracks if not diggable
3870 if (runData->dig_time_complete >= 100000.0) {
3871 } else if (runData->dig_index < crack_animation_length) {
3872 //TimeTaker timer("client.setTempMod");
3873 //infostream<<"dig_index="<<dig_index<<std::endl;
3874 client->setCrack(runData->dig_index, nodepos);
3876 infostream << "Digging completed" << std::endl;
3877 client->interact(2, pointed);
3878 client->setCrack(-1, v3s16(0, 0, 0));
3879 bool is_valid_position;
3880 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3881 if (is_valid_position)
3882 client->removeNode(nodepos);
3884 if (m_cache_enable_particles) {
3885 const ContentFeatures &features =
3886 client->getNodeDefManager()->get(wasnode);
3887 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3888 player, nodepos, features.tiles);
3891 runData->dig_time = 0;
3892 runData->digging = false;
3894 runData->nodig_delay_timer =
3895 runData->dig_time_complete / (float)crack_animation_length;
3897 // We don't want a corresponding delay to
3898 // very time consuming nodes
3899 if (runData->nodig_delay_timer > 0.3)
3900 runData->nodig_delay_timer = 0.3;
3902 // We want a slight delay to very little
3903 // time consuming nodes
3904 const float mindelay = 0.15;
3906 if (runData->nodig_delay_timer < mindelay)
3907 runData->nodig_delay_timer = mindelay;
3909 // Send event to trigger sound
3910 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3911 gamedef->event()->put(e);
3914 if (runData->dig_time_complete < 100000.0) {
3915 runData->dig_time += dtime;
3917 runData->dig_time = 0;
3918 client->setCrack(-1, nodepos);
3921 camera->setDigging(0); // left click animation
3925 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
3926 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
3927 const CameraOrientation &cam)
3929 LocalPlayer *player = client->getEnv().getLocalPlayer();
3935 if (draw_control->range_all) {
3936 runData->fog_range = 100000 * BS;
3938 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
3942 Calculate general brightness
3944 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3945 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3946 float direct_brightness;
3949 if (g_settings->getBool("free_move")) {
3950 direct_brightness = time_brightness;
3951 sunlight_seen = true;
3953 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3954 float old_brightness = sky->getBrightness();
3955 direct_brightness = client->getEnv().getClientMap()
3956 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3957 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3961 float time_of_day = runData->time_of_day;
3962 float time_of_day_smooth = runData->time_of_day_smooth;
3964 time_of_day = client->getEnv().getTimeOfDayF();
3966 const float maxsm = 0.05;
3967 const float todsm = 0.05;
3969 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3970 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3971 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3972 time_of_day_smooth = time_of_day;
3974 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3975 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3976 + (time_of_day + 1.0) * todsm;
3978 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3979 + time_of_day * todsm;
3981 runData->time_of_day = time_of_day;
3982 runData->time_of_day_smooth = time_of_day_smooth;
3984 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3985 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3986 player->getPitch());
3992 v3f player_position = player->getPosition();
3993 if (sky->getCloudsVisible()) {
3994 clouds->setVisible(true);
3995 clouds->step(dtime);
3996 clouds->update(v2f(player_position.X, player_position.Z),
3997 sky->getCloudColor());
3999 clouds->setVisible(false);
4006 client->getParticleManager()->step(dtime);
4012 if (m_cache_enable_fog && !flags.force_fog_off) {
4015 video::EFT_FOG_LINEAR,
4016 runData->fog_range * 0.4,
4017 runData->fog_range * 1.0,
4025 video::EFT_FOG_LINEAR,
4035 Get chat messages from client
4038 v2u32 screensize = driver->getScreenSize();
4040 updateChat(*client, dtime, flags.show_debug, screensize,
4041 flags.show_chat, runData->profiler_current_page,
4042 *chat_backend, guitext_chat);
4048 if (client->getPlayerItem() != runData->new_playeritem)
4049 client->selectPlayerItem(runData->new_playeritem);
4051 // Update local inventory if it has changed
4052 if (client->getLocalInventoryUpdated()) {
4053 //infostream<<"Updating local inventory"<<std::endl;
4054 client->getLocalInventory(*local_inventory);
4055 runData->update_wielded_item_trigger = true;
4058 if (runData->update_wielded_item_trigger) {
4059 // Update wielded tool
4060 InventoryList *mlist = local_inventory->getList("main");
4062 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4063 ItemStack item = mlist->getItem(client->getPlayerItem());
4064 camera->wield(item);
4066 runData->update_wielded_item_trigger = false;
4070 Update block draw list every 200ms or when camera direction has
4073 runData->update_draw_list_timer += dtime;
4075 v3f camera_direction = camera->getDirection();
4076 if (runData->update_draw_list_timer >= 0.2
4077 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4078 || flags.camera_offset_changed) {
4079 runData->update_draw_list_timer = 0;
4080 client->getEnv().getClientMap().updateDrawList(driver);
4081 runData->update_draw_list_last_cam_dir = camera_direction;
4084 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4087 make sure menu is on top
4088 1. Delete formspec menu reference if menu was removed
4089 2. Else, make sure formspec menu is on top
4091 if (current_formspec) {
4092 if (current_formspec->getReferenceCount() == 1) {
4093 current_formspec->drop();
4094 current_formspec = NULL;
4095 } else if (!noMenuActive()) {
4096 guiroot->bringToFront(current_formspec);
4104 video::SColor skycolor = sky->getSkyColor();
4106 TimeTaker tt_draw("mainloop: draw");
4108 TimeTaker timer("beginScene");
4109 driver->beginScene(true, true, skycolor);
4110 stats->beginscenetime = timer.stop(true);
4113 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4114 guienv, screensize, skycolor, flags.show_hud,
4115 flags.show_minimap);
4120 if (flags.show_profiler_graph)
4121 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4126 if (runData->damage_flash > 0.0) {
4127 video::SColor color(std::min(runData->damage_flash, 180.0f),
4131 driver->draw2DRectangle(color,
4132 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4135 runData->damage_flash -= 100.0 * dtime;
4141 if (player->hurt_tilt_timer > 0.0) {
4142 player->hurt_tilt_timer -= dtime * 5;
4144 if (player->hurt_tilt_timer < 0)
4145 player->hurt_tilt_strength = 0;
4149 Update minimap pos and rotation
4151 if (flags.show_minimap && flags.show_hud) {
4152 mapper->setPos(floatToInt(player->getPosition(), BS));
4153 mapper->setAngle(player->getYaw());
4160 TimeTaker timer("endScene");
4162 stats->endscenetime = timer.stop(true);
4165 stats->drawtime = tt_draw.stop(true);
4166 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4170 inline static const char *yawToDirectionString(int yaw)
4172 // NOTE: TODO: This can be done mathematically without the else/else-if
4175 const char *player_direction;
4177 yaw = wrapDegrees_0_360(yaw);
4179 if (yaw >= 45 && yaw < 135)
4180 player_direction = "West [-X]";
4181 else if (yaw >= 135 && yaw < 225)
4182 player_direction = "South [-Z]";
4183 else if (yaw >= 225 && yaw < 315)
4184 player_direction = "East [+X]";
4186 player_direction = "North [+Z]";
4188 return player_direction;
4192 void Game::updateGui(float *statustext_time, const RunStats &stats,
4193 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4194 const CameraOrientation &cam)
4196 v2u32 screensize = driver->getScreenSize();
4197 LocalPlayer *player = client->getEnv().getLocalPlayer();
4198 v3f player_position = player->getPosition();
4200 if (flags.show_debug) {
4201 static float drawtime_avg = 0;
4202 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4204 u16 fps = 1.0 / stats.dtime_jitter.avg;
4205 //s32 fps = driver->getFPS();
4207 std::ostringstream os(std::ios_base::binary);
4209 << PROJECT_NAME_C " " << g_version_hash
4211 << " (R: range_all=" << draw_control->range_all << ")"
4212 << std::setprecision(0)
4213 << " drawtime = " << drawtime_avg
4214 << std::setprecision(1)
4215 << ", dtime_jitter = "
4216 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4217 << std::setprecision(1)
4218 << ", v_range = " << draw_control->wanted_range
4219 << std::setprecision(3)
4220 << ", RTT = " << client->getRTT();
4221 guitext->setText(utf8_to_wide(os.str()).c_str());
4222 guitext->setVisible(true);
4223 } else if (flags.show_hud || flags.show_chat) {
4224 std::ostringstream os(std::ios_base::binary);
4225 os << PROJECT_NAME_C " " << g_version_hash;
4226 guitext->setText(utf8_to_wide(os.str()).c_str());
4227 guitext->setVisible(true);
4229 guitext->setVisible(false);
4232 if (guitext->isVisible()) {
4233 core::rect<s32> rect(
4235 screensize.X, 5 + g_fontengine->getTextHeight()
4237 guitext->setRelativePosition(rect);
4240 if (flags.show_debug) {
4241 std::ostringstream os(std::ios_base::binary);
4242 os << std::setprecision(1) << std::fixed
4243 << "(" << (player_position.X / BS)
4244 << ", " << (player_position.Y / BS)
4245 << ", " << (player_position.Z / BS)
4246 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4247 << " " << yawToDirectionString(cam.camera_yaw)
4248 << ") (seed = " << ((u64)client->getMapSeed())
4251 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4252 ClientMap &map = client->getEnv().getClientMap();
4253 const INodeDefManager *nodedef = client->getNodeDefManager();
4254 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4255 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4256 const ContentFeatures &features = nodedef->get(n);
4257 os << " (pointing_at = " << nodedef->get(n).name
4258 << " - " << features.tiledef[0].name.c_str()
4263 guitext2->setText(utf8_to_wide(os.str()).c_str());
4264 guitext2->setVisible(true);
4266 core::rect<s32> rect(
4267 5, 5 + g_fontengine->getTextHeight(),
4268 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4270 guitext2->setRelativePosition(rect);
4272 guitext2->setVisible(false);
4275 guitext_info->setText(infotext.c_str());
4276 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4278 float statustext_time_max = 1.5;
4280 if (!statustext.empty()) {
4281 *statustext_time += dtime;
4283 if (*statustext_time >= statustext_time_max) {
4285 *statustext_time = 0;
4289 guitext_status->setText(statustext.c_str());
4290 guitext_status->setVisible(!statustext.empty());
4292 if (!statustext.empty()) {
4293 s32 status_width = guitext_status->getTextWidth();
4294 s32 status_height = guitext_status->getTextHeight();
4295 s32 status_y = screensize.Y - 150;
4296 s32 status_x = (screensize.X - status_width) / 2;
4297 core::rect<s32> rect(
4298 status_x , status_y - status_height,
4299 status_x + status_width, status_y
4301 guitext_status->setRelativePosition(rect);
4304 video::SColor initial_color(255, 0, 0, 0);
4306 if (guienv->getSkin())
4307 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4309 video::SColor final_color = initial_color;
4310 final_color.setAlpha(0);
4311 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4312 initial_color, final_color,
4313 pow(*statustext_time / statustext_time_max, 2.0f));
4314 guitext_status->setOverrideColor(fade_color);
4315 guitext_status->enableOverrideColor(true);
4320 /* Log times and stuff for visualization */
4321 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4323 Profiler::GraphValues values;
4324 g_profiler->graphGet(values);
4330 /****************************************************************************
4332 ****************************************************************************/
4334 /* On some computers framerate doesn't seem to be automatically limited
4336 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4338 // not using getRealTime is necessary for wine
4339 device->getTimer()->tick(); // Maker sure device time is up-to-date
4340 u32 time = device->getTimer()->getTime();
4341 u32 last_time = fps_timings->last_time;
4343 if (time > last_time) // Make sure time hasn't overflowed
4344 fps_timings->busy_time = time - last_time;
4346 fps_timings->busy_time = 0;
4348 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4349 ? g_settings->getFloat("pause_fps_max")
4350 : g_settings->getFloat("fps_max"));
4352 if (fps_timings->busy_time < frametime_min) {
4353 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4354 device->sleep(fps_timings->sleep_time);
4356 fps_timings->sleep_time = 0;
4359 /* Get the new value of the device timer. Note that device->sleep() may
4360 * not sleep for the entire requested time as sleep may be interrupted and
4361 * therefore it is arguably more accurate to get the new time from the
4362 * device rather than calculating it by adding sleep_time to time.
4365 device->getTimer()->tick(); // Update device timer
4366 time = device->getTimer()->getTime();
4368 if (time > last_time) // Make sure last_time hasn't overflowed
4369 *dtime = (time - last_time) / 1000.0;
4373 fps_timings->last_time = time;
4376 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4377 // pass a copy of it to this function
4378 // Note: \p msg must be allocated using new (not malloc())
4379 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4380 int percent, bool draw_clouds)
4382 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4386 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4388 ((Game *)data)->readSettings();
4391 void Game::readSettings()
4393 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4394 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4395 m_cache_enable_particles = g_settings->getBool("enable_particles");
4396 m_cache_enable_fog = g_settings->getBool("enable_fog");
4397 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4398 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4400 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4403 /****************************************************************************/
4404 /****************************************************************************
4406 ****************************************************************************/
4407 /****************************************************************************/
4409 void Game::extendedResourceCleanup()
4411 // Extended resource accounting
4412 infostream << "Irrlicht resources after cleanup:" << std::endl;
4413 infostream << "\tRemaining meshes : "
4414 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4415 infostream << "\tRemaining textures : "
4416 << driver->getTextureCount() << std::endl;
4418 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4419 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4420 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4424 clearTextureNameCache();
4425 infostream << "\tRemaining materials: "
4426 << driver-> getMaterialRendererCount()
4427 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4431 /****************************************************************************/
4432 /****************************************************************************
4433 extern function for launching the game
4434 ****************************************************************************/
4435 /****************************************************************************/
4437 void the_game(bool *kill,
4439 InputHandler *input,
4440 IrrlichtDevice *device,
4442 const std::string &map_dir,
4443 const std::string &playername,
4444 const std::string &password,
4445 const std::string &address, // If empty local server is created
4448 std::string &error_message,
4449 ChatBackend &chat_backend,
4450 bool *reconnect_requested,
4451 const SubgameSpec &gamespec, // Used for local game
4452 bool simple_singleplayer_mode)
4456 /* Make a copy of the server address because if a local singleplayer server
4457 * is created then this is updated and we don't want to change the value
4458 * passed to us by the calling function
4460 std::string server_address = address;
4464 if (game.startup(kill, random_input, input, device, map_dir,
4465 playername, password, &server_address, port, error_message,
4466 reconnect_requested, &chat_backend, gamespec,
4467 simple_singleplayer_mode)) {
4472 } catch (SerializationError &e) {
4473 error_message = std::string("A serialization error occurred:\n")
4474 + e.what() + "\n\nThe server is probably "
4475 " running a different version of " PROJECT_NAME_C ".";
4476 errorstream << error_message << std::endl;
4477 } catch (ServerError &e) {
4478 error_message = e.what();
4479 errorstream << "ServerError: " << error_message << std::endl;
4480 } catch (ModError &e) {
4481 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4482 errorstream << "ModError: " << error_message << std::endl;