1
0
mirror of https://gitlab.com/OpenMW/openmw.git synced 2025-01-30 21:32:42 +00:00
OpenMW/apps/openmw/mwworld/worldmodel.cpp

523 lines
17 KiB
C++
Raw Normal View History

2022-12-06 00:11:19 +01:00
#include "worldmodel.hpp"
#include <algorithm>
#include <cassert>
#include <optional>
#include <stdexcept>
2018-08-14 23:05:43 +04:00
#include <components/debug/debuglog.hpp>
#include <components/esm/defs.hpp>
#include <components/esm3/cellid.hpp>
#include <components/esm3/cellref.hpp>
2022-09-22 21:26:05 +03:00
#include <components/esm3/cellstate.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/loadregn.hpp>
#include <components/esm4/loadwrld.hpp>
2015-07-09 19:22:04 +02:00
#include <components/loadinglistener/loadinglistener.hpp>
2023-05-22 14:23:06 +02:00
#include <components/settings/values.hpp>
2014-02-23 20:11:05 +01:00
#include "cellstore.hpp"
2022-09-22 21:26:05 +03:00
#include "esmstore.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/luamanager.hpp"
namespace MWWorld
{
namespace
{
const ESM::RefId draftCellId = ESM::RefId::index(ESM::REC_CSTA, 0);
template <class T>
CellStore& emplaceCellStore(ESM::RefId id, const T& cell, ESMStore& store, ESM::ReadersCache& readers,
std::unordered_map<ESM::RefId, CellStore>& cells)
{
const auto [it, inserted] = cells.emplace(
std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(Cell(cell), store, readers));
assert(inserted);
return it->second;
}
CellStore* emplaceInteriorCellStore(std::string_view name, ESMStore& store, ESM::ReadersCache& readers,
std::unordered_map<ESM::RefId, CellStore>& cells)
{
if (const ESM::Cell* cell = store.get<ESM::Cell>().search(name))
return &emplaceCellStore(cell->mId, *cell, store, readers, cells);
if (const ESM4::Cell* cell = store.get<ESM4::Cell>().searchCellName(name);
cell != nullptr && !cell->isExterior())
{
return &emplaceCellStore(cell->mId, *cell, store, readers, cells);
}
return nullptr;
}
const ESM::Cell* createEsmCell(ESM::ExteriorCellLocation location, ESMStore& store)
{
ESM::Cell record = {};
record.mData.mFlags = ESM::Cell::HasWater;
record.mData.mX = location.mX;
record.mData.mY = location.mY;
record.updateId();
return store.insert(record);
}
const ESM4::Cell* createEsm4Cell(ESM::ExteriorCellLocation location, ESMStore& store)
{
ESM4::Cell record = {};
record.mParent = location.mWorldspace;
record.mX = location.mX;
record.mY = location.mY;
return store.insert(record);
}
std::tuple<Cell, bool> createExteriorCell(ESM::ExteriorCellLocation location, ESMStore& store)
{
if (ESM::isEsm4Ext(location.mWorldspace))
{
if (store.get<ESM4::World>().search(location.mWorldspace) == nullptr)
throw std::runtime_error(
"Exterior ESM4 world is not found: " + location.mWorldspace.toDebugString());
const ESM4::Cell* cell = store.get<ESM4::Cell>().searchExterior(location);
bool created = cell == nullptr;
if (created)
cell = createEsm4Cell(location, store);
assert(cell != nullptr);
return { MWWorld::Cell(*cell), created };
}
const ESM::Cell* cell = store.get<ESM::Cell>().search(location.mX, location.mY);
bool created = cell == nullptr;
if (created)
cell = createEsmCell(location, store);
assert(cell != nullptr);
return { Cell(*cell), created };
}
std::optional<Cell> createCell(ESM::RefId id, const ESMStore& store)
{
if (const ESM4::Cell* cell = store.get<ESM4::Cell>().search(id))
return Cell(*cell);
if (const ESM::Cell* cell = store.get<ESM::Cell>().search(id))
return Cell(*cell);
return std::nullopt;
}
CellStore* getOrCreateExterior(const ESM::ExteriorCellLocation& location,
std::map<ESM::ExteriorCellLocation, MWWorld::CellStore*>& exteriors, ESMStore& store,
ESM::ReadersCache& readers, std::unordered_map<ESM::RefId, CellStore>& cells, bool triggerEvent)
{
if (const auto it = exteriors.find(location); it != exteriors.end())
{
assert(it->second != nullptr);
return it->second;
}
auto [cell, created] = createExteriorCell(location, store);
const ESM::RefId id = cell.getId();
CellStore* const cellStore = &emplaceCellStore(id, std::move(cell), store, readers, cells);
exteriors.emplace(location, cellStore);
if (created && triggerEvent)
MWBase::Environment::get().getLuaManager()->exteriorCreated(*cellStore);
return cellStore;
}
}
}
MWWorld::CellStore& MWWorld::WorldModel::getOrInsertCellStore(const ESM::Cell& cell)
{
const auto it = mCells.find(cell.mId);
if (it != mCells.end())
return it->second;
return insertCellStore(cell);
}
MWWorld::CellStore& MWWorld::WorldModel::insertCellStore(const ESM::Cell& cell)
{
CellStore& cellStore = emplaceCellStore(cell.mId, cell, mStore, mReaders, mCells);
if (cell.mData.mFlags & ESM::Cell::Interior)
mInteriors.emplace(cell.mName, &cellStore);
else
mExteriors.emplace(
ESM::ExteriorCellLocation(cell.getGridX(), cell.getGridY(), ESM::Cell::sDefaultWorldspaceId), &cellStore);
return cellStore;
}
2022-12-06 00:11:19 +01:00
void MWWorld::WorldModel::clear()
2013-05-15 17:54:18 +02:00
{
mPtrRegistry.clear();
2013-05-15 17:54:18 +02:00
mInteriors.clear();
mExteriors.clear();
2023-02-20 00:18:34 +01:00
mCells.clear();
std::fill(mIdCache.begin(), mIdCache.end(), std::make_pair(ESM::RefId(), (MWWorld::CellStore*)nullptr));
2013-05-15 17:54:18 +02:00
mIdCacheIndex = 0;
}
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
MWWorld::Ptr MWWorld::WorldModel::getPtrAndCache(const ESM::RefId& name, CellStore& cellStore)
{
Ptr ptr = cellStore.getPtr(name);
if (!ptr.isEmpty() && ptr.isInCell())
{
mIdCache[mIdCacheIndex].first = name;
mIdCache[mIdCacheIndex].second = &cellStore;
2022-09-22 21:26:05 +03:00
if (++mIdCacheIndex >= mIdCache.size())
mIdCacheIndex = 0;
}
return ptr;
}
2022-12-06 00:11:19 +01:00
void MWWorld::WorldModel::writeCell(ESM::ESMWriter& writer, CellStore& cell) const
{
2022-09-22 21:26:05 +03:00
if (cell.getState() != CellStore::State_Loaded)
cell.load();
ESM::CellState cellState;
2022-09-22 21:26:05 +03:00
cell.saveState(cellState);
2022-09-22 21:26:05 +03:00
writer.startRecord(ESM::REC_CSTA);
2023-02-21 23:26:40 +01:00
writer.writeCellId(cellState.mId);
2022-09-22 21:26:05 +03:00
cellState.save(writer);
cell.writeFog(writer);
2022-09-22 21:26:05 +03:00
cell.writeReferences(writer);
writer.endRecord(ESM::REC_CSTA);
}
MWWorld::WorldModel::WorldModel(MWWorld::ESMStore& store, ESM::ReadersCache& readers)
: mStore(store)
, mReaders(readers)
2023-05-22 14:23:06 +02:00
, mIdCache(Settings::cells().mPointersCacheSize, { ESM::RefId(), nullptr })
{
mDraftCell.mId = draftCellId;
}
namespace MWWorld
{
CellStore& WorldModel::getExterior(ESM::ExteriorCellLocation location, bool forceLoad) const
{
CellStore* cellStore = getOrCreateExterior(location, mExteriors, mStore, mReaders, mCells, true);
if (forceLoad && cellStore->getState() != CellStore::State_Loaded)
cellStore->load();
return *cellStore;
}
CellStore* WorldModel::findInterior(std::string_view name, bool forceLoad) const
{
const auto it = mInteriors.find(name);
CellStore* cellStore = nullptr;
if (it == mInteriors.end())
{
cellStore = emplaceInteriorCellStore(name, mStore, mReaders, mCells);
if (cellStore == nullptr)
return cellStore;
mInteriors.emplace(name, cellStore);
}
else
{
assert(it->second != nullptr);
cellStore = it->second;
}
if (forceLoad && cellStore->getState() != CellStore::State_Loaded)
cellStore->load();
return cellStore;
2012-02-12 12:35:29 +01:00
}
CellStore& WorldModel::getInterior(std::string_view name, bool forceLoad) const
{
CellStore* const cellStore = findInterior(name, forceLoad);
if (cellStore == nullptr)
throw std::runtime_error("Interior cell is not found: '" + std::string(name) + "'");
return *cellStore;
}
CellStore* WorldModel::findCell(ESM::RefId id, bool forceLoad) const
{
auto it = mCells.find(id);
if (it != mCells.end())
2023-07-23 18:25:20 +02:00
{
CellStore& cellStore = it->second;
if (forceLoad && cellStore.getState() != CellStore::State_Loaded)
cellStore.load();
return &cellStore;
}
if (id == draftCellId)
{
CellStore& cellStore = emplaceCellStore(id, Cell(mDraftCell), mStore, mReaders, mCells);
cellStore.load();
return &cellStore;
}
if (const auto* exteriorId = id.getIf<ESM::ESM3ExteriorCellRefId>())
return &getExterior(
ESM::ExteriorCellLocation(exteriorId->getX(), exteriorId->getY(), ESM::Cell::sDefaultWorldspaceId),
forceLoad);
std::optional<Cell> cell = createCell(id, mStore);
if (!cell.has_value())
return nullptr;
CellStore& cellStore = emplaceCellStore(id, std::move(*cell), mStore, mReaders, mCells);
if (cellStore.isExterior())
mExteriors.emplace(ESM::ExteriorCellLocation(cellStore.getCell()->getGridX(),
cellStore.getCell()->getGridY(), cellStore.getCell()->getWorldSpace()),
&cellStore);
else
mInteriors.emplace(cellStore.getCell()->getNameId(), &cellStore);
if (forceLoad && cellStore.getState() != CellStore::State_Loaded)
cellStore.load();
return &cellStore;
}
CellStore& WorldModel::getCell(ESM::RefId id, bool forceLoad) const
{
CellStore* const result = findCell(id, forceLoad);
if (result == nullptr)
throw std::runtime_error("Cell does not exist: " + id.toDebugString());
return *result;
}
CellStore& WorldModel::getDraftCell() const
{
return getCell(draftCellId);
}
CellStore* WorldModel::findCell(std::string_view name, bool forceLoad) const
2023-05-13 19:30:18 +02:00
{
if (CellStore* const cellStore = findInterior(name, forceLoad))
return cellStore;
// try named exteriors
const ESM::Cell* cell = mStore.get<ESM::Cell>().searchExtByName(name);
if (cell == nullptr)
{
// treat "Wilderness" like an empty string
static const std::string& defaultName
= mStore.get<ESM::GameSetting>().find("sDefaultCellname")->mValue.getString();
if (Misc::StringUtils::ciEqual(name, defaultName))
cell = mStore.get<ESM::Cell>().searchExtByName({});
}
if (cell == nullptr)
{
// now check for regions
const Store<ESM::Region>& regions = mStore.get<ESM::Region>();
const auto region = std::find_if(regions.begin(), regions.end(),
[&](const ESM::Region& v) { return Misc::StringUtils::ciEqual(name, v.mName); });
if (region != regions.end())
cell = mStore.get<ESM::Cell>().searchExtByRegion(region->mId);
}
if (cell != nullptr)
return &getExterior(
ESM::ExteriorCellLocation(cell->getGridX(), cell->getGridY(), ESM::Cell::sDefaultWorldspaceId),
forceLoad);
if (const ESM4::Cell* cell4 = mStore.get<ESM4::Cell>().searchCellName(name);
cell4 != nullptr && cell4->isExterior())
{
return &getExterior(cell4->getExteriorCellLocation(), forceLoad);
}
return nullptr;
}
CellStore& WorldModel::getCell(std::string_view name, bool forceLoad) const
{
CellStore* const result = findCell(name, forceLoad);
if (result == nullptr)
throw std::runtime_error(std::string("Can't find cell with name ") + std::string(name));
return *result;
}
void WorldModel::registerPtr(const Ptr& ptr)
{
if (ptr.mRef == nullptr)
throw std::logic_error("Ptr with nullptr mRef is not allowed to be registered");
mPtrRegistry.insert(ptr);
ptr.mRef->mWorldModel = this;
}
void WorldModel::deregisterLiveCellRef(LiveCellRefBase& ref) noexcept
{
mPtrRegistry.remove(ref);
ref.mWorldModel = nullptr;
}
}
2023-07-30 21:55:36 +02:00
MWWorld::Ptr MWWorld::WorldModel::getPtrByRefId(const ESM::RefId& name)
{
2023-05-26 19:26:23 +02:00
for (const auto& [cachedId, cellStore] : mIdCache)
{
if (cachedId != name || cellStore == nullptr)
continue;
Ptr ptr = cellStore->getPtr(name);
if (!ptr.isEmpty())
return ptr;
}
// Then check cells that are already listed
// Search in reverse, this is a workaround for an ambiguous chargen_plank reference in the vanilla game.
// there is one at -22,16 and one at -2,-9, the latter should be used.
for (auto iter = mExteriors.rbegin(); iter != mExteriors.rend(); ++iter)
{
Ptr ptr = getPtrAndCache(name, *iter->second);
if (!ptr.isEmpty())
return ptr;
}
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
for (auto iter = mInteriors.begin(); iter != mInteriors.end(); ++iter)
{
2023-02-18 23:42:20 +01:00
Ptr ptr = getPtrAndCache(name, *iter->second);
if (!ptr.isEmpty())
return ptr;
}
// Now try the other cells
2022-09-22 21:26:05 +03:00
const MWWorld::Store<ESM::Cell>& cells = mStore.get<ESM::Cell>();
for (auto iter = cells.extBegin(); iter != cells.extEnd(); ++iter)
{
if (mCells.contains(iter->mId))
continue;
Ptr ptr = getPtrAndCache(name, insertCellStore(*iter));
if (!ptr.isEmpty())
return ptr;
}
for (auto iter = cells.intBegin(); iter != cells.intEnd(); ++iter)
{
if (mCells.contains(iter->mId))
continue;
Ptr ptr = getPtrAndCache(name, insertCellStore(*iter));
if (!ptr.isEmpty())
return ptr;
}
// giving up
return Ptr();
}
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
void MWWorld::WorldModel::getExteriorPtrs(const ESM::RefId& name, std::vector<MWWorld::Ptr>& out)
{
2022-09-22 21:26:05 +03:00
const MWWorld::Store<ESM::Cell>& cells = mStore.get<ESM::Cell>();
for (MWWorld::Store<ESM::Cell>::iterator iter = cells.extBegin(); iter != cells.extEnd(); ++iter)
{
CellStore& cellStore = getOrInsertCellStore(*iter);
Ptr ptr = getPtrAndCache(name, cellStore);
if (!ptr.isEmpty())
out.push_back(ptr);
}
}
Initial commit: In ESM structures, replace the string members that are RefIds to other records, to a new strong type The strong type is actually just a string underneath, but this will help in the future to have a distinction so it's easier to search and replace when we use an integer ID Slowly going through all the changes to make, still hundreds of errors a lot of functions/structures use std::string or stringview to designate an ID. So it takes time Continues slowly replacing ids. There are technically more and more compilation errors I have good hope that there is a point where the amount of errors will dramatically go down as all the main functions use the ESM::RefId type Continue moving forward, changes to the stores slowly moving along Starting to see the fruit of those changes. still many many error, but more and more Irun into a situation where a function is sandwiched between two functions that use the RefId type. More replacements. Things are starting to get easier I can see more and more often the issue is that the function is awaiting a RefId, but is given a string there is less need to go down functions and to fix a long list of them. Still moving forward, and for the first time error count is going down! Good pace, not sure about topics though, mId and mName are actually the same thing and are used interchangeably Cells are back to using string for the name, haven't fixed everything yet. Many other changes Under the bar of 400 compilation errors. more good progress <100 compile errors! More progress Game settings store can use string for find, it was a bit absurd how every use of it required to create refId from string some more progress on other fronts Mostly game settings clean one error opened a lot of other errors. Down to 18, but more will prbably appear only link errors left?? Fixed link errors OpenMW compiles, and launches, with some issues, but still!
2022-09-25 13:17:09 +02:00
std::vector<MWWorld::Ptr> MWWorld::WorldModel::getAll(const ESM::RefId& id)
{
std::vector<Ptr> result;
for (auto& [cellId, cellStore] : mCells)
{
if (cellStore.getState() == CellStore::State_Unloaded)
cellStore.preload();
if (cellStore.getState() == CellStore::State_Preloaded)
{
if (!cellStore.hasId(id))
continue;
cellStore.load();
}
cellStore.forEach([&](const Ptr& ptr) {
if (ptr.getCellRef().getRefId() == id)
result.push_back(ptr);
return true;
});
}
return result;
}
2022-12-06 00:11:19 +01:00
int MWWorld::WorldModel::countSavedGameRecords() const
{
return std::count_if(mCells.begin(), mCells.end(), [](const auto& v) { return v.second.hasState(); });
}
2022-12-06 00:11:19 +01:00
void MWWorld::WorldModel::write(ESM::ESMWriter& writer, Loading::Listener& progress) const
{
2023-05-26 19:26:23 +02:00
for (auto& [id, cellStore] : mCells)
if (cellStore.hasState())
{
2023-05-26 19:26:23 +02:00
writeCell(writer, cellStore);
progress.increaseProgress();
}
}
struct MWWorld::WorldModel::GetCellStoreCallback : public CellStore::GetCellStoreCallback
{
public:
GetCellStoreCallback(WorldModel& worldModel)
2022-12-15 20:56:17 +01:00
: mWorldModel(worldModel)
{
}
WorldModel& mWorldModel;
CellStore* getCellStore(const ESM::RefId& cellId) override
{
if (const auto* exteriorId = cellId.getIf<ESM::ESM3ExteriorCellRefId>())
{
ESM::ExteriorCellLocation location(exteriorId->getX(), exteriorId->getY(), ESM::Cell::sDefaultWorldspaceId);
return getOrCreateExterior(
location, mWorldModel.mExteriors, mWorldModel.mStore, mWorldModel.mReaders, mWorldModel.mCells, false);
}
return mWorldModel.findCell(cellId);
}
};
bool MWWorld::WorldModel::readRecord(ESM::ESMReader& reader, uint32_t type)
{
2022-09-22 21:26:05 +03:00
if (type == ESM::REC_CSTA)
{
ESM::CellState state;
2023-02-21 23:26:40 +01:00
state.mId = reader.getCellId();
GetCellStoreCallback callback(*this);
CellStore* const cellStore = callback.getCellStore(state.mId);
if (cellStore == nullptr)
{
Log(Debug::Warning) << "Dropping state for cell " << state.mId << " (cell no longer exists)";
reader.skipRecord();
return true;
}
2022-09-22 21:26:05 +03:00
state.load(reader);
cellStore->loadState(state);
if (state.mHasFogOfWar)
cellStore->readFog(reader);
2022-09-22 21:26:05 +03:00
if (cellStore->getState() != CellStore::State_Loaded)
cellStore->load();
cellStore->readReferences(reader, &callback);
return true;
}
return false;
}