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