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>
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiFormSpecMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
35 #include "guiChatConsole.h"
43 #include "mainmenumanager.h"
47 // Needed for determining pointing to nodes
49 #include "nodemetadata.h"
50 #include "main.h" // For g_settings
52 #include "tile.h" // For TextureSource
53 #include "logoutputbuffer.h"
55 #include "quicktune_shortcutter.h"
56 #include "clientmap.h"
60 #include "sound_openal.h"
62 #include "event_manager.h"
64 #include "util/directiontables.h"
70 struct TextDestChat : public TextDest
72 TextDestChat(Client *client)
76 void gotText(std::wstring text)
78 m_client->typeChatMessage(text);
80 void gotText(std::map<std::string, std::string> fields)
82 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
88 struct TextDestNodeMetadata : public TextDest
90 TextDestNodeMetadata(v3s16 p, Client *client)
95 // This is deprecated I guess? -celeron55
96 void gotText(std::wstring text)
98 std::string ntext = wide_to_narrow(text);
99 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
100 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
101 std::map<std::string, std::string> fields;
102 fields["text"] = ntext;
103 m_client->sendNodemetaFields(m_p, "", fields);
105 void gotText(std::map<std::string, std::string> fields)
107 m_client->sendNodemetaFields(m_p, "", fields);
114 struct TextDestPlayerInventory : public TextDest
116 TextDestPlayerInventory(Client *client)
120 void gotText(std::map<std::string, std::string> fields)
122 m_client->sendInventoryFields("", fields);
128 /* Respawn menu callback */
130 class MainRespawnInitiator: public IRespawnInitiator
133 MainRespawnInitiator(bool *active, Client *client):
134 m_active(active), m_client(client)
141 m_client->sendRespawn();
148 /* Form update callback */
150 class NodeMetadataFormSource: public IFormSource
153 NodeMetadataFormSource(ClientMap *map, v3s16 p):
158 std::string getForm()
160 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
163 return meta->getString("formspec");
165 std::string resolveText(std::string str)
167 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
170 return meta->resolveString(str);
177 class PlayerInventoryFormSource: public IFormSource
180 PlayerInventoryFormSource(Client *client):
184 std::string getForm()
186 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
187 return player->inventory_formspec;
196 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
198 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
199 Inventory *inventory, s32 halfheartcount, u16 playeritem)
201 InventoryList *mainlist = inventory->getList("main");
204 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
208 s32 padding = imgsize/12;
209 //s32 height = imgsize + padding*2;
210 s32 width = itemcount*(imgsize+padding*2);
212 // Position of upper left corner of bar
213 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
215 // Draw background color
216 /*core::rect<s32> barrect(0,0,width,height);
218 video::SColor bgcolor(255,128,128,128);
219 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
221 core::rect<s32> imgrect(0,0,imgsize,imgsize);
223 for(s32 i=0; i<itemcount; i++)
225 const ItemStack &item = mainlist->getItem(i);
227 core::rect<s32> rect = imgrect + pos
228 + v2s32(padding+i*(imgsize+padding*2), padding);
232 video::SColor c_outside(255,255,0,0);
233 //video::SColor c_outside(255,0,0,0);
234 //video::SColor c_inside(255,192,192,192);
235 s32 x1 = rect.UpperLeftCorner.X;
236 s32 y1 = rect.UpperLeftCorner.Y;
237 s32 x2 = rect.LowerRightCorner.X;
238 s32 y2 = rect.LowerRightCorner.Y;
239 // Black base borders
240 driver->draw2DRectangle(c_outside,
242 v2s32(x1 - padding, y1 - padding),
243 v2s32(x2 + padding, y1)
245 driver->draw2DRectangle(c_outside,
247 v2s32(x1 - padding, y2),
248 v2s32(x2 + padding, y2 + padding)
250 driver->draw2DRectangle(c_outside,
252 v2s32(x1 - padding, y1),
255 driver->draw2DRectangle(c_outside,
258 v2s32(x2 + padding, y2)
260 /*// Light inside borders
261 driver->draw2DRectangle(c_inside,
263 v2s32(x1 - padding/2, y1 - padding/2),
264 v2s32(x2 + padding/2, y1)
266 driver->draw2DRectangle(c_inside,
268 v2s32(x1 - padding/2, y2),
269 v2s32(x2 + padding/2, y2 + padding/2)
271 driver->draw2DRectangle(c_inside,
273 v2s32(x1 - padding/2, y1),
276 driver->draw2DRectangle(c_inside,
279 v2s32(x2 + padding/2, y2)
284 video::SColor bgcolor2(128,0,0,0);
285 driver->draw2DRectangle(bgcolor2, rect, NULL);
286 drawItemStack(driver, font, item, rect, NULL, gamedef);
292 video::ITexture *heart_texture =
293 gamedef->getTextureSource()->getTextureRaw("heart.png");
296 v2s32 p = pos + v2s32(0, -20);
297 for(s32 i=0; i<halfheartcount/2; i++)
299 const video::SColor color(255,255,255,255);
300 const video::SColor colors[] = {color,color,color,color};
301 core::rect<s32> rect(0,0,16,16);
303 driver->draw2DImage(heart_texture, rect,
304 core::rect<s32>(core::position2d<s32>(0,0),
305 core::dimension2di(heart_texture->getOriginalSize())),
309 if(halfheartcount % 2 == 1)
311 const video::SColor color(255,255,255,255);
312 const video::SColor colors[] = {color,color,color,color};
313 core::rect<s32> rect(0,0,16/2,16);
315 core::dimension2di srcd(heart_texture->getOriginalSize());
317 driver->draw2DImage(heart_texture, rect,
318 core::rect<s32>(core::position2d<s32>(0,0), srcd),
326 Check if a node is pointable
328 inline bool isPointableNode(const MapNode& n,
329 Client *client, bool liquids_pointable)
331 const ContentFeatures &features = client->getNodeDefManager()->get(n);
332 return features.pointable ||
333 (liquids_pointable && features.isLiquid());
337 Find what the player is pointing at
339 PointedThing getPointedThing(Client *client, v3f player_position,
340 v3f camera_direction, v3f camera_position,
341 core::line3d<f32> shootline, f32 d,
342 bool liquids_pointable,
343 bool look_for_object,
344 std::vector<aabb3f> &hilightboxes,
345 ClientActiveObject *&selected_object)
349 hilightboxes.clear();
350 selected_object = NULL;
352 INodeDefManager *nodedef = client->getNodeDefManager();
353 ClientMap &map = client->getEnv().getClientMap();
355 // First try to find a pointed at active object
358 selected_object = client->getSelectedActiveObject(d*BS,
359 camera_position, shootline);
361 if(selected_object != NULL)
363 if(selected_object->doShowSelectionBox())
365 aabb3f *selection_box = selected_object->getSelectionBox();
366 // Box should exist because object was
367 // returned in the first place
368 assert(selection_box);
370 v3f pos = selected_object->getPosition();
371 hilightboxes.push_back(aabb3f(
372 selection_box->MinEdge + pos,
373 selection_box->MaxEdge + pos));
377 result.type = POINTEDTHING_OBJECT;
378 result.object_id = selected_object->getId();
383 // That didn't work, try to find a pointed at node
385 f32 mindistance = BS * 1001;
387 v3s16 pos_i = floatToInt(player_position, BS);
389 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
393 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
394 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
395 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
396 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
397 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
398 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
400 // Prevent signed number overflow
408 for(s16 y = ystart; y <= yend; y++)
409 for(s16 z = zstart; z <= zend; z++)
410 for(s16 x = xstart; x <= xend; x++)
415 n = map.getNode(v3s16(x,y,z));
417 catch(InvalidPositionException &e)
421 if(!isPointableNode(n, client, liquids_pointable))
424 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
427 v3f npf = intToFloat(np, BS);
429 for(std::vector<aabb3f>::const_iterator
431 i != boxes.end(); i++)
437 for(u16 j=0; j<6; j++)
439 v3s16 facedir = g_6dirs[j];
440 aabb3f facebox = box;
444 facebox.MinEdge.X = facebox.MaxEdge.X-d;
445 else if(facedir.X < 0)
446 facebox.MaxEdge.X = facebox.MinEdge.X+d;
447 else if(facedir.Y > 0)
448 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
449 else if(facedir.Y < 0)
450 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
451 else if(facedir.Z > 0)
452 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
453 else if(facedir.Z < 0)
454 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
456 v3f centerpoint = facebox.getCenter();
457 f32 distance = (centerpoint - camera_position).getLength();
458 if(distance >= mindistance)
460 if(!facebox.intersectsWithLine(shootline))
463 v3s16 np_above = np + facedir;
465 result.type = POINTEDTHING_NODE;
466 result.node_undersurface = np;
467 result.node_abovesurface = np_above;
468 mindistance = distance;
470 hilightboxes.clear();
471 for(std::vector<aabb3f>::const_iterator
473 i2 != boxes.end(); i2++)
476 box.MinEdge += npf + v3f(-d,-d,-d);
477 box.MaxEdge += npf + v3f(d,d,d);
478 hilightboxes.push_back(box);
488 Draws a screen with a single text on it.
489 Text will be removed when the screen is drawn the next time.
491 /*gui::IGUIStaticText **/
492 void draw_load_screen(const std::wstring &text,
493 video::IVideoDriver* driver, gui::IGUIFont* font)
495 v2u32 screensize = driver->getScreenSize();
496 const wchar_t *loadingtext = text.c_str();
497 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
498 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
499 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
500 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
502 gui::IGUIStaticText *guitext = guienv->addStaticText(
503 loadingtext, textrect, false, false);
504 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
506 driver->beginScene(true, true, video::SColor(255,0,0,0));
515 /* Profiler display */
517 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
518 gui::IGUIFont *font, u32 text_height,
519 u32 show_profiler, u32 show_profiler_max)
521 if(show_profiler == 0)
523 guitext_profiler->setVisible(false);
528 std::ostringstream os(std::ios_base::binary);
529 g_profiler->printPage(os, show_profiler, show_profiler_max);
530 std::wstring text = narrow_to_wide(os.str());
531 guitext_profiler->setText(text.c_str());
532 guitext_profiler->setVisible(true);
534 s32 w = font->getDimension(text.c_str()).Width;
537 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
538 8+(text_height+5)*2 +
539 font->getDimension(text.c_str()).Height);
540 guitext_profiler->setRelativePosition(rect);
541 guitext_profiler->setVisible(true);
549 Profiler::GraphValues values;
555 Meta(float initial=0, video::SColor color=
556 video::SColor(255,255,255,255)):
562 std::list<Piece> m_log;
570 void put(const Profiler::GraphValues &values)
573 piece.values = values;
574 m_log.push_back(piece);
575 while(m_log.size() > m_log_max_size)
576 m_log.erase(m_log.begin());
579 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
580 gui::IGUIFont* font) const
582 std::map<std::string, Meta> m_meta;
583 for(std::list<Piece>::const_iterator k = m_log.begin();
584 k != m_log.end(); k++)
586 const Piece &piece = *k;
587 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
588 i != piece.values.end(); i++){
589 const std::string &id = i->first;
590 const float &value = i->second;
591 std::map<std::string, Meta>::iterator j =
593 if(j == m_meta.end()){
594 m_meta[id] = Meta(value);
597 if(value < j->second.min)
598 j->second.min = value;
599 if(value > j->second.max)
600 j->second.max = value;
605 static const video::SColor usable_colors[] = {
606 video::SColor(255,255,100,100),
607 video::SColor(255,90,225,90),
608 video::SColor(255,100,100,255),
609 video::SColor(255,255,150,50),
610 video::SColor(255,220,220,100)
612 static const u32 usable_colors_count =
613 sizeof(usable_colors) / sizeof(*usable_colors);
614 u32 next_color_i = 0;
615 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
616 i != m_meta.end(); i++){
617 Meta &meta = i->second;
618 video::SColor color(255,200,200,200);
619 if(next_color_i < usable_colors_count)
620 color = usable_colors[next_color_i++];
625 s32 textx = x_left + m_log_max_size + 15;
626 s32 textx2 = textx + 200 - 15;
630 u32 num_graphs = m_meta.size();
631 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
633 video::SColor bgcolor(120,0,0,0);
634 driver->draw2DRectangle(bgcolor, rect, NULL);
638 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
639 i != m_meta.end(); i++){
640 const std::string &id = i->first;
641 const Meta &meta = i->second;
643 s32 y = y_bottom - meta_i * 50;
644 float show_min = meta.min;
645 float show_max = meta.max;
646 if(show_min >= -0.0001 && show_max >= -0.0001){
647 if(show_min <= show_max * 0.5)
652 snprintf(buf, 10, "%.3g", show_max);
653 font->draw(narrow_to_wide(buf).c_str(),
654 core::rect<s32>(textx, y - graphh,
655 textx2, y - graphh + texth),
657 snprintf(buf, 10, "%.3g", show_min);
658 font->draw(narrow_to_wide(buf).c_str(),
659 core::rect<s32>(textx, y - texth,
662 font->draw(narrow_to_wide(id).c_str(),
663 core::rect<s32>(textx, y - graphh/2 - texth/2,
664 textx2, y - graphh/2 + texth/2),
667 s32 graph1h = graphh;
668 bool relativegraph = (show_min != 0 && show_min != show_max);
669 float lastscaledvalue = 0.0;
670 bool lastscaledvalue_exists = false;
671 for(std::list<Piece>::const_iterator j = m_log.begin();
672 j != m_log.end(); j++)
674 const Piece &piece = *j;
676 bool value_exists = false;
677 Profiler::GraphValues::const_iterator k =
678 piece.values.find(id);
679 if(k != piece.values.end()){
685 lastscaledvalue_exists = false;
688 float scaledvalue = 1.0;
689 if(show_max != show_min)
690 scaledvalue = (value - show_min) / (show_max - show_min);
691 if(scaledvalue == 1.0 && value == 0){
693 lastscaledvalue_exists = false;
697 if(lastscaledvalue_exists){
698 s32 ivalue1 = lastscaledvalue * graph1h;
699 s32 ivalue2 = scaledvalue * graph1h;
700 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
701 v2s32(x, graph1y - ivalue2), meta.color);
703 lastscaledvalue = scaledvalue;
704 lastscaledvalue_exists = true;
706 s32 ivalue = scaledvalue * graph1h;
707 driver->draw2DLine(v2s32(x, graph1y),
708 v2s32(x, graph1y - ivalue), meta.color);
717 class NodeDugEvent: public MtEvent
723 NodeDugEvent(v3s16 p, MapNode n):
727 const char* getType() const
733 ISoundManager *m_sound;
734 INodeDefManager *m_ndef;
736 float m_player_step_timer;
738 SimpleSoundSpec m_player_step_sound;
739 SimpleSoundSpec m_player_leftpunch_sound;
740 SimpleSoundSpec m_player_rightpunch_sound;
742 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
745 m_player_step_timer(0)
749 void playPlayerStep()
751 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
752 m_player_step_timer = 0.03;
753 m_sound->playSound(m_player_step_sound, false);
757 static void viewBobbingStep(MtEvent *e, void *data)
759 SoundMaker *sm = (SoundMaker*)data;
760 sm->playPlayerStep();
763 static void playerRegainGround(MtEvent *e, void *data)
765 SoundMaker *sm = (SoundMaker*)data;
766 sm->playPlayerStep();
769 static void playerJump(MtEvent *e, void *data)
771 //SoundMaker *sm = (SoundMaker*)data;
774 static void cameraPunchLeft(MtEvent *e, void *data)
776 SoundMaker *sm = (SoundMaker*)data;
777 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
780 static void cameraPunchRight(MtEvent *e, void *data)
782 SoundMaker *sm = (SoundMaker*)data;
783 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
786 static void nodeDug(MtEvent *e, void *data)
788 SoundMaker *sm = (SoundMaker*)data;
789 NodeDugEvent *nde = (NodeDugEvent*)e;
790 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
793 void registerReceiver(MtEventManager *mgr)
795 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
796 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
797 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
798 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
799 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
800 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
803 void step(float dtime)
805 m_player_step_timer -= dtime;
809 // Locally stored sounds don't need to be preloaded because of this
810 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
812 std::set<std::string> m_fetched;
815 void fetchSounds(const std::string &name,
816 std::set<std::string> &dst_paths,
817 std::set<std::string> &dst_datas)
819 if(m_fetched.count(name))
821 m_fetched.insert(name);
822 std::string base = porting::path_share + DIR_DELIM + "testsounds";
823 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
824 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
825 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
826 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
827 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
828 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
829 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
830 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
831 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
832 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
833 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
841 IrrlichtDevice *device,
844 std::string playername,
845 std::string password,
846 std::string address, // If "", local server is used
848 std::wstring &error_message,
849 std::string configpath,
850 ChatBackend &chat_backend,
851 const SubgameSpec &gamespec, // Used for local game,
852 bool simple_singleplayer_mode
855 video::IVideoDriver* driver = device->getVideoDriver();
856 scene::ISceneManager* smgr = device->getSceneManager();
858 // Calculate text height using the font
859 u32 text_height = font->getDimension(L"Random test string").Height;
861 v2u32 screensize(0,0);
862 v2u32 last_screensize(0,0);
863 screensize = driver->getScreenSize();
865 const s32 hotbar_itemcount = 8;
866 //const s32 hotbar_imagesize = 36;
867 //const s32 hotbar_imagesize = 64;
868 s32 hotbar_imagesize = 48;
871 Draw "Loading" screen
874 draw_load_screen(L"Loading...", driver, font);
876 // Create texture source
877 IWritableTextureSource *tsrc = createTextureSource(device);
879 // These will be filled by data received from the server
880 // Create item definition manager
881 IWritableItemDefManager *itemdef = createItemDefManager();
882 // Create node definition manager
883 IWritableNodeDefManager *nodedef = createNodeDefManager();
885 // Sound fetcher (useful when testing)
886 GameOnDemandSoundFetcher soundfetcher;
889 ISoundManager *sound = NULL;
890 bool sound_is_dummy = false;
892 if(g_settings->getBool("enable_sound")){
893 infostream<<"Attempting to use OpenAL audio"<<std::endl;
894 sound = createOpenALSoundManager(&soundfetcher);
896 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
898 infostream<<"Sound disabled."<<std::endl;
902 infostream<<"Using dummy audio."<<std::endl;
903 sound = &dummySoundManager;
904 sound_is_dummy = true;
908 EventManager eventmgr;
911 SoundMaker soundmaker(sound, nodedef);
912 soundmaker.registerReceiver(&eventmgr);
914 // Add chat log output for errors to be shown in chat
915 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
917 // Create UI for modifying quicktune values
918 QuicktuneShortcutter quicktune;
922 SharedPtr will delete it when it goes out of scope.
924 SharedPtr<Server> server;
926 draw_load_screen(L"Creating server...", driver, font);
927 infostream<<"Creating server"<<std::endl;
928 server = new Server(map_dir, configpath, gamespec,
929 simple_singleplayer_mode);
934 do{ // Client scope (breakable do-while(0))
940 draw_load_screen(L"Creating client...", driver, font);
941 infostream<<"Creating client"<<std::endl;
943 MapDrawControl draw_control;
945 Client client(device, playername.c_str(), password, draw_control,
946 tsrc, itemdef, nodedef, sound, &eventmgr);
948 // Client acts as our GameDef
949 IGameDef *gamedef = &client;
951 draw_load_screen(L"Resolving address...", driver, font);
952 Address connect_address(0,0,0,0, port);
955 //connect_address.Resolve("localhost");
956 connect_address.setAddress(127,0,0,1);
958 connect_address.Resolve(address.c_str());
960 catch(ResolveError &e)
962 error_message = L"Couldn't resolve address";
963 errorstream<<wide_to_narrow(error_message)<<std::endl;
964 // Break out of client scope
969 Attempt to connect to the server
972 infostream<<"Connecting to server at ";
973 connect_address.print(&infostream);
974 infostream<<std::endl;
975 client.connect(connect_address);
978 Wait for server to accept connection
980 bool could_connect = false;
981 bool connect_aborted = false;
983 float frametime = 0.033;
984 float time_counter = 0.0;
988 // Update client and server
989 client.step(frametime);
991 server->step(frametime);
994 if(client.connectedAndInitialized()){
995 could_connect = true;
999 if(client.accessDenied()){
1000 error_message = L"Access denied. Reason: "
1001 +client.accessDeniedReason();
1002 errorstream<<wide_to_narrow(error_message)<<std::endl;
1005 if(input->wasKeyDown(EscapeKey)){
1006 connect_aborted = true;
1007 infostream<<"Connect aborted [Escape]"<<std::endl;
1012 std::wostringstream ss;
1013 ss<<L"Connecting to server... (press Escape to cancel)\n";
1014 std::wstring animation = L"/-\\|";
1015 ss<<animation[(int)(time_counter/0.2)%4];
1016 draw_load_screen(ss.str(), driver, font);
1019 sleep_ms(1000*frametime);
1020 time_counter += frametime;
1023 catch(con::PeerNotFoundException &e)
1027 Handle failure to connect
1030 if(error_message == L"" && !connect_aborted){
1031 error_message = L"Connection failed";
1032 errorstream<<wide_to_narrow(error_message)<<std::endl;
1034 // Break out of client scope
1039 Wait until content has been received
1041 bool got_content = false;
1042 bool content_aborted = false;
1044 float frametime = 0.033;
1045 float time_counter = 0.0;
1047 while(device->run())
1049 // Update client and server
1050 client.step(frametime);
1052 server->step(frametime);
1055 if(client.texturesReceived() &&
1056 client.itemdefReceived() &&
1057 client.nodedefReceived()){
1062 if(!client.connectedAndInitialized()){
1063 error_message = L"Client disconnected";
1064 errorstream<<wide_to_narrow(error_message)<<std::endl;
1067 if(input->wasKeyDown(EscapeKey)){
1068 content_aborted = true;
1069 infostream<<"Connect aborted [Escape]"<<std::endl;
1074 std::wostringstream ss;
1075 ss<<L"Waiting content... (press Escape to cancel)\n";
1077 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1078 ss<<L" Item definitions\n";
1079 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1080 ss<<L" Node definitions\n";
1081 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1084 draw_load_screen(ss.str(), driver, font);
1087 sleep_ms(1000*frametime);
1088 time_counter += frametime;
1093 if(error_message == L"" && !content_aborted){
1094 error_message = L"Something failed";
1095 errorstream<<wide_to_narrow(error_message)<<std::endl;
1097 // Break out of client scope
1102 After all content has been received:
1103 Update cached textures, meshes and materials
1105 client.afterContentReceived();
1108 Create the camera node
1110 Camera camera(smgr, draw_control, gamedef);
1111 if (!camera.successfullyCreated(error_message))
1114 f32 camera_yaw = 0; // "right/left"
1115 f32 camera_pitch = 0; // "up/down"
1121 Clouds *clouds = NULL;
1122 if(g_settings->getBool("enable_clouds"))
1124 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1132 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1138 FarMesh *farmesh = NULL;
1139 if(g_settings->getBool("enable_farmesh"))
1141 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1145 A copy of the local inventory
1147 Inventory local_inventory(itemdef);
1150 Find out size of crack animation
1152 int crack_animation_length = 5;
1154 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1155 v2u32 size = t->getOriginalSize();
1156 crack_animation_length = size.Y / size.X;
1163 // First line of debug text
1164 gui::IGUIStaticText *guitext = guienv->addStaticText(
1166 core::rect<s32>(5, 5, 795, 5+text_height),
1168 // Second line of debug text
1169 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1171 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1173 // At the middle of the screen
1174 // Object infos are shown in this
1175 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1177 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1180 // Status text (displays info when showing and hiding GUI stuff, etc.)
1181 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1183 core::rect<s32>(0,0,0,0),
1185 guitext_status->setVisible(false);
1187 std::wstring statustext;
1188 float statustext_time = 0;
1191 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1193 core::rect<s32>(0,0,0,0),
1194 //false, false); // Disable word wrap as of now
1196 // Remove stale "recent" chat messages from previous connections
1197 chat_backend.clearRecentChat();
1198 // Chat backend and console
1199 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1201 // Profiler text (size is updated when text is updated)
1202 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1204 core::rect<s32>(0,0,0,0),
1206 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1207 guitext_profiler->setVisible(false);
1210 Some statistics are collected in these
1213 u32 beginscenetime = 0;
1215 u32 endscenetime = 0;
1217 float recent_turn_speed = 0.0;
1219 ProfilerGraph graph;
1220 // Initially clear the profiler
1221 Profiler::GraphValues dummyvalues;
1222 g_profiler->graphGet(dummyvalues);
1224 float nodig_delay_timer = 0.0;
1225 float dig_time = 0.0;
1227 PointedThing pointed_old;
1228 bool digging = false;
1229 bool ldown_for_dig = false;
1231 float damage_flash_timer = 0;
1232 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1234 const float object_hit_delay = 0.2;
1235 float object_hit_delay_timer = 0.0;
1236 float time_from_last_punch = 10;
1238 bool invert_mouse = g_settings->getBool("invert_mouse");
1240 bool respawn_menu_active = false;
1241 bool update_wielded_item_trigger = false;
1243 bool show_hud = true;
1244 bool show_chat = true;
1245 bool force_fog_off = false;
1246 bool disable_camera_update = false;
1247 bool show_debug = g_settings->getBool("show_debug");
1248 bool show_profiler_graph = false;
1249 u32 show_profiler = 0;
1250 u32 show_profiler_max = 3; // Number of pages
1252 float time_of_day = 0;
1253 float time_of_day_smooth = 0;
1259 bool first_loop_after_window_activation = true;
1261 // TODO: Convert the static interval timers to these
1262 // Interval limiter for profiler
1263 IntervalLimiter m_profiler_interval;
1265 // Time is in milliseconds
1266 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1267 // NOTE: So we have to use getTime() and call run()s between them
1268 u32 lasttime = device->getTimer()->getTime();
1272 if(device->run() == false || kill == true)
1275 // Time of frame without fps limit
1279 // not using getRealTime is necessary for wine
1280 u32 time = device->getTimer()->getTime();
1282 busytime_u32 = time - lasttime;
1285 busytime = busytime_u32 / 1000.0;
1288 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1290 // Necessary for device->getTimer()->getTime()
1298 float fps_max = g_settings->getFloat("fps_max");
1299 u32 frametime_min = 1000./fps_max;
1301 if(busytime_u32 < frametime_min)
1303 u32 sleeptime = frametime_min - busytime_u32;
1304 device->sleep(sleeptime);
1305 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1309 // Necessary for device->getTimer()->getTime()
1313 Time difference calculation
1315 f32 dtime; // in seconds
1317 u32 time = device->getTimer()->getTime();
1319 dtime = (time - lasttime) / 1000.0;
1324 g_profiler->graphAdd("mainloop_dtime", dtime);
1328 if(nodig_delay_timer >= 0)
1329 nodig_delay_timer -= dtime;
1330 if(object_hit_delay_timer >= 0)
1331 object_hit_delay_timer -= dtime;
1332 time_from_last_punch += dtime;
1334 g_profiler->add("Elapsed time", dtime);
1335 g_profiler->avg("FPS", 1./dtime);
1338 Time average and jitter calculation
1341 static f32 dtime_avg1 = 0.0;
1342 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1343 f32 dtime_jitter1 = dtime - dtime_avg1;
1345 static f32 dtime_jitter1_max_sample = 0.0;
1346 static f32 dtime_jitter1_max_fraction = 0.0;
1348 static f32 jitter1_max = 0.0;
1349 static f32 counter = 0.0;
1350 if(dtime_jitter1 > jitter1_max)
1351 jitter1_max = dtime_jitter1;
1356 dtime_jitter1_max_sample = jitter1_max;
1357 dtime_jitter1_max_fraction
1358 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1364 Busytime average and jitter calculation
1367 static f32 busytime_avg1 = 0.0;
1368 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1369 f32 busytime_jitter1 = busytime - busytime_avg1;
1371 static f32 busytime_jitter1_max_sample = 0.0;
1372 static f32 busytime_jitter1_min_sample = 0.0;
1374 static f32 jitter1_max = 0.0;
1375 static f32 jitter1_min = 0.0;
1376 static f32 counter = 0.0;
1377 if(busytime_jitter1 > jitter1_max)
1378 jitter1_max = busytime_jitter1;
1379 if(busytime_jitter1 < jitter1_min)
1380 jitter1_min = busytime_jitter1;
1384 busytime_jitter1_max_sample = jitter1_max;
1385 busytime_jitter1_min_sample = jitter1_min;
1392 Handle miscellaneous stuff
1395 if(client.accessDenied())
1397 error_message = L"Access denied. Reason: "
1398 +client.accessDeniedReason();
1399 errorstream<<wide_to_narrow(error_message)<<std::endl;
1403 if(g_gamecallback->disconnect_requested)
1405 g_gamecallback->disconnect_requested = false;
1409 if(g_gamecallback->changepassword_requested)
1411 (new GUIPasswordChange(guienv, guiroot, -1,
1412 &g_menumgr, &client))->drop();
1413 g_gamecallback->changepassword_requested = false;
1417 Process TextureSource's queue
1419 tsrc->processQueue();
1424 last_screensize = screensize;
1425 screensize = driver->getScreenSize();
1426 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1427 //bool screensize_changed = screensize != last_screensize;
1430 if(screensize.Y <= 800)
1431 hotbar_imagesize = 32;
1432 else if(screensize.Y <= 1280)
1433 hotbar_imagesize = 48;
1435 hotbar_imagesize = 64;
1437 // Hilight boxes collected during the loop and displayed
1438 std::vector<aabb3f> hilightboxes;
1441 std::wstring infotext;
1444 Debug info for client
1447 static float counter = 0.0;
1452 client.printDebugInfo(infostream);
1459 float profiler_print_interval =
1460 g_settings->getFloat("profiler_print_interval");
1461 bool print_to_log = true;
1462 if(profiler_print_interval == 0){
1463 print_to_log = false;
1464 profiler_print_interval = 5;
1466 if(m_profiler_interval.step(dtime, profiler_print_interval))
1469 infostream<<"Profiler:"<<std::endl;
1470 g_profiler->print(infostream);
1473 update_profiler_gui(guitext_profiler, font, text_height,
1474 show_profiler, show_profiler_max);
1476 g_profiler->clear();
1480 Direct handling of user input
1483 // Reset input if window not active or some menu is active
1484 if(device->isWindowActive() == false
1485 || noMenuActive() == false
1486 || guienv->hasFocus(gui_chat_console))
1491 // Input handler step() (used by the random input generator)
1495 Launch menus and trigger stuff according to keys
1497 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1499 // drop selected item
1500 IDropAction *a = new IDropAction();
1502 a->from_inv.setCurrentPlayer();
1503 a->from_list = "main";
1504 a->from_i = client.getPlayerItem();
1505 client.inventoryAction(a);
1507 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1509 infostream<<"the_game: "
1510 <<"Launching inventory"<<std::endl;
1512 GUIFormSpecMenu *menu =
1513 new GUIFormSpecMenu(guienv, guiroot, -1,
1517 InventoryLocation inventoryloc;
1518 inventoryloc.setCurrentPlayer();
1520 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1522 menu->setFormSpec(src->getForm(), inventoryloc);
1523 menu->setFormSource(src);
1524 menu->setTextDest(new TextDestPlayerInventory(&client));
1527 else if(input->wasKeyDown(EscapeKey))
1529 infostream<<"the_game: "
1530 <<"Launching pause menu"<<std::endl;
1531 // It will delete itself by itself
1532 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1533 &g_menumgr, simple_singleplayer_mode))->drop();
1535 // Move mouse cursor on top of the disconnect button
1536 if(simple_singleplayer_mode)
1537 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1539 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1541 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1543 TextDest *dest = new TextDestChat(&client);
1545 (new GUITextInputMenu(guienv, guiroot, -1,
1549 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1551 TextDest *dest = new TextDestChat(&client);
1553 (new GUITextInputMenu(guienv, guiroot, -1,
1557 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1559 if (!gui_chat_console->isOpenInhibited())
1561 // Open up to over half of the screen
1562 gui_chat_console->openConsole(0.6);
1563 guienv->setFocus(gui_chat_console);
1566 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1568 if(g_settings->getBool("free_move"))
1570 g_settings->set("free_move","false");
1571 statustext = L"free_move disabled";
1572 statustext_time = 0;
1576 g_settings->set("free_move","true");
1577 statustext = L"free_move enabled";
1578 statustext_time = 0;
1579 if(!client.checkPrivilege("fly"))
1580 statustext += L" (note: no 'fly' privilege)";
1583 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1585 if(g_settings->getBool("fast_move"))
1587 g_settings->set("fast_move","false");
1588 statustext = L"fast_move disabled";
1589 statustext_time = 0;
1593 g_settings->set("fast_move","true");
1594 statustext = L"fast_move enabled";
1595 statustext_time = 0;
1596 if(!client.checkPrivilege("fast"))
1597 statustext += L" (note: no 'fast' privilege)";
1600 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1602 irr::video::IImage* const image = driver->createScreenShot();
1604 irr::c8 filename[256];
1605 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1606 g_settings->get("screenshot_path").c_str(),
1607 device->getTimer()->getRealTime());
1608 if (driver->writeImageToFile(image, filename)) {
1609 std::wstringstream sstr;
1610 sstr<<"Saved screenshot to '"<<filename<<"'";
1611 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1612 statustext = sstr.str();
1613 statustext_time = 0;
1615 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1620 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1622 show_hud = !show_hud;
1624 statustext = L"HUD shown";
1626 statustext = L"HUD hidden";
1627 statustext_time = 0;
1629 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1631 show_chat = !show_chat;
1633 statustext = L"Chat shown";
1635 statustext = L"Chat hidden";
1636 statustext_time = 0;
1638 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1640 force_fog_off = !force_fog_off;
1642 statustext = L"Fog disabled";
1644 statustext = L"Fog enabled";
1645 statustext_time = 0;
1647 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1649 disable_camera_update = !disable_camera_update;
1650 if(disable_camera_update)
1651 statustext = L"Camera update disabled";
1653 statustext = L"Camera update enabled";
1654 statustext_time = 0;
1656 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1658 // Initial / 3x toggle: Chat only
1659 // 1x toggle: Debug text with chat
1660 // 2x toggle: Debug text with profiler graph
1664 show_profiler_graph = false;
1665 statustext = L"Debug info shown";
1666 statustext_time = 0;
1668 else if(show_profiler_graph)
1671 show_profiler_graph = false;
1672 statustext = L"Debug info and profiler graph hidden";
1673 statustext_time = 0;
1677 show_profiler_graph = true;
1678 statustext = L"Profiler graph shown";
1679 statustext_time = 0;
1682 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1684 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1686 // FIXME: This updates the profiler with incomplete values
1687 update_profiler_gui(guitext_profiler, font, text_height,
1688 show_profiler, show_profiler_max);
1690 if(show_profiler != 0)
1692 std::wstringstream sstr;
1693 sstr<<"Profiler shown (page "<<show_profiler
1694 <<" of "<<show_profiler_max<<")";
1695 statustext = sstr.str();
1696 statustext_time = 0;
1700 statustext = L"Profiler hidden";
1701 statustext_time = 0;
1704 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1706 s16 range = g_settings->getS16("viewing_range_nodes_min");
1707 s16 range_new = range + 10;
1708 g_settings->set("viewing_range_nodes_min", itos(range_new));
1709 statustext = narrow_to_wide(
1710 "Minimum viewing range changed to "
1712 statustext_time = 0;
1714 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1716 s16 range = g_settings->getS16("viewing_range_nodes_min");
1717 s16 range_new = range - 10;
1720 g_settings->set("viewing_range_nodes_min",
1722 statustext = narrow_to_wide(
1723 "Minimum viewing range changed to "
1725 statustext_time = 0;
1728 // Handle QuicktuneShortcutter
1729 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1731 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1733 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1735 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1738 std::string msg = quicktune.getMessage();
1740 statustext = narrow_to_wide(msg);
1741 statustext_time = 0;
1745 // Item selection with mouse wheel
1746 u16 new_playeritem = client.getPlayerItem();
1748 s32 wheel = input->getMouseWheel();
1749 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1750 hotbar_itemcount-1);
1754 if(new_playeritem < max_item)
1761 if(new_playeritem > 0)
1764 new_playeritem = max_item;
1769 for(u16 i=0; i<10; i++)
1771 const KeyPress *kp = NumberKey + (i + 1) % 10;
1772 if(input->wasKeyDown(*kp))
1774 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1778 infostream<<"Selected item: "
1779 <<new_playeritem<<std::endl;
1784 // Viewing range selection
1785 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1787 draw_control.range_all = !draw_control.range_all;
1788 if(draw_control.range_all)
1790 infostream<<"Enabled full viewing range"<<std::endl;
1791 statustext = L"Enabled full viewing range";
1792 statustext_time = 0;
1796 infostream<<"Disabled full viewing range"<<std::endl;
1797 statustext = L"Disabled full viewing range";
1798 statustext_time = 0;
1802 // Print debug stacks
1803 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1805 dstream<<"-----------------------------------------"
1807 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1808 dstream<<"-----------------------------------------"
1810 debug_stacks_print();
1814 Mouse and camera control
1815 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1818 float turn_amount = 0;
1819 if((device->isWindowActive() && noMenuActive()) || random_input)
1823 // Mac OSX gets upset if this is set every frame
1824 if(device->getCursorControl()->isVisible())
1825 device->getCursorControl()->setVisible(false);
1828 if(first_loop_after_window_activation){
1829 //infostream<<"window active, first loop"<<std::endl;
1830 first_loop_after_window_activation = false;
1833 s32 dx = input->getMousePos().X - displaycenter.X;
1834 s32 dy = input->getMousePos().Y - displaycenter.Y;
1837 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1839 /*const float keyspeed = 500;
1840 if(input->isKeyDown(irr::KEY_UP))
1841 dy -= dtime * keyspeed;
1842 if(input->isKeyDown(irr::KEY_DOWN))
1843 dy += dtime * keyspeed;
1844 if(input->isKeyDown(irr::KEY_LEFT))
1845 dx -= dtime * keyspeed;
1846 if(input->isKeyDown(irr::KEY_RIGHT))
1847 dx += dtime * keyspeed;*/
1851 camera_pitch += dy*d;
1852 if(camera_pitch < -89.5) camera_pitch = -89.5;
1853 if(camera_pitch > 89.5) camera_pitch = 89.5;
1855 turn_amount = v2f(dx, dy).getLength() * d;
1857 input->setMousePos(displaycenter.X, displaycenter.Y);
1860 // Mac OSX gets upset if this is set every frame
1861 if(device->getCursorControl()->isVisible() == false)
1862 device->getCursorControl()->setVisible(true);
1864 //infostream<<"window inactive"<<std::endl;
1865 first_loop_after_window_activation = true;
1867 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1868 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1871 Player speed control
1883 PlayerControl control(
1884 input->isKeyDown(getKeySetting("keymap_forward")),
1885 input->isKeyDown(getKeySetting("keymap_backward")),
1886 input->isKeyDown(getKeySetting("keymap_left")),
1887 input->isKeyDown(getKeySetting("keymap_right")),
1888 input->isKeyDown(getKeySetting("keymap_jump")),
1889 input->isKeyDown(getKeySetting("keymap_special1")),
1890 input->isKeyDown(getKeySetting("keymap_sneak")),
1894 client.setPlayerControl(control);
1903 //TimeTaker timer("server->step(dtime)");
1904 server->step(dtime);
1912 //TimeTaker timer("client.step(dtime)");
1914 //client.step(dtime_avg1);
1918 // Read client events
1921 ClientEvent event = client.getClientEvent();
1922 if(event.type == CE_NONE)
1926 else if(event.type == CE_PLAYER_DAMAGE)
1928 //u16 damage = event.player_damage.amount;
1929 //infostream<<"Player damage: "<<damage<<std::endl;
1930 damage_flash_timer = 0.05;
1931 if(event.player_damage.amount >= 2){
1932 damage_flash_timer += 0.05 * event.player_damage.amount;
1935 else if(event.type == CE_PLAYER_FORCE_MOVE)
1937 camera_yaw = event.player_force_move.yaw;
1938 camera_pitch = event.player_force_move.pitch;
1940 else if(event.type == CE_DEATHSCREEN)
1942 if(respawn_menu_active)
1945 /*bool set_camera_point_target =
1946 event.deathscreen.set_camera_point_target;
1947 v3f camera_point_target;
1948 camera_point_target.X = event.deathscreen.camera_point_target_x;
1949 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1950 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1951 MainRespawnInitiator *respawner =
1952 new MainRespawnInitiator(
1953 &respawn_menu_active, &client);
1954 GUIDeathScreen *menu =
1955 new GUIDeathScreen(guienv, guiroot, -1,
1956 &g_menumgr, respawner);
1959 chat_backend.addMessage(L"", L"You died.");
1961 /* Handle visualization */
1963 damage_flash_timer = 0;
1965 /*LocalPlayer* player = client.getLocalPlayer();
1966 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1967 camera.update(player, busytime, screensize);*/
1969 else if(event.type == CE_TEXTURES_UPDATED)
1971 update_wielded_item_trigger = true;
1976 //TimeTaker //timer2("//timer2");
1979 For interaction purposes, get info about the held item
1981 - Is it a usable item?
1982 - Can it point to liquids?
1984 ItemStack playeritem;
1985 bool playeritem_usable = false;
1986 bool playeritem_liquids_pointable = false;
1988 InventoryList *mlist = local_inventory.getList("main");
1991 playeritem = mlist->getItem(client.getPlayerItem());
1992 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1993 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1996 ToolCapabilities playeritem_toolcap =
1997 playeritem.getToolCapabilities(itemdef);
2003 LocalPlayer* player = client.getEnv().getLocalPlayer();
2004 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2005 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2006 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2007 camera.update(player, busytime, screensize, tool_reload_ratio);
2010 v3f player_position = player->getPosition();
2011 v3f camera_position = camera.getPosition();
2012 v3f camera_direction = camera.getDirection();
2013 f32 camera_fov = camera.getFovMax();
2015 if(!disable_camera_update){
2016 client.getEnv().getClientMap().updateCamera(camera_position,
2017 camera_direction, camera_fov);
2020 // Update sound listener
2021 sound->updateListener(camera.getCameraNode()->getPosition(),
2022 v3f(0,0,0), // velocity
2023 camera.getDirection(),
2024 camera.getCameraNode()->getUpVector());
2025 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2031 soundmaker.step(dtime);
2033 ClientMap &map = client.getEnv().getClientMap();
2034 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2035 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2039 Calculate what block is the crosshair pointing to
2042 //u32 t1 = device->getTimer()->getRealTime();
2044 f32 d = 4; // max. distance
2045 core::line3d<f32> shootline(camera_position,
2046 camera_position + camera_direction * BS * (d+1));
2048 ClientActiveObject *selected_object = NULL;
2050 PointedThing pointed = getPointedThing(
2052 &client, player_position, camera_direction,
2053 camera_position, shootline, d,
2054 playeritem_liquids_pointable, !ldown_for_dig,
2059 if(pointed != pointed_old)
2061 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2062 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2067 - releasing left mouse button
2068 - pointing away from node
2072 if(input->getLeftReleased())
2074 infostream<<"Left button released"
2075 <<" (stopped digging)"<<std::endl;
2078 else if(pointed != pointed_old)
2080 if (pointed.type == POINTEDTHING_NODE
2081 && pointed_old.type == POINTEDTHING_NODE
2082 && pointed.node_undersurface == pointed_old.node_undersurface)
2084 // Still pointing to the same node,
2085 // but a different face. Don't reset.
2089 infostream<<"Pointing away from node"
2090 <<" (stopped digging)"<<std::endl;
2096 client.interact(1, pointed_old);
2097 client.setCrack(-1, v3s16(0,0,0));
2101 if(!digging && ldown_for_dig && !input->getLeftState())
2103 ldown_for_dig = false;
2106 bool left_punch = false;
2107 soundmaker.m_player_leftpunch_sound.name = "";
2109 if(playeritem_usable && input->getLeftState())
2111 if(input->getLeftClicked())
2112 client.interact(4, pointed);
2114 else if(pointed.type == POINTEDTHING_NODE)
2116 v3s16 nodepos = pointed.node_undersurface;
2117 v3s16 neighbourpos = pointed.node_abovesurface;
2120 Check information text of node
2123 ClientMap &map = client.getEnv().getClientMap();
2124 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2126 infotext = narrow_to_wide(meta->getString("infotext"));
2128 MapNode n = map.getNode(nodepos);
2129 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2130 infotext = L"Unknown node: ";
2131 infotext += narrow_to_wide(nodedef->get(n).name);
2135 // We can't actually know, but assume the sound of right-clicking
2136 // to be the sound of placing a node
2137 soundmaker.m_player_rightpunch_sound.gain = 0.5;
2138 soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2144 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2148 infostream<<"Started digging"<<std::endl;
2149 client.interact(0, pointed);
2151 ldown_for_dig = true;
2153 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2155 // NOTE: Similar piece of code exists on the server side for
2157 // Get digging parameters
2158 DigParams params = getDigParams(nodedef->get(n).groups,
2159 &playeritem_toolcap);
2160 // If can't dig, try hand
2161 if(!params.diggable){
2162 const ItemDefinition &hand = itemdef->get("");
2163 const ToolCapabilities *tp = hand.tool_capabilities;
2165 params = getDigParams(nodedef->get(n).groups, tp);
2168 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2169 if(sound_dig.exists()){
2170 if(sound_dig.name == "__group"){
2171 if(params.main_group != ""){
2172 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2173 soundmaker.m_player_leftpunch_sound.name =
2174 std::string("default_dig_") +
2178 soundmaker.m_player_leftpunch_sound = sound_dig;
2182 float dig_time_complete = 0.0;
2184 if(params.diggable == false)
2186 // I guess nobody will wait for this long
2187 dig_time_complete = 10000000.0;
2191 dig_time_complete = params.time;
2194 if(dig_time_complete >= 0.001)
2196 dig_index = (u16)((float)crack_animation_length
2197 * dig_time/dig_time_complete);
2199 // This is for torches
2202 dig_index = crack_animation_length;
2205 // Don't show cracks if not diggable
2206 if(dig_time_complete >= 100000.0)
2209 else if(dig_index < crack_animation_length)
2211 //TimeTaker timer("client.setTempMod");
2212 //infostream<<"dig_index="<<dig_index<<std::endl;
2213 client.setCrack(dig_index, nodepos);
2217 infostream<<"Digging completed"<<std::endl;
2218 client.interact(2, pointed);
2219 client.setCrack(-1, v3s16(0,0,0));
2220 MapNode wasnode = map.getNode(nodepos);
2221 client.removeNode(nodepos);
2226 nodig_delay_timer = dig_time_complete
2227 / (float)crack_animation_length;
2229 // We don't want a corresponding delay to
2230 // very time consuming nodes
2231 if(nodig_delay_timer > 0.3)
2232 nodig_delay_timer = 0.3;
2233 // We want a slight delay to very little
2234 // time consuming nodes
2235 float mindelay = 0.15;
2236 if(nodig_delay_timer < mindelay)
2237 nodig_delay_timer = mindelay;
2239 // Send event to trigger sound
2240 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2241 gamedef->event()->put(e);
2246 camera.setDigging(0); // left click animation
2249 if(input->getRightClicked())
2251 infostream<<"Ground right-clicked"<<std::endl;
2253 // Sign special case, at least until formspec is properly implemented.
2255 if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
2257 infostream<<"Launching metadata text input"<<std::endl;
2259 // Get a new text for it
2261 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2263 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2265 (new GUITextInputMenu(guienv, guiroot, -1,
2269 // If metadata provides an inventory view, activate it
2270 else if(meta && meta->getString("formspec") != "" && !random_input)
2272 infostream<<"Launching custom inventory view"<<std::endl;
2274 InventoryLocation inventoryloc;
2275 inventoryloc.setNodeMeta(nodepos);
2279 GUIFormSpecMenu *menu =
2280 new GUIFormSpecMenu(guienv, guiroot, -1,
2283 menu->setFormSpec(meta->getString("formspec"),
2285 menu->setFormSource(new NodeMetadataFormSource(
2286 &client.getEnv().getClientMap(), nodepos));
2287 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2290 // Otherwise report right click to server
2294 client.interact(3, pointed);
2295 camera.setDigging(1); // right click animation
2297 // If the wielded item has node placement prediction,
2299 const ItemDefinition &def =
2300 playeritem.getDefinition(itemdef);
2301 if(def.node_placement_prediction != "")
2303 verbosestream<<"Node placement prediction for "
2304 <<playeritem.name<<" is "
2305 <<def.node_placement_prediction<<std::endl;
2306 v3s16 p = neighbourpos;
2307 // Place inside node itself if buildable_to
2309 MapNode n_under = map.getNode(nodepos);
2310 if(nodedef->get(n_under).buildable_to)
2312 }catch(InvalidPositionException &e){}
2313 // Find id of predicted node
2316 nodedef->getId(def.node_placement_prediction, id);
2318 errorstream<<"Node placement prediction failed for "
2319 <<playeritem.name<<" (places "
2320 <<def.node_placement_prediction
2321 <<") - Name not known"<<std::endl;
2326 // This triggers the required mesh update too
2327 client.addNode(p, n);
2328 }catch(InvalidPositionException &e){
2329 errorstream<<"Node placement prediction failed for "
2330 <<playeritem.name<<" (places "
2331 <<def.node_placement_prediction
2332 <<") - Position not loaded"<<std::endl;
2338 else if(pointed.type == POINTEDTHING_OBJECT)
2340 infotext = narrow_to_wide(selected_object->infoText());
2342 if(infotext == L"" && show_debug){
2343 infotext = narrow_to_wide(selected_object->debugInfoText());
2346 //if(input->getLeftClicked())
2347 if(input->getLeftState())
2349 bool do_punch = false;
2350 bool do_punch_damage = false;
2351 if(object_hit_delay_timer <= 0.0){
2353 do_punch_damage = true;
2354 object_hit_delay_timer = object_hit_delay;
2356 if(input->getLeftClicked()){
2360 infostream<<"Left-clicked object"<<std::endl;
2363 if(do_punch_damage){
2364 // Report direct punch
2365 v3f objpos = selected_object->getPosition();
2366 v3f dir = (objpos - player_position).normalize();
2368 bool disable_send = selected_object->directReportPunch(
2369 dir, &playeritem, time_from_last_punch);
2370 time_from_last_punch = 0;
2372 client.interact(0, pointed);
2375 else if(input->getRightClicked())
2377 infostream<<"Right-clicked object"<<std::endl;
2378 client.interact(3, pointed); // place
2381 else if(input->getLeftState())
2383 // When button is held down in air, show continuous animation
2387 pointed_old = pointed;
2389 if(left_punch || input->getLeftClicked())
2391 camera.setDigging(0); // left click animation
2394 input->resetLeftClicked();
2395 input->resetRightClicked();
2397 input->resetLeftReleased();
2398 input->resetRightReleased();
2401 Calculate stuff for drawing
2411 fog_range = BS*farmesh_range;
2415 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2417 if(draw_control.range_all)
2418 fog_range = 100000*BS;
2422 Calculate general brightness
2424 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2425 float time_brightness = (float)decode_light(
2426 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2427 float direct_brightness = 0;
2428 bool sunlight_seen = false;
2429 if(g_settings->getBool("free_move")){
2430 direct_brightness = time_brightness;
2431 sunlight_seen = true;
2433 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2434 float old_brightness = sky->getBrightness();
2435 direct_brightness = (float)client.getEnv().getClientMap()
2436 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2437 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2441 time_of_day = client.getEnv().getTimeOfDayF();
2443 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2444 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2445 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2446 time_of_day_smooth = time_of_day;
2448 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2449 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2450 + (time_of_day+1.0) * todsm;
2452 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2453 + time_of_day * todsm;
2455 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2458 float brightness = sky->getBrightness();
2459 video::SColor bgcolor = sky->getBgColor();
2460 video::SColor skycolor = sky->getSkyColor();
2466 if(sky->getCloudsVisible()){
2467 clouds->setVisible(true);
2468 clouds->step(dtime);
2469 clouds->update(v2f(player_position.X, player_position.Z),
2470 sky->getCloudColor());
2472 clouds->setVisible(false);
2481 farmesh_range = draw_control.wanted_range * 10;
2482 if(draw_control.range_all && farmesh_range < 500)
2483 farmesh_range = 500;
2484 if(farmesh_range > 1000)
2485 farmesh_range = 1000;
2487 farmesh->step(dtime);
2488 farmesh->update(v2f(player_position.X, player_position.Z),
2489 brightness, farmesh_range);
2496 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2500 video::EFT_FOG_LINEAR,
2512 video::EFT_FOG_LINEAR,
2522 Update gui stuff (0ms)
2525 //TimeTaker guiupdatetimer("Gui updating");
2527 const char program_name_and_version[] =
2528 "Minetest-c55 " VERSION_STRING;
2532 static float drawtime_avg = 0;
2533 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2534 /*static float beginscenetime_avg = 0;
2535 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2536 static float scenetime_avg = 0;
2537 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2538 static float endscenetime_avg = 0;
2539 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2542 snprintf(temptext, 300, "%s ("
2545 " drawtime=%.0f, dtime_jitter = % .1f %%"
2546 ", v_range = %.1f, RTT = %.3f",
2547 program_name_and_version,
2548 draw_control.range_all,
2550 dtime_jitter1_max_fraction * 100.0,
2551 draw_control.wanted_range,
2555 guitext->setText(narrow_to_wide(temptext).c_str());
2556 guitext->setVisible(true);
2558 else if(show_hud || show_chat)
2560 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2561 guitext->setVisible(true);
2565 guitext->setVisible(false);
2571 snprintf(temptext, 300,
2572 "(% .1f, % .1f, % .1f)"
2573 " (yaw = %.1f) (seed = %lli)",
2574 player_position.X/BS,
2575 player_position.Y/BS,
2576 player_position.Z/BS,
2577 wrapDegrees_0_360(camera_yaw),
2578 client.getMapSeed());
2580 guitext2->setText(narrow_to_wide(temptext).c_str());
2581 guitext2->setVisible(true);
2585 guitext2->setVisible(false);
2589 guitext_info->setText(infotext.c_str());
2590 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2594 float statustext_time_max = 1.5;
2595 if(!statustext.empty())
2597 statustext_time += dtime;
2598 if(statustext_time >= statustext_time_max)
2601 statustext_time = 0;
2604 guitext_status->setText(statustext.c_str());
2605 guitext_status->setVisible(!statustext.empty());
2607 if(!statustext.empty())
2609 s32 status_y = screensize.Y - 130;
2610 core::rect<s32> rect(
2612 status_y - guitext_status->getTextHeight(),
2616 guitext_status->setRelativePosition(rect);
2619 video::SColor initial_color(255,0,0,0);
2620 if(guienv->getSkin())
2621 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2622 video::SColor final_color = initial_color;
2623 final_color.setAlpha(0);
2624 video::SColor fade_color =
2625 initial_color.getInterpolated_quadratic(
2628 pow(statustext_time / (float)statustext_time_max, 2.0f));
2629 guitext_status->setOverrideColor(fade_color);
2630 guitext_status->enableOverrideColor(true);
2635 Get chat messages from client
2638 // Get new messages from error log buffer
2639 while(!chat_log_error_buf.empty())
2641 chat_backend.addMessage(L"", narrow_to_wide(
2642 chat_log_error_buf.get()));
2644 // Get new messages from client
2645 std::wstring message;
2646 while(client.getChatMessage(message))
2648 chat_backend.addUnparsedMessage(message);
2650 // Remove old messages
2651 chat_backend.step(dtime);
2653 // Display all messages in a static text element
2654 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2655 std::wstring recent_chat = chat_backend.getRecentChat();
2656 guitext_chat->setText(recent_chat.c_str());
2658 // Update gui element size and position
2659 s32 chat_y = 5+(text_height+5);
2661 chat_y += (text_height+5);
2662 core::rect<s32> rect(
2666 chat_y + guitext_chat->getTextHeight()
2668 guitext_chat->setRelativePosition(rect);
2670 // Don't show chat if disabled or empty or profiler is enabled
2671 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2679 if(client.getPlayerItem() != new_playeritem)
2681 client.selectPlayerItem(new_playeritem);
2683 if(client.getLocalInventoryUpdated())
2685 //infostream<<"Updating local inventory"<<std::endl;
2686 client.getLocalInventory(local_inventory);
2688 update_wielded_item_trigger = true;
2690 if(update_wielded_item_trigger)
2692 update_wielded_item_trigger = false;
2693 // Update wielded tool
2694 InventoryList *mlist = local_inventory.getList("main");
2697 item = mlist->getItem(client.getPlayerItem());
2705 TimeTaker tt_draw("mainloop: draw");
2709 TimeTaker timer("beginScene");
2710 //driver->beginScene(false, true, bgcolor);
2711 //driver->beginScene(true, true, bgcolor);
2712 driver->beginScene(true, true, skycolor);
2713 beginscenetime = timer.stop(true);
2718 //infostream<<"smgr->drawAll()"<<std::endl;
2720 TimeTaker timer("smgr");
2722 scenetime = timer.stop(true);
2726 //TimeTaker timer9("auxiliary drawings");
2730 //TimeTaker //timer10("//timer10");
2736 driver->setMaterial(m);
2738 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2742 for(std::vector<aabb3f>::const_iterator
2743 i = hilightboxes.begin();
2744 i != hilightboxes.end(); i++)
2746 /*infostream<<"hilightbox min="
2747 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2749 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2751 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2760 // Warning: This clears the Z buffer.
2761 camera.drawWieldedTool();
2768 client.getEnv().getClientMap().renderPostFx();
2774 if(show_profiler_graph)
2776 graph.draw(10, screensize.Y - 10, driver, font);
2784 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2785 displaycenter + core::vector2d<s32>(10,0),
2786 video::SColor(255,255,255,255));
2787 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2788 displaycenter + core::vector2d<s32>(0,10),
2789 video::SColor(255,255,255,255));
2795 //TimeTaker //timer11("//timer11");
2808 draw_hotbar(driver, font, gamedef,
2809 v2s32(displaycenter.X, screensize.Y),
2810 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2811 client.getHP(), client.getPlayerItem());
2817 if(damage_flash_timer > 0.0)
2819 damage_flash_timer -= dtime;
2821 video::SColor color(128,255,0,0);
2822 driver->draw2DRectangle(color,
2823 core::rect<s32>(0,0,screensize.X,screensize.Y),
2831 TimeTaker timer("endScene");
2833 endscenetime = timer.stop(true);
2836 drawtime = tt_draw.stop(true);
2837 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2843 static s16 lastFPS = 0;
2844 //u16 fps = driver->getFPS();
2845 u16 fps = (1.0/dtime_avg1);
2849 core::stringw str = L"Minetest [";
2850 str += driver->getName();
2854 device->setWindowCaption(str.c_str());
2859 Log times and stuff for visualization
2861 Profiler::GraphValues values;
2862 g_profiler->graphGet(values);
2871 if(gui_chat_console)
2872 gui_chat_console->drop();
2875 Draw a "shutting down" screen, which will be shown while the map
2876 generator and other stuff quits
2879 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2880 draw_load_screen(L"Shutting down stuff...", driver, font);
2881 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2884 gui_shuttingdowntext->remove();*/
2887 chat_backend.addMessage(L"", L"# Disconnected.");
2888 chat_backend.addMessage(L"", L"");
2890 // Client scope (client is destructed before destructing *def and tsrc)
2893 catch(SerializationError &e)
2895 error_message = L"A serialization error occurred:\n"
2896 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
2897 L" running a different version of Minetest.";
2898 errorstream<<wide_to_narrow(error_message)<<std::endl;