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