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