-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathPlayState.hx
3484 lines (2967 loc) · 102 KB
/
PlayState.hx
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
package funkin.play;
import flixel.addons.transition.FlxTransitionableState;
import flixel.addons.transition.Transition;
import flixel.FlxCamera;
import flixel.FlxObject;
import flixel.FlxSubState;
import flixel.math.FlxMath;
import flixel.math.FlxPoint;
import flixel.text.FlxText;
import flixel.tweens.FlxTween;
import flixel.ui.FlxBar;
import flixel.util.FlxColor;
import flixel.util.FlxStringUtil;
import flixel.util.FlxTimer;
import funkin.api.newgrounds.NGio;
import funkin.audio.FunkinSound;
import funkin.audio.VoicesGroup;
import funkin.data.dialogue.conversation.ConversationRegistry;
import funkin.data.event.SongEventRegistry;
import funkin.data.notestyle.NoteStyleRegistry;
import funkin.data.song.SongData.SongCharacterData;
import funkin.data.song.SongData.SongEventData;
import funkin.data.song.SongData.SongNoteData;
import funkin.data.song.SongRegistry;
import funkin.data.stage.StageRegistry;
import funkin.graphics.FunkinCamera;
import funkin.graphics.FunkinSprite;
import funkin.Highscore.Tallies;
import funkin.input.PreciseInputManager;
import funkin.modding.events.ScriptEvent;
import funkin.modding.events.ScriptEventDispatcher;
import funkin.play.character.BaseCharacter;
import funkin.play.character.CharacterData.CharacterDataParser;
import funkin.play.components.ComboMilestone;
import funkin.play.components.HealthIcon;
import funkin.play.components.PopUpStuff;
import funkin.play.cutscene.dialogue.Conversation;
import funkin.play.cutscene.VanillaCutscenes;
import funkin.play.cutscene.VideoCutscene;
import funkin.play.notes.NoteDirection;
import funkin.play.notes.notekind.NoteKindManager;
import funkin.play.notes.NoteSprite;
import funkin.play.notes.notestyle.NoteStyle;
import funkin.play.notes.Strumline;
import funkin.play.notes.SustainTrail;
import funkin.play.scoring.Scoring;
import funkin.play.song.Song;
import funkin.play.stage.Stage;
import funkin.save.Save;
import funkin.ui.debug.charting.ChartEditorState;
import funkin.ui.debug.stage.StageOffsetSubState;
import funkin.ui.mainmenu.MainMenuState;
import funkin.ui.MusicBeatSubState;
import funkin.ui.transition.LoadingState;
import funkin.util.SerializerUtil;
import haxe.Int64;
#if FEATURE_DISCORD_RPC
import funkin.api.discord.DiscordClient;
#end
/**
* Parameters used to initialize the PlayState.
*/
typedef PlayStateParams =
{
/**
* The song to play.
*/
targetSong:Song,
/**
* The difficulty to play the song on.
* @default `Constants.DEFAULT_DIFFICULTY`
*/
?targetDifficulty:String,
/**
* The variation to play on.
* @default `Constants.DEFAULT_VARIATION`
*/
?targetVariation:String,
/**
* The instrumental to play with.
* Significant if the `targetSong` supports alternate instrumentals.
* @default `null`
*/
?targetInstrumental:String,
/**
* Whether the song should start in Practice Mode.
* @default `false`
*/
?practiceMode:Bool,
/**
* Whether the song should start in Bot Play Mode.
* @default `false`
*/
?botPlayMode:Bool,
/**
* Whether the song should be in minimal mode.
* @default `false`
*/
?minimalMode:Bool,
/**
* If specified, the game will jump to the specified timestamp after the countdown ends.
* @default `0.0`
*/
?startTimestamp:Float,
/**
* If specified, the game will play the song with the given speed.
* @default `1.0` for 100% speed.
*/
?playbackRate:Float,
/**
* If specified, the game will not load the instrumental or vocal tracks,
* and must be loaded externally.
*/
?overrideMusic:Bool,
/**
* The initial camera follow point.
* Used to persist the position of the `cameraFollowPosition` between levels.
*/
?cameraFollowPoint:FlxPoint,
}
/**
* The gameplay state, where all the rhythm gaming happens.
* SubState so it can be loaded as a child of the chart editor.
*/
class PlayState extends MusicBeatSubState
{
/**
* STATIC VARIABLES
* Static variables should be used for information that must be persisted between states or between resets,
* such as the active song or song playlist.
*/
/**
* The currently active PlayState.
* There should be only one PlayState in existance at a time, we can use a singleton.
*/
public static var instance:PlayState = null;
/**
* This sucks. We need this because FlxG.resetState(); assumes the constructor has no arguments.
* @see https://github.com/HaxeFlixel/flixel/issues/2541
*/
static var lastParams:PlayStateParams = null;
/**
* PUBLIC INSTANCE VARIABLES
* Public instance variables should be used for information that must be reset or dereferenced
* every time the state is changed, but may need to be accessed externally.
*/
/**
* The currently selected stage.
*/
public var currentSong:Song = null;
/**
* The currently selected difficulty.
*/
public var currentDifficulty:String = Constants.DEFAULT_DIFFICULTY;
/**
* The currently selected variation.
*/
public var currentVariation:String = Constants.DEFAULT_VARIATION;
/**
* The currently selected instrumental ID.
* @default `''`
*/
public var currentInstrumental:String = '';
/**
* The currently active Stage. This is the object containing all the props.
*/
public var currentStage:Stage = null;
/**
* Gets set to true when the PlayState needs to reset (player opted to restart or died).
* Gets disabled once resetting happens.
*/
public var needsReset:Bool = false;
/**
* The current 'Blueball Counter' to display in the pause menu.
* Resets when you beat a song or go back to the main menu.
*/
public var deathCounter:Int = 0;
/**
* The player's current health.
*/
public var health:Float = Constants.HEALTH_STARTING;
/**
* The player's current score.
* TODO: Move this to its own class.
*/
public var songScore:Int = 0;
/**
* Start at this point in the song once the countdown is done.
* For example, if `startTimestamp` is `30000`, the song will start at the 30 second mark.
* Used for chart playtesting or practice.
*/
public var startTimestamp:Float = 0.0;
/**
* Play back the song at this speed.
* @default `1.0` for normal speed.
*/
public var playbackRate:Float = 1.0;
/**
* An empty FlxObject contained in the scene.
* The current gameplay camera will always follow this object. Tween its position to move the camera smoothly.
*
* It needs to be an object in the scene for the camera to be configured to follow it.
* We optionally make this a sprite so we can draw a debug graphic with it.
*/
public var cameraFollowPoint:FlxObject;
/**
* An FlxTween that tweens the camera to the follow point.
* Only used when tweening the camera manually, rather than tweening via follow.
*/
public var cameraFollowTween:FlxTween;
/**
* An FlxTween that zooms the camera to the desired amount.
*/
public var cameraZoomTween:FlxTween;
/**
* An FlxTween that changes the additive speed to the desired amount.
*/
public var scrollSpeedTweens:Array<FlxTween> = [];
/**
* The camera follow point from the last stage.
* Used to persist the position of the `cameraFollowPosition` between levels.
*/
public var previousCameraFollowPoint:FlxPoint = null;
/**
* The current camera zoom level without any modifiers applied.
*/
public var currentCameraZoom:Float = FlxCamera.defaultZoom;
/**
* Multiplier for currentCameraZoom for camera bops.
* Lerped back to 1.0x every frame.
*/
public var cameraBopMultiplier:Float = 1.0;
/**
* Default camera zoom for the current stage.
* If we aren't in a stage, just use the default zoom (1.05x).
*/
public var stageZoom(get, never):Float;
function get_stageZoom():Float
{
if (currentStage != null) return currentStage.camZoom;
else
return FlxCamera.defaultZoom * 1.05;
}
/**
* The current HUD camera zoom level.
*
* The camera zoom is increased every beat, and lerped back to this value every frame, creating a smooth 'zoom-in' effect.
*/
public var defaultHUDCameraZoom:Float = FlxCamera.defaultZoom * 1.0;
/**
* Camera bop intensity multiplier.
* Applied to cameraBopMultiplier on camera bops (usually every beat).
* @default `101.5%`
*/
public var cameraBopIntensity:Float = Constants.DEFAULT_BOP_INTENSITY;
/**
* Intensity of the HUD camera zoom.
* Need to make this a multiplier later. Just shoving in 0.015 for now so it doesn't break.
* @default `3.0%`
*/
public var hudCameraZoomIntensity:Float = 0.015 * 2.0;
/**
* How many beats (quarter notes) between camera zooms.
* @default One camera zoom per measure (four beats).
*/
public var cameraZoomRate:Int = Constants.DEFAULT_ZOOM_RATE;
/**
* Whether the game is currently in the countdown before the song resumes.
*/
public var isInCountdown:Bool = false;
/**
* Whether the game is currently in Practice Mode.
* If true, player will not lose gain or lose score from notes.
*/
public var isPracticeMode:Bool = false;
/**
* Whether the game is currently in Bot Play Mode.
* If true, player will not lose gain or lose score from notes.
*/
public var isBotPlayMode:Bool = false;
/**
* Whether the player has dropped below zero health,
* and we are just waiting for an animation to play out before transitioning.
*/
public var isPlayerDying:Bool = false;
/**
* In Minimal Mode, the stage and characters are not loaded and a standard background is used.
*/
public var isMinimalMode:Bool = false;
/**
* Whether the game is currently in an animated cutscene, and gameplay should be stopped.
*/
public var isInCutscene:Bool = false;
/**
* Whether the inputs should be disabled for whatever reason... used for the stage edit lol!
*/
public var disableKeys:Bool = false;
public var isSubState(get, never):Bool;
function get_isSubState():Bool
{
return this._parentState != null;
}
public var isChartingMode(get, never):Bool;
function get_isChartingMode():Bool
{
return this._parentState != null && Std.isOfType(this._parentState, ChartEditorState);
}
/**
* The current dialogue.
*/
public var currentConversation:Conversation;
/**
* Key press inputs which have been received but not yet processed.
* These are encoded with an OS timestamp, so they
**/
var inputPressQueue:Array<PreciseInputEvent> = [];
/**
* Key release inputs which have been received but not yet processed.
* These are encoded with an OS timestamp, so they
**/
var inputReleaseQueue:Array<PreciseInputEvent> = [];
/**
* If we just unpaused the game, we shouldn't be able to pause again for one frame.
*/
var justUnpaused:Bool = false;
/**
* PRIVATE INSTANCE VARIABLES
* Private instance variables should be used for information that must be reset or dereferenced
* every time the state is reset, but should not be accessed externally.
*/
/**
* The Array containing the upcoming song events.
* The `update()` function regularly shifts these out to trigger events.
*/
var songEvents:Array<SongEventData>;
/**
* If true, the player is allowed to pause the game.
* Disabled during the ending of a song.
*/
var mayPauseGame:Bool = true;
/**
* The displayed value of the player's health.
* Used to provide smooth animations based on linear interpolation of the player's health.
*/
var healthLerp:Float = Constants.HEALTH_STARTING;
/**
* How long the user has held the "Skip Video Cutscene" button for.
*/
var skipHeldTimer:Float = 0;
/**
* Whether the PlayState was started with instrumentals and vocals already provided.
* Used by the chart editor to prevent replacing the music.
*/
var overrideMusic:Bool = false;
/**
* Forcibly disables all update logic while the game moves back to the Menu state.
* This is used only when a critical error occurs and the game absolutely cannot continue.
*/
var criticalFailure:Bool = false;
/**
* False as long as the countdown has not finished yet.
*/
var startingSong:Bool = false;
/**
* Track if we currently have the music paused for a Pause substate, so we can unpause it when we return.
*/
var musicPausedBySubState:Bool = false;
/**
* Track any camera tweens we've paused for a Pause substate, so we can unpause them when we return.
*/
var cameraTweensPausedBySubState:List<FlxTween> = new List<FlxTween>();
/**
* False until `create()` has completed.
*/
var initialized:Bool = false;
/**
* A group of audio tracks, used to play the song's vocals.
*/
public var vocals:VoicesGroup;
#if FEATURE_DISCORD_RPC
// Discord RPC variables
var discordRPCAlbum:String = '';
var discordRPCIcon:String = '';
#end
/**
* RENDER OBJECTS
*/
/**
* The FlxText which displays the current score.
*/
var scoreText:FlxText;
/**
* The bar which displays the player's health.
* Dynamically updated based on the value of `healthLerp` (which is based on `health`).
*/
public var healthBar:FlxBar;
/**
* The background image used for the health bar.
* Emma says the image is slightly skewed so I'm leaving it as an image instead of a `createGraphic`.
*/
public var healthBarBG:FunkinSprite;
/**
* The health icon representing the player.
*/
public var iconP1:HealthIcon;
/**
* The health icon representing the opponent.
*/
public var iconP2:HealthIcon;
/**
* The sprite group containing active player's strumline notes.
*/
public var playerStrumline:Strumline;
/**
* The sprite group containing opponent's strumline notes.
*/
public var opponentStrumline:Strumline;
/**
* The camera which contains, and controls visibility of, the user interface elements.
*/
public var camHUD:FlxCamera;
/**
* The camera which contains, and controls visibility of, the stage and characters.
*/
public var camGame:FlxCamera;
/**
* Simple helper debug variable, to be able to move the camera around for debug purposes
* without worrying about the camera tweening back to the follow point.
*/
public var debugUnbindCameraZoom:Bool = false;
/**
* The camera which contains, and controls visibility of, a video cutscene, dialogue, pause menu and sticker transition.
*/
public var camCutscene:FlxCamera;
/**
* The combo popups. Includes the real-time combo counter and the rating.
*/
public var comboPopUps:PopUpStuff;
/**
* PROPERTIES
*/
/**
* If a substate is rendering over the PlayState, it is paused and normal update logic is skipped.
* Examples include:
* - The Pause screen is open.
* - The Game Over screen is open.
* - The Chart Editor screen is open.
*/
var isGamePaused(get, never):Bool;
function get_isGamePaused():Bool
{
// Note: If there is a substate which requires the game to act unpaused,
// this should be changed to include something like `&& Std.isOfType()`
return this.subState != null;
}
var isExitingViaPauseMenu(get, never):Bool;
function get_isExitingViaPauseMenu():Bool
{
if (this.subState == null) return false;
if (!Std.isOfType(this.subState, PauseSubState)) return false;
var pauseSubState:PauseSubState = cast this.subState;
return !pauseSubState.allowInput;
}
/**
* Data for the current difficulty for the current song.
* Includes chart data, scroll speed, and other information.
*/
public var currentChart(get, never):SongDifficulty;
function get_currentChart():SongDifficulty
{
if (currentSong == null || currentDifficulty == null) return null;
return currentSong.getDifficulty(currentDifficulty, currentVariation);
}
/**
* The internal ID of the currently active Stage.
* Used to retrieve the data required to build the `currentStage`.
*/
public var currentStageId(get, never):String;
function get_currentStageId():String
{
if (currentChart == null || currentChart.stage == null || currentChart.stage == '') return Constants.DEFAULT_STAGE;
return currentChart.stage;
}
/**
* The length of the current song, in milliseconds.
*/
var currentSongLengthMs(get, never):Float;
function get_currentSongLengthMs():Float
{
return FlxG?.sound?.music?.length;
}
// TODO: Refactor or document
var generatedMusic:Bool = false;
var skipEndingTransition:Bool = false;
static final BACKGROUND_COLOR:FlxColor = FlxColor.BLACK;
/**
* Instantiate a new PlayState.
* @param params The parameters used to initialize the PlayState.
* Includes information about what song to play and more.
*/
public function new(params:PlayStateParams)
{
super();
// Validate parameters.
if (params == null && lastParams == null)
{
throw 'PlayState constructor called with no available parameters.';
}
else if (params == null)
{
trace('WARNING: PlayState constructor called with no parameters. Reusing previous parameters.');
params = lastParams;
}
else
{
lastParams = params;
}
// Apply parameters.
currentSong = params.targetSong;
if (params.targetDifficulty != null) currentDifficulty = params.targetDifficulty;
if (params.targetVariation != null) currentVariation = params.targetVariation;
if (params.targetInstrumental != null) currentInstrumental = params.targetInstrumental;
isPracticeMode = params.practiceMode ?? false;
isBotPlayMode = params.botPlayMode ?? false;
isMinimalMode = params.minimalMode ?? false;
startTimestamp = params.startTimestamp ?? 0.0;
playbackRate = params.playbackRate ?? 1.0;
overrideMusic = params.overrideMusic ?? false;
previousCameraFollowPoint = params.cameraFollowPoint;
// Don't do anything else here! Wait until create() when we attach to the camera.
}
/**
* Called when the PlayState is switched to.
*/
public override function create():Void
{
if (instance != null)
{
// TODO: Do something in this case? IDK.
trace('WARNING: PlayState instance already exists. This should not happen.');
}
instance = this;
if (!assertChartExists()) return;
// TODO: Add something to toggle this on!
if (false)
{
// Displays the camera follow point as a sprite for debug purposes.
var cameraFollowPoint = new FunkinSprite(0, 0);
cameraFollowPoint.makeSolidColor(8, 8, 0xFF00FF00);
cameraFollowPoint.visible = false;
cameraFollowPoint.zIndex = 1000000;
this.cameraFollowPoint = cameraFollowPoint;
}
else
{
// Camera follow point is an invisible point in space.
cameraFollowPoint = new FlxObject(0, 0);
}
// Reduce physics accuracy (who cares!!!) to improve animation quality.
FlxG.fixedTimestep = false;
// This state receives update() even when a substate is active.
this.persistentUpdate = true;
// This state receives draw calls even when a substate is active.
this.persistentDraw = true;
// Stop any pre-existing music.
if (!overrideMusic && FlxG.sound.music != null) FlxG.sound.music.stop();
// Prepare the current song's instrumental and vocals to be played.
if (!overrideMusic && currentChart != null)
{
currentChart.cacheInst(currentInstrumental);
currentChart.cacheVocals();
}
// Prepare the Conductor.
Conductor.instance.forceBPM(null);
if (currentChart.offsets != null)
{
Conductor.instance.instrumentalOffset = currentChart.offsets.getInstrumentalOffset(currentInstrumental);
}
Conductor.instance.mapTimeChanges(currentChart.timeChanges);
var pre:Float = (Conductor.instance.beatLengthMs * -5) + startTimestamp;
trace('Attempting to start at ' + pre);
Conductor.instance.update(pre);
// The song is now loaded. We can continue to initialize the play state.
initCameras();
initHealthBar();
if (!isMinimalMode)
{
initStage();
initCharacters();
}
else
{
initMinimalMode();
}
initStrumlines();
initPopups();
#if FEATURE_DISCORD_RPC
// Initialize Discord Rich Presence.
initDiscord();
#end
// Read the song's note data and pass it to the strumlines.
generateSong();
// Reset the camera's zoom and force it to focus on the camera follow point.
resetCamera();
initPreciseInputs();
FlxG.worldBounds.set(0, 0, FlxG.width, FlxG.height);
// The song is loaded and in the process of starting.
// This gets set back to false when the chart actually starts.
startingSong = true;
// TODO: We hardcoded the transition into Winter Horrorland. Do this with a ScriptedSong instead.
if ((currentSong?.id ?? '').toLowerCase() == 'winter-horrorland')
{
// VanillaCutscenes will call startCountdown later.
VanillaCutscenes.playHorrorStartCutscene();
}
else
{
// Call a script event to start the countdown.
// Songs with cutscenes should call event.cancel().
// As long as they call `PlayState.instance.startCountdown()` later, the countdown will start.
startCountdown();
}
// Do this last to prevent beatHit from being called before create() is done.
super.create();
leftWatermarkText.cameras = [camHUD];
rightWatermarkText.cameras = [camHUD];
// Initialize some debug stuff.
#if FEATURE_DEBUG_FUNCTIONS
// Display the version number (and git commit hash) in the bottom right corner.
this.rightWatermarkText.text = Constants.VERSION;
FlxG.console.registerObject('playState', this);
#end
initialized = true;
// This step ensures z-indexes are applied properly,
// and it's important to call it last so all elements get affected.
refresh();
}
function assertChartExists():Bool
{
// Returns null if the song failed to load or doesn't have the selected difficulty.
if (currentSong == null || currentChart == null || currentChart.notes == null)
{
// We have encountered a critical error. Prevent Flixel from trying to run any gameplay logic.
criticalFailure = true;
// Choose an error message.
var message:String = 'There was a critical error. Click OK to return to the main menu.';
if (currentSong == null)
{
message = 'There was a critical error loading this song\'s chart. Click OK to return to the main menu.';
}
else if (currentDifficulty == null)
{
message = 'There was a critical error selecting a difficulty for this song. Click OK to return to the main menu.';
}
else if (currentChart == null)
{
message = 'There was a critical error retrieving data for this song on "$currentDifficulty" difficulty with variation "$currentVariation". Click OK to return to the main menu.';
}
else if (currentChart.notes == null)
{
message = 'There was a critical error retrieving note data for this song on "$currentDifficulty" difficulty with variation "$currentVariation". Click OK to return to the main menu.';
}
// Display a popup. This blocks the application until the user clicks OK.
lime.app.Application.current.window.alert(message, 'Error loading PlayState');
// Force the user back to the main menu.
if (isSubState)
{
this.close();
}
else
{
this.remove(currentStage);
FlxG.switchState(() -> new MainMenuState());
}
return false;
}
return true;
}
public override function update(elapsed:Float):Void
{
// TOTAL: 9.42% CPU Time when profiled in VS 2019.
if (criticalFailure) return;
super.update(elapsed);
var list = FlxG.sound.list;
updateHealthBar();
updateScoreText();
// Handle restarting the song when needed (player death or pressing Retry)
if (needsReset)
{
if (!assertChartExists()) return;
prevScrollTargets = [];
dispatchEvent(new ScriptEvent(SONG_RETRY));
resetCamera();
var fromDeathState = isPlayerDying;
persistentUpdate = true;
persistentDraw = true;
startingSong = true;
isPlayerDying = false;
inputSpitter = [];
// Reset music properly.
if (FlxG.sound.music != null)
{
FlxG.sound.music.time = startTimestamp - Conductor.instance.combinedOffset;
FlxG.sound.music.pitch = playbackRate;
FlxG.sound.music.pause();
}
if (!overrideMusic)
{
// Stop the vocals if they already exist.
if (vocals != null) vocals.stop();
vocals = currentChart.buildVocals(currentInstrumental);
if (vocals.members.length == 0)
{
trace('WARNING: No vocals found for this song.');
}
}
vocals.pause();
vocals.time = 0 - Conductor.instance.combinedOffset;
if (FlxG.sound.music != null) FlxG.sound.music.volume = 1;
vocals.volume = 1;
vocals.playerVolume = 1;
vocals.opponentVolume = 1;
if (currentStage != null) currentStage.resetStage();
if (!fromDeathState)
{
playerStrumline.vwooshNotes();
opponentStrumline.vwooshNotes();
}
playerStrumline.clean();
opponentStrumline.clean();
// Delete all notes and reset the arrays.
regenNoteData();
// Reset camera zooming
cameraBopIntensity = Constants.DEFAULT_BOP_INTENSITY;
hudCameraZoomIntensity = (cameraBopIntensity - 1.0) * 2.0;
cameraZoomRate = Constants.DEFAULT_ZOOM_RATE;
health = Constants.HEALTH_STARTING;
songScore = 0;
Highscore.tallies.combo = 0;
Countdown.performCountdown();
needsReset = false;
}
// Update the conductor.
if (startingSong)
{
if (isInCountdown)
{
// Do NOT apply offsets at this point, because they already got applied the previous frame!
Conductor.instance.update(Conductor.instance.songPosition + elapsed * 1000, false);
if (Conductor.instance.songPosition >= (startTimestamp + Conductor.instance.combinedOffset))
{
trace("started song at " + Conductor.instance.songPosition);
startSong();
}
}
}
else
{
if (Constants.EXT_SOUND == 'mp3')
{
Conductor.instance.formatOffset = Constants.MP3_DELAY_MS;
}
else
{
Conductor.instance.formatOffset = 0.0;
}
Conductor.instance.update(); // Normal conductor update.
}
var androidPause:Bool = false;
#if android
androidPause = FlxG.android.justPressed.BACK;
#end
// Attempt to pause the game.
if ((controls.PAUSE || androidPause) && isInCountdown && mayPauseGame && !justUnpaused)
{
var event = new PauseScriptEvent(FlxG.random.bool(1 / 1000));
dispatchEvent(event);
if (!event.eventCanceled)
{
// Pause updates while the substate is open, preventing the game state from advancing.
persistentUpdate = false;
// Enable drawing while the substate is open, allowing the game state to be shown behind the pause menu.
persistentDraw = true;
// There is a 1/1000 change to use a special pause menu.
// This prevents the player from resuming, but that's the point.
// It's a reference to Gitaroo Man, which doesn't let you pause the game.
if (!isSubState && event.gitaroo)
{
this.remove(currentStage);
FlxG.switchState(() -> new GitarooPause(
{
targetSong: currentSong,
targetDifficulty: currentDifficulty,
targetVariation: currentVariation,
}));
}
else
{
var boyfriendPos:FlxPoint = new FlxPoint(0, 0);
// Prevent the game from crashing if Boyfriend isn't present.
if (currentStage != null && currentStage.getBoyfriend() != null)
{
boyfriendPos = currentStage.getBoyfriend().getScreenPosition();
}
var pauseSubState:FlxSubState = new PauseSubState({mode: isChartingMode ? Charting : Standard});
FlxTransitionableState.skipNextTransIn = true;
FlxTransitionableState.skipNextTransOut = true;
pauseSubState.camera = camCutscene;
openSubState(pauseSubState);
// boyfriendPos.put(); // TODO: Why is this here?
}
#if FEATURE_DISCORD_RPC
DiscordClient.instance.setPresence(
{
details: 'Paused - ${buildDiscordRPCDetails()}',
state: buildDiscordRPCState(),
largeImageKey: discordRPCAlbum,
smallImageKey: discordRPCIcon
});
#end
}
}
// Cap health.
if (health > Constants.HEALTH_MAX) health = Constants.HEALTH_MAX;
if (health < Constants.HEALTH_MIN) health = Constants.HEALTH_MIN;
// Apply camera zoom + multipliers.
if (subState == null && cameraZoomRate > 0.0) // && !isInCutscene)
{
cameraBopMultiplier = FlxMath.lerp(1.0, cameraBopMultiplier, 0.95); // Lerp bop multiplier back to 1.0x
var zoomPlusBop = currentCameraZoom * cameraBopMultiplier; // Apply camera bop multiplier.
if (!debugUnbindCameraZoom) FlxG.camera.zoom = zoomPlusBop; // Actually apply the zoom to the camera.
camHUD.zoom = FlxMath.lerp(defaultHUDCameraZoom, camHUD.zoom, 0.95);
}
if (currentStage != null && currentStage.getBoyfriend() != null)
{
FlxG.watch.addQuick('bfAnim', currentStage.getBoyfriend().getCurrentAnimation());
}
FlxG.watch.addQuick('health', health);
FlxG.watch.addQuick('cameraBopIntensity', cameraBopIntensity);
// TODO: Add a song event for Handle GF dance speed.