3 Copyright (C) 2010-2011 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>
30 #include "guiPauseMenu.h"
31 #include "guiPasswordChange.h"
32 #include "guiFormSpecMenu.h"
33 #include "guiTextInputMenu.h"
34 #include "guiDeathScreen.h"
36 #include "guiChatConsole.h"
44 #include "mainmenumanager.h"
48 // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "main.h" // For g_settings
53 #include "tile.h" // For TextureSource
54 #include "shader.h" // For ShaderSource
55 #include "logoutputbuffer.h"
57 #include "quicktune_shortcutter.h"
58 #include "clientmap.h"
62 #include "sound_openal.h"
64 #include "event_manager.h"
66 #include "util/directiontables.h"
72 struct TextDestChat : public TextDest
74 TextDestChat(Client *client)
78 void gotText(std::wstring text)
80 m_client->typeChatMessage(text);
82 void gotText(std::map<std::string, std::string> fields)
84 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
90 struct TextDestNodeMetadata : public TextDest
92 TextDestNodeMetadata(v3s16 p, Client *client)
97 // This is deprecated I guess? -celeron55
98 void gotText(std::wstring text)
100 std::string ntext = wide_to_narrow(text);
101 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
102 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
103 std::map<std::string, std::string> fields;
104 fields["text"] = ntext;
105 m_client->sendNodemetaFields(m_p, "", fields);
107 void gotText(std::map<std::string, std::string> fields)
109 m_client->sendNodemetaFields(m_p, "", fields);
116 struct TextDestPlayerInventory : public TextDest
118 TextDestPlayerInventory(Client *client)
123 TextDestPlayerInventory(Client *client, std::string formname)
126 m_formname = formname;
128 void gotText(std::map<std::string, std::string> fields)
130 m_client->sendInventoryFields(m_formname, fields);
134 std::string m_formname;
137 /* Respawn menu callback */
139 class MainRespawnInitiator: public IRespawnInitiator
142 MainRespawnInitiator(bool *active, Client *client):
143 m_active(active), m_client(client)
150 m_client->sendRespawn();
157 /* Form update callback */
159 class NodeMetadataFormSource: public IFormSource
162 NodeMetadataFormSource(ClientMap *map, v3s16 p):
167 std::string getForm()
169 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
172 return meta->getString("formspec");
174 std::string resolveText(std::string str)
176 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
179 return meta->resolveString(str);
186 class PlayerInventoryFormSource: public IFormSource
189 PlayerInventoryFormSource(Client *client):
193 std::string getForm()
195 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
196 return player->inventory_formspec;
202 class FormspecFormSource: public IFormSource
205 FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
207 m_formspec = formspec;
208 m_game_formspec = game_formspec;
211 ~FormspecFormSource()
213 *m_game_formspec = 0;
216 void setForm(std::string formspec) {
217 m_formspec = formspec;
220 std::string getForm()
225 std::string m_formspec;
226 FormspecFormSource** m_game_formspec;
231 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
233 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
234 Inventory *inventory, s32 halfheartcount, u16 playeritem)
236 InventoryList *mainlist = inventory->getList("main");
239 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
243 s32 padding = imgsize/12;
244 //s32 height = imgsize + padding*2;
245 s32 width = itemcount*(imgsize+padding*2);
247 // Position of upper left corner of bar
248 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
250 // Draw background color
251 /*core::rect<s32> barrect(0,0,width,height);
253 video::SColor bgcolor(255,128,128,128);
254 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
256 core::rect<s32> imgrect(0,0,imgsize,imgsize);
258 for(s32 i=0; i<itemcount; i++)
260 const ItemStack &item = mainlist->getItem(i);
262 core::rect<s32> rect = imgrect + pos
263 + v2s32(padding+i*(imgsize+padding*2), padding);
267 video::SColor c_outside(255,255,0,0);
268 //video::SColor c_outside(255,0,0,0);
269 //video::SColor c_inside(255,192,192,192);
270 s32 x1 = rect.UpperLeftCorner.X;
271 s32 y1 = rect.UpperLeftCorner.Y;
272 s32 x2 = rect.LowerRightCorner.X;
273 s32 y2 = rect.LowerRightCorner.Y;
274 // Black base borders
275 driver->draw2DRectangle(c_outside,
277 v2s32(x1 - padding, y1 - padding),
278 v2s32(x2 + padding, y1)
280 driver->draw2DRectangle(c_outside,
282 v2s32(x1 - padding, y2),
283 v2s32(x2 + padding, y2 + padding)
285 driver->draw2DRectangle(c_outside,
287 v2s32(x1 - padding, y1),
290 driver->draw2DRectangle(c_outside,
293 v2s32(x2 + padding, y2)
295 /*// Light inside borders
296 driver->draw2DRectangle(c_inside,
298 v2s32(x1 - padding/2, y1 - padding/2),
299 v2s32(x2 + padding/2, y1)
301 driver->draw2DRectangle(c_inside,
303 v2s32(x1 - padding/2, y2),
304 v2s32(x2 + padding/2, y2 + padding/2)
306 driver->draw2DRectangle(c_inside,
308 v2s32(x1 - padding/2, y1),
311 driver->draw2DRectangle(c_inside,
314 v2s32(x2 + padding/2, y2)
319 video::SColor bgcolor2(128,0,0,0);
320 driver->draw2DRectangle(bgcolor2, rect, NULL);
321 drawItemStack(driver, font, item, rect, NULL, gamedef);
327 video::ITexture *heart_texture =
328 gamedef->getTextureSource()->getTextureRaw("heart.png");
331 v2s32 p = pos + v2s32(0, -20);
332 for(s32 i=0; i<halfheartcount/2; i++)
334 const video::SColor color(255,255,255,255);
335 const video::SColor colors[] = {color,color,color,color};
336 core::rect<s32> rect(0,0,16,16);
338 driver->draw2DImage(heart_texture, rect,
339 core::rect<s32>(core::position2d<s32>(0,0),
340 core::dimension2di(heart_texture->getOriginalSize())),
344 if(halfheartcount % 2 == 1)
346 const video::SColor color(255,255,255,255);
347 const video::SColor colors[] = {color,color,color,color};
348 core::rect<s32> rect(0,0,16/2,16);
350 core::dimension2di srcd(heart_texture->getOriginalSize());
352 driver->draw2DImage(heart_texture, rect,
353 core::rect<s32>(core::position2d<s32>(0,0), srcd),
361 Check if a node is pointable
363 inline bool isPointableNode(const MapNode& n,
364 Client *client, bool liquids_pointable)
366 const ContentFeatures &features = client->getNodeDefManager()->get(n);
367 return features.pointable ||
368 (liquids_pointable && features.isLiquid());
372 Find what the player is pointing at
374 PointedThing getPointedThing(Client *client, v3f player_position,
375 v3f camera_direction, v3f camera_position,
376 core::line3d<f32> shootline, f32 d,
377 bool liquids_pointable,
378 bool look_for_object,
379 std::vector<aabb3f> &hilightboxes,
380 ClientActiveObject *&selected_object)
384 hilightboxes.clear();
385 selected_object = NULL;
387 INodeDefManager *nodedef = client->getNodeDefManager();
388 ClientMap &map = client->getEnv().getClientMap();
390 // First try to find a pointed at active object
393 selected_object = client->getSelectedActiveObject(d*BS,
394 camera_position, shootline);
396 if(selected_object != NULL)
398 if(selected_object->doShowSelectionBox())
400 aabb3f *selection_box = selected_object->getSelectionBox();
401 // Box should exist because object was
402 // returned in the first place
403 assert(selection_box);
405 v3f pos = selected_object->getPosition();
406 hilightboxes.push_back(aabb3f(
407 selection_box->MinEdge + pos,
408 selection_box->MaxEdge + pos));
412 result.type = POINTEDTHING_OBJECT;
413 result.object_id = selected_object->getId();
418 // That didn't work, try to find a pointed at node
420 f32 mindistance = BS * 1001;
422 v3s16 pos_i = floatToInt(player_position, BS);
424 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
428 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
429 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
430 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
431 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
432 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
433 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
435 // Prevent signed number overflow
443 for(s16 y = ystart; y <= yend; y++)
444 for(s16 z = zstart; z <= zend; z++)
445 for(s16 x = xstart; x <= xend; x++)
450 n = map.getNode(v3s16(x,y,z));
452 catch(InvalidPositionException &e)
456 if(!isPointableNode(n, client, liquids_pointable))
459 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
462 v3f npf = intToFloat(np, BS);
464 for(std::vector<aabb3f>::const_iterator
466 i != boxes.end(); i++)
472 for(u16 j=0; j<6; j++)
474 v3s16 facedir = g_6dirs[j];
475 aabb3f facebox = box;
479 facebox.MinEdge.X = facebox.MaxEdge.X-d;
480 else if(facedir.X < 0)
481 facebox.MaxEdge.X = facebox.MinEdge.X+d;
482 else if(facedir.Y > 0)
483 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
484 else if(facedir.Y < 0)
485 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
486 else if(facedir.Z > 0)
487 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
488 else if(facedir.Z < 0)
489 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
491 v3f centerpoint = facebox.getCenter();
492 f32 distance = (centerpoint - camera_position).getLength();
493 if(distance >= mindistance)
495 if(!facebox.intersectsWithLine(shootline))
498 v3s16 np_above = np + facedir;
500 result.type = POINTEDTHING_NODE;
501 result.node_undersurface = np;
502 result.node_abovesurface = np_above;
503 mindistance = distance;
505 hilightboxes.clear();
506 for(std::vector<aabb3f>::const_iterator
508 i2 != boxes.end(); i2++)
511 box.MinEdge += npf + v3f(-d,-d,-d);
512 box.MaxEdge += npf + v3f(d,d,d);
513 hilightboxes.push_back(box);
523 Draws a screen with a single text on it.
524 Text will be removed when the screen is drawn the next time.
526 /*gui::IGUIStaticText **/
527 void draw_load_screen(const std::wstring &text,
528 video::IVideoDriver* driver, gui::IGUIFont* font)
530 v2u32 screensize = driver->getScreenSize();
531 const wchar_t *loadingtext = text.c_str();
532 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
533 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
534 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
535 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
537 gui::IGUIStaticText *guitext = guienv->addStaticText(
538 loadingtext, textrect, false, false);
539 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
541 driver->beginScene(true, true, video::SColor(255,0,0,0));
550 /* Profiler display */
552 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
553 gui::IGUIFont *font, u32 text_height,
554 u32 show_profiler, u32 show_profiler_max)
556 if(show_profiler == 0)
558 guitext_profiler->setVisible(false);
563 std::ostringstream os(std::ios_base::binary);
564 g_profiler->printPage(os, show_profiler, show_profiler_max);
565 std::wstring text = narrow_to_wide(os.str());
566 guitext_profiler->setText(text.c_str());
567 guitext_profiler->setVisible(true);
569 s32 w = font->getDimension(text.c_str()).Width;
572 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
573 8+(text_height+5)*2 +
574 font->getDimension(text.c_str()).Height);
575 guitext_profiler->setRelativePosition(rect);
576 guitext_profiler->setVisible(true);
584 Profiler::GraphValues values;
590 Meta(float initial=0, video::SColor color=
591 video::SColor(255,255,255,255)):
597 std::list<Piece> m_log;
605 void put(const Profiler::GraphValues &values)
608 piece.values = values;
609 m_log.push_back(piece);
610 while(m_log.size() > m_log_max_size)
611 m_log.erase(m_log.begin());
614 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
615 gui::IGUIFont* font) const
617 std::map<std::string, Meta> m_meta;
618 for(std::list<Piece>::const_iterator k = m_log.begin();
619 k != m_log.end(); k++)
621 const Piece &piece = *k;
622 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
623 i != piece.values.end(); i++){
624 const std::string &id = i->first;
625 const float &value = i->second;
626 std::map<std::string, Meta>::iterator j =
628 if(j == m_meta.end()){
629 m_meta[id] = Meta(value);
632 if(value < j->second.min)
633 j->second.min = value;
634 if(value > j->second.max)
635 j->second.max = value;
640 static const video::SColor usable_colors[] = {
641 video::SColor(255,255,100,100),
642 video::SColor(255,90,225,90),
643 video::SColor(255,100,100,255),
644 video::SColor(255,255,150,50),
645 video::SColor(255,220,220,100)
647 static const u32 usable_colors_count =
648 sizeof(usable_colors) / sizeof(*usable_colors);
649 u32 next_color_i = 0;
650 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
651 i != m_meta.end(); i++){
652 Meta &meta = i->second;
653 video::SColor color(255,200,200,200);
654 if(next_color_i < usable_colors_count)
655 color = usable_colors[next_color_i++];
660 s32 textx = x_left + m_log_max_size + 15;
661 s32 textx2 = textx + 200 - 15;
665 u32 num_graphs = m_meta.size();
666 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
668 video::SColor bgcolor(120,0,0,0);
669 driver->draw2DRectangle(bgcolor, rect, NULL);
673 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
674 i != m_meta.end(); i++){
675 const std::string &id = i->first;
676 const Meta &meta = i->second;
678 s32 y = y_bottom - meta_i * 50;
679 float show_min = meta.min;
680 float show_max = meta.max;
681 if(show_min >= -0.0001 && show_max >= -0.0001){
682 if(show_min <= show_max * 0.5)
687 snprintf(buf, 10, "%.3g", show_max);
688 font->draw(narrow_to_wide(buf).c_str(),
689 core::rect<s32>(textx, y - graphh,
690 textx2, y - graphh + texth),
692 snprintf(buf, 10, "%.3g", show_min);
693 font->draw(narrow_to_wide(buf).c_str(),
694 core::rect<s32>(textx, y - texth,
697 font->draw(narrow_to_wide(id).c_str(),
698 core::rect<s32>(textx, y - graphh/2 - texth/2,
699 textx2, y - graphh/2 + texth/2),
702 s32 graph1h = graphh;
703 bool relativegraph = (show_min != 0 && show_min != show_max);
704 float lastscaledvalue = 0.0;
705 bool lastscaledvalue_exists = false;
706 for(std::list<Piece>::const_iterator j = m_log.begin();
707 j != m_log.end(); j++)
709 const Piece &piece = *j;
711 bool value_exists = false;
712 Profiler::GraphValues::const_iterator k =
713 piece.values.find(id);
714 if(k != piece.values.end()){
720 lastscaledvalue_exists = false;
723 float scaledvalue = 1.0;
724 if(show_max != show_min)
725 scaledvalue = (value - show_min) / (show_max - show_min);
726 if(scaledvalue == 1.0 && value == 0){
728 lastscaledvalue_exists = false;
732 if(lastscaledvalue_exists){
733 s32 ivalue1 = lastscaledvalue * graph1h;
734 s32 ivalue2 = scaledvalue * graph1h;
735 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
736 v2s32(x, graph1y - ivalue2), meta.color);
738 lastscaledvalue = scaledvalue;
739 lastscaledvalue_exists = true;
741 s32 ivalue = scaledvalue * graph1h;
742 driver->draw2DLine(v2s32(x, graph1y),
743 v2s32(x, graph1y - ivalue), meta.color);
752 class NodeDugEvent: public MtEvent
758 NodeDugEvent(v3s16 p, MapNode n):
762 const char* getType() const
768 ISoundManager *m_sound;
769 INodeDefManager *m_ndef;
771 float m_player_step_timer;
773 SimpleSoundSpec m_player_step_sound;
774 SimpleSoundSpec m_player_leftpunch_sound;
775 SimpleSoundSpec m_player_rightpunch_sound;
777 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
780 m_player_step_timer(0)
784 void playPlayerStep()
786 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
787 m_player_step_timer = 0.03;
788 m_sound->playSound(m_player_step_sound, false);
792 static void viewBobbingStep(MtEvent *e, void *data)
794 SoundMaker *sm = (SoundMaker*)data;
795 sm->playPlayerStep();
798 static void playerRegainGround(MtEvent *e, void *data)
800 SoundMaker *sm = (SoundMaker*)data;
801 sm->playPlayerStep();
804 static void playerJump(MtEvent *e, void *data)
806 //SoundMaker *sm = (SoundMaker*)data;
809 static void cameraPunchLeft(MtEvent *e, void *data)
811 SoundMaker *sm = (SoundMaker*)data;
812 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
815 static void cameraPunchRight(MtEvent *e, void *data)
817 SoundMaker *sm = (SoundMaker*)data;
818 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
821 static void nodeDug(MtEvent *e, void *data)
823 SoundMaker *sm = (SoundMaker*)data;
824 NodeDugEvent *nde = (NodeDugEvent*)e;
825 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
828 void registerReceiver(MtEventManager *mgr)
830 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
831 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
832 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
833 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
834 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
835 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
838 void step(float dtime)
840 m_player_step_timer -= dtime;
844 // Locally stored sounds don't need to be preloaded because of this
845 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
847 std::set<std::string> m_fetched;
850 void fetchSounds(const std::string &name,
851 std::set<std::string> &dst_paths,
852 std::set<std::string> &dst_datas)
854 if(m_fetched.count(name))
856 m_fetched.insert(name);
857 std::string base = porting::path_share + DIR_DELIM + "testsounds";
858 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
859 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
860 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
861 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
862 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
863 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
864 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
865 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
866 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
867 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
868 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
872 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
875 bool *m_force_fog_off;
880 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
881 f32 *fog_range, Client *client):
883 m_force_fog_off(force_fog_off),
884 m_fog_range(fog_range),
887 ~GameGlobalShaderConstantSetter() {}
889 virtual void onSetConstants(video::IMaterialRendererServices *services,
896 video::SColor bgcolor = m_sky->getBgColor();
897 video::SColorf bgcolorf(bgcolor);
898 float bgcolorfa[4] = {
904 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
907 float fog_distance = *m_fog_range;
909 fog_distance = 10000*BS;
910 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
913 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
914 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
915 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
923 IrrlichtDevice *device,
926 std::string playername,
927 std::string password,
928 std::string address, // If "", local server is used
930 std::wstring &error_message,
931 std::string configpath,
932 ChatBackend &chat_backend,
933 const SubgameSpec &gamespec, // Used for local game,
934 bool simple_singleplayer_mode
937 FormspecFormSource* current_formspec = 0;
938 video::IVideoDriver* driver = device->getVideoDriver();
939 scene::ISceneManager* smgr = device->getSceneManager();
941 // Calculate text height using the font
942 u32 text_height = font->getDimension(L"Random test string").Height;
944 v2u32 screensize(0,0);
945 v2u32 last_screensize(0,0);
946 screensize = driver->getScreenSize();
948 const s32 hotbar_itemcount = 8;
949 //const s32 hotbar_imagesize = 36;
950 //const s32 hotbar_imagesize = 64;
951 s32 hotbar_imagesize = 48;
954 Draw "Loading" screen
957 draw_load_screen(L"Loading...", driver, font);
959 // Create texture source
960 IWritableTextureSource *tsrc = createTextureSource(device);
962 // Create shader source
963 IWritableShaderSource *shsrc = createShaderSource(device);
965 // These will be filled by data received from the server
966 // Create item definition manager
967 IWritableItemDefManager *itemdef = createItemDefManager();
968 // Create node definition manager
969 IWritableNodeDefManager *nodedef = createNodeDefManager();
971 // Sound fetcher (useful when testing)
972 GameOnDemandSoundFetcher soundfetcher;
975 ISoundManager *sound = NULL;
976 bool sound_is_dummy = false;
978 if(g_settings->getBool("enable_sound")){
979 infostream<<"Attempting to use OpenAL audio"<<std::endl;
980 sound = createOpenALSoundManager(&soundfetcher);
982 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
984 infostream<<"Sound disabled."<<std::endl;
988 infostream<<"Using dummy audio."<<std::endl;
989 sound = &dummySoundManager;
990 sound_is_dummy = true;
994 EventManager eventmgr;
997 SoundMaker soundmaker(sound, nodedef);
998 soundmaker.registerReceiver(&eventmgr);
1000 // Add chat log output for errors to be shown in chat
1001 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1003 // Create UI for modifying quicktune values
1004 QuicktuneShortcutter quicktune;
1008 SharedPtr will delete it when it goes out of scope.
1010 SharedPtr<Server> server;
1012 draw_load_screen(L"Creating server...", driver, font);
1013 infostream<<"Creating server"<<std::endl;
1014 server = new Server(map_dir, configpath, gamespec,
1015 simple_singleplayer_mode);
1016 server->start(port);
1020 do{ // Client scope (breakable do-while(0))
1026 draw_load_screen(L"Creating client...", driver, font);
1027 infostream<<"Creating client"<<std::endl;
1029 MapDrawControl draw_control;
1031 Client client(device, playername.c_str(), password, draw_control,
1032 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
1034 // Client acts as our GameDef
1035 IGameDef *gamedef = &client;
1037 draw_load_screen(L"Resolving address...", driver, font);
1038 Address connect_address(0,0,0,0, port);
1041 //connect_address.Resolve("localhost");
1042 connect_address.setAddress(127,0,0,1);
1044 connect_address.Resolve(address.c_str());
1046 catch(ResolveError &e)
1048 error_message = L"Couldn't resolve address";
1049 errorstream<<wide_to_narrow(error_message)<<std::endl;
1050 // Break out of client scope
1055 Attempt to connect to the server
1058 infostream<<"Connecting to server at ";
1059 connect_address.print(&infostream);
1060 infostream<<std::endl;
1061 client.connect(connect_address);
1064 Wait for server to accept connection
1066 bool could_connect = false;
1067 bool connect_aborted = false;
1069 float frametime = 0.033;
1070 float time_counter = 0.0;
1072 while(device->run())
1074 // Update client and server
1075 client.step(frametime);
1077 server->step(frametime);
1080 if(client.connectedAndInitialized()){
1081 could_connect = true;
1085 if(client.accessDenied()){
1086 error_message = L"Access denied. Reason: "
1087 +client.accessDeniedReason();
1088 errorstream<<wide_to_narrow(error_message)<<std::endl;
1091 if(input->wasKeyDown(EscapeKey)){
1092 connect_aborted = true;
1093 infostream<<"Connect aborted [Escape]"<<std::endl;
1098 std::wostringstream ss;
1099 ss<<L"Connecting to server... (press Escape to cancel)\n";
1100 std::wstring animation = L"/-\\|";
1101 ss<<animation[(int)(time_counter/0.2)%4];
1102 draw_load_screen(ss.str(), driver, font);
1105 sleep_ms(1000*frametime);
1106 time_counter += frametime;
1109 catch(con::PeerNotFoundException &e)
1113 Handle failure to connect
1116 if(error_message == L"" && !connect_aborted){
1117 error_message = L"Connection failed";
1118 errorstream<<wide_to_narrow(error_message)<<std::endl;
1120 // Break out of client scope
1125 Wait until content has been received
1127 bool got_content = false;
1128 bool content_aborted = false;
1130 float frametime = 0.033;
1131 float time_counter = 0.0;
1133 while(device->run())
1135 // Update client and server
1136 client.step(frametime);
1138 server->step(frametime);
1141 if(client.texturesReceived() &&
1142 client.itemdefReceived() &&
1143 client.nodedefReceived()){
1148 if(!client.connectedAndInitialized()){
1149 error_message = L"Client disconnected";
1150 errorstream<<wide_to_narrow(error_message)<<std::endl;
1153 if(input->wasKeyDown(EscapeKey)){
1154 content_aborted = true;
1155 infostream<<"Connect aborted [Escape]"<<std::endl;
1160 std::wostringstream ss;
1161 ss<<L"Waiting content... (press Escape to cancel)\n";
1163 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1164 ss<<L" Item definitions\n";
1165 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1166 ss<<L" Node definitions\n";
1167 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1170 draw_load_screen(ss.str(), driver, font);
1173 sleep_ms(1000*frametime);
1174 time_counter += frametime;
1179 if(error_message == L"" && !content_aborted){
1180 error_message = L"Something failed";
1181 errorstream<<wide_to_narrow(error_message)<<std::endl;
1183 // Break out of client scope
1188 After all content has been received:
1189 Update cached textures, meshes and materials
1191 client.afterContentReceived();
1194 Create the camera node
1196 Camera camera(smgr, draw_control, gamedef);
1197 if (!camera.successfullyCreated(error_message))
1200 f32 camera_yaw = 0; // "right/left"
1201 f32 camera_pitch = 0; // "up/down"
1207 Clouds *clouds = NULL;
1208 if(g_settings->getBool("enable_clouds"))
1210 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1218 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1224 FarMesh *farmesh = NULL;
1225 if(g_settings->getBool("enable_farmesh"))
1227 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1231 A copy of the local inventory
1233 Inventory local_inventory(itemdef);
1236 Find out size of crack animation
1238 int crack_animation_length = 5;
1240 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1241 v2u32 size = t->getOriginalSize();
1242 crack_animation_length = size.Y / size.X;
1249 // First line of debug text
1250 gui::IGUIStaticText *guitext = guienv->addStaticText(
1252 core::rect<s32>(5, 5, 795, 5+text_height),
1254 // Second line of debug text
1255 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1257 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1259 // At the middle of the screen
1260 // Object infos are shown in this
1261 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1263 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1266 // Status text (displays info when showing and hiding GUI stuff, etc.)
1267 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1269 core::rect<s32>(0,0,0,0),
1271 guitext_status->setVisible(false);
1273 std::wstring statustext;
1274 float statustext_time = 0;
1277 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1279 core::rect<s32>(0,0,0,0),
1280 //false, false); // Disable word wrap as of now
1282 // Remove stale "recent" chat messages from previous connections
1283 chat_backend.clearRecentChat();
1284 // Chat backend and console
1285 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1287 // Profiler text (size is updated when text is updated)
1288 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1290 core::rect<s32>(0,0,0,0),
1292 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1293 guitext_profiler->setVisible(false);
1296 Some statistics are collected in these
1299 u32 beginscenetime = 0;
1301 u32 endscenetime = 0;
1303 float recent_turn_speed = 0.0;
1305 ProfilerGraph graph;
1306 // Initially clear the profiler
1307 Profiler::GraphValues dummyvalues;
1308 g_profiler->graphGet(dummyvalues);
1310 float nodig_delay_timer = 0.0;
1311 float dig_time = 0.0;
1313 PointedThing pointed_old;
1314 bool digging = false;
1315 bool ldown_for_dig = false;
1317 float damage_flash = 0;
1318 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1320 float jump_timer = 0;
1321 bool reset_jump_timer = false;
1323 const float object_hit_delay = 0.2;
1324 float object_hit_delay_timer = 0.0;
1325 float time_from_last_punch = 10;
1327 float update_draw_list_timer = 0.0;
1328 v3f update_draw_list_last_cam_dir;
1330 bool invert_mouse = g_settings->getBool("invert_mouse");
1332 bool respawn_menu_active = false;
1333 bool update_wielded_item_trigger = false;
1335 bool show_hud = true;
1336 bool show_chat = true;
1337 bool force_fog_off = false;
1338 f32 fog_range = 100*BS;
1339 bool disable_camera_update = false;
1340 bool show_debug = g_settings->getBool("show_debug");
1341 bool show_profiler_graph = false;
1342 u32 show_profiler = 0;
1343 u32 show_profiler_max = 3; // Number of pages
1345 float time_of_day = 0;
1346 float time_of_day_smooth = 0;
1348 float repeat_rightclick_timer = 0;
1353 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1354 sky, &force_fog_off, &fog_range, &client));
1360 bool first_loop_after_window_activation = true;
1362 // TODO: Convert the static interval timers to these
1363 // Interval limiter for profiler
1364 IntervalLimiter m_profiler_interval;
1366 // Time is in milliseconds
1367 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1368 // NOTE: So we have to use getTime() and call run()s between them
1369 u32 lasttime = device->getTimer()->getTime();
1371 LocalPlayer* player = client.getEnv().getLocalPlayer();
1372 player->hurt_tilt_timer = 0;
1373 player->hurt_tilt_strength = 0;
1377 if(device->run() == false || kill == true)
1380 // Time of frame without fps limit
1384 // not using getRealTime is necessary for wine
1385 u32 time = device->getTimer()->getTime();
1387 busytime_u32 = time - lasttime;
1390 busytime = busytime_u32 / 1000.0;
1393 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1395 // Necessary for device->getTimer()->getTime()
1403 float fps_max = g_settings->getFloat("fps_max");
1404 u32 frametime_min = 1000./fps_max;
1406 if(busytime_u32 < frametime_min)
1408 u32 sleeptime = frametime_min - busytime_u32;
1409 device->sleep(sleeptime);
1410 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1414 // Necessary for device->getTimer()->getTime()
1418 Time difference calculation
1420 f32 dtime; // in seconds
1422 u32 time = device->getTimer()->getTime();
1424 dtime = (time - lasttime) / 1000.0;
1429 g_profiler->graphAdd("mainloop_dtime", dtime);
1433 if(nodig_delay_timer >= 0)
1434 nodig_delay_timer -= dtime;
1435 if(object_hit_delay_timer >= 0)
1436 object_hit_delay_timer -= dtime;
1437 time_from_last_punch += dtime;
1439 g_profiler->add("Elapsed time", dtime);
1440 g_profiler->avg("FPS", 1./dtime);
1443 Time average and jitter calculation
1446 static f32 dtime_avg1 = 0.0;
1447 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1448 f32 dtime_jitter1 = dtime - dtime_avg1;
1450 static f32 dtime_jitter1_max_sample = 0.0;
1451 static f32 dtime_jitter1_max_fraction = 0.0;
1453 static f32 jitter1_max = 0.0;
1454 static f32 counter = 0.0;
1455 if(dtime_jitter1 > jitter1_max)
1456 jitter1_max = dtime_jitter1;
1461 dtime_jitter1_max_sample = jitter1_max;
1462 dtime_jitter1_max_fraction
1463 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1469 Busytime average and jitter calculation
1472 static f32 busytime_avg1 = 0.0;
1473 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1474 f32 busytime_jitter1 = busytime - busytime_avg1;
1476 static f32 busytime_jitter1_max_sample = 0.0;
1477 static f32 busytime_jitter1_min_sample = 0.0;
1479 static f32 jitter1_max = 0.0;
1480 static f32 jitter1_min = 0.0;
1481 static f32 counter = 0.0;
1482 if(busytime_jitter1 > jitter1_max)
1483 jitter1_max = busytime_jitter1;
1484 if(busytime_jitter1 < jitter1_min)
1485 jitter1_min = busytime_jitter1;
1489 busytime_jitter1_max_sample = jitter1_max;
1490 busytime_jitter1_min_sample = jitter1_min;
1497 Handle miscellaneous stuff
1500 if(client.accessDenied())
1502 error_message = L"Access denied. Reason: "
1503 +client.accessDeniedReason();
1504 errorstream<<wide_to_narrow(error_message)<<std::endl;
1508 if(g_gamecallback->disconnect_requested)
1510 g_gamecallback->disconnect_requested = false;
1514 if(g_gamecallback->changepassword_requested)
1516 (new GUIPasswordChange(guienv, guiroot, -1,
1517 &g_menumgr, &client))->drop();
1518 g_gamecallback->changepassword_requested = false;
1521 /* Process TextureSource's queue */
1522 tsrc->processQueue();
1524 /* Process ItemDefManager's queue */
1525 itemdef->processQueue(gamedef);
1528 Process ShaderSource's queue
1530 shsrc->processQueue();
1535 last_screensize = screensize;
1536 screensize = driver->getScreenSize();
1537 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1538 //bool screensize_changed = screensize != last_screensize;
1541 if(screensize.Y <= 800)
1542 hotbar_imagesize = 32;
1543 else if(screensize.Y <= 1280)
1544 hotbar_imagesize = 48;
1546 hotbar_imagesize = 64;
1548 // Hilight boxes collected during the loop and displayed
1549 std::vector<aabb3f> hilightboxes;
1552 std::wstring infotext;
1555 Debug info for client
1558 static float counter = 0.0;
1563 client.printDebugInfo(infostream);
1570 float profiler_print_interval =
1571 g_settings->getFloat("profiler_print_interval");
1572 bool print_to_log = true;
1573 if(profiler_print_interval == 0){
1574 print_to_log = false;
1575 profiler_print_interval = 5;
1577 if(m_profiler_interval.step(dtime, profiler_print_interval))
1580 infostream<<"Profiler:"<<std::endl;
1581 g_profiler->print(infostream);
1584 update_profiler_gui(guitext_profiler, font, text_height,
1585 show_profiler, show_profiler_max);
1587 g_profiler->clear();
1591 Direct handling of user input
1594 // Reset input if window not active or some menu is active
1595 if(device->isWindowActive() == false
1596 || noMenuActive() == false
1597 || guienv->hasFocus(gui_chat_console))
1602 // Input handler step() (used by the random input generator)
1605 // Increase timer for doubleclick of "jump"
1606 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1607 jump_timer += dtime;
1610 Launch menus and trigger stuff according to keys
1612 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1614 // drop selected item
1615 IDropAction *a = new IDropAction();
1617 a->from_inv.setCurrentPlayer();
1618 a->from_list = "main";
1619 a->from_i = client.getPlayerItem();
1620 client.inventoryAction(a);
1622 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1624 infostream<<"the_game: "
1625 <<"Launching inventory"<<std::endl;
1627 GUIFormSpecMenu *menu =
1628 new GUIFormSpecMenu(device, guiroot, -1,
1632 InventoryLocation inventoryloc;
1633 inventoryloc.setCurrentPlayer();
1635 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1637 menu->setFormSpec(src->getForm(), inventoryloc);
1638 menu->setFormSource(src);
1639 menu->setTextDest(new TextDestPlayerInventory(&client));
1642 else if(input->wasKeyDown(EscapeKey))
1644 infostream<<"the_game: "
1645 <<"Launching pause menu"<<std::endl;
1646 // It will delete itself by itself
1647 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1648 &g_menumgr, simple_singleplayer_mode))->drop();
1650 // Move mouse cursor on top of the disconnect button
1651 if(simple_singleplayer_mode)
1652 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1654 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1656 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1658 TextDest *dest = new TextDestChat(&client);
1660 (new GUITextInputMenu(guienv, guiroot, -1,
1664 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1666 TextDest *dest = new TextDestChat(&client);
1668 (new GUITextInputMenu(guienv, guiroot, -1,
1672 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1674 if (!gui_chat_console->isOpenInhibited())
1676 // Open up to over half of the screen
1677 gui_chat_console->openConsole(0.6);
1678 guienv->setFocus(gui_chat_console);
1681 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1683 if(g_settings->getBool("free_move"))
1685 g_settings->set("free_move","false");
1686 statustext = L"free_move disabled";
1687 statustext_time = 0;
1691 g_settings->set("free_move","true");
1692 statustext = L"free_move enabled";
1693 statustext_time = 0;
1694 if(!client.checkPrivilege("fly"))
1695 statustext += L" (note: no 'fly' privilege)";
1698 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1700 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1702 if(g_settings->getBool("free_move"))
1704 g_settings->set("free_move","false");
1705 statustext = L"free_move disabled";
1706 statustext_time = 0;
1710 g_settings->set("free_move","true");
1711 statustext = L"free_move enabled";
1712 statustext_time = 0;
1713 if(!client.checkPrivilege("fly"))
1714 statustext += L" (note: no 'fly' privilege)";
1717 reset_jump_timer = true;
1719 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1721 if(g_settings->getBool("fast_move"))
1723 g_settings->set("fast_move","false");
1724 statustext = L"fast_move disabled";
1725 statustext_time = 0;
1729 g_settings->set("fast_move","true");
1730 statustext = L"fast_move enabled";
1731 statustext_time = 0;
1732 if(!client.checkPrivilege("fast"))
1733 statustext += L" (note: no 'fast' privilege)";
1736 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1738 if(g_settings->getBool("noclip"))
1740 g_settings->set("noclip","false");
1741 statustext = L"noclip disabled";
1742 statustext_time = 0;
1746 g_settings->set("noclip","true");
1747 statustext = L"noclip enabled";
1748 statustext_time = 0;
1749 if(!client.checkPrivilege("noclip"))
1750 statustext += L" (note: no 'noclip' privilege)";
1753 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1755 irr::video::IImage* const image = driver->createScreenShot();
1757 irr::c8 filename[256];
1758 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1759 g_settings->get("screenshot_path").c_str(),
1760 device->getTimer()->getRealTime());
1761 if (driver->writeImageToFile(image, filename)) {
1762 std::wstringstream sstr;
1763 sstr<<"Saved screenshot to '"<<filename<<"'";
1764 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1765 statustext = sstr.str();
1766 statustext_time = 0;
1768 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1773 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1775 show_hud = !show_hud;
1777 statustext = L"HUD shown";
1779 statustext = L"HUD hidden";
1780 statustext_time = 0;
1782 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1784 show_chat = !show_chat;
1786 statustext = L"Chat shown";
1788 statustext = L"Chat hidden";
1789 statustext_time = 0;
1791 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1793 force_fog_off = !force_fog_off;
1795 statustext = L"Fog disabled";
1797 statustext = L"Fog enabled";
1798 statustext_time = 0;
1800 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1802 disable_camera_update = !disable_camera_update;
1803 if(disable_camera_update)
1804 statustext = L"Camera update disabled";
1806 statustext = L"Camera update enabled";
1807 statustext_time = 0;
1809 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1811 // Initial / 3x toggle: Chat only
1812 // 1x toggle: Debug text with chat
1813 // 2x toggle: Debug text with profiler graph
1817 show_profiler_graph = false;
1818 statustext = L"Debug info shown";
1819 statustext_time = 0;
1821 else if(show_profiler_graph)
1824 show_profiler_graph = false;
1825 statustext = L"Debug info and profiler graph hidden";
1826 statustext_time = 0;
1830 show_profiler_graph = true;
1831 statustext = L"Profiler graph shown";
1832 statustext_time = 0;
1835 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1837 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1839 // FIXME: This updates the profiler with incomplete values
1840 update_profiler_gui(guitext_profiler, font, text_height,
1841 show_profiler, show_profiler_max);
1843 if(show_profiler != 0)
1845 std::wstringstream sstr;
1846 sstr<<"Profiler shown (page "<<show_profiler
1847 <<" of "<<show_profiler_max<<")";
1848 statustext = sstr.str();
1849 statustext_time = 0;
1853 statustext = L"Profiler hidden";
1854 statustext_time = 0;
1857 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1859 s16 range = g_settings->getS16("viewing_range_nodes_min");
1860 s16 range_new = range + 10;
1861 g_settings->set("viewing_range_nodes_min", itos(range_new));
1862 statustext = narrow_to_wide(
1863 "Minimum viewing range changed to "
1865 statustext_time = 0;
1867 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1869 s16 range = g_settings->getS16("viewing_range_nodes_min");
1870 s16 range_new = range - 10;
1873 g_settings->set("viewing_range_nodes_min",
1875 statustext = narrow_to_wide(
1876 "Minimum viewing range changed to "
1878 statustext_time = 0;
1882 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1884 reset_jump_timer = false;
1888 // Handle QuicktuneShortcutter
1889 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1891 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1893 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1895 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1898 std::string msg = quicktune.getMessage();
1900 statustext = narrow_to_wide(msg);
1901 statustext_time = 0;
1905 // Item selection with mouse wheel
1906 u16 new_playeritem = client.getPlayerItem();
1908 s32 wheel = input->getMouseWheel();
1909 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1910 hotbar_itemcount-1);
1914 if(new_playeritem < max_item)
1921 if(new_playeritem > 0)
1924 new_playeritem = max_item;
1929 for(u16 i=0; i<10; i++)
1931 const KeyPress *kp = NumberKey + (i + 1) % 10;
1932 if(input->wasKeyDown(*kp))
1934 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1938 infostream<<"Selected item: "
1939 <<new_playeritem<<std::endl;
1944 // Viewing range selection
1945 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1947 draw_control.range_all = !draw_control.range_all;
1948 if(draw_control.range_all)
1950 infostream<<"Enabled full viewing range"<<std::endl;
1951 statustext = L"Enabled full viewing range";
1952 statustext_time = 0;
1956 infostream<<"Disabled full viewing range"<<std::endl;
1957 statustext = L"Disabled full viewing range";
1958 statustext_time = 0;
1962 // Print debug stacks
1963 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1965 dstream<<"-----------------------------------------"
1967 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1968 dstream<<"-----------------------------------------"
1970 debug_stacks_print();
1974 Mouse and camera control
1975 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1978 float turn_amount = 0;
1979 if((device->isWindowActive() && noMenuActive()) || random_input)
1983 // Mac OSX gets upset if this is set every frame
1984 if(device->getCursorControl()->isVisible())
1985 device->getCursorControl()->setVisible(false);
1988 if(first_loop_after_window_activation){
1989 //infostream<<"window active, first loop"<<std::endl;
1990 first_loop_after_window_activation = false;
1993 s32 dx = input->getMousePos().X - displaycenter.X;
1994 s32 dy = input->getMousePos().Y - displaycenter.Y;
1997 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1999 /*const float keyspeed = 500;
2000 if(input->isKeyDown(irr::KEY_UP))
2001 dy -= dtime * keyspeed;
2002 if(input->isKeyDown(irr::KEY_DOWN))
2003 dy += dtime * keyspeed;
2004 if(input->isKeyDown(irr::KEY_LEFT))
2005 dx -= dtime * keyspeed;
2006 if(input->isKeyDown(irr::KEY_RIGHT))
2007 dx += dtime * keyspeed;*/
2011 camera_pitch += dy*d;
2012 if(camera_pitch < -89.5) camera_pitch = -89.5;
2013 if(camera_pitch > 89.5) camera_pitch = 89.5;
2015 turn_amount = v2f(dx, dy).getLength() * d;
2017 input->setMousePos(displaycenter.X, displaycenter.Y);
2020 // Mac OSX gets upset if this is set every frame
2021 if(device->getCursorControl()->isVisible() == false)
2022 device->getCursorControl()->setVisible(true);
2024 //infostream<<"window inactive"<<std::endl;
2025 first_loop_after_window_activation = true;
2027 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2028 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2031 Player speed control
2045 PlayerControl control(
2046 input->isKeyDown(getKeySetting("keymap_forward")),
2047 input->isKeyDown(getKeySetting("keymap_backward")),
2048 input->isKeyDown(getKeySetting("keymap_left")),
2049 input->isKeyDown(getKeySetting("keymap_right")),
2050 input->isKeyDown(getKeySetting("keymap_jump")),
2051 input->isKeyDown(getKeySetting("keymap_special1")),
2052 input->isKeyDown(getKeySetting("keymap_sneak")),
2053 input->getLeftState(),
2054 input->getRightState(),
2058 client.setPlayerControl(control);
2060 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2061 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2062 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2063 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2064 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2065 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2066 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2067 128*(int)input->getLeftState()+
2068 256*(int)input->getRightState();
2069 LocalPlayer* player = client.getEnv().getLocalPlayer();
2070 player->keyPressed=keyPressed;
2079 //TimeTaker timer("server->step(dtime)");
2080 server->step(dtime);
2088 //TimeTaker timer("client.step(dtime)");
2090 //client.step(dtime_avg1);
2094 // Read client events
2097 ClientEvent event = client.getClientEvent();
2098 if(event.type == CE_NONE)
2102 else if(event.type == CE_PLAYER_DAMAGE)
2104 //u16 damage = event.player_damage.amount;
2105 //infostream<<"Player damage: "<<damage<<std::endl;
2107 damage_flash += 100.0;
2108 damage_flash += 8.0 * event.player_damage.amount;
2110 player->hurt_tilt_timer = 1.5;
2111 player->hurt_tilt_strength = event.player_damage.amount/2;
2112 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2114 else if(event.type == CE_PLAYER_FORCE_MOVE)
2116 camera_yaw = event.player_force_move.yaw;
2117 camera_pitch = event.player_force_move.pitch;
2119 else if(event.type == CE_DEATHSCREEN)
2121 if(respawn_menu_active)
2124 /*bool set_camera_point_target =
2125 event.deathscreen.set_camera_point_target;
2126 v3f camera_point_target;
2127 camera_point_target.X = event.deathscreen.camera_point_target_x;
2128 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2129 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2130 MainRespawnInitiator *respawner =
2131 new MainRespawnInitiator(
2132 &respawn_menu_active, &client);
2133 GUIDeathScreen *menu =
2134 new GUIDeathScreen(guienv, guiroot, -1,
2135 &g_menumgr, respawner);
2138 chat_backend.addMessage(L"", L"You died.");
2140 /* Handle visualization */
2144 LocalPlayer* player = client.getEnv().getLocalPlayer();
2145 player->hurt_tilt_timer = 0;
2146 player->hurt_tilt_strength = 0;
2148 /*LocalPlayer* player = client.getLocalPlayer();
2149 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2150 camera.update(player, busytime, screensize);*/
2152 else if (event.type == CE_SHOW_FORMSPEC)
2154 if (current_formspec == 0)
2157 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2159 GUIFormSpecMenu *menu =
2160 new GUIFormSpecMenu(device, guiroot, -1,
2163 menu->setFormSource(current_formspec);
2164 menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
2170 current_formspec->setForm(*(event.show_formspec.formspec));
2172 delete(event.show_formspec.formspec);
2173 delete(event.show_formspec.formname);
2175 else if(event.type == CE_TEXTURES_UPDATED)
2177 update_wielded_item_trigger = true;
2182 //TimeTaker //timer2("//timer2");
2185 For interaction purposes, get info about the held item
2187 - Is it a usable item?
2188 - Can it point to liquids?
2190 ItemStack playeritem;
2191 bool playeritem_usable = false;
2192 bool playeritem_liquids_pointable = false;
2194 InventoryList *mlist = local_inventory.getList("main");
2197 playeritem = mlist->getItem(client.getPlayerItem());
2198 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2199 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2202 ToolCapabilities playeritem_toolcap =
2203 playeritem.getToolCapabilities(itemdef);
2209 LocalPlayer* player = client.getEnv().getLocalPlayer();
2210 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2211 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2212 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2213 camera.update(player, busytime, screensize, tool_reload_ratio);
2216 v3f player_position = player->getPosition();
2217 v3f camera_position = camera.getPosition();
2218 v3f camera_direction = camera.getDirection();
2219 f32 camera_fov = camera.getFovMax();
2221 if(!disable_camera_update){
2222 client.getEnv().getClientMap().updateCamera(camera_position,
2223 camera_direction, camera_fov);
2226 // Update sound listener
2227 sound->updateListener(camera.getCameraNode()->getPosition(),
2228 v3f(0,0,0), // velocity
2229 camera.getDirection(),
2230 camera.getCameraNode()->getUpVector());
2231 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2237 soundmaker.step(dtime);
2239 ClientMap &map = client.getEnv().getClientMap();
2240 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2241 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2245 Calculate what block is the crosshair pointing to
2248 //u32 t1 = device->getTimer()->getRealTime();
2250 f32 d = 4; // max. distance
2251 core::line3d<f32> shootline(camera_position,
2252 camera_position + camera_direction * BS * (d+1));
2254 ClientActiveObject *selected_object = NULL;
2256 PointedThing pointed = getPointedThing(
2258 &client, player_position, camera_direction,
2259 camera_position, shootline, d,
2260 playeritem_liquids_pointable, !ldown_for_dig,
2265 if(pointed != pointed_old)
2267 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2268 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2273 - releasing left mouse button
2274 - pointing away from node
2278 if(input->getLeftReleased())
2280 infostream<<"Left button released"
2281 <<" (stopped digging)"<<std::endl;
2284 else if(pointed != pointed_old)
2286 if (pointed.type == POINTEDTHING_NODE
2287 && pointed_old.type == POINTEDTHING_NODE
2288 && pointed.node_undersurface == pointed_old.node_undersurface)
2290 // Still pointing to the same node,
2291 // but a different face. Don't reset.
2295 infostream<<"Pointing away from node"
2296 <<" (stopped digging)"<<std::endl;
2302 client.interact(1, pointed_old);
2303 client.setCrack(-1, v3s16(0,0,0));
2307 if(!digging && ldown_for_dig && !input->getLeftState())
2309 ldown_for_dig = false;
2312 bool left_punch = false;
2313 soundmaker.m_player_leftpunch_sound.name = "";
2315 if(input->getRightState())
2316 repeat_rightclick_timer += dtime;
2318 if(playeritem_usable && input->getLeftState())
2320 if(input->getLeftClicked())
2321 client.interact(4, pointed);
2323 else if(pointed.type == POINTEDTHING_NODE)
2325 v3s16 nodepos = pointed.node_undersurface;
2326 v3s16 neighbourpos = pointed.node_abovesurface;
2329 Check information text of node
2332 ClientMap &map = client.getEnv().getClientMap();
2333 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2335 infotext = narrow_to_wide(meta->getString("infotext"));
2337 MapNode n = map.getNode(nodepos);
2338 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2339 infotext = L"Unknown node: ";
2340 infotext += narrow_to_wide(nodedef->get(n).name);
2344 // We can't actually know, but assume the sound of right-clicking
2345 // to be the sound of placing a node
2346 soundmaker.m_player_rightpunch_sound.gain = 0.5;
2347 soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2353 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2357 infostream<<"Started digging"<<std::endl;
2358 client.interact(0, pointed);
2360 ldown_for_dig = true;
2362 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2364 // NOTE: Similar piece of code exists on the server side for
2366 // Get digging parameters
2367 DigParams params = getDigParams(nodedef->get(n).groups,
2368 &playeritem_toolcap);
2369 // If can't dig, try hand
2370 if(!params.diggable){
2371 const ItemDefinition &hand = itemdef->get("");
2372 const ToolCapabilities *tp = hand.tool_capabilities;
2374 params = getDigParams(nodedef->get(n).groups, tp);
2377 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2378 if(sound_dig.exists()){
2379 if(sound_dig.name == "__group"){
2380 if(params.main_group != ""){
2381 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2382 soundmaker.m_player_leftpunch_sound.name =
2383 std::string("default_dig_") +
2387 soundmaker.m_player_leftpunch_sound = sound_dig;
2391 float dig_time_complete = 0.0;
2393 if(params.diggable == false)
2395 // I guess nobody will wait for this long
2396 dig_time_complete = 10000000.0;
2400 dig_time_complete = params.time;
2403 if(dig_time_complete >= 0.001)
2405 dig_index = (u16)((float)crack_animation_length
2406 * dig_time/dig_time_complete);
2408 // This is for torches
2411 dig_index = crack_animation_length;
2414 // Don't show cracks if not diggable
2415 if(dig_time_complete >= 100000.0)
2418 else if(dig_index < crack_animation_length)
2420 //TimeTaker timer("client.setTempMod");
2421 //infostream<<"dig_index="<<dig_index<<std::endl;
2422 client.setCrack(dig_index, nodepos);
2426 infostream<<"Digging completed"<<std::endl;
2427 client.interact(2, pointed);
2428 client.setCrack(-1, v3s16(0,0,0));
2429 MapNode wasnode = map.getNode(nodepos);
2430 client.removeNode(nodepos);
2435 nodig_delay_timer = dig_time_complete
2436 / (float)crack_animation_length;
2438 // We don't want a corresponding delay to
2439 // very time consuming nodes
2440 if(nodig_delay_timer > 0.3)
2441 nodig_delay_timer = 0.3;
2442 // We want a slight delay to very little
2443 // time consuming nodes
2444 float mindelay = 0.15;
2445 if(nodig_delay_timer < mindelay)
2446 nodig_delay_timer = mindelay;
2448 // Send event to trigger sound
2449 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2450 gamedef->event()->put(e);
2455 camera.setDigging(0); // left click animation
2458 if(input->getRightClicked() ||
2459 repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2461 repeat_rightclick_timer = 0;
2462 infostream<<"Ground right-clicked"<<std::endl;
2464 // Sign special case, at least until formspec is properly implemented.
2466 if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
2468 infostream<<"Launching metadata text input"<<std::endl;
2470 // Get a new text for it
2472 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2474 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2476 (new GUITextInputMenu(guienv, guiroot, -1,
2480 // If metadata provides an inventory view, activate it
2481 else if(meta && meta->getString("formspec") != "" && !random_input)
2483 infostream<<"Launching custom inventory view"<<std::endl;
2485 InventoryLocation inventoryloc;
2486 inventoryloc.setNodeMeta(nodepos);
2490 GUIFormSpecMenu *menu =
2491 new GUIFormSpecMenu(device, guiroot, -1,
2494 menu->setFormSpec(meta->getString("formspec"),
2496 menu->setFormSource(new NodeMetadataFormSource(
2497 &client.getEnv().getClientMap(), nodepos));
2498 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2501 // Otherwise report right click to server
2505 client.interact(3, pointed);
2506 camera.setDigging(1); // right click animation
2508 // If the wielded item has node placement prediction,
2510 const ItemDefinition &def =
2511 playeritem.getDefinition(itemdef);
2512 if(def.node_placement_prediction != "")
2514 verbosestream<<"Node placement prediction for "
2515 <<playeritem.name<<" is "
2516 <<def.node_placement_prediction<<std::endl;
2517 v3s16 p = neighbourpos;
2518 // Place inside node itself if buildable_to
2520 MapNode n_under = map.getNode(nodepos);
2521 if(nodedef->get(n_under).buildable_to)
2523 }catch(InvalidPositionException &e){}
2524 // Find id of predicted node
2527 nodedef->getId(def.node_placement_prediction, id);
2529 errorstream<<"Node placement prediction failed for "
2530 <<playeritem.name<<" (places "
2531 <<def.node_placement_prediction
2532 <<") - Name not known"<<std::endl;
2537 // This triggers the required mesh update too
2538 client.addNode(p, n);
2539 }catch(InvalidPositionException &e){
2540 errorstream<<"Node placement prediction failed for "
2541 <<playeritem.name<<" (places "
2542 <<def.node_placement_prediction
2543 <<") - Position not loaded"<<std::endl;
2549 else if(pointed.type == POINTEDTHING_OBJECT)
2551 infotext = narrow_to_wide(selected_object->infoText());
2553 if(infotext == L"" && show_debug){
2554 infotext = narrow_to_wide(selected_object->debugInfoText());
2557 //if(input->getLeftClicked())
2558 if(input->getLeftState())
2560 bool do_punch = false;
2561 bool do_punch_damage = false;
2562 if(object_hit_delay_timer <= 0.0){
2564 do_punch_damage = true;
2565 object_hit_delay_timer = object_hit_delay;
2567 if(input->getLeftClicked()){
2571 infostream<<"Left-clicked object"<<std::endl;
2574 if(do_punch_damage){
2575 // Report direct punch
2576 v3f objpos = selected_object->getPosition();
2577 v3f dir = (objpos - player_position).normalize();
2579 bool disable_send = selected_object->directReportPunch(
2580 dir, &playeritem, time_from_last_punch);
2581 time_from_last_punch = 0;
2583 client.interact(0, pointed);
2586 else if(input->getRightClicked())
2588 infostream<<"Right-clicked object"<<std::endl;
2589 client.interact(3, pointed); // place
2592 else if(input->getLeftState())
2594 // When button is held down in air, show continuous animation
2598 pointed_old = pointed;
2600 if(left_punch || input->getLeftClicked())
2602 camera.setDigging(0); // left click animation
2605 input->resetLeftClicked();
2606 input->resetRightClicked();
2608 input->resetLeftReleased();
2609 input->resetRightReleased();
2612 Calculate stuff for drawing
2621 fog_range = BS*farmesh_range;
2625 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2627 if(draw_control.range_all)
2628 fog_range = 100000*BS;
2632 Calculate general brightness
2634 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2635 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2636 float direct_brightness = 0;
2637 bool sunlight_seen = false;
2638 if(g_settings->getBool("free_move")){
2639 direct_brightness = time_brightness;
2640 sunlight_seen = true;
2642 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2643 float old_brightness = sky->getBrightness();
2644 direct_brightness = (float)client.getEnv().getClientMap()
2645 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2646 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2650 time_of_day = client.getEnv().getTimeOfDayF();
2652 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2653 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2654 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2655 time_of_day_smooth = time_of_day;
2657 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2658 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2659 + (time_of_day+1.0) * todsm;
2661 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2662 + time_of_day * todsm;
2664 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2667 float brightness = sky->getBrightness();
2668 video::SColor bgcolor = sky->getBgColor();
2669 video::SColor skycolor = sky->getSkyColor();
2675 if(sky->getCloudsVisible()){
2676 clouds->setVisible(true);
2677 clouds->step(dtime);
2678 clouds->update(v2f(player_position.X, player_position.Z),
2679 sky->getCloudColor());
2681 clouds->setVisible(false);
2690 farmesh_range = draw_control.wanted_range * 10;
2691 if(draw_control.range_all && farmesh_range < 500)
2692 farmesh_range = 500;
2693 if(farmesh_range > 1000)
2694 farmesh_range = 1000;
2696 farmesh->step(dtime);
2697 farmesh->update(v2f(player_position.X, player_position.Z),
2698 brightness, farmesh_range);
2705 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2709 video::EFT_FOG_LINEAR,
2721 video::EFT_FOG_LINEAR,
2731 Update gui stuff (0ms)
2734 //TimeTaker guiupdatetimer("Gui updating");
2736 const char program_name_and_version[] =
2737 "Minetest " VERSION_STRING;
2741 static float drawtime_avg = 0;
2742 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2743 /*static float beginscenetime_avg = 0;
2744 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2745 static float scenetime_avg = 0;
2746 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2747 static float endscenetime_avg = 0;
2748 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2751 snprintf(temptext, 300, "%s ("
2754 " drawtime=%.0f, dtime_jitter = % .1f %%"
2755 ", v_range = %.1f, RTT = %.3f",
2756 program_name_and_version,
2757 draw_control.range_all,
2759 dtime_jitter1_max_fraction * 100.0,
2760 draw_control.wanted_range,
2764 guitext->setText(narrow_to_wide(temptext).c_str());
2765 guitext->setVisible(true);
2767 else if(show_hud || show_chat)
2769 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2770 guitext->setVisible(true);
2774 guitext->setVisible(false);
2780 snprintf(temptext, 300,
2781 "(% .1f, % .1f, % .1f)"
2782 " (yaw = %.1f) (seed = %lli)",
2783 player_position.X/BS,
2784 player_position.Y/BS,
2785 player_position.Z/BS,
2786 wrapDegrees_0_360(camera_yaw),
2787 client.getMapSeed());
2789 guitext2->setText(narrow_to_wide(temptext).c_str());
2790 guitext2->setVisible(true);
2794 guitext2->setVisible(false);
2798 guitext_info->setText(infotext.c_str());
2799 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2803 float statustext_time_max = 1.5;
2804 if(!statustext.empty())
2806 statustext_time += dtime;
2807 if(statustext_time >= statustext_time_max)
2810 statustext_time = 0;
2813 guitext_status->setText(statustext.c_str());
2814 guitext_status->setVisible(!statustext.empty());
2816 if(!statustext.empty())
2818 s32 status_y = screensize.Y - 130;
2819 core::rect<s32> rect(
2821 status_y - guitext_status->getTextHeight(),
2825 guitext_status->setRelativePosition(rect);
2828 video::SColor initial_color(255,0,0,0);
2829 if(guienv->getSkin())
2830 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2831 video::SColor final_color = initial_color;
2832 final_color.setAlpha(0);
2833 video::SColor fade_color =
2834 initial_color.getInterpolated_quadratic(
2837 pow(statustext_time / (float)statustext_time_max, 2.0f));
2838 guitext_status->setOverrideColor(fade_color);
2839 guitext_status->enableOverrideColor(true);
2844 Get chat messages from client
2847 // Get new messages from error log buffer
2848 while(!chat_log_error_buf.empty())
2850 chat_backend.addMessage(L"", narrow_to_wide(
2851 chat_log_error_buf.get()));
2853 // Get new messages from client
2854 std::wstring message;
2855 while(client.getChatMessage(message))
2857 chat_backend.addUnparsedMessage(message);
2859 // Remove old messages
2860 chat_backend.step(dtime);
2862 // Display all messages in a static text element
2863 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2864 std::wstring recent_chat = chat_backend.getRecentChat();
2865 guitext_chat->setText(recent_chat.c_str());
2867 // Update gui element size and position
2868 s32 chat_y = 5+(text_height+5);
2870 chat_y += (text_height+5);
2871 core::rect<s32> rect(
2875 chat_y + guitext_chat->getTextHeight()
2877 guitext_chat->setRelativePosition(rect);
2879 // Don't show chat if disabled or empty or profiler is enabled
2880 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2888 if(client.getPlayerItem() != new_playeritem)
2890 client.selectPlayerItem(new_playeritem);
2892 if(client.getLocalInventoryUpdated())
2894 //infostream<<"Updating local inventory"<<std::endl;
2895 client.getLocalInventory(local_inventory);
2897 update_wielded_item_trigger = true;
2899 if(update_wielded_item_trigger)
2901 update_wielded_item_trigger = false;
2902 // Update wielded tool
2903 InventoryList *mlist = local_inventory.getList("main");
2906 item = mlist->getItem(client.getPlayerItem());
2911 Update block draw list every 200ms or when camera direction has
2914 update_draw_list_timer += dtime;
2915 if(update_draw_list_timer >= 0.2 ||
2916 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2917 update_draw_list_timer = 0;
2918 client.getEnv().getClientMap().updateDrawList(driver);
2919 update_draw_list_last_cam_dir = camera_direction;
2926 TimeTaker tt_draw("mainloop: draw");
2930 TimeTaker timer("beginScene");
2931 //driver->beginScene(false, true, bgcolor);
2932 //driver->beginScene(true, true, bgcolor);
2933 driver->beginScene(true, true, skycolor);
2934 beginscenetime = timer.stop(true);
2939 //infostream<<"smgr->drawAll()"<<std::endl;
2941 TimeTaker timer("smgr");
2944 if(g_settings->getBool("anaglyph"))
2946 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
2947 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
2949 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
2951 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
2952 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
2953 camera.getCameraNode()->getAbsolutePosition() ;
2956 irr::core::vector3df leftEye;
2957 irr::core::matrix4 leftMove;
2959 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2960 leftEye=(startMatrix*leftMove).getTranslation();
2962 //clear the depth buffer, and color
2963 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
2965 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
2966 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
2967 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2968 irr::scene::ESNRP_SOLID +
2969 irr::scene::ESNRP_TRANSPARENT +
2970 irr::scene::ESNRP_TRANSPARENT_EFFECT +
2971 irr::scene::ESNRP_SHADOW;
2973 camera.getCameraNode()->setPosition( leftEye );
2974 camera.getCameraNode()->setTarget( focusPoint );
2976 smgr->drawAll(); // 'smgr->drawAll();' may go here
2980 irr::core::vector3df rightEye;
2981 irr::core::matrix4 rightMove;
2983 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2984 rightEye=(startMatrix*rightMove).getTranslation();
2986 //clear the depth buffer
2987 driver->clearZBuffer();
2989 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
2990 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
2991 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2992 irr::scene::ESNRP_SOLID +
2993 irr::scene::ESNRP_TRANSPARENT +
2994 irr::scene::ESNRP_TRANSPARENT_EFFECT +
2995 irr::scene::ESNRP_SHADOW;
2997 camera.getCameraNode()->setPosition( rightEye );
2998 camera.getCameraNode()->setTarget( focusPoint );
3000 smgr->drawAll(); // 'smgr->drawAll();' may go here
3003 //driver->endScene();
3005 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3006 driver->getOverrideMaterial().EnableFlags=0;
3007 driver->getOverrideMaterial().EnablePasses=0;
3009 camera.getCameraNode()->setPosition( oldPosition );
3010 camera.getCameraNode()->setTarget( oldTarget );
3013 scenetime = timer.stop(true);
3017 //TimeTaker timer9("auxiliary drawings");
3021 //TimeTaker //timer10("//timer10");
3027 driver->setMaterial(m);
3029 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3033 v3f selectionbox_color = g_settings->getV3F("selectionbox_color");
3034 u32 selectionbox_color_r = rangelim(myround(selectionbox_color.X), 0, 255);
3035 u32 selectionbox_color_g = rangelim(myround(selectionbox_color.Y), 0, 255);
3036 u32 selectionbox_color_b = rangelim(myround(selectionbox_color.Z), 0, 255);
3038 for(std::vector<aabb3f>::const_iterator
3039 i = hilightboxes.begin();
3040 i != hilightboxes.end(); i++)
3042 /*infostream<<"hilightbox min="
3043 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
3045 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
3047 driver->draw3DBox(*i, video::SColor(255,selectionbox_color_r,selectionbox_color_g,selectionbox_color_b));
3056 // Warning: This clears the Z buffer.
3057 camera.drawWieldedTool();
3064 client.getEnv().getClientMap().renderPostFx();
3070 if(show_profiler_graph)
3072 graph.draw(10, screensize.Y - 10, driver, font);
3080 v3f crosshair_color = g_settings->getV3F("crosshair_color");
3081 u32 crosshair_color_r = rangelim(myround(crosshair_color.X), 0, 255);
3082 u32 crosshair_color_g = rangelim(myround(crosshair_color.Y), 0, 255);
3083 u32 crosshair_color_b = rangelim(myround(crosshair_color.Z), 0, 255);
3084 u32 crosshair_alpha = rangelim(g_settings->getS32("crosshair_alpha"), 0, 255);
3086 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
3087 displaycenter + core::vector2d<s32>(10,0),
3088 video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3089 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
3090 displaycenter + core::vector2d<s32>(0,10),
3091 video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3097 //TimeTaker //timer11("//timer11");
3105 draw_hotbar(driver, font, gamedef,
3106 v2s32(displaycenter.X, screensize.Y),
3107 hotbar_imagesize, hotbar_itemcount, &local_inventory,
3108 client.getHP(), client.getPlayerItem());
3114 if(damage_flash > 0.0)
3116 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3117 driver->draw2DRectangle(color,
3118 core::rect<s32>(0,0,screensize.X,screensize.Y),
3121 damage_flash -= 100.0*dtime;
3127 if(player->hurt_tilt_timer > 0.0)
3129 player->hurt_tilt_timer -= dtime*5;
3130 if(player->hurt_tilt_timer < 0)
3131 player->hurt_tilt_strength = 0;
3144 TimeTaker timer("endScene");
3146 endscenetime = timer.stop(true);
3149 drawtime = tt_draw.stop(true);
3150 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3156 static s16 lastFPS = 0;
3157 //u16 fps = driver->getFPS();
3158 u16 fps = (1.0/dtime_avg1);
3162 core::stringw str = L"Minetest [";
3163 str += driver->getName();
3167 device->setWindowCaption(str.c_str());
3172 Log times and stuff for visualization
3174 Profiler::GraphValues values;
3175 g_profiler->graphGet(values);
3184 if(gui_chat_console)
3185 gui_chat_console->drop();
3188 Draw a "shutting down" screen, which will be shown while the map
3189 generator and other stuff quits
3192 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3193 draw_load_screen(L"Shutting down stuff...", driver, font);
3194 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3197 gui_shuttingdowntext->remove();*/
3200 chat_backend.addMessage(L"", L"# Disconnected.");
3201 chat_backend.addMessage(L"", L"");
3203 // Client scope (client is destructed before destructing *def and tsrc)
3206 catch(SerializationError &e)
3208 error_message = L"A serialization error occurred:\n"
3209 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3210 L" running a different version of Minetest.";
3211 errorstream<<wide_to_narrow(error_message)<<std::endl;