3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
31 #include "guiPauseMenu.h"
32 #include "guiPasswordChange.h"
33 #include "guiVolumeChange.h"
34 #include "guiFormSpecMenu.h"
35 #include "guiTextInputMenu.h"
36 #include "guiDeathScreen.h"
38 #include "guiChatConsole.h"
41 #include "particles.h"
47 #include "mainmenumanager.h"
51 // Needed for determining pointing to nodes
53 #include "nodemetadata.h"
54 #include "main.h" // For g_settings
56 #include "tile.h" // For TextureSource
57 #include "shader.h" // For ShaderSource
58 #include "logoutputbuffer.h"
60 #include "quicktune_shortcutter.h"
61 #include "clientmap.h"
66 #include "sound_openal.h"
68 #include "event_manager.h"
71 #include "util/directiontables.h"
77 struct TextDestChat : public TextDest
79 TextDestChat(Client *client)
83 void gotText(std::wstring text)
85 m_client->typeChatMessage(text);
87 void gotText(std::map<std::string, std::string> fields)
89 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
95 struct TextDestNodeMetadata : public TextDest
97 TextDestNodeMetadata(v3s16 p, Client *client)
102 // This is deprecated I guess? -celeron55
103 void gotText(std::wstring text)
105 std::string ntext = wide_to_narrow(text);
106 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
107 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
108 std::map<std::string, std::string> fields;
109 fields["text"] = ntext;
110 m_client->sendNodemetaFields(m_p, "", fields);
112 void gotText(std::map<std::string, std::string> fields)
114 m_client->sendNodemetaFields(m_p, "", fields);
121 struct TextDestPlayerInventory : public TextDest
123 TextDestPlayerInventory(Client *client)
128 TextDestPlayerInventory(Client *client, std::string formname)
131 m_formname = formname;
133 void gotText(std::map<std::string, std::string> fields)
135 m_client->sendInventoryFields(m_formname, fields);
138 void setFormName(std::string formname) {
139 m_formname = formname;
143 std::string m_formname;
146 /* Respawn menu callback */
148 class MainRespawnInitiator: public IRespawnInitiator
151 MainRespawnInitiator(bool *active, Client *client):
152 m_active(active), m_client(client)
159 m_client->sendRespawn();
166 /* Form update callback */
168 class NodeMetadataFormSource: public IFormSource
171 NodeMetadataFormSource(ClientMap *map, v3s16 p):
176 std::string getForm()
178 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
181 return meta->getString("formspec");
183 std::string resolveText(std::string str)
185 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
188 return meta->resolveString(str);
195 class PlayerInventoryFormSource: public IFormSource
198 PlayerInventoryFormSource(Client *client):
202 std::string getForm()
204 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
205 return player->inventory_formspec;
212 Check if a node is pointable
214 inline bool isPointableNode(const MapNode& n,
215 Client *client, bool liquids_pointable)
217 const ContentFeatures &features = client->getNodeDefManager()->get(n);
218 return features.pointable ||
219 (liquids_pointable && features.isLiquid());
223 Find what the player is pointing at
225 PointedThing getPointedThing(Client *client, v3f player_position,
226 v3f camera_direction, v3f camera_position,
227 core::line3d<f32> shootline, f32 d,
228 bool liquids_pointable,
229 bool look_for_object,
230 std::vector<aabb3f> &hilightboxes,
231 ClientActiveObject *&selected_object)
235 hilightboxes.clear();
236 selected_object = NULL;
238 INodeDefManager *nodedef = client->getNodeDefManager();
239 ClientMap &map = client->getEnv().getClientMap();
241 // First try to find a pointed at active object
244 selected_object = client->getSelectedActiveObject(d*BS,
245 camera_position, shootline);
247 if(selected_object != NULL)
249 if(selected_object->doShowSelectionBox())
251 aabb3f *selection_box = selected_object->getSelectionBox();
252 // Box should exist because object was
253 // returned in the first place
254 assert(selection_box);
256 v3f pos = selected_object->getPosition();
257 hilightboxes.push_back(aabb3f(
258 selection_box->MinEdge + pos,
259 selection_box->MaxEdge + pos));
263 result.type = POINTEDTHING_OBJECT;
264 result.object_id = selected_object->getId();
269 // That didn't work, try to find a pointed at node
271 f32 mindistance = BS * 1001;
273 v3s16 pos_i = floatToInt(player_position, BS);
275 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
279 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
280 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
281 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
282 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
283 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
284 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
286 // Prevent signed number overflow
294 for(s16 y = ystart; y <= yend; y++)
295 for(s16 z = zstart; z <= zend; z++)
296 for(s16 x = xstart; x <= xend; x++)
301 n = map.getNode(v3s16(x,y,z));
303 catch(InvalidPositionException &e)
307 if(!isPointableNode(n, client, liquids_pointable))
310 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
313 v3f npf = intToFloat(np, BS);
315 for(std::vector<aabb3f>::const_iterator
317 i != boxes.end(); i++)
323 for(u16 j=0; j<6; j++)
325 v3s16 facedir = g_6dirs[j];
326 aabb3f facebox = box;
330 facebox.MinEdge.X = facebox.MaxEdge.X-d;
331 else if(facedir.X < 0)
332 facebox.MaxEdge.X = facebox.MinEdge.X+d;
333 else if(facedir.Y > 0)
334 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
335 else if(facedir.Y < 0)
336 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
337 else if(facedir.Z > 0)
338 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
339 else if(facedir.Z < 0)
340 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
342 v3f centerpoint = facebox.getCenter();
343 f32 distance = (centerpoint - camera_position).getLength();
344 if(distance >= mindistance)
346 if(!facebox.intersectsWithLine(shootline))
349 v3s16 np_above = np + facedir;
351 result.type = POINTEDTHING_NODE;
352 result.node_undersurface = np;
353 result.node_abovesurface = np_above;
354 mindistance = distance;
356 hilightboxes.clear();
357 for(std::vector<aabb3f>::const_iterator
359 i2 != boxes.end(); i2++)
362 box.MinEdge += npf + v3f(-d,-d,-d);
363 box.MaxEdge += npf + v3f(d,d,d);
364 hilightboxes.push_back(box);
374 Draws a screen with a single text on it.
375 Text will be removed when the screen is drawn the next time.
376 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
378 /*gui::IGUIStaticText **/
379 void draw_load_screen(const std::wstring &text,
380 IrrlichtDevice* device, gui::IGUIFont* font,
381 float dtime=0 ,int percent=0, bool clouds=true)
383 video::IVideoDriver* driver = device->getVideoDriver();
384 v2u32 screensize = driver->getScreenSize();
385 const wchar_t *loadingtext = text.c_str();
386 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
387 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
388 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
389 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
391 gui::IGUIStaticText *guitext = guienv->addStaticText(
392 loadingtext, textrect, false, false);
393 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
395 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
396 if (cloud_menu_background)
398 g_menuclouds->step(dtime*3);
399 g_menuclouds->render();
400 driver->beginScene(true, true, video::SColor(255,140,186,250));
401 g_menucloudsmgr->drawAll();
404 driver->beginScene(true, true, video::SColor(255,0,0,0));
405 if (percent >= 0 && percent <= 100) // draw progress bar
407 core::vector2d<s32> barsize(256,32);
408 core::rect<s32> barrect(center-barsize/2, center+barsize/2);
409 driver->draw2DRectangle(video::SColor(255,255,255,255),barrect, NULL); // border
410 driver->draw2DRectangle(video::SColor(255,64,64,64), core::rect<s32> (
411 barrect.UpperLeftCorner+1,
412 barrect.LowerRightCorner-1), NULL); // black inside the bar
413 driver->draw2DRectangle(video::SColor(255,128,128,128), core::rect<s32> (
414 barrect.UpperLeftCorner+1,
416 barrect.LowerRightCorner.X-(barsize.X-1)+percent*(barsize.X-2)/100,
417 barrect.LowerRightCorner.Y-1)), NULL); // the actual progress
427 /* Profiler display */
429 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
430 gui::IGUIFont *font, u32 text_height,
431 u32 show_profiler, u32 show_profiler_max)
433 if(show_profiler == 0)
435 guitext_profiler->setVisible(false);
440 std::ostringstream os(std::ios_base::binary);
441 g_profiler->printPage(os, show_profiler, show_profiler_max);
442 std::wstring text = narrow_to_wide(os.str());
443 guitext_profiler->setText(text.c_str());
444 guitext_profiler->setVisible(true);
446 s32 w = font->getDimension(text.c_str()).Width;
449 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
450 8+(text_height+5)*2 +
451 font->getDimension(text.c_str()).Height);
452 guitext_profiler->setRelativePosition(rect);
453 guitext_profiler->setVisible(true);
461 Profiler::GraphValues values;
467 Meta(float initial=0, video::SColor color=
468 video::SColor(255,255,255,255)):
474 std::list<Piece> m_log;
482 void put(const Profiler::GraphValues &values)
485 piece.values = values;
486 m_log.push_back(piece);
487 while(m_log.size() > m_log_max_size)
488 m_log.erase(m_log.begin());
491 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
492 gui::IGUIFont* font) const
494 std::map<std::string, Meta> m_meta;
495 for(std::list<Piece>::const_iterator k = m_log.begin();
496 k != m_log.end(); k++)
498 const Piece &piece = *k;
499 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
500 i != piece.values.end(); i++){
501 const std::string &id = i->first;
502 const float &value = i->second;
503 std::map<std::string, Meta>::iterator j =
505 if(j == m_meta.end()){
506 m_meta[id] = Meta(value);
509 if(value < j->second.min)
510 j->second.min = value;
511 if(value > j->second.max)
512 j->second.max = value;
517 static const video::SColor usable_colors[] = {
518 video::SColor(255,255,100,100),
519 video::SColor(255,90,225,90),
520 video::SColor(255,100,100,255),
521 video::SColor(255,255,150,50),
522 video::SColor(255,220,220,100)
524 static const u32 usable_colors_count =
525 sizeof(usable_colors) / sizeof(*usable_colors);
526 u32 next_color_i = 0;
527 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
528 i != m_meta.end(); i++){
529 Meta &meta = i->second;
530 video::SColor color(255,200,200,200);
531 if(next_color_i < usable_colors_count)
532 color = usable_colors[next_color_i++];
537 s32 textx = x_left + m_log_max_size + 15;
538 s32 textx2 = textx + 200 - 15;
542 u32 num_graphs = m_meta.size();
543 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
545 video::SColor bgcolor(120,0,0,0);
546 driver->draw2DRectangle(bgcolor, rect, NULL);
550 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
551 i != m_meta.end(); i++){
552 const std::string &id = i->first;
553 const Meta &meta = i->second;
555 s32 y = y_bottom - meta_i * 50;
556 float show_min = meta.min;
557 float show_max = meta.max;
558 if(show_min >= -0.0001 && show_max >= -0.0001){
559 if(show_min <= show_max * 0.5)
564 snprintf(buf, 10, "%.3g", show_max);
565 font->draw(narrow_to_wide(buf).c_str(),
566 core::rect<s32>(textx, y - graphh,
567 textx2, y - graphh + texth),
569 snprintf(buf, 10, "%.3g", show_min);
570 font->draw(narrow_to_wide(buf).c_str(),
571 core::rect<s32>(textx, y - texth,
574 font->draw(narrow_to_wide(id).c_str(),
575 core::rect<s32>(textx, y - graphh/2 - texth/2,
576 textx2, y - graphh/2 + texth/2),
579 s32 graph1h = graphh;
580 bool relativegraph = (show_min != 0 && show_min != show_max);
581 float lastscaledvalue = 0.0;
582 bool lastscaledvalue_exists = false;
583 for(std::list<Piece>::const_iterator j = m_log.begin();
584 j != m_log.end(); j++)
586 const Piece &piece = *j;
588 bool value_exists = false;
589 Profiler::GraphValues::const_iterator k =
590 piece.values.find(id);
591 if(k != piece.values.end()){
597 lastscaledvalue_exists = false;
600 float scaledvalue = 1.0;
601 if(show_max != show_min)
602 scaledvalue = (value - show_min) / (show_max - show_min);
603 if(scaledvalue == 1.0 && value == 0){
605 lastscaledvalue_exists = false;
609 if(lastscaledvalue_exists){
610 s32 ivalue1 = lastscaledvalue * graph1h;
611 s32 ivalue2 = scaledvalue * graph1h;
612 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
613 v2s32(x, graph1y - ivalue2), meta.color);
615 lastscaledvalue = scaledvalue;
616 lastscaledvalue_exists = true;
618 s32 ivalue = scaledvalue * graph1h;
619 driver->draw2DLine(v2s32(x, graph1y),
620 v2s32(x, graph1y - ivalue), meta.color);
629 class NodeDugEvent: public MtEvent
635 NodeDugEvent(v3s16 p, MapNode n):
639 const char* getType() const
645 ISoundManager *m_sound;
646 INodeDefManager *m_ndef;
648 float m_player_step_timer;
650 SimpleSoundSpec m_player_step_sound;
651 SimpleSoundSpec m_player_leftpunch_sound;
652 SimpleSoundSpec m_player_rightpunch_sound;
654 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
657 m_player_step_timer(0)
661 void playPlayerStep()
663 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
664 m_player_step_timer = 0.03;
665 m_sound->playSound(m_player_step_sound, false);
669 static void viewBobbingStep(MtEvent *e, void *data)
671 SoundMaker *sm = (SoundMaker*)data;
672 sm->playPlayerStep();
675 static void playerRegainGround(MtEvent *e, void *data)
677 SoundMaker *sm = (SoundMaker*)data;
678 sm->playPlayerStep();
681 static void playerJump(MtEvent *e, void *data)
683 //SoundMaker *sm = (SoundMaker*)data;
686 static void cameraPunchLeft(MtEvent *e, void *data)
688 SoundMaker *sm = (SoundMaker*)data;
689 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
692 static void cameraPunchRight(MtEvent *e, void *data)
694 SoundMaker *sm = (SoundMaker*)data;
695 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
698 static void nodeDug(MtEvent *e, void *data)
700 SoundMaker *sm = (SoundMaker*)data;
701 NodeDugEvent *nde = (NodeDugEvent*)e;
702 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
705 static void playerDamage(MtEvent *e, void *data)
707 SoundMaker *sm = (SoundMaker*)data;
708 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
711 static void playerFallingDamage(MtEvent *e, void *data)
713 SoundMaker *sm = (SoundMaker*)data;
714 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
717 void registerReceiver(MtEventManager *mgr)
719 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
720 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
721 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
722 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
723 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
724 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
725 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
726 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
729 void step(float dtime)
731 m_player_step_timer -= dtime;
735 // Locally stored sounds don't need to be preloaded because of this
736 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
738 std::set<std::string> m_fetched;
741 void fetchSounds(const std::string &name,
742 std::set<std::string> &dst_paths,
743 std::set<std::string> &dst_datas)
745 if(m_fetched.count(name))
747 m_fetched.insert(name);
748 std::string base = porting::path_share + DIR_DELIM + "testsounds";
749 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
750 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
751 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
752 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
753 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
754 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
755 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
756 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
757 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
758 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
759 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
763 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
766 bool *m_force_fog_off;
771 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
772 f32 *fog_range, Client *client):
774 m_force_fog_off(force_fog_off),
775 m_fog_range(fog_range),
778 ~GameGlobalShaderConstantSetter() {}
780 virtual void onSetConstants(video::IMaterialRendererServices *services,
787 video::SColor bgcolor = m_sky->getBgColor();
788 video::SColorf bgcolorf(bgcolor);
789 float bgcolorfa[4] = {
795 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
798 float fog_distance = *m_fog_range;
800 fog_distance = 10000*BS;
801 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
804 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
805 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
806 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
808 // Normal map texture layer
810 // before 1.8 there isn't a "integer interface", only float
811 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
812 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer, 1);
814 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer, 1);
819 bool nodePlacementPrediction(Client &client,
820 const ItemDefinition &playeritem_def,
821 v3s16 nodepos, v3s16 neighbourpos)
823 std::string prediction = playeritem_def.node_placement_prediction;
824 INodeDefManager *nodedef = client.ndef();
825 ClientMap &map = client.getEnv().getClientMap();
827 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
829 verbosestream<<"Node placement prediction for "
830 <<playeritem_def.name<<" is "
831 <<prediction<<std::endl;
832 v3s16 p = neighbourpos;
833 // Place inside node itself if buildable_to
835 MapNode n_under = map.getNode(nodepos);
836 if(nodedef->get(n_under).buildable_to)
838 else if (!nodedef->get(map.getNode(p)).buildable_to)
840 }catch(InvalidPositionException &e){}
841 // Find id of predicted node
843 bool found = nodedef->getId(prediction, id);
845 errorstream<<"Node placement prediction failed for "
846 <<playeritem_def.name<<" (places "
848 <<") - Name not known"<<std::endl;
851 // Predict param2 for facedir and wallmounted nodes
853 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
854 v3s16 dir = nodepos - neighbourpos;
855 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
856 param2 = dir.Y < 0 ? 1 : 0;
857 } else if(abs(dir.X) > abs(dir.Z)){
858 param2 = dir.X < 0 ? 3 : 2;
860 param2 = dir.Z < 0 ? 5 : 4;
863 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
864 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
865 if(abs(dir.X) > abs(dir.Z)){
866 param2 = dir.X < 0 ? 3 : 1;
868 param2 = dir.Z < 0 ? 2 : 0;
871 assert(param2 >= 0 && param2 <= 5);
872 //Check attachment if node is in group attached_node
873 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
874 static v3s16 wallmounted_dirs[8] = {
883 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
884 pp = p + wallmounted_dirs[param2];
886 pp = p + v3s16(0,-1,0);
887 if(!nodedef->get(map.getNode(pp)).walkable)
890 // Add node to client map
891 MapNode n(id, 0, param2);
893 // This triggers the required mesh update too
894 client.addNode(p, n);
896 }catch(InvalidPositionException &e){
897 errorstream<<"Node placement prediction failed for "
898 <<playeritem_def.name<<" (places "
900 <<") - Position not loaded"<<std::endl;
911 IrrlichtDevice *device,
914 std::string playername,
915 std::string password,
916 std::string address, // If "", local server is used
918 std::wstring &error_message,
919 std::string configpath,
920 ChatBackend &chat_backend,
921 const SubgameSpec &gamespec, // Used for local game,
922 bool simple_singleplayer_mode
925 FormspecFormSource* current_formspec = 0;
926 TextDestPlayerInventory* current_textdest = 0;
927 video::IVideoDriver* driver = device->getVideoDriver();
928 scene::ISceneManager* smgr = device->getSceneManager();
930 // Calculate text height using the font
931 u32 text_height = font->getDimension(L"Random test string").Height;
933 v2u32 last_screensize(0,0);
934 v2u32 screensize = driver->getScreenSize();
937 Draw "Loading" screen
941 wchar_t* text = wgettext("Loading...");
942 draw_load_screen(text, device, font,0,0);
946 // Create texture source
947 IWritableTextureSource *tsrc = createTextureSource(device);
949 // Create shader source
950 IWritableShaderSource *shsrc = createShaderSource(device);
952 // These will be filled by data received from the server
953 // Create item definition manager
954 IWritableItemDefManager *itemdef = createItemDefManager();
955 // Create node definition manager
956 IWritableNodeDefManager *nodedef = createNodeDefManager();
958 // Sound fetcher (useful when testing)
959 GameOnDemandSoundFetcher soundfetcher;
962 ISoundManager *sound = NULL;
963 bool sound_is_dummy = false;
965 if(g_settings->getBool("enable_sound")){
966 infostream<<"Attempting to use OpenAL audio"<<std::endl;
967 sound = createOpenALSoundManager(&soundfetcher);
969 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
971 infostream<<"Sound disabled."<<std::endl;
975 infostream<<"Using dummy audio."<<std::endl;
976 sound = &dummySoundManager;
977 sound_is_dummy = true;
980 Server *server = NULL;
984 EventManager eventmgr;
987 SoundMaker soundmaker(sound, nodedef);
988 soundmaker.registerReceiver(&eventmgr);
990 // Add chat log output for errors to be shown in chat
991 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
993 // Create UI for modifying quicktune values
994 QuicktuneShortcutter quicktune;
1001 wchar_t* text = wgettext("Creating server....");
1002 draw_load_screen(text, device, font,0,25);
1004 infostream<<"Creating server"<<std::endl;
1005 server = new Server(map_dir, configpath, gamespec,
1006 simple_singleplayer_mode);
1007 server->start(port);
1010 do{ // Client scope (breakable do-while(0))
1017 wchar_t* text = wgettext("Creating client...");
1018 draw_load_screen(text, device, font,0,50);
1021 infostream<<"Creating client"<<std::endl;
1023 MapDrawControl draw_control;
1026 wchar_t* text = wgettext("Resolving address...");
1027 draw_load_screen(text, device, font,0,75);
1030 Address connect_address(0,0,0,0, port);
1034 //connect_address.Resolve("localhost");
1035 if(g_settings->getBool("enable_ipv6") && g_settings->getBool("ipv6_server"))
1037 IPv6AddressBytes addr_bytes;
1038 addr_bytes.bytes[15] = 1;
1039 connect_address.setAddress(&addr_bytes);
1043 connect_address.setAddress(127,0,0,1);
1047 connect_address.Resolve(address.c_str());
1049 catch(ResolveError &e)
1051 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1052 errorstream<<wide_to_narrow(error_message)<<std::endl;
1053 // Break out of client scope
1060 Client client(device, playername.c_str(), password, draw_control,
1061 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1062 connect_address.isIPv6());
1064 // Client acts as our GameDef
1065 IGameDef *gamedef = &client;
1068 Attempt to connect to the server
1071 infostream<<"Connecting to server at ";
1072 connect_address.print(&infostream);
1073 infostream<<std::endl;
1074 client.connect(connect_address);
1077 Wait for server to accept connection
1079 bool could_connect = false;
1080 bool connect_aborted = false;
1082 float time_counter = 0.0;
1084 float fps_max = g_settings->getFloat("fps_max");
1085 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1086 u32 lasttime = device->getTimer()->getTime();
1087 while(device->run())
1089 f32 dtime = 0.033; // in seconds
1090 if (cloud_menu_background) {
1091 u32 time = device->getTimer()->getTime();
1093 dtime = (time - lasttime) / 1000.0;
1098 // Update client and server
1101 server->step(dtime);
1104 if(client.connectedAndInitialized()){
1105 could_connect = true;
1109 if(client.accessDenied()){
1110 error_message = L"Access denied. Reason: "
1111 +client.accessDeniedReason();
1112 errorstream<<wide_to_narrow(error_message)<<std::endl;
1115 if(input->wasKeyDown(EscapeKey)){
1116 connect_aborted = true;
1117 infostream<<"Connect aborted [Escape]"<<std::endl;
1123 wchar_t* text = wgettext("Connecting to server...");
1124 draw_load_screen(text, device, font, dtime, 100);
1128 // On some computers framerate doesn't seem to be
1129 // automatically limited
1130 if (cloud_menu_background) {
1131 // Time of frame without fps limit
1134 // not using getRealTime is necessary for wine
1135 u32 time = device->getTimer()->getTime();
1137 busytime_u32 = time - lasttime;
1140 busytime = busytime_u32 / 1000.0;
1143 u32 frametime_min = 1000./fps_max;
1145 if(busytime_u32 < frametime_min) {
1146 u32 sleeptime = frametime_min - busytime_u32;
1147 device->sleep(sleeptime);
1152 time_counter += dtime;
1155 catch(con::PeerNotFoundException &e)
1159 Handle failure to connect
1162 if(error_message == L"" && !connect_aborted){
1163 error_message = L"Connection failed";
1164 errorstream<<wide_to_narrow(error_message)<<std::endl;
1166 // Break out of client scope
1171 Wait until content has been received
1173 bool got_content = false;
1174 bool content_aborted = false;
1176 float time_counter = 0.0;
1178 float fps_max = g_settings->getFloat("fps_max");
1179 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1180 u32 lasttime = device->getTimer()->getTime();
1181 while(device->run())
1183 f32 dtime = 0.033; // in seconds
1184 if (cloud_menu_background) {
1185 u32 time = device->getTimer()->getTime();
1187 dtime = (time - lasttime) / 1000.0;
1192 // Update client and server
1195 server->step(dtime);
1198 if(client.texturesReceived() &&
1199 client.itemdefReceived() &&
1200 client.nodedefReceived()){
1205 if(!client.connectedAndInitialized()){
1206 error_message = L"Client disconnected";
1207 errorstream<<wide_to_narrow(error_message)<<std::endl;
1210 if(input->wasKeyDown(EscapeKey)){
1211 content_aborted = true;
1212 infostream<<"Connect aborted [Escape]"<<std::endl;
1218 if (!client.itemdefReceived())
1220 wchar_t* text = wgettext("Item definitions...");
1222 draw_load_screen(text, device, font, dtime, progress);
1225 else if (!client.nodedefReceived())
1227 wchar_t* text = wgettext("Node definitions...");
1229 draw_load_screen(text, device, font, dtime, progress);
1234 wchar_t* text = wgettext("Media...");
1235 progress = 50+client.mediaReceiveProgress()*50+0.5;
1236 draw_load_screen(text, device, font, dtime, progress);
1240 // On some computers framerate doesn't seem to be
1241 // automatically limited
1242 if (cloud_menu_background) {
1243 // Time of frame without fps limit
1246 // not using getRealTime is necessary for wine
1247 u32 time = device->getTimer()->getTime();
1249 busytime_u32 = time - lasttime;
1252 busytime = busytime_u32 / 1000.0;
1255 u32 frametime_min = 1000./fps_max;
1257 if(busytime_u32 < frametime_min) {
1258 u32 sleeptime = frametime_min - busytime_u32;
1259 device->sleep(sleeptime);
1264 time_counter += dtime;
1269 if(error_message == L"" && !content_aborted){
1270 error_message = L"Something failed";
1271 errorstream<<wide_to_narrow(error_message)<<std::endl;
1273 // Break out of client scope
1278 After all content has been received:
1279 Update cached textures, meshes and materials
1281 client.afterContentReceived(device,font);
1284 Create the camera node
1286 Camera camera(smgr, draw_control, gamedef);
1287 if (!camera.successfullyCreated(error_message))
1290 f32 camera_yaw = 0; // "right/left"
1291 f32 camera_pitch = 0; // "up/down"
1297 Clouds *clouds = NULL;
1298 if(g_settings->getBool("enable_clouds"))
1300 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1308 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1314 FarMesh *farmesh = NULL;
1315 if(g_settings->getBool("enable_farmesh"))
1317 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1321 A copy of the local inventory
1323 Inventory local_inventory(itemdef);
1326 Find out size of crack animation
1328 int crack_animation_length = 5;
1330 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1331 v2u32 size = t->getOriginalSize();
1332 crack_animation_length = size.Y / size.X;
1339 // First line of debug text
1340 gui::IGUIStaticText *guitext = guienv->addStaticText(
1342 core::rect<s32>(5, 5, 795, 5+text_height),
1344 // Second line of debug text
1345 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1347 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1349 // At the middle of the screen
1350 // Object infos are shown in this
1351 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1353 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1356 // Status text (displays info when showing and hiding GUI stuff, etc.)
1357 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1359 core::rect<s32>(0,0,0,0),
1361 guitext_status->setVisible(false);
1363 std::wstring statustext;
1364 float statustext_time = 0;
1367 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1369 core::rect<s32>(0,0,0,0),
1370 //false, false); // Disable word wrap as of now
1372 // Remove stale "recent" chat messages from previous connections
1373 chat_backend.clearRecentChat();
1374 // Chat backend and console
1375 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1377 // Profiler text (size is updated when text is updated)
1378 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1380 core::rect<s32>(0,0,0,0),
1382 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1383 guitext_profiler->setVisible(false);
1384 guitext_profiler->setWordWrap(true);
1387 Some statistics are collected in these
1390 u32 beginscenetime = 0;
1392 u32 endscenetime = 0;
1394 float recent_turn_speed = 0.0;
1396 ProfilerGraph graph;
1397 // Initially clear the profiler
1398 Profiler::GraphValues dummyvalues;
1399 g_profiler->graphGet(dummyvalues);
1401 float nodig_delay_timer = 0.0;
1402 float dig_time = 0.0;
1404 PointedThing pointed_old;
1405 bool digging = false;
1406 bool ldown_for_dig = false;
1408 float damage_flash = 0;
1409 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1411 float jump_timer = 0;
1412 bool reset_jump_timer = false;
1414 const float object_hit_delay = 0.2;
1415 float object_hit_delay_timer = 0.0;
1416 float time_from_last_punch = 10;
1418 float update_draw_list_timer = 0.0;
1419 v3f update_draw_list_last_cam_dir;
1421 bool invert_mouse = g_settings->getBool("invert_mouse");
1423 bool respawn_menu_active = false;
1424 bool update_wielded_item_trigger = false;
1426 bool show_hud = true;
1427 bool show_chat = true;
1428 bool force_fog_off = false;
1429 f32 fog_range = 100*BS;
1430 bool disable_camera_update = false;
1431 bool show_debug = g_settings->getBool("show_debug");
1432 bool show_profiler_graph = false;
1433 u32 show_profiler = 0;
1434 u32 show_profiler_max = 3; // Number of pages
1436 float time_of_day = 0;
1437 float time_of_day_smooth = 0;
1439 float repeat_rightclick_timer = 0;
1444 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1445 sky, &force_fog_off, &fog_range, &client));
1451 bool first_loop_after_window_activation = true;
1453 // TODO: Convert the static interval timers to these
1454 // Interval limiter for profiler
1455 IntervalLimiter m_profiler_interval;
1457 // Time is in milliseconds
1458 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1459 // NOTE: So we have to use getTime() and call run()s between them
1460 u32 lasttime = device->getTimer()->getTime();
1462 LocalPlayer* player = client.getEnv().getLocalPlayer();
1463 player->hurt_tilt_timer = 0;
1464 player->hurt_tilt_strength = 0;
1469 Hud hud(driver, guienv, font, text_height,
1470 gamedef, player, &local_inventory);
1474 if(device->run() == false || kill == true)
1477 // Time of frame without fps limit
1481 // not using getRealTime is necessary for wine
1482 u32 time = device->getTimer()->getTime();
1484 busytime_u32 = time - lasttime;
1487 busytime = busytime_u32 / 1000.0;
1490 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1492 // Necessary for device->getTimer()->getTime()
1500 float fps_max = g_settings->getFloat("fps_max");
1501 u32 frametime_min = 1000./fps_max;
1503 if(busytime_u32 < frametime_min)
1505 u32 sleeptime = frametime_min - busytime_u32;
1506 device->sleep(sleeptime);
1507 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1511 // Necessary for device->getTimer()->getTime()
1515 Time difference calculation
1517 f32 dtime; // in seconds
1519 u32 time = device->getTimer()->getTime();
1521 dtime = (time - lasttime) / 1000.0;
1526 g_profiler->graphAdd("mainloop_dtime", dtime);
1530 if(nodig_delay_timer >= 0)
1531 nodig_delay_timer -= dtime;
1532 if(object_hit_delay_timer >= 0)
1533 object_hit_delay_timer -= dtime;
1534 time_from_last_punch += dtime;
1536 g_profiler->add("Elapsed time", dtime);
1537 g_profiler->avg("FPS", 1./dtime);
1540 Time average and jitter calculation
1543 static f32 dtime_avg1 = 0.0;
1544 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1545 f32 dtime_jitter1 = dtime - dtime_avg1;
1547 static f32 dtime_jitter1_max_sample = 0.0;
1548 static f32 dtime_jitter1_max_fraction = 0.0;
1550 static f32 jitter1_max = 0.0;
1551 static f32 counter = 0.0;
1552 if(dtime_jitter1 > jitter1_max)
1553 jitter1_max = dtime_jitter1;
1558 dtime_jitter1_max_sample = jitter1_max;
1559 dtime_jitter1_max_fraction
1560 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1566 Busytime average and jitter calculation
1569 static f32 busytime_avg1 = 0.0;
1570 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1571 f32 busytime_jitter1 = busytime - busytime_avg1;
1573 static f32 busytime_jitter1_max_sample = 0.0;
1574 static f32 busytime_jitter1_min_sample = 0.0;
1576 static f32 jitter1_max = 0.0;
1577 static f32 jitter1_min = 0.0;
1578 static f32 counter = 0.0;
1579 if(busytime_jitter1 > jitter1_max)
1580 jitter1_max = busytime_jitter1;
1581 if(busytime_jitter1 < jitter1_min)
1582 jitter1_min = busytime_jitter1;
1586 busytime_jitter1_max_sample = jitter1_max;
1587 busytime_jitter1_min_sample = jitter1_min;
1594 Handle miscellaneous stuff
1597 if(client.accessDenied())
1599 error_message = L"Access denied. Reason: "
1600 +client.accessDeniedReason();
1601 errorstream<<wide_to_narrow(error_message)<<std::endl;
1605 if(g_gamecallback->disconnect_requested)
1607 g_gamecallback->disconnect_requested = false;
1611 if(g_gamecallback->changepassword_requested)
1613 (new GUIPasswordChange(guienv, guiroot, -1,
1614 &g_menumgr, &client))->drop();
1615 g_gamecallback->changepassword_requested = false;
1618 if(g_gamecallback->changevolume_requested)
1620 (new GUIVolumeChange(guienv, guiroot, -1,
1621 &g_menumgr, &client))->drop();
1622 g_gamecallback->changevolume_requested = false;
1625 /* Process TextureSource's queue */
1626 tsrc->processQueue();
1628 /* Process ItemDefManager's queue */
1629 itemdef->processQueue(gamedef);
1632 Process ShaderSource's queue
1634 shsrc->processQueue();
1639 last_screensize = screensize;
1640 screensize = driver->getScreenSize();
1641 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1642 //bool screensize_changed = screensize != last_screensize;
1645 // Update HUD values
1646 hud.screensize = screensize;
1647 hud.displaycenter = displaycenter;
1650 // Hilight boxes collected during the loop and displayed
1651 std::vector<aabb3f> hilightboxes;
1654 std::wstring infotext;
1657 Debug info for client
1660 static float counter = 0.0;
1665 client.printDebugInfo(infostream);
1672 float profiler_print_interval =
1673 g_settings->getFloat("profiler_print_interval");
1674 bool print_to_log = true;
1675 if(profiler_print_interval == 0){
1676 print_to_log = false;
1677 profiler_print_interval = 5;
1679 if(m_profiler_interval.step(dtime, profiler_print_interval))
1682 infostream<<"Profiler:"<<std::endl;
1683 g_profiler->print(infostream);
1686 update_profiler_gui(guitext_profiler, font, text_height,
1687 show_profiler, show_profiler_max);
1689 g_profiler->clear();
1693 Direct handling of user input
1696 // Reset input if window not active or some menu is active
1697 if(device->isWindowActive() == false
1698 || noMenuActive() == false
1699 || guienv->hasFocus(gui_chat_console))
1703 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1705 gui_chat_console->closeConsoleAtOnce();
1708 // Input handler step() (used by the random input generator)
1711 // Increase timer for doubleclick of "jump"
1712 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1713 jump_timer += dtime;
1716 Launch menus and trigger stuff according to keys
1718 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1720 // drop selected item
1721 IDropAction *a = new IDropAction();
1723 a->from_inv.setCurrentPlayer();
1724 a->from_list = "main";
1725 a->from_i = client.getPlayerItem();
1726 client.inventoryAction(a);
1728 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1730 infostream<<"the_game: "
1731 <<"Launching inventory"<<std::endl;
1733 GUIFormSpecMenu *menu =
1734 new GUIFormSpecMenu(device, guiroot, -1,
1738 InventoryLocation inventoryloc;
1739 inventoryloc.setCurrentPlayer();
1741 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1743 menu->setFormSpec(src->getForm(), inventoryloc);
1744 menu->setFormSource(src);
1745 menu->setTextDest(new TextDestPlayerInventory(&client));
1748 else if(input->wasKeyDown(EscapeKey))
1750 infostream<<"the_game: "
1751 <<"Launching pause menu"<<std::endl;
1752 // It will delete itself by itself
1753 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1754 &g_menumgr, simple_singleplayer_mode))->drop();
1756 // Move mouse cursor on top of the disconnect button
1757 if(simple_singleplayer_mode)
1758 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1760 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1762 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1764 TextDest *dest = new TextDestChat(&client);
1766 (new GUITextInputMenu(guienv, guiroot, -1,
1770 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1772 TextDest *dest = new TextDestChat(&client);
1774 (new GUITextInputMenu(guienv, guiroot, -1,
1778 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1780 if (!gui_chat_console->isOpenInhibited())
1782 // Open up to over half of the screen
1783 gui_chat_console->openConsole(0.6);
1784 guienv->setFocus(gui_chat_console);
1787 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1789 if(g_settings->getBool("free_move"))
1791 g_settings->set("free_move","false");
1792 statustext = L"free_move disabled";
1793 statustext_time = 0;
1797 g_settings->set("free_move","true");
1798 statustext = L"free_move enabled";
1799 statustext_time = 0;
1800 if(!client.checkPrivilege("fly"))
1801 statustext += L" (note: no 'fly' privilege)";
1804 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1806 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1808 if(g_settings->getBool("free_move"))
1810 g_settings->set("free_move","false");
1811 statustext = L"free_move disabled";
1812 statustext_time = 0;
1816 g_settings->set("free_move","true");
1817 statustext = L"free_move enabled";
1818 statustext_time = 0;
1819 if(!client.checkPrivilege("fly"))
1820 statustext += L" (note: no 'fly' privilege)";
1823 reset_jump_timer = true;
1825 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1827 if(g_settings->getBool("fast_move"))
1829 g_settings->set("fast_move","false");
1830 statustext = L"fast_move disabled";
1831 statustext_time = 0;
1835 g_settings->set("fast_move","true");
1836 statustext = L"fast_move enabled";
1837 statustext_time = 0;
1838 if(!client.checkPrivilege("fast"))
1839 statustext += L" (note: no 'fast' privilege)";
1842 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1844 if(g_settings->getBool("noclip"))
1846 g_settings->set("noclip","false");
1847 statustext = L"noclip disabled";
1848 statustext_time = 0;
1852 g_settings->set("noclip","true");
1853 statustext = L"noclip enabled";
1854 statustext_time = 0;
1855 if(!client.checkPrivilege("noclip"))
1856 statustext += L" (note: no 'noclip' privilege)";
1859 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1861 irr::video::IImage* const image = driver->createScreenShot();
1863 irr::c8 filename[256];
1864 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1865 g_settings->get("screenshot_path").c_str(),
1866 device->getTimer()->getRealTime());
1867 if (driver->writeImageToFile(image, filename)) {
1868 std::wstringstream sstr;
1869 sstr<<"Saved screenshot to '"<<filename<<"'";
1870 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1871 statustext = sstr.str();
1872 statustext_time = 0;
1874 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1879 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1881 show_hud = !show_hud;
1883 statustext = L"HUD shown";
1885 statustext = L"HUD hidden";
1886 statustext_time = 0;
1888 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1890 show_chat = !show_chat;
1892 statustext = L"Chat shown";
1894 statustext = L"Chat hidden";
1895 statustext_time = 0;
1897 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1899 force_fog_off = !force_fog_off;
1901 statustext = L"Fog disabled";
1903 statustext = L"Fog enabled";
1904 statustext_time = 0;
1906 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1908 disable_camera_update = !disable_camera_update;
1909 if(disable_camera_update)
1910 statustext = L"Camera update disabled";
1912 statustext = L"Camera update enabled";
1913 statustext_time = 0;
1915 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1917 // Initial / 3x toggle: Chat only
1918 // 1x toggle: Debug text with chat
1919 // 2x toggle: Debug text with profiler graph
1923 show_profiler_graph = false;
1924 statustext = L"Debug info shown";
1925 statustext_time = 0;
1927 else if(show_profiler_graph)
1930 show_profiler_graph = false;
1931 statustext = L"Debug info and profiler graph hidden";
1932 statustext_time = 0;
1936 show_profiler_graph = true;
1937 statustext = L"Profiler graph shown";
1938 statustext_time = 0;
1941 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1943 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1945 // FIXME: This updates the profiler with incomplete values
1946 update_profiler_gui(guitext_profiler, font, text_height,
1947 show_profiler, show_profiler_max);
1949 if(show_profiler != 0)
1951 std::wstringstream sstr;
1952 sstr<<"Profiler shown (page "<<show_profiler
1953 <<" of "<<show_profiler_max<<")";
1954 statustext = sstr.str();
1955 statustext_time = 0;
1959 statustext = L"Profiler hidden";
1960 statustext_time = 0;
1963 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1965 s16 range = g_settings->getS16("viewing_range_nodes_min");
1966 s16 range_new = range + 10;
1967 g_settings->set("viewing_range_nodes_min", itos(range_new));
1968 statustext = narrow_to_wide(
1969 "Minimum viewing range changed to "
1971 statustext_time = 0;
1973 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1975 s16 range = g_settings->getS16("viewing_range_nodes_min");
1976 s16 range_new = range - 10;
1979 g_settings->set("viewing_range_nodes_min",
1981 statustext = narrow_to_wide(
1982 "Minimum viewing range changed to "
1984 statustext_time = 0;
1988 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1990 reset_jump_timer = false;
1994 // Handle QuicktuneShortcutter
1995 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1997 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1999 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2001 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2004 std::string msg = quicktune.getMessage();
2006 statustext = narrow_to_wide(msg);
2007 statustext_time = 0;
2011 // Item selection with mouse wheel
2012 u16 new_playeritem = client.getPlayerItem();
2014 s32 wheel = input->getMouseWheel();
2015 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2016 player->hud_hotbar_itemcount-1);
2020 if(new_playeritem < max_item)
2027 if(new_playeritem > 0)
2030 new_playeritem = max_item;
2035 for(u16 i=0; i<10; i++)
2037 const KeyPress *kp = NumberKey + (i + 1) % 10;
2038 if(input->wasKeyDown(*kp))
2040 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2044 infostream<<"Selected item: "
2045 <<new_playeritem<<std::endl;
2050 // Viewing range selection
2051 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2053 draw_control.range_all = !draw_control.range_all;
2054 if(draw_control.range_all)
2056 infostream<<"Enabled full viewing range"<<std::endl;
2057 statustext = L"Enabled full viewing range";
2058 statustext_time = 0;
2062 infostream<<"Disabled full viewing range"<<std::endl;
2063 statustext = L"Disabled full viewing range";
2064 statustext_time = 0;
2068 // Print debug stacks
2069 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2071 dstream<<"-----------------------------------------"
2073 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2074 dstream<<"-----------------------------------------"
2076 debug_stacks_print();
2080 Mouse and camera control
2081 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2084 float turn_amount = 0;
2085 if((device->isWindowActive() && noMenuActive()) || random_input)
2089 // Mac OSX gets upset if this is set every frame
2090 if(device->getCursorControl()->isVisible())
2091 device->getCursorControl()->setVisible(false);
2094 if(first_loop_after_window_activation){
2095 //infostream<<"window active, first loop"<<std::endl;
2096 first_loop_after_window_activation = false;
2099 s32 dx = input->getMousePos().X - displaycenter.X;
2100 s32 dy = input->getMousePos().Y - displaycenter.Y;
2103 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2105 /*const float keyspeed = 500;
2106 if(input->isKeyDown(irr::KEY_UP))
2107 dy -= dtime * keyspeed;
2108 if(input->isKeyDown(irr::KEY_DOWN))
2109 dy += dtime * keyspeed;
2110 if(input->isKeyDown(irr::KEY_LEFT))
2111 dx -= dtime * keyspeed;
2112 if(input->isKeyDown(irr::KEY_RIGHT))
2113 dx += dtime * keyspeed;*/
2115 float d = g_settings->getFloat("mouse_sensitivity");
2116 d = rangelim(d, 0.01, 100.0);
2118 camera_pitch += dy*d;
2119 if(camera_pitch < -89.5) camera_pitch = -89.5;
2120 if(camera_pitch > 89.5) camera_pitch = 89.5;
2122 turn_amount = v2f(dx, dy).getLength() * d;
2124 input->setMousePos(displaycenter.X, displaycenter.Y);
2127 // Mac OSX gets upset if this is set every frame
2128 if(device->getCursorControl()->isVisible() == false)
2129 device->getCursorControl()->setVisible(true);
2131 //infostream<<"window inactive"<<std::endl;
2132 first_loop_after_window_activation = true;
2134 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2135 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2138 Player speed control
2152 PlayerControl control(
2153 input->isKeyDown(getKeySetting("keymap_forward")),
2154 input->isKeyDown(getKeySetting("keymap_backward")),
2155 input->isKeyDown(getKeySetting("keymap_left")),
2156 input->isKeyDown(getKeySetting("keymap_right")),
2157 input->isKeyDown(getKeySetting("keymap_jump")),
2158 input->isKeyDown(getKeySetting("keymap_special1")),
2159 input->isKeyDown(getKeySetting("keymap_sneak")),
2160 input->getLeftState(),
2161 input->getRightState(),
2165 client.setPlayerControl(control);
2167 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2168 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2169 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2170 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2171 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2172 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2173 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2174 128*(int)input->getLeftState()+
2175 256*(int)input->getRightState();
2176 LocalPlayer* player = client.getEnv().getLocalPlayer();
2177 player->keyPressed=keyPressed;
2186 //TimeTaker timer("server->step(dtime)");
2187 server->step(dtime);
2195 //TimeTaker timer("client.step(dtime)");
2197 //client.step(dtime_avg1);
2201 // Read client events
2204 ClientEvent event = client.getClientEvent();
2205 if(event.type == CE_NONE)
2209 else if(event.type == CE_PLAYER_DAMAGE &&
2210 client.getHP() != 0)
2212 //u16 damage = event.player_damage.amount;
2213 //infostream<<"Player damage: "<<damage<<std::endl;
2215 damage_flash += 100.0;
2216 damage_flash += 8.0 * event.player_damage.amount;
2218 player->hurt_tilt_timer = 1.5;
2219 player->hurt_tilt_strength = event.player_damage.amount/2;
2220 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2222 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2223 gamedef->event()->put(e);
2225 else if(event.type == CE_PLAYER_FORCE_MOVE)
2227 camera_yaw = event.player_force_move.yaw;
2228 camera_pitch = event.player_force_move.pitch;
2230 else if(event.type == CE_DEATHSCREEN)
2232 if(respawn_menu_active)
2235 /*bool set_camera_point_target =
2236 event.deathscreen.set_camera_point_target;
2237 v3f camera_point_target;
2238 camera_point_target.X = event.deathscreen.camera_point_target_x;
2239 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2240 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2241 MainRespawnInitiator *respawner =
2242 new MainRespawnInitiator(
2243 &respawn_menu_active, &client);
2244 GUIDeathScreen *menu =
2245 new GUIDeathScreen(guienv, guiroot, -1,
2246 &g_menumgr, respawner);
2249 chat_backend.addMessage(L"", L"You died.");
2251 /* Handle visualization */
2255 LocalPlayer* player = client.getEnv().getLocalPlayer();
2256 player->hurt_tilt_timer = 0;
2257 player->hurt_tilt_strength = 0;
2259 /*LocalPlayer* player = client.getLocalPlayer();
2260 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2261 camera.update(player, busytime, screensize);*/
2263 else if (event.type == CE_SHOW_FORMSPEC)
2265 if (current_formspec == 0)
2268 /* Note: FormspecFormSource and TextDestPlayerInventory
2269 * are deleted by guiFormSpecMenu */
2270 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2271 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2272 GUIFormSpecMenu *menu =
2273 new GUIFormSpecMenu(device, guiroot, -1,
2276 menu->setFormSource(current_formspec);
2277 menu->setTextDest(current_textdest);
2282 assert(current_textdest != 0);
2284 current_textdest->setFormName(*(event.show_formspec.formname));
2285 current_formspec->setForm(*(event.show_formspec.formspec));
2287 delete(event.show_formspec.formspec);
2288 delete(event.show_formspec.formname);
2290 else if(event.type == CE_TEXTURES_UPDATED)
2292 update_wielded_item_trigger = true;
2294 else if(event.type == CE_SPAWN_PARTICLE)
2296 LocalPlayer* player = client.getEnv().getLocalPlayer();
2297 video::ITexture *texture =
2298 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2300 new Particle(gamedef, smgr, player, client.getEnv(),
2301 *event.spawn_particle.pos,
2302 *event.spawn_particle.vel,
2303 *event.spawn_particle.acc,
2304 event.spawn_particle.expirationtime,
2305 event.spawn_particle.size,
2306 event.spawn_particle.collisiondetection,
2311 else if(event.type == CE_ADD_PARTICLESPAWNER)
2313 LocalPlayer* player = client.getEnv().getLocalPlayer();
2314 video::ITexture *texture =
2315 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2317 new ParticleSpawner(gamedef, smgr, player,
2318 event.add_particlespawner.amount,
2319 event.add_particlespawner.spawntime,
2320 *event.add_particlespawner.minpos,
2321 *event.add_particlespawner.maxpos,
2322 *event.add_particlespawner.minvel,
2323 *event.add_particlespawner.maxvel,
2324 *event.add_particlespawner.minacc,
2325 *event.add_particlespawner.maxacc,
2326 event.add_particlespawner.minexptime,
2327 event.add_particlespawner.maxexptime,
2328 event.add_particlespawner.minsize,
2329 event.add_particlespawner.maxsize,
2330 event.add_particlespawner.collisiondetection,
2332 event.add_particlespawner.id);
2334 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2336 delete_particlespawner (event.delete_particlespawner.id);
2338 else if (event.type == CE_HUDADD)
2340 u32 id = event.hudadd.id;
2341 size_t nhudelem = player->hud.size();
2342 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2343 delete event.hudadd.pos;
2344 delete event.hudadd.name;
2345 delete event.hudadd.scale;
2346 delete event.hudadd.text;
2347 delete event.hudadd.align;
2348 delete event.hudadd.offset;
2352 HudElement *e = new HudElement;
2353 e->type = (HudElementType)event.hudadd.type;
2354 e->pos = *event.hudadd.pos;
2355 e->name = *event.hudadd.name;
2356 e->scale = *event.hudadd.scale;
2357 e->text = *event.hudadd.text;
2358 e->number = event.hudadd.number;
2359 e->item = event.hudadd.item;
2360 e->dir = event.hudadd.dir;
2361 e->align = *event.hudadd.align;
2362 e->offset = *event.hudadd.offset;
2365 player->hud.push_back(e);
2367 player->hud[id] = e;
2369 delete event.hudadd.pos;
2370 delete event.hudadd.name;
2371 delete event.hudadd.scale;
2372 delete event.hudadd.text;
2373 delete event.hudadd.align;
2374 delete event.hudadd.offset;
2376 else if (event.type == CE_HUDRM)
2378 u32 id = event.hudrm.id;
2379 if (id < player->hud.size() && player->hud[id]) {
2380 delete player->hud[id];
2381 player->hud[id] = NULL;
2384 else if (event.type == CE_HUDCHANGE)
2386 u32 id = event.hudchange.id;
2387 if (id >= player->hud.size() || !player->hud[id]) {
2388 delete event.hudchange.v2fdata;
2389 delete event.hudchange.sdata;
2393 HudElement* e = player->hud[id];
2394 switch (event.hudchange.stat) {
2396 e->pos = *event.hudchange.v2fdata;
2399 e->name = *event.hudchange.sdata;
2401 case HUD_STAT_SCALE:
2402 e->scale = *event.hudchange.v2fdata;
2405 e->text = *event.hudchange.sdata;
2407 case HUD_STAT_NUMBER:
2408 e->number = event.hudchange.data;
2411 e->item = event.hudchange.data;
2414 e->dir = event.hudchange.data;
2416 case HUD_STAT_ALIGN:
2417 e->align = *event.hudchange.v2fdata;
2419 case HUD_STAT_OFFSET:
2420 e->offset = *event.hudchange.v2fdata;
2424 delete event.hudchange.v2fdata;
2425 delete event.hudchange.sdata;
2430 //TimeTaker //timer2("//timer2");
2433 For interaction purposes, get info about the held item
2435 - Is it a usable item?
2436 - Can it point to liquids?
2438 ItemStack playeritem;
2440 InventoryList *mlist = local_inventory.getList("main");
2443 playeritem = mlist->getItem(client.getPlayerItem());
2446 const ItemDefinition &playeritem_def =
2447 playeritem.getDefinition(itemdef);
2448 ToolCapabilities playeritem_toolcap =
2449 playeritem.getToolCapabilities(itemdef);
2455 LocalPlayer* player = client.getEnv().getLocalPlayer();
2456 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2457 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2458 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2459 camera.update(player, busytime, screensize, tool_reload_ratio);
2462 v3f player_position = player->getPosition();
2463 v3s16 pos_i = floatToInt(player_position, BS);
2464 v3f camera_position = camera.getPosition();
2465 v3f camera_direction = camera.getDirection();
2466 f32 camera_fov = camera.getFovMax();
2468 if(!disable_camera_update){
2469 client.getEnv().getClientMap().updateCamera(camera_position,
2470 camera_direction, camera_fov);
2473 // Update sound listener
2474 sound->updateListener(camera.getCameraNode()->getPosition(),
2475 v3f(0,0,0), // velocity
2476 camera.getDirection(),
2477 camera.getCameraNode()->getUpVector());
2478 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2484 soundmaker.step(dtime);
2486 ClientMap &map = client.getEnv().getClientMap();
2487 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2488 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2492 Calculate what block is the crosshair pointing to
2495 //u32 t1 = device->getTimer()->getRealTime();
2497 f32 d = playeritem_def.range; // max. distance
2498 f32 d_hand = itemdef->get("").range;
2499 if(d < 0 && d_hand >= 0)
2503 core::line3d<f32> shootline(camera_position,
2504 camera_position + camera_direction * BS * (d+1));
2506 ClientActiveObject *selected_object = NULL;
2508 PointedThing pointed = getPointedThing(
2510 &client, player_position, camera_direction,
2511 camera_position, shootline, d,
2512 playeritem_def.liquids_pointable, !ldown_for_dig,
2517 if(pointed != pointed_old)
2519 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2520 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2525 - releasing left mouse button
2526 - pointing away from node
2530 if(input->getLeftReleased())
2532 infostream<<"Left button released"
2533 <<" (stopped digging)"<<std::endl;
2536 else if(pointed != pointed_old)
2538 if (pointed.type == POINTEDTHING_NODE
2539 && pointed_old.type == POINTEDTHING_NODE
2540 && pointed.node_undersurface == pointed_old.node_undersurface)
2542 // Still pointing to the same node,
2543 // but a different face. Don't reset.
2547 infostream<<"Pointing away from node"
2548 <<" (stopped digging)"<<std::endl;
2554 client.interact(1, pointed_old);
2555 client.setCrack(-1, v3s16(0,0,0));
2559 if(!digging && ldown_for_dig && !input->getLeftState())
2561 ldown_for_dig = false;
2564 bool left_punch = false;
2565 soundmaker.m_player_leftpunch_sound.name = "";
2567 if(input->getRightState())
2568 repeat_rightclick_timer += dtime;
2570 repeat_rightclick_timer = 0;
2572 if(playeritem_def.usable && input->getLeftState())
2574 if(input->getLeftClicked())
2575 client.interact(4, pointed);
2577 else if(pointed.type == POINTEDTHING_NODE)
2579 v3s16 nodepos = pointed.node_undersurface;
2580 v3s16 neighbourpos = pointed.node_abovesurface;
2583 Check information text of node
2586 ClientMap &map = client.getEnv().getClientMap();
2587 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2589 infotext = narrow_to_wide(meta->getString("infotext"));
2591 MapNode n = map.getNode(nodepos);
2592 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2593 infotext = L"Unknown node: ";
2594 infotext += narrow_to_wide(nodedef->get(n).name);
2602 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2603 && client.checkPrivilege("interact"))
2607 infostream<<"Started digging"<<std::endl;
2608 client.interact(0, pointed);
2610 ldown_for_dig = true;
2612 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2614 // NOTE: Similar piece of code exists on the server side for
2616 // Get digging parameters
2617 DigParams params = getDigParams(nodedef->get(n).groups,
2618 &playeritem_toolcap);
2619 // If can't dig, try hand
2620 if(!params.diggable){
2621 const ItemDefinition &hand = itemdef->get("");
2622 const ToolCapabilities *tp = hand.tool_capabilities;
2624 params = getDigParams(nodedef->get(n).groups, tp);
2627 float dig_time_complete = 0.0;
2629 if(params.diggable == false)
2631 // I guess nobody will wait for this long
2632 dig_time_complete = 10000000.0;
2636 dig_time_complete = params.time;
2637 if (g_settings->getBool("enable_particles"))
2639 const ContentFeatures &features =
2640 client.getNodeDefManager()->get(n);
2641 addPunchingParticles
2642 (gamedef, smgr, player, client.getEnv(),
2643 nodepos, features.tiles);
2647 if(dig_time_complete >= 0.001)
2649 dig_index = (u16)((float)crack_animation_length
2650 * dig_time/dig_time_complete);
2652 // This is for torches
2655 dig_index = crack_animation_length;
2658 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2659 if(sound_dig.exists() && params.diggable){
2660 if(sound_dig.name == "__group"){
2661 if(params.main_group != ""){
2662 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2663 soundmaker.m_player_leftpunch_sound.name =
2664 std::string("default_dig_") +
2668 soundmaker.m_player_leftpunch_sound = sound_dig;
2672 // Don't show cracks if not diggable
2673 if(dig_time_complete >= 100000.0)
2676 else if(dig_index < crack_animation_length)
2678 //TimeTaker timer("client.setTempMod");
2679 //infostream<<"dig_index="<<dig_index<<std::endl;
2680 client.setCrack(dig_index, nodepos);
2684 infostream<<"Digging completed"<<std::endl;
2685 client.interact(2, pointed);
2686 client.setCrack(-1, v3s16(0,0,0));
2687 MapNode wasnode = map.getNode(nodepos);
2688 client.removeNode(nodepos);
2690 if (g_settings->getBool("enable_particles"))
2692 const ContentFeatures &features =
2693 client.getNodeDefManager()->get(wasnode);
2695 (gamedef, smgr, player, client.getEnv(),
2696 nodepos, features.tiles);
2702 nodig_delay_timer = dig_time_complete
2703 / (float)crack_animation_length;
2705 // We don't want a corresponding delay to
2706 // very time consuming nodes
2707 if(nodig_delay_timer > 0.3)
2708 nodig_delay_timer = 0.3;
2709 // We want a slight delay to very little
2710 // time consuming nodes
2711 float mindelay = 0.15;
2712 if(nodig_delay_timer < mindelay)
2713 nodig_delay_timer = mindelay;
2715 // Send event to trigger sound
2716 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2717 gamedef->event()->put(e);
2720 if(dig_time_complete < 100000.0)
2724 client.setCrack(-1, nodepos);
2727 camera.setDigging(0); // left click animation
2730 if((input->getRightClicked() ||
2731 repeat_rightclick_timer >=
2732 g_settings->getFloat("repeat_rightclick_time")) &&
2733 client.checkPrivilege("interact"))
2735 repeat_rightclick_timer = 0;
2736 infostream<<"Ground right-clicked"<<std::endl;
2738 // Sign special case, at least until formspec is properly implemented.
2740 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2742 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2744 infostream<<"Launching metadata text input"<<std::endl;
2746 // Get a new text for it
2748 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2750 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2752 (new GUITextInputMenu(guienv, guiroot, -1,
2756 // If metadata provides an inventory view, activate it
2757 else if(meta && meta->getString("formspec") != "" && !random_input
2758 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2760 infostream<<"Launching custom inventory view"<<std::endl;
2762 InventoryLocation inventoryloc;
2763 inventoryloc.setNodeMeta(nodepos);
2767 GUIFormSpecMenu *menu =
2768 new GUIFormSpecMenu(device, guiroot, -1,
2771 menu->setFormSpec(meta->getString("formspec"),
2773 menu->setFormSource(new NodeMetadataFormSource(
2774 &client.getEnv().getClientMap(), nodepos));
2775 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2778 // Otherwise report right click to server
2782 client.interact(3, pointed);
2783 camera.setDigging(1); // right click animation
2785 // If the wielded item has node placement prediction,
2787 bool placed = nodePlacementPrediction(client,
2789 nodepos, neighbourpos);
2793 soundmaker.m_player_rightpunch_sound =
2794 playeritem_def.sound_place;
2796 soundmaker.m_player_rightpunch_sound =
2801 else if(pointed.type == POINTEDTHING_OBJECT)
2803 infotext = narrow_to_wide(selected_object->infoText());
2805 if(infotext == L"" && show_debug){
2806 infotext = narrow_to_wide(selected_object->debugInfoText());
2809 //if(input->getLeftClicked())
2810 if(input->getLeftState())
2812 bool do_punch = false;
2813 bool do_punch_damage = false;
2814 if(object_hit_delay_timer <= 0.0){
2816 do_punch_damage = true;
2817 object_hit_delay_timer = object_hit_delay;
2819 if(input->getLeftClicked()){
2823 infostream<<"Left-clicked object"<<std::endl;
2826 if(do_punch_damage){
2827 // Report direct punch
2828 v3f objpos = selected_object->getPosition();
2829 v3f dir = (objpos - player_position).normalize();
2831 bool disable_send = selected_object->directReportPunch(
2832 dir, &playeritem, time_from_last_punch);
2833 time_from_last_punch = 0;
2835 client.interact(0, pointed);
2838 else if(input->getRightClicked())
2840 infostream<<"Right-clicked object"<<std::endl;
2841 client.interact(3, pointed); // place
2844 else if(input->getLeftState())
2846 // When button is held down in air, show continuous animation
2850 pointed_old = pointed;
2852 if(left_punch || input->getLeftClicked())
2854 camera.setDigging(0); // left click animation
2857 input->resetLeftClicked();
2858 input->resetRightClicked();
2860 input->resetLeftReleased();
2861 input->resetRightReleased();
2864 Calculate stuff for drawing
2873 fog_range = BS*farmesh_range;
2877 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2879 if(draw_control.range_all)
2880 fog_range = 100000*BS;
2884 Calculate general brightness
2886 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2887 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2888 float direct_brightness = 0;
2889 bool sunlight_seen = false;
2890 if(g_settings->getBool("free_move")){
2891 direct_brightness = time_brightness;
2892 sunlight_seen = true;
2894 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2895 float old_brightness = sky->getBrightness();
2896 direct_brightness = (float)client.getEnv().getClientMap()
2897 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2898 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2902 time_of_day = client.getEnv().getTimeOfDayF();
2904 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2905 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2906 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2907 time_of_day_smooth = time_of_day;
2909 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2910 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2911 + (time_of_day+1.0) * todsm;
2913 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2914 + time_of_day * todsm;
2916 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2919 float brightness = sky->getBrightness();
2920 video::SColor bgcolor = sky->getBgColor();
2921 video::SColor skycolor = sky->getSkyColor();
2927 if(sky->getCloudsVisible()){
2928 clouds->setVisible(true);
2929 clouds->step(dtime);
2930 clouds->update(v2f(player_position.X, player_position.Z),
2931 sky->getCloudColor());
2933 clouds->setVisible(false);
2942 farmesh_range = draw_control.wanted_range * 10;
2943 if(draw_control.range_all && farmesh_range < 500)
2944 farmesh_range = 500;
2945 if(farmesh_range > 1000)
2946 farmesh_range = 1000;
2948 farmesh->step(dtime);
2949 farmesh->update(v2f(player_position.X, player_position.Z),
2950 brightness, farmesh_range);
2957 allparticles_step(dtime, client.getEnv());
2958 allparticlespawners_step(dtime, client.getEnv());
2964 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2968 video::EFT_FOG_LINEAR,
2980 video::EFT_FOG_LINEAR,
2990 Update gui stuff (0ms)
2993 //TimeTaker guiupdatetimer("Gui updating");
2995 const char program_name_and_version[] =
2996 "Minetest " VERSION_STRING;
3000 static float drawtime_avg = 0;
3001 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3002 /*static float beginscenetime_avg = 0;
3003 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3004 static float scenetime_avg = 0;
3005 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3006 static float endscenetime_avg = 0;
3007 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3009 std::ostringstream os(std::ios_base::binary);
3011 <<program_name_and_version
3012 <<" (R: range_all="<<draw_control.range_all<<")"
3013 <<std::setprecision(0)
3014 <<" drawtime = "<<drawtime_avg
3015 <<std::setprecision(1)
3016 <<", dtime_jitter = "
3017 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3018 <<std::setprecision(1)
3019 <<", v_range = "<<draw_control.wanted_range
3020 <<std::setprecision(3)
3021 <<", RTT = "<<client.getRTT();
3022 guitext->setText(narrow_to_wide(os.str()).c_str());
3023 guitext->setVisible(true);
3025 else if(show_hud || show_chat)
3027 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
3028 guitext->setVisible(true);
3032 guitext->setVisible(false);
3037 std::ostringstream os(std::ios_base::binary);
3038 os<<std::setprecision(1)<<std::fixed
3039 <<"(" <<(player_position.X/BS)
3040 <<", "<<(player_position.Y/BS)
3041 <<", "<<(player_position.Z/BS)
3042 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3043 <<") (t="<<client.getEnv().getClientMap().getHeat(pos_i)
3044 <<"C, h="<<client.getEnv().getClientMap().getHumidity(pos_i)
3045 <<"%) (seed = "<<((unsigned long long)client.getMapSeed())
3047 guitext2->setText(narrow_to_wide(os.str()).c_str());
3048 guitext2->setVisible(true);
3052 guitext2->setVisible(false);
3056 guitext_info->setText(infotext.c_str());
3057 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3061 float statustext_time_max = 1.5;
3062 if(!statustext.empty())
3064 statustext_time += dtime;
3065 if(statustext_time >= statustext_time_max)
3068 statustext_time = 0;
3071 guitext_status->setText(statustext.c_str());
3072 guitext_status->setVisible(!statustext.empty());
3074 if(!statustext.empty())
3076 s32 status_y = screensize.Y - 130;
3077 core::rect<s32> rect(
3079 status_y - guitext_status->getTextHeight(),
3083 guitext_status->setRelativePosition(rect);
3086 video::SColor initial_color(255,0,0,0);
3087 if(guienv->getSkin())
3088 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3089 video::SColor final_color = initial_color;
3090 final_color.setAlpha(0);
3091 video::SColor fade_color =
3092 initial_color.getInterpolated_quadratic(
3095 pow(statustext_time / (float)statustext_time_max, 2.0f));
3096 guitext_status->setOverrideColor(fade_color);
3097 guitext_status->enableOverrideColor(true);
3102 Get chat messages from client
3105 // Get new messages from error log buffer
3106 while(!chat_log_error_buf.empty())
3108 chat_backend.addMessage(L"", narrow_to_wide(
3109 chat_log_error_buf.get()));
3111 // Get new messages from client
3112 std::wstring message;
3113 while(client.getChatMessage(message))
3115 chat_backend.addUnparsedMessage(message);
3117 // Remove old messages
3118 chat_backend.step(dtime);
3120 // Display all messages in a static text element
3121 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3122 std::wstring recent_chat = chat_backend.getRecentChat();
3123 guitext_chat->setText(recent_chat.c_str());
3125 // Update gui element size and position
3126 s32 chat_y = 5+(text_height+5);
3128 chat_y += (text_height+5);
3129 core::rect<s32> rect(
3133 chat_y + guitext_chat->getTextHeight()
3135 guitext_chat->setRelativePosition(rect);
3137 // Don't show chat if disabled or empty or profiler is enabled
3138 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3146 if(client.getPlayerItem() != new_playeritem)
3148 client.selectPlayerItem(new_playeritem);
3150 if(client.getLocalInventoryUpdated())
3152 //infostream<<"Updating local inventory"<<std::endl;
3153 client.getLocalInventory(local_inventory);
3155 update_wielded_item_trigger = true;
3157 if(update_wielded_item_trigger)
3159 update_wielded_item_trigger = false;
3160 // Update wielded tool
3161 InventoryList *mlist = local_inventory.getList("main");
3164 item = mlist->getItem(client.getPlayerItem());
3165 camera.wield(item, client.getPlayerItem());
3169 Update block draw list every 200ms or when camera direction has
3172 update_draw_list_timer += dtime;
3173 if(update_draw_list_timer >= 0.2 ||
3174 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3175 update_draw_list_timer = 0;
3176 client.getEnv().getClientMap().updateDrawList(driver);
3177 update_draw_list_last_cam_dir = camera_direction;
3184 TimeTaker tt_draw("mainloop: draw");
3187 TimeTaker timer("beginScene");
3188 //driver->beginScene(false, true, bgcolor);
3189 //driver->beginScene(true, true, bgcolor);
3190 driver->beginScene(true, true, skycolor);
3191 beginscenetime = timer.stop(true);
3196 //infostream<<"smgr->drawAll()"<<std::endl;
3198 TimeTaker timer("smgr");
3201 if(g_settings->getBool("anaglyph"))
3203 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3204 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3206 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3208 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3209 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3210 camera.getCameraNode()->getAbsolutePosition() ;
3213 irr::core::vector3df leftEye;
3214 irr::core::matrix4 leftMove;
3216 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3217 leftEye=(startMatrix*leftMove).getTranslation();
3219 //clear the depth buffer, and color
3220 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3222 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3223 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3224 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3225 irr::scene::ESNRP_SOLID +
3226 irr::scene::ESNRP_TRANSPARENT +
3227 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3228 irr::scene::ESNRP_SHADOW;
3230 camera.getCameraNode()->setPosition( leftEye );
3231 camera.getCameraNode()->setTarget( focusPoint );
3233 smgr->drawAll(); // 'smgr->drawAll();' may go here
3237 irr::core::vector3df rightEye;
3238 irr::core::matrix4 rightMove;
3240 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3241 rightEye=(startMatrix*rightMove).getTranslation();
3243 //clear the depth buffer
3244 driver->clearZBuffer();
3246 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3247 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3248 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3249 irr::scene::ESNRP_SOLID +
3250 irr::scene::ESNRP_TRANSPARENT +
3251 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3252 irr::scene::ESNRP_SHADOW;
3254 camera.getCameraNode()->setPosition( rightEye );
3255 camera.getCameraNode()->setTarget( focusPoint );
3257 smgr->drawAll(); // 'smgr->drawAll();' may go here
3260 //driver->endScene();
3262 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3263 driver->getOverrideMaterial().EnableFlags=0;
3264 driver->getOverrideMaterial().EnablePasses=0;
3266 camera.getCameraNode()->setPosition( oldPosition );
3267 camera.getCameraNode()->setTarget( oldTarget );
3270 scenetime = timer.stop(true);
3274 //TimeTaker timer9("auxiliary drawings");
3278 //TimeTaker //timer10("//timer10");
3284 driver->setMaterial(m);
3286 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3289 hud.drawSelectionBoxes(hilightboxes);
3293 if(show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE))
3295 // Warning: This clears the Z buffer.
3296 camera.drawWieldedTool();
3303 client.getEnv().getClientMap().renderPostFx();
3309 if(show_profiler_graph)
3311 graph.draw(10, screensize.Y - 10, driver, font);
3318 hud.drawCrosshair();
3323 //TimeTaker //timer11("//timer11");
3331 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3332 client.getHP(), client.getPlayerItem(), client.getBreath());
3338 if(damage_flash > 0.0)
3340 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3341 driver->draw2DRectangle(color,
3342 core::rect<s32>(0,0,screensize.X,screensize.Y),
3345 damage_flash -= 100.0*dtime;
3351 if(player->hurt_tilt_timer > 0.0)
3353 player->hurt_tilt_timer -= dtime*5;
3354 if(player->hurt_tilt_timer < 0)
3355 player->hurt_tilt_strength = 0;
3362 hud.drawLuaElements();
3374 TimeTaker timer("endScene");
3376 endscenetime = timer.stop(true);
3379 drawtime = tt_draw.stop(true);
3380 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3386 static s16 lastFPS = 0;
3387 //u16 fps = driver->getFPS();
3388 u16 fps = (1.0/dtime_avg1);
3392 core::stringw str = L"Minetest [";
3393 str += driver->getName();
3397 device->setWindowCaption(str.c_str());
3402 Log times and stuff for visualization
3404 Profiler::GraphValues values;
3405 g_profiler->graphGet(values);
3414 if (gui_chat_console)
3415 gui_chat_console->drop();
3421 Draw a "shutting down" screen, which will be shown while the map
3422 generator and other stuff quits
3425 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3426 wchar_t* text = wgettext("Shutting down stuff...");
3427 draw_load_screen(text, device, font, 0, -1, false);
3429 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3432 gui_shuttingdowntext->remove();*/
3435 chat_backend.addMessage(L"", L"# Disconnected.");
3436 chat_backend.addMessage(L"", L"");
3438 // Client scope (client is destructed before destructing *def and tsrc)
3441 catch(SerializationError &e)
3443 error_message = L"A serialization error occurred:\n"
3444 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3445 L" running a different version of Minetest.";
3446 errorstream<<wide_to_narrow(error_message)<<std::endl;
3448 catch(ServerError &e)
3450 error_message = narrow_to_wide(e.what());
3451 errorstream<<wide_to_narrow(error_message)<<std::endl;
3455 errorstream<<e.what()<<std::endl;
3456 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3464 //has to be deleted first to stop all server threads
3472 //extended resource accounting
3473 infostream << "Irrlicht resources after cleanup:" << std::endl;
3474 infostream << "\tRemaining meshes : "
3475 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3476 infostream << "\tRemaining textures : "
3477 << driver->getTextureCount() << std::endl;
3478 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3479 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3480 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3483 infostream << "\tRemaining materials: "
3484 << driver-> getMaterialRendererCount ()
3485 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;