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,442
dragEvent.cpp
xavieran_BaKGL/gui/core/dragEvent.cpp
#include "gui/core/dragEvent.hpp" #include "graphics/glm.hpp" namespace Gui { std::ostream& operator<<(std::ostream& os, const DragStarted& event) { return os << "DragStarted { " << std::hex << event.mWidget << std::dec << " " << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const Dragging& event) { return os << "Dragging { " << std::hex << event.mWidget << std::dec << " " << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const DragEnded& event) { return os << "DragEnded { " << std::hex << event.mWidget << std::dec << " " << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const DragEvent& event) { return std::visit([&](const auto& e) -> std::ostream& { os << e; return os; }, event); } const glm::vec2& GetValue(const DragEvent& event) { return std::visit([&](const auto& e) -> const glm::vec2& { return e.mValue; }, event); } }
1,007
C++
.cpp
33
26.090909
105
0.576166
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,443
widget.cpp
xavieran_BaKGL/gui/core/widget.cpp
#include "gui/core/widget.hpp" #include "com/assert.hpp" #include "graphics/glm.hpp" namespace Gui { Widget::Widget( Graphics::DrawMode drawMode, Graphics::SpriteSheetIndex spriteSheet, Graphics::TextureIndex texture, Graphics::ColorMode colorMode, glm::vec4 color, glm::vec2 pos, glm::vec2 dims, bool childrenRelative) : mDrawInfo{ drawMode, spriteSheet, texture, colorMode, color}, mPositionInfo{ pos, dims, 0.0, childrenRelative}, mParent{nullptr}, mChildren{}, mActive{true} {} Widget::Widget( ImageTag, Graphics::SpriteSheetIndex spriteSheet, Graphics::TextureIndex texture, glm::vec2 pos, glm::vec2 dims, bool childrenRelative) : Widget{ Graphics::DrawMode::Sprite, spriteSheet, texture, Graphics::ColorMode::Texture, glm::vec4{1}, pos, dims, childrenRelative } { } Widget::Widget( ClipRegionTag, glm::vec2 pos, glm::vec2 dims, bool childrenRelative) : Widget{ Graphics::DrawMode::ClipRegion, Graphics::SpriteSheetIndex{0}, Graphics::TextureIndex{0}, Graphics::ColorMode::SolidColor, glm::vec4{1}, pos, dims, childrenRelative } { } Widget::Widget( RectTag, glm::vec2 pos, glm::vec2 dims, glm::vec4 color, bool childrenRelative) : Widget{ Graphics::DrawMode::Rect, Graphics::SpriteSheetIndex{0}, Graphics::TextureIndex{0}, Graphics::ColorMode::SolidColor, color, pos, dims, childrenRelative } { } Widget::~Widget() { } void Widget::SetActive() { mActive = true; } void Widget::SetInactive() { mActive = false; } bool Widget::OnKeyEvent(const KeyEvent& event) { if (mActive) { for (auto& c : mChildren) { const bool handled = c->OnKeyEvent(event); if (handled) return true; } } return false; } bool Widget::OnMouseEvent(const MouseEvent& event) { if (mActive) { for (auto& c : mChildren) { const bool handled = c->OnMouseEvent( TransformEvent(event)); if (handled) return true; } } return false; } bool Widget::OnDragEvent(const DragEvent& event) { if (mActive) { for (auto& c : mChildren) { const bool handled = c->OnDragEvent( TransformEvent(event)); if (handled) return true; } } return false; } void Widget::PropagateUp(const DragEvent& event) { if (mActive && mParent != nullptr) { // When the event arrives at the parent it should be in the same // space as the parent mParent->PropagateUp( mParent->InverseTransformEvent(event)); } } const Graphics::DrawInfo& Widget::GetDrawInfo() const { return mDrawInfo; } const Graphics::PositionInfo& Widget::GetPositionInfo() const { return mPositionInfo; } void Widget::AddChildFront(Widget* widget) { ASSERT(std::find(mChildren.begin(), mChildren.end(), widget) == mChildren.end()); mChildren.insert(mChildren.begin(), widget); widget->SetParent(this); Graphics::IGuiElement::AddChildFront( static_cast<Graphics::IGuiElement*>(widget)); } void Widget::AddChildBack(Widget* widget) { ASSERT(std::find(mChildren.begin(), mChildren.end(), widget) == mChildren.end()); mChildren.emplace_back(widget); widget->SetParent(this); Graphics::IGuiElement::AddChildBack( static_cast<Graphics::IGuiElement*>(widget)); } bool Widget::HaveChild(Widget* elem) { return std::find(mChildren.begin(), mChildren.end(), elem) != mChildren.end(); } void Widget::RemoveChild(Widget* elem) { elem->SetParent(nullptr); Graphics::IGuiElement::RemoveChild(elem); const auto it = std::find(mChildren.begin(), mChildren.end(), elem); ASSERT(it != mChildren.end()); mChildren.erase(it); } void Widget::PopChild() { if (mChildren.size() > 0) { auto widget = mChildren.back(); RemoveChild(widget); } } void Widget::ClearChildren() { Graphics::IGuiElement::ClearChildren(); for (auto* child : mChildren) child->SetParent(nullptr); mChildren.clear(); } void Widget::SetParent(Widget* widget) { mParent = widget; } void Widget::SetCenter(glm::vec2 pos) { mPositionInfo.mPosition = pos - (mPositionInfo.mDimensions / 2.0f); } glm::vec2 Widget::GetCenter() const { return mPositionInfo.mPosition + (mPositionInfo.mDimensions / 2.0f); } glm::vec2 Widget::GetTopLeft() const { return mPositionInfo.mPosition; } glm::vec2 Widget::GetDimensions() const { return mPositionInfo.mDimensions; } void Widget::SetPosition(glm::vec2 pos) { mPositionInfo.mPosition = pos; } void Widget::AdjustPosition(glm::vec2 adj) { mPositionInfo.mPosition += adj; } void Widget::SetRotation(float rot) { mPositionInfo.mRotation = rot; } void Widget::SetSpriteSheet(Graphics::SpriteSheetIndex spriteSheet) { mDrawInfo.mSpriteSheet = spriteSheet; } void Widget::SetTexture(Graphics::TextureIndex texture) { mDrawInfo.mTexture = texture; } void Widget::SetColorMode(Graphics::ColorMode cm) { mDrawInfo.mColorMode = cm; } void Widget::SetColor(glm::vec4 color) { mDrawInfo.mColor = color; } void Widget::SetDimensions(glm::vec2 dims) { mPositionInfo.mDimensions = dims; } std::size_t Widget::size() const { return mChildren.size(); } bool Widget::Within(glm::vec2 click) { return Graphics::PointWithinRectangle( glm::vec2{click}, glm::vec2{GetPositionInfo().mPosition}, glm::vec2{GetPositionInfo().mDimensions}); } glm::vec2 Widget::TransformPosition(const glm::vec2& pos) { if (mPositionInfo.mChildrenRelative) return pos - GetPositionInfo().mPosition; else return pos; } glm::vec2 Widget::InverseTransformPosition(const glm::vec2& pos) { if (mPositionInfo.mChildrenRelative) return pos + GetPositionInfo().mPosition; else return pos; } // When propagating event from parent to child MouseEvent Widget::TransformEvent(const MouseEvent& event) { return std::visit( [&]<typename T>(const T& e) -> MouseEvent { const auto newPos = TransformPosition(e.mValue); return MouseEvent{T{newPos}}; }, event); } DragEvent Widget::TransformEvent(const DragEvent& event) { return std::visit( [&]<typename T>(const T& e) -> DragEvent { const auto newPos = TransformPosition(e.mValue); return DragEvent{T{e.mWidget, newPos}}; }, event); } DragEvent Widget::InverseTransformEvent(const DragEvent& event) { return std::visit( [&]<typename T>(const T& e) -> DragEvent { const auto newPos = InverseTransformPosition(e.mValue); return DragEvent{T{e.mWidget, newPos}}; }, event); } }
7,212
C++
.cpp
313
18.009585
72
0.648175
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,444
keyEvent.cpp
xavieran_BaKGL/gui/core/keyEvent.cpp
#include "gui/core/keyEvent.hpp" namespace Gui { std::ostream& operator<<(std::ostream& os, const KeyPress& event) { return os << "KeyPress {" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const Character& event) { return os << "Character {" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const KeyEvent& event) { return std::visit([&](const auto& e) -> std::ostream& { os << e; return os; }, event); } }
515
C++
.cpp
20
21.5
66
0.585714
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,445
mouseEvent.cpp
xavieran_BaKGL/gui/core/mouseEvent.cpp
#include "gui/core/mouseEvent.hpp" #include "graphics/glm.hpp" namespace Gui { std::ostream& operator<<(std::ostream& os, const LeftMousePress& event) { return os << "LeftMousePress {" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const LeftMouseRelease& event) { return os << "LeftMouseRelease {" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const LeftMouseDoublePress& event) { return os << "LeftMouseDoublePress{" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const RightMousePress& event) { return os << "RightMousePress {" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const RightMouseRelease& event) { return os << "RightMouseRelease {" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const MouseMove& event) { return os << "MouseMove {" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const MouseScroll& event) { return os << "MouseScroll {" << event.mValue << "}"; } std::ostream& operator<<(std::ostream& os, const MouseEvent& event) { return std::visit([&](const auto& e) -> std::ostream& { os << e; return os; }, event); } const glm::vec2& GetValue(const MouseEvent& event) { return std::visit([&](const auto& e) -> const glm::vec2& { return e.mValue; }, event); } }
1,445
C++
.cpp
49
25.795918
77
0.629335
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,446
doubleClickStateMachine.cpp
xavieran_BaKGL/gui/core/doubleClickStateMachine.cpp
#include "gui/core/doubleClickStateMachine.hpp" namespace Gui { DoubleClickStateMachine::DoubleClickStateMachine( std::function<void(glm::vec2)>&& singlePress, std::function<void(glm::vec2)>&& singleRelease, std::function<void(glm::vec2)>&& doublePress) : mSinglePress{std::move(singlePress)}, mSingleRelease{std::move(singleRelease)}, mDoublePress{std::move(doublePress)} {} void DoubleClickStateMachine::HandlePress(glm::vec2 clickPos, float time) { if (mPress) { mDoublePress(clickPos); mPress.reset(); mRelease.reset(); } else { mRelease.reset(); mPress = Event{time, clickPos}; } } void DoubleClickStateMachine::HandleRelease(glm::vec2 clickPos, float time) { if (!mPress) { mSingleRelease(clickPos); } else { mRelease = Event{time, clickPos}; } } void DoubleClickStateMachine::UpdateTime(float time) { if (mPress && ((time - mPress->mClickTime) > mReleaseTimeout)) { if (!mRelease || (((time - mPress->mClickTime) > mDoubleClickTimeout))) { mSinglePress(mPress->mClickPos); if (mRelease) { mSingleRelease(mRelease->mClickPos); } mPress.reset(); mRelease.reset(); } } } }
1,335
C++
.cpp
53
19.320755
79
0.626959
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,447
widgetTest.cpp
xavieran_BaKGL/gui/core/test/widgetTest.cpp
#include "gtest/gtest.h" #include "com/logger.hpp" #include "gui/core/widget.hpp" #include <glm/glm.hpp> namespace Gui::Test { struct TestWidget : public Widget { template <typename ...Args> TestWidget(Args&&... args) : Widget{std::forward<Args>(args)...} {} bool OnMouseEvent( const MouseEvent& event) override { mMouseEvents.emplace_back(event); return Widget::OnMouseEvent(event); } void PropagateUp( const DragEvent& event) override { mDragEventsUp.emplace_back(event); return Widget::PropagateUp(event); } bool OnDragEvent( const DragEvent& event) override { mDragEventsDown.emplace_back(event); return Widget::OnDragEvent(event); } std::vector<DragEvent> mDragEventsUp; std::vector<DragEvent> mDragEventsDown; std::vector<MouseEvent> mMouseEvents; }; struct WidgetTestFixture : public ::testing::Test { WidgetTestFixture() : mRoot{ RectTag{}, glm::vec2{10, 10}, glm::vec2{50, 50}, glm::vec4{}, true }, mChild1{ RectTag{}, glm::vec2{2, 2}, glm::vec2{10, 10}, glm::vec4{}, true }, mChild2{ RectTag{}, glm::vec2{5, 5}, glm::vec2{10, 10}, glm::vec4{}, true } {} protected: void SetUp() override { Logging::LogState::SetLevel(Logging::LogLevel::Debug); mRoot.AddChildBack(&mChild1); mChild1.AddChildBack(&mChild2); } TestWidget mRoot; TestWidget mChild1; TestWidget mChild2; }; TEST_F(WidgetTestFixture, RelativeMouseEventPropagation) { const auto event = MouseEvent{LeftMousePress{glm::vec2{20, 20}}}; bool handled = mRoot.OnMouseEvent(event); EXPECT_EQ(handled, false); ASSERT_EQ(mRoot.mMouseEvents.size(), 1); EXPECT_EQ(mRoot.mMouseEvents.back(), event); ASSERT_EQ(mChild1.mMouseEvents.size(), 1); EXPECT_EQ( GetValue(mChild1.mMouseEvents.back()), (GetValue(event) - mRoot.GetPositionInfo().mPosition)); ASSERT_EQ(mChild2.mMouseEvents.size(), 1); EXPECT_EQ( GetValue(mChild2.mMouseEvents.back()), (GetValue(event) - mRoot.GetPositionInfo().mPosition - mChild1.GetPositionInfo().mPosition)); } TEST_F(WidgetTestFixture, DragEventPropagationUp) { const auto event = DragEvent{DragStarted{&mChild2, glm::vec2{8, 8}}}; const auto expected = DragEvent{DragStarted{&mChild2, glm::vec2{20, 20}}}; mChild2.PropagateUp(event); ASSERT_EQ(mRoot.mDragEventsUp.size(), 1); EXPECT_EQ(mRoot.mDragEventsUp.back(), expected); } TEST_F(WidgetTestFixture, RelativeDragEventPropagation) { const auto event = DragEvent{DragStarted{&mChild2, glm::vec2{20, 20}}}; bool handled = mRoot.OnDragEvent(event); EXPECT_EQ(handled, false); ASSERT_EQ(mRoot.mDragEventsDown.size(), 1); EXPECT_EQ(mRoot.mDragEventsDown.back(), event); ASSERT_EQ(mChild1.mDragEventsDown.size(), 1); EXPECT_EQ( GetValue(mChild1.mDragEventsDown.back()), (GetValue(event) - glm::vec2{10, 10})); ASSERT_EQ(mChild2.mDragEventsDown.size(), 1); EXPECT_EQ( GetValue(mChild2.mDragEventsDown.back()), (GetValue(event) - glm::vec2{10, 10} - glm::vec2{2, 2})); } } // namespace
3,462
C++
.cpp
114
23.754386
78
0.631056
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,448
itemArranger.cpp
xavieran_BaKGL/gui/inventory/itemArranger.cpp
#include "gui/inventory/itemArranger.hpp" namespace Gui { Grid::Grid( unsigned columns, unsigned rows) : mColumns{columns}, mRows{rows}, mGrid{std::invoke([&]{ std::vector<std::vector<bool>> grid; for (unsigned i = 0; i < rows; i++) grid.emplace_back(columns, false); return grid; })} { } void Grid::Occupy( unsigned columns, unsigned rows) { const auto& logger = Logging::LogState::GetLogger("Grid"); const auto currentPos = GetNextSlot(); for (unsigned r = 0; r < rows; r++) { for (unsigned c = 0; c < columns; c++) { ASSERT(currentPos.y + r < mRows); ASSERT(currentPos.x + c < mColumns); mGrid[currentPos.y + r][currentPos.x + c] = true; } } } glm::vec<2, unsigned> Grid::GetNextSlot() const { const auto& logger = Logging::LogState::GetLogger("Grid"); std::optional<glm::vec<2, unsigned>> slot{}; unsigned r = 0; unsigned c = 0; while (!slot) { if (!Get(c, r)) slot = glm::vec<2, unsigned>{c, r}; if ((++r) == mRows) { r = 0; c++; } } ASSERT(slot); return *slot; } const auto& Grid::GetGrid() const { return mGrid; } bool Grid::Get(unsigned column, unsigned row) const { ASSERT(row < mRows); ASSERT(column < mColumns); return mGrid[row][column]; } std::ostream& operator<<(std::ostream& os, const Grid& grid) { for (const auto& row : grid.GetGrid()) { for (const auto c : row) { os << (c ? '*' : '.'); } os << '\n'; } return os; } ItemArranger::ItemArranger() : mLogger{Logging::LogState::GetLogger("Gui::Inventory::ItemArranger")} { } }
1,786
C++
.cpp
79
17.253165
73
0.556342
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,449
inventoryScreen.cpp
xavieran_BaKGL/gui/inventory/inventoryScreen.cpp
#include "gui/inventory/inventoryScreen.hpp" #include "bak/haggle.hpp" #include "bak/inventoryItem.hpp" #include "bak/itemNumbers.hpp" #include "bak/itemInteractions.hpp" namespace Gui { InventoryScreen::InventoryScreen( IGuiManager& guiManager, const Backgrounds& backgrounds, const Icons& icons, const Font& font, BAK::GameState& gameState) : // Black background Widget{ RectTag{}, glm::vec2{0, 0}, glm::vec2{320, 200}, Color::black, true }, mGuiManager{guiManager}, mFont{font}, mIcons{icons}, mGameState{gameState}, mDialogScene{ []{}, []{}, [](const auto&){} }, mLayout{sLayoutFile}, mFrame{ ImageTag{}, backgrounds.GetSpriteSheet(), backgrounds.GetScreen(sBackground), glm::vec2{0}, GetPositionInfo().mDimensions, true }, mCharacters{}, mNextPage{ mLayout.GetWidgetLocation(mNextPageRequest), mLayout.GetWidgetDimensions(mNextPageRequest), std::get<Graphics::SpriteSheetIndex>(mIcons.GetButton(mNextPageButton)), std::get<Graphics::TextureIndex>(mIcons.GetButton(mNextPageButton)), std::get<Graphics::TextureIndex>(mIcons.GetPressedButton(mNextPageButton)), [this]{ AdvanceNextPage(); }, []{} }, mExit{ mLayout.GetWidgetLocation(mExitRequest), mLayout.GetWidgetDimensions(mExitRequest), std::get<Graphics::SpriteSheetIndex>(mIcons.GetButton(mExitButton)), std::get<Graphics::TextureIndex>(mIcons.GetButton(mExitButton)), std::get<Graphics::TextureIndex>(mIcons.GetPressedButton(mExitButton)), [this]{ mGuiManager.ExitInventory(); }, []{} }, mGoldDisplay{ mLayout.GetWidgetLocation(mGoldRequest), mLayout.GetWidgetDimensions(mGoldRequest), }, mContainerTypeDisplay{ [this](auto& item){ SplitStackBeforeMoveItemToContainer(item); }, mLayout.GetWidgetLocation(mContainerTypeRequest), mLayout.GetWidgetDimensions(mContainerTypeRequest), Graphics::SpriteSheetIndex{0}, Graphics::TextureIndex{0}, Graphics::TextureIndex{0}, [&]{ ShowContainer(); RefreshGui(); }, []{} }, mContainerScreen{ {11, 11}, {294, 121}, mIcons, mFont, [this](const auto& item){ ShowItemDescription(item); } }, mShopScreen{ {11, 11}, {294, 121}, mIcons, mFont, gameState, [this](const auto& item){ ShowItemDescription(item); } }, mDetails{ glm::vec2{}, glm::vec2{}, mIcons, mFont, [this]{ ExitDetails(); } }, mWeapon{ [this](auto& item){ MoveItemToEquipmentSlot(item, BAK::ItemType::Sword); }, glm::vec2{13, 15}, glm::vec2{80, 29}, mIcons, 130 }, mCrossbow{ [this](auto& item){ MoveItemToEquipmentSlot(item, BAK::ItemType::Crossbow); }, glm::vec2{13, 15 + 29}, glm::vec2{80, 29}, mIcons, 130 }, mArmor{ [this](auto& item){ MoveItemToEquipmentSlot(item, BAK::ItemType::Armor); }, glm::vec2{13, 15 + 29 * 2}, glm::vec2{80, 58}, mIcons, 131 }, mInventoryItems{}, mSplitStackDialog{ {128, 80}, mFont }, mSelectedCharacter{}, mDisplayContainer{false}, mItemSelectionMode{false}, mDisplayDetails{false}, mItemSelectionCallback{nullptr}, mSelectedItem{}, mContainer{nullptr}, mNeedRefresh{false}, mLogger{Logging::LogState::GetLogger("Gui::InventoryScreen")} { mCharacters.reserve(3); ClearContainer(); } void InventoryScreen::SetSelectedCharacter( BAK::ActiveCharIndex character) { mSelectedItem = std::nullopt; ShowCharacter(character); RefreshGui(); } void InventoryScreen::ClearContainer() { SetContainerTypeImage(11); mSelectedCharacter.reset(); mContainerScreen.SetContainer(&mGameState.GetParty().GetKeys()); mContainer = nullptr; mDisplayContainer = false; } void InventoryScreen::SetContainer(BAK::IContainer* container, BAK::EntityType entityType) { ASSERT(container != nullptr); mContainer = container; if (container->IsShop()) { SetContainerTypeImage(7); mShopScreen.SetContainer(container); } else { SetContainerTypeImage(BAK::GetContainerTypeFromEntityType(entityType)); mContainerScreen.SetContainer(container); } ShowContainer(); RefreshGui(); } /* Widget */ bool InventoryScreen::OnMouseEvent(const MouseEvent& event) { const bool handled = Widget::OnMouseEvent(event); if (std::holds_alternative<LeftMousePress>(event) && mItemSelectionMode) { HandleItemSelected(); mNeedRefresh = true; } // Don't refresh things until we have finished // processing this event. This prevents deleting // children that are about to handle it. if (mNeedRefresh // dirty hack :( // probably want some callback to force a refresh instead of this... || mItemSelectionMode) { RefreshGui(); mNeedRefresh = false; } return handled; } void InventoryScreen::PropagateUp(const DragEvent& event) { mLogger.Debug() << __FUNCTION__ << " ev: " << event << "\n"; if (std::holds_alternative<DragStarted>(event)) { auto& slot = *static_cast<InventorySlot*>( std::get<DragStarted>(event).mWidget); HighlightValidDrops(slot); // FIXME: Ideally this happens when an item is first clicked, // not just when dragged... mGameState.SetInventoryItem(slot.GetItem()); } else if (std::holds_alternative<DragEnded>(event)) { UnhighlightDrops(); const auto& pos = std::get<DragEnded>(event).mValue; mSplitStackDialog.SetCenter(pos); } bool handled = Widget::OnDragEvent(event); if (handled) return; } void InventoryScreen::RefreshGui() { ClearChildren(); UpdatePartyMembers(); UpdateGold(); if (mDisplayContainer) { if (mContainer && mContainer->IsShop()) { mShopScreen.RefreshGui(); } else { mContainerScreen.RefreshGui(); } } else UpdateInventoryContents(); AddChildren(); } void InventoryScreen::ExitDetails() { mDisplayDetails = false; mNeedRefresh = true; } void InventoryScreen::SetContainerTypeImage(unsigned containerType) { const auto [ss, ti, dims] = mIcons.GetInventoryMiscIcon(containerType); mContainerTypeDisplay.SetTexture(ss, ti); mContainerTypeDisplay.CenterImage(dims); } void InventoryScreen::ShowContainer() { mDisplayContainer = true; mSelectedCharacter.reset(); } void InventoryScreen::ShowCharacter(BAK::ActiveCharIndex character) { mDisplayContainer = false; mSelectedCharacter = character; mGameState.SetActiveCharacter(GetCharacter(character).mCharacterIndex); } void InventoryScreen::SetSelectionMode(bool mode, std::function<void(std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>>)>&& itemSelected) { SetSelectedCharacter(BAK::ActiveCharIndex{0}); mItemSelectionMode = mode; mItemSelectionCallback = std::move(itemSelected); } void InventoryScreen::TransferItemFromCharacterToCharacter( InventorySlot& slot, unsigned amount, BAK::ActiveCharIndex source, BAK::ActiveCharIndex dest) { auto item = slot.GetItem(); if (item.IsEquipped() && (item.IsItemType(BAK::ItemType::Sword) || item.IsItemType(BAK::ItemType::Staff))) { auto& srcC = GetCharacter(source); auto& dstC = GetCharacter(dest); if (dstC.CanSwapItem(item)) { ASSERT(srcC.IsSwordsman() == dstC.IsSwordsman()); const auto sourceItem = item; const auto destItemIt = dstC.GetInventory() .FindEquipped(item.GetObject().mType); const auto dstIndex = dstC.GetInventory().GetIndexFromIt(destItemIt); ASSERT(dstIndex); const auto destItem = *destItemIt; dstC.GetInventory().RemoveItem(*dstIndex); dstC.GiveItem(sourceItem); srcC.GetInventory().RemoveItem(slot.GetItemIndex()); srcC.GiveItem(destItem); srcC.CheckPostConditions(); dstC.CheckPostConditions(); AudioA::AudioManager::Get().PlaySound(DRAG_SOUND); } else { mGameState.SetActiveCharacter(srcC.mCharacterIndex); StartDialog(BAK::DialogSources::mCantDiscardOnlyWeapon); } return; } // Reduce item amount to chosen amount item.SetQuantity(amount); if (GetCharacter(dest).CanAddItem(item)) { GetCharacter(dest).GiveItem(item); if (item.IsStackable()) GetCharacter(source) .GetInventory() .RemoveItem(item); else GetCharacter(source) .GetInventory() .RemoveItem(slot.GetItemIndex()); AudioA::AudioManager::Get().PlaySound(DRAG_SOUND); } else { mGameState.SetDialogContext_7530(1); mGameState.SetActiveCharacter( GetCharacter(dest).mCharacterIndex); StartDialog(BAK::DialogSources::mContainerHasNoRoomForItem); } mLogger.Debug() << __FUNCTION__ << " Source: " << GetCharacter(source).GetInventory() << "\n" << "Dest: " << GetCharacter(dest).GetInventory() << "\n"; GetCharacter(source).CheckPostConditions(); } void InventoryScreen::TransferItemFromContainerToCharacter( InventorySlot& slot, BAK::ActiveCharIndex character, bool share, unsigned amount) { ASSERT(mContainer); auto item = slot.GetItem(); item.SetQuantity(amount); if (item.IsMoney() || item.IsKey()) { ASSERT(mDisplayContainer); mGameState.GetParty().AddItem(item); mContainer->GetInventory() .RemoveItem(slot.GetItemIndex()); AudioA::AudioManager::Get().PlaySound(DRAG_SOUND); } else if (GetCharacter(character).GiveItem(item)) { if (item.IsStackable()) mContainer->GetInventory().RemoveItem(item); else mContainer->GetInventory().RemoveItem(slot.GetItemIndex()); AudioA::AudioManager::Get().PlaySound(DRAG_SOUND); } else { } } void InventoryScreen::SellItem( InventorySlot& slot, BAK::ActiveCharIndex character) { ASSERT(mContainer); mGameState.GetParty().GainMoney( mShopScreen.GetBuyPrice(slot.GetItem())); mContainer->GiveItem(slot.GetItem()); GetCharacter(character).GetInventory() .RemoveItem(slot.GetItemIndex()); AudioA::AudioManager::Get().PlaySound(BUY_SOUND); mNeedRefresh = true; } void InventoryScreen::BuyItem( InventorySlot& slot, BAK::ActiveCharIndex character, bool share, unsigned amount) { ASSERT(mContainer); auto item = slot.GetItem(); item.SetQuantity(amount); const auto price = mShopScreen.GetSellPrice(slot.GetItemIndex(), amount); if (mGameState.GetParty().GetGold().mValue >= price.mValue) { ASSERT(GetCharacter(character).CanAddItem(item)); if (item.IsKey()) { ASSERT(mDisplayContainer); mGameState.GetParty().AddItem(item); } else { const auto result = GetCharacter(character).GiveItem(item); ASSERT(result); } mGameState.GetParty().LoseMoney(price); AudioA::AudioManager::Get().PlaySound(BUY_SOUND); } mNeedRefresh = true; } void InventoryScreen::TransferItemToShop( InventorySlot& slot, BAK::ActiveCharIndex character) { ASSERT(mContainer); const auto& item = slot.GetItem(); if (item.IsEquipped() && (item.IsItemType(BAK::ItemType::Sword) || item.IsItemType(BAK::ItemType::Staff))) { mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mCantDiscardOnlyWeapon); return; } if (mShopScreen.CanBuyItem(slot.GetItem())) { mGameState.SetItemValue(mShopScreen.GetBuyPrice(slot.GetItem())); mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mSellItemDialog); mDialogScene.SetDialogFinished( [this, &slot, character](const auto& choice) { ASSERT(choice); if (choice->mValue == BAK::Keywords::sAcceptIndex) { SellItem(slot, character); } mDialogScene.ResetDialogFinished(); }); } else if (false) // Shop has no room for item, what triggers this?? { mGameState.SetDialogContext_7530(0xa); mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mContainerHasNoRoomForItem); } else { StartDialog(BAK::DialogSources::mShopWontBuyItem); } } void InventoryScreen::TransferItemFromShopToCharacter( InventorySlot& slot, BAK::ActiveCharIndex character, bool share, unsigned amount) { ASSERT(mContainer); const auto itemIndex = slot.GetItem().GetItemIndex(); if ((itemIndex == BAK::sBrandy || itemIndex == BAK::sAle) && mGameState.GetParty().GetCharacter(character) .GetConditions().GetCondition(BAK::Condition::Drunk).Get() >= 100) { mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mCantBuyTooDrunk); return; } if (GetCharacter(character).CanAddItem(slot.GetItem())) { const auto sellPrice = mShopScreen.GetSellPrice(slot.GetItemIndex(), amount); if (sellPrice == BAK::sUnpurchaseablePrice) { return; } mGameState.SetItemValue(sellPrice); mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mBuyItemDialog); mDialogScene.SetDialogFinished( [this, &slot, character, share, amount](const auto& choice) { ASSERT(choice); if (choice->mValue == BAK::Keywords::sAcceptIndex) { BuyItem(slot, character, share, amount); mDialogScene.ResetDialogFinished(); } else if (choice->mValue == BAK::Keywords::sHaggleIndex) { HaggleItem(slot, character); } }); } else { mGameState.SetDialogContext_7530(0xb); mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mContainerHasNoRoomForItem); } } void InventoryScreen::HaggleItem( InventorySlot& slot, BAK::ActiveCharIndex character) { ASSERT(mContainer); mGameState.SetActiveCharacter(GetCharacter(character).mCharacterIndex); const auto& item = slot.GetItem(); if (item.GetItemIndex() == BAK::sScroll) { mDialogScene.ResetDialogFinished(); mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mCantHaggleScroll); return; } const auto result = BAK::Haggle::TryHaggle( mGameState.GetParty(), character, mContainer->GetShop(), item.GetItemIndex(), mShopScreen.GetDiscount(slot.GetItemIndex()).mValue); if (!result) { mDialogScene.ResetDialogFinished(); mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mFailHaggleItemUnavailable); mNeedRefresh = true; return; } const auto value = BAK::Royals{*result}; mShopScreen.SetItemDiscount(slot.GetItemIndex(), value); if (result && value == BAK::sUnpurchaseablePrice) { mDialogScene.ResetDialogFinished(); mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mFailHaggleItemUnavailable); mNeedRefresh = true; } else { mGameState.SetActiveCharacter( GetCharacter(character).mCharacterIndex); StartDialog(BAK::DialogSources::mSucceedHaggle); mDialogScene.SetDialogFinished( [this, &slot, character](const auto& choice) { SplitStackBeforeTransferItemToCharacter(slot, character); }); // So that the slot reference above is not invalid mNeedRefresh = false; } } void InventoryScreen::TransferItemToCharacter( InventorySlot& slot, BAK::ActiveCharIndex character, bool share, unsigned amount) { CheckExclusivity(); if (mSelectedCharacter && (*mSelectedCharacter != character)) { TransferItemFromCharacterToCharacter( slot, amount, *mSelectedCharacter, character); } else { if (mContainer->IsShop()) { const auto* shopItem = dynamic_cast<const ShopItemSlot*>(&slot); ASSERT(shopItem); if (shopItem->GetAvailable()) { TransferItemFromShopToCharacter( slot, character, share, amount); } } else { TransferItemFromContainerToCharacter( slot, character, share, amount); } } GetCharacter(character).CheckPostConditions(); mNeedRefresh = true; } void InventoryScreen::SplitStackBeforeTransferItemToCharacter( InventorySlot& slot, BAK::ActiveCharIndex character) { // Can't transfer items when displaying keys if (mDisplayContainer && mContainer == nullptr) return; // Can't transfer items to self if (mSelectedCharacter && (*mSelectedCharacter == character)) return; // Can't buy split stacks from shops if (slot.GetItem().IsStackable() && (slot.GetItem().GetQuantity() > 1) && (!mDisplayContainer || !mContainer || !mContainer->IsShop())) { const auto maxAmount = GetCharacter(character).GetInventory() .CanAddCharacter(slot.GetItem()); mSplitStackDialog.BeginSplitDialog( [&, character](bool share, unsigned amount){ mGuiManager.GetScreenStack().PopScreen(); TransferItemToCharacter(slot, character, share, amount); }, maxAmount); mGuiManager.GetScreenStack().PushScreen(&mSplitStackDialog); } else { TransferItemToCharacter( slot, character, false, slot.GetItem().GetQuantity()); } } void InventoryScreen::MoveItemToEquipmentSlot( InventorySlot& item, BAK::ItemType slot) { ASSERT(mSelectedCharacter); auto& character = GetCharacter(*mSelectedCharacter) ; mLogger.Debug() << "Move item to equipment slot: " << item.GetItem() << " " << BAK::ToString(slot) << "\n"; const auto& slotItem = item.GetItem(); const auto weaponSlotType = character.IsSwordsman() ? BAK::ItemType::Sword : BAK::ItemType::Staff; if (slot == BAK::ItemType::Sword && (slotItem.IsItemType(BAK::ItemType::Sword) || slotItem.IsItemType(BAK::ItemType::Staff))) { character.ApplyItemToSlot(item.GetItemIndex(), weaponSlotType); } else if (slot == BAK::ItemType::Crossbow && slotItem.IsItemType(BAK::ItemType::Crossbow)) { character.ApplyItemToSlot(item.GetItemIndex(), slot); } else if (slot == BAK::ItemType::Armor && slotItem.IsItemType(BAK::ItemType::Armor)) { character.ApplyItemToSlot(item.GetItemIndex(), slot); } else { UseItem(item, character.GetItemAtSlot(slot)); } GetCharacter(*mSelectedCharacter).CheckPostConditions(); mNeedRefresh = true; } void InventoryScreen::MoveItemToContainer( InventorySlot& slot, bool share, unsigned amount) { // Can't move an item in a container to the container... ASSERT(!mDisplayContainer); ASSERT(mSelectedCharacter); auto item = slot.GetItem(); item.SetQuantity(amount); if (item.IsEquipped() && (item.IsItemType(BAK::ItemType::Sword) || item.IsItemType(BAK::ItemType::Staff))) { mGameState.SetActiveCharacter( GetCharacter(*mSelectedCharacter).mCharacterIndex); StartDialog(BAK::DialogSources::mCantDiscardOnlyWeapon); return; } mLogger.Debug() << "Move item to container: " << item << "\n"; if (mContainer && mContainer->IsShop()) { ASSERT(mSelectedCharacter); TransferItemToShop( slot, *mSelectedCharacter); } else if (mContainer && mContainer->CanAddItem(item)) { mContainer->GetInventory().AddItem(item); if (item.IsStackable()) GetCharacter(*mSelectedCharacter).GetInventory() .RemoveItem(item); else GetCharacter(*mSelectedCharacter).GetInventory() .RemoveItem(slot.GetItemIndex()); } else { mGameState.SetActiveCharacter( GetCharacter(*mSelectedCharacter).mCharacterIndex); StartDialog(BAK::DialogSources::mContainerHasNoRoomForItem); } GetCharacter(*mSelectedCharacter).CheckPostConditions(); mNeedRefresh = true; } void InventoryScreen::SplitStackBeforeMoveItemToContainer(InventorySlot& slot) { if (mDisplayContainer || !mContainer) return; // Game doesn't split stacks when selling to shops if (slot.GetItem().IsStackable() && !mContainer->IsShop()) { const auto maxAmount = mContainer->GetInventory() .CanAddContainer(slot.GetItem()); mSplitStackDialog.BeginSplitDialog( [&](bool share, unsigned amount){ mGuiManager.GetScreenStack().PopScreen(); MoveItemToContainer(slot, share, amount); }, maxAmount); mGuiManager.GetScreenStack().PushScreen(&mSplitStackDialog); } else { MoveItemToContainer(slot, false, slot.GetItem().GetQuantity()); } } void InventoryScreen::UseItem(BAK::InventoryIndex inventoryIndex) { auto& character = GetCharacter(*mSelectedCharacter); auto& item = character.GetInventory().GetAtIndex(inventoryIndex); mLogger.Debug() << "UseItem: @" << inventoryIndex << " - " << item << "\n"; mGameState.SetActiveCharacter(character.mCharacterIndex); mGameState.SetInventoryItem(item); const auto result = BAK::UseItem(mGameState, character, inventoryIndex); if (result.mUseSound) { const auto [sound, times] = *result.mUseSound; for (unsigned i = 0; i < (times + 1); i++) { AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{sound}); } } if (result.mDialogContext) { mGameState.SetDialogContext_7530(*result.mDialogContext); } StartDialog(result.mDialog); mNeedRefresh = true; } void InventoryScreen::UseItem(InventorySlot& sourceItemSlot, BAK::InventoryIndex targetItemIndex) { ASSERT(mSelectedCharacter); auto& character = GetCharacter(*mSelectedCharacter) ; mGameState.SetInventoryItem(sourceItemSlot.GetItem()); mGameState.SetDialogContext_7530(sourceItemSlot.GetItem().GetItemIndex().mValue); mGameState.GetTextVariableStore().SetTextVariable(1, sourceItemSlot.GetItem().GetObject().mName); mGameState.SetActiveCharacter(character.mCharacterIndex); const auto result = BAK::ApplyItemTo(character, sourceItemSlot.GetItemIndex(), targetItemIndex); character.CheckPostConditions(); mNeedRefresh = true; if (result.mUseSound) { const auto [sound, times] = *result.mUseSound; for (unsigned i = 0; i < (times + 1); i++) { AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{sound}); } } StartDialog(result.mDialog); } void InventoryScreen::AdvanceNextPage() { mLogger.Debug() << __FUNCTION__ << "\n"; if (mDisplayContainer) { mShopScreen.AdvanceNextPage(); mNeedRefresh = true; } } void InventoryScreen::ShowItemDescription(const BAK::InventoryItem& item) { mDetails.AddItem(item, mGameState); mDisplayDetails = true; mNeedRefresh = true; } void InventoryScreen::HighlightValidDrops(const InventorySlot& slot) { const auto& party = mGameState.GetParty(); BAK::ActiveCharIndex person{0}; do { if (person != mSelectedCharacter) { const auto& item = slot.GetItem(); const auto mustSwap = item.IsEquipped() && (item.IsItemType(BAK::ItemType::Sword) || item.IsItemType(BAK::ItemType::Staff)); const auto giveable = GetCharacter(person) .CanAddItem(slot.GetItem()); const auto* shopItem = dynamic_cast<const ShopItemSlot*>(&slot); const auto inShopScreen = mDisplayContainer && mContainer && mContainer->IsShop(); if (inShopScreen) { ASSERT(shopItem); } const auto isAvailableShopItem = !mDisplayContainer || !inShopScreen || shopItem->GetAvailable(); if (isAvailableShopItem && ((mustSwap && (GetCharacter(person).CanSwapItem(item))) || (giveable && !mustSwap))) { mCharacters[person.mValue].SetColor(glm::vec4{.0, .05, .0, 1}); mCharacters[person.mValue].SetColorMode(Graphics::ColorMode::TintColor); } else { mCharacters[person.mValue].SetColor(glm::vec4{.05, .0, .0, 1}); mCharacters[person.mValue].SetColorMode(Graphics::ColorMode::TintColor); } } person = party.NextActiveCharacter(person); } while (person != BAK::ActiveCharIndex{0}); } void InventoryScreen::UnhighlightDrops() { const auto& party = mGameState.GetParty(); BAK::ActiveCharIndex person{0}; do { if (person != mSelectedCharacter) { mCharacters[person.mValue].SetColor(glm::vec4{.05, .05, .05, 1}); mCharacters[person.mValue].SetColorMode(Graphics::ColorMode::TintColor); } person = party.NextActiveCharacter(person); } while (person != BAK::ActiveCharIndex{0}); } void InventoryScreen::UpdatePartyMembers() { mCharacters.clear(); const auto& party = mGameState.GetParty(); BAK::ActiveCharIndex person{0}; do { const auto [spriteSheet, image, _] = mIcons.GetCharacterHead( party.GetCharacter(person).GetIndex().mValue); mCharacters.emplace_back( [this, character=person](InventorySlot& slot){ SplitStackBeforeTransferItemToCharacter(slot, character); }, [this, character=person]{ // Switch character SetSelectedCharacter(character); }, [this, character=person]{ mGuiManager.ShowCharacterPortrait(character); }, ImageTag{}, spriteSheet, image, mLayout.GetWidgetLocation(person.mValue), mLayout.GetWidgetDimensions(person.mValue), true ); if (person != mSelectedCharacter) { mCharacters[person.mValue].SetColor(glm::vec4{.05, .05, .05, 1}); mCharacters[person.mValue].SetColorMode(Graphics::ColorMode::TintColor); } person = party.NextActiveCharacter(person); } while (person != BAK::ActiveCharIndex{0}); } void InventoryScreen::UpdateGold() { const auto gold = mGameState.GetParty().GetGold(); const auto text = ToString(gold); const auto [textDims, _] = mGoldDisplay.SetText(mFont, text); // Justify text to the right const auto basePos = mLayout.GetWidgetLocation(mGoldRequest); const auto newPos = basePos + glm::vec2{ 3 + mLayout.GetWidgetDimensions(mGoldRequest).x - textDims.x, 4}; mGoldDisplay.SetPosition(newPos); } void InventoryScreen::UpdateInventoryContents() { CheckExclusivity(); const auto& inventory = std::invoke([&]() -> const BAK::Inventory& { if (mDisplayContainer) { ASSERT(mContainer == nullptr); return mGameState.GetParty().GetKeys().GetInventory(); } else { return GetCharacter(*mSelectedCharacter).GetInventory(); } }); mInventoryItems.clear(); mInventoryItems.reserve(inventory.GetNumberItems()); std::vector< std::pair< BAK::InventoryIndex, const BAK::InventoryItem*>> items{}; const auto numItems = inventory.GetItems().size(); items.reserve(numItems); unsigned index{0}; std::transform( inventory.GetItems().begin(), inventory.GetItems().end(), std::back_inserter(items), [&index](const auto& i) -> std::pair<BAK::InventoryIndex, const BAK::InventoryItem*> { return std::make_pair(BAK::InventoryIndex{index++}, &i); }); mCrossbow.ClearItem(); mArmor.ClearItem(); const auto slotDims = glm::vec2{40, 29}; // Add equipped items for (const auto& [invIndex, itemPtr] : items) { ASSERT(itemPtr); const auto& item = *itemPtr; const auto& [ss, ti, _] = mIcons.GetInventoryIcon(item.GetItemIndex().mValue); if ((item.IsItemType(BAK::ItemType::Sword) || item.IsItemType(BAK::ItemType::Staff)) && item.IsEquipped()) { auto scale = slotDims * glm::vec2{2, 1}; if (item.IsItemType(BAK::ItemType::Staff)) { scale = scale * glm::vec2{1, 2}; mWeapon.SetDimensions({80, 58}); } else { mWeapon.SetDimensions({80, 29}); } mWeapon.AddItem( glm::vec2{0}, scale, mFont, mIcons, invIndex, item, // Staffs are usable.. [this, inventoryIndex=invIndex]{ UseItem(inventoryIndex); }, [&]{ ShowItemDescription(item); }); continue; } if (item.IsItemType(BAK::ItemType::Crossbow) && item.IsEquipped()) { mCrossbow.AddItem( glm::vec2{0}, slotDims * glm::vec2{2, 1}, mFont, mIcons, invIndex, item, []{}, [&]{ ShowItemDescription(item); }); continue; } if (item.IsItemType(BAK::ItemType::Armor) && item.IsEquipped()) { mArmor.AddItem( glm::vec2{0}, slotDims * glm::vec2{2}, mFont, mIcons, invIndex, item, []{}, [&]{ ShowItemDescription(item); }); continue; } } // Don't display equipped items in the inventory items.erase( std::remove_if( items.begin(), items.end(), [&](const auto& i){ return inventory .GetAtIndex(std::get<BAK::InventoryIndex>(i)) .IsEquipped(); }), items.end()); // Sort by item size to ensure nice packing std::sort(items.begin(), items.end(), [](const auto& l, const auto& r) { return (std::get<1>(l)->GetObject().mImageSize > std::get<1>(r)->GetObject().mImageSize); }); const auto pos = glm::vec2{105, 11}; auto arranger = ItemArranger{}; arranger.PlaceItems( items.begin(), items.end(), 6, 4, slotDims, false, [&](auto invIndex, const auto& item, const auto itemPos, const auto dims) { mInventoryItems.emplace_back( [this, index=invIndex](auto& item){ this->UseItem(item, BAK::InventoryIndex{index}); }, itemPos + pos, dims, mFont, mIcons, invIndex, item, [this, inventoryIndex=invIndex]{ UseItem(inventoryIndex); }, [&]{ ShowItemDescription(item); }); }); } void InventoryScreen::AddChildren() { AddChildBack(&mFrame); if (mDisplayDetails) { AddChildBack(&mDetails); } AddChildBack(&mExit); AddChildBack(&mGoldDisplay); AddChildBack(&mContainerTypeDisplay); for (auto& character : mCharacters) { AddChildBack(&character); } if (mDisplayDetails) return; if (mSelectedCharacter && !mDisplayContainer) { AddChildBack(&mWeapon); if (GetCharacter(*mSelectedCharacter).IsSwordsman()) AddChildBack(&mCrossbow); AddChildBack(&mArmor); for (auto& item : mInventoryItems) AddChildBack(&item); } else if (mDisplayContainer) { if (mContainer && mContainer->IsShop()) { AddChildBack(&mShopScreen); if (mShopScreen.GetMaxPages() > 1) AddChildBack(&mNextPage); } else { AddChildBack(&mContainerScreen); } } } void InventoryScreen::CheckExclusivity() { ASSERT(bool{mSelectedCharacter} ^ mDisplayContainer); } void InventoryScreen::HandleItemSelected() { const auto checkItem = [&](auto& item) -> bool { if (item.IsSelected()) { mSelectedItem = item.GetItemIndex(); ASSERT(mItemSelectionCallback); mItemSelectionCallback(GetSelectedItem()); item.ResetSelected(); return true; } return false; }; for (auto& item : mInventoryItems) { if (checkItem(item)) return; } if (mWeapon.HasItem() && checkItem(mWeapon.GetInventorySlot())) return; if (mArmor.HasItem() && checkItem(mArmor.GetInventorySlot())) return; if (mCrossbow.HasItem() && checkItem(mCrossbow.GetInventorySlot())) return; } std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>> InventoryScreen::GetSelectedItem() const { if (mSelectedItem && mSelectedCharacter) { return std::make_pair(*mSelectedCharacter, *mSelectedItem); } return std::nullopt; } }
35,628
C++
.cpp
1,109
23.93147
154
0.613731
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,450
itemArrangerTest.cpp
xavieran_BaKGL/gui/inventory/test/itemArrangerTest.cpp
#include "gtest/gtest.h" #include "com/logger.hpp" #include "gui/inventory/itemArranger.hpp" #include <glm/glm.hpp> namespace Gui::Test { TEST(GridTest, FillWithSize1) { const auto& logger = Logging::LogState::GetLogger("GridTest"); const auto rows = 4; const auto columns = 5; auto grid = Grid{columns, rows}; unsigned row = 0; unsigned column = 0; for (unsigned i = 0; i < rows * columns; i++) { EXPECT_EQ( grid.GetNextSlot(), (glm::vec<2, unsigned>{column, row})); EXPECT_EQ(grid.Get(column, row), false); grid.Occupy(1, 1); EXPECT_EQ(grid.Get(column, row), true); if ((++row) == rows) { row = 0; column++; } } } } // namespace
783
C++
.cpp
29
20.793103
66
0.573351
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,456
assert.hpp
xavieran_BaKGL/com/assert.hpp
#pragma once #include <cassert> #ifdef NDEBUG #define ASSERT(x) {}; #else #define ASSERT(x) assert((x)); #endif
114
C++
.h
7
15
30
0.733333
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,457
ostreamMux.hpp
xavieran_BaKGL/com/ostreamMux.hpp
#pragma once #include <iostream> #include <vector> class OStreamMux : public std::streambuf { public: OStreamMux(); std::streamsize xsputn( const char_type* s, std::streamsize n) override; int_type overflow(int_type c) override; void AddStream(std::ostream* stream); void RemoveStream(std::ostream* stream); private: std::vector<std::ostream*> mOutputs; };
404
C++
.h
16
21.3125
44
0.703412
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,458
algorithm.hpp
xavieran_BaKGL/com/algorithm.hpp
#pragma once #include <algorithm> #include <cassert> template <typename T, typename It> It find_nth(It begin, It end, const T& needle, unsigned n) { assert(n > 0); do { begin = std::find(begin, end, needle); if (begin != end) begin++; else break; } while ((--n) > 0); return begin; }
331
C++
.h
15
17.933333
58
0.597444
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,459
ostream.hpp
xavieran_BaKGL/com/ostream.hpp
#pragma once #include "com/demangle.hpp" #include <array> #include <iomanip> #include <ostream> #include <optional> #include <vector> namespace std { template <typename T, std::size_t N> inline ostream& operator<<(ostream& os, const array<T, N>& a) { string sep = ""; for (unsigned i = 0; i < N; i++) { os << sep << setw(2) << setfill('0') << +a[i]; sep = " "; } return os; } template <typename T, typename U> inline ostream& operator<<(ostream& os, const pair<T, U>& p) { const auto& [a, b] = p; os << "(" << a << ", " << b << ")"; return os; } template <typename T> inline ostream& operator<<(ostream& os, const vector<T>& items) { string sep = ""; for (const auto& item : items) { os << sep << item; sep = ","; } return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const std::optional<T>& o) { if (o) os << "[[" << *o << "]]"; else os << "[[null]]"; return os; } template <typename T> concept NotScalar = (!std::is_scalar_v<T>); template <NotScalar T> std::ostream& operator<<(std::ostream& os, T* ptr) { os << com::demangle(typeid(ptr).name()) << "[" << std::hex << reinterpret_cast<int*>(ptr) << std::dec << "]"; return os; } }
1,289
C++
.h
55
20.072727
113
0.568627
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,460
bits.hpp
xavieran_BaKGL/com/bits.hpp
#pragma once template <typename T, typename U> bool CheckBitSet(T value, U flag) { const auto shifted = static_cast<T>(1) << static_cast<T>(flag); return (value & shifted) != 0; } template <typename T, typename U> T SetBit(T status, U flag, bool state) { if (state) return status | (static_cast<T>(1) << static_cast<T>(flag)); else return status & (~(static_cast<T>(1) << static_cast<T>(flag))); }
432
C++
.h
15
25.533333
71
0.643373
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,461
logger.hpp
xavieran_BaKGL/com/logger.hpp
#pragma once #include "com/ostreamMux.hpp" #include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <memory> #include <string> #include <vector> namespace Logging { enum class LogLevel { Spam, Debug, Info, Warn, Error, Fatal, Always }; std::string_view LevelToString(LogLevel level); std::string_view LevelToColor(LogLevel level); class Logger; class LogState { public: static void Disable(const std::string& logger) { sDisabledLoggers.emplace_back(logger); } static void SetLevel(LogLevel level) { sGlobalLogLevel = level; } static void SetLevel(std::string_view level) { if (level == LevelToString(Logging::LogLevel::Spam)) { Logging::LogState::SetLevel(Logging::LogLevel::Spam); } else if (level == LevelToString(Logging::LogLevel::Debug)) { Logging::LogState::SetLevel(Logging::LogLevel::Debug); } else if (level == LevelToString(Logging::LogLevel::Info)) { Logging::LogState::SetLevel(Logging::LogLevel::Info); } else if (level == LevelToString(Logging::LogLevel::Warn)) { Logging::LogState::SetLevel(Logging::LogLevel::Warn); } else if (level == LevelToString(Logging::LogLevel::Fatal)) { Logging::LogState::SetLevel(Logging::LogLevel::Fatal); } } static void SetLogTime(bool value) { sLogTime = value; } static void SetLogColor(bool value) { sLogColor = value; } static std::ostream& Log(LogLevel level, const std::string& loggerName) { const auto it = std::find( sDisabledLoggers.begin(), sDisabledLoggers.end(), loggerName); if (level >= sGlobalLogLevel && it == sDisabledLoggers.end()) return DoLog(level, loggerName); return nullStream; } static const Logger& GetLogger(const std::string& name){ return GetLoggerT<Logger>(name); } // FIXME: Clang complains about incomplete type in lambda template <typename T> static const T& GetLoggerT(const std::string& name) { const auto it = std::find_if(sLoggers.begin(), sLoggers.end(), [&name](const auto& l){ return l->GetName() == name; }); if (it == sLoggers.end()) { return *sLoggers.emplace_back(std::make_unique<T>(name)); } else { return **it; } } static void AddStream(std::ostream* stream) { sMux.AddStream(stream); } static void RemoveStream(std::ostream* stream) { sMux.RemoveStream(stream); } private: static std::ostream& DoLog(LogLevel level, const std::string& loggerName) { if (sLogTime) { const auto t = std::chrono::system_clock::now(); const auto time = std::chrono::system_clock::to_time_t(t); auto gmt_time = tm{}; #ifdef _MSC_VER gmtime_s(&gmt_time , &time); #else gmtime_r(&time, &gmt_time); #endif sOutput << std::put_time(&gmt_time, sTimeFormat.c_str()) << " "; } if (sLogColor) { sOutput << LevelToColor(level); } sOutput << LevelToString(level) << " [" << loggerName << "] "; if (sLogColor) { sOutput << "\033[0m "; } return sOutput; } static LogLevel sGlobalLogLevel; static std::string sTimeFormat; static bool sLogTime; static bool sLogColor; static std::vector<std::string> sEnabledLoggers; static std::vector<std::string> sDisabledLoggers; static std::vector<std::unique_ptr<Logger>> sLoggers; static OStreamMux sMux; static std::ostream sOutput; static std::ostream nullStream; }; class Logger { public: Logger(std::string name) : mName{name} { } std::ostream& Debug() const { return LogState::Log(LogLevel::Debug, mName); } template <typename T> void Debug(T&& log) const { Debug() << std::forward<T>(log) << std::endl; } std::ostream& Info() const { return LogState::Log(LogLevel::Info, mName); } std::ostream& Warn() const { return LogState::Log(LogLevel::Warn, mName); } std::ostream& Error() const { return LogState::Log(LogLevel::Error, mName); } std::ostream& Spam() const { return LogState::Log(LogLevel::Spam, mName); } std::ostream& Log(LogLevel level) const { return LogState::Log(level, mName); } const std::string& GetName() const { return mName; } private: std::string mName; }; std::ostream& LogFatal(const std::string& loggerName); std::ostream& LogError(const std::string& loggerName); std::ostream& LogWarn(const std::string& loggerName); std::ostream& LogInfo(const std::string& loggerName); std::ostream& LogDebug(const std::string& loggerName); std::ostream& LogSpam(const std::string& loggerName); }
5,129
C++
.h
183
21.612022
95
0.612132
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,462
string.hpp
xavieran_BaKGL/com/string.hpp
#pragma once #include <string> #include <string_view> #include <vector> std::string ToUpper(std::string_view str); std::vector<std::string> SplitString( std::string delim, std::string input);
203
C++
.h
8
23
42
0.739583
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,463
visit.hpp
xavieran_BaKGL/com/visit.hpp
#pragma once #include <variant> template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; template <typename T, typename F, typename ...Ts> decltype(auto) evaluate_if(std::variant<Ts...>& value, F&& function) { using ReturnType = decltype(function(std::declval<T>())); if constexpr (!std::is_same_v<void, ReturnType>) { if (std::holds_alternative<T>(value)) return function(std::get<T>(value)); else return ReturnType{}; } else { if (std::holds_alternative<T>(value)) function(std::get<T>(value)); } } template <typename T, typename F, typename ...Ts> decltype(auto) evaluate_if(const std::variant<Ts...>& value, F&& function) { using ReturnType = decltype(function(std::declval<T>())); if constexpr (!std::is_same_v<void, ReturnType>) { if (std::holds_alternative<T>(value)) return function(std::get<T>(value)); else return ReturnType{}; } else { if (std::holds_alternative<T>(value)) function(std::get<T>(value)); } }
1,187
C++
.h
43
22.302326
74
0.602283
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,464
demangle.hpp
xavieran_BaKGL/com/demangle.hpp
#pragma once #include <string> #ifndef _MSC_VER #include <cxxabi.h> #endif #include <memory> namespace com { std::string demangle(const char* mangled); }
159
C++
.h
9
16.111111
42
0.772414
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,465
saturatingNum.hpp
xavieran_BaKGL/com/saturatingNum.hpp
#pragma once #include <algorithm> #include <limits> #include <ostream> template < typename T, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()> class SaturatingNum { public: using SelfType = SaturatingNum<T, min, max>; static constexpr auto sMin = min; static constexpr auto sMax = max; constexpr explicit SaturatingNum(T value) noexcept : mValue{value} {} constexpr SaturatingNum(SelfType&&) noexcept = default; constexpr SaturatingNum& operator=(SelfType&&) noexcept = default; constexpr SaturatingNum(const SelfType&) noexcept = default; constexpr SaturatingNum& operator=(const SelfType&) noexcept = default; constexpr SaturatingNum() noexcept : mValue{} {} SelfType& operator=(int rhs) { mValue = static_cast<T>( std::clamp( rhs, static_cast<int>(min), static_cast<int>(max))); return *this; } SelfType& operator+=(int rhs) { const auto result = static_cast<int>(mValue) + rhs; *this = result; return *this; } SelfType& operator-=(int rhs) { return (*this) += (-rhs); } SelfType operator+(int rhs) const { SelfType result = static_cast<int>(mValue) + rhs; return result; } SelfType operator-(int rhs) const { return (*this) + (-rhs); } auto operator<=>(const SaturatingNum&) const = default; template <typename R> auto operator!=(R rhs) const { return mValue != rhs; } template <typename R> auto operator==(R rhs) const { return mValue == rhs; } T Get() const { return mValue; } private: T mValue; }; template <typename T, T min, T max> std::ostream& operator<<(std::ostream& os, const SaturatingNum<T, min, max>& s) { return os << +s.Get(); }
1,949
C++
.h
77
19.480519
79
0.604965
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,466
getopt.h
xavieran_BaKGL/com/getopt.h
/*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #pragma once /* * GNU-like getopt_long() and 4.4BSD getsubopt()/optreset extensions */ #define no_argument 0 #define required_argument 1 #define optional_argument 2 struct option { /* name of long option */ const char *name; /* * one of no_argument, required_argument, and optional_argument: * whether option takes an argument */ int has_arg; /* if not NULL, set *flag to val when option found */ int *flag; /* if flag not NULL, value to set *flag to; else return value */ int val; }; int getopt_long(int, char * const *, const char *, const struct option *, int *); int getopt_long_only(int, char * const *, const char *, const struct option *, int *); int getopt(int, char * const *, const char *); extern char *optarg; /* getopt(3) external variables */ extern int opterr; extern int optind; extern int optopt; extern int optreset;
2,858
C++
.h
65
41.969231
78
0.746055
xavieran/BaKGL
39
2
32
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,533,467
random.hpp
xavieran_BaKGL/com/random.hpp
#pragma once // Replace with something a bit better... unsigned GetRandomNumber(unsigned min, unsigned max);
111
C++
.h
3
35.333333
53
0.801887
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,469
strongType.hpp
xavieran_BaKGL/com/strongType.hpp
#pragma once #include "com/assert.hpp" #include <functional> #include <ostream> template <typename UnderlyingT, typename StrongTag> class StrongType { public: using UnderlyingType = UnderlyingT; using ConcreteType = StrongType<UnderlyingType, StrongTag>; constexpr StrongType() noexcept : mValue{} {} constexpr explicit StrongType(UnderlyingType v) noexcept : mValue{v} {} constexpr StrongType(const ConcreteType&) noexcept = default; constexpr ConcreteType& operator=(const ConcreteType&) noexcept = default; constexpr StrongType(ConcreteType&&) noexcept = default; constexpr ConcreteType& operator=(ConcreteType&&) noexcept = default; auto operator<=>(const ConcreteType&) const = default; UnderlyingType mValue; }; template <typename UnderlyingType, typename Tag> std::ostream& operator<<(std::ostream& os, const StrongType<UnderlyingType, Tag>& s) { return os << +s.mValue; } namespace std { template<typename U, typename Tag> struct hash<StrongType<U, Tag>> { std::size_t operator()(const StrongType<U, Tag>& t) const noexcept { return std::hash<U>{}(t.mValue); } }; } // [min, max) template < typename StrongT, typename StrongT::UnderlyingType min, typename StrongT::UnderlyingType max> class Bounded : public StrongT { public: using ConcreteType = Bounded<StrongT, min, max>; using typename StrongT::UnderlyingType; using StrongT::operator<=>; constexpr explicit Bounded(UnderlyingType v) noexcept : StrongT{v} { ASSERT(v >= min && v < max); } constexpr Bounded() noexcept : StrongT{min} {} constexpr Bounded(const ConcreteType&) noexcept = default; constexpr ConcreteType& operator=(const ConcreteType&) noexcept = default; constexpr Bounded(ConcreteType&&) noexcept = default; constexpr ConcreteType& operator=(ConcreteType&&) noexcept = default; }; namespace std { template < typename StrongT, typename StrongT::UnderlyingType min, typename StrongT::UnderlyingType max> struct hash<Bounded<StrongT, min, max>> { std::size_t operator()(const Bounded<StrongT, min, max>& t) const noexcept { return std::hash<StrongT>{}(t); } }; }
2,201
C++
.h
70
28.114286
84
0.736493
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,470
cpptrace.hpp
xavieran_BaKGL/com/cpptrace.hpp
#pragma once #ifdef ENABLE_CPPTRACE #include <cpptrace/cpptrace.hpp> #define CPPTRACE(OSTREAM, PREFIX) (OSTREAM) << (PREFIX) << " -- " << cpptrace::stacktrace::current() << "\n" #else #define CPPTRACE(OSTREAM, PREFIX) {} #endif
230
C++
.h
7
31.571429
108
0.710407
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,472
quad.hpp
xavieran_BaKGL/graphics/quad.hpp
#pragma once #include "com/logger.hpp" #include "graphics/glm.hpp" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/string_cast.hpp> #include <algorithm> #include <functional> #include <vector> namespace Graphics { class Quad { public: Quad( double width, double height, double maxDim, unsigned textureIndex) : Quad{ std::invoke([&](){ const auto top = 0; const auto bottom = 1; const auto left = 0; const auto right = 1; return std::vector<glm::vec3>{ {left, bottom, 0}, {left, top, 0}, {right, top, 0}, {left, bottom, 0}, {right, top, 0}, {right, bottom, 0}}; }), std::invoke([&](){ const auto maxU = width / maxDim; const auto maxV = height / maxDim; return std::vector<glm::vec3>{ {0, 0, textureIndex}, {0, maxV, textureIndex}, {maxU, maxV, textureIndex}, {0, 0, textureIndex}, {maxU, maxV, textureIndex}, {maxU, 0, textureIndex}}; }), {0, 1, 2, 3, 4, 5}} {} Quad( std::vector<glm::vec3> vertices, std::vector<glm::vec3> textureCoords, std::vector<unsigned> indices) : mVertices{vertices}, mTextureCoords{textureCoords}, mIndices{indices} { } Quad( glm::vec3 va, glm::vec3 vb, glm::vec3 vc, glm::vec3 vd) { const auto normal = glm::normalize( glm::cross( vd - va, vb - va)); for (unsigned i = 0; i < 6; i++) { mNormals.emplace_back(normal); mIndices.emplace_back(i); } // Triangle one mVertices.emplace_back(vd); mVertices.emplace_back(va); mVertices.emplace_back(vb); mVertices.emplace_back(vd); mVertices.emplace_back(vb); mVertices.emplace_back(vc); } std::size_t GetNumVertices() const { return mVertices.size(); } //private: std::vector<glm::vec3> mVertices; std::vector<glm::vec3> mNormals; std::vector<glm::vec3> mTextureCoords; std::vector<unsigned> mIndices; }; class QuadStorage { public: using OffsetAndLength = std::pair<unsigned, unsigned>; QuadStorage() : mOffset{0}, mVertices{}, mTextureCoords{}, mIndices{} { } OffsetAndLength AddObject( const Quad& obj) { auto length = obj.GetNumVertices(); auto& offsetAndLength = mObjects.emplace_back(mOffset, length); std::copy(obj.mVertices.begin(), obj.mVertices.end(), std::back_inserter(mVertices)); std::copy(obj.mTextureCoords.begin(), obj.mTextureCoords.end(), std::back_inserter(mTextureCoords)); std::copy(obj.mIndices.begin(), obj.mIndices.end(), std::back_inserter(mIndices)); mOffset += obj.GetNumVertices(); return offsetAndLength; } OffsetAndLength GetObject(std::size_t i) const { if (i >= mObjects.size()) { std::stringstream ss{}; ss << "Couldn't find: " << i; throw std::runtime_error(ss.str()); } return mObjects[i]; } std::size_t size() const { return mObjects.size(); } //private: unsigned long mOffset; std::vector<OffsetAndLength> mObjects; std::vector<glm::vec3> mVertices; std::vector<glm::vec3> mTextureCoords; std::vector<unsigned> mIndices; }; }
3,853
C++
.h
134
19.865672
108
0.529921
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,473
shaderProgram.hpp
xavieran_BaKGL/graphics/shaderProgram.hpp
#pragma once #include "com/logger.hpp" #include "com/strongType.hpp" #include <GL/glew.h> #include <glm/glm.hpp> #include <optional> #include <string> #include <vector> using Float = StrongType<float, struct FloatTag>; std::string ShaderTypeToString(GLenum shaderType); class ShaderProgramHandle { public: ShaderProgramHandle(GLuint handle); ShaderProgramHandle& operator=(const ShaderProgramHandle&) = delete; ShaderProgramHandle(const ShaderProgramHandle&) = delete; ShaderProgramHandle& operator=(ShaderProgramHandle&& other) noexcept; ShaderProgramHandle(ShaderProgramHandle&& other) noexcept; ~ShaderProgramHandle(); void UseProgramGL() const; static void SetUniform(GLuint id, const glm::mat4& value); static void SetUniform(GLuint id, int value); static void SetUniform(GLuint id, unsigned value); static void SetUniform(GLuint id, Float value); static void SetUniform(GLuint id, const glm::vec3& value); static void SetUniform(GLuint id, const glm::vec4& value); GLuint GetUniformLocation(const std::string& name) const; GLuint GetHandle() const; private: GLuint mHandle; }; class ShaderProgram { public: ShaderProgram( const std::string& vertexShader, const std::string& fragmentShader); ShaderProgram( const std::string& vertexShader, const std::optional<std::string>& geometryShader, const std::string& fragmentShader); ShaderProgramHandle Compile(); GLuint GetProgramId() const; private: GLuint CompileShader(const std::string& shader, GLenum shaderType); std::optional<std::string> FindFile(const std::string& shaderPath); std::string LoadFileContents(const std::string& path); std::string mVertexShader; std::optional<std::string> mGeometryShader; std::string mFragmentShader; GLuint mProgramId; const Logging::Logger& mLogger; };
1,928
C++
.h
53
31.924528
73
0.750542
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,474
guiTypes.hpp
xavieran_BaKGL/graphics/guiTypes.hpp
#pragma once #include "graphics/types.hpp" #include <glm/glm.hpp> #include <ostream> namespace Graphics { enum class DrawMode { Rect = 0, Sprite = 1, ClipRegion = 2, }; enum class ColorMode { // Use the color from the given texture Texture = 0, // Use a solid color SolidColor = 1, // Tint the texture this color (respects texture alpha) TintColor = 2 , // Replace the textures color with this, respecting the texture alpha ReplaceColor = 3 }; struct DrawInfo { Graphics::DrawMode mDrawMode; Graphics::SpriteSheetIndex mSpriteSheet; Graphics::TextureIndex mTexture; Graphics::ColorMode mColorMode; glm::vec4 mColor; }; struct PositionInfo { glm::vec2 mPosition; glm::vec2 mDimensions; // actually more like scale than dim..... float mRotation; bool mChildrenRelative; }; std::ostream& operator<<(std::ostream& os, const ColorMode&); std::ostream& operator<<(std::ostream& os, const DrawMode&); std::ostream& operator<<(std::ostream& os, const DrawInfo&); std::ostream& operator<<(std::ostream& os, const PositionInfo&); }
1,115
C++
.h
42
23.333333
73
0.71442
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,475
renderer.hpp
xavieran_BaKGL/graphics/renderer.hpp
#pragma once #include "graphics/meshObject.hpp" #include "graphics/opengl.hpp" #include "graphics/framebuffer.hpp" #include "graphics/shaderProgram.hpp" namespace Graphics { struct Light { glm::vec3 mDirection; glm::vec3 mAmbientColor; glm::vec3 mDiffuseColor; glm::vec3 mSpecularColor; float mFogStrength; glm::vec3 mFogColor; }; class Renderer { static constexpr auto sDrawDistance = 128000; static constexpr auto sClickDistance = 16000; public: Renderer( float screenWidth, float screenHeight, unsigned depthMapWidth, unsigned depthMapHeight) : mModelShader{std::invoke([]{ auto shader = ShaderProgram{ "directional.vert.glsl", "directional.frag.glsl"}; return shader.Compile(); })}, mPickShader{std::invoke([]{ auto shader = ShaderProgram{ "pick.vert.glsl", "pick.frag.glsl"}; return shader.Compile(); })}, mShadowMapShader{std::invoke([]{ auto shader = ShaderProgram{ "shadowMap.vert.glsl", "shadowMap.frag.glsl" }; return shader.Compile(); })}, mNormalShader{std::invoke([]{ auto shader = ShaderProgram{ "see_norm.vert.glsl", "see_norm.geom.glsl", "see_norm.frag.glsl" }; return shader.Compile(); })}, mVertexArrayObject{}, mGLBuffers{}, mTextureBuffer{GL_TEXTURE_2D_ARRAY}, mPickFB{}, mPickTexture{GL_TEXTURE_2D}, mPickDepth{GL_TEXTURE_2D}, mDepthMapDims{depthMapWidth, depthMapHeight}, mDepthFB1{}, mDepthFB2{}, mDepthBuffer1{GL_TEXTURE_2D}, mDepthBuffer2{GL_TEXTURE_2D}, mScreenDims{screenWidth, screenHeight}, mUseDepthBuffer1{false} { mPickTexture.MakePickBuffer(screenWidth, screenHeight); mPickDepth.MakeDepthBuffer(screenWidth, screenHeight); mPickFB.AttachTexture(mPickTexture); mPickFB.AttachDepthTexture(mPickDepth, false); mDepthBuffer1.MakeDepthBuffer( mDepthMapDims.x, mDepthMapDims.y); mDepthFB1.AttachDepthTexture(mDepthBuffer1, true); mDepthBuffer2.MakeDepthBuffer( mDepthMapDims.x, mDepthMapDims.y); mDepthFB2.AttachDepthTexture(mDepthBuffer2, true); } template <typename TextureStoreT> void LoadData( const MeshObjectStorage& objectStore, const TextureStoreT& textureStore) { // FIXME Issue 48: Need to do destruct and restruct all the buffers // when we load new data... mVertexArrayObject.BindGL(); mGLBuffers.AddStaticArrayBuffer<glm::vec3>("vertex", GLLocation{0}); mGLBuffers.AddStaticArrayBuffer<glm::vec3>("normal", GLLocation{1}); mGLBuffers.AddStaticArrayBuffer<glm::vec4>("color", GLLocation{2}); mGLBuffers.AddStaticArrayBuffer<glm::vec3>("textureCoord", GLLocation{3}); mGLBuffers.AddStaticArrayBuffer<glm::vec1>("textureBlend", GLLocation{4}); mGLBuffers.AddElementBuffer("elements"); mGLBuffers.LoadBufferDataGL("vertex", objectStore.mVertices); mGLBuffers.LoadBufferDataGL("normal", objectStore.mNormals); mGLBuffers.LoadBufferDataGL("color", objectStore.mColors); mGLBuffers.LoadBufferDataGL("textureCoord", objectStore.mTextureCoords); mGLBuffers.LoadBufferDataGL("textureBlend", objectStore.mTextureBlends); mGLBuffers.LoadBufferDataGL("elements", objectStore.mIndices); mGLBuffers.BindArraysGL(); mTextureBuffer.LoadTexturesGL( textureStore.GetTextures(), textureStore.GetMaxDim()); } template <typename Renderables, typename Camera> void DrawForPicking( const Renderables& renderables, const Renderables& sprites, const Camera& camera) { mVertexArrayObject.BindGL(); glActiveTexture(GL_TEXTURE0); mTextureBuffer.BindGL(); mPickFB.BindGL(); glViewport(0, 0, mScreenDims.x, mScreenDims.y); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); auto& shader = mPickShader; shader.UseProgramGL(); shader.SetUniform(shader.GetUniformLocation("texture0"), 0); const auto mvpMatrixId = shader.GetUniformLocation("MVP"); const auto entityIdId = shader.GetUniformLocation("entityId"); const auto& viewMatrix = camera.GetViewMatrix(); glm::mat4 MVP; const auto RenderItem = [&](const auto& item) { if (glm::distance(camera.GetPosition(), item.GetLocation()) > sClickDistance) return; const auto [offset, length] = item.GetObject(); const auto& modelMatrix = item.GetModelMatrix(); MVP = camera.GetProjectionMatrix() * viewMatrix * modelMatrix; shader.SetUniform(mvpMatrixId, MVP); shader.SetUniform(entityIdId, item.GetId().mValue); glDrawElementsBaseVertex( GL_TRIANGLES, length, GL_UNSIGNED_INT, (void*) (offset * sizeof(GLuint)), offset ); }; for (const auto& item : renderables) { RenderItem(item); } for (const auto& item : sprites) { RenderItem(item); } mPickFB.UnbindGL(); glFinish(); } template <typename Renderables, typename Camera> void DrawWithShadow( const Renderables& renderables, const Light& light, const Camera& lightCamera, const Camera& camera) { mVertexArrayObject.BindGL(); glActiveTexture(GL_TEXTURE0); mTextureBuffer.BindGL(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, mUseDepthBuffer1 ? mDepthBuffer1.GetId() : mDepthBuffer2.GetId()); auto& shader = mModelShader; shader.UseProgramGL(); shader.SetUniform(shader.GetUniformLocation("texture0"), 0); shader.SetUniform(shader.GetUniformLocation("shadowMap"), 1); shader.SetUniform(shader.GetUniformLocation("fogStrength"), Float{light.mFogStrength}); shader.SetUniform(shader.GetUniformLocation("fogColor"), light.mFogColor); shader.SetUniform(shader.GetUniformLocation("light.mDirection"), light.mDirection); shader.SetUniform(shader.GetUniformLocation("light.mAmbientColor"), light.mAmbientColor); shader.SetUniform(shader.GetUniformLocation("light.mDiffuseColor"), light.mDiffuseColor); shader.SetUniform(shader.GetUniformLocation("light.mSpecularColor"), light.mSpecularColor); shader.SetUniform( shader.GetUniformLocation("lightSpaceMatrix"), lightCamera.GetProjectionMatrix() * lightCamera.GetViewMatrix()); shader.SetUniform(shader.GetUniformLocation("cameraPosition_worldspace"), camera.GetNormalisedPosition()); const auto mvpMatrixId = shader.GetUniformLocation("MVP"); const auto modelMatrixId = shader.GetUniformLocation("M"); const auto viewMatrixId = shader.GetUniformLocation("V"); const auto& viewMatrix = camera.GetViewMatrix(); glm::mat4 MVP; for (const auto& item : renderables) { if (glm::distance(camera.GetPosition(), item.GetLocation()) > sDrawDistance) continue; const auto [offset, length] = item.GetObject(); const auto& modelMatrix = item.GetModelMatrix(); MVP = camera.GetProjectionMatrix() * viewMatrix * modelMatrix; shader.SetUniform(mvpMatrixId, MVP); shader.SetUniform(modelMatrixId, modelMatrix); shader.SetUniform(viewMatrixId, viewMatrix); glDrawElementsBaseVertex( GL_TRIANGLES, length, GL_UNSIGNED_INT, (void*) (offset * sizeof(GLuint)), offset ); } } unsigned GetClickedEntity(glm::vec2 click) { mPickFB.BindGL(); glReadBuffer(GL_COLOR_ATTACHMENT0); glm::vec4 data{}; auto newClick = click; newClick.y = mScreenDims.y - click.y; glReadPixels(newClick.x, newClick.y, 1, 1, GL_RGBA, GL_FLOAT, &data); mPickFB.UnbindGL(); const auto entityIndex = static_cast<unsigned>(data.r) | (static_cast<unsigned>(data.g) << 8) | (static_cast<unsigned>(data.b) << 16) | (static_cast<unsigned>(data.a) << 24); return entityIndex; } void BeginDepthMapDraw() { if (mUseDepthBuffer1) { mDepthFB1.BindGL(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, mDepthMapDims.x, mDepthMapDims.y); } else { mDepthFB2.BindGL(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, mDepthMapDims.x, mDepthMapDims.y); } } void EndDepthMapDraw() { if (mUseDepthBuffer1) { mDepthFB1.UnbindGL(); } else { mDepthFB2.UnbindGL(); } mUseDepthBuffer1 = !mUseDepthBuffer1; } template <typename Renderables, typename Camera> void DrawDepthMap( const Renderables& renderables, const Camera& lightCamera) { mVertexArrayObject.BindGL(); auto& shader = mShadowMapShader; shader.UseProgramGL(); // Required so we get correct depth for sprites with alpha glActiveTexture(GL_TEXTURE0); mTextureBuffer.BindGL(); shader.SetUniform(shader.GetUniformLocation("texture0"), 0); const auto lightSpaceMatrixId = shader.GetUniformLocation("lightSpaceMatrix"); shader.SetUniform( lightSpaceMatrixId, lightCamera.GetProjectionMatrix() * lightCamera.GetViewMatrix()); const auto modelMatrixId = shader.GetUniformLocation("M"); for (const auto& item : renderables) { if (glm::distance(lightCamera.GetPosition(), item.GetLocation()) > sDrawDistance) continue; const auto [offset, length] = item.GetObject(); const auto& modelMatrix = item.GetModelMatrix(); shader.SetUniform(modelMatrixId, modelMatrix); glDrawElementsBaseVertex( GL_TRIANGLES, length, GL_UNSIGNED_INT, (void*) (offset * sizeof(GLuint)), offset ); } } //private: ShaderProgramHandle mModelShader; ShaderProgramHandle mPickShader; ShaderProgramHandle mShadowMapShader; ShaderProgramHandle mNormalShader; VertexArrayObject mVertexArrayObject; GLBuffers mGLBuffers; TextureBuffer mTextureBuffer; FrameBuffer mPickFB; TextureBuffer mPickTexture; TextureBuffer mPickDepth; glm::uvec2 mDepthMapDims; FrameBuffer mDepthFB1; FrameBuffer mDepthFB2; TextureBuffer mDepthBuffer1; TextureBuffer mDepthBuffer2; glm::vec2 mScreenDims; bool mUseDepthBuffer1; }; }
11,421
C++
.h
298
28.828859
114
0.633662
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,476
texture.hpp
xavieran_BaKGL/graphics/texture.hpp
#pragma once #include "com/assert.hpp" #include <glm/glm.hpp> #include <string> #include <vector> namespace Graphics { class Texture { public: using TextureType = std::vector<glm::vec4>; Texture( const TextureType& texture, unsigned width, unsigned height) : mTexture{texture}, mWidth{width}, mHeight{height} {} Texture( unsigned width, unsigned height) : mTexture{width * height, glm::vec4{0}}, mWidth{width}, mHeight{height} { } // Get pixel wrapping access const auto& GetPixel(unsigned x, unsigned y) const { return mTexture[ (x % GetWidth()) + (y % GetHeight()) * GetWidth()]; } void SetPixel(unsigned x, unsigned y, glm::vec4 color) { mTexture[ (x % GetWidth()) + (y % GetHeight()) * GetWidth()] = color; } void Invert() { for (unsigned x = 0; x < GetWidth(); x++) for (unsigned y = 0; y < (GetHeight() / 2); y++) std::swap( mTexture[x + (y * GetWidth())], mTexture[x + ((GetHeight() - 1 - y) * GetWidth())]); } Texture GetRegion(glm::ivec2 pos, glm::uvec2 dims) const { auto newTexture = Texture{dims.x, dims.y}; for (unsigned x = 0; x < dims.x; x++) { for (unsigned y = 0; y < dims.y; y++) { newTexture.SetPixel(x, y, GetPixel(pos.x + x, pos.y + y)); } } return newTexture; } unsigned GetWidth() const { return mWidth; } unsigned GetHeight() const { return mHeight; } glm::ivec2 GetDims() const { return glm::ivec2(GetWidth(), GetHeight()); } const TextureType& GetTexture() const { return mTexture; } TextureType& GetTexture() { return mTexture; } private: TextureType mTexture; unsigned mWidth; unsigned mHeight; }; class TextureStore { public: TextureStore() : mTextures{}, mMaxHeight{0}, mMaxWidth{0}, mMaxDim{0} {} void AddTexture(const Texture& texture) { if (texture.GetHeight() > mMaxHeight) mMaxHeight = texture.GetHeight(); if (texture.GetWidth() > mMaxWidth) mMaxWidth = texture.GetWidth(); mMaxDim = std::max(mMaxHeight, mMaxWidth); mTextures.emplace_back(texture); } const std::vector<Texture>& GetTextures() const { return mTextures; } const Texture& GetTexture(std::size_t i) const { ASSERT(i < mTextures.size()); return mTextures[i]; } Texture& GetTexture(std::size_t i) { ASSERT(i < mTextures.size()); return mTextures[i]; } unsigned GetMaxDim() const { return mMaxDim; } unsigned GetMaxHeight() const { return mMaxHeight; } unsigned GetMaxWidth() const { return mMaxWidth; } std::size_t size() const { return mTextures.size(); } private: std::vector<Texture> mTextures; unsigned mMaxHeight; unsigned mMaxWidth; unsigned mMaxDim; }; }
3,075
C++
.h
104
22.653846
105
0.585085
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,477
framebuffer.hpp
xavieran_BaKGL/graphics/framebuffer.hpp
#pragma once #include "graphics/opengl.hpp" #include <GL/glew.h> namespace Graphics { class FrameBuffer { public: FrameBuffer(); FrameBuffer(const FrameBuffer&) = delete; FrameBuffer& operator=(const FrameBuffer&) = delete; FrameBuffer(FrameBuffer&& other) noexcept; FrameBuffer& operator=(FrameBuffer&& other) noexcept; ~FrameBuffer(); void BindGL() const; void UnbindGL() const; void AttachDepthTexture(const Graphics::TextureBuffer&, bool clearDrawBuffer) const; void AttachTexture(const Graphics::TextureBuffer&) const; private: static GLuint GenFrameBufferGL(); GLuint mFrameBufferId; bool mActive; }; }
672
C++
.h
23
25.478261
88
0.750784
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,478
types.hpp
xavieran_BaKGL/graphics/types.hpp
#pragma once #include "com/strongType.hpp" namespace Graphics { using SpriteSheetIndex = StrongType<unsigned, struct SpriteSheetIndexTag>; using TextureIndex = StrongType<unsigned, struct TextureIndexTag>; using MeshOffset = unsigned; using MeshLength = unsigned; }
270
C++
.h
8
32.25
74
0.837209
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,479
cube.hpp
xavieran_BaKGL/graphics/cube.hpp
#pragma once #include "graphics/meshObject.hpp" #include "graphics/quad.hpp" #include "com/assert.hpp" #include <glm/glm.hpp> #include <vector> namespace Graphics { // ______ // /| /| // / | / | // /______/ / // | | / // |______|/ // // This will be centered around it's x and y dimensions // with its bottom face on the ground plane (0) // class Cuboid { public: Cuboid( unsigned x_dim, unsigned y_dim, unsigned z_dim) : mQuads{} { const auto xd = x_dim / 2.; const auto yd = y_dim / 2.; const auto a = glm::vec3{-xd, 0, yd}; const auto b = glm::vec3{xd, 0, yd}; const auto c = glm::vec3{xd, 0, -yd}; const auto d = glm::vec3{-xd, 0, -yd}; const auto zd = glm::vec3{0, z_dim, 0}; const auto e = a + zd; const auto f = b + zd; const auto g = c + zd; const auto h = d + zd; // 4 Sides to the quad... mQuads.emplace_back(a, e, h, d); mQuads.emplace_back(a, e, f, b); mQuads.emplace_back(b, f, g, c); mQuads.emplace_back(d, h, g, c); mQuads.emplace_back(h, g, f, e); } MeshObject ToMeshObject(glm::vec4 color) const { auto vertices = std::vector<glm::vec3>{}; auto normals = std::vector<glm::vec3>{}; auto indices = std::vector<unsigned>{}; unsigned off = 0; for (const auto& q : mQuads) { ASSERT(q.mVertices.size() == q.mNormals.size()); ASSERT(q.mVertices.size() == q.mIndices.size()); for (unsigned i = 0; i < q.GetNumVertices(); i++) { vertices.emplace_back(q.mVertices[i]); normals.emplace_back(q.mNormals[i]); indices.emplace_back(q.mIndices[i] + off); } off += q.GetNumVertices(); } const auto textureCoords = std::vector<glm::vec3>( vertices.size(), glm::vec3{0}); const auto colors = std::vector<glm::vec4>( vertices.size(), color); const auto textureBlends = std::vector<float>( vertices.size(), 0.0f); return MeshObject{ vertices, normals, colors, textureCoords, textureBlends, indices }; } std::vector<Quad> mQuads; }; }
2,389
C++
.h
81
21.864198
61
0.515679
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,480
glfw.hpp
xavieran_BaKGL/graphics/glfw.hpp
#pragma once #include <GL/glew.h> #include <GLFW/glfw3.h> #include <string_view> #include <memory> namespace Graphics { struct DestroyGlfwWindow { void operator()(GLFWwindow* window) { glfwDestroyWindow(window); glfwTerminate(); } }; std::unique_ptr<GLFWwindow, DestroyGlfwWindow> MakeGlfwWindow( unsigned height, unsigned width, std::string_view title); }
404
C++
.h
19
17.789474
62
0.722222
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,481
sprites.hpp
xavieran_BaKGL/graphics/sprites.hpp
#pragma once #include "graphics/quad.hpp" #include "graphics/opengl.hpp" #include "graphics/texture.hpp" #include "graphics/types.hpp" #include "com/logger.hpp" #include <GL/glew.h> #include <memory> #include <optional> #include <unordered_map> #include <vector> namespace Graphics { class Sprites { public: Sprites() noexcept; Sprites(const Sprites&) = delete; Sprites& operator=(const Sprites&) = delete; Sprites(Sprites&& other) noexcept; Sprites& operator=(Sprites&& other) noexcept; void BindGL() const; void UnbindGL() const; void LoadTexturesGL(const TextureStore& textures); std::size_t size(); auto GetRect() const { return mObjects.GetObject(0); } auto Get(unsigned i) const { return mObjects.GetObject(i + mNonSpriteObjects); } glm::vec2 GetDimensions(unsigned i) const; //private: std::size_t mNonSpriteObjects; VertexArrayObject mVertexArray; GLBuffers mBuffers; TextureBuffer mTextureBuffer; QuadStorage mObjects; std::vector<glm::vec2> mSpriteDimensions; }; class SpriteManager; struct TemporarySpriteHandle { SpriteManager* mManager; SpriteSheetIndex mSpriteSheet; }; struct DestroySpriteSheet { void operator()(TemporarySpriteHandle* handle); }; class SpriteManager { public: SpriteManager(); SpriteManager(const SpriteManager&) = delete; SpriteManager& operator=(const SpriteManager&) = delete; SpriteManager(SpriteManager&& other) = delete; SpriteManager& operator=(SpriteManager&& other) = delete; using TemporarySpriteSheet = std::unique_ptr<TemporarySpriteHandle, DestroySpriteSheet>; SpriteSheetIndex AddSpriteSheet(); TemporarySpriteSheet AddTemporarySpriteSheet(); void RemoveSpriteSheet(SpriteSheetIndex); void DeactivateSpriteSheet(); void ActivateSpriteSheet(SpriteSheetIndex spriteSheet); Sprites& GetSpriteSheet(SpriteSheetIndex spriteSheet); private: SpriteSheetIndex NextSpriteSheet(); std::unordered_map<SpriteSheetIndex, Sprites> mSprites; unsigned mNextSpriteSheet; std::optional<SpriteSheetIndex> mActiveSpriteSheet; }; }
2,175
C++
.h
73
25.835616
93
0.75847
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,482
meshObject.hpp
xavieran_BaKGL/graphics/meshObject.hpp
#pragma once #include "com/logger.hpp" #include "graphics/sphere.hpp" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "graphics/glm.hpp" #include <algorithm> #include <vector> #include <unordered_map> namespace Graphics { class MeshObject { public: MeshObject( std::vector<glm::vec3> vertices, std::vector<glm::vec3> normals, std::vector<glm::vec4> colors, std::vector<glm::vec3> textureCoords, std::vector<float> textureBlends, std::vector<unsigned> indices) : mVertices{vertices}, mNormals{normals}, mColors{colors}, mTextureCoords{textureCoords}, mTextureBlends{textureBlends}, mIndices{indices} { } unsigned long GetNumVertices() const { return mVertices.size(); } //private: std::vector<glm::vec3> mVertices; std::vector<glm::vec3> mNormals; std::vector<glm::vec4> mColors; std::vector<glm::vec3> mTextureCoords; // Ratio of texture to material color // - solution to having textured and // non-textured objects (should I use diff shaders?) std::vector<float> mTextureBlends; std::vector<unsigned> mIndices; }; MeshObject SphereToMeshObject(const Sphere& sphere, glm::vec4 color); class MeshObjectStorage { public: using OffsetAndLength = std::pair<unsigned, unsigned>; MeshObjectStorage() : mOffset{0}, mVertices{}, mNormals{}, mColors{}, mTextureCoords{}, mTextureBlends{}, mIndices{} { } OffsetAndLength AddObject( const std::string& id, const MeshObject& obj) { if (mObjects.find(id) != mObjects.end()) { mLog.Debug() << id << " already loaded" << std::endl; return GetObject(id); } auto length = obj.GetNumVertices(); const auto offsetAndLength = std::make_pair(mOffset, length); mObjects.emplace(id, offsetAndLength); std::copy(obj.mVertices.begin(), obj.mVertices.end(), std::back_inserter(mVertices)); std::copy(obj.mNormals.begin(), obj.mNormals.end(), std::back_inserter(mNormals)); std::copy(obj.mColors.begin(), obj.mColors.end(), std::back_inserter(mColors)); std::copy(obj.mTextureCoords.begin(), obj.mTextureCoords.end(), std::back_inserter(mTextureCoords)); std::copy(obj.mTextureBlends.begin(), obj.mTextureBlends.end(), std::back_inserter(mTextureBlends)); std::copy(obj.mIndices.begin(), obj.mIndices.end(), std::back_inserter(mIndices)); mLog.Debug() << __FUNCTION__ << " " << id << " off: " << mOffset << " len: " << length << std::endl; mOffset += obj.GetNumVertices(); return offsetAndLength; } OffsetAndLength GetObject(const std::string& id) { if (mObjects.find(id) == mObjects.end()) { std::stringstream ss{}; ss << "Couldn't find: " << id; throw std::runtime_error(ss.str()); } return mObjects.find(id)->second; } //private: unsigned long mOffset; std::unordered_map<std::string, OffsetAndLength> mObjects; std::vector<glm::vec3> mVertices; std::vector<glm::vec3> mNormals; std::vector<glm::vec4> mColors; std::vector<glm::vec3> mTextureCoords; std::vector<float> mTextureBlends; std::vector<unsigned> mIndices; const Logging::Logger& mLog{ Logging::LogState::GetLogger("MeshObjectStore")}; }; }
3,534
C++
.h
106
26.849057
108
0.636203
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,483
opengl.hpp
xavieran_BaKGL/graphics/opengl.hpp
#pragma once #include "graphics/texture.hpp" #include "com/logger.hpp" #include "com/strongType.hpp" #include <GL/glew.h> namespace Graphics { using GLLocation = StrongType<unsigned, struct GLLocationTag>; using GLElems = StrongType<unsigned, struct GLElemsTag>; using GLDataType = StrongType<unsigned, struct GLDataTypeTag>; using GLBufferId = StrongType<unsigned, struct GLBufferIdTag>; static constexpr auto GLNullLocation = GLLocation{static_cast<unsigned>(-1)}; enum class GLBindPoint { ArrayBuffer, ElementArrayBuffer, TextureBuffer }; GLenum ToGlEnum(GLBindPoint); enum class GLUpdateType { StaticDraw, DynamicDraw }; GLenum ToGlEnum(GLUpdateType); struct GLBuffer { // Location in the shader GLLocation mLocation; // Elements per object (e.g. color = 4 floats) GLElems mElems; // GLBindPoint (ARRAY, ELEMENT_ARRAY, etc) GLBindPoint mGLBindPoint; // e.g. GL_FLOAT, or GL_UNSIGNED GLDataType mDataType; // e.g. StaticDraw or DynamicDraw GLUpdateType mUpdateType; // GL assigned buffer id GLBufferId mBuffer; }; class VertexArrayObject { public: VertexArrayObject(); VertexArrayObject(const VertexArrayObject&) = delete; VertexArrayObject& operator=(const VertexArrayObject&) = delete; VertexArrayObject(VertexArrayObject&& other) noexcept; VertexArrayObject& operator=(VertexArrayObject&& other) noexcept; ~VertexArrayObject(); void BindGL() const; void UnbindGL() const; private: static GLuint GenVertexArrayGL(); GLuint mVertexArrayId; bool mActive; }; class GLBuffers { public: GLBuffers(); GLBuffers(GLBuffers&& other) noexcept; GLBuffers& operator=(GLBuffers&& other) noexcept; GLBuffers(const GLBuffers&) = delete; GLBuffers& operator=(const GLBuffers&) = delete; ~GLBuffers(); const auto& GetGLBuffer(const std::string& name) const { if (!mBuffers.contains(name)) { Logging::LogDebug("GLBuffers") << "No buffer named: " << name << std::endl; throw std::runtime_error("Request for nonexistent GL Buffer"); } return mBuffers.find(name)->second; } void AddBuffer( const std::string& name, GLLocation, GLElems, GLDataType, GLBindPoint, GLUpdateType); template <typename T> void AddStaticArrayBuffer( const std::string& name, GLLocation location) { static_assert(std::is_same_v<typename T::value_type, float> || std::is_same_v<typename T::value_type, unsigned>); constexpr auto dataType = std::invoke([](){ if constexpr (std::is_same_v<typename T::value_type, float>) return GLDataType{GL_FLOAT}; else return GLDataType{GL_UNSIGNED_INT}; }); AddBuffer(name, location, GLElems{T::length()}, dataType, GLBindPoint::ArrayBuffer, GLUpdateType::StaticDraw); } void AddElementBuffer(const std::string& name); void AddTextureBuffer(const std::string& name); static GLBufferId GenBufferGL(); template <typename T> void LoadBufferDataGL( const std::string& name, const std::vector<T>& data) { LoadBufferDataGL(GetGLBuffer(name), data); } template <typename T> void LoadBufferDataGL( const GLBuffer& buffer, const std::vector<T>& data) { glBindBuffer( ToGlEnum(buffer.mGLBindPoint), buffer.mBuffer.mValue); glBufferData( ToGlEnum(buffer.mGLBindPoint), data.size() * sizeof(T), &data.front(), ToGlEnum(buffer.mUpdateType)); } template <typename T> void ModifyBufferDataGL( const std::string& name, GLenum target, unsigned offset, const std::vector<T>& data) { glBindBuffer(target, GetGLBuffer(name).mBuffer.mValue); glBufferSubData( target, offset, data.size() * sizeof(T), &data.front()); } void BindAttribArrayGL(const GLBuffer&); void BindArraysGL(); void SetAttribDivisor(const std::string& name, unsigned divisor) { const auto location = GetGLBuffer(name).mLocation; glEnableVertexAttribArray(location.mValue); glVertexAttribDivisor(location.mValue, divisor); } //private: std::unordered_map<std::string, GLBuffer> mBuffers; GLuint mElementBuffer; // disable when moving from bool mActive; }; class TextureBuffer { public: static constexpr auto sMaxTextures = 256; TextureBuffer(GLenum textureType); TextureBuffer(TextureBuffer&& other) noexcept; TextureBuffer& operator=(TextureBuffer&& other) noexcept; TextureBuffer(const TextureBuffer&) = delete; TextureBuffer& operator=(const TextureBuffer&) = delete; ~TextureBuffer(); void BindGL() const; void UnbindGL() const; GLuint GetId() const; void MakeDepthBuffer(unsigned width, unsigned height); void MakePickBuffer(unsigned width, unsigned height); void MakeTexture2DArray(); void LoadTexturesGL( const std::vector<Texture>& textures, unsigned maxDim); //private: GLuint mTextureBuffer; GLenum mTextureType; bool mActive; }; }
5,322
C++
.h
169
25.532544
121
0.683621
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,484
IGuiElement.hpp
xavieran_BaKGL/graphics/IGuiElement.hpp
#pragma once #include "graphics/guiTypes.hpp" #include <glm/glm.hpp> #include <ostream> #include <vector> namespace Graphics { class IGuiElement { public: IGuiElement(); virtual ~IGuiElement(); virtual const DrawInfo& GetDrawInfo() const = 0; virtual const PositionInfo& GetPositionInfo() const = 0; virtual const std::vector<IGuiElement*>& GetChildren() const; void AddChildFront(Graphics::IGuiElement* elem); void AddChildBack(Graphics::IGuiElement* elem); void RemoveChild(Graphics::IGuiElement* elem); void ClearChildren(); private: std::vector<Graphics::IGuiElement*> mChildren; }; std::ostream& operator<<(std::ostream& os, const IGuiElement& element); }
712
C++
.h
23
27.73913
71
0.749263
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,485
guiRenderer.hpp
xavieran_BaKGL/graphics/guiRenderer.hpp
#pragma once #include "graphics/IGuiElement.hpp" #include "graphics/shaderProgram.hpp" #include "graphics/sprites.hpp" #include "graphics/texture.hpp" #include "graphics/types.hpp" #include "com/logger.hpp" namespace Graphics { // Tightly coupled with the GUI shader class GuiCamera { public: GuiCamera( float width, float height, float scale, const ShaderProgramHandle& shader); void CalculateMatrices(); void UpdateModelViewMatrix(const glm::mat4& modelMatrix); void ScissorRegion(glm::vec2 topLeft, glm::vec2 dimensions); void DisableScissor(); //private: float mWidth; float mHeight; float mScale; glm::mat4 mScaleMatrix; glm::mat4 mViewMatrix; glm::mat4 mModelMatrix; glm::mat4 mMVP; GLuint mMvpMatrixId; GLuint mModelMatrixId; GLuint mViewMatrixId; }; class GuiRenderer { public: static constexpr auto vertexShader = "gui.vert.glsl"; static constexpr auto fragmentShader = "gui.frag.glsl"; GuiRenderer( float width, float height, float scale, SpriteManager& spriteManager); void RenderGui( Graphics::IGuiElement* element); //private: void RenderGuiImpl( glm::vec2 translate, Graphics::IGuiElement* element); void Draw( const glm::mat4& modelMatrix, ColorMode colorMode, const glm::vec4& blockColor, TextureIndex texture, std::tuple<unsigned, unsigned> object); ShaderProgramHandle mShader; SpriteManager& mSpriteManager; glm::vec3 mDimensions; GuiCamera mCamera; // These are straight from the shader... GLuint mBlockColorId; GLuint mColorModeId; unsigned mRenderCalls; const Logging::Logger& mLogger; }; }
1,795
C++
.h
66
21.954545
64
0.705952
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,486
glm.hpp
xavieran_BaKGL/graphics/glm.hpp
#pragma once #include <glm/glm.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/string_cast.hpp> namespace glm { template <int Size, typename T> std::ostream& operator<<(std::ostream& os, const glm::vec<Size, T>& x) { os << glm::to_string(x); return os; } template <typename S, typename T> vec<2, S> cast(const vec<2, T>& x) { return static_cast<vec<2, S>>(x); } template <typename S, typename T> vec<3, S> cast(const vec<3, T>& x) { return static_cast<vec<3, S>>(x); } } namespace Graphics { template <typename T> bool PointWithinRectangle(glm::vec<2, T> point, glm::vec<2, T> topLeft, glm::vec<2, T> dimensions) { const auto bottomRight = topLeft + dimensions; return glm::all(glm::greaterThanEqual(point, topLeft)) && glm::all(glm::lessThanEqual(point, bottomRight)); } }
822
C++
.h
31
24.193548
98
0.693095
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,488
inputHandler.hpp
xavieran_BaKGL/graphics/inputHandler.hpp
#pragma once #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <functional> namespace Graphics { class InputHandler { public: using KeyCallback = std::function<void()>; using CharacterCallback = std::function<void(char)>; using MouseCallback = std::function<void(glm::vec2)>; InputHandler() noexcept; static void BindMouseToWindow(GLFWwindow* window, InputHandler& handler); static void BindKeyboardToWindow(GLFWwindow* window, InputHandler& handler); void SetHandleInput(bool value) { mHandleInput = value; } void Bind(int key, KeyCallback&& callback); void BindCharacter(CharacterCallback&& callback); void BindMouse( int button, MouseCallback&& pressed, MouseCallback&& released); void BindMouseMotion(MouseCallback&& moved); void BindMouseScroll(MouseCallback&& scrolled); void HandleInput(GLFWwindow* window); void HandleMouseInput(GLFWwindow* window); void HandleKeyboardCallback(GLFWwindow* window, int key, int scancode, int action, int mods); void HandleCharacterCallback(GLFWwindow* window, unsigned character); void HandleMouseCallback(GLFWwindow* window, int button, int action, int mods); void HandleMouseMotionCallback(GLFWwindow* window, double xpos, double ypos); void HandleMouseScrollCallback(GLFWwindow* window, double xpos, double ypos); private: static void MouseAction(GLFWwindow* window, int button, int action, int mods); static void MouseMotionAction(GLFWwindow* window, double xpos, double ypos); static void MouseScrollAction(GLFWwindow* window, double xpos, double ypos); static void KeyboardAction(GLFWwindow* window, int key, int scancode, int action, int mods); static void CharacterAction(GLFWwindow* window, unsigned character); static InputHandler* sHandler; bool mHandleInput; std::unordered_map<int, KeyCallback> mKeyBindings; CharacterCallback mCharacterCallback; std::unordered_map<int, std::pair<MouseCallback, MouseCallback>> mMouseBindings; MouseCallback mMouseMovedBinding; MouseCallback mMouseScrolledBinding; }; }
2,164
C++
.h
49
39.510204
97
0.762857
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,489
saveManager.hpp
xavieran_BaKGL/bak/saveManager.hpp
#pragma once #include "bak/save.hpp" #include "com/logger.hpp" #include "com/path.hpp" #include <algorithm> #include <filesystem> #include <regex> namespace BAK { std::string LoadSaveName(FileBuffer& fb); class SaveFile { public: unsigned mIndex; std::string mName; std::string mPath; std::string GetFilename() const { return std::filesystem::path{mPath}.filename().string(); } }; std::ostream& operator<<(std::ostream& os, const SaveFile&); class SaveDirectory { public: std::string GetPath() const { std::stringstream ss{}; ss << mName << ".G" << std::setw(2) << std::setfill('0') << mIndex; return ss.str(); } std::string GetName() const { return mName; } unsigned mIndex; std::string mName; std::vector<SaveFile> mSaves; }; std::ostream& operator<<(std::ostream&, const SaveDirectory&); class SaveManager { public: SaveManager(const std::string& savePath); const std::vector<SaveDirectory>& GetSaves() const; void RefreshSaves(); void RemoveDirectory(unsigned index); void RemoveSave(unsigned directory, unsigned save); const SaveFile& MakeSave( const std::string& saveDirectory, const std::string& saveName, bool isBookmark); private: std::vector<SaveFile> MakeSaveFiles(std::filesystem::path saveDir); std::vector<SaveDirectory> MakeSaveDirectories(); std::filesystem::path mSavePath; std::vector<SaveDirectory> mDirectories; const Logging::Logger& mLogger; }; }
1,556
C++
.h
59
22.20339
75
0.687415
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,490
hotspotRef.hpp
xavieran_BaKGL/bak/hotspotRef.hpp
#pragma once #include <string> #include <cstdint> namespace BAK { struct HotspotRef { std::uint8_t mGdsNumber; char mGdsChar; bool operator==(const auto& rhs) const { return mGdsNumber == rhs.mGdsNumber && mGdsChar == rhs.mGdsChar; } bool operator!=(const auto& rhs) { return !(*this == rhs); } std::string ToString() const; std::string ToFilename() const; }; char MakeHotspotChar(std::uint8_t); std::ostream& operator<<(std::ostream&, const HotspotRef&); }
535
C++
.h
23
18.913043
59
0.650099
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,491
monster.hpp
xavieran_BaKGL/bak/monster.hpp
#pragma once #include "bak/types.hpp" #include <cstdint> #include <vector> #include <string> namespace BAK { class MonsterNames { static constexpr std::string sInvalidMonster = "INVALID MONSTER"; public: static const MonsterNames& Get() { static auto mnames = MonsterNames{}; return mnames; } struct Monster { Monster( std::string prefix, std::uint8_t unknown0, std::uint8_t unknown1, std::uint8_t unknown2, std::uint8_t colorSwap) : mPrefix{prefix}, mUnknown0{unknown0}, mUnknown1{unknown1}, mUnknown2{unknown2}, mColorSwap{colorSwap} {} std::string mPrefix; std::uint8_t mUnknown0; std::uint8_t mUnknown1; std::uint8_t mUnknown2; std::uint8_t mColorSwap; }; const std::string& GetMonsterName(MonsterIndex monster) const { if (monster.mValue < mMonsterNames.size()) { return mMonsterNames[monster.mValue]; } else { return sInvalidMonster; } } const std::string& GetMonsterAnimationFile(MonsterIndex monster) const { ASSERT(monster.mValue < mMonsterPrefixes.size()); return mMonsterPrefixes[monster.mValue].mPrefix; } auto GetColorSwap(MonsterIndex monster) const { ASSERT(monster.mValue < mMonsterPrefixes.size()); return mMonsterPrefixes[monster.mValue].mColorSwap; } auto size() const { return mMonsterPrefixes.size(); } private: MonsterNames(); std::vector<std::string> mMonsterNames; std::vector<Monster> mMonsterPrefixes; }; }
1,730
C++
.h
64
19.828125
74
0.62069
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,492
IContainer.hpp
xavieran_BaKGL/bak/IContainer.hpp
#pragma once #include "bak/inventory.hpp" #include "bak/lock.hpp" #include <string_view> namespace BAK { struct ShopStats; enum class ContainerType { Bag = 0x0, CT1 = 0x1, Gravestone = 0x2, Building = 0x3, Shop = 0x4, Inn = 0x6, TimirianyaHut = 0x8, Combat = 0xa, //(0x8 + 0x2) Chest = 0x10, FairyChest = 0x11, EventChest = 0x19, Hole = 0x21, Key = 0xfe, Inv = 0xff }; std::string_view ToString(ContainerType); class IContainer { public: virtual const Inventory& GetInventory() const = 0; virtual Inventory& GetInventory() = 0; virtual bool CanAddItem(const InventoryItem&) const = 0; // These can invalidate refs virtual bool GiveItem(const InventoryItem&) = 0; virtual bool RemoveItem(const InventoryItem&) = 0; virtual ContainerType GetContainerType() const = 0; virtual ShopStats& GetShop() = 0; virtual const ShopStats& GetShop() const = 0; virtual LockStats& GetLock() = 0; bool IsShop() const; bool HasLock() const; }; }
1,126
C++
.h
41
23.707317
60
0.629182
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,493
layout.hpp
xavieran_BaKGL/bak/layout.hpp
#pragma once #include <glm/glm.hpp> #include <string> #include <vector> namespace BAK { class Layout { public: struct LayoutWidget { LayoutWidget( unsigned widget, unsigned action, bool isVisible, glm::vec2 position, glm::vec2 dimensions, unsigned teleport, unsigned image, unsigned group, std::string label) : mWidget{widget}, mAction{action}, mIsVisible{isVisible}, mPosition{position}, mDimensions{dimensions}, mTeleport{teleport}, mImage{image}, mGroup{group}, mLabel{label} {} unsigned mWidget; unsigned mAction; bool mIsVisible; glm::vec2 mPosition; glm::vec2 mDimensions; unsigned mTeleport; unsigned mImage; unsigned mGroup; std::string mLabel; }; Layout(const std::string& path); const LayoutWidget& GetWidget(unsigned index) const; glm::vec2 GetWidgetLocation(unsigned index) const; glm::vec2 GetWidgetDimensions(unsigned index) const; std::size_t GetSize() const { return mWidgets.size(); } private: bool mIsPopup; glm::vec2 mPosition; glm::vec2 mDimensions; glm::vec2 mOffset; std::vector<LayoutWidget> mWidgets; }; }
1,406
C++
.h
54
18.074074
59
0.596269
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,494
itemNumbers.hpp
xavieran_BaKGL/bak/itemNumbers.hpp
#pragma once #include "bak/inventoryItem.hpp" namespace BAK { static constexpr auto sLightCrossbow = BAK::ItemIndex{30}; static constexpr auto sMediumCrossbow = BAK::ItemIndex{31}; static constexpr auto sBessyMauler = BAK::ItemIndex{32}; static constexpr auto sTsuraniLightCrossbow = BAK::ItemIndex{33}; static constexpr auto sTsuraniHeavyCrossbow = BAK::ItemIndex{34}; static constexpr auto sElvenCrossbow = BAK::ItemIndex{35}; static constexpr auto sHeavyBowstring = BAK::ItemIndex{76}; static constexpr auto sLightBowstring = BAK::ItemIndex{77}; static constexpr auto sQuarrels = BAK::ItemIndex{36}; static constexpr auto sElvenQuarrels = BAK::ItemIndex{37}; static constexpr auto sTsuraniQuarrels = BAK::ItemIndex{38}; static constexpr auto sPoisonedQuarrels = BAK::ItemIndex{39}; static constexpr auto sPoisonedElvenQuarrels = BAK::ItemIndex{40}; static constexpr auto sPoisonedTsuraniQuarrels = BAK::ItemIndex{41}; static constexpr auto sPoisonOffset = 3; static constexpr auto sRations = BAK::ItemIndex{72}; static constexpr auto sPoisonedRations = BAK::ItemIndex{73}; static constexpr auto sSpoiledRations = BAK::ItemIndex{74}; static constexpr auto sColtariPoison = BAK::ItemIndex{105}; static constexpr auto sEliaemsShell = BAK::ItemIndex{16}; static constexpr auto sGreatsword = BAK::ItemIndex{21}; static constexpr auto sGuardaRevanche = BAK::ItemIndex{22}; static constexpr auto sExoticSword = BAK::ItemIndex{23}; static constexpr auto sStandardArmor = BAK::ItemIndex{48}; static constexpr auto sSovereigns = BAK::ItemIndex{53}; static constexpr auto sRoyals = BAK::ItemIndex{54}; static constexpr auto sRope = BAK::ItemIndex{82}; static constexpr auto sShovel = BAK::ItemIndex{83}; static constexpr auto sScroll = BAK::ItemIndex{133}; static constexpr auto sDayRations = BAK::ItemIndex{134}; static constexpr auto sAleCask = BAK::ItemIndex{79}; static constexpr auto sBrandy = BAK::ItemIndex{135}; static constexpr auto sAle = BAK::ItemIndex{136}; static constexpr auto sKeshianAle = BAK::ItemIndex{137}; static constexpr auto sPicklock = BAK::ItemIndex{'P'}; static constexpr auto sTorch = BAK::ItemIndex{84}; static constexpr auto sNapthaMask = BAK::ItemIndex{89}; static constexpr auto sRingOfPrandur = BAK::ItemIndex{6}; static constexpr auto sCupOfRlnnSkrr = BAK::ItemIndex{8}; static constexpr auto sSpynote = BAK::ItemIndex{120}; static constexpr auto sSilverthornAntiVenom = BAK::ItemIndex{113}; static constexpr auto sPractiseLute = BAK::ItemIndex{81}; static constexpr auto sWaani = BAK::ItemIndex{101}; static constexpr auto sBagOfGrain = BAK::ItemIndex{60}; static constexpr auto sAbbotsJournal = BAK::ItemIndex{124}; }
2,719
C++
.h
49
54.22449
68
0.787354
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,495
temple.hpp
xavieran_BaKGL/bak/temple.hpp
#pragma once #include "bak/dialog.hpp" #include "bak/condition.hpp" #include "bak/money.hpp" #include "bak/shop.hpp" #include "bak/types.hpp" namespace BAK::Temple { static constexpr auto sTempleOfSung = 4; static constexpr auto sChapelOfIshap = 12; bool CanBlessItem(const BAK::InventoryItem& item); bool IsBlessed(const BAK::InventoryItem& item); Royals CalculateBlessPrice(const BAK::InventoryItem& item, const ShopStats& shop); void BlessItem(BAK::InventoryItem& item, const ShopStats& shop); void RemoveBlessing(BAK::InventoryItem& item); Royals CalculateTeleportCost( unsigned srcTemple, unsigned dstTemple, glm::vec2 srcPos, glm::vec2 dstPos, unsigned teleportMultiplier, unsigned teleportConstant); Royals CalculateCureCost( unsigned cureFactor, bool isTempleOfSung, Skills&, const Conditions&, const std::vector<SkillAffector>&); void CureCharacter(Skills&, Conditions&, bool isTempleOfSung); }
979
C++
.h
29
30.172414
82
0.764581
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,496
startupFiles.hpp
xavieran_BaKGL/bak/startupFiles.hpp
#pragma once #include "bak/time.hpp" #include "bak/types.hpp" #include "bak/coordinates.hpp" #include <array> namespace BAK { struct ChapterStartLocation { MapLocation mMapLocation; Location mLocation; Time mTimeElapsed; }; std::ostream& operator<<(std::ostream&, const ChapterStartLocation&); ChapterStartLocation LoadChapterStartLocation(Chapter); void LoadFilter(); void LoadDetect(); void LoadZoneDat(ZoneNumber); void LoadZoneDefDat(ZoneNumber); using ZoneMap = std::array<std::uint8_t, 0x190>; // This is used to say whether there is a tile adjacent // for the purposes of loading surrounding tiles ZoneMap LoadZoneMap(ZoneNumber); unsigned GetMapDatTileValue( unsigned x, unsigned y, const ZoneMap& mapDat); void LoadStartDat(); }
771
C++
.h
29
24.448276
69
0.792633
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,497
money.hpp
xavieran_BaKGL/bak/money.hpp
#pragma once #include "bak/types.hpp" #include "com/strongType.hpp" namespace BAK { static constexpr Royals sUnpurchaseablePrice{0xffffffff}; Sovereigns GetSovereigns(Royals); Royals GetRoyals(Sovereigns sovereigns); Royals GetRemainingRoyals(Royals); std::string ToString(Royals); std::string ToShopString(Royals); std::string ToShopDialogString(Royals); }
365
C++
.h
12
28.833333
57
0.84104
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,498
party.hpp
xavieran_BaKGL/bak/party.hpp
#pragma once #include "bak/character.hpp" #include "bak/keyContainer.hpp" #include "bak/money.hpp" #include "bak/types.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include <vector> namespace BAK { class Party { public: std::size_t GetNumCharacters() const { return mActiveCharacters.size(); } const Character& GetCharacter(CharIndex i) const { //ASSERT(mCharacters.size() == sMaxCharacters); ASSERT(i.mValue < mCharacters.size()); return mCharacters[i.mValue]; } Character& GetCharacter(CharIndex i) { //ASSERT(mCharacters.size() == sMaxCharacters); ASSERT(i.mValue < mCharacters.size()); return mCharacters[i.mValue]; } std::optional<ActiveCharIndex> FindActiveCharacter(CharIndex index) const { const auto it = std::find(mActiveCharacters.begin(), mActiveCharacters.end(), index); if (it != mActiveCharacters.end()) return ActiveCharIndex{ static_cast<unsigned>( std::distance(mActiveCharacters.begin(), it))}; else return std::optional<ActiveCharIndex>{}; } std::optional<ActiveCharIndex> GetSpellcaster() const { for (unsigned i = 0; i < mActiveCharacters.size(); i++) { if (GetCharacter(ActiveCharIndex{i}).IsSpellcaster()) { return ActiveCharIndex{i}; } } return std::nullopt; } const Character& GetCharacter(ActiveCharIndex i) const { ASSERT(mActiveCharacters.size() <= sMaxActiveCharacters); return GetCharacter(mActiveCharacters[i.mValue]); } Character& GetCharacter(ActiveCharIndex i) { ASSERT(mActiveCharacters.size() <= sMaxActiveCharacters); return GetCharacter(mActiveCharacters[i.mValue]); } void SetActiveCharacters(const std::vector<CharIndex>& characters) { mActiveCharacters = characters; } const auto& GetKeys() const { return mKeys; } auto& GetKeys() { return mKeys; } Royals GetGold() const { return mGold; } bool HaveItem(ItemIndex itemIndex) const { const auto item = InventoryItemFactory::MakeItem( itemIndex, 1); for (const auto& character : mActiveCharacters) if (GetCharacter(character).GetInventory().HaveItem(item)) return true; return mKeys.GetInventory().HaveItem(item); } void SetMoney(Royals royals) { mGold = royals; } void GainMoney(Royals royals) { mGold.mValue += royals.mValue; } void LoseMoney(Royals royals) { if (mGold.mValue < royals.mValue) { mGold = Royals{0}; } else { mGold.mValue -= royals.mValue; } } void RemoveItem(unsigned itemIndex, unsigned quantity) { if (ItemIndex{itemIndex} == sSovereigns) { LoseMoney(GetRoyals(Sovereigns{quantity})); } else if (ItemIndex{itemIndex} == sRoyals) { LoseMoney(Royals{quantity}); } else { auto item = InventoryItemFactory::MakeItem( ItemIndex{itemIndex}, static_cast<std::uint8_t>(quantity)); if (item.IsKey()) mKeys.RemoveItem(item); else for (const auto& character : mActiveCharacters) if (GetCharacter(character).RemoveItem(item)) return; } } void AddItem(const InventoryItem& item) { if (item.IsMoney()) GainItem(item.GetItemIndex().mValue, item.GetQuantity()); else if (item.IsKey()) mKeys.GiveItem(item); } void GainItem(unsigned itemIndex, unsigned quantity) { if (ItemIndex{itemIndex} == sSovereigns) { mGold.mValue += GetRoyals(Sovereigns{quantity}).mValue; return; } else if (ItemIndex{itemIndex} == sRoyals) { mGold.mValue += quantity; return; } auto baseItem = InventoryItemFactory::MakeItem( ItemIndex{itemIndex}, static_cast<std::uint8_t>(quantity)); if (baseItem.IsKey()) { mKeys.GiveItem(baseItem); return; } ForEachActiveCharacter([&](auto& character) { character.GiveItem(baseItem); return Loop::Continue; }); } ActiveCharIndex NextActiveCharacter(ActiveCharIndex currentCharacter) const { unsigned i = currentCharacter.mValue; if (++i == mActiveCharacters.size()) i = 0; return ActiveCharIndex{i}; } template <typename F> void ForEachActiveCharacter(F&& f) const { for (const auto character : mActiveCharacters) { if (std::forward<F>(f)(GetCharacter(character)) == Loop::Finish) { return; } } } template <typename F> void ForEachActiveCharacter(F&& f) { for (const auto character : mActiveCharacters) { if (std::forward<F>(f)(GetCharacter(character)) == Loop::Finish) { return; } } } std::pair<CharIndex, unsigned> GetSkill(BAK::SkillType skill, bool best) { std::optional<unsigned> skillValue{}; auto character = CharIndex{0}; for (unsigned i = 0; i < mActiveCharacters.size(); i++) { const auto charSkill = GetCharacter(ActiveCharIndex{i}).GetSkill(skill); Logging::LogDebug(__FUNCTION__) << "Char: " << GetCharacter(ActiveCharIndex{i}).mName << " skill: " << charSkill << "\n"; if (!skillValue || best ? charSkill > skillValue : charSkill < skillValue) { skillValue = charSkill; character = mActiveCharacters[i]; } } ASSERT(skillValue); return std::make_pair(character, *skillValue); } void ImproveSkillForAll(SkillType skill, SkillChange skillChangeType, int multiplier) { for (const auto c : mActiveCharacters) { GetCharacter(c).ImproveSkill( skill, skillChangeType, multiplier); } } Royals mGold; KeyContainer mKeys; std::vector<Character> mCharacters; std::vector<CharIndex> mActiveCharacters; }; std::ostream& operator<<(std::ostream&, const Party&); }
6,725
C++
.h
225
21.142222
133
0.577881
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,499
hotspot.hpp
xavieran_BaKGL/bak/hotspot.hpp
#pragma once #include "bak/dialog.hpp" #include "bak/resourceNames.hpp" #include "bak/scene.hpp" #include "bak/types.hpp" #include "com/logger.hpp" #include "bak/fileBufferFactory.hpp" #include <glm/glm.hpp> #include <string_view> namespace BAK { enum class HotspotAction { UNKNOWN_0 = 0, UNKNOWN_1 = 1, DIALOG = 2, EXIT = 3, GOTO = 4, BARMAID = 5, SHOP = 6, INN = 7, CONTAINER = 8, LUTE = 9, REPAIR_2 = 0xa, TELEPORT = 0xb, UNKNOWN_C = 0xc, TEMPLE = 0xd, UNKNOWN_E = 0xe, CHAPTER_END = 0xf, REPAIR = 0x10, UNKNOWN_X = 0x100 }; std::ostream& operator<<(std::ostream&, HotspotAction); struct Hotspot { Hotspot( std::uint16_t hotspot, glm::vec<2, int> topLeft, glm::vec<2, int> dimensions, std::uint16_t chapterMask, std::uint16_t keyword, HotspotAction action, std::uint8_t unknown_d, std::uint16_t actionArg1, std::uint16_t actionArg2, std::uint32_t actionArg3, KeyTarget tooltip, std::uint32_t unknown_1a, KeyTarget dialog, std::uint16_t checkEventState) : mHotspot{hotspot}, mTopLeft{topLeft}, mDimensions{dimensions}, mChapterMask{chapterMask}, mKeyword{keyword}, mAction{action}, mUnknown_d{unknown_d}, mActionArg1{actionArg1}, mActionArg2{actionArg2}, mActionArg3{actionArg3}, mTooltip{tooltip}, mUnknown_1a{unknown_1a}, mDialog{dialog}, mCheckEventState{checkEventState} {} // Yes but there is more to it - e.g. Sarth bool IsActive(GameState& gameState) const { // ovr148:86D test mChapterMask, 0x8000??? const auto state = CreateChoice(mDialog.mValue & 0xffff); const auto expectedVal = (mDialog.mValue >> 16) & 0xffff; Logging::LogDebug(__FUNCTION__) << "Unk2: " << mCheckEventState << " Eq: " << (mCheckEventState == 1) << " GS: " << std::hex << state << " st: " << gameState.GetEventState(state) << " exp: " << expectedVal << " Unk0: " << mChapterMask << "\n"; if (mCheckEventState != 0 && !std::holds_alternative<NoChoice>(state)) { return gameState.GetEventState(state) == expectedVal; } return (mChapterMask ^ 0xffff) & (1 << (gameState.GetChapter().mValue - 1)); } bool EvaluateImmediately() const { return (mChapterMask & 0x8000) != 0; } std::uint16_t mHotspot{}; glm::vec<2, int> mTopLeft{}; glm::vec<2, int> mDimensions{}; std::uint16_t mChapterMask{}; std::uint16_t mKeyword{}; HotspotAction mAction{}; std::uint8_t mUnknown_d{}; std::uint16_t mActionArg1{}; std::uint16_t mActionArg2{}; std::uint32_t mActionArg3{}; KeyTarget mTooltip{}; std::uint32_t mUnknown_1a{}; KeyTarget mDialog{}; std::uint16_t mCheckEventState{}; }; std::ostream& operator<<(std::ostream&, const Hotspot&); // Loaded from a GDS File class SceneHotspots { public: explicit SceneHotspots(FileBuffer&&); std::string mSceneTTM{}; std::string mSceneADS{}; std::array<std::uint8_t, 6> mUnknown_6{}; std::uint8_t mUnknown_c{}; std::uint8_t mTempleIndex{}; std::uint8_t mUnknown_e{}; std::uint8_t mUnknown_f{}; std::uint8_t mUnknown_10{}; SongIndex mSong{}; std::uint16_t mUnknownIdx_13{}; AdsSceneIndex mSceneIndex1{}; std::uint16_t mUnknown_16{}; AdsSceneIndex mSceneIndex2{}; std::uint16_t mNumHotspots{}; std::uint32_t mFlavourText{}; std::uint16_t mUnknown_1f{}; std::uint16_t mUnknown_21{}; std::uint16_t mUnknown_23{}; std::uint16_t mUnknown_25{}; std::vector<Hotspot> mHotspots{}; std::unordered_map<unsigned, SceneIndex> mAdsIndices{}; std::unordered_map<unsigned, Scene> mScenes{}; const Scene& GetScene(unsigned adsIndex, const GameState& gs); std::optional<unsigned> GetTempleNumber() const { if (!(0x80 & mTempleIndex)) return std::nullopt; return mTempleIndex & 0x7f; } }; }
4,205
C++
.h
135
25.274074
107
0.616052
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,500
constants.hpp
xavieran_BaKGL/bak/constants.hpp
#pragma once #include <string> #include "bak/types.hpp" #include "bak/worldClock.hpp" namespace BAK { static constexpr float gWorldScale = 100.; static constexpr float gTileSize = 64000.; static constexpr auto gCellSize = 0x640; // (1600) enum class Terrain { Ground = 0, Road = 1, Waterfall = 2, Path = 3, Dirt = 4, River = 5, Sand = 6, Bank = 7 }; enum class Enemy { SolidCrystal = 0x09, TransparentCrystal = 0x0a, Blaster = 0x0b, SolidOctagon = 0x0c, LavaOctagon = 0x0d, Unknown = 0x0e, Gorath = 0x0f, Owyn = 0x10, Locklear = 0x11, Moredhel = 0x12, BrakNurr = 0x13, Egg = 0x14, MoredhelMagician = 0x15, BlackSlayer = 0x16, Nighthawk = 0x17, Rogue = 0x18 }; static constexpr auto Locklear = CharIndex{0}; static constexpr auto Gorath = CharIndex{1}; static constexpr auto Owyn = CharIndex{2}; static constexpr auto Pug = CharIndex{3}; static constexpr auto James = CharIndex{4}; static constexpr auto Patrus = CharIndex{5}; enum class Actor { Locklear = 1, Gorath = 2, Owyn = 3, Pug = 4, James = 5, Patrus = 6, NavonDuSandau = 7, UgyneCorvalis = 8, SquirePhillip = 24 }; namespace Times { static constexpr auto HalfHour = Time{0x384}; static constexpr auto OneHour = Time{0x708}; static constexpr auto ThreeHours = Time{0x1518}; static constexpr auto EightHours = Time{0x3840}; static constexpr auto TwelveHours = Time{0x5460}; static constexpr auto ThirteenHours = Time{0x5b68}; static constexpr auto SeventeenHours = Time{0x7788}; static constexpr auto EighteenHours = Time{0x7e90}; static constexpr auto OneDay = Time{0xa8c0}; } }
1,713
C++
.h
68
22.058824
52
0.694002
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,501
save.hpp
xavieran_BaKGL/bak/save.hpp
#pragma once #include "bak/character.hpp" #include "bak/container.hpp" #include "bak/inventory.hpp" #include "bak/party.hpp" #include "bak/coordinates.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK { void Save(const Inventory&, FileBuffer&); void Save(const GenericContainer&, FileBuffer&); void Save(const Character&, FileBuffer&); void Save(const Party&, FileBuffer&); void Save(const WorldClock&, FileBuffer&); void Save(const std::vector<TimeExpiringState>& storage, FileBuffer& fb); void Save(const SpellState& spells, FileBuffer& fb); void Save(Chapter chapter, FileBuffer& fb); void Save(const MapLocation& location, FileBuffer& fb); void Save(const Location& location, FileBuffer& fb); }
710
C++
.h
19
36.105263
73
0.790087
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,502
worldClock.hpp
xavieran_BaKGL/bak/worldClock.hpp
#pragma once #include <cstdint> #include <iomanip> #include <ios> #include <ostream> namespace BAK { // Tracks the time in the game world struct Time { unsigned GetDays() const { return GetHours() / 24; } unsigned GetHour() const { return GetHours() % 24; } unsigned GetHours() const { return GetSeconds() / 3600; } unsigned GetMinutes() const { return GetSeconds() / 60; } unsigned GetMinute() const { return GetMinutes() % 60; } unsigned GetSeconds() const { return mTime * 2; } constexpr auto operator<=>(const Time&) const = default; Time operator+(const Time& lhs) const { return Time(mTime + lhs.mTime); } Time& operator+=(const Time& lhs) { mTime += lhs.mTime; return *this; } Time operator-(const Time& lhs) const { return Time(mTime - lhs.mTime); } Time& operator-=(const Time& lhs) { mTime -= lhs.mTime; return *this; } Time operator*(const Time& lhs) const { return Time(mTime * lhs.mTime); } template <typename Numeric> requires std::is_integral_v<Numeric> Time operator*(Numeric lhs) const { return Time(mTime * lhs); } Time operator/(const Time& lhs) const { return Time(mTime / lhs.mTime); } std::uint32_t mTime; }; std::string ToString(Time t); std::ostream& operator<<(std::ostream&, const Time&); class WorldClock { public: // 0x0000 0000 is 0AM // 0x0001 0000 is 12AM // 0x0001 0800 is 1AM // 1 hour = 1800 ticks // Each tick is 2 seconds // One step forward is 0x1e ticks (60 seconds) WorldClock(Time time, Time timeLastSlept) : mTime{time}, mTimeLastSlept{timeLastSlept} { } Time GetTime() const { return mTime; } Time GetTimeLastSlept() const { return mTimeLastSlept; } Time GetTimeSinceLastSlept() const { return Time{mTime - mTimeLastSlept}; } void AdvanceTime(Time timeDelta) { mTime = mTime + timeDelta; } void SetTimeLastSlept(Time time) { mTimeLastSlept = time; } void SetTime(Time time) { mTime = time; mTimeLastSlept = time; } private: Time mTime; Time mTimeLastSlept; }; std::ostream& operator<<(std::ostream&, const WorldClock&); }
2,473
C++
.h
115
16.078261
68
0.603693
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,503
bard.hpp
xavieran_BaKGL/bak/bard.hpp
#pragma once #include "bak/dialog.hpp" #include "bak/money.hpp" #include "bak/shop.hpp" #include "bak/types.hpp" namespace BAK::Bard { enum class BardStatus { Failed, Poor, Good, Best }; BardStatus ClassifyBardAttempt( unsigned bardingSkill, unsigned innRequirement); Royals GetReward(BardStatus, Sovereigns innReward, Chapter); void ReduceAvailableReward(ShopStats&, Royals reward); KeyTarget GetDialog(BardStatus); SongIndex GetSong(BardStatus); }
483
C++
.h
21
20.428571
60
0.788079
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,504
zoneReference.hpp
xavieran_BaKGL/bak/zoneReference.hpp
#pragma once #include <glm/glm.hpp> #include <string> #include <vector> namespace BAK { std::vector<glm::uvec2> LoadZoneRef( const std::string& path); }
162
C++
.h
8
18.125
36
0.738255
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,505
fileBufferFactory.hpp
xavieran_BaKGL/bak/fileBufferFactory.hpp
#pragma once #include "bak/file/fileBuffer.hpp" #include "bak/file/aggregateFileProvider.hpp" #include <string> namespace BAK { class FileBufferFactory { public: static FileBufferFactory& Get(); void SetDataPath(const std::string&); void SetSavePath(const std::string&); bool DataBufferExists(const std::string& path); FileBuffer CreateDataBuffer(const std::string& path); bool SaveBufferExists(const std::string& path); FileBuffer CreateSaveBuffer(const std::string& path); FileBuffer CreateFileBuffer(const std::string& path); private: FileBufferFactory(); FileBufferFactory& operator=(const FileBufferFactory&) noexcept = delete; FileBufferFactory(const FileBufferFactory&) noexcept = delete; FileBufferFactory& operator=(FileBufferFactory&&) noexcept = delete; FileBufferFactory(FileBufferFactory&&) noexcept = delete; std::string mDataPath; std::string mSavePath; File::AggregateFileProvider mDataFileProvider; }; }
995
C++
.h
27
33.111111
77
0.772443
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,506
spriteRenderer.hpp
xavieran_BaKGL/bak/spriteRenderer.hpp
#pragma once #include "bak/image.hpp" #include "bak/palette.hpp" #include "bak/sceneData.hpp" #include "graphics/texture.hpp" #include <optional> namespace BAK { // Used to render TTM scenes class SpriteRenderer { public: SpriteRenderer() : mForegroundLayer{320, 200}, mBackgroundLayer{320, 200}, mSavedImagesLayer0{320, 200}, mSavedImagesLayer1{320, 200}, mSavedImagesLayerBG{320, 200} { } void SetColors(std::uint8_t fg, std::uint8_t bg) { mForegroundColor = fg; mBackgroundColor = bg; } void RenderTexture( const Graphics::Texture& texture, glm::ivec2 pos, Graphics::Texture& layer) { for (int x = 0; x < static_cast<int>(texture.GetWidth()); x++) { for (int y = 0; y < static_cast<int>(texture.GetHeight()); y++) { const auto pixelPos = pos + glm::ivec2{x, y}; if (mClipRegion) { if (pixelPos.x < mClipRegion->mTopLeft.x || pixelPos.x > mClipRegion->mBottomRight.x || pixelPos.y < mClipRegion->mTopLeft.y || pixelPos.y > mClipRegion->mBottomRight.y) { continue; } } const auto color = texture.GetPixel(x, y); if (std::abs(0.0 - color.a) < .0001) continue; if (pixelPos.x > 320 || pixelPos.y > 200) continue; layer.SetPixel( pixelPos.x, pixelPos.y, color); } } } void RenderSprite( BAK::Image sprite, const BAK::Palette& palette, glm::ivec2 pos, bool flipped, Graphics::Texture& layer) { for (int x = 0; x < static_cast<int>(sprite.GetWidth()); x++) { for (int y = 0; y < static_cast<int>(sprite.GetHeight()); y++) { const auto pixelPos = pos + glm::ivec2{ flipped ? sprite.GetWidth() - x : x, y}; if (mClipRegion)// && !background) { if (pixelPos.x < mClipRegion->mTopLeft.x || pixelPos.x > mClipRegion->mBottomRight.x || pixelPos.y < mClipRegion->mTopLeft.y || pixelPos.y > mClipRegion->mBottomRight.y) { continue; } } else if (pixelPos.x < 0 || pixelPos.x > 320 || pixelPos.y < 0 || pixelPos.y > 200) { continue; } const auto color = palette.GetColor(sprite.GetPixel(x, y)); if (color.a == 0) continue; if (pixelPos.x > 320 || pixelPos.y > 200) continue; layer.SetPixel( pixelPos.x, pixelPos.y, color); } } } void DrawRect(glm::ivec2 pos, glm::ivec2 dims, const BAK::Palette& palette, Graphics::Texture& layer) { for (int x = 0; x < static_cast<int>(dims.x); x++) { for (int y = 0; y < static_cast<int>(dims.y); y++) { const auto pixelPos = pos + glm::ivec2{x, y}; const auto color = palette.GetColor(mForegroundColor); if (color.a == 0) continue; if (pixelPos.x > 320 || pixelPos.y > 200) continue; layer.SetPixel( pixelPos.x, pixelPos.y, color); } } } void Clear() { mForegroundLayer = Graphics::Texture{320, 200}; mBackgroundLayer = Graphics::Texture{320, 200}; mSavedImagesLayer0 = Graphics::Texture{320, 200}; mSavedImagesLayer1 = Graphics::Texture{320, 200}; mSavedImagesLayerBG = Graphics::Texture{320, 200}; } Graphics::Texture& GetForegroundLayer() { return mForegroundLayer; } Graphics::Texture& GetBackgroundLayer() { return mBackgroundLayer; } Graphics::Texture& GetSavedImagesLayerBG() { return mSavedImagesLayerBG; } Graphics::Texture& GetSavedImagesLayer0() { return mSavedImagesLayer0; } Graphics::Texture& GetSavedImagesLayer1() { return mSavedImagesLayer1; } void SetClipRegion(BAK::ClipRegion clipRegion) { mClipRegion = clipRegion; } void ClearClipRegion() { mClipRegion.reset(); } Graphics::Texture SaveImage(glm::ivec2 pos, glm::ivec2 dims, unsigned layer) { auto image = Graphics::Texture{static_cast<unsigned>(dims.x), static_cast<unsigned>(dims.y)}; for (int x = 0; x < dims.x; x++) { for (int y = 0; y < dims.y; y++) { image.SetPixel(x, y, mForegroundLayer.GetPixel(x + pos.x, y + pos.y)); } } RenderTexture(image, pos, GetSaveLayer(layer)); return image; } Graphics::Texture& GetSaveLayer(unsigned layer) { if (layer == 0) { return mSavedImagesLayer0; } else if (layer == 1) { return mSavedImagesLayer1; } else if (layer == 2) { return mSavedImagesLayerBG; } assert(false); return mSavedImagesLayer0; } private: Graphics::Texture mForegroundLayer; Graphics::Texture mBackgroundLayer; Graphics::Texture mSavedImagesLayer0; Graphics::Texture mSavedImagesLayer1; Graphics::Texture mSavedImagesLayerBG; std::optional<BAK::ClipRegion> mClipRegion; std::uint8_t mBackgroundColor{}; std::uint8_t mForegroundColor{}; }; }
5,913
C++
.h
186
21.295699
108
0.520786
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,507
screen.hpp
xavieran_BaKGL/bak/screen.hpp
#pragma once #include "bak/image.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK { Image LoadScreenResource(FileBuffer& fb); }
140
C++
.h
6
21.5
41
0.813953
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,508
spells.hpp
xavieran_BaKGL/bak/spells.hpp
#pragma once #include "bak/fileBufferFactory.hpp" #include "bak/types.hpp" #include "bak/monster.hpp" #include "com/assert.hpp" #include "com/bits.hpp" #include "com/logger.hpp" #include "com/ostream.hpp" #include "graphics/glm.hpp" #include <string_view> #include <vector> namespace BAK { enum class StaticSpells : std::uint16_t { DragonsBreath = 0, CandleGlow = 1, Stardusk = 2, AndTheLightShallLie = 3, Union = 4, ScentOfSarig = 5 }; static constexpr std::array<std::uint8_t, 6> sStaticSpellMapping = { 30, 31, 32, 34, 33, 35 }; std::ostream& operator<<(std::ostream&, StaticSpells); StaticSpells ToStaticSpell(SpellIndex); enum class SpellCalculationType { NonCostRelated, FixedAmount, CostTimesDamage, CostTimesDuration, Special1, Special2 }; std::string_view ToString(SpellCalculationType); std::ostream& operator<<(std::ostream&, SpellCalculationType); class Spells { public: explicit Spells(std::array<std::uint8_t, 6> spells) { std::copy(spells.data(), spells.data() + 6, reinterpret_cast<std::uint8_t*>(&mSpellBytes)); for (std::uint64_t i = 0; i < 8 * 6; i++) { if (HaveSpell(SpellIndex{i})) { mSpellIndices.emplace_back(SpellIndex{i}); } } } bool HaveSpell(SpellIndex spellIndex) const { return CheckBitSet(mSpellBytes, spellIndex.mValue); } void SetSpell(SpellIndex spellIndex) { if (!HaveSpell(spellIndex)) { mSpellIndices.emplace_back(spellIndex); } mSpellBytes = SetBit(mSpellBytes, spellIndex.mValue, true); } const std::uint64_t& GetSpellBytes() const { return mSpellBytes; } auto GetSpells() const { return mSpellIndices; } private: std::uint64_t mSpellBytes{}; std::vector<SpellIndex> mSpellIndices{}; }; std::ostream& operator<<(std::ostream&, const Spells&); class Spell { public: bool HasSpell(Spells spells) const { return spells.HaveSpell(mIndex); } SpellIndex mIndex{}; std::string mName{}; unsigned mMinCost{}; unsigned mMaxCost{}; bool mIsMartial{}; std::uint16_t mTargetingType{}; std::optional<std::uint16_t> mColor{}; std::optional<std::uint16_t> mAnimationEffectType{}; std::optional<ItemIndex> mObjectRequired{}; SpellCalculationType mCalculationType{}; int mDamage{}; unsigned mDuration{}; }; std::ostream& operator<<(std::ostream&, const Spell&); class SpellDoc { public: SpellIndex mIndex{}; std::string mTitle{}; std::string mCost{}; std::string mDamage{}; std::string mDuration{}; std::string mLineOfSight{}; std::string mDescription{}; }; class Symbol { public: struct SymbolSlot { SpellIndex mSpell; unsigned mSpellIcon; glm::vec<2, std::uint16_t> mPosition; }; explicit Symbol(unsigned index) { assert(index > 0 && index < 7); std::stringstream ss{}; ss << "SYMBOL" << index << ".DAT"; auto fb = FileBufferFactory::Get().CreateDataBuffer(ss.str()); auto slotCount = fb.GetUint16LE(); Logging::LogDebug(__FUNCTION__) << "Loading SymbolIndex #" << index << "\n"; Logging::LogDebug(__FUNCTION__) << " slots: " << slotCount << "\n"; for (unsigned i = 0; i < slotCount; i++) { auto spell = SpellIndex{fb.GetUint16LE()}; auto position = fb.LoadVector<std::uint16_t, 2>(); auto symbolIcon = fb.GetUint8(); mSymbolSlots.emplace_back(SymbolSlot{spell, symbolIcon, position}); Logging::LogDebug(__FUNCTION__) << " spell: " << spell << " icon: " << +symbolIcon << " @ " << position << "\n"; } } const auto& GetSymbolSlots() const { return mSymbolSlots; } private: std::vector<SymbolSlot> mSymbolSlots{}; }; class SpellDatabase { static constexpr auto sSpellNamesFile = "SPELLS.DAT"; static constexpr auto sSpellDocsFile = "SPELLDOC.DAT"; static constexpr auto sSpellWeaknessesFile = "SPELLWEA.DAT"; static constexpr auto sSpellResistances = "SPELLRES.DAT"; public: static const SpellDatabase& Get() { static SpellDatabase spellDb{}; return spellDb; } const auto& GetSpells() const { return mSpells; } std::string_view GetSpellName(SpellIndex spellIndex) const { ASSERT(spellIndex.mValue < mSpells.size()); return mSpells[spellIndex.mValue].mName; } const Spell& GetSpell(SpellIndex spellIndex) const { ASSERT(spellIndex.mValue < mSpells.size()); return mSpells[spellIndex.mValue]; } const SpellDoc& GetSpellDoc(SpellIndex spellIndex) const { ASSERT(spellIndex.mValue < mSpells.size()); return mSpellDocs[spellIndex.mValue]; } const auto& GetSymbols() const { return mSymbols; } private: SpellDatabase() : mSpells{}, mSpellDocs{} { LoadSpells(); LoadSpellDoc(); //LoadSpellWeaknesses(); //LoadSpellResistances(); for (unsigned i = 1; i < 7; i++) { mSymbols.emplace_back(BAK::Symbol{i}); } } void LoadSpells() { auto fb = FileBufferFactory::Get().CreateDataBuffer(sSpellNamesFile); const auto spells = fb.GetUint16LE(); auto nameOffsets = std::vector<unsigned>{}; for (unsigned i = 0; i < spells; i++) { unsigned nameOffset = fb.GetUint16LE(); nameOffsets.emplace_back(nameOffset); unsigned minCost = fb.GetUint16LE(); unsigned maxCost = fb.GetUint16LE(); auto isMartialFlag = fb.GetUint16LE(); assert(isMartialFlag == 0 || isMartialFlag == 1); bool isMartial = isMartialFlag == 0x1; // name taken from SPELLREQ.DAT auto targetingType = fb.GetUint16LE(); // targeting type - this seems to be affected by the effectAnimationType // e.g. when using effect animation 12 (winds of eortis), 0-3 only target enemies with LOS // 0 - only targets enemies - LOS // 1 - only target enemies - ignores LOS // 2 - targets allies - ignores LOS // 3 - targets allies - ignores LOS // 4 - targes enemies - ignores LOS // 5 - targets empty squares // 6 - targets empty squares // Color of any related effect sprites, e.g. sparks of flamecast, mind melt color auto color = fb.GetUint16LE(); // Determines whether we throw a ball (flamecast), strike an enemy, // what kind of animation is used. Combines weirdly with the actual spell auto effectAnimationType = fb.GetUint16LE(); // object required to cast spell auto objectRequired = ItemIndex{fb.GetUint16LE()}; auto calculationType = static_cast<SpellCalculationType>(fb.GetUint16LE()); int damage = fb.GetSint16LE(); unsigned duration = fb.GetSint16LE(); mSpells.emplace_back(Spell{ SpellIndex{i}, "", minCost, maxCost, isMartial, targetingType, (color != 0xffff) ? std::make_optional(color) : std::nullopt, (effectAnimationType != 0xffff) ? std::make_optional(effectAnimationType) : std::nullopt, (objectRequired.mValue != 0xffff) ? std::make_optional(objectRequired) : std::nullopt, calculationType, damage, duration}); } fb.GetUint16LE(); auto here = fb.Tell(); for (unsigned i = 0; i < spells; i++) { fb.Seek(here + nameOffsets[i]); mSpells[i].mName = fb.GetString(); Logging::LogDebug(__FUNCTION__) << mSpells[i] << "\n"; } } void LoadSpellDoc() { assert(!mSpells.empty()); auto fb = FileBufferFactory::Get().CreateDataBuffer(sSpellDocsFile); const auto offsetCount = fb.GetUint16LE(); auto stringOffsets = std::vector<unsigned>{}; for (unsigned i = 0; i < offsetCount; i++) { stringOffsets.emplace_back(fb.GetUint32LE()); } fb.Skip(2); auto here = fb.Tell(); for (unsigned i = 0, entry = 0; i < mSpells.size(); i++) { fb.Seek(here + stringOffsets[entry++]); auto title = fb.GetString(); fb.Seek(here + stringOffsets[entry++]); auto cost = fb.GetString(); fb.Seek(here + stringOffsets[entry++]); auto damage = fb.GetString(); fb.Seek(here + stringOffsets[entry++]); auto duration = fb.GetString(); fb.Seek(here + stringOffsets[entry++]); auto lineOfSight = fb.GetString(); fb.Seek(here + stringOffsets[entry++]); auto description = fb.GetString(); fb.Seek(here + stringOffsets[entry++]); description += " " + fb.GetString(); mSpellDocs.emplace_back( SpellDoc{ SpellIndex{i}, title, cost, damage, duration, lineOfSight, description}); } for (unsigned i = 0; i < mSpells.size(); i++) { auto doc = mSpellDocs[i]; Logging::LogDebug(__FUNCTION__) << GetSpellName(SpellIndex{i}) << "\nTitle: " << doc.mTitle << "\nCost: " << doc.mCost << "\nDamage: " << doc.mDamage << "\nDuration: " << doc.mDuration << "\nLOS: " << doc.mLineOfSight << "\nDescription: " << doc.mDescription << "\n"; } } void LoadSpellWeaknesses() { auto monsters = MonsterNames::Get(); auto fb = FileBufferFactory::Get().CreateDataBuffer(sSpellWeaknessesFile); unsigned entries = fb.GetUint16LE(); for (unsigned i = 0; i < entries; i++) { fb.Dump(6); auto spells = Spells{fb.GetArray<6>()}; std::stringstream ss{}; for (const auto& spell : mSpells) { if (spell.HasSpell(spells)) { ss << spell.mName << ","; } } Logging::LogDebug(__FUNCTION__) << "Monster: " << i - 1 << std::dec << "(" << i - 1<< ") - " << monsters.GetMonsterName(MonsterIndex{i - 1}) << " (" << std::hex << spells.GetSpells() << std::dec << ") " << ss.str() << "\n"; } } void LoadSpellResistances() { auto monsters = MonsterNames::Get(); auto fb = FileBufferFactory::Get().CreateDataBuffer(sSpellResistances); unsigned entries = fb.GetUint16LE(); for (unsigned i = 0; i < entries; i++) { fb.Dump(6); auto spells = Spells{fb.GetArray<6>()}; std::stringstream ss{}; for (const auto& spell : mSpells) { if (spell.HasSpell(spells)) { ss << spell.mName << ","; } } Logging::LogDebug(__FUNCTION__) << "Monster: " << i - 1 << std::dec << "(" << i - 1<< ") - " << monsters.GetMonsterName(MonsterIndex{i - 1}) << " " << ss.str() << "\n"; } } private: std::vector<Spell> mSpells{}; std::vector<SpellDoc> mSpellDocs{}; std::vector<Symbol> mSymbols{}; }; // These are the locations of the dots for the spell power ring class PowerRing { public: static const PowerRing& Get() { static auto ring = PowerRing{}; return ring; } const auto& GetPoints() const { return mPoints; } private: PowerRing() { auto fb = FileBufferFactory::Get().CreateDataBuffer("RING.DAT"); unsigned points = 30; std::vector<int> xs{}; std::vector<int> ys{}; for (unsigned i = 0; i < points; i++) { xs.emplace_back(fb.GetSint16LE()); } for (unsigned i = 0; i < points; i++) { ys.emplace_back(fb.GetSint16LE()); } for (unsigned i = 0; i < points; i++) { mPoints.emplace_back(xs[i], ys[i]); } } std::vector<glm::ivec2> mPoints{}; }; class SymbolLines { static constexpr std::uint16_t sCoords [] = { 0x47, 0x5F, 0x7B, 0x13, 0x31, 0x3B, 0x10, 0x65, 0x3D, 0x3D, 0x65, 0x3D, 0x7C, 0x47, 0x28, 0x68, 0x47, 0x13, 0x3E, 0x10, 0x61, 0x61, 0x10, 0x3E, 0x68, 0x13, 0x69, 0x27, 0x7B, 0x29, 0x62, 0x3E, 0x1A, 0x1A, 0x3D, 0x62, 0x25, 0x25, 0x6B, 0x6B, 0x25, 0x6B, 0x1D, 0x60, 0x1D, 0x60, 0x60, 0x60, 0x4B, 0x72, 0x4B, 0x4B, 0x1F, 0x4B, 0x48, 0x59, 0x11, 0x48, 0x59, 0x11, 0x13, 0x2F, 0x6C, 0x22, 0x5C, 0x7B, 0x46, 0x16, 0x5D, 0x5D, 0x14, 0x46, 0x46, 0x73, 0x75, 0x48, 0x1A, 0x19, 0x10, 0x25, 0x53, 0x6B, 0x56, 0x28 }; static constexpr std::uint16_t sXPointers [] = { 0x1726, 0x179E, 0x173E, 0x1756, 0x176E, 0x1786, 0x17B6 }; static constexpr std::uint16_t sYPointers [] = { 0x1732, 0x17AA, 0x174A, 0x1762, 0x177A, 0x1792, 0x17C2 }; public: static std::vector<glm::vec2> GetPoints(unsigned symbol) { const auto offset = 0x1726; const unsigned xPointer = (sXPointers[symbol] - offset) >> 1; const unsigned yPointer = (sYPointers[symbol] - offset) >> 1; std::vector<glm::vec2> points{}; for (unsigned i = 0; i < 6; i++) { auto x = sCoords[xPointer + i]; auto y = sCoords[yPointer + i]; points.emplace_back(glm::vec2{x, y}); } return points; } }; class SpellState { public: SpellState() = default; explicit SpellState(std::uint16_t spells) : mSpells{spells} {} bool SpellActive(StaticSpells spell) const { return CheckBitSet(mSpells, spell); } void SetSpellState(StaticSpells spell, bool state) { mSpells = SetBit(mSpells, spell, state); } std::uint16_t GetSpells() const { return mSpells; } private: std::uint16_t mSpells{}; }; }
14,473
C++
.h
436
25.087156
146
0.572072
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,509
worldItem.hpp
xavieran_BaKGL/bak/worldItem.hpp
#pragma once #include "bak/constants.hpp" #include "bak/coordinates.hpp" #include "bak/fileBufferFactory.hpp" #include <vector> namespace BAK { struct WorldItem { unsigned mItemType; glm::ivec3 mRotation; glm::ivec3 mLocation; }; auto LoadWorldTile(FileBuffer& fb) -> std::pair<std::vector<WorldItem>, glm::ivec2>; }
342
C++
.h
15
20.133333
53
0.749216
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,510
backgroundSounds.hpp
xavieran_BaKGL/bak/backgroundSounds.hpp
#pragma once #include "audio/audio.hpp" namespace BAK { class GameState; void PlayBackgroundSounds(GameState&); }
119
C++
.h
6
18
38
0.824074
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,511
entityType.hpp
xavieran_BaKGL/bak/entityType.hpp
#pragma once #include <string_view> namespace BAK { enum class EntityType { TERRAIN = 0, EXTERIOR = 1, BRIDGE = 2, INTERIOR = 3, HILL = 4, TREE = 5, CHEST = 6, DEADBODY1 = 7, FENCE = 8, GATE = 9, // RIFT GATE BUILDING = 10, TOMBSTONE = 12, SIGN = 13, TUNNEL1 = 14, // ALSO TUNNEL... PIT = 15, DEADBODY2 = 16, DIRTPILE = 17, CORN = 18, FIRE = 19, ENTRANCE = 20, GROVE = 21, FERN = 22, DOOR = 23, CRYST = 24, ROCKPILE = 25, BUSH1 = 26, BUSH2 = 27, BUSH3 = 28, SLAB = 29, STUMP = 30, WELL = 31, ENGINE = 33, SCARECROW = 34, TRAP = 35, CATAPULT = 36, COLUMN = 37, LANDSCAPE = 38, TUNNEL2 = 39, // with tunnel BAG = 41, LADDER = 42, DEAD_COMBATANT = 106, LIVING_COMBATANT = 107 }; unsigned GetContainerTypeFromEntityType(EntityType); EntityType EntityTypeFromModelName(std::string_view name); }
1,137
C++
.h
51
17.901961
58
0.484736
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,512
fixedObject.hpp
xavieran_BaKGL/bak/fixedObject.hpp
#pragma once #include "bak/container.hpp" namespace BAK { std::vector<GenericContainer> LoadFixedObjects(unsigned targetZone); }
133
C++
.h
5
24.8
68
0.830645
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,513
worldFactory.hpp
xavieran_BaKGL/bak/worldFactory.hpp
#pragma once #include "bak/constants.hpp" #include "bak/coordinates.hpp" #include "bak/encounter/encounter.hpp" #include "bak/model.hpp" #include "bak/monster.hpp" #include "bak/resourceNames.hpp" #include "bak/textureFactory.hpp" #include "bak/worldItem.hpp" #include "bak/zoneReference.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "graphics/meshObject.hpp" #include "bak/fileBufferFactory.hpp" #include "bak/entityType.hpp" #include <functional> #include <optional> namespace BAK { class ZoneTextureStore { public: ZoneTextureStore( const ZoneLabel& zoneLabel, const BAK::Palette& palette); const Graphics::Texture& GetTexture(const unsigned i) const { return mTextures.GetTexture(i); } const std::vector<Graphics::Texture>& GetTextures() const { return mTextures.GetTextures(); } unsigned GetMaxDim() const { return mTextures.GetMaxDim(); } unsigned GetTerrainOffset(BAK::Terrain t) const { return mTerrainOffset + static_cast<unsigned>(t); } unsigned GetHorizonOffset() const { return mHorizonOffset; } private: Graphics::TextureStore mTextures; unsigned mTerrainOffset; unsigned mHorizonOffset; }; class ZoneItem { public: ZoneItem( const Model& model, const ZoneTextureStore& textureStore) : mName{model.mName}, mEntityFlags{model.mEntityFlags}, mEntityType{static_cast<EntityType>(model.mEntityType)}, mScale{static_cast<float>(1 << model.mScale)}, mSpriteIndex{model.mSprite}, mColors{}, mVertices{}, mPalettes{}, mFaces{}, mPush{} { if (mSpriteIndex == 0 || mSpriteIndex > 400) { for (const auto& vertex : model.mVertices) { mVertices.emplace_back(BAK::ToGlCoord<int>(vertex)); } for (const auto& component : model.mComponents) { for (const auto& mesh : component.mMeshes) { assert(mesh.mFaceOptions.size() > 0); // Only show the first face option. These typically correspond to // animation states, e.g. for the door, or catapult, or rift gate. // Will need to work out how to handle animated things later... const auto& faceOption = mesh.mFaceOptions[0]; //for (const auto& faceOption : mesh.mFaceOptions) { for (const auto& face : faceOption.mFaces) { mFaces.emplace_back(face); } for (const auto& palette : faceOption.mPalettes) { mPalettes.emplace_back(palette); } for (const auto& colorVec : faceOption.mFaceColors) { const auto color = colorVec.x; mColors.emplace_back(color); if ((GetName().substr(0, 5) == "house" || GetName().substr(0, 3) == "inn") && (color == 190 || color == 191)) mPush.emplace_back(false); else if (GetName().substr(0, 4) == "blck" && (color == 145 || color == 191)) mPush.emplace_back(false); else if (GetName().substr(0, 4) == "brid" && (color == 147)) mPush.emplace_back(false); else if (GetName().substr(0, 4) == "temp" && (color == 218 || color == 220 || color == 221)) mPush.emplace_back(false); else if (GetName().substr(0, 6) == "church" && (color == 191 || color == 0)) mPush.emplace_back(false); else if (GetName().substr(0, 6) == "ground") mPush.emplace_back(false); else mPush.emplace_back(true); } } } } } else { // Need this to set the right dimensions for the texture const auto& tex = textureStore.GetTexture(mSpriteIndex); const auto spriteScale = 7.0f; auto width = static_cast<int>(static_cast<float>(tex.GetWidth()) * (spriteScale * .75)); auto height = tex.GetHeight() * spriteScale; mVertices.emplace_back(-width, height, 0); mVertices.emplace_back(width, height, 0); mVertices.emplace_back(width, 0, 0); mVertices.emplace_back(-width, 0, 0); auto faces = std::vector<std::uint16_t>{}; faces.emplace_back(0); faces.emplace_back(1); faces.emplace_back(2); faces.emplace_back(3); mFaces.emplace_back(faces); mPush.emplace_back(false); mPalettes.emplace_back(0x91); mColors.emplace_back(model.mSprite); } ASSERT((mFaces.size() == mColors.size()) && (mFaces.size() == mPalettes.size()) && (mFaces.size() == mPush.size())); } ZoneItem( unsigned i, const BAK::MonsterNames& monsters, const ZoneTextureStore& textureStore) : mName{monsters.GetMonsterAnimationFile(MonsterIndex{i})}, mEntityFlags{0}, mEntityType{EntityType::DEADBODY1}, mScale{1}, mSpriteIndex{i + textureStore.GetHorizonOffset()}, mColors{}, mVertices{}, mPalettes{}, mFaces{}, mPush{} { // Need this to set the right dimensions for the texture const auto& tex = textureStore.GetTexture(mSpriteIndex); const auto spriteScale = 7.0f; auto width = static_cast<int>(static_cast<float>(tex.GetWidth()) * (spriteScale * .75)); auto height = tex.GetHeight() * spriteScale; mVertices.emplace_back(-width, height, 0); mVertices.emplace_back(width, height, 0); mVertices.emplace_back(width, 0, 0); mVertices.emplace_back(-width, 0, 0); auto faces = std::vector<std::uint16_t>{}; faces.emplace_back(0); faces.emplace_back(1); faces.emplace_back(2); faces.emplace_back(3); mFaces.emplace_back(faces); mPush.emplace_back(false); mPalettes.emplace_back(0x91); mColors.emplace_back(mSpriteIndex); ASSERT((mFaces.size() == mColors.size()) && (mFaces.size() == mPalettes.size()) && (mFaces.size() == mPush.size())); } void SetPush(unsigned i){ mPush[i] = true; } const std::string& GetName() const { return mName; } bool IsSprite() const { return mSpriteIndex > 0 && mSpriteIndex < 400; } const auto& GetColors() const { return mColors; } const auto& GetFaces() const { return mFaces; } const auto& GetPush() const { return mPush; } const auto& GetPalettes() const { return mPalettes; } const auto& GetVertices() const { return mVertices; } auto GetScale() const { return mScale; } bool GetClickable() const { //return static_cast<unsigned>(mEntityType) > 5; for (std::string s : { "ground", "genmtn", "zero", "one", "bridge", "fence", "tree", "db0", "db1", "db2", "db8", "t0", "g0", "r0", "spring", "fall", "landscp", // Mine stuff "m_r", "m_1", "m_2", "m_3", "m_4", "m_b", "m_c", "m_h"}) { if (mName.substr(0, s.length()) == s) return false; } return true; } EntityType GetEntityType() const { return mEntityType; } private: std::string mName; unsigned mEntityFlags; EntityType mEntityType; float mScale; unsigned mSpriteIndex; std::vector<std::uint8_t> mColors; std::vector<glm::vec<3, int>> mVertices; std::vector<std::uint8_t> mPalettes; std::vector<std::vector<std::uint16_t>> mFaces; std::vector<bool> mPush; friend std::ostream& operator<<(std::ostream& os, const ZoneItem& d); }; std::ostream& operator<<(std::ostream& os, const ZoneItem& d); Graphics::MeshObject ZoneItemToMeshObject( const ZoneItem& item, const ZoneTextureStore& store, const Palette& pal); class ZoneItemStore { public: ZoneItemStore( const ZoneLabel& zoneLabel, // Should one really need a texture store to load this? const ZoneTextureStore& textureStore) : mZoneLabel{zoneLabel}, mItems{} { auto fb = FileBufferFactory::Get() .CreateDataBuffer(mZoneLabel.GetTable()); const auto models = LoadTBL(fb); for (unsigned i = 0; i < models.size(); i++) { mItems.emplace_back( models[i], textureStore); } } const ZoneLabel& GetZoneLabel() const { return mZoneLabel; } const ZoneItem& GetZoneItem(const unsigned i) const { ASSERT(i < mItems.size()); return mItems[i]; } const ZoneItem& GetZoneItem(const std::string& name) const { auto it = std::find_if(mItems.begin(), mItems.end(), [&name](const auto& item){ return name == item.GetName(); }); ASSERT(it != mItems.end()); return *it; } const std::vector<ZoneItem>& GetItems() const { return mItems; } std::vector<ZoneItem>& GetItems() { return mItems; } private: const ZoneLabel mZoneLabel; std::vector<ZoneItem> mItems; }; class WorldItemInstance { public: WorldItemInstance( const ZoneItem& zoneItem, const WorldItem& worldItem) : mZoneItem{zoneItem}, mType{worldItem.mItemType}, mRotation{BAK::ToGlAngle(worldItem.mRotation)}, mLocation{BAK::ToGlCoord<float>(worldItem.mLocation)}, mBakLocation{worldItem.mLocation.x, worldItem.mLocation.y} { } const ZoneItem& GetZoneItem() const { return mZoneItem; } const glm::vec3& GetRotation() const { return mRotation; } const glm::vec3& GetLocation() const { return mLocation; } const glm::uvec2& GetBakLocation() const { return mBakLocation; } unsigned GetType() const { return mType; } private: const ZoneItem& mZoneItem; unsigned mType; glm::vec3 mRotation; glm::vec3 mLocation; glm::vec<2, unsigned> mBakLocation; friend std::ostream& operator<<(std::ostream& os, const WorldItemInstance& d); }; std::ostream& operator<<(std::ostream& os, const WorldItemInstance& d); class World { public: World( const ZoneItemStore& zoneItems, Encounter::EncounterFactory ef, unsigned x, unsigned y, unsigned tileIndex) : mCenter{}, mTile{x, y}, mTileIndex{tileIndex}, mItemInsts{}, mEncounters{}, mEmpty{} { LoadWorld(zoneItems, ef, x, y, tileIndex); } void LoadWorld( const ZoneItemStore& zoneItems, const Encounter::EncounterFactory ef, unsigned x, unsigned y, unsigned tileIndex) { const auto& logger = Logging::LogState::GetLogger("World"); const auto tileWorld = zoneItems.GetZoneLabel().GetTileWorld(x, y); logger.Debug() << "Loading tile: " << tileWorld << std::endl; auto fb = FileBufferFactory::Get().CreateDataBuffer(tileWorld); const auto [tileWorldItems, tileCenter] = LoadWorldTile(fb); for (const auto& item : tileWorldItems) { if (item.mItemType == 0) mCenter = ToGlCoord<float>(item.mLocation); mItemInsts.emplace_back( zoneItems.GetZoneItem(item.mItemType), item); } const auto tileData = zoneItems.GetZoneLabel().GetTileData(x, y); if (FileBufferFactory::Get().DataBufferExists(tileData)) { auto fb = FileBufferFactory::Get().CreateDataBuffer(tileData); mEncounters = Encounter::EncounterStore( ef, fb, mTile, mTileIndex); } } const auto& GetTile() const { return mTile; } const auto& GetItems() const { return mItemInsts; } const auto& GetEncounters(Chapter chapter) const { if (mEncounters) return mEncounters->GetEncounters(chapter); else return mEmpty; } auto GetCenter() const { return mCenter.value_or( GetItems().front().GetLocation()); } private: std::optional<glm::vec3> mCenter; glm::vec<2, unsigned> mTile; unsigned mTileIndex; std::vector<WorldItemInstance> mItemInsts; std::optional<Encounter::EncounterStore> mEncounters; std::vector<Encounter::Encounter> mEmpty; }; class WorldTileStore { public: WorldTileStore( const ZoneItemStore& zoneItems, const Encounter::EncounterFactory& ef) : mWorlds{ std::invoke([&zoneItems, &ef]() { const auto tiles = LoadZoneRef( zoneItems.GetZoneLabel().GetZoneReference()); std::vector<World> worlds{}; worlds.reserve(tiles.size()); for (unsigned tileIndex = 0; tileIndex < tiles.size(); tileIndex++) { const auto& tile = tiles[tileIndex]; auto it = worlds.emplace_back( zoneItems, ef, tile.x, tile.y, tileIndex); } return worlds; }) } {} const std::vector<World>& GetTiles() const { return mWorlds; } private: std::vector<World> mWorlds; }; }
14,683
C++
.h
422
24.113744
101
0.545057
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,514
trap.hpp
xavieran_BaKGL/bak/trap.hpp
#pragma once #include "graphics/glm.hpp" #include <vector> namespace BAK { enum class TrapElementType { RedCrystal = 0x7, GreenCrystal = 0x8, SolidDiamond = 0x9, TransparentDiamond = 0xA, Unknown_C3 = 0xc3, Unknown_FFEE = 0xffee, Character0 = 0xffef, Character1 = 0xfff0, Character2 = 0xfff1, BlasterDown = 0xfff3, BlasterUp = 0xfff4, BlasterRight = 0xfff5, BlasterLeft = 0xfff6, Exit = 0xfffa }; class TrapElement { public: TrapElementType mElement; glm::uvec2 mPosition; }; class Trap { public: unsigned mIndex; std::vector<TrapElement> mElements; }; std::ostream& operator<<(std::ostream& os, const Trap& trap); std::vector<Trap> LoadTraps(); }
729
C++
.h
36
17
61
0.707602
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,515
dialogReplacements.hpp
xavieran_BaKGL/bak/dialogReplacements.hpp
#pragma once #include "bak/dialogAction.hpp" #include "bak/dialogTarget.hpp" #include "bak/constants.hpp" namespace BAK { // Version 1.02 is rather buggy - many dialog actions seem to be // scrambled - I have substituted these as appropriate from // v1.01 dialog files. struct Replacement { OffsetTarget mTarget; std::vector<std::pair<unsigned, DialogAction>> mReplacements; }; class Replacements { public: static void ReplaceActions(OffsetTarget target, std::vector<DialogAction>& actions); private: static const std::vector<Replacement> sReplacements; }; }
581
C++
.h
21
25.619048
88
0.781588
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,516
timeExpiringState.hpp
xavieran_BaKGL/bak/timeExpiringState.hpp
#pragma once #include <cstdint> #include <iosfwd> #include <vector> #include "bak/worldClock.hpp" namespace BAK { enum class ExpiringStateType : std::uint8_t { None = 0, Light = 1, Spell = 2, SetState = 3, ResetState = 4 }; std::ostream& operator<<(std::ostream&, ExpiringStateType); struct TimeExpiringState { ExpiringStateType mType; std::uint8_t mFlags; std::uint16_t mData; Time mDuration; }; std::ostream& operator<<(std::ostream&, const TimeExpiringState&); TimeExpiringState* AddTimeExpiringState( std::vector<TimeExpiringState>& storage, ExpiringStateType type, std::uint16_t data, std::uint8_t flags, Time duration); TimeExpiringState* AddLightTimeExpiringState( std::vector<TimeExpiringState>& storage, unsigned stateType, Time duration); TimeExpiringState* AddSpellTimeExpiringState( std::vector<TimeExpiringState>& storage, unsigned spell, Time duration); }
960
C++
.h
38
21.894737
66
0.740132
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,517
types.hpp
xavieran_BaKGL/bak/types.hpp
#pragma once #include "com/strongType.hpp" #include <cstdint> namespace BAK { using Chapter = Bounded<StrongType<unsigned, struct ChapterTag>, 1, 11>; using EntityIndex = StrongType<unsigned, struct EntityIndexTag>; using ChoiceIndex = StrongType<unsigned, struct ChoiceIndexTag>; using CombatantIndex = StrongType<unsigned, struct CombatantIndexTag>; using DoorIndex = StrongType<unsigned, struct DoorIndexTag>; using MonsterIndex = StrongType<unsigned, struct MonsterIndexTag>; using SpellIndex = StrongType<std::uint64_t, struct SpellIndexTag>; using SongIndex = std::uint16_t; using Sovereigns = StrongType<unsigned, struct SovereignsTag>; using Royals = StrongType<unsigned, struct RoyalsTag>; using AdsSceneIndex = std::uint16_t; using ItemIndex = StrongType<unsigned, struct ItemIndexTag>; using ZoneNumber = StrongType<unsigned, struct ZoneNumberTag>; using ZoneTransitionIndex = StrongType<unsigned, struct ZoneTransitionIndexTag>; using TeleportIndex = StrongType<unsigned, struct TeleportIndexTag>; static constexpr auto sMaxActiveCharacters = 3; static constexpr auto sMaxCharacters = 6; using ActiveCharIndex = Bounded< StrongType<unsigned, struct ActiveCharIndexTag>, 0, sMaxActiveCharacters>; using CharIndex = Bounded< StrongType<unsigned, struct CharIndexTag>, 0, sMaxCharacters>; enum class Loop { Continue, Finish }; }
1,372
C++
.h
33
39.545455
80
0.815651
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,518
container.hpp
xavieran_BaKGL/bak/container.hpp
#pragma once #include "bak/IContainer.hpp" #include "bak/coordinates.hpp" #include "bak/dialog.hpp" #include "bak/shop.hpp" #include "bak/hotspotRef.hpp" #include "bak/inventory.hpp" #include "bak/types.hpp" #include "com/assert.hpp" #include "com/bits.hpp" #include <variant> #include <ostream> namespace BAK { // Bit indices enum class ContainerProperty { HasLock = 0, // 0x1 HasDialog = 1, // 0x2 HasShop = 2, // 0x4 HasEncounter = 3, // 0x8 HasTime = 4, // 0x10 HasDoor = 5 // 0x20 }; struct ContainerWorldLocationTag {}; struct ContainerWorldLocation { ZoneNumber mZone; std::uint8_t mChapterRange; std::uint8_t mModel; std::uint8_t mUnknown; glm::uvec2 mLocation; unsigned GetFrom() const; unsigned GetTo() const; }; std::ostream& operator<<(std::ostream&, const ContainerWorldLocation&); struct ContainerGDSLocationTag{}; struct ContainerGDSLocation { std::array<std::uint8_t, 4> mUnknown; HotspotRef mLocation; }; std::ostream& operator<<(std::ostream&, const ContainerGDSLocation&); struct ContainerCombatLocationTag{}; struct ContainerCombatLocation { std::array<std::uint8_t, 4> mUnknown; std::uint32_t mCombatant; std::uint32_t mCombat; }; std::ostream& operator<<(std::ostream&, const ContainerCombatLocation&); using ContainerLocation = std::variant< ContainerWorldLocation, ContainerGDSLocation, ContainerCombatLocation>; std::ostream& operator<<(std::ostream&, const ContainerLocation&); class ContainerHeader { public: ContainerHeader(); ContainerHeader(ContainerWorldLocationTag, FileBuffer& fb); ContainerHeader(ContainerGDSLocationTag, FileBuffer& fb); ContainerHeader(ContainerCombatLocationTag, FileBuffer& fb); ZoneNumber GetZone() const; GamePosition GetPosition() const; HotspotRef GetHotspotRef() const; unsigned GetCombatNumber() const; unsigned GetCombatantNumber() const; unsigned GetModel() const; bool PresentInChapter(Chapter) const; bool HasLock() const { return CheckBitSet(mFlags, ContainerProperty::HasLock); } bool HasDialog() const { return CheckBitSet(mFlags, ContainerProperty::HasDialog); } bool HasShop() const { return CheckBitSet(mFlags, ContainerProperty::HasShop); } bool HasEncounter() const { return CheckBitSet(mFlags, ContainerProperty::HasEncounter); } bool HasTime() const { return CheckBitSet(mFlags, ContainerProperty::HasTime); } bool HasDoor() const { return CheckBitSet(mFlags, ContainerProperty::HasDoor); } bool HasInventory() const { return mCapacity != 0; } std::uint32_t GetAddress() const { return mAddress; } //private: std::uint32_t mAddress; ContainerLocation mLocation; std::uint8_t mLocationType; // no idea std::uint8_t mItems; std::uint8_t mCapacity; std::uint8_t mFlags; }; std::ostream& operator<<(std::ostream&, const ContainerHeader&); struct ContainerEncounter { std::uint16_t mRequireEventFlag; std::uint16_t mSetEventFlag; std::optional<HotspotRef> mHotspotRef; std::optional<GamePosition> mEncounterPos; }; std::ostream& operator<<(std::ostream&, const ContainerEncounter&); struct ContainerDialog { std::uint8_t mContextVar; std::uint8_t mDialogOrder; Target mDialog; }; std::ostream& operator<<(std::ostream&, const ContainerDialog&); class GenericContainer final : public IContainer { public: static constexpr auto sTypicalShopBuffer = 6; GenericContainer( ContainerHeader header, std::optional<LockStats> lock, std::optional<Door> door, std::optional<ContainerDialog> dialog, std::optional<ShopStats> shop, std::optional<ContainerEncounter> encounter, std::optional<Time> lastAccessed, Inventory&& inventory) : mHeader{header}, mLock{lock}, mDoor{door}, mDialog{dialog}, mShop{shop}, mEncounter{encounter}, mLastAccessed{lastAccessed}, mInventory{std::move(inventory)} { } GenericContainer(GenericContainer&&) noexcept = default; GenericContainer& operator=(GenericContainer&&) noexcept = default; GenericContainer(const GenericContainer&) noexcept = default; GenericContainer& operator=(const GenericContainer&) noexcept = default; const ContainerHeader& GetHeader() const { return mHeader; } bool HasLock() const { return bool{mLock}; } LockStats& GetLock() override { ASSERT(mLock); return *mLock; } const LockStats& GetLock() const { ASSERT(mLock); return *mLock; } bool HasDialog() const { return bool{mDialog}; } const ContainerDialog& GetDialog() const { ASSERT(mDialog); return *mDialog; } ContainerDialog& GetDialog() { ASSERT(mDialog); return *mDialog; } bool HasDoor() const { return bool{mDoor}; } DoorIndex GetDoor() const { ASSERT(mDoor); return mDoor->mDoorIndex; } DoorIndex GetDoor() { ASSERT(mDoor); return mDoor->mDoorIndex; } bool HasShop() const { return bool{mShop}; } ShopStats& GetShop() override { ASSERT(mShop); return *mShop; } const ShopStats& GetShop() const override { ASSERT(mShop); return *mShop; } bool HasEncounter() const { return bool{mEncounter}; } ContainerEncounter& GetEncounter() { ASSERT(mEncounter); return *mEncounter; } const ContainerEncounter& GetEncounter() const { ASSERT(mEncounter); return *mEncounter; } bool HasLastAccessed() const { return bool{mLastAccessed}; } Time& GetLastAccessed() { ASSERT(mLastAccessed); return *mLastAccessed; } const Time& GetLastAccessed() const { ASSERT(mLastAccessed); return *mLastAccessed; } bool HasInventory() const { return bool{mHeader.mCapacity != 0}; } Inventory& GetInventory() override { return mInventory; } const Inventory& GetInventory() const override { return mInventory; } bool CanAddItem(const InventoryItem& item) const override { return mInventory.CanAddContainer(item); } bool GiveItem(const InventoryItem& item) override { if (mShop && !mInventory.CanAddContainer(item)) { // Remove the earliest added item mInventory.RemoveItem(BAK::InventoryIndex(mInventory.GetCapacity() - sTypicalShopBuffer)); } mInventory.AddItem(item); return true; } bool RemoveItem(const InventoryItem& item) override { mInventory.RemoveItem(item); return true; } ContainerType GetContainerType() const override { return static_cast<ContainerType>(mHeader.mFlags); } private: ContainerHeader mHeader; std::optional<LockStats> mLock; std::optional<Door> mDoor; std::optional<ContainerDialog> mDialog; std::optional<ShopStats> mShop; std::optional<ContainerEncounter> mEncounter; std::optional<Time> mLastAccessed; Inventory mInventory; }; template <typename HeaderTag> GenericContainer LoadGenericContainer(FileBuffer& fb) { auto header = ContainerHeader{HeaderTag{}, fb}; auto lockData = std::optional<LockStats>{}; auto door = std::optional<Door>{}; auto dialog = std::optional<ContainerDialog>{}; auto shopData = std::optional<ShopStats>{}; auto encounter = std::optional<ContainerEncounter>{}; auto lastAccessed = std::optional<Time>{}; auto inventory = LoadInventory(fb, header.mItems, header.mCapacity); { if (header.HasLock()) { lockData = LoadLock(fb); } if (header.HasDoor()) { const auto doorIndex = fb.GetUint16LE(); door = Door{DoorIndex{doorIndex}}; } if (header.HasDialog()) { const auto contextVar = fb.GetUint8(); const auto dialogOrder = fb.GetUint8(); const auto dialogKey = KeyTarget{fb.GetUint32LE()}; dialog = ContainerDialog{contextVar, dialogOrder, dialogKey}; } if (header.HasShop()) { shopData = LoadShop(fb); } if (header.HasEncounter()) { const auto requireEventFlag = fb.GetUint16LE(); const auto setEventFlag = fb.GetUint16LE(); auto hotspotRef = std::optional<HotspotRef>{}; hotspotRef = HotspotRef{ fb.GetUint8(), static_cast<char>( fb.GetUint8() + 0x40)}; if (hotspotRef->mGdsNumber == 0) hotspotRef.reset(); auto encounterPos = std::optional<glm::uvec2>{}; const auto hasEncounter = fb.GetUint8(); const auto xOff = fb.GetUint8(); const auto yOff = fb.GetUint8(); if (hasEncounter != 0) { const auto encounterOff = glm::uvec2{xOff, yOff}; encounterPos = MakeGamePositionFromTileAndCell( GetTile(header.GetPosition()), encounterOff); } encounter = ContainerEncounter{ requireEventFlag, setEventFlag, hotspotRef, encounterPos}; } if (header.HasTime()) { lastAccessed = Time{fb.GetUint32LE()}; } } return GenericContainer{ header, lockData, door, dialog, shopData, encounter, lastAccessed, std::move(inventory)}; } std::ostream& operator<<(std::ostream&, const GenericContainer&); }
9,548
C++
.h
260
30.265385
102
0.67082
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,519
character.hpp
xavieran_BaKGL/bak/character.hpp
#pragma once #include "com/logger.hpp" #include "bak/IContainer.hpp" #include "bak/condition.hpp" #include "bak/skills.hpp" #include "bak/spells.hpp" #include "bak/types.hpp" #include "bak/inventory.hpp" #include <cstdint> #include <ostream> #include <string> namespace BAK { class Character final : public IContainer { public: Character( unsigned index, const std::string& name, const Skills& skills, Spells spells, const std::array<std::uint8_t, 2>& unknown, const std::array<std::uint8_t, 7>& unknown2, const Conditions& conditions, Inventory&& inventory); /* IContainer */ Inventory& GetInventory() override; const Inventory& GetInventory() const override; bool CanAddItem(const InventoryItem& ref) const override; bool GiveItem(const InventoryItem& ref) override; bool RemoveItem(const InventoryItem& item) override; ContainerType GetContainerType() const override; ShopStats& GetShop() override; const ShopStats& GetShop() const override; LockStats& GetLock() override; /* Character Getters */ bool CanSwapItem(const InventoryItem& ref) const; CharIndex GetIndex() const; bool IsSpellcaster() const; bool IsSwordsman() const; bool HasEmptyStaffSlot() const; bool HasEmptySwordSlot() const; bool HasEmptyCrossbowSlot() const; bool HasEmptyArmorSlot() const; InventoryIndex GetItemAtSlot(ItemType slot) const; ItemType GetWeaponType() const; bool CanReplaceEquippableItem(ItemType type) const; void ApplyItemToSlot(InventoryIndex index, ItemType slot); void CheckPostConditions(); unsigned GetTotalItem(const std::vector<BAK::ItemIndex>& itemIndex); const std::string& GetName() const; bool CanHeal(bool isInn); bool HaveNegativeCondition(); const Skills& GetSkills() const; Skills& GetSkills(); void ImproveSkill(SkillType skill, SkillChange skillChangeType, int multiplier); unsigned GetSkill(SkillType skill) const; unsigned GetMaxSkill(SkillType skill) const; void AdjustCondition(BAK::Condition cond, signed amount); const Conditions& GetConditions() const; Conditions& GetConditions(); void UpdateSkills(); Spells& GetSpells(); const Spells& GetSpells() const; void AddSkillAffector(const SkillAffector& affector); std::vector<SkillAffector>& GetSkillAffectors(); const std::vector<SkillAffector>& GetSkillAffectors() const; CharIndex mCharacterIndex; std::string mName; mutable Skills mSkills; Spells mSpells; std::array<std::uint8_t, 2> mUnknown; std::array<std::uint8_t, 7> mUnknown2; Conditions mConditions; Inventory mInventory; std::vector<SkillAffector> mSkillAffectors; const Logging::Logger& mLogger; }; std::ostream& operator<<(std::ostream&, const Character&); }
2,881
C++
.h
79
31.708861
84
0.73319
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,520
scene.hpp
xavieran_BaKGL/bak/scene.hpp
#pragma once #include "bak/gameState.hpp" #include "bak/sceneData.hpp" #include "bak/types.hpp" #include "com/assert.hpp" #include "bak/fileBufferFactory.hpp" #include <optional> #include <vector> #include <unordered_map> #include <map> namespace BAK { using TTMIndex = unsigned; struct ADSIndex { ADSIndex() : mIf{0}, mElse{}, mGreaterThan{}, mLessThan{} {} TTMIndex GetTTMIndex(Chapter chapter) const { if (mGreaterThan && mLessThan) { if (chapter.mValue >= *mGreaterThan && chapter.mValue <= *mLessThan) return mIf; else { ASSERT(mElse); return *mElse; } } else if (mGreaterThan && chapter.mValue >= *mGreaterThan) { return mIf; } else if (mLessThan && chapter.mValue <= *mLessThan) { return mIf; } else if (!mGreaterThan && !mLessThan) { return mIf; } else { ASSERT(mElse); return *mElse; } } TTMIndex mIf; std::optional<TTMIndex> mElse; std::optional<unsigned> mGreaterThan; std::optional<unsigned> mLessThan; }; std::ostream& operator<<(std::ostream&, const ADSIndex&); struct SceneIndex { std::string mSceneTag; ADSIndex mSceneIndex; }; struct SceneADS { unsigned mInitScene; unsigned mDrawScene; bool mPlayAllScenes; }; struct SceneSequence { std::string mName; std::vector<SceneADS> mScenes; }; std::ostream& operator<<(std::ostream&, const SceneIndex&); struct ImageSlot { std::vector<std::string> mImage; std::optional<unsigned> mPalette; }; using PaletteSlot = unsigned; struct Scene { std::string mSceneTag; std::vector<SceneAction> mActions; std::unordered_map<PaletteSlot, std::string> mPalettes; std::unordered_map<unsigned, std::pair<std::string, PaletteSlot>> mImages; std::unordered_map<PaletteSlot, std::pair<std::string, PaletteSlot>> mScreens; std::optional<ClipRegion> mClipRegion; }; std::ostream& operator<<(std::ostream&, const Scene&); struct DynamicScene { std::map<unsigned, unsigned> mScenes; std::vector<SceneAction> mActions; }; std::unordered_map<unsigned, std::vector<SceneSequence>> LoadSceneSequences(FileBuffer& fb); std::unordered_map<unsigned, SceneIndex> LoadSceneIndices(FileBuffer& fb); std::unordered_map<unsigned, Scene> LoadScenes(FileBuffer& fb); std::vector<SceneAction> LoadDynamicScenes(FileBuffer& fb); FileBuffer DecompressTTM(FileBuffer& fb); // Helper during loading struct SceneChunk { SceneChunk( Actions action, std::optional<std::string> resourceName, std::vector<std::int16_t> arguments) : mAction{action}, mResourceName{resourceName}, mArguments{arguments} {} Actions mAction; std::optional<std::string> mResourceName; std::vector<std::int16_t> mArguments; }; }
3,051
C++
.h
118
20.364407
92
0.652563
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,521
sounds.hpp
xavieran_BaKGL/bak/sounds.hpp
#pragma once namespace BAK { static constexpr auto sTeleportSound = 0xc; }
78
C++
.h
4
17.75
43
0.816901
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,522
gameData.hpp
xavieran_BaKGL/bak/gameData.hpp
#pragma once #include <glm/glm.hpp> #include "bak/constants.hpp" #include "bak/character.hpp" #include "bak/condition.hpp" #include "bak/container.hpp" #include "bak/combat.hpp" #include "bak/dialogAction.hpp" #include "bak/encounter/encounter.hpp" #include "bak/money.hpp" #include "bak/party.hpp" #include "bak/resourceNames.hpp" #include "bak/saveManager.hpp" #include "bak/skills.hpp" #include "bak/spells.hpp" #include "bak/timeExpiringState.hpp" #include "bak/types.hpp" #include "bak/worldClock.hpp" #include "com/logger.hpp" #include "bak/fileBufferFactory.hpp" #include <vector> #include <memory> namespace BAK { class GameData { public: /* * * 0x04fb0 - Combat locations * Note: This is only populated if loaded by a tile * 0x52f0 - combat 1 location start * c8 a4 00 00 5a 2b 00 00 00 80 00 03 00 * X loc yloc rotation State (dead/alive/invislbe?) * 0x0913e - Events End?? * @10 bytes each => 1678 combat locs? * */ /* * Combat starts 31340 - 12 2 06 - 12 sprite 2,6 grid location * Combat Zone 1 1 * Inventory #3 Combat #1 Person #0 0x460b7 * Combat Stats #3 0x9268 (bbe0)? */ // Offset refers to the raw offset in the save file // "Flag" refers to the flag used in the code that is // processed by "CalculateEventOffset" or "CalculateComplexEventOffset" // to generate a raw offset static constexpr auto sCharacterCount = 6; static constexpr auto sChapterOffset = 0x5a; // -> 5c static constexpr auto sMapPositionOffset = 0x5c; // -> 4c static constexpr auto sGoldOffset = 0x66; // -> 6a static constexpr auto sTimeOffset = 0x6a; // -> 0x72 static constexpr auto sLocationOffset = 0x76; // -> 0x88 static constexpr auto sCharacterNameOffset = 0x9f; // -> 0xdb static constexpr auto sCharacterNameLength = 10; static constexpr auto sCharacterSkillOffset = 0xdb; // -> 0x315 static constexpr auto sCharacterSkillLength = 5 * 16 + 8 + 7; static constexpr auto sActiveCharactersOffset = 0x315; // -> 0x319 // static constexpr auto sCharacterStatusOffset = 0x330; static constexpr auto sCharacterSkillAffectorOffset = 0x35a; static constexpr auto sTimeExpiringEventRecordOffset = 0x616; static constexpr auto sActiveSpells = 0x6b8; static constexpr auto sPantathiansEventFlag = 0x1ed4; static constexpr auto sCombatEntityListCount = 700; static constexpr auto sCombatEntityListOffset = 0x1383; static constexpr auto sCombatWorldLocationsOffset = 0x4fab; static constexpr auto sCombatWorldLocationsCount = 1400; static constexpr auto sCombatSkillsListOffset = 0x914b; static constexpr auto sCombatSkillsListCount = 1698; static constexpr auto sCombatGridLocationsOffset = 0x31349; static constexpr auto sCombatGridLocationsCount = 1699; static constexpr auto sCombatStatsOffset = 0x914b; static constexpr auto sCombatStatsCount = 1698; static constexpr auto sCharacterInventoryOffset = 0x3a804; // -> 3aa4b static constexpr auto sCharacterInventoryLength = 0x70; // -> 3aa4b static constexpr auto sPartyKeyInventoryOffset = 0x3aaa4; static constexpr std::array<std::pair<unsigned, unsigned>, 13> sZoneContainerOffsets = { std::make_pair(0x3ab4f, 15), // cheat chests and debug inventories... {0x3b621, 36}, {0x3be55, 25}, {0x3c55f, 54}, {0x3d0b4, 65}, {0x3dc07, 63}, {0x3e708, 131}, {0x3f8b2, 115}, {0x40c97, 67}, {0x416b7, 110}, {0x42868, 25}, {0x43012, 30}, {0x4378f, 60} }; static constexpr auto sShopsCount = 98; static constexpr auto sShopsOffset = 0x443c9; static constexpr auto sCombatInventoryCount = 1734; static constexpr auto sCombatInventoryOffset = 0x46053; GameData(const std::string& save); void Save(const SaveFile& saveFile) { Save(saveFile.mName, saveFile.mPath); } void Save( const std::string& saveName, const std::string& savePath) { ASSERT(saveName.size() < 30); mBuffer.Seek(0); mBuffer.PutString(saveName); mLogger.Info() << "Saving game to: " << savePath << std::endl; auto saveFile = std::ofstream{ savePath, std::ios::binary | std::ios::out}; mBuffer.Save(saveFile); } FileBuffer& GetFileBuffer() { return mBuffer; } std::vector<TimeExpiringState> LoadTimeExpiringState(); SpellState LoadSpells(); std::vector<SkillAffector> GetCharacterSkillAffectors(CharIndex character); /* ************* LOAD Game STATE ***************** */ static constexpr unsigned GetCharacterNameOffset(unsigned c) { return c * sCharacterNameLength + sCharacterNameOffset; } static constexpr unsigned GetCharacterSkillOffset(unsigned c) { return c * sCharacterSkillLength + sCharacterSkillOffset; } static constexpr unsigned GetCharacterInventoryOffset(unsigned c) { return c * sCharacterInventoryLength + sCharacterInventoryOffset; } static constexpr unsigned GetCharacterConditionOffset(unsigned c) { return c * Conditions::sNumConditions + sCharacterStatusOffset; } static constexpr unsigned GetCharacterAffectorsOffset(unsigned c) { return (c * 8 * 14) + sCharacterSkillAffectorOffset; } Party LoadParty(); std::vector<Character> LoadCharacters(); Conditions LoadConditions(unsigned character); unsigned LoadChapter(); Royals LoadGold(); std::vector<CharIndex> LoadActiveCharacters(); MapLocation LoadMapLocation(); Location LoadLocation(); WorldClock LoadWorldTime(); Inventory LoadCharacterInventory(unsigned offset); std::vector<GenericContainer> LoadShops(); std::vector<GenericContainer> LoadContainers(unsigned zone); std::vector<GenericContainer> LoadCombatInventories(); // Probably not chapter offsets.. ? void LoadChapterOffsetP(); std::vector<CombatEntityList> LoadCombatEntityLists(); std::vector<CombatGridLocation> LoadCombatGridLocations(); std::vector<CombatWorldLocation> LoadCombatWorldLocations(); void LoadCombatStats(unsigned offset, unsigned num); void LoadCombatClickedTimes(); mutable FileBuffer mBuffer; Logging::Logger mLogger; const std::string mName; Chapter mChapter; MapLocation mMapLocation; Location mLocation; WorldClock mTime; Party mParty; }; }
6,488
C++
.h
154
36.792208
139
0.715172
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,523
resourceNames.hpp
xavieran_BaKGL/bak/resourceNames.hpp
#pragma once #include <functional> #include <sstream> #include <iomanip> namespace BAK { constexpr auto DIALOG_POINTERS = "DEF_DIAL.DAT"; constexpr auto TOWN_DEFINITIONS = "DEF_TOWN.DAT"; class ZoneLabel { public: ZoneLabel(unsigned zoneNumber) : mZoneLabel{std::invoke([&]{ std::stringstream ss{}; ss << "Z" << std::setw(2) << std::setfill('0') << zoneNumber; return ss.str(); })} {} ZoneLabel(const std::string& zoneLabel) : mZoneLabel{zoneLabel} {} std::string GetHorizon() const { std::stringstream ss{""}; ss << GetZone() << "H.SCX"; return ss.str(); } std::string GetTerrain() const { std::stringstream ss{""}; ss << GetZone() << "L.SCX"; return ss.str(); } std::string GetSpriteSlot(unsigned i) const { std::stringstream ss{""}; ss << GetZone() << "SLOT" << std::setfill('0') << std::setw(1) << i << ".BMX"; return ss.str(); } std::string GetPalette() const { std::stringstream ss{""}; ss << GetZone() << ".PAL"; return ss.str(); } std::string GetTile(unsigned x, unsigned y) const { std::stringstream ss{""}; ss << "T" << std::setfill('0') << mZoneLabel.substr(1,2) << std::setw(2) << x << std::setw(2) << y; return ss.str(); } std::string GetTileWorld(unsigned x, unsigned y) const { return GetTile(x, y) + ".WLD"; } std::string GetTileData(unsigned x, unsigned y) const { return GetTile(x, y) + ".DAT"; } std::string GetTable() const { std::stringstream ss{""}; ss << GetZoneLabel() << ".TBL"; return ss.str(); } std::string GetZone() const { return mZoneLabel.substr(0, 3); } std::string GetZoneLabel() const { return mZoneLabel; } unsigned GetZoneNumber() const { return std::atoi(mZoneLabel.substr(1,2).c_str()); } std::string GetZoneReference() const { std::stringstream ss{""}; ss << GetZoneLabel() << "REF.DAT"; return ss.str(); }; std::string GetZoneDefault() const { std::stringstream ss{""}; ss << GetZoneLabel() << "DEF.DAT"; return ss.str(); }; std::string GetZoneMap() const { std::stringstream ss{""}; ss << GetZoneLabel() << "MAP.DAT"; return ss.str(); }; std::string GetZoneDat() const { std::stringstream ss{""}; ss << GetZoneLabel() << ".DAT"; return ss.str(); }; private: std::string mZoneLabel; }; }
2,723
C++
.h
108
18.712963
73
0.535466
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,524
objectInfo.hpp
xavieran_BaKGL/bak/objectInfo.hpp
#pragma once #include "bak/types.hpp" #include <array> #include <ostream> #include <string> namespace BAK { enum class Modifier { Flaming = 0, SteelFire = 1, Frost = 2, Enhancement1 = 3, Enhancement2 = 4, Blessing1 = 5, Blessing2 = 6, Blessing3 = 7 }; std::string_view ToString(Modifier); std::ostream& operator<<(std::ostream& os, Modifier); Modifier ToModifier(unsigned modifierMask); enum class RacialModifier { None, Tsurani, Elf, Human, Dwarf }; std::string_view ToString(RacialModifier); enum class SaleCategory : std::uint16_t { Jewellery = 0x0000, Utility = 0x0001, Rations = 0x0002, PreciousGems = 0x0004, Keys = 0x0008, All = 0x0010, // I put this here... QuestItem = 0x0020, UsableMundaneItem = 0x0040, Sword = 0x0080, CrossbowRelated = 0x0100, Armor = 0x0200, UsableMagicalItem = 0x0400, Staff = 0x0800, Scroll = 0x1000, BookOrNote = 0x2000, Potions = 0x4000, Modifier = 0x8000 }; std::string_view ToString(SaleCategory); std::ostream& operator<<(std::ostream& os, SaleCategory cat); enum class ItemCategory : std::uint16_t { Inn, // ale and brandy, etc. Key, Armor, NonSaleable, Other, Rations, Gemstones, Combat, // potion noxum, powder bag, tuning fork Crossbow, Sword, // include quarrel & bowstring Scroll, // excl. Valheru Armor Magical, Staff, // excl. Crystal Staff Book, // excl. Journals Potion, // incl. Herbal Pack Modifier // incl. Coltari }; std::string_view ToString(ItemCategory); std::ostream& operator<<(std::ostream& os, ItemCategory cat); std::vector<SaleCategory> GetCategories(std::uint16_t); enum class ItemType { Unspecified = 0, Sword = 1, Crossbow = 2, Staff = 3, Armor = 4, Key = 7, Tool = 8, WeaponOil = 9, ArmorOil = 0xa, SpecialOil = 0xb, Bowstring = 0xc, Scroll = 0xd, Note = 0x10, Book = 0x11, Potion = 0x12, Restoratives = 0x13, ConditionModifier = 0x14, Light = 0x15, Ingredient = 0x16, Ration = 0x17, Food = 0x18, Other = 0x19 }; std::string_view ToString(ItemType); struct GameObject { std::string mName{}; unsigned int mFlags{}; int mLevel{}; int mValue{}; int mStrengthSwing{}; int mAccuracySwing{}; int mStrengthThrust{}; int mAccuracyThrust{}; unsigned mImageIndex{}; unsigned mImageSize{}; unsigned mUseSound{}; unsigned mSoundPlayTimes{}; unsigned mStackSize{}; unsigned mDefaultStackSize{}; RacialModifier mRace{}; std::uint16_t mCategories{}; ItemType mType{}; std::uint16_t mEffectMask{}; std::int16_t mEffect{}; std::uint16_t mPotionPowerOrBookChance{}; std::uint16_t mAlternativeEffect{}; std::uint16_t mModifierMask{}; std::int16_t mModifier{}; std::uint16_t mDullFactor0{}; std::uint16_t mDullFactor1{}; std::uint16_t mMinCondition{}; }; std::ostream& operator<<(std::ostream&, const GameObject&); class ObjectIndex { public: static constexpr auto sObjectCount = 0x8a; static const ObjectIndex& Get(); const GameObject& GetObject(ItemIndex) const; Royals GetScrollValue(SpellIndex) const; private: ObjectIndex(); std::array<GameObject, sObjectCount> mObjects; std::vector<Royals> mScrollValues; }; std::ostream& operator<<(std::ostream&, const ObjectIndex&); }
3,637
C++
.h
143
21.398601
61
0.641558
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,525
zone.hpp
xavieran_BaKGL/bak/zone.hpp
#pragma once #include "bak/encounter/encounter.hpp" #include "bak/fixedObject.hpp" #include "bak/resourceNames.hpp" #include "bak/palette.hpp" #include "bak/worldFactory.hpp" #include "graphics/cube.hpp" #include "graphics/meshObject.hpp" namespace BAK { // Contains all the data one would need for a zone class Zone { public: Zone(unsigned zoneNumber) : mZoneLabel{zoneNumber}, mPalette{mZoneLabel.GetPalette()}, mFixedObjects{LoadFixedObjects(zoneNumber)}, mZoneTextures{mZoneLabel, mPalette}, mZoneItems{mZoneLabel, mZoneTextures}, mWorldTiles{mZoneItems, BAK::Encounter::EncounterFactory{}}, mObjects{} { for (auto& item : mZoneItems.GetItems()) mObjects.AddObject( item.GetName(), BAK::ZoneItemToMeshObject(item, mZoneTextures, mPalette)); const auto monsters = MonsterNames::Get(); for (unsigned i = 0; i < monsters.size(); i++) { mObjects.AddObject( monsters.GetMonsterAnimationFile(MonsterIndex{i}), BAK::ZoneItemToMeshObject( ZoneItem{i, monsters, mZoneTextures}, mZoneTextures, mPalette)); } const auto cube = Graphics::Cuboid{1, 1, 50}; mObjects.AddObject("Combat", cube.ToMeshObject(glm::vec4{1.0, 0, 0, .3})); mObjects.AddObject("Trap", cube.ToMeshObject(glm::vec4{.8, 0, 0, .3})); mObjects.AddObject("Dialog", cube.ToMeshObject(glm::vec4{0.0, 1, 0, .3})); //mObjects.AddObject("Dialog", cube.ToMeshObject(glm::vec4{0.0, 1, 0, .0})); mObjects.AddObject("Zone", cube.ToMeshObject(glm::vec4{1.0, 1, 0, .3})); mObjects.AddObject("GDSEntry", cube.ToMeshObject(glm::vec4{1.0, 0, 1, .3})); mObjects.AddObject("EventFlag", cube.ToMeshObject(glm::vec4{.0, .0, .7, .3})); mObjects.AddObject("Block", cube.ToMeshObject(glm::vec4{0,0,0, .3})); const auto click = Graphics::Cuboid{1, 1, 50}; mObjects.AddObject("clickable", click.ToMeshObject(glm::vec4{1.0, 0, 0, .3})); const auto enemy = Graphics::Cuboid{1, 1, 6}; mObjects.AddObject("enemy", enemy.ToMeshObject(glm::vec4{0.0, 1.0, 1.0, .8})); } ZoneLabel mZoneLabel; BAK::Palette mPalette; std::vector<GenericContainer> mFixedObjects; BAK::ZoneTextureStore mZoneTextures; ZoneItemStore mZoneItems; WorldTileStore mWorldTiles; Graphics::MeshObjectStorage mObjects; }; }
2,531
C++
.h
60
34.383333
86
0.641548
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,526
palette.hpp
xavieran_BaKGL/bak/palette.hpp
#pragma once #include <glm/glm.hpp> #include <functional> #include <string> #include <vector> namespace BAK { class Palette; class ColorSwap { public: static constexpr auto sSize = 256; ColorSwap(const std::string& filename); const glm::vec4& GetColor(unsigned i, const Palette&) const; private: std::vector<unsigned> mIndices; }; class Palette { public: Palette(const std::string& filename); Palette(const Palette& pal, const ColorSwap& cs) : mColors{std::invoke([&](){ auto swappedPal = std::vector<glm::vec4>{}; for (unsigned i = 0; i < 256; i++) { swappedPal.emplace_back(cs.GetColor(i, pal)); } return swappedPal; })} { } const glm::vec4& GetColor(unsigned i) const; private: std::vector<glm::vec4> mColors; }; }
867
C++
.h
37
18.405405
64
0.627907
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,527
lock.hpp
xavieran_BaKGL/bak/lock.hpp
#pragma once #include "bak/inventoryItem.hpp" #include "bak/skills.hpp" #include "bak/fileBufferFactory.hpp" #include <optional> #include <ostream> namespace BAK { struct LockStats { unsigned mLockFlag; unsigned mRating; unsigned mFairyChestIndex; unsigned mTrapDamage; bool IsFairyChest() { return mFairyChestIndex != 0; } bool IsTrapped() { return mLockFlag == 1 || mLockFlag == 4; } }; LockStats LoadLock(FileBuffer& fb); struct FairyChest { std::string mAnswer; std::vector<std::string> mOptions; std::string mHint; }; std::ostream& operator<<(std::ostream&, const LockStats&); struct Door { DoorIndex mDoorIndex; }; std::ostream& operator<<(std::ostream&, const Door&); // This is the lock "image" type enum class LockType { Easy, Medium, Hard, Unpickable }; std::string_view ToString(LockType); LockType ClassifyLock(unsigned lockRating); std::optional<unsigned> GetLockIndex(unsigned lockRating); ItemIndex GetCorrespondingKey(unsigned lockIndex); unsigned DescribeLock(unsigned picklockSkill, unsigned lockRating); bool TryOpenLockWithKey(const BAK::InventoryItem&, unsigned lockRating); bool WouldKeyBreak(const BAK::InventoryItem&, unsigned lockRating); bool KeyBroken(const InventoryItem& item, unsigned skill, unsigned lockRating); bool PicklockBroken(unsigned skill, unsigned lockRating); bool PicklockSkillImproved(); bool CanPickLock(unsigned skill, unsigned lockRating); FairyChest GenerateFairyChest(const std::string&); }
1,550
C++
.h
56
24.714286
79
0.767821
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,528
imageStore.hpp
xavieran_BaKGL/bak/imageStore.hpp
#pragma once #include "bak/image.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK { std::vector<Image> LoadImages(FileBuffer& fb); }
145
C++
.h
6
22.333333
46
0.791045
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,529
soundStore.hpp
xavieran_BaKGL/bak/soundStore.hpp
#pragma once #include "bak/sound.hpp" #include <unordered_map> #include <vector> namespace BAK { class SoundData { public: SoundData( std::string name, unsigned type, std::vector<Sound>&& sounds) : mName{name}, mType{type}, mSounds{std::move(sounds)} { } std::vector<Sound>& GetSounds() { return mSounds; } private: std::string mName; unsigned mType; std::vector<Sound> mSounds; }; class SoundStore { static constexpr auto sSoundFile = "frp.sx"; public: static SoundStore& Get(); SoundData& GetSoundData(unsigned id); private: SoundStore(); std::unordered_map<unsigned, SoundData> mSoundMap; }; }
709
C++
.h
35
16.057143
55
0.661631
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,530
haggle.hpp
xavieran_BaKGL/bak/haggle.hpp
#pragma once #include "bak/character.hpp" #include "bak/party.hpp" #include "bak/shop.hpp" #include "com/random.hpp" #include <algorithm> #include <cmath> namespace BAK::Haggle { std::optional<unsigned> TryHaggle( Party& party, ActiveCharIndex character, ShopStats& shop, ItemIndex item, int shopCurrentValue); }
339
C++
.h
15
19.866667
34
0.751572
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,531
textVariableStore.hpp
xavieran_BaKGL/bak/textVariableStore.hpp
#pragma once #include "bak/dialog.hpp" #include "bak/dialogAction.hpp" #include "bak/dialogChoice.hpp" #include "bak/gameData.hpp" #include "bak/money.hpp" #include "bak/types.hpp" #include "com/logger.hpp" #include "com/visit.hpp" #include <string> #include <regex> #include <unordered_map> namespace BAK { class TextVariableStore { public: TextVariableStore() : mTextVariables{}, mSelectedCharacter{}, mLogger{Logging::LogState::GetLogger("BAK::TextVariableStore")} {} void Clear() { mTextVariables.clear(); } void SetTextVariable(unsigned variable, std::string value) { mLogger.Spam() << "Setting " << variable << " to " << value << "\n"; mTextVariables.emplace(MakeVariableName(variable), value); } void SetActiveCharacter(std::string value) { mSelectedCharacter = value; } std::string SubstituteVariables(const std::string& text) const { auto newText = text; for (const auto& [key, value] : mTextVariables) { mLogger.Spam() << "replacing " << key << " with " << value << "\n"; newText = std::regex_replace( newText, std::regex{key}, value); } // Do this last so it doesn't break all the others newText = std::regex_replace( newText, std::regex{"@"}, mSelectedCharacter); return newText; } private: std::string MakeVariableName(unsigned variable) { std::stringstream ss{}; ss << "@" << variable; return ss.str(); } std::unordered_map<std::string, std::string> mTextVariables; std::string mSelectedCharacter; const Logging::Logger& mLogger; }; }
1,806
C++
.h
65
21.292308
79
0.606148
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,532
skills.hpp
xavieran_BaKGL/bak/skills.hpp
#pragma once #include "com/assert.hpp" #include "com/strongType.hpp" #include "bak/condition.hpp" #include "bak/worldClock.hpp" #include "bak/file/fileBuffer.hpp" #include <array> #include <numeric> #include <ostream> #include <string_view> namespace BAK { enum class SkillType { Health = 0, Stamina = 1, Speed = 2, Strength = 3, Defense = 4, Crossbow = 5, Melee = 6, Casting = 7, Assessment = 8, Armorcraft = 9, Weaponcraft = 0xa, Barding = 0xb, Haggling = 0xc, Lockpick = 0xd, Scouting = 0xe, Stealth = 0xf, TotalHealth = 0x10 }; enum class SkillTypeMask { Health = 1, Stamina = 2, Speed = 4, Strength = 8, Defense = 0x10, Crossbow = 0x20, Melee = 0x40, Casting = 0x80, Assessment = 0x100, Armorcraft = 0x200, Weaponcraft = 0x400, Barding = 0x800, Haggling = 0x1000, Lockpick = 0x2000, Scouting = 0x4000, Stealth = 0x8000, TotalHealth = 0x10000 }; enum class SkillChange { Direct = 0, FractionOfSkill = 1, DifferenceOfSkill = 2, ExercisedSkill = 3, HealMultiplier_80 = 80, HealMultiplier_100 = 100 }; enum class SkillRead { Current = 0, MaxSkill = 1, TrueSkill = 3, NoHealthEffect = 4 }; static constexpr auto sEffectiveSkillMin = std::array<std::uint16_t, 16>{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static constexpr auto sSkillCaps = std::array<std::uint16_t, 16>{ 0x1f4, 0x1f4, 0x1f4, 0x1f4, 0x0c8, 0x0c8, 0x0c8, 0x0c8, 0x0c8, 0x0c8, 0x0c8, 0x0c8, 0x0c8, 0x064, 0x0c8, 0x0c8}; constexpr std::uint16_t sSkillAbsMax = 0xfa; constexpr std::uint8_t sSkillHealthEffect[16] = { 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2}; constexpr std::uint8_t sSkillExperienceVar1[16] = { 3, 3, 1, 1, 2, 3, 1, 3, 8, 5, 5, 0x20, 2, 3, 8, 1}; constexpr std::uint8_t sSkillExperienceVar2[16] = { 0x33, 0x33, 8, 8, 8, 0x33, 8, 0x33, 0, 0, 0, 0x80, 0x20, 0x33, 0, 0x40}; constexpr std::uint8_t sSkillMin[16] = { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; constexpr std::uint8_t sSkillMax[16] = { 0xFA, 0xFA, 0xFA, 0xFA, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64, 0x64}; constexpr std::uint8_t sTotalSelectedSkillPool = 0x1a; std::string_view ToString(SkillType); SkillType ToSkill(SkillTypeMask); struct Skill { std::uint8_t mMax; std::uint8_t mTrueSkill; std::uint8_t mCurrent; std::uint8_t mExperience; std::int8_t mModifier; bool mSelected; bool mUnseenImprovement; }; std::ostream& operator<<(std::ostream&, const Skill&); struct SkillAffector { std::uint16_t mType; SkillType mSkill; int mAdjustment; Time mStartTime; Time mEndTime; }; std::ostream& operator<<(std::ostream&, const SkillAffector&); class Skills; unsigned CalculateEffectiveSkillValue( SkillType, Skills&, const Conditions&, const std::vector<SkillAffector>&, SkillRead); void DoImproveSkill( SkillType skillType, Skill& skill, SkillChange skillChangeType, unsigned multiplier, unsigned selectedSkillPool); signed DoAdjustHealth( Skills& skills, Conditions& conditions, signed healthChangePercent, signed multiplier); class Skills { public: static constexpr auto sSkills = 16; using SkillArray = std::array<Skill, sSkills>; Skills(const SkillArray&, unsigned); Skills() = default; Skills(const Skills&) = default; Skills& operator=(const Skills&) = default; Skills(Skills&&) = default; Skills& operator=(Skills&&) = default; const Skill& GetSkill(SkillType skill) const; Skill& GetSkill(SkillType skill); void SetSkill(BAK::SkillType skillType, const Skill& skill); void SetSelectedSkillPool(unsigned); void ToggleSkill(BAK::SkillType skillType); void ClearUnseenImprovements(); std::uint8_t CalculateSelectedSkillPool() const; void ImproveSkill( Conditions& conditions, SkillType skill, SkillChange skillChangeType, int multiplier); friend std::ostream& operator<<(std::ostream&, const Skills&); private: SkillArray mSkills{}; unsigned mSelectedSkillPool{}; }; std::ostream& operator<<(std::ostream&, const Skills&); Skills LoadSkills(FileBuffer&); }
4,456
C++
.h
160
23.825
76
0.656485
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,533
dialogAction.hpp
xavieran_BaKGL/bak/dialogAction.hpp
#pragma once #include "bak/condition.hpp" #include "bak/timeExpiringState.hpp" #include "bak/types.hpp" #include "bak/skills.hpp" #include "bak/dialogTarget.hpp" #include "bak/worldClock.hpp" #include <glm/glm.hpp> #include <variant> namespace BAK { enum class DialogResult { SetTextVariable = 0x01, GiveItem = 0x02, LoseItem = 0x03, SetFlag = 0x04, LoadActor = 0x05, SetPopupDimensions = 0x06, SpecialAction = 0x07, GainCondition = 0x08, GainSkill = 0x09, LoadSkillValue = 0x0a, //PlaySound2 = 0x0b, unused, but calls same code as play sound... PlaySound = 0x0c, ElapseTime = 0x0d, SetAddResetState = 0x0e, // This seems irrelevant to us - calls a function which // seems to reset some state and free memory FreeMemoryP = 0x0f, PushNextDialog = 0x10, UpdateCharacters = 0x11, HealCharacters = 0x12, LearnSpell = 0x13, Teleport = 0x14, SetEndOfDialogState = 0x15, SetTimeExpiringState = 0x16, LoseNOfItem = 0x17, // 18 - seems to remove/move mney at a chapter transition BuggedAction = 0xff }; enum class SpecialActionType : std::uint16_t { ReduceGold = 0, // reduces party gold by val of item or to 0 if lt IncreaseGold = 1, RepairAllEquippedArmor = 2, ResetCombatState = 3, SetCombatState = 4, CopyStandardInnToShop0 = 5, CopyStandardInnToShop1 = 6, Increase753f = 7, // this literally adds the value to 753f Gamble = 8, RepairAndBlessEquippedSwords = 9, // this does something funky with inventory ReturnAlcoholToShops = 10, ResetGambleValueTo = 11, BeginCombat = 12, ExtinguishAllLightSources = 13, // seems to expire TESs EmptyArlieContainer = 14, CheatIncreaseSkill = 15, UnifyOwynAndPugsSpells = 16, // modifies vars at 3ec3 and 3f22 }; struct SetTextVariable { // Sets the variable (@mWhich) to mWhat std::uint16_t mWhich; // mWhat: // 0x0b - selected party member (e.g. give item to b) // 0x10 - other party member? // 0x11 - monster ? // 0x12 - chosen item (e.g. in bless screen choose a sword) // 0x13 - shop cost (e.g. in bless screen cost of blessing) // 0x14 - party wallet (e.g. in bless screen amount of cash) // 0x1c - shop attendant name (e.g. shop keeper) // 0x1d - Stat? e.g. health std::uint16_t mWhat; std::array<std::uint8_t, 4> mRest; }; struct LoseItem { std::uint16_t mItemIndex; std::uint16_t mQuantity; std::array<std::uint8_t, 4> mRest; }; struct GiveItem { std::uint8_t mItemIndex; std::uint8_t mWho; std::uint16_t mQuantity; std::array<std::uint8_t, 4> mRest; }; // single bit flags // 1 -> ab (these are for dialog choices) // and // 1a2d -> 1fd3 // 104 (seems to be set to 0 when short of money?) struct SetFlag { std::uint16_t mEventPointer; std::uint8_t mEventMask; std::uint8_t mEventData; std::uint16_t mAlwaysZero; std::uint16_t mEventValue; }; // Unclear what this does. Modifying it in the DIAL_Z** files // and running the game seems to do nothing. It is definitely // related to the actor portrait index, but unclear how. // Maybe preloads palettes and images???? struct LoadActor { std::uint16_t mActor1; std::uint16_t mActor2; std::uint16_t mActor3; std::uint16_t mUnknown; }; struct SetPopupDimensions { glm::vec2 mPos; glm::vec2 mDims; }; struct GainCondition { // if flag == 0 or 1 affects all // 2 affects person who was set by "SetTextVariable" // 8, 9 - locklear // if flag == 7 gorath last person in party? // if flag == 6 locklear party leader.. ? // if flag == 5 owyn second party member? // std::uint16_t mWho; Condition mCondition; std::int16_t mMin; std::int16_t mMax; }; struct GainSkill { std::uint16_t mWho; SkillType mSkill; std::int16_t mMin; std::int16_t mMax; }; struct SpecialAction { SpecialActionType mType; std::uint16_t mVar1; std::uint16_t mVar2; std::uint16_t mVar3; }; struct LoadSkillValue { std::uint16_t mTarget; SkillType mSkill; }; struct PlaySound { std::uint16_t mSoundIndex; std::uint16_t mFlag; std::uint32_t mRest; }; struct ElapseTime { Time mTime; std::array<std::uint8_t, 4> mRest; }; struct PushNextDialog { BAK::Target mTarget; std::array<std::uint8_t, 4> mRest; }; struct UpdateCharacters { std::vector<CharIndex> mCharacters; }; struct Teleport { TeleportIndex mIndex; }; struct SetAddResetState { std::uint16_t mEventPtr; std::uint16_t mUnknown0; Time mTimeToExpire; }; struct HealCharacters { std::uint16_t mWho; std::uint16_t mHowMuch; }; struct SetEndOfDialogState { std::int16_t mState; std::array<std::uint8_t, 6> mRest; }; struct LearnSpell { LearnSpell( std::uint16_t who, std::uint16_t whichSpell) : mWho(who), mWhichSpell(whichSpell) {} std::uint16_t mWho; SpellIndex mWhichSpell; }; struct SetTimeExpiringState { ExpiringStateType mType; std::uint8_t mFlags; std::uint16_t mEventPtr; Time mTimeToExpire; }; struct LoseNOfItem { std::uint16_t mItemIndex; std::uint16_t mQuantity; std::array<std::uint8_t, 4> mRest; }; struct BuggedAction { std::array<std::uint8_t, 8> mRest; }; struct UnknownAction { UnknownAction( std::uint16_t type, const std::array<std::uint8_t, 8>& rest) : mType{static_cast<DialogResult>(type)}, mRest{rest} {} DialogResult mType; std::array<std::uint8_t, 8> mRest; }; using DialogAction = std::variant< SetTextVariable, GiveItem, LoseItem, SetFlag, LoadActor, SetPopupDimensions, SpecialAction, GainCondition, GainSkill, LoadSkillValue, PlaySound, ElapseTime, SetAddResetState, PushNextDialog, UpdateCharacters, HealCharacters, LearnSpell, Teleport, SetEndOfDialogState, SetTimeExpiringState, LoseNOfItem, BuggedAction, UnknownAction>; std::ostream& operator<<(std::ostream& os, const DialogAction& d); }
6,174
C++
.h
258
20.166667
81
0.681463
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,534
dataTags.hpp
xavieran_BaKGL/bak/dataTags.hpp
#pragma once #include <cstdint> namespace BAK { enum class DataTag : std::uint32_t { ADS = 0x3a534441, APP = 0x3a505041, BIN = 0x3a4e4942, BMP = 0x3a504d42, DAT = 0x3a544144, FNT = 0x3a544e46, GID = 0x3a444947, INF = 0x3a464e49, MAP = 0x3a50414d, PAG = 0x3a474150, PAL = 0x3a4c4150, RES = 0x3a534552, SCR = 0x3a524353, SND = 0x3a444e53, TAG = 0x3a474154, TT3 = 0x3a335454, TTI = 0x3a495454, VER = 0x3a524556, VGA = 0x3a414756 }; }
511
C++
.h
25
16.24
36
0.641079
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,535
inventory.hpp
xavieran_BaKGL/bak/inventory.hpp
#pragma once #include "bak/inventoryItem.hpp" #include "bak/objectInfo.hpp" #include "bak/skills.hpp" #include "com/assert.hpp" #include "com/strongType.hpp" #include "bak/fileBufferFactory.hpp" #include <iostream> #include <optional> #include <vector> namespace BAK { using InventoryIndex = StrongType<unsigned, struct InventoryIndexTag>; class Inventory { public: Inventory( unsigned capacity) : mCapacity{capacity}, mItems{} {} Inventory( unsigned capacity, std::vector<InventoryItem>&& items) : mCapacity{capacity}, mItems{std::move(items)} {} Inventory(Inventory&&) noexcept = default; Inventory& operator=(Inventory&&) noexcept = default; Inventory(const Inventory&) noexcept = default; Inventory& operator=(const Inventory&) noexcept = default; const auto& GetItems() const { return mItems; } auto& GetItems() { return mItems; } std::size_t GetCapacity() const { return mCapacity; } std::size_t GetNumberItems() const { return mItems.size(); } std::size_t GetSpaceUsed() const; const auto& GetAtIndex(InventoryIndex i) const { ASSERT(i.mValue < mItems.size()); return mItems[i.mValue]; } auto& GetAtIndex(InventoryIndex i) { ASSERT(i.mValue < mItems.size()); return mItems[i.mValue]; } auto FindItem(const InventoryItem& item) const { return std::find_if( mItems.begin(), mItems.end(), [&item](const auto& elem){ return elem.GetItemIndex() == item.GetItemIndex(); }); } auto FindItem(const InventoryItem& item) { return std::find_if( mItems.begin(), mItems.end(), [&item](const auto& elem){ return elem.GetItemIndex() == item.GetItemIndex(); }); } std::optional<InventoryIndex> GetIndexFromIt(std::vector<InventoryItem>::iterator it) { if (it == mItems.end()) return std::nullopt; else return std::make_optional( static_cast<InventoryIndex>(std::distance(mItems.begin(), it))); } std::optional<InventoryIndex> GetIndexFromIt(std::vector<InventoryItem>::const_iterator it) const { if (it == mItems.end()) return std::nullopt; else return std::make_optional( static_cast<InventoryIndex>(std::distance(mItems.cbegin(), it))); } // Search for a stackable item prioritising incomplete stacks auto FindStack(const InventoryItem& item) const { // This is unpleasant, the dream would be to use // std::views::zip_view (C++23) with std::views::filter... ASSERT(item.IsStackable() || item.IsChargeBased()); auto items = std::vector< std::pair< std::size_t, std::reference_wrapper<const InventoryItem>>>{}; for (std::size_t i = 0; i < mItems.size(); i++) { if (mItems[i].GetItemIndex() == item.GetItemIndex()) items.emplace_back(i, std::ref(mItems[i])); } auto it = std::min_element(items.begin(), items.end(), [](const auto& l, const auto& r){ return (std::get<1>(l).get().GetQuantity() < std::get<1>(r).get().GetQuantity()); }); // If we didn't find an incomplete stack, return a complete one if (it == items.end()) return FindItem(item); else return std::next(mItems.begin(), it->first); } // Search for a stackable item prioritising incomplete stacks auto FindStack(const InventoryItem& item) { // Is there a better way? auto cit = static_cast<const Inventory*>(this)->FindStack(item); return std::next( mItems.begin(), std::distance(mItems.cbegin(), cit)); } auto FindEquipped(BAK::ItemType slot) const { return std::find_if( mItems.begin(), mItems.end(), [&slot](const auto& elem){ return elem.IsItemType(slot) && elem.IsEquipped(); }); } auto FindEquipped(BAK::ItemType slot) { return std::find_if( mItems.begin(), mItems.end(), [&slot](const auto& elem){ return elem.IsItemType(slot) && elem.IsEquipped(); }); } auto FindItemType(BAK::ItemType slot) const { return std::find_if( mItems.begin(), mItems.end(), [&slot](const auto& elem){ return elem.IsItemType(slot); }); } auto FindItemType(BAK::ItemType slot) { return std::find_if( mItems.begin(), mItems.end(), [&slot](const auto& elem){ return elem.IsItemType(slot); }); } bool HasIncompleteStack(const InventoryItem& item) const; // Characters can be added up to the size of the inventory // accounting for the size of items std::size_t CanAddCharacter(const InventoryItem& item) const; // Containers can be added up to their capacity std::size_t CanAddContainer(const InventoryItem& item) const; bool HaveItem(const InventoryItem& item) const; // Adds the given item with no checks void AddItem(const InventoryItem& item); bool RemoveItem(const InventoryItem& item); bool RemoveItem(BAK::InventoryIndex); bool RemoveItem(BAK::InventoryIndex, unsigned quantity); bool ReplaceItem(BAK::InventoryIndex, BAK::InventoryItem); void CheckPostConditions(); unsigned CalculateModifiers(SkillType skill) const { unsigned mods = 0; for (const auto& item : mItems) { if ((item.GetObject().mModifierMask & (1 << static_cast<unsigned>(skill))) != 0) { mods += item.GetObject().mModifier; } } return mods; } void CopyFrom(Inventory& other) { for (const auto& item : other.GetItems()) { auto newItem = item; newItem.SetActivated(false); newItem.SetEquipped(false); AddItem(newItem); } } private: // result > 0 if can add item to inventory. // for stackable items result amount is how // much of this item can be added to inventory. std::size_t CanAdd(bool fits, const InventoryItem& item) const; unsigned mCapacity; std::vector<InventoryItem> mItems; }; std::ostream& operator<<(std::ostream&, const Inventory&); Inventory LoadInventory( FileBuffer& fb, unsigned itemCount, unsigned capacity); }
6,757
C++
.h
196
26.403061
101
0.599417
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,536
coordinates.hpp
xavieran_BaKGL/bak/coordinates.hpp
#pragma once // BAK coordinate system // // Origin is at 0 // positive x goes right // positive y goes up // // e.g. // // T1117 (736'000, 1'120'000) // T1016 (672'000, 1'056'000) T1116 (736'000, 1'056'000) // // Need to convert this to open gl system by swapping y and z // and negating z (depth goes towards us) #include "bak/types.hpp" #include "graphics/glm.hpp" #include <glm/glm.hpp> #include <ostream> namespace BAK { using GamePosition = glm::uvec2; using GameHeading = std::uint16_t; struct GamePositionAndHeading { GamePosition mPosition; GameHeading mHeading; }; std::ostream& operator<<(std::ostream& os, const GamePositionAndHeading&); glm::uvec2 GetTile( glm::uvec2 pos); GamePosition MakeGamePositionFromTileAndCell( glm::uvec2 tile, glm::vec<2, std::uint8_t> offset); template <typename T> glm::vec<3, T> ToGlCoord(const glm::ivec3& coord) { return glm::vec<3, T>{ static_cast<T>(coord.x), static_cast<T>(coord.z), -static_cast<T>(coord.y)}; } template <typename T> glm::vec<3, T> ToGlCoord(const glm::uvec2& coord) { return glm::vec<3, T>{ static_cast<T>(coord.x), static_cast<T>(0), -static_cast<T>(coord.y)}; } // Convert a 16 bit BAK angle to radians glm::vec3 ToGlAngle(const glm::ivec3& angle); // Convert a 16 bit BAK angle to radians glm::vec2 ToGlAngle(GameHeading); template <typename T, typename C> glm::vec<4, T> ToGlColor(const C& color) { const auto F = [](auto x){ return static_cast<T>(x) / 256.; }; return glm::vec<4, T>{ F(color.r), F(color.g), F(color.b), F(color.a)}; } BAK::GameHeading ToBakAngle(double angle); double NormaliseRadians(double angle); // This is the location on the start of chapter map screen struct MapLocation { glm::uvec2 mPosition; std::uint16_t mHeading; }; std::ostream& operator<<(std::ostream& os, const MapLocation&); struct Location { ZoneNumber mZone; glm::uvec2 mTile; GamePositionAndHeading mLocation; }; std::ostream& operator<<(std::ostream& os, const Location&); std::uint16_t HeadingToFullMapAngle(std::uint16_t heading); }
2,194
C++
.h
81
23.975309
74
0.681361
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,537
model.hpp
xavieran_BaKGL/bak/model.hpp
#pragma once #include "com/logger.hpp" #include "bak/fileBufferFactory.hpp" #include "glm/fwd.hpp" #include <glm/glm.hpp> #include <optional> #include <string> #include <vector> namespace BAK { constexpr unsigned EF_TERRAIN = 0x00; constexpr unsigned EF_UNBOUNDED = 0x20; constexpr unsigned EF_2D_OBJECT = 0x40; struct ModelClip { unsigned xradius; unsigned yradius; unsigned flags; unsigned extras; char extraFlag; std::vector<glm::ivec2> textureCoords; std::vector<glm::ivec2> otherCoords; }; struct ClipPoint { glm::ivec2 mUV; glm::ivec2 mXY; }; struct ClipElement { std::vector<ClipPoint> mPoints; std::optional<ClipPoint> mExtraPoint; std::array<std::uint8_t, 3> mUnknown; }; struct ModelClipX { glm::ivec2 mRadius; bool hasVertical; std::vector<ClipElement> mElements; std::string mName; }; struct FaceOption { unsigned mFaceType; unsigned mEdgeCount; std::vector<glm::vec<4, std::uint8_t>> mFaceColors; std::vector<std::uint8_t> mPalettes; std::vector<std::vector<std::uint16_t>> mFaces; }; struct Mesh { std::vector<FaceOption> mFaceOptions; }; struct Component { std::vector<Mesh> mMeshes; }; struct Model { std::string mName; unsigned mEntityFlags; unsigned mEntityType; unsigned mTerrainType; unsigned mScale; unsigned mSprite; glm::ivec3 mMin; glm::ivec3 mMax; glm::ivec3 mPos; std::vector<glm::i32vec3> mVertices; std::vector<Component> mComponents; }; std::vector<std::string> LoadModelNames(FileBuffer& fb); std::vector<ModelClipX> LoadModelClip(FileBuffer& fb, unsigned numItems); std::vector<Model> LoadTBL(FileBuffer& fb); }
1,697
C++
.h
74
19.878378
73
0.729309
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,538
dialogChoice.hpp
xavieran_BaKGL/bak/dialogChoice.hpp
#pragma once #include "bak/dialogTarget.hpp" #include "bak/types.hpp" #include <ostream> #include <variant> namespace BAK { // Choice's that depend on the game's active state enum class ActiveStateFlag : std::uint16_t { // Context dependent Context = 0x7530, Money = 0x7531, // Tried to buy but can't afford CantAfford = 0x7533, Chapter = 0x7537, NightTime = 0x7539, DayTime = 0x753a, TimeBetween = 0x753c, SkillCheck = 0x753d, ItemValue_753e = 0x753e, Context_753f = 0x753f, // e.g. KeyTarget{1b7767} Repair, Flterchers Post == 4 Shop = 0x7542, Zone = 0x7543, // 0x7544 - 0x754c - which chapter Gambler = 0x754d // gambler has no money? }; std::string ToString(ActiveStateFlag f); enum class ChoiceMask : std::uint16_t { NoChoice = 0x0000, // Choices as present in conversations with NPCs (1 -> 0xab) Conversation = 0x00ab, // Keyword choices such as Yes/No, Buy/Haggle (f1 -> 118) Query = 0x01ff, EventFlag = 0x1fff, GameState = 0x75ff, CustomState = 0x9cff, Inventory = 0xc3ff, HaveNote = 0xc7ff, CastSpell = 0xcbff, Random = 0xcfff, ComplexEvent = 0xdfff, Unknown = 0xffff }; std::string_view ToString(ChoiceMask m); struct ConversationChoice { std::uint16_t mEventPointer; std::string mKeyword; }; struct QueryChoice { std::uint16_t mQueryIndex; std::string mKeyword; }; struct EventFlagChoice { std::uint16_t mEventPointer; }; struct GameStateChoice { ActiveStateFlag mState; }; enum class Scenario : std::uint8_t { MortificationOfTheFlesh = 1, Plagued = 2, HaveSixSuitsOfArmor = 3, AllPartyArmorIsGoodCondition = 4, PoisonedDelekhanArmyChests = 5, AnyCharacterSansWeapon = 6, AlwaysFalse = 7, AlwaysFalse2 = 8, AnyCharacterHasNegativeCondition = 9, AnyCharacterIsUnhealthy = 10, AllPartyMembersHaveNapthaMask = 11, NormalFoodInArlieChest = 12, // Guess... PoisonedFoodInArlieChest = 13 // ? }; struct CustomStateChoice { Scenario mScenario; }; struct InventoryChoice { ItemIndex mRequiredItem; }; struct ComplexEventChoice { std::uint16_t mEventPointer; //std::uint8_t mXorMask; //std::uint8_t mExpected; //std::uint8_t mMustEqualExpected; //std::uint8_t mChapterMask; }; struct NoChoice { }; struct CastSpellChoice { unsigned mRequiredSpell; }; struct HaveNoteChoice { unsigned mRequiredNote; }; struct RandomChoice { unsigned mRange; }; struct UnknownChoice { ChoiceMask mChoiceCategory; std::uint16_t mEventPointer; }; using Choice = std::variant< NoChoice, ConversationChoice, QueryChoice, EventFlagChoice, GameStateChoice, CustomStateChoice, InventoryChoice, ComplexEventChoice, CastSpellChoice, HaveNoteChoice, RandomChoice, UnknownChoice>; std::ostream& operator<<(std::ostream&, const Choice&); Choice CreateChoice(std::uint16_t state); struct DialogChoice { DialogChoice( std::uint16_t state, std::uint16_t min, std::uint16_t max, Target target); Choice mChoice; std::uint16_t mMin; std::uint16_t mMax; Target mTarget; }; std::ostream& operator<<(std::ostream&, const DialogChoice&); }
3,327
C++
.h
145
19.351724
64
0.699525
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,539
cutscenes.hpp
xavieran_BaKGL/bak/cutscenes.hpp
#pragma once #include "bak/types.hpp" #include <string> #include <variant> #include <vector> namespace BAK { struct TTMScene { std::string mAdsFile; std::string mTTMFile; }; struct BookChapter { std::string mBookFile; }; using CutsceneAction = std::variant<TTMScene, BookChapter>; class CutsceneList { public: static std::vector<CutsceneAction> GetStartScene(Chapter); static std::vector<CutsceneAction> GetFinishScene(Chapter); }; }
463
C++
.h
23
17.869565
63
0.772622
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,540
fmap.hpp
xavieran_BaKGL/bak/fmap.hpp
#pragma once #include "bak/resourceNames.hpp" #include "bak/types.hpp" #include "bak/zoneReference.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "com/ostream.hpp" #include "graphics/glm.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK { class FMapXY { public: static constexpr auto sFile = "FMAP_XY.DAT"; FMapXY() { auto fb = FileBufferFactory::Get().CreateDataBuffer(sFile); unsigned i = 0; for (unsigned zone = 0; zone < 12; zone++) { mTiles.emplace_back(LoadZoneRef(ZoneLabel{zone + 1}.GetZoneReference())); unsigned i = 0; const auto nTiles = fb.GetUint16LE(); Logging::LogDebug("FMAP") << "Tiles in zone: " << (zone + 1) << ": " << nTiles << std::endl; auto& tileCoords = mTileCoords.emplace_back(); for (unsigned i = 0; i < nTiles; i++) { const auto x = fb.GetUint16LE(); const auto y = fb.GetUint16LE(); tileCoords.emplace_back(x, y); Logging::LogDebug("FMAP") << zone + 1 << " " << i << " " << mTiles.back()[i] << " ( " << x << ", " << y << ")\n"; } } } glm::vec2 GetTileCoords(ZoneNumber zone, glm::uvec2 tile) { const auto& tiles = mTiles[zone.mValue - 1]; const auto it = std::find(tiles.begin(), tiles.end(), tile); // Obviously this should not happen, but since I haven't implemented clipping it can if (it == tiles.end()) return glm::vec2{0, 0}; //ASSERT(it != tiles.end()); const auto index = std::distance(tiles.begin(), it); // There's no full map for Timirianya if (zone.mValue == 9) { return glm::vec2{0, 0}; } return mTileCoords[zone.mValue - 1][index]; } private: std::vector<std::vector<glm::uvec2>> mTiles; std::vector<std::vector<glm::vec2>> mTileCoords; }; struct Town { Town( std::string name, std::uint16_t type, glm::vec2 coord) : mName{name}, mType{type}, mCoord{coord} {} std::string mName; std::uint16_t mType; glm::vec2 mCoord; }; class FMapTowns { public: static constexpr auto sFile = "FMAP_TWN.DAT"; FMapTowns() { auto fb = FileBufferFactory::Get().Get().CreateDataBuffer(sFile); const auto x1 = fb.GetUint16LE(); const auto x2 = fb.GetUint16LE(); const auto y1 = fb.GetUint16LE(); const auto y2 = fb.GetUint16LE(); const auto z1 = fb.GetUint16LE(); Logging::LogDebug("FMAP_TWN") << x1 << " " << x2 << " " << y1 << " " << y2 << " " << z1 << "\n"; for (unsigned i = 0; i < 33; i++) { const auto type = fb.GetUint16LE(); const auto town = fb.GetString(); const auto x = fb.GetUint16LE(); const auto y = fb.GetUint16LE(); Logging::LogDebug("FMAP_TWN") << i << " " << town << " ( " << x << ", " << y << ") tp: " << type << "\n"; mTowns.emplace_back(town, type, glm::vec2{x, y}); } } const auto& GetTowns() const { return mTowns; } private: std::vector<Town> mTowns; }; }
3,310
C++
.h
101
25.029703
104
0.53605
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,541
font.hpp
xavieran_BaKGL/bak/font.hpp
#pragma once #include "graphics/texture.hpp" #include "com/assert.hpp" #include "com/logger.hpp" #include "bak/fileBufferFactory.hpp" #include <iostream> #include <vector> namespace BAK { struct Glyph { static constexpr auto MAX_FONT_HEIGHT = 16; Glyph( unsigned width, unsigned height, std::array<std::uint16_t, MAX_FONT_HEIGHT> points) : mWidth{width}, mHeight{height}, mPoints{points} {} unsigned mWidth; unsigned mHeight; std::array<std::uint16_t, MAX_FONT_HEIGHT> mPoints; }; Graphics::Texture GlyphToTexture(const Glyph&); class Font { public: Font( int firstChar, unsigned height, Graphics::TextureStore textures) : mFirstChar{firstChar}, mHeight{height}, mCharacters{textures} {} char GetIndex(char c) const { if (!(mFirstChar <= c)) { Logging::LogFatal("BAK::Font") << "Request for bad char: {" << std::hex << +c << std::dec << "} [" << c << "]" << std::endl; } ASSERT(mFirstChar <= c); return c - mFirstChar; } const auto& GetCharacters(){ return mCharacters; } std::size_t GetSpace() const { // The width of 'a' return static_cast<float>( mCharacters.GetTexture(0).GetWidth()); } char GetFirstChar() const { return mFirstChar; } unsigned GetWidth(char c) const { return mCharacters.GetTexture(GetIndex(c)).GetWidth(); } unsigned GetHeight() const { return mHeight; } private: int mFirstChar; unsigned mHeight; Graphics::TextureStore mCharacters; }; Font LoadFont(FileBuffer& fb); }
1,727
C++
.h
70
18.9
80
0.614024
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,542
chapterTransitions.hpp
xavieran_BaKGL/bak/chapterTransitions.hpp
#pragma once #include "bak/types.hpp" #include "bak/dialogAction.hpp" #include <optional> namespace BAK { class GameState; std::optional<BAK::Teleport> TransitionToChapter(Chapter chapter, GameState& gs); }
213
C++
.h
8
24.875
81
0.80402
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,543
dialogTarget.hpp
xavieran_BaKGL/bak/dialogTarget.hpp
#pragma once #include "com/strongType.hpp" #include <cstdint> #include <functional> #include <ostream> #include <variant> namespace BAK { using KeyTarget = StrongType<std::uint32_t, struct KeyTargetTag>; struct OffsetTarget { std::uint8_t dialogFile; std::uint32_t value; bool operator==(const OffsetTarget other) const { return value == other.value && dialogFile == other.dialogFile; } }; using Target = std::variant<KeyTarget, OffsetTarget>; std::ostream& operator<<(std::ostream& os, const Target& t); } // namespace BAK { namespace std { template<> struct hash<BAK::OffsetTarget> { std::size_t operator()(const BAK::OffsetTarget& t) const noexcept { return std::hash<std::size_t>{}( static_cast<std::size_t>(t.value) + ((static_cast<std::size_t>(t.dialogFile) << 32))); } }; } // namespace std
872
C++
.h
32
23.9375
66
0.690821
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,544
condition.hpp
xavieran_BaKGL/bak/condition.hpp
#pragma once #include "com/assert.hpp" #include "com/saturatingNum.hpp" #include <array> #include <cstdint> #include <ostream> #include <string_view> namespace BAK { class Skills; enum class Condition { Sick = 0, Plagued = 1, Poisoned = 2, Drunk = 3, Healing = 4, Starving = 5, NearDeath = 6 }; std::string_view ToString(Condition); // deterioration // heal reduction // .... constexpr std::uint16_t sConditionSkillEffect[7][6] = { { 1, 0xFFFF, 0, 0, 0, 0}, // Sick { 1, 0xFFFE, 0, 0, 0, 0}, // Plagued { 1, 0xFFFD, 0, 0, 0, 0}, // Poisoned {0xFFFE, 0, 0xFFF2, 0xFFC4, 0, 0}, // Drunk {0xFFFD, 1, 0, 0, 0, 0}, // Healing { 0, 0xFFFE, 0, 0, 0, 0}, // Starving { 0, 0, 0, 0, 0, 0}}; // Near Death using ConditionValue = SaturatingNum<std::uint8_t, 0, 100>; class Conditions { public: static constexpr auto sNumConditions = 7; std::array<ConditionValue, sNumConditions> mConditions; bool NoConditions() const; const ConditionValue& GetCondition(BAK::Condition cond) const; void IncreaseCondition(BAK::Condition cond, signed value); void AdjustCondition(Skills&, BAK::Condition, signed amount); void SetCondition(BAK::Condition cond, std::uint8_t amount); }; std::ostream& operator<<(std::ostream&, const Conditions&); }
1,432
C++
.h
45
28.622222
66
0.614431
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,545
textureFactory.hpp
xavieran_BaKGL/bak/textureFactory.hpp
#pragma once #include <string> #include <string_view> #include <vector> #include "bak/image.hpp" #include "bak/palette.hpp" #include "graphics/texture.hpp" #include "bak/fileBufferFactory.hpp" namespace BAK { class TextureFactory { public: static Graphics::TextureStore MakeTextureStore( std::string_view bmx, std::string_view pal); static void AddToTextureStore( Graphics::TextureStore&, std::string_view bmx, std::string_view pal); static void AddScreenToTextureStore( Graphics::TextureStore&, std::string_view scx, std::string_view pal); static void AddTerrainToTextureStore( Graphics::TextureStore&, const BAK::Image& terrain, const BAK::Palette&); static void AddToTextureStore( Graphics::TextureStore& store, const BAK::Image& image, const Palette& palette); static void AddToTextureStore( Graphics::TextureStore& store, const std::vector<BAK::Image>& images, const Palette& palette); }; }
1,068
C++
.h
37
23.216216
51
0.684985
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,546
inventoryItem.hpp
xavieran_BaKGL/bak/inventoryItem.hpp
#pragma once #include "bak/objectInfo.hpp" #include "bak/itemNumbers.hpp" #include "bak/types.hpp" #include "com/bits.hpp" #include <iostream> namespace BAK { enum class ItemStatus : std::uint8_t { Activated = 1, Broken = 4, Repairable = 5, Equipped = 6, Poisoned = 7 }; enum class ItemFlags : std::uint16_t { Consumable = 4, // 0x0010 MagicalItem = 7, // 0x0080 Combat = 8, // 0x0100 // ?? SwordsmanItem = 9, // 0x0200 // ?? NonCombatItem = 10, // 0x0400 // ?? Stackable = 11, // 0x0800 ConditionBased = 12, // 0x1000 ChargeBased = 13, // 0x2000 QuantityBased = 15, // 0x8000 }; bool CheckItemStatus(std::uint8_t status, ItemStatus flag); std::uint8_t SetItemStatus(std::uint8_t status, ItemStatus flag, bool state); class InventoryItem { public: InventoryItem( GameObject const* object, ItemIndex itemIndex, unsigned condition, std::uint8_t status, std::uint8_t modifiers); const GameObject& GetObject() const { ASSERT(mObject); return *mObject; } auto GetItemIndex() const { return mItemIndex; } auto GetQuantity() const { return mCondition; } auto GetSpell() const { return SpellIndex{mCondition}; } auto GetCondition() const { return mCondition; } auto GetStatus() const { return mStatus; } auto GetModifierMask() const { return mModifiers; } bool IsActivated() const { return CheckItemStatus(mStatus, ItemStatus::Activated); } bool IsEquipped() const { return CheckItemStatus(mStatus, ItemStatus::Equipped); } bool IsBroken() const { return CheckItemStatus(mStatus, ItemStatus::Broken); } bool IsRepairable() const { return CheckItemStatus(mStatus, ItemStatus::Repairable) && !IsBroken(); } bool IsRepairableByShop() const { return GetCondition() != 100; } bool IsPoisoned() const { return CheckItemStatus(mStatus, ItemStatus::Poisoned); } bool IsMoney() const { return mItemIndex == ItemIndex{0x35} || mItemIndex == ItemIndex{0x36}; } bool IsKey() const { return IsItemType(ItemType::Key) || mItemIndex == BAK::sPicklock; } void SetActivated(bool state) { mStatus = SetItemStatus(mStatus, ItemStatus::Activated, state); } void SetEquipped(bool state) { mStatus = SetItemStatus(mStatus, ItemStatus::Equipped, state); } void SetRepairable(bool state) { mStatus = SetItemStatus(mStatus, ItemStatus::Repairable, state); } void SetBroken(bool state) { mStatus = SetItemStatus(mStatus, ItemStatus::Broken, state); } void SetCondition(unsigned condition) { mCondition = condition; } void SetQuantity(unsigned quantity) { ASSERT(!IsStackable() || (IsStackable() && quantity <= GetObject().mStackSize)); mCondition = quantity; } bool HasFlag(ItemFlags flag) const { return CheckBitSet(GetObject().mFlags, flag); } bool IsConditionBased() const { return HasFlag(ItemFlags::ConditionBased); } bool IsChargeBased() const { return HasFlag(ItemFlags::ChargeBased); } bool IsStackable() const { return HasFlag(ItemFlags::Stackable); } bool IsQuantityBased() const { return HasFlag(ItemFlags::QuantityBased); } bool IsConsumable() const { return HasFlag(ItemFlags::Consumable); } bool IsMagicUserOnly() const { return HasFlag(ItemFlags::MagicalItem); } bool IsSwordsmanUserOnly() const { return HasFlag(ItemFlags::SwordsmanItem); } bool IsSkillModifier() const { return GetObject().mModifierMask != 0; } bool IsItemType(BAK::ItemType type) const { return GetObject().mType == type; } bool IsItemModifier() const { return IsItemType(ItemType::WeaponOil) || IsItemType(ItemType::ArmorOil) || IsItemType(BAK::ItemType::SpecialOil); } bool IsModifiableBy(ItemType itemType) { return (itemType == ItemType::WeaponOil && IsItemType(ItemType::Sword)) || (itemType == ItemType::ArmorOil && IsItemType(ItemType::Armor)) || (itemType == ItemType::SpecialOil && (IsItemType(ItemType::Armor) || IsItemType(ItemType::Sword))); } bool IsRepairItem() const { return IsItemType(BAK::ItemType::Tool); } bool DisplayCondition() const { return IsConditionBased(); } bool DisplayNumber() const { return IsConditionBased() || IsStackable() || IsChargeBased() || IsQuantityBased() || IsKey(); } bool HasModifier(Modifier mod) const { return CheckBitSet(mModifiers, mod); } void ClearTemporaryModifiers() { mStatus = mStatus & 0b0111'1111; mModifiers = mModifiers & 0b1110'0000; } void SetStatusAndModifierFromMask(std::uint16_t mask) { mStatus |= (mask & 0xff); mModifiers |= ((mask >> 8) & 0xff); } void SetModifier(Modifier mod) { mModifiers = SetBit(mModifiers, static_cast<std::uint8_t>(mod), true); } void UnsetModifier(Modifier mod) { mModifiers = SetBit(mModifiers, static_cast<std::uint8_t>(mod), false); } std::vector<Modifier> GetModifiers() const { auto mods = std::vector<Modifier>{}; for (unsigned i = 0; i < 8; i++) if (CheckBitSet(mModifiers, i)) mods.emplace_back(static_cast<Modifier>(i)); return mods; } std::pair<unsigned, unsigned> GetItemUseSound() const { return std::make_pair(GetObject().mUseSound, GetObject().mSoundPlayTimes); } private: GameObject const* mObject; ItemIndex mItemIndex; unsigned mCondition; std::uint8_t mStatus; std::uint8_t mModifiers; }; std::ostream& operator<<(std::ostream&, const InventoryItem&); class InventoryItemFactory { public: static InventoryItem MakeItem( ItemIndex itemIndex, std::uint8_t quantity, std::uint8_t status, std::uint8_t modifiers) { const auto& objects = ObjectIndex::Get(); return InventoryItem{ &objects.GetObject(itemIndex), itemIndex, quantity, status, modifiers}; } static InventoryItem MakeItem( ItemIndex itemIndex, std::uint8_t quantity) { return MakeItem( itemIndex, quantity, 0, 0); } }; }
6,824
C++
.h
244
21.463115
88
0.620711
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,547
sound.hpp
xavieran_BaKGL/bak/sound.hpp
#pragma once #include "bak/fileBufferFactory.hpp" #include <cstdint> #include <map> #include <memory> namespace BAK { enum class SoundFormat { Wave, Midi, Unknown }; struct MidiEvent { unsigned delta; unsigned size; std::uint8_t data[8]; }; class Sound { public: Sound(unsigned t); unsigned GetType() const; unsigned GetChannel() const; SoundFormat GetFormat() const; FileBuffer* GetSamples(); void AddVoice(FileBuffer&); void GenerateBuffer(); private: unsigned int mType; unsigned int mChannel; SoundFormat mFormat; std::unique_ptr<FileBuffer> mBuffer; std::multimap<unsigned, MidiEvent> mMidiEvents; void PutVariableLength(FileBuffer& buf, unsigned n); void CreateWaveSamples(FileBuffer& buf); void CreateMidiEvents(FileBuffer& buf); void GenerateMidi(); void GenerateWave(); }; }
888
C++
.h
41
18.121951
56
0.725749
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,548
keyContainer.hpp
xavieran_BaKGL/bak/keyContainer.hpp
#pragma once #include "bak/IContainer.hpp" #include "bak/inventory.hpp" #include "bak/inventoryItem.hpp" #include <ostream> namespace BAK { class KeyContainer : public IContainer { public: KeyContainer(Inventory&&); Inventory& GetInventory() override { return mInventory; } const Inventory& GetInventory() const override { return mInventory; } bool CanAddItem(const InventoryItem& item) const override { return item.IsItemType(ItemType::Key); } bool GiveItem(const InventoryItem& item) override { ASSERT(item.IsKey()); auto it = mInventory.FindItem(item); if (it != mInventory.GetItems().end()) it->SetQuantity(it->GetQuantity() + 1); else mInventory.AddItem(item); return true; } bool RemoveItem(const InventoryItem& item) override { auto it = mInventory.FindItem(item); if (it != mInventory.GetItems().end()) { ASSERT(it->GetQuantity() > 0); it->SetQuantity(it->GetQuantity() - 1); if (it->GetQuantity() == 0) { mInventory.RemoveItem( InventoryIndex{static_cast<unsigned>( std::distance( mInventory.GetItems().begin(),it))}); } } else { return false; } return true; } ContainerType GetContainerType() const override { return ContainerType::Key; } ShopStats& GetShop() override { ASSERT(false); return *reinterpret_cast<ShopStats*>(this);} const ShopStats& GetShop() const override { ASSERT(false); return *reinterpret_cast<const ShopStats*>(this);} LockStats& GetLock() override { ASSERT(false); return *reinterpret_cast<LockStats*>(this); } Inventory mInventory; }; std::ostream& operator<<(std::ostream& os, const KeyContainer& i); }
1,933
C++
.h
58
25.517241
113
0.615591
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,549
dialogSources.hpp
xavieran_BaKGL/bak/dialogSources.hpp
#pragma once #include "bak/types.hpp" #include "bak/dialog.hpp" #include <functional> #include <iomanip> #include <type_traits> #include <variant> namespace BAK { class DialogSources { public: static KeyTarget GetFairyChestKey(unsigned chest) { return KeyTarget{mFairyChestKey + chest}; } static std::string_view GetItemDescription(unsigned itemIndex) { return DialogStore::Get().GetSnippet( GetChoiceResult(mItemDescription, itemIndex)).GetText(); } static std::string_view GetScrollDescription(SpellIndex spellIndex) { return DialogStore::Get().GetSnippet( GetChoiceResult(mScrollDescriptions, spellIndex.mValue)).GetText(); } static KeyTarget GetItemUseText(unsigned itemIndex) { // Item use text takes a "context variable" which is // the item number. return KeyTarget{mItemDescription}; } static KeyTarget GetSpynote() { return KeyTarget{mSpyNoteContents}; } static KeyTarget GetSpellCastDialog(unsigned spell) { return KeyTarget{mDragonsBreath + spell}; } static KeyTarget GetTTMDialogKey(unsigned index) { return KeyTarget{0x186a00 + index}; } static KeyTarget GetChapterStartText(Chapter chapter) { return BAK::KeyTarget{mChapterFullMapScreenText + (chapter.mValue - 1)}; } static Target GetChoiceResult(KeyTarget dialog, unsigned index) { const auto& choices = DialogStore::Get().GetSnippet(dialog).GetChoices(); const auto it = std::find_if(choices.begin(), choices.end(), [&](const auto& a){ ASSERT(std::holds_alternative<GameStateChoice>(a.mChoice)); return a.mMin == index ;} ); ASSERT(it != choices.end()); return it->mTarget; } static constexpr auto mFairyChestKey = 0x19f0a0; static constexpr auto mItemDescription = KeyTarget{0x1b7741}; static constexpr auto mItemUseSucessful = KeyTarget{0x1b7742}; static constexpr auto mItemUseFailure = KeyTarget{0x1b7743}; static constexpr auto mHealthPotionDialog = 0x1b7744; static constexpr auto mConsumeAntiVenom = KeyTarget{0x1b776f}; static constexpr auto mNoSpaceForNewItem = 0x1b775b; static constexpr auto mWarriorCantUseMagiciansItem = KeyTarget{0x1b7745}; static constexpr auto mMagicianCantUseWarriorsItem = KeyTarget{0x1b7771}; static constexpr auto mCantUseItemRightNow = 0x1b7746; static constexpr auto mCantUseItemDuringCombat = 0x1b7747; // Contextual static constexpr auto mItemHasNoCharges = KeyTarget{0x1b776c}; // Contextual on container type (use to deduce container types?) static constexpr auto mContainerHasNoRoomForItem = KeyTarget{0x1b7748}; static constexpr auto mDropItem = 0x1b7749; static constexpr auto mGenericCantUseItem = KeyTarget{0x1b774a}; static constexpr auto mGenericCharacterClassCantUseItem = 0x1b774b; // Though he was fascinated by the @1, he realised that this was neither the time nor the place for him to be toying with it, especially when spying eyes might be watching him. static constexpr auto mCantUseItemRightNowSpyingEyes = 0x1b7770; static constexpr auto mCantUseItemOnTimirianya = 0x1b7772; static constexpr auto mCantGiveItemDuringCombat = 0x1b774c; static constexpr auto mCantTakeItemDuringCombat = 0x1b774d; static constexpr auto mCantStealItemDuringCombat = 0x1b7769; static constexpr auto mCantDiscardOnlyWeapon = KeyTarget{0x1b774e}; static constexpr auto mCantDropFlamingTorch = 0x1b775d; static constexpr auto mCantRepairItemFurther = KeyTarget{0x1b775e}; static constexpr auto mCantConsumeMorePotion = KeyTarget{0x1b7760}; static constexpr auto mLitTorchInNapthaCaverns = KeyTarget{0x1b776e}; static constexpr auto mInventoryInterfaceTooltips = 0x1b775a; static constexpr auto mInventoryInterfaceTooltips2 = 0x1b7751; static constexpr auto mPartyFundsTooltip = 0x1b7762; // Some of these seem to be unused - dialogs to describe spells that are used static constexpr auto mSpellCastDialogs = 0x1b7752; static constexpr auto mSpyNoteContents = 0x1b7753; static constexpr auto mUseTimirianyaMap = 0x1b7772; static constexpr auto mFailHaggleItemUnavailable = KeyTarget{0x1b7754}; static constexpr auto mSucceedHaggle = KeyTarget{0x1b7755}; static constexpr auto mSellItemDialog = KeyTarget{0x1b7756}; static constexpr auto mBuyItemDialog = KeyTarget{0x1b7757}; static constexpr auto mCantAffordItem = KeyTarget{0x1b7758}; static constexpr auto mShopWontBuyItem = KeyTarget{0x1b7759}; static constexpr auto mCantHaggleScroll = KeyTarget{0x1b775f}; static constexpr auto mCantBuyTooDrunk = KeyTarget{0x1b775c}; static constexpr auto mEmptyPopup = KeyTarget{0x1b7768}; static constexpr auto mScrollDescriptions = KeyTarget{0x1b7761}; static constexpr auto mRepairShopCost = KeyTarget{0x1b7763}; static constexpr auto mRepairShopCantRepairItem = KeyTarget{0x1b7764}; static constexpr auto mRepairShopItemDoesntNeedRepair = KeyTarget{0x1b7765}; static constexpr auto mShopBeginRepairDialog = KeyTarget{0x1b7766}; static constexpr auto mShopRepairDialogTooltip = KeyTarget{0x1b7767}; static constexpr auto mLockKnown = KeyTarget{0x1b776a}; static constexpr auto mLockDialog = KeyTarget{0x1b776b}; static constexpr auto mInnDialog = KeyTarget{0x13d672}; static constexpr auto mHealDialogTooltips = KeyTarget{0x13d66a}; static constexpr auto mHealDialogCantHealNotSick = KeyTarget{0x13d66b}; static constexpr auto mHealDialogCantHealNotSickEnough = KeyTarget{0x13d673}; static constexpr auto mHealDialogCantAfford = KeyTarget{0x13d66c}; static constexpr auto mHealDialogCost = KeyTarget{0x13d66d}; static constexpr auto mHealDialogPostHealing = KeyTarget{0x13d66e}; static constexpr auto mBlessDialogItemAlreadyBlessed = KeyTarget{0x13d66f}; static constexpr auto mBlessDialogCost = KeyTarget{0x13d670}; static constexpr auto mBlessDialogCantBlessItem = KeyTarget{0x13d671}; static constexpr auto mTempleDialog = KeyTarget{0x13d668}; static constexpr auto mTeleportDialog = KeyTarget{0x13d663}; static constexpr auto mTeleportDialogIntro = KeyTarget{0x13d65d}; static constexpr auto mTeleportDialogCantAfford = KeyTarget{0x13d65e}; static constexpr auto mTeleportDialogNoDestinations = KeyTarget{0x13d65f}; static constexpr auto mTeleportDialogPostTeleport = KeyTarget{0x13d660}; static constexpr auto mTeleportDialogCancel = KeyTarget{0x13d661}; static constexpr auto mTeleportDialogTeleportedToSameTemple = KeyTarget{0x13d674}; static constexpr auto mTeleportDialogTeleportBlockedMalacsCrossDest= KeyTarget{0x493fd}; static constexpr auto mTeleportDialogTeleportBlockedMalacsCrossSource= KeyTarget{0x493fe}; static constexpr auto mBardingAlreadyDone = KeyTarget{0x47}; static constexpr auto mBardingBad = KeyTarget{0x49}; static constexpr auto mBardingPoor = KeyTarget{0x58}; static constexpr auto mBardingOkay = KeyTarget{0x59}; static constexpr auto mBardingGood = KeyTarget{0x5a}; static constexpr auto mWordlockIntro = KeyTarget{0xc}; static constexpr auto mCantOpenWorldock = KeyTarget{0xd}; static constexpr auto mOpenedWordlock = KeyTarget{0xe}; static constexpr auto mTrappedChestExplodes = KeyTarget{0xc0}; static constexpr auto mOpenUnlockedBox = KeyTarget{0xc2}; static constexpr auto mOpenTrappedBox = KeyTarget{0xbe}; static constexpr auto mDisarmedTrappedBox = KeyTarget{0xbf}; static constexpr auto mChooseUnlock = KeyTarget{0x4f}; static constexpr auto mOpenExplodedChest = KeyTarget{0x13d}; static constexpr auto mKeyOpenedLock = KeyTarget{0x51}; static constexpr auto mKeyDoesntFit = KeyTarget{0x52}; static constexpr auto mLockPicked = KeyTarget{0x53}; static constexpr auto mFailedToPickLock = KeyTarget{0x54}; static constexpr auto mPicklockBroken = KeyTarget{0x55}; static constexpr auto mKeyBroken = KeyTarget{0xf5}; static constexpr auto mTombNoShovel = KeyTarget{0x42}; static constexpr auto mTombNoBody = KeyTarget{0x43}; static constexpr auto mTombJustABody = KeyTarget{0x44}; static constexpr auto mUnknownObject = KeyTarget{0x9a}; static constexpr auto mBag = KeyTarget{0x9e}; static constexpr auto mBody = KeyTarget{0x4e}; static constexpr auto mFoodBush = KeyTarget{0x9f}; static constexpr auto mCampfire = KeyTarget{0xa6}; static constexpr auto mCorn = KeyTarget{0xaa}; static constexpr auto mCrystalTree = KeyTarget{0xb2}; static constexpr auto mDirtpile = KeyTarget{0xf}; static constexpr auto mHealthBush = KeyTarget{0xa0}; static constexpr auto mPoisonBush = KeyTarget{0xa1}; static constexpr auto mStones = KeyTarget{0xaf}; static constexpr auto mScarecrow = KeyTarget{0xb5}; static constexpr auto mSiegeEngine = KeyTarget{0xb7}; static constexpr auto mStump = KeyTarget{0xba}; static constexpr auto mTrappedAnimal = KeyTarget{0xab}; static constexpr auto mWell = KeyTarget{0xbc}; static constexpr auto mDoorTooClose = KeyTarget{0x9d}; static constexpr auto mPitHaveRope = KeyTarget{0xc5}; static constexpr auto mPitNoRope = KeyTarget{0xc6}; static constexpr auto mCharacterIsNotASpellcaster = KeyTarget{0xd8}; static constexpr auto mGenericScoutedCombat = KeyTarget{0x2f}; static constexpr auto mCharacterFlavourDialog = BAK::KeyTarget{0x69}; static constexpr auto mAfterNagoCombatSetKeys = BAK::KeyTarget{0x1cfdf1}; static constexpr auto mChapterFullMapScreenText = 0x126; static constexpr auto mStartOfChapterActions = KeyTarget{0x1e8497}; static constexpr auto mDragonsBreath = 0xc7; }; }
10,100
C++
.h
181
50.39779
180
0.75612
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