forked from stepmania/stepmania
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScreenManager.cpp
1079 lines (931 loc) · 31.1 KB
/
ScreenManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* We maintain a pool of "prepared" screens, which are screens previously loaded
* to be available on demand.
*
* When a screen pops off the stack that's in g_setPersistantScreens, it goes to
* the prepared list. If that screen is used again before it's deleted, it'll be
* reused.
*
* Typically, the first screen in a group will prepare all of the nearby screens it
* may load. When it loads one, the prepared screen will be used.
*
* A group of screens may only want to preload some screens, and not others,
* while still considering those screens part of the same group. For example,
* an attract loop typically has several very lightweight screens and a few
* expensive screens. Preloading the lightweight screens can improve responsiveness,
* but preloading the expensive screens may use too much memory and take too long
* to load all at once. By calling GroupScreen(), entering these screens will not
* trigger cleanup.
*
* Example uses:
* - ScreenOptions1 preloads ScreenOptions2, and persists both. Moving from Options1
* and Options2 and back is instant and reuses both.
* - ScreenMenu groups and persists itself and ScreenSubmenu. ScreenSubmenu
* is not preloaded, so it will be loaded on demand the first time it's used,
* but will remain loaded if it returns to ScreenMenu.
* - ScreenSelectMusic groups itself and ScreenPlayerOptions, and persists only
* ScreenSelectMusic. This will cause SSMusic will be loaded once, and SPO to
* be loaded on demand.
* - ScreenAttract1 preloads and persists ScreenAttract1, 3, 5 and 7, and groups 1
* through 7. 1, 3, 5 and 7 will remain in memory; the rest will be loaded on
* demand.
*
* If a screen is added to the screen stack that isn't in the current screen group
* (added to by GroupScreen), the screen group is reset: all prepared screens are
* unloaded and the persistence list is cleared.
*
* Note that not all screens yet support reuse in this way; proper use of BeginScreen
* is required. This will misbehave if a screen pushes another screen that's already
* in use lower on the stack, but that's not useful; it would allow infinite screen
* recursion.
*
* SM_GainFocus/SM_LoseFocus: These are sent to screens when they become the
* topmost screen, or stop being the topmost screen.
*
* A few subtleties:
*
* With delayed screens (eg. ScreenGameplay being pre-loaded by ScreenStage), SM_GainFocus
* isn't sent until the loaded screen actually is activated (put on the stack).
*
* With normal screen loads, the new screen is loaded before the old screen is destroyed.
* This means that the old dtor is called *after* the new ctor. If some global properties
* (eg. GAMESTATE) are being unset by the old screen's destructor, and set by the new
* screen's constructor, they'll happen in the wrong order. Use SM_GainFocus and
* SM_LoseFocus, instead.
*
* SM_LoseFocus is always sent after SM_GainFocus, and vice-versa: you can't gain focus
* if you already have it, and you can't lose focus if you don't have it.
*/
#include "global.h"
#include "ScreenManager.h"
#include "Preference.h"
#include "RageLog.h"
#include "RageUtil.h"
#include "GameSoundManager.h"
#include "RageDisplay.h"
#include "SongManager.h"
#include "RageTextureManager.h"
#include "ThemeManager.h"
#include "FontManager.h"
#include "Screen.h"
#include "ScreenDimensions.h"
#include "ActorUtil.h"
#include "Sprite.h"
#include "InputEventPlus.h"
using std::vector;
ScreenManager* SCREENMAN = nullptr; // global and accessible from anywhere in our program
static Preference<bool> g_bDelayedScreenLoad( "DelayedScreenLoad", false );
//static Preference<bool> g_bPruneFonts( "PruneFonts", true );
// Screen registration
static std::unordered_map<std::string,CreateScreenFn> *g_pmapRegistrees = nullptr;
/** @brief Utility functions for the ScreenManager. */
namespace ScreenManagerUtil
{
// in draw order first to last
struct LoadedScreen
{
Screen *m_pScreen;
/* Normally true. If false, the screen is owned by another screen
* and was given to us for use, and it's not ours to free. */
bool m_bDeleteWhenDone;
ScreenMessage m_SendOnPop;
LoadedScreen()
{
m_pScreen = nullptr;
m_bDeleteWhenDone = true;
m_SendOnPop = SM_None;
}
};
Actor *g_pSharedBGA; // BGA object that's persistent between screens
std::string m_sPreviousTopScreen;
vector<LoadedScreen> g_ScreenStack; // bottommost to topmost
vector<Screen*> g_OverlayScreens;
std::set<std::string> g_setGroupedScreens;
std::set<std::string> g_setPersistantScreens;
vector<LoadedScreen> g_vPreparedScreens;
vector<Actor*> g_vPreparedBackgrounds;
// Add a screen to g_ScreenStack. This is the only function that adds to g_ScreenStack.
void PushLoadedScreen( const LoadedScreen &ls )
{
LOG->Trace( "PushScreen: \"%s\"", ls.m_pScreen->GetName().c_str() );
LOG->MapLog( "ScreenManager::TopScreen", "Top Screen: %s", ls.m_pScreen->GetName().c_str() );
// Be sure to push the screen first, so GetTopScreen returns the screen
// during BeginScreen.
g_ScreenStack.push_back( ls );
// Set the name of the loading screen.
{
LuaThreadVariable var1( "PreviousScreen", m_sPreviousTopScreen );
LuaThreadVariable var2( "LoadingScreen", ls.m_pScreen->GetName() );
ls.m_pScreen->BeginScreen();
}
// If this is the new top screen, save the name.
if( g_ScreenStack.size() == 1 )
m_sPreviousTopScreen = ls.m_pScreen->GetName();
SCREENMAN->RefreshCreditsMessages();
SCREENMAN->PostMessageToTopScreen( SM_GainFocus, 0 );
}
bool ScreenIsPrepped( const std::string &sScreenName )
{
for (auto &s: g_vPreparedScreens)
{
if( s.m_pScreen->GetName() == sScreenName )
return true;
}
return false;
}
/* If the named screen is loaded, remove it from the prepared list and
* return it in ls. */
bool GetPreppedScreen( const std::string &sScreenName, LoadedScreen &ls )
{
for (auto s = g_vPreparedScreens.begin(); s != g_vPreparedScreens.end(); ++s)
{
if( s->m_pScreen->GetName() == sScreenName )
{
ls = *s;
g_vPreparedScreens.erase( s );
return true;
}
}
return false;
}
void BeforeDeleteScreen()
{
// Deleting a screen can take enough time to cause a frame skip.
SCREENMAN->ZeroNextUpdate();
}
/* If we're deleting a screen, it's probably releasing texture and other
* resources, so trigger cleanups. */
void AfterDeleteScreen()
{
/* Now that we've actually deleted a screen, it makes sense to clear out
* cached textures. */
TEXTUREMAN->DeleteCachedTextures();
/* Cleanup song data. This can free up a fair bit of memory, so do it
* after deleting screens. */
SONGMAN->Cleanup();
}
/* Take ownership of all screens and backgrounds that are owned by
* us (this excludes screens where m_bDeleteWhenDone is false).
* Clear the prepared lists. The contents of apOut must be
* freed by the caller. */
void GrabPreparedActors( vector<Actor*> &apOut )
{
for (auto &s: g_vPreparedScreens)
{
if( s.m_bDeleteWhenDone )
apOut.push_back( s.m_pScreen );
}
g_vPreparedScreens.clear();
for (auto *a: g_vPreparedBackgrounds)
{
apOut.push_back( a );
}
g_vPreparedBackgrounds.clear();
g_setGroupedScreens.clear();
g_setPersistantScreens.clear();
}
/* Called when changing screen groups. Delete all prepared screens,
* reset the screen group and list of persistant screens. */
void DeletePreparedScreens()
{
vector<Actor*> apActorsToDelete;
GrabPreparedActors( apActorsToDelete );
BeforeDeleteScreen();
for (auto *a: apActorsToDelete)
{
Rage::safe_delete( a );
}
AfterDeleteScreen();
}
};
using namespace ScreenManagerUtil;
RegisterScreenClass::RegisterScreenClass( const std::string& sClassName, CreateScreenFn pfn )
{
if( g_pmapRegistrees == nullptr )
{
g_pmapRegistrees = new std::unordered_map<std::string,CreateScreenFn>;
}
auto iter = g_pmapRegistrees->find(sClassName);
ASSERT_M( iter == g_pmapRegistrees->end(), fmt::sprintf("Screen class '%s' already registered.", sClassName.c_str()) );
(*g_pmapRegistrees)[sClassName] = pfn;
}
ScreenManager::ScreenManager()
{
// Register with Lua.
{
Lua *L = LUA->Get();
lua_pushstring( L, "SCREENMAN" );
this->PushSelf( L );
lua_settable( L, LUA_GLOBALSINDEX );
LUA->Release( L );
}
g_pSharedBGA = new Actor;
m_disable_special_keys= false;
m_bReloadOverlayScreensAfterInput= false;
m_bZeroNextUpdate = false;
m_PopTopScreen = SM_Invalid;
m_OnDonePreparingScreen = SM_Invalid;
}
ScreenManager::~ScreenManager()
{
LOG->Trace( "ScreenManager::~ScreenManager()" );
LOG->UnmapLog( "ScreenManager::TopScreen" );
Rage::safe_delete( g_pSharedBGA );
for (auto &stack: g_ScreenStack)
{
if( stack.m_bDeleteWhenDone )
{
Rage::safe_delete( stack.m_pScreen );
}
}
g_ScreenStack.clear();
DeletePreparedScreens();
for (auto *screen: g_OverlayScreens)
{
Rage::safe_delete( screen );
}
g_OverlayScreens.clear();
// Unregister with Lua.
LUA->UnsetGlobal( "SCREENMAN" );
}
// This is called when we start up, and when the theme changes or is reloaded.
void ScreenManager::ThemeChanged()
{
LOG->Trace( "ScreenManager::ThemeChanged" );
// reload common sounds
m_soundStart.Load( THEME->GetPathS("Common","start") );
m_soundCoin.Load( THEME->GetPathS("Common","coin"), true );
m_soundCancel.Load( THEME->GetPathS("Common","cancel"), true );
m_soundInvalid.Load( THEME->GetPathS("Common","invalid") );
m_soundScreenshot.Load( THEME->GetPathS("Common","screenshot") );
// reload song manager colors (to avoid crashes) -aj
SONGMAN->ResetGroupColors();
ReloadOverlayScreens();
// force recreate of new BGA
Rage::safe_delete( g_pSharedBGA );
g_pSharedBGA = new Actor;
}
void ScreenManager::ReloadOverlayScreens()
{
// unload overlay screens
for (auto *screen: g_OverlayScreens)
{
Rage::safe_delete( screen );
}
g_OverlayScreens.clear();
// reload overlay screens
std::string sOverlays = THEME->GetMetric( "Common","OverlayScreens" );
auto asOverlays = Rage::split(sOverlays, ",");
for (auto &overlay: asOverlays)
{
Screen *pScreen = MakeNewScreen( overlay );
if(pScreen)
{
LuaThreadVariable var2( "LoadingScreen", pScreen->GetName() );
pScreen->BeginScreen();
g_OverlayScreens.push_back( pScreen );
}
}
this->RefreshCreditsMessages();
}
void ScreenManager::ReloadOverlayScreensAfterInputFinishes()
{
m_bReloadOverlayScreensAfterInput= true;
}
Screen *ScreenManager::GetTopScreen()
{
if( g_ScreenStack.empty() )
return nullptr;
return g_ScreenStack[g_ScreenStack.size()-1].m_pScreen;
}
Screen* ScreenManager::GetSubTopScreen()
{
if(g_ScreenStack.size() < 2)
{
return nullptr;
}
return g_ScreenStack[g_ScreenStack.size()-2].m_pScreen;
}
Screen *ScreenManager::GetScreen( int iPosition )
{
if( iPosition >= (int) g_ScreenStack.size() )
return nullptr;
return g_ScreenStack[iPosition].m_pScreen;
}
bool ScreenManager::AllowOperatorMenuButton() const
{
auto canAccessOpMenu = [](LoadedScreen const &s) {
return s.m_pScreen->AllowOperatorMenuButton();
};
return std::all_of(g_ScreenStack.begin(), g_ScreenStack.end(), canAccessOpMenu);
}
bool ScreenManager::IsScreenNameValid(std::string const& name) const
{
if(name.empty() || !THEME->HasMetric(name, "Class"))
{
return false;
}
std::string class_name = THEME->GetMetric(name, "Class");
return g_pmapRegistrees->find(class_name) != g_pmapRegistrees->end();
}
bool ScreenManager::IsStackedScreen( const Screen *pScreen ) const
{
auto isStacked = [pScreen](ScreenManagerUtil::LoadedScreen const &stack) {
return stack.m_pScreen == pScreen;
};
// True if the screen is in the screen stack, but not the first.
return std::any_of(g_ScreenStack.begin() + 1, g_ScreenStack.end(), isStacked);
}
bool ScreenManager::get_input_redirected(PlayerNumber pn)
{
if(pn >= m_input_redirected.size())
{
return false;
}
return m_input_redirected[pn];
}
void ScreenManager::set_input_redirected(PlayerNumber pn, bool redir)
{
while(pn >= m_input_redirected.size())
{
m_input_redirected.push_back(false);
}
m_input_redirected[pn]= redir;
}
/* Pop the top screen off the stack, sending SM_LoseFocus messages and
* returning the message the popped screen wants sent to the new top
* screen. Does not send SM_GainFocus. */
ScreenMessage ScreenManager::PopTopScreenInternal( bool bSendLoseFocus )
{
if( g_ScreenStack.empty() )
return SM_None;
LoadedScreen ls = g_ScreenStack.back();
g_ScreenStack.erase( g_ScreenStack.end()-1, g_ScreenStack.end() );
if( bSendLoseFocus )
ls.m_pScreen->HandleScreenMessage( SM_LoseFocus );
ls.m_pScreen->EndScreen();
if( g_setPersistantScreens.find(ls.m_pScreen->GetName()) != g_setPersistantScreens.end() )
{
// Move the screen back to the prepared list.
g_vPreparedScreens.push_back( ls );
}
else
{
if( ls.m_bDeleteWhenDone )
{
BeforeDeleteScreen();
Rage::safe_delete( ls.m_pScreen );
AfterDeleteScreen();
}
}
if( g_ScreenStack.size() )
LOG->MapLog( "ScreenManager::TopScreen", "Top Screen: %s", g_ScreenStack.back().m_pScreen->GetName().c_str() );
else
LOG->UnmapLog( "ScreenManager::TopScreen" );
return ls.m_SendOnPop;
}
void ScreenManager::Update( float fDeltaTime )
{
// Pop the top screen, if PopTopScreen was called.
if( m_PopTopScreen != SM_Invalid )
{
ScreenMessage SM = m_PopTopScreen;
m_PopTopScreen = SM_Invalid;
ScreenMessage SM2 = PopTopScreenInternal();
SendMessageToTopScreen( SM_GainFocus );
SendMessageToTopScreen( SM );
SendMessageToTopScreen( SM2 );
}
/* Screens take some time to load. If we don't do this, then screens
* receive an initial update that includes all of the time they spent
* loading, which will chop off their tweens.
*
* We don't want to simply cap update times; for example, the stage
* screen sets a 4 second timer, preps the gameplay screen, and then
* displays the prepped screen after the timer runs out; this lets the
* load time be masked (as long as the load takes less than 4 seconds).
* If we cap that large update delta from the screen load, the update
* to load the new screen will come after 4 seconds plus the load time.
*
* So, let's just zero the first update for every screen. */
ASSERT( !g_ScreenStack.empty() || m_sDelayedScreen != "" ); // Why play the game if there is nothing showing?
Screen* pScreen = g_ScreenStack.empty() ? nullptr : GetTopScreen();
bool bFirstUpdate = pScreen && pScreen->IsFirstUpdate();
/* Loading a new screen can take seconds and cause a big jump on the new
* Screen's first update. Clamp the first update delta so that the
* animations don't jump. */
if( pScreen && m_bZeroNextUpdate )
{
LOG->Trace( "Zeroing this update. Was %f", fDeltaTime );
fDeltaTime = 0;
m_bZeroNextUpdate = false;
}
// Update screens.
{
for (auto &stack: g_ScreenStack)
{
stack.m_pScreen->Update( fDeltaTime );
}
g_pSharedBGA->Update( fDeltaTime );
for (auto *screen: g_OverlayScreens)
{
screen->Update( fDeltaTime );
}
}
/* The music may be started on the first update. If we're reading from a CD,
* it might not start immediately. Make sure we start playing the sound before
* continuing, since it's strange to start rendering before the music starts. */
if( bFirstUpdate )
SOUND->Flush();
/* If we're currently inside a background screen load, and m_sDelayedScreen
* is set, then the screen called SetNewScreen before we finished preparing.
* Postpone it until we're finished loading. */
if( m_sDelayedScreen.size() != 0 )
{
LoadDelayedScreen();
}
}
void ScreenManager::Draw()
{
/* If it hasn't been updated yet, skip the render. We can't call Update(0), since
* that'll confuse the "zero out the next update after loading a screen logic.
* If we don't render, don't call BeginFrame or EndFrame. That way, we won't
* clear the buffer, and we won't wait for vsync. */
if( g_ScreenStack.size() && g_ScreenStack.back().m_pScreen->IsFirstUpdate() )
return;
if( !DISPLAY->BeginFrame() )
return;
DISPLAY->CameraPushMatrix();
DISPLAY->LoadMenuPerspective( 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_CENTER_X, SCREEN_CENTER_Y );
g_pSharedBGA->Draw();
DISPLAY->CameraPopMatrix();
for (auto &stack: g_ScreenStack) // Draw all screens bottom to top
{
stack.m_pScreen->Draw();
}
for (auto *screen: g_OverlayScreens)
{
screen->Draw();
}
DISPLAY->EndFrame();
}
void ScreenManager::Input( const InputEventPlus &input )
{
// LOG->Trace( "ScreenManager::Input( %d-%d, %d-%d, %d-%d, %d-%d )",
// DeviceI.device, DeviceI.button, GameI.controller, GameI.button, MenuI.player, MenuI.button, StyleI.player, StyleI.col );
// First, give overlay screens a shot at the input. If Input returns
// true, it handled the input, so don't pass it further.
for (auto *pScreen: g_OverlayScreens)
{
bool handled= pScreen->Input(input);
// Pass input to the screen and lua. Contention shouldn't be a problem
// because anybody setting an input callback is probably doing it to
// do something in addition to whatever the screen does.
if(pScreen->PassInputToLua(input) || handled)
{
if(m_bReloadOverlayScreensAfterInput)
{
ReloadOverlayScreens();
m_bReloadOverlayScreensAfterInput= false;
}
return;
}
}
// Pass input to the topmost screen. If we have a new top screen pending, don't
// send to the old screen, but do send to overlay screens.
if( m_sDelayedScreen != "" )
return;
if( g_ScreenStack.empty() )
return;
if(!get_input_redirected(input.pn))
{
g_ScreenStack.back().m_pScreen->Input( input );
}
g_ScreenStack.back().m_pScreen->PassInputToLua( input );
}
// Just create a new screen; don't do any associated cleanup.
Screen* ScreenManager::MakeNewScreen( const std::string &sScreenName )
{
RageTimer t;
LOG->Trace( "Loading screen: \"%s\"", sScreenName.c_str() );
std::string class_name = THEME->GetMetric( sScreenName,"Class" );
auto iter = g_pmapRegistrees->find(class_name);
if( iter == g_pmapRegistrees->end() )
{
LuaHelpers::ReportScriptErrorFmt("Screen \"%s\" has an invalid class \"%s\".", sScreenName.c_str(), class_name.c_str());
return nullptr;
}
this->ZeroNextUpdate();
CreateScreenFn pfn = iter->second;
Screen *ret = pfn( sScreenName );
LOG->Trace( "Loaded \"%s\" (\"%s\") in %f", sScreenName.c_str(), class_name.c_str(), t.GetDeltaTime() );
return ret;
}
void ScreenManager::PrepareScreen( const std::string &sScreenName )
{
// If the screen is already prepared, stop.
if( ScreenIsPrepped(sScreenName) )
return;
Screen* pNewScreen = MakeNewScreen(sScreenName);
if(pNewScreen == nullptr)
{
return;
}
{
LoadedScreen ls;
ls.m_pScreen = pNewScreen;
g_vPreparedScreens.push_back( ls );
}
/* Don't delete previously prepared versions of the screen's background,
* and only prepare it if it's different than the current background
* and not already loaded. */
std::string sNewBGA = THEME->GetPathB(sScreenName,"background");
if( !sNewBGA.empty() && sNewBGA != g_pSharedBGA->GetName() )
{
Actor *pNewBGA = nullptr;
for (auto *a: g_vPreparedBackgrounds)
{
if( a->GetName() == sNewBGA )
{
pNewBGA = a;
break;
}
}
// Create the new background before deleting the previous so that we keep
// any common textures loaded.
if( pNewBGA == nullptr )
{
LOG->Trace( "Loading screen background \"%s\"", sNewBGA.c_str() );
Actor *pActor = ActorUtil::MakeActor( sNewBGA );
if( pActor != nullptr )
{
pActor->SetName( sNewBGA );
g_vPreparedBackgrounds.push_back( pActor );
}
}
}
// Prune any unused fonts now that we have had a chance to reference the fonts
/*
if(g_bPruneFonts) {
FONT->PruneFonts();
}
*/
//TEXTUREMAN->DiagnosticOutput();
}
void ScreenManager::GroupScreen( const std::string &sScreenName )
{
g_setGroupedScreens.insert( sScreenName );
}
void ScreenManager::PersistantScreen( const std::string &sScreenName )
{
g_setPersistantScreens.insert( sScreenName );
}
void ScreenManager::SetNewScreen( const std::string &sScreenName )
{
ASSERT( sScreenName != "" );
m_sDelayedScreen = sScreenName;
}
/* Activate the screen and/or its background, if either are loaded.
* Return true if both were activated. */
bool ScreenManager::ActivatePreparedScreenAndBackground( const std::string &sScreenName )
{
bool bLoadedBoth = true;
// Find the prepped screen.
if( GetTopScreen() == nullptr || GetTopScreen()->GetName() != sScreenName )
{
LoadedScreen ls;
if( !GetPreppedScreen(sScreenName, ls) )
{
bLoadedBoth = false;
}
else
{
PushLoadedScreen( ls );
}
}
// Find the prepared shared background (if any), and activate it.
std::string sNewBGA = THEME->GetPathB(sScreenName,"background");
if( sNewBGA != g_pSharedBGA->GetName() )
{
Actor *pNewBGA = nullptr;
if( sNewBGA.empty() )
{
pNewBGA = new Actor;
}
else
{
for (auto a = g_vPreparedBackgrounds.begin(); a != g_vPreparedBackgrounds.end(); ++a)
{
if( (*a)->GetName() == sNewBGA )
{
pNewBGA = *a;
g_vPreparedBackgrounds.erase( a );
break;
}
}
}
/* If the BGA isn't loaded yet, load a dummy actor. If we're not going to use the same
* BGA for the new screen, always move the old BGA back to g_vPreparedBackgrounds now. */
if( pNewBGA == nullptr )
{
bLoadedBoth = false;
pNewBGA = new Actor;
}
/* Move the old background back to the prepared list, or delete it if
* it's a blank actor. */
if( g_pSharedBGA->GetName() == "" )
delete g_pSharedBGA;
else
g_vPreparedBackgrounds.push_back( g_pSharedBGA );
g_pSharedBGA = pNewBGA;
g_pSharedBGA->PlayCommand( "On" );
}
return bLoadedBoth;
}
void ScreenManager::LoadDelayedScreen()
{
std::string sScreenName = m_sDelayedScreen;
m_sDelayedScreen = "";
if(!IsScreenNameValid(sScreenName))
{
LuaHelpers::ReportScriptError("Tried to go to invalid screen: " + sScreenName, "INVALID_SCREEN");
return;
}
// Pop the top screen, if any.
ScreenMessage SM = PopTopScreenInternal();
/* If the screen is already prepared, activate it before performing any
* cleanup, so it doesn't get deleted by cleanup. */
bool bLoaded = ActivatePreparedScreenAndBackground( sScreenName );
vector<Actor*> apActorsToDelete;
if( g_setGroupedScreens.find(sScreenName) == g_setGroupedScreens.end() )
{
/* It's time to delete all old prepared screens. Depending on
* DelayedScreenLoad, we can either delete the screens before or after
* we load the new screen. Either way, we must remove them from the
* prepared list before we prepare new screens.
* If DelayedScreenLoad is true, delete them now; this lowers memory
* requirements, but results in redundant loads as we unload common data. */
if( g_bDelayedScreenLoad )
DeletePreparedScreens();
else
GrabPreparedActors( apActorsToDelete );
}
// If the screen wasn't already prepared, load it.
if( !bLoaded )
{
PrepareScreen( sScreenName );
// Screens may not call SetNewScreen from the ctor or Init(). (We don't do this
// check inside PrepareScreen; that may be called from a thread for concurrent
// loading, and the main thread may call SetNewScreen during that time.)
// Emit an error instead of asserting. -Kyz
if(!m_sDelayedScreen.empty())
{
LuaHelpers::ReportScriptError("Setting a new screen during an InitCommand is not allowed.");
m_sDelayedScreen= "";
}
bLoaded = ActivatePreparedScreenAndBackground( sScreenName );
ASSERT( bLoaded );
}
if( !apActorsToDelete.empty() )
{
BeforeDeleteScreen();
for (auto *a: apActorsToDelete)
{
Rage::safe_delete( a );
}
AfterDeleteScreen();
}
MESSAGEMAN->Broadcast( Message_ScreenChanged );
SendMessageToTopScreen( SM );
}
void ScreenManager::AddNewScreenToTop( const std::string &sScreenName, ScreenMessage SendOnPop )
{
// Load the screen, if it's not already prepared.
PrepareScreen( sScreenName );
// Find the prepped screen.
LoadedScreen ls;
bool screen_load_success = GetPreppedScreen( sScreenName, ls );
ASSERT_M(screen_load_success, fmt::sprintf("ScreenManager::AddNewScreenToTop: Failed to load screen %s", sScreenName.c_str()));
ls.m_SendOnPop = SendOnPop;
if( g_ScreenStack.size() )
g_ScreenStack.back().m_pScreen->HandleScreenMessage( SM_LoseFocus );
PushLoadedScreen( ls );
}
void ScreenManager::PopTopScreen( ScreenMessage SM )
{
ASSERT( g_ScreenStack.size() > 0 );
m_PopTopScreen = SM;
}
/* Clear the screen stack; only used before major, unusual state changes,
* such as resetting the game or jumping to the service menu. Don't call
* from inside a screen. */
void ScreenManager::PopAllScreens()
{
m_input_redirected.clear();
// Make sure only the top screen receives LoseFocus.
bool bFirst = true;
while( !g_ScreenStack.empty() )
{
PopTopScreenInternal( bFirst );
bFirst = false;
}
DeletePreparedScreens();
}
void ScreenManager::PostMessageToTopScreen( ScreenMessage SM, float fDelay )
{
Screen* pTopScreen = GetTopScreen();
if( pTopScreen != nullptr )
pTopScreen->PostScreenMessage( SM, fDelay );
}
void ScreenManager::SendMessageToTopScreen( ScreenMessage SM )
{
Screen* pTopScreen = GetTopScreen();
if( pTopScreen != nullptr )
pTopScreen->HandleScreenMessage( SM );
}
void ScreenManager::SystemMessage( const std::string &sMessage )
{
LOG->Trace( "%s", sMessage.c_str() );
Message msg( "SystemMessage" );
msg.SetParam( "Message", sMessage );
msg.SetParam( "NoAnimate", false );
MESSAGEMAN->Broadcast( msg );
}
void ScreenManager::SystemMessageNoAnimate( const std::string &sMessage )
{
// LOG->Trace( "%s", sMessage.c_str() ); // don't log because the caller is likely calling us every frame
Message msg( "SystemMessage" );
msg.SetParam( "Message", sMessage );
msg.SetParam( "NoAnimate", true );
MESSAGEMAN->Broadcast( msg );
}
void ScreenManager::HideSystemMessage()
{
MESSAGEMAN->Broadcast( "HideSystemMessage" );
}
void ScreenManager::RefreshCreditsMessages()
{
MESSAGEMAN->Broadcast( "RefreshCreditText" );
}
void ScreenManager::ZeroNextUpdate()
{
m_bZeroNextUpdate = true;
/* Loading probably took a little while. Let's reset stats. This prevents us
* from displaying an unnaturally low FPS value, and the next FPS value we
* display will be accurate, which makes skips in the initial tween-ins more
* apparent. */
DISPLAY->ResetStats();
}
/** @brief Offer a quick way to play any critical sound. */
#define PLAY_CRITICAL(snd) \
{ \
RageSoundParams p; \
p.m_bIsCriticalSound = true; \
snd.Play(false, &p); \
}
/* Always play these sounds, even if we're in a silent attract loop. */
void ScreenManager::PlayInvalidSound() { PLAY_CRITICAL(m_soundInvalid); }
void ScreenManager::PlayStartSound() { PLAY_CRITICAL(m_soundStart); }
void ScreenManager::PlayCoinSound() { PLAY_CRITICAL(m_soundCoin); }
void ScreenManager::PlayCancelSound() { PLAY_CRITICAL(m_soundCancel); }
void ScreenManager::PlayScreenshotSound() { PLAY_CRITICAL(m_soundScreenshot); }
#undef PLAY_CRITICAL
void ScreenManager::PlaySharedBackgroundOffCommand()
{
g_pSharedBGA->PlayCommand("Off");
}
// lua start
#include "LuaBinding.h"
/** @brief Allow Lua to have access to the ScreenManager. */
class LunaScreenManager: public Luna<ScreenManager>
{
public:
// Note: PrepareScreen binding is not allowed; loading data inside
// Lua causes the Lua lock to be held for the duration of the load,
// which blocks concurrent rendering
static void ValidateScreenName(lua_State* L, std::string& name)
{
if(name == "")
{
std::string errstr= "Screen name is empty.";
SCREENMAN->SystemMessage(errstr);
luaL_error(L, errstr.c_str());
}
std::string class_name= THEME->GetMetric(name, "Class");
if(g_pmapRegistrees->find(class_name) == g_pmapRegistrees->end())
{
std::string errstr= "Screen \"" + name + "\" has an invalid class \"" + class_name + "\".";
SCREENMAN->SystemMessage(errstr);
luaL_error(L, errstr.c_str());
}
}
static int SetNewScreen( T* p, lua_State *L )
{
std::string screen= SArg(1);
ValidateScreenName(L, screen);
p->SetNewScreen(screen);
COMMON_RETURN_SELF;
}
static int GetTopScreen( T* p, lua_State *L )
{
Actor *pScreen = p->GetTopScreen();
if( pScreen != nullptr )
pScreen->PushSelf(L);
else
lua_pushnil( L );
return 1;
}
static int SystemMessage( T* p, lua_State *L ) { p->SystemMessage( SArg(1) ); COMMON_RETURN_SELF; }
static int ScreenIsPrepped(T*, lua_State* L)
{
lua_pushboolean(L, ScreenManagerUtil::ScreenIsPrepped(SArg(1)));
return 1;
}
static int ScreenClassExists(T*, lua_State* L)
{
lua_pushboolean(L, g_pmapRegistrees->find(SArg(1)) != g_pmapRegistrees->end());
return 1;
}
static int AddNewScreenToTop( T* p, lua_State *L )
{
std::string screen= SArg(1);
ValidateScreenName(L, screen);
ScreenMessage SM = SM_None;
if( lua_gettop(L) >= 2 && !lua_isnil(L,2) )
{
std::string sMessage = SArg(2);
SM = ScreenMessageHelpers::ToScreenMessage( sMessage );
}