summaryrefslogtreecommitdiff
path: root/include/SSVOpenHexagon/Core/HexagonGame.hpp
blob: f015e859c3431fcc8c20a7717d5af7e18fa9793d (plain)
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
// Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: https://opensource.org/licenses/AFL-3.0

#pragma once

#include "SSVOpenHexagon/Core/CustomTimelineManager.hpp"
#include "SSVOpenHexagon/Core/HGStatus.hpp"
#include "SSVOpenHexagon/Core/RandomNumberGenerator.hpp"
#include "SSVOpenHexagon/Core/Replay.hpp"

#include "SSVOpenHexagon/Data/LevelStatus.hpp"
#include "SSVOpenHexagon/Data/MusicData.hpp"
#include "SSVOpenHexagon/Data/StyleData.hpp"

#include "SSVOpenHexagon/Components/CPlayer.hpp"

#include "SSVOpenHexagon/Utils/Utils.hpp"
#include "SSVOpenHexagon/Utils/LuaWrapper.hpp"
#include "SSVOpenHexagon/Utils/FastVertexVector.hpp"
#include "SSVOpenHexagon/Utils/Timeline2.hpp"

#include "SSVOpenHexagon/Components/CCustomWallManager.hpp"

#include <SSVStart/GameSystem/GameSystem.hpp>
#include <SSVStart/Camera/Camera.hpp>
#include <SSVStart/VertexVector/VertexVector.hpp>

#include <SSVUtils/Core/Common/Frametime.hpp>
#include <SSVUtils/Timeline/Timeline.hpp>

#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/Graphics/Texture.hpp>

#include <SFML/System/Vector2.hpp>
#include <SFML/System/Clock.hpp>

#include <cstdint>
#include <sstream>
#include <unordered_set>
#include <functional>
#include <optional>
#include <vector>
#include <string>

struct ImGuiInputTextCallbackData;

namespace Json {
class Value;
}

namespace ssvuj {
using Obj = Json::Value;
}

namespace ssvs::Input {
class Trigger;
}

namespace hg {

class Audio;
class HGAssets;
class HexagonClient;
struct LevelData;
struct SpeedData;
struct PackData;

namespace Steam {
class steam_manager;
}

namespace Discord {
class discord_manager;
}

class HexagonGame
{
private:
    Steam::steam_manager* steamManager;
    Discord::discord_manager* discordManager;
    bool discordHung{false};
    bool steamHung{false};
    std::int8_t discordAttempt{1};
    std::int8_t steamAttempt{1};

    HGAssets& assets;
    sf::Font& font;
    sf::Font& fontBold;

    Audio* audio;

    const LevelData* levelData;

    ssvs::GameState game;
    ssvs::GameWindow* window;

    HexagonClient* hexagonClient;

    // IMGUI Lua Console
    sf::Clock ilcDeltaClock;
    std::vector<std::string> ilcCmdLog;
    std::vector<std::string> ilcHistory;
    int ilcHistoryPos{-1};
    std::string ilcCmdBuffer;
    std::string ilcTrackBuffer;
    bool ilcShowConsole{false};
    bool ilcShowConsoleNext{false};
    std::vector<std::string> ilcLuaTracked;
    std::vector<std::string> ilcLuaTrackedNames;
    std::vector<std::string> ilcLuaTrackedResults;
    bool debugPause{false};

    std::vector<std::string> execScriptPackPathContext;

public:
    int ilcTextEditCallback(ImGuiInputTextCallbackData* data);

public:
    CPlayer player;
    std::vector<CWall> walls;
    CCustomWallManager cwManager;
    float timeUntilRichPresenceUpdate = 0.f;

private:
    std::optional<ssvs::Camera> backgroundCamera;
    std::optional<ssvs::Camera> overlayCamera;

    struct PreShakeCenters
    {
        sf::Vector2f background;
        sf::Vector2f overlay;
    };

    std::optional<PreShakeCenters> preShakeCenters;


    ssvu::TimelineManager effectTimelineManager;

    const sf::Vector2f centerPos{0.f, 0.f};

    Lua::LuaContext lua;
    std::unordered_set<std::string> calledDeprecatedFunctions;

    LevelStatus levelStatus;
    MusicData musicData;
    StyleData styleData;

    Utils::timeline2 timeline;
    Utils::timeline2_runner timelineRunner;

    Utils::timeline2 eventTimeline;
    Utils::timeline2_runner eventTimelineRunner;

    Utils::timeline2 messageTimeline;
    Utils::timeline2_runner messageTimelineRunner;

    CustomTimelineManager _customTimelineManager;

    sf::Text messageText;
    sf::Text pbText;

    Utils::FastVertexVectorTris flashPolygon;

    struct Particle
    {
        sf::Sprite sprite;
        sf::Vector2f velocity;
        float angularVelocity;
    };

    struct TrailParticle
    {
        sf::Sprite sprite;
        float angle;
    };

    struct SwapParticle
    {
        sf::Sprite sprite;
        sf::Vector2f velocity;
    };

    sf::Texture* txStarParticle;
    sf::Texture* txSmallCircle;

    std::vector<Particle> particles;
    std::vector<TrailParticle> trailParticles;
    std::vector<SwapParticle> swapParticles;
    bool mustSpawnPBParticles{false};

    struct SwapParticleSpawnInfo
    {
        bool ready;
        sf::Vector2f position;
        float angle;
    };

    std::optional<SwapParticleSpawnInfo> swapParticlesSpawnInfo;
    float nextPBParticleSpawn{0.f};
    float pbTextGrowth{0.f};

    sf::Sprite keyIconLeft;
    sf::Sprite keyIconRight;
    sf::Sprite keyIconFocus;
    sf::Sprite keyIconSwap;
    sf::Sprite replayIcon;

    sf::RectangleShape levelInfoRectangle;
    sf::Text levelInfoTextLevel;
    sf::Text levelInfoTextPack;
    sf::Text levelInfoTextAuthor;
    sf::Text levelInfoTextBy;
    sf::Text levelInfoTextDM;

    bool firstPlay{true};
    bool restartFirstTime{true};
    bool inputFocused{false};
    bool inputSwap{false};
    bool mustTakeScreenshot{false};
    bool mustChangeSides{false};
    bool mustStart{false};

    random_number_generator rng;
    HexagonGameStatus status;

    float deathInputIgnore{0.f};

    struct ActiveReplay
    {
        replay_file replayFile;
        replay_player replayPlayer;
        std::string replayPackName;
        std::string replayLevelName;

        explicit ActiveReplay(const replay_file& mReplayFile);
    };

    std::optional<ActiveReplay> activeReplay;

    random_number_generator::seed_type lastSeed{};
    replay_data lastReplayData{};
    bool lastFirstPlay{};
    double lastPlayedScore{};

    std::string restartId;
    float difficultyMult{1};
    int inputImplLastMovement{0};
    int inputMovement{0};
    bool inputImplCW{false};
    bool inputImplCCW{false};
    bool playerNowReadyToSwap{false};

    std::ostringstream os;

    sf::Text fpsText;
    sf::Text timeText;
    sf::Text text;
    sf::Text replayText;

    // Color of the polygon in the center.
    CapColor capColor;

    std::string packId;
    std::string levelId;

    // Lua related methods
    void initLua_Utils();
    void initLua_AudioControl();
    void initLua_MainTimeline();
    void initLua_EventTimeline();
    void initLua_CustomTimelines();
    void initLua_LevelControl();
    void initLua_StyleControl();
    void initLua_WallCreation();
    void initLua_Steam();
    void initLua_CustomWalls();
    void initLua_Deprecated();

    void initLua();
    void runLuaFile(const std::string& mFileName);

    // Wall creation
    void createWall(int mSide, float mThickness, const SpeedData& mSpeed,
        const SpeedData& mCurve, float mHueMod);

public:
    // ------------------------------------------------------------------------
    // Testing-related utilities
    std::function<void(const replay_file&)> onDeathReplayCreated;

    void setMustStart(const bool x);

    bool executeRandomInputs{false};
    bool alwaysSpinRight{false};

    // ------------------------------------------------------------------------
    // Lua stuff

    void initLuaAndPrintDocs();

    void luaExceptionLippincottHandler(const std::string& mName);

    template <typename T, typename... TArgs>
    auto runLuaFunctionIfExists(const std::string& mName, const TArgs&... mArgs)
    try
    {
        return Utils::runLuaFunctionIfExists<T, TArgs...>(lua, mName, mArgs...);
    }
    catch(...)
    {
        luaExceptionLippincottHandler(mName);
        return decltype(Utils::runLuaFunctionIfExists<T, TArgs...>(
            lua, mName, mArgs...)){};
    }

    void raiseWarning(
        const std::string& mFunctionName, const std::string& mAdditionalInfo);

    void setLastReplay(const replay_file& mReplayFile);

private:
    void start();

    void initKeyIcons();
    void initFlashEffect(int r, int g, int b);

    // Fast-forward
    std::optional<double> fastForwardTarget;
    void fastForwardTo(const double target);

    // Advance by ticks
    std::optional<int> advanceTickCount;
    void advanceByTicks(const int nTicks);

    // Update methods
    void update(ssvu::FT mFT, const float timescale);
    void updateInput();
    void updateInput_UpdateJoystickControls();
    void updateInput_UpdateTouchControls();
    void updateInput_ResolveInputImplToInputMovement();
    void updateInput_RecordCurrentInputToLastReplayData();
    void updateWalls(ssvu::FT mFT);
    void updateIncrement();
    void updateEvents(ssvu::FT mFT);
    void updateLevel(ssvu::FT mFT);
    void updateCustomTimelines();
    void updateCustomWalls(ssvu::FT mFT);
    void updatePulse(ssvu::FT mFT);
    void updateBeatPulse(ssvu::FT mFT);
    void updateRotation(ssvu::FT mFT);
    void updateCameraShake(ssvu::FT mFT);
    void updateFlash(ssvu::FT mFT);
    void updatePulse3D(ssvu::FT mFT);
    void updateText(ssvu::FT mFT);
    void updateKeyIcons();
    void updateLevelInfo();
    void updateParticles(ssvu::FT mFT);
    void updateTrailParticles(ssvu::FT mFT);
    void updateSwapParticles(ssvu::FT mFT);

    // Post update methods
    void postUpdate();
    void postUpdate_ImguiLuaConsole();

    // Draw methods
    void draw();

    // Gameplay methods
    void incrementDifficulty();
    void sideChange(unsigned int mSideNumber);

    // Draw methods
    void drawText_TimeAndStatus(const sf::Color& offsetColor);
    void drawText_Message(const sf::Color& offsetColor);
    void drawText_PersonalBest(const sf::Color& offsetColor);
    void drawText();
    void drawKeyIcons();
    void drawLevelInfo();
    void drawParticles();
    void drawTrailParticles();
    void drawSwapParticles();
    void drawImguiLuaConsole();

    // Data-related methods
    void setLevelData(const LevelData& mLevelData, bool mMusicFirstPlay);
    void playLevelMusic();
    void playLevelMusicAtTime(float mSeconds);
    void stopLevelMusic();

    // Message-related methods
    void addMessage(std::string mMessage, double mDuration, bool mSoundToggle);
    void clearMessages();

    enum class CheckScore
    {
        NoLocalProfile,
        Ineligible,
        Invalid,
        Valid,
    };

    // Level/menu loading/unloading/changing
    [[nodiscard]] bool shouldSaveScore();
    void goToMenu(bool mSendScores = true, bool mError = false);

    void invalidateScore(const std::string& mReason);

    [[nodiscard]] bool imguiLuaConsoleHasInput();

    template <typename T>
    auto makeLuaAccessor(T& obj, const std::string& prefix);

    static void nameFormat(std::string& name);
    [[nodiscard]] static std::string diffFormat(float diff);
    [[nodiscard]] static std::string timeFormat(float time);

private:
    void performPlayerSwap(const bool mPlaySound);
    void performPlayerKill();

    Utils::FastVertexVectorTris backgroundTris;
    Utils::FastVertexVectorTris wallQuads;
    Utils::FastVertexVectorTris pivotQuads;
    Utils::FastVertexVectorTris playerTris;
    Utils::FastVertexVectorTris capTris;
    Utils::FastVertexVectorTris wallQuads3D;
    Utils::FastVertexVectorTris pivotQuads3D;
    Utils::FastVertexVectorTris playerTris3D;

public:
    std::function<void(const bool)> fnGoToMenu;

    HexagonGame(Steam::steam_manager* mSteamManager,
        Discord::discord_manager* mDiscordManager, HGAssets& mAssets,
        Audio* mAudio, ssvs::GameWindow* mGameWindow,
        HexagonClient* mHexagonClient);

    ~HexagonGame();

    void refreshTrigger(const ssvs::Input::Trigger& trigger, const int bindID);

    // Gameplay methods
    void newGame(const std::string& mPackId, const std::string& mId,
        bool mFirstPlay, float mDifficultyMult, bool executeLastReplay);

    enum class SaveScoreIfNeededResult
    {
        NoWindow = 0,
        ShouldNotSave = 1,
        NotPersonalBest = 2,
        PersonalBest = 3,
    };

    void death(bool mForce = false);
    void death_shakeCamera();
    void death_flashEffect();
    [[nodiscard]] replay_file death_createReplayFile();
    void death_updateRichPresence();
    [[nodiscard]] SaveScoreIfNeededResult death_saveScoreIfNeeded();
    void death_saveScoreIfNeededAndShowPBEffects();
    void death_sendAndSaveReplay(const replay_file& rf);
    [[nodiscard]] bool death_sendReplay(
        const std::string& levelValidator, const compressed_replay_file& crf);
    [[nodiscard]] bool death_saveReplay(
        const std::string& filename, const compressed_replay_file& crf);

    struct GameExecutionResult
    {
        double playedTimeSeconds;
        double pausedTimeSeconds;
        double totalTimeSeconds;
        float customScore;
    };

    [[nodiscard]] std::optional<GameExecutionResult> executeGameUntilDeath(
        const int maxProcessingSeconds, const float timescale);

    [[nodiscard]] std::optional<GameExecutionResult>
    runReplayUntilDeathAndGetScore(const replay_file& mReplayFile,
        const int maxProcessingSeconds, const float timescale);

    // Other methods
    void executeEvents(ssvuj::Obj& mRoot, float mTime);
    void updateRichPresenceCallbacks();

    [[nodiscard]] bool shouldPlaySounds() const;
    [[nodiscard]] bool shouldPlayMusic() const;
    void playSoundOverride(const std::string& mId);
    void playSoundAbort(const std::string& mId);
    void playPackSoundOverride(
        const std::string& mPackId, const std::string& mId);

    // Graphics-related methods
    void render(sf::Drawable& mDrawable,
        const sf::RenderStates& mStates = sf::RenderStates::Default);

    // Setters
    void setSides(unsigned int mSides);

    // Getters
    [[nodiscard]] ssvs::GameState& getGame() noexcept;
    [[nodiscard]] float getRadius() const noexcept;
    [[nodiscard]] const sf::Color& getColor(int mIdx) const noexcept;
    [[nodiscard]] float getSpeedMultDM() const noexcept;
    [[nodiscard]] float getDelayMultDM() const noexcept;
    [[nodiscard]] float getRotationSpeed() const noexcept;
    [[nodiscard]] unsigned int getSides() const noexcept;
    [[nodiscard]] float getWallSkewLeft() const noexcept;
    [[nodiscard]] float getWallSkewRight() const noexcept;
    [[nodiscard]] float getWallAngleLeft() const noexcept;
    [[nodiscard]] float getWallAngleRight() const noexcept;
    [[nodiscard]] float get3DEffectMult() const noexcept;
    [[nodiscard]] HexagonGameStatus& getStatus() noexcept;
    [[nodiscard]] const HexagonGameStatus& getStatus() const noexcept;
    [[nodiscard]] LevelStatus& getLevelStatus();
    [[nodiscard]] HGAssets& getAssets();
    [[nodiscard]] sf::Color getColorMain() const;
    [[nodiscard]] sf::Color getColorPlayer() const;
    [[nodiscard]] sf::Color getColorPlayerAdjustedForSwap() const;
    [[nodiscard]] sf::Color getColorPlayerTrail() const;
    [[nodiscard]] sf::Color getColorText() const;
    [[nodiscard]] sf::Color getColorCap() const;
    [[nodiscard]] sf::Color getColorWall() const;
    [[nodiscard]] float getMusicDMSyncFactor() const;
    [[nodiscard]] float getOptionalMusicDMSyncFactor() const;

    void refreshMusicPitch();

    // Input
    [[nodiscard]] bool getInputFocused() const;
    [[nodiscard]] float getPlayerSpeedMult() const;
    [[nodiscard]] bool getInputSwap() const;
    [[nodiscard]] int getInputMovement() const;

    // Pack information
    [[nodiscard]] const PackData& getPackData() const noexcept;
    [[nodiscard]] const std::string& getPackId() const noexcept;
    [[nodiscard]] const std::string& getPackDisambiguator() const noexcept;
    [[nodiscard]] const std::string& getPackAuthor() const noexcept;
    [[nodiscard]] const std::string& getPackName() const noexcept;
    [[nodiscard]] int getPackVersion() const noexcept;

    [[nodiscard]] bool inReplay() const noexcept;
    [[nodiscard]] bool mustReplayInput() const noexcept;
    [[nodiscard]] bool mustShowReplayUI() const noexcept;

    [[nodiscard]] float getSwapCooldown() const noexcept;
};

} // namespace hg