id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,533,550
|
tags.hpp
|
xavieran_BaKGL/bak/tags.hpp
|
#pragma once
#include "com/strongType.hpp"
#include "bak/fileBufferFactory.hpp"
#include <optional>
#include <unordered_map>
namespace BAK {
using Tag = StrongType<unsigned, struct TagT>;
class Tags
{
public:
void Load(FileBuffer& fb);
std::optional<std::string> GetTag(Tag) const;
std::optional<Tag> FindTag(const std::string&) const;
void DumpTags() const;
private:
std::unordered_map<Tag, std::string> mTags;
};
}
| 445
|
C++
|
.h
| 18
| 22.166667
| 57
| 0.739857
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,551
|
ramp.hpp
|
xavieran_BaKGL/bak/ramp.hpp
|
#pragma once
#include <array>
#include <cstdint>
#include <iosfwd>
#include <vector>
#include "bak/file/fileBuffer.hpp"
namespace BAK {
// These are used to determine the "fog" effect on sprites in
// the world based on their distance. The palette is modified
// by these at steps of 7 for zones.
class Ramp
{
public:
std::vector<std::array<std::uint8_t, 256>> mRamps;
};
std::ostream& operator<<(std::ostream&, const Ramp&);
Ramp LoadRamp(FileBuffer&);
}
| 467
|
C++
|
.h
| 18
| 24.333333
| 61
| 0.744344
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,552
|
shop.hpp
|
xavieran_BaKGL/bak/shop.hpp
|
#pragma once
#include "bak/types.hpp"
#include "bak/objectInfo.hpp"
namespace BAK {
class IContainer;
class FileBuffer;
class InventoryItem;
}
namespace BAK {
struct ShopStats
{
std::uint8_t mTempleNumber;
std::uint8_t mSellFactor;
std::uint8_t mMaxDiscount;
std::uint8_t mBuyFactor;
std::uint8_t mHaggleDifficulty;
std::uint8_t mHaggleAnnoyanceFactor;
std::uint8_t mBardingSkill;
std::uint8_t mBardingReward;
std::uint8_t mBardingMaxReward;
std::uint8_t mUnknown;
std::uint8_t mInnSleepTilHour;
std::uint8_t mInnCost;
std::uint8_t mRepairTypes;
std::uint8_t mRepairFactor;
std::uint16_t mCategories;
std::uint8_t GetRepairFactor() const;
std::uint8_t GetTempleBlessFixedCost() const;
std::uint8_t GetTempleBlessPercent() const;
Modifier GetTempleBlessType() const;
std::uint8_t GetTempleHealFactor() const;
};
std::ostream& operator<<(std::ostream&, const ShopStats&);
ShopStats LoadShop(FileBuffer& fb);
}
namespace BAK::Shop {
bool CanBuyItem(const InventoryItem& item, const IContainer& shop);
Royals GetSellPrice(const InventoryItem&, const ShopStats&, Royals discount, bool isRomneyGuildWars);
Royals GetBuyPrice (const InventoryItem&, const ShopStats&, bool isRomneyGuildWars);
bool CanRepair(const InventoryItem&, const ShopStats&);
Royals CalculateRepairCost(const InventoryItem&, const ShopStats&);
void RepairItem(InventoryItem& item);
double GetItemQuantityMultiple(const InventoryItem&);
}
| 1,494
|
C++
|
.h
| 44
| 30.886364
| 101
| 0.773454
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,553
|
screens.hpp
|
xavieran_BaKGL/bak/screens.hpp
|
#include "bak/camera.hpp"
#include "bak/container.hpp"
#include "bak/constants.hpp"
#include "bak/dialog.hpp"
#include "bak/gameData.hpp"
#include "graphics/renderer.hpp"
#include "com/logger.hpp"
#include "com/ostream.hpp"
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <stack>
#include <sstream>
void ShowDialogGui(
BAK::Target dialogKey,
const auto& dialogStore,
const BAK::GameData* saveData = nullptr)
{
static auto chosenKey = BAK::Target{BAK::KeyTarget{0x72}};
static auto current = BAK::Target{BAK::KeyTarget{0x72}};
static auto history = std::stack<BAK::Target>{};
if (chosenKey != dialogKey)
{
chosenKey = dialogKey;
current = dialogKey;
}
const auto& snippet = dialogStore.GetSnippet(current);
ImGui::Begin("Dialog");
{
std::stringstream ss{};
ss << "Previous: ";
if (!history.empty()) ss << history.top();
else ss << "[None]";
ss << " Current: " << current;
ImGui::Text(ss.str().c_str());
}
{
std::stringstream ss{};
ss << "[ ds: " << std::hex << +snippet.mDisplayStyle << " act: " << +snippet.mActor
<< " ds2: " << +snippet.mDisplayStyle2 << " ds3: " << +snippet.mDisplayStyle3 << " ]" << std::endl;
for (const auto& action : snippet.mActions)
ss << "Action :: " << action << std::endl;
ImGui::TextWrapped(ss.str().c_str());
}
ImGui::TextWrapped("Text:\n %s", snippet.GetText().data());
if (ImGui::Button("Back") && (!history.empty()))
{
current = history.top();
history.pop();
}
for (const auto& choice : snippet.GetChoices())
{
std::stringstream ss{};
ss << choice;
if (ImGui::Button(ss.str().c_str()))
{
history.push(current);
current = choice.mTarget;
}
//if (saveData != nullptr)
//{
// ss.str(""); ss << "Val: " << saveData->ReadEvent(choice.mState);
// ImGui::SameLine(); ImGui::Text(ss.str().c_str());
//}
if (evaluate_if<BAK::KeyTarget>(choice.mTarget, [](const auto& current){ return current != BAK::KeyTarget{0}; }))
{
ImGui::TextWrapped(dialogStore.GetFirstText(
dialogStore.GetSnippet(choice.mTarget)).substr(0, 40).data());
}
else
{
ImGui::TextWrapped("No text");
}
}
ImGui::End();
}
void ShowCameraGui(
const Camera& camera)
{
const auto& pos = camera.GetPosition();
ImGui::Begin("Info");
std::stringstream ss{};
ss << "Pos: " << pos
<< "\nHPos: " << std::hex << static_cast<std::uint32_t>(pos.x)
<< ", " << static_cast<std::uint32_t>(-pos.z) << std::dec
<< "\nTile: " << camera.GetGameTile()
<< "\nAngle: " << (360.0f * (camera.GetAngle() / (2.0f*3.141592f)));
ImGui::TextWrapped(ss.str().c_str());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f
/ ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
void ShowContainerGui(
const BAK::GenericContainer& container)
{
std::cout << "Container: " << container << std::endl;
std::stringstream ss{};
ss << "\n" << container << "\n";
ImGui::Text(ss.str().c_str());
ImGui::BeginTable("Items", 4, ImGuiTableFlags_Resizable);
ImGui::TableNextColumn(); ImGui::Text("Name");
ImGui::TableNextColumn(); ImGui::Text("Cond/Qty");
ImGui::TableNextColumn(); ImGui::Text("Status");
ImGui::TableNextColumn(); ImGui::Text("Mods");
ImGui::TableNextRow();
for (const auto& item : container.GetInventory().GetItems())
{
ImGui::TableNextColumn();
ImGui::TableNextColumn();
ss.str(""); ss << item.GetObject().mName; ImGui::Text(ss.str().c_str());
ImGui::TableNextColumn();
ss.str(""); ss << +item.GetCondition(); ImGui::Text(ss.str().c_str());
ImGui::TableNextColumn();
ss.str(""); ss << +item.GetStatus(); ImGui::Text(ss.str().c_str());
ImGui::TableNextRow();
ss.str(""); ss << +item.GetModifierMask(); ImGui::Text(ss.str().c_str());
ImGui::TableNextRow();
}
ImGui::EndTable();
}
void ShowLightGui(
Graphics::Light& light)
{
ImGui::Begin("Light");
ImGui::SliderFloat3("Dire", static_cast<float*>(&light.mDirection.x), -1.0f, 1.0f, "%.3f");
ImGui::SliderFloat3("Ambi", static_cast<float*>(&light.mAmbientColor.x), .0f, 1.0f, "%.3f");
ImGui::SliderFloat3("Diff", static_cast<float*>(&light.mDiffuseColor.x), .0f, 1.0f, "%.3f");
ImGui::SliderFloat3("Spec", static_cast<float*>(&light.mSpecularColor.x), .0f, 1.0f, "%.3f");
ImGui::End();
}
| 4,824
|
C++
|
.h
| 132
| 30.348485
| 121
| 0.585047
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,554
|
sceneData.hpp
|
xavieran_BaKGL/bak/sceneData.hpp
|
#pragma once
#include <glm/glm.hpp>
#include <cstdint>
#include <string>
#include <ostream>
#include <variant>
#include "bak/dialogTarget.hpp"
namespace BAK {
enum class AdsActions
{
INDEX = 0x1030,
IF_NOT_PLAYED = 0x1330,
IF_PLAYED = 0x1350,
IF_CHAP_LTE = 0x13a0,
IF_CHAP_GTE = 0x13b0,
AND = 0x1420,
OR = 0x1430,
ELSE = 0x1500,
ADD_SCENE2 = 0x2000,
ADD_SCENE = 0x2005,
STOP_SCENE = 0x2010,
PLAY_SCENE = 0x1510,
PLAY_ALL_SCENES = 0x1520,
FADE_OUT = 0xf010,
END_IF = 0xfff0,
END = 0xffff
};
std::string_view ToString(AdsActions a);
std::ostream& operator<<(std::ostream&, AdsActions);
enum class Actions
{
SAVE_BACKGROUND = 0x0020,
UNKNOWN_A = 0x0070,
DRAW_BACKGROUND = 0x0080,
DRAW_BACKGROUND_B = 0x00c0,
PURGE = 0x0110,
// Purge means jump out of this scene
// if no purge, then we continue looping through the
// actions. This is how C12 archer works...
UPDATE = 0x0ff0,
DO_SOMETHING_A = 0x0400,
// Don't clear sprites between updates...
DISABLE_CLEAR = 0x0500,
ENABLE_CLEAR = 0x0510,
DELAY = 0x1020,
SLOT_IMAGE = 0x1050,
SLOT_PALETTE = 0x1060,
SLOT_FONT = 0x1070,
SET_SCENEA = 0x1100, // Local taG?
SET_SCENE = 0x1110, // TAG??
SET_SAVE_LAYER = 0x1120,
GOTO_TAG = 0x1200,
SET_COLOR = 0x2000,
SHOW_DIALOG = 0x2010,
UNKNOWN3 = 0x2300,
UNKNOWN6 = 0x2310,
UNKNOWN7 = 0x2320,
UNKNOWN4 = 0x2400,
SET_CLIP_REGION = 0x4000,
FADE_OUT = 0x4110,
FADE_IN = 0x4120,
SAVE_IMAGE0 = 0x4200,
SAVE_REGION_TO_LAYER = 0x4210,
SET_WINDOWA = 0xa010,
SET_WINDOWB = 0xa030,
SET_UNKNOWN = 0xa090,
SET_WINDOWC = 0xa0b0, // draw line?
DRAW_RECT = 0xa100,
DRAW_FRAME = 0xa110,
DRAW_TEXT = 0xa200,
DRAW_SPRITE0 = 0xa500,
DRAW_SPRITE1 = 0xa510,
DRAW_SPRITE_FLIP_Y = 0xa520,
DRAW_SPRITE_FLIP_XY = 0xa530,
DRAW_SPRITE_ROTATE = 0xa5a0,
DRAW_SAVED_REGION = 0xa600,
DRAW_SCREEN = 0xb600, // COPY_LAYER_TO_LAYER?
LOAD_SOUND_RESOURCE = 0xc020,
SELECT_SOUND = 0xc030,
DESELECT_SOUND = 0xc040,
PLAY_SOUND = 0xc050,
STOP_SOUND = 0xc060,
LOAD_SCREEN = 0xf010,
LOAD_IMAGE = 0xf020,
LOAD_FONT = 0xf040,
LOAD_PALETTE = 0xf050
};
std::string_view ToString(Actions a);
std::ostream& operator<<(std::ostream&, Actions);
struct SetScene
{
std::string mName;
std::uint16_t mSceneNumber;
};
std::ostream& operator<<(std::ostream&, const SetScene&);
struct LoadScreen
{
std::string mScreenName;
};
struct ClearScreen
{
};
struct DrawRect
{
std::pair<unsigned, unsigned> mPaletteColor;
glm::ivec2 mPos;
glm::ivec2 mDims;
};
std::ostream& operator<<(std::ostream&, const DrawRect&);
struct DrawSprite
{
bool mFlippedInY;
std::int16_t mX;
std::int16_t mY;
std::int16_t mSpriteIndex;
std::int16_t mImageSlot;
std::int16_t mTargetWidth;
std::int16_t mTargetHeight;
};
std::ostream& operator<<(std::ostream&, const DrawSprite&);
struct DrawScreen
{
glm::ivec2 mPosition;
glm::ivec2 mDimensions;
unsigned mArg1;
unsigned mArg2;
};
struct PlaySoundS
{
unsigned mSoundIndex;
};
struct ClipRegion
{
glm::vec<2, int> mTopLeft;
glm::vec<2, int> mBottomRight;
};
std::ostream& operator<<(std::ostream& os, const ClipRegion& a);
struct DisableClipRegion
{
};
std::ostream& operator<<(std::ostream& os, const DisableClipRegion& a);
struct SaveBackground
{
};
struct DrawBackground
{
};
struct GotoTag
{
unsigned mTag;
};
struct SaveImage
{
glm::ivec2 pos;
glm::ivec2 dims;
};
struct SaveRegionToLayer
{
glm::ivec2 pos;
glm::ivec2 dims;
};
struct Purge
{
};
struct SetWindow
{
std::uint16_t mX;
std::uint16_t mY;
std::uint16_t mWidth;
std::uint16_t mHeight;
};
struct Delay
{
unsigned mDelayMs; // units??
};
struct Update
{
};
struct SetColors
{
unsigned mForegroundColor;
unsigned mBackgroundColor;
};
struct FadeIn
{
};
struct FadeOut
{
};
struct SetSaveLayer
{
unsigned mLayer;
};
struct DrawSavedRegion
{
unsigned mLayer;
};
struct SlotImage
{
unsigned mSlot;
};
struct LoadPalette
{
std::string mPalette;
};
struct LoadImage
{
std::string mImage;
};
struct SlotPalette
{
unsigned mSlot;
};
struct ShowDialog
{
unsigned mDialogKey;
unsigned mDialogType;
};
using SceneAction = std::variant<
ClearScreen,
ClipRegion,
Delay,
DisableClipRegion,
DrawBackground,
DrawRect,
DrawScreen,
DrawSprite,
Purge,
SaveBackground,
SaveImage,
Update,
LoadImage,
LoadPalette,
FadeOut,
FadeIn,
LoadScreen,
SetScene,
SetColors,
SlotImage,
SetSaveLayer,
DrawSavedRegion,
ShowDialog,
PlaySoundS,
SaveRegionToLayer,
GotoTag,
SlotPalette>;
std::ostream& operator<<(std::ostream& os, const SceneAction& sa);
}
| 5,430
|
C++
|
.h
| 248
| 18.459677
| 71
| 0.617647
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,555
|
camera.hpp
|
xavieran_BaKGL/bak/camera.hpp
|
#pragma once
#include "bak/constants.hpp"
#include "bak/coordinates.hpp"
#include "com/logger.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <utility>
class Camera
{
public:
Camera(
unsigned width,
unsigned height,
float moveSpeed,
float turnSpeed)
:
mMoveSpeed{moveSpeed},
mTurnSpeed{turnSpeed},
mDeltaTime{0},
mPosition{0,1.4,0},
mLastPosition{mPosition},
mDistanceTravelled{0.0},
mProjectionMatrix{CalculatePerspectiveMatrix(width, height)},
mAngle{3.14, 0}
{}
glm::mat4 CalculateOrthoMatrix(unsigned width, unsigned height)
{
const auto w = static_cast<float>(width);
const auto h = static_cast<float>(height);
return glm::ortho(
-w,
h,
-w,
h,
1.0f,
1000.0f
//-1000.0f,
//1000.0f
);
}
glm::mat4 CalculatePerspectiveMatrix(unsigned width, unsigned height)
{
return glm::perspective(
glm::radians(45.0f),
static_cast<float>(width) / static_cast<float>(height),
1.0f,
4000.0f
);
}
void UseOrthoMatrix(unsigned width, unsigned height)
{
mProjectionMatrix = CalculateOrthoMatrix(width, height);
}
void UsePerspectiveMatrix(unsigned width, unsigned height)
{
mProjectionMatrix = CalculatePerspectiveMatrix(width, height);
}
void SetGameLocation(const BAK::GamePositionAndHeading& location)
{
auto pos = BAK::ToGlCoord<float>(location.mPosition);
//pos.y = mPosition.y;
pos.y = 100;
SetPosition(pos);
SetAngle(BAK::ToGlAngle(location.mHeading));
}
BAK::GamePositionAndHeading GetGameLocation() const
{
auto pos = glm::uvec2{mPosition.x, -mPosition.z};
return BAK::GamePositionAndHeading{pos, GetGameAngle()};
}
glm::uvec2 GetGameTile() const
{
const auto gamePosition = GetGameLocation();
return BAK::GetTile(gamePosition.mPosition);
}
void SetPosition(const glm::vec3& position)
{
mPosition = position;
PositionChanged();
mDistanceTravelled = 0;
}
void SetAngle(glm::vec2 angle)
{
mAngle = angle;
mAngle.x = BAK::NormaliseRadians(mAngle.x);
mAngle.y = BAK::NormaliseRadians(mAngle.y);
}
BAK::GameHeading GetHeading()
{
// Make sure to normalise this between 0 and 1
const auto bakAngle = BAK::ToBakAngle(mAngle.x);
return static_cast<std::uint16_t>(bakAngle);
}
void SetDeltaTime(double dt)
{
mDeltaTime = dt;
}
void MoveForward()
{
PositionChanged();
mPosition += GetDirection() * (mMoveSpeed * mDeltaTime);
}
void MoveBackward()
{
PositionChanged();
mPosition -= GetDirection() * (mMoveSpeed * mDeltaTime);
}
void StrafeForward()
{
PositionChanged();
mPosition += GetForward() * (mMoveSpeed * mDeltaTime);
}
void StrafeBackward()
{
PositionChanged();
mPosition -= GetForward() * (mMoveSpeed * mDeltaTime);
}
void StrafeRight()
{
PositionChanged();
mPosition += GetRight() * (mMoveSpeed * mDeltaTime);
}
void StrafeLeft()
{
PositionChanged();
mPosition -= GetRight() * (mMoveSpeed * mDeltaTime);
}
void StrafeUp()
{
PositionChanged();
mPosition += GetUp() * (mMoveSpeed * mDeltaTime);
}
void StrafeDown()
{
PositionChanged();
mPosition -= GetUp() * (mMoveSpeed * mDeltaTime);
}
void PositionChanged()
{
mDistanceTravelled += std::abs(glm::distance(mPosition, mLastPosition));
mLastPosition = mPosition;
mDirty = true;
}
void UndoPositionChange()
{
mPosition = mLastPosition;
}
void RotateLeft()
{
SetAngle(
glm::vec2{
mAngle.x + mTurnSpeed * mDeltaTime,
mAngle.y});
}
void RotateRight()
{
SetAngle(
glm::vec2{
mAngle.x - mTurnSpeed * mDeltaTime,
mAngle.y});
}
void RotateVerticalUp()
{
SetAngle(
glm::vec2{
mAngle.x,
mAngle.y + mTurnSpeed * mDeltaTime});
}
void RotateVerticalDown()
{
SetAngle(
glm::vec2{
mAngle.x,
mAngle.y - mTurnSpeed * mDeltaTime});
}
glm::vec3 GetDirection() const
{
return {
cos(mAngle.y) * sin(mAngle.x),
sin(mAngle.y),
cos(mAngle.y) * cos(mAngle.x)
};
}
glm::vec3 GetForward() const
{
return {
cos(mAngle.x - 3.14f/2.0f),
0,
-sin(mAngle.x - 3.14f/2.0f)
};
}
glm::vec3 GetRight() const
{
return {
sin(mAngle.x - 3.14f/2.0f),
0,
cos(mAngle.x - 3.14f/2.0f)
};
}
glm::vec3 GetUp() const
{
return glm::cross(GetRight(), GetDirection());
}
glm::vec2 GetAngle() const
{
return mAngle;
}
BAK::GameHeading GetGameAngle() const
{
return BAK::ToBakAngle(mAngle.x);
}
glm::mat4 GetViewMatrix() const
{
return glm::lookAt(
GetNormalisedPosition(),
GetNormalisedPosition() + GetDirection(),
GetUp()
);
}
glm::vec3 GetPosition() const { return mPosition; }
glm::vec3 GetNormalisedPosition() const { return mPosition / BAK::gWorldScale; }
const glm::mat4& GetProjectionMatrix() const { return mProjectionMatrix; }
bool CheckAndResetDirty()
{
return std::exchange(mDirty, false);
}
unsigned GetAndClearUnitsTravelled()
{
auto unitsTravelled = static_cast<unsigned>(std::round(std::floor(mDistanceTravelled / 400.0)));
if (unitsTravelled > 0)
{
mDistanceTravelled -= (unitsTravelled * 400);
return unitsTravelled;
}
return 0;
}
private:
float mMoveSpeed;
float mTurnSpeed;
float mDeltaTime;
glm::vec3 mPosition;
glm::vec3 mLastPosition;
double mDistanceTravelled;
glm::mat4 mProjectionMatrix;
glm::vec2 mAngle;
bool mDirty{};
};
| 6,509
|
C++
|
.h
| 247
| 18.696356
| 104
| 0.576348
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,556
|
itemInteractions.hpp
|
xavieran_BaKGL/bak/itemInteractions.hpp
|
#pragma once
#include "bak/character.hpp"
#include "bak/dialog.hpp"
#include "bak/gameState.hpp"
#include "bak/inventoryItem.hpp"
#include "bak/objectInfo.hpp"
namespace BAK {
struct ItemUseResult
{
std::optional<std::pair<unsigned, unsigned>> mUseSound;
std::optional<unsigned> mDialogContext;
Target mDialog;
};
ItemUseResult ApplyItemTo(
Character&,
InventoryIndex sourceItem,
InventoryIndex targetItem);
ItemUseResult UseItem(
GameState& gameState,
Character&,
InventoryIndex sourceItem);
}
| 538
|
C++
|
.h
| 22
| 21.5
| 59
| 0.774067
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,557
|
dialog.hpp
|
xavieran_BaKGL/bak/dialog.hpp
|
#pragma once
#include "bak/dialogAction.hpp"
#include "bak/dialogChoice.hpp"
#include "bak/dialogTarget.hpp"
#include "bak/resourceNames.hpp"
#include "com/logger.hpp"
#include "com/visit.hpp"
#include "bak/fileBufferFactory.hpp"
#include <iosfwd>
#include <optional>
#include <unordered_map>
namespace BAK {
class Keywords
{
public:
Keywords();
std::string_view GetDialogChoice(unsigned i) const;
std::string_view GetQueryChoice(unsigned i) const;
std::string_view GetNPCName(unsigned i) const;
static constexpr unsigned sYesIndex = 0x100;
static constexpr unsigned sNoIndex = 0x101;
static constexpr unsigned sAcceptIndex = 0x104;
static constexpr unsigned sDeclineIndex = 0x105;
static constexpr unsigned sHaggleIndex = 0x106;
private:
static constexpr auto mCharacterNameOffset = 293;
std::vector<std::string> mPartyMembers;
std::vector<std::string> mKeywords;
};
enum class DisplayFlags
{
Fullscreen = 0x6,
};
enum class DialogStyle
{
Fullscreen,
ActionArea,
LowerArea,
Popup
};
enum class TextStyle
{
VerticalCenter = 1,
HorizontalCenter = 2,
IsBold = 4
};
enum class ChoiceStyle
{
EvaluateState,
Prompt, // e.g. display yes/no buttons
Dialog, // display "Locklear asked about: "
Random // pick a random choice
};
class DialogSnippet
{
public:
DialogSnippet(FileBuffer& fb, std::uint8_t dialogFile);
const auto& GetActions() const { return mActions; }
const auto& GetChoices() const { return mChoices; }
std::string_view GetText() const { return mText; }
bool IsQueryChoice() const { return (mDisplayStyle3 & 0x2) != 0; }
bool IsDialogChoice() const { return mDisplayStyle3 == 0x4; }
bool IsRandomChoice() const { return mDisplayStyle3 == 0x8; }
bool IsDisplayable() const { return !mText.empty() || IsDialogChoice(); }
std::optional<SetPopupDimensions> GetPopup() const
{
std::optional<SetPopupDimensions> popup{};
for (const auto& action : mActions)
{
evaluate_if<SetPopupDimensions>(
action,
[&popup](const auto& action) { popup = action; });
}
return popup;
}
// Display Style One - where to display text
// 0x00 -> Center of full screen
// 0x02 -> In action/game part of screen
// 0x03 -> In non-bold at bottom
// 0x04 -> In bold at bottom
// 0x05 -> In large action/game part of screen (e.g. temple iface)
// 0x06 -> Center of full screen
std::uint8_t mDisplayStyle;
// Actor <= 0x6 => Show alternate background (player character is talking...)
// Actor > 0x6 show normal background
// Actor == 0xff party leader is talking
std::uint16_t mActor;
// 0x10 Vertically centered, background is with flowers, text always scrolls in
// 0x04 Vertically and horizontally centered
// 0x03 Show background
std::uint8_t mDisplayStyle2;
// Display Style 3:
// 0x0 -> No choices
// 0x1 -> Show in action part of screen...
// 0x2 -> Lay choices side by side (e.g. Yes/No prompt)
// 0x4 -> (Dialog tree root... Character "asked about")
// -> Choices in grid
// -> Goodbye is special and immediately quits the dialog
std::uint8_t mDisplayStyle3;
std::vector<DialogChoice> mChoices;
std::vector<DialogAction> mActions;
std::string mText;
};
std::ostream& operator<<(std::ostream& os, const DialogSnippet& d);
class DialogStore
{
public:
static const DialogStore& Get();
void ShowAllDialogs();
void ShowDialog(Target dialogKey);
const DialogSnippet& GetSnippet(Target target) const;
bool HasSnippet(Target target) const;
OffsetTarget GetTarget(KeyTarget dialogKey) const;
std::string_view GetFirstText(const DialogSnippet& snippet) const;
const DialogSnippet& operator()(KeyTarget dialogKey) const;
const DialogSnippet& operator()(OffsetTarget snippetKey) const;
private:
DialogStore();
void Load();
std::string GetDialogFile(std::uint8_t i);
std::unordered_map<
KeyTarget,
OffsetTarget> mDialogMap;
std::unordered_map<
OffsetTarget,
DialogSnippet> mSnippetMap;
const Logging::Logger& mLogger;
};
}
| 4,268
|
C++
|
.h
| 129
| 28.51938
| 83
| 0.694275
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,558
|
ttmRunner.hpp
|
xavieran_BaKGL/bak/ttmRunner.hpp
|
#pragma once
#include "bak/scene.hpp"
#include "com/logger.hpp"
namespace BAK {
class TTMRunner
{
public:
TTMRunner();
void LoadTTM(
std::string adsFile,
std::string ttmFile);
std::optional<BAK::SceneAction> GetNextAction();
private:
void AdvanceToNextScene();
unsigned FindActionMatchingTag(unsigned tag);
std::unordered_map<unsigned, std::vector<BAK::SceneSequence>> mSceneSequences;
std::vector<BAK::SceneAction> mActions;
unsigned mCurrentAction = 0;
unsigned mCurrentSequence = 0;
unsigned mCurrentSequenceScene = 0;
const Logging::Logger& mLogger;
};
}
| 635
|
C++
|
.h
| 23
| 23.304348
| 82
| 0.729866
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,559
|
ttmRenderer.hpp
|
xavieran_BaKGL/bak/ttmRenderer.hpp
|
#pragma once
#include "bak/image.hpp"
#include "bak/palette.hpp"
#include "bak/scene.hpp"
#include "bak/spriteRenderer.hpp"
#include "bak/ttmRunner.hpp"
#include "com/logger.hpp"
namespace BAK {
class TTMRenderer
{
public:
TTMRenderer(
std::string adsFile,
std::string ttmFile);
Graphics::TextureStore RenderTTM();
private:
bool AdvanceAction();
void RenderFrame();
TTMRunner mRunner;
struct PaletteSlot
{
BAK::Palette mPaletteData;
};
struct ImageSlot
{
std::vector<BAK::Image> mImages;
};
unsigned mCurrentPaletteSlot = 0;
unsigned mCurrentImageSlot = 0;
unsigned mImageSaveLayer = 0;
std::unordered_map<unsigned, BAK::SaveRegionToLayer> mClearRegions;
std::unordered_map<unsigned, Graphics::Texture> mSaves;
std::unordered_map<unsigned, ImageSlot> mImageSlots;
std::unordered_map<unsigned, PaletteSlot> mPaletteSlots;
std::unordered_map<unsigned, Graphics::TextureStore> mTextures;
BAK::SpriteRenderer mRenderer;
std::optional<BAK::Image> mScreen;
Graphics::TextureStore mRenderedFrames;
const Logging::Logger& mLogger;
};
}
| 1,171
|
C++
|
.h
| 41
| 24.073171
| 71
| 0.723921
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,560
|
time.hpp
|
xavieran_BaKGL/bak/time.hpp
|
#pragma once
#include "bak/gameState.hpp"
namespace BAK {
void EffectOfConditionsWithTime(
Skills& skills,
Conditions& conditions,
unsigned healFraction,
unsigned healPercentCeiling);
void ImproveNearDeath(
Skills& skills,
Conditions& conditions);
void DamageDueToLackOfSleep(
Conditions& conditions,
CharIndex charIndex,
Skills& skills);
class TimeChanger
{
public:
TimeChanger(GameState& gameState)
:
mGameState{gameState}
{}
void HandleGameTimeChange(
Time timeDelta,
bool canDisplayDialog,
bool mustConsumeRations,
bool isNotSleeping,
unsigned healFraction,
unsigned healPercentCeiling)
{
Logging::LogDebug(__FUNCTION__) << "(" << timeDelta
<< " canDisplayDialog: " << canDisplayDialog << " consRat: "
<< mustConsumeRations << " sleep? "
<< isNotSleeping << " hl: " << healFraction << " - " << healPercentCeiling << ")\n";
auto& currentTime = mGameState.GetWorldTime();
auto oldTime = currentTime;
auto hourOfDay = currentTime.GetTime().GetHour();
auto daysElapsedBefore = currentTime.GetTime().GetDays();
currentTime.AdvanceTime(timeDelta);
auto daysElapsedAfter = currentTime.GetTime().GetDays();
if (daysElapsedAfter != daysElapsedBefore)
{
if ((daysElapsedAfter % 30) == 0)
{
ImproveActiveCharactersHealthAndStamina();
}
if (mustConsumeRations)
{
PartyConsumeRations();
}
mGameState.GetParty().ForEachActiveCharacter([&](auto& character){
ImproveNearDeath(character.GetSkills(), character.GetConditions());
return Loop::Continue;
});
}
auto newHourOfDay = currentTime.GetTime().GetHour();
if (newHourOfDay != hourOfDay)
{
HandleGameTimeIncreased(
canDisplayDialog,
isNotSleeping,
healFraction,
healPercentCeiling);
}
CheckAndClearSkillAffectors();
mGameState.ReduceAndEvaluateTimeExpiringState(timeDelta);
}
// Time change per step
// minStep: 0x1e 30 secs distance: 400
// medStep: 0x3c 60 secs distance: 800
// bigStep: 0x78 120 secs distance: 1600
void ElapseTimeInMainView(Time delta)
{
HandleGameTimeChange(
delta,
true, true, true, 0, 0);
}
void ElapseTimeInSleepView(Time delta, unsigned healFraction, unsigned healPercentCeiling)
{
HandleGameTimeChange(
BAK::Times::OneHour,
true, true, false, healFraction, healPercentCeiling);
mGameState.GetWorldTime().SetTimeLastSlept(
mGameState.GetWorldTime().GetTime());
}
private:
void ImproveActiveCharactersHealthAndStamina()
{
mGameState.GetParty().ForEachActiveCharacter([&](auto& character){
character.ImproveSkill(SkillType::Health, SkillChange::Direct, 1);
character.ImproveSkill(SkillType::Stamina, SkillChange::Direct, 1);
return Loop::Continue;
});
}
void ConsumeRations(auto& character)
{
auto rations = InventoryItemFactory::MakeItem(sRations, 1);
auto spoiled = InventoryItemFactory::MakeItem(sSpoiledRations, 1);
auto poisoned = InventoryItemFactory::MakeItem(sPoisonedRations, 1);
if (character.RemoveItem(rations))
{
// Eating rations instantly removes starving...
character.GetConditions().AdjustCondition(
character.GetSkills(),
BAK::Condition::Starving,
-100);
}
else if (character.RemoveItem(spoiled))
{
character.GetConditions().AdjustCondition(
character.GetSkills(),
BAK::Condition::Starving,
-100);
character.GetConditions().AdjustCondition(
character.GetSkills(),
BAK::Condition::Sick,
3);
}
else if (character.RemoveItem(poisoned))
{
character.GetConditions().AdjustCondition(
character.GetSkills(),
BAK::Condition::Poisoned,
4);
}
else // no rations of any kind
{
character.GetConditions().AdjustCondition(
character.GetSkills(),
BAK::Condition::Starving,
5);
}
}
void PartyConsumeRations()
{
mGameState.GetParty().ForEachActiveCharacter([&](auto& character){
ConsumeRations(character);
return Loop::Continue;
});
}
void HandleGameTimeIncreased(
bool canDisplayDialog,
bool isNotSleeping,
unsigned healFraction,
unsigned healPercentCeiling)
{
Logging::LogDebug(__FUNCTION__) << "(" << canDisplayDialog
<< ", " << isNotSleeping << ", " << healFraction
<< " - " << healPercentCeiling << ")\n";
if (canDisplayDialog)
{
if (isNotSleeping)
{
auto timeDiff = mGameState.GetWorldTime().GetTimeSinceLastSlept();
if (timeDiff >= Times::SeventeenHours)
{
//ShowNeedSleepDialog(0x40)
Logging::LogWarn(__FUNCTION__) << " We need sleep!\n";
}
if (timeDiff >= Times::EighteenHours)
{
Logging::LogWarn(__FUNCTION__) << " Damaging due to lack of sleep!\n";
mGameState.GetParty().ForEachActiveCharacter([&](auto& character){
DamageDueToLackOfSleep(character.GetConditions(), character.mCharacterIndex, character.GetSkills());
return Loop::Continue;
});
}
}
}
mGameState.GetParty().ForEachActiveCharacter([&](auto& character){
EffectOfConditionsWithTime(
character.GetSkills(),
character.GetConditions(),
healFraction,
healPercentCeiling);
return Loop::Continue;
});
}
unsigned calculateTimeOfDayForPalette()
{
auto time = mGameState.GetWorldTime().GetTime();
auto hourOfDay = time.GetHour();
auto secondsOfDay = time.mTime % Times::OneDay.mTime;
if (hourOfDay > 8 && hourOfDay < 17)
{
return 0x40;
}
if (hourOfDay < 4 || hourOfDay >= 20)
{
return 0xf;
}
if (hourOfDay < 17)
{
secondsOfDay -= 0x1c20;
auto x = (secondsOfDay * 0x31) / 0x1c20;
return x + 0xf;
}
else
{
secondsOfDay += 0x8878;
auto x = (secondsOfDay * 0x31) / 0x1518;
return 0x40 - x;
}
}
void CheckAndClearSkillAffectors()
{
const auto time = mGameState.GetWorldTime().GetTime();
mGameState.GetParty().ForEachActiveCharacter([&](auto& character){
auto& affectors = character.GetSkillAffectors();
std::erase_if(
affectors,
[&](auto& affector){
return affector.mEndTime < time;
});
return Loop::Continue;
});
}
private:
GameState& mGameState;
};
}
| 7,582
|
C++
|
.h
| 221
| 23.81448
| 124
| 0.568488
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,561
|
book.hpp
|
xavieran_BaKGL/bak/book.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
#include "graphics/glm.hpp"
#include <iosfwd>
#include <optional>
#include <vector>
namespace BAK {
// Courtesy of Joris van Eijden
struct ReservedArea
{
glm::ivec2 mPos;
glm::ivec2 mDims;
};
enum class TextAlignment
{
Left = 1,
Right = 2,
Justify = 3,
Center = 4
};
enum class FontStyle
{
Normal = 1,
Bold = 2,
Italic = 4,
Underlined = 8,
Ghosted = 16
};
struct TextSegment
{
unsigned mFont;
unsigned mYOff;
FontStyle mFontStyle;
std::string mText;
unsigned mColor;
};
struct Paragraph
{
glm::ivec2 mOffset;
unsigned mWidth;
unsigned mLineSpacing;
unsigned mWordSpacing;
unsigned mStartIndent;
TextAlignment mAlignment;
std::vector<TextSegment> mText;
};
enum class Mirroring
{
None = 0,
Horizontal = 1,
Vertical = 2,
HorizontalAndVertical = 3
};
struct BookImage
{
glm::ivec2 mPos;
unsigned mImage;
Mirroring mMirroring;
};
struct Page
{
// Offset applies to all text within this page
unsigned mDisplayNumber;
glm::ivec2 mOffset;
glm::ivec2 mDims;
unsigned mPageNumber;
unsigned mPreviousPageNumber;
unsigned mNextPageNumber;
unsigned mShowPageNumber;
std::vector<ReservedArea> mReservedAreas;
std::vector<BookImage> mImages;
std::vector<Paragraph> mParagraphs;
};
struct Book
{
std::vector<Page> mPages;
};
Book LoadBook(FileBuffer&);
std::ostream& operator<<(std::ostream&, const Paragraph&);
std::ostream& operator<<(std::ostream&, const Page&);
std::ostream& operator<<(std::ostream&, const Book&);
}
| 1,640
|
C++
|
.h
| 82
| 16.743902
| 58
| 0.709929
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,562
|
combat.hpp
|
xavieran_BaKGL/bak/combat.hpp
|
#pragma once
#include "bak/coordinates.hpp"
#include <cstdint>
#include <iosfwd>
namespace BAK {
class CombatWorldLocation
{
public:
GamePositionAndHeading mPosition;
std::uint8_t mUnknownFlag;
// 0 - invisible?
// 1 - invisible?
// 2 - moving
// 3 - moving
// 4 - dead
std::uint8_t mState;
};
std::ostream& operator<<(std::ostream&, const CombatWorldLocation&);
class CombatGridLocation
{
public:
MonsterIndex mMonster;
glm::uvec2 mGridPos;
};
std::ostream& operator<<(std::ostream&, const CombatGridLocation&);
class CombatEntityList
{
public:
std::vector<CombatantIndex> mCombatants;
};
std::ostream& operator<<(std::ostream&, const CombatEntityList&);
void LoadP1Dat();
}
| 735
|
C++
|
.h
| 33
| 19.484848
| 68
| 0.727802
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,563
|
IZoneLoader.hpp
|
xavieran_BaKGL/bak/IZoneLoader.hpp
|
#pragma once
#include "bak/types.hpp"
namespace BAK {
// Interface to load zone
class IZoneLoader
{
public:
// Load zone based on zone info in DEF_ZONE.DAT
virtual void DoTeleport(BAK::Encounter::Teleport) = 0;
virtual void LoadGame(std::string, std::optional<Chapter>) = 0;
};
}
| 296
|
C++
|
.h
| 12
| 22.333333
| 67
| 0.732143
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,564
|
gameState.hpp
|
xavieran_BaKGL/bak/gameState.hpp
|
#pragma once
#include "bak/container.hpp"
#include "bak/constants.hpp"
#include "bak/coordinates.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogAction.hpp"
#include "bak/dialogChoice.hpp"
#include "bak/fmap.hpp"
#include "bak/gameData.hpp"
#include "bak/money.hpp"
#include "bak/save.hpp"
#include "bak/textVariableStore.hpp"
#include "bak/timeExpiringState.hpp"
#include "bak/types.hpp"
#include "com/random.hpp"
#include "com/visit.hpp"
#include <type_traits>
namespace BAK {
template <typename F, typename ...Args>
using invoke_result_with_fb = std::invoke_result_t<F, FileBuffer&, Args...>;
class GameState
{
public:
GameState();
GameState(GameData* gameData);
template <typename F, typename ...Args>
void Apply(F&& func, Args&&... args) const
requires(std::is_void_v<invoke_result_with_fb<F, Args...>>)
{
if (mGameData)
{
std::invoke(func, mGameData->GetFileBuffer(), args...);
}
}
template <typename F, typename ...Args>
void Apply(F&& func, Args&&... args)
requires(std::is_void_v<invoke_result_with_fb<F, Args...>>)
{
if (mGameData)
{
std::invoke(func, mGameData->GetFileBuffer(), args...);
}
}
template <typename F, typename ...Args>
auto Apply(F&& func, Args&&... args)
requires(!std::is_void_v<invoke_result_with_fb<F, Args...>>)
{
if (mGameData)
{
return std::invoke(func, mGameData->GetFileBuffer(), args...);
}
return invoke_result_with_fb<F, Args...>{};
}
template <typename F, typename ...Args>
auto Apply(F&& func, Args&&... args) const
requires(!std::is_void_v<invoke_result_with_fb<F, Args...>>)
{
if (mGameData)
{
return std::invoke(func, mGameData->GetFileBuffer(), args...);
}
return invoke_result_with_fb<F, Args...>{};
}
void LoadGameData(GameData* gameData);
GameData* GetGameData(){ return mGameData; }
const Party& GetParty() const;
Party& GetParty();
std::vector<GenericContainer>& GetCombatContainers() { return mCombatContainers; }
std::int16_t GetEndOfDialogState() const;
void DoSetEndOfDialogState(std::int16_t state);
void SetActiveCharacter(ActiveCharIndex character);
void SetActiveCharacter(CharIndex character);
const TextVariableStore& GetTextVariableStore() const;
TextVariableStore& GetTextVariableStore();
void SetChapter(Chapter chapter);
Chapter GetChapter() const;
void SetMonster(MonsterIndex);
Royals GetMoney() const;
void SetLocation(Location loc);
void SetLocation(GamePositionAndHeading posAndHeading);
void SetMapLocation(MapLocation) const;
GamePositionAndHeading GetLocation() const;
MapLocation GetMapLocation() const;
ZoneNumber GetZone() const;
auto& GetTimeExpiringState() { return mTimeExpiringState; }
const WorldClock& GetWorldTime() const;
WorldClock& GetWorldTime();
void SetTransitionChapter_7541(bool);
bool GetTransitionChapter_7541() const;
void SetShopType_7542(unsigned shopType);
unsigned GetShopType_7542() const;
GenericContainer* GetContainerForGDSScene(HotspotRef ref);
GenericContainer* GetWorldContainer(ZoneNumber zone, GamePosition location);
GenericContainer const* GetWorldContainer(ZoneNumber zone, GamePosition location) const;
std::optional<unsigned> GetActor(unsigned actor) const;
bool GetSpellActive(StaticSpells spell) const;
bool ClearActiveSpells();
// prefer to use this function when getting best skill
// as it will set the appropriate internal state.
std::pair<CharIndex, unsigned> GetPartySkill(SkillType skill, bool best);
void SetCharacterTextVariables();
void SetDefaultDialogTextVariables();
void SetDialogTextVariable(unsigned index, unsigned attribute);
CharIndex GetPartyLeader() const;
void SelectRandomActiveCharacter(unsigned index, unsigned attribute);
void EvaluateAction(const DialogAction& action);
void EvaluateSpecialAction(const SpecialAction& action);
void DoGamble(unsigned playerChance, unsigned gamblerChance, unsigned reward);
unsigned GetState(const Choice& choice) const;
unsigned GetGameState(const GameStateChoice& choice) const;
bool EvaluateGameStateChoice(const GameStateChoice& choice) const;
void DoElapseTime(Time time);
void ReduceAndEvaluateTimeExpiringState(Time delta);
void RecalculatePalettesForPotionOrSpellEffect(TimeExpiringState& state);
void DeactivateLightSource();
bool HaveActiveLightSource();
void SetSpellState(const TimeExpiringState& state);
void CastStaticSpell(StaticSpells spell, Time duration);
bool CanCastSpell(SpellIndex spell, ActiveCharIndex character);
void HealCharacter(CharIndex who, unsigned amount);
// Remove these from game state, now that we have Apply fn that can be used instead
bool EvaluateDialogChoice(const DialogChoice& choice) const;
unsigned GetEventState(Choice choice) const;
unsigned ReadEvent(unsigned eventPtr) const;
bool ReadEventBool(unsigned eventPtr) const;
void SetEventValue(unsigned eventPtr, unsigned value);
void SetEventState(const SetFlag& setFlag);
bool GetMoreThanOneTempleSeen() const;
void SetDialogContext_7530(unsigned contextValue);
void SetBardReward_754d(unsigned value);
unsigned GetBardReward_754d();
void SetItemValue(Royals value);
void SetInventoryItem(const InventoryItem& item);
void ClearUnseenImprovements(unsigned character);
bool SaveState();
bool Save(const SaveFile& saveFile);
bool Save(const std::string& saveName);
std::vector<GenericContainer>& GetContainers(ZoneNumber zone);
const std::vector<GenericContainer>& GetContainers(ZoneNumber zone) const;
bool HaveNote(unsigned note) const;
bool CheckConversationItemAvailable(unsigned conversationItem) const;
private:
std::optional<CharIndex> mDialogCharacter{};
CharIndex mActiveCharacter{};
CharIndex mSkillCheckedCharacter{};
// 0 - defaults to someone other than party leader
// 1 - will be selected so as not to equal 0
// 2 - will be selected so as not to be either 0 or 1
// 3 - party magician
// 4 - party leader
// 5 - party warrior
std::array<std::uint8_t, 6> mDialogCharacterList{};
GameData* mGameData;
Party mParty;
unsigned mContextValue_7530{};
bool mTransitionChapter_7541{};
unsigned mShopType_7542{};
unsigned mBardReward_754d{};
Royals mItemValue_753e{};
unsigned mSkillValue{};
unsigned mContextVar_753f{};
std::optional<InventoryItem> mSelectedItem{};
std::optional<MonsterIndex> mCurrentMonster{};
Chapter mChapter{};
ZoneNumber mZone{};
std::int16_t mEndOfDialogState{};
std::vector<
std::vector<GenericContainer>> mContainers{};
std::vector<GenericContainer> mGDSContainers{};
std::vector<GenericContainer> mCombatContainers;
std::vector<TimeExpiringState> mTimeExpiringState{};
SpellState mSpellState{};
TextVariableStore mTextVariableStore{};
FMapXY mFullMap;
WorldClock mFakeWorldClock{{0}, {0}};
const Logging::Logger& mLogger;
};
}
| 7,295
|
C++
|
.h
| 178
| 35.674157
| 92
| 0.72771
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,565
|
image.hpp
|
xavieran_BaKGL/bak/image.hpp
|
#pragma once
#include <vector>
#include "bak/fileBufferFactory.hpp"
namespace BAK {
class Image
{
public:
Image(unsigned width, unsigned height, unsigned flags, bool isHighResLowCol);
unsigned GetWidth() const;
unsigned GetHeight() const;
unsigned GetSize() const;
bool IsHighResLowCol() const;
uint8_t * GetPixels() const;
uint8_t GetPixel(unsigned x, unsigned y) const;
void Load(FileBuffer *buffer);
void SetPixel(unsigned x, unsigned y, std::uint8_t color );
private:
unsigned mWidth;
unsigned mHeight;
unsigned int mFlags;
bool mIsHighResLowCol;
std::vector<uint8_t> mPixels;
};
}
| 649
|
C++
|
.h
| 24
| 23.416667
| 81
| 0.731392
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,566
|
camp.hpp
|
xavieran_BaKGL/bak/camp.hpp
|
#pragma once
#include "bak/fileBufferFactory.hpp"
#include <glm/glm.hpp>
namespace BAK {
class CampData
{
public:
CampData();
const std::vector<glm::vec2>& GetClockTicks() const;
const std::vector<glm::vec2>& GetDaytimeShadow() const;
private:
glm::vec2 mHighlightSize{};
std::vector<glm::vec2> mClockTicks{};
glm::vec2 mClockTwelve{};
glm::vec2 mClockCenter{};
std::vector<glm::vec2> mDaytimeShadow{};
};
}
| 446
|
C++
|
.h
| 18
| 21.666667
| 59
| 0.708531
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,567
|
fileProvider.hpp
|
xavieran_BaKGL/bak/file/fileProvider.hpp
|
#pragma once
#include "bak/fileBufferFactory.hpp"
#include "bak/file/IDataBufferProvider.hpp"
#include <filesystem>
#include <string>
#include <unordered_map>
namespace BAK::File {
class FileDataProvider : public IDataBufferProvider
{
public:
FileDataProvider(const std::string& basePath);
FileBuffer* GetDataBuffer(const std::string& path) override;
private:
bool DataFileExists(const std::string& path) const;
std::unordered_map<std::string, FileBuffer> mCache;
std::filesystem::path mBasePath;
};
}
| 530
|
C++
|
.h
| 18
| 26.888889
| 64
| 0.781746
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,568
|
aggregateFileProvider.hpp
|
xavieran_BaKGL/bak/file/aggregateFileProvider.hpp
|
#pragma once
#include "bak/file/IDataBufferProvider.hpp"
#include <memory>
#include <vector>
namespace BAK::File {
class AggregateFileProvider : public IDataBufferProvider
{
public:
AggregateFileProvider(const std::vector<std::string>& searchPaths);
FileBuffer* GetDataBuffer(const std::string& fileName) override;
private:
std::vector<std::unique_ptr<IDataBufferProvider>> mProviders;
};
}
| 410
|
C++
|
.h
| 14
| 26.928571
| 71
| 0.796915
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,569
|
IDataBufferProvider.hpp
|
xavieran_BaKGL/bak/file/IDataBufferProvider.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
namespace BAK::File {
class IDataBufferProvider
{
public:
virtual FileBuffer* GetDataBuffer(const std::string& fileName) = 0;
virtual ~IDataBufferProvider() {};
};
}
| 227
|
C++
|
.h
| 10
| 20.4
| 71
| 0.764151
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,570
|
fileBuffer.hpp
|
xavieran_BaKGL/bak/file/fileBuffer.hpp
|
#pragma once
#include <glm/glm.hpp>
#include <array>
#include <fstream>
#include <string>
#include <type_traits>
#include <cstdint>
#include <ostream>
namespace BAK {
static constexpr auto COMPRESSION_LZW = 0;
static constexpr auto COMPRESSION_LZSS = 1;
static constexpr auto COMPRESSION_RLE = 2;
class FileBuffer
{
public:
explicit FileBuffer(unsigned n);
FileBuffer(const FileBuffer&) noexcept = delete;
FileBuffer& operator=(const FileBuffer&) noexcept = delete;
FileBuffer(FileBuffer&&) noexcept;
FileBuffer& operator=(FileBuffer&&) noexcept;
~FileBuffer();
// Create a new file mBuffer starting from this tag
FileBuffer Find(std::uint32_t tag) const;
template <typename T>
FileBuffer Find(T tag) const
{
return Find(static_cast<std::uint32_t>(tag));
}
FileBuffer MakeSubBuffer(std::uint32_t offset, std::uint32_t size) const;
void Load(std::ifstream &ifs);
void Save(std::ofstream &ofs);
void Save(std::ofstream &ofs, unsigned n);
void Show(std::ostream&);
void Dump(std::ostream&, unsigned n = 0);
void Dump(unsigned n = 0);
void DumpAndSkip(unsigned n = 0);
void CopyFrom(FileBuffer *buf, unsigned n);
void CopyTo(FileBuffer *buf, unsigned n);
void Fill(FileBuffer *buf);
void Rewind();
unsigned Tell();
void Seek(unsigned n);
void Skip(int n);
void SkipBits();
unsigned CompressLZW(FileBuffer *result);
unsigned CompressLZSS(FileBuffer *result);
unsigned CompressRLE(FileBuffer *result);
unsigned Compress(FileBuffer *result, unsigned method);
unsigned DecompressLZW(FileBuffer *result);
unsigned DecompressLZSS(FileBuffer *result);
unsigned DecompressRLE(FileBuffer *result);
unsigned Decompress(FileBuffer *result, unsigned method);
bool AtEnd() const;
unsigned GetSize() const;
unsigned GetBytesDone() const;
unsigned GetBytesLeft() const;
std::uint8_t * GetCurrent() const;
unsigned GetNextBit() const;
std::uint8_t Peek();
std::uint8_t GetUint8();
std::uint16_t GetUint16LE();
std::uint16_t GetUint16BE();
std::uint32_t GetUint32LE();
std::uint32_t GetUint32BE();
std::int8_t GetSint8();
std::int16_t GetSint16LE();
std::int16_t GetSint16BE();
std::int32_t GetSint32LE();
std::int32_t GetSint32BE();
template <typename T, bool littleEndian=true>
requires std::is_integral_v<T>
T Get()
{
if constexpr (std::is_same_v<T, std::uint8_t>)
{
return GetUint8();
}
else if constexpr (std::is_same_v<T, std::int8_t>)
{
return GetSint8();
}
else if constexpr (std::is_same_v<T, std::uint16_t>)
{
return littleEndian ? GetUint16LE() : GetUint16BE();
}
else if constexpr (std::is_same_v<T, std::int16_t>)
{
return littleEndian ? GetSint16LE() : GetSint16BE();
}
else if constexpr (std::is_same_v<T, std::uint32_t>)
{
return littleEndian ? GetUint32LE() : GetUint32BE();
}
else if constexpr (std::is_same_v<T, std::int32_t>)
{
return littleEndian ? GetSint32LE() : GetSint32BE();
}
else
{
static_assert(std::is_same_v<T, std::uint8_t>, "Unsupported integral type");
return T{};
}
}
template <std::size_t N>
auto GetArray()
{
std::array<std::uint8_t, N> arr{};
for (unsigned i = 0; i < N; i++)
{
arr[i] = GetUint8();
}
return arr;
}
template <typename T, std::size_t N>
auto LoadVector()
{
glm::vec<N, T> tmp{};
for (unsigned i = 0; i < N; i++)
{
tmp[i] = Get<T>();
}
return tmp;
}
std::string GetString();
std::string GetString(unsigned len);
void GetData(void * data, unsigned n);
unsigned GetBits(unsigned n);
void PutUint8(uint8_t x);
void PutUint16LE(std::uint16_t x);
void PutUint16BE(std::uint16_t x);
void PutUint32LE(std::uint32_t x);
void PutUint32BE(std::uint32_t x);
void PutSint8(std::int8_t x);
void PutSint16LE(std::int16_t x);
void PutSint16BE(std::int16_t x);
void PutSint32LE(std::int32_t x);
void PutSint32BE(std::int32_t x);
void PutString(std::string s);
void PutString(std::string s, unsigned len);
void PutData(void * data, unsigned n);
void PutData(std::uint8_t x, unsigned n);
void PutBits(unsigned x, unsigned n);
private:
// Be nicer if this was a shared ptr...
std::uint8_t * mBuffer;
std::uint8_t * mCurrent;
unsigned mSize;
unsigned mNextBit;
bool mOwnBuffer;
FileBuffer(
std::uint8_t*,
std::uint8_t*,
std::uint32_t,
std::uint32_t);
};
}
| 4,881
|
C++
|
.h
| 156
| 25.083333
| 88
| 0.626971
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,571
|
packedFileProvider.hpp
|
xavieran_BaKGL/bak/file/packedFileProvider.hpp
|
#pragma once
#include "bak/file/IDataBufferProvider.hpp"
#include "com/logger.hpp"
#include <string>
#include <unordered_map>
namespace BAK::File {
class PackedFileDataProvider : public IDataBufferProvider
{
public:
PackedFileDataProvider(IDataBufferProvider& dataProvider);
FileBuffer* GetDataBuffer(const std::string& path) override;
private:
std::unordered_map<std::string, FileBuffer> mCache;
const Logging::Logger& mLogger;
};
}
| 459
|
C++
|
.h
| 16
| 26.125
| 64
| 0.794931
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,572
|
packedResourceFile.hpp
|
xavieran_BaKGL/bak/file/packedResourceFile.hpp
|
#pragma once
#include "bak/fileBufferFactory.hpp"
#include <unordered_map>
namespace BAK::File {
class ResourceIndex
{
public:
static constexpr auto sFilename = "krondor.rmf";
static constexpr auto sFilenameLength = 13;
struct ResourceIndexData
{
unsigned mHashKey;
std::streamoff mOffset;
};
ResourceIndex(FileBuffer&);
const std::string& GetPackedResourceFile() const;
unsigned GetResourceSize() const;
const std::vector<ResourceIndex::ResourceIndexData>&
GetResourceIndex() const;
private:
std::string mPackedResourceName;
std::vector<ResourceIndexData> mResourceIndexData;
};
}
| 659
|
C++
|
.h
| 24
| 23.25
| 56
| 0.744409
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,573
|
util.hpp
|
xavieran_BaKGL/bak/file/util.hpp
|
#include "bak/fileBufferFactory.hpp"
namespace BAK::File {
unsigned GetStreamSize(std::ifstream& ifs);
FileBuffer CreateFileBuffer(const std::string& fileName);
}
| 167
|
C++
|
.h
| 5
| 31.6
| 57
| 0.816456
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,574
|
temple.hpp
|
xavieran_BaKGL/bak/state/temple.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
namespace BAK {
class GameState;
}
namespace BAK::State {
void SetTempleSeen(FileBuffer&, unsigned temple);
bool ReadTempleSeen(const GameState&, unsigned temple);
}
| 219
|
C++
|
.h
| 9
| 22.777778
| 55
| 0.814634
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,575
|
customStateChoice.hpp
|
xavieran_BaKGL/bak/state/customStateChoice.hpp
|
#pragma once
#include "bak/dialogChoice.hpp"
namespace BAK {
class GameState;
};
namespace BAK::State {
class CustomStateEvaluator
{
public:
CustomStateEvaluator(const GameState&);
bool AnyCharacterStarving() const;
bool Plagued() const;
bool HaveSixSuitsOfArmor() const;
bool AllPartyArmorIsGoodCondition() const;
bool PoisonedDelekhanArmyChests() const;
bool AnyCharacterSansWeapon() const;
bool AnyCharacterHasNegativeCondition() const;
bool AnyCharacterIsUnhealthy() const;
bool AllCharactersHaveNapthaMask() const;
bool NormalFoodInArlieChest() const;
bool PoisonedFoodInArlieChest() const;
private:
const GameState& mGameState;
};
}
| 698
|
C++
|
.h
| 25
| 24.56
| 50
| 0.785285
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,576
|
money.hpp
|
xavieran_BaKGL/bak/state/money.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
#include "bak/money.hpp"
#include "bak/types.hpp"
namespace BAK {
class GameState;
struct ShopStats;
}
namespace BAK::State {
void WritePartyMoney(FileBuffer&, Chapter, Royals);
Royals ReadPartyMoney(FileBuffer&, Chapter);
bool IsRomneyGuildWars(const GameState&, const ShopStats&);
}
| 340
|
C++
|
.h
| 13
| 24.615385
| 59
| 0.809375
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,577
|
event.hpp
|
xavieran_BaKGL/bak/state/event.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
namespace BAK::State {
void SetBitValueAt(FileBuffer&, unsigned byteOffset, unsigned bitOffset, unsigned value);
std::pair<unsigned, unsigned> CalculateComplexEventOffset(unsigned eventPtr);
std::pair<unsigned, unsigned> CalculateEventOffset(unsigned eventPtr);
void SetEventFlag(FileBuffer&, unsigned eventPtr, unsigned value);
void SetEventFlagTrue (FileBuffer&, unsigned eventPtr);
void SetEventFlagFalse(FileBuffer&, unsigned eventPtr);
unsigned ReadBitValueAt(FileBuffer&, unsigned byteOffset, unsigned bitOffset);
unsigned ReadEvent(FileBuffer&, unsigned eventPtr);
bool ReadEventBool(FileBuffer&, unsigned eventPtr);
}
| 681
|
C++
|
.h
| 13
| 50.846154
| 89
| 0.839637
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,578
|
offsets.hpp
|
xavieran_BaKGL/bak/state/offsets.hpp
|
#pragma once
namespace BAK::State {
static constexpr auto sCharacterSelectedSkillPool = 0x324; // -> 0x319
//
static constexpr auto sSkillSelectedEventFlag = 0x1856;
static constexpr auto sSkillImprovementEventFlag = 0x18ce;
static constexpr auto sConditionStateEventFlag = 0x1c98;
// e.g. books
static constexpr auto sItemUsedForCharacterAtLeastOnce = 0x194c;
static constexpr auto sSpynoteHasBeenRead = 0x1964;
// Single bit indicators for event state tracking
// In the code this offset is 0x440a in the game -> diff of 0x3d28
static constexpr auto sGameEventRecordOffset = 0x6e2; // -> 0xadc
static constexpr auto sGameComplexEventRecordOffset = 0xb09;
static constexpr auto sConversationChoiceMarkedFlag = 0x1d4c;
static constexpr auto sConversationOptionInhibitedFlag = 0x1a2c;
static constexpr auto sLockHasBeenSeenFlag = 0x1c5c;
// Based on disassembly this may be the state of doors (open/closed)
static constexpr auto sDoorFlag = 0x1b58;
}
| 1,019
|
C++
|
.h
| 20
| 46.5
| 70
| 0.780808
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,579
|
item.hpp
|
xavieran_BaKGL/bak/state/item.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
namespace BAK {
class GameState;
}
namespace BAK::State {
bool ReadItemHasBeenUsed(const GameState&, unsigned character, unsigned itemIndex);
void SetItemHasBeenUsed(FileBuffer&, unsigned character, unsigned itemIndex);
}
| 275
|
C++
|
.h
| 9
| 29
| 83
| 0.831418
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,580
|
lock.hpp
|
xavieran_BaKGL/bak/state/lock.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
namespace BAK {
class GameState;
}
namespace BAK::State {
void SetLockHasBeenSeen(FileBuffer&, unsigned lockIndex);
bool CheckLockHasBeenSeen(const GameState&, unsigned lockIndex);
}
| 237
|
C++
|
.h
| 9
| 24.666667
| 64
| 0.828829
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,581
|
encounter.hpp
|
xavieran_BaKGL/bak/state/encounter.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
#include "bak/encounter/encounter.hpp"
namespace BAK {
class GameState;
}
namespace BAK::State {
// Called by
// * checkBlockTriggered
// * checkTownTriggered
// * checkBackgroundTriggered
// * checkZoneTriggered,
// * doEnableEncounter
// * doDialogEncounter
// * doDisableEncounter
// * doSoundEncounter
bool CheckEncounterActive(
const GameState&,
const Encounter::Encounter& encounter,
ZoneNumber zone);
bool CheckCombatActive(
const GameState&,
const Encounter::Encounter& encounter,
ZoneNumber zone);
// Used by
// * Dialog
void SetPostDialogEventFlags(
FileBuffer&,
const Encounter::Encounter& encounter,
ZoneNumber zone);
// Used by
// * Background
// * Town
void SetPostGDSEventFlags(
FileBuffer&,
const Encounter::Encounter& encounter);
// Used by
// * Block
// * Disable
// * Enable
// * Sound
// * Zone
void SetPostEnableOrDisableEventFlags(
FileBuffer&,
const Encounter::Encounter& encounter,
ZoneNumber zone);
// For each encounter in every zone there is a unique enabled/disabled flag.
// This is reset every time a new chapter is loaded (I think);
unsigned CalculateUniqueEncounterStateFlagOffset(
ZoneNumber zone,
std::uint8_t tileIndex,
std::uint8_t encounterIndex);
bool CheckUniqueEncounterStateFlag(
const GameState&,
ZoneNumber zone,
std::uint8_t tileIndex,
std::uint8_t encounterIndex);
void SetUniqueEncounterStateFlag(
FileBuffer& fb,
ZoneNumber zone,
std::uint8_t tileIndex,
std::uint8_t encounterIndex,
bool value);
// 1450 is "recently encountered this encounter"
// should be cleared when we move to a new tile
// (or it will inhibit the events of the new tile)
unsigned CalculateRecentEncounterStateFlag(
std::uint8_t encounterIndex);
// 1464 is combat completed flag
unsigned CalculateCombatEncounterStateFlag(
unsigned combatIndex);
bool CheckCombatEncounterStateFlag(
const GameState&,
unsigned combatIndex);
void SetCombatEncounterState(
FileBuffer& fb,
unsigned combatIndex,
bool state);
// 145a is combat scouted flag
unsigned CalculateCombatEncounterScoutedStateFlag(
std::uint8_t encounterIndex);
void SetCombatEncounterScoutedState(
FileBuffer&,
std::uint8_t encounterIndex, bool state);
void SetRecentlyEncountered(FileBuffer&, std::uint8_t encounterIndex);
bool CheckRecentlyEncountered(const GameState&, std::uint8_t encounterIndex);
void ClearTileRecentEncounters(FileBuffer&);
void SetPostCombatCombatSpecificFlags(GameState& gs, unsigned combatIndex);
Time GetCombatClickedTime(FileBuffer& fb, unsigned combatIndex);
void SetCombatClickedTime(FileBuffer& fb, unsigned combatIndex, Time time);
}
| 2,755
|
C++
|
.h
| 91
| 27.43956
| 77
| 0.779796
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,582
|
skill.hpp
|
xavieran_BaKGL/bak/state/skill.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
namespace BAK::State {
bool ReadSkillSelected(FileBuffer&, unsigned character, unsigned skill);
bool ReadSkillUnseenImprovement(FileBuffer&, unsigned character, unsigned skill);
void ClearUnseenImprovements(FileBuffer&, unsigned character);
std::uint8_t ReadSelectedSkillPool(FileBuffer&, unsigned character);
void SetSelectedSkillPool(FileBuffer&, unsigned character, std::uint8_t value);
}
| 445
|
C++
|
.h
| 9
| 47.888889
| 81
| 0.837587
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,583
|
dialog.hpp
|
xavieran_BaKGL/bak/state/dialog.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
#include "bak/dialogAction.hpp"
namespace BAK {
class GameState;
}
namespace BAK::State {
void SetEventDialogAction(FileBuffer&, const SetFlag& setFlag);
bool ReadConversationItemClicked(const GameState&, unsigned eventPtr);
void SetConversationItemClicked(FileBuffer&, unsigned eventPtr);
bool CheckConversationOptionInhibited(const GameState&, unsigned eventPtr);
}
| 422
|
C++
|
.h
| 12
| 33.666667
| 75
| 0.844059
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,584
|
door.hpp
|
xavieran_BaKGL/bak/state/door.hpp
|
#pragma once
#include "bak/file/fileBuffer.hpp"
namespace BAK {
class GameState;
}
namespace BAK::State {
bool GetDoorState(const GameState&, unsigned doorIndex);
void SetDoorState(FileBuffer&, unsigned doorIndex, bool state);
}
| 235
|
C++
|
.h
| 9
| 24.444444
| 63
| 0.813636
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,585
|
eventFlag.hpp
|
xavieran_BaKGL/bak/encounter/eventFlag.hpp
|
#pragma once
#include "com/assert.hpp"
#include <cstdint>
#include <ostream>
#include <vector>
namespace BAK::Encounter {
struct EventFlag
{
EventFlag(
std::uint8_t percentChance,
std::uint16_t eventPointer,
bool isEnable)
:
mPercentChance{percentChance},
mEventPointer{eventPointer},
mIsEnable{isEnable}
{}
std::uint8_t mPercentChance;
std::uint16_t mEventPointer;
bool mIsEnable;
};
std::ostream& operator<<(std::ostream& os, const EventFlag&);
template <bool isEnable>
class EventFlagFactory
{
public:
static constexpr auto sEnable = "DEF_ENAB.DAT";
static constexpr auto sDisable = "DEF_DISA.DAT";
EventFlagFactory();
EventFlag Get(unsigned i) const;
private:
void Load();
std::vector<EventFlag> mEventFlags;
};
}
| 827
|
C++
|
.h
| 35
| 19.542857
| 61
| 0.703846
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,586
|
trap.hpp
|
xavieran_BaKGL/bak/encounter/trap.hpp
|
#pragma once
#include "bak/encounter/combat.ipp"
namespace BAK::Encounter {
using TrapFactory = GenericCombatFactory<true>;
}
| 130
|
C++
|
.h
| 5
| 24.2
| 47
| 0.818182
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,587
|
background.hpp
|
xavieran_BaKGL/bak/encounter/background.hpp
|
#pragma once
#include "bak/encounter/gdsEntry.ipp"
namespace BAK::Encounter {
struct backgroundFile { static constexpr auto file = "DEF_BKGR.DAT"; };
using BackgroundFactory = GDSEntryFactory<backgroundFile>;
}
| 216
|
C++
|
.h
| 6
| 34.166667
| 71
| 0.804878
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,588
|
town.hpp
|
xavieran_BaKGL/bak/encounter/town.hpp
|
#pragma once
#include "bak/encounter/gdsEntry.ipp"
namespace BAK::Encounter {
struct townFile { static constexpr auto file = "DEF_TOWN.DAT"; };
using TownFactory = GDSEntryFactory<townFile>;
}
| 198
|
C++
|
.h
| 6
| 31.166667
| 65
| 0.786096
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,589
|
zone.hpp
|
xavieran_BaKGL/bak/encounter/zone.hpp
|
#pragma once
#include "bak/coordinates.hpp"
#include "bak/types.hpp"
#include "bak/dialogTarget.hpp"
#include <glm/glm.hpp>
#include <vector>
namespace BAK::Encounter {
class Zone
{
public:
ZoneNumber mTargetZone;
GamePositionAndHeading mTargetLocation;
KeyTarget mDialog;
};
std::ostream& operator<<(std::ostream& os, const Zone&);
class ZoneFactory
{
public:
static constexpr auto sFilename = "DEF_ZONE.DAT";
ZoneFactory();
const Zone& Get(unsigned i) const;
private:
void Load();
std::vector<Zone> mZones;
};
}
| 557
|
C++
|
.h
| 26
| 18.769231
| 56
| 0.742308
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,590
|
encounter.hpp
|
xavieran_BaKGL/bak/encounter/encounter.hpp
|
#pragma once
#include "bak/constants.hpp"
#include "bak/encounter/background.hpp"
#include "bak/encounter/block.hpp"
#include "bak/encounter/combat.hpp"
#include "bak/encounter/dialog.hpp"
#include "bak/encounter/disable.hpp"
#include "bak/encounter/enable.hpp"
#include "bak/encounter/town.hpp"
#include "bak/encounter/trap.hpp"
#include "bak/encounter/zone.hpp"
#include "com/strongType.hpp"
#include <glm/glm.hpp>
#include <ostream>
#include <string_view>
#include <variant>
#include <vector>
namespace BAK::Encounter {
using EncounterIndex = StrongType<unsigned, struct EncounterIndexTag>;
// These are enumerated in "LIST_TYP.DAT"
enum class EncounterType : std::uint16_t
{
Background = 0, // DEF_BKGR.DAT?? teleport??
Combat = 1, // DEF_COMB.DAT
Comment = 2, // no file exists, but would be DEF_COMM.DAT
Dialog = 3, // DEF_DIAL.DAT
Health = 4, // no file exists, but would be DEF_HEAL.DAT
Sound = 5, // DEF_SOUN.DAT
Town = 6, // DEF_TOWN.DAT
Trap = 7, // DEF_TRAP.DAT
Zone = 8, // DEF_ZONE.DAT
Disable = 9, // DEF_DISA.DAT
Enable = 0xa, // DEF_ENAB.DAT
Block = 0xb // DEF_BLOC.DAT
};
std::string_view ToString(EncounterType t);
std::ostream& operator<<(std::ostream& os, EncounterType e);
using EncounterT = std::variant<
GDSEntry,
Block,
Combat,
Dialog,
EventFlag,
Zone>;
std::ostream& operator<<(std::ostream& os, const EncounterT&);
std::string_view ToString(const EncounterT&);
class EncounterFactory
{
public:
EncounterT MakeEncounter(
EncounterType,
unsigned,
glm::uvec2 tile) const;
private:
BackgroundFactory mBackgrounds;
BlockFactory mBlocks;
CombatFactory mCombats;
DialogFactory mDialogs;
DisableFactory mDisables;
EnableFactory mEnables;
TownFactory mTowns;
TrapFactory mTraps;
ZoneFactory mZones;
};
class Encounter
{
public:
Encounter(
EncounterT encounter,
EncounterIndex index,
glm::uvec2 topLeft,
glm::uvec2 bottomRight,
glm::uvec2 location,
glm::uvec2 dims,
glm::uvec2 tile,
unsigned tileIndex,
unsigned saveAddress,
unsigned saveAddress2,
unsigned saveAddress3,
std::uint8_t unknown0,
std::uint8_t unknown1,
std::uint8_t unknown2,
std::uint16_t unknown3)
:
mEncounter{encounter},
mIndex{index},
mTopLeft{topLeft},
mBottomRight{bottomRight},
mLocation{location},
mDimensions{dims},
mTile{tile},
mTileIndex{tileIndex},
mSaveAddress{saveAddress},
mSaveAddress2{saveAddress2},
mSaveAddress3{saveAddress3},
mUnknown0{unknown0},
mUnknown1{unknown1},
mUnknown2{unknown2},
mUnknown3{unknown3}
{}
const auto& GetEncounter() const { return mEncounter; }
// This is specifically the index of the encounter in the DAT file
// NOT the index of the encounter type in its table (DEF_BLOC etc.)
auto GetIndex() const { return mIndex; }
auto GetSaveAddress() const { return mSaveAddress; }
auto GetTile() const { return mTile; }
auto GetTileIndex() const { return mTileIndex; }
auto GetLocation() const
{
return ToGlCoord<float>(mLocation);
}
auto GetDims() const
{
return mDimensions;
}
EncounterT mEncounter;
EncounterIndex mIndex;
glm::uvec2 mTopLeft;
glm::uvec2 mBottomRight;
glm::uvec2 mLocation;
glm::uvec2 mDimensions;
glm::uvec2 mTile;
unsigned mTileIndex;
// Place in the save file that is checked
// by this encounter to see if it has
// already been encountered
unsigned mSaveAddress;
unsigned mSaveAddress2;
unsigned mSaveAddress3;
std::uint8_t mUnknown0;
std::uint8_t mUnknown1;
std::uint8_t mUnknown2;
std::uint16_t mUnknown3;
friend std::ostream& operator<<(std::ostream&, const Encounter&);
};
std::ostream& operator<<(std::ostream&, const Encounter&);
class EncounterStore
{
public:
EncounterStore(
const EncounterFactory&,
FileBuffer& fb,
glm::uvec2 tile,
unsigned tileIndex);
const std::vector<Encounter>& GetEncounters(
Chapter chapter) const;
private:
std::vector<
std::vector<Encounter>> mChapters;
};
std::vector<Encounter> LoadEncounters(
const EncounterFactory&,
FileBuffer& fb,
Chapter chapter,
glm::uvec2 tile,
unsigned tileIndex);
}
| 4,528
|
C++
|
.h
| 157
| 23.732484
| 71
| 0.680498
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,591
|
disable.hpp
|
xavieran_BaKGL/bak/encounter/disable.hpp
|
#pragma once
#include "bak/encounter/eventFlag.ipp"
namespace BAK::Encounter {
using DisableFactory = EventFlagFactory<false>;
}
| 133
|
C++
|
.h
| 5
| 24.8
| 47
| 0.822581
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,592
|
gdsEntry.hpp
|
xavieran_BaKGL/bak/encounter/gdsEntry.hpp
|
#pragma once
#include "bak/coordinates.hpp"
#include "bak/dialog.hpp"
#include "bak/hotspotRef.hpp"
#include "graphics/glm.hpp"
namespace BAK::Encounter {
// This is a GDS scene ala towns
struct RawGDSEntry
{
RawGDSEntry(
HotspotRef hotspot,
KeyTarget entryDialog,
KeyTarget exitDialog,
glm::vec<2, unsigned> exitOffset,
std::uint16_t exitHeading,
// Whether to animate travelling into the town
bool walkToDest)
:
mHotspot{hotspot},
mEntryDialog{entryDialog},
mExitDialog{exitDialog},
mExitOffset{exitOffset},
mExitHeading{exitHeading},
mWalkToDest{walkToDest}
{}
HotspotRef mHotspot;
KeyTarget mEntryDialog;
KeyTarget mExitDialog;
glm::vec<2, unsigned> mExitOffset;
std::uint16_t mExitHeading;
// Whether to animate travelling into the town
bool mWalkToDest;
};
struct GDSEntry
{
HotspotRef mHotspot;
KeyTarget mEntryDialog;
KeyTarget mExitDialog;
GamePositionAndHeading mExitPosition;
// Whether to animate travelling into the town
bool mWalkToDest;
};
std::ostream& operator<<(std::ostream& os, const GDSEntry&);
template <typename SourceFile>
class GDSEntryFactory
{
public:
static constexpr auto sFilename = SourceFile::file;
GDSEntryFactory();
GDSEntry Get(unsigned i, glm::vec<2, unsigned> tile) const;
private:
void Load();
std::vector<RawGDSEntry> mGDSEntrys;
};
}
| 1,475
|
C++
|
.h
| 55
| 22.163636
| 63
| 0.714996
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,593
|
teleport.hpp
|
xavieran_BaKGL/bak/encounter/teleport.hpp
|
#pragma once
#include "bak/coordinates.hpp"
#include "bak/hotspotRef.hpp"
#include "bak/types.hpp"
#include <optional>
namespace BAK::Encounter {
struct Teleport
{
Teleport(
std::optional<ZoneNumber> targetZone,
GamePositionAndHeading targetLocation,
std::optional<HotspotRef> targetGDSScene)
:
mTargetZone{targetZone},
mTargetLocation{targetLocation},
mTargetGDSScene{targetGDSScene}
{}
std::optional<ZoneNumber> mTargetZone;
GamePositionAndHeading mTargetLocation;
std::optional<HotspotRef> mTargetGDSScene;
};
std::ostream& operator<<(std::ostream& os, const Teleport&);
class TeleportFactory
{
public:
static constexpr auto sFilename = "TELEPORT.DAT";
TeleportFactory();
const Teleport& Get(unsigned i) const;
private:
void Load();
std::vector<Teleport> mTeleports;
};
}
| 878
|
C++
|
.h
| 33
| 22.484848
| 60
| 0.736211
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,594
|
block.hpp
|
xavieran_BaKGL/bak/encounter/block.hpp
|
#pragma once
#include "bak/dialogTarget.hpp"
namespace BAK::Encounter {
/*
3F 00 00 00
01 04 00 0F FE 1C 00 00 00
01 27 00 F5 32 29 00 00 00
*/
struct Block
{
Block(KeyTarget dialog) : mDialog{dialog} {}
KeyTarget mDialog;
};
std::ostream& operator<<(std::ostream& os, const Block&);
class BlockFactory
{
public:
static constexpr auto sFilename = "DEF_BLOC.DAT";
BlockFactory();
const Block& Get(unsigned i) const;
private:
void Load();
std::vector<Block> mBlocks;
};
}
| 508
|
C++
|
.h
| 25
| 17.8
| 57
| 0.710359
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,595
|
dialog.hpp
|
xavieran_BaKGL/bak/encounter/dialog.hpp
|
#pragma once
#include "bak/dialogTarget.hpp"
namespace BAK::Encounter {
struct Dialog {
Dialog(KeyTarget dialog) : mDialog{dialog} {}
KeyTarget mDialog;
};
std::ostream& operator<<(std::ostream& os, const Dialog&);
class DialogFactory
{
public:
static constexpr auto sFilename = "DEF_DIAL.DAT";
DialogFactory();
const Dialog& Get(unsigned i) const;
private:
void Load();
std::vector<Dialog> mDialogs;
};
}
| 443
|
C++
|
.h
| 19
| 20.368421
| 58
| 0.722892
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,596
|
enable.hpp
|
xavieran_BaKGL/bak/encounter/enable.hpp
|
#pragma once
#include "bak/encounter/eventFlag.ipp"
namespace BAK::Encounter {
using EnableFactory = EventFlagFactory<true>;
}
| 131
|
C++
|
.h
| 5
| 24.4
| 45
| 0.819672
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,597
|
combat.hpp
|
xavieran_BaKGL/bak/encounter/combat.hpp
|
#pragma once
#include "bak/coordinates.hpp"
#include "bak/dialogTarget.hpp"
#include "bak/types.hpp"
#include <optional>
#include <vector>
namespace BAK::Encounter {
// From REQ_TE13.DAT:
// Type (Monster type)
// Movement Style
// Where (location)
// Width
// Height
// Radius
// Road End 1
// Road End 2
struct CombatantData
{
CombatantData(
std::uint16_t monster,
std::uint16_t movementType,
GamePositionAndHeading location)
:
mMonster{monster},
mMovementType{movementType},
mLocation{location}
{}
std::uint16_t mMonster;
std::uint16_t mMovementType;
GamePositionAndHeading mLocation;
// path...
};
std::ostream& operator<<(std::ostream&, const CombatantData&);
// From REQ_TE12.DAT:
// Combat Situation
// Objects
// Enter Dialogue
// Scout Dialogue
// Ambush / Regular
// North Retreat
// West Retreat
// South Retreat
// East Retreat
class Combat
{
public:
Combat(
unsigned combatIndex,
KeyTarget entryDialog,
KeyTarget scoutDialog,
std::optional<GamePositionAndHeading> trap,
GamePositionAndHeading northRetreat,
GamePositionAndHeading westRetreat,
GamePositionAndHeading southRetreat,
GamePositionAndHeading eastRetreat,
std::vector<CombatantData> combatants,
std::uint16_t unknown,
bool isAmbush)
:
mCombatIndex{combatIndex},
mEntryDialog{entryDialog},
mScoutDialog{scoutDialog},
mTrap{trap},
mNorthRetreat{northRetreat},
mWestRetreat{westRetreat},
mSouthRetreat{southRetreat},
mEastRetreat{eastRetreat},
mCombatants{combatants},
mUnknown{unknown},
mIsAmbush{isAmbush}
{}
unsigned mCombatIndex;
KeyTarget mEntryDialog;
KeyTarget mScoutDialog;
std::optional<GamePositionAndHeading> mTrap;
GamePositionAndHeading mNorthRetreat;
GamePositionAndHeading mWestRetreat;
GamePositionAndHeading mSouthRetreat;
GamePositionAndHeading mEastRetreat;
std::vector<CombatantData> mCombatants;
std::uint16_t mUnknown;
// ambushes are not visible, but are scoutable
// not ambushes are visible, but not scoutable
bool mIsAmbush;
};
std::ostream& operator<<(std::ostream&, const Combat&);
template <bool isTrap>
class GenericCombatFactory
{
public:
static constexpr auto sCombatFilename = "DEF_COMB.DAT";
static constexpr auto sTrapFilename = "DEF_TRAP.DAT";
GenericCombatFactory();
const Combat& Get(unsigned i) const;
private:
void Load();
std::vector<Combat> mCombats;
};
using CombatFactory = GenericCombatFactory<false>;
}
| 2,681
|
C++
|
.h
| 100
| 22.21
| 62
| 0.715736
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,598
|
audio.hpp
|
xavieran_BaKGL/audio/audio.hpp
|
#pragma once
#include "com/logger.hpp"
#include "com/strongType.hpp"
#include "com/visit.hpp"
#include <SDL2/SDL.h>
#include "SDL_mixer_ext/SDL_mixer_ext.h"
#include <chrono>
#include <ostream>
#include <queue>
#include <stack>
#include <thread>
#include <variant>
namespace AudioA {
static constexpr auto MIN_SOUND = 1;
static constexpr auto MAX_SOUND = 134;
static constexpr auto MIN_SONG = 1001;
static constexpr auto MAX_SONG = 1063;
using SoundIndex = Bounded<StrongType<unsigned, struct SoundIndexTag>, MIN_SOUND, MAX_SOUND>;
using MusicIndex = Bounded<StrongType<unsigned, struct MusicIndexTag>, MIN_SONG, MAX_SONG>;
static constexpr auto PUZZLE_CHEST_THEME = MusicIndex{1003};
static constexpr auto BAD_BARD = MusicIndex{1008};
static constexpr auto POOR_BARD = MusicIndex{1040};
static constexpr auto GOOD_BARD = MusicIndex{1039};
static constexpr auto BEST_BARD = MusicIndex{1007};
enum class MidiPlayer
{
ADLMIDI = 0,
OPNMIDI = 1,
FluidSynth = 2
};
class AudioManager
{
static constexpr auto sAudioRate{MIX_DEFAULT_FREQUENCY};
static constexpr auto sAudioFormat{MIX_DEFAULT_FORMAT};
static constexpr auto sAudioChannels{MIX_DEFAULT_CHANNELS};
static constexpr auto sAudioBuffers{4096};
static constexpr auto sAudioVolume{MIX_MAX_VOLUME};
static constexpr auto sMusicTempo{0.9};
static constexpr auto sFadeOutTime{1500};
using Sound = std::variant<Mix_Music*, Mix_Chunk*>;
public:
static AudioManager& Get();
void ChangeMusicTrack(MusicIndex);
void PopTrack();
void PauseMusicTrack();
void PlayMusicTrack();
void StopMusicTrack();
void PlaySound(SoundIndex);
void PlaySoundImpl(SoundIndex);
void SwitchMidiPlayer(MidiPlayer);
private:
void PlayTrack(Mix_Music* music);
Sound GetSound(SoundIndex);
Mix_Music* GetMusic(MusicIndex);
static void RewindMusic(Mix_Music*, void*);
void ClearSounds();
AudioManager();
~AudioManager();
Mix_Music* mCurrentMusicTrack;
std::stack<Mix_Music*> mMusicStack;
std::queue<SoundIndex> mSoundQueue;
bool mSoundPlaying;
std::unordered_map<SoundIndex, Sound> mSoundData;
std::unordered_map<MusicIndex, Mix_Music*> mMusicData;
bool mRunning;
std::thread mQueuePlayThread;
const Logging::Logger& mLogger;
};
}
| 2,321
|
C++
|
.h
| 69
| 30.130435
| 93
| 0.755286
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,599
|
shaders.hpp
|
xavieran_BaKGL/shaders/shaders.hpp
|
#pragma once
#include <optional>
#include <string>
namespace Shaders
{
std::optional<std::string> GetFile(std::string shaderFile);
}
| 136
|
C++
|
.h
| 7
| 18
| 59
| 0.793651
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,600
|
systems.hpp
|
xavieran_BaKGL/game/systems.hpp
|
#pragma once
#include "bak/constants.hpp"
#include "bak/types.hpp"
#include "com/visit.hpp"
#include "graphics/glm.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/intersect.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <optional>
#include <variant>
#include <vector>
class Intersectable
{
public:
struct Rect
{
double mWidth;
double mHeight;
};
struct Circle
{
double mRadius;
};
using IntersectionType = std::variant<Circle, Rect>;
Intersectable(
BAK::EntityIndex itemId,
IntersectionType intersection,
glm::vec3 location)
:
mItemId{itemId},
mIntersection{intersection},
mLocation{location}
{}
BAK::EntityIndex GetId() const { return mItemId; }
bool Intersects(glm::vec3 position) const
{
return std::visit(
overloaded{
[&](const Rect& rect) -> bool
{
const auto x_d = rect.mWidth / 2;
const auto z_d = rect.mHeight / 2;
return ((mLocation.x - x_d) < position.x)
&& ((mLocation.x + x_d) > position.x)
&& ((mLocation.z - z_d) < position.z)
&& ((mLocation.z + z_d) > position.z);
},
[&](const Circle& circle)
{
auto distance = glm::distance(mLocation, position);
return distance < circle.mRadius;
}
},
mIntersection);
}
auto GetLocation() const { return mLocation; }
private:
BAK::EntityIndex mItemId;
IntersectionType mIntersection;
glm::vec3 mLocation;
};
class Clickable
{
public:
explicit Clickable(
BAK::EntityIndex itemId)
:
mItemId{itemId}
{}
BAK::EntityIndex GetId() const { return mItemId; }
private:
BAK::EntityIndex mItemId;
};
class Renderable
{
public:
Renderable(
BAK::EntityIndex itemId,
std::pair<unsigned, unsigned> object,
glm::vec3 location,
glm::vec3 rotation,
glm::vec3 scale)
:
mItemId{itemId},
mObject{object},
mLocation{location},
mRotation{rotation},
mScale{scale},
mModelMatrix{CalculateModelMatrix()}
{}
BAK::EntityIndex GetId() const { return mItemId; }
const glm::mat4& GetModelMatrix() const
{
return mModelMatrix;
}
const auto& GetLocation() const { return mLocation; }
std::pair<unsigned, unsigned> GetObject() const
{
return mObject;
}
private:
glm::mat4 CalculateModelMatrix()
{
auto modelMatrix = glm::mat4{1.0};
modelMatrix = glm::translate(modelMatrix, mLocation / BAK::gWorldScale);
modelMatrix = glm::scale(modelMatrix, mScale);
// Dodgy... only works for rotation about y
modelMatrix = glm::rotate(
modelMatrix,
mRotation.y,
glm::vec3(0,1,0));
return modelMatrix;
}
BAK::EntityIndex mItemId;
std::pair<unsigned, unsigned> mObject;
glm::vec3 mLocation;
glm::vec3 mRotation;
glm::vec3 mScale;
glm::mat4 mModelMatrix;
};
class Systems
{
public:
Systems()
:
mNextItemId{0}
{}
BAK::EntityIndex GetNextItemId()
{
return BAK::EntityIndex{mNextItemId++};
}
void AddIntersectable(const Intersectable& item)
{
mIntersectables.emplace_back(item);
}
void AddClickable(const Clickable& item)
{
mClickables.emplace_back(item);
}
void AddRenderable(const Renderable& item)
{
mRenderables.emplace_back(item);
}
void RemoveRenderable(BAK::EntityIndex i)
{
auto it = std::find_if(
mRenderables.begin(), mRenderables.end(),
[i=i](const auto& r){ return r.GetId() == i; });
if (it != mRenderables.end())
mRenderables.erase(it);
}
void AddSprite(const Renderable& item)
{
mSprites.emplace_back(item);
}
std::optional<BAK::EntityIndex> RunIntersection(glm::vec3 cameraPos) const
{
for (const auto& item : GetIntersectables())
{
if (item.Intersects(cameraPos))
return item.GetId();
}
return std::optional<BAK::EntityIndex>{};
}
const std::vector<Intersectable>& GetIntersectables() const { return mIntersectables; }
const std::vector<Renderable>& GetRenderables() const { return mRenderables; }
const std::vector<Renderable>& GetSprites() const { return mSprites; }
const std::vector<Clickable>& GetClickables() const { return mClickables; }
private:
unsigned mNextItemId;
std::vector<Intersectable> mIntersectables;
std::vector<Renderable> mRenderables;
std::vector<Renderable> mSprites;
std::vector<Clickable> mClickables;
};
| 4,972
|
C++
|
.h
| 176
| 21.056818
| 91
| 0.606099
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,601
|
gameRunner.hpp
|
xavieran_BaKGL/game/gameRunner.hpp
|
#pragma once
#include "game/interactable/factory.hpp"
#include "game/systems.hpp"
#include "bak/IZoneLoader.hpp"
#include "bak/camera.hpp"
#include "bak/chapterTransitions.hpp"
#include "bak/coordinates.hpp"
#include "bak/dialog.hpp"
#include "bak/encounter/encounter.hpp"
#include "bak/encounter/teleport.hpp"
#include "bak/monster.hpp"
#include "bak/state/encounter.hpp"
#include "bak/state/event.hpp"
#include "bak/time.hpp"
#include "bak/types.hpp"
#include "bak/zone.hpp"
#include "com/logger.hpp"
#include "gui/guiManager.hpp"
#include <unordered_set>
namespace Game {
class ClickableEntity
{
public:
BAK::EntityType mEntityType;
BAK::GenericContainer* mContainer;
};
class GameRunner : public BAK::IZoneLoader
{
public:
GameRunner(
Camera& camera,
BAK::GameState& gameState,
Gui::GuiManager& guiManager,
std::function<void(const BAK::Zone&)>&& loadRenderer)
:
mCamera{camera},
mGameState{gameState},
mGuiManager{guiManager},
mInteractableFactory{
mGuiManager,
mGameState,
[this](const auto& pos){ CheckAndDoEncounter(pos); }},
mCurrentInteractable{nullptr},
mDynamicDialogScene{
[&](){ mCamera.SetAngle(mSavedAngle); },
[&](){ mCamera.SetAngle(mSavedAngle + glm::vec2{3.14, 0}); },
[&](const auto&){ }
},
mGameData{nullptr},
mZoneData{nullptr},
mActiveEncounter{nullptr},
mEncounters{},
mClickables{},
mNullContainer{
BAK::ContainerHeader{},
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
BAK::Inventory{0}},
mSystems{nullptr},
mSavedAngle{0},
mLoadRenderer{std::move(loadRenderer)},
mTeleportFactory{},
mClickablesEnabled{false},
mLogger{Logging::LogState::GetLogger("Game::GameRunner")}
{
ASSERT(mLoadRenderer);
}
void DoTeleport(BAK::Encounter::Teleport teleport) override
{
mLogger.Debug() << "Teleporting to: " << teleport << "\n";
if (teleport.mTargetZone)
{
DoTransition(
*teleport.mTargetZone,
teleport.mTargetLocation);
}
if (teleport.mTargetGDSScene)
{
mGuiManager.TeleportToGDS(
*teleport.mTargetGDSScene);
}
}
void LoadGame(std::string savePath, std::optional<BAK::Chapter> chapter) override
{
mGameData = std::make_unique<BAK::GameData>(savePath);
mGameState.LoadGameData(mGameData.get());
if (chapter)
{
BAK::TransitionToChapter(*chapter, mGameState);
}
LoadZoneData(mGameState.GetZone());
}
void LoadZoneData(BAK::ZoneNumber zone)
{
mZoneData = std::make_unique<BAK::Zone>(zone.mValue);
mLoadRenderer(*mZoneData);
LoadSystems();
mCamera.SetGameLocation(mGameState.GetLocation());
}
void DoTransition(
BAK::ZoneNumber targetZone,
BAK::GamePositionAndHeading targetLocation)
{
mGameState.SetLocation(
BAK::Location{
targetZone,
BAK::GetTile(targetLocation.mPosition),
targetLocation});
LoadZoneData(targetZone);
}
void LoadSystems()
{
mSystems = std::make_unique<Systems>();
mEncounters.clear();
mClickables.clear();
mActiveEncounter = nullptr;
std::vector<glm::uvec2> handledLocations{};
for (const auto& world : mZoneData->mWorldTiles.GetTiles())
{
for (const auto& item : world.GetItems())
{
if (item.GetZoneItem().GetVertices().size() > 1)
{
auto id = mSystems->GetNextItemId();
auto renderable = Renderable{
id,
mZoneData->mObjects.GetObject(item.GetZoneItem().GetName()),
item.GetLocation(),
item.GetRotation(),
glm::vec3{static_cast<float>(item.GetZoneItem().GetScale())}};
if (item.GetZoneItem().IsSprite())
mSystems->AddSprite(renderable);
else
mSystems->AddRenderable(renderable);
if (item.GetZoneItem().GetClickable())
{
const auto bakLocation = item.GetBakLocation();
const auto et = item.GetZoneItem().GetEntityType();
mSystems->AddClickable(Clickable{id});
auto& containers = mGameState.GetContainers(
BAK::ZoneNumber{mZoneData->mZoneLabel.GetZoneNumber()});
auto cit = std::find_if(containers.begin(), containers.end(),
[&](const auto& x){
return x.GetHeader().GetPosition() == bakLocation
&& x.GetHeader().PresentInChapter(mGameState.GetChapter());
});
if (cit != containers.end())
{
mClickables.emplace(id, ClickableEntity{et, &(*cit)});
handledLocations.emplace_back(item.GetBakLocation());
continue;
}
auto fit = std::find_if(
mZoneData->mFixedObjects.begin(),
mZoneData->mFixedObjects.end(),
[&](const auto& x){
return x.GetHeader().GetPosition() == bakLocation
&& x.GetHeader().PresentInChapter(mGameState.GetChapter());
});
if (fit != mZoneData->mFixedObjects.end())
{
mClickables.emplace(id, ClickableEntity{et, &(*fit)});
handledLocations.emplace_back(item.GetBakLocation());
continue;
}
mClickables.emplace(id, ClickableEntity{et, &mNullContainer});
}
}
}
}
auto& containers = mGameState.GetContainers(
BAK::ZoneNumber{mZoneData->mZoneLabel.GetZoneNumber()});
for (auto& container : containers)
{
const auto& header = container.GetHeader();
const auto bakPosition = header.GetPosition();
if ((std::find(handledLocations.begin(), handledLocations.end(), bakPosition) != handledLocations.end())
|| !header.PresentInChapter(mGameState.GetChapter()))
{
continue;
}
handledLocations.emplace_back(bakPosition);
mLogger.Spam() << "Hidden container found: " << container << "\n";
const auto id = mSystems->GetNextItemId();
const auto& item = mZoneData->mZoneItems.GetZoneItem(header.GetModel());
const auto location = BAK::ToGlCoord<float>(bakPosition);
auto renderable = Renderable{
id,
mZoneData->mObjects.GetObject(item.GetName()),
location,
glm::vec3{},
glm::vec3{static_cast<float>(item.GetScale())}};
mSystems->AddRenderable(renderable);
mSystems->AddClickable(Clickable{id});
mClickables.emplace(id, ClickableEntity(BAK::EntityTypeFromModelName(item.GetName()), &container));
}
auto& fixedObjects = mZoneData->mFixedObjects;
for (auto& container : fixedObjects)
{
const auto& header = container.GetHeader();
const auto bakPosition = header.GetPosition();
if ((std::find(handledLocations.begin(), handledLocations.end(), bakPosition) != handledLocations.end())
|| !header.PresentInChapter(mGameState.GetChapter()))
{
continue;
}
handledLocations.emplace_back(bakPosition);
mLogger.Debug() << "Hidden container found: " << container << "\n";
const auto id = mSystems->GetNextItemId();
const auto& item = mZoneData->mZoneItems.GetZoneItem(header.GetModel());
const auto location = BAK::ToGlCoord<float>(bakPosition);
auto renderable = Renderable{
id,
mZoneData->mObjects.GetObject(item.GetName()),
location,
glm::vec3{},
glm::vec3{static_cast<float>(item.GetScale())}};
mSystems->AddRenderable(renderable);
mSystems->AddClickable(Clickable{id});
mClickables.emplace(id, ClickableEntity(BAK::EntityTypeFromModelName(item.GetName()), &container));
}
const auto monsters = BAK::MonsterNames::Get();
for (const auto& world : mZoneData->mWorldTiles.GetTiles())
{
for (const auto& enc : world.GetEncounters(mGameState.GetChapter()))
{
auto id = mSystems->GetNextItemId();
const auto dims = enc.GetDims();
//if (std::holds_alternative<BAK::Encounter::Dialog>(enc.GetEncounter()))
//{
// mSystems->AddRenderable(
// Renderable{
// id,
// mZoneData->mObjects.GetObject(std::string{BAK::Encounter::ToString(enc.GetEncounter())}),
// enc.GetLocation(),
// glm::vec3{0.0},
// glm::vec3{dims.x, 50.0, dims.y} / BAK::gWorldScale});
//}
mSystems->AddIntersectable(
Intersectable{
id,
Intersectable::Rect{
static_cast<double>(dims.x),
static_cast<double>(dims.y)},
enc.GetLocation()});
// Throw the enemies onto the map...
evaluate_if<BAK::Encounter::Combat>(enc.GetEncounter(),
[&](const auto& combat){
for (unsigned i = 0; i < combat.mCombatants.size(); i++)
{
const auto& enemy = combat.mCombatants[i];
auto entityId = mSystems->GetNextItemId();
mSystems->AddRenderable(
Renderable{
entityId,
mZoneData->mObjects.GetObject(
monsters.GetMonsterAnimationFile(BAK::MonsterIndex{enemy.mMonster - 1u})),
BAK::ToGlCoord<float>(enemy.mLocation.mPosition),
glm::vec3{0},
glm::vec3{1}});
auto& containers = mGameState.GetCombatContainers();
auto container = std::find_if(containers.begin(), containers.end(),
[&](auto& lhs){
return lhs.GetHeader().GetCombatNumber() == combat.mCombatIndex
&& lhs.GetHeader().GetCombatantNumber() == i;
});
if (container != containers.end())
{
mSystems->AddClickable(Clickable{entityId});
mClickables.emplace(entityId, ClickableEntity(BAK::EntityType::DEAD_COMBATANT, &(*container)));
}
}
});
mEncounters.emplace(id, &enc);
}
}
}
void DoGenericContainer(BAK::EntityType et, BAK::GenericContainer& container)
{
mLogger.Debug() << __FUNCTION__ << " "
<< static_cast<unsigned>(et) << " " << container << "\n";
mCurrentInteractable = mInteractableFactory.MakeInteractable(et);
ASSERT(mCurrentInteractable);
mCurrentInteractable->BeginInteraction(container, et);
}
// Returns <combatActive, combatScouted>
std::pair<bool, bool> CheckCombatEncounter(
const BAK::Encounter::Encounter& encounter,
const BAK::Encounter::Combat& combat)
{
mLogger.Info() << __FUNCTION__ << " Checking combat active\n";
if (!BAK::State::CheckCombatActive(mGameState, encounter, mGameState.GetZone()))
{
mLogger.Info() << __FUNCTION__ << " Combat inactive\n";
return std::make_pair(false, false);
}
if (!combat.mIsAmbush)
{
mLogger.Info() << __FUNCTION__ << " Combat is not ambush\n";
return std::make_pair(true, false);
}
else
{
// This seems to be a variable used to prevent the scouting of multiple combats
// at once...
const auto arg_dontDoCombatIfIsAmbush = false;
if (arg_dontDoCombatIfIsAmbush)
{
return std::make_pair(false, false);
}
else
{
if (!BAK::State::CheckRecentlyEncountered(mGameState, encounter.GetIndex().mValue))
{
mGameState.Apply(BAK::State::SetRecentlyEncountered, encounter.GetIndex().mValue);
auto chance = GetRandomNumber(0, 0xfff) % 100;
const auto [character, scoutSkill] = mGameState.GetPartySkill(BAK::SkillType::Scouting, true);
mLogger.Info() << __FUNCTION__ << " Trying to scout combat: "
<< scoutSkill << " chance: " << chance << "\n";
if (scoutSkill > chance)
{
mGameState.GetParty().ImproveSkillForAll(
BAK::SkillType::Scouting, BAK::SkillChange::ExercisedSkill, 1);
mGuiManager.StartDialog(
combat.mScoutDialog,
false,
false,
&mDynamicDialogScene);
mGameState.Apply(BAK::State::SetCombatEncounterScoutedState,
encounter.GetIndex().mValue, true);
return std::make_pair(false, true);
}
else
{
return std::make_pair(true, false);
}
}
else
{
mLogger.Info() << __FUNCTION__ << " Combat was scouted already\n";
return std::make_pair(true, false);
}
}
}
}
void CheckAndDoCombatEncounter(
const BAK::Encounter::Encounter& encounter,
const BAK::Encounter::Combat& combat)
{
const auto [combatActive, combatScouted] = CheckCombatEncounter(encounter, combat);
mLogger.Debug() << __FUNCTION__ << " Combat checked, result: [" << combatActive << ", " << combatScouted << "]\n";
if (!combatActive)
{
mLogger.Debug() << __FUNCTION__ << " Combat not active, not doing it\n";
return;
}
const auto [character, stealthSkill] = mGameState.GetPartySkill(BAK::SkillType::Stealth, false);
auto lowestStealth = stealthSkill;
if (lowestStealth < 0x5a) // 90
{
lowestStealth *= 0x1e; // 30
lowestStealth += (lowestStealth / 100);
}
if (lowestStealth > 0x5a) lowestStealth = 0x5a;
if (combat.mIsAmbush)
{
if (mGameState.GetSpellActive(BAK::StaticSpells::DragonsBreath))
{
lowestStealth = lowestStealth + ((100 - lowestStealth) >> 1);
}
}
auto chance = GetRandomNumber(0, 0xfff) % 100;
if (lowestStealth > chance)
{
mGameState.GetParty().ImproveSkillForAll(
BAK::SkillType::Stealth , BAK::SkillChange::ExercisedSkill, 1);
mLogger.Debug() << __FUNCTION__ << " Avoided combat due to stealth\n";
return;
}
// Check whether players are in valid combatable position???
auto timeOfScouting = mGameState.Apply(BAK::State::GetCombatClickedTime, combat.mCombatIndex);
auto timeDiff = (mGameState.GetWorldTime().GetTime()- timeOfScouting).mTime;
if ((timeDiff / 0x1e) < 0x1e) // within scouting valid time
{
auto chance = GetRandomNumber(0, 0xfff) % 100;
if (chance > lowestStealth)
{
// failed to sneak up
mGameState.SetDialogContext_7530(1);
}
else
{
// Successfully snuck
mGameState.GetParty().ImproveSkillForAll(
BAK::SkillType::Stealth , BAK::SkillChange::ExercisedSkill, 1);
mGameState.SetDialogContext_7530(0);
}
}
else
{
mGameState.SetDialogContext_7530(2);
}
if (!combat.mCombatants.empty())
{
mGameState.SetMonster(BAK::MonsterIndex{combat.mCombatants.back().mMonster + 1u});
}
if (combat.mEntryDialog.mValue != 0)
{
mGuiManager.StartDialog(
combat.mEntryDialog,
false,
false,
&mDynamicDialogScene);
}
// The below needs to be called in the return from the combat screen
bool combatRetreated;
//auto combatResult = EnterCombatScreen(surprisedEnemy, &combatRetreated);
auto combatResult = 1;
//recordTimeOfCombat at (combatIndex << 2) + 0x3967
if (combatResult == 2)
{
// retreat to a combat retreat location based on player entry
}
else if (combatResult == 1)
{
// Victory?
if (encounter.mSaveAddress3 != 0)
{
mGameState.Apply(BAK::State::SetEventFlagTrue, encounter.mSaveAddress3);
}
}
mGameState.Apply(
BAK::State::SetUniqueEncounterStateFlag,
mGameState.GetZone(),
encounter.GetTileIndex(),
encounter.GetIndex().mValue,
true);
mGameState.Apply(
BAK::State::SetCombatEncounterState,
combat.mCombatIndex,
true);
BAK::State::SetPostCombatCombatSpecificFlags(mGameState, combat.mCombatIndex);
// This is a part of the above function, but I separate it out here
// to keep things cleaner. Yes this is hardcoded in the game code.
static constexpr auto NagoCombatIndex = 74;
if (combat.mCombatIndex == NagoCombatIndex)
{
// I happen to know all this "dialog" does is set a bunch of flags,
// so it's safe to do this rather than triggering an actual dialog.
for (const auto& action : BAK::DialogStore::Get().GetSnippet(BAK::DialogSources::mAfterNagoCombatSetKeys).mActions)
{
mGameState.EvaluateAction(action);
}
}
if (combatResult == 3)
{
}
}
void DoBlockEncounter(
const BAK::Encounter::Encounter& encounter,
const BAK::Encounter::Block& block)
{
if (!BAK::State::CheckEncounterActive(mGameState, encounter, mGameState.GetZone()))
return;
mGuiManager.StartDialog(
block.mDialog,
false,
false,
&mDynamicDialogScene);
mCamera.UndoPositionChange();
mGameState.Apply(
BAK::State::SetPostEnableOrDisableEventFlags,
encounter,
mGameState.GetZone());
}
void DoEventFlagEncounter(
const BAK::Encounter::Encounter& encounter,
const BAK::Encounter::EventFlag& flag)
{
if (!BAK::State::CheckEncounterActive(mGameState, encounter, mGameState.GetZone()))
return;
if (flag.mEventPointer != 0)
mGameState.SetEventValue(flag.mEventPointer, flag.mIsEnable ? 1 : 0);
mGameState.Apply(
BAK::State::SetPostEnableOrDisableEventFlags,
encounter,
mGameState.GetZone());
}
void DoZoneEncounter(
const BAK::Encounter::Encounter& encounter,
const BAK::Encounter::Zone& zone)
{
if (!BAK::State::CheckEncounterActive(mGameState, encounter, mGameState.GetZone()))
return;
const auto& choices = BAK::DialogStore::Get().GetSnippet(zone.mDialog).mChoices;
const bool isNoAffirmative = choices.size() == 2
&& std::holds_alternative<BAK::QueryChoice>(choices.begin()->mChoice)
&& std::get<BAK::QueryChoice>(choices.begin()->mChoice).mQueryIndex == BAK::Keywords::sNoIndex;
mDynamicDialogScene.SetDialogFinished(
[&, isNoAffirmative=isNoAffirmative, zone=zone](const auto& choice){
// These dialogs should always result in a choice
ASSERT(choice);
Logging::LogDebug("Game::GameRunner") << "Switch to zone: " << zone << " got choice: " << choice << "\n";
if ((choice->mValue == BAK::Keywords::sYesIndex && !isNoAffirmative)
|| (choice->mValue == BAK::Keywords::sNoIndex && isNoAffirmative))
{
DoTransition(
zone.mTargetZone,
zone.mTargetLocation);
Logging::LogDebug("Game::GameRunner") << "Transition to: " << zone.mTargetZone << " complete\n";
}
else
{
mCamera.UndoPositionChange();
}
mDynamicDialogScene.ResetDialogFinished();
});
mLogger.Info() << "Zone transition: " << zone << "\n";
mGuiManager.StartDialog(
zone.mDialog,
false,
false,
&mDynamicDialogScene);
}
void DoDialogEncounter(
const BAK::Encounter::Encounter& encounter,
const BAK::Encounter::Dialog& dialog)
{
if (!BAK::State::CheckEncounterActive(mGameState, encounter, mGameState.GetZone()))
return;
mSavedAngle = mCamera.GetAngle();
mDynamicDialogScene.SetDialogFinished(
[&](const auto&){
mCamera.SetAngle(mSavedAngle);
mDynamicDialogScene.ResetDialogFinished();
});
mGuiManager.StartDialog(
dialog.mDialog,
false,
true,
&mDynamicDialogScene);
mGameState.Apply(
BAK::State::SetPostDialogEventFlags,
encounter,
mGameState.GetZone());
}
void DoGDSEncounter(
const BAK::Encounter::Encounter& encounter,
const BAK::Encounter::GDSEntry& gds)
{
// Pretty sure GDS encoutners will always happen...
//if (!mGameState.Apply(BAK::State::CheckEncounterActive, encounter, mGameState.GetZone()))
// return;
mDynamicDialogScene.SetDialogFinished(
[&, gds=gds](const auto& choice){
// These dialogs should always result in a choice
ASSERT(choice);
if (choice->mValue == BAK::Keywords::sYesIndex)
{
mGuiManager.DoFade(.8, [this, gds=gds]{
mGuiManager.EnterGDSScene(
gds.mHotspot,
[&, exitDialog=gds.mExitDialog](){
mGuiManager.StartDialog(
exitDialog,
false,
false,
&mDynamicDialogScene);
});
mCamera.SetGameLocation(gds.mExitPosition);
});
}
else
{
mCamera.UndoPositionChange();
}
mGameState.Apply(BAK::State::SetPostGDSEventFlags, encounter);
mDynamicDialogScene.ResetDialogFinished();
});
mGuiManager.StartDialog(
gds.mEntryDialog,
false,
false,
&mDynamicDialogScene);
}
void DoEncounter(const BAK::Encounter::Encounter& encounter)
{
mLogger.Spam() << "Doing Encounter: " << encounter << "\n";
std::visit(
overloaded{
[&](const BAK::Encounter::GDSEntry& gds){
if (mGuiManager.InMainView())
DoGDSEncounter(encounter, gds);
},
[&](const BAK::Encounter::Block& block){
if (mGuiManager.InMainView())
DoBlockEncounter(encounter, block);
},
[&](const BAK::Encounter::Combat& combat){
if (mGuiManager.InMainView())
CheckAndDoCombatEncounter(encounter, combat);
},
[&](const BAK::Encounter::Dialog& dialog){
if (mGuiManager.InMainView())
DoDialogEncounter(encounter, dialog);
},
[&](const BAK::Encounter::EventFlag& flag){
if (mGuiManager.InMainView())
DoEventFlagEncounter(encounter, flag);
},
[&](const BAK::Encounter::Zone& zone){
if (mGuiManager.InMainView())
DoZoneEncounter(encounter, zone);
},
},
encounter.GetEncounter());
}
void CheckAndDoEncounter(glm::uvec2 position)
{
mLogger.Debug() << __FUNCTION__ << " Pos: " << position << "\n";
auto intersectable = mSystems->RunIntersection(
BAK::ToGlCoord<float>(position));
if (intersectable)
{
auto it = mEncounters.find(*intersectable);
if (it != mEncounters.end())
{
const auto* encounter = it->second;
mActiveEncounter = encounter;
if (mActiveEncounter)
DoEncounter(*mActiveEncounter);
}
}
}
void RunGameUpdate()
{
if (mCamera.CheckAndResetDirty())
{
// This class var is only really necessary so that
// we can us IMGUI to pull the latest triggered interactable.
// Might want to clean this up.
mActiveEncounter = nullptr;
auto intersectable = mSystems->RunIntersection(mCamera.GetPosition());
if (intersectable)
{
auto it = mEncounters.find(*intersectable);
if (it != mEncounters.end())
{
const auto* encounter = it->second;
mActiveEncounter = encounter;
}
}
if (auto unitsTravelled = mCamera.GetAndClearUnitsTravelled(); unitsTravelled > 0)
{
//auto camp = BAK::TimeChanger{mGameState};
//camp.ElapseTimeInMainView(
// BAK::Time{0x1e * unitsTravelled});
}
if (mActiveEncounter)
{
DoEncounter(*mActiveEncounter);
}
}
}
void CheckClickable(unsigned entityId)
{
assert(mSystems);
auto bestId = std::optional<BAK::EntityIndex>{};
for (const auto& entity : mSystems->GetClickables())
{
if (entity.GetId().mValue == entityId)
{
bestId = entity.GetId();
break;
}
}
mLogger.Debug() << "Checked clickable entity id: " << entityId
<< " found: " << bestId << "\n";
if (bestId)
{
auto it = mClickables.find(*bestId);
assert (it != mClickables.end());
auto& clickable = mClickables[*bestId];
assert(clickable.mContainer);
DoGenericContainer(clickable.mEntityType, *clickable.mContainer);
}
}
Camera& mCamera;
BAK::GameState& mGameState;
Gui::GuiManager& mGuiManager;
InteractableFactory mInteractableFactory;
std::unique_ptr<IInteractable> mCurrentInteractable;
Gui::DynamicDialogScene mDynamicDialogScene;
std::unique_ptr<BAK::GameData> mGameData;
std::unique_ptr<BAK::Zone> mZoneData;
const BAK::Encounter::Encounter* mActiveEncounter;
std::unordered_map<BAK::EntityIndex, const BAK::Encounter::Encounter*> mEncounters;
std::unordered_map<BAK::EntityIndex, ClickableEntity> mClickables{};
BAK::GenericContainer mNullContainer;
std::unique_ptr<Systems> mSystems;
glm::vec2 mSavedAngle;
std::function<void(const BAK::Zone&)> mLoadRenderer;
BAK::Encounter::TeleportFactory mTeleportFactory;
bool mClickablesEnabled;
const Logging::Logger& mLogger;
};
}
| 29,525
|
C++
|
.h
| 711
| 27.759494
| 127
| 0.531001
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,602
|
console.hpp
|
xavieran_BaKGL/game/console.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/camera.hpp"
#include "bak/coordinates.hpp"
#include "bak/encounter/teleport.hpp"
#include "bak/spells.hpp"
#include "bak/worldClock.hpp"
#include "com/string.hpp"
#include "game/gameRunner.hpp"
#include "imgui/imgui.h"
#include <iomanip>
struct Console : public std::streambuf
{
using ConsoleCommand = std::function<void(const std::vector<std::string>&)>;
std::streamsize xsputn(const char_type* s, std::streamsize n)
{
std::size_t from = 0;
for (unsigned i = 0; i < n; i++)
{
if (s[i] == '\n')
{
mStreamBuffer += std::string{s + from, i - from};
AddLog(mStreamBuffer.c_str());
mStreamBuffer.clear();
from = i;
}
}
if (from != static_cast<std::size_t>(n))
{
mStreamBuffer += std::string{s + from, n - from};
}
return n;
}
int_type overflow(int_type c)
{
mStreamBuffer += std::string{1, static_cast<char_type>(c)};
if (c == '\n')
{
AddLog(mStreamBuffer.c_str());
mStreamBuffer.clear();
}
return c;
}
// Console commands
void ShowTeleports(const std::vector<std::string>& words)
{
if (!mGameRunner)
{
AddLog("[error] SHOW_TELEPORTS FAILED No GameRunner Connected");
return;
}
std::stringstream ss{};
for (unsigned i = 0; i < 40; i++)
{
ss = std::stringstream{};
ss << i << " " << mGameRunner->mTeleportFactory.Get(i);
AddLog(ss.str().c_str());
}
}
void NextChapter(const std::vector<std::string>& words)
{
if (!mGameRunner)
{
AddLog("[error] NEXT_CHAPTER FAILED No GameRunner Connected");
return;
}
AddLog("Transitioning to chapter: %d", mGameState->GetChapter().mValue + 1);
mGuiManager->DoChapterTransition();
}
void SetComplexEvent(const std::vector<std::string>& words)
{
if (words.size() < 5)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: SET_COMPLEX_EVENT EV_PTR EV_MASK EV_DATA EV_VALUE (%s)", ss.str().c_str());
return;
}
if (!mGameState)
{
AddLog("[error] SET_COMPLEX_EVENT FAILED No GameState Connected");
return;
}
std::uint16_t eventPtr;
{
std::stringstream ss{};
ss << words[1];
ss >> eventPtr;
}
unsigned eventMask;
{
std::stringstream ss{};
ss << words[2];
ss >> eventMask;
}
unsigned eventData;
{
std::stringstream ss{};
ss << words[3];
ss >> eventData;
}
std::uint16_t eventValue;
{
std::stringstream ss{};
ss << words[4];
ss >> eventValue;
}
auto setFlag = BAK::SetFlag{
eventPtr,
static_cast<std::uint8_t>(eventMask),
static_cast<std::uint8_t>(eventData),
0,
eventValue};
Logging::LogInfo(__FUNCTION__) << " Setting event with: " << setFlag << "\n";
mGameState->SetEventState(setFlag);
}
void CastSpell(const std::vector<std::string>& words)
{
if (words.size() < 3)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: CAST_SPELL SPELL DURATION (%s)", ss.str().c_str());
return;
}
if (!mGameState)
{
AddLog("[error] CAST_SPELL FAILED No GameState Connected");
return;
}
std::uint16_t spellI;
{
std::stringstream ss{};
ss << words[1];
ss >> spellI;
}
auto spell = BAK::StaticSpells{spellI};
std::uint32_t duration;
{
std::stringstream ss{};
ss << words[2];
ss >> duration;
}
mGameState->CastStaticSpell(spell, BAK::Time{duration});
}
void SaveGame(const std::vector<std::string>& words)
{
if (words.size() < 2)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: SAVE_GAME FILENAME (%s)", ss.str().c_str());
return;
}
if (!mGameState)
{
AddLog("[error] SAVE_GAME FAILED No GameState Connected");
return;
}
const auto saved = mGameState->Save(words[1]);
if (saved)
AddLog("Game saved to: %s", words[1].c_str());
else
AddLog("Game not saved, no game data");
}
void StopMusic(const std::vector<std::string>& words)
{
AudioA::AudioManager::Get().StopMusicTrack();
}
void SwitchMidiPlayer(const std::vector<std::string>& words)
{
if (words.size() < 1)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: SWITCH_MIDI_PLAYER MIDI_PLAYER [0, 1, 2] (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned midiPlayer;
ss >> std::setbase(0) >> midiPlayer;
AudioA::AudioManager::Get().SwitchMidiPlayer(static_cast<AudioA::MidiPlayer>(midiPlayer));
}
void PlayMusic(const std::vector<std::string>& words)
{
if (words.size() < 1)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: PLAY_MUSIC MUSIC_INDEX (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned music_index;
ss >> std::setbase(0) >> music_index;
AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::MusicIndex{music_index});
}
void LoadGame(const std::vector<std::string>& words)
{
if (words.size() < 1)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: LOAD_GAME SAVE_PATH (%s)", ss.str().c_str());
return;
}
ASSERT(mGameRunner);
mGameRunner->LoadGame(words[1], std::nullopt);
mGuiManager->EnterMainView();
}
void PlaySound(const std::vector<std::string>& words)
{
if (words.size() < 1)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: PLAY_SOUND SOUND_INDEX (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned sound_index;
ss >> std::setbase(0) >> sound_index;
AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{sound_index});
}
void SetEventState(const std::vector<std::string>& words)
{
if (words.size() < 2)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: SET_EVENT_STATE PTR VALUE (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned ptr;
ss >> std::setbase(0) >> ptr;
ss = std::stringstream{};
ss << words[2];
unsigned value;
ss >> std::setbase(0) >> value;
if (!mGameState)
{
AddLog("[error] SET_EVENT_STATE FAILED No GameState Connected");
return;
}
mGameState->SetEventValue(ptr, value);
}
void RemoveItem(const std::vector<std::string>& words)
{
if (words.size() < 3)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: REMOVE_ITEM INDEX AMOUNT (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned itemIndex;
ss >> std::setbase(0) >> itemIndex;
ss = std::stringstream{};
ss << words[2];
unsigned amount;
ss >> std::setbase(0) >> amount;
if (!mGameState)
{
AddLog("[error] REMOVE_ITEM FAILED No GameState Connected");
return;
}
mGameState->GetParty().RemoveItem(
itemIndex,
amount);
}
void GiveItem(const std::vector<std::string>& words)
{
if (words.size() < 3)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: GIVE_ITEM INDEX AMOUNT (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned itemIndex;
ss >> std::setbase(0) >> itemIndex;
ss = std::stringstream{};
ss << words[2];
unsigned amount;
ss >> std::setbase(0) >> amount;
if (!mGameState)
{
AddLog("[error] GiveItem FAILED No GameState Connected");
return;
}
mGameState->GetParty().GainItem(
itemIndex,
amount);
}
void DoTeleport(const std::vector<std::string>& words)
{
if (words.size() < 2)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: DO_TELEPORT INDEX (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned index;
ss >> std::setbase(0) >> index;
if (!mGameRunner)
{
AddLog("[error] DoTeleport FAILED No GameRunner Connected");
return;
}
auto factory = BAK::Encounter::TeleportFactory();
mGameRunner->DoTeleport(factory.Get(index));
}
void SetPosition(const std::vector<std::string>& words)
{
if (words.size() < 3)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: SET_POSITION X Y (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned x;
ss >> std::setbase(0) >> x;
ss = std::stringstream{};
ss << words[2];
unsigned y;
ss >> std::setbase(0) >> y;
if (!mCamera)
{
AddLog("[error] SetPosition FAILED No Camera Connected");
return;
}
AddLog("SetPosition(%d, %d", x, y);
mCamera->SetGameLocation(
BAK::GamePositionAndHeading{
BAK::GamePosition{x, y},
BAK::GameHeading{0}});
}
void SetChapter(const std::vector<std::string>& words)
{
if (words.size() < 2)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: SET_CHAPTER CHAPTER (%s)", ss.str().c_str());
return;
}
std::stringstream ss{};
ss << words[1];
unsigned chapter;
ss >> std::setbase(0) >> chapter;
if (!mGameState)
{
AddLog("[error] SetChapter FAILED No GameState Connected");
return;
}
mGameState->SetChapter(BAK::Chapter{chapter});
}
void SetLogLevel(const std::vector<std::string>& words)
{
if (words.size() < 2)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: SET_LOG_LEVEL LEVEL (%s)", ss.str().c_str());
return;
}
if (words[1] == LevelToString(Logging::LogLevel::Spam))
{
Logging::LogState::SetLevel(Logging::LogLevel::Spam);
}
else if (words[1] == LevelToString(Logging::LogLevel::Debug))
{
Logging::LogState::SetLevel(Logging::LogLevel::Debug);
}
else if (words[1] == LevelToString(Logging::LogLevel::Info))
{
Logging::LogState::SetLevel(Logging::LogLevel::Info);
}
else if (words[1] == LevelToString(Logging::LogLevel::Fatal))
{
Logging::LogState::SetLevel(Logging::LogLevel::Fatal);
}
else
{
AddLog("[error] SET_LOG_LEVEL FAILED Invalid log level provided");
}
}
void DisableLogger(const std::vector<std::string>& words)
{
if (words.size() < 2)
{
std::stringstream ss{};
for (const auto& w : words)
ss << w << "|";
AddLog("[error] Usage: DISABLE_LOGGER LOGGER (%s)", ss.str().c_str());
return;
}
Logging::LogState::Disable(words[1]);
}
Console()
:
mStream{this},
mStreamBuffer{}
{
ClearLog();
memset(mInputBuf, 0, sizeof(mInputBuf));
mHistoryPos = -1;
mCommands.push_back("HELP");
mCommandActions.emplace_back([this](const auto&)
{
AddLog("Commands:");
for (int i = 0; i < mCommands.Size; i++)
AddLog("- %s", mCommands[i]);
});
mCommands.push_back("SAVE_GAME");
mCommandActions.emplace_back([this](const auto& cmd){ SaveGame(cmd); });
mCommands.push_back("SET_EVENT_STATE");
mCommandActions.emplace_back([this](const auto& cmd){ SetEventState(cmd); });
mCommands.push_back("REMOVE_ITEM");
mCommandActions.emplace_back([this](const auto& cmd){ RemoveItem(cmd); });
mCommands.push_back("GIVE_ITEM");
mCommandActions.emplace_back([this](const auto& cmd){ GiveItem(cmd); });
mCommands.push_back("DO_TELEPORT");
mCommandActions.emplace_back([this](const auto& cmd){ DoTeleport(cmd); });
mCommands.push_back("SHOW_TELEPORTS");
mCommandActions.emplace_back([this](const auto& cmd){ ShowTeleports(cmd); });
mCommands.push_back("SET_POSITION");
mCommandActions.emplace_back([this](const auto& cmd){ SetPosition(cmd); });
mCommands.push_back("SET_CHAPTER");
mCommandActions.emplace_back([this](const auto& cmd){ SetChapter(cmd); });
mCommands.push_back("STOP_MUSIC");
mCommandActions.emplace_back([this](const auto& cmd){ StopMusic(cmd); });
mCommands.push_back("SWITCH_MIDI_PLAYER");
mCommandActions.emplace_back([this](const auto& cmd){ SwitchMidiPlayer(cmd); });
mCommands.push_back("LOAD_GAME");
mCommandActions.emplace_back([this](const auto& cmd){ LoadGame(cmd); });
mCommands.push_back("PLAY_SOUND");
mCommandActions.emplace_back([this](const auto& cmd){ PlaySound(cmd); });
mCommands.push_back("PLAY_MUSIC");
mCommandActions.emplace_back([this](const auto& cmd){ PlayMusic(cmd); });
mCommands.push_back("HISTORY");
mCommandActions.emplace_back([this](const auto& cmd)
{
int first = mHistory.Size - 10;
for (int i = first > 0 ? first : 0; i < mHistory.Size; i++)
AddLog("%3d: %s\n", i, mHistory[i]);
});
mCommands.push_back("SET_LOG_LEVEL");
mCommandActions.emplace_back([this](const auto& cmd){ SetLogLevel(cmd); });
mCommands.push_back("DISABLE_LOGGER");
mCommandActions.emplace_back([this](const auto& cmd){ DisableLogger(cmd); });
mCommands.push_back("SET_COMPLEX_EVENT");
mCommandActions.emplace_back([this](const auto& cmd){ SetComplexEvent(cmd); });
mCommands.push_back("CAST_SPELL");
mCommandActions.emplace_back([this](const auto& cmd){ CastSpell(cmd); });
mCommands.push_back("NEXT_CHAPTER");
mCommandActions.emplace_back([this](const auto& cmd){ NextChapter(cmd); });
mCommands.push_back("CLEAR");
mCommandActions.emplace_back([this](const auto& cmd)
{
ClearLog();
});
ASSERT(static_cast<std::size_t>(mCommands.size())
== mCommandActions.size());
mAutoScroll = true;
mScrollToBottom = false;
AddLog("Enter HELP for a list of commands");
mStreamLog = false;
}
~Console()
{
ClearLog();
for (int i = 0; i < mHistory.Size; i++)
free(mHistory[i]);
}
// Portable helpers
static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; }
static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; }
static char* Strdup(const char* s) { IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); }
static void Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; }
void ToggleLog()
{
mStreamLog = !mStreamLog;
if (mStreamLog)
Logging::LogState::AddStream(&mStream);
else
Logging::LogState::RemoveStream(&mStream);
}
void ClearLog()
{
for (int i = 0; i < mItems.Size; i++)
free(mItems[i]);
mItems.clear();
}
void AddLog(const char* fmt, ...) IM_FMTARGS(2)
{
// FIXME-OPT
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args);
buf[IM_ARRAYSIZE(buf) - 1] = 0;
va_end(args);
mItems.push_back(Strdup(buf));
}
void Draw(const char* title, bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (!ImGui::Begin(title, p_open))
{
ImGui::End();
return;
}
// As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar.
// So e.g. IsItemHovered() will return true when hovering the title bar.
// Here we create a context menu only available from the title bar.
if (ImGui::BeginPopupContextItem())
{
if (ImGui::MenuItem("Close Console"))
*p_open = false;
ImGui::EndPopup();
}
ImGui::TextWrapped("Enter 'HELP' for help.");
if (ImGui::SmallButton(mStreamLog ? "Logging On" : "Logging Off")) { ToggleLog(); }
ImGui::SameLine();
if (ImGui::SmallButton("Clear")) { ClearLog(); }
ImGui::SameLine();
bool copy_to_clipboard = ImGui::SmallButton("Copy");
ImGui::Separator();
// Options menu
if (ImGui::BeginPopup("Options"))
{
ImGui::Checkbox("Auto-scroll", &mAutoScroll);
ImGui::EndPopup();
}
// Options, Filter
if (ImGui::Button("Options"))
ImGui::OpenPopup("Options");
ImGui::SameLine();
mFilter.Draw("Filter (\"incl,-excl\") (\"error\")", 180);
ImGui::Separator();
// Reserve enough left-over height for 1 separator + 1 input text
const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing();
ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar);
if (ImGui::BeginPopupContextWindow())
{
if (ImGui::Selectable("Clear")) ClearLog();
ImGui::EndPopup();
}
// Display every line as a separate entry so we can change their color or add custom widgets.
// If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());
// NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping
// to only process visible items. The clipper will automatically measure the height of your first item and then
// "seek" to display only items in the visible area.
// To use the clipper we can replace your standard loop:
// for (int i = 0; i < mItems.Size; i++)
// With:
// ImGuiListClipper clipper;
// clipper.Begin(mItems.Size);
// while (clipper.Step())
// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
// - That your items are evenly spaced (same height)
// - That you have cheap random access to your elements (you can access them given their index,
// without processing all the ones before)
// You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property.
// We would need random-access on the post-filtered list.
// A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices
// or offsets of items that passed the filtering test, recomputing this array when user changes the filter,
// and appending newly elements as they are inserted. This is left as a task to the user until we can manage
// to improve this example code!
// If your items are of variable height:
// - Split them into same height items would be simpler and facilitate random-seeking into your list.
// - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items.
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing
if (copy_to_clipboard)
ImGui::LogToClipboard();
for (int i = 0; i < mItems.Size; i++)
ImGui::TextUnformatted(mItems[i]);
//for (int i = 0; i < mItems.Size; i++)
//{
// const char* item = mItems[i];
// if (!mFilter.PassFilter(item))
// continue;
// // Normally you would store more information in your item than just a string.
// // (e.g. make mItems[] an array of structure, store color/type etc.)
// ImVec4 color;
// bool has_color = false;
// if (strstr(item, "[error]")) { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; }
// else if (strncmp(item, "# ", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; }
// if (has_color)
// ImGui::PushStyleColor(ImGuiCol_Text, color);
// ImGui::TextUnformatted(item);
// if (has_color)
// ImGui::PopStyleColor();
//}
if (copy_to_clipboard)
ImGui::LogFinish();
if (mScrollToBottom || (mAutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()))
ImGui::SetScrollHereY(1.0f);
mScrollToBottom = false;
ImGui::PopStyleVar();
ImGui::EndChild();
ImGui::Separator();
// Command-line
bool reclaim_focus = false;
ImGuiInputTextFlags input_text_flags
= ImGuiInputTextFlags_EnterReturnsTrue
| ImGuiInputTextFlags_CallbackCompletion
| ImGuiInputTextFlags_CallbackHistory;
const auto inputText = ImGui::InputText(
"Input",
mInputBuf,
IM_ARRAYSIZE(mInputBuf),
input_text_flags,
&TextEditCallbackStub,
(void*)this);
if (inputText)
{
char* s = mInputBuf;
Strtrim(s);
if (s[0])
ExecCommand(s);
strcpy(s, "");
reclaim_focus = true;
}
// Auto-focus on window apparition
ImGui::SetItemDefaultFocus();
if (reclaim_focus)
ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
ImGui::End();
}
void ExecCommand(const char* command_line)
{
AddLog("# %s\n", command_line);
// Insert into history. First find match and delete it so it can be pushed to the back.
// This isn't trying to be smart or optimal.
mHistoryPos = -1;
for (int i = mHistory.Size - 1; i >= 0; i--)
if (Stricmp(mHistory[i], command_line) == 0)
{
free(mHistory[i]);
mHistory.erase(mHistory.begin() + i);
break;
}
mHistory.push_back(Strdup(command_line));
const auto command = std::string{command_line};
const auto words = SplitString(" ", command);
bool succeeded = false;
for (unsigned i = 0; i < mCommandActions.size(); i++)
{
const auto candidate = std::string{mCommands[i]};
if (command.substr(0, candidate.length()) == candidate)
{
std::invoke(mCommandActions[i], words);
succeeded = true;
}
}
if (!succeeded)
{
AddLog("Unknown command: '%s'\n", command_line);
}
// On command input, we scroll to bottom even if mAutoScroll==false
mScrollToBottom = true;
}
// In C++11 you'd be better off using lambdas for this sort of forwarding callbacks
static int TextEditCallbackStub(ImGuiInputTextCallbackData* data)
{
Console* console = (Console*)data->UserData;
return console->TextEditCallback(data);
}
int TextEditCallback(ImGuiInputTextCallbackData* data)
{
switch (data->EventFlag)
{
case ImGuiInputTextFlags_CallbackCompletion:
{
// Locate beginning of current word
const char* word_end = data->Buf + data->CursorPos;
const char* word_start = word_end;
while (word_start > data->Buf)
{
const char c = word_start[-1];
if (c == ' ' || c == '\t' || c == ',' || c == ';')
break;
word_start--;
}
// Build a list of candidates
ImVector<const char*> candidates;
for (int i = 0; i < mCommands.Size; i++)
if (Strnicmp(mCommands[i], word_start, (int)(word_end - word_start)) == 0)
candidates.push_back(mCommands[i]);
if (candidates.Size == 0)
{
// No match
AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start);
}
else if (candidates.Size == 1)
{
// Single match. Delete the beginning of the word and replace it entirely so we've got nice casing.
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0]);
data->InsertChars(data->CursorPos, " ");
}
else
{
// Multiple matches. Complete as much as we can..
// So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches.
int match_len = (int)(word_end - word_start);
for (;;)
{
int c = 0;
bool all_candidates_matches = true;
for (int i = 0; i < candidates.Size && all_candidates_matches; i++)
if (i == 0)
c = toupper(candidates[i][match_len]);
else if (c == 0 || c != toupper(candidates[i][match_len]))
all_candidates_matches = false;
if (!all_candidates_matches)
break;
match_len++;
}
if (match_len > 0)
{
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
}
// List matches
AddLog("Possible matches:\n");
for (int i = 0; i < candidates.Size; i++)
AddLog("- %s\n", candidates[i]);
}
break;
}
case ImGuiInputTextFlags_CallbackHistory:
{
// Example of HISTORY
const int prev_history_pos = mHistoryPos;
if (data->EventKey == ImGuiKey_UpArrow)
{
if (mHistoryPos == -1)
mHistoryPos = mHistory.Size - 1;
else if (mHistoryPos > 0)
mHistoryPos--;
}
else if (data->EventKey == ImGuiKey_DownArrow)
{
if (mHistoryPos != -1)
if (++mHistoryPos >= mHistory.Size)
mHistoryPos = -1;
}
// A better implementation would preserve the data on the current input line along with cursor position.
if (prev_history_pos != mHistoryPos)
{
const char* history_str = (mHistoryPos >= 0) ? mHistory[mHistoryPos] : "";
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, history_str);
}
}
}
return 0;
}
//private:
char mInputBuf[256];
ImVector<char*> mItems;
ImVector<const char*> mCommands;
std::vector<ConsoleCommand> mCommandActions;
ImVector<char*> mHistory;
int mHistoryPos; // -1: new line, 0..mHistory.Size-1 browsing history.
ImGuiTextFilter mFilter;
bool mAutoScroll;
bool mScrollToBottom;
bool mStreamLog;
std::ostream mStream;
std::string mStreamBuffer;
Camera* mCamera;
Game::GameRunner* mGameRunner;
Gui::IGuiManager* mGuiManager;
BAK::GameState* mGameState;
};
static void ShowConsole(bool* p_open)
{
static Console console;
console.Draw("Console", p_open);
}
| 31,010
|
C++
|
.h
| 813
| 27.409594
| 199
| 0.523589
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,603
|
ladder.hpp
|
xavieran_BaKGL/game/interactable/ladder.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "bak/IContainer.hpp"
#include "bak/container.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogSources.hpp"
#include "bak/gameState.hpp"
#include "bak/itemNumbers.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
namespace Game::Interactable {
class Ladder : public IInteractable
{
private:
enum class State
{
Idle,
Done,
};
public:
Ladder(
Gui::IGuiManager& guiManager,
BAK::GameState& gameState)
:
mGuiManager{guiManager},
mGameState{gameState},
mDialogScene{
[]{},
[]{},
[&](const auto& choice){ DialogFinished(choice); }},
mCurrentLadder{nullptr},
mState{State::Idle}
{}
void BeginInteraction(BAK::GenericContainer& ladder, BAK::EntityType) override
{
ASSERT(mState == State::Idle);
mCurrentLadder = &ladder;
mGameState.SetDialogContext_7530(3);
// All ladders should have dialog and a lock
ASSERT(mCurrentLadder->HasLock())
StartDialog(BAK::DialogSources::mChooseUnlock);
}
void LockFinished()
{
ASSERT(!mCurrentLadder->GetLock().IsFairyChest())
if (mGuiManager.IsLockOpened())
{
// Unlockable ladders must always have a dialog
ASSERT(mCurrentLadder->HasDialog());
mState = State::Done;
StartDialog(mCurrentLadder->GetDialog().mDialog);
}
else
{
mState = State::Idle;
}
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
ASSERT(mCurrentLadder);
if (mState == State::Done)
{
mState = State::Idle;
if (mGameState.GetTransitionChapter_7541())
{
mGameState.SetTransitionChapter_7541(false);
mGuiManager.DoChapterTransition();
}
return;
}
ASSERT(choice);
if (choice->mValue == BAK::Keywords::sYesIndex)
{
mGuiManager.ShowLock(
mCurrentLadder,
[this]{ LockFinished(); });
}
}
void EncounterFinished() override
{
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
private:
Gui::IGuiManager& mGuiManager;
BAK::GameState& mGameState;
Gui::DynamicDialogScene mDialogScene;
BAK::GenericContainer* mCurrentLadder;
State mState;
};
}
| 2,642
|
C++
|
.h
| 97
| 19.505155
| 82
| 0.598653
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,604
|
tomb.hpp
|
xavieran_BaKGL/game/interactable/tomb.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "bak/IContainer.hpp"
#include "bak/container.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogSources.hpp"
#include "bak/entityType.hpp"
#include "bak/dialog.hpp"
#include "bak/gameState.hpp"
#include "bak/itemNumbers.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
namespace Game::Interactable {
class Tomb : public IInteractable
{
private:
enum class State
{
Idle,
Done,
};
public:
Tomb(
Gui::IGuiManager& guiManager,
BAK::GameState& gameState,
const EncounterCallback& encounterCallback)
:
mGuiManager{guiManager},
mGameState{gameState},
mDialogScene{
[]{},
[]{},
[&](const auto& choice){ DialogFinished(choice); }},
mCurrentTomb{nullptr},
mState{State::Idle},
mEncounterCallback{encounterCallback}
{}
void BeginInteraction(BAK::GenericContainer& tomb, BAK::EntityType) override
{
mCurrentTomb = &tomb;
mGameState.SetDialogContext_7530(0);
ASSERT(mState == State::Idle);
// All tombs should have dialog
ASSERT(mCurrentTomb->HasDialog());
StartDialog(mCurrentTomb->GetDialog().mDialog);
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
ASSERT(mCurrentTomb);
if (mState == State::Done || !choice)
{
mState = State::Idle;
return;
}
if (choice->mValue == BAK::Keywords::sYesIndex)
{
if (!mGameState.GetParty().HaveItem(BAK::sShovel))
{
// Don't have a shovel
mState = State::Done;
StartDialog(BAK::DialogSources::mTombNoShovel);
}
else
{
if (mCurrentTomb->HasEncounter())
{
DoEncounter();
}
else
{
DigTomb();
}
}
}
}
void DigTomb()
{
const auto dialogOrder = mCurrentTomb->GetDialog().mDialogOrder;
mGameState.GetParty().RemoveItem(BAK::sShovel.mValue, 1);
// Just show this dialog and do nothing else
if (CheckBitSet(dialogOrder, 1))
{
mState = State::Idle;
ShowTombContents();
}
else if (CheckBitSet(dialogOrder, 2))
{
mState = State::Done;
// Just a body
StartDialog(BAK::DialogSources::mTombJustABody);
}
else if (CheckBitSet(dialogOrder, 3))
{
mState = State::Done;
// No body
StartDialog(BAK::DialogSources::mTombNoBody);
}
else
{
ASSERT(false);
}
}
void DoEncounter()
{
Logging::LogInfo("Tomb") << __FUNCTION__ << " "
<< mCurrentTomb->GetEncounter() << "\n";
std::invoke(
mEncounterCallback,
*mCurrentTomb->GetEncounter().mEncounterPos);
}
void EncounterFinished() override
{
DigTomb();
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
void ShowTombContents()
{
if (mCurrentTomb->HasEncounter()
&& mCurrentTomb->GetEncounter().mSetEventFlag != 0)
{
mGameState.SetEventValue(
mCurrentTomb->GetEncounter().mSetEventFlag,
1);
}
mGuiManager.ShowContainer(mCurrentTomb, BAK::EntityType::TOMBSTONE);
}
private:
Gui::IGuiManager& mGuiManager;
BAK::GameState& mGameState;
Gui::DynamicDialogScene mDialogScene;
BAK::GenericContainer* mCurrentTomb;
State mState;
const EncounterCallback& mEncounterCallback;
};
}
| 3,974
|
C++
|
.h
| 142
| 19.274648
| 80
| 0.565354
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,605
|
chest.hpp
|
xavieran_BaKGL/game/interactable/chest.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "audio/audio.hpp"
#include "bak/IContainer.hpp"
#include "bak/container.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogSources.hpp"
#include "bak/gameState.hpp"
#include "com/logger.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
namespace Game::Interactable {
class Chest : public IInteractable
{
private:
enum class State
{
Idle,
OpenChest,
UnlockChest,
DisarmedTrap,
Exploded
};
static constexpr auto sExploded = AudioA::SoundIndex{0x39};
public:
Chest(
Gui::IGuiManager& guiManager,
BAK::GameState& gameState)
:
mGuiManager{guiManager},
mGameState{gameState},
mDialogScene{
[]{},
[]{},
[&](const auto& choice){ DialogFinished(choice); }},
mCurrentChest{nullptr},
mState{State::Idle}
{}
void BeginInteraction(BAK::GenericContainer& chest, BAK::EntityType) override
{
ASSERT(mState == State::Idle);
mCurrentChest = &chest;
mGameState.SetDialogContext_7530(0);
mState = State::OpenChest;
if (!chest.HasLock())
{
// If no lock, just open the box
StartDialog(BAK::DialogSources::mOpenUnlockedBox);
}
else if (chest.GetLock().IsFairyChest())
{
// If word lock, show flavour text then transition
// into word lock screen
StartDialog(BAK::DialogSources::mWordlockIntro);
}
else if (!chest.GetLock().IsTrapped())
{
// If normal lock, ask if user wants to open lock
StartDialog(BAK::DialogSources::mChooseUnlock);
}
else
{
// Scent of sarig active and chest is trapped
if (mGameState.GetSpellActive(BAK::StaticSpells::ScentOfSarig)
&& chest.GetLock().mLockFlag == 4 && chest.GetLock().mTrapDamage > 0)
{
StartDialog(BAK::DialogSources::mOpenTrappedBox);
}
// Scent of sarig not active and chest was trapped, chest is incinerated
else if (chest.GetLock().mLockFlag == 4 && chest.GetLock().mTrapDamage == 0)
{
StartDialog(BAK::DialogSources::mOpenExplodedChest);
}
// Chest is not trapped
else if (chest.GetLock().mLockFlag == 1)
{
ASSERT(chest.GetLock().mLockFlag == 1);
StartDialog(BAK::DialogSources::mChooseUnlock);
}
else
{
StartDialog(BAK::DialogSources::mChooseUnlock);
}
}
}
void EncounterFinished() override {}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
if (mState == State::OpenChest)
{
ASSERT(mCurrentChest);
TryOpenChest(!choice
|| (choice->mValue == BAK::Keywords::sYesIndex));
}
else if (mState == State::DisarmedTrap)
{
ShowChestContents();
mState = State::Idle;
}
else if (mState == State::Exploded)
{
mState = State::Idle;
}
else
{
return;
}
}
void TryOpenChest(bool openChest)
{
ASSERT(mCurrentChest);
ASSERT(mState != State::Idle);
if (!mCurrentChest->HasLock())
{
mState = State::Idle;
ShowChestContents();
}
else if (mCurrentChest->GetLock().IsFairyChest())
{
TryUnlockChest();
}
else if (!mCurrentChest->GetLock().IsTrapped())
{
if (openChest)
TryUnlockChest();
else
mState = State::Idle;
}
else
{
if (openChest)
{
auto& lock = mCurrentChest->GetLock();
if (mGameState.GetSpellActive(BAK::StaticSpells::ScentOfSarig)
&& lock.mLockFlag == 4 && lock.mTrapDamage > 0)
{
TryDisarmTrap();
}
else if ((lock.mLockFlag == 4 && lock.mTrapDamage == 0)
|| lock.mLockFlag == 1)
{
mState = State::Idle;
ShowChestContents();
}
else
{
Explode();
}
}
else
mState = State::Idle;
}
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
void TryDisarmTrap()
{
ASSERT(mState == State::OpenChest);
ASSERT(mCurrentChest);
auto& lock = mCurrentChest->GetLock();
const auto& [character, skill] = mGameState
.GetPartySkill(BAK::SkillType::Lockpick, true);
if (skill > lock.mRating)
{
mGameState.GetParty()
.GetCharacter(character)
.ImproveSkill(
BAK::SkillType::Lockpick,
BAK::SkillChange::ExercisedSkill,
2);
lock.mTrapDamage = 0;
mState = State::DisarmedTrap;
StartDialog(BAK::DialogSources::mDisarmedTrappedBox);
}
else
{
Explode();
}
}
void Explode()
{
ASSERT(mCurrentChest->HasLock());
mGameState.GetParty().ImproveSkillForAll(
BAK::SkillType::TotalHealth,
BAK::SkillChange::HealMultiplier_100,
-(mCurrentChest->GetLock().mTrapDamage << 8));
mCurrentChest->GetLock().mTrapDamage = 0;
StartDialog(BAK::DialogSources::mTrappedChestExplodes);
mState = State::Exploded;
AudioA::AudioManager::Get().PlaySound(sExploded);
}
void ShowChestContents()
{
if (mCurrentChest->HasEncounter()
&& mCurrentChest->GetEncounter().mSetEventFlag != 0)
{
mGameState.SetEventValue(
mCurrentChest->GetEncounter().mSetEventFlag,
1);
}
mGuiManager.ShowContainer(mCurrentChest, BAK::EntityType::CHEST);
}
void TryUnlockChest()
{
mState = State::UnlockChest;
mGuiManager.ShowLock(
mCurrentChest,
[this]{ LockFinished(); });
}
void LockFinished()
{
ASSERT(mState == State::UnlockChest);
mState = State::Idle;
if (mCurrentChest->GetLock().IsFairyChest())
{
if (mGuiManager.IsWordLockOpened())
ShowChestContents();
}
else
{
if (mGuiManager.IsLockOpened())
ShowChestContents();
}
}
private:
Gui::IGuiManager& mGuiManager;
BAK::GameState& mGameState;
Gui::DynamicDialogScene mDialogScene;
BAK::GenericContainer* mCurrentChest;
State mState;
};
}
| 7,149
|
C++
|
.h
| 238
| 19.920168
| 88
| 0.53711
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,606
|
generic.hpp
|
xavieran_BaKGL/game/interactable/generic.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "bak/IContainer.hpp"
#include "bak/container.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogSources.hpp"
#include "bak/gameState.hpp"
#include "bak/itemNumbers.hpp"
#include "bak/types.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
namespace Game::Interactable {
/*
* These containers have an optional dialog and inventory encounter
*/
class Generic : public IInteractable
{
private:
public:
Generic(
Gui::IGuiManager& guiManager,
BAK::Target target,
const EncounterCallback& encounterCallback)
:
mGuiManager{guiManager},
mDialogScene{
[]{},
[]{},
[&](const auto& choice){ DialogFinished(choice); }},
mDefaultDialog{target},
mContainer{nullptr},
mEncounterCallback{encounterCallback}
{}
void BeginInteraction(BAK::GenericContainer& container, BAK::EntityType entityType) override
{
mContainer = &container;
mEntityType = entityType;
if (container.HasDialog())
StartDialog(container.GetDialog().mDialog);
else if (container.HasEncounter())
DoEncounter();
else
StartDialog(mDefaultDialog);
}
void DoEncounter()
{
std::invoke(
mEncounterCallback,
*mContainer->GetEncounter().mEncounterPos);
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
ASSERT(mContainer);
if (mContainer->HasInventory())
{
mGuiManager.ShowContainer(mContainer, mEntityType);
}
}
void EncounterFinished() override
{
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
private:
Gui::IGuiManager& mGuiManager;
Gui::DynamicDialogScene mDialogScene;
BAK::Target mDefaultDialog;
BAK::GenericContainer* mContainer;
BAK::EntityType mEntityType;
const EncounterCallback& mEncounterCallback;
};
}
| 2,145
|
C++
|
.h
| 78
| 21.115385
| 96
| 0.657574
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,607
|
combatant.hpp
|
xavieran_BaKGL/game/interactable/combatant.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "bak/IContainer.hpp"
#include "bak/container.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogSources.hpp"
#include "bak/gameState.hpp"
#include "bak/itemNumbers.hpp"
#include "bak/types.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
namespace Game::Interactable {
/*
* These containers have an optional dialog and inventory encounter
*/
class Combatant : public IInteractable
{
private:
public:
Combatant(
Gui::IGuiManager& guiManager,
BAK::Target target)
:
mGuiManager{guiManager},
mDialogScene{
[]{},
[]{},
[&](const auto& choice){ DialogFinished(choice); }},
mDefaultDialog{target},
mContainer{nullptr}
{}
void BeginInteraction(BAK::GenericContainer& container, BAK::EntityType entityType) override
{
mContainer = &container;
mEntityType = entityType;
StartDialog(BAK::DialogSources::mBody);
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
ASSERT(mContainer);
if (mContainer->HasInventory())
{
mGuiManager.ShowContainer(mContainer, BAK::EntityType::DEADBODY1);
}
}
void EncounterFinished() override
{
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
private:
Gui::IGuiManager& mGuiManager;
Gui::DynamicDialogScene mDialogScene;
BAK::Target mDefaultDialog;
BAK::GenericContainer* mContainer;
BAK::EntityType mEntityType;
};
}
| 1,704
|
C++
|
.h
| 64
| 20.890625
| 96
| 0.665642
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,608
|
IInteractable.hpp
|
xavieran_BaKGL/game/interactable/IInteractable.hpp
|
#pragma once
#include "bak/container.hpp"
#include "bak/entityType.hpp"
namespace Game {
using EncounterCallback = std::function<void(glm::uvec2)>;
class IInteractable
{
public:
virtual void BeginInteraction(BAK::GenericContainer&, BAK::EntityType) = 0;
virtual void EncounterFinished() = 0;
virtual ~IInteractable() {};
};
}
| 344
|
C++
|
.h
| 13
| 24.076923
| 79
| 0.756923
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,609
|
factory.hpp
|
xavieran_BaKGL/game/interactable/factory.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "game/interactable/building.hpp"
#include "game/interactable/chest.hpp"
#include "game/interactable/combatant.hpp"
#include "game/interactable/door.hpp"
#include "game/interactable/generic.hpp"
#include "game/interactable/ladder.hpp"
#include "game/interactable/pit.hpp"
#include "game/interactable/tomb.hpp"
#include "gui/IGuiManager.hpp"
#include "bak/gameState.hpp"
#include <memory>
namespace Game {
enum class InteractableType
{
Chest = 0,
RiftMachine = 3,
Building = 4,
Tombstone = 6,
Sign = 7,
Pit = 9,
Body = 10,
DirtMound = 11,
Corn = 12,
Campfire = 13,
Tunnel0 = 14,
Door = 17,
CrystalTree = 18,
Stones = 19,
FoodBush = 20,
PoisonBush = 21,
HealthBush = 22,
Slab = 23,
Stump = 24,
Well = 25,
SiegeEngine = 27,
Scarecrow = 28,
DeadAnimal = 29,
Catapult = 30,
Column = 31,
Tunnel1 = 33,
Bag = 35,
Ladder = 36,
DeadCombatant = 100,
LivingCombatant = 101,
};
std::string_view ToString(InteractableType);
class InteractableFactory
{
public:
InteractableFactory(
Gui::IGuiManager& guiManager,
BAK::GameState& gameState,
EncounterCallback&& encounterCallback)
:
mGuiManager{guiManager},
mGameState{gameState},
mEncounterCallback{std::move(encounterCallback)}
{}
std::unique_ptr<IInteractable> MakeInteractable(
BAK::EntityType entity) const
{
using namespace Interactable;
constexpr auto nonInteractables = 6;
const auto interactableType = static_cast<InteractableType>(
static_cast<unsigned>(entity) - nonInteractables);
Logging::LogDebug(__FUNCTION__) << " Handling: " << ToString(interactableType) << "\n";
const auto MakeGeneric = [this](BAK::Target dialog){
return std::make_unique<Generic>(
mGuiManager,
dialog,
mEncounterCallback);
};
switch (interactableType)
{
case InteractableType::Building:
return std::make_unique<Building>(
mGuiManager,
mGameState,
mEncounterCallback);
case InteractableType::Chest:
return std::make_unique<Chest>(
mGuiManager,
mGameState);
case InteractableType::Tombstone:
return std::make_unique<Tomb>(
mGuiManager,
mGameState,
mEncounterCallback);
case InteractableType::Ladder:
return std::make_unique<Ladder>(
mGuiManager,
mGameState);
case InteractableType::Bag:
return MakeGeneric(BAK::DialogSources::mBag);
case InteractableType::Body:
return MakeGeneric(BAK::DialogSources::mBody);
case InteractableType::Campfire:
return MakeGeneric(BAK::DialogSources::mCampfire);
case InteractableType::Door:
return std::make_unique<Door>(
mGuiManager,
mGameState);
case InteractableType::Pit:
return std::make_unique<Pit>(
mGuiManager,
mGameState);
case InteractableType::Corn:
return MakeGeneric(BAK::DialogSources::mCorn);
case InteractableType::CrystalTree:
return MakeGeneric(BAK::DialogSources::mCrystalTree);
case InteractableType::DirtMound:
return MakeGeneric(BAK::DialogSources::mDirtpile);
case InteractableType::Stones:
return MakeGeneric(BAK::DialogSources::mStones);
case InteractableType::Scarecrow:
return MakeGeneric(BAK::DialogSources::mScarecrow);
case InteractableType::Stump:
return MakeGeneric(BAK::DialogSources::mStump);
case InteractableType::SiegeEngine:
return MakeGeneric(BAK::DialogSources::mSiegeEngine);
case InteractableType::DeadAnimal:
return MakeGeneric(BAK::DialogSources::mTrappedAnimal);
case InteractableType::HealthBush:
return MakeGeneric(BAK::DialogSources::mHealthBush);
case InteractableType::PoisonBush:
return MakeGeneric(BAK::DialogSources::mPoisonBush);
case InteractableType::FoodBush:
return MakeGeneric(BAK::DialogSources::mFoodBush);
case InteractableType::Well:
return MakeGeneric(BAK::DialogSources::mWell);
case InteractableType::Column: [[ fallthrough ]];
case InteractableType::Sign: [[ fallthrough ]];
case InteractableType::Slab: [[ fallthrough ]];
case InteractableType::Tunnel0: [[ fallthrough ]];
case InteractableType::Tunnel1:
return MakeGeneric(BAK::DialogSources::mUnknownObject);
case InteractableType::DeadCombatant:
return std::make_unique<Combatant>(
mGuiManager,
BAK::KeyTarget{0});
default:
Logging::LogFatal(__FUNCTION__) << "Unhandled entity type: "
<< static_cast<unsigned>(entity) << " interactableType: "
<< ToString(interactableType) << std::endl;
return MakeGeneric(BAK::DialogSources::mUnknownObject);
}
}
private:
Gui::IGuiManager& mGuiManager;
BAK::GameState& mGameState;
EncounterCallback mEncounterCallback;
};
}
| 5,605
|
C++
|
.h
| 155
| 27.496774
| 95
| 0.620309
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,610
|
building.hpp
|
xavieran_BaKGL/game/interactable/building.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "bak/IContainer.hpp"
#include "bak/container.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogSources.hpp"
#include "bak/gameState.hpp"
#include "bak/itemNumbers.hpp"
#include "com/logger.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
namespace Game::Interactable {
class Building : public IInteractable
{
private:
enum class State
{
Idle,
SkipFirstDialog,
DoFirstDialog,
TryUnlock,
Unlocking,
ShowInventory,
TryDoGDS,
Done,
};
public:
Building(
Gui::IGuiManager& guiManager,
BAK::GameState& gameState,
const EncounterCallback& encounterCallback)
:
mGuiManager{guiManager},
mGameState{gameState},
mDialogScene{
[]{},
[]{},
[&](const auto& choice){ DialogFinished(choice); }},
mCurrentBuilding{nullptr},
mState{State::Idle},
mEncounterCallback{encounterCallback}
{}
void BeginInteraction(BAK::GenericContainer& building, BAK::EntityType) override
{
ASSERT(mState == State::Idle);
mCurrentBuilding = &building;
ASSERT(mCurrentBuilding->HasDialog());
mGameState.SetDialogContext_7530(2);
if (!CheckBitSet(mCurrentBuilding->GetDialog().mDialogOrder, 5))
{
// Skip dialog
mState = State::SkipFirstDialog;
Logging::LogDebug("Building") << "State: SkipFirstDialog\n";
TryDoEncounter();
}
else
{
mState = State::DoFirstDialog;
Logging::LogDebug("Building") << "State: DoFirstDialog\n";
StartDialog(mCurrentBuilding->GetDialog().mDialog);
}
}
void LockFinished()
{
ASSERT(!mCurrentBuilding->GetLock().IsFairyChest())
if (mGuiManager.IsLockOpened())
{
// Unlockable buildings must always have a dialog
ASSERT(mCurrentBuilding->HasDialog());
mState = State::ShowInventory;
if (!CheckBitSet(mCurrentBuilding->GetDialog().mDialogOrder, 5))
{
StartDialog(mCurrentBuilding->GetDialog().mDialog);
}
else
{
TryDoInventory();
}
}
else
{
mState = State::Idle;
}
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
ASSERT(mState != State::SkipFirstDialog);
if (mState == State::DoFirstDialog)
{
Logging::LogDebug("Building") << "State: DoneFirstDialog: \n";
TryDoEncounter();
StartDialog(mCurrentBuilding->GetDialog().mDialog);
return;
}
else if (mState == State::TryUnlock)
{
ASSERT(choice);
if (choice->mValue == BAK::Keywords::sYesIndex)
{
mState = State::Unlocking;
mGuiManager.ShowLock(
mCurrentBuilding,
[this]{ LockFinished(); });
}
else
{
mState = State::Idle;
}
}
else if (mState == State::ShowInventory)
{
Logging::LogDebug("Building") << "State: ShowInv\n";
TryDoInventory();
}
else if (mState == State::TryDoGDS)
{
Logging::LogDebug("Building") << "State: TryDoGDS\n";
if ((!choice || choice->mValue == BAK::Keywords::sYesIndex)
&& mGameState.GetEndOfDialogState() != -1)
TryDoGDS();
else
mState = State::Idle;
}
else if (mState == State::Done)
{
mState = State::Idle;
}
else
{
ASSERT(false);
}
}
void TryDoEncounter()
{
if (mCurrentBuilding->HasEncounter()
// Hack... probably there's a nicer way
&& !mCurrentBuilding->GetEncounter().mHotspotRef)
{
Logging::LogInfo("Building") << __FUNCTION__ << " "
<< mCurrentBuilding->GetEncounter() << "\n";
std::invoke(
mEncounterCallback,
*mCurrentBuilding->GetEncounter().mEncounterPos + glm::uvec2{600, 600});
// If this encounter is now inactive, we can run this dialog instead
//StartDialog(mCurrentBuilding->GetDialog().mDialog);
//mState = State::Done;
}
else
{
TryDoLock();
}
}
void TryDoLock()
{
if (mCurrentBuilding->HasLock())
{
mState = State::TryUnlock;
mGameState.SetDialogContext_7530(2);
StartDialog(BAK::DialogSources::mChooseUnlock);
}
else
{
mState = State::TryDoGDS;
if (!CheckBitSet(mCurrentBuilding->GetDialog().mDialogOrder, 5))
StartDialog(mCurrentBuilding->GetDialog().mDialog);
else
TryDoGDS();
}
}
void TryDoGDS()
{
ASSERT(mState == State::TryDoGDS);
if (mCurrentBuilding->HasEncounter()
&& mCurrentBuilding->GetEncounter().mHotspotRef)
{
// Do GDS
mState = State::Idle;
mGuiManager.DoFade(.8, [this]{
mGuiManager.EnterGDSScene(
*mCurrentBuilding->GetEncounter().mHotspotRef,
[]{});
});
}
else
{
mState = State::ShowInventory;
TryDoInventory();
}
}
void TryDoInventory()
{
ASSERT(mState == State::ShowInventory);
if (mCurrentBuilding->HasInventory())
{
mGuiManager.ShowContainer(mCurrentBuilding, BAK::EntityType::BUILDING);
}
mState = State::Idle;
}
void EncounterFinished() override
{
TryDoLock();
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
private:
Gui::IGuiManager& mGuiManager;
BAK::GameState& mGameState;
Gui::DynamicDialogScene mDialogScene;
BAK::GenericContainer* mCurrentBuilding;
State mState;
const EncounterCallback& mEncounterCallback;
};
}
| 6,473
|
C++
|
.h
| 219
| 19.945205
| 88
| 0.5476
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,611
|
door.hpp
|
xavieran_BaKGL/game/interactable/door.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "bak/dialogTarget.hpp"
#include "bak/state/door.hpp"
#include "bak/IContainer.hpp"
#include "bak/container.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogSources.hpp"
#include "bak/gameState.hpp"
#include "graphics/glm.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include <glm/geometric.hpp>
namespace Game::Interactable {
class Door : public IInteractable
{
private:
public:
Door(
Gui::IGuiManager& guiManager,
BAK::GameState& gameState)
:
mGuiManager{guiManager},
mGameState{gameState},
mDialogScene{
[]{},
[]{},
[&](const auto& choice){ DialogFinished(choice); }},
mContainer{nullptr}
{}
void BeginInteraction(BAK::GenericContainer& container, BAK::EntityType) override
{
mContainer = &container;
assert(mContainer->HasDoor());
const auto doorIndex = mContainer->GetDoor();
const auto doorState = BAK::State::GetDoorState(mGameState, doorIndex.mValue);
Logging::LogInfo("Door") << "DoorIndex: " << doorIndex << " DoorOpen? " << std::boolalpha << doorState << " locked? " << (mContainer->HasLock() ? mContainer->GetLock().mRating : 0) << "\n";
const auto playerPos = glm::cast<float>(mGameState.GetLocation().mPosition);
const auto doorPos = glm::cast<float>(container.GetHeader().GetPosition());
if (glm::distance(playerPos, doorPos) < 800)
{
StartDialog(BAK::DialogSources::mDoorTooClose);
}
else if (doorState)
{
// Door opened, can always close it
CloseDoor();
}
else if (mContainer->HasLock() && mContainer->GetLock().mRating > 0)
{
mGameState.SetDialogContext_7530(1);
StartDialog(BAK::DialogSources::mChooseUnlock);
}
else
{
OpenDoor();
}
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
ASSERT(mContainer);
ASSERT(choice);
if (choice->mValue == BAK::Keywords::sYesIndex)
{
mGuiManager.ShowLock(
mContainer,
[this]{ LockFinished(); });
}
}
void LockFinished()
{
if (mGuiManager.IsLockOpened())
{
OpenDoor();
}
}
void OpenDoor()
{
const auto doorIndex = mContainer->GetDoor().mValue;
mGameState.Apply(BAK::State::SetDoorState, doorIndex, true);
Logging::LogInfo(__FUNCTION__) << " index; " << doorIndex << "\n";
}
void CloseDoor()
{
const auto doorIndex = mContainer->GetDoor().mValue;
mGameState.Apply(BAK::State::SetDoorState, doorIndex, false);
Logging::LogInfo(__FUNCTION__) << " index; " << doorIndex << "\n";
}
void EncounterFinished() override
{
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
private:
Gui::IGuiManager& mGuiManager;
BAK::GameState& mGameState;
Gui::DynamicDialogScene mDialogScene;
BAK::GenericContainer* mContainer;
};
}
| 3,298
|
C++
|
.h
| 106
| 23.830189
| 197
| 0.607256
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,612
|
pit.hpp
|
xavieran_BaKGL/game/interactable/pit.hpp
|
#pragma once
#include "game/interactable/IInteractable.hpp"
#include "bak/IContainer.hpp"
#include "bak/container.hpp"
#include "bak/dialog.hpp"
#include "bak/dialogSources.hpp"
#include "bak/entityType.hpp"
#include "bak/dialog.hpp"
#include "bak/gameState.hpp"
#include "bak/itemNumbers.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
namespace Game::Interactable {
class Pit : public IInteractable
{
public:
Pit(
Gui::IGuiManager& guiManager,
BAK::GameState& gameState)
:
mGuiManager{guiManager},
mGameState{gameState},
mDialogScene{
[]{},
[]{},
[&](const auto& choice){ DialogFinished(choice); }},
mCurrentPit{nullptr}
{}
void BeginInteraction(BAK::GenericContainer& pit, BAK::EntityType) override
{
mCurrentPit = &pit;
if (mGameState.GetParty().HaveItem(BAK::sRope))
{
StartDialog(BAK::DialogSources::mPitHaveRope);
}
else
{
StartDialog(BAK::DialogSources::mPitNoRope);
}
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
ASSERT(mCurrentPit);
if (choice && choice->mValue == BAK::Keywords::sYesIndex)
{
Logging::LogDebug(__FUNCTION__) << "Swing across pit...\n";
}
else
{
Logging::LogDebug(__FUNCTION__) << "Not crossing pit\n";
}
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
void EncounterFinished() override
{
}
private:
Gui::IGuiManager& mGuiManager;
BAK::GameState& mGameState;
Gui::DynamicDialogScene mDialogScene;
BAK::GenericContainer* mCurrentPit;
};
}
| 1,855
|
C++
|
.h
| 70
| 19.971429
| 79
| 0.618377
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,613
|
textBox.hpp
|
xavieran_BaKGL/gui/textBox.hpp
|
#pragma once
#include "bak/font.hpp"
#include "com/assert.hpp"
#include "com/logger.hpp"
#include "graphics/glm.hpp"
#include "graphics/sprites.hpp"
#include "gui/colors.hpp"
#include "gui/fontManager.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
class TextBox : public Widget
{
public:
TextBox(
glm::vec2 pos,
glm::vec2 dim)
:
Widget{
RectTag{},
pos,
dim,
glm::vec4{0},
//glm::vec4{0,1,0,.3},
true
},
mText{}
{
// no point propagating MouseMoved to every
// character of text
SetInactive();
}
struct Line
{
std::vector<std::size_t> mChars;
glm::vec2 mDimensions;
};
std::pair<glm::vec2, std::string_view> SetText(
const Font& fr,
std::string_view text,
bool centerHorizontal=false,
bool centerVertical=false,
bool isBold=false,
double newLineMultiplier=1.0,
float scale=1.0)
{
const auto& logger = Logging::LogState::GetLogger("Gui::TextBox");
ClearChildren();
mText.clear();
mText.reserve(text.size() * 2);
const auto& font = fr.GetFont();
const auto initialPosition = glm::vec2{0};
auto charPos = initialPosition;
auto limit = initialPosition + GetPositionInfo().mDimensions;
std::vector<Line> lines{};
lines.emplace_back(Line{{}, glm::vec2{0}});
auto italic = false;
auto emphasis = false;
auto bold = false;
auto unbold = false;
auto red = false;
auto white = false;
auto inWord = false;
auto moredhel = false;
const auto NextLine = [&](bool halfLine){
// Save this line's dims and move on to the next
ASSERT(lines.size() > 0);
auto ydiff = ((font.GetHeight() * newLineMultiplier + 1) / scale) * (halfLine ? .45 : 1.0);
lines.back().mDimensions = glm::vec2{
charPos.x + (font.GetSpace() / scale),
charPos.y + ydiff
};
logger.Spam() << "NextLine: pos: " << charPos << " prevDims: " << lines.back().mDimensions << "\n";
lines.emplace_back(Line{{}, glm::vec2{0}});
charPos.x = initialPosition.x;
charPos.y += ydiff;
italic = false;
unbold = false;
red = false;
white = false;
emphasis = false;
inWord = false;
};
const auto AdvanceChar = [&](auto w){
charPos.x += (w / scale);
};
const auto Advance = [&](auto w){
AdvanceChar(w);
if (charPos.x > limit.x)
NextLine(false);
};
unsigned wordLetters = 0;
const auto Draw = [&](const auto& pos, auto c, const auto& color)
{
ASSERT(lines.size() > 0);
lines.back().mChars.emplace_back(mText.size());
mText.emplace_back(
Graphics::DrawMode::Sprite,
fr.GetSpriteSheet(),
static_cast<Graphics::TextureIndex>(
font.GetIndex(c)),
Graphics::ColorMode::ReplaceColor,
color,
pos,
glm::vec2{fr.GetFont().GetWidth(c), fr.GetFont().GetHeight()} / scale,
true);
};
const auto DrawNormal = [&](const auto& pos, auto c)
{
Draw(
charPos,
c,
Color::black);
};
const auto DrawBold = [&](const auto& pos, auto c, auto bg, auto fg)
{
Draw(
charPos + glm::vec2{0, 1},
c,
bg);
Draw(
charPos,
c,
fg);
};
const auto DrawMoredhel = [&](const auto& pos, auto c)
{
Draw(
charPos + glm::vec2{0, -1},
c,
Color::moredhelFontUpper);
Draw(
charPos + glm::vec2{0, 1},
c,
Color::moredhelFontLower);
Draw(
charPos,
c,
Color::black);
};
unsigned currentChar = 0;
for (; currentChar < text.size(); currentChar++)
{
if (text.size() == 0)
{
break;
}
const auto c = text[currentChar];
logger.Spam() << "Char[" << c << "]" << std::hex
<< +c << std::dec << " " << charPos << "\n";
if (c == '\n')
{
NextLine(false);
}
else if (c == '\t')
{
Advance(font.GetSpace() * 4);
bold = false;
}
else if (c == ' ')
{
if (moredhel)
{
// moredhel text is very spaced...
Advance(font.GetSpace() * 6);
}
Advance(font.GetSpace());
emphasis = false;
italic = false;
}
else if (c == '#')
{
bold = !bold;
}
else if (c == static_cast<char>(0xf0))
{
emphasis = true;
}
else if (c == static_cast<char>(0xf1))
{
emphasis = true;
}
else if (c == static_cast<char>(0xf3))
{
italic = true;
}
else if (c == static_cast<char>(0xf4))
{
unbold = !unbold;
}
else if (c == static_cast<char>(0xf5))
{
red = !red;
}
else if (c == static_cast<char>(0xf6))
{
white = !white;
}
else if (c == static_cast<char>(0xf7))
{
moredhel = !moredhel;
}
else if (c == static_cast<char>(0xf8))
{
NextLine(true);
}
else if (c == static_cast<char>(0xe1)
|| c == static_cast<char>(0xe2) // not sure on e2
|| c == static_cast<char>(0xe3)) // not sure on e3
{
// Book text.. quoted or something
DrawNormal(charPos, ' ');
Advance(font.GetSpace() / 2.0);
}
else
{
if (moredhel)
{
DrawMoredhel(charPos, c);
}
else if (bold)
{
if (isBold)
DrawNormal(charPos, c);
else
DrawBold(charPos, c, Color::buttonShadow, Color::fontHighlight);
}
else if (unbold)
{
// Maybe "lowlight", inactive
DrawBold(charPos, c, Color::black, Color::fontUnbold);
//DrawUnbold(charPos, c);
}
else if (red)
{
DrawBold(charPos, c, Color::fontRedLowlight, Color::fontRedHighlight);
}
else if (white)
{
DrawBold(charPos, c, Color::black, Color::fontWhiteHighlight);
}
else if (emphasis)
{
Draw(
charPos,
c,
Color::fontEmphasis);
}
else if (italic)
{
Draw(
charPos,
c,
Color::fontLowlight);
// Draw italic...
}
else
{
if (isBold)
DrawBold(charPos, c, Color::buttonShadow, Color::fontHighlight);
else
DrawNormal(charPos, c);
}
Advance(font.GetWidth(c));
}
const auto nextChar = currentChar + 1;
if (nextChar < text.size())
{
const auto ch = text[nextChar];
const auto isAlphaNum = ch >= '!' || c <= 'z';
if (isAlphaNum && !inWord)
{
const auto saved = charPos;
const auto wordStart = std::next(text.begin(), nextChar);
const auto it = std::find_if(
wordStart,
std::next(text.begin(), text.size()),
[](const auto& c){ return c < '!' || c > 'z'; });
// Check if this word would overflow our bounds
wordLetters = std::distance(wordStart, it);
for (const auto& ch : text.substr(nextChar, wordLetters))
AdvanceChar(font.GetWidth(ch));
logger.Spam() << "Next Word: " << text.substr(nextChar, wordLetters) << "\n";
if (charPos.x >= limit.x)
{
charPos = saved;
NextLine(false);
}
else
charPos = saved;
}
else if (isAlphaNum)
{
inWord = true;
}
else
{
// Exiting a word
emphasis = false;
italic = false;
inWord = false;
}
}
if (charPos.y + font.GetHeight() > limit.y)
break;
}
// Set the dims of the final line
logger.Spam() << "LastLine\n";
NextLine(false);
for (auto& elem : mText)
this->AddChildBack(&elem);
if (centerVertical)
{
const auto verticalAdjustment = limit.y > charPos.y
? (limit.y - charPos.y ) / 2.0
: 0;
for (auto& w : mText)
w.AdjustPosition(
glm::vec2{0, verticalAdjustment});
charPos.y += verticalAdjustment;
}
if (centerHorizontal)
{
for (const auto& line : lines)
{
const auto lineWidth = line.mDimensions.x;
auto horizontalAdjustment = (limit.x - lineWidth) / 2.0;
if (horizontalAdjustment < 0) horizontalAdjustment = 0;
logger.Spam() << "Line: " << lineWidth << " lim: " << limit.x << " adj: " << horizontalAdjustment << "\n";
for (const auto c : line.mChars)
{
ASSERT(c < mText.size());
mText[c].AdjustPosition(
glm::vec2{horizontalAdjustment, 0});
}
}
}
auto maxX = std::max_element(
lines.begin(), lines.end(),
[](auto lhs, auto rhs){
return lhs.mDimensions.x < rhs.mDimensions.x;
});
ASSERT(currentChar <= text.size() * 2);
return std::make_pair(
glm::vec2{maxX->mDimensions.x, charPos.y},
text.substr(
currentChar,
text.size() - currentChar));
}
private:
std::vector<Widget> mText;
};
}
| 11,695
|
C++
|
.h
| 353
| 19.025496
| 122
| 0.416955
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,614
|
temple.hpp
|
xavieran_BaKGL/gui/temple.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/hotspot.hpp"
#include "bak/dialogSources.hpp"
#include "bak/money.hpp"
#include "bak/temple.hpp"
#include "bak/textureFactory.hpp"
#include "com/logger.hpp"
#include "graphics/sprites.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/dialogDisplay.hpp"
#include "gui/hotspot.hpp"
#include "gui/staticTTM.hpp"
#include "gui/core/widget.hpp"
namespace Gui {
class Temple : public IDialogScene
{
enum class State
{
Idle,
Talk,
Cure,
Bless,
BlessChosen,
BlessAlreadyBlessed,
};
public:
Temple(
BAK::GameState& gameState,
IGuiManager& guiManager)
:
mState{State::Idle},
mGameState{gameState},
mGuiManager{guiManager},
mItem{nullptr},
mShopStats{nullptr},
mTarget{BAK::KeyTarget{0}},
mTempleNumber{0},
mParentScene{},
mLogger{Logging::LogState::GetLogger("Gui::Temple")}
{}
Temple(const Temple&) = delete;
Temple& operator=(const Temple&) = delete;
void EnterTemple(
BAK::KeyTarget keyTarget,
unsigned templeIndex,
BAK::ShopStats& shopStats,
IDialogScene* parentScene)
{
mShopStats = &shopStats;
mTarget = keyTarget;
mState = State::Idle;
mTempleNumber = templeIndex;
mGameState.SetDialogContext_7530(templeIndex);
mParentScene = parentScene;
StartDialog(keyTarget);
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice) override
{
mLogger.Info() << " Choice: " << choice << "\n";
if (mState == State::Idle)
{
if (choice)
{
// (269, #Talk),(272, #Cure),(271, #Bless),(268, #Done)
if (*choice == BAK::ChoiceIndex{269})
{
StartDialog(mTarget);
}
else if (*choice == BAK::ChoiceIndex{272})
{
if (mGameState.GetEndOfDialogState() != -1)
{
bool canHeal = false;
for (unsigned i = 0; i < mGameState.GetParty().GetNumCharacters(); i++)
{
const auto& character = mGameState.GetParty().GetCharacter(BAK::ActiveCharIndex{i});
const auto cureCost = BAK::Temple::CalculateCureCost(
mShopStats->GetTempleHealFactor(),
mTempleNumber == BAK::Temple::sTempleOfSung,
character.mSkills,
character.GetConditions(),
character.GetSkillAffectors());
if (cureCost.mValue != 0)
{
// will this always be true?
// I vaguely remember temple of Eortis might be free
canHeal = true;
}
}
mState = State::Cure;
if (canHeal)
{
mGuiManager.ShowCureScreen(
mTempleNumber,
mShopStats->GetTempleHealFactor(),
[this](){
DialogFinished(std::nullopt); });
}
else
{
StartDialog(
mTempleNumber == BAK::Temple::sTempleOfSung
? BAK::DialogSources::mHealDialogCantHealNotSick
: BAK::DialogSources::mHealDialogCantHealNotSickEnough);
}
}
else
{
mState = State::Idle;
StartDialog(mTarget);
}
}
else if (*choice == BAK::ChoiceIndex{271})
{
mLogger.Debug() << "End of dialog state: " << mGameState.GetEndOfDialogState() << "\n";
if (mGameState.GetEndOfDialogState() != -1)
{
mState = State::Bless;
mGuiManager.SelectItem(
[this](auto item){ HandleItemSelected(item); });
}
else
{
mState = State::Idle;
StartDialog(mTarget);
}
}
else if (*choice == BAK::ChoiceIndex{268})
{
mParentScene->DialogFinished(std::nullopt);
}
}
}
else if (mState == State::BlessChosen)
{
if (choice)
HandleBlessChoice(*choice);
}
else if (mState == State::BlessAlreadyBlessed)
{
ASSERT(choice);
HandleUnblessChoice(*choice);
}
else if (mState == State::Cure)
{
mState = State::Idle;
StartDialog(mTarget);
}
}
void DisplayNPCBackground() override
{
assert(mParentScene);
mParentScene->DisplayNPCBackground();
}
void DisplayPlayerBackground() override
{
assert(mParentScene);
mParentScene->DisplayPlayerBackground();
}
private:
void StartDialog(BAK::KeyTarget keyTarget)
{
mGuiManager.StartDialog(keyTarget, false, false, this);
}
void HandleBlessChoice(BAK::ChoiceIndex choice)
{
ASSERT(mItem);
const auto cost = BAK::Temple::CalculateBlessPrice(*mItem, *mShopStats);
if (choice == BAK::ChoiceIndex{260} && mGameState.GetMoney() > cost)
{
mLogger.Info() << __FUNCTION__ << " Blessing item\n";
mGameState.GetParty().LoseMoney(cost);
if (BAK::Temple::IsBlessed(*mItem))
{
BAK::Temple::RemoveBlessing(*mItem);
}
BAK::Temple::BlessItem(*mItem, *mShopStats);
AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{0x3e});
}
}
void HandleUnblessChoice(BAK::ChoiceIndex choice)
{
ASSERT(mItem);
if (choice == BAK::ChoiceIndex{256})
{
mLogger.Info() << __FUNCTION__ << " Unblessing item\n";
mState = State::BlessChosen;
StartDialog(BAK::DialogSources::mBlessDialogCost);
}
}
void HandleItemSelected(std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>> selectedItem)
{
ASSERT(mShopStats);
if (!selectedItem)
{
mState = State::Idle;
StartDialog(mTarget);
return;
}
const auto [charIndex, itemIndex] = *selectedItem;
auto& character = mGameState.GetParty().GetCharacter(charIndex);
auto& item = character.GetInventory().GetAtIndex(itemIndex);
mItem = &item;
mGameState.SetActiveCharacter(character.GetIndex());
mGameState.SetInventoryItem(item);
mGameState.SetItemValue(BAK::Temple::CalculateBlessPrice(item, *mShopStats));
if (BAK::Temple::IsBlessed(item))
{
mState = State::BlessAlreadyBlessed;
StartDialog(BAK::DialogSources::mBlessDialogItemAlreadyBlessed);
}
else if (!BAK::Temple::CanBlessItem(item))
{
StartDialog(BAK::DialogSources::mBlessDialogCantBlessItem);
}
else
{
mState = State::BlessChosen;
if (mItem->IsItemType(BAK::ItemType::Sword))
{
mGameState.SetDialogContext_7530(0);
}
else
{
mGameState.SetDialogContext_7530(1);
}
StartDialog(BAK::DialogSources::mBlessDialogCost);
}
}
State mState;
BAK::GameState& mGameState;
IGuiManager& mGuiManager;
BAK::InventoryItem* mItem;
BAK::ShopStats* mShopStats;
BAK::KeyTarget mTarget;
unsigned mTempleNumber;
IDialogScene* mParentScene;
const Logging::Logger& mLogger;
};
}
| 8,434
|
C++
|
.h
| 242
| 21.966942
| 112
| 0.508884
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,615
|
gdsScene.hpp
|
xavieran_BaKGL/gui/gdsScene.hpp
|
#pragma once
#include "bak/hotspot.hpp"
#include "bak/textureFactory.hpp"
#include "graphics/sprites.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/dialogDisplay.hpp"
#include "gui/hotspot.hpp"
#include "gui/staticTTM.hpp"
#include "gui/temple.hpp"
#include "gui/repair.hpp"
#include "gui/core/widget.hpp"
namespace Gui {
class GDSScene : public Widget, public IDialogScene
{
public:
GDSScene(
Cursor& cursor,
BAK::HotspotRef hotspotRef,
Graphics::SpriteManager& spriteManager,
const Actors& actors,
const Backgrounds& backgrounds,
const Font& font,
BAK::GameState& gameState,
IGuiManager& guiManager);
GDSScene(const GDSScene&) = delete;
GDSScene& operator=(const GDSScene&) = delete;
void EnterGDSScene();
void DisplayNPCBackground() override;
void DisplayPlayerBackground() override;
const auto& GetSceneHotspots() const { return mSceneHotspots; }
public:
void HandleHotspotLeftClicked(const BAK::Hotspot& hotspot, bool);
void HandleHotspotLeftClicked2(const BAK::Hotspot& hotspot, bool);
void HandleHotspotRightClicked(const BAK::Hotspot& hotspot);
void StartDialog(BAK::Target target, bool isTooltip);
void DialogFinished(const std::optional<BAK::ChoiceIndex>&) override;
void AddStaticTTM(BAK::Scene scene1, BAK::Scene scene2);
void EvaluateHotspotAction();
void EnterContainer();
void DoInn();
void DoBard();
void DoRepair();
void DoTeleport();
void DoTemple(BAK::KeyTarget);
void DoGoto();
void DoExit();
Graphics::SpriteManager::TemporarySpriteSheet mSpriteSheet;
const Font& mFont;
BAK::HotspotRef mReference;
BAK::GameState& mGameState;
BAK::SceneHotspots mSceneHotspots;
BAK::KeyTarget mFlavourText;
Graphics::SpriteManager& mSpriteManager;
// Frame to surround the scene
Widget mFrame;
std::vector<StaticTTM> mStaticTTMs{};
std::vector<Hotspot> mHotspots{};
std::vector<bool> mHotspotClicked{};
Cursor& mCursor;
IGuiManager& mGuiManager;
DialogDisplay mDialogDisplay;
std::optional<BAK::HotspotAction> mPendingAction{};
std::optional<BAK::HotspotRef> mPendingGoto{};
// e.g. when you fail barding
bool mKickedOut{};
bool mBarding{};
Temple mTemple;
Repair mRepair;
static constexpr auto mMaxSceneNesting = 4;
const Logging::Logger& mLogger;
};
}
| 2,473
|
C++
|
.h
| 73
| 29.054795
| 73
| 0.727733
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,616
|
hotspot.hpp
|
xavieran_BaKGL/gui/hotspot.hpp
|
#pragma once
#include "com/logger.hpp"
#include "com/visit.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/highlightable.hpp"
#include "gui/core/widget.hpp"
#include "gui/colors.hpp"
#include "gui/cursor.hpp"
#include "gui/textBox.hpp"
namespace Gui {
namespace detail {
class HotspotBase : public Widget
{
public:
HotspotBase(
Cursor& cursor,
const Font& font,
glm::vec2 pos,
glm::vec2 dims,
unsigned id,
unsigned highlightCursor)
:
Widget{
RectTag{},
// Filthy hack - make these a little smaller
// because some of them overlap which breaks the cursor
pos + glm::vec2{2},
dims - glm::vec2{3},
//Color::debug,
glm::vec4{0},
true
},
mCursor{cursor},
mHighlightCursor{highlightCursor}
{
}
void Entered()
{
mCursor.PushCursor(mHighlightCursor);
}
void Exited()
{
mCursor.PopCursor();
}
private:
Cursor& mCursor;
unsigned mHighlightCursor;
};
}
using Hotspot = Clickable<
Clickable<
Highlightable<
detail::HotspotBase, false>,
RightMousePress,
std::function<void()>>,
LeftMousePress,
std::function<void()>>;
}
| 1,317
|
C++
|
.h
| 58
| 16.534483
| 67
| 0.603047
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,617
|
scrollView.hpp
|
xavieran_BaKGL/gui/scrollView.hpp
|
#pragma once
#include "gui/backgrounds.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/icons.hpp"
#include "gui/scrollBar.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
template <ImplementsWidget T>
class ScrollView : public Widget
{
// FIXME: Implement horizontal scroll
static constexpr auto sScrollSpeed = 10.0f;
public:
template <typename ...Args>
ScrollView(
glm::vec2 pos,
glm::vec2 dims,
const Icons& icons,
bool scrollHorizontal,
bool scrollVertical,
Args&&... childArgs)
:
Widget{
ClipRegionTag{},
pos,
dims,
true
},
mScrollHorizontal{scrollHorizontal},
mScrollVertical{scrollVertical},
mLastMousePos{0},
mChild{std::forward<Args>(childArgs)...},
mScrollBar{
glm::vec2{dims.x - 16, 0},
glm::vec2{16, dims.y},
icons,
glm::vec2{16, dims.y},
true,
[this](const auto& adjustment){ Scroll(adjustment); }
},
mLogger{Logging::LogState::GetLogger("Gui::ScrollView")}
{
AddChildren();
}
T& GetChild()
{
return mChild;
}
void SetDimensions(glm::vec2 dims) override
{
Widget::SetDimensions(dims);
mChild.SetDimensions(dims);
mScrollBar.SetDimensions(glm::vec2{16, dims.y});
}
bool OnMouseEvent(const MouseEvent& event) override
{
// ... track mouse position
if (std::holds_alternative<MouseMove>(event))
{
mLastMousePos = GetValue(event);
return Widget::OnMouseEvent(event);
}
if (Within(mLastMousePos) &&
std::holds_alternative<MouseScroll>(event))
{
Scroll(GetValue(event));
return true;
}
else if (Within(GetValue(event)))
{
return Widget::OnMouseEvent(event);
}
return false;
}
void ResetScroll()
{
mScrollBar.SetScale(std::min(GetDimensions().y / mChild.GetDimensions().y, 1.0f));
mChild.SetPosition(glm::vec2{});
mScrollBar.SetBarPosition(0);
}
private:
void Scroll(glm::vec2 adjustment)
{
const auto scale = glm::vec2{mScrollHorizontal, mScrollVertical} * sScrollSpeed;
auto newPosition = mChild.GetTopLeft() + adjustment * scale;
const auto dimDiff = (GetDimensions().y - mChild.GetDimensions().y);
if (newPosition.y > 0
|| newPosition.y < dimDiff)
{
if (adjustment.y > 0)
{
newPosition = glm::vec2{newPosition.x, 0};
}
else if (adjustment.y < 0)
{
newPosition = glm::vec2{newPosition.x, dimDiff};
}
}
// No need for scrolling if the child fits in the scroll view
if (mChild.GetDimensions().y < GetDimensions().y) return;
mChild.SetPosition(newPosition);
mScrollBar.SetBarPosition(mChild.GetTopLeft().y / dimDiff);
}
void AddChildren()
{
ClearChildren();
AddChildBack(&mChild);
AddChildBack(&mScrollBar);
}
// Ideally we'd just track the cursor..?
const bool mScrollHorizontal;
const bool mScrollVertical;
glm::vec2 mLastMousePos;
T mChild;
ScrollBar mScrollBar;
const Logging::Logger& mLogger;
};
}
| 3,496
|
C++
|
.h
| 120
| 21.183333
| 90
| 0.58927
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,618
|
animatorStore.hpp
|
xavieran_BaKGL/gui/animatorStore.hpp
|
#pragma once
#include "com/assert.hpp"
#include "com/logger.hpp"
#include "com/visit.hpp"
#include "gui/IAnimator.hpp"
#include <glm/glm.hpp>
namespace Gui {
class AnimatorStore
{
public:
AnimatorStore()
:
mAnimators{},
mLogger{Logging::LogState::GetLogger("Gui::AnimatorStore")}
{
}
void AddAnimator(std::unique_ptr<IAnimator>&& animator)
{
mAnimators.emplace_back(std::move(animator));
mLogger.Spam() << "Added animator @" << mAnimators.back() << "\n";
}
void OnTimeDelta(double delta)
{
mLogger.Spam() << "Ticking : " << delta << "\n";
for (auto& animator : mAnimators)
animator->OnTimeDelta(delta);
mAnimators.erase(
std::remove_if(
mAnimators.begin(), mAnimators.end(),
[&](const auto& a){
return !a->IsAlive();
}),
mAnimators.end());
}
private:
std::vector<std::unique_ptr<IAnimator>> mAnimators;
const Logging::Logger& mLogger;
};
}
| 1,059
|
C++
|
.h
| 39
| 20.538462
| 74
| 0.585728
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,619
|
cutscenePlayer.hpp
|
xavieran_BaKGL/gui/cutscenePlayer.hpp
|
#pragma once
#include "bak/cutscenes.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/bookPlayer.hpp"
#include "gui/core/widget.hpp"
#include "gui/dynamicTTM.hpp"
namespace Gui {
class CutscenePlayer : public Widget
{
public:
CutscenePlayer(
Graphics::SpriteManager& spriteManager,
AnimatorStore& animatorStore,
const Font& font,
const Font& bookFont,
const Backgrounds& background,
IGuiManager& guiManager,
std::function<void()>&& cutsceneFinished)
:
Widget(RectTag{}, glm::vec2{}, glm::vec2{320, 200}, glm::vec4{}, true),
mBookPlayer(
spriteManager,
bookFont,
background,
[&](){ BookFinished(); }),
mDynamicTTM(
spriteManager,
animatorStore,
font,
background,
[&](){ SceneFinished(); },
[&](auto book){ PlayBook(book); }),
mGuiManager{guiManager},
mCutsceneFinished{std::move(cutsceneFinished)}
{
}
void QueueAction(BAK::CutsceneAction action)
{
mActions.emplace_back(action);
}
void Play()
{
if (mActions.empty())
{
mCutsceneFinished();
return;
}
auto action = *mActions.begin();
mActions.erase(mActions.begin());
std::visit(overloaded{
[&](const BAK::TTMScene& scene)
{
mDynamicTTM.BeginScene(scene.mAdsFile, scene.mTTMFile);
ClearChildren();
AddChildBack(mDynamicTTM.GetScene());
mTtmPlaying = true;
mDynamicTTM.AdvanceAction();
},
[&](const BAK::BookChapter& book)
{
mBookPlayer.PlayBook(book.mBookFile);
ClearChildren();
AddChildBack(mBookPlayer.GetBackground());
}},
action);
}
bool OnMouseEvent(const MouseEvent& event) override
{
const auto result = std::visit(overloaded{
[this](const LeftMousePress& p){ Advance(); return true; },
[](const auto& p){ return false; }
},
event);
if (result)
return result;
return false;
}
void Advance()
{
if (GetChildren()[0] == mDynamicTTM.GetScene())
{
mDynamicTTM.AdvanceAction();
}
else if (GetChildren()[0] == mBookPlayer.GetBackground())
{
mBookPlayer.AdvancePage();
}
}
private:
void BookFinished()
{
if (mTtmPlaying)
{
mGuiManager.DoFade(1.5, [&]{
ClearChildren();
AddChildBack(mDynamicTTM.GetScene());
mDynamicTTM.AdvanceAction();
});
}
else
{
mGuiManager.DoFade(1.5, [&]{ Play(); });
}
}
void SceneFinished()
{
mTtmPlaying = false;
mGuiManager.DoFade(1.5, [&]{
Play();
});
}
void PlayBook(unsigned book)
{
ClearChildren();
AddChildBack(mBookPlayer.GetBackground());
std::stringstream ss{};
ss << "C";
ss << (book / 10) % 10;
ss << book % 10;
ss << ".BOK";
mBookPlayer.PlayBook(ss.str());
}
bool mTtmPlaying = false;
std::vector<BAK::CutsceneAction> mActions;
BookPlayer mBookPlayer;
DynamicTTM mDynamicTTM;
IGuiManager& mGuiManager;
std::function<void()> mCutsceneFinished;
};
}
| 3,572
|
C++
|
.h
| 130
| 18.492308
| 79
| 0.537091
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,620
|
guiManager.hpp
|
xavieran_BaKGL/gui/guiManager.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/IZoneLoader.hpp"
#include "bak/chapterTransitions.hpp"
#include "bak/cutscenes.hpp"
#include "bak/dialog.hpp"
#include "bak/encounter/teleport.hpp"
#include "bak/entityType.hpp"
#include "bak/gameState.hpp"
#include "bak/saveManager.hpp"
#include "bak/startupFiles.hpp"
#include "com/assert.hpp"
#include "com/cpptrace.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/animatorStore.hpp"
#include "gui/camp/campScreen.hpp"
#include "gui/cast/castScreen.hpp"
#include "gui/cureScreen.hpp"
#include "gui/dialogRunner.hpp"
#include "gui/fadeScreen.hpp"
#include "gui/fontManager.hpp"
#include "gui/fullMap.hpp"
#include "gui/gdsScene.hpp"
#include "gui/icons.hpp"
#include "gui/info/infoScreen.hpp"
#include "gui/inventory/inventoryScreen.hpp"
#include "gui/lock/lockScreen.hpp"
#include "gui/lock/moredhelScreen.hpp"
#include "gui/mainMenuScreen.hpp"
#include "gui/mainView.hpp"
#include "gui/teleportScreen.hpp"
#include "gui/cutscenePlayer.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <functional>
#include <utility>
#include <variant>
namespace Gui {
class GuiScreen
{
public:
GuiScreen(std::function<void()> finished)
:
mFinished{finished}
{}
std::function<void()> mFinished;
};
class GuiManager final : public Widget, public IGuiManager
{
public:
GuiManager(
Cursor& cursor,
Graphics::SpriteManager& spriteManager,
BAK::GameState& gameState)
:
Widget{
Graphics::DrawMode::Rect,
Graphics::SpriteSheetIndex{0},
Graphics::TextureIndex{0},
Graphics::ColorMode::SolidColor,
glm::vec4{0},
glm::vec2{0},
glm::vec2{1},
false
},
mFontManager{spriteManager},
mActors{spriteManager},
mBackgrounds{spriteManager},
mIcons{spriteManager},
mCursor{cursor},
mGameState{gameState},
mScreenStack{},
mDialogRunner{
glm::vec2{0, 0},
glm::vec2{320, 240},
mActors,
mBackgrounds,
mFontManager.GetGameFont(),
gameState,
mScreenStack,
[this](const auto& choice){ DialogFinished(choice); }
},
mSpriteManager{spriteManager},
mCutscenePlayer{
spriteManager,
mAnimatorStore,
mFontManager.GetGameFont(),
mFontManager.GetBookFont(),
mBackgrounds,
*this,
[this](){ CutsceneFinished(); }
},
mMainView{*this, mBackgrounds, mIcons, mFontManager.GetSpellFont()},
mMainMenu{*this, mSpriteManager, mBackgrounds, mIcons, mFontManager.GetGameFont()},
mInfoScreen{
*this,
mActors,
mBackgrounds,
mIcons,
mFontManager.GetGameFont(),
mGameState
},
mInventoryScreen{
*this,
mBackgrounds,
mIcons,
mFontManager.GetGameFont(),
mGameState
},
mCampScreen{
*this,
mBackgrounds,
mIcons,
mFontManager.GetGameFont(),
mGameState
},
mCastScreen{
*this,
mBackgrounds,
mIcons,
mFontManager.GetGameFont(),
mFontManager.GetSpellFont(),
mGameState
},
mCureScreen{
*this,
mActors,
mBackgrounds,
mIcons,
mFontManager.GetGameFont(),
mGameState
},
mLockScreen{
*this,
mBackgrounds,
mIcons,
mFontManager.GetGameFont(),
mGameState
},
mFullMap{
*this,
mBackgrounds,
mIcons,
mFontManager.GetGameFont(),
mGameState
},
mMoredhelScreen{
*this,
mBackgrounds,
mIcons,
mFontManager.GetAlienFont(),
mFontManager.GetPuzzleFont(),
mGameState
},
mTeleportScreen{
*this,
mBackgrounds,
mIcons,
mFontManager.GetGameFont(),
mGameState
},
mFadeScreen{
mAnimatorStore,
[this]{ FadeInDone(); },
[this]{ FadeOutDone(); }
},
mFadeFunction{},
mGdsScenes{},
mDialogScene{nullptr},
mGuiScreens{},
mAnimatorStore{},
mZoneLoader{nullptr},
mLogger{Logging::LogState::GetLogger("Gui::GuiManager")}
{
mGdsScenes.reserve(4);
AddChildBack(&mScreenStack);
}
[[nodiscard]] bool OnMouseEvent(const MouseEvent& event) override
{
if (HaveChild(&mFadeScreen))
{
return true;
}
else
{
return Widget::OnMouseEvent(event);
}
}
ScreenStack& GetScreenStack() override
{
return mScreenStack;
}
void LoadGame(std::string save, std::optional<BAK::Chapter> chapter) override
{
ASSERT(mZoneLoader);
mZoneLoader->LoadGame(save, chapter);
mMainView.SetHeading(mGameState.GetLocation().mHeading);
}
void SaveGame(const BAK::SaveFile& saveFile) override
{
mGameState.Save(saveFile);
EnterMainView();
}
void SetZoneLoader(BAK::IZoneLoader* zoneLoader)
{
ASSERT(zoneLoader);
mZoneLoader = zoneLoader;
}
void DoFade(double duration, std::function<void()>&& fadeFunction) override
{
CPPTRACE(mLogger.Info(), __FUNCTION__);
mFadeFunction.emplace_back(std::move(fadeFunction));
if (!HaveChild(&mFadeScreen))
{
AddChildBack(&mFadeScreen);
mFadeScreen.FadeIn(duration);
}
}
void PlayCutscene(
std::vector<BAK::CutsceneAction> actions,
std::function<void()>&& cutsceneFinished) override
{
mCutsceneFinished = std::move(cutsceneFinished);
for (const auto& action : actions)
{
mCutscenePlayer.QueueAction(action);
}
DoFade(1.5, [this]{
if (mScreenStack.HasChildren())
{
mPreviousScreen = mScreenStack.Top();
mScreenStack.PopScreen();
}
mScreenStack.PushScreen(&mCutscenePlayer);
mCutscenePlayer.Play();
});
}
void CutsceneFinished()
{
mCutsceneFinished();
}
bool InMainView() const override
{
return mScreenStack.size() > 0 && mScreenStack.Top() == &mMainView;
}
void EnterMainView() override
{
mLogger.Info() << "Entering main view\n";
mMainView.UpdatePartyMembers(mGameState);
DoFade(1.0, [this]{
mScreenStack.PopScreen();
mScreenStack.PushScreen(&mMainView);
if (mOnEnterMainView)
{
mOnEnterMainView();
mOnEnterMainView = nullptr;
}
});
}
void EnterMainMenu(bool gameRunning) override
{
DoFade(1.0, [this, gameRunning]{
if (gameRunning)
{
mScreenStack.PopScreen();
}
mScreenStack.PushScreen(&mMainMenu);
mMainMenu.EnterMainMenu(gameRunning);
});
}
void TeleportToGDS(
const BAK::HotspotRef& hotspot)
{
mLogger.Debug() << __FUNCTION__ << ":" << hotspot << "\n";
// When teleporting we need to add the "root" GDS scene to the stack
// because it won't have been there...
if (hotspot.mGdsNumber < 12 && hotspot.mGdsChar != 'A')
{
const auto rootScene = BAK::HotspotRef{hotspot.mGdsNumber, 'A'};
mLogger.Debug() << "Teleporting to root first: " << rootScene << "\n";
EnterGDSScene(rootScene, []{});
}
mLogger.Debug() << "Teleporting to child: " << hotspot << "\n";
EnterGDSScene(hotspot, []{});
}
void OnTimeDelta(double delta)
{
mAnimatorStore.OnTimeDelta(delta);
}
void AddAnimator(std::unique_ptr<IAnimator>&& animator) override
{
mAnimatorStore.AddAnimator(std::move(animator));
}
void EnterGDSScene(
const BAK::HotspotRef& hotspot,
std::function<void()>&& finished) override
{
mLogger.Debug() << __FUNCTION__ << ":" << hotspot << "\n";
mCursor.PushCursor(0);
mGdsScenes.emplace_back(
std::make_unique<GDSScene>(
mCursor,
hotspot,
mSpriteManager,
mActors,
mBackgrounds,
mFontManager.GetGameFont(),
mGameState,
static_cast<IGuiManager&>(*this)));
const auto song = mGdsScenes.back()->GetSceneHotspots().mSong;
if (song != 0)
{
AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::MusicIndex{song});
mGuiScreens.push(GuiScreen{
[fin = std::move(finished)](){
AudioA::AudioManager::Get().PopTrack();
std::invoke(fin);
}});
}
else
{
mGuiScreens.push(finished);
}
mScreenStack.PushScreen(mGdsScenes.back().get());
mGdsScenes.back()->EnterGDSScene();
}
void ExitGDSScene() override
{
mLogger.Debug() << "Exiting GDS Scene" << std::endl;
RemoveGDSScene(true);
}
void RemoveGDSScene(bool runFinished=false)
{
ASSERT(!mGdsScenes.empty());
mLogger.Debug() << __FUNCTION__ << " Widgets: " << mScreenStack.GetChildren() << "\n";
mScreenStack.PopScreen();
mCursor.PopCursor();
mCursor.PopCursor();
if (runFinished)
PopAndRunGuiScreen();
else
PopGuiScreen();
mLogger.Debug() << "Removed GDS Scene: " << mGdsScenes.back() << std::endl;
mGdsScenes.pop_back();
}
void StartDialog(
BAK::Target dialog,
bool isTooltip,
bool drawWorldFrame,
IDialogScene* scene) override
{
mCursor.PushCursor(0);
mDialogRunner.SetInWorldView(InMainView() || drawWorldFrame);
mGuiScreens.push(GuiScreen{[](){
}});
mScreenStack.PushScreen(&mDialogRunner);
mDialogScene = scene;
mDialogRunner.SetDialogScene(scene);
mDialogRunner.BeginDialog(dialog, isTooltip);
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice)
{
ASSERT(mDialogScene);
PopAndRunGuiScreen();
mScreenStack.PopScreen(); // Dialog runner
mCursor.PopCursor();
mLogger.Debug() << "Finished dialog with choice : " << choice << "\n";
mDialogScene->DialogFinished(choice);
const auto teleportIndex = mDialogRunner.GetAndResetPendingTeleport();
if (teleportIndex)
{
const auto& teleport = mTeleportFactory.Get(teleportIndex->mValue);
DoTeleport(teleport);
}
if (mGameState.GetTransitionChapter_7541())
{
mGameState.SetTransitionChapter_7541(false);
DoChapterTransition();
}
mMainView.UpdatePartyMembers(mGameState);
}
void DoChapterTransition() override
{
auto actions = BAK::CutsceneList::GetFinishScene(mGameState.GetChapter());
const auto nextChapter = BAK::Chapter(mGameState.GetChapter().mValue + 1);
for (const auto& action : BAK::CutsceneList::GetStartScene(nextChapter))
{
actions.emplace_back(action);
}
PlayCutscene(actions, [this, nextChapter]{
// Remove gds scenes in case we transitioned from a GDS
while (!mGdsScenes.empty())
RemoveGDSScene();
auto teleport = BAK::TransitionToChapter(nextChapter, mGameState);
ShowGameStartMap();
mOnEnterMainView = [this, nextChapter, teleport]{
// Always teleport to the new world location
const auto startLocation = LoadChapterStartLocation(nextChapter).mLocation;
DoTeleport(
BAK::Encounter::Teleport{
startLocation.mZone,
startLocation.mLocation,
std::nullopt});
// Optionally we may need to teleport to a GDS location
if (teleport)
{
mLogger.Info() << "Teleporting to: " << *teleport << std::endl;
DoTeleport(mTeleportFactory.Get(teleport->mIndex.mValue));
}
};
});
}
void DoTeleport(BAK::Encounter::Teleport teleport) override
{
mLogger.Info() << "Teleporting to teleport index: " << teleport << "\n";
// Clear all stacked GDS scenes
while (!mGdsScenes.empty())
RemoveGDSScene();
mLogger.Debug() << __FUNCTION__ << "Widgets: " << GetChildren() << "\n";
if (mZoneLoader)
mZoneLoader->DoTeleport(teleport);
mLogger.Debug() << "Finished teleporting Widgets: " << GetChildren() << "\n";
}
void ShowCharacterPortrait(BAK::ActiveCharIndex character) override
{
DoFade(.8, [this, character]{
mInfoScreen.SetSelectedCharacter(character);
mInfoScreen.UpdateCharacter();
mScreenStack.PushScreen(&mInfoScreen);
});
}
void ExitSimpleScreen() override
{
mScreenStack.PopScreen();
}
void ShowInventory(BAK::ActiveCharIndex character) override
{
DoFade(.8, [this, character]{
mCursor.PushCursor(0);
mGuiScreens.push(GuiScreen{[](){}});
mInventoryScreen.SetSelectionMode(false, nullptr);
mInventoryScreen.SetSelectedCharacter(character);
mScreenStack.PushScreen(&mInventoryScreen);
});
}
void ShowContainer(BAK::GenericContainer* container, BAK::EntityType containerType) override
{
mCursor.PushCursor(0);
ASSERT(container);
ASSERT(container->GetInventory().GetCapacity() > 0);
mGuiScreens.push(GuiScreen{[this, container, containerType](){
mLogger.Debug() << "ExitContainer guiScreen hasDiag: " << container->HasDialog() << " et: " << std::to_underlying(containerType) << "\n";
mInventoryScreen.ClearContainer();
if (container->HasDialog())
{
if (containerType == BAK::EntityType::CHEST)
{
StartDialog(container->GetDialog().mDialog, false, false, mDialogScene);
}
}
}});
mInventoryScreen.SetSelectionMode(false, nullptr);
mInventoryScreen.SetContainer(container, containerType);
mLogger.Debug() << __FUNCTION__ << " Pushing inv\n";
mScreenStack.PushScreen(&mInventoryScreen);
}
void SelectItem(std::function<void(std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>>)>&& itemSelected) override
{
mCursor.PushCursor(0);
mGuiScreens.push(GuiScreen{[&, selected=itemSelected]() mutable {
mLogger.Debug() << __FUNCTION__ << " SelectItem\n";
selected(std::nullopt);
}});
mInventoryScreen.SetSelectionMode(true, std::move(itemSelected));
mLogger.Debug() << __FUNCTION__ << " Pushing select item\n";
mScreenStack.PushScreen(&mInventoryScreen);
}
void ExitInventory() override
{
mLogger.Debug() << __FUNCTION__ << " BEGIN" << std::endl;
auto exitInventory = [&]{
mCursor.PopCursor();
mScreenStack.PopScreen();
PopAndRunGuiScreen();
};
if (mGameState.GetTransitionChapter_7541())
{
exitInventory();
mGameState.SetTransitionChapter_7541(false);
DoChapterTransition();
}
else
{
DoFade(1.0, [this, exitInventory]{
exitInventory();
mLogger.Debug() << __FUNCTION__ << " ExitInventory" << std::endl;
});
}
}
void ShowLock(
BAK::IContainer* container,
std::function<void()>&& finished) override
{
ASSERT(container->HasLock()
&& (container->GetLock().IsFairyChest()
|| !container->GetLock().IsTrapped()));
mCursor.PushCursor(0);
if (container->GetLock().IsFairyChest())
{
mMoredhelScreen.SetContainer(container);
mScreenStack.PushScreen(&mMoredhelScreen);
AudioA::AudioManager::Get().ChangeMusicTrack(AudioA::PUZZLE_CHEST_THEME);
mGuiScreens.push(GuiScreen{
[fin = std::move(finished)](){
AudioA::AudioManager::Get().PopTrack();
std::invoke(fin);
}});
}
else
{
mLockScreen.SetContainer(container);
mScreenStack.PushScreen(&mLockScreen);
mGuiScreens.push(finished);
}
}
void ShowCamp(bool isInn, BAK::ShopStats* inn) override
{
assert(!isInn || inn);
mGuiScreens.push(GuiScreen{[this]{
mCursor.PopCursor();
}});
DoFade(.8, [this, isInn, inn]{
mScreenStack.PushScreen(&mCampScreen);
mCursor.PushCursor(0);
mCampScreen.BeginCamp(isInn, inn);
});
}
void ShowCast(bool inCombat) override
{
mGuiScreens.push(GuiScreen{[this]{
mCursor.PopCursor();
}});
DoFade(.8, [this, inCombat]{
mScreenStack.PushScreen(&mCastScreen);
mCursor.PushCursor(0);
mCastScreen.BeginCast(inCombat);
});
}
void ShowFullMap() override
{
mFullMap.UpdateLocation();
mFullMap.DisplayMapMode();
DoFade(1.0, [this]{
mScreenStack.PushScreen(&mFullMap);
});
}
void ShowGameStartMap() override
{
DoFade(1.0, [this]{
mScreenStack.PopScreen();
mFullMap.DisplayGameStartMode(mGameState.GetChapter(), mGameState.GetMapLocation());
mScreenStack.PushScreen(&mFullMap);
});
}
void ShowCureScreen(
unsigned templeNumber,
unsigned cureFactor,
std::function<void()>&& finished) override
{
DoFade(.8, [this, templeNumber, cureFactor, finished=std::move(finished)]() mutable {
mCureScreen.EnterScreen(templeNumber, cureFactor, std::move(finished));
mScreenStack.PushScreen(&mCureScreen);
});
}
void ShowTeleport(unsigned sourceTemple, BAK::ShopStats* temple) override
{
mTeleportScreen.SetSourceTemple(sourceTemple, temple);
DoFade(.8, [this]{
mCursor.PopCursor();
mScreenStack.PushScreen(&mTeleportScreen);
});
}
void ExitLock() override
{
mCursor.PopCursor();
mScreenStack.PopScreen();
PopAndRunGuiScreen();
}
bool IsLockOpened() const override
{
return mLockScreen.IsUnlocked();
}
bool IsWordLockOpened() const override
{
return mMoredhelScreen.IsUnlocked();
}
void PopGuiScreen()
{
mGuiScreens.pop();
}
void PopAndRunGuiScreen()
{
// Avoids reentrancy issue by ensuring this gui screen is not
// in the stack when it is executed.
auto guiScreen = mGuiScreens.top();
mGuiScreens.pop();
guiScreen.mFinished();
}
private:
void FadeInDone()
{
mLogger.Spam() << "FadeInDone\n";
ASSERT(!mFadeFunction.empty());
unsigned i = 0;
while (!mFadeFunction.empty())
{
mLogger.Spam() << "Executing fade function #" << i++ << "\n";
auto function = std::move(mFadeFunction.front());
mFadeFunction.erase(mFadeFunction.begin());
function();
}
mFadeScreen.FadeOut();
}
void FadeOutDone()
{
RemoveChild(&mFadeScreen);
if (mEndFadeFunction)
{
mEndFadeFunction();
mEndFadeFunction = nullptr;
}
}
FontManager mFontManager;
Actors mActors;
Backgrounds mBackgrounds;
Icons mIcons;
Cursor& mCursor;
BAK::GameState& mGameState;
ScreenStack mScreenStack;
DialogRunner mDialogRunner;
Graphics::SpriteManager& mSpriteManager;
CutscenePlayer mCutscenePlayer;
public:
MainView mMainView;
private:
MainMenuScreen mMainMenu;
InfoScreen mInfoScreen;
InventoryScreen mInventoryScreen;
Camp::CampScreen mCampScreen;
Cast::CastScreen mCastScreen;
CureScreen mCureScreen;
LockScreen mLockScreen;
public:
FullMap mFullMap;
private:
MoredhelScreen mMoredhelScreen;
TeleportScreen mTeleportScreen;
FadeScreen mFadeScreen;
std::vector<std::function<void()>> mFadeFunction;
std::function<void()> mEndFadeFunction;
std::function<void()> mCutsceneFinished;
std::function<void()> mOnEnterMainView;
std::vector<std::unique_ptr<GDSScene>> mGdsScenes;
IDialogScene* mDialogScene;
std::stack<GuiScreen> mGuiScreens;
AnimatorStore mAnimatorStore;
BAK::IZoneLoader* mZoneLoader;
Widget* mPreviousScreen{nullptr};
BAK::Encounter::TeleportFactory mTeleportFactory{};
const Logging::Logger& mLogger;
};
}
| 21,784
|
C++
|
.h
| 674
| 23.155786
| 149
| 0.588294
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,621
|
repair.hpp
|
xavieran_BaKGL/gui/repair.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/hotspot.hpp"
#include "bak/dialogSources.hpp"
#include "bak/money.hpp"
#include "bak/shop.hpp"
#include "bak/textureFactory.hpp"
#include "graphics/sprites.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/dialogDisplay.hpp"
#include "gui/hotspot.hpp"
#include "gui/staticTTM.hpp"
#include "gui/core/widget.hpp"
namespace Gui {
class Repair : public IDialogScene
{
enum class State
{
Idle,
Repairing
};
public:
Repair(
BAK::GameState& gameState,
IGuiManager& guiManager)
:
mState{State::Idle},
mGameState{gameState},
mGuiManager{guiManager},
mItem{nullptr},
mShopStats{nullptr},
mLogger{Logging::LogState::GetLogger("Gui::Repair")}
{}
Repair(const Repair&) = delete;
Repair& operator=(const Repair&) = delete;
void EnterRepair(
BAK::ShopStats& shopStats)
{
mShopStats = &shopStats;
mState = State::Idle;
mGuiManager.SelectItem(
[this](auto item){ HandleItemSelected(item); });
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice) override
{
mLogger.Info() << " Choice: " << choice << "\n";
if (mState == State::Idle)
{
}
else if (mState == State::Repairing)
{
mState = State::Idle;
ASSERT(mItem);
ASSERT(mShopStats);
const auto cost = BAK::Shop::CalculateRepairCost(*mItem, *mShopStats);
if (choice && *choice == BAK::ChoiceIndex{260}
&& mGameState.GetParty().GetGold().mValue > cost.mValue)
{
mGameState.GetParty().LoseMoney(cost);
BAK::Shop::RepairItem(*mItem);
}
}
}
void DisplayNPCBackground() override { }
void DisplayPlayerBackground() override { }
private:
void StartDialog(BAK::KeyTarget keyTarget)
{
mGuiManager.StartDialog(keyTarget, false, false, this);
}
void HandleItemSelected(std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>> selectedItem)
{
ASSERT(mShopStats);
if (!selectedItem)
{
mState = State::Idle;
return;
}
const auto [charIndex, itemIndex] = *selectedItem;
auto& character = mGameState.GetParty().GetCharacter(charIndex);
auto& item = character.GetInventory().GetAtIndex(itemIndex);
mItem = &item;
mGameState.SetActiveCharacter(character.GetIndex());
mGameState.SetInventoryItem(item);
if (!BAK::Shop::CanRepair(item, *mShopStats))
{
StartDialog(BAK::DialogSources::mRepairShopCantRepairItem);
}
else if (!item.IsRepairableByShop() && !item.IsBroken())
{
StartDialog(BAK::DialogSources::mRepairShopItemDoesntNeedRepair);
}
else
{
mState = State::Repairing;
mGameState.SetItemValue(BAK::Shop::CalculateRepairCost(item, *mShopStats));
StartDialog(BAK::DialogSources::mRepairShopCost);
}
}
State mState;
BAK::GameState& mGameState;
IGuiManager& mGuiManager;
BAK::InventoryItem* mItem;
BAK::ShopStats* mShopStats;
const Logging::Logger& mLogger;
};
}
| 3,387
|
C++
|
.h
| 108
| 23.916667
| 109
| 0.6235
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,622
|
window.hpp
|
xavieran_BaKGL/gui/window.hpp
|
#pragma once
#include "gui/core/widget.hpp"
#include "gui/cursor.hpp"
#include "gui/colors.hpp"
#include "com/visit.hpp"
namespace Gui {
class Window : public Widget
{
public:
Window(
Graphics::SpriteManager& spriteManager,
float width,
float height)
:
Widget{
RectTag{},
glm::vec2{0},
glm::vec2{width, height},
glm::vec4{0},
true},
mCursor{spriteManager}
{
AddChildBack(&mCursor);
}
bool OnMouseEvent(const MouseEvent& event) override
{
Logging::LogSpam("Window") << __FUNCTION__ << " " << event << "\n";
return std::visit(overloaded{
[this](const MouseMove& p){
mCursor.SetPosition(p.mValue);
return Widget::OnMouseEvent(p);
},
[this](const auto& p){
return Widget::OnMouseEvent(p);
}},
event);
}
void ShowCursor()
{
AddChildBack(&mCursor);
}
void HideCursor()
{
RemoveChild(&mCursor);
}
Cursor& GetCursor()
{
return mCursor;
}
private:
Cursor mCursor;
};
}
| 1,194
|
C++
|
.h
| 53
| 15.226415
| 75
| 0.538462
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,623
|
icons.hpp
|
xavieran_BaKGL/gui/icons.hpp
|
#pragma once
#include "bak/textureFactory.hpp"
#include "com/assert.hpp"
#include "graphics/texture.hpp"
#include "graphics/sprites.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <tuple>
#include <variant>
namespace Gui {
class Icons
{
public:
using IconInfo = std::tuple<
Graphics::SpriteSheetIndex,
Graphics::TextureIndex,
glm::vec2>;
static constexpr auto sInventoryModsOffset = 132;
Icons(
Graphics::SpriteManager& spriteManager)
:
mButtonIconsSpriteSheet{spriteManager.AddSpriteSheet()},
mInventoryIconsSpriteSheet{spriteManager.AddSpriteSheet()},
mLogger{Logging::LogState::GetLogger("Gui::Icons")}
{
{
auto textures = Graphics::TextureStore{};
BAK::TextureFactory::AddToTextureStore(
textures, "BICONS1.BMX", "OPTIONS.PAL");
mPressedOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "BICONS2.BMX", "OPTIONS.PAL");
for (const auto& t : textures.GetTextures())
{
mButtonIconsDims.emplace_back(t.GetDims());
}
auto& spriteSheet = spriteManager.GetSpriteSheet(mButtonIconsSpriteSheet);
spriteSheet.LoadTexturesGL(textures);
}
{
auto textures = Graphics::TextureStore{};
BAK::TextureFactory::AddToTextureStore(
textures, "INVSHP1.BMX", "OPTIONS.PAL");
BAK::TextureFactory::AddToTextureStore(
textures, "INVSHP2.BMX", "OPTIONS.PAL");
mHeadsOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "HEADS.BMX", "OPTIONS.PAL");
mCompassOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "COMPASS.BMX", "OPTIONS.PAL");
mInventoryMiscOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "INVMISC.BMX", "OPTIONS.PAL");
mInventoryLockOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "INVLOCK.BMX", "OPTIONS.PAL");
mFullMapIconOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "FMAP_ICN.BMX", "FULLMAP.PAL");
mTeleportIconOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "TELEPORT.BMX", "TELEPORT.PAL");
mEncampIconOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "ENCAMP.BMX", "OPTIONS.PAL");
mCastIconOffset = textures.size();
BAK::TextureFactory::AddToTextureStore(
textures, "CASTFACE.BMX", "OPTIONS.PAL");
for (const auto& t : textures.GetTextures())
{
mInventoryIconsDims.emplace_back(t.GetDims());
}
auto& spriteSheet = spriteManager.GetSpriteSheet(mInventoryIconsSpriteSheet);
spriteSheet.LoadTexturesGL(textures);
}
}
IconInfo GetButton(unsigned i) const
{
ASSERT(i < mButtonIconsDims.size());
return std::make_tuple(
mButtonIconsSpriteSheet,
Graphics::TextureIndex{i},
mButtonIconsDims[i]);
}
IconInfo GetPressedButton(unsigned i) const
{
const auto index = i + mPressedOffset;
ASSERT(index < mButtonIconsDims.size());
return std::make_tuple(
mButtonIconsSpriteSheet,
Graphics::TextureIndex{index},
mButtonIconsDims[index]);
}
IconInfo GetInventoryIcon(unsigned i) const
{
ASSERT(i < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{i},
mInventoryIconsDims[i]);
}
IconInfo GetStippledBorderHorizontal() const
{
return GetInventoryIcon(145);
}
IconInfo GetStippledBorderVertical() const
{
return GetInventoryIcon(146);
}
IconInfo GetCharacterHead(unsigned i) const
{
const auto index = i + mHeadsOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
IconInfo GetCompass() const
{
const auto index = mCompassOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
IconInfo GetInventoryMiscIcon(unsigned i) const
{
const auto index = i + mInventoryMiscOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
IconInfo GetInventoryModifierIcon(unsigned i) const
{
const auto index = i + sInventoryModsOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
IconInfo GetInventoryLockIcon(unsigned i) const
{
const auto index = i + mInventoryLockOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
IconInfo GetFullMapIcon(unsigned i) const
{
const auto index = i + mFullMapIconOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
IconInfo GetTeleportIcon(unsigned i) const
{
const auto index = i + mTeleportIconOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
IconInfo GetEncampIcon(unsigned i) const
{
const auto index = i + mEncampIconOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
IconInfo GetCastIcon(unsigned i) const
{
const auto index = i + mCastIconOffset;
ASSERT(index < mInventoryIconsDims.size());
return std::make_tuple(
mInventoryIconsSpriteSheet,
Graphics::TextureIndex{index},
mInventoryIconsDims[index]);
}
std::size_t GetSize() const
{
return mInventoryIconsDims.size();
}
private:
Graphics::SpriteSheetIndex mButtonIconsSpriteSheet;
unsigned mPressedOffset;
std::vector<glm::vec2> mButtonIconsDims;
Graphics::SpriteSheetIndex mInventoryIconsSpriteSheet;
unsigned mHeadsOffset;
unsigned mCompassOffset;
unsigned mInventoryMiscOffset;
unsigned mInventoryLockOffset;
unsigned mFullMapIconOffset;
unsigned mTeleportIconOffset;
unsigned mEncampIconOffset;
unsigned mCastIconOffset;
std::vector<glm::vec2> mInventoryIconsDims;
const Logging::Logger& mLogger;
};
}
| 7,716
|
C++
|
.h
| 213
| 27.046948
| 89
| 0.636047
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,624
|
tickAnimator.hpp
|
xavieran_BaKGL/gui/tickAnimator.hpp
|
#pragma once
#include "gui/IAnimator.hpp"
#include <functional>
namespace Gui {
// Calls the callback every "tickSpeed" seconds, until stopped.
class TickAnimator : public IAnimator
{
public:
TickAnimator(
double tickSpeed,
std::function<void()>&& callback)
:
mTickSpeed{tickSpeed},
mAccumulatedTimeDelta{0},
mAlive{true},
mCallback{std::move(callback)}
{
}
void OnTimeDelta(double delta) override
{
mAccumulatedTimeDelta += delta;
if (mAccumulatedTimeDelta > mTickSpeed && mAlive)
{
mAccumulatedTimeDelta = 0;
mCallback();
}
}
bool IsAlive() const override
{
return mAlive;
}
void Stop()
{
mAlive = false;
}
private:
double mTickSpeed;
double mAccumulatedTimeDelta;
bool mAlive;
std::function<void()> mCallback;
};
}
| 915
|
C++
|
.h
| 42
| 16.095238
| 63
| 0.627315
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,625
|
IDialogScene.hpp
|
xavieran_BaKGL/gui/IDialogScene.hpp
|
#pragma once
#include "bak/types.hpp"
#include <functional>
#include <optional>
namespace Gui {
// Interface for a DialogScene
// This should be implemented by GDSScenes and the 3d adventure view
class IDialogScene
{
public:
virtual void DisplayNPCBackground() = 0;
virtual void DisplayPlayerBackground() = 0;
virtual void DialogFinished(const std::optional<BAK::ChoiceIndex>&) = 0;
};
class NullDialogScene : public IDialogScene
{
public:
void DisplayNPCBackground() override {}
void DisplayPlayerBackground() override {}
void DialogFinished(const std::optional<BAK::ChoiceIndex>&) override {}
};
class DynamicDialogScene : public IDialogScene
{
public:
DynamicDialogScene(
std::function<void()>&& displayNPC,
std::function<void()>&& displayPlayer,
std::function<void(const std::optional<BAK::ChoiceIndex>&)>&& dialogFinished)
:
mDisplayNPC{displayNPC},
mDisplayPlayer{displayPlayer},
mDialogFinished{dialogFinished}
{}
void DisplayNPCBackground() override { mDisplayNPC(); }
void DisplayPlayerBackground() override { mDisplayPlayer(); }
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice) override { mDialogFinished(choice); }
void SetDialogFinished(std::function<void(const std::optional<BAK::ChoiceIndex>&)>&& fn)
{
mDialogFinished = std::move(fn);
}
void ResetDialogFinished()
{
mDialogFinished = [](const auto&){};
}
private:
std::function<void()> mDisplayNPC;
std::function<void()> mDisplayPlayer;
std::function<void(const std::optional<BAK::ChoiceIndex>&)> mDialogFinished;
};
}
| 1,661
|
C++
|
.h
| 50
| 29.04
| 108
| 0.72125
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,626
|
mainMenuScreen.hpp
|
xavieran_BaKGL/gui/mainMenuScreen.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/IContainer.hpp"
#include "bak/textureFactory.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/contents.hpp"
#include "gui/preferencesScreen.hpp"
#include "gui/saveScreen.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
class MainMenuScreen: public Widget
{
public:
static constexpr auto sMainMenuSong = AudioA::MusicIndex{1015};
static constexpr auto sLayoutFile = "REQ_OPT0.DAT";
static constexpr auto sLayoutFileGameRunning = "REQ_OPT1.DAT";
static constexpr auto sBackground = "OPTIONS0.SCX";
static constexpr auto sBackgroundGameRunning = "OPTIONS1.SCX";
static constexpr auto sStartNew = 0;
static constexpr auto sRestore = 1;
static constexpr auto sSaveGame= 2;
static constexpr auto sPreferences = 3;
static constexpr auto sContents = 4;
static constexpr auto sQuit = 5;
static constexpr auto sCancel = 6;
MainMenuScreen(
IGuiManager& guiManager,
Graphics::SpriteManager& spriteManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font)
:
Widget{
RectTag{},
glm::vec2{0, 0},
glm::vec2{320, 200},
Color::black,
false
},
mGuiManager{guiManager},
mFont{font},
mBackgrounds{backgrounds},
mLayout{sLayoutFile},
mLayoutGameRunning{sLayoutFileGameRunning},
mFrame{
ImageTag{},
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sBackground),
glm::vec2{0},
GetPositionInfo().mDimensions,
true
},
mStartNew{
mLayout.GetWidgetLocation(sStartNew),
mLayout.GetWidgetDimensions(sStartNew),
mFont,
"#Start New Game",
[this]{ StartNewGame(); }
},
mRestore{
mLayout.GetWidgetLocation(sRestore),
mLayout.GetWidgetDimensions(sRestore),
mFont,
"#Restore Game",
[this]{ ShowSaveOrLoad(false); }
},
mSaveGame{
mLayoutGameRunning.GetWidgetLocation(sSaveGame),
mLayoutGameRunning.GetWidgetDimensions(sSaveGame),
mFont,
"#Save Game",
[this]{ ShowSaveOrLoad(true); }
},
mPreferences{
mLayout.GetWidgetLocation(sPreferences),
mLayout.GetWidgetDimensions(sPreferences),
mFont,
"#Preferences",
[this]{ ShowPreferences(); }
},
mContents{
mLayout.GetWidgetLocation(sContents),
mLayout.GetWidgetDimensions(sContents),
mFont,
"#Contents",
[this]{ ShowContents(); }
},
mQuit{
mLayout.GetWidgetLocation(sQuit),
mLayout.GetWidgetDimensions(sQuit),
mFont,
"#Quit to DOS",
[this]{
mGuiManager.DoFade(
1.0,
[]{ std::exit(0); });
}
},
mCancel{
mLayoutGameRunning.GetWidgetLocation(sCancel),
mLayoutGameRunning.GetWidgetDimensions(sCancel),
mFont,
"#Cancel",
[this]{ EnterMainView(); }
},
mPreferencesScreen{
guiManager,
backgrounds,
font,
[this]{ BackToMainMenu(); }
},
mContentsScreen{
guiManager,
spriteManager,
backgrounds,
font,
[this]{ BackToMainMenu(); }
},
mSaveScreen{
backgrounds,
icons,
font,
[this]{ BackToMainMenu(); },
[this](const auto& file){
Load(file);
},
[this](const auto& saveFile){
mState = State::MainMenu;
AudioA::AudioManager::Get().PopTrack();
mGuiManager.SaveGame(saveFile);
}
},
mState{State::MainMenu},
mGameRunning{false},
mLogger{Logging::LogState::GetLogger("Gui::MainMenuScreen")}
{
}
void EnterMainMenu(bool gameRunning)
{
mGameRunning = gameRunning;
AddChildren();
AudioA::AudioManager::Get().ChangeMusicTrack(sMainMenuSong);
}
[[nodiscard]] bool OnMouseEvent(const MouseEvent& event) override
{
return Widget::OnMouseEvent(event) || true;
}
private:
enum class State
{
MainMenu,
Preferences,
Save,
Contents
};
void ShowPreferences()
{
mGuiManager.DoFade(1.0, [this]{
mState = State::Preferences;
AddChildren();
});
}
void ShowContents()
{
mGuiManager.DoFade(1.0, [this]{
mState = State::Contents;
AddChildren();
});
}
void ShowSaveOrLoad(bool isSave)
{
mGuiManager.DoFade(1.0, [this, isSave]{
mState = State::Save;
mSaveScreen.SetSaveOrLoad(isSave);
AddChildren();
});
}
void BackToMainMenu()
{
mGuiManager.DoFade(1.0, [this]{
mState = State::MainMenu;
AddChildren();
});
}
void EnterMainView()
{
AudioA::AudioManager::Get().PopTrack();
mGuiManager.EnterMainView();
}
void StartNewGame()
{
AudioA::AudioManager::Get().PopTrack();
auto start = BAK::CutsceneList::GetStartScene(BAK::Chapter{1});
mGuiManager.PlayCutscene(start , [&]{
mGuiManager.ShowGameStartMap();
});
mGuiManager.LoadGame("startup.gam", std::make_optional(BAK::Chapter{1}));
}
void Load(std::string file)
{
mState = State::MainMenu;
AudioA::AudioManager::Get().PopTrack();
mGuiManager.LoadGame(file, std::nullopt);
mGuiManager.ShowGameStartMap();
}
void AddChildren()
{
ClearChildren();
switch (mState)
{
case State::MainMenu:
AddMainMenu();
break;
case State::Preferences:
AddPreferences();
break;
case State::Contents:
AddContents();
break;
case State::Save:
AddSave();
break;
}
}
void AddMainMenu()
{
AddChildBack(&mFrame);
if (mGameRunning)
{
mFrame.SetTexture(mBackgrounds.GetScreen(sBackgroundGameRunning));
mStartNew.SetPosition(mLayoutGameRunning.GetWidgetLocation(sStartNew));
mRestore.SetPosition(mLayoutGameRunning.GetWidgetLocation(sRestore));
mPreferences.SetPosition(mLayoutGameRunning.GetWidgetLocation(sPreferences));
mContents.SetPosition(mLayoutGameRunning.GetWidgetLocation(sContents));
mQuit.SetPosition(mLayoutGameRunning.GetWidgetLocation(sQuit));
AddChildBack(&mSaveGame);
AddChildBack(&mCancel);
}
else
{
mFrame.SetTexture(mBackgrounds.GetScreen(sBackground));
mStartNew.SetPosition(mLayout.GetWidgetLocation(sStartNew));
mRestore.SetPosition(mLayout.GetWidgetLocation(sRestore));
mPreferences.SetPosition(mLayout.GetWidgetLocation(sPreferences));
mContents.SetPosition(mLayout.GetWidgetLocation(sContents));
mQuit.SetPosition(mLayout.GetWidgetLocation(sQuit));
}
AddChildBack(&mStartNew);
AddChildBack(&mRestore);
AddChildBack(&mPreferences);
AddChildBack(&mContents);
AddChildBack(&mQuit);
}
void AddPreferences()
{
AddChildBack(&mPreferencesScreen);
}
void AddContents()
{
AddChildBack(&mContentsScreen);
}
void AddSave()
{
AddChildBack(&mSaveScreen);
}
IGuiManager& mGuiManager;
const Font& mFont;
const Backgrounds& mBackgrounds;
BAK::Layout mLayout;
BAK::Layout mLayoutGameRunning;
Widget mFrame;
ClickButton mStartNew;
ClickButton mRestore;
ClickButton mSaveGame;
ClickButton mPreferences;
ClickButton mContents;
ClickButton mQuit;
ClickButton mCancel;
PreferencesScreen mPreferencesScreen;
ContentsScreen mContentsScreen;
SaveScreen mSaveScreen;
State mState;
bool mGameRunning;
const Logging::Logger& mLogger;
};
}
| 8,745
|
C++
|
.h
| 292
| 20.804795
| 89
| 0.588899
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,627
|
animator.hpp
|
xavieran_BaKGL/gui/animator.hpp
|
#pragma once
#include "gui/IAnimator.hpp"
#include "com/assert.hpp"
#include "com/logger.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class LinearAnimator : public IAnimator
{
public:
// every 10ms
static constexpr auto mTickFrequency = .01;
LinearAnimator(
double duration,
glm::vec4 begin,
glm::vec4 end,
std::function<bool(glm::vec4)>&& callback,
std::function<void()>&& finished)
:
mAlive{true},
mAccumulatedTimeDelta{0},
mDuration{duration},
mTrueDuration{duration},
mDelta{(end - begin)},
mCallback{std::move(callback)},
mFinished{std::move(finished)}
{
ASSERT(mCallback);
ASSERT(mFinished);
}
~LinearAnimator()
{
}
void OnTimeDelta(double delta) override
{
mAccumulatedTimeDelta += delta;
mDuration -= delta;
bool finishEarly = false;
if (mAccumulatedTimeDelta > mTickFrequency)
{
mAccumulatedTimeDelta -= mTickFrequency;
finishEarly = mCallback(mDelta * static_cast<float>(delta / mTrueDuration));//mDelta);
}
if (finishEarly || mDuration < 0)
{
mAlive = false;
mFinished();
}
}
bool IsAlive() const override { return mAlive; }
private:
bool mAlive;
double mAccumulatedTimeDelta;
double mDuration;
double mTrueDuration;
glm::vec4 mDelta;
std::function<bool(glm::vec4)> mCallback;
std::function<void()> mFinished;
};
}
| 1,630
|
C++
|
.h
| 63
| 19.698413
| 98
| 0.628461
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,628
|
button.hpp
|
xavieran_BaKGL/gui/button.hpp
|
#pragma once
#include "gui/core/widget.hpp"
#include "gui/colors.hpp"
namespace Gui {
class Button : public Widget
{
public:
Button(
glm::vec2 pos,
glm::vec2 dim,
glm::vec4 mainColor,
glm::vec4 highlight,
glm::vec4 shadow,
glm::vec4 dropShadow=Color::black)
:
// Bottom left edge
Widget{
RectTag{},
pos,
dim,
shadow,
true
},
mTopRightEdge{
RectTag{},
glm::vec2{1, 0},
dim - glm::vec2{1, 1},
highlight,
true
},
mCenter{
RectTag{},
glm::vec2{1, 1},
dim - glm::vec2{2, 2},
mainColor,
true
}
{
// Top Right edge
AddChildBack(&mTopRightEdge);
AddChildBack(&mCenter);
}
void SetDimensions(glm::vec2 dims) override
{
Widget::SetDimensions(dims);
mTopRightEdge.SetDimensions(dims - glm::vec2{1});
mCenter.SetDimensions(dims - glm::vec2{2});
}
Widget mTopRightEdge;
Widget mCenter;
};
}
| 1,153
|
C++
|
.h
| 52
| 13.961538
| 57
| 0.505484
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,629
|
dialogRunner.hpp
|
xavieran_BaKGL/gui/dialogRunner.hpp
|
#pragma once
#include "bak/dialog.hpp"
#include "bak/gameState.hpp"
#include "bak/types.hpp"
#include "com/algorithm.hpp"
#include "com/assert.hpp"
#include "com/ostream.hpp"
#include "com/random.hpp"
#include "com/visit.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/actors.hpp"
#include "gui/backgrounds.hpp"
#include "gui/colors.hpp"
#include "gui/choiceScreen.hpp"
#include "gui/dialogDisplay.hpp"
#include "gui/label.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <regex>
#include <stack>
#include <variant>
namespace Gui {
class DialogRunner : public Widget
{
public:
using FinishCallback = std::function<
void(std::optional<BAK::ChoiceIndex>)>;
DialogRunner(
glm::vec2 pos,
glm::vec2 dims,
const Actors& actors,
const Backgrounds& bgs,
const Font& fr,
BAK::GameState& gameState,
ScreenStack& screenStack,
FinishCallback&& finished);
~DialogRunner();
const std::optional<BAK::ChoiceIndex>& GetLastChoice() const { return mLastChoice; }
std::optional<BAK::TeleportIndex> GetAndResetPendingTeleport();
void SetDialogScene(IDialogScene* dialogScene);
void SetInWorldView(bool);
void BeginDialog(
BAK::Target target,
bool isTooltip);
bool OnMouseEvent(const MouseEvent& event) override;
private:
bool IsActive();
bool LeftMousePressed(glm::vec2);
bool MouseMoved(glm::vec2 pos);
void EvaluateSnippetActions();
void DisplaySnippet();
const BAK::DialogSnippet& GetSnippet() const;
std::optional<BAK::Target> GetNextTarget();
void MakeChoice(BAK::ChoiceIndex choice);
void ShowDialogChoices();
void ShowQueryChoices();
void ContinueDialogFromStack();
bool RunDialog();
void CompleteDialog();
BAK::Target GetAndPopTargetStack();
struct DialogState
{
void ActivateDialog()
{
mDialogActive = true;
}
void MouseMoved(glm::vec2 pos)
{
mMousePos = pos;
}
void ActivateTooltip()
{
mTooltipPos = mMousePos;
mTooltipActive = true;
}
void DeactivateDialog()
{
mDialogActive = false;
}
template <typename F>
void ForceDeactivateTooltip(F&& f)
{
ASSERT(mTooltipActive);
f();
mTooltipActive = false;
}
template <typename F>
void DeactivateTooltip(F&& f)
{
constexpr auto tooltipSensitivity = 15;
if (mTooltipActive
&& glm::distance(mMousePos, mTooltipPos) > tooltipSensitivity)
{
f();
mTooltipActive = false;
}
}
bool mDialogActive{};
bool mTooltipActive{};
glm::vec2 mMousePos{};
glm::vec2 mTooltipPos{};
};
ScreenStack& mScreenStack;
DialogState mDialogState;
ChoiceScreen mChoices;
BAK::Keywords mKeywords;
BAK::GameState& mGameState;
glm::vec2 mCenter{};
const Font& mFont;
const Actors& mActors;
std::optional<BAK::Target> mCurrentTarget{};
std::optional<BAK::ChoiceIndex> mLastChoice{};
std::optional<BAK::TeleportIndex> mPendingZoneTeleport{};
std::stack<BAK::Target> mTargetStack{};
bool mStartedMusic{};
bool mInWorldView{};
std::string mRemainingText{};
glm::vec2 mTextDims{};
DialogDisplay mDialogDisplay;
FinishCallback mFinished;
IDialogScene* mDialogScene;
const Logging::Logger& mLogger;
};
}
| 3,619
|
C++
|
.h
| 124
| 22.572581
| 88
| 0.649884
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,630
|
bookPlayer.hpp
|
xavieran_BaKGL/gui/bookPlayer.hpp
|
#pragma once
#include "bak/book.hpp"
#include "com/logger.hpp"
#include "graphics/guiTypes.hpp"
#include "graphics/sprites.hpp"
#include "gui/animatorStore.hpp"
#include "gui/scene.hpp"
#include "gui/dialogDisplay.hpp"
#include "gui/core/widget.hpp"
#include "gui/textBox.hpp"
namespace Gui {
class BookPlayer
{
public:
BookPlayer(
Graphics::SpriteManager& spriteManager,
const Font& font,
const Backgrounds& background,
std::function<void()> finishedBook);
void PlayBook(std::string);
void AdvancePage();
Widget* GetBackground();
private:
void RenderPage(const BAK::Page&);
Graphics::SpriteManager& mSpriteManager;
Graphics::SpriteManager::TemporarySpriteSheet mSpriteSheet;
const Font& mFont;
Graphics::TextureStore mTextures;
Widget mBackground;
TextBox mTextBox;
std::vector<Widget> mImages;
std::optional<BAK::Book> mBook{};
unsigned mCurrentPage{};
std::string mText{};
std::function<void()> mFinishedBook{};
};
}
| 1,034
|
C++
|
.h
| 37
| 23.864865
| 63
| 0.726251
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,631
|
IDialogDisplay.hpp
|
xavieran_BaKGL/gui/IDialogDisplay.hpp
|
#pragma once
#include "bak/dialog.hpp"
#include "gui/IDialogScene.hpp"
#include "graphics/glm.hpp"
namespace Gui {
class IDialogDisplay
{
virtual void DisplayPlayer(IDialogScene& dialogScene, unsigned act) = 0;
virtual std::pair<glm::vec2, std::string> DisplaySnippet(
IDialogScene& dialogScene,
const BAK::DialogSnippet& snippet,
std::string_view remainingText,
bool inMainView,
glm::vec2) = 0;
virtual void ShowFlavourText(BAK::Target target) = 0;
virtual void Clear() = 0;
};
}
| 606
|
C++
|
.h
| 18
| 29.222222
| 76
| 0.630584
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,632
|
textInput.hpp
|
xavieran_BaKGL/gui/textInput.hpp
|
#pragma once
#include "graphics/glfw.hpp"
#include "gui/button.hpp"
#include "gui/core/widget.hpp"
#include "gui/colors.hpp"
#include "gui/fontManager.hpp"
#include "gui/textBox.hpp"
#include "com/logger.hpp"
#include "com/visit.hpp"
namespace Gui {
class TextInput : public Widget
{
public:
TextInput(
const Font& font,
glm::vec2 pos,
glm::vec2 dim,
unsigned maxChars)
:
Widget{
RectTag{},
pos,
dim,
glm::vec4{0},
true
},
mFont{font},
mButton{glm::vec2{}, dim, Color::buttonBackground, Color::buttonShadow, Color::buttonShadow},
mHighlight{RectTag{}, glm::vec2{2}, glm::vec2{3, dim.y - 4}, {}, true},
mTextBox{glm::vec2{2}, dim - glm::vec2{2}},
mText{},
mMaxChars{maxChars},
mHaveFocus{false}
{
AddChildBack(&mButton);
AddChildBack(&mHighlight);
AddChildBack(&mTextBox);
}
bool OnMouseEvent(const MouseEvent& event) override
{
return std::visit(overloaded{
[this](const LeftMousePress& p){ return LeftMousePressed(p.mValue); },
[](const auto&){ return false; }
}, event);
}
bool OnKeyEvent(const KeyEvent& event) override
{
return std::visit(overloaded{
[this](const KeyPress& p){ return KeyPressed(p.mValue); },
[this](const Character& p){ return CharacterEntered(p.mValue); },
[](const auto&){ return false; }
}, event);
}
void SetText(const std::string& text)
{
mText = text;
RefreshText();
}
const std::string& GetText() const
{
return mText;
}
void SetFocus(bool focus)
{
mHaveFocus = focus;
if (!mHaveFocus)
{
mHighlight.SetColor(glm::vec4{0, 0, 0, 0});
}
else
{
mHighlight.SetColor(glm::vec4{0, 0, 0, .2});
}
}
private:
bool LeftMousePressed(const auto& clickPos)
{
if (Within(clickPos))
{
SetFocus(true);
}
else
{
SetFocus(false);
}
return false;
}
bool KeyPressed(int key)
{
if (mHaveFocus)
{
if (key == GLFW_KEY_BACKSPACE)
{
if (mText.size() > 0)
{
mText.pop_back();
RefreshText();
}
return true;
}
}
return false;
}
void RefreshText()
{
const auto [pos, _] = mTextBox.SetText(mFont, mText);
mHighlight.SetPosition(glm::vec2{pos.x - 2, 2});
}
bool CharacterEntered(char character)
{
if (mHaveFocus && mText.size() < mMaxChars)
{
mText += character;
RefreshText();
return true;
}
return false;
}
const Font& mFont;
Button mButton;
Widget mHighlight;
TextBox mTextBox;
std::string mText;
unsigned mMaxChars;
bool mHaveFocus;
};
}
| 3,146
|
C++
|
.h
| 127
| 16.629921
| 101
| 0.528743
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,633
|
scene.hpp
|
xavieran_BaKGL/gui/scene.hpp
|
#pragma once
#include "bak/scene.hpp"
#include "bak/sceneData.hpp"
#include <glm/glm.hpp>
#include <variant>
namespace Gui {
struct EnableClipRegion
{
glm::vec<2, int> mTopLeft;
glm::vec<2, int> mDims;
};
struct DisableClipRegion
{
};
struct SceneSprite
{
unsigned mImage;
glm::vec2 mPosition;
glm::vec2 mScale;
};
struct SceneRect
{
glm::vec4 mColor;
glm::vec2 mPosition;
glm::vec2 mDimensions;
};
using DrawingAction = std::variant<
EnableClipRegion,
DisableClipRegion,
SceneSprite,
SceneRect>;
DrawingAction ConvertSceneAction(const BAK::SceneAction& action);
EnableClipRegion ConvertSceneAction(const BAK::ClipRegion&);
DisableClipRegion ConvertSceneAction(const BAK::DisableClipRegion&);
template <typename T, typename S>
SceneSprite ConvertSceneAction(
const BAK::DrawScreen& action,
const T& textures,
const S& offsets) // make this const
{
const auto sprite = offsets.at(25);
const auto tex = textures.GetTexture(sprite);
//auto scale = glm::vec2{tex.GetWidth(), tex.GetHeight()};
auto scale = action.mDimensions;
return SceneSprite{
sprite,
action.mPosition,
scale};
}
template <typename T, typename S>
SceneSprite ConvertSceneAction(
const BAK::DrawSprite& action,
const T& textures,
const S& offsets) // make this const
{
const auto sprite = action.mSpriteIndex
+ offsets.at(action.mImageSlot);
const auto tex = textures.GetTexture(sprite);
auto x = action.mX;
auto y = action.mY;
auto scale = glm::vec2{tex.GetWidth(), tex.GetHeight()};
if (action.mTargetWidth != 0)
{
scale.x = static_cast<float>(action.mTargetWidth);
scale.y = static_cast<float>(action.mTargetHeight);
}
if (action.mFlippedInY)
{
// Need to shift before flip to ensure sprite stays in same
// relative pos. One way of achieving rotation about the
// centerline of the sprite...
x += scale.x;
scale.x *= -1;
}
return SceneSprite{
sprite,
glm::vec2{x, y},
scale};
}
template <typename T>
SceneSprite ConvertSceneAction(
const BAK::DrawSprite& action,
const T& textures)
{
const auto sprite = static_cast<unsigned>(action.mSpriteIndex);
const auto tex = textures.GetTexture(sprite);
auto x = action.mX;
auto y = action.mY;
auto scale = glm::vec2{tex.GetWidth(), tex.GetHeight()};
if (action.mTargetWidth != 0)
{
scale.x = static_cast<float>(action.mTargetWidth);
scale.y = static_cast<float>(action.mTargetHeight);
}
if (action.mFlippedInY)
{
// Need to shift before flip to ensure sprite stays in same
// relative pos. One way of achieving rotation about the
// centerline of the sprite...
x += scale.x;
scale.x *= -1;
}
return SceneSprite{
sprite,
glm::vec2{x, y},
scale};
}
}
| 2,981
|
C++
|
.h
| 108
| 22.685185
| 68
| 0.670891
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,634
|
screenStack.hpp
|
xavieran_BaKGL/gui/screenStack.hpp
|
#pragma once
#include "gui/colors.hpp"
#include "gui/core/widget.hpp"
#include "com/ostream.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <variant>
namespace Gui {
// Renders all screens in order from bottom to back,
// only passes input to the back screen
class ScreenStack : public Widget
{
public:
ScreenStack()
:
Widget{
Graphics::DrawMode::Rect,
Graphics::SpriteSheetIndex{0},
Graphics::TextureIndex{0},
Graphics::ColorMode::SolidColor,
Color::debug,
glm::vec2{0},
glm::vec2{1},
false
},
mLogger{Logging::LogState::GetLogger("Gui::ScreenStack")}
{
mLogger.Debug() << "Constructed @" << std::hex << this << std::dec << "\n";
}
bool OnMouseEvent(const MouseEvent& event) override
{
if (mChildren.size() > 0)
{
if (mChildren.back()->OnMouseEvent(event))
return true;
}
return false;
}
void PushScreen(Widget* widget)
{
mLogger.Debug() << "Widgets: " << GetChildren() << " Pushed widget " << std::hex << widget << std::dec << "\n";
AddChildBack(widget);
}
void PopScreen()
{
ASSERT(mChildren.size() > 0);
mLogger.Debug() << "Popped widget: " << std::hex << mChildren.back() << std::dec << "\n";
PopChild();
}
Widget* Top() const
{
assert(mChildren.size() > 0);
return mChildren.back();
}
bool HasChildren()
{
return mChildren.size() > 0;
}
private:
const Logging::Logger& mLogger;
};
}
| 1,647
|
C++
|
.h
| 62
| 19.951613
| 119
| 0.565966
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,635
|
mainView.hpp
|
xavieran_BaKGL/gui/mainView.hpp
|
#pragma once
#include "bak/coordinates.hpp"
#include "bak/hotspot.hpp"
#include "bak/layout.hpp"
#include "bak/scene.hpp"
#include "bak/sceneData.hpp"
#include "bak/textureFactory.hpp"
#include "graphics/IGuiElement.hpp"
#include "graphics/texture.hpp"
#include "graphics/sprites.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/colors.hpp"
#include "gui/compass.hpp"
#include "gui/clickButton.hpp"
#include "gui/icons.hpp"
#include "gui/scene.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class MainView : public Widget
{
public:
static constexpr auto sLayoutFile = "REQ_MAIN.DAT";
static constexpr auto sForward = 2;
static constexpr auto sBackward = 1;
static constexpr auto sSnapToRoad = 4;
static constexpr auto sFullMap = 5;
static constexpr auto sCast = 6;
static constexpr auto sBookmark = 7;
static constexpr auto sCamp = 8;
static constexpr auto sMainMenu = 9;
static constexpr auto sCharacterWidgetBegin = 10;
MainView(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& spellFont)
:
Widget{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen("FRAME.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200},
true
},
mGuiManager{guiManager},
mIcons{icons},
mSpellFont{spellFont},
mLayout{sLayoutFile},
mActiveSpells{},
mCompass{
glm::vec2{144,121},
glm::vec2{32,12},
std::get<glm::vec2>(icons.GetCompass())
+ glm::vec2{0, 1},
std::get<Graphics::SpriteSheetIndex>(icons.GetCompass()),
std::get<Graphics::TextureIndex>(icons.GetCompass())
},
mButtons{},
mCharacters{},
mLogger{Logging::LogState::GetLogger("Gui::MainView")}
{
mButtons.reserve(mLayout.GetSize());
for (unsigned i = 0; i < mLayout.GetSize(); i++)
{
const auto& widget = mLayout.GetWidget(i);
switch (widget.mWidget)
{
case 3: //REQ_IMAGEBUTTON
{
const auto& button = icons.GetButton(widget.mImage);
assert(std::get<Graphics::SpriteSheetIndex>(button)
== std::get<Graphics::SpriteSheetIndex>(icons.GetPressedButton(widget.mImage)));
mButtons.emplace_back(
mLayout.GetWidgetLocation(i),
mLayout.GetWidgetDimensions(i),
std::get<Graphics::SpriteSheetIndex>(button),
std::get<Graphics::TextureIndex>(button),
std::get<Graphics::TextureIndex>(icons.GetPressedButton(widget.mImage)),
[this, buttonIndex=i]{ HandleButton(buttonIndex); },
[]{});
mButtons.back().CenterImage(std::get<glm::vec2>(button));
// Not sure why the dims aren't right to begin with for these buttons
if (i == sForward || i == sBackward)
{
mButtons.back().AdjustPosition(
glm::vec2{-mButtons.back().GetDimensions().x / 4 + 1.5, 0});
}
}
break;
default:
mLogger.Info() << "Unhandled: " << i << "\n";
break;
}
}
AddChildren();
}
void SetHeading(BAK::GameHeading heading)
{
mCompass.SetHeading(heading);
}
void HandleButton(unsigned buttonIndex)
{
switch (buttonIndex)
{
case sCast:
mGuiManager.ShowCast(false);
break;
case sCamp:
mGuiManager.ShowCamp(false, nullptr);
break;
case sFullMap:
mGuiManager.ShowFullMap();
break;
case sBookmark:
break;
case sMainMenu:
mGuiManager.EnterMainMenu(true);
break;
default:
break;
}
}
void UpdatePartyMembers(const BAK::GameState& gameState)
{
ClearChildren();
mCharacters.clear();
mCharacters.reserve(3);
const auto& party = gameState.GetParty();
mLogger.Spam() << "Updating Party: " << party<< "\n";
BAK::ActiveCharIndex person{0};
do
{
const auto [spriteSheet, image, dimss] = mIcons.GetCharacterHead(
party.GetCharacter(person).GetIndex().mValue);
mCharacters.emplace_back(
mLayout.GetWidgetLocation(person.mValue + sCharacterWidgetBegin),
mLayout.GetWidgetDimensions(person.mValue + sCharacterWidgetBegin),
spriteSheet,
image,
image,
[this, character=person]{
ShowInventory(character);
},
[this, character=person]{
ShowPortrait(character);
}
);
person = party.NextActiveCharacter(person);
} while (person != BAK::ActiveCharIndex{0});
auto pos = glm::vec2{140, 1};
// FIXME: Update these whenever time changes...
mActiveSpells.clear();
for (std::uint16_t i = 0; i < 6; i++)
{
if (gameState.GetSpellActive(BAK::StaticSpells{i}))
{
auto spellI = BAK::sStaticSpellMapping[i];
mActiveSpells.emplace_back(Gui::Widget{
Graphics::DrawMode::Sprite,
mSpellFont.GetSpriteSheet(),
static_cast<Graphics::TextureIndex>(
mSpellFont.GetFont().GetIndex(spellI)),
Graphics::ColorMode::Texture,
glm::vec4{1.2f, 0.f, 0.f, 1.f},
pos,
glm::vec2{
mSpellFont.GetFont().GetWidth(spellI),
mSpellFont.GetFont().GetHeight()},
true
});
pos += glm::vec2{mSpellFont.GetFont().GetWidth(spellI) + 1, 0};
}
}
AddChildren();
}
void ShowPortrait(BAK::ActiveCharIndex character)
{
mGuiManager.ShowCharacterPortrait(character);
}
void ShowInventory(BAK::ActiveCharIndex character)
{
mGuiManager.ShowInventory(character);
}
private:
void AddChildren()
{
ClearChildren();
for (auto& button : mButtons)
{
AddChildBack(&button);
}
for (auto& spell : mActiveSpells)
{
AddChildBack(&spell);
}
AddChildBack(&mCompass);
for (auto& character : mCharacters)
AddChildBack(&character);
}
IGuiManager& mGuiManager;
const Icons& mIcons;
const Font& mSpellFont;
BAK::Layout mLayout;
std::vector<Widget> mActiveSpells;
Compass mCompass;
std::vector<ClickButtonImage> mButtons;
std::vector<ClickButtonImage> mCharacters;
const Logging::Logger& mLogger;
};
}
| 7,351
|
C++
|
.h
| 218
| 23.293578
| 100
| 0.560508
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,636
|
saveScreen.hpp
|
xavieran_BaKGL/gui/saveScreen.hpp
|
#pragma once
#include "bak/saveManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/colors.hpp"
#include "gui/list.hpp"
#include "gui/clickButton.hpp"
#include "gui/scrollView.hpp"
#include "gui/textBox.hpp"
#include "gui/textInput.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iomanip>
#include <filesystem>
#include <functional>
namespace Gui {
class SaveScreen: public Widget
{
public:
static constexpr auto sLayoutFile = "REQ_SAVE.DAT";
static constexpr auto sLayoutRestoreFile = "REQ_LOAD.DAT";
static constexpr auto sBackground = "OPTIONS2.SCX";
static constexpr auto sDirectories = 0;
static constexpr auto sFiles = 1;
static constexpr auto sRmDirectory = 2;
static constexpr auto sRmFile = 3;
static constexpr auto sSave = 4;
static constexpr auto sCancel = 5;
static constexpr auto sLoadOffset = 2;
using LeaveSaveFn = std::function<void()>;
using LoadSaveFn = std::function<void(std::string)>;
using SaveFn = std::function<void(const BAK::SaveFile&)>;
SaveScreen(
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
LeaveSaveFn&& leaveSaveFn,
LoadSaveFn&& loadSaveFn,
SaveFn&& saveFn)
:
Widget{
RectTag{},
glm::vec2{0, 0},
glm::vec2{320, 200},
Color::black,
false
},
mFont{font},
mBackgrounds{backgrounds},
mLayout{sLayoutFile},
mLayoutRestore{sLayoutRestoreFile},
mLeaveSaveFn{std::move(leaveSaveFn)},
mLoadSaveFn{std::move(loadSaveFn)},
mSaveFn{std::move(saveFn)},
mIsSave{true},
mFrame{
ImageTag{},
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sBackground),
glm::vec2{0},
GetPositionInfo().mDimensions,
true
},
mRestoreLabel{
glm::vec2{132, 12},
glm::vec2{80, 16}
},
mDirectoryLabel{
glm::vec2{22, 30},
glm::vec2{80, 16}
},
mFilesLabel{
glm::vec2{132, 30},
glm::vec2{40, 16}
},
mDirectories{
glm::vec2{20, 40},
glm::vec2{100, 90},
icons,
false,
true,
40u, 0.0f, true},
mDirectorySaveInput{
font,
glm::vec2{20, 132},
glm::vec2{100, 16},
30
},
mFiles{
glm::vec2{130, 40},
glm::vec2{160, 90},
icons,
false,
true,
40u, 0.0f, true},
mFileSaveInput{
font,
glm::vec2{130, 132},
glm::vec2{160, 16},
30
},
mRmDirectory{
mLayout.GetWidgetLocation(sRmDirectory),
mLayout.GetWidgetDimensions(sRmDirectory),
mFont,
"#Remove Directory",
[&]{ RemoveDirectory(); }
},
mRmFile{
mLayout.GetWidgetLocation(sRmFile),
mLayout.GetWidgetDimensions(sRmFile),
mFont,
"#Remove File",
[&]{ RemoveFile(); }
},
mSave{
mLayout.GetWidgetLocation(sSave),
mLayout.GetWidgetDimensions(sSave),
mFont,
"#Save",
[this]{ SaveGame(false); }
},
mRestore{
mLayoutRestore.GetWidgetLocation(sSave - sLoadOffset),
mLayoutRestore.GetWidgetDimensions(sSave - sLoadOffset),
mFont,
"#Restore",
[this]{ RestoreGame(); }
},
mCancel{
mLayout.GetWidgetLocation(sCancel),
mLayout.GetWidgetDimensions(sCancel),
mFont,
"#Cancel",
[this]{ std::invoke(mLeaveSaveFn); }
},
mRefreshDirectories{false},
mRefreshSaves{false},
mSelectedDirectory{},
mSelectedSave{},
mSaveManager{(GetBakDirectoryPath() / "GAMES").string()},
mNeedRefresh{false},
mLogger{Logging::LogState::GetLogger("Gui::SaveScreen")}
{
mDirectoryLabel.SetText(mFont, "Directories");
mFilesLabel.SetText(mFont, "Games");
mRestoreLabel.SetText(mFont, "#Restore Game");
}
bool OnMouseEvent(const MouseEvent& event) override
{
const bool handled = Widget::OnMouseEvent(event);
if (mNeedRefresh)
{
RefreshGui();
}
return handled;
}
void SetSaveOrLoad(bool isSave)
{
mSaveManager.RefreshSaves();
mIsSave = isSave;
mDirectories.SetDimensions(glm::vec2{100, mIsSave ? 90 : 108});
mFiles.SetDimensions(glm::vec2{160, mIsSave ? 90 : 108});
if (!mSelectedDirectory || !mSelectedSave)
{
if (mSaveManager.GetSaves().size() > 0)
{
mSelectedDirectory = 0;
if (mSaveManager.GetSaves().at(*mSelectedDirectory).mSaves.size() > 0)
{
mSelectedSave = 0;
}
}
}
mDirectorySaveInput.SetText(
mSelectedDirectory
? mSaveManager.GetSaves().at(*mSelectedDirectory).mName
: "");
mFileSaveInput.SetText(
(mSelectedDirectory && mSelectedSave)
? mSaveManager.GetSaves().at(*mSelectedDirectory).mSaves.at(*mSelectedSave).mName
: "");
mRefreshSaves = true;
mRefreshDirectories = true;
RefreshGui();
}
private:
void RemoveDirectory()
{
if (!mSelectedDirectory)
return;
mSaveManager.RemoveDirectory(*mSelectedDirectory);
if (*mSelectedDirectory > 0)
{
(*mSelectedDirectory)--;
}
RefreshGui();
}
void RemoveFile()
{
if (!mSelectedSave)
return;
assert(mSelectedDirectory);
// Disable remove file button when no saves in selected dir
mSaveManager.RemoveSave(*mSelectedDirectory, *mSelectedSave);
if (*mSelectedSave > 0)
{
(*mSelectedSave)--;
mFileSaveInput.SetText(mSaveManager.GetSaves().at(*mSelectedDirectory).mSaves.front().mName);
}
if (mSaveManager.GetSaves().at(*mSelectedDirectory).mSaves.size() == 0)
{
RemoveDirectory();
}
RefreshGui();
}
void SaveGame(bool isBookmark)
{
const auto saveDir = mDirectorySaveInput.GetText();
const auto saveName = mFileSaveInput.GetText();
if (saveDir.empty() || saveName.empty())
{
mLogger.Error() << "Cannot save game, no directory or save name\n";
return;
}
mLogger.Info() << "Saving game to: " << saveDir << " " << saveName << "\n";
mSaveFn(mSaveManager.MakeSave(saveDir, saveName, isBookmark));
}
void RestoreGame()
{
assert(mSelectedDirectory && mSelectedSave);
const auto savePath = mSaveManager.GetSaves().at(*mSelectedDirectory)
.mSaves.at(*mSelectedSave).mPath;
std::invoke(mLoadSaveFn, savePath);
}
void DirectorySelected(std::size_t i)
{
mSelectedDirectory = i;
const auto& saves = mSaveManager.GetSaves().at(*mSelectedDirectory).mSaves;
mSelectedSave = saves.size() > 0
? std::make_optional(0)
: std::nullopt;
mDirectorySaveInput.SetFocus(true);
mFileSaveInput.SetFocus(false);
mDirectorySaveInput.SetText(
mSaveManager.GetSaves().at(*mSelectedDirectory).mName);
mFileSaveInput.SetText(saves.size() > 0
? saves.front().mName
: "");
mNeedRefresh = true;
mRefreshSaves = true;
}
void SaveSelected(std::size_t i)
{
assert(mSelectedDirectory);
const auto& saves = mSaveManager.GetSaves().at(*mSelectedDirectory).mSaves;
mSelectedSave = i;
mDirectorySaveInput.SetFocus(false);
mFileSaveInput.SetFocus(true);
const auto saveName = saves.at(*mSelectedSave).mName;
mFileSaveInput.SetText(saveName);
mNeedRefresh = true;
}
void RefreshGui()
{
mNeedRefresh = false;
AddChildren();
}
void AddChildren()
{
mDirectories.GetChild().ClearWidgets();
mFiles.GetChild().ClearWidgets();
ClearChildren();
AddChildBack(&mFrame);
std::size_t index = 0;
for (const auto& dir : mSaveManager.GetSaves())
{
mDirectories.GetChild().AddWidget(
glm::vec2{0, 0},
glm::vec2{mDirectories.GetDimensions().x - 16, 15},
mFont,
(index == mSelectedDirectory ? "#" : "") + dir.mName,
[this, i=index]{ DirectorySelected(i); }
);
index++;
}
if (mSelectedDirectory)
{
index = 0;
for (auto save : mSaveManager.GetSaves().at(*mSelectedDirectory).mSaves)
{
mFiles.GetChild().AddWidget(
glm::vec2{0, 0},
glm::vec2{mFiles.GetDimensions().x - 16, 15},
mFont,
(index == mSelectedSave ? "#" : "") + save.mName,
[this, i=index]{ SaveSelected(i); }
);
index++;
}
}
AddChildBack(&mDirectories);
AddChildBack(&mFiles);
AddChildBack(&mDirectoryLabel);
AddChildBack(&mFilesLabel);
AddChildBack(&mCancel);
if (mIsSave)
{
mRmDirectory.SetPosition(mLayout.GetWidgetLocation(sRmDirectory));
mRmFile.SetPosition(mLayout.GetWidgetLocation(sRmFile));
mSave.SetPosition(mLayout.GetWidgetLocation(sSave));
mCancel.SetPosition(mLayout.GetWidgetLocation(sCancel));
AddChildBack(&mRmDirectory);
AddChildBack(&mRmFile);
AddChildBack(&mSave);
AddChildBack(&mRestoreLabel);
AddChildBack(&mDirectorySaveInput);
AddChildBack(&mFileSaveInput);
}
else
{
mCancel.SetPosition(mLayoutRestore.GetWidgetLocation(sCancel - sLoadOffset));
AddChildBack(&mRestore);
AddChildBack(&mRestoreLabel);
}
// Only refresh this when the directory changes
// otherwises the scroll view will pop back to the top
// when we click on a save
if (mRefreshSaves)
{
mFiles.ResetScroll();
mRefreshSaves = false;
}
if (mRefreshDirectories)
{
mDirectories.ResetScroll();
mRefreshDirectories = false;
}
}
const Font& mFont;
const Backgrounds& mBackgrounds;
BAK::Layout mLayout;
BAK::Layout mLayoutRestore;
LeaveSaveFn mLeaveSaveFn;
LoadSaveFn mLoadSaveFn;
SaveFn mSaveFn;
bool mIsSave;
Widget mFrame;
TextBox mRestoreLabel;
TextBox mDirectoryLabel;
TextBox mFilesLabel;
ScrollView<List<ClickButton>> mDirectories;
TextInput mDirectorySaveInput;
ScrollView<List<ClickButton>> mFiles;
TextInput mFileSaveInput;
ClickButton mRmDirectory;
ClickButton mRmFile;
ClickButton mSave;
ClickButton mRestore;
ClickButton mCancel;
bool mRefreshDirectories;
bool mRefreshSaves;
std::optional<std::size_t> mSelectedDirectory;
std::optional<std::size_t> mSelectedSave;
BAK::SaveManager mSaveManager;
bool mNeedRefresh;
const Logging::Logger& mLogger;
};
}
| 11,785
|
C++
|
.h
| 368
| 22.434783
| 105
| 0.574659
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,637
|
dialogDisplay.hpp
|
xavieran_BaKGL/gui/dialogDisplay.hpp
|
#pragma once
#include "bak/dialog.hpp"
#include "bak/gameState.hpp"
#include "com/algorithm.hpp"
#include "com/assert.hpp"
#include "com/visit.hpp"
#include "gui/IDialogDisplay.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/actors.hpp"
#include "gui/backgrounds.hpp"
#include "gui/button.hpp"
#include "gui/colors.hpp"
#include "gui/label.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <string>
#include <string_view>
namespace Gui {
enum class DialogFrame
{
Fullscreen = 0,
ActionArea = 1,
ActionAreaInventory = 2,
LowerArea = 3,
Popup = 4
};
class DialogDisplay : public Widget, IDialogDisplay
{
public:
DialogDisplay(
glm::vec2 pos,
glm::vec2 dims,
const Actors& actors,
const Backgrounds& bgs,
const Font& fr,
BAK::GameState& gameState)
:
Widget{
RectTag{},
pos,
dims,
glm::vec4{0},
true
},
mKeywords{},
mGameState{gameState},
mCenter{160, 112},
mFont{fr},
mActors{actors},
mLabel{
mCenter,
glm::vec2{320, 20},
mFont,
"#LABEL#"},
mActor{
Graphics::DrawMode::Sprite,
mActors.GetSpriteSheet(),
Graphics::TextureIndex{},
Graphics::ColorMode::Texture,
glm::vec4{0},
glm::vec2{100, 19},
glm::vec2{0},
true},
mFullscreenFrame{
Graphics::DrawMode::Sprite,
bgs.GetSpriteSheet(),
bgs.GetScreen("OPTIONS2.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{0},
glm::vec2{0, 0},
glm::vec2{320, 200},
true
},
mWorldViewFrame{
Graphics::DrawMode::Sprite,
bgs.GetSpriteSheet(),
bgs.GetScreen("DIALOG_BG_MAIN.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{0},
glm::vec2{0, 0},
glm::vec2{320, 200},
true
},
mActionAreaFrame{
ClipRegionTag{},
glm::vec2{15, 11},
glm::vec2{289, 101},
true
},
mActionAreaBackground{
Graphics::DrawMode::Sprite,
bgs.GetSpriteSheet(),
bgs.GetScreen("DIALOG.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{0},
glm::vec2{-15, -11},
glm::vec2{320, 200},
true
},
mLowerFrame{
RectTag{},
glm::vec2{15, 125},
glm::vec2{285, 66},
glm::vec4{0},
true
},
mFullscreenTextBox{
glm::vec2{30, 30},
glm::vec2{320 - 30*2, 135}
},
mActionAreaTextBox{
glm::vec2{6, 6},
glm::vec2{290, 103}
},
mLowerTextBox{
glm::vec2{0, 0},
glm::vec2{285, 66}
},
mPopup{
glm::vec2{},
glm::vec2{},
Color::buttonBackground,
Color::buttonHighlight,
Color::buttonShadow,
Color::black
},
mPopupText{
glm::vec2{},
glm::vec2{}
},
mLogger{Logging::LogState::GetLogger("Gui::DialogDisplay")}
{
mFullscreenFrame.AddChildBack(&mFullscreenTextBox);
mLowerFrame.AddChildBack(&mLowerTextBox);
mActionAreaFrame.AddChildBack(&mActionAreaBackground);
mActionAreaFrame.AddChildBack(&mActionAreaTextBox);
mPopup.AddChildBack(&mPopupText);
}
void ShowWorldViewPane(bool isInWorldView)
{
if (isInWorldView)
AddChildBack(&mWorldViewFrame);
}
void DisplayPlayer(IDialogScene& dialogScene, unsigned act)
{
const auto actor = mGameState.GetActor(act);
if (actor)
{
SetActor(*actor, dialogScene, false);
AddLabel("#"
+ std::string{mKeywords.GetNPCName(*actor)}
+ " asked about:#");
}
else
{
}
}
std::pair<glm::vec2, std::string> DisplaySnippet(
IDialogScene& dialogScene,
const BAK::DialogSnippet& snippet,
std::string_view remainingText,
bool isInWorldView,
glm::vec2 mousePos)
{
ClearChildren();
auto popup = snippet.GetPopup();
if (popup)
{
// Need a more reliable way of getting mouse pos
//mPopup.SetPosition(mousePos);
mPopup.SetPosition(popup->mPos);
mPopup.SetDimensions(popup->mDims);
mPopupText.SetPosition(glm::vec2{1});
mPopupText.SetDimensions(popup->mDims);
}
std::string text{remainingText};
text = mGameState.GetTextVariableStore().SubstituteVariables(text);
const auto ds1 = snippet.mDisplayStyle;
const auto ds2 = snippet.mDisplayStyle2;
const auto ds3 = snippet.mDisplayStyle3;
const auto act = snippet.mActor;
const auto dialogFrame = std::invoke([&]{
if (popup)
return DialogFrame::Popup;
else if (act != 0x0)
return DialogFrame::LowerArea;
else if (ds1 == 0x06)
return DialogFrame::Fullscreen;
else if (ds1 == 0x05)
return DialogFrame::ActionAreaInventory;
else if (ds1 == 0x03 || ds1 == 0x04)
return DialogFrame::LowerArea;
else if (ds1 == 0x02 || ds2 == 0x14 || ds3 == 0x02 || ds2 == 0x10)
return DialogFrame::ActionArea;
else
return DialogFrame::Fullscreen;
});
const bool verticallyCentered
= ((ds2 & 0x10) != 0) || (ds2 == 0x3);
const bool horizontallyCentered
= (ds2 & 0x4) == 0x4;
const bool isBold
= ds2 == 0x3;
std::optional<unsigned> actor{};
if (act != 0)
{
actor = mGameState.GetActor(act);
}
const auto [charPos, undisplayedText] = SetText(
text,
dialogFrame,
horizontallyCentered,
verticallyCentered,
isBold,
isInWorldView);
if (actor)
{
SetActor(*actor, dialogScene, true);
}
return std::make_pair(charPos, std::string{undisplayedText});
}
void ShowFlavourText(BAK::Target target)
{
const auto& snippet = BAK::DialogStore::Get().GetSnippet(target);
const auto text = snippet.GetText();
const auto flavourText = find_nth(text.begin(), text.end(), '#', 2);
ASSERT(flavourText != text.end());
const auto remainingText = std::string{flavourText, text.end()};
auto nullScene = NullDialogScene{};
DisplaySnippet(nullScene, snippet, remainingText, false, glm::vec2{});
const auto label = std::string{text.begin(), flavourText};
AddLabel(label);
}
void Clear()
{
ClearChildren();
mWorldViewFrame.ClearChildren();
}
private:
void AddLabel(std::string_view text)
{
mLabel.SetText(text);
mLabel.SetCenter(mCenter);
AddChildBack(&mLabel);
}
std::pair<glm::vec2, std::string_view> SetText(
std::string_view text,
DialogFrame dialogFrame,
bool centeredX,
bool centeredY,
bool isBold,
bool isInWorldView)
{
Clear();
switch (dialogFrame)
{
case DialogFrame::Fullscreen:
{
AddChildBack(&mFullscreenFrame);
auto [charPos, remaining] = mFullscreenTextBox.SetText(
mFont,
text,
centeredX,
centeredY,
isBold);
return std::make_pair<glm::vec2, std::string_view>(charPos + mFullscreenTextBox.GetTopLeft(), std::move(remaining));
} break;
case DialogFrame::ActionAreaInventory: [[fallthrough]];
case DialogFrame::ActionArea:
{
AddChildBack(&mActionAreaFrame);
if (dialogFrame == DialogFrame::ActionArea)
{
mActionAreaFrame.SetPosition({13, 11});
mActionAreaFrame.SetDimensions({295, 101});
mActionAreaTextBox.SetDimensions({288, 97});
}
// Inventory style is a bit bigger..
else
{
mActionAreaFrame.SetPosition({12, 11});
mActionAreaFrame.SetDimensions({295, 121});
mActionAreaTextBox.SetDimensions({288, 118});
}
auto [charPos, remaining] = mActionAreaTextBox.SetText(
mFont,
text,
centeredX,
centeredY,
isBold);
return std::make_pair<glm::vec2, std::string_view>(charPos + mActionAreaFrame.GetTopLeft(), std::move(remaining));
} break;
case DialogFrame::LowerArea:
{
if (isInWorldView)
{
AddChildBack(&mWorldViewFrame);
mWorldViewFrame.AddChildBack(&mLowerFrame);
}
else
{
AddChildBack(&mLowerFrame);
}
auto [charPos, remaining] = mLowerTextBox.SetText(
mFont,
text,
centeredX,
centeredY,
isBold);
// the subtraction of 10 is a hack to stop the buttons getting displayed half off the bottom of the screen... not ideal
return std::make_pair<glm::vec2, std::string_view>(charPos + mLowerFrame.GetTopLeft() - glm::vec2{0, 10}, std::move(remaining));
} break;
case DialogFrame::Popup:
{
AddChildBack(&mPopup);
auto [charPos, remaining] = mPopupText.SetText(mFont, text, true, true);
// probably not required...
return std::make_pair<glm::vec2, std::string_view>(charPos + mPopup.GetTopLeft() - glm::vec2{0, 10}, std::move(remaining));
} break;
default:
throw std::runtime_error("Invalid DialogArea");
}
}
void SetActor(
unsigned actor,
IDialogScene& dialogScene,
bool showName)
{
mLogger.Debug() <<" Actor: " << actor << "\n";
if (actor > 6)
dialogScene.DisplayNPCBackground();
else
dialogScene.DisplayPlayerBackground();
const auto& [index, dims] = mActors.GetActor(actor);
mActor.SetTexture(index);
// we want the bottom of this picture to end up here
mActor.SetPosition(glm::vec2{100, 112 - dims.y});
mActor.SetDimensions(dims);
AddChildBack(&mActor);
if (showName)
{
AddLabel("#" + std::string{mKeywords.GetNPCName(actor)} + "#");
}
}
private:
BAK::Keywords mKeywords;
BAK::GameState& mGameState;
glm::vec2 mCenter;
const Font& mFont;
const Actors& mActors;
Label mLabel;
Widget mActor;
Widget mFullscreenFrame;
Widget mWorldViewFrame;
Widget mActionAreaFrame;
Widget mActionAreaBackground;
Widget mLowerFrame;
TextBox mFullscreenTextBox;
TextBox mActionAreaTextBox;
TextBox mLowerTextBox;
Button mPopup;
TextBox mPopupText;
const Logging::Logger& mLogger;
};
}
| 11,540
|
C++
|
.h
| 365
| 21.619178
| 140
| 0.550777
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,638
|
IAnimator.hpp
|
xavieran_BaKGL/gui/IAnimator.hpp
|
#pragma once
namespace Gui {
class IAnimator
{
public:
virtual void OnTimeDelta(double delta) = 0;
virtual bool IsAlive() const = 0;
virtual ~IAnimator() = default;
};
}
| 186
|
C++
|
.h
| 10
| 16
| 47
| 0.715116
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,639
|
cureScreen.hpp
|
xavieran_BaKGL/gui/cureScreen.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/dialogSources.hpp"
#include "bak/layout.hpp"
#include "bak/temple.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/icons.hpp"
#include "gui/info/portrait.hpp"
#include "gui/info/ratings.hpp"
#include "gui/colors.hpp"
#include "gui/teleportDest.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class CureScreen : public Widget, public IDialogScene
{
public:
static constexpr auto sLayoutFile = "REQ_HEAL.DAT";
static constexpr auto sInfoLayoutFile = "REQ_INFO.DAT";
static constexpr auto sScreen = "OPTIONS1.SCX";
static constexpr auto sCurePlayer = 0;
static constexpr auto sNextPlayer = 1;
static constexpr auto sDone = 2;
static constexpr auto sPortraitWidget = 0;
CureScreen(
IGuiManager& guiManager,
const Actors& actors,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
BAK::GameState& gameState)
:
Widget{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sScreen),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200},
true
},
mGuiManager{guiManager},
mFont{font},
mGameState{gameState},
mIcons{icons},
mLayout{sLayoutFile},
mInfoLayout{sInfoLayoutFile},
mSelectedCharacter{BAK::ActiveCharIndex{0}},
mTempleNumber{BAK::Temple::sTempleOfSung},
mCureFactor{65},
mFinished{nullptr},
mCost{BAK::Royals{0}},
mPortrait{
mInfoLayout.GetWidgetLocation(sPortraitWidget),
mInfoLayout.GetWidgetDimensions(sPortraitWidget),
actors,
mFont,
std::get<Graphics::SpriteSheetIndex>(icons.GetStippledBorderVertical()),
std::get<Graphics::TextureIndex>(icons.GetStippledBorderHorizontal()),
std::get<Graphics::TextureIndex>(icons.GetStippledBorderVertical()),
[this](){
AdvanceCharacter(); },
[this](){
const auto character = mGameState
.GetParty()
.GetCharacter(BAK::ActiveCharIndex{mSelectedCharacter})
.GetIndex();
mGameState.SetDialogContext_7530(character.mValue);
mGuiManager.StartDialog(
BAK::DialogSources::mCharacterFlavourDialog, false, false, this);
}
},
mRatings{
mPortrait.GetPositionInfo().mPosition
+ glm::vec2{mPortrait.GetPositionInfo().mDimensions.x + 4, 0},
glm::vec2{222, mPortrait.GetPositionInfo().mDimensions.y},
mFont,
std::get<Graphics::SpriteSheetIndex>(icons.GetStippledBorderVertical()),
std::get<Graphics::TextureIndex>(icons.GetStippledBorderHorizontal()),
std::get<Graphics::TextureIndex>(icons.GetStippledBorderVertical())
},
mCureText{
glm::vec2{34, 94},
glm::vec2{240, 80}
},
mCureButton{
mLayout.GetWidgetLocation(sCurePlayer),
mLayout.GetWidgetDimensions(sCurePlayer) + glm::vec2{0, 1},
mFont,
"#Cure Player",
[this]{
CureCharacter();
}
},
mNextPlayerButton{
mLayout.GetWidgetLocation(sNextPlayer),
mLayout.GetWidgetDimensions(sNextPlayer) + glm::vec2{0, 1},
mFont,
"#Next Player",
[this]{
AdvanceCharacter();
}
},
mDoneButton{
mLayout.GetWidgetLocation(sDone),
mLayout.GetWidgetDimensions(sDone) + glm::vec2{0, 1},
mFont,
"#Done",
[this]{
mGuiManager.ExitSimpleScreen();
ASSERT(mFinished);
mFinished();
}
},
mLogger{Logging::LogState::GetLogger("Gui::CureScreen")}
{
AddChildren();
}
void DisplayNPCBackground() override {}
void DisplayPlayerBackground() override {}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice) override
{
AdvanceCharacter();
}
void EnterScreen(unsigned templeNumber, unsigned cureFactor, std::function<void()>&& finished)
{
mFinished = finished;
ASSERT(mFinished);
mTempleNumber = templeNumber;
mCureFactor = cureFactor;
mSelectedCharacter = BAK::ActiveCharIndex{0};
AdvanceCharacter();
}
private:
void CureCharacter()
{
if (mCost.mValue > mGameState.GetMoney().mValue)
{
mGuiManager.StartDialog(BAK::DialogSources::mHealDialogCantAfford, false, false, this);
}
else
{
AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{0xc});
mGameState.SetActiveCharacter(mSelectedCharacter);
mGuiManager.StartDialog(BAK::DialogSources::mHealDialogPostHealing, false, false, this);
auto& character = mGameState.GetParty().GetCharacter(mSelectedCharacter);
BAK::Temple::CureCharacter(character.mSkills, character.mConditions, mTempleNumber == BAK::Temple::sTempleOfSung);
}
}
void AdvanceCharacter()
{
const auto startCharacter = mSelectedCharacter;
SetSelectedCharacter(
mGameState.GetParty().NextActiveCharacter(mSelectedCharacter));
while (CalculateCureCost().mValue == 0
&& mSelectedCharacter != startCharacter)
{
SetSelectedCharacter(
mGameState.GetParty().NextActiveCharacter(mSelectedCharacter));
}
if (mSelectedCharacter == startCharacter && CalculateCureCost().mValue == 0)
{
mGuiManager.ExitSimpleScreen();
mFinished();
}
UpdateCharacter();
}
void SetSelectedCharacter(BAK::ActiveCharIndex character)
{
mSelectedCharacter = character;
}
BAK::Royals CalculateCureCost()
{
auto& character = mGameState.GetParty().GetCharacter(mSelectedCharacter);
return BAK::Temple::CalculateCureCost(
mCureFactor,
mTempleNumber == BAK::Temple::sTempleOfSung,
character.mSkills,
character.mConditions,
character.mSkillAffectors);
}
void UpdateCharacter()
{
auto& character = mGameState.GetParty().GetCharacter(mSelectedCharacter);
mPortrait.SetCharacter(character.GetIndex(), character.mName);
mRatings.SetCharacter(character);
mCost = CalculateCureCost();
mGameState.SetItemValue(mCost);
// FIXME: This is awful... would be nice to generically deal with text vars
const auto snip = BAK::DialogStore::Get().GetSnippet(BAK::DialogSources::mHealDialogCost);
mGameState.SetActiveCharacter(mSelectedCharacter);
mGameState.SetCharacterTextVariables();
// For some reason the dialog action sets text variable 1 for cost but the dialog uses 0 for cost.
mGameState.GetTextVariableStore().SetTextVariable(0, BAK::ToShopDialogString(mCost));
mCureText.SetText(mFont, mGameState.GetTextVariableStore()
.SubstituteVariables(std::string{snip.GetText()}), false, false, true);
}
void AddChildren()
{
ClearChildren();
AddChildBack(&mPortrait);
AddChildBack(&mRatings);
AddChildBack(&mCureText);
AddChildBack(&mCureButton);
AddChildBack(&mNextPlayerButton);
AddChildBack(&mDoneButton);
}
private:
IGuiManager& mGuiManager;
const Font& mFont;
BAK::GameState& mGameState;
const Icons& mIcons;
BAK::Layout mLayout;
BAK::Layout mInfoLayout;
BAK::ActiveCharIndex mSelectedCharacter;
unsigned mTempleNumber;
unsigned mCureFactor;
std::function<void()> mFinished;
BAK::Royals mCost;
Portrait mPortrait;
Ratings mRatings;
TextBox mCureText;
ClickButton mCureButton;
ClickButton mNextPlayerButton;
ClickButton mDoneButton;
const Logging::Logger& mLogger;
};
}
| 8,415
|
C++
|
.h
| 234
| 27.029915
| 126
| 0.634368
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,640
|
label.hpp
|
xavieran_BaKGL/gui/label.hpp
|
#pragma once
#include "gui/colors.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <variant>
namespace Gui {
class Label : public Widget
{
public:
Label(
glm::vec2 pos,
glm::vec2 dims,
const Font& fr,
const std::string& text)
:
Widget{
RectTag{},
pos,
dims,
Color::frameMaroon,
true
},
mForeground{
RectTag{},
glm::vec2{1,1},
dims,
Color::buttonBackground,
true
},
mTextBox{
glm::vec2{3, 2},
dims
},
mFont{fr},
mLogger{Logging::LogState::GetLogger("Gui::Label")}
{
AddChildBack(&mForeground);
AddChildBack(&mTextBox);
SetText(text);
}
void SetText(std::string_view text)
{
auto [dims, remaining] = mTextBox
.SetText(mFont, text);
// Add margin
dims += glm::vec2{3, 4};
// Resize to flow around text
SetDimensions(dims);
mForeground.SetDimensions(
dims - glm::vec2{2,2});
}
Widget mForeground;
TextBox mTextBox;
const Font& mFont;
const Logging::Logger& mLogger;
};
}
| 1,322
|
C++
|
.h
| 59
| 14.813559
| 59
| 0.531898
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,641
|
fadeScreen.hpp
|
xavieran_BaKGL/gui/fadeScreen.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/animator.hpp"
#include "gui/animatorStore.hpp"
#include "gui/colors.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
class FadeScreen: public Widget
{
public:
using DoneFunction = std::function<void()>;
FadeScreen(
AnimatorStore& animatorStore,
DoneFunction&& fadeInDone,
DoneFunction&& fadeOutDone)
:
Widget{
RectTag{},
glm::vec2{0, 0},
glm::vec2{320, 200},
Color::black,
false
},
mAnimatorStore{animatorStore},
mFadeInDone{std::move(fadeInDone)},
mFadeOutDone{std::move(fadeOutDone)},
mDuration{0.0},
mFading{false},
mLogger{Logging::LogState::GetLogger("Gui::FadeScreen")}
{
}
[[nodiscard]] bool OnMouseEvent(const MouseEvent& event) override
{
mLogger.Debug() << "Got mouse event: " << event << "\n";
return true;
}
void FadeIn(double duration)
{
ASSERT(!mFading);
mFading = true;
mDuration = duration;
SetColor(glm::vec4{0,0,0,0});
mAnimatorStore.AddAnimator(
std::make_unique<LinearAnimator>(
mDuration / 2,
glm::vec4{0, 0, 0, 0},
glm::vec4{0, 0, 0, 1},
[&](const auto& delta){
SetColor(GetDrawInfo().mColor + delta);
return false;
},
[&]{
mFading = false;
mFadeInDone();
}
));
}
void FadeOut()
{
ASSERT(!mFading);
mFading = true;
SetColor(glm::vec4{0,0,0,1});
mAnimatorStore.AddAnimator(
std::make_unique<LinearAnimator>(
mDuration / 2,
glm::vec4{0, 0, 0, 1},
glm::vec4{0, 0, 0, 0},
[&](const auto& delta){
SetColor(GetDrawInfo().mColor + delta);
return false;
},
[&]{
mFading = false;
mFadeOutDone();
}
));
}
private:
AnimatorStore& mAnimatorStore;
DoneFunction mFadeInDone;
DoneFunction mFadeOutDone;
double mDuration;
bool mFading;
const Logging::Logger& mLogger;
};
}
| 2,456
|
C++
|
.h
| 88
| 18.215909
| 69
| 0.513594
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,642
|
townLabel.hpp
|
xavieran_BaKGL/gui/townLabel.hpp
|
#pragma once
#include "com/logger.hpp"
#include "com/visit.hpp"
#include "gui/core/highlightable.hpp"
#include "gui/core/widget.hpp"
#include "gui/colors.hpp"
#include "gui/cursor.hpp"
#include "gui/textBox.hpp"
namespace Gui {
namespace detail {
class TownLabelBase : public Widget
{
public:
TownLabelBase(
glm::vec2 pos,
glm::vec2 dims,
const Font& font,
const std::string& label)
:
Widget{
RectTag{},
pos,
dims,
glm::vec4{0},
true
},
mTown{label},
mLabel{{}, glm::vec2{120, 32}}
{
const auto& [tDims, _] = mLabel.SetText(font, label);
mLabel.SetDimensions(tDims);
mLabel.SetCenter(glm::vec2{0, -3});
}
void Entered()
{
ClearChildren();
AddChildBack(&mLabel);
}
void Exited()
{
ClearChildren();
}
private:
std::string mTown;
TextBox mLabel;
};
}
using TownLabel = Highlightable<detail::TownLabelBase, false>;
}
| 1,045
|
C++
|
.h
| 49
| 15.591837
| 62
| 0.590447
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,643
|
actors.hpp
|
xavieran_BaKGL/gui/actors.hpp
|
#pragma once
#include "bak/textureFactory.hpp"
#include "com/assert.hpp"
#include "graphics/IGuiElement.hpp"
#include "graphics/texture.hpp"
#include "graphics/sprites.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <variant>
namespace Gui {
class Actors
{
public:
Actors(
Graphics::SpriteManager& spriteManager)
:
mSpriteSheet{spriteManager.AddSpriteSheet()},
mActorDimensions{},
mActorADimensions{},
mLogger{Logging::LogState::GetLogger("Gui::Actors")}
{
auto textures = Graphics::TextureStore{};
unsigned textureIndex = 0;
for (unsigned i = 1; i < 54; i++)
{
std::stringstream actN{};
actN << "ACT0" << std::setw(2) << std::setfill('0') << i;
std::stringstream pal{};
pal << actN.str() << ".PAL";
{
if ( i == 9
|| i == 12
|| i == 18
|| i == 30)
actN << "A";
std::stringstream bmx{};
bmx << actN.str() << ".BMX";
mLogger.Spam() << "Loading: " << bmx.str() << " " << pal.str() << std::endl;
BAK::TextureFactory::AddToTextureStore(
textures, bmx.str(), pal.str());
const auto dims = textures.GetTexture(textureIndex).GetDims();
mActorDimensions.emplace_back(std::make_pair(textureIndex, dims));
textureIndex++;
}
// Add all alternates ... "A"
if (i < 7)
{
actN << "A";
std::stringstream bmx{};
bmx << actN.str() << ".BMX";
mLogger.Spam() << "Loading alternate: " << bmx.str() << " " << pal.str() << std::endl;
BAK::TextureFactory::AddToTextureStore(
textures, bmx.str(), pal.str());
const auto dims = textures.GetTexture(textureIndex).GetDims();
mActorADimensions.emplace(
i,
std::make_pair(textureIndex, dims));
textureIndex++;
}
}
auto& spriteSheet = spriteManager.GetSpriteSheet(mSpriteSheet);
spriteSheet.LoadTexturesGL(textures);
}
Graphics::SpriteSheetIndex GetSpriteSheet() const
{
return mSpriteSheet;
}
std::pair<
Graphics::TextureIndex,
glm::vec2>
GetActor(unsigned actor) const
{
mLogger.Info() << "Get Actor: " << actor << "\n";
unsigned index = actor - 1;
ASSERT(index < mActorDimensions.size());
return mActorDimensions[index];
}
std::pair<
Graphics::TextureIndex,
glm::vec2>
GetActorA(unsigned actor) const
{
ASSERT(mActorADimensions.contains(actor));
return mActorADimensions.find(actor)->second;
}
private:
Graphics::SpriteSheetIndex mSpriteSheet;
std::vector<std::pair<Graphics::TextureIndex, glm::vec2>> mActorDimensions;
std::unordered_map<
unsigned,
std::pair<Graphics::TextureIndex, glm::vec2>> mActorADimensions;
const Logging::Logger& mLogger;
};
}
| 3,252
|
C++
|
.h
| 95
| 24.442105
| 102
| 0.543686
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,644
|
colors.hpp
|
xavieran_BaKGL/gui/colors.hpp
|
#pragma once
#include <glm/glm.hpp>
namespace Gui::Color {
constexpr auto black = glm::vec4{0.00, 0.00, 0.00, 1};
constexpr auto debug = glm::vec4{0.00, 0.00, 0.00, .4};
constexpr auto frameMaroon = glm::vec4{.300, .110, .094, 1};
constexpr auto fontHighlight = glm::vec4{.859, .780, .475, 1};
constexpr auto fontLowlight = glm::vec4{.302, .110, .094, 1};
constexpr auto fontUnbold = glm::vec4{.333, .271, .173, 1};
constexpr auto fontEmphasis = glm::vec4{.094, .125, .204, 1};
constexpr auto fontWhiteHighlight = glm::vec4{.969, .780, .651, 1};
constexpr auto fontRedHighlight = glm::vec4{.620, .188, .188, 1};
constexpr auto fontRedLowlight = glm::vec4{.255, .016, .031, 1};
constexpr auto infoBackground = glm::vec4{.125, .110, .094, 1};
constexpr auto buttonBackground = glm::vec4{.604, .427, .220, 1};
constexpr auto buttonPressed = glm::vec4{.573, .380, .204, 1};
constexpr auto buttonShadow = glm::vec4{.333, .271, .173, 1};
constexpr auto buttonHighlight = glm::vec4{.651, .573, .255, 1};
constexpr auto itemHighlighted = glm::vec4{.490, .063, .031, .5};
constexpr auto moredhelFontUpper = glm::vec4{.188, .157, .188, 1};
constexpr auto moredhelFontLower = glm::vec4{.255, .286, .255, 1};
constexpr auto tumblerBackground = glm::vec4{.188, .255, .286, 1};
constexpr auto tumblerShadow = glm::vec4{.349, .349, .318, 1};
constexpr auto tumblerHighlight = glm::vec4{.063, .063, .094, 1};
}
| 1,474
|
C++
|
.h
| 25
| 57.4
| 67
| 0.665505
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,645
|
cursor.hpp
|
xavieran_BaKGL/gui/cursor.hpp
|
#pragma once
#include "bak/textureFactory.hpp"
#include "com/assert.hpp"
#include "graphics/texture.hpp"
#include "graphics/sprites.hpp"
#include "gui/core/widget.hpp"
#include <stack>
namespace Gui {
class Cursor : public Widget
{
public:
using Dimensions = glm::vec2;
using CursorIndex = unsigned;
Cursor(
Graphics::SpriteManager& spriteManager)
:
Widget{
Graphics::DrawMode::Sprite,
spriteManager.AddSpriteSheet(),
Graphics::TextureIndex{0},
Graphics::ColorMode::Texture,
glm::vec4{0},
glm::vec2{0},
glm::vec2{1},
false
},
mCursors{},
mSprites{
spriteManager.GetSpriteSheet(
mDrawInfo.mSpriteSheet)},
mLogger{Logging::LogState::GetLogger("Gui::Cursor")}
{
auto textures = Graphics::TextureStore{};
BAK::TextureFactory::AddToTextureStore(
textures,
"POINTERG.BMX",
"OPTIONS.PAL");
mSprites.LoadTexturesGL(textures);
PushCursor(0);
}
void Clear()
{
while (mCursors.size() > 1)
mCursors.pop();
}
void PushCursor(unsigned cursor)
{
ASSERT(cursor < mSprites.size());
mCursors.push(
std::make_pair(
mSprites.GetDimensions(cursor),
cursor));
mLogger.Spam() << "Pushed Cursor: " << cursor << "\n";
UpdateCursor();
}
void PopCursor()
{
if (mCursors.size() < 2)
{
// This probably isn't an error...
mLogger.Error() << "Only have one cursor, not popping it!\n";
}
else
{
mLogger.Spam() << "Popped Cursor: " << std::get<unsigned>(mCursors.top()) << "\n";
mCursors.pop();
UpdateCursor();
}
}
void Hide()
{
SetColorMode(Graphics::ColorMode::SolidColor);
}
void Show()
{
SetColorMode(Graphics::ColorMode::Texture);
}
const auto& GetCursor()
{
ASSERT(mCursors.size() >= 1);
return mCursors.top();
}
const Graphics::Sprites& GetSprites()
{
return mSprites;
}
private:
void UpdateCursor()
{
ASSERT(mCursors.size() >= 1);
const auto & [dimensions, texture] = GetCursor();
mDrawInfo.mTexture = Graphics::TextureIndex{texture};
mPositionInfo.mDimensions = dimensions;
std::stringstream ss{};
std::stack<std::pair<Dimensions, CursorIndex>> cursors{};
while (!mCursors.empty())
{
auto tmp = mCursors.top();
mCursors.pop();
cursors.push(tmp);
ss << " " << tmp.second << ",";
}
mLogger.Spam() << " Stack: " << ss.str() << std::endl;
while (!cursors.empty())
{
auto tmp = cursors.top();
cursors.pop();
mCursors.push(tmp);
}
}
std::stack<std::pair<Dimensions, CursorIndex>> mCursors;
Graphics::Sprites& mSprites;
const Logging::Logger& mLogger;
};
}
| 3,150
|
C++
|
.h
| 115
| 19.226087
| 94
| 0.546932
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,646
|
dynamicTTM.hpp
|
xavieran_BaKGL/gui/dynamicTTM.hpp
|
#pragma once
#include "bak/ttmRunner.hpp"
#include "com/logger.hpp"
#include "graphics/sprites.hpp"
#include "gui/animatorStore.hpp"
#include "gui/core/widget.hpp"
#include "gui/button.hpp"
#include "gui/textBox.hpp"
#include <vector>
namespace Gui {
class Backgrounds;
class Font;
class DynamicTTM
{
public:
DynamicTTM(
Graphics::SpriteManager& spriteManager,
AnimatorStore& animatorStore,
const Font& font,
const Backgrounds& background,
std::function<void()>&& sceneFinished,
std::function<void(unsigned)>&& displayBook);
Widget* GetScene();
void BeginScene(std::string adsFile, std::string ttmFile);
bool AdvanceAction();
private:
bool RenderDialog(const BAK::ShowDialog&);
void ClearText();
Graphics::SpriteManager& mSpriteManager;
AnimatorStore& mAnimatorStore;
const Font& mFont;
Widget mSceneFrame;
Widget mDialogBackground;
Widget mRenderedElements;
TextBox mLowerTextBox;
Button mPopup;
TextBox mPopupText;
std::vector<Widget> mSceneElements;
BAK::TTMRunner mRunner;
bool mDelaying = false;
double mDelay = 0;
Graphics::TextureStore mRenderedFrames;
Graphics::SpriteManager::TemporarySpriteSheet mRenderedFramesSheet;
unsigned mCurrentRenderedFrame{0};
bool mWaitAtNextUpdate{false};
std::function<void()> mSceneFinished;
std::function<void(unsigned)> mDisplayBook;
const Logging::Logger& mLogger;
};
}
| 1,489
|
C++
|
.h
| 50
| 25.26
| 71
| 0.738516
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,647
|
scrollBar.hpp
|
xavieran_BaKGL/gui/scrollBar.hpp
|
#pragma once
#include "gui/button.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/icons.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
class ScrollBar : public Widget
{
static constexpr auto sMarginPixels = 2;
public:
ScrollBar(
glm::vec2 pos,
glm::vec2 dims,
const Icons& icons,
glm::vec2 barDim,
bool scrollVertical,
std::function<void(glm::vec2)>&& adjustScrollable)
:
Widget{
ClipRegionTag{},
pos,
dims,
true
},
mScrollVertical{scrollVertical},
mLastMousePos{},
mHandlePressed{false},
mScale{1.0},
mAdjustScrollable{std::move(adjustScrollable)},
mBar{
glm::vec2{0},
barDim,
Color::buttonBackground,
Color::buttonHighlight,
Color::buttonShadow
},
mHandle{
glm::vec2{sMarginPixels},
barDim - glm::vec2{sMarginPixels * 2},
Color::buttonBackground,
Color::buttonHighlight,
Color::buttonShadow
},
mUp{
glm::vec2{0},
std::get<glm::vec2>(icons.GetButton(1)),
std::get<Graphics::SpriteSheetIndex>(icons.GetButton(1)),
std::get<Graphics::TextureIndex>(icons.GetButton(1)),
std::get<Graphics::TextureIndex>(icons.GetPressedButton(1)),
[]{ },//Scroll(glm::vec2{0, 1}); },
[]{}
},
mDown{
glm::vec2{0, 16},
std::get<glm::vec2>(icons.GetButton(1)),
std::get<Graphics::SpriteSheetIndex>(icons.GetButton(1)),
std::get<Graphics::TextureIndex>(icons.GetButton(1)),
std::get<Graphics::TextureIndex>(icons.GetPressedButton(1)),
[]{}, //Scroll(glm::vec2{0, -1}); },
[]{}
},
mLogger{Logging::LogState::GetLogger("Gui::ScrollBar")}
{
AddChildren();
}
void SetDimensions(glm::vec2 dims) override
{
Widget::SetDimensions(dims);
mBar.SetDimensions(glm::vec2{16, dims.y});
mHandle.SetDimensions(mBar.GetDimensions() - glm::vec2{sMarginPixels * 2});
SetScale(mScale);
}
void SetScale(float scale)
{
mScale = scale;
mHandle.SetDimensions(
glm::vec2{mHandle.GetDimensions().x,
(mBar.GetDimensions().y - sMarginPixels * 2) * mScale});
}
bool OnMouseEvent(const MouseEvent& event) override
{
if (std::holds_alternative<LeftMousePress>(event)
&& Within(GetValue(event)))
{
mHandlePressed = true;
return true;
}
else if (std::holds_alternative<LeftMouseRelease>(event))
{
mHandlePressed = false;
}
if (mHandlePressed && std::holds_alternative<MouseMove>(event))
{
mAdjustScrollable((mLastMousePos - GetValue(event)) / (mBar.GetDimensions().y * mScale));
return true;
}
if (std::holds_alternative<MouseMove>(event))
{
mLastMousePos = GetValue(event);
}
return false;
}
void SetBarPosition(float position)
{
mHandle.SetPosition(
glm::vec2{
sMarginPixels,
sMarginPixels + (mBar.GetDimensions().y - sMarginPixels * 2 - mHandle.GetDimensions().y) * position});
}
private:
void AddChildren()
{
ClearChildren();
AddChildBack(&mBar);
AddChildBack(&mHandle);
//AddChildBack(&mUp);
//AddChildBack(&mDown);
}
const bool mScrollVertical;
glm::vec2 mLastMousePos;
bool mHandlePressed;
float mScale;
std::function<void(glm::vec2)> mAdjustScrollable;
Button mBar;
Button mHandle;
ClickButtonImage mUp;
ClickButtonImage mDown;
const Logging::Logger& mLogger;
};
}
| 3,977
|
C++
|
.h
| 132
| 21.530303
| 114
| 0.574524
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,648
|
fullMap.hpp
|
xavieran_BaKGL/gui/fullMap.hpp
|
#pragma once
#include "bak/coordinates.hpp"
#include "bak/fmap.hpp"
#include "bak/layout.hpp"
#include "bak/dialogSources.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/callbackDelay.hpp"
#include "gui/clickButton.hpp"
#include "gui/icons.hpp"
#include "gui/tickAnimator.hpp"
#include "gui/townLabel.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <memory>
namespace Gui {
class FullMap : public Widget
{
public:
static constexpr auto sLayoutFile = "REQ_FMAP.DAT";
static constexpr auto sExitWidget = 0;
FullMap(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
BAK::GameState& gameState)
:
Widget{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen("FULLMAP.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200}, true
},
mGuiManager{guiManager},
mFont{font},
mGameState{gameState},
mIcons{icons},
mFMapXY{},
mFMapTowns{},
mLayout{sLayoutFile},
mExitButton{
mLayout.GetWidgetLocation(sExitWidget),
mLayout.GetWidgetDimensions(sExitWidget),
mFont,
"#Exit",
[this]{
mGuiManager.DoFade(.8, [this]{
mPlayerPositionFlasher->Stop();
mGuiManager.ExitSimpleScreen(); });
}
},
mPopup{
glm::vec2{},
glm::vec2{},
Color::buttonBackground,
Color::buttonHighlight,
Color::buttonShadow,
Color::black
},
mPopupText{
glm::vec2{},
glm::vec2{}
},
mPlayerLocation{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(icons.GetFullMapIcon(0)),
std::get<Graphics::TextureIndex>(icons.GetFullMapIcon(0)),
mFMapXY.GetTileCoords(BAK::ZoneNumber{1}, glm::uvec2{10, 15}),
std::get<glm::vec2>(icons.GetFullMapIcon(0)),
false
},
mTowns{},
mGameStartScreenMode{false},
mLogger{Logging::LogState::GetLogger("Gui::FullMap")}
{
mTowns.reserve(mFMapTowns.GetTowns().size());
for (const auto& town : mFMapTowns.GetTowns())
{
mTowns.emplace_back(
town.mCoord,
glm::vec2{5, 5},
mFont,
town.mName);
}
mPopup.AddChildBack(&mPopupText);
}
void DisplayMapMode()
{
mGameStartScreenMode = false;
StartPlayerPositionFlasher();
AddChildren();
}
void DisplayGameStartMode(BAK::Chapter chapter, BAK::MapLocation location)
{
mGameStartScreenMode = true;
SetPlayerLocation(location);
DisplayGameStart(chapter);
AddChildren();
StartPlayerPositionFlasher();
mGuiManager.AddAnimator(
std::make_unique<CallbackDelay>(
[&](){
mGuiManager.EnterMainView();
mPlayerPositionFlasher->Stop();
},
3));
}
void UpdateLocation()
{
SetPlayerLocation(mGameState.GetZone(), mGameState.GetLocation());
}
private:
void SetPlayerLocation(
BAK::ZoneNumber zone,
BAK::GamePositionAndHeading location)
{
mPlayerPositionBaseIcon = BAK::HeadingToFullMapAngle(location.mHeading);
UpdatePlayerPositionIcon();
mPlayerLocation.SetCenter(
mFMapXY.GetTileCoords(
zone,
BAK::GetTile(location.mPosition)));
}
void SetPlayerLocation(BAK::MapLocation location)
{
mPlayerPositionBaseIcon = BAK::HeadingToFullMapAngle(location.mHeading);
mPlayerLocation.SetCenter(location.mPosition);
UpdatePlayerPositionIcon();
}
void DisplayGameStart(BAK::Chapter chapter)
{
const auto& snippet = BAK::DialogStore::Get().GetSnippet(
BAK::DialogSources::GetChapterStartText(chapter));
assert(snippet.GetPopup());
const auto popup = snippet.GetPopup();
mLogger.Debug() << "Show snippet;" << snippet << "\n";
mPopup.SetPosition(popup->mPos);
mPopup.SetDimensions(popup->mDims);
mPopupText.SetPosition(glm::vec2{1});
mPopupText.SetDimensions(popup->mDims);
mPopupText.SetText(mFont, snippet.GetText(), true, true);
}
void StartPlayerPositionFlasher()
{
auto flasher = std::make_unique<TickAnimator>(
.1,
[&](){
if (mPlayerPositionIconOffset == 3)
{
mPlayerPositionIconPulseDirection = -1;
}
else if (mPlayerPositionIconOffset == 0)
{
mPlayerPositionIconPulseDirection = 1;
}
mPlayerPositionIconOffset += mPlayerPositionIconPulseDirection;
UpdatePlayerPositionIcon();
});
mPlayerPositionFlasher = flasher.get();
mGuiManager.AddAnimator(std::move(flasher));
}
void UpdatePlayerPositionIcon()
{
const auto& [ss, ti, dims] = mIcons.GetFullMapIcon(mPlayerPositionBaseIcon + mPlayerPositionIconOffset);
mPlayerLocation.SetSpriteSheet(ss);
mPlayerLocation.SetTexture(ti);
mPlayerLocation.SetDimensions(dims);
}
void AddChildren()
{
ClearChildren();
if (mGameStartScreenMode)
{
AddChildBack(&mPopup);
}
else
{
AddChildBack(&mExitButton);
for (auto& t : mTowns)
AddChildBack(&t);
}
AddChildBack(&mPlayerLocation);
}
IGuiManager& mGuiManager;
const Font& mFont;
BAK::GameState& mGameState;
const Icons& mIcons;
BAK::FMapXY mFMapXY;
BAK::FMapTowns mFMapTowns;
BAK::Layout mLayout;
ClickButton mExitButton;
Button mPopup;
TextBox mPopupText;
Widget mPlayerLocation;
std::vector<TownLabel> mTowns{};
unsigned mPlayerPositionBaseIcon{};
unsigned mPlayerPositionIconOffset{};
int mPlayerPositionIconPulseDirection{1};
TickAnimator* mPlayerPositionFlasher{};
bool mGameStartScreenMode{};
const Logging::Logger& mLogger;
};
}
| 6,545
|
C++
|
.h
| 207
| 22.483092
| 112
| 0.59816
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,649
|
preferencesScreen.hpp
|
xavieran_BaKGL/gui/preferencesScreen.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/IContainer.hpp"
#include "bak/textureFactory.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
class PreferencesScreen: public Widget
{
public:
static constexpr auto sLayoutFile = "REQ_PREF.DAT";
static constexpr auto sBackground = "OPTIONS2.SCX";
static constexpr auto sOk = 0;
static constexpr auto sCancel = 1;
static constexpr auto sDefaults = 2;
using LeavePreferencesFn = std::function<void()>;
PreferencesScreen(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Font& font,
LeavePreferencesFn&& leavePreferenceFn)
:
Widget{
RectTag{},
glm::vec2{0, 0},
glm::vec2{320, 200},
Color::black,
false
},
mGuiManager{guiManager},
mFont{font},
mBackgrounds{backgrounds},
mLayout{sLayoutFile},
mLeavePreferencesFn{std::move(leavePreferenceFn)},
mFrame{
ImageTag{},
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sBackground),
glm::vec2{0},
GetPositionInfo().mDimensions,
true
},
mOk{
mLayout.GetWidgetLocation(sOk),
mLayout.GetWidgetDimensions(sOk),
mFont,
"#OK",
[this]{ std::invoke(mLeavePreferencesFn); }
},
mCancel{
mLayout.GetWidgetLocation(sCancel),
mLayout.GetWidgetDimensions(sCancel),
mFont,
"#Cancel",
[this]{ std::invoke(mLeavePreferencesFn); }
},
mDefaults{
mLayout.GetWidgetLocation(sDefaults),
mLayout.GetWidgetDimensions(sDefaults),
mFont,
"#Defaults",
[]{ }
},
mLogger{Logging::LogState::GetLogger("Gui::PreferencesScreen")}
{
AddChildren();
}
private:
void AddChildren()
{
ClearChildren();
AddChildBack(&mFrame);
mOk.SetPosition(mLayout.GetWidgetLocation(sOk));
mCancel.SetPosition(mLayout.GetWidgetLocation(sCancel));
mDefaults.SetPosition(mLayout.GetWidgetLocation(sDefaults));
AddChildBack(&mOk);
AddChildBack(&mCancel);
AddChildBack(&mDefaults);
}
IGuiManager& mGuiManager;
const Font& mFont;
const Backgrounds& mBackgrounds;
BAK::Layout mLayout;
LeavePreferencesFn mLeavePreferencesFn;
Widget mFrame;
ClickButton mOk;
ClickButton mCancel;
ClickButton mDefaults;
const Logging::Logger& mLogger;
};
}
| 2,848
|
C++
|
.h
| 97
| 21.608247
| 71
| 0.626052
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.