fix fatal error on invalid item id in inventory

This commit is contained in:
MihailRis 2025-12-16 00:17:51 +03:00
parent 77b4382577
commit 180dd5051b
4 changed files with 27 additions and 2 deletions

View file

@ -1,6 +1,9 @@
#include "Inventory.hpp"
#include "content/ContentReport.hpp"
#include "debug/Logger.hpp"
static debug::Logger logger("inventory");
Inventory::Inventory(int64_t id, size_t size) : id(id), slots(size) {
}
@ -104,6 +107,22 @@ dv::value Inventory::serialize() const {
return map;
}
void Inventory::check(const ContentIndices& indices) {
for (size_t i = 0; i < slots.size(); i++) {
auto& slot = slots[i];
if (indices.items.get(slot.getItemId()) == nullptr) {
#ifdef NDEBUG
logger.error() << "invalid item id " << slot.getItemId()
<< " found in inventory #" << id << " slot #" << i
<< "; will reset";
slot.clear();
#else
abort();
#endif
}
}
}
void Inventory::convert(const ContentReport* report) {
for (auto& slot : slots) {
itemid_t id = slot.getItemId();

View file

@ -39,6 +39,7 @@ public:
dv::value serialize() const override;
void check(const ContentIndices& indices);
void convert(const ContentReport* report);
static void convert(dv::value& data, const ContentReport* report);

View file

@ -4,6 +4,7 @@
#include <glm/gtx/norm.hpp>
#include "Player.hpp"
#include "content/Content.hpp"
#include "items/Inventories.hpp"
#include "world/Level.hpp"
#include "world/World.hpp"
@ -87,7 +88,9 @@ Player* Players::create(int64_t id) {
auto player = playerPtr.get();
add(std::move(playerPtr));
level.inventories->store(player->getInventory());
auto inventory = player->getInventory();
inventory->check(*level.content.getIndices());
level.inventories->store(std::move(inventory));
return player;
}
@ -147,6 +150,7 @@ void Players::deserialize(const dv::value& src) {
if (inventory->getId() == 0) {
inventory->setId(level.getWorld()->getNextInventoryId());
}
level.inventories->store(player->getInventory());
inventory->check(*level.content.getIndices());
level.inventories->store(inventory);
}
}

View file

@ -128,6 +128,7 @@ std::shared_ptr<Chunk> GlobalChunks::create(int x, int z, bool lighting) {
chunk->flags.loaded = true;
for (auto& entry : chunk->inventories) {
entry.second->check(indices);
level.inventories->store(entry.second);
}
}