refactor(component): group the component files by the client's families

Physics/, Activity/ (activity, scripted activity, shooting gallery,
quickbuild, minigame control, racing control base, racing control, gate rush),
Vendor/, Character/ (what the client makes with a character, plus ghost,
minifig and mission), Sound/ and Property/; the rest stays where it was.
File moves only; DLU_COMPONENT_INCLUDE_DIRS gives every target the folders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Aaron Kimbrell
2026-10-01 15:37:45 -05:00
parent 8f09121ad4
commit 9a464ac35f
76 changed files with 37 additions and 34 deletions

View File

@@ -0,0 +1,45 @@
#include "eMissionTaskType.h"
#ifndef __ACHIEVEMENTCACHEKEY__H__
#define __ACHIEVEMENTCACHEKEY__H__
class AchievementCacheKey {
public:
AchievementCacheKey() {
targets = "";
value = 0;
type = eMissionTaskType::UNKNOWN;
};
bool operator==(const AchievementCacheKey& point) const {
return this->targets == point.targets && this->value == point.value && this->type == point.type;
};
void SetTargets(const std::string value) { this->targets = value; };
void SetValue(uint32_t value) { this->value = value; };
void SetType(eMissionTaskType value) { this->type = value; };
std::string GetTargets() const { return this->targets; };
uint32_t GetValue() const { return this->value; };
eMissionTaskType GetType() const { return this->type; };
private:
std::string targets;
uint32_t value;
eMissionTaskType type;
};
// Specialization of hash for the above class
namespace std {
template<>
struct hash<AchievementCacheKey> {
size_t operator()(const AchievementCacheKey& key) const {
size_t hash = 0;
GeneralUtils::hash_combine(hash, key.GetType());
GeneralUtils::hash_combine(hash, key.GetValue());
GeneralUtils::hash_combine(hash, key.GetTargets());
return hash;
};
};
};
#endif //!__ACHIEVEMENTCACHEKEY__H__

View File

@@ -0,0 +1,85 @@
#include "AchievementVendorComponent.h"
#include "MissionComponent.h"
#include "InventoryComponent.h"
#include "eMissionState.h"
#include "CDComponentsRegistryTable.h"
#include "CDItemComponentTable.h"
#include "eVendorTransactionResult.h"
#include "CheatDetection.h"
#include "UserManager.h"
#include "CDMissionsTable.h"
AchievementVendorComponent::AchievementVendorComponent(Entity* parent, const int32_t componentID) : VendorComponent(parent, componentID) {
}
// The base vendor's template load, then the achievement vendor's stock
void AchievementVendorComponent::LoadDataFromTemplate() {
VendorComponent::LoadDataFromTemplate();
RefreshInventory(true);
};
bool AchievementVendorComponent::SellsItem(Entity* buyer, const LOT lot) {
auto* missionComponent = buyer->GetComponent<MissionComponent>();
if (!missionComponent) return false;
if (m_PlayerPurchasableItems[buyer->GetObjectID()].contains(lot)) {
return true;
}
CDMissionsTable* missionsTable = CDClientManager::GetTable<CDMissionsTable>();
const auto missions = missionsTable->GetMissionsForReward(lot);
for (const auto mission : missions) {
if (missionComponent->GetMissionState(mission) == eMissionState::COMPLETE) {
m_PlayerPurchasableItems[buyer->GetObjectID()].insert(lot);
return true;
}
}
return false;
}
void AchievementVendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) {
// get the item Comp from the item LOT
CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable<CDComponentsRegistryTable>();
CDItemComponentTable* itemComponentTable = CDClientManager::GetTable<CDItemComponentTable>();
int itemCompID = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::ITEM);
CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID);
uint32_t costLOT = itemComp.commendationLOT;
if (costLOT == -1 || !SellsItem(buyer, lot)) {
auto* user = UserManager::Instance()->GetUser(buyer->GetSystemAddress());
CheatDetection::ReportCheat(user, buyer->GetSystemAddress(), "Attempted to buy item %i from achievement vendor %i that is not purchasable", lot, m_Parent->GetLOT());
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
auto* inventoryComponent = buyer->GetComponent<InventoryComponent>();
if (!inventoryComponent) {
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
if (costLOT == 13763) { // Faction Token Proxy
auto* missionComponent = buyer->GetComponent<MissionComponent>();
if (!missionComponent) return;
if (missionComponent->GetMissionState(545) == eMissionState::COMPLETE) costLOT = 8318; // "Assembly Token"
if (missionComponent->GetMissionState(556) == eMissionState::COMPLETE) costLOT = 8321; // "Venture League Token"
if (missionComponent->GetMissionState(567) == eMissionState::COMPLETE) costLOT = 8319; // "Sentinels Token"
if (missionComponent->GetMissionState(578) == eMissionState::COMPLETE) costLOT = 8320; // "Paradox Token"
}
const uint32_t altCurrencyCost = itemComp.commendationCost * count;
if (inventoryComponent->GetLotCount(costLOT) < altCurrencyCost || !inventoryComponent->RemoveItem(costLOT, altCurrencyCost, eInventoryType::ALL)) {
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
inventoryComponent->AddItem(lot, count, eLootSourceType::VENDOR);
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_SUCCESS);
}
void AchievementVendorComponent::RefreshInventory(bool isCreation) {
SetHasStandardCostItems(true);
Game::entityManager->SerializeEntity(m_Parent);
}

View File

@@ -0,0 +1,27 @@
#ifndef __ACHIEVEMENTVENDORCOMPONENT__H__
#define __ACHIEVEMENTVENDORCOMPONENT__H__
#include "VendorComponent.h"
#include "eReplicaComponentType.h"
#include <set>
#include <map>
class Entity;
class AchievementVendorComponent final : public VendorComponent {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::ACHIEVEMENT_VENDOR;
AchievementVendorComponent(Entity* parent, const int32_t componentID);
void LoadDataFromTemplate() override;
void RefreshInventory(bool isCreation = false) override;
bool SellsItem(Entity* buyer, const LOT lot);
void Buy(Entity* buyer, LOT lot, uint32_t count);
private:
std::map<LWOOBJID,std::set<LOT>> m_PlayerPurchasableItems;
};
#endif //!__ACHIEVEMENTVENDORCOMPONENT__H__

View File

@@ -0,0 +1,110 @@
#include "DonationVendorComponent.h"
#include "Database.h"
#include "CharacterComponent.h"
#include "EconomyLedger.h"
#include "eInventoryType.h"
#include "eMissionTaskType.h"
#include "EntityManager.h"
#include "Game.h"
#include "InventoryComponent.h"
#include "Item.h"
#include "LeaderboardManager.h"
#include "Logger.h"
#include "MissionComponent.h"
#include "User.h"
#include "UserManager.h"
DonationVendorComponent::DonationVendorComponent(Entity* parent, const int32_t componentID) : VendorComponent(parent, componentID) {
}
// The level config: the donation goal and activity, and the total donated so far
void DonationVendorComponent::LoadConfigData() {
m_PercentComplete = 0.0;
m_TotalDonated = 0;
m_TotalRemaining = 0;
// custom attribute to calculate other values
m_Goal = m_Parent->GetVar<int32_t>(u"donationGoal");
if (m_Goal == 0) m_Goal = INT32_MAX;
// Default to the nexus tower jawbox activity and setup settings
m_ActivityId = m_Parent->GetVar<uint32_t>(u"activityID");
if ((m_ActivityId == 0) || (m_ActivityId == 117)) {
m_ActivityId = 117;
m_PercentComplete = 1.0;
m_TotalDonated = INT32_MAX;
m_TotalRemaining = 0;
m_Goal = INT32_MAX;
return;
}
auto donationTotal = Database::Get()->GetDonationTotal(m_ActivityId);
if (donationTotal) m_TotalDonated = donationTotal.value();
m_TotalRemaining = m_Goal - m_TotalDonated;
m_PercentComplete = m_TotalDonated/static_cast<float>(m_Goal);
}
void DonationVendorComponent::SubmitDonation(uint32_t count) {
if (count <= 0 && ((m_TotalDonated + count) > 0)) return;
m_TotalDonated += count;
m_TotalRemaining = m_Goal - m_TotalDonated;
m_PercentComplete = m_TotalDonated/static_cast<float>(m_Goal);
m_DirtyDonationVendor = true;
}
void DonationVendorComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) {
VendorComponent::Serialize(outBitStream, bIsInitialUpdate);
outBitStream.Write(bIsInitialUpdate || m_DirtyDonationVendor);
if (bIsInitialUpdate || m_DirtyDonationVendor) {
outBitStream.Write(m_PercentComplete);
outBitStream.Write(m_TotalDonated);
outBitStream.Write(m_TotalRemaining);
if (!bIsInitialUpdate) m_DirtyDonationVendor = false;
}
}
void DonationVendorComponent::AddDonationItem(const SystemAddress& sysAddr, LWOOBJID itemObjID, uint32_t count) {
if (GetActivityID() == 0) {
LOG("WARNING: Trying to dontate to a vendor with no activity");
return;
}
User* user = UserManager::Instance()->GetUser(sysAddr);
if (!user) return;
Entity* player = Game::entityManager->GetEntity(user->GetLoggedInChar());
if (!player) return;
auto* characterComponent = player->GetComponent<CharacterComponent>();
if (!characterComponent) return;
auto* inventoryComponent = player->GetComponent<InventoryComponent>();
if (!inventoryComponent) return;
Item* item = inventoryComponent->FindItemById(itemObjID);
if (!item) return;
if (item->GetCount() < count) return;
characterComponent->SetCurrentInteracting(m_Parent->GetObjectID());
inventoryComponent->MoveItemToInventory(item, eInventoryType::DONATION, count, true, false, true);
}
void DonationVendorComponent::ConfirmDonation(Entity& player) {
const auto [inventoryComponent, missionComponent, characterComponent] = player.GetComponentsMut<InventoryComponent, MissionComponent, CharacterComponent>();
if (!inventoryComponent || !missionComponent || !characterComponent || !characterComponent->GetCurrentInteracting()) return;
if (GetActivityID() == 0) {
LOG("WARNING: Trying to dontate to a vendor with no activity");
return;
}
auto* inventory = inventoryComponent->GetInventory(eInventoryType::DONATION);
if (!inventory) return;
auto items = inventory->GetItems();
if (!items.empty()) {
uint32_t count = 0;
for (auto& [itemID, item] : items) {
count += item->GetCount();
EconomyLedger::RecordItemsUnsuppressed(&player, item->GetLot(), -static_cast<int64_t>(item->GetCount()), EconomyLedger::DONATION_SOURCE);
item->RemoveFromInventory();
}
missionComponent->Progress(eMissionTaskType::DONATION, 0, LWOOBJID_EMPTY, "", count);
LeaderboardManager::SaveScore(player.GetObjectID(), GetActivityID(), count);
SubmitDonation(count);
Game::entityManager->SerializeEntity(m_Parent);
}
characterComponent->SetCurrentInteracting(LWOOBJID_EMPTY);
}

View File

@@ -0,0 +1,35 @@
#ifndef __DONATIONVENDORCOMPONENT__H__
#define __DONATIONVENDORCOMPONENT__H__
#include "VendorComponent.h"
#include "eReplicaComponentType.h"
class Entity;
class DonationVendorComponent final : public VendorComponent {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::DONATION_VENDOR;
DonationVendorComponent(Entity* parent, const int32_t componentID);
void LoadConfigData() override;
void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override;
uint32_t GetActivityID() {return m_ActivityId;};
void SubmitDonation(uint32_t count);
// AddDonationItem from the player at sysAddr: moves count of the item into their donation inventory.
void AddDonationItem(const SystemAddress& sysAddr, LWOOBJID itemObjID, uint32_t count);
// ConfirmDonationOnPlayer: the player donates everything in their donation inventory to this vendor.
void ConfirmDonation(Entity& player);
private:
bool m_DirtyDonationVendor = false;
float m_PercentComplete = 0.0;
int32_t m_TotalDonated = 0;
int32_t m_TotalRemaining = 0;
uint32_t m_ActivityId = 0;
int32_t m_Goal = 0;
};
#endif //!__DONATIONVENDORCOMPONENT__H__

View File

@@ -0,0 +1,364 @@
#include "VendorComponent.h"
#include "ObjectMessages.h"
#include "BitStream.h"
#include "dServer.h"
#include "dZoneManager.h"
#include "WorldConfig.h"
#include "CDComponentsRegistryTable.h"
#include "CDVendorComponentTable.h"
#include "CDLootMatrixTable.h"
#include "CDLootTableTable.h"
#include "CDItemComponentTable.h"
#include "InventoryComponent.h"
#include "Character.h"
#include "eVendorTransactionResult.h"
#include "UserManager.h"
#include "CheatDetection.h"
#include "VendorMessages.h"
#include "Item.h"
#include "EconomyLedger.h"
#include <algorithm>
#include <ranges>
VendorComponent::VendorComponent(Entity* parent, const int32_t componentID) : Component(parent, componentID) {
RegisterMsg(&VendorComponent::OnRequestUse);
m_HasStandardCostItems = false;
m_HasMultiCostItems = false;
}
// The vendor's constants and its stock (the base's refresh: a derived vendor adds its own after)
void VendorComponent::LoadDataFromTemplate() {
SetupConstants();
VendorComponent::RefreshInventory(true);
}
void VendorComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) {
outBitStream.Write(bIsInitialUpdate || m_DirtyVendor);
if (bIsInitialUpdate || m_DirtyVendor) {
outBitStream.Write(m_HasStandardCostItems);
outBitStream.Write(m_HasMultiCostItems);
if (!bIsInitialUpdate) m_DirtyVendor = false;
}
}
bool VendorComponent::OnRequestUse(GameMessages::RequestUseEvent& event) {
if (event.msg.IsMissionChoice()) return false;
auto* const originator = event.user;
GameMessages::VendorOpenWindow openWindow;
openWindow.target = m_Parent->GetObjectID();
openWindow.SendToClient(originator->GetSystemAddress());
// Only the entity's VENDOR component sends its stock (achievement and donation vendors never did).
auto* vendor = static_cast<VendorComponent*>(m_Parent->GetComponent(eReplicaComponentType::VENDOR));
if (vendor) vendor->SendStatusUpdate(originator->GetSystemAddress());
return true;
}
void VendorComponent::RefreshInventory(bool isCreation) {
SetHasStandardCostItems(false);
SetHasMultiCostItems(false);
m_Inventory.clear();
// Custom code for Vanity Vendor Invetory Override
if(m_Parent->HasVar(u"vendorInvOverride")) {
std::vector<std::string> items = GeneralUtils::SplitString(m_Parent->GetVarAsString(u"vendorInvOverride"), ',');
uint32_t sortPriority = -1;
for (auto& itemString : items) {
itemString.erase(remove_if(itemString.begin(), itemString.end(), isspace), itemString.end());
auto item = GeneralUtils::TryParse<uint32_t>(itemString);
if (!item) continue;
if (SetupItem(item.value())) {
sortPriority++;
m_Inventory.push_back(SoldItem(item.value(), sortPriority));
}
}
return;
}
auto* lootMatrixTable = CDClientManager::GetTable<CDLootMatrixTable>();
const auto& lootMatrices = lootMatrixTable->GetMatrix(m_LootMatrixID);
if (lootMatrices.empty()) return;
auto* lootTableTable = CDClientManager::GetTable<CDLootTableTable>();
for (const auto& lootMatrix : lootMatrices) {
auto vendorItems = lootTableTable->GetTable(lootMatrix.LootTableIndex);
if (lootMatrix.maxToDrop == 0 || lootMatrix.minToDrop == 0) {
for (const auto& item : vendorItems) {
if (SetupItem(item.itemid)) m_Inventory.push_back(SoldItem(item.itemid, item.sortPriority));
}
} else {
auto randomCount = GeneralUtils::GenerateRandomNumber<int32_t>(lootMatrix.minToDrop, lootMatrix.maxToDrop);
for (size_t i = 0; i < randomCount; i++) {
if (vendorItems.empty()) break;
auto randomItemIndex = GeneralUtils::GenerateRandomNumber<int32_t>(0, vendorItems.size() - 1);
const auto& randomItem = vendorItems.at(randomItemIndex);
if (SetupItem(randomItem.itemid)) m_Inventory.push_back(SoldItem(randomItem.itemid, randomItem.sortPriority));
vendorItems.erase(vendorItems.begin() + randomItemIndex);
}
}
}
HandleMrReeCameras();
// Callback timer to refresh this inventory.
if (m_RefreshTimeSeconds > 0.0) {
m_Parent->AddCallbackTimer(m_RefreshTimeSeconds, [this]() {
RefreshInventory();
});
}
Game::entityManager->SerializeEntity(m_Parent);
// Only the entity's VENDOR component sends its stock (achievement and donation vendors never did).
auto* vendor = static_cast<VendorComponent*>(m_Parent->GetComponent(eReplicaComponentType::VENDOR));
if (vendor) vendor->SendStatusUpdate(UNASSIGNED_SYSTEM_ADDRESS);
}
void VendorComponent::SetupConstants() {
auto* compRegistryTable = CDClientManager::GetTable<CDComponentsRegistryTable>();
int componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::VENDOR);
auto* vendorComponentTable = CDClientManager::GetTable<CDVendorComponentTable>();
std::vector<CDVendorComponent> vendorComps = vendorComponentTable->Query([=](CDVendorComponent entry) { return (entry.id == componentID); });
if (vendorComps.empty()) return;
auto vendorData = vendorComps.at(0);
if (vendorData.buyScalar == 0.0) m_BuyScalar = Game::zoneManager->GetWorldConfig().vendorBuyMultiplier;
else m_BuyScalar = vendorData.buyScalar;
m_SellScalar = vendorData.sellScalar;
m_RefreshTimeSeconds = vendorData.refreshTimeSeconds;
m_LootMatrixID = vendorData.LootMatrixIndex;
}
bool VendorComponent::SellsItem(const LOT item) const {
return std::count_if(m_Inventory.begin(), m_Inventory.end(), [item](const SoldItem& lhs) {
return lhs.lot == item;
}) > 0;
}
void VendorComponent::HandleMrReeCameras(){
if (m_Parent->GetLOT() == 13569) {
SetHasStandardCostItems(true);
auto randomCamera = GeneralUtils::GenerateRandomNumber<int32_t>(0, 2);
LOT camera = 0;
DluAssert(randomCamera >= 0 && randomCamera <= 2);
switch (randomCamera) {
case 0:
camera = 16253; // Grungagroid
break;
case 1:
camera = 16254; // Hipstabrick
break;
case 2:
camera = 16204; // Megabrixel snapshot
break;
}
m_Inventory.push_back(SoldItem(camera, 0));
}
}
void VendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) {
if (!SellsItem(lot)) {
auto* user = UserManager::Instance()->GetUser(buyer->GetSystemAddress());
CheatDetection::ReportCheat(user, buyer->GetSystemAddress(), "Attempted to buy item %i from achievement vendor %i that is not purchasable", lot, m_Parent->GetLOT());
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
auto* inventoryComponent = buyer->GetComponent<InventoryComponent>();
if (!inventoryComponent) {
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable<CDComponentsRegistryTable>();
CDItemComponentTable* itemComponentTable = CDClientManager::GetTable<CDItemComponentTable>();
int itemCompID = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::ITEM);
CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID);
// Extra currency that needs to be deducted in case of crafting
auto craftingCurrencies = CDItemComponentTable::ParseCraftingCurrencies(itemComp);
for (const auto& [crafintCurrencyLOT, crafintCurrencyCount]: craftingCurrencies) {
if (inventoryComponent->GetLotCount(crafintCurrencyLOT) < (crafintCurrencyCount * count)) {
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
}
bool success = true;
for (const auto& [crafintCurrencyLOT, crafintCurrencyCount]: craftingCurrencies) {
success = inventoryComponent->RemoveItem(crafintCurrencyLOT, crafintCurrencyCount * count, eInventoryType::ALL);
if (!success) break;
}
if (!success) {
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
float buyScalar = GetBuyScalar();
const auto coinCost = static_cast<uint32_t>(std::floor((itemComp.baseValue * buyScalar) * count));
Character* character = buyer->GetCharacter();
if (!character || character->GetCoins() < coinCost) {
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
if (Inventory::IsValidItem(itemComp.currencyLOT)) {
const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * buyScalar) * count;
if (inventoryComponent->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) {
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL);
return;
}
inventoryComponent->RemoveItem(itemComp.currencyLOT, altCurrencyCost, eInventoryType::ALL);
}
character->SetCoins(character->GetCoins() - (coinCost), eLootSourceType::VENDOR, CoinSource::Object(*m_Parent));
// Live sent the vendor's LOT, and the coins paid when there were any, with the bought items
LootMetrics metrics{};
metrics.sourceLot = m_Parent->GetLOT();
if (coinCost > 0) metrics.currencyDelta = -static_cast<int32_t>(coinCost);
inventoryComponent->AddItem(lot, count, eLootSourceType::VENDOR, eInventoryType::INVALID, {}, LWOOBJID_EMPTY, true, false, LWOOBJID_EMPTY, eInventoryType::INVALID, 0, false, -1, metrics);
SendTransactionResult(buyer->GetObjectID(), buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_SUCCESS);
}
bool VendorComponent::SetupItem(LOT item) {
auto* itemComponentTable = CDClientManager::GetTable<CDItemComponentTable>();
auto* compRegistryTable = CDClientManager::GetTable<CDComponentsRegistryTable>();
auto itemComponentID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM, -1);
if (itemComponentID == -1) {
LOG("Attempted to add item %i with ItemComponent ID -1 to vendor %i inventory. Not adding item!", itemComponentID, m_Parent->GetLOT());
return false;
}
if (!m_HasStandardCostItems || !m_HasMultiCostItems) {
auto itemComponent = itemComponentTable->GetItemComponentByID(itemComponentID);
if (!m_HasStandardCostItems && itemComponent.baseValue != -1) SetHasStandardCostItems(true);
if (!m_HasMultiCostItems && !itemComponent.currencyCosts.empty()) SetHasMultiCostItems(true);
}
return true;
}
void VendorComponent::SendStatusUpdate(const SystemAddress& sysAddr, bool bUpdateOnly) {
GameMessages::VendorStatusUpdate statusUpdate;
statusUpdate.target = m_Parent->GetObjectID();
statusUpdate.bUpdateOnly = bUpdateOnly;
statusUpdate.inventoryList.reserve(m_Inventory.size());
for (const auto& item : m_Inventory) statusUpdate.inventoryList.push_back({ item.lot, item.sortPriority });
statusUpdate.Send(sysAddr);
}
void VendorComponent::SendTransactionResult(LWOOBJID target, const SystemAddress& sysAddr, eVendorTransactionResult result) {
GameMessages::VendorTransactionResult transactionResult;
transactionResult.target = target;
transactionResult.iResult = result;
transactionResult.SendToClient(sysAddr);
}
void VendorComponent::SellToVendor(Entity& player, const SystemAddress& sysAddr, LWOOBJID itemObjID, int32_t count) {
Character* character = player.GetCharacter();
if (!character) return;
InventoryComponent* inv = static_cast<InventoryComponent*>(player.GetComponent(eReplicaComponentType::INVENTORY));
if (!inv) return;
Item* item = inv->FindItemById(itemObjID);
if (!item) return;
CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable<CDComponentsRegistryTable>();
CDItemComponentTable* itemComponentTable = CDClientManager::GetTable<CDItemComponentTable>();
int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM);
CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID);
// Items with a base value of 0 or max int are special items that should not be sold if they're not sub items
if (itemComp.baseValue == 0 || itemComp.baseValue == UINT_MAX) {
SendTransactionResult(m_Parent->GetObjectID(), sysAddr, eVendorTransactionResult::SELL_FAIL);
return;
}
float sellScalar = GetSellScalar();
if (Inventory::IsValidItem(itemComp.currencyLOT)) {
const auto altCurrency = static_cast<uint32_t>(itemComp.altCurrencyCost * sellScalar) * count;
inv->AddItem(itemComp.currencyLOT, std::floor(altCurrency), eLootSourceType::VENDOR); // Return alt currencies like faction tokens.
}
MakeRoomInBuyback(*inv, *item, static_cast<uint32_t>(std::max(count, 0)));
inv->MoveItemToInventory(item, eInventoryType::VENDOR_BUYBACK, count, true, false, true);
character->SetCoins(std::floor(character->GetCoins() + (static_cast<uint32_t>(itemComp.baseValue * sellScalar) * count)), eLootSourceType::VENDOR, CoinSource::Object(*m_Parent));
SendTransactionResult(m_Parent->GetObjectID(), sysAddr, eVendorTransactionResult::SELL_SUCCESS);
}
void VendorComponent::BuybackFromVendor(Entity& player, const SystemAddress& sysAddr, LWOOBJID itemObjID, int32_t count) {
Character* character = player.GetCharacter();
if (!character) return;
InventoryComponent* inv = static_cast<InventoryComponent*>(player.GetComponent(eReplicaComponentType::INVENTORY));
if (!inv) return;
Item* item = inv->FindItemById(itemObjID);
if (!item) return;
CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable<CDComponentsRegistryTable>();
CDItemComponentTable* itemComponentTable = CDClientManager::GetTable<CDItemComponentTable>();
int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM);
CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID);
float sellScalar = GetSellScalar();
const auto cost = static_cast<uint32_t>(std::floor(((itemComp.baseValue * sellScalar) * count)));
if (character->GetCoins() < cost) {
SendTransactionResult(m_Parent->GetObjectID(), sysAddr, eVendorTransactionResult::PURCHASE_FAIL);
return;
}
if (Inventory::IsValidItem(itemComp.currencyLOT)) {
const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * sellScalar) * count;
if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost || !inv->RemoveItem(itemComp.currencyLOT, altCurrencyCost, eInventoryType::ALL)) {
SendTransactionResult(m_Parent->GetObjectID(), sysAddr, eVendorTransactionResult::PURCHASE_FAIL);
return;
}
}
//inv->RemoveItem(count, -1, iObjID);
inv->MoveItemToInventory(item, Inventory::FindInventoryTypeForLot(item->GetLot()), count, true, false);
character->SetCoins(character->GetCoins() - cost, eLootSourceType::VENDOR, CoinSource::Object(*m_Parent));
//Game::entityManager->SerializeEntity(player); // so inventory updates
SendTransactionResult(m_Parent->GetObjectID(), sysAddr, eVendorTransactionResult::PURCHASE_SUCCESS);
}
void VendorComponent::MakeRoomInBuyback(InventoryComponent& inventory, const Item& sold, const uint32_t count) {
auto* const buyback = inventory.GetInventory(eInventoryType::VENDOR_BUYBACK);
if (!buyback) return;
// No new slot is needed when all of it fits on buyback stacks of the same item
const auto lot = sold.GetLot();
const auto stackSize = sold.GetInfo().stackSize;
const bool mergeable = sold.GetSubKey() == LWOOBJID_EMPTY && sold.GetConfig().values.empty() && !InventoryComponent::IsUniqueLot(lot);
if (mergeable) {
uint64_t room = 0;
for (const auto* const item : buyback->GetItems() | std::views::values) {
if (item->GetLot() == lot && item->GetCount() < stackSize) room += stackSize - item->GetCount();
}
if (room >= count) return;
}
// Live kept 27 items (the buyback window's size) and dropped the oldest when a 28th was sold: a 2014 capture shows
// RemoveItemFromInventory for the first item sold, in the buyback inventory, just before the 28th sale's item was
// added. Each item gets a new, higher object ID when it is sold, so the oldest is the one with the lowest ID.
// The ledger counted these items as gone when they were sold
EconomyLedger::ScopedItemTransfer alreadyCounted;
while (buyback->GetItems().size() >= BUYBACK_SIZE) {
const auto items = buyback->GetItems().size();
const auto oldest = std::ranges::min_element(buyback->GetItems(), {}, [](const auto& entry) { return entry.first; });
oldest->second->SetCount(0, false, false, false, eLootSourceType::VENDOR);
if (buyback->GetItems().size() >= items) break; // not removed (an empty stack)
}
}

View File

@@ -0,0 +1,88 @@
#pragma once
#ifndef VENDORCOMPONENT_H
#define VENDORCOMPONENT_H
#include "CDClientManager.h"
#include "Component.h"
#include "Entity.h"
#include "GameMessages.h"
#include "RakNetTypes.h"
#include "eReplicaComponentType.h"
enum class eVendorTransactionResult : uint32_t;
class InventoryComponent;
class Item;
struct SoldItem {
SoldItem(const LOT lot, const int32_t sortPriority) {
this->lot = lot;
this->sortPriority = sortPriority;
};
LOT lot = 0;
int32_t sortPriority = 0;
};
class VendorComponent : public Component {
public:
static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::VENDOR;
VendorComponent(Entity* parent, const int32_t componentID);
void LoadDataFromTemplate() override;
void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override;
bool OnRequestUse(GameMessages::RequestUseEvent& event);
virtual void RefreshInventory(bool isCreation = false);
void SetupConstants();
bool SellsItem(const LOT item) const;
float GetBuyScalar() const { return m_BuyScalar; }
float GetSellScalar() const { return m_SellScalar; }
void SetBuyScalar(const float value) { m_BuyScalar = value; }
void SetSellScalar(const float value) { m_SellScalar = value; }
const std::vector<SoldItem>& GetInventory() { return m_Inventory; }
void SetHasMultiCostItems(const bool hasMultiCostItems) {
if (m_HasMultiCostItems == hasMultiCostItems) return;
m_HasMultiCostItems = hasMultiCostItems;
m_DirtyVendor = true;
}
void SetHasStandardCostItems(const bool hasStandardCostItems) {
if (m_HasStandardCostItems == hasStandardCostItems) return;
m_HasStandardCostItems = hasStandardCostItems;
m_DirtyVendor = true;
}
void Buy(Entity* buyer, LOT lot, uint32_t count);
// SellToVendor / BuybackFromVendor from player (sent from sysAddr), for the item with object ID itemObjID.
void SellToVendor(Entity& player, const SystemAddress& sysAddr, LWOOBJID itemObjID, int32_t count);
void BuybackFromVendor(Entity& player, const SystemAddress& sysAddr, LWOOBJID itemObjID, int32_t count);
// Sends this vendor's stock (VendorStatusUpdate) to sysAddr; UNASSIGNED_SYSTEM_ADDRESS broadcasts.
void SendStatusUpdate(const SystemAddress& sysAddr, bool bUpdateOnly = false);
// Sends a VendorTransactionResult targeting target to sysAddr only.
static void SendTransactionResult(LWOOBJID target, const SystemAddress& sysAddr, eVendorTransactionResult result);
// How many items the buyback inventory keeps (the vendor window's buyback page)
static constexpr size_t BUYBACK_SIZE = 27;
// Before count of sold go to the buyback inventory: drops the oldest buyback items while it is full and they need
// a slot of their own.
static void MakeRoomInBuyback(InventoryComponent& inventory, const Item& sold, uint32_t count);
private:
void HandleMrReeCameras();
bool SetupItem(LOT item);
float m_BuyScalar = 0.0f;
float m_SellScalar = 0.0f;
float m_RefreshTimeSeconds = 0.0f;
uint32_t m_LootMatrixID = 0;
std::vector<SoldItem> m_Inventory;
bool m_DirtyVendor = false;
bool m_HasStandardCostItems = false;
bool m_HasMultiCostItems = false;
};
#endif // VENDORCOMPONENT_H