]> git.lizzy.rs Git - minetest.git/blob - src/main.cpp
Merge remote-tracking branch 'jn/random-fixes'
[minetest.git] / src / main.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
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 General Public License for more details.
14
15 You should have received a copy of the GNU 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.
18 */
19
20 /*
21 =============================== NOTES ==============================
22 NOTE: Things starting with TODO are sometimes only suggestions.
23
24 NOTE: iostream.imbue(std::locale("C")) is very slow
25 NOTE: Global locale is now set at initialization
26
27 NOTE: If VBO (EHM_STATIC) is used, remember to explicitly free the
28       hardware buffer (it is not freed automatically)
29
30 NOTE: A random to-do list saved here as documentation:
31 A list of "active blocks" in which stuff happens. (+=done)
32         + Add a never-resetted game timer to the server
33         + Add a timestamp value to blocks
34         + The simple rule: All blocks near some player are "active"
35         - Do stuff in real time in active blocks
36                 + Handle objects
37                 - Grow grass, delete leaves without a tree
38                 - Spawn some mobs based on some rules
39                 - Transform cobble to mossy cobble near water
40                 - Run a custom script
41                 - ...And all kinds of other dynamic stuff
42         + Keep track of when a block becomes active and becomes inactive
43         + When a block goes inactive:
44                 + Store objects statically to block
45                 + Store timer value as the timestamp
46         + When a block goes active:
47                 + Create active objects out of static objects
48                 - Simulate the results of what would have happened if it would have
49                   been active for all the time
50                         - Grow a lot of grass and so on
51         + Initially it is fine to send information about every active object
52           to every player. Eventually it should be modified to only send info
53           about the nearest ones.
54                 + This was left to be done by the old system and it sends only the
55                   nearest ones.
56
57 NOTE: Seeds in 1260:6c77e7dbfd29:
58 5721858502589302589:
59         Spawns you on a small sand island with a surface dungeon
60 2983455799928051958:
61         Enormous jungle + a surface dungeon at ~(250,0,0)
62
63 Old, wild and random suggestions that probably won't be done:
64 -------------------------------------------------------------
65
66 SUGG: If player is on ground, mainly fetch ground-level blocks
67
68 SUGG: Expose Connection's seqnums and ACKs to server and client.
69       - This enables saving many packets and making a faster connection
70           - This also enables server to check if client has received the
71             most recent block sent, for example.
72 SUGG: Add a sane bandwidth throttling system to Connection
73
74 SUGG: More fine-grained control of client's dumping of blocks from
75       memory
76           - ...What does this mean in the first place?
77
78 SUGG: A map editing mode (similar to dedicated server mode)
79
80 SUGG: Transfer more blocks in a single packet
81 SUGG: A blockdata combiner class, to which blocks are added and at
82       destruction it sends all the stuff in as few packets as possible.
83 SUGG: Make a PACKET_COMBINED which contains many subpackets. Utilize
84       it by sending more stuff in a single packet.
85           - Add a packet queue to RemoteClient, from which packets will be
86             combined with object data packets
87                 - This is not exactly trivial: the object data packets are
88                   sometimes very big by themselves
89           - This might not give much network performance gain though.
90
91 SUGG: Precalculate lighting translation table at runtime (at startup)
92       - This is not doable because it is currently hand-made and not
93             based on some mathematical function.
94                 - Note: This has been changing lately
95
96 SUGG: A version number to blocks, which increments when the block is
97       modified (node add/remove, water update, lighting update)
98           - This can then be used to make sure the most recent version of
99             a block has been sent to client, for example
100
101 SUGG: Make the amount of blocks sending to client and the total
102           amount of blocks dynamically limited. Transferring blocks is the
103           main network eater of this system, so it is the one that has
104           to be throttled so that RTTs stay low.
105
106 SUGG: Meshes of blocks could be split into 6 meshes facing into
107       different directions and then only those drawn that need to be
108
109 SUGG: Background music based on cellular automata?
110       http://www.earslap.com/projectslab/otomata
111
112 SUGG: Simple light color information to air
113
114 SUGG: Server-side objects could be moved based on nodes to enable very
115       lightweight operation and simple AI
116         - Not practical; client would still need to show smooth movement.
117
118 SUGG: Make a system for pregenerating quick information for mapblocks, so
119           that the client can show them as cubes before they are actually sent
120           or even generated.
121
122 SUGG: Erosion simulation at map generation time
123     - This might be plausible if larger areas of map were pregenerated
124           without lighting (which is slow)
125         - Simulate water flows, which would carve out dirt fast and
126           then turn stone into gravel and sand and relocate it.
127         - How about relocating minerals, too? Coal and gold in
128           downstream sand and gravel would be kind of cool
129           - This would need a better way of handling minerals, mainly
130                 to have mineral content as a separate field. the first
131                 parameter field is free for this.
132         - Simulate rock falling from cliffs when water has removed
133           enough solid rock from the bottom
134
135 SUGG: For non-mapgen FarMesh: Add a per-sector database to store surface
136       stuff as simple flags/values
137       - Light?
138           - A building?
139           And at some point make the server send this data to the client too,
140           instead of referring to the noise functions
141           - Ground height
142           - Surface ground type
143           - Trees?
144
145 Gaming ideas:
146 -------------
147
148 - Aim for something like controlling a single dwarf in Dwarf Fortress
149 - The player could go faster by a crafting a boat, or riding an animal
150 - Random NPC traders. what else?
151
152 Game content:
153 -------------
154
155 - When furnace is destroyed, move items to player's inventory
156 - Add lots of stuff
157 - Glass blocks
158 - Growing grass, decaying leaves
159         - This can be done in the active blocks I guess.
160         - Lots of stuff can be done in the active blocks.
161         - Uh, is there an active block list somewhere? I think not. Add it.
162 - Breaking weak structures
163         - This can probably be accomplished in the same way as grass
164 - Player health points
165         - When player dies, throw items on map (needs better item-on-map
166           implementation)
167 - Cobble to get mossy if near water
168 - More slots in furnace source list, so that multiple ingredients
169   are possible.
170 - Keys to chests?
171
172 - The Treasure Guard; a big monster with a hammer
173         - The hammer does great damage, shakes the ground and removes a block
174         - You can drop on top of it, and have some time to attack there
175           before he shakes you off
176
177 - Maybe the difficulty could come from monsters getting tougher in
178   far-away places, and the player starting to need something from
179   there when time goes by.
180   - The player would have some of that stuff at the beginning, and
181     would need new supplies of it when it runs out
182
183 - A bomb
184 - A spread-items-on-map routine for the bomb, and for dying players
185
186 - Fighting:
187   - Proper sword swing simulation
188   - Player should get damage from colliding to a wall at high speed
189
190 Documentation:
191 --------------
192
193 Build system / running:
194 -----------------------
195
196 Networking and serialization:
197 -----------------------------
198
199 SUGG: Fix address to be ipv6 compatible
200
201 User Interface:
202 ---------------
203
204 Graphics:
205 ---------
206
207 SUGG: Combine MapBlock's face caches to so big pieces that VBO
208       can be used
209       - That is >500 vertices
210           - This is not easy; all the MapBlocks close to the player would
211             still need to be drawn separately and combining the blocks
212                 would have to happen in a background thread
213
214 SUGG: Make fetching sector's blocks more efficient when rendering
215       sectors that have very large amounts of blocks (on client)
216           - Is this necessary at all?
217
218 SUGG: Draw cubes in inventory directly with 3D drawing commands, so that
219       animating them is easier.
220
221 SUGG: Option for enabling proper alpha channel for textures
222
223 TODO: Flowing water animation
224
225 TODO: A setting for enabling bilinear filtering for textures
226
227 TODO: Better control of draw_control.wanted_max_blocks
228
229 TODO: Further investigate the use of GPU lighting in addition to the
230       current one
231
232 TODO: Artificial (night) light could be more yellow colored than sunlight.
233       - This is technically doable.
234           - Also the actual colors of the textures could be made less colorful
235             in the dark but it's a bit more difficult.
236
237 SUGG: Somehow make the night less colorful
238
239 TODO: Occlusion culling
240       - At the same time, move some of the renderMap() block choosing code
241         to the same place as where the new culling happens.
242       - Shoot some rays per frame and when ready, make a new list of
243             blocks for usage of renderMap and give it a new pointer to it.
244
245 Configuration:
246 --------------
247
248 Client:
249 -------
250
251 TODO: Untie client network operations from framerate
252       - Needs some input queues or something
253           - This won't give much performance boost because calculating block
254             meshes takes so long
255
256 SUGG: Make morning and evening transition more smooth and maybe shorter
257
258 TODO: Don't update all meshes always on single node changes, but
259       check which ones should be updated
260           - implement Map::updateNodeMeshes() and the usage of it
261           - It will give almost always a 4x boost in mesh update performance.
262
263 - A weapon engine
264
265 - Tool/weapon visualization
266
267 FIXME: When disconnected to the menu, memory is not freed properly
268
269 TODO: Investigate how much the mesh generator thread gets used when
270       transferring map data
271
272 Server:
273 -------
274
275 SUGG: Make an option to the server to disable building and digging near
276       the starting position
277
278 FIXME: Server sometimes goes into some infinite PeerNotFoundException loop
279
280 * Fix the problem with the server constantly saving one or a few
281   blocks? List the first saved block, maybe it explains.
282   - It is probably caused by oscillating water
283   - TODO: Investigate if this still happens (this is a very old one)
284 * Make a small history check to transformLiquids to detect and log
285   continuous oscillations, in such detail that they can be fixed.
286
287 FIXME: The new optimized map sending doesn't sometimes send enough blocks
288        from big caves and such
289 FIXME: Block send distance configuration does not take effect for some reason
290
291 Environment:
292 ------------
293
294 TODO: Add proper hooks to when adding and removing active blocks
295
296 TODO: Finish the ActiveBlockModifier stuff and use it for something
297
298 Objects:
299 --------
300
301 TODO: Get rid of MapBlockObjects and use only ActiveObjects
302         - Skipping the MapBlockObject data is nasty - there is no "total
303           length" stored; have to make a SkipMBOs function which contains
304           enough of the current code to skip them properly.
305
306 SUGG: MovingObject::move and Player::move are basically the same.
307       combine them.
308         - NOTE: This is a bit tricky because player has the sneaking ability
309         - NOTE: Player::move is more up-to-date.
310         - NOTE: There is a simple move implementation now in collision.{h,cpp}
311         - NOTE: MovingObject will be deleted (MapBlockObject)
312
313 TODO: Add a long step function to objects that is called with the time
314       difference when block activates
315
316 Map:
317 ----
318
319 TODO: Flowing water to actually contain flow direction information
320       - There is a space for this - it just has to be implemented.
321
322 TODO: Consider smoothening cave floors after generating them
323
324 TODO: Fix make_tree, make_* to use seed-position-consistent pseudorandom
325           - delta also
326
327 Misc. stuff:
328 ------------
329 TODO: Make sure server handles removing grass when a block is placed (etc)
330       - The client should not do it by itself
331           - NOTE: I think nobody does it currently...
332 TODO: Block cube placement around player's head
333 TODO: Protocol version field
334 TODO: Think about using same bits for material for fences and doors, for
335           example
336
337 SUGG: Restart irrlicht completely when coming back to main menu from game.
338         - This gets rid of everything that is stored in irrlicht's caches.
339         - This might be needed for texture pack selection in menu
340
341 TODO: Merge bahamada's audio stuff (clean patch available)
342
343 Making it more portable:
344 ------------------------
345  
346 Stuff to do before release:
347 ---------------------------
348
349 Fixes to the current release:
350 -----------------------------
351
352 Stuff to do after release:
353 ---------------------------
354
355 Doing currently:
356 ----------------
357
358 ======================================================================
359
360 */
361
362 #ifdef NDEBUG
363         /*#ifdef _WIN32
364                 #pragma message ("Disabling unit tests")
365         #else
366                 #warning "Disabling unit tests"
367         #endif*/
368         // Disable unit tests
369         #define ENABLE_TESTS 0
370 #else
371         // Enable unit tests
372         #define ENABLE_TESTS 1
373 #endif
374
375 #ifdef _MSC_VER
376         #pragma comment(lib, "Irrlicht.lib")
377         //#pragma comment(lib, "jthread.lib")
378         #pragma comment(lib, "zlibwapi.lib")
379         #pragma comment(lib, "Shell32.lib")
380         // This would get rid of the console window
381         //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
382 #endif
383
384 #include "irrlicht.h" // createDevice
385
386 #include "main.h"
387 #include "mainmenumanager.h"
388 #include <iostream>
389 #include <fstream>
390 #include <locale.h>
391 #include "common_irrlicht.h"
392 #include "debug.h"
393 #include "test.h"
394 #include "server.h"
395 #include "constants.h"
396 #include "porting.h"
397 #include "gettime.h"
398 #include "guiMessageMenu.h"
399 #include "filesys.h"
400 #include "config.h"
401 #include "guiMainMenu.h"
402 #include "materials.h"
403 #include "game.h"
404 #include "keycode.h"
405 #include "tile.h"
406 #include "defaultsettings.h"
407 #include "gettext.h"
408 #include "settings.h"
409 #include "profiler.h"
410 #include "log.h"
411 #include "mods.h"
412
413 /*
414         Settings.
415         These are loaded from the config file.
416 */
417 Settings main_settings;
418 Settings *g_settings = &main_settings;
419
420 // Global profiler
421 Profiler main_profiler;
422 Profiler *g_profiler = &main_profiler;
423
424 /*
425         Random stuff
426 */
427
428 /*
429         mainmenumanager.h
430 */
431
432 gui::IGUIEnvironment* guienv = NULL;
433 gui::IGUIStaticText *guiroot = NULL;
434 MainMenuManager g_menumgr;
435
436 bool noMenuActive()
437 {
438         return (g_menumgr.menuCount() == 0);
439 }
440
441 // Passed to menus to allow disconnecting and exiting
442 MainGameCallback *g_gamecallback = NULL;
443
444 /*
445         Debug streams
446 */
447
448 // Connection
449 std::ostream *dout_con_ptr = &dummyout;
450 std::ostream *derr_con_ptr = &verbosestream;
451 //std::ostream *dout_con_ptr = &infostream;
452 //std::ostream *derr_con_ptr = &errorstream;
453
454 // Server
455 std::ostream *dout_server_ptr = &infostream;
456 std::ostream *derr_server_ptr = &errorstream;
457
458 // Client
459 std::ostream *dout_client_ptr = &infostream;
460 std::ostream *derr_client_ptr = &errorstream;
461
462 /*
463         gettime.h implementation
464 */
465
466 // A small helper class
467 class TimeGetter
468 {
469 public:
470         virtual u32 getTime() = 0;
471 };
472
473 // A precise irrlicht one
474 class IrrlichtTimeGetter: public TimeGetter
475 {
476 public:
477         IrrlichtTimeGetter(IrrlichtDevice *device):
478                 m_device(device)
479         {}
480         u32 getTime()
481         {
482                 if(m_device == NULL)
483                         return 0;
484                 return m_device->getTimer()->getRealTime();
485         }
486 private:
487         IrrlichtDevice *m_device;
488 };
489 // Not so precise one which works without irrlicht
490 class SimpleTimeGetter: public TimeGetter
491 {
492 public:
493         u32 getTime()
494         {
495                 return porting::getTimeMs();
496         }
497 };
498
499 // A pointer to a global instance of the time getter
500 // TODO: why?
501 TimeGetter *g_timegetter = NULL;
502
503 u32 getTimeMs()
504 {
505         if(g_timegetter == NULL)
506                 return 0;
507         return g_timegetter->getTime();
508 }
509
510 /*
511         Event handler for Irrlicht
512
513         NOTE: Everything possible should be moved out from here,
514               probably to InputHandler and the_game
515 */
516
517 class MyEventReceiver : public IEventReceiver
518 {
519 public:
520         // This is the one method that we have to implement
521         virtual bool OnEvent(const SEvent& event)
522         {
523                 /*
524                         React to nothing here if a menu is active
525                 */
526                 if(noMenuActive() == false)
527                 {
528                         return false;
529                 }
530
531                 // Remember whether each key is down or up
532                 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
533                 {
534                         if(event.KeyInput.PressedDown) {
535                                 keyIsDown.set(event.KeyInput);
536                                 keyWasDown.set(event.KeyInput);
537                         } else {
538                                 keyIsDown.unset(event.KeyInput);
539                         }
540                 }
541
542                 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
543                 {
544                         if(noMenuActive() == false)
545                         {
546                                 left_active = false;
547                                 middle_active = false;
548                                 right_active = false;
549                         }
550                         else
551                         {
552                                 left_active = event.MouseInput.isLeftPressed();
553                                 middle_active = event.MouseInput.isMiddlePressed();
554                                 right_active = event.MouseInput.isRightPressed();
555
556                                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
557                                 {
558                                         leftclicked = true;
559                                 }
560                                 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
561                                 {
562                                         rightclicked = true;
563                                 }
564                                 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
565                                 {
566                                         leftreleased = true;
567                                 }
568                                 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
569                                 {
570                                         rightreleased = true;
571                                 }
572                                 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
573                                 {
574                                         mouse_wheel += event.MouseInput.Wheel;
575                                 }
576                         }
577                 }
578
579                 return false;
580         }
581
582         bool IsKeyDown(const KeyPress &keyCode) const
583         {
584                 return keyIsDown[keyCode];
585         }
586         
587         // Checks whether a key was down and resets the state
588         bool WasKeyDown(const KeyPress &keyCode)
589         {
590                 bool b = keyWasDown[keyCode];
591                 if (b)
592                         keyWasDown.unset(keyCode);
593                 return b;
594         }
595
596         s32 getMouseWheel()
597         {
598                 s32 a = mouse_wheel;
599                 mouse_wheel = 0;
600                 return a;
601         }
602
603         void clearInput()
604         {
605                 keyIsDown.clear();
606                 keyWasDown.clear();
607
608                 leftclicked = false;
609                 rightclicked = false;
610                 leftreleased = false;
611                 rightreleased = false;
612
613                 left_active = false;
614                 middle_active = false;
615                 right_active = false;
616
617                 mouse_wheel = 0;
618         }
619
620         MyEventReceiver()
621         {
622                 clearInput();
623         }
624
625         bool leftclicked;
626         bool rightclicked;
627         bool leftreleased;
628         bool rightreleased;
629
630         bool left_active;
631         bool middle_active;
632         bool right_active;
633
634         s32 mouse_wheel;
635
636 private:
637         IrrlichtDevice *m_device;
638         
639         // The current state of keys
640         KeyList keyIsDown;
641         // Whether a key has been pressed or not
642         KeyList keyWasDown;
643 };
644
645 /*
646         Separated input handler
647 */
648
649 class RealInputHandler : public InputHandler
650 {
651 public:
652         RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
653                 m_device(device),
654                 m_receiver(receiver)
655         {
656         }
657         virtual bool isKeyDown(const KeyPress &keyCode)
658         {
659                 return m_receiver->IsKeyDown(keyCode);
660         }
661         virtual bool wasKeyDown(const KeyPress &keyCode)
662         {
663                 return m_receiver->WasKeyDown(keyCode);
664         }
665         virtual v2s32 getMousePos()
666         {
667                 return m_device->getCursorControl()->getPosition();
668         }
669         virtual void setMousePos(s32 x, s32 y)
670         {
671                 m_device->getCursorControl()->setPosition(x, y);
672         }
673
674         virtual bool getLeftState()
675         {
676                 return m_receiver->left_active;
677         }
678         virtual bool getRightState()
679         {
680                 return m_receiver->right_active;
681         }
682         
683         virtual bool getLeftClicked()
684         {
685                 return m_receiver->leftclicked;
686         }
687         virtual bool getRightClicked()
688         {
689                 return m_receiver->rightclicked;
690         }
691         virtual void resetLeftClicked()
692         {
693                 m_receiver->leftclicked = false;
694         }
695         virtual void resetRightClicked()
696         {
697                 m_receiver->rightclicked = false;
698         }
699
700         virtual bool getLeftReleased()
701         {
702                 return m_receiver->leftreleased;
703         }
704         virtual bool getRightReleased()
705         {
706                 return m_receiver->rightreleased;
707         }
708         virtual void resetLeftReleased()
709         {
710                 m_receiver->leftreleased = false;
711         }
712         virtual void resetRightReleased()
713         {
714                 m_receiver->rightreleased = false;
715         }
716
717         virtual s32 getMouseWheel()
718         {
719                 return m_receiver->getMouseWheel();
720         }
721
722         void clear()
723         {
724                 m_receiver->clearInput();
725         }
726 private:
727         IrrlichtDevice *m_device;
728         MyEventReceiver *m_receiver;
729 };
730
731 class RandomInputHandler : public InputHandler
732 {
733 public:
734         RandomInputHandler()
735         {
736                 leftdown = false;
737                 rightdown = false;
738                 leftclicked = false;
739                 rightclicked = false;
740                 leftreleased = false;
741                 rightreleased = false;
742                 keydown.clear();
743         }
744         virtual bool isKeyDown(const KeyPress &keyCode)
745         {
746                 return keydown[keyCode];
747         }
748         virtual bool wasKeyDown(const KeyPress &keyCode)
749         {
750                 return false;
751         }
752         virtual v2s32 getMousePos()
753         {
754                 return mousepos;
755         }
756         virtual void setMousePos(s32 x, s32 y)
757         {
758                 mousepos = v2s32(x,y);
759         }
760
761         virtual bool getLeftState()
762         {
763                 return leftdown;
764         }
765         virtual bool getRightState()
766         {
767                 return rightdown;
768         }
769
770         virtual bool getLeftClicked()
771         {
772                 return leftclicked;
773         }
774         virtual bool getRightClicked()
775         {
776                 return rightclicked;
777         }
778         virtual void resetLeftClicked()
779         {
780                 leftclicked = false;
781         }
782         virtual void resetRightClicked()
783         {
784                 rightclicked = false;
785         }
786
787         virtual bool getLeftReleased()
788         {
789                 return leftreleased;
790         }
791         virtual bool getRightReleased()
792         {
793                 return rightreleased;
794         }
795         virtual void resetLeftReleased()
796         {
797                 leftreleased = false;
798         }
799         virtual void resetRightReleased()
800         {
801                 rightreleased = false;
802         }
803
804         virtual s32 getMouseWheel()
805         {
806                 return 0;
807         }
808
809         virtual void step(float dtime)
810         {
811                 {
812                         static float counter1 = 0;
813                         counter1 -= dtime;
814                         if(counter1 < 0.0)
815                         {
816                                 counter1 = 0.1*Rand(1, 40);
817                                 keydown.toggle(getKeySetting("keymap_jump"));
818                         }
819                 }
820                 {
821                         static float counter1 = 0;
822                         counter1 -= dtime;
823                         if(counter1 < 0.0)
824                         {
825                                 counter1 = 0.1*Rand(1, 40);
826                                 keydown.toggle(getKeySetting("keymap_special1"));
827                         }
828                 }
829                 {
830                         static float counter1 = 0;
831                         counter1 -= dtime;
832                         if(counter1 < 0.0)
833                         {
834                                 counter1 = 0.1*Rand(1, 40);
835                                 keydown.toggle(getKeySetting("keymap_forward"));
836                         }
837                 }
838                 {
839                         static float counter1 = 0;
840                         counter1 -= dtime;
841                         if(counter1 < 0.0)
842                         {
843                                 counter1 = 0.1*Rand(1, 40);
844                                 keydown.toggle(getKeySetting("keymap_left"));
845                         }
846                 }
847                 {
848                         static float counter1 = 0;
849                         counter1 -= dtime;
850                         if(counter1 < 0.0)
851                         {
852                                 counter1 = 0.1*Rand(1, 20);
853                                 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
854                         }
855                 }
856                 {
857                         static float counter1 = 0;
858                         counter1 -= dtime;
859                         if(counter1 < 0.0)
860                         {
861                                 counter1 = 0.1*Rand(1, 30);
862                                 leftdown = !leftdown;
863                                 if(leftdown)
864                                         leftclicked = true;
865                                 if(!leftdown)
866                                         leftreleased = true;
867                         }
868                 }
869                 {
870                         static float counter1 = 0;
871                         counter1 -= dtime;
872                         if(counter1 < 0.0)
873                         {
874                                 counter1 = 0.1*Rand(1, 15);
875                                 rightdown = !rightdown;
876                                 if(rightdown)
877                                         rightclicked = true;
878                                 if(!rightdown)
879                                         rightreleased = true;
880                         }
881                 }
882                 mousepos += mousespeed;
883         }
884
885         s32 Rand(s32 min, s32 max)
886         {
887                 return (myrand()%(max-min+1))+min;
888         }
889 private:
890         KeyList keydown;
891         v2s32 mousepos;
892         v2s32 mousespeed;
893         bool leftdown;
894         bool rightdown;
895         bool leftclicked;
896         bool rightclicked;
897         bool leftreleased;
898         bool rightreleased;
899 };
900
901 // These are defined global so that they're not optimized too much.
902 // Can't change them to volatile.
903 s16 temp16;
904 f32 tempf;
905 v3f tempv3f1;
906 v3f tempv3f2;
907 std::string tempstring;
908 std::string tempstring2;
909
910 void SpeedTests()
911 {
912         {
913                 dstream<<"The following test should take around 20ms."<<std::endl;
914                 TimeTaker timer("Testing std::string speed");
915                 const u32 jj = 10000;
916                 for(u32 j=0; j<jj; j++)
917                 {
918                         tempstring = "";
919                         tempstring2 = "";
920                         const u32 ii = 10;
921                         for(u32 i=0; i<ii; i++){
922                                 tempstring2 += "asd";
923                         }
924                         for(u32 i=0; i<ii+1; i++){
925                                 tempstring += "asd";
926                                 if(tempstring == tempstring2)
927                                         break;
928                         }
929                 }
930         }
931         
932         dstream<<"All of the following tests should take around 100ms each."
933                         <<std::endl;
934
935         {
936                 TimeTaker timer("Testing floating-point conversion speed");
937                 tempf = 0.001;
938                 for(u32 i=0; i<4000000; i++){
939                         temp16 += tempf;
940                         tempf += 0.001;
941                 }
942         }
943         
944         {
945                 TimeTaker timer("Testing floating-point vector speed");
946
947                 tempv3f1 = v3f(1,2,3);
948                 tempv3f2 = v3f(4,5,6);
949                 for(u32 i=0; i<10000000; i++){
950                         tempf += tempv3f1.dotProduct(tempv3f2);
951                         tempv3f2 += v3f(7,8,9);
952                 }
953         }
954
955         {
956                 TimeTaker timer("Testing core::map speed");
957                 
958                 core::map<v2s16, f32> map1;
959                 tempf = -324;
960                 const s16 ii=300;
961                 for(s16 y=0; y<ii; y++){
962                         for(s16 x=0; x<ii; x++){
963                                 map1.insert(v2s16(x,y), tempf);
964                                 tempf += 1;
965                         }
966                 }
967                 for(s16 y=ii-1; y>=0; y--){
968                         for(s16 x=0; x<ii; x++){
969                                 tempf = map1[v2s16(x,y)];
970                         }
971                 }
972         }
973
974         {
975                 dstream<<"Around 5000/ms should do well here."<<std::endl;
976                 TimeTaker timer("Testing mutex speed");
977                 
978                 JMutex m;
979                 m.Init();
980                 u32 n = 0;
981                 u32 i = 0;
982                 do{
983                         n += 10000;
984                         for(; i<n; i++){
985                                 m.Lock();
986                                 m.Unlock();
987                         }
988                 }
989                 // Do at least 10ms
990                 while(timer.getTime() < 10);
991
992                 u32 dtime = timer.stop();
993                 u32 per_ms = n / dtime;
994                 dstream<<"Done. "<<dtime<<"ms, "
995                                 <<per_ms<<"/ms"<<std::endl;
996         }
997 }
998
999 void drawMenuBackground(video::IVideoDriver* driver)
1000 {
1001         core::dimension2d<u32> screensize = driver->getScreenSize();
1002                 
1003         video::ITexture *bgtexture =
1004                         driver->getTexture(getTexturePath("menubg.png").c_str());
1005         if(bgtexture)
1006         {
1007                 s32 texturesize = 128;
1008                 s32 tiled_y = screensize.Height / texturesize + 1;
1009                 s32 tiled_x = screensize.Width / texturesize + 1;
1010                 
1011                 for(s32 y=0; y<tiled_y; y++)
1012                 for(s32 x=0; x<tiled_x; x++)
1013                 {
1014                         core::rect<s32> rect(0,0,texturesize,texturesize);
1015                         rect += v2s32(x*texturesize, y*texturesize);
1016                         driver->draw2DImage(bgtexture, rect,
1017                                 core::rect<s32>(core::position2d<s32>(0,0),
1018                                 core::dimension2di(bgtexture->getSize())),
1019                                 NULL, NULL, true);
1020                 }
1021         }
1022         
1023         video::ITexture *logotexture =
1024                         driver->getTexture(getTexturePath("menulogo.png").c_str());
1025         if(logotexture)
1026         {
1027                 v2s32 logosize(logotexture->getOriginalSize().Width,
1028                                 logotexture->getOriginalSize().Height);
1029                 logosize *= 4;
1030
1031                 video::SColor bgcolor(255,50,50,50);
1032                 core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,
1033                                 screensize.Width, screensize.Height);
1034                 driver->draw2DRectangle(bgcolor, bgrect, NULL);
1035
1036                 core::rect<s32> rect(0,0,logosize.X,logosize.Y);
1037                 rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);
1038                 rect -= v2s32(logosize.X/2, 0);
1039                 driver->draw2DImage(logotexture, rect,
1040                         core::rect<s32>(core::position2d<s32>(0,0),
1041                         core::dimension2di(logotexture->getSize())),
1042                         NULL, NULL, true);
1043         }
1044 }
1045
1046 class StderrLogOutput: public ILogOutput
1047 {
1048 public:
1049         /* line: Full line with timestamp, level and thread */
1050         void printLog(const std::string &line)
1051         {
1052                 std::cerr<<line<<std::endl;
1053         }
1054 } main_stderr_log_out;
1055
1056 class DstreamNoStderrLogOutput: public ILogOutput
1057 {
1058 public:
1059         /* line: Full line with timestamp, level and thread */
1060         void printLog(const std::string &line)
1061         {
1062                 dstream_no_stderr<<line<<std::endl;
1063         }
1064 } main_dstream_no_stderr_log_out;
1065
1066 int main(int argc, char *argv[])
1067 {
1068         /*
1069                 Initialization
1070         */
1071
1072         log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
1073         log_add_output_all_levs(&main_dstream_no_stderr_log_out);
1074
1075         log_register_thread("main");
1076
1077         // Set locale. This is for forcing '.' as the decimal point.
1078         std::locale::global(std::locale("C"));
1079         // This enables printing all characters in bitmap font
1080         setlocale(LC_CTYPE, "en_US");
1081
1082         /*
1083                 Parse command line
1084         */
1085         
1086         // List all allowed options
1087         core::map<std::string, ValueSpec> allowed_options;
1088         allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
1089                         "Show allowed options"));
1090         allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
1091                         "Run server directly"));
1092         allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
1093                         "Load configuration from specified file"));
1094         allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
1095                         "Set network port to connect to"));
1096         allowed_options.insert("address", ValueSpec(VALUETYPE_STRING,
1097                         "Address to connect to"));
1098         allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG,
1099                         "Enable random user input, for testing"));
1100         allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
1101                         "Disable unit tests"));
1102         allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
1103                         "Enable unit tests"));
1104         allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
1105                         "Map directory (where everything in the world is stored)"));
1106 #ifdef _WIN32
1107         allowed_options.insert("dstream-on-stderr", ValueSpec(VALUETYPE_FLAG));
1108 #endif
1109         allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
1110                         "Run speed tests"));
1111         allowed_options.insert("info-on-stderr", ValueSpec(VALUETYPE_FLAG,
1112                         "Print debug information to console"));
1113
1114         Settings cmd_args;
1115         
1116         bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
1117
1118         if(ret == false || cmd_args.getFlag("help"))
1119         {
1120                 dstream<<"Allowed options:"<<std::endl;
1121                 for(core::map<std::string, ValueSpec>::Iterator
1122                                 i = allowed_options.getIterator();
1123                                 i.atEnd() == false; i++)
1124                 {
1125                         dstream<<"  --"<<i.getNode()->getKey();
1126                         if(i.getNode()->getValue().type == VALUETYPE_FLAG)
1127                         {
1128                         }
1129                         else
1130                         {
1131                                 dstream<<" <value>";
1132                         }
1133                         dstream<<std::endl;
1134
1135                         if(i.getNode()->getValue().help != NULL)
1136                         {
1137                                 dstream<<"      "<<i.getNode()->getValue().help
1138                                                 <<std::endl;
1139                         }
1140                 }
1141
1142                 return cmd_args.getFlag("help") ? 0 : 1;
1143         }
1144         
1145         /*
1146                 Low-level initialization
1147         */
1148
1149         bool disable_stderr = false;
1150 #ifdef _WIN32
1151         if(cmd_args.getFlag("dstream-on-stderr") == false)
1152                 disable_stderr = true;
1153 #endif
1154         
1155         if(cmd_args.getFlag("info-on-stderr"))
1156                 log_add_output(&main_stderr_log_out, LMT_INFO);
1157
1158         porting::signal_handler_init();
1159         bool &kill = *porting::signal_handler_killstatus();
1160         
1161         // Initialize porting::path_data and porting::path_userdata
1162         porting::initializePaths();
1163
1164         // Create user data directory
1165         fs::CreateDir(porting::path_userdata);
1166
1167         init_gettext((porting::path_data+DIR_DELIM+".."+DIR_DELIM+"locale").c_str());
1168         
1169         // Initialize debug streams
1170 #ifdef RUN_IN_PLACE
1171         std::string debugfile = DEBUGFILE;
1172 #else
1173         std::string debugfile = porting::path_userdata+DIR_DELIM+DEBUGFILE;
1174 #endif
1175         debugstreams_init(disable_stderr, debugfile.c_str());
1176         // Initialize debug stacks
1177         debug_stacks_init();
1178
1179         DSTACK(__FUNCTION_NAME);
1180
1181         // Init material properties table
1182         //initializeMaterialProperties();
1183
1184         // Debug handler
1185         BEGIN_DEBUG_EXCEPTION_HANDLER
1186
1187         // Print startup message
1188         actionstream<<PROJECT_NAME<<
1189                         " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
1190                         <<", "<<BUILD_INFO
1191                         <<std::endl;
1192         
1193         /*
1194                 Basic initialization
1195         */
1196
1197         // Initialize default settings
1198         set_default_settings(g_settings);
1199         
1200         // Initialize sockets
1201         sockets_init();
1202         atexit(sockets_cleanup);
1203         
1204         /*
1205                 Read config file
1206         */
1207         
1208         // Path of configuration file in use
1209         std::string configpath = "";
1210         
1211         if(cmd_args.exists("config"))
1212         {
1213                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1214                 if(r == false)
1215                 {
1216                         errorstream<<"Could not read configuration from \""
1217                                         <<cmd_args.get("config")<<"\""<<std::endl;
1218                         return 1;
1219                 }
1220                 configpath = cmd_args.get("config");
1221         }
1222         else
1223         {
1224                 core::array<std::string> filenames;
1225                 filenames.push_back(porting::path_userdata +
1226                                 DIR_DELIM + "minetest.conf");
1227 #ifdef RUN_IN_PLACE
1228                 filenames.push_back(porting::path_userdata +
1229                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1230 #endif
1231
1232                 for(u32 i=0; i<filenames.size(); i++)
1233                 {
1234                         bool r = g_settings->readConfigFile(filenames[i].c_str());
1235                         if(r)
1236                         {
1237                                 configpath = filenames[i];
1238                                 break;
1239                         }
1240                 }
1241                 
1242                 // If no path found, use the first one (menu creates the file)
1243                 if(configpath == "")
1244                         configpath = filenames[0];
1245         }
1246
1247         // Initialize random seed
1248         srand(time(0));
1249         mysrand(time(0));
1250
1251         /*
1252                 Run unit tests
1253         */
1254
1255         if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1256                         || cmd_args.getFlag("enable-unittests") == true)
1257         {
1258                 run_tests();
1259         }
1260         
1261         /*for(s16 y=-100; y<100; y++)
1262         for(s16 x=-100; x<100; x++)
1263         {
1264                 std::cout<<noise2d_gradient((double)x/10,(double)y/10, 32415)<<std::endl;
1265         }
1266         return 0;*/
1267         
1268         /*
1269                 Game parameters
1270         */
1271
1272         // Port
1273         u16 port = 30000;
1274         if(cmd_args.exists("port"))
1275                 port = cmd_args.getU16("port");
1276         else if(g_settings->exists("port"))
1277                 port = g_settings->getU16("port");
1278         if(port == 0)
1279                 port = 30000;
1280         
1281         // Map directory
1282         std::string map_dir = porting::path_userdata+DIR_DELIM+"world";
1283         if(cmd_args.exists("map-dir"))
1284                 map_dir = cmd_args.get("map-dir");
1285         else if(g_settings->exists("map-dir"))
1286                 map_dir = g_settings->get("map-dir");
1287         
1288         // Run dedicated server if asked to
1289         if(cmd_args.getFlag("server"))
1290         {
1291                 DSTACK("Dedicated server branch");
1292
1293                 // Create time getter
1294                 g_timegetter = new SimpleTimeGetter();
1295                 
1296                 // Create server
1297                 Server server(map_dir.c_str(), configpath);
1298                 server.start(port);
1299                 
1300                 // Run server
1301                 dedicated_server_loop(server, kill);
1302
1303                 return 0;
1304         }
1305
1306
1307         /*
1308                 More parameters
1309         */
1310         
1311         // Address to connect to
1312         std::string address = "";
1313         
1314         if(cmd_args.exists("address"))
1315         {
1316                 address = cmd_args.get("address");
1317         }
1318         else
1319         {
1320                 address = g_settings->get("address");
1321         }
1322         
1323         std::string playername = g_settings->get("name");
1324
1325         /*
1326                 Device initialization
1327         */
1328
1329         // Resolution selection
1330         
1331         bool fullscreen = false;
1332         u16 screenW = g_settings->getU16("screenW");
1333         u16 screenH = g_settings->getU16("screenH");
1334
1335         // Determine driver
1336
1337         video::E_DRIVER_TYPE driverType;
1338         
1339         std::string driverstring = g_settings->get("video_driver");
1340
1341         if(driverstring == "null")
1342                 driverType = video::EDT_NULL;
1343         else if(driverstring == "software")
1344                 driverType = video::EDT_SOFTWARE;
1345         else if(driverstring == "burningsvideo")
1346                 driverType = video::EDT_BURNINGSVIDEO;
1347         else if(driverstring == "direct3d8")
1348                 driverType = video::EDT_DIRECT3D8;
1349         else if(driverstring == "direct3d9")
1350                 driverType = video::EDT_DIRECT3D9;
1351         else if(driverstring == "opengl")
1352                 driverType = video::EDT_OPENGL;
1353         else
1354         {
1355                 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1356                                 "to opengl"<<std::endl;
1357                 driverType = video::EDT_OPENGL;
1358         }
1359
1360         /*
1361                 Create device and exit if creation failed
1362         */
1363
1364         MyEventReceiver receiver;
1365
1366         IrrlichtDevice *device;
1367         device = createDevice(driverType,
1368                         core::dimension2d<u32>(screenW, screenH),
1369                         16, fullscreen, false, false, &receiver);
1370
1371         if (device == 0)
1372                 return 1; // could not create selected driver.
1373         
1374         /*
1375                 Continue initialization
1376         */
1377
1378         video::IVideoDriver* driver = device->getVideoDriver();
1379
1380         // Disable mipmaps (because some of them look ugly)
1381         driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
1382
1383         /*
1384                 This changes the minimum allowed number of vertices in a VBO.
1385                 Default is 500.
1386         */
1387         //driver->setMinHardwareBufferVertexCount(50);
1388
1389         // Set the window caption
1390         device->setWindowCaption(L"Minetest [Main Menu]");
1391         
1392         // Create time getter
1393         g_timegetter = new IrrlichtTimeGetter(device);
1394         
1395         // Create game callback for menus
1396         g_gamecallback = new MainGameCallback(device);
1397         
1398         /*
1399                 Speed tests (done after irrlicht is loaded to get timer)
1400         */
1401         if(cmd_args.getFlag("speedtests"))
1402         {
1403                 dstream<<"Running speed tests"<<std::endl;
1404                 SpeedTests();
1405                 return 0;
1406         }
1407         
1408         device->setResizable(true);
1409
1410         bool random_input = g_settings->getBool("random_input")
1411                         || cmd_args.getFlag("random-input");
1412         InputHandler *input = NULL;
1413         if(random_input)
1414                 input = new RandomInputHandler();
1415         else
1416                 input = new RealInputHandler(device, &receiver);
1417         
1418         scene::ISceneManager* smgr = device->getSceneManager();
1419
1420         guienv = device->getGUIEnvironment();
1421         gui::IGUISkin* skin = guienv->getSkin();
1422         gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1423         if(font)
1424                 skin->setFont(font);
1425         else
1426                 errorstream<<"WARNING: Font file was not found."
1427                                 " Using default font."<<std::endl;
1428         // If font was not found, this will get us one
1429         font = skin->getFont();
1430         assert(font);
1431         
1432         u32 text_height = font->getDimension(L"Hello, world!").Height;
1433         infostream<<"text_height="<<text_height<<std::endl;
1434
1435         //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1436         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1437         //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1438         //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1439         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1440         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1441         
1442         /*
1443                 GUI stuff
1444         */
1445
1446         /*
1447                 If an error occurs, this is set to something and the
1448                 menu-game loop is restarted. It is then displayed before
1449                 the menu.
1450         */
1451         std::wstring error_message = L"";
1452
1453         // The password entered during the menu screen,
1454         std::string password;
1455
1456         /*
1457                 Menu-game loop
1458         */
1459         while(device->run() && kill == false)
1460         {
1461
1462                 // This is used for catching disconnects
1463                 try
1464                 {
1465
1466                         /*
1467                                 Clear everything from the GUIEnvironment
1468                         */
1469                         guienv->clear();
1470                         
1471                         /*
1472                                 We need some kind of a root node to be able to add
1473                                 custom gui elements directly on the screen.
1474                                 Otherwise they won't be automatically drawn.
1475                         */
1476                         guiroot = guienv->addStaticText(L"",
1477                                         core::rect<s32>(0, 0, 10000, 10000));
1478                         
1479                         /*
1480                                 Out-of-game menu loop.
1481
1482                                 Loop quits when menu returns proper parameters.
1483                         */
1484                         while(kill == false)
1485                         {
1486                                 // Cursor can be non-visible when coming from the game
1487                                 device->getCursorControl()->setVisible(true);
1488                                 // Some stuff are left to scene manager when coming from the game
1489                                 // (map at least?)
1490                                 smgr->clear();
1491                                 // Reset or hide the debug gui texts
1492                                 /*guitext->setText(L"Minetest-c55");
1493                                 guitext2->setVisible(false);
1494                                 guitext_info->setVisible(false);
1495                                 guitext_chat->setVisible(false);*/
1496                                 
1497                                 // Initialize menu data
1498                                 MainMenuData menudata;
1499                                 menudata.address = narrow_to_wide(address);
1500                                 menudata.name = narrow_to_wide(playername);
1501                                 menudata.port = narrow_to_wide(itos(port));
1502                                 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1503                                 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1504                                 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1505                                 menudata.opaque_water = g_settings->getBool("opaque_water");
1506                                 menudata.creative_mode = g_settings->getBool("creative_mode");
1507                                 menudata.enable_damage = g_settings->getBool("enable_damage");
1508
1509                                 GUIMainMenu *menu =
1510                                                 new GUIMainMenu(guienv, guiroot, -1, 
1511                                                         &g_menumgr, &menudata, g_gamecallback);
1512                                 menu->allowFocusRemoval(true);
1513
1514                                 if(error_message != L"")
1515                                 {
1516                                         errorstream<<"error_message = "
1517                                                         <<wide_to_narrow(error_message)<<std::endl;
1518
1519                                         GUIMessageMenu *menu2 =
1520                                                         new GUIMessageMenu(guienv, guiroot, -1, 
1521                                                                 &g_menumgr, error_message.c_str());
1522                                         menu2->drop();
1523                                         error_message = L"";
1524                                 }
1525
1526                                 video::IVideoDriver* driver = device->getVideoDriver();
1527                                 
1528                                 infostream<<"Created main menu"<<std::endl;
1529
1530                                 while(device->run() && kill == false)
1531                                 {
1532                                         if(menu->getStatus() == true)
1533                                                 break;
1534
1535                                         //driver->beginScene(true, true, video::SColor(255,0,0,0));
1536                                         driver->beginScene(true, true, video::SColor(255,128,128,128));
1537
1538                                         drawMenuBackground(driver);
1539
1540                                         guienv->drawAll();
1541                                         
1542                                         driver->endScene();
1543                                         
1544                                         // On some computers framerate doesn't seem to be
1545                                         // automatically limited
1546                                         sleep_ms(25);
1547                                 }
1548                                 
1549                                 // Break out of menu-game loop to shut down cleanly
1550                                 if(device->run() == false || kill == true)
1551                                         break;
1552                                 
1553                                 infostream<<"Dropping main menu"<<std::endl;
1554
1555                                 menu->drop();
1556                                 
1557                                 // Delete map if requested
1558                                 if(menudata.delete_map)
1559                                 {
1560                                         bool r = fs::RecursiveDeleteContent(map_dir);
1561                                         if(r == false)
1562                                                 error_message = L"Delete failed";
1563                                         continue;
1564                                 }
1565
1566                                 playername = wide_to_narrow(menudata.name);
1567
1568                                 password = translatePassword(playername, menudata.password);
1569
1570                                 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1571
1572                                 address = wide_to_narrow(menudata.address);
1573                                 int newport = stoi(wide_to_narrow(menudata.port));
1574                                 if(newport != 0)
1575                                         port = newport;
1576                                 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1577                                 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1578                                 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1579                                 g_settings->set("opaque_water", itos(menudata.opaque_water));
1580                                 g_settings->set("creative_mode", itos(menudata.creative_mode));
1581                                 g_settings->set("enable_damage", itos(menudata.enable_damage));
1582                                 
1583                                 // NOTE: These are now checked server side; no need to do it
1584                                 //       here, so let's not do it here.
1585                                 /*// Check for valid parameters, restart menu if invalid.
1586                                 if(playername == "")
1587                                 {
1588                                         error_message = L"Name required.";
1589                                         continue;
1590                                 }
1591                                 // Check that name has only valid chars
1592                                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1593                                 {
1594                                         error_message = L"Characters allowed: "
1595                                                         +narrow_to_wide(PLAYERNAME_ALLOWED_CHARS);
1596                                         continue;
1597                                 }*/
1598
1599                                 // Save settings
1600                                 g_settings->set("name", playername);
1601                                 g_settings->set("address", address);
1602                                 g_settings->set("port", itos(port));
1603                                 // Update configuration file
1604                                 if(configpath != "")
1605                                         g_settings->updateConfigFile(configpath.c_str());
1606                         
1607                                 // Continue to game
1608                                 break;
1609                         }
1610                         
1611                         // Break out of menu-game loop to shut down cleanly
1612                         if(device->run() == false || kill == true)
1613                                 break;
1614                         
1615                         /*
1616                                 Run game
1617                         */
1618                         the_game(
1619                                 kill,
1620                                 random_input,
1621                                 input,
1622                                 device,
1623                                 font,
1624                                 map_dir,
1625                                 playername,
1626                                 password,
1627                                 address,
1628                                 port,
1629                                 error_message,
1630                                 configpath
1631                         );
1632
1633                 } //try
1634                 catch(con::PeerNotFoundException &e)
1635                 {
1636                         errorstream<<"Connection error (timed out?)"<<std::endl;
1637                         error_message = L"Connection error (timed out?)";
1638                 }
1639                 catch(SocketException &e)
1640                 {
1641                         errorstream<<"Socket error (port already in use?)"<<std::endl;
1642                         error_message = L"Socket error (port already in use?)";
1643                 }
1644                 catch(ModError &e)
1645                 {
1646                         errorstream<<e.what()<<std::endl;
1647                         error_message = narrow_to_wide(e.what()) + L"\nCheck debug.txt for details.";
1648                 }
1649 #ifdef NDEBUG
1650                 catch(std::exception &e)
1651                 {
1652                         std::string narrow_message = "Some exception, what()=\"";
1653                         narrow_message += e.what();
1654                         narrow_message += "\"";
1655                         errorstream<<narrow_message<<std::endl;
1656                         error_message = narrow_to_wide(narrow_message);
1657                 }
1658 #endif
1659
1660         } // Menu-game loop
1661         
1662         delete input;
1663
1664         /*
1665                 In the end, delete the Irrlicht device.
1666         */
1667         device->drop();
1668         
1669         END_DEBUG_EXCEPTION_HANDLER(errorstream)
1670         
1671         debugstreams_deinit();
1672         
1673         return 0;
1674 }
1675
1676 //END
1677