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