]> git.lizzy.rs Git - dragonfireclient.git/blob - src/guiEngine.cpp
Bunch of small fixes (coding style, very unlikely errors, warning messages)
[dragonfireclient.git] / src / guiEngine.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 sapier
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "guiEngine.h"
21
22 #include "scripting_mainmenu.h"
23 #include "config.h"
24 #include "version.h"
25 #include "porting.h"
26 #include "filesys.h"
27 #include "main.h"
28 #include "settings.h"
29 #include "guiMainMenu.h"
30 #include "sound.h"
31 #include "sound_openal.h"
32 #include "clouds.h"
33 #include "httpfetch.h"
34
35 #include <IGUIStaticText.h>
36 #include <ICameraSceneNode.h>
37
38 #if USE_CURL
39 #include <curl/curl.h>
40 #endif
41
42 /******************************************************************************/
43 /** TextDestGuiEngine                                                         */
44 /******************************************************************************/
45 TextDestGuiEngine::TextDestGuiEngine(GUIEngine* engine)
46 {
47         m_engine = engine;
48 }
49
50 /******************************************************************************/
51 void TextDestGuiEngine::gotText(std::map<std::string, std::string> fields)
52 {
53         m_engine->getScriptIface()->handleMainMenuButtons(fields);
54 }
55
56 /******************************************************************************/
57 void TextDestGuiEngine::gotText(std::wstring text)
58 {
59         m_engine->getScriptIface()->handleMainMenuEvent(wide_to_narrow(text));
60 }
61
62 /******************************************************************************/
63 /** MenuTextureSource                                                         */
64 /******************************************************************************/
65 MenuTextureSource::MenuTextureSource(video::IVideoDriver *driver)
66 {
67         m_driver = driver;
68 }
69
70 /******************************************************************************/
71 MenuTextureSource::~MenuTextureSource()
72 {
73         for (std::set<std::string>::iterator it = m_to_delete.begin();
74                         it != m_to_delete.end(); ++it) {
75                 const char *tname = (*it).c_str();
76                 video::ITexture *texture = m_driver->getTexture(tname);
77                 m_driver->removeTexture(texture);
78         }
79 }
80
81 /******************************************************************************/
82 video::ITexture* MenuTextureSource::getTexture(const std::string &name, u32 *id)
83 {
84         if(id)
85                 *id = 0;
86         if(name.empty())
87                 return NULL;
88         m_to_delete.insert(name);
89         return m_driver->getTexture(name.c_str());
90 }
91
92 /******************************************************************************/
93 /** MenuMusicFetcher                                                          */
94 /******************************************************************************/
95 void MenuMusicFetcher::fetchSounds(const std::string &name,
96                         std::set<std::string> &dst_paths,
97                         std::set<std::string> &dst_datas)
98 {
99         if(m_fetched.count(name))
100                 return;
101         m_fetched.insert(name);
102         std::string base;
103         base = porting::path_share + DIR_DELIM + "sounds";
104         dst_paths.insert(base + DIR_DELIM + name + ".ogg");
105         int i;
106         for(i=0; i<10; i++)
107                 dst_paths.insert(base + DIR_DELIM + name + "."+itos(i)+".ogg");
108         base = porting::path_user + DIR_DELIM + "sounds";
109         dst_paths.insert(base + DIR_DELIM + name + ".ogg");
110         for(i=0; i<10; i++)
111                 dst_paths.insert(base + DIR_DELIM + name + "."+itos(i)+".ogg");
112 }
113
114 /******************************************************************************/
115 /** GUIEngine                                                                 */
116 /******************************************************************************/
117 GUIEngine::GUIEngine(   irr::IrrlichtDevice* dev,
118                                                 gui::IGUIElement* parent,
119                                                 IMenuManager *menumgr,
120                                                 scene::ISceneManager* smgr,
121                                                 MainMenuData* data,
122                                                 bool& kill) :
123         m_device(dev),
124         m_parent(parent),
125         m_menumanager(menumgr),
126         m_smgr(smgr),
127         m_data(data),
128         m_texture_source(NULL),
129         m_sound_manager(NULL),
130         m_formspecgui(0),
131         m_buttonhandler(0),
132         m_menu(0),
133         m_kill(kill),
134         m_startgame(false),
135         m_script(0),
136         m_scriptdir(""),
137         m_irr_toplefttext(0),
138         m_clouds_enabled(true),
139         m_cloud()
140 {
141         //initialize texture pointers
142         for (unsigned int i = 0; i < TEX_LAYER_MAX; i++) {
143                 m_textures[i] = 0;
144         }
145         // is deleted by guiformspec!
146         m_buttonhandler = new TextDestGuiEngine(this);
147
148         //create texture source
149         m_texture_source = new MenuTextureSource(m_device->getVideoDriver());
150
151         //create soundmanager
152         MenuMusicFetcher soundfetcher;
153 #if USE_SOUND
154         m_sound_manager = createOpenALSoundManager(&soundfetcher);
155 #endif
156         if(!m_sound_manager)
157                 m_sound_manager = &dummySoundManager;
158
159         //create topleft header
160         core::rect<s32> rect(0, 0, 500, 20);
161         rect += v2s32(4, 0);
162         std::string t = std::string("Minetest ") + minetest_version_hash;
163
164         m_irr_toplefttext =
165                 m_device->getGUIEnvironment()->addStaticText(narrow_to_wide(t).c_str(),
166                 rect,false,true,0,-1);
167
168         //create formspecsource
169         m_formspecgui = new FormspecFormSource("",&m_formspecgui);
170
171         /* Create menu */
172         m_menu =
173                 new GUIFormSpecMenu(    m_device,
174                                                                 m_parent,
175                                                                 -1,
176                                                                 m_menumanager,
177                                                                 0 /* &client */,
178                                                                 0 /* gamedef */,
179                                                                 m_texture_source);
180
181         m_menu->allowClose(false);
182         m_menu->lockSize(true,v2u32(800,600));
183         m_menu->setFormSource(m_formspecgui);
184         m_menu->setTextDest(m_buttonhandler);
185
186         // Initialize scripting
187
188         infostream<<"GUIEngine: Initializing Lua"<<std::endl;
189
190         m_script = new MainMenuScripting(this);
191
192         try {
193                 if (m_data->errormessage != "")
194                 {
195                         m_script->setMainMenuErrorMessage(m_data->errormessage);
196                         m_data->errormessage = "";
197                 }
198
199                 if (!loadMainMenuScript())
200                         assert("no future without mainmenu" == 0);
201
202                 run();
203         }
204         catch(LuaError &e) {
205                 errorstream << "MAINMENU ERROR: " << e.what() << std::endl;
206                 m_data->errormessage = e.what();
207         }
208
209         m_menu->quitMenu();
210         m_menu->drop();
211         m_menu = 0;
212 }
213
214 /******************************************************************************/
215 bool GUIEngine::loadMainMenuScript()
216 {
217         // Try custom menu script (main_menu_script)
218
219         std::string menuscript = g_settings->get("main_menu_script");
220         if(menuscript != "") {
221                 m_scriptdir = fs::RemoveLastPathComponent(menuscript);
222
223                 if(m_script->loadMod(menuscript, "__custommenu")) {
224                         // custom menu script loaded
225                         return true;
226                 }
227                 else {
228                         infostream
229                                 << "GUIEngine: execution of custom menu: \""
230                                 << menuscript << "\" failed!"
231                                 << std::endl
232                                 << "\tfalling back to builtin menu"
233                                 << std::endl;
234                 }
235         }
236
237         // Try builtin menu script (main_menu_script)
238
239         std::string builtin_menuscript =
240                         porting::path_share + DIR_DELIM + "builtin"
241                                 + DIR_DELIM + "mainmenu.lua";
242
243         m_scriptdir = fs::RemoveRelativePathComponents(
244                         fs::RemoveLastPathComponent(builtin_menuscript));
245
246         if(m_script->loadMod(builtin_menuscript, "__builtinmenu")) {
247                 // builtin menu script loaded
248                 return true;
249         }
250         else {
251                 errorstream
252                         << "GUIEngine: unable to load builtin menu"
253                         << std::endl;
254         }
255
256         return false;
257 }
258
259 /******************************************************************************/
260 void GUIEngine::run()
261 {
262
263         // Always create clouds because they may or may not be
264         // needed based on the game selected
265         video::IVideoDriver* driver = m_device->getVideoDriver();
266
267         cloudInit();
268
269         while(m_device->run() && (!m_startgame) && (!m_kill)) {
270                 driver->beginScene(true, true, video::SColor(255,140,186,250));
271
272                 if (m_clouds_enabled)
273                 {
274                         cloudPreProcess();
275                         drawOverlay(driver);
276                 }
277                 else
278                         drawBackground(driver);
279
280                 drawHeader(driver);
281                 drawFooter(driver);
282
283                 m_device->getGUIEnvironment()->drawAll();
284
285                 driver->endScene();
286
287                 if (m_clouds_enabled)
288                         cloudPostProcess();
289                 else
290                         sleep_ms(25);
291
292                 m_script->Step();
293         }
294 }
295
296 /******************************************************************************/
297 GUIEngine::~GUIEngine()
298 {
299         video::IVideoDriver* driver = m_device->getVideoDriver();
300         assert(driver != 0);
301
302         if(m_sound_manager != &dummySoundManager){
303                 delete m_sound_manager;
304                 m_sound_manager = NULL;
305         }
306
307         //TODO: clean up m_menu here
308
309         infostream<<"GUIEngine: Deinitializing scripting"<<std::endl;
310         delete m_script;
311
312         m_irr_toplefttext->setText(L"");
313
314         //clean up texture pointers
315         for (unsigned int i = 0; i < TEX_LAYER_MAX; i++) {
316                 if (m_textures[i] != 0)
317                         driver->removeTexture(m_textures[i]);
318         }
319
320         delete m_texture_source;
321         
322         if (m_cloud.clouds)
323                 m_cloud.clouds->drop();
324 }
325
326 /******************************************************************************/
327 void GUIEngine::cloudInit()
328 {
329         m_cloud.clouds = new Clouds(m_smgr->getRootSceneNode(),
330                         m_smgr, -1, rand(), 100);
331         m_cloud.clouds->update(v2f(0, 0), video::SColor(255,200,200,255));
332
333         m_cloud.camera = m_smgr->addCameraSceneNode(0,
334                                 v3f(0,0,0), v3f(0, 60, 100));
335         m_cloud.camera->setFarValue(10000);
336
337         m_cloud.lasttime = m_device->getTimer()->getTime();
338 }
339
340 /******************************************************************************/
341 void GUIEngine::cloudPreProcess()
342 {
343         u32 time = m_device->getTimer()->getTime();
344
345         if(time > m_cloud.lasttime)
346                 m_cloud.dtime = (time - m_cloud.lasttime) / 1000.0;
347         else
348                 m_cloud.dtime = 0;
349
350         m_cloud.lasttime = time;
351
352         m_cloud.clouds->step(m_cloud.dtime*3);
353         m_cloud.clouds->render();
354         m_smgr->drawAll();
355 }
356
357 /******************************************************************************/
358 void GUIEngine::cloudPostProcess()
359 {
360         float fps_max = g_settings->getFloat("fps_max");
361         // Time of frame without fps limit
362         float busytime;
363         u32 busytime_u32;
364         // not using getRealTime is necessary for wine
365         u32 time = m_device->getTimer()->getTime();
366         if(time > m_cloud.lasttime)
367                 busytime_u32 = time - m_cloud.lasttime;
368         else
369                 busytime_u32 = 0;
370         busytime = busytime_u32 / 1000.0;
371
372         // FPS limiter
373         u32 frametime_min = 1000./fps_max;
374
375         if(busytime_u32 < frametime_min) {
376                 u32 sleeptime = frametime_min - busytime_u32;
377                 m_device->sleep(sleeptime);
378         }
379 }
380
381 /******************************************************************************/
382 void GUIEngine::drawBackground(video::IVideoDriver* driver)
383 {
384         v2u32 screensize = driver->getScreenSize();
385
386         video::ITexture* texture = m_textures[TEX_LAYER_BACKGROUND];
387
388         /* If no texture, draw background of solid color */
389         if(!texture){
390                 video::SColor color(255,80,58,37);
391                 core::rect<s32> rect(0, 0, screensize.X, screensize.Y);
392                 driver->draw2DRectangle(color, rect, NULL);
393                 return;
394         }
395
396         /* Draw background texture */
397         v2u32 sourcesize = texture->getOriginalSize();
398         driver->draw2DImage(texture,
399                 core::rect<s32>(0, 0, screensize.X, screensize.Y),
400                 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
401                 NULL, NULL, true);
402 }
403
404 /******************************************************************************/
405 void GUIEngine::drawOverlay(video::IVideoDriver* driver)
406 {
407         v2u32 screensize = driver->getScreenSize();
408
409         video::ITexture* texture = m_textures[TEX_LAYER_OVERLAY];
410
411         /* If no texture, draw background of solid color */
412         if(!texture)
413                 return;
414
415         /* Draw background texture */
416         v2u32 sourcesize = texture->getOriginalSize();
417         driver->draw2DImage(texture,
418                 core::rect<s32>(0, 0, screensize.X, screensize.Y),
419                 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
420                 NULL, NULL, true);
421 }
422
423 /******************************************************************************/
424 void GUIEngine::drawHeader(video::IVideoDriver* driver)
425 {
426         core::dimension2d<u32> screensize = driver->getScreenSize();
427
428         video::ITexture* texture = m_textures[TEX_LAYER_HEADER];
429
430         /* If no texture, draw nothing */
431         if(!texture)
432                 return;
433
434         f32 mult = (((f32)screensize.Width / 2.0)) /
435                         ((f32)texture->getOriginalSize().Width);
436
437         v2s32 splashsize(((f32)texture->getOriginalSize().Width) * mult,
438                         ((f32)texture->getOriginalSize().Height) * mult);
439
440         // Don't draw the header is there isn't enough room
441         s32 free_space = (((s32)screensize.Height)-320)/2;
442
443         if (free_space > splashsize.Y) {
444                 core::rect<s32> splashrect(0, 0, splashsize.X, splashsize.Y);
445                 splashrect += v2s32((screensize.Width/2)-(splashsize.X/2),
446                                 ((free_space/2)-splashsize.Y/2)+10);
447
448         video::SColor bgcolor(255,50,50,50);
449
450         driver->draw2DImage(texture, splashrect,
451                 core::rect<s32>(core::position2d<s32>(0,0),
452                 core::dimension2di(texture->getOriginalSize())),
453                 NULL, NULL, true);
454         }
455 }
456
457 /******************************************************************************/
458 void GUIEngine::drawFooter(video::IVideoDriver* driver)
459 {
460         core::dimension2d<u32> screensize = driver->getScreenSize();
461
462         video::ITexture* texture = m_textures[TEX_LAYER_FOOTER];
463
464         /* If no texture, draw nothing */
465         if(!texture)
466                 return;
467
468         f32 mult = (((f32)screensize.Width)) /
469                         ((f32)texture->getOriginalSize().Width);
470
471         v2s32 footersize(((f32)texture->getOriginalSize().Width) * mult,
472                         ((f32)texture->getOriginalSize().Height) * mult);
473
474         // Don't draw the footer if there isn't enough room
475         s32 free_space = (((s32)screensize.Height)-320)/2;
476
477         if (free_space > footersize.Y) {
478                 core::rect<s32> rect(0,0,footersize.X,footersize.Y);
479                 rect += v2s32(screensize.Width/2,screensize.Height-footersize.Y);
480                 rect -= v2s32(footersize.X/2, 0);
481
482                 driver->draw2DImage(texture, rect,
483                         core::rect<s32>(core::position2d<s32>(0,0),
484                         core::dimension2di(texture->getOriginalSize())),
485                         NULL, NULL, true);
486         }
487 }
488
489 /******************************************************************************/
490 bool GUIEngine::setTexture(texture_layer layer,std::string texturepath) {
491
492         video::IVideoDriver* driver = m_device->getVideoDriver();
493         assert(driver != 0);
494
495         if (m_textures[layer] != 0)
496         {
497                 driver->removeTexture(m_textures[layer]);
498                 m_textures[layer] = 0;
499         }
500
501         if ((texturepath == "") || !fs::PathExists(texturepath))
502                 return false;
503
504         m_textures[layer] = driver->getTexture(texturepath.c_str());
505
506         if (m_textures[layer] == 0) return false;
507
508         return true;
509 }
510
511 /******************************************************************************/
512 bool GUIEngine::downloadFile(std::string url,std::string target) {
513 #if USE_CURL
514         bool retval = true;
515
516         FILE* targetfile = fopen(target.c_str(),"wb");
517
518         if (targetfile) {
519                 HTTPFetchRequest fetchrequest;
520                 HTTPFetchResult fetchresult;
521                 fetchrequest.url = url;
522                 fetchrequest.caller = HTTPFETCH_SYNC;
523                 httpfetch_sync(fetchrequest,fetchresult);
524
525                 if (fetchresult.succeeded) {
526                         if (fwrite(fetchresult.data.c_str(),1,fetchresult.data.size(),targetfile) != fetchresult.data.size()) {
527                                 retval = false;
528                         }
529                 }
530                 else {
531                         retval = false;
532                 }
533                 fclose(targetfile);
534         }
535         else {
536                 retval = false;
537         }
538
539         return retval;
540 #else
541         return false;
542 #endif
543 }
544
545 /******************************************************************************/
546 void GUIEngine::setTopleftText(std::string append) {
547         std::string toset = std::string("Minetest ") + minetest_version_hash;
548
549         if (append != "") {
550                 toset += " / ";
551                 toset += append;
552         }
553
554         m_irr_toplefttext->setText(narrow_to_wide(toset).c_str());
555 }
556
557 /******************************************************************************/
558 s32 GUIEngine::playSound(SimpleSoundSpec spec, bool looped)
559 {
560         s32 handle = m_sound_manager->playSound(spec, looped);
561         return handle;
562 }
563
564 /******************************************************************************/
565 void GUIEngine::stopSound(s32 handle)
566 {
567         m_sound_manager->stopSound(handle);
568 }
569
570 /******************************************************************************/
571 unsigned int GUIEngine::DoAsync(std::string serialized_fct,
572                 std::string serialized_params) {
573         return m_script->DoAsync(serialized_fct,serialized_params);
574 }