id
int64 0
755k
| 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
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35,121
|
lightingnight.cpp
|
OpenMW_openmw/apps/opencs/view/render/lightingnight.cpp
|
#include "lightingnight.hpp"
#include <osg/Group>
#include <osg/Light>
#include <osg/LightSource>
#include <osg/ref_ptr>
void CSVRender::LightingNight::activate(osg::Group* rootNode, bool isExterior)
{
mRootNode = rootNode;
mLightSource = new osg::LightSource;
osg::ref_ptr<osg::Light> light(new osg::Light);
light->setPosition(osg::Vec4f(0.f, 0.f, 1.f, 0.f));
light->setAmbient(osg::Vec4f(0.f, 0.f, 0.f, 1.f));
light->setDiffuse(osg::Vec4f(0.2f, 0.2f, 0.2f, 1.f));
light->setSpecular(osg::Vec4f(0.f, 0.f, 0.f, 0.f));
light->setConstantAttenuation(1.f);
mLightSource->setLight(light);
mRootNode->addChild(mLightSource);
updateDayNightMode(isExterior ? 1 : 0);
}
void CSVRender::LightingNight::deactivate()
{
if (mRootNode && mLightSource.get())
mRootNode->removeChild(mLightSource);
}
osg::Vec4f CSVRender::LightingNight::getAmbientColour(osg::Vec4f* defaultAmbient)
{
if (defaultAmbient)
return *defaultAmbient;
else
return osg::Vec4f(0.2f, 0.2f, 0.2f, 1.f);
}
| 1,051
|
C++
|
.cpp
| 31
| 30.032258
| 81
| 0.694362
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,122
|
terrainselection.cpp
|
OpenMW_openmw/apps/opencs/view/render/terrainselection.cpp
|
#include "terrainselection.hpp"
#include <algorithm>
#include <cmath>
#include <osg/GL>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/PositionAttitudeTransform>
#include <osg/PrimitiveSet>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Vec3f>
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/world/cellcoordinates.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/land.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <components/esm3/loadland.hpp>
#include "cell.hpp"
#include "worldspacewidget.hpp"
namespace CSMWorld
{
struct Cell;
}
CSVRender::TerrainSelection::TerrainSelection(
osg::Group* parentNode, WorldspaceWidget* worldspaceWidget, TerrainSelectionType type)
: mParentNode(parentNode)
, mWorldspaceWidget(worldspaceWidget)
, mSelectionType(type)
{
mGeometry = new osg::Geometry();
mSelectionNode = new osg::Group();
mSelectionNode->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
mSelectionNode->getOrCreateStateSet()->setRenderBinDetails(11, "RenderBin");
mSelectionNode->addChild(mGeometry);
activate();
}
CSVRender::TerrainSelection::~TerrainSelection()
{
deactivate();
}
std::vector<std::pair<int, int>> CSVRender::TerrainSelection::getTerrainSelection() const
{
return mSelection;
}
void CSVRender::TerrainSelection::onlySelect(const std::vector<std::pair<int, int>>& localPositions)
{
mSelection = localPositions;
update();
}
void CSVRender::TerrainSelection::addSelect(const std::vector<std::pair<int, int>>& localPositions)
{
handleSelection(localPositions, SelectionMethod::AddSelect);
}
void CSVRender::TerrainSelection::removeSelect(const std::vector<std::pair<int, int>>& localPositions)
{
handleSelection(localPositions, SelectionMethod::RemoveSelect);
}
void CSVRender::TerrainSelection::toggleSelect(const std::vector<std::pair<int, int>>& localPositions)
{
handleSelection(localPositions, SelectionMethod::ToggleSelect);
}
void CSVRender::TerrainSelection::clearTemporarySelection()
{
mTemporarySelection.clear();
}
void CSVRender::TerrainSelection::activate()
{
if (!mParentNode->containsNode(mSelectionNode))
mParentNode->addChild(mSelectionNode);
}
void CSVRender::TerrainSelection::deactivate()
{
mParentNode->removeChild(mSelectionNode);
}
void CSVRender::TerrainSelection::update()
{
mSelectionNode->removeChild(mGeometry);
mGeometry = new osg::Geometry();
const osg::ref_ptr<osg::Vec3Array> vertices(new osg::Vec3Array);
switch (mSelectionType)
{
case TerrainSelectionType::Texture:
drawTextureSelection(vertices);
break;
case TerrainSelectionType::Shape:
drawShapeSelection(vertices);
break;
}
mGeometry->setVertexArray(vertices);
osg::ref_ptr<osg::DrawArrays> drawArrays = new osg::DrawArrays(osg::PrimitiveSet::LINES);
drawArrays->setCount(vertices->size());
if (vertices->size() != 0)
mGeometry->addPrimitiveSet(drawArrays);
mSelectionNode->addChild(mGeometry);
}
void CSVRender::TerrainSelection::drawShapeSelection(const osg::ref_ptr<osg::Vec3Array> vertices)
{
if (!mSelection.empty())
{
for (std::pair<int, int>& localPos : mSelection)
{
int x(localPos.first);
int y(localPos.second);
float xWorldCoord(CSMWorld::CellCoordinates::vertexGlobalToWorldCoords(x));
float yWorldCoord(CSMWorld::CellCoordinates::vertexGlobalToWorldCoords(y));
osg::Vec3f pointXY(xWorldCoord, yWorldCoord, calculateLandHeight(x, y));
vertices->push_back(pointXY);
vertices->push_back(osg::Vec3f(xWorldCoord, CSMWorld::CellCoordinates::vertexGlobalToWorldCoords(y - 1),
calculateLandHeight(x, y - 1)));
vertices->push_back(pointXY);
vertices->push_back(osg::Vec3f(CSMWorld::CellCoordinates::vertexGlobalToWorldCoords(x - 1), yWorldCoord,
calculateLandHeight(x - 1, y)));
vertices->push_back(pointXY);
vertices->push_back(osg::Vec3f(xWorldCoord, CSMWorld::CellCoordinates::vertexGlobalToWorldCoords(y + 1),
calculateLandHeight(x, y + 1)));
vertices->push_back(pointXY);
vertices->push_back(osg::Vec3f(CSMWorld::CellCoordinates::vertexGlobalToWorldCoords(x + 1), yWorldCoord,
calculateLandHeight(x + 1, y)));
}
}
}
void CSVRender::TerrainSelection::drawTextureSelection(const osg::ref_ptr<osg::Vec3Array> vertices)
{
if (!mSelection.empty())
{
const int landHeightsNudge = (ESM::Land::REAL_SIZE / ESM::Land::LAND_SIZE)
/ (ESM::Land::LAND_SIZE - 1); // Does this work with all land size configurations?
const int textureSizeToLandSizeModifier = (ESM::Land::LAND_SIZE - 1) / ESM::Land::LAND_TEXTURE_SIZE;
for (std::pair<int, int>& localPos : mSelection)
{
int x(localPos.first);
int y(localPos.second);
// convert texture selection to global vertex coordinates at selection box corners
int x1 = x * textureSizeToLandSizeModifier + landHeightsNudge;
int x2 = x * textureSizeToLandSizeModifier + textureSizeToLandSizeModifier + landHeightsNudge;
int y1 = y * textureSizeToLandSizeModifier - landHeightsNudge;
int y2 = y * textureSizeToLandSizeModifier + textureSizeToLandSizeModifier - landHeightsNudge;
// Draw edges (check all sides, draw lines between vertices, +1 height to keep lines above ground)
// Check adjancent selections, draw lines only to edges of the selection
const auto north = std::find(mSelection.begin(), mSelection.end(), std::make_pair(x, y + 1));
if (north == mSelection.end())
{
for (int i = 1; i < (textureSizeToLandSizeModifier + 1); i++)
{
float drawPreviousX = CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(x)
+ (i - 1) * (ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1));
float drawCurrentX = CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(x)
+ i * (ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1));
vertices->push_back(
osg::Vec3f(drawPreviousX, CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(y + 1),
calculateLandHeight(x1 + (i - 1), y2)));
vertices->push_back(
osg::Vec3f(drawCurrentX, CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(y + 1),
calculateLandHeight(x1 + i, y2)));
}
}
const auto south = std::find(mSelection.begin(), mSelection.end(), std::make_pair(x, y - 1));
if (south == mSelection.end())
{
for (int i = 1; i < (textureSizeToLandSizeModifier + 1); i++)
{
float drawPreviousX = CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(x)
+ (i - 1) * (ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1));
float drawCurrentX = CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(x)
+ i * (ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1));
vertices->push_back(
osg::Vec3f(drawPreviousX, CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(y),
calculateLandHeight(x1 + (i - 1), y1)));
vertices->push_back(osg::Vec3f(drawCurrentX,
CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(y), calculateLandHeight(x1 + i, y1)));
}
}
const auto east = std::find(mSelection.begin(), mSelection.end(), std::make_pair(x + 1, y));
if (east == mSelection.end())
{
for (int i = 1; i < (textureSizeToLandSizeModifier + 1); i++)
{
float drawPreviousY = CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(y)
+ (i - 1) * (ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1));
float drawCurrentY = CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(y)
+ i * (ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1));
vertices->push_back(osg::Vec3f(CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(x + 1),
drawPreviousY, calculateLandHeight(x2, y1 + (i - 1))));
vertices->push_back(osg::Vec3f(CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(x + 1),
drawCurrentY, calculateLandHeight(x2, y1 + i)));
}
}
const auto west = std::find(mSelection.begin(), mSelection.end(), std::make_pair(x - 1, y));
if (west == mSelection.end())
{
for (int i = 1; i < (textureSizeToLandSizeModifier + 1); i++)
{
float drawPreviousY = CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(y)
+ (i - 1) * (ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1));
float drawCurrentY = CSMWorld::CellCoordinates::textureGlobalYToWorldCoords(y)
+ i * (ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1));
vertices->push_back(osg::Vec3f(CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(x),
drawPreviousY, calculateLandHeight(x1, y1 + (i - 1))));
vertices->push_back(osg::Vec3f(CSMWorld::CellCoordinates::textureGlobalXToWorldCoords(x),
drawCurrentY, calculateLandHeight(x1, y1 + i)));
}
}
}
}
}
void CSVRender::TerrainSelection::handleSelection(
const std::vector<std::pair<int, int>>& localPositions, SelectionMethod selectionMethod)
{
for (auto const& localPos : localPositions)
{
const auto iter = std::find(mSelection.begin(), mSelection.end(), localPos);
switch (selectionMethod)
{
case SelectionMethod::OnlySelect:
break;
case SelectionMethod::AddSelect:
if (iter == mSelection.end())
{
mSelection.emplace_back(localPos);
}
break;
case SelectionMethod::RemoveSelect:
if (iter != mSelection.end())
{
mSelection.erase(iter);
}
break;
case SelectionMethod::ToggleSelect:
{
const auto iterTemp = std::find(mTemporarySelection.begin(), mTemporarySelection.end(), localPos);
if (iterTemp == mTemporarySelection.end())
{
if (iter == mSelection.end())
{
mSelection.emplace_back(localPos);
}
else
{
mSelection.erase(iter);
}
}
mTemporarySelection.emplace_back(localPos);
break;
}
default:
break;
}
}
update();
}
bool CSVRender::TerrainSelection::noCell(const std::string& cellId)
{
CSMDoc::Document& document = mWorldspaceWidget->getDocument();
const CSMWorld::IdCollection<CSMWorld::Cell>& cellCollection = document.getData().getCells();
return cellCollection.searchId(ESM::RefId::stringRefId(cellId)) == -1;
}
bool CSVRender::TerrainSelection::noLand(const std::string& cellId)
{
CSMDoc::Document& document = mWorldspaceWidget->getDocument();
const CSMWorld::IdCollection<CSMWorld::Land>& landCollection = document.getData().getLand();
return landCollection.searchId(ESM::RefId::stringRefId(cellId)) == -1;
}
bool CSVRender::TerrainSelection::noLandLoaded(const std::string& cellId)
{
CSMDoc::Document& document = mWorldspaceWidget->getDocument();
const CSMWorld::IdCollection<CSMWorld::Land>& landCollection = document.getData().getLand();
return !landCollection.getRecord(ESM::RefId::stringRefId(cellId)).get().isDataLoaded(ESM::Land::DATA_VNML);
}
bool CSVRender::TerrainSelection::isLandLoaded(const std::string& cellId)
{
if (!noCell(cellId) && !noLand(cellId) && !noLandLoaded(cellId))
return true;
return false;
}
int CSVRender::TerrainSelection::calculateLandHeight(int x, int y) // global vertex coordinates
{
int cellX = std::floor(static_cast<float>(x) / (ESM::Land::LAND_SIZE - 1));
int cellY = std::floor(static_cast<float>(y) / (ESM::Land::LAND_SIZE - 1));
int localX = x - cellX * (ESM::Land::LAND_SIZE - 1);
int localY = y - cellY * (ESM::Land::LAND_SIZE - 1);
CSMWorld::CellCoordinates coords(cellX, cellY);
float landHeight = 0.f;
if (CSVRender::Cell* cell = dynamic_cast<CSVRender::Cell*>(mWorldspaceWidget->getCell(coords)))
{
landHeight = cell->getSumOfAlteredAndTrueHeight(cellX, cellY, localX, localY);
}
else if (isLandLoaded(CSMWorld::CellCoordinates::generateId(cellX, cellY)))
{
CSMDoc::Document& document = mWorldspaceWidget->getDocument();
std::string cellId = CSMWorld::CellCoordinates::generateId(cellX, cellY);
const ESM::Land::LandData* landData = document.getData()
.getLand()
.getRecord(ESM::RefId::stringRefId(cellId))
.get()
.getLandData(ESM::Land::DATA_VHGT);
return landData->mHeights[localY * ESM::Land::LAND_SIZE + localX];
}
return landHeight;
}
| 14,135
|
C++
|
.cpp
| 300
| 36.776667
| 117
| 0.62169
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,123
|
tagbase.cpp
|
OpenMW_openmw/apps/opencs/view/render/tagbase.cpp
|
#include "tagbase.hpp"
#include <apps/opencs/view/render/mask.hpp>
CSVRender::TagBase::TagBase(Mask mask)
: mMask(mask)
{
}
CSVRender::Mask CSVRender::TagBase::getMask() const
{
return mMask;
}
QString CSVRender::TagBase::getToolTip(bool hideBasics, const WorldspaceHitResult& /*hit*/) const
{
return "";
}
| 323
|
C++
|
.cpp
| 14
| 20.928571
| 97
| 0.747541
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,124
|
lightingbright.cpp
|
OpenMW_openmw/apps/opencs/view/render/lightingbright.cpp
|
#include "lightingbright.hpp"
#include <osg/Group>
#include <osg/Light>
#include <osg/LightSource>
#include <osg/ref_ptr>
CSVRender::LightingBright::LightingBright() {}
void CSVRender::LightingBright::activate(osg::Group* rootNode, bool /*isExterior*/)
{
mRootNode = rootNode;
mLightSource = (new osg::LightSource);
osg::ref_ptr<osg::Light> light(new osg::Light);
light->setAmbient(osg::Vec4f(0.f, 0.f, 0.f, 1.f));
light->setPosition(osg::Vec4f(0.f, 0.f, 1.f, 0.f));
light->setDiffuse(osg::Vec4f(1.f, 1.f, 1.f, 1.f));
light->setSpecular(osg::Vec4f(0.f, 0.f, 0.f, 0.f));
light->setConstantAttenuation(1.f);
mLightSource->setLight(light);
mRootNode->addChild(mLightSource);
updateDayNightMode(0);
}
void CSVRender::LightingBright::deactivate()
{
if (mRootNode && mLightSource.get())
mRootNode->removeChild(mLightSource);
}
osg::Vec4f CSVRender::LightingBright::getAmbientColour(osg::Vec4f* /*defaultAmbient*/)
{
return osg::Vec4f(1.f, 1.f, 1.f, 1.f);
}
| 1,021
|
C++
|
.cpp
| 29
| 31.793103
| 86
| 0.698574
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,125
|
pathgridmode.cpp
|
OpenMW_openmw/apps/opencs/view/render/pathgridmode.cpp
|
#include "pathgridmode.hpp"
#include <QIcon>
#include <components/misc/scalableicon.hpp>
#include <components/sceneutil/pathgridutil.hpp>
#include "../../model/prefs/state.hpp"
#include "../../model/world/commandmacro.hpp"
#include "../widget/scenetoolbar.hpp"
#include "cell.hpp"
#include "mask.hpp"
#include "pathgrid.hpp"
#include "pathgridselectionmode.hpp"
#include "worldspacewidget.hpp"
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/view/render/editmode.hpp>
#include <apps/opencs/view/render/tagbase.hpp>
#include <osg/Camera>
#include <osg/Matrixd>
#include <osg/Vec3d>
#include <osg/ref_ptr>
#include <vector>
class QPoint;
class QUndoStack;
class QWidget;
namespace CSVRender
{
PathgridMode::PathgridMode(WorldspaceWidget* worldspaceWidget, QWidget* parent)
: EditMode(worldspaceWidget, Misc::ScalableIcon::load(":scenetoolbar/editing-pathgrid"),
Mask_Pathgrid | Mask_Terrain | Mask_Reference, getTooltip(), parent)
, mDragMode(DragMode_None)
, mFromNode(0)
, mSelectionMode(nullptr)
{
}
QString PathgridMode::getTooltip()
{
return QString(
"Pathgrid editing"
"<ul><li>Press {scene-edit-primary} to add a node to the cursor location</li>"
"<li>Press {scene-edit-secondary} to connect the selected nodes to the node beneath the cursor</li>"
"<li>Press {scene-edit-primary} and drag to move selected nodes</li>"
"<li>Press {scene-edit-secondary} and drag to connect one node to another</li>"
"</ul><p>Note: Only a single cell's pathgrid may be edited at a time");
}
void PathgridMode::activate(CSVWidget::SceneToolbar* toolbar)
{
if (!mSelectionMode)
{
mSelectionMode = new PathgridSelectionMode(toolbar, getWorldspaceWidget());
}
EditMode::activate(toolbar);
toolbar->addTool(mSelectionMode);
}
void PathgridMode::deactivate(CSVWidget::SceneToolbar* toolbar)
{
if (mSelectionMode)
{
toolbar->removeTool(mSelectionMode);
delete mSelectionMode;
mSelectionMode = nullptr;
}
}
void PathgridMode::primaryOpenPressed(const WorldspaceHitResult& hitResult) {}
void PathgridMode::primaryEditPressed(const WorldspaceHitResult& hitResult)
{
if (CSMPrefs::get()["3D Scene Input"]["context-select"].isTrue()
&& dynamic_cast<PathgridTag*>(hitResult.tag.get()))
{
primarySelectPressed(hitResult);
}
else if (Cell* cell = getWorldspaceWidget().getCell(hitResult.worldPos))
{
if (cell->getPathgrid())
{
// Add node
QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
QString description = "Add node";
CSMWorld::CommandMacro macro(undoStack, description);
cell->getPathgrid()->applyPoint(macro, hitResult.worldPos);
}
}
}
void PathgridMode::secondaryEditPressed(const WorldspaceHitResult& hit)
{
if (hit.tag)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(hit.tag.get()))
{
if (tag->getPathgrid()->isSelected())
{
unsigned short node = SceneUtil::getPathgridNode(hit.index0);
QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
QString description = "Connect node to selected nodes";
CSMWorld::CommandMacro macro(undoStack, description);
tag->getPathgrid()->applyEdges(macro, node);
}
}
}
}
void PathgridMode::primarySelectPressed(const WorldspaceHitResult& hit)
{
getWorldspaceWidget().clearSelection(Mask_Pathgrid);
if (hit.tag)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(hit.tag.get()))
{
mLastId = tag->getPathgrid()->getId();
unsigned short node = SceneUtil::getPathgridNode(hit.index0);
tag->getPathgrid()->toggleSelected(node);
}
}
}
void PathgridMode::secondarySelectPressed(const WorldspaceHitResult& hit)
{
if (hit.tag)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(hit.tag.get()))
{
if (tag->getPathgrid()->getId() != mLastId)
{
getWorldspaceWidget().clearSelection(Mask_Pathgrid);
mLastId = tag->getPathgrid()->getId();
}
unsigned short node = SceneUtil::getPathgridNode(hit.index0);
tag->getPathgrid()->toggleSelected(node);
return;
}
}
getWorldspaceWidget().clearSelection(Mask_Pathgrid);
}
bool PathgridMode::primaryEditStartDrag(const QPoint& pos)
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Pathgrid);
if (CSMPrefs::get()["3D Scene Input"]["context-select"].isTrue())
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
if (dynamic_cast<PathgridTag*>(hit.tag.get()))
{
primarySelectPressed(hit);
selection = getWorldspaceWidget().getSelection(Mask_Pathgrid);
}
}
if (!selection.empty())
{
mDragMode = DragMode_Move;
return true;
}
return false;
}
bool PathgridMode::secondaryEditStartDrag(const QPoint& pos)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
if (hit.tag)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(hit.tag.get()))
{
mDragMode = DragMode_Edge;
mEdgeId = tag->getPathgrid()->getId();
mFromNode = SceneUtil::getPathgridNode(hit.index0);
tag->getPathgrid()->setDragOrigin(mFromNode);
return true;
}
}
return false;
}
void PathgridMode::drag(const QPoint& pos, int diffX, int diffY, double speedFactor)
{
if (mDragMode == DragMode_Move)
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Pathgrid);
for (std::vector<osg::ref_ptr<TagBase>>::iterator it = selection.begin(); it != selection.end(); ++it)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(it->get()))
{
osg::Vec3d eye, center, up, offset;
getWorldspaceWidget().getCamera()->getViewMatrix().getLookAt(eye, center, up);
offset = (up * diffY * speedFactor) + (((center - eye) ^ up) * diffX * speedFactor);
tag->getPathgrid()->moveSelected(offset);
}
}
}
else if (mDragMode == DragMode_Edge)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
Cell* cell = getWorldspaceWidget().getCell(hit.worldPos);
if (cell && cell->getPathgrid())
{
PathgridTag* tag = nullptr;
if (hit.tag && (tag = dynamic_cast<PathgridTag*>(hit.tag.get()))
&& tag->getPathgrid()->getId() == mEdgeId)
{
unsigned short node = SceneUtil::getPathgridNode(hit.index0);
cell->getPathgrid()->setDragEndpoint(node);
}
else
{
cell->getPathgrid()->setDragEndpoint(hit.worldPos);
}
}
}
}
void PathgridMode::dragCompleted(const QPoint& pos)
{
if (mDragMode == DragMode_Move)
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Pathgrid);
for (std::vector<osg::ref_ptr<TagBase>>::iterator it = selection.begin(); it != selection.end(); ++it)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(it->get()))
{
QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
QString description = "Move pathgrid node(s)";
CSMWorld::CommandMacro macro(undoStack, description);
tag->getPathgrid()->applyPosition(macro);
}
}
}
else if (mDragMode == DragMode_Edge)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
if (hit.tag)
{
if (PathgridTag* tag = dynamic_cast<PathgridTag*>(hit.tag.get()))
{
if (tag->getPathgrid()->getId() == mEdgeId)
{
unsigned short toNode = SceneUtil::getPathgridNode(hit.index0);
QUndoStack& undoStack = getWorldspaceWidget().getDocument().getUndoStack();
QString description = "Add edge between nodes";
CSMWorld::CommandMacro macro(undoStack, description);
tag->getPathgrid()->applyEdge(macro, mFromNode, toNode);
}
}
}
mEdgeId.clear();
mFromNode = 0;
}
mDragMode = DragMode_None;
getWorldspaceWidget().reset(Mask_Pathgrid);
}
void PathgridMode::dragAborted()
{
getWorldspaceWidget().reset(Mask_Pathgrid);
}
}
| 10,043
|
C++
|
.cpp
| 246
| 29.630081
| 119
| 0.580983
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,126
|
terrainshapemode.cpp
|
OpenMW_openmw/apps/opencs/view/render/terrainshapemode.cpp
|
#include "terrainshapemode.hpp"
#include <algorithm>
#include <cmath>
#include <memory>
#include <string>
#include <QComboBox>
#include <QDropEvent>
#include <QEvent>
#include <QIcon>
#include <QWidget>
#include <osg/Camera>
#include <osg/Vec3f>
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/cellselection.hpp>
#include <apps/opencs/model/world/columnimp.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/idtable.hpp>
#include <apps/opencs/model/world/land.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/widget/brushshapes.hpp>
#include <apps/opencs/view/widget/scenetool.hpp>
#include <components/debug/debuglog.hpp>
#include <components/esm3/loadland.hpp>
#include <components/misc/scalableicon.hpp>
#include "../widget/scenetoolbar.hpp"
#include "../widget/scenetoolshapebrush.hpp"
#include "../../model/prefs/state.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/idtree.hpp"
#include "brushdraw.hpp"
#include "commands.hpp"
#include "editmode.hpp"
#include "mask.hpp"
#include "pagedworldspacewidget.hpp"
#include "terrainselection.hpp"
#include "worldspacewidget.hpp"
class QPoint;
class QWidget;
namespace CSMWorld
{
struct Cell;
}
namespace osg
{
class Group;
}
CSVRender::TerrainShapeMode::TerrainShapeMode(
WorldspaceWidget* worldspaceWidget, osg::Group* parentNode, QWidget* parent)
: EditMode(worldspaceWidget, Misc::ScalableIcon::load(":scenetoolbar/editing-terrain-shape"), Mask_Terrain,
"Terrain land editing", parent)
, mParentNode(parentNode)
{
}
void CSVRender::TerrainShapeMode::activate(CSVWidget::SceneToolbar* toolbar)
{
if (!mTerrainShapeSelection)
{
mTerrainShapeSelection
= std::make_shared<TerrainSelection>(mParentNode, &getWorldspaceWidget(), TerrainSelectionType::Shape);
}
if (!mShapeBrushScenetool)
{
mShapeBrushScenetool
= new CSVWidget::SceneToolShapeBrush(toolbar, "scenetoolshapebrush", getWorldspaceWidget().getDocument());
connect(mShapeBrushScenetool, &CSVWidget::SceneTool::clicked, mShapeBrushScenetool,
&CSVWidget::SceneToolShapeBrush::activate);
connect(mShapeBrushScenetool->mShapeBrushWindow, &CSVWidget::ShapeBrushWindow::passBrushSize, this,
&TerrainShapeMode::setBrushSize);
connect(mShapeBrushScenetool->mShapeBrushWindow, &CSVWidget::ShapeBrushWindow::passBrushShape, this,
&TerrainShapeMode::setBrushShape);
connect(mShapeBrushScenetool->mShapeBrushWindow->mSizeSliders->mBrushSizeSlider, &QSlider::valueChanged, this,
&TerrainShapeMode::setBrushSize);
connect(mShapeBrushScenetool->mShapeBrushWindow->mToolSelector, qOverload<int>(&QComboBox::currentIndexChanged),
this, &TerrainShapeMode::setShapeEditTool);
connect(mShapeBrushScenetool->mShapeBrushWindow->mToolStrengthSlider, &QSlider::valueChanged, this,
&TerrainShapeMode::setShapeEditToolStrength);
}
if (!mBrushDraw)
mBrushDraw = std::make_unique<BrushDraw>(mParentNode);
EditMode::activate(toolbar);
toolbar->addTool(mShapeBrushScenetool);
}
void CSVRender::TerrainShapeMode::deactivate(CSVWidget::SceneToolbar* toolbar)
{
if (mShapeBrushScenetool)
{
toolbar->removeTool(mShapeBrushScenetool);
}
if (mTerrainShapeSelection)
{
mTerrainShapeSelection.reset();
}
if (mBrushDraw)
mBrushDraw.reset();
EditMode::deactivate(toolbar);
}
void CSVRender::TerrainShapeMode::primaryOpenPressed(const WorldspaceHitResult& hit) // Apply changes here
{
}
void CSVRender::TerrainShapeMode::primaryEditPressed(const WorldspaceHitResult& hit)
{
if (hit.hit && hit.tag == nullptr)
{
if (mShapeEditTool == ShapeEditTool_Flatten || mShapeEditTool == ShapeEditTool_Equalize)
setFlattenToolTargetHeight(hit);
if (mDragMode == InteractionType_PrimaryEdit && mShapeEditTool != ShapeEditTool_Drag)
{
editTerrainShapeGrid(CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos), true);
applyTerrainEditChanges();
}
}
clearTransientEdits();
}
void CSVRender::TerrainShapeMode::primarySelectPressed(const WorldspaceHitResult& hit)
{
if (hit.hit && hit.tag == nullptr)
{
selectTerrainShapes(CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos), 0);
mTerrainShapeSelection->clearTemporarySelection();
}
}
void CSVRender::TerrainShapeMode::secondarySelectPressed(const WorldspaceHitResult& hit)
{
if (hit.hit && hit.tag == nullptr)
{
selectTerrainShapes(CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos), 1);
mTerrainShapeSelection->clearTemporarySelection();
}
}
bool CSVRender::TerrainShapeMode::primaryEditStartDrag(const QPoint& pos)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
mDragMode = InteractionType_PrimaryEdit;
if (hit.hit && hit.tag == nullptr)
{
mEditingPos = hit.worldPos;
mIsEditing = true;
if (mShapeEditTool == ShapeEditTool_Flatten || mShapeEditTool == ShapeEditTool_Equalize)
setFlattenToolTargetHeight(hit);
}
return true;
}
bool CSVRender::TerrainShapeMode::secondaryEditStartDrag(const QPoint& pos)
{
return false;
}
bool CSVRender::TerrainShapeMode::primarySelectStartDrag(const QPoint& pos)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
mDragMode = InteractionType_PrimarySelect;
if (!hit.hit || hit.tag != nullptr)
{
mDragMode = InteractionType_None;
return false;
}
selectTerrainShapes(CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos), 0);
return true;
}
bool CSVRender::TerrainShapeMode::secondarySelectStartDrag(const QPoint& pos)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
mDragMode = InteractionType_SecondarySelect;
if (!hit.hit || hit.tag != nullptr)
{
mDragMode = InteractionType_None;
return false;
}
selectTerrainShapes(CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos), 1);
return true;
}
void CSVRender::TerrainShapeMode::drag(const QPoint& pos, int diffX, int diffY, double speedFactor)
{
if (mDragMode == InteractionType_PrimaryEdit)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
mTotalDiffY += diffY;
if (mIsEditing)
{
if (mShapeEditTool == ShapeEditTool_Drag)
editTerrainShapeGrid(CSMWorld::CellCoordinates::toVertexCoords(mEditingPos), true);
else
editTerrainShapeGrid(CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos), true);
}
}
if (mDragMode == InteractionType_PrimarySelect)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
if (hit.hit && hit.tag == nullptr)
selectTerrainShapes(CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos), 0);
}
if (mDragMode == InteractionType_SecondarySelect)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
if (hit.hit && hit.tag == nullptr)
selectTerrainShapes(CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos), 1);
}
}
void CSVRender::TerrainShapeMode::dragCompleted(const QPoint& pos)
{
if (mDragMode == InteractionType_PrimaryEdit)
{
applyTerrainEditChanges();
clearTransientEdits();
}
if (mDragMode == InteractionType_PrimarySelect || mDragMode == InteractionType_SecondarySelect)
{
mTerrainShapeSelection->clearTemporarySelection();
}
}
void CSVRender::TerrainShapeMode::dragAborted()
{
clearTransientEdits();
mDragMode = InteractionType_None;
}
void CSVRender::TerrainShapeMode::dragWheel(int diff, double speedFactor) {}
void CSVRender::TerrainShapeMode::sortAndLimitAlteredCells()
{
bool passing = false;
int passes = 0;
std::sort(mAlteredCells.begin(), mAlteredCells.end());
mAlteredCells.erase(std::unique(mAlteredCells.begin(), mAlteredCells.end()), mAlteredCells.end());
while (!passing) // Multiple passes are needed when steepness problems arise for both x and y axis simultaneously
{
passing = true;
for (CSMWorld::CellCoordinates cellCoordinates : mAlteredCells)
{
limitAlteredHeights(cellCoordinates);
}
std::reverse(mAlteredCells.begin(),
mAlteredCells
.end()); // Instead of alphabetical order, this should be fixed to sort cells by cell coordinates
for (CSMWorld::CellCoordinates cellCoordinates : mAlteredCells)
{
if (!limitAlteredHeights(cellCoordinates, true))
passing = false;
}
++passes;
if (passes > 2)
{
Log(Debug::Warning) << "Warning: User edit exceeds accepted slope steepness. Automatic limiting has "
"failed, edit has been discarded.";
clearTransientEdits();
return;
}
}
}
void CSVRender::TerrainShapeMode::clearTransientEdits()
{
mTotalDiffY = 0;
mIsEditing = false;
mAlteredCells.clear();
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
paged->resetAllAlteredHeights();
mTerrainShapeSelection->update();
}
void CSVRender::TerrainShapeMode::applyTerrainEditChanges()
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
CSMWorld::IdTable& ltexTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
int landnormalsColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandNormalsIndex);
QUndoStack& undoStack = document.getUndoStack();
sortAndLimitAlteredCells();
undoStack.beginMacro("Edit shape and normal records");
// One command at the beginning of the macro for redrawing the terrain-selection grid when undoing the changes.
undoStack.push(new DrawTerrainSelectionCommand(&getWorldspaceWidget()));
for (CSMWorld::CellCoordinates cellCoordinates : mAlteredCells)
{
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoordinates.getX(), cellCoordinates.getY());
undoStack.push(new CSMWorld::TouchLandCommand(landTable, ltexTable, cellId));
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
CSMWorld::LandHeightsColumn::DataType landShapeNew(landShapePointer);
CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget());
// Generate land height record
for (int i = 0; i < ESM::Land::LAND_SIZE; ++i)
{
for (int j = 0; j < ESM::Land::LAND_SIZE; ++j)
{
if (paged && paged->getCellAlteredHeight(cellCoordinates, i, j))
landShapeNew[j * ESM::Land::LAND_SIZE + i] = landShapePointer[j * ESM::Land::LAND_SIZE + i]
+ *paged->getCellAlteredHeight(cellCoordinates, i, j);
else
landShapeNew[j * ESM::Land::LAND_SIZE + i] = 0;
}
}
pushEditToCommand(landShapeNew, document, landTable, cellId);
}
for (CSMWorld::CellCoordinates cellCoordinates : mAlteredCells)
{
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoordinates.getX(), cellCoordinates.getY());
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
const CSMWorld::LandHeightsColumn::DataType landRightShapePointer
= landTable
.data(landTable.getModelIndex(
CSMWorld::CellCoordinates::generateId(cellCoordinates.getX() + 1, cellCoordinates.getY()),
landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
const CSMWorld::LandHeightsColumn::DataType landDownShapePointer
= landTable
.data(landTable.getModelIndex(
CSMWorld::CellCoordinates::generateId(cellCoordinates.getX(), cellCoordinates.getY() + 1),
landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
const CSMWorld::LandNormalsColumn::DataType landNormalsPointer
= landTable.data(landTable.getModelIndex(cellId, landnormalsColumn))
.value<CSMWorld::LandNormalsColumn::DataType>();
CSMWorld::LandNormalsColumn::DataType landNormalsNew(landNormalsPointer);
// Generate land normals record
for (int i = 0; i < ESM::Land::LAND_SIZE; ++i)
{
for (int j = 0; j < ESM::Land::LAND_SIZE; ++j)
{
osg::Vec3f v1(128, 0, 0);
osg::Vec3f v2(0, 128, 0);
if (i < ESM::Land::LAND_SIZE - 1)
v1.z() = landShapePointer[j * ESM::Land::LAND_SIZE + i + 1]
- landShapePointer[j * ESM::Land::LAND_SIZE + i];
else
{
std::string shiftedCellId
= CSMWorld::CellCoordinates::generateId(cellCoordinates.getX() + 1, cellCoordinates.getY());
if (isLandLoaded(shiftedCellId))
v1.z() = landRightShapePointer[j * ESM::Land::LAND_SIZE + 1]
- landShapePointer[j * ESM::Land::LAND_SIZE + i];
}
if (j < ESM::Land::LAND_SIZE - 1)
v2.z() = landShapePointer[(j + 1) * ESM::Land::LAND_SIZE + i]
- landShapePointer[j * ESM::Land::LAND_SIZE + i];
else
{
std::string shiftedCellId
= CSMWorld::CellCoordinates::generateId(cellCoordinates.getX(), cellCoordinates.getY() + 1);
if (isLandLoaded(shiftedCellId))
v2.z() = landDownShapePointer[ESM::Land::LAND_SIZE + i]
- landShapePointer[j * ESM::Land::LAND_SIZE + i];
}
osg::Vec3f normal = v1 ^ v2;
const float hyp = normal.length() / 127.0f;
normal /= hyp;
landNormalsNew[(j * ESM::Land::LAND_SIZE + i) * 3 + 0] = normal.x();
landNormalsNew[(j * ESM::Land::LAND_SIZE + i) * 3 + 1] = normal.y();
landNormalsNew[(j * ESM::Land::LAND_SIZE + i) * 3 + 2] = normal.z();
}
}
pushNormalsEditToCommand(landNormalsNew, document, landTable, cellId);
}
// One command at the end of the macro for redrawing the terrain-selection grid when redoing the changes.
undoStack.push(new DrawTerrainSelectionCommand(&getWorldspaceWidget()));
undoStack.endMacro();
clearTransientEdits();
}
float CSVRender::TerrainShapeMode::calculateBumpShape(float distance, int radius, float height)
{
float distancePerRadius = distance / radius;
return height
- height
* (3 * distancePerRadius * distancePerRadius - 2 * distancePerRadius * distancePerRadius * distancePerRadius);
}
void CSVRender::TerrainShapeMode::editTerrainShapeGrid(const std::pair<int, int>& vertexCoords, bool dragOperation)
{
int r = mBrushSize / 2;
if (r == 0)
r = 1; // Prevent division by zero later, which might happen when mBrushSize == 1
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
if (mShapeEditTool == ShapeEditTool_Drag)
paged->resetAllAlteredHeights();
}
if (mBrushShape == CSVWidget::BrushShape_Point)
{
std::string cellId = CSMWorld::CellCoordinates::vertexGlobalToCellId(vertexCoords);
CSMWorld::CellCoordinates cellCoords = CSMWorld::CellCoordinates::fromId(cellId).first;
int x = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(vertexCoords.first);
int y = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(vertexCoords.second);
if (mShapeEditTool == ShapeEditTool_Drag)
alterHeight(cellCoords, x, y, mTotalDiffY);
if (mShapeEditTool == ShapeEditTool_PaintToRaise || mShapeEditTool == ShapeEditTool_PaintToLower)
{
alterHeight(cellCoords, x, y, mShapeEditToolStrength);
float smoothMultiplier
= static_cast<float>(CSMPrefs::get()["3D Scene Editing"]["landedit-post-smoothstrength"].toDouble());
if (CSMPrefs::get()["3D Scene Editing"]["landedit-post-smoothpainting"].isTrue())
smoothHeight(cellCoords, x, y, mShapeEditToolStrength * smoothMultiplier);
}
if (mShapeEditTool == ShapeEditTool_Smooth)
smoothHeight(cellCoords, x, y, mShapeEditToolStrength);
if (mShapeEditTool == ShapeEditTool_Flatten)
flattenHeight(cellCoords, x, y, mShapeEditToolStrength, mTargetHeight);
if (mShapeEditTool == ShapeEditTool_Equalize)
equalizeHeight(cellCoords, x, y, mTargetHeight);
}
if (mBrushShape == CSVWidget::BrushShape_Square)
{
for (int i = vertexCoords.first - r; i <= vertexCoords.first + r; ++i)
{
for (int j = vertexCoords.second - r; j <= vertexCoords.second + r; ++j)
{
std::string cellId = CSMWorld::CellCoordinates::vertexGlobalToCellId(std::make_pair(i, j));
CSMWorld::CellCoordinates cellCoords = CSMWorld::CellCoordinates::fromId(cellId).first;
int x = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(i);
int y = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(j);
if (mShapeEditTool == ShapeEditTool_Drag)
alterHeight(cellCoords, x, y, mTotalDiffY);
if (mShapeEditTool == ShapeEditTool_PaintToRaise || mShapeEditTool == ShapeEditTool_PaintToLower)
{
alterHeight(cellCoords, x, y, mShapeEditToolStrength);
float smoothMultiplier = static_cast<float>(
CSMPrefs::get()["3D Scene Editing"]["landedit-post-smoothstrength"].toDouble());
if (CSMPrefs::get()["3D Scene Editing"]["landedit-post-smoothpainting"].isTrue())
smoothHeight(cellCoords, x, y, mShapeEditToolStrength * smoothMultiplier);
}
if (mShapeEditTool == ShapeEditTool_Smooth)
smoothHeight(cellCoords, x, y, mShapeEditToolStrength);
if (mShapeEditTool == ShapeEditTool_Flatten)
flattenHeight(cellCoords, x, y, mShapeEditToolStrength, mTargetHeight);
if (mShapeEditTool == ShapeEditTool_Equalize)
equalizeHeight(cellCoords, x, y, mTargetHeight);
}
}
}
if (mBrushShape == CSVWidget::BrushShape_Circle)
{
for (int i = vertexCoords.first - r; i <= vertexCoords.first + r; ++i)
{
for (int j = vertexCoords.second - r; j <= vertexCoords.second + r; ++j)
{
std::string cellId = CSMWorld::CellCoordinates::vertexGlobalToCellId(std::make_pair(i, j));
CSMWorld::CellCoordinates cellCoords = CSMWorld::CellCoordinates::fromId(cellId).first;
int x = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(i);
int y = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(j);
int distanceX = abs(i - vertexCoords.first);
int distanceY = abs(j - vertexCoords.second);
float distance = sqrt(pow(distanceX, 2) + pow(distanceY, 2));
float smoothedByDistance = 0.0f;
if (mShapeEditTool == ShapeEditTool_Drag)
smoothedByDistance = calculateBumpShape(distance, r, mTotalDiffY);
if (mShapeEditTool == ShapeEditTool_PaintToRaise || mShapeEditTool == ShapeEditTool_PaintToLower)
smoothedByDistance = calculateBumpShape(distance, r, r + mShapeEditToolStrength);
// Using floating-point radius here to prevent selecting too few vertices.
if (distance <= mBrushSize / 2.0f)
{
if (mShapeEditTool == ShapeEditTool_Drag)
alterHeight(cellCoords, x, y, smoothedByDistance);
if (mShapeEditTool == ShapeEditTool_PaintToRaise || mShapeEditTool == ShapeEditTool_PaintToLower)
{
alterHeight(cellCoords, x, y, smoothedByDistance);
float smoothMultiplier = static_cast<float>(
CSMPrefs::get()["3D Scene Editing"]["landedit-post-smoothstrength"].toDouble());
if (CSMPrefs::get()["3D Scene Editing"]["landedit-post-smoothpainting"].isTrue())
smoothHeight(cellCoords, x, y, mShapeEditToolStrength * smoothMultiplier);
}
if (mShapeEditTool == ShapeEditTool_Smooth)
smoothHeight(cellCoords, x, y, mShapeEditToolStrength);
if (mShapeEditTool == ShapeEditTool_Flatten)
flattenHeight(cellCoords, x, y, mShapeEditToolStrength, mTargetHeight);
if (mShapeEditTool == ShapeEditTool_Equalize)
equalizeHeight(cellCoords, x, y, mTargetHeight);
}
}
}
}
if (mBrushShape == CSVWidget::BrushShape_Custom)
{
if (!mCustomBrushShape.empty())
{
for (auto const& value : mCustomBrushShape)
{
std::string cellId = CSMWorld::CellCoordinates::vertexGlobalToCellId(
std::make_pair(vertexCoords.first + value.first, vertexCoords.second + value.second));
CSMWorld::CellCoordinates cellCoords = CSMWorld::CellCoordinates::fromId(cellId).first;
int x = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(vertexCoords.first + value.first);
int y = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(vertexCoords.second + value.second);
if (mShapeEditTool == ShapeEditTool_Drag)
alterHeight(cellCoords, x, y, mTotalDiffY);
if (mShapeEditTool == ShapeEditTool_PaintToRaise || mShapeEditTool == ShapeEditTool_PaintToLower)
{
alterHeight(cellCoords, x, y, mShapeEditToolStrength);
float smoothMultiplier = static_cast<float>(
CSMPrefs::get()["3D Scene Editing"]["landedit-post-smoothstrength"].toDouble());
if (CSMPrefs::get()["3D Scene Editing"]["landedit-post-smoothpainting"].isTrue())
smoothHeight(cellCoords, x, y, mShapeEditToolStrength * smoothMultiplier);
}
if (mShapeEditTool == ShapeEditTool_Smooth)
smoothHeight(cellCoords, x, y, mShapeEditToolStrength);
if (mShapeEditTool == ShapeEditTool_Flatten)
flattenHeight(cellCoords, x, y, mShapeEditToolStrength, mTargetHeight);
if (mShapeEditTool == ShapeEditTool_Equalize)
equalizeHeight(cellCoords, x, y, mTargetHeight);
}
}
}
mTerrainShapeSelection->update();
}
void CSVRender::TerrainShapeMode::setFlattenToolTargetHeight(const WorldspaceHitResult& hit)
{
std::pair<int, int> vertexCoords = CSMWorld::CellCoordinates::toVertexCoords(hit.worldPos);
std::string cellId = CSMWorld::CellCoordinates::vertexGlobalToCellId(vertexCoords);
int inCellX = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(vertexCoords.first);
int inCellY = CSMWorld::CellCoordinates::vertexGlobalToInCellCoords(vertexCoords.second);
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
mTargetHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX];
}
void CSVRender::TerrainShapeMode::alterHeight(
const CSMWorld::CellCoordinates& cellCoords, int inCellX, int inCellY, float alteredHeight, bool useTool)
{
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY());
if (!(allowLandShapeEditing(cellId, useTool) && (useTool || (isLandLoaded(cellId)))))
return;
CSVRender::PagedWorldspaceWidget* paged = dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget());
if (!paged)
return;
std::string cellLeftId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() - 1, cellCoords.getY());
std::string cellRightId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() + 1, cellCoords.getY());
std::string cellUpId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY() - 1);
std::string cellDownId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY() + 1);
std::string cellUpLeftId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() - 1, cellCoords.getY() - 1);
std::string cellUpRightId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() + 1, cellCoords.getY() - 1);
std::string cellDownLeftId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() - 1, cellCoords.getY() + 1);
std::string cellDownRightId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() + 1, cellCoords.getY() + 1);
if (useTool)
{
mAlteredCells.emplace_back(cellCoords);
if (mShapeEditTool == ShapeEditTool_Drag)
{
// Get distance from modified land, alter land change based on zoom
osg::Vec3d eye, center, up;
paged->getCamera()->getViewMatrixAsLookAt(eye, center, up);
osg::Vec3d distance = eye - mEditingPos;
alteredHeight = alteredHeight * (distance.length() / 500);
}
if (mShapeEditTool == ShapeEditTool_PaintToRaise)
alteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY) + alteredHeight;
if (mShapeEditTool == ShapeEditTool_PaintToLower)
alteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY) - alteredHeight;
if (mShapeEditTool == ShapeEditTool_Smooth)
alteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY) + alteredHeight;
}
if (inCellX != 0 && inCellY != 0 && inCellX != ESM::Land::LAND_SIZE - 1 && inCellY != ESM::Land::LAND_SIZE - 1)
paged->setCellAlteredHeight(cellCoords, inCellX, inCellY, alteredHeight);
// Change values of cornering cells
if ((inCellX == 0 && inCellY == 0) && (useTool || isLandLoaded(cellUpLeftId)))
{
if (allowLandShapeEditing(cellUpLeftId, useTool) && allowLandShapeEditing(cellLeftId, useTool)
&& allowLandShapeEditing(cellUpId, useTool))
{
CSMWorld::CellCoordinates cornerCellCoords = cellCoords.move(-1, -1);
if (useTool
&& std::find(mAlteredCells.begin(), mAlteredCells.end(), cornerCellCoords) == mAlteredCells.end())
mAlteredCells.emplace_back(cornerCellCoords);
paged->setCellAlteredHeight(
cornerCellCoords, ESM::Land::LAND_SIZE - 1, ESM::Land::LAND_SIZE - 1, alteredHeight);
}
else
return;
}
else if ((inCellX == 0 && inCellY == ESM::Land::LAND_SIZE - 1) && (useTool || isLandLoaded(cellDownLeftId)))
{
if (allowLandShapeEditing(cellDownLeftId, useTool) && allowLandShapeEditing(cellLeftId, useTool)
&& allowLandShapeEditing(cellDownId, useTool))
{
CSMWorld::CellCoordinates cornerCellCoords = cellCoords.move(-1, 1);
if (useTool
&& std::find(mAlteredCells.begin(), mAlteredCells.end(), cornerCellCoords) == mAlteredCells.end())
mAlteredCells.emplace_back(cornerCellCoords);
paged->setCellAlteredHeight(cornerCellCoords, ESM::Land::LAND_SIZE - 1, 0, alteredHeight);
}
else
return;
}
else if ((inCellX == ESM::Land::LAND_SIZE - 1 && inCellY == 0) && (useTool || isLandLoaded(cellUpRightId)))
{
if (allowLandShapeEditing(cellUpRightId, useTool) && allowLandShapeEditing(cellRightId, useTool)
&& allowLandShapeEditing(cellUpId, useTool))
{
CSMWorld::CellCoordinates cornerCellCoords = cellCoords.move(1, -1);
if (useTool
&& std::find(mAlteredCells.begin(), mAlteredCells.end(), cornerCellCoords) == mAlteredCells.end())
mAlteredCells.emplace_back(cornerCellCoords);
paged->setCellAlteredHeight(cornerCellCoords, 0, ESM::Land::LAND_SIZE - 1, alteredHeight);
}
else
return;
}
else if ((inCellX == ESM::Land::LAND_SIZE - 1 && inCellY == ESM::Land::LAND_SIZE - 1)
&& (useTool || isLandLoaded(cellDownRightId)))
{
if (allowLandShapeEditing(cellDownRightId, useTool) && allowLandShapeEditing(cellRightId, useTool)
&& allowLandShapeEditing(cellDownId, useTool))
{
CSMWorld::CellCoordinates cornerCellCoords = cellCoords.move(1, 1);
if (useTool
&& std::find(mAlteredCells.begin(), mAlteredCells.end(), cornerCellCoords) == mAlteredCells.end())
mAlteredCells.emplace_back(cornerCellCoords);
paged->setCellAlteredHeight(cornerCellCoords, 0, 0, alteredHeight);
}
else
return;
}
// Change values of edging cells
if ((inCellX == 0) && (useTool || isLandLoaded(cellLeftId)))
{
if (allowLandShapeEditing(cellLeftId, useTool))
{
CSMWorld::CellCoordinates edgeCellCoords = cellCoords.move(-1, 0);
if (useTool && std::find(mAlteredCells.begin(), mAlteredCells.end(), edgeCellCoords) == mAlteredCells.end())
mAlteredCells.emplace_back(edgeCellCoords);
paged->setCellAlteredHeight(cellCoords, inCellX, inCellY, alteredHeight);
paged->setCellAlteredHeight(edgeCellCoords, ESM::Land::LAND_SIZE - 1, inCellY, alteredHeight);
}
}
if ((inCellY == 0) && (useTool || isLandLoaded(cellUpId)))
{
if (allowLandShapeEditing(cellUpId, useTool))
{
CSMWorld::CellCoordinates edgeCellCoords = cellCoords.move(0, -1);
if (useTool && std::find(mAlteredCells.begin(), mAlteredCells.end(), edgeCellCoords) == mAlteredCells.end())
mAlteredCells.emplace_back(edgeCellCoords);
paged->setCellAlteredHeight(cellCoords, inCellX, inCellY, alteredHeight);
paged->setCellAlteredHeight(edgeCellCoords, inCellX, ESM::Land::LAND_SIZE - 1, alteredHeight);
}
}
if ((inCellX == ESM::Land::LAND_SIZE - 1) && (useTool || isLandLoaded(cellRightId)))
{
if (allowLandShapeEditing(cellRightId, useTool))
{
CSMWorld::CellCoordinates edgeCellCoords = cellCoords.move(1, 0);
if (useTool && std::find(mAlteredCells.begin(), mAlteredCells.end(), edgeCellCoords) == mAlteredCells.end())
mAlteredCells.emplace_back(edgeCellCoords);
paged->setCellAlteredHeight(cellCoords, inCellX, inCellY, alteredHeight);
paged->setCellAlteredHeight(edgeCellCoords, 0, inCellY, alteredHeight);
}
}
if ((inCellY == ESM::Land::LAND_SIZE - 1) && (useTool || isLandLoaded(cellDownId)))
{
if (allowLandShapeEditing(cellDownId, useTool))
{
CSMWorld::CellCoordinates edgeCellCoords = cellCoords.move(0, 1);
if (useTool && std::find(mAlteredCells.begin(), mAlteredCells.end(), edgeCellCoords) == mAlteredCells.end())
mAlteredCells.emplace_back(edgeCellCoords);
paged->setCellAlteredHeight(cellCoords, inCellX, inCellY, alteredHeight);
paged->setCellAlteredHeight(edgeCellCoords, inCellX, 0, alteredHeight);
}
}
}
void CSVRender::TerrainShapeMode::smoothHeight(
const CSMWorld::CellCoordinates& cellCoords, int inCellX, int inCellY, int toolStrength)
{
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY());
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
// ### Variable naming key ###
// Variables here hold either the real value, or the altered value of current edit.
// this = this Cell
// left = x - 1, up = y - 1, right = x + 1, down = y + 1
// Altered = transient edit (in current edited)
float thisAlteredHeight = 0.0f;
if (paged->getCellAlteredHeight(cellCoords, inCellX, inCellY) != nullptr)
thisAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY);
float thisHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX];
float leftHeight = 0.0f;
float leftAlteredHeight = 0.0f;
float upAlteredHeight = 0.0f;
float rightHeight = 0.0f;
float rightAlteredHeight = 0.0f;
float downHeight = 0.0f;
float downAlteredHeight = 0.0f;
float upHeight = 0.0f;
if (allowLandShapeEditing(cellId))
{
// Get key values for calculating average, handle cell edges, check for null pointers
if (inCellX == 0)
{
cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() - 1, cellCoords.getY());
const CSMWorld::LandHeightsColumn::DataType landLeftShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
leftHeight = landLeftShapePointer[inCellY * ESM::Land::LAND_SIZE + (ESM::Land::LAND_SIZE - 2)];
if (paged->getCellAlteredHeight(cellCoords.move(-1, 0), inCellX, ESM::Land::LAND_SIZE - 2))
leftAlteredHeight
= *paged->getCellAlteredHeight(cellCoords.move(-1, 0), ESM::Land::LAND_SIZE - 2, inCellY);
}
if (inCellY == 0)
{
cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY() - 1);
const CSMWorld::LandHeightsColumn::DataType landUpShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
upHeight = landUpShapePointer[(ESM::Land::LAND_SIZE - 2) * ESM::Land::LAND_SIZE + inCellX];
if (paged->getCellAlteredHeight(cellCoords.move(0, -1), inCellX, ESM::Land::LAND_SIZE - 2))
upAlteredHeight
= *paged->getCellAlteredHeight(cellCoords.move(0, -1), inCellX, ESM::Land::LAND_SIZE - 2);
}
if (inCellX > 0)
{
leftHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX - 1];
leftAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX - 1, inCellY);
}
if (inCellY > 0)
{
upHeight = landShapePointer[(inCellY - 1) * ESM::Land::LAND_SIZE + inCellX];
upAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY - 1);
}
if (inCellX == ESM::Land::LAND_SIZE - 1)
{
cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() + 1, cellCoords.getY());
const CSMWorld::LandHeightsColumn::DataType landRightShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
rightHeight = landRightShapePointer[inCellY * ESM::Land::LAND_SIZE + 1];
if (paged->getCellAlteredHeight(cellCoords.move(1, 0), 1, inCellY))
{
rightAlteredHeight = *paged->getCellAlteredHeight(cellCoords.move(1, 0), 1, inCellY);
}
}
if (inCellY == ESM::Land::LAND_SIZE - 1)
{
cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY() + 1);
const CSMWorld::LandHeightsColumn::DataType landDownShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
downHeight = landDownShapePointer[1 * ESM::Land::LAND_SIZE + inCellX];
if (paged->getCellAlteredHeight(cellCoords.move(0, 1), inCellX, 1))
{
downAlteredHeight = *paged->getCellAlteredHeight(cellCoords.move(0, 1), inCellX, 1);
}
}
if (inCellX < ESM::Land::LAND_SIZE - 1)
{
rightHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX + 1];
if (paged->getCellAlteredHeight(cellCoords, inCellX + 1, inCellY))
rightAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX + 1, inCellY);
}
if (inCellY < ESM::Land::LAND_SIZE - 1)
{
downHeight = landShapePointer[(inCellY + 1) * ESM::Land::LAND_SIZE + inCellX];
if (paged->getCellAlteredHeight(cellCoords, inCellX, inCellY + 1))
downAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY + 1);
}
float averageHeight = (upHeight + downHeight + rightHeight + leftHeight + upAlteredHeight
+ downAlteredHeight + rightAlteredHeight + leftAlteredHeight)
/ 4;
if ((thisHeight + thisAlteredHeight) != averageHeight)
mAlteredCells.emplace_back(cellCoords);
if (toolStrength > abs(thisHeight + thisAlteredHeight - averageHeight))
toolStrength = abs(thisHeight + thisAlteredHeight - averageHeight);
if (thisHeight + thisAlteredHeight > averageHeight)
alterHeight(cellCoords, inCellX, inCellY, -toolStrength);
if (thisHeight + thisAlteredHeight < averageHeight)
alterHeight(cellCoords, inCellX, inCellY, +toolStrength);
}
}
}
void CSVRender::TerrainShapeMode::flattenHeight(
const CSMWorld::CellCoordinates& cellCoords, int inCellX, int inCellY, int toolStrength, int targetHeight)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
float thisHeight = 0.0f;
float thisAlteredHeight = 0.0f;
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY());
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
if (!noCell(cellId) && !noLand(cellId))
{
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
if (paged->getCellAlteredHeight(cellCoords, inCellX, inCellY))
thisAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY);
thisHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX];
}
}
if (toolStrength > abs(thisHeight - targetHeight) && toolStrength > 8.0f)
toolStrength = abs(thisHeight - targetHeight); // Cut down excessive changes
if (thisHeight + thisAlteredHeight > targetHeight)
alterHeight(cellCoords, inCellX, inCellY, thisAlteredHeight - toolStrength);
if (thisHeight + thisAlteredHeight < targetHeight)
alterHeight(cellCoords, inCellX, inCellY, thisAlteredHeight + toolStrength);
}
void CSVRender::TerrainShapeMode::equalizeHeight(
const CSMWorld::CellCoordinates& cellCoords, int inCellX, int inCellY, int targetHeight)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
float thisHeight = 0.0f;
const std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY());
if (!noCell(cellId) && !noLand(cellId))
{
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
thisHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX];
}
alterHeight(cellCoords, inCellX, inCellY, targetHeight - thisHeight);
}
void CSVRender::TerrainShapeMode::updateKeyHeightValues(const CSMWorld::CellCoordinates& cellCoords, int inCellX,
int inCellY, float* thisHeight, float* thisAlteredHeight, float* leftHeight, float* leftAlteredHeight,
float* upHeight, float* upAlteredHeight, float* rightHeight, float* rightAlteredHeight, float* downHeight,
float* downAlteredHeight)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY());
std::string cellLeftId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() - 1, cellCoords.getY());
std::string cellUpId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY() - 1);
std::string cellRightId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() + 1, cellCoords.getY());
std::string cellDownId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY() + 1);
*thisHeight = 0.0f; // real + altered height
*thisAlteredHeight = 0.0f; // only altered height
*leftHeight = 0.0f;
*leftAlteredHeight = 0.0f;
*upHeight = 0.0f;
*upAlteredHeight = 0.0f;
*rightHeight = 0.0f;
*rightAlteredHeight = 0.0f;
*downHeight = 0.0f;
*downAlteredHeight = 0.0f;
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
if (!noCell(cellId) && !noLand(cellId))
{
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
if (paged->getCellAlteredHeight(cellCoords, inCellX, inCellY))
*thisAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY);
*thisHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX] + *thisAlteredHeight;
// Default to the same value as thisHeight, which happens in the case of cell edge where next cell/land is
// not found, which is to prevent unnecessary action at limitHeightChange().
*leftHeight = *thisHeight;
*upHeight = *thisHeight;
*rightHeight = *thisHeight;
*downHeight = *thisHeight;
// If at edge, get values from neighboring cell
if (inCellX == 0)
{
if (isLandLoaded(cellLeftId))
{
const CSMWorld::LandHeightsColumn::DataType landLeftShapePointer
= landTable.data(landTable.getModelIndex(cellLeftId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
*leftHeight = landLeftShapePointer[inCellY * ESM::Land::LAND_SIZE + (ESM::Land::LAND_SIZE - 2)];
if (paged->getCellAlteredHeight(cellCoords.move(-1, 0), ESM::Land::LAND_SIZE - 2, inCellY))
{
*leftAlteredHeight
= *paged->getCellAlteredHeight(cellCoords.move(-1, 0), ESM::Land::LAND_SIZE - 2, inCellY);
*leftHeight += *leftAlteredHeight;
}
}
}
if (inCellY == 0)
{
if (isLandLoaded(cellUpId))
{
const CSMWorld::LandHeightsColumn::DataType landUpShapePointer
= landTable.data(landTable.getModelIndex(cellUpId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
*upHeight = landUpShapePointer[(ESM::Land::LAND_SIZE - 2) * ESM::Land::LAND_SIZE + inCellX];
if (paged->getCellAlteredHeight(cellCoords.move(0, -1), inCellX, ESM::Land::LAND_SIZE - 2))
{
*upAlteredHeight
= *paged->getCellAlteredHeight(cellCoords.move(0, -1), inCellX, ESM::Land::LAND_SIZE - 2);
*upHeight += *upAlteredHeight;
}
}
}
if (inCellX == ESM::Land::LAND_SIZE - 1)
{
if (isLandLoaded(cellRightId))
{
const CSMWorld::LandHeightsColumn::DataType landRightShapePointer
= landTable.data(landTable.getModelIndex(cellRightId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
*rightHeight = landRightShapePointer[inCellY * ESM::Land::LAND_SIZE + 1];
if (paged->getCellAlteredHeight(cellCoords.move(1, 0), 1, inCellY))
{
*rightAlteredHeight = *paged->getCellAlteredHeight(cellCoords.move(1, 0), 1, inCellY);
*rightHeight += *rightAlteredHeight;
}
}
}
if (inCellY == ESM::Land::LAND_SIZE - 1)
{
if (isLandLoaded(cellDownId))
{
const CSMWorld::LandHeightsColumn::DataType landDownShapePointer
= landTable.data(landTable.getModelIndex(cellDownId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
*downHeight = landDownShapePointer[ESM::Land::LAND_SIZE + inCellX];
if (paged->getCellAlteredHeight(cellCoords.move(0, 1), inCellX, 1))
{
*downAlteredHeight = *paged->getCellAlteredHeight(cellCoords.move(0, 1), inCellX, 1);
*downHeight += *downAlteredHeight;
}
}
}
// If not at edge, get values from the same cell
if (inCellX != 0)
{
*leftHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX - 1];
if (paged->getCellAlteredHeight(cellCoords, inCellX - 1, inCellY))
*leftAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX - 1, inCellY);
*leftHeight += *leftAlteredHeight;
}
if (inCellY != 0)
{
*upHeight = landShapePointer[(inCellY - 1) * ESM::Land::LAND_SIZE + inCellX];
if (paged->getCellAlteredHeight(cellCoords, inCellX, inCellY - 1))
*upAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY - 1);
*upHeight += *upAlteredHeight;
}
if (inCellX != ESM::Land::LAND_SIZE - 1)
{
*rightHeight = landShapePointer[inCellY * ESM::Land::LAND_SIZE + inCellX + 1];
if (paged->getCellAlteredHeight(cellCoords, inCellX + 1, inCellY))
*rightAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX + 1, inCellY);
*rightHeight += *rightAlteredHeight;
}
if (inCellY != ESM::Land::LAND_SIZE - 1)
{
*downHeight = landShapePointer[(inCellY + 1) * ESM::Land::LAND_SIZE + inCellX];
if (paged->getCellAlteredHeight(cellCoords, inCellX, inCellY + 1))
*downAlteredHeight = *paged->getCellAlteredHeight(cellCoords, inCellX, inCellY + 1);
*downHeight += *downAlteredHeight;
}
}
}
}
void CSVRender::TerrainShapeMode::compareAndLimit(const CSMWorld::CellCoordinates& cellCoords, int inCellX, int inCellY,
float* limitedAlteredHeightXAxis, float* limitedAlteredHeightYAxis, bool* steepnessIsWithinLimits)
{
if (limitedAlteredHeightXAxis)
{
if (limitedAlteredHeightYAxis)
{
if (std::abs(*limitedAlteredHeightXAxis) >= std::abs(*limitedAlteredHeightYAxis))
{
alterHeight(cellCoords, inCellX, inCellY, *limitedAlteredHeightXAxis, false);
*steepnessIsWithinLimits = false;
}
else
{
alterHeight(cellCoords, inCellX, inCellY, *limitedAlteredHeightYAxis, false);
*steepnessIsWithinLimits = false;
}
}
else
{
alterHeight(cellCoords, inCellX, inCellY, *limitedAlteredHeightXAxis, false);
*steepnessIsWithinLimits = false;
}
}
else if (limitedAlteredHeightYAxis)
{
alterHeight(cellCoords, inCellX, inCellY, *limitedAlteredHeightYAxis, false);
*steepnessIsWithinLimits = false;
}
}
bool CSVRender::TerrainShapeMode::limitAlteredHeights(const CSMWorld::CellCoordinates& cellCoords, bool reverseMode)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY());
int limitHeightChange = 1016.0f; // Limited by save format
bool steepnessIsWithinLimits = true;
if (isLandLoaded(cellId))
{
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
float thisHeight = 0.0f;
float thisAlteredHeight = 0.0f;
float leftHeight = 0.0f;
float leftAlteredHeight = 0.0f;
float upHeight = 0.0f;
float upAlteredHeight = 0.0f;
float rightHeight = 0.0f;
float rightAlteredHeight = 0.0f;
float downHeight = 0.0f;
float downAlteredHeight = 0.0f;
if (!reverseMode)
{
for (int inCellY = 0; inCellY < ESM::Land::LAND_SIZE; ++inCellY)
{
for (int inCellX = 0; inCellX < ESM::Land::LAND_SIZE; ++inCellX)
{
std::unique_ptr<float> limitedAlteredHeightXAxis(nullptr);
std::unique_ptr<float> limitedAlteredHeightYAxis(nullptr);
updateKeyHeightValues(cellCoords, inCellX, inCellY, &thisHeight, &thisAlteredHeight, &leftHeight,
&leftAlteredHeight, &upHeight, &upAlteredHeight, &rightHeight, &rightAlteredHeight, &downHeight,
&downAlteredHeight);
// Check for height limits on x-axis
if (leftHeight - thisHeight > limitHeightChange)
limitedAlteredHeightXAxis = std::make_unique<float>(
leftHeight - limitHeightChange - (thisHeight - thisAlteredHeight));
else if (leftHeight - thisHeight < -limitHeightChange)
limitedAlteredHeightXAxis = std::make_unique<float>(
leftHeight + limitHeightChange - (thisHeight - thisAlteredHeight));
// Check for height limits on y-axis
if (upHeight - thisHeight > limitHeightChange)
limitedAlteredHeightYAxis
= std::make_unique<float>(upHeight - limitHeightChange - (thisHeight - thisAlteredHeight));
else if (upHeight - thisHeight < -limitHeightChange)
limitedAlteredHeightYAxis
= std::make_unique<float>(upHeight + limitHeightChange - (thisHeight - thisAlteredHeight));
// Limit altered height value based on x or y, whichever is the smallest
compareAndLimit(cellCoords, inCellX, inCellY, limitedAlteredHeightXAxis.get(),
limitedAlteredHeightYAxis.get(), &steepnessIsWithinLimits);
}
}
}
if (reverseMode)
{
for (int inCellY = ESM::Land::LAND_SIZE - 1; inCellY >= 0; --inCellY)
{
for (int inCellX = ESM::Land::LAND_SIZE - 1; inCellX >= 0; --inCellX)
{
std::unique_ptr<float> limitedAlteredHeightXAxis(nullptr);
std::unique_ptr<float> limitedAlteredHeightYAxis(nullptr);
updateKeyHeightValues(cellCoords, inCellX, inCellY, &thisHeight, &thisAlteredHeight, &leftHeight,
&leftAlteredHeight, &upHeight, &upAlteredHeight, &rightHeight, &rightAlteredHeight, &downHeight,
&downAlteredHeight);
// Check for height limits on x-axis
if (rightHeight - thisHeight > limitHeightChange)
limitedAlteredHeightXAxis = std::make_unique<float>(
rightHeight - limitHeightChange - (thisHeight - thisAlteredHeight));
else if (rightHeight - thisHeight < -limitHeightChange)
limitedAlteredHeightXAxis = std::make_unique<float>(
rightHeight + limitHeightChange - (thisHeight - thisAlteredHeight));
// Check for height limits on y-axis
if (downHeight - thisHeight > limitHeightChange)
limitedAlteredHeightYAxis = std::make_unique<float>(
downHeight - limitHeightChange - (thisHeight - thisAlteredHeight));
else if (downHeight - thisHeight < -limitHeightChange)
limitedAlteredHeightYAxis = std::make_unique<float>(
downHeight + limitHeightChange - (thisHeight - thisAlteredHeight));
// Limit altered height value based on x or y, whichever is the smallest
compareAndLimit(cellCoords, inCellX, inCellY, limitedAlteredHeightXAxis.get(),
limitedAlteredHeightYAxis.get(), &steepnessIsWithinLimits);
}
}
}
}
return steepnessIsWithinLimits;
}
bool CSVRender::TerrainShapeMode::isInCellSelection(int globalSelectionX, int globalSelectionY)
{
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
std::pair<int, int> vertexCoords = std::make_pair(globalSelectionX, globalSelectionY);
std::string cellId = CSMWorld::CellCoordinates::vertexGlobalToCellId(vertexCoords);
return paged->getCellSelection().has(CSMWorld::CellCoordinates::fromId(cellId).first) && isLandLoaded(cellId);
}
return false;
}
void CSVRender::TerrainShapeMode::handleSelection(
int globalSelectionX, int globalSelectionY, std::vector<std::pair<int, int>>* selections)
{
if (isInCellSelection(globalSelectionX, globalSelectionY))
selections->emplace_back(globalSelectionX, globalSelectionY);
else
{
int moduloX = globalSelectionX % (ESM::Land::LAND_SIZE - 1);
int moduloY = globalSelectionY % (ESM::Land::LAND_SIZE - 1);
bool xIsAtCellBorder = moduloX == 0;
bool yIsAtCellBorder = moduloY == 0;
if (!xIsAtCellBorder && !yIsAtCellBorder)
return;
int selectionX = globalSelectionX;
int selectionY = globalSelectionY;
/*
The northern and eastern edges don't belong to the current cell.
If the corresponding adjacent cell is not loaded, some special handling is necessary to select border
vertices.
*/
if (xIsAtCellBorder && yIsAtCellBorder)
{
/*
Handle the NW, NE, and SE corner vertices.
NW corner: (+1, -1) offset to reach current cell.
NE corner: (-1, -1) offset to reach current cell.
SE corner: (-1, +1) offset to reach current cell.
*/
if (isInCellSelection(globalSelectionX - 1, globalSelectionY - 1)
|| isInCellSelection(globalSelectionX + 1, globalSelectionY - 1)
|| isInCellSelection(globalSelectionX - 1, globalSelectionY + 1))
{
selections->emplace_back(globalSelectionX, globalSelectionY);
}
}
else if (xIsAtCellBorder)
{
selectionX--;
}
else if (yIsAtCellBorder)
{
selectionY--;
}
if (isInCellSelection(selectionX, selectionY))
selections->emplace_back(globalSelectionX, globalSelectionY);
}
}
void CSVRender::TerrainShapeMode::selectTerrainShapes(const std::pair<int, int>& vertexCoords, unsigned char selectMode)
{
int r = mBrushSize / 2;
std::vector<std::pair<int, int>> selections;
if (mBrushShape == CSVWidget::BrushShape_Point)
{
handleSelection(vertexCoords.first, vertexCoords.second, &selections);
}
if (mBrushShape == CSVWidget::BrushShape_Square)
{
for (int i = vertexCoords.first - r; i <= vertexCoords.first + r; ++i)
{
for (int j = vertexCoords.second - r; j <= vertexCoords.second + r; ++j)
{
handleSelection(i, j, &selections);
}
}
}
if (mBrushShape == CSVWidget::BrushShape_Circle)
{
for (int i = vertexCoords.first - r; i <= vertexCoords.first + r; ++i)
{
for (int j = vertexCoords.second - r; j <= vertexCoords.second + r; ++j)
{
int distanceX = abs(i - vertexCoords.first);
int distanceY = abs(j - vertexCoords.second);
float distance = sqrt(pow(distanceX, 2) + pow(distanceY, 2));
// Using floating-point radius here to prevent selecting too few vertices.
if (distance <= mBrushSize / 2.0f)
handleSelection(i, j, &selections);
}
}
}
if (mBrushShape == CSVWidget::BrushShape_Custom)
{
if (!mCustomBrushShape.empty())
{
for (auto const& value : mCustomBrushShape)
{
std::pair<int, int> localVertexCoords(
vertexCoords.first + value.first, vertexCoords.second + value.second);
handleSelection(localVertexCoords.first, localVertexCoords.second, &selections);
}
}
}
std::string selectAction;
if (selectMode == 0)
selectAction = CSMPrefs::get()["3D Scene Editing"]["primary-select-action"].toString();
else
selectAction = CSMPrefs::get()["3D Scene Editing"]["secondary-select-action"].toString();
if (selectAction == "Select only")
mTerrainShapeSelection->onlySelect(selections);
else if (selectAction == "Add to selection")
mTerrainShapeSelection->addSelect(selections);
else if (selectAction == "Remove from selection")
mTerrainShapeSelection->removeSelect(selections);
else if (selectAction == "Invert selection")
mTerrainShapeSelection->toggleSelect(selections);
}
void CSVRender::TerrainShapeMode::pushEditToCommand(const CSMWorld::LandHeightsColumn::DataType& newLandGrid,
CSMDoc::Document& document, CSMWorld::IdTable& landTable, const std::string& cellId)
{
QVariant changedLand;
changedLand.setValue(newLandGrid);
QModelIndex index(
landTable.getModelIndex(cellId, landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex)));
QUndoStack& undoStack = document.getUndoStack();
undoStack.push(new CSMWorld::ModifyCommand(landTable, index, changedLand));
}
void CSVRender::TerrainShapeMode::pushNormalsEditToCommand(const CSMWorld::LandNormalsColumn::DataType& newLandGrid,
CSMDoc::Document& document, CSMWorld::IdTable& landTable, const std::string& cellId)
{
QVariant changedLand;
changedLand.setValue(newLandGrid);
QModelIndex index(
landTable.getModelIndex(cellId, landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandNormalsIndex)));
QUndoStack& undoStack = document.getUndoStack();
undoStack.push(new CSMWorld::ModifyCommand(landTable, index, changedLand));
}
bool CSVRender::TerrainShapeMode::noCell(const std::string& cellId)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
const CSMWorld::IdCollection<CSMWorld::Cell>& cellCollection = document.getData().getCells();
return cellCollection.searchId(ESM::RefId::stringRefId(cellId)) == -1;
}
bool CSVRender::TerrainShapeMode::noLand(const std::string& cellId)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
const CSMWorld::IdCollection<CSMWorld::Land>& landCollection = document.getData().getLand();
return landCollection.searchId(ESM::RefId::stringRefId(cellId)) == -1;
}
bool CSVRender::TerrainShapeMode::noLandLoaded(const std::string& cellId)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
const CSMWorld::IdCollection<CSMWorld::Land>& landCollection = document.getData().getLand();
return !landCollection.getRecord(ESM::RefId::stringRefId(cellId)).get().isDataLoaded(ESM::Land::DATA_VNML);
}
bool CSVRender::TerrainShapeMode::isLandLoaded(const std::string& cellId)
{
if (!noCell(cellId) && !noLand(cellId) && !noLandLoaded(cellId))
return true;
return false;
}
void CSVRender::TerrainShapeMode::createNewLandData(const CSMWorld::CellCoordinates& cellCoords)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
CSMWorld::IdTable& ltexTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
int landnormalsColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandNormalsIndex);
float defaultHeight = 0.f;
int averageDivider = 0;
CSMWorld::CellCoordinates cellLeftCoords = cellCoords.move(-1, 0);
CSMWorld::CellCoordinates cellRightCoords = cellCoords.move(1, 0);
CSMWorld::CellCoordinates cellUpCoords = cellCoords.move(0, -1);
CSMWorld::CellCoordinates cellDownCoords = cellCoords.move(0, 1);
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY());
std::string cellLeftId = CSMWorld::CellCoordinates::generateId(cellLeftCoords.getX(), cellLeftCoords.getY());
std::string cellRightId = CSMWorld::CellCoordinates::generateId(cellRightCoords.getX(), cellRightCoords.getY());
std::string cellUpId = CSMWorld::CellCoordinates::generateId(cellUpCoords.getX(), cellUpCoords.getY());
std::string cellDownId = CSMWorld::CellCoordinates::generateId(cellDownCoords.getX(), cellDownCoords.getY());
float leftCellSampleHeight = 0.0f;
float rightCellSampleHeight = 0.0f;
float upCellSampleHeight = 0.0f;
float downCellSampleHeight = 0.0f;
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
const CSMWorld::LandNormalsColumn::DataType landNormalsPointer
= landTable.data(landTable.getModelIndex(cellId, landnormalsColumn))
.value<CSMWorld::LandNormalsColumn::DataType>();
CSMWorld::LandHeightsColumn::DataType landShapeNew(landShapePointer);
CSMWorld::LandNormalsColumn::DataType landNormalsNew(landNormalsPointer);
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
if (isLandLoaded(cellLeftId))
{
const CSMWorld::LandHeightsColumn::DataType landLeftShapePointer
= landTable.data(landTable.getModelIndex(cellLeftId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
++averageDivider;
leftCellSampleHeight
= landLeftShapePointer[(ESM::Land::LAND_SIZE / 2) * ESM::Land::LAND_SIZE + ESM::Land::LAND_SIZE - 1];
if (paged->getCellAlteredHeight(cellLeftCoords, ESM::Land::LAND_SIZE - 1, ESM::Land::LAND_SIZE / 2))
leftCellSampleHeight
+= *paged->getCellAlteredHeight(cellLeftCoords, ESM::Land::LAND_SIZE - 1, ESM::Land::LAND_SIZE / 2);
}
if (isLandLoaded(cellRightId))
{
const CSMWorld::LandHeightsColumn::DataType landRightShapePointer
= landTable.data(landTable.getModelIndex(cellRightId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
++averageDivider;
rightCellSampleHeight = landRightShapePointer[(ESM::Land::LAND_SIZE / 2) * ESM::Land::LAND_SIZE];
if (paged->getCellAlteredHeight(cellRightCoords, 0, ESM::Land::LAND_SIZE / 2))
rightCellSampleHeight += *paged->getCellAlteredHeight(cellRightCoords, 0, ESM::Land::LAND_SIZE / 2);
}
if (isLandLoaded(cellUpId))
{
const CSMWorld::LandHeightsColumn::DataType landUpShapePointer
= landTable.data(landTable.getModelIndex(cellUpId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
++averageDivider;
upCellSampleHeight
= landUpShapePointer[(ESM::Land::LAND_SIZE - 1) * ESM::Land::LAND_SIZE + (ESM::Land::LAND_SIZE / 2)];
if (paged->getCellAlteredHeight(cellUpCoords, ESM::Land::LAND_SIZE / 2, ESM::Land::LAND_SIZE - 1))
upCellSampleHeight
+= *paged->getCellAlteredHeight(cellUpCoords, ESM::Land::LAND_SIZE / 2, ESM::Land::LAND_SIZE - 1);
}
if (isLandLoaded(cellDownId))
{
const CSMWorld::LandHeightsColumn::DataType landDownShapePointer
= landTable.data(landTable.getModelIndex(cellDownId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
++averageDivider;
downCellSampleHeight = landDownShapePointer[ESM::Land::LAND_SIZE / 2];
if (paged->getCellAlteredHeight(cellDownCoords, ESM::Land::LAND_SIZE / 2, 0))
downCellSampleHeight += *paged->getCellAlteredHeight(cellDownCoords, ESM::Land::LAND_SIZE / 2, 0);
}
}
if (averageDivider > 0)
defaultHeight = (leftCellSampleHeight + rightCellSampleHeight + upCellSampleHeight + downCellSampleHeight)
/ averageDivider;
for (int i = 0; i < ESM::Land::LAND_SIZE; ++i)
{
for (int j = 0; j < ESM::Land::LAND_SIZE; ++j)
{
landShapeNew[j * ESM::Land::LAND_SIZE + i] = defaultHeight;
landNormalsNew[(j * ESM::Land::LAND_SIZE + i) * 3 + 0] = 0;
landNormalsNew[(j * ESM::Land::LAND_SIZE + i) * 3 + 1] = 0;
landNormalsNew[(j * ESM::Land::LAND_SIZE + i) * 3 + 2] = 127;
}
}
QVariant changedShape;
changedShape.setValue(landShapeNew);
QVariant changedNormals;
changedNormals.setValue(landNormalsNew);
QModelIndex indexShape(
landTable.getModelIndex(cellId, landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex)));
QModelIndex indexNormal(
landTable.getModelIndex(cellId, landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandNormalsIndex)));
document.getUndoStack().push(new CSMWorld::TouchLandCommand(landTable, ltexTable, cellId));
document.getUndoStack().push(new CSMWorld::ModifyCommand(landTable, indexShape, changedShape));
document.getUndoStack().push(new CSMWorld::ModifyCommand(landTable, indexNormal, changedNormals));
}
bool CSVRender::TerrainShapeMode::allowLandShapeEditing(const std::string& cellId, bool useTool)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
CSMWorld::IdTree& cellTable
= dynamic_cast<CSMWorld::IdTree&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Cells));
if (noCell(cellId))
{
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-landedit"].toString();
// target cell does not exist
if (mode == "Discard")
return false;
if (mode == "Create cell and land, then edit" && useTool)
{
auto createCommand = std::make_unique<CSMWorld::CreateCommand>(cellTable, cellId);
int parentIndex = cellTable.findColumnIndex(CSMWorld::Columns::ColumnId_Cell);
int index = cellTable.findNestedColumnIndex(parentIndex, CSMWorld::Columns::ColumnId_Interior);
createCommand->addNestedValue(parentIndex, index, false);
document.getUndoStack().push(createCommand.release());
if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
CSMWorld::CellSelection selection = paged->getCellSelection();
selection.add(CSMWorld::CellCoordinates::fromId(cellId).first);
paged->setCellSelection(selection);
}
}
}
else if (CSVRender::PagedWorldspaceWidget* paged
= dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
{
CSMWorld::CellSelection selection = paged->getCellSelection();
if (!selection.has(CSMWorld::CellCoordinates::fromId(cellId).first))
{
// target cell exists, but is not shown
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-visible-landedit"].toString();
if (mode == "Discard")
return false;
if (mode == "Show cell and edit" && useTool)
{
selection.add(CSMWorld::CellCoordinates::fromId(cellId).first);
paged->setCellSelection(selection);
}
}
}
if (noLand(cellId))
{
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-landedit"].toString();
// target cell does not exist
if (mode == "Discard")
return false;
if (mode == "Create cell and land, then edit" && useTool)
{
document.getUndoStack().push(new CSMWorld::CreateCommand(landTable, cellId));
createNewLandData(CSMWorld::CellCoordinates::fromId(cellId).first);
fixEdges(CSMWorld::CellCoordinates::fromId(cellId).first);
sortAndLimitAlteredCells();
}
}
else if (noLandLoaded(cellId))
{
std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-landedit"].toString();
if (mode == "Discard")
return false;
if (mode == "Create cell and land, then edit" && useTool)
{
createNewLandData(CSMWorld::CellCoordinates::fromId(cellId).first);
fixEdges(CSMWorld::CellCoordinates::fromId(cellId).first);
sortAndLimitAlteredCells();
}
}
if (useTool && (noCell(cellId) || noLand(cellId) || noLandLoaded(cellId)))
{
Log(Debug::Warning) << "Land creation failed at cell id: " << cellId;
return false;
}
return true;
}
void CSVRender::TerrainShapeMode::fixEdges(CSMWorld::CellCoordinates cellCoords)
{
CSMDoc::Document& document = getWorldspaceWidget().getDocument();
CSMWorld::IdTable& landTable
= dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
int landshapeColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex);
std::string cellId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY());
std::string cellLeftId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() - 1, cellCoords.getY());
std::string cellRightId = CSMWorld::CellCoordinates::generateId(cellCoords.getX() + 1, cellCoords.getY());
std::string cellUpId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY() - 1);
std::string cellDownId = CSMWorld::CellCoordinates::generateId(cellCoords.getX(), cellCoords.getY() + 1);
const CSMWorld::LandHeightsColumn::DataType landShapePointer
= landTable.data(landTable.getModelIndex(cellId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
const CSMWorld::LandHeightsColumn::DataType landLeftShapePointer
= landTable.data(landTable.getModelIndex(cellLeftId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
const CSMWorld::LandHeightsColumn::DataType landRightShapePointer
= landTable.data(landTable.getModelIndex(cellRightId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
const CSMWorld::LandHeightsColumn::DataType landUpShapePointer
= landTable.data(landTable.getModelIndex(cellUpId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
const CSMWorld::LandHeightsColumn::DataType landDownShapePointer
= landTable.data(landTable.getModelIndex(cellDownId, landshapeColumn))
.value<CSMWorld::LandHeightsColumn::DataType>();
CSMWorld::LandHeightsColumn::DataType landShapeNew(landShapePointer);
for (int i = 0; i < ESM::Land::LAND_SIZE; ++i)
{
if (isLandLoaded(cellLeftId)
&& landShapePointer[i * ESM::Land::LAND_SIZE]
!= landLeftShapePointer[i * ESM::Land::LAND_SIZE + ESM::Land::LAND_SIZE - 1])
landShapeNew[i * ESM::Land::LAND_SIZE]
= landLeftShapePointer[i * ESM::Land::LAND_SIZE + ESM::Land::LAND_SIZE - 1];
if (isLandLoaded(cellRightId)
&& landShapePointer[i * ESM::Land::LAND_SIZE + ESM::Land::LAND_SIZE - 1]
!= landRightShapePointer[i * ESM::Land::LAND_SIZE])
landShapeNew[i * ESM::Land::LAND_SIZE + ESM::Land::LAND_SIZE - 1]
= landRightShapePointer[i * ESM::Land::LAND_SIZE];
if (isLandLoaded(cellUpId)
&& landShapePointer[i] != landUpShapePointer[(ESM::Land::LAND_SIZE - 1) * ESM::Land::LAND_SIZE + i])
landShapeNew[i] = landUpShapePointer[(ESM::Land::LAND_SIZE - 1) * ESM::Land::LAND_SIZE + i];
if (isLandLoaded(cellDownId)
&& landShapePointer[(ESM::Land::LAND_SIZE - 1) * ESM::Land::LAND_SIZE + i] != landDownShapePointer[i])
landShapeNew[(ESM::Land::LAND_SIZE - 1) * ESM::Land::LAND_SIZE + i] = landDownShapePointer[i];
}
QVariant changedLand;
changedLand.setValue(landShapeNew);
QModelIndex index(
landTable.getModelIndex(cellId, landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandHeightsIndex)));
QUndoStack& undoStack = document.getUndoStack();
undoStack.push(new CSMWorld::ModifyCommand(landTable, index, changedLand));
}
void CSVRender::TerrainShapeMode::dragMoveEvent(QDragMoveEvent* event) {}
void CSVRender::TerrainShapeMode::mouseMoveEvent(QMouseEvent* event)
{
WorldspaceHitResult hit = getWorldspaceWidget().mousePick(event->pos(), getInteractionMask());
if (hit.hit && mBrushDraw && !(mShapeEditTool == ShapeEditTool_Drag && mIsEditing))
mBrushDraw->update(hit.worldPos, mBrushSize, mBrushShape);
if (!hit.hit && mBrushDraw && !(mShapeEditTool == ShapeEditTool_Drag && mIsEditing))
mBrushDraw->hide();
}
std::shared_ptr<CSVRender::TerrainSelection> CSVRender::TerrainShapeMode::getTerrainSelection()
{
return mTerrainShapeSelection;
}
void CSVRender::TerrainShapeMode::setBrushSize(int brushSize)
{
mBrushSize = brushSize;
}
void CSVRender::TerrainShapeMode::setBrushShape(CSVWidget::BrushShape brushShape)
{
mBrushShape = brushShape;
// Set custom brush shape
if (mBrushShape == CSVWidget::BrushShape_Custom && !mTerrainShapeSelection->getTerrainSelection().empty())
{
auto terrainSelection = mTerrainShapeSelection->getTerrainSelection();
int selectionCenterX = 0;
int selectionCenterY = 0;
int selectionAmount = 0;
for (auto const& value : terrainSelection)
{
selectionCenterX = selectionCenterX + value.first;
selectionCenterY = selectionCenterY + value.second;
++selectionAmount;
}
if (selectionAmount != 0)
{
selectionCenterX /= selectionAmount;
selectionCenterY /= selectionAmount;
}
mCustomBrushShape.clear();
std::pair<int, int> differentialPos{};
for (auto const& value : terrainSelection)
{
differentialPos.first = value.first - selectionCenterX;
differentialPos.second = value.second - selectionCenterY;
mCustomBrushShape.push_back(differentialPos);
}
}
}
void CSVRender::TerrainShapeMode::setShapeEditTool(int shapeEditTool)
{
mShapeEditTool = shapeEditTool;
}
void CSVRender::TerrainShapeMode::setShapeEditToolStrength(int shapeEditToolStrength)
{
mShapeEditToolStrength = shapeEditToolStrength;
}
CSVRender::PagedWorldspaceWidget& CSVRender::TerrainShapeMode::getPagedWorldspaceWidget()
{
return dynamic_cast<PagedWorldspaceWidget&>(getWorldspaceWidget());
}
| 81,331
|
C++
|
.cpp
| 1,542
| 42.297017
| 120
| 0.651174
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,127
|
editmode.cpp
|
OpenMW_openmw/apps/opencs/view/render/editmode.cpp
|
#include "editmode.hpp"
#include <apps/opencs/view/widget/modebutton.hpp>
#include "worldspacewidget.hpp"
class QMouseEvent;
class QWidget;
namespace CSVWidget
{
class SceneToolbar;
}
CSVRender::WorldspaceWidget& CSVRender::EditMode::getWorldspaceWidget()
{
return *mWorldspaceWidget;
}
CSVRender::EditMode::EditMode(
WorldspaceWidget* worldspaceWidget, const QIcon& icon, unsigned int mask, const QString& tooltip, QWidget* parent)
: ModeButton(icon, tooltip, parent)
, mWorldspaceWidget(worldspaceWidget)
, mMask(mask)
{
}
unsigned int CSVRender::EditMode::getInteractionMask() const
{
return mMask;
}
void CSVRender::EditMode::activate(CSVWidget::SceneToolbar* toolbar)
{
mWorldspaceWidget->setInteractionMask(mMask);
mWorldspaceWidget->clearSelection(~mMask);
}
void CSVRender::EditMode::setEditLock(bool locked) {}
void CSVRender::EditMode::primaryOpenPressed(const WorldspaceHitResult& hit) {}
void CSVRender::EditMode::primaryEditPressed(const WorldspaceHitResult& hit) {}
void CSVRender::EditMode::secondaryEditPressed(const WorldspaceHitResult& hit) {}
void CSVRender::EditMode::primarySelectPressed(const WorldspaceHitResult& hit) {}
void CSVRender::EditMode::secondarySelectPressed(const WorldspaceHitResult& hit) {}
void CSVRender::EditMode::tertiarySelectPressed(const WorldspaceHitResult& hit) {}
bool CSVRender::EditMode::primaryEditStartDrag(const QPoint& pos)
{
return false;
}
bool CSVRender::EditMode::secondaryEditStartDrag(const QPoint& pos)
{
return false;
}
bool CSVRender::EditMode::primarySelectStartDrag(const QPoint& pos)
{
return false;
}
bool CSVRender::EditMode::secondarySelectStartDrag(const QPoint& pos)
{
return false;
}
void CSVRender::EditMode::drag(const QPoint& pos, int diffX, int diffY, double speedFactor) {}
void CSVRender::EditMode::dragCompleted(const QPoint& pos) {}
void CSVRender::EditMode::dragAborted() {}
void CSVRender::EditMode::dragWheel(int diff, double speedFactor) {}
void CSVRender::EditMode::dragEnterEvent(QDragEnterEvent* event) {}
void CSVRender::EditMode::dropEvent(QDropEvent* event) {}
void CSVRender::EditMode::dragMoveEvent(QDragMoveEvent* event) {}
void CSVRender::EditMode::mouseMoveEvent(QMouseEvent* event) {}
int CSVRender::EditMode::getSubMode() const
{
return -1;
}
| 2,323
|
C++
|
.cpp
| 64
| 33.984375
| 118
| 0.800538
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,129
|
instanceselectionmode.cpp
|
OpenMW_openmw/apps/opencs/view/render/instanceselectionmode.cpp
|
#include "instanceselectionmode.hpp"
#include <cmath>
#include <string>
#include <vector>
#include <apps/opencs/model/doc/document.hpp>
#include <apps/opencs/model/world/data.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/render/mask.hpp>
#include <apps/opencs/view/render/selectionmode.hpp>
#include <osg/Array>
#include <osg/GL>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/Math>
#include <osg/PositionAttitudeTransform>
#include <osg/PrimitiveSet>
#include <osg/StateAttribute>
#include <osg/StateSet>
#include <osg/Vec3d>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include <osg/ref_ptr>
#include <QAction>
#include <QMenu>
#include <QPoint>
#include "../../model/world/commands.hpp"
#include "../../model/world/idtable.hpp"
#include "instancedragmodes.hpp"
#include "object.hpp"
#include "worldspacewidget.hpp"
namespace CSVWidget
{
class SceneToolbar;
}
namespace CSVRender
{
class TagBase;
InstanceSelectionMode::InstanceSelectionMode(
CSVWidget::SceneToolbar* parent, WorldspaceWidget& worldspaceWidget, osg::Group* cellNode)
: SelectionMode(parent, worldspaceWidget, Mask_Reference)
, mParentNode(cellNode)
{
mSelectSame = new QAction("Extend selection to instances with same object ID", this);
mDeleteSelection = new QAction("Delete selected instances", this);
connect(mSelectSame, &QAction::triggered, this, &InstanceSelectionMode::selectSame);
connect(mDeleteSelection, &QAction::triggered, this, &InstanceSelectionMode::deleteSelection);
}
InstanceSelectionMode::~InstanceSelectionMode()
{
if (mBaseNode)
mParentNode->removeChild(mBaseNode);
}
void InstanceSelectionMode::setDragStart(const osg::Vec3d& dragStart)
{
mDragStart = dragStart;
}
const osg::Vec3d& InstanceSelectionMode::getDragStart()
{
return mDragStart;
}
void InstanceSelectionMode::dragEnded(const osg::Vec3d& dragEndPoint, DragMode dragMode)
{
float dragDistance = (mDragStart - dragEndPoint).length();
if (mBaseNode)
mParentNode->removeChild(mBaseNode);
if (getCurrentId() == "cube-centre")
{
osg::Vec3d pointA(mDragStart[0] - dragDistance, mDragStart[1] - dragDistance, mDragStart[2] - dragDistance);
osg::Vec3d pointB(mDragStart[0] + dragDistance, mDragStart[1] + dragDistance, mDragStart[2] + dragDistance);
getWorldspaceWidget().selectInsideCube(pointA, pointB, dragMode);
}
else if (getCurrentId() == "cube-corner")
{
getWorldspaceWidget().selectInsideCube(mDragStart, dragEndPoint, dragMode);
}
else if (getCurrentId() == "sphere")
{
getWorldspaceWidget().selectWithinDistance(mDragStart, dragDistance, dragMode);
}
}
void InstanceSelectionMode::drawSelectionCubeCentre(const osg::Vec3f& mousePlanePoint)
{
float dragDistance = (mDragStart - mousePlanePoint).length();
drawSelectionCube(mDragStart, dragDistance);
}
void InstanceSelectionMode::drawSelectionCubeCorner(const osg::Vec3f& mousePlanePoint)
{
drawSelectionBox(mDragStart, mousePlanePoint);
}
void InstanceSelectionMode::drawSelectionBox(const osg::Vec3d& pointA, const osg::Vec3d& pointB)
{
if (mBaseNode)
mParentNode->removeChild(mBaseNode);
mBaseNode = new osg::PositionAttitudeTransform;
mBaseNode->setPosition(pointA);
osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry);
osg::Vec3Array* vertices = new osg::Vec3Array;
vertices->push_back(osg::Vec3f(0.0f, 0.0f, 0.0f));
vertices->push_back(osg::Vec3f(0.0f, 0.0f, pointB[2] - pointA[2]));
vertices->push_back(osg::Vec3f(0.0f, pointB[1] - pointA[1], 0.0f));
vertices->push_back(osg::Vec3f(0.0f, pointB[1] - pointA[1], pointB[2] - pointA[2]));
vertices->push_back(osg::Vec3f(pointB[0] - pointA[0], 0.0f, 0.0f));
vertices->push_back(osg::Vec3f(pointB[0] - pointA[0], 0.0f, pointB[2] - pointA[2]));
vertices->push_back(osg::Vec3f(pointB[0] - pointA[0], pointB[1] - pointA[1], 0.0f));
vertices->push_back(osg::Vec3f(pointB[0] - pointA[0], pointB[1] - pointA[1], pointB[2] - pointA[2]));
geometry->setVertexArray(vertices);
osg::DrawElementsUShort* primitives = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, 0);
// top
primitives->push_back(2);
primitives->push_back(1);
primitives->push_back(0);
primitives->push_back(3);
primitives->push_back(1);
primitives->push_back(2);
// bottom
primitives->push_back(4);
primitives->push_back(5);
primitives->push_back(6);
primitives->push_back(6);
primitives->push_back(5);
primitives->push_back(7);
// sides
primitives->push_back(1);
primitives->push_back(4);
primitives->push_back(0);
primitives->push_back(4);
primitives->push_back(1);
primitives->push_back(5);
primitives->push_back(4);
primitives->push_back(2);
primitives->push_back(0);
primitives->push_back(6);
primitives->push_back(2);
primitives->push_back(4);
primitives->push_back(6);
primitives->push_back(3);
primitives->push_back(2);
primitives->push_back(7);
primitives->push_back(3);
primitives->push_back(6);
primitives->push_back(1);
primitives->push_back(3);
primitives->push_back(5);
primitives->push_back(5);
primitives->push_back(3);
primitives->push_back(7);
geometry->addPrimitiveSet(primitives);
osg::Vec4Array* colours = new osg::Vec4Array;
colours->push_back(osg::Vec4f(0.3f, 0.3f, 0.5f, 0.2f));
colours->push_back(osg::Vec4f(0.9f, 0.9f, 1.0f, 0.2f));
colours->push_back(osg::Vec4f(0.3f, 0.3f, 0.4f, 0.2f));
colours->push_back(osg::Vec4f(0.9f, 0.9f, 1.0f, 0.2f));
colours->push_back(osg::Vec4f(0.3f, 0.3f, 0.4f, 0.2f));
colours->push_back(osg::Vec4f(0.9f, 0.9f, 1.0f, 0.2f));
colours->push_back(osg::Vec4f(0.3f, 0.3f, 0.4f, 0.2f));
colours->push_back(osg::Vec4f(0.9f, 0.9f, 1.0f, 0.2f));
geometry->setColorArray(colours, osg::Array::BIND_PER_VERTEX);
geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
geometry->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
geometry->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
mBaseNode->addChild(geometry);
mParentNode->addChild(mBaseNode);
}
void InstanceSelectionMode::drawSelectionCube(const osg::Vec3d& point, float radius)
{
if (mBaseNode)
mParentNode->removeChild(mBaseNode);
mBaseNode = new osg::PositionAttitudeTransform;
mBaseNode->setPosition(point);
osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry);
osg::Vec3Array* vertices = new osg::Vec3Array;
for (int i = 0; i < 2; ++i)
{
float height = i ? -radius : radius;
vertices->push_back(osg::Vec3f(height, -radius, -radius));
vertices->push_back(osg::Vec3f(height, -radius, radius));
vertices->push_back(osg::Vec3f(height, radius, -radius));
vertices->push_back(osg::Vec3f(height, radius, radius));
}
geometry->setVertexArray(vertices);
osg::DrawElementsUShort* primitives = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES, 0);
// top
primitives->push_back(2);
primitives->push_back(1);
primitives->push_back(0);
primitives->push_back(3);
primitives->push_back(1);
primitives->push_back(2);
// bottom
primitives->push_back(4);
primitives->push_back(5);
primitives->push_back(6);
primitives->push_back(6);
primitives->push_back(5);
primitives->push_back(7);
// sides
primitives->push_back(1);
primitives->push_back(4);
primitives->push_back(0);
primitives->push_back(4);
primitives->push_back(1);
primitives->push_back(5);
primitives->push_back(4);
primitives->push_back(2);
primitives->push_back(0);
primitives->push_back(6);
primitives->push_back(2);
primitives->push_back(4);
primitives->push_back(6);
primitives->push_back(3);
primitives->push_back(2);
primitives->push_back(7);
primitives->push_back(3);
primitives->push_back(6);
primitives->push_back(1);
primitives->push_back(3);
primitives->push_back(5);
primitives->push_back(5);
primitives->push_back(3);
primitives->push_back(7);
geometry->addPrimitiveSet(primitives);
osg::Vec4Array* colours = new osg::Vec4Array;
colours->push_back(osg::Vec4f(0.3f, 0.3f, 0.5f, 0.2f));
colours->push_back(osg::Vec4f(0.9f, 0.9f, 1.0f, 0.2f));
colours->push_back(osg::Vec4f(0.3f, 0.3f, 0.4f, 0.2f));
colours->push_back(osg::Vec4f(0.9f, 0.9f, 1.0f, 0.2f));
colours->push_back(osg::Vec4f(0.3f, 0.3f, 0.4f, 0.2f));
colours->push_back(osg::Vec4f(0.9f, 0.9f, 1.0f, 0.2f));
colours->push_back(osg::Vec4f(0.3f, 0.3f, 0.4f, 0.2f));
colours->push_back(osg::Vec4f(0.9f, 0.9f, 1.0f, 0.2f));
geometry->setColorArray(colours, osg::Array::BIND_PER_VERTEX);
geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
geometry->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
geometry->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
mBaseNode->addChild(geometry);
mParentNode->addChild(mBaseNode);
}
void InstanceSelectionMode::drawSelectionSphere(const osg::Vec3f& mousePlanePoint)
{
float dragDistance = (mDragStart - mousePlanePoint).length();
drawSelectionSphere(mDragStart, dragDistance);
}
void InstanceSelectionMode::drawSelectionSphere(const osg::Vec3d& point, float radius)
{
if (mBaseNode)
mParentNode->removeChild(mBaseNode);
mBaseNode = new osg::PositionAttitudeTransform;
mBaseNode->setPosition(point);
osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry);
osg::Vec3Array* vertices = new osg::Vec3Array;
constexpr int resolution = 32;
float radiusPerResolution = radius / resolution;
float reciprocalResolution = 1.0f / resolution;
float doubleReciprocalRes = reciprocalResolution * 2;
osg::Vec4Array* colours = new osg::Vec4Array;
for (int i = 0; i <= resolution; i += 2)
{
float iShifted = (static_cast<float>(i) - resolution / 2.0f); // i - 16 = -16 ... 16
float xPercentile = iShifted * doubleReciprocalRes;
float x = xPercentile * radius;
float thisRadius = sqrt(radius * radius - x * x);
// the next row
float iShifted2 = (static_cast<float>(i + 1) - resolution / 2.0f);
float xPercentile2 = iShifted2 * doubleReciprocalRes;
float x2 = xPercentile2 * radius;
float thisRadius2 = sqrt(radius * radius - x2 * x2);
for (int j = 0; j < resolution; ++j)
{
float vertexX = thisRadius * sin(j * reciprocalResolution * osg::PI * 2);
float vertexY = i * radiusPerResolution * 2 - radius;
float vertexZ = thisRadius * cos(j * reciprocalResolution * osg::PI * 2);
float heightPercentage = (vertexZ + radius) / (radius * 2);
vertices->push_back(osg::Vec3f(vertexX, vertexY, vertexZ));
colours->push_back(osg::Vec4f(heightPercentage, heightPercentage, heightPercentage, 0.3f));
float vertexNextRowX = thisRadius2 * sin(j * reciprocalResolution * osg::PI * 2);
float vertexNextRowY = (i + 1) * radiusPerResolution * 2 - radius;
float vertexNextRowZ = thisRadius2 * cos(j * reciprocalResolution * osg::PI * 2);
float heightPercentageNextRow = (vertexZ + radius) / (radius * 2);
vertices->push_back(osg::Vec3f(vertexNextRowX, vertexNextRowY, vertexNextRowZ));
colours->push_back(
osg::Vec4f(heightPercentageNextRow, heightPercentageNextRow, heightPercentageNextRow, 0.3f));
}
}
geometry->setVertexArray(vertices);
osg::DrawElementsUShort* primitives = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLE_STRIP, 0);
for (int i = 0; i < resolution; ++i)
{
// Even
for (int j = 0; j < resolution * 2; ++j)
{
if (i * resolution * 2 + j > static_cast<int>(vertices->size()) - 1)
continue;
primitives->push_back(i * resolution * 2 + j);
}
if (i * resolution * 2 > static_cast<int>(vertices->size()) - 1)
continue;
primitives->push_back(i * resolution * 2);
primitives->push_back(i * resolution * 2 + 1);
// Odd
for (int j = 1; j < resolution * 2 - 2; j += 2)
{
if ((i + 1) * resolution * 2 + j - 1 > static_cast<int>(vertices->size()) - 1)
continue;
primitives->push_back((i + 1) * resolution * 2 + j - 1);
primitives->push_back(i * resolution * 2 + j + 2);
}
if ((i + 2) * resolution * 2 - 2 > static_cast<int>(vertices->size()) - 1)
continue;
primitives->push_back((i + 2) * resolution * 2 - 2);
primitives->push_back(i * resolution * 2 + 1);
primitives->push_back((i + 1) * resolution * 2);
}
geometry->addPrimitiveSet(primitives);
geometry->setColorArray(colours, osg::Array::BIND_PER_VERTEX);
geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
geometry->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
geometry->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
mBaseNode->addChild(geometry);
mParentNode->addChild(mBaseNode);
}
bool InstanceSelectionMode::createContextMenu(QMenu* menu)
{
if (menu)
{
SelectionMode::createContextMenu(menu);
menu->addAction(mSelectSame);
menu->addAction(mDeleteSelection);
}
return true;
}
void InstanceSelectionMode::selectSame()
{
getWorldspaceWidget().selectAllWithSameParentId(Mask_Reference);
}
void InstanceSelectionMode::deleteSelection()
{
std::vector<osg::ref_ptr<TagBase>> selection = getWorldspaceWidget().getSelection(Mask_Reference);
CSMWorld::IdTable& referencesTable = dynamic_cast<CSMWorld::IdTable&>(
*getWorldspaceWidget().getDocument().getData().getTableModel(CSMWorld::UniversalId::Type_References));
for (std::vector<osg::ref_ptr<TagBase>>::iterator iter = selection.begin(); iter != selection.end(); ++iter)
{
CSMWorld::DeleteCommand* command = new CSMWorld::DeleteCommand(
referencesTable, static_cast<ObjectTag*>(iter->get())->mObject->getReferenceId());
getWorldspaceWidget().getDocument().getUndoStack().push(command);
}
}
}
| 16,089
|
C++
|
.cpp
| 350
| 36.934286
| 120
| 0.626669
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,130
|
orbitcameramode.cpp
|
OpenMW_openmw/apps/opencs/view/render/orbitcameramode.cpp
|
#include "orbitcameramode.hpp"
#include <QMenu>
#include <memory>
#include "../../model/prefs/shortcut.hpp"
#include <apps/opencs/view/widget/modebutton.hpp>
#include "worldspacewidget.hpp"
namespace CSVWidget
{
class SceneToolbar;
}
namespace CSVRender
{
OrbitCameraMode::OrbitCameraMode(
WorldspaceWidget* worldspaceWidget, const QIcon& icon, const QString& tooltip, QWidget* parent)
: ModeButton(icon, tooltip, parent)
, mWorldspaceWidget(worldspaceWidget)
, mCenterOnSelection(nullptr)
{
mCenterShortcut = new CSMPrefs::Shortcut("orbit-center-selection", worldspaceWidget);
mCenterShortcut->enable(false);
connect(mCenterShortcut, qOverload<>(&CSMPrefs::Shortcut::activated), this, &OrbitCameraMode::centerSelection);
}
void OrbitCameraMode::activate(CSVWidget::SceneToolbar* toolbar)
{
mCenterOnSelection = new QAction("Center on selected object", this);
mCenterShortcut->associateAction(mCenterOnSelection);
connect(mCenterOnSelection, &QAction::triggered, this, &OrbitCameraMode::centerSelection);
mCenterShortcut->enable(true);
}
void OrbitCameraMode::deactivate(CSVWidget::SceneToolbar* toolbar)
{
mCenterShortcut->associateAction(nullptr);
mCenterShortcut->enable(false);
}
bool OrbitCameraMode::createContextMenu(QMenu* menu)
{
if (menu)
{
menu->addAction(mCenterOnSelection);
}
return true;
}
void OrbitCameraMode::centerSelection()
{
mWorldspaceWidget->centerOrbitCameraOnSelection();
}
}
| 1,635
|
C++
|
.cpp
| 47
| 28.829787
| 119
| 0.713651
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,131
|
recordfilterbox.cpp
|
OpenMW_openmw/apps/opencs/view/filter/recordfilterbox.cpp
|
#include "recordfilterbox.hpp"
#include <variant>
#include <QHBoxLayout>
#include <QLabel>
#include <QVariant>
#include "editwidget.hpp"
#include "filterdata.hpp"
CSVFilter::RecordFilterBox::RecordFilterBox(CSMWorld::Data& data, QWidget* parent)
: QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 6, 5, 0);
QLabel* label = new QLabel("Record Filter", this);
label->setIndent(2);
layout->addWidget(label);
mEdit = new EditWidget(data, this);
layout->addWidget(mEdit);
setLayout(layout);
connect(mEdit, &EditWidget::filterChanged, this, &RecordFilterBox::filterChanged);
}
void CSVFilter::RecordFilterBox::setFilter(const std::string& filter)
{
mEdit->clear();
mEdit->setText(QString::fromUtf8(filter.c_str()));
}
void CSVFilter::RecordFilterBox::createFilterRequest(const std::vector<FilterData>& sourceFilter, Qt::DropAction action)
{
mEdit->createFilterRequest(sourceFilter, action);
}
| 995
|
C++
|
.cpp
| 29
| 31.103448
| 120
| 0.749476
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
35,132
|
editwidget.cpp
|
OpenMW_openmw/apps/opencs/view/filter/editwidget.cpp
|
#include "editwidget.hpp"
#include <sstream>
#include <variant>
#include <QAction>
#include <QApplication>
#include <QContextMenuEvent>
#include <QMenu>
#include <QRegularExpression>
#include <QString>
#include <QVariant>
#include "filterdata.hpp"
#include <apps/opencs/model/filter/parser.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <components/debug/debuglog.hpp>
#include <components/misc/helpviewer.hpp>
#include <components/misc/scalableicon.hpp>
#include "../../model/prefs/shortcut.hpp"
#include "../../model/world/columns.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idtablebase.hpp"
CSVFilter::EditWidget::EditWidget(CSMWorld::Data& data, QWidget* parent)
: QLineEdit(parent)
, mParser(data)
, mIsEmpty(true)
{
mPalette = palette();
connect(this, &QLineEdit::textChanged, this, &EditWidget::textChanged);
const CSMWorld::IdTableBase* model
= static_cast<const CSMWorld::IdTableBase*>(data.getTableModel(CSMWorld::UniversalId::Type_Filters));
connect(model, &CSMWorld::IdTableBase::dataChanged, this, &EditWidget::filterDataChanged, Qt::QueuedConnection);
connect(model, &CSMWorld::IdTableBase::rowsRemoved, this, &EditWidget::filterRowsRemoved, Qt::QueuedConnection);
connect(model, &CSMWorld::IdTableBase::rowsInserted, this, &EditWidget::filterRowsInserted, Qt::QueuedConnection);
mStateColumnIndex = model->findColumnIndex(CSMWorld::Columns::ColumnId_Modification);
mDescColumnIndex = model->findColumnIndex(CSMWorld::Columns::ColumnId_Description);
mHelpAction = new QAction(tr("Help"), this);
connect(mHelpAction, &QAction::triggered, this, &EditWidget::openHelp);
mHelpAction->setIcon(Misc::ScalableIcon::load(":info"));
addAction(mHelpAction);
auto* openHelpShortcut = new CSMPrefs::Shortcut("help", this);
openHelpShortcut->associateAction(mHelpAction);
setText("!string(\"ID\", \".*\")");
}
void CSVFilter::EditWidget::textChanged(const QString& text)
{
// no need to parse and apply filter if it was empty and now is empty too.
// e.g. - we modifiing content of filter with already opened some other (big) tables.
if (text.length() == 0)
{
if (mIsEmpty)
return;
else
mIsEmpty = true;
}
else
mIsEmpty = false;
if (mParser.parse(text.toUtf8().constData()))
{
setPalette(mPalette);
emit filterChanged(mParser.getFilter());
}
else
{
QPalette palette(mPalette);
palette.setColor(QPalette::Text, Qt::red);
setPalette(palette);
/// \todo improve error reporting; mark only the faulty part
}
}
void CSVFilter::EditWidget::filterDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
for (int i = topLeft.column(); i <= bottomRight.column(); ++i)
if (i != mStateColumnIndex && i != mDescColumnIndex)
textChanged(text());
}
void CSVFilter::EditWidget::filterRowsRemoved(const QModelIndex& parent, int start, int end)
{
textChanged(text());
}
void CSVFilter::EditWidget::filterRowsInserted(const QModelIndex& parent, int start, int end)
{
textChanged(text());
}
void CSVFilter::EditWidget::createFilterRequest(const std::vector<FilterData>& sourceFilter, Qt::DropAction action)
{
FilterType filterType = FilterType::String;
std::vector<FilterData> newFilter;
for (auto filterData : sourceFilter)
{
FilterData newFilterData;
std::pair<std::string, FilterType> pair = std::visit(FilterVisitor(), filterData.searchData);
std::string searchString = pair.first;
filterType = pair.second;
newFilterData.searchData = searchString;
newFilterData.columns = filterData.columns;
newFilter.emplace_back(newFilterData);
}
const unsigned count = newFilter.size();
bool multipleElements = false;
switch (count) // setting multipleElements;
{
case 0: // empty
return; // nothing to do here
case 1: // only single
multipleElements = false;
break;
default:
multipleElements = true;
break;
}
Qt::KeyboardModifiers key = QApplication::keyboardModifiers();
QString oldContent(text());
bool replaceMode = false;
std::string orAnd;
switch (key) // setting replaceMode and string used to glue expressions
{
case Qt::ShiftModifier:
orAnd = "!or(";
replaceMode = false;
break;
case Qt::ControlModifier:
orAnd = "!and(";
replaceMode = false;
break;
default:
replaceMode = true;
break;
}
if (oldContent.isEmpty()
|| !oldContent.contains(QRegularExpression("^!.*$",
QRegularExpression::CaseInsensitiveOption))) // if line edit is empty or it does not contain one shot filter
// go into replace mode
{
replaceMode = true;
}
if (!replaceMode)
{
oldContent.remove('!');
}
std::stringstream ss;
if (multipleElements)
{
if (replaceMode)
{
ss << "!or(";
}
else
{
ss << orAnd << oldContent.toUtf8().constData() << ',';
}
for (unsigned i = 0; i < count; ++i)
{
ss << generateFilter(newFilter[i], filterType);
if (i + 1 != count)
{
ss << ", ";
}
}
ss << ')';
}
else
{
if (!replaceMode)
{
ss << orAnd << oldContent.toUtf8().constData() << ',';
}
else
{
ss << '!';
}
ss << generateFilter(newFilter[0], filterType);
if (!replaceMode)
{
ss << ')';
}
}
if (ss.str().length() > 4)
{
clear();
insert(QString::fromUtf8(ss.str().c_str()));
}
}
std::string CSVFilter::EditWidget::generateFilter(const FilterData& filterData, FilterType filterType) const
{
const unsigned columns = filterData.columns.size();
bool multipleColumns = false;
switch (columns)
{
case 0: // empty
return ""; // no column to filter
case 1: // one column to look for
multipleColumns = false;
break;
default:
multipleColumns = true;
break;
}
std::string quotesResolved;
if (std::get_if<std::string>(&filterData.searchData))
quotesResolved = std::get<std::string>(filterData.searchData);
else
{
Log(Debug::Warning) << "Generating record filter failed.";
return "";
}
if (filterType == FilterType::String)
quotesResolved = '"' + quotesResolved + '"';
std::stringstream ss;
if (multipleColumns)
{
ss << "or(";
for (unsigned i = 0; i < columns; ++i)
{
ss << filterTypeName(filterType) << "(" << '"' << filterData.columns[i] << '"' << ',' << quotesResolved
<< ')';
if (i + 1 != columns)
ss << ',';
}
ss << ')';
}
else
{
ss << filterTypeName(filterType) << '(' << '"' << filterData.columns[0] << "\"," << quotesResolved << ")";
}
return ss.str();
}
void CSVFilter::EditWidget::contextMenuEvent(QContextMenuEvent* event)
{
QMenu* menu = createStandardContextMenu();
menu->addAction(mHelpAction);
menu->exec(event->globalPos());
delete menu;
}
void CSVFilter::EditWidget::openHelp()
{
Misc::HelpViewer::openHelp("manuals/openmw-cs/record-filters.html");
}
| 7,753
|
C++
|
.cpp
| 236
| 25.898305
| 120
| 0.616765
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,133
|
filterbox.cpp
|
OpenMW_openmw/apps/opencs/view/filter/filterbox.cpp
|
#include "filterbox.hpp"
#include <string>
#include <utility>
#include <variant>
#include <vector>
#include <QDragEnterEvent>
#include <QHBoxLayout>
#include <QVariant>
#include "filterdata.hpp"
#include "recordfilterbox.hpp"
#include <apps/opencs/model/world/tablemimedata.hpp>
#include <apps/opencs/model/world/universalid.hpp>
#include <apps/opencs/view/world/dragrecordtable.hpp>
CSVFilter::FilterBox::FilterBox(CSMWorld::Data& data, QWidget* parent)
: QWidget(parent)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
mRecordFilterBox = new RecordFilterBox(data, this);
layout->addWidget(mRecordFilterBox);
setLayout(layout);
connect(mRecordFilterBox, &RecordFilterBox::filterChanged, this, &FilterBox::recordFilterChanged);
setAcceptDrops(true);
}
void CSVFilter::FilterBox::setRecordFilter(const std::string& filter)
{
mRecordFilterBox->setFilter(filter);
}
void CSVFilter::FilterBox::dropEvent(QDropEvent* event)
{
const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData());
if (!mime) // May happen when non-records (e.g. plain text) are dragged and dropped
return;
std::vector<CSMWorld::UniversalId> universalIdData = mime->getData();
QModelIndex index = mime->getIndexAtDragStart();
const CSVWorld::DragRecordTable* dragTable = mime->getTableOfDragStart();
QVariant qData;
std::string searchColumn;
if (index.isValid() && dragTable)
{
qData = dragTable->model()->data(index);
searchColumn = dragTable->model()->headerData(index.column(), Qt::Horizontal).toString().toStdString();
}
emit recordDropped(universalIdData, std::make_pair(qData, searchColumn), event->proposedAction());
}
void CSVFilter::FilterBox::dragEnterEvent(QDragEnterEvent* event)
{
event->acceptProposedAction();
}
void CSVFilter::FilterBox::dragMoveEvent(QDragMoveEvent* event)
{
event->accept();
}
void CSVFilter::FilterBox::createFilterRequest(const std::vector<FilterData>& sourceFilter, Qt::DropAction action)
{
mRecordFilterBox->createFilterRequest(sourceFilter, action);
}
| 2,175
|
C++
|
.cpp
| 57
| 34.789474
| 114
| 0.75798
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,134
|
sdlinit.cpp
|
OpenMW_openmw/apps/launcher/sdlinit.cpp
|
#include <signal.h>
#include <SDL.h>
bool initSDL()
{
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "software");
SDL_SetMainReady();
// Required for determining screen resolution and such on the Graphics tab
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
return false;
}
signal(SIGINT, SIG_DFL); // We don't want to use the SDL event loop in the launcher,
// so reset SIGINT which SDL wants to redirect to an SDL_Quit event.
return true;
}
void quitSDL()
{
// Disconnect from SDL processes
SDL_Quit();
}
| 540
|
C++
|
.cpp
| 20
| 23.2
| 88
| 0.676357
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,135
|
main.cpp
|
OpenMW_openmw/apps/launcher/main.cpp
|
#include <iostream>
#include <QDir>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <components/debug/debugging.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/files/qtconversion.hpp>
#include <components/l10n/qttranslations.hpp>
#include <components/platform/application.hpp>
#include <components/platform/platform.hpp>
#ifdef MAC_OS_X_VERSION_MIN_REQUIRED
#undef MAC_OS_X_VERSION_MIN_REQUIRED
// We need to do this because of Qt: https://bugreports.qt-project.org/browse/QTBUG-22154
#define MAC_OS_X_VERSION_MIN_REQUIRED __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
#endif // MAC_OS_X_VERSION_MIN_REQUIRED
#include "maindialog.hpp"
int runLauncher(int argc, char* argv[])
{
Platform::init();
boost::program_options::variables_map variables;
boost::program_options::options_description description;
Files::ConfigurationManager configurationManager;
configurationManager.addCommonOptions(description);
configurationManager.readConfiguration(variables, description, true);
Debug::setupLogging(configurationManager.getLogPath(), "Launcher");
try
{
Platform::Application app(argc, argv);
QString resourcesPath(".");
if (!variables["resources"].empty())
{
resourcesPath = Files::pathToQString(variables["resources"].as<Files::MaybeQuotedPath>().u8string());
}
l10n::installQtTranslations(app, "launcher", resourcesPath);
Launcher::MainDialog mainWin(configurationManager);
Launcher::FirstRunDialogResult result = mainWin.showFirstRunDialog();
if (result == Launcher::FirstRunDialogResultFailure)
return 0;
if (result == Launcher::FirstRunDialogResultContinue)
mainWin.show();
int exitCode = app.exec();
return exitCode;
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Unexpected exception: " << e.what();
return 0;
}
}
int main(int argc, char* argv[])
{
return Debug::wrapApplication(runLauncher, argc, argv, "Launcher");
}
| 2,152
|
C++
|
.cpp
| 53
| 35.433962
| 113
| 0.724784
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,136
|
importpage.cpp
|
OpenMW_openmw/apps/launcher/importpage.cpp
|
#include "importpage.hpp"
#include <QDebug>
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>
#include <components/files/configurationmanager.hpp>
#include <components/files/qtconversion.hpp>
using namespace Process;
Launcher::ImportPage::ImportPage(const Files::ConfigurationManager& cfg, Config::GameSettings& gameSettings,
Config::LauncherSettings& launcherSettings, MainDialog* parent)
: QWidget(parent)
, mCfgMgr(cfg)
, mGameSettings(gameSettings)
, mLauncherSettings(launcherSettings)
, mMain(parent)
{
setupUi(this);
mWizardInvoker = new ProcessInvoker();
mImporterInvoker = new ProcessInvoker();
resetProgressBar();
connect(mWizardInvoker->getProcess(), &QProcess::started, this, &ImportPage::wizardStarted);
connect(mWizardInvoker->getProcess(), qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this,
&ImportPage::wizardFinished);
connect(mImporterInvoker->getProcess(), &QProcess::started, this, &ImportPage::importerStarted);
connect(mImporterInvoker->getProcess(), qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this,
&ImportPage::importerFinished);
// Detect Morrowind configuration files
QStringList iniPaths;
for (const auto& path : mGameSettings.getDataDirs())
{
QDir dir(path.value);
dir.setPath(dir.canonicalPath()); // Resolve symlinks
if (dir.exists(QString("Morrowind.ini")))
iniPaths.append(dir.absoluteFilePath(QString("Morrowind.ini")));
else
{
if (!dir.cdUp())
continue; // Cannot move from Data Files
if (dir.exists(QString("Morrowind.ini")))
iniPaths.append(dir.absoluteFilePath(QString("Morrowind.ini")));
}
}
if (!iniPaths.isEmpty())
{
settingsComboBox->addItems(iniPaths);
importerButton->setEnabled(true);
}
else
{
importerButton->setEnabled(false);
}
loadSettings();
}
Launcher::ImportPage::~ImportPage()
{
delete mWizardInvoker;
delete mImporterInvoker;
}
void Launcher::ImportPage::on_wizardButton_clicked()
{
mMain->writeSettings();
if (!mWizardInvoker->startProcess(QLatin1String("openmw-wizard"), false))
return;
}
void Launcher::ImportPage::on_importerButton_clicked()
{
mMain->writeSettings();
// Create the file if it doesn't already exist, else the importer will fail
auto path = mCfgMgr.getUserConfigPath();
path /= "openmw.cfg";
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QFile file(path);
#else
QFile file(Files::pathToQString(path));
#endif
if (!file.exists())
{
if (!file.open(QIODevice::ReadWrite))
{
// File cannot be created
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Error writing OpenMW configuration file"));
msgBox.setIcon(QMessageBox::Critical);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setText(
tr("<html><head/><body><p><b>Could not open or create %1 for writing </b></p>"
"<p>Please make sure you have the right permissions "
"and try again.</p></body></html>")
.arg(file.fileName()));
msgBox.exec();
return;
}
file.close();
}
// Construct the arguments to run the importer
QStringList arguments;
if (addonsCheckBox->isChecked())
arguments.append(QString("--game-files"));
if (fontsCheckBox->isChecked())
arguments.append(QString("--fonts"));
arguments.append(QString("--encoding"));
arguments.append(mGameSettings.value(QString("encoding"), { "win1252" }).value);
arguments.append(QString("--ini"));
arguments.append(settingsComboBox->currentText());
arguments.append(QString("--cfg"));
arguments.append(Files::pathToQString(path));
qDebug() << "arguments " << arguments;
// start the progress bar as a "bouncing ball"
progressBar->setMaximum(0);
progressBar->setValue(0);
if (!mImporterInvoker->startProcess(QLatin1String("openmw-iniimporter"), arguments, false))
{
resetProgressBar();
}
}
void Launcher::ImportPage::on_browseButton_clicked()
{
QString iniFile = QFileDialog::getOpenFileName(this, QObject::tr("Select configuration file"), QDir::currentPath(),
QString(tr("Morrowind configuration file (*.ini)")));
if (iniFile.isEmpty())
return;
QFileInfo info(iniFile);
if (!info.exists() || !info.isReadable())
return;
const QString path(QDir::toNativeSeparators(info.absoluteFilePath()));
if (settingsComboBox->findText(path) == -1)
{
settingsComboBox->addItem(path);
settingsComboBox->setCurrentIndex(settingsComboBox->findText(path));
importerButton->setEnabled(true);
}
}
void Launcher::ImportPage::wizardStarted()
{
mMain->hide(); // Hide the launcher
wizardButton->setEnabled(false);
}
void Launcher::ImportPage::wizardFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
if (exitCode != 0 || exitStatus == QProcess::CrashExit)
return qApp->quit();
mMain->reloadSettings();
wizardButton->setEnabled(true);
mMain->show(); // Show the launcher again
}
void Launcher::ImportPage::importerStarted()
{
importerButton->setEnabled(false);
}
void Launcher::ImportPage::importerFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
if (exitCode != 0 || exitStatus == QProcess::CrashExit)
{
resetProgressBar();
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Importer finished"));
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText(tr("Failed to import settings from INI file."));
msgBox.exec();
}
else
{
// indicate progress finished
progressBar->setMaximum(1);
progressBar->setValue(1);
// Importer may have changed settings, so refresh
mMain->reloadSettings();
}
importerButton->setEnabled(true);
}
void Launcher::ImportPage::resetProgressBar()
{
// set progress bar to 0 %
progressBar->reset();
}
void Launcher::ImportPage::saveSettings()
{
mLauncherSettings.setImportContentSetup(addonsCheckBox->isChecked());
mLauncherSettings.setImportFontSetup(fontsCheckBox->isChecked());
}
bool Launcher::ImportPage::loadSettings()
{
addonsCheckBox->setChecked(mLauncherSettings.getImportContentSetup());
fontsCheckBox->setChecked(mLauncherSettings.getImportFontSetup());
return true;
}
| 6,667
|
C++
|
.cpp
| 187
| 29.684492
| 119
| 0.682574
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,137
|
datafilespage.cpp
|
OpenMW_openmw/apps/launcher/datafilespage.cpp
|
#include "datafilespage.hpp"
#include "maindialog.hpp"
#include <QDebug>
#include <QFileDialog>
#include <QList>
#include <QMessageBox>
#include <QPair>
#include <QPushButton>
#include <algorithm>
#include <mutex>
#include <thread>
#include <unordered_set>
#include <apps/launcher/utils/cellnameloader.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/contentselector/model/esmfile.hpp>
#include <components/contentselector/view/contentselector.hpp>
#include <components/config/gamesettings.hpp>
#include <components/config/launchersettings.hpp>
#include <components/bsa/compressedbsafile.hpp>
#include <components/debug/debuglog.hpp>
#include <components/files/qtconversion.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/navmeshtool/protocol.hpp>
#include <components/settings/values.hpp>
#include <components/vfs/bsaarchive.hpp>
#include <components/vfs/qtconversion.hpp>
#include "utils/profilescombobox.hpp"
#include "utils/textinputdialog.hpp"
#include "ui_directorypicker.h"
const char* Launcher::DataFilesPage::mDefaultContentListName = "Default";
namespace
{
void contentSubdirs(const QString& path, QStringList& dirs)
{
static const QStringList fileFilter{
"*.esm",
"*.esp",
"*.bsa",
"*.ba2",
"*.omwgame",
"*.omwaddon",
"*.omwscripts",
};
static const QStringList dirFilter{
"animations",
"bookart",
"fonts",
"icons",
"interface",
"l10n",
"meshes",
"music",
"mygui",
"scripts",
"shaders",
"sound",
"splash",
"strings",
"textures",
"trees",
"video",
};
QDir currentDir(path);
if (!currentDir.entryInfoList(fileFilter, QDir::Files).empty()
|| !currentDir.entryInfoList(dirFilter, QDir::Dirs | QDir::NoDotAndDotDot).empty())
{
dirs.push_back(currentDir.canonicalPath());
return;
}
for (const auto& subdir : currentDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
contentSubdirs(subdir.canonicalFilePath(), dirs);
}
QList<QPair<int, QListWidgetItem*>> sortedSelectedItems(QListWidget* list, bool reverse = false)
{
QList<QPair<int, QListWidgetItem*>> sortedItems;
for (QListWidgetItem* item : list->selectedItems())
sortedItems.append(qMakePair(list->row(item), item));
if (reverse)
std::sort(sortedItems.begin(), sortedItems.end(), [](auto a, auto b) { return a.first > b.first; });
else
std::sort(sortedItems.begin(), sortedItems.end(), [](auto a, auto b) { return a.first < b.first; });
return sortedItems;
}
}
namespace Launcher
{
namespace
{
struct HandleNavMeshToolMessage
{
int mCellsCount;
int mExpectedMaxProgress;
int mMaxProgress;
int mProgress;
HandleNavMeshToolMessage operator()(NavMeshTool::ExpectedCells&& message) const
{
return HandleNavMeshToolMessage{ static_cast<int>(message.mCount), mExpectedMaxProgress,
static_cast<int>(message.mCount) * 100, mProgress };
}
HandleNavMeshToolMessage operator()(NavMeshTool::ProcessedCells&& message) const
{
return HandleNavMeshToolMessage{ mCellsCount, mExpectedMaxProgress, mMaxProgress,
std::max(mProgress, static_cast<int>(message.mCount)) };
}
HandleNavMeshToolMessage operator()(NavMeshTool::ExpectedTiles&& message) const
{
const int expectedMaxProgress = mCellsCount + static_cast<int>(message.mCount);
return HandleNavMeshToolMessage{ mCellsCount, expectedMaxProgress,
std::max(mMaxProgress, expectedMaxProgress), mProgress };
}
HandleNavMeshToolMessage operator()(NavMeshTool::GeneratedTiles&& message) const
{
int progress = mCellsCount + static_cast<int>(message.mCount);
if (mExpectedMaxProgress < mMaxProgress)
progress += static_cast<int>(std::round((mMaxProgress - mExpectedMaxProgress)
* (static_cast<float>(progress) / static_cast<float>(mExpectedMaxProgress))));
return HandleNavMeshToolMessage{ mCellsCount, mExpectedMaxProgress, mMaxProgress,
std::max(mProgress, progress) };
}
};
int getMaxNavMeshDbFileSizeMiB()
{
return Settings::navigator().mMaxNavmeshdbFileSize / (1024 * 1024);
}
}
}
Launcher::DataFilesPage::DataFilesPage(const Files::ConfigurationManager& cfg, Config::GameSettings& gameSettings,
Config::LauncherSettings& launcherSettings, MainDialog* parent)
: QWidget(parent)
, mMainDialog(parent)
, mCfgMgr(cfg)
, mGameSettings(gameSettings)
, mLauncherSettings(launcherSettings)
, mNavMeshToolInvoker(new Process::ProcessInvoker(this))
{
ui.setupUi(this);
setObjectName("DataFilesPage");
mSelector = new ContentSelectorView::ContentSelector(ui.contentSelectorWidget, /*showOMWScripts=*/true);
const QString encoding = mGameSettings.value("encoding", { "win1252" }).value;
mSelector->setEncoding(encoding);
QVector<std::pair<QString, QString>> languages = { { "English", tr("English") }, { "French", tr("French") },
{ "German", tr("German") }, { "Italian", tr("Italian") }, { "Polish", tr("Polish") },
{ "Russian", tr("Russian") }, { "Spanish", tr("Spanish") } };
for (auto lang : languages)
{
mSelector->languageBox()->addItem(lang.second, lang.first);
}
mNewProfileDialog = new TextInputDialog(tr("New Content List"), tr("Content List name:"), this);
mCloneProfileDialog = new TextInputDialog(tr("Clone Content List"), tr("Content List name:"), this);
connect(mNewProfileDialog->lineEdit(), &LineEdit::textChanged, this, &DataFilesPage::updateNewProfileOkButton);
connect(mCloneProfileDialog->lineEdit(), &LineEdit::textChanged, this, &DataFilesPage::updateCloneProfileOkButton);
connect(ui.directoryAddSubdirsButton, &QPushButton::released, this, [this]() { this->addSubdirectories(true); });
connect(ui.directoryInsertButton, &QPushButton::released, this, [this]() { this->addSubdirectories(false); });
connect(ui.directoryUpButton, &QPushButton::released, this,
[this]() { this->moveSources(ui.directoryListWidget, -1); });
connect(ui.directoryDownButton, &QPushButton::released, this,
[this]() { this->moveSources(ui.directoryListWidget, 1); });
connect(ui.directoryRemoveButton, &QPushButton::released, this, &DataFilesPage::removeDirectory);
connect(
ui.archiveUpButton, &QPushButton::released, this, [this]() { this->moveSources(ui.archiveListWidget, -1); });
connect(
ui.archiveDownButton, &QPushButton::released, this, [this]() { this->moveSources(ui.archiveListWidget, 1); });
connect(ui.directoryListWidget->model(), &QAbstractItemModel::rowsMoved, this, &DataFilesPage::sortDirectories);
connect(ui.archiveListWidget->model(), &QAbstractItemModel::rowsMoved, this, &DataFilesPage::sortArchives);
buildView();
loadSettings();
// Connect signal and slot after the settings have been loaded. We only care about the user changing
// the addons and don't want to get signals of the system doing it during startup.
connect(mSelector, &ContentSelectorView::ContentSelector::signalAddonDataChanged, this,
&DataFilesPage::slotAddonDataChanged);
// Call manually to indicate all changes to addon data during startup.
slotAddonDataChanged();
}
void Launcher::DataFilesPage::buildView()
{
QToolButton* refreshButton = mSelector->refreshButton();
// tool buttons
ui.newProfileButton->setToolTip("Create a new Content List");
ui.cloneProfileButton->setToolTip("Clone the current Content List");
ui.deleteProfileButton->setToolTip("Delete an existing Content List");
// combo box
ui.profilesComboBox->addItem(mDefaultContentListName);
ui.profilesComboBox->setPlaceholderText(QString("Select a Content List..."));
ui.profilesComboBox->setCurrentIndex(ui.profilesComboBox->findText(QLatin1String(mDefaultContentListName)));
// Add the actions to the toolbuttons
ui.newProfileButton->setDefaultAction(ui.newProfileAction);
ui.cloneProfileButton->setDefaultAction(ui.cloneProfileAction);
ui.deleteProfileButton->setDefaultAction(ui.deleteProfileAction);
refreshButton->setDefaultAction(ui.refreshDataFilesAction);
// establish connections
connect(ui.profilesComboBox, qOverload<int>(&::ProfilesComboBox::currentIndexChanged), this,
&DataFilesPage::slotProfileChanged);
connect(ui.profilesComboBox, &::ProfilesComboBox::profileRenamed, this, &DataFilesPage::slotProfileRenamed);
connect(ui.profilesComboBox, qOverload<const QString&, const QString&>(&::ProfilesComboBox::signalProfileChanged),
this, &DataFilesPage::slotProfileChangedByUser);
connect(ui.refreshDataFilesAction, &QAction::triggered, this, &DataFilesPage::slotRefreshButtonClicked);
connect(ui.updateNavMeshButton, &QPushButton::clicked, this, &DataFilesPage::startNavMeshTool);
connect(ui.cancelNavMeshButton, &QPushButton::clicked, this, &DataFilesPage::killNavMeshTool);
connect(mNavMeshToolInvoker->getProcess(), &QProcess::readyReadStandardOutput, this,
&DataFilesPage::readNavMeshToolStdout);
connect(mNavMeshToolInvoker->getProcess(), &QProcess::readyReadStandardError, this,
&DataFilesPage::readNavMeshToolStderr);
connect(mNavMeshToolInvoker->getProcess(), qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this,
&DataFilesPage::navMeshToolFinished);
buildArchiveContextMenu();
}
void Launcher::DataFilesPage::buildArchiveContextMenu()
{
connect(ui.archiveListWidget, &QListWidget::customContextMenuRequested, this,
&DataFilesPage::slotShowArchiveContextMenu);
mArchiveContextMenu = new QMenu(ui.archiveListWidget);
mArchiveContextMenu->addAction(tr("&Check Selected"), this, SLOT(slotCheckMultiSelectedItems()));
mArchiveContextMenu->addAction(tr("&Uncheck Selected"), this, SLOT(slotUncheckMultiSelectedItems()));
}
bool Launcher::DataFilesPage::loadSettings()
{
ui.navMeshMaxSizeSpinBox->setValue(getMaxNavMeshDbFileSizeMiB());
QStringList profiles = mLauncherSettings.getContentLists();
QString currentProfile = mLauncherSettings.getCurrentContentListName();
qDebug() << "The current profile is: " << currentProfile;
for (const QString& item : profiles)
addProfile(item, false);
// Hack: also add the current profile
if (!currentProfile.isEmpty())
addProfile(currentProfile, true);
auto language = mLauncherSettings.getLanguage();
for (int i = 0; i < mSelector->languageBox()->count(); ++i)
{
QString languageItem = mSelector->languageBox()->itemData(i).toString();
if (language == languageItem)
{
mSelector->languageBox()->setCurrentIndex(i);
break;
}
}
return true;
}
void Launcher::DataFilesPage::populateFileViews(const QString& contentModelName)
{
mSelector->clearFiles();
ui.archiveListWidget->clear();
ui.directoryListWidget->clear();
QList<Config::SettingValue> directories = mGameSettings.getDataDirs();
QStringList contentModelDirectories = mLauncherSettings.getDataDirectoryList(contentModelName);
if (!contentModelDirectories.isEmpty())
{
directories.erase(std::remove_if(directories.begin(), directories.end(),
[&](const Config::SettingValue& dir) { return mGameSettings.isUserSetting(dir); }),
directories.end());
for (const auto& dir : contentModelDirectories)
directories.push_back(mGameSettings.processPathSettingValue({ dir }));
}
mDataLocal = mGameSettings.getDataLocal();
if (!mDataLocal.isEmpty())
directories.insert(0, { mDataLocal });
const auto& resourcesVfs = mGameSettings.getResourcesVfs();
if (!resourcesVfs.isEmpty())
directories.insert(0, { resourcesVfs });
std::unordered_set<QString> visitedDirectories;
for (const Config::SettingValue& currentDir : directories)
{
if (!visitedDirectories.insert(currentDir.value).second)
continue;
// add new achives files presents in current directory
addArchivesFromDir(currentDir.value);
QStringList tooltip;
// add content files presents in current directory
mSelector->addFiles(currentDir.value, mNewDataDirs.contains(currentDir.value));
// add current directory to list
ui.directoryListWidget->addItem(currentDir.originalRepresentation);
auto row = ui.directoryListWidget->count() - 1;
auto* item = ui.directoryListWidget->item(row);
item->setData(Qt::UserRole, QVariant::fromValue(currentDir));
if (currentDir.value != currentDir.originalRepresentation)
tooltip << tr("Resolved as %1").arg(currentDir.value);
// Display new content with custom formatting
if (mNewDataDirs.contains(currentDir.value))
{
tooltip << tr("Will be added to the current profile");
QFont font = item->font();
font.setBold(true);
font.setItalic(true);
item->setFont(font);
}
// deactivate data-local and resources/vfs: they are always included
// same for ones from non-user config files
if (currentDir.value == mDataLocal || currentDir.value == resourcesVfs
|| !mGameSettings.isUserSetting(currentDir))
{
auto flags = item->flags();
item->setFlags(flags & ~(Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled));
if (currentDir.value == mDataLocal)
tooltip << tr("This is the data-local directory and cannot be disabled");
else if (currentDir.value == resourcesVfs)
tooltip << tr("This directory is part of OpenMW and cannot be disabled");
else
tooltip << tr("This directory is enabled in an openmw.cfg other than the user one");
}
// Add a "data file" icon if the directory contains a content file
if (mSelector->containsDataFiles(currentDir.value))
{
item->setIcon(QIcon(":/images/openmw-plugin.png"));
tooltip << tr("Contains content file(s)");
}
else
{
// Pad to correct vertical alignment
QPixmap pixmap(QSize(200, 200)); // Arbitrary big number, will be scaled down to widget size
pixmap.fill(QColor(0, 0, 0, 0));
auto emptyIcon = QIcon(pixmap);
item->setIcon(emptyIcon);
}
item->setToolTip(tooltip.join('\n'));
}
mSelector->sortFiles();
QList<Config::SettingValue> selectedArchives = mGameSettings.getArchiveList();
QStringList contentModelSelectedArchives = mLauncherSettings.getArchiveList(contentModelName);
if (!contentModelSelectedArchives.isEmpty())
{
selectedArchives.erase(std::remove_if(selectedArchives.begin(), selectedArchives.end(),
[&](const Config::SettingValue& dir) { return mGameSettings.isUserSetting(dir); }),
selectedArchives.end());
for (const auto& dir : contentModelSelectedArchives)
selectedArchives.push_back({ dir });
}
// sort and tick BSA according to profile
int row = 0;
for (const auto& archive : selectedArchives)
{
const auto match = ui.archiveListWidget->findItems(archive.value, Qt::MatchFixedString);
if (match.isEmpty())
continue;
const auto name = match[0]->text();
const auto oldrow = ui.archiveListWidget->row(match[0]);
// entries may be duplicated, e.g. if a content list predated a BSA being added to a non-user config file
if (oldrow < row)
continue;
ui.archiveListWidget->takeItem(oldrow);
ui.archiveListWidget->insertItem(row, name);
ui.archiveListWidget->item(row)->setCheckState(Qt::Checked);
ui.archiveListWidget->item(row)->setData(Qt::UserRole, QVariant::fromValue(archive));
if (!mGameSettings.isUserSetting(archive))
{
auto flags = ui.archiveListWidget->item(row)->flags();
ui.archiveListWidget->item(row)->setFlags(
flags & ~(Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled));
ui.archiveListWidget->item(row)->setToolTip(
tr("This archive is enabled in an openmw.cfg other than the user one"));
}
row++;
}
QStringList nonUserContent;
for (const auto& content : mGameSettings.getContentList())
{
if (!mGameSettings.isUserSetting(content))
nonUserContent.push_back(content.value);
}
mSelector->setNonUserContent(nonUserContent);
mSelector->setProfileContent(mLauncherSettings.getContentListFiles(contentModelName));
}
void Launcher::DataFilesPage::saveSettings(const QString& profile)
{
Settings::navigator().mMaxNavmeshdbFileSize.set(
static_cast<std::uint64_t>(std::max(0, ui.navMeshMaxSizeSpinBox->value())) * 1024 * 1024);
QString profileName = profile;
if (profileName.isEmpty())
profileName = ui.profilesComboBox->currentText();
// retrieve the data paths
auto dirList = selectedDirectoriesPaths();
// retrieve the files selected for the profile
ContentSelectorModel::ContentFileList items = mSelector->selectedFiles();
// set the value of the current profile (not necessarily the profile being saved!)
mLauncherSettings.setCurrentContentListName(ui.profilesComboBox->currentText());
QStringList fileNames;
for (const ContentSelectorModel::EsmFile* item : items)
{
fileNames.append(item->fileName());
}
QStringList dirNames;
for (const auto& dir : dirList)
{
if (mGameSettings.isUserSetting(dir))
dirNames.push_back(dir.originalRepresentation);
}
QStringList archiveNames;
for (const auto& archive : selectedArchivePaths())
{
if (mGameSettings.isUserSetting(archive))
archiveNames.push_back(archive.originalRepresentation);
}
mLauncherSettings.setContentList(profileName, dirNames, archiveNames, fileNames);
mGameSettings.setContentList(dirList, selectedArchivePaths(), fileNames);
QString language(mSelector->languageBox()->currentData().toString());
mLauncherSettings.setLanguage(language);
if (language == QLatin1String("Polish"))
{
mGameSettings.setValue(QLatin1String("encoding"), { "win1250" });
}
else if (language == QLatin1String("Russian"))
{
mGameSettings.setValue(QLatin1String("encoding"), { "win1251" });
}
else
{
mGameSettings.setValue(QLatin1String("encoding"), { "win1252" });
}
}
QList<Config::SettingValue> Launcher::DataFilesPage::selectedDirectoriesPaths() const
{
QList<Config::SettingValue> dirList;
for (int i = 0; i < ui.directoryListWidget->count(); ++i)
{
const QListWidgetItem* item = ui.directoryListWidget->item(i);
if (item->flags() & Qt::ItemIsEnabled)
dirList.append(qvariant_cast<Config::SettingValue>(item->data(Qt::UserRole)));
}
return dirList;
}
QList<Config::SettingValue> Launcher::DataFilesPage::selectedArchivePaths() const
{
QList<Config::SettingValue> archiveList;
for (int i = 0; i < ui.archiveListWidget->count(); ++i)
{
const QListWidgetItem* item = ui.archiveListWidget->item(i);
if (item->checkState() == Qt::Checked)
archiveList.append(qvariant_cast<Config::SettingValue>(item->data(Qt::UserRole)));
}
return archiveList;
}
QStringList Launcher::DataFilesPage::selectedFilePaths() const
{
// retrieve the files selected for the profile
ContentSelectorModel::ContentFileList items = mSelector->selectedFiles();
QStringList filePaths;
for (const ContentSelectorModel::EsmFile* item : items)
if (QFile::exists(item->filePath()))
filePaths.append(item->filePath());
return filePaths;
}
void Launcher::DataFilesPage::removeProfile(const QString& profile)
{
mLauncherSettings.removeContentList(profile);
}
QAbstractItemModel* Launcher::DataFilesPage::profilesModel() const
{
return ui.profilesComboBox->model();
}
int Launcher::DataFilesPage::profilesIndex() const
{
return ui.profilesComboBox->currentIndex();
}
void Launcher::DataFilesPage::setProfile(int index, bool savePrevious)
{
if (index >= -1 && index < ui.profilesComboBox->count())
{
QString previous = mPreviousProfile;
QString current = ui.profilesComboBox->itemText(index);
mPreviousProfile = current;
setProfile(previous, current, savePrevious);
}
}
void Launcher::DataFilesPage::setProfile(const QString& previous, const QString& current, bool savePrevious)
{
// abort if no change (poss. duplicate signal)
if (previous == current)
return;
if (!previous.isEmpty() && savePrevious)
saveSettings(previous);
ui.profilesComboBox->setCurrentProfile(ui.profilesComboBox->findText(current));
mNewDataDirs.clear();
mKnownArchives.clear();
populateFileViews(current);
// save list of "old" bsa to be able to display "new" bsa in a different colour
for (int i = 0; i < ui.archiveListWidget->count(); ++i)
{
auto* item = ui.archiveListWidget->item(i);
mKnownArchives.push_back(item->text());
}
checkForDefaultProfile();
}
void Launcher::DataFilesPage::slotProfileDeleted(const QString& item)
{
removeProfile(item);
}
void Launcher::DataFilesPage::refreshDataFilesView()
{
QString currentProfile = ui.profilesComboBox->currentText();
saveSettings(currentProfile);
populateFileViews(currentProfile);
}
void Launcher::DataFilesPage::slotRefreshButtonClicked()
{
refreshDataFilesView();
}
void Launcher::DataFilesPage::slotProfileChangedByUser(const QString& previous, const QString& current)
{
setProfile(previous, current, true);
emit signalProfileChanged(ui.profilesComboBox->findText(current));
}
void Launcher::DataFilesPage::slotProfileRenamed(const QString& previous, const QString& current)
{
if (previous.isEmpty())
return;
// Save the new profile name
saveSettings();
// Remove the old one
removeProfile(previous);
loadSettings();
}
void Launcher::DataFilesPage::slotProfileChanged(int index)
{
// in case the event was triggered externally
if (ui.profilesComboBox->currentIndex() != index)
ui.profilesComboBox->setCurrentIndex(index);
setProfile(index, true);
}
void Launcher::DataFilesPage::on_newProfileAction_triggered()
{
if (mNewProfileDialog->exec() != QDialog::Accepted)
return;
QString profile = mNewProfileDialog->lineEdit()->text();
if (profile.isEmpty())
return;
saveSettings();
mLauncherSettings.setCurrentContentListName(profile);
addProfile(profile, true);
}
void Launcher::DataFilesPage::addProfile(const QString& profile, bool setAsCurrent)
{
if (profile.isEmpty())
return;
if (ui.profilesComboBox->findText(profile) == -1)
ui.profilesComboBox->addItem(profile);
if (setAsCurrent)
setProfile(ui.profilesComboBox->findText(profile), false);
}
void Launcher::DataFilesPage::on_cloneProfileAction_triggered()
{
if (mCloneProfileDialog->exec() != QDialog::Accepted)
return;
QString profile = mCloneProfileDialog->lineEdit()->text();
if (profile.isEmpty())
return;
const auto& dirList = selectedDirectoriesPaths();
QStringList dirNames;
for (const auto& dir : dirList)
{
if (mGameSettings.isUserSetting(dir))
dirNames.push_back(dir.originalRepresentation);
}
QStringList archiveNames;
for (const auto& archive : selectedArchivePaths())
{
if (mGameSettings.isUserSetting(archive))
archiveNames.push_back(archive.originalRepresentation);
}
mLauncherSettings.setContentList(profile, dirNames, archiveNames, selectedFilePaths());
addProfile(profile, true);
}
void Launcher::DataFilesPage::on_deleteProfileAction_triggered()
{
QString profile = ui.profilesComboBox->currentText();
if (profile.isEmpty())
return;
if (!showDeleteMessageBox(profile))
return;
// this should work since the Default profile can't be deleted and is always index 0
int next = ui.profilesComboBox->currentIndex() - 1;
// changing the profile forces a reload of plugin file views.
ui.profilesComboBox->setCurrentIndex(next);
removeProfile(profile);
ui.profilesComboBox->removeItem(ui.profilesComboBox->findText(profile));
checkForDefaultProfile();
}
void Launcher::DataFilesPage::updateNewProfileOkButton(const QString& text)
{
// We do this here because we need the profiles combobox text
mNewProfileDialog->setOkButtonEnabled(!text.isEmpty() && ui.profilesComboBox->findText(text) == -1);
}
void Launcher::DataFilesPage::updateCloneProfileOkButton(const QString& text)
{
// We do this here because we need the profiles combobox text
mCloneProfileDialog->setOkButtonEnabled(!text.isEmpty() && ui.profilesComboBox->findText(text) == -1);
}
void Launcher::DataFilesPage::addSubdirectories(bool append)
{
int selectedRow = -1;
if (append)
{
selectedRow = ui.directoryListWidget->count();
}
else
{
const QList<QPair<int, QListWidgetItem*>> sortedItems = sortedSelectedItems(ui.directoryListWidget);
if (!sortedItems.isEmpty())
selectedRow = sortedItems.first().first;
}
if (selectedRow == -1)
return;
QString rootPath = QFileDialog::getExistingDirectory(
this, tr("Select Directory"), QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::Option::ReadOnly);
if (rootPath.isEmpty())
return;
const QDir rootDir(rootPath);
rootPath = rootDir.canonicalPath();
QStringList subdirs;
contentSubdirs(rootPath, subdirs);
// Always offer to append the root directory just in case
if (subdirs.isEmpty() || subdirs[0] != rootPath)
subdirs.prepend(rootPath);
else if (subdirs.size() == 1)
{
// We didn't find anything else that looks like a content directory
// Automatically add the directory selected by user
if (!ui.directoryListWidget->findItems(rootPath, Qt::MatchFixedString).isEmpty())
return;
ui.directoryListWidget->insertItem(selectedRow, rootPath);
auto* item = ui.directoryListWidget->item(selectedRow);
item->setData(Qt::UserRole, QVariant::fromValue(Config::SettingValue{ rootPath }));
mNewDataDirs.push_back(rootPath);
refreshDataFilesView();
return;
}
QDialog dialog;
Ui::SelectSubdirs select;
select.setupUi(&dialog);
for (const auto& dir : subdirs)
{
if (!ui.directoryListWidget->findItems(dir, Qt::MatchFixedString).isEmpty())
continue;
const auto lastRow = select.dirListWidget->count();
select.dirListWidget->addItem(dir);
select.dirListWidget->item(lastRow)->setCheckState(Qt::Unchecked);
}
dialog.show();
if (dialog.exec() == QDialog::Rejected)
return;
for (int i = 0; i < select.dirListWidget->count(); ++i)
{
const auto* dir = select.dirListWidget->item(i);
if (dir->checkState() == Qt::Checked)
{
ui.directoryListWidget->insertItem(selectedRow, dir->text());
auto* item = ui.directoryListWidget->item(selectedRow);
item->setData(Qt::UserRole, QVariant::fromValue(Config::SettingValue{ dir->text() }));
mNewDataDirs.push_back(dir->text());
++selectedRow;
}
}
refreshDataFilesView();
}
void Launcher::DataFilesPage::sortDirectories()
{
// Ensure disabled entries (aka default directories) are always at the top.
for (auto i = 1; i < ui.directoryListWidget->count(); ++i)
{
if (!(ui.directoryListWidget->item(i)->flags() & Qt::ItemIsEnabled)
&& (ui.directoryListWidget->item(i - 1)->flags() & Qt::ItemIsEnabled))
{
const auto item = ui.directoryListWidget->takeItem(i);
ui.directoryListWidget->insertItem(i - 1, item);
ui.directoryListWidget->setCurrentRow(i);
}
}
}
void Launcher::DataFilesPage::sortArchives()
{
// Ensure disabled entries (aka ones from non-user config files) are always at the top.
for (auto i = 1; i < ui.archiveListWidget->count(); ++i)
{
if (!(ui.archiveListWidget->item(i)->flags() & Qt::ItemIsEnabled)
&& (ui.archiveListWidget->item(i - 1)->flags() & Qt::ItemIsEnabled))
{
const auto item = ui.archiveListWidget->takeItem(i);
ui.archiveListWidget->insertItem(i - 1, item);
ui.archiveListWidget->setCurrentRow(i);
}
}
}
void Launcher::DataFilesPage::removeDirectory()
{
for (const auto& path : ui.directoryListWidget->selectedItems())
ui.directoryListWidget->takeItem(ui.directoryListWidget->row(path));
refreshDataFilesView();
}
void Launcher::DataFilesPage::slotShowArchiveContextMenu(const QPoint& pos)
{
QPoint globalPos = ui.archiveListWidget->viewport()->mapToGlobal(pos);
mArchiveContextMenu->exec(globalPos);
}
void Launcher::DataFilesPage::setCheckStateForMultiSelectedItems(bool checked)
{
Qt::CheckState checkState = checked ? Qt::Checked : Qt::Unchecked;
for (QListWidgetItem* selectedItem : ui.archiveListWidget->selectedItems())
{
selectedItem->setCheckState(checkState);
}
}
void Launcher::DataFilesPage::slotUncheckMultiSelectedItems()
{
setCheckStateForMultiSelectedItems(false);
}
void Launcher::DataFilesPage::slotCheckMultiSelectedItems()
{
setCheckStateForMultiSelectedItems(true);
}
void Launcher::DataFilesPage::moveSources(QListWidget* sourceList, int step)
{
const QList<QPair<int, QListWidgetItem*>> sortedItems = sortedSelectedItems(sourceList, step > 0);
for (const auto& i : sortedItems)
{
int selectedRow = sourceList->row(i.second);
int newRow = selectedRow + step;
if (selectedRow == -1 || newRow < 0 || newRow > sourceList->count() - 1)
break;
if (!(sourceList->item(newRow)->flags() & Qt::ItemIsEnabled))
break;
const auto item = sourceList->takeItem(selectedRow);
sourceList->insertItem(newRow, item);
sourceList->setCurrentRow(newRow);
}
}
void Launcher::DataFilesPage::addArchive(const QString& name, Qt::CheckState selected, int row)
{
if (row == -1)
row = ui.archiveListWidget->count();
ui.archiveListWidget->insertItem(row, name);
ui.archiveListWidget->item(row)->setCheckState(selected);
ui.archiveListWidget->item(row)->setData(Qt::UserRole, QVariant::fromValue(Config::SettingValue{ name }));
if (mKnownArchives.filter(name).isEmpty()) // XXX why contains doesn't work here ???
{
auto item = ui.archiveListWidget->item(row);
QFont font = item->font();
font.setBold(true);
font.setItalic(true);
item->setFont(font);
}
}
void Launcher::DataFilesPage::addArchivesFromDir(const QString& path)
{
QStringList archiveFilter{ "*.bsa", "*.ba2" };
QDir dir(path);
std::unordered_set<VFS::Path::Normalized, VFS::Path::Hash> archives;
for (int i = 0; i < ui.archiveListWidget->count(); ++i)
archives.insert(VFS::Path::normalizedFromQString(ui.archiveListWidget->item(i)->text()));
for (const auto& fileinfo : dir.entryInfoList(archiveFilter))
{
const auto absPath = fileinfo.absoluteFilePath();
if (Bsa::BSAFile::detectVersion(Files::pathFromQString(absPath)) == Bsa::BsaVersion::Unknown)
continue;
const auto fileName = fileinfo.fileName();
if (archives.insert(VFS::Path::normalizedFromQString(fileName)).second)
addArchive(fileName, Qt::Unchecked);
}
}
void Launcher::DataFilesPage::checkForDefaultProfile()
{
// don't allow deleting "Default" profile
bool success = (ui.profilesComboBox->currentText() != mDefaultContentListName);
ui.deleteProfileAction->setEnabled(success);
ui.profilesComboBox->setEditEnabled(success);
}
bool Launcher::DataFilesPage::showDeleteMessageBox(const QString& text)
{
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Delete Content List"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.setStandardButtons(QMessageBox::Cancel);
msgBox.setText(tr("Are you sure you want to delete <b>%1</b>?").arg(text));
QAbstractButton* deleteButton = msgBox.addButton(tr("Delete"), QMessageBox::ActionRole);
msgBox.exec();
return (msgBox.clickedButton() == deleteButton);
}
void Launcher::DataFilesPage::slotAddonDataChanged()
{
QStringList selectedFiles = selectedFilePaths();
if (previousSelectedFiles != selectedFiles)
{
previousSelectedFiles = selectedFiles;
// Loading cells for core Morrowind + Expansions takes about 0.2 seconds, which is enough to cause a
// barely perceptible UI lag. Splitting into its own thread to alleviate that.
std::thread loadCellsThread(&DataFilesPage::reloadCells, this, selectedFiles);
loadCellsThread.detach();
}
}
// Mutex lock to run reloadCells synchronously.
static std::mutex reloadCellsMutex;
void Launcher::DataFilesPage::reloadCells(QStringList selectedFiles)
{
// Use a mutex lock so that we can prevent two threads from executing the rest of this code at the same time
// Based on https://stackoverflow.com/a/5429695/531762
std::unique_lock<std::mutex> lock(reloadCellsMutex);
// The following code will run only if there is not another thread currently running it
CellNameLoader cellNameLoader;
QSet<QString> set = cellNameLoader.getCellNames(selectedFiles);
QStringList cellNamesList(set.begin(), set.end());
std::sort(cellNamesList.begin(), cellNamesList.end());
emit signalLoadedCellsChanged(cellNamesList);
}
void Launcher::DataFilesPage::startNavMeshTool()
{
mMainDialog->writeSettings();
ui.navMeshLogPlainTextEdit->clear();
ui.navMeshProgressBar->setValue(0);
ui.navMeshProgressBar->setMaximum(1);
ui.navMeshProgressBar->resetFormat();
mNavMeshToolProgress = NavMeshToolProgress{};
QStringList arguments({ "--write-binary-log" });
if (ui.navMeshRemoveUnusedTilesCheckBox->checkState() == Qt::Checked)
arguments.append("--remove-unused-tiles");
if (!mNavMeshToolInvoker->startProcess(QLatin1String("openmw-navmeshtool"), arguments))
return;
ui.cancelNavMeshButton->setEnabled(true);
ui.navMeshProgressBar->setEnabled(true);
}
void Launcher::DataFilesPage::killNavMeshTool()
{
mNavMeshToolInvoker->killProcess();
}
void Launcher::DataFilesPage::readNavMeshToolStderr()
{
updateNavMeshProgress(4096);
}
void Launcher::DataFilesPage::updateNavMeshProgress(int minDataSize)
{
if (!mNavMeshToolProgress.mEnabled)
return;
QProcess& process = *mNavMeshToolInvoker->getProcess();
mNavMeshToolProgress.mMessagesData.append(process.readAllStandardError());
if (mNavMeshToolProgress.mMessagesData.size() < minDataSize)
return;
const std::byte* const begin = reinterpret_cast<const std::byte*>(mNavMeshToolProgress.mMessagesData.constData());
const std::byte* const end = begin + mNavMeshToolProgress.mMessagesData.size();
const std::byte* position = begin;
HandleNavMeshToolMessage handle{
mNavMeshToolProgress.mCellsCount,
mNavMeshToolProgress.mExpectedMaxProgress,
ui.navMeshProgressBar->maximum(),
ui.navMeshProgressBar->value(),
};
try
{
while (true)
{
NavMeshTool::Message message;
const std::byte* const nextPosition = NavMeshTool::deserialize(position, end, message);
if (nextPosition == position)
break;
position = nextPosition;
handle = std::visit(handle, NavMeshTool::decode(message));
}
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Failed to deserialize navmeshtool message: " << e.what();
mNavMeshToolProgress.mEnabled = false;
ui.navMeshProgressBar->setFormat("Failed to update progress: " + QString(e.what()));
}
if (position != begin)
mNavMeshToolProgress.mMessagesData = mNavMeshToolProgress.mMessagesData.mid(position - begin);
mNavMeshToolProgress.mCellsCount = handle.mCellsCount;
mNavMeshToolProgress.mExpectedMaxProgress = handle.mExpectedMaxProgress;
ui.navMeshProgressBar->setMaximum(handle.mMaxProgress);
ui.navMeshProgressBar->setValue(handle.mProgress);
}
void Launcher::DataFilesPage::readNavMeshToolStdout()
{
QProcess& process = *mNavMeshToolInvoker->getProcess();
QByteArray& logData = mNavMeshToolProgress.mLogData;
logData.append(process.readAllStandardOutput());
const int lineEnd = logData.lastIndexOf('\n');
if (lineEnd == -1)
return;
const int size = logData.size() >= lineEnd && logData[lineEnd - 1] == '\r' ? lineEnd - 1 : lineEnd;
ui.navMeshLogPlainTextEdit->appendPlainText(QString::fromUtf8(logData.data(), size));
logData = logData.mid(lineEnd + 1);
}
void Launcher::DataFilesPage::navMeshToolFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
updateNavMeshProgress(0);
ui.navMeshLogPlainTextEdit->appendPlainText(
QString::fromUtf8(mNavMeshToolInvoker->getProcess()->readAllStandardOutput()));
if (exitCode == 0 && exitStatus == QProcess::ExitStatus::NormalExit)
{
ui.navMeshProgressBar->setValue(ui.navMeshProgressBar->maximum());
ui.navMeshProgressBar->resetFormat();
}
ui.cancelNavMeshButton->setEnabled(false);
ui.navMeshProgressBar->setEnabled(false);
}
| 38,650
|
C++
|
.cpp
| 890
| 36.779775
| 119
| 0.69566
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,138
|
settingspage.cpp
|
OpenMW_openmw/apps/launcher/settingspage.cpp
|
#include "settingspage.hpp"
#include <array>
#include <cmath>
#include <string>
#include <QCompleter>
#include <QFileDialog>
#include <QString>
#include <components/config/gamesettings.hpp>
#include <components/settings/values.hpp>
#include "utils/openalutil.hpp"
namespace
{
void loadSettingBool(const Settings::SettingValue<bool>& value, QCheckBox& checkbox)
{
checkbox.setCheckState(value ? Qt::Checked : Qt::Unchecked);
}
void saveSettingBool(const QCheckBox& checkbox, Settings::SettingValue<bool>& value)
{
value.set(checkbox.checkState() == Qt::Checked);
}
void loadSettingInt(const Settings::SettingValue<int>& value, QComboBox& comboBox)
{
comboBox.setCurrentIndex(value);
}
void loadSettingInt(const Settings::SettingValue<DetourNavigator::CollisionShapeType>& value, QComboBox& comboBox)
{
comboBox.setCurrentIndex(static_cast<int>(value.get()));
}
void saveSettingInt(const QComboBox& comboBox, Settings::SettingValue<int>& value)
{
value.set(comboBox.currentIndex());
}
void saveSettingInt(const QComboBox& comboBox, Settings::SettingValue<DetourNavigator::CollisionShapeType>& value)
{
value.set(static_cast<DetourNavigator::CollisionShapeType>(comboBox.currentIndex()));
}
void loadSettingInt(const Settings::SettingValue<int>& value, QSpinBox& spinBox)
{
spinBox.setValue(value);
}
void saveSettingInt(const QSpinBox& spinBox, Settings::SettingValue<int>& value)
{
value.set(spinBox.value());
}
int toIndex(Settings::HrtfMode value)
{
switch (value)
{
case Settings::HrtfMode::Auto:
return 0;
case Settings::HrtfMode::Disable:
return 1;
case Settings::HrtfMode::Enable:
return 2;
}
return 0;
}
}
Launcher::SettingsPage::SettingsPage(Config::GameSettings& gameSettings, QWidget* parent)
: QWidget(parent)
, mGameSettings(gameSettings)
{
setObjectName("SettingsPage");
setupUi(this);
for (const std::string& name : Launcher::enumerateOpenALDevices())
{
audioDeviceSelectorComboBox->addItem(QString::fromStdString(name), QString::fromStdString(name));
}
for (const std::string& name : Launcher::enumerateOpenALDevicesHrtf())
{
hrtfProfileSelectorComboBox->addItem(QString::fromStdString(name), QString::fromStdString(name));
}
loadSettings();
mCellNameCompleter.setModel(&mCellNameCompleterModel);
startDefaultCharacterAtField->setCompleter(&mCellNameCompleter);
}
void Launcher::SettingsPage::loadCellsForAutocomplete(QStringList cellNames)
{
// Update the list of suggestions for the "Start default character at" field
mCellNameCompleterModel.setStringList(cellNames);
mCellNameCompleter.setCompletionMode(QCompleter::PopupCompletion);
mCellNameCompleter.setCaseSensitivity(Qt::CaseSensitivity::CaseInsensitive);
}
void Launcher::SettingsPage::on_skipMenuCheckBox_stateChanged(int state)
{
startDefaultCharacterAtLabel->setEnabled(state == Qt::Checked);
startDefaultCharacterAtField->setEnabled(state == Qt::Checked);
}
void Launcher::SettingsPage::on_runScriptAfterStartupBrowseButton_clicked()
{
QString scriptFile = QFileDialog::getOpenFileName(
this, QObject::tr("Select script file"), QDir::currentPath(), QString(tr("Text file (*.txt)")));
if (scriptFile.isEmpty())
return;
QFileInfo info(scriptFile);
if (!info.exists() || !info.isReadable())
return;
const QString path(QDir::toNativeSeparators(info.absoluteFilePath()));
runScriptAfterStartupField->setText(path);
}
namespace
{
constexpr double CellSizeInUnits = 8192;
double convertToCells(double unitRadius)
{
return unitRadius / CellSizeInUnits;
}
int convertToUnits(double CellGridRadius)
{
return static_cast<int>(CellSizeInUnits * CellGridRadius);
}
}
bool Launcher::SettingsPage::loadSettings()
{
// Game mechanics
{
loadSettingBool(Settings::game().mCanLootDuringDeathAnimation, *canLootDuringDeathAnimationCheckBox);
loadSettingBool(Settings::game().mFollowersAttackOnSight, *followersAttackOnSightCheckBox);
loadSettingBool(Settings::game().mRebalanceSoulGemValues, *rebalanceSoulGemValuesCheckBox);
loadSettingBool(Settings::game().mEnchantedWeaponsAreMagical, *enchantedWeaponsMagicalCheckBox);
loadSettingBool(
Settings::game().mBarterDispositionChangeIsPermanent, *permanentBarterDispositionChangeCheckBox);
loadSettingBool(Settings::game().mClassicReflectedAbsorbSpellsBehavior, *classicReflectedAbsorbSpellsCheckBox);
loadSettingBool(Settings::game().mClassicCalmSpellsBehavior, *classicCalmSpellsCheckBox);
loadSettingBool(
Settings::game().mOnlyAppropriateAmmunitionBypassesResistance, *requireAppropriateAmmunitionCheckBox);
loadSettingBool(Settings::game().mUncappedDamageFatigue, *uncappedDamageFatigueCheckBox);
loadSettingBool(Settings::game().mNormaliseRaceSpeed, *normaliseRaceSpeedCheckBox);
loadSettingBool(Settings::game().mSwimUpwardCorrection, *swimUpwardCorrectionCheckBox);
loadSettingBool(Settings::game().mNPCsAvoidCollisions, *avoidCollisionsCheckBox);
loadSettingInt(Settings::game().mStrengthInfluencesHandToHand, *unarmedFactorsStrengthComboBox);
loadSettingBool(Settings::game().mAlwaysAllowStealingFromKnockedOutActors, *stealingFromKnockedOutCheckBox);
loadSettingBool(Settings::navigator().mEnable, *enableNavigatorCheckBox);
loadSettingInt(Settings::physics().mAsyncNumThreads, *physicsThreadsSpinBox);
loadSettingBool(
Settings::game().mAllowActorsToFollowOverWaterSurface, *allowNPCToFollowOverWaterSurfaceCheckBox);
loadSettingBool(
Settings::game().mUnarmedCreatureAttacksDamageArmor, *unarmedCreatureAttacksDamageArmorCheckBox);
loadSettingInt(Settings::game().mActorCollisionShapeType, *actorCollisonShapeTypeComboBox);
}
// Visuals
{
loadSettingBool(Settings::shaders().mAutoUseObjectNormalMaps, *autoUseObjectNormalMapsCheckBox);
loadSettingBool(Settings::shaders().mAutoUseObjectSpecularMaps, *autoUseObjectSpecularMapsCheckBox);
loadSettingBool(Settings::shaders().mAutoUseTerrainNormalMaps, *autoUseTerrainNormalMapsCheckBox);
loadSettingBool(Settings::shaders().mAutoUseTerrainSpecularMaps, *autoUseTerrainSpecularMapsCheckBox);
loadSettingBool(Settings::shaders().mApplyLightingToEnvironmentMaps, *bumpMapLocalLightingCheckBox);
loadSettingBool(Settings::shaders().mSoftParticles, *softParticlesCheckBox);
loadSettingBool(Settings::shaders().mAntialiasAlphaTest, *antialiasAlphaTestCheckBox);
if (Settings::shaders().mAntialiasAlphaTest == 0)
antialiasAlphaTestCheckBox->setCheckState(Qt::Unchecked);
loadSettingBool(Settings::shaders().mAdjustCoverageForAlphaTest, *adjustCoverageForAlphaTestCheckBox);
loadSettingBool(Settings::shaders().mWeatherParticleOcclusion, *weatherParticleOcclusionCheckBox);
loadSettingBool(Settings::game().mUseMagicItemAnimations, *magicItemAnimationsCheckBox);
connect(animSourcesCheckBox, &QCheckBox::toggled, this, &SettingsPage::slotAnimSourcesToggled);
loadSettingBool(Settings::game().mUseAdditionalAnimSources, *animSourcesCheckBox);
if (animSourcesCheckBox->checkState() != Qt::Unchecked)
{
loadSettingBool(Settings::game().mWeaponSheathing, *weaponSheathingCheckBox);
loadSettingBool(Settings::game().mShieldSheathing, *shieldSheathingCheckBox);
}
loadSettingBool(Settings::game().mSmoothAnimTransitions, *smoothAnimTransitionsCheckBox);
loadSettingBool(Settings::game().mTurnToMovementDirection, *turnToMovementDirectionCheckBox);
loadSettingBool(Settings::game().mSmoothMovement, *smoothMovementCheckBox);
loadSettingBool(Settings::game().mPlayerMovementIgnoresAnimation, *playerMovementIgnoresAnimationCheckBox);
connect(distantLandCheckBox, &QCheckBox::toggled, this, &SettingsPage::slotDistantLandToggled);
bool distantLandEnabled = Settings::terrain().mDistantTerrain && Settings::terrain().mObjectPaging;
distantLandCheckBox->setCheckState(distantLandEnabled ? Qt::Checked : Qt::Unchecked);
slotDistantLandToggled(distantLandEnabled);
loadSettingBool(Settings::terrain().mObjectPagingActiveGrid, *activeGridObjectPagingCheckBox);
viewingDistanceComboBox->setValue(convertToCells(Settings::camera().mViewingDistance));
objectPagingMinSizeComboBox->setValue(Settings::terrain().mObjectPagingMinSize);
loadSettingBool(Settings::game().mDayNightSwitches, *nightDaySwitchesCheckBox);
connect(postprocessEnabledCheckBox, &QCheckBox::toggled, this, &SettingsPage::slotPostProcessToggled);
loadSettingBool(Settings::postProcessing().mEnabled, *postprocessEnabledCheckBox);
loadSettingBool(Settings::postProcessing().mTransparentPostpass, *postprocessTransparentPostpassCheckBox);
postprocessHDRTimeComboBox->setValue(Settings::postProcessing().mAutoExposureSpeed);
connect(skyBlendingCheckBox, &QCheckBox::toggled, this, &SettingsPage::slotSkyBlendingToggled);
loadSettingBool(Settings::fog().mRadialFog, *radialFogCheckBox);
loadSettingBool(Settings::fog().mExponentialFog, *exponentialFogCheckBox);
loadSettingBool(Settings::fog().mSkyBlending, *skyBlendingCheckBox);
skyBlendingStartComboBox->setValue(Settings::fog().mSkyBlendingStart);
loadSettingBool(Settings::shadows().mActorShadows, *actorShadowsCheckBox);
loadSettingBool(Settings::shadows().mPlayerShadows, *playerShadowsCheckBox);
loadSettingBool(Settings::shadows().mTerrainShadows, *terrainShadowsCheckBox);
loadSettingBool(Settings::shadows().mObjectShadows, *objectShadowsCheckBox);
loadSettingBool(Settings::shadows().mEnableIndoorShadows, *indoorShadowsCheckBox);
const auto& boundMethod = Settings::shadows().mComputeSceneBounds.get();
if (boundMethod == "bounds")
shadowComputeSceneBoundsComboBox->setCurrentIndex(0);
else if (boundMethod == "primitives")
shadowComputeSceneBoundsComboBox->setCurrentIndex(1);
else
shadowComputeSceneBoundsComboBox->setCurrentIndex(2);
const int shadowDistLimit = Settings::shadows().mMaximumShadowMapDistance;
if (shadowDistLimit > 0)
{
shadowDistanceCheckBox->setCheckState(Qt::Checked);
shadowDistanceSpinBox->setValue(shadowDistLimit);
shadowDistanceSpinBox->setEnabled(true);
fadeStartSpinBox->setEnabled(true);
}
const float shadowFadeStart = Settings::shadows().mShadowFadeStart;
if (shadowFadeStart != 0)
fadeStartSpinBox->setValue(shadowFadeStart);
const int shadowRes = Settings::shadows().mShadowMapResolution;
int shadowResIndex = shadowResolutionComboBox->findText(QString::number(shadowRes));
if (shadowResIndex != -1)
shadowResolutionComboBox->setCurrentIndex(shadowResIndex);
else
{
shadowResolutionComboBox->addItem(QString::number(shadowRes));
shadowResolutionComboBox->setCurrentIndex(shadowResolutionComboBox->count() - 1);
}
connect(shadowDistanceCheckBox, &QCheckBox::toggled, this, &SettingsPage::slotShadowDistLimitToggled);
int lightingMethod = 1;
switch (Settings::shaders().mLightingMethod)
{
case SceneUtil::LightingMethod::FFP:
lightingMethod = 0;
break;
case SceneUtil::LightingMethod::PerObjectUniform:
lightingMethod = 1;
break;
case SceneUtil::LightingMethod::SingleUBO:
lightingMethod = 2;
break;
}
lightingMethodComboBox->setCurrentIndex(lightingMethod);
}
// Audio
{
const std::string& selectedAudioDevice = Settings::sound().mDevice;
if (selectedAudioDevice.empty() == false)
{
int audioDeviceIndex = audioDeviceSelectorComboBox->findData(QString::fromStdString(selectedAudioDevice));
if (audioDeviceIndex != -1)
{
audioDeviceSelectorComboBox->setCurrentIndex(audioDeviceIndex);
}
}
enableHRTFComboBox->setCurrentIndex(toIndex(Settings::sound().mHrtfEnable));
const std::string& selectedHRTFProfile = Settings::sound().mHrtf;
if (selectedHRTFProfile.empty() == false)
{
int hrtfProfileIndex = hrtfProfileSelectorComboBox->findData(QString::fromStdString(selectedHRTFProfile));
if (hrtfProfileIndex != -1)
{
hrtfProfileSelectorComboBox->setCurrentIndex(hrtfProfileIndex);
}
}
loadSettingBool(Settings::sound().mCameraListener, *cameraListenerCheckBox);
}
// Interface Changes
{
loadSettingBool(Settings::game().mShowEffectDuration, *showEffectDurationCheckBox);
loadSettingBool(Settings::game().mShowEnchantChance, *showEnchantChanceCheckBox);
loadSettingBool(Settings::game().mShowMeleeInfo, *showMeleeInfoCheckBox);
loadSettingBool(Settings::game().mShowProjectileDamage, *showProjectileDamageCheckBox);
loadSettingBool(Settings::gui().mColorTopicEnable, *changeDialogTopicsCheckBox);
showOwnedComboBox->setCurrentIndex(Settings::game().mShowOwned);
loadSettingBool(Settings::gui().mStretchMenuBackground, *stretchBackgroundCheckBox);
loadSettingBool(Settings::map().mAllowZooming, *useZoomOnMapCheckBox);
loadSettingBool(Settings::game().mGraphicHerbalism, *graphicHerbalismCheckBox);
scalingSpinBox->setValue(Settings::gui().mScalingFactor);
fontSizeSpinBox->setValue(Settings::gui().mFontSize);
}
// Bug fixes
{
loadSettingBool(Settings::game().mPreventMerchantEquipping, *preventMerchantEquippingCheckBox);
loadSettingBool(
Settings::game().mTrainersTrainingSkillsBasedOnBaseSkill, *trainersTrainingSkillsBasedOnBaseSkillCheckBox);
}
// Miscellaneous
{
// Saves
loadSettingInt(Settings::saves().mMaxQuicksaves, *maximumQuicksavesComboBox);
// Other Settings
QString screenshotFormatString = QString::fromStdString(Settings::general().mScreenshotFormat).toUpper();
if (screenshotFormatComboBox->findText(screenshotFormatString) == -1)
screenshotFormatComboBox->addItem(screenshotFormatString);
screenshotFormatComboBox->setCurrentIndex(screenshotFormatComboBox->findText(screenshotFormatString));
loadSettingBool(Settings::general().mNotifyOnSavedScreenshot, *notifyOnSavedScreenshotCheckBox);
}
// Testing
{
loadSettingBool(Settings::input().mGrabCursor, *grabCursorCheckBox);
bool skipMenu = mGameSettings.value("skip-menu").value.toInt() == 1;
if (skipMenu)
{
skipMenuCheckBox->setCheckState(Qt::Checked);
}
startDefaultCharacterAtLabel->setEnabled(skipMenu);
startDefaultCharacterAtField->setEnabled(skipMenu);
startDefaultCharacterAtField->setText(mGameSettings.value("start").value);
runScriptAfterStartupField->setText(mGameSettings.value("script-run").value);
}
return true;
}
void Launcher::SettingsPage::saveSettings()
{
// Game mechanics
{
saveSettingBool(*canLootDuringDeathAnimationCheckBox, Settings::game().mCanLootDuringDeathAnimation);
saveSettingBool(*followersAttackOnSightCheckBox, Settings::game().mFollowersAttackOnSight);
saveSettingBool(*rebalanceSoulGemValuesCheckBox, Settings::game().mRebalanceSoulGemValues);
saveSettingBool(*enchantedWeaponsMagicalCheckBox, Settings::game().mEnchantedWeaponsAreMagical);
saveSettingBool(
*permanentBarterDispositionChangeCheckBox, Settings::game().mBarterDispositionChangeIsPermanent);
saveSettingBool(*classicReflectedAbsorbSpellsCheckBox, Settings::game().mClassicReflectedAbsorbSpellsBehavior);
saveSettingBool(*classicCalmSpellsCheckBox, Settings::game().mClassicCalmSpellsBehavior);
saveSettingBool(
*requireAppropriateAmmunitionCheckBox, Settings::game().mOnlyAppropriateAmmunitionBypassesResistance);
saveSettingBool(*uncappedDamageFatigueCheckBox, Settings::game().mUncappedDamageFatigue);
saveSettingBool(*normaliseRaceSpeedCheckBox, Settings::game().mNormaliseRaceSpeed);
saveSettingBool(*swimUpwardCorrectionCheckBox, Settings::game().mSwimUpwardCorrection);
saveSettingBool(*avoidCollisionsCheckBox, Settings::game().mNPCsAvoidCollisions);
saveSettingInt(*unarmedFactorsStrengthComboBox, Settings::game().mStrengthInfluencesHandToHand);
saveSettingBool(*stealingFromKnockedOutCheckBox, Settings::game().mAlwaysAllowStealingFromKnockedOutActors);
saveSettingBool(*enableNavigatorCheckBox, Settings::navigator().mEnable);
saveSettingInt(*physicsThreadsSpinBox, Settings::physics().mAsyncNumThreads);
saveSettingBool(
*allowNPCToFollowOverWaterSurfaceCheckBox, Settings::game().mAllowActorsToFollowOverWaterSurface);
saveSettingBool(
*unarmedCreatureAttacksDamageArmorCheckBox, Settings::game().mUnarmedCreatureAttacksDamageArmor);
saveSettingInt(*actorCollisonShapeTypeComboBox, Settings::game().mActorCollisionShapeType);
}
// Visuals
{
saveSettingBool(*autoUseObjectNormalMapsCheckBox, Settings::shaders().mAutoUseObjectNormalMaps);
saveSettingBool(*autoUseObjectSpecularMapsCheckBox, Settings::shaders().mAutoUseObjectSpecularMaps);
saveSettingBool(*autoUseTerrainNormalMapsCheckBox, Settings::shaders().mAutoUseTerrainNormalMaps);
saveSettingBool(*autoUseTerrainSpecularMapsCheckBox, Settings::shaders().mAutoUseTerrainSpecularMaps);
saveSettingBool(*bumpMapLocalLightingCheckBox, Settings::shaders().mApplyLightingToEnvironmentMaps);
saveSettingBool(*radialFogCheckBox, Settings::fog().mRadialFog);
saveSettingBool(*softParticlesCheckBox, Settings::shaders().mSoftParticles);
saveSettingBool(*antialiasAlphaTestCheckBox, Settings::shaders().mAntialiasAlphaTest);
saveSettingBool(*adjustCoverageForAlphaTestCheckBox, Settings::shaders().mAdjustCoverageForAlphaTest);
saveSettingBool(*weatherParticleOcclusionCheckBox, Settings::shaders().mWeatherParticleOcclusion);
saveSettingBool(*magicItemAnimationsCheckBox, Settings::game().mUseMagicItemAnimations);
saveSettingBool(*animSourcesCheckBox, Settings::game().mUseAdditionalAnimSources);
saveSettingBool(*weaponSheathingCheckBox, Settings::game().mWeaponSheathing);
saveSettingBool(*shieldSheathingCheckBox, Settings::game().mShieldSheathing);
saveSettingBool(*turnToMovementDirectionCheckBox, Settings::game().mTurnToMovementDirection);
saveSettingBool(*smoothAnimTransitionsCheckBox, Settings::game().mSmoothAnimTransitions);
saveSettingBool(*smoothMovementCheckBox, Settings::game().mSmoothMovement);
saveSettingBool(*playerMovementIgnoresAnimationCheckBox, Settings::game().mPlayerMovementIgnoresAnimation);
const bool wantDistantLand = distantLandCheckBox->checkState() == Qt::Checked;
if (wantDistantLand != (Settings::terrain().mDistantTerrain && Settings::terrain().mObjectPaging))
{
Settings::terrain().mDistantTerrain.set(wantDistantLand);
Settings::terrain().mObjectPaging.set(wantDistantLand);
}
saveSettingBool(*activeGridObjectPagingCheckBox, Settings::terrain().mObjectPagingActiveGrid);
Settings::camera().mViewingDistance.set(convertToUnits(viewingDistanceComboBox->value()));
Settings::terrain().mObjectPagingMinSize.set(objectPagingMinSizeComboBox->value());
saveSettingBool(*nightDaySwitchesCheckBox, Settings::game().mDayNightSwitches);
saveSettingBool(*postprocessEnabledCheckBox, Settings::postProcessing().mEnabled);
saveSettingBool(*postprocessTransparentPostpassCheckBox, Settings::postProcessing().mTransparentPostpass);
Settings::postProcessing().mAutoExposureSpeed.set(postprocessHDRTimeComboBox->value());
saveSettingBool(*radialFogCheckBox, Settings::fog().mRadialFog);
saveSettingBool(*exponentialFogCheckBox, Settings::fog().mExponentialFog);
saveSettingBool(*skyBlendingCheckBox, Settings::fog().mSkyBlending);
Settings::fog().mSkyBlendingStart.set(skyBlendingStartComboBox->value());
static constexpr std::array<SceneUtil::LightingMethod, 3> lightingMethodMap = {
SceneUtil::LightingMethod::FFP,
SceneUtil::LightingMethod::PerObjectUniform,
SceneUtil::LightingMethod::SingleUBO,
};
Settings::shaders().mLightingMethod.set(lightingMethodMap[lightingMethodComboBox->currentIndex()]);
const int cShadowDist
= shadowDistanceCheckBox->checkState() != Qt::Unchecked ? shadowDistanceSpinBox->value() : 0;
Settings::shadows().mMaximumShadowMapDistance.set(cShadowDist);
const float cFadeStart = fadeStartSpinBox->value();
if (cShadowDist > 0)
Settings::shadows().mShadowFadeStart.set(cFadeStart);
const bool cActorShadows = actorShadowsCheckBox->checkState() != Qt::Unchecked;
const bool cObjectShadows = objectShadowsCheckBox->checkState() != Qt::Unchecked;
const bool cTerrainShadows = terrainShadowsCheckBox->checkState() != Qt::Unchecked;
const bool cPlayerShadows = playerShadowsCheckBox->checkState() != Qt::Unchecked;
if (cActorShadows || cObjectShadows || cTerrainShadows || cPlayerShadows)
{
Settings::shadows().mEnableShadows.set(true);
Settings::shadows().mActorShadows.set(cActorShadows);
Settings::shadows().mPlayerShadows.set(cPlayerShadows);
Settings::shadows().mObjectShadows.set(cObjectShadows);
Settings::shadows().mTerrainShadows.set(cTerrainShadows);
}
else
{
Settings::shadows().mEnableShadows.set(false);
Settings::shadows().mActorShadows.set(false);
Settings::shadows().mPlayerShadows.set(false);
Settings::shadows().mObjectShadows.set(false);
Settings::shadows().mTerrainShadows.set(false);
}
Settings::shadows().mEnableIndoorShadows.set(indoorShadowsCheckBox->checkState() != Qt::Unchecked);
Settings::shadows().mShadowMapResolution.set(shadowResolutionComboBox->currentText().toInt());
auto index = shadowComputeSceneBoundsComboBox->currentIndex();
if (index == 0)
Settings::shadows().mComputeSceneBounds.set("bounds");
else if (index == 1)
Settings::shadows().mComputeSceneBounds.set("primitives");
else
Settings::shadows().mComputeSceneBounds.set("none");
}
// Audio
{
if (audioDeviceSelectorComboBox->currentIndex() != 0)
Settings::sound().mDevice.set(audioDeviceSelectorComboBox->currentText().toStdString());
else
Settings::sound().mDevice.set({});
static constexpr std::array<Settings::HrtfMode, 3> hrtfModes{
Settings::HrtfMode::Auto,
Settings::HrtfMode::Disable,
Settings::HrtfMode::Enable,
};
Settings::sound().mHrtfEnable.set(hrtfModes[enableHRTFComboBox->currentIndex()]);
if (hrtfProfileSelectorComboBox->currentIndex() != 0)
Settings::sound().mHrtf.set(hrtfProfileSelectorComboBox->currentText().toStdString());
else
Settings::sound().mHrtf.set({});
const bool cCameraListener = cameraListenerCheckBox->checkState() != Qt::Unchecked;
Settings::sound().mCameraListener.set(cCameraListener);
}
// Interface Changes
{
saveSettingBool(*showEffectDurationCheckBox, Settings::game().mShowEffectDuration);
saveSettingBool(*showEnchantChanceCheckBox, Settings::game().mShowEnchantChance);
saveSettingBool(*showMeleeInfoCheckBox, Settings::game().mShowMeleeInfo);
saveSettingBool(*showProjectileDamageCheckBox, Settings::game().mShowProjectileDamage);
saveSettingBool(*changeDialogTopicsCheckBox, Settings::gui().mColorTopicEnable);
saveSettingInt(*showOwnedComboBox, Settings::game().mShowOwned);
saveSettingBool(*stretchBackgroundCheckBox, Settings::gui().mStretchMenuBackground);
saveSettingBool(*useZoomOnMapCheckBox, Settings::map().mAllowZooming);
saveSettingBool(*graphicHerbalismCheckBox, Settings::game().mGraphicHerbalism);
Settings::gui().mScalingFactor.set(scalingSpinBox->value());
Settings::gui().mFontSize.set(fontSizeSpinBox->value());
}
// Bug fixes
{
saveSettingBool(*preventMerchantEquippingCheckBox, Settings::game().mPreventMerchantEquipping);
saveSettingBool(
*trainersTrainingSkillsBasedOnBaseSkillCheckBox, Settings::game().mTrainersTrainingSkillsBasedOnBaseSkill);
}
// Miscellaneous
{
// Saves Settings
saveSettingInt(*maximumQuicksavesComboBox, Settings::saves().mMaxQuicksaves);
// Other Settings
Settings::general().mScreenshotFormat.set(screenshotFormatComboBox->currentText().toLower().toStdString());
saveSettingBool(*notifyOnSavedScreenshotCheckBox, Settings::general().mNotifyOnSavedScreenshot);
}
// Testing
{
saveSettingBool(*grabCursorCheckBox, Settings::input().mGrabCursor);
int skipMenu = skipMenuCheckBox->checkState() == Qt::Checked;
if (skipMenu != mGameSettings.value("skip-menu").value.toInt())
mGameSettings.setValue("skip-menu", { QString::number(skipMenu) });
QString startCell = startDefaultCharacterAtField->text();
if (startCell != mGameSettings.value("start").value)
{
mGameSettings.setValue("start", { startCell });
}
QString scriptRun = runScriptAfterStartupField->text();
if (scriptRun != mGameSettings.value("script-run").value)
mGameSettings.setValue("script-run", { scriptRun });
}
}
void Launcher::SettingsPage::slotLoadedCellsChanged(QStringList cellNames)
{
loadCellsForAutocomplete(std::move(cellNames));
}
void Launcher::SettingsPage::slotAnimSourcesToggled(bool checked)
{
weaponSheathingCheckBox->setEnabled(checked);
shieldSheathingCheckBox->setEnabled(checked);
if (!checked)
{
weaponSheathingCheckBox->setCheckState(Qt::Unchecked);
shieldSheathingCheckBox->setCheckState(Qt::Unchecked);
}
}
void Launcher::SettingsPage::slotPostProcessToggled(bool checked)
{
postprocessTransparentPostpassCheckBox->setEnabled(checked);
postprocessHDRTimeComboBox->setEnabled(checked);
postprocessHDRTimeLabel->setEnabled(checked);
}
void Launcher::SettingsPage::slotSkyBlendingToggled(bool checked)
{
skyBlendingStartComboBox->setEnabled(checked);
skyBlendingStartLabel->setEnabled(checked);
}
void Launcher::SettingsPage::slotShadowDistLimitToggled(bool checked)
{
shadowDistanceSpinBox->setEnabled(checked);
fadeStartSpinBox->setEnabled(checked);
}
void Launcher::SettingsPage::slotDistantLandToggled(bool checked)
{
activeGridObjectPagingCheckBox->setEnabled(checked);
objectPagingMinSizeComboBox->setEnabled(checked);
}
| 27,864
|
C++
|
.cpp
| 504
| 47.156746
| 119
| 0.737236
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,139
|
maindialog.cpp
|
OpenMW_openmw/apps/launcher/maindialog.cpp
|
#include "maindialog.hpp"
#include <QCloseEvent>
#include <QDir>
#include <QMessageBox>
#include <QStringList>
#include <QTime>
#include <components/debug/debugging.hpp>
#include <components/debug/debuglog.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/files/conversion.hpp>
#include <components/files/qtconfigpath.hpp>
#include <components/files/qtconversion.hpp>
#include <components/misc/helpviewer.hpp>
#include <components/misc/utf8qtextstream.hpp>
#include <components/settings/settings.hpp>
#include <components/version/version.hpp>
#include "datafilespage.hpp"
#include "graphicspage.hpp"
#include "importpage.hpp"
#include "settingspage.hpp"
namespace
{
constexpr const char* toolBarStyle = "QToolBar { border: 0px; } QToolButton { min-width: 70px }";
}
using namespace Process;
void cfgError(const QString& title, const QString& msg)
{
QMessageBox msgBox;
msgBox.setWindowTitle(title);
msgBox.setIcon(QMessageBox::Critical);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setText(msg);
msgBox.exec();
}
Launcher::MainDialog::MainDialog(const Files::ConfigurationManager& configurationManager, QWidget* parent)
: QMainWindow(parent)
, mCfgMgr(configurationManager)
, mGameSettings(mCfgMgr)
{
setupUi(this);
mGameInvoker = new ProcessInvoker();
mWizardInvoker = new ProcessInvoker();
connect(mWizardInvoker->getProcess(), &QProcess::started, this, &MainDialog::wizardStarted);
connect(mWizardInvoker->getProcess(), qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this,
&MainDialog::wizardFinished);
buttonBox->button(QDialogButtonBox::Close)->setText(tr("Close"));
buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Launch OpenMW"));
buttonBox->button(QDialogButtonBox::Help)->setText(tr("Help"));
buttonBox->button(QDialogButtonBox::Ok)->setMinimumWidth(160);
// Order of buttons can be different on different setups,
// so make sure that the Play button has a focus by default.
buttonBox->button(QDialogButtonBox::Ok)->setFocus();
connect(buttonBox, &QDialogButtonBox::rejected, this, &MainDialog::close);
connect(buttonBox, &QDialogButtonBox::accepted, this, &MainDialog::play);
connect(buttonBox, &QDialogButtonBox::helpRequested, this, &MainDialog::help);
// Remove what's this? button
setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);
createIcons();
QWidget* spacer = new QWidget();
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
toolBar->addWidget(spacer);
QLabel* logo = new QLabel(this);
logo->setPixmap(QIcon(":/images/openmw-header.png").pixmap(QSize(294, 64)));
toolBar->addWidget(logo);
toolBar->setStyleSheet(toolBarStyle);
}
Launcher::MainDialog::~MainDialog()
{
delete mGameInvoker;
delete mWizardInvoker;
}
bool Launcher::MainDialog::event(QEvent* event)
{
// Apply style sheet again if style was changed
if (event->type() == QEvent::PaletteChange)
{
if (toolBar != nullptr)
toolBar->setStyleSheet(toolBarStyle);
}
return QMainWindow::event(event);
}
void Launcher::MainDialog::createIcons()
{
if (!QIcon::hasThemeIcon("document-new"))
QIcon::setThemeName("fallback");
connect(dataAction, &QAction::triggered, this, &MainDialog::enableDataPage);
connect(graphicsAction, &QAction::triggered, this, &MainDialog::enableGraphicsPage);
connect(settingsAction, &QAction::triggered, this, &MainDialog::enableSettingsPage);
connect(importAction, &QAction::triggered, this, &MainDialog::enableImportPage);
}
void Launcher::MainDialog::createPages()
{
// Avoid creating the widgets twice
if (pagesWidget->count() != 0)
return;
mDataFilesPage = new DataFilesPage(mCfgMgr, mGameSettings, mLauncherSettings, this);
mGraphicsPage = new GraphicsPage(this);
mImportPage = new ImportPage(mCfgMgr, mGameSettings, mLauncherSettings, this);
mSettingsPage = new SettingsPage(mGameSettings, this);
// Add the pages to the stacked widget
pagesWidget->addWidget(mDataFilesPage);
pagesWidget->addWidget(mGraphicsPage);
pagesWidget->addWidget(mSettingsPage);
pagesWidget->addWidget(mImportPage);
// Select the first page
dataAction->setChecked(true);
// Using Qt::QueuedConnection because signal is emitted in a subthread and slot is in the main thread
connect(mDataFilesPage, &DataFilesPage::signalLoadedCellsChanged, mSettingsPage,
&SettingsPage::slotLoadedCellsChanged, Qt::QueuedConnection);
}
Launcher::FirstRunDialogResult Launcher::MainDialog::showFirstRunDialog()
{
if (!setupLauncherSettings())
return FirstRunDialogResultFailure;
// Dialog wizard and setup will fail if the config directory does not already exist
const auto& userConfigDir = mCfgMgr.getUserConfigPath();
if (!exists(userConfigDir))
{
std::error_code ec;
if (!create_directories(userConfigDir, ec))
{
cfgError(tr("Error creating OpenMW configuration directory: code %0").arg(ec.value()),
tr("<br><b>Could not create directory %0</b><br><br>"
"%1<br>")
.arg(Files::pathToQString(userConfigDir))
.arg(QString(ec.message().c_str())));
return FirstRunDialogResultFailure;
}
}
if (mLauncherSettings.isFirstRun())
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("First run"));
msgBox.setIcon(QMessageBox::Question);
msgBox.setStandardButtons(QMessageBox::NoButton);
msgBox.setText(
tr("<html><head/><body><p><b>Welcome to OpenMW!</b></p>"
"<p>It is recommended to run the Installation Wizard.</p>"
"<p>The Wizard will let you select an existing Morrowind installation, "
"or install Morrowind for OpenMW to use.</p></body></html>"));
QAbstractButton* wizardButton
= msgBox.addButton(tr("Run &Installation Wizard"), QMessageBox::AcceptRole); // ActionRole doesn't work?!
QAbstractButton* skipButton = msgBox.addButton(tr("Skip"), QMessageBox::RejectRole);
msgBox.exec();
if (msgBox.clickedButton() == wizardButton)
{
if (mWizardInvoker->startProcess(QLatin1String("openmw-wizard"), false))
return FirstRunDialogResultWizard;
}
else if (msgBox.clickedButton() == skipButton)
{
// Don't bother setting up absent game data.
if (setup())
return FirstRunDialogResultContinue;
}
return FirstRunDialogResultFailure;
}
if (!setup() || !setupGameData())
{
return FirstRunDialogResultFailure;
}
return FirstRunDialogResultContinue;
}
void Launcher::MainDialog::setVersionLabel()
{
// Add version information to bottom of the window
QString revision(QString::fromUtf8(Version::getCommitHash().data(), Version::getCommitHash().size()));
QString tag(QString::fromUtf8(Version::getTagHash().data(), Version::getTagHash().size()));
versionLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
if (!Version::getVersion().empty() && (revision.isEmpty() || revision == tag))
versionLabel->setText(
tr("OpenMW %1 release").arg(QString::fromUtf8(Version::getVersion().data(), Version::getVersion().size())));
else
versionLabel->setText(tr("OpenMW development (%1)").arg(revision.left(10)));
// Add the compile date and time
auto compileDate = QLocale(QLocale::C).toDate(QString(__DATE__).simplified(), QLatin1String("MMM d yyyy"));
auto compileTime = QLocale(QLocale::C).toTime(QString(__TIME__).simplified(), QLatin1String("hh:mm:ss"));
versionLabel->setToolTip(tr("Compiled on %1 %2")
.arg(QLocale::system().toString(compileDate, QLocale::LongFormat),
QLocale::system().toString(compileTime, QLocale::ShortFormat)));
}
bool Launcher::MainDialog::setup()
{
if (!setupGameSettings())
return false;
setVersionLabel();
mLauncherSettings.setContentList(mGameSettings);
if (!setupGraphicsSettings())
return false;
// Now create the pages as they need the settings
createPages();
// Call this so we can exit on SDL errors before mainwindow is shown
if (!mGraphicsPage->loadSettings())
return false;
loadSettings();
return true;
}
bool Launcher::MainDialog::reloadSettings()
{
if (!setupLauncherSettings())
return false;
if (!setupGameSettings())
return false;
mLauncherSettings.setContentList(mGameSettings);
if (!setupGraphicsSettings())
return false;
if (!mImportPage->loadSettings())
return false;
if (!mDataFilesPage->loadSettings())
return false;
if (!mGraphicsPage->loadSettings())
return false;
if (!mSettingsPage->loadSettings())
return false;
return true;
}
void Launcher::MainDialog::enableDataPage()
{
pagesWidget->setCurrentIndex(0);
mImportPage->resetProgressBar();
dataAction->setChecked(true);
graphicsAction->setChecked(false);
importAction->setChecked(false);
settingsAction->setChecked(false);
}
void Launcher::MainDialog::enableGraphicsPage()
{
pagesWidget->setCurrentIndex(1);
mImportPage->resetProgressBar();
dataAction->setChecked(false);
graphicsAction->setChecked(true);
settingsAction->setChecked(false);
importAction->setChecked(false);
}
void Launcher::MainDialog::enableSettingsPage()
{
pagesWidget->setCurrentIndex(2);
mImportPage->resetProgressBar();
dataAction->setChecked(false);
graphicsAction->setChecked(false);
settingsAction->setChecked(true);
importAction->setChecked(false);
}
void Launcher::MainDialog::enableImportPage()
{
pagesWidget->setCurrentIndex(3);
mImportPage->resetProgressBar();
dataAction->setChecked(false);
graphicsAction->setChecked(false);
settingsAction->setChecked(false);
importAction->setChecked(true);
}
bool Launcher::MainDialog::setupLauncherSettings()
{
mLauncherSettings.clear();
const QString path
= Files::pathToQString(mCfgMgr.getUserConfigPath() / Config::LauncherSettings::sLauncherConfigFileName);
if (!QFile::exists(path))
return true;
Log(Debug::Info) << "Loading config file: " << path.toUtf8().constData();
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
cfgError(tr("Error opening OpenMW configuration file"),
tr("<br><b>Could not open %0 for reading:</b><br><br>%1<br><br>"
"Please make sure you have the right permissions "
"and try again.<br>")
.arg(file.fileName())
.arg(file.errorString()));
return false;
}
QTextStream stream(&file);
Misc::ensureUtf8Encoding(stream);
mLauncherSettings.readFile(stream);
return true;
}
bool Launcher::MainDialog::setupGameSettings()
{
mGameSettings.clear();
QFile file;
auto loadFile = [&](const QString& path, bool (Config::GameSettings::*reader)(QTextStream&, const QString&, bool),
bool ignoreContent = false) -> std::optional<bool> {
file.setFileName(path);
if (file.exists())
{
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
cfgError(tr("Error opening OpenMW configuration file"),
tr("<br><b>Could not open %0 for reading</b><br><br>"
"Please make sure you have the right permissions "
"and try again.<br>")
.arg(file.fileName()));
return {};
}
QTextStream stream(&file);
Misc::ensureUtf8Encoding(stream);
(mGameSettings.*reader)(stream, QFileInfo(path).dir().path(), ignoreContent);
file.close();
return true;
}
return false;
};
// Load the user config file first, separately
// So we can write it properly, uncontaminated
if (!loadFile(Files::getUserConfigPathQString(mCfgMgr), &Config::GameSettings::readUserFile))
return false;
for (const auto& path : Files::getActiveConfigPathsQString(mCfgMgr))
{
Log(Debug::Info) << "Loading config file: " << path.toUtf8().constData();
if (!loadFile(path, &Config::GameSettings::readFile))
return false;
}
return true;
}
bool Launcher::MainDialog::setupGameData()
{
bool foundData = false;
// Check if the paths actually contain data files
for (const auto& path3 : mGameSettings.getDataDirs())
{
QDir dir(path3.value);
QStringList filters;
filters << "*.esp"
<< "*.esm"
<< "*.omwgame"
<< "*.omwaddon";
if (!dir.entryList(filters).isEmpty())
{
foundData = true;
break;
}
}
if (!foundData)
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Error detecting Morrowind installation"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.setStandardButtons(QMessageBox::NoButton);
msgBox.setText(
tr("<br><b>Could not find the Data Files location</b><br><br>"
"The directory containing the data files was not found."));
QAbstractButton* wizardButton = msgBox.addButton(tr("Run &Installation Wizard..."), QMessageBox::ActionRole);
QAbstractButton* skipButton = msgBox.addButton(tr("Skip"), QMessageBox::RejectRole);
Q_UNUSED(skipButton); // Suppress compiler unused warning
msgBox.exec();
if (msgBox.clickedButton() == wizardButton)
{
if (!mWizardInvoker->startProcess(QLatin1String("openmw-wizard"), false))
return false;
}
}
return true;
}
bool Launcher::MainDialog::setupGraphicsSettings()
{
Settings::Manager::clear(); // Ensure to clear previous settings in case we had already loaded settings.
try
{
Settings::Manager::load(mCfgMgr);
return true;
}
catch (std::exception& e)
{
cfgError(tr("Error reading OpenMW configuration files"),
tr("<br>The problem may be due to an incomplete installation of OpenMW.<br>"
"Reinstalling OpenMW may resolve the problem.<br>")
+ e.what());
return false;
}
}
void Launcher::MainDialog::loadSettings()
{
const auto& mainWindow = mLauncherSettings.getMainWindow();
resize(mainWindow.mWidth, mainWindow.mHeight);
move(mainWindow.mPosX, mainWindow.mPosY);
}
void Launcher::MainDialog::saveSettings()
{
mLauncherSettings.setMainWindow(Config::LauncherSettings::MainWindow{
.mWidth = width(),
.mHeight = height(),
.mPosX = pos().x(),
.mPosY = pos().y(),
});
mLauncherSettings.resetFirstRun();
}
bool Launcher::MainDialog::writeSettings()
{
// Now write all config files
saveSettings();
mDataFilesPage->saveSettings();
mGraphicsPage->saveSettings();
mImportPage->saveSettings();
mSettingsPage->saveSettings();
const auto& userPath = mCfgMgr.getUserConfigPath();
if (!exists(userPath))
{
std::error_code ec;
if (!create_directories(userPath, ec))
{
cfgError(tr("Error creating OpenMW configuration directory: code %0").arg(ec.value()),
tr("<br><b>Could not create directory %0</b><br><br>"
"%1<br>")
.arg(Files::pathToQString(userPath))
.arg(QString(ec.message().c_str())));
return false;
}
}
// Game settings
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
QFile file(userPath / Files::openmwCfgFile);
#else
QFile file(Files::getUserConfigPathQString(mCfgMgr));
#endif
if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
{
// File cannot be opened or created
cfgError(tr("Error writing OpenMW configuration file"),
tr("<br><b>Could not open or create %0 for writing</b><br><br>"
"Please make sure you have the right permissions "
"and try again.<br>")
.arg(file.fileName()));
return false;
}
mGameSettings.writeFileWithComments(file);
file.close();
// Graphics settings
const auto settingsPath = mCfgMgr.getUserConfigPath() / "settings.cfg";
try
{
Settings::Manager::saveUser(settingsPath);
}
catch (std::exception& e)
{
std::string msg = "<br><b>Error writing settings.cfg</b><br><br>" + Files::pathToUnicodeString(settingsPath)
+ "<br><br>" + e.what();
cfgError(tr("Error writing user settings file"), tr(msg.c_str()));
return false;
}
// Launcher settings
file.setFileName(Files::pathToQString(userPath / Config::LauncherSettings::sLauncherConfigFileName));
if (!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate))
{
// File cannot be opened or created
cfgError(tr("Error writing Launcher configuration file"),
tr("<br><b>Could not open or create %0 for writing</b><br><br>"
"Please make sure you have the right permissions "
"and try again.<br>")
.arg(file.fileName()));
return false;
}
QTextStream stream(&file);
stream.setDevice(&file);
Misc::ensureUtf8Encoding(stream);
mLauncherSettings.writeFile(stream);
file.close();
return true;
}
void Launcher::MainDialog::closeEvent(QCloseEvent* event)
{
writeSettings();
event->accept();
}
void Launcher::MainDialog::wizardStarted()
{
hide();
}
void Launcher::MainDialog::wizardFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
if (exitCode != 0 || exitStatus == QProcess::CrashExit)
return qApp->quit();
// HACK: Ensure the pages are created, else segfault
setup();
if (setupGameData() && reloadSettings())
show();
}
void Launcher::MainDialog::play()
{
if (!writeSettings())
return qApp->quit();
if (!mGameSettings.hasMaster())
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("No game file selected"));
msgBox.setIcon(QMessageBox::Warning);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setText(
tr("<br><b>You do not have a game file selected.</b><br><br>"
"OpenMW will not start without a game file selected.<br>"));
msgBox.exec();
return;
}
// Launch the game detached
if (mGameInvoker->startProcess(QLatin1String("openmw"), true))
return qApp->quit();
}
void Launcher::MainDialog::help()
{
Misc::HelpViewer::openHelp("reference/index.html");
}
| 19,084
|
C++
|
.cpp
| 500
| 31.38
| 120
| 0.665404
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,140
|
graphicspage.cpp
|
OpenMW_openmw/apps/launcher/graphicspage.cpp
|
#include "graphicspage.hpp"
#include "sdlinit.hpp"
#include <components/misc/display.hpp>
#include <components/settings/values.hpp>
#include <QMessageBox>
#include <QScreen>
#ifdef MAC_OS_X_VERSION_MIN_REQUIRED
#undef MAC_OS_X_VERSION_MIN_REQUIRED
// We need to do this because of Qt: https://bugreports.qt-project.org/browse/QTBUG-22154
#define MAC_OS_X_VERSION_MIN_REQUIRED __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__
#endif // MAC_OS_X_VERSION_MIN_REQUIRED
#include <SDL_video.h>
#include <array>
Launcher::GraphicsPage::GraphicsPage(QWidget* parent)
: QWidget(parent)
{
setObjectName("GraphicsPage");
setupUi(this);
// Set the maximum res we can set in windowed mode
QRect res = getMaximumResolution();
customWidthSpinBox->setMaximum(res.width());
customHeightSpinBox->setMaximum(res.height());
connect(windowModeComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this,
&GraphicsPage::slotFullScreenChanged);
connect(standardRadioButton, &QRadioButton::toggled, this, &GraphicsPage::slotStandardToggled);
connect(screenComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &GraphicsPage::screenChanged);
connect(framerateLimitCheckBox, &QCheckBox::toggled, this, &GraphicsPage::slotFramerateLimitToggled);
}
bool Launcher::GraphicsPage::setupSDL()
{
bool sdlConnectSuccessful = initSDL();
if (!sdlConnectSuccessful)
{
return false;
}
int displays = SDL_GetNumVideoDisplays();
if (displays < 0)
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Error receiving number of screens"));
msgBox.setIcon(QMessageBox::Critical);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setText(
tr("<br><b>SDL_GetNumVideoDisplays failed:</b><br><br>") + QString::fromUtf8(SDL_GetError()) + "<br>");
msgBox.exec();
return false;
}
screenComboBox->clear();
mResolutionsPerScreen.clear();
for (int i = 0; i < displays; i++)
{
mResolutionsPerScreen.append(getAvailableResolutions(i));
screenComboBox->addItem(QString(tr("Screen ")) + QString::number(i + 1));
}
screenChanged(0);
// Disconnect from SDL processes
quitSDL();
return true;
}
bool Launcher::GraphicsPage::loadSettings()
{
if (!setupSDL())
return false;
// Visuals
const int vsync = Settings::video().mVsyncMode;
vSyncComboBox->setCurrentIndex(vsync);
const Settings::WindowMode windowMode = Settings::video().mWindowMode;
windowModeComboBox->setCurrentIndex(static_cast<int>(windowMode));
handleWindowModeChange(windowMode);
if (Settings::video().mWindowBorder)
windowBorderCheckBox->setCheckState(Qt::Checked);
// aaValue is the actual value (0, 1, 2, 4, 8, 16)
const int aaValue = Settings::video().mAntialiasing;
// aaIndex is the index into the allowed values in the pull down.
const int aaIndex = antiAliasingComboBox->findText(QString::number(aaValue));
if (aaIndex != -1)
antiAliasingComboBox->setCurrentIndex(aaIndex);
const int width = Settings::video().mResolutionX;
const int height = Settings::video().mResolutionY;
QString resolution = QString::number(width) + QString(" × ") + QString::number(height);
screenComboBox->setCurrentIndex(Settings::video().mScreen);
int resIndex = resolutionComboBox->findText(resolution, Qt::MatchStartsWith);
if (resIndex != -1)
{
standardRadioButton->toggle();
resolutionComboBox->setCurrentIndex(resIndex);
}
else
{
customRadioButton->toggle();
customWidthSpinBox->setValue(width);
customHeightSpinBox->setValue(height);
}
const float fpsLimit = Settings::video().mFramerateLimit;
if (fpsLimit != 0)
{
framerateLimitCheckBox->setCheckState(Qt::Checked);
framerateLimitSpinBox->setValue(fpsLimit);
}
return true;
}
void Launcher::GraphicsPage::saveSettings()
{
// Visuals
Settings::video().mVsyncMode.set(static_cast<SDLUtil::VSyncMode>(vSyncComboBox->currentIndex()));
Settings::video().mWindowMode.set(static_cast<Settings::WindowMode>(windowModeComboBox->currentIndex()));
Settings::video().mWindowBorder.set(windowBorderCheckBox->checkState() == Qt::Checked);
Settings::video().mAntialiasing.set(antiAliasingComboBox->currentText().toInt());
int cWidth = 0;
int cHeight = 0;
if (standardRadioButton->isChecked())
{
QRegularExpression resolutionRe("^(\\d+) × (\\d+)");
QRegularExpressionMatch match = resolutionRe.match(resolutionComboBox->currentText().simplified());
if (match.hasMatch())
{
cWidth = match.captured(1).toInt();
cHeight = match.captured(2).toInt();
}
}
else
{
cWidth = customWidthSpinBox->value();
cHeight = customHeightSpinBox->value();
}
Settings::video().mResolutionX.set(cWidth);
Settings::video().mResolutionY.set(cHeight);
Settings::video().mScreen.set(screenComboBox->currentIndex());
if (framerateLimitCheckBox->checkState() != Qt::Unchecked)
{
Settings::video().mFramerateLimit.set(framerateLimitSpinBox->value());
}
else if (Settings::video().mFramerateLimit != 0)
{
Settings::video().mFramerateLimit.set(0);
}
}
QStringList Launcher::GraphicsPage::getAvailableResolutions(int screen)
{
QStringList result;
SDL_DisplayMode mode;
int modeIndex, modes = SDL_GetNumDisplayModes(screen);
if (modes < 0)
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Error receiving resolutions"));
msgBox.setIcon(QMessageBox::Critical);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setText(
tr("<br><b>SDL_GetNumDisplayModes failed:</b><br><br>") + QString::fromUtf8(SDL_GetError()) + "<br>");
msgBox.exec();
return result;
}
for (modeIndex = 0; modeIndex < modes; modeIndex++)
{
if (SDL_GetDisplayMode(screen, modeIndex, &mode) < 0)
{
QMessageBox msgBox;
msgBox.setWindowTitle(tr("Error receiving resolutions"));
msgBox.setIcon(QMessageBox::Critical);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setText(
tr("<br><b>SDL_GetDisplayMode failed:</b><br><br>") + QString::fromUtf8(SDL_GetError()) + "<br>");
msgBox.exec();
return result;
}
auto str = Misc::getResolutionText(mode.w, mode.h, "%i × %i (%i:%i)");
result.append(QString(str.c_str()));
}
result.removeDuplicates();
return result;
}
QRect Launcher::GraphicsPage::getMaximumResolution()
{
QRect max;
for (QScreen* screen : QGuiApplication::screens())
{
QRect res = screen->geometry();
if (res.width() > max.width())
max.setWidth(res.width());
if (res.height() > max.height())
max.setHeight(res.height());
}
return max;
}
void Launcher::GraphicsPage::screenChanged(int screen)
{
if (screen >= 0)
{
resolutionComboBox->clear();
resolutionComboBox->addItems(mResolutionsPerScreen[screen]);
}
}
void Launcher::GraphicsPage::slotFullScreenChanged(int mode)
{
handleWindowModeChange(static_cast<Settings::WindowMode>(mode));
}
void Launcher::GraphicsPage::handleWindowModeChange(Settings::WindowMode mode)
{
if (mode == Settings::WindowMode::Fullscreen || mode == Settings::WindowMode::WindowedFullscreen)
{
standardRadioButton->toggle();
customRadioButton->setEnabled(false);
customWidthSpinBox->setEnabled(false);
customHeightSpinBox->setEnabled(false);
windowBorderCheckBox->setEnabled(false);
}
else
{
customRadioButton->setEnabled(true);
customWidthSpinBox->setEnabled(true);
customHeightSpinBox->setEnabled(true);
windowBorderCheckBox->setEnabled(true);
}
}
void Launcher::GraphicsPage::slotStandardToggled(bool checked)
{
if (checked)
{
resolutionComboBox->setEnabled(true);
customWidthSpinBox->setEnabled(false);
customHeightSpinBox->setEnabled(false);
}
else
{
resolutionComboBox->setEnabled(false);
customWidthSpinBox->setEnabled(true);
customHeightSpinBox->setEnabled(true);
}
}
void Launcher::GraphicsPage::slotFramerateLimitToggled(bool checked)
{
framerateLimitSpinBox->setEnabled(checked);
}
| 8,559
|
C++
|
.cpp
| 234
| 30.602564
| 115
| 0.685152
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,141
|
profilescombobox.cpp
|
OpenMW_openmw/apps/launcher/utils/profilescombobox.cpp
|
#include <QApplication>
#include <QString>
#include "profilescombobox.hpp"
ProfilesComboBox::ProfilesComboBox(QWidget* parent)
: ContentSelectorView::ComboBox(parent)
{
connect(this, qOverload<int>(&ProfilesComboBox::activated), this, &ProfilesComboBox::slotIndexChangedByUser);
setInsertPolicy(QComboBox::NoInsert);
}
void ProfilesComboBox::setEditEnabled(bool editable)
{
if (isEditable() == editable)
return;
if (!editable)
{
disconnect(lineEdit(), &QLineEdit::editingFinished, this, &ProfilesComboBox::slotEditingFinished);
disconnect(lineEdit(), &QLineEdit::textChanged, this, &ProfilesComboBox::slotTextChanged);
return setEditable(false);
}
// Reset the completer and validator
setEditable(true);
setValidator(mValidator);
auto* edit = new ComboBoxLineEdit(this);
setLineEdit(edit);
setCompleter(nullptr);
connect(lineEdit(), &QLineEdit::editingFinished, this, &ProfilesComboBox::slotEditingFinished);
connect(lineEdit(), &QLineEdit::textChanged, this, &ProfilesComboBox::slotTextChanged);
connect(lineEdit(), &QLineEdit::textChanged, this, &ProfilesComboBox::signalProfileTextChanged);
}
void ProfilesComboBox::slotTextChanged(const QString& text)
{
QPalette palette;
palette.setColor(QPalette::Text, Qt::red);
int index = findText(text);
if (text.isEmpty() || (index != -1 && index != currentIndex()))
{
lineEdit()->setPalette(palette);
}
else
{
lineEdit()->setPalette(QApplication::palette());
}
}
void ProfilesComboBox::slotEditingFinished()
{
QString current = currentText();
QString previous = itemText(currentIndex());
if (currentIndex() == -1)
return;
if (current.isEmpty())
return;
if (current == previous)
return;
if (findText(current) != -1)
return;
setItemText(currentIndex(), current);
emit profileRenamed(previous, current);
}
void ProfilesComboBox::slotIndexChangedByUser(int index)
{
if (index == -1)
return;
emit signalProfileChanged(mOldProfile, currentText());
mOldProfile = currentText();
}
ProfilesComboBox::ComboBoxLineEdit::ComboBoxLineEdit(QWidget* parent)
: LineEdit(parent)
{
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
setObjectName(QString("ComboBoxLineEdit"));
setStyleSheet(QString("ComboBoxLineEdit { background-color: transparent; padding-right: %1px; } ")
.arg(mClearButton->sizeHint().width() + frameWidth + 1));
}
| 2,575
|
C++
|
.cpp
| 73
| 30.246575
| 113
| 0.71025
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,142
|
textinputdialog.cpp
|
OpenMW_openmw/apps/launcher/utils/textinputdialog.cpp
|
#include "textinputdialog.hpp"
#include <QApplication>
#include <QDialogButtonBox>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QValidator>
Launcher::TextInputDialog::TextInputDialog(const QString& title, const QString& text, QWidget* parent)
: QDialog(parent)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
mButtonBox = new QDialogButtonBox(this);
mButtonBox->addButton(QDialogButtonBox::Ok);
mButtonBox->addButton(QDialogButtonBox::Cancel);
mButtonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
auto* label = new QLabel(this);
label->setText(text);
// Line edit
QValidator* validator = new QRegularExpressionValidator(QRegularExpression("^[a-zA-Z0-9_]*$"), this);
mLineEdit = new LineEdit(this);
mLineEdit->setValidator(validator);
mLineEdit->setCompleter(nullptr);
auto* dialogLayout = new QVBoxLayout(this);
dialogLayout->addWidget(label);
dialogLayout->addWidget(mLineEdit);
dialogLayout->addWidget(mButtonBox);
// Messageboxes on mac have no title
#ifndef Q_OS_MAC
setWindowTitle(title);
#else
Q_UNUSED(title);
#endif
setModal(true);
connect(mButtonBox, &QDialogButtonBox::accepted, this, &TextInputDialog::accept);
connect(mButtonBox, &QDialogButtonBox::rejected, this, &TextInputDialog::reject);
}
int Launcher::TextInputDialog::exec()
{
mLineEdit->clear();
mLineEdit->setFocus();
return QDialog::exec();
}
void Launcher::TextInputDialog::setOkButtonEnabled(bool enabled)
{
QPushButton* okButton = mButtonBox->button(QDialogButtonBox::Ok);
okButton->setEnabled(enabled);
QPalette palette;
palette.setColor(QPalette::Text, Qt::red);
if (enabled)
{
mLineEdit->setPalette(QApplication::palette());
}
else
{
// Existing profile name, make the text red
mLineEdit->setPalette(palette);
}
}
| 1,929
|
C++
|
.cpp
| 58
| 29.155172
| 105
| 0.73319
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,143
|
openalutil.cpp
|
OpenMW_openmw/apps/launcher/utils/openalutil.cpp
|
#include <cstring>
#include <vector>
#include "apps/openmw/mwsound/alext.h"
#include "openalutil.hpp"
#ifndef ALC_ALL_DEVICES_SPECIFIER
#define ALC_ALL_DEVICES_SPECIFIER 0x1013
#endif
std::vector<std::string> Launcher::enumerateOpenALDevices()
{
std::vector<std::string> devlist;
const ALCchar* devnames;
if (alcIsExtensionPresent(nullptr, "ALC_ENUMERATE_ALL_EXT"))
{
devnames = alcGetString(nullptr, ALC_ALL_DEVICES_SPECIFIER);
}
else
{
devnames = alcGetString(nullptr, ALC_DEVICE_SPECIFIER);
}
while (devnames && *devnames)
{
devlist.emplace_back(devnames);
devnames += strlen(devnames) + 1;
}
return devlist;
}
std::vector<std::string> Launcher::enumerateOpenALDevicesHrtf()
{
std::vector<std::string> ret;
ALCdevice* device = alcOpenDevice(nullptr);
if (device)
{
if (alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
{
LPALCGETSTRINGISOFT alcGetStringiSOFT = nullptr;
void* funcPtr = alcGetProcAddress(device, "alcGetStringiSOFT");
memcpy(&alcGetStringiSOFT, &funcPtr, sizeof(funcPtr));
ALCint num_hrtf;
alcGetIntegerv(device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf);
ret.reserve(num_hrtf);
for (ALCint i = 0; i < num_hrtf; ++i)
{
const ALCchar* entry = alcGetStringiSOFT(device, ALC_HRTF_SPECIFIER_SOFT, i);
if (strcmp(entry, "") == 0)
break;
ret.emplace_back(entry);
}
}
alcCloseDevice(device);
}
return ret;
}
| 1,640
|
C++
|
.cpp
| 52
| 24.384615
| 93
| 0.625949
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,144
|
lineedit.cpp
|
OpenMW_openmw/apps/launcher/utils/lineedit.cpp
|
#include "lineedit.hpp"
LineEdit::LineEdit(QWidget* parent)
: QLineEdit(parent)
{
setupClearButton();
}
void LineEdit::setupClearButton()
{
mClearButton = new QToolButton(this);
mClearButton->setIcon(QIcon::fromTheme("edit-clear"));
mClearButton->setCursor(Qt::ArrowCursor);
mClearButton->setAutoRaise(true);
mClearButton->hide();
connect(mClearButton, &QToolButton::clicked, this, &LineEdit::clear);
connect(this, &LineEdit::textChanged, this, &LineEdit::updateClearButton);
}
void LineEdit::resizeEvent(QResizeEvent*)
{
QSize sz = mClearButton->sizeHint();
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
mClearButton->move(rect().right() - frameWidth - sz.width(), (rect().bottom() + 1 - sz.height()) / 2);
}
void LineEdit::updateClearButton(const QString& text)
{
mClearButton->setVisible(!text.isEmpty());
}
| 890
|
C++
|
.cpp
| 26
| 31.076923
| 106
| 0.726744
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,145
|
cellnameloader.cpp
|
OpenMW_openmw/apps/launcher/utils/cellnameloader.cpp
|
#include "cellnameloader.hpp"
#include <fstream>
#include <components/debug/debuglog.hpp>
#include <components/esm/format.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/files/openfile.hpp>
#include <components/files/qtconversion.hpp>
QSet<QString> CellNameLoader::getCellNames(const QStringList& contentPaths)
{
QSet<QString> cellNames;
ESM::ESMReader esmReader;
// Loop through all content files
for (const QString& contentPath : contentPaths)
{
if (contentPath.endsWith(".omwscripts", Qt::CaseInsensitive))
continue;
try
{
std::filesystem::path filepath = Files::pathFromQString(contentPath);
auto stream = Files::openBinaryInputFileStream(filepath);
if (!stream->is_open())
continue;
const ESM::Format format = ESM::readFormat(*stream);
if (format != ESM::Format::Tes3)
continue;
stream->seekg(0);
esmReader.open(std::move(stream), filepath);
// Loop through all records
while (esmReader.hasMoreRecs())
{
ESM::NAME recordName = esmReader.getRecName();
esmReader.getRecHeader();
if (isCellRecord(recordName))
{
QString cellName = getCellName(esmReader);
if (!cellName.isEmpty())
{
cellNames.insert(cellName);
}
}
// Stop loading content for this record and continue to the next
esmReader.skipRecord();
}
}
catch (const std::exception& e)
{
Log(Debug::Error) << "Failed to get cell names from " << contentPath.toStdString() << ": " << e.what();
}
}
return cellNames;
}
bool CellNameLoader::isCellRecord(ESM::NAME& recordName)
{
return recordName.toInt() == ESM::REC_CELL;
}
QString CellNameLoader::getCellName(ESM::ESMReader& esmReader)
{
ESM::Cell cell;
bool isDeleted = false;
cell.loadNameAndData(esmReader, isDeleted);
return QString::fromStdString(cell.mName);
}
| 2,209
|
C++
|
.cpp
| 62
| 26.225806
| 115
| 0.598407
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,146
|
importer.cpp
|
OpenMW_openmw/apps/mwiniimporter/importer.cpp
|
#include "importer.hpp"
#include <components/esm3/esmreader.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/misc/timeconvert.hpp>
#include <filesystem>
#include <fstream>
#include <iostream>
namespace sfs = std::filesystem;
MwIniImporter::MwIniImporter()
: mVerbose(false)
, mEncoding(ToUTF8::WINDOWS_1250)
{
const char* map[][2] = { { "no-sound", "General:Disable Audio" }, { 0, 0 } };
const char* fallback[] = {
// light
"LightAttenuation:UseConstant", "LightAttenuation:ConstantValue", "LightAttenuation:UseLinear",
"LightAttenuation:LinearMethod", "LightAttenuation:LinearValue", "LightAttenuation:LinearRadiusMult",
"LightAttenuation:UseQuadratic", "LightAttenuation:QuadraticMethod", "LightAttenuation:QuadraticValue",
"LightAttenuation:QuadraticRadiusMult", "LightAttenuation:OutQuadInLin",
// inventory
"Inventory:DirectionalDiffuseR", "Inventory:DirectionalDiffuseG", "Inventory:DirectionalDiffuseB",
"Inventory:DirectionalAmbientR", "Inventory:DirectionalAmbientG", "Inventory:DirectionalAmbientB",
"Inventory:DirectionalRotationX", "Inventory:DirectionalRotationY", "Inventory:UniformScaling",
// map
"Map:Travel Siltstrider Red", "Map:Travel Siltstrider Green", "Map:Travel Siltstrider Blue",
"Map:Travel Boat Red", "Map:Travel Boat Green", "Map:Travel Boat Blue", "Map:Travel Magic Red",
"Map:Travel Magic Green", "Map:Travel Magic Blue", "Map:Show Travel Lines",
// water
"Water:Map Alpha", "Water:World Alpha", "Water:SurfaceTextureSize", "Water:SurfaceTileCount",
"Water:SurfaceFPS", "Water:SurfaceTexture", "Water:SurfaceFrameCount", "Water:TileTextureDivisor",
"Water:RippleTexture", "Water:RippleFrameCount", "Water:RippleLifetime", "Water:MaxNumberRipples",
"Water:RippleScale", "Water:RippleRotSpeed", "Water:RippleAlphas", "Water:PSWaterReflectTerrain",
"Water:PSWaterReflectUpdate", "Water:NearWaterRadius", "Water:NearWaterPoints", "Water:NearWaterUnderwaterFreq",
"Water:NearWaterUnderwaterVolume", "Water:NearWaterIndoorTolerance", "Water:NearWaterOutdoorTolerance",
"Water:NearWaterIndoorID", "Water:NearWaterOutdoorID", "Water:UnderwaterSunriseFog", "Water:UnderwaterDayFog",
"Water:UnderwaterSunsetFog", "Water:UnderwaterNightFog", "Water:UnderwaterIndoorFog", "Water:UnderwaterColor",
"Water:UnderwaterColorWeight",
// pixelwater
"PixelWater:SurfaceFPS", "PixelWater:TileCount", "PixelWater:Resolution",
// fonts
"Fonts:Font 0", "Fonts:Font 1", "Fonts:Font 2",
// UI colors
"FontColor:color_normal", "FontColor:color_normal_over", "FontColor:color_normal_pressed",
"FontColor:color_active", "FontColor:color_active_over", "FontColor:color_active_pressed",
"FontColor:color_disabled", "FontColor:color_disabled_over", "FontColor:color_disabled_pressed",
"FontColor:color_link", "FontColor:color_link_over", "FontColor:color_link_pressed",
"FontColor:color_journal_link", "FontColor:color_journal_link_over", "FontColor:color_journal_link_pressed",
"FontColor:color_journal_topic", "FontColor:color_journal_topic_over", "FontColor:color_journal_topic_pressed",
"FontColor:color_answer", "FontColor:color_answer_over", "FontColor:color_answer_pressed",
"FontColor:color_header", "FontColor:color_notify", "FontColor:color_big_normal",
"FontColor:color_big_normal_over", "FontColor:color_big_normal_pressed", "FontColor:color_big_link",
"FontColor:color_big_link_over", "FontColor:color_big_link_pressed", "FontColor:color_big_answer",
"FontColor:color_big_answer_over", "FontColor:color_big_answer_pressed", "FontColor:color_big_header",
"FontColor:color_big_notify", "FontColor:color_background", "FontColor:color_focus", "FontColor:color_health",
"FontColor:color_magic", "FontColor:color_fatigue", "FontColor:color_misc", "FontColor:color_weapon_fill",
"FontColor:color_magic_fill", "FontColor:color_positive", "FontColor:color_negative", "FontColor:color_count",
// level up messages
"Level Up:Level2", "Level Up:Level3", "Level Up:Level4", "Level Up:Level5", "Level Up:Level6",
"Level Up:Level7", "Level Up:Level8", "Level Up:Level9", "Level Up:Level10", "Level Up:Level11",
"Level Up:Level12", "Level Up:Level13", "Level Up:Level14", "Level Up:Level15", "Level Up:Level16",
"Level Up:Level17", "Level Up:Level18", "Level Up:Level19", "Level Up:Level20", "Level Up:Default",
// character creation multiple choice test
"Question 1:Question", "Question 1:AnswerOne", "Question 1:AnswerTwo", "Question 1:AnswerThree",
"Question 1:Sound", "Question 2:Question", "Question 2:AnswerOne", "Question 2:AnswerTwo",
"Question 2:AnswerThree", "Question 2:Sound", "Question 3:Question", "Question 3:AnswerOne",
"Question 3:AnswerTwo", "Question 3:AnswerThree", "Question 3:Sound", "Question 4:Question",
"Question 4:AnswerOne", "Question 4:AnswerTwo", "Question 4:AnswerThree", "Question 4:Sound",
"Question 5:Question", "Question 5:AnswerOne", "Question 5:AnswerTwo", "Question 5:AnswerThree",
"Question 5:Sound", "Question 6:Question", "Question 6:AnswerOne", "Question 6:AnswerTwo",
"Question 6:AnswerThree", "Question 6:Sound", "Question 7:Question", "Question 7:AnswerOne",
"Question 7:AnswerTwo", "Question 7:AnswerThree", "Question 7:Sound", "Question 8:Question",
"Question 8:AnswerOne", "Question 8:AnswerTwo", "Question 8:AnswerThree", "Question 8:Sound",
"Question 9:Question", "Question 9:AnswerOne", "Question 9:AnswerTwo", "Question 9:AnswerThree",
"Question 9:Sound", "Question 10:Question", "Question 10:AnswerOne", "Question 10:AnswerTwo",
"Question 10:AnswerThree", "Question 10:Sound",
// blood textures and models
"Blood:Model 0", "Blood:Model 1", "Blood:Model 2", "Blood:Texture 0", "Blood:Texture 1", "Blood:Texture 2",
"Blood:Texture 3", "Blood:Texture 4", "Blood:Texture 5", "Blood:Texture 6", "Blood:Texture 7",
"Blood:Texture Name 0", "Blood:Texture Name 1", "Blood:Texture Name 2", "Blood:Texture Name 3",
"Blood:Texture Name 4", "Blood:Texture Name 5", "Blood:Texture Name 6", "Blood:Texture Name 7",
// movies
"Movies:Company Logo", "Movies:Morrowind Logo", "Movies:New Game", "Movies:Loading", "Movies:Options Menu",
// weather related values
"Weather Thunderstorm:Thunder Sound ID 0", "Weather Thunderstorm:Thunder Sound ID 1",
"Weather Thunderstorm:Thunder Sound ID 2", "Weather Thunderstorm:Thunder Sound ID 3", "Weather:Sunrise Time",
"Weather:Sunset Time", "Weather:Sunrise Duration", "Weather:Sunset Duration",
"Weather:Hours Between Weather Changes", // AKA weather update time
"Weather Thunderstorm:Thunder Frequency", "Weather Thunderstorm:Thunder Threshold",
"Weather:EnvReduceColor", "Weather:LerpCloseColor", "Weather:BumpFadeColor", "Weather:AlphaReduce",
"Weather:Minimum Time Between Environmental Sounds", "Weather:Maximum Time Between Environmental Sounds",
"Weather:Sun Glare Fader Max", "Weather:Sun Glare Fader Angle Max", "Weather:Sun Glare Fader Color",
"Weather:Timescale Clouds", "Weather:Precip Gravity", "Weather:Rain Ripples", "Weather:Rain Ripple Radius",
"Weather:Rain Ripples Per Drop", "Weather:Rain Ripple Scale", "Weather:Rain Ripple Speed",
"Weather:Fog Depth Change Speed", "Weather:Sky Pre-Sunrise Time", "Weather:Sky Post-Sunrise Time",
"Weather:Sky Pre-Sunset Time", "Weather:Sky Post-Sunset Time", "Weather:Ambient Pre-Sunrise Time",
"Weather:Ambient Post-Sunrise Time", "Weather:Ambient Pre-Sunset Time", "Weather:Ambient Post-Sunset Time",
"Weather:Fog Pre-Sunrise Time", "Weather:Fog Post-Sunrise Time", "Weather:Fog Pre-Sunset Time",
"Weather:Fog Post-Sunset Time", "Weather:Sun Pre-Sunrise Time", "Weather:Sun Post-Sunrise Time",
"Weather:Sun Pre-Sunset Time", "Weather:Sun Post-Sunset Time", "Weather:Stars Post-Sunset Start",
"Weather:Stars Pre-Sunrise Finish", "Weather:Stars Fading Duration", "Weather:Snow Ripples",
"Weather:Snow Ripple Radius", "Weather:Snow Ripples Per Flake", "Weather:Snow Ripple Scale",
"Weather:Snow Ripple Speed", "Weather:Snow Gravity Scale", "Weather:Snow High Kill", "Weather:Snow Low Kill",
"Weather Clear:Cloud Texture", "Weather Clear:Clouds Maximum Percent", "Weather Clear:Transition Delta",
"Weather Clear:Sky Sunrise Color", "Weather Clear:Sky Day Color", "Weather Clear:Sky Sunset Color",
"Weather Clear:Sky Night Color", "Weather Clear:Fog Sunrise Color", "Weather Clear:Fog Day Color",
"Weather Clear:Fog Sunset Color", "Weather Clear:Fog Night Color", "Weather Clear:Ambient Sunrise Color",
"Weather Clear:Ambient Day Color", "Weather Clear:Ambient Sunset Color", "Weather Clear:Ambient Night Color",
"Weather Clear:Sun Sunrise Color", "Weather Clear:Sun Day Color", "Weather Clear:Sun Sunset Color",
"Weather Clear:Sun Night Color", "Weather Clear:Sun Disc Sunset Color", "Weather Clear:Land Fog Day Depth",
"Weather Clear:Land Fog Night Depth", "Weather Clear:Wind Speed", "Weather Clear:Cloud Speed",
"Weather Clear:Glare View", "Weather Clear:Ambient Loop Sound ID",
"Weather Cloudy:Cloud Texture", "Weather Cloudy:Clouds Maximum Percent", "Weather Cloudy:Transition Delta",
"Weather Cloudy:Sky Sunrise Color", "Weather Cloudy:Sky Day Color", "Weather Cloudy:Sky Sunset Color",
"Weather Cloudy:Sky Night Color", "Weather Cloudy:Fog Sunrise Color", "Weather Cloudy:Fog Day Color",
"Weather Cloudy:Fog Sunset Color", "Weather Cloudy:Fog Night Color", "Weather Cloudy:Ambient Sunrise Color",
"Weather Cloudy:Ambient Day Color", "Weather Cloudy:Ambient Sunset Color", "Weather Cloudy:Ambient Night Color",
"Weather Cloudy:Sun Sunrise Color", "Weather Cloudy:Sun Day Color", "Weather Cloudy:Sun Sunset Color",
"Weather Cloudy:Sun Night Color", "Weather Cloudy:Sun Disc Sunset Color", "Weather Cloudy:Land Fog Day Depth",
"Weather Cloudy:Land Fog Night Depth", "Weather Cloudy:Wind Speed", "Weather Cloudy:Cloud Speed",
"Weather Cloudy:Glare View", "Weather Cloudy:Ambient Loop Sound ID",
"Weather Foggy:Cloud Texture", "Weather Foggy:Clouds Maximum Percent", "Weather Foggy:Transition Delta",
"Weather Foggy:Sky Sunrise Color", "Weather Foggy:Sky Day Color", "Weather Foggy:Sky Sunset Color",
"Weather Foggy:Sky Night Color", "Weather Foggy:Fog Sunrise Color", "Weather Foggy:Fog Day Color",
"Weather Foggy:Fog Sunset Color", "Weather Foggy:Fog Night Color", "Weather Foggy:Ambient Sunrise Color",
"Weather Foggy:Ambient Day Color", "Weather Foggy:Ambient Sunset Color", "Weather Foggy:Ambient Night Color",
"Weather Foggy:Sun Sunrise Color", "Weather Foggy:Sun Day Color", "Weather Foggy:Sun Sunset Color",
"Weather Foggy:Sun Night Color", "Weather Foggy:Sun Disc Sunset Color", "Weather Foggy:Land Fog Day Depth",
"Weather Foggy:Land Fog Night Depth", "Weather Foggy:Wind Speed", "Weather Foggy:Cloud Speed",
"Weather Foggy:Glare View", "Weather Foggy:Ambient Loop Sound ID",
"Weather Thunderstorm:Cloud Texture", "Weather Thunderstorm:Clouds Maximum Percent",
"Weather Thunderstorm:Transition Delta", "Weather Thunderstorm:Sky Sunrise Color",
"Weather Thunderstorm:Sky Day Color", "Weather Thunderstorm:Sky Sunset Color",
"Weather Thunderstorm:Sky Night Color", "Weather Thunderstorm:Fog Sunrise Color",
"Weather Thunderstorm:Fog Day Color", "Weather Thunderstorm:Fog Sunset Color",
"Weather Thunderstorm:Fog Night Color", "Weather Thunderstorm:Ambient Sunrise Color",
"Weather Thunderstorm:Ambient Day Color", "Weather Thunderstorm:Ambient Sunset Color",
"Weather Thunderstorm:Ambient Night Color", "Weather Thunderstorm:Sun Sunrise Color",
"Weather Thunderstorm:Sun Day Color", "Weather Thunderstorm:Sun Sunset Color",
"Weather Thunderstorm:Sun Night Color", "Weather Thunderstorm:Sun Disc Sunset Color",
"Weather Thunderstorm:Land Fog Day Depth", "Weather Thunderstorm:Land Fog Night Depth",
"Weather Thunderstorm:Wind Speed", "Weather Thunderstorm:Cloud Speed", "Weather Thunderstorm:Glare View",
"Weather Thunderstorm:Rain Loop Sound ID", "Weather Thunderstorm:Using Precip",
"Weather Thunderstorm:Rain Diameter", "Weather Thunderstorm:Rain Height Min",
"Weather Thunderstorm:Rain Height Max", "Weather Thunderstorm:Rain Threshold",
"Weather Thunderstorm:Max Raindrops", "Weather Thunderstorm:Rain Entrance Speed",
"Weather Thunderstorm:Ambient Loop Sound ID", "Weather Thunderstorm:Flash Decrement",
"Weather Rain:Cloud Texture", "Weather Rain:Clouds Maximum Percent", "Weather Rain:Transition Delta",
"Weather Rain:Sky Sunrise Color", "Weather Rain:Sky Day Color", "Weather Rain:Sky Sunset Color",
"Weather Rain:Sky Night Color", "Weather Rain:Fog Sunrise Color", "Weather Rain:Fog Day Color",
"Weather Rain:Fog Sunset Color", "Weather Rain:Fog Night Color", "Weather Rain:Ambient Sunrise Color",
"Weather Rain:Ambient Day Color", "Weather Rain:Ambient Sunset Color", "Weather Rain:Ambient Night Color",
"Weather Rain:Sun Sunrise Color", "Weather Rain:Sun Day Color", "Weather Rain:Sun Sunset Color",
"Weather Rain:Sun Night Color", "Weather Rain:Sun Disc Sunset Color", "Weather Rain:Land Fog Day Depth",
"Weather Rain:Land Fog Night Depth", "Weather Rain:Wind Speed", "Weather Rain:Cloud Speed",
"Weather Rain:Glare View", "Weather Rain:Rain Loop Sound ID", "Weather Rain:Using Precip",
"Weather Rain:Rain Diameter", "Weather Rain:Rain Height Min", "Weather Rain:Rain Height Max",
"Weather Rain:Rain Threshold", "Weather Rain:Rain Entrance Speed", "Weather Rain:Ambient Loop Sound ID",
"Weather Rain:Max Raindrops",
"Weather Overcast:Cloud Texture", "Weather Overcast:Clouds Maximum Percent",
"Weather Overcast:Transition Delta", "Weather Overcast:Sky Sunrise Color", "Weather Overcast:Sky Day Color",
"Weather Overcast:Sky Sunset Color", "Weather Overcast:Sky Night Color", "Weather Overcast:Fog Sunrise Color",
"Weather Overcast:Fog Day Color", "Weather Overcast:Fog Sunset Color", "Weather Overcast:Fog Night Color",
"Weather Overcast:Ambient Sunrise Color", "Weather Overcast:Ambient Day Color",
"Weather Overcast:Ambient Sunset Color", "Weather Overcast:Ambient Night Color",
"Weather Overcast:Sun Sunrise Color", "Weather Overcast:Sun Day Color", "Weather Overcast:Sun Sunset Color",
"Weather Overcast:Sun Night Color", "Weather Overcast:Sun Disc Sunset Color",
"Weather Overcast:Land Fog Day Depth", "Weather Overcast:Land Fog Night Depth", "Weather Overcast:Wind Speed",
"Weather Overcast:Cloud Speed", "Weather Overcast:Glare View", "Weather Overcast:Ambient Loop Sound ID",
"Weather Ashstorm:Cloud Texture", "Weather Ashstorm:Clouds Maximum Percent",
"Weather Ashstorm:Transition Delta", "Weather Ashstorm:Sky Sunrise Color", "Weather Ashstorm:Sky Day Color",
"Weather Ashstorm:Sky Sunset Color", "Weather Ashstorm:Sky Night Color", "Weather Ashstorm:Fog Sunrise Color",
"Weather Ashstorm:Fog Day Color", "Weather Ashstorm:Fog Sunset Color", "Weather Ashstorm:Fog Night Color",
"Weather Ashstorm:Ambient Sunrise Color", "Weather Ashstorm:Ambient Day Color",
"Weather Ashstorm:Ambient Sunset Color", "Weather Ashstorm:Ambient Night Color",
"Weather Ashstorm:Sun Sunrise Color", "Weather Ashstorm:Sun Day Color", "Weather Ashstorm:Sun Sunset Color",
"Weather Ashstorm:Sun Night Color", "Weather Ashstorm:Sun Disc Sunset Color",
"Weather Ashstorm:Land Fog Day Depth", "Weather Ashstorm:Land Fog Night Depth", "Weather Ashstorm:Wind Speed",
"Weather Ashstorm:Cloud Speed", "Weather Ashstorm:Glare View", "Weather Ashstorm:Ambient Loop Sound ID",
"Weather Ashstorm:Storm Threshold",
"Weather Blight:Cloud Texture", "Weather Blight:Clouds Maximum Percent", "Weather Blight:Transition Delta",
"Weather Blight:Sky Sunrise Color", "Weather Blight:Sky Day Color", "Weather Blight:Sky Sunset Color",
"Weather Blight:Sky Night Color", "Weather Blight:Fog Sunrise Color", "Weather Blight:Fog Day Color",
"Weather Blight:Fog Sunset Color", "Weather Blight:Fog Night Color", "Weather Blight:Ambient Sunrise Color",
"Weather Blight:Ambient Day Color", "Weather Blight:Ambient Sunset Color", "Weather Blight:Ambient Night Color",
"Weather Blight:Sun Sunrise Color", "Weather Blight:Sun Day Color", "Weather Blight:Sun Sunset Color",
"Weather Blight:Sun Night Color", "Weather Blight:Sun Disc Sunset Color", "Weather Blight:Land Fog Day Depth",
"Weather Blight:Land Fog Night Depth", "Weather Blight:Wind Speed", "Weather Blight:Cloud Speed",
"Weather Blight:Glare View", "Weather Blight:Ambient Loop Sound ID", "Weather Blight:Storm Threshold",
"Weather Blight:Disease Chance",
// for Bloodmoon
"Weather Snow:Cloud Texture", "Weather Snow:Clouds Maximum Percent", "Weather Snow:Transition Delta",
"Weather Snow:Sky Sunrise Color", "Weather Snow:Sky Day Color", "Weather Snow:Sky Sunset Color",
"Weather Snow:Sky Night Color", "Weather Snow:Fog Sunrise Color", "Weather Snow:Fog Day Color",
"Weather Snow:Fog Sunset Color", "Weather Snow:Fog Night Color", "Weather Snow:Ambient Sunrise Color",
"Weather Snow:Ambient Day Color", "Weather Snow:Ambient Sunset Color", "Weather Snow:Ambient Night Color",
"Weather Snow:Sun Sunrise Color", "Weather Snow:Sun Day Color", "Weather Snow:Sun Sunset Color",
"Weather Snow:Sun Night Color", "Weather Snow:Sun Disc Sunset Color", "Weather Snow:Land Fog Day Depth",
"Weather Snow:Land Fog Night Depth", "Weather Snow:Wind Speed", "Weather Snow:Cloud Speed",
"Weather Snow:Glare View", "Weather Snow:Snow Diameter", "Weather Snow:Snow Height Min",
"Weather Snow:Snow Height Max", "Weather Snow:Snow Entrance Speed", "Weather Snow:Max Snowflakes",
"Weather Snow:Ambient Loop Sound ID", "Weather Snow:Snow Threshold",
// for Bloodmoon
"Weather Blizzard:Cloud Texture", "Weather Blizzard:Clouds Maximum Percent",
"Weather Blizzard:Transition Delta", "Weather Blizzard:Sky Sunrise Color", "Weather Blizzard:Sky Day Color",
"Weather Blizzard:Sky Sunset Color", "Weather Blizzard:Sky Night Color", "Weather Blizzard:Fog Sunrise Color",
"Weather Blizzard:Fog Day Color", "Weather Blizzard:Fog Sunset Color", "Weather Blizzard:Fog Night Color",
"Weather Blizzard:Ambient Sunrise Color", "Weather Blizzard:Ambient Day Color",
"Weather Blizzard:Ambient Sunset Color", "Weather Blizzard:Ambient Night Color",
"Weather Blizzard:Sun Sunrise Color", "Weather Blizzard:Sun Day Color", "Weather Blizzard:Sun Sunset Color",
"Weather Blizzard:Sun Night Color", "Weather Blizzard:Sun Disc Sunset Color",
"Weather Blizzard:Land Fog Day Depth", "Weather Blizzard:Land Fog Night Depth", "Weather Blizzard:Wind Speed",
"Weather Blizzard:Cloud Speed", "Weather Blizzard:Glare View", "Weather Blizzard:Ambient Loop Sound ID",
"Weather Blizzard:Storm Threshold",
// moons
"Moons:Secunda Size", "Moons:Secunda Axis Offset", "Moons:Secunda Speed", "Moons:Secunda Daily Increment",
"Moons:Secunda Moon Shadow Early Fade Angle", "Moons:Secunda Fade Start Angle", "Moons:Secunda Fade End Angle",
"Moons:Secunda Fade In Start", "Moons:Secunda Fade In Finish", "Moons:Secunda Fade Out Start",
"Moons:Secunda Fade Out Finish", "Moons:Masser Size", "Moons:Masser Axis Offset", "Moons:Masser Speed",
"Moons:Masser Daily Increment", "Moons:Masser Moon Shadow Early Fade Angle", "Moons:Masser Fade Start Angle",
"Moons:Masser Fade End Angle", "Moons:Masser Fade In Start", "Moons:Masser Fade In Finish",
"Moons:Masser Fade Out Start", "Moons:Masser Fade Out Finish", "Moons:Script Color",
// werewolf (Bloodmoon)
"General:Werewolf FOV",
0
};
for (int i = 0; map[i][0]; i++)
{
mMergeMap.insert(std::make_pair<std::string, std::string>(map[i][0], map[i][1]));
}
for (int i = 0; fallback[i]; i++)
{
mMergeFallback.emplace_back(fallback[i]);
}
}
void MwIniImporter::setVerbose(bool verbose)
{
mVerbose = verbose;
}
MwIniImporter::multistrmap MwIniImporter::loadIniFile(const std::filesystem::path& filename) const
{
std::cout << "load ini file: " << Files::pathToUnicodeString(filename) << std::endl;
std::string section("");
MwIniImporter::multistrmap map;
std::ifstream file(filename);
ToUTF8::Utf8Encoder encoder(mEncoding);
std::string line;
while (std::getline(file, line))
{
std::string_view utf8 = encoder.getUtf8(line);
// unify Unix-style and Windows file ending
if (!(utf8.empty()) && (utf8[utf8.length() - 1]) == '\r')
{
utf8 = utf8.substr(0, utf8.length() - 1);
}
if (utf8.empty())
{
continue;
}
if (utf8[0] == '[')
{
int pos = static_cast<int>(utf8.find(']'));
if (pos < 2)
{
std::cout << "Warning: ini file wrongly formatted (" << utf8 << "). Line ignored." << std::endl;
continue;
}
section = utf8.substr(1, utf8.find(']') - 1);
continue;
}
int comment_pos = static_cast<int>(utf8.find(';'));
if (comment_pos > 0)
{
utf8 = utf8.substr(0, comment_pos);
}
int pos = static_cast<int>(utf8.find('='));
if (pos < 1)
{
continue;
}
std::string key(section + ":" + std::string(utf8.substr(0, pos)));
const std::string_view value(utf8.substr(pos + 1));
if (value.empty())
{
std::cout << "Warning: ignored empty value for key '" << key << "'." << std::endl;
continue;
}
auto it = map.find(key);
if (it == map.end())
it = map.emplace_hint(it, std::move(key), std::vector<std::string>());
it->second.push_back(std::string(value));
}
return map;
}
MwIniImporter::multistrmap MwIniImporter::loadCfgFile(const std::filesystem::path& filename)
{
std::cout << "load cfg file: " << Files::pathToUnicodeString(filename) << std::endl;
MwIniImporter::multistrmap map;
std::ifstream file(filename);
std::string line;
while (std::getline(file, line))
{
// we cant say comment by only looking at first char anymore
int comment_pos = static_cast<int>(line.find('#'));
if (comment_pos > 0)
{
line = line.substr(0, comment_pos);
}
if (line.empty())
{
continue;
}
int pos = static_cast<int>(line.find('='));
if (pos < 1)
{
continue;
}
std::string key(line.substr(0, pos));
std::string value(line.substr(pos + 1));
if (map.find(key) == map.end())
{
map.insert(std::make_pair(key, std::vector<std::string>()));
}
map[key].push_back(value);
}
return map;
}
void MwIniImporter::merge(multistrmap& cfg, const multistrmap& ini) const
{
multistrmap::const_iterator iniIt;
for (strmap::const_iterator it = mMergeMap.begin(); it != mMergeMap.end(); ++it)
{
if ((iniIt = ini.find(it->second)) != ini.end())
{
for (std::vector<std::string>::const_iterator vc = iniIt->second.begin(); vc != iniIt->second.end(); ++vc)
{
cfg.erase(it->first);
insertMultistrmap(cfg, it->first, *vc);
}
}
}
}
void MwIniImporter::mergeFallback(multistrmap& cfg, const multistrmap& ini) const
{
cfg.erase("fallback");
multistrmap::const_iterator iniIt;
for (std::vector<std::string>::const_iterator it = mMergeFallback.begin(); it != mMergeFallback.end(); ++it)
{
if ((iniIt = ini.find(*it)) != ini.end())
{
for (std::vector<std::string>::const_iterator vc = iniIt->second.begin(); vc != iniIt->second.end(); ++vc)
{
std::string value(*it);
std::replace(value.begin(), value.end(), ' ', '_');
std::replace(value.begin(), value.end(), ':', '_');
value.append(",").append(vc->substr(0, vc->length()));
insertMultistrmap(cfg, "fallback", value);
}
}
}
}
void MwIniImporter::insertMultistrmap(multistrmap& cfg, const std::string& key, const std::string& value)
{
const auto it = cfg.find(key);
if (it == cfg.end())
{
cfg.insert(std::make_pair(key, std::vector<std::string>()));
}
cfg[key].push_back(value);
}
void MwIniImporter::importArchives(multistrmap& cfg, const multistrmap& ini) const
{
std::vector<std::string> archives;
// Search archives listed in ini file
auto it = ini.begin();
for (int i = 0; it != ini.end(); i++)
{
std::string archive("Archives:Archive " + std::to_string(i));
it = ini.find(archive);
if (it == ini.end())
{
break;
}
for (std::vector<std::string>::const_iterator entry = it->second.begin(); entry != it->second.end(); ++entry)
{
archives.push_back(*entry);
}
}
cfg.erase("fallback-archive");
cfg.insert(std::make_pair<std::string, std::vector<std::string>>("fallback-archive", std::vector<std::string>()));
// Add Morrowind.bsa by default, since Vanilla loads this archive even if it
// does not appears in the ini file
cfg["fallback-archive"].push_back("Morrowind.bsa");
for (auto iter = archives.begin(); iter != archives.end(); ++iter)
{
cfg["fallback-archive"].push_back(*iter);
}
}
void MwIniImporter::dependencySortStep(
std::string& element, MwIniImporter::dependencyList& source, std::vector<std::string>& result)
{
auto iter = std::find_if(
source.begin(), source.end(), [&element](std::pair<std::string, std::vector<std::string>>& sourceElement) {
return sourceElement.first == element;
});
if (iter != source.end())
{
auto foundElement = std::move(*iter);
source.erase(iter);
for (auto name : foundElement.second)
{
MwIniImporter::dependencySortStep(name, source, result);
}
result.push_back(std::move(foundElement.first));
}
}
std::vector<std::string> MwIniImporter::dependencySort(MwIniImporter::dependencyList source)
{
std::vector<std::string> result;
while (!source.empty())
{
MwIniImporter::dependencySortStep(source.begin()->first, source, result);
}
return result;
}
std::vector<std::string>::iterator MwIniImporter::findString(
std::vector<std::string>& source, const std::string& string)
{
return std::find_if(source.begin(), source.end(),
[&string](const std::string& sourceString) { return Misc::StringUtils::ciEqual(sourceString, string); });
}
void MwIniImporter::addPaths(std::vector<std::filesystem::path>& output, std::vector<std::string> input)
{
for (auto& path : input)
{
if (path.front() == '"')
{
// Drop first and last characters - quotation marks
path = path.substr(1, path.size() - 2);
}
output.emplace_back(Files::pathFromUnicodeString(path));
}
}
void MwIniImporter::importGameFiles(
multistrmap& cfg, const multistrmap& ini, const std::filesystem::path& iniFilename) const
{
std::vector<std::pair<std::time_t, std::filesystem::path>> contentFiles;
std::time_t defaultTime = 0;
ToUTF8::Utf8Encoder encoder(mEncoding);
std::vector<std::filesystem::path> dataPaths;
if (cfg.count("data"))
addPaths(dataPaths, cfg["data"]);
if (cfg.count("data-local"))
addPaths(dataPaths, cfg["data-local"]);
dataPaths.push_back(iniFilename.parent_path() /= "Data Files");
auto it = ini.begin();
for (int i = 0; it != ini.end(); i++)
{
std::string gameFile("Game Files:GameFile" + std::to_string(i));
it = ini.find(gameFile);
if (it == ini.end())
break;
for (const std::string& file : it->second)
{
if (Misc::StringUtils::ciEndsWith(file, "esm") || Misc::StringUtils::ciEndsWith(file, "esp"))
{
bool found = false;
for (auto& dataPath : dataPaths)
{
std::filesystem::path path = dataPath / file;
std::time_t time = lastWriteTime(path, defaultTime);
if (time != defaultTime)
{
contentFiles.emplace_back(time, std::move(path));
found = true;
break;
}
}
if (!found)
std::cout << "Warning: " << file << " not found, ignoring" << std::endl;
}
}
}
cfg.erase("content");
cfg.insert(std::make_pair("content", std::vector<std::string>()));
// sort by timestamp
sort(contentFiles.begin(), contentFiles.end());
MwIniImporter::dependencyList unsortedFiles;
ESM::ESMReader reader;
reader.setEncoder(&encoder);
for (auto& file : contentFiles)
{
reader.open(file.second);
std::vector<std::string> dependencies;
for (auto& gameFile : reader.getGameFiles())
{
dependencies.push_back(gameFile.name);
}
unsortedFiles.emplace_back(Files::pathToUnicodeString(reader.getName().filename()), dependencies);
reader.close();
}
auto sortedFiles = dependencySort(std::move(unsortedFiles));
// hard-coded dependency Morrowind - Tribunal - Bloodmoon
if (findString(sortedFiles, "Morrowind.esm") != sortedFiles.end())
{
auto tribunalIter = findString(sortedFiles, "Tribunal.esm");
auto bloodmoonIter = findString(sortedFiles, "Bloodmoon.esm");
if (bloodmoonIter != sortedFiles.end() && tribunalIter != sortedFiles.end())
{
size_t bloodmoonIndex = std::distance(sortedFiles.begin(), bloodmoonIter);
size_t tribunalIndex = std::distance(sortedFiles.begin(), tribunalIter);
if (bloodmoonIndex < tribunalIndex)
tribunalIndex++;
sortedFiles.insert(bloodmoonIter, *tribunalIter);
sortedFiles.erase(sortedFiles.begin() + tribunalIndex);
}
}
for (auto& file : sortedFiles)
cfg["content"].push_back(file);
}
void MwIniImporter::writeToFile(std::ostream& out, const multistrmap& cfg)
{
for (multistrmap::const_iterator it = cfg.begin(); it != cfg.end(); ++it)
{
for (auto entry = it->second.begin(); entry != it->second.end(); ++entry)
{
out << (it->first) << "=" << (*entry) << std::endl;
}
}
}
void MwIniImporter::setInputEncoding(const ToUTF8::FromType& encoding)
{
mEncoding = encoding;
}
std::time_t MwIniImporter::lastWriteTime(const std::filesystem::path& filename, std::time_t defaultTime)
{
std::time_t writeTime(defaultTime);
if (std::filesystem::exists(filename))
{
std::filesystem::path resolved = std::filesystem::canonical(filename);
const auto time = std::filesystem::last_write_time(resolved);
writeTime = Misc::toTimeT(time);
// print timestamp
const auto str = Misc::fileTimeToString(time, "%x %X");
if (!str.empty())
std::cout << "content file: " << resolved << " timestamp = (" << writeTime << ") " << str << std::endl;
}
return writeTime;
}
| 32,562
|
C++
|
.cpp
| 550
| 50.945455
| 120
| 0.666823
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,147
|
main.cpp
|
OpenMW_openmw/apps/mwiniimporter/main.cpp
|
#include "importer.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <boost/program_options.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/files/conversion.hpp>
namespace bpo = boost::program_options;
namespace sfs = std::filesystem;
#ifndef _WIN32
int main(int argc, char* argv[])
{
#else
// Include on Windows only
#include <codecvt>
#include <locale>
class utf8argv
{
public:
utf8argv(int argc, wchar_t* wargv[])
{
args.reserve(argc);
argv = new const char*[argc];
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
for (int i = 0; i < argc; ++i)
{
args.push_back(converter.to_bytes(wargv[i]));
argv[i] = args.back().c_str();
}
}
~utf8argv() { delete[] argv; }
char** get() const { return const_cast<char**>(argv); }
private:
utf8argv(const utf8argv&);
utf8argv& operator=(const utf8argv&);
const char** argv;
std::vector<std::string> args;
};
/* The only way to pass Unicode on Winodws with CLI is to use wide
characters interface which presents UTF-16 encoding. The rest of
OpenMW application stack assumes UTF-8 encoding, therefore this
conversion.
*/
int wmain(int argc, wchar_t* wargv[])
{
utf8argv converter(argc, wargv);
char** argv = converter.get();
#endif
try
{
bpo::options_description desc("Syntax: openmw-iniimporter <options> inifile configfile\nAllowed options");
bpo::positional_options_description p_desc;
auto addOption = desc.add_options();
addOption("help,h", "produce help message");
addOption("verbose,v", "verbose output");
addOption("ini,i", bpo::value<Files::MaybeQuotedPath>(), "morrowind.ini file");
addOption("cfg,c", bpo::value<Files::MaybeQuotedPath>(), "openmw.cfg file");
addOption("output,o", bpo::value<Files::MaybeQuotedPath>()->default_value({}), "openmw.cfg file");
addOption("game-files,g", "import esm and esp files");
addOption("fonts,f", "import bitmap fonts");
addOption("no-archives,A", "disable bsa archives import");
addOption("encoding,e", bpo::value<std::string>()->default_value("win1252"),
"Character encoding used in OpenMW game messages:\n"
"\n\twin1250 - Central and Eastern European such as Polish, Czech, Slovak, Hungarian, Slovene, Bosnian, "
"Croatian, Serbian (Latin script), Romanian and Albanian languages\n"
"\n\twin1251 - Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic and other languages\n"
"\n\twin1252 - Western European (Latin) alphabet, used by default");
;
p_desc.add("ini", 1).add("cfg", 1);
bpo::variables_map vm;
bpo::parsed_options parsed = bpo::command_line_parser(argc, argv).options(desc).positional(p_desc).run();
bpo::store(parsed, vm);
if (vm.count("help") || !vm.count("ini") || !vm.count("cfg"))
{
std::cout << desc;
return 0;
}
bpo::notify(vm);
std::filesystem::path iniFile(
vm["ini"].as<Files::MaybeQuotedPath>().u8string()); // This call to u8string is redundant, but required to
// build on MSVC 14.26 due to implementation bugs.
std::filesystem::path cfgFile(
vm["cfg"].as<Files::MaybeQuotedPath>().u8string()); // This call to u8string is redundant, but required to
// build on MSVC 14.26 due to implementation bugs.
// if no output is given, write back to cfg file
std::filesystem::path outputFile = vm["output"]
.as<Files::MaybeQuotedPath>()
.u8string(); // This call to u8string is redundant, but required to build
// on MSVC 14.26 due to implementation bugs.
if (vm["output"].defaulted())
{
outputFile = vm["cfg"]
.as<Files::MaybeQuotedPath>()
.u8string(); // This call to u8string is redundant, but required to build on MSVC 14.26 due
// to implementation bugs.
}
if (!std::filesystem::exists(iniFile))
{
std::cerr << "ini file does not exist" << std::endl;
return -3;
}
if (!std::filesystem::exists(cfgFile))
std::cerr << "cfg file does not exist" << std::endl;
MwIniImporter importer;
importer.setVerbose(vm.count("verbose") != 0);
// Font encoding settings
std::string encoding(vm["encoding"].as<std::string>());
importer.setInputEncoding(ToUTF8::calculateEncoding(encoding));
MwIniImporter::multistrmap ini = importer.loadIniFile(iniFile);
MwIniImporter::multistrmap cfg = importer.loadCfgFile(cfgFile);
if (!vm.count("fonts"))
{
ini.erase("Fonts:Font 0");
ini.erase("Fonts:Font 1");
ini.erase("Fonts:Font 2");
}
importer.merge(cfg, ini);
importer.mergeFallback(cfg, ini);
if (vm.count("game-files"))
{
importer.importGameFiles(cfg, ini, iniFile);
}
if (!vm.count("no-archives"))
{
importer.importArchives(cfg, ini);
}
std::cout << "write to: " << Files::pathToUnicodeString(outputFile) << std::endl;
std::ofstream file(outputFile);
importer.writeToFile(file, cfg);
}
catch (std::exception& e)
{
std::cerr << "ERROR: " << e.what() << std::endl;
}
return 0;
}
| 5,861
|
C++
|
.cpp
| 136
| 33.161765
| 120
| 0.58585
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,148
|
bsatool.cpp
|
OpenMW_openmw/apps/bsatool/bsatool.cpp
|
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
#include <components/bsa/ba2dx10file.hpp>
#include <components/bsa/ba2gnrlfile.hpp>
#include <components/bsa/compressedbsafile.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/conversion.hpp>
#define BSATOOL_VERSION 1.1
// Create local aliases for brevity
namespace bpo = boost::program_options;
struct Arguments
{
std::string mode;
std::filesystem::path filename;
std::filesystem::path extractfile;
std::filesystem::path addfile;
std::filesystem::path outdir;
bool longformat;
bool fullpath;
};
bool parseOptions(int argc, char** argv, Arguments& info)
{
bpo::options_description desc(R"(Inspect and extract files from Bethesda BSA archives
Usages:
bsatool list [-l] archivefile\n
List the files presents in the input archive.
bsatool extract [-f] archivefile [file_to_extract] [output_directory]
Extract a file from the input archive.
bsatool extractall archivefile [output_directory]
Extract all files from the input archive.
bsatool add [-a] archivefile file_to_add
Add a file to the input archive.
bsatool create [-c] archivefile
Create an archive.
Allowed options)");
auto addOption = desc.add_options();
addOption("help,h", "print help message.");
addOption("version,v", "print version information and quit.");
addOption("long,l", "Include extra information in archive listing.");
addOption("full-path,f", "Create directory hierarchy on file extraction (always true for extractall).");
// input-file is hidden and used as a positional argument
bpo::options_description hidden("Hidden Options");
auto addHiddenOption = hidden.add_options();
addHiddenOption("mode,m", bpo::value<std::string>(), "bsatool mode");
addHiddenOption("input-file,i", bpo::value<Files::MaybeQuotedPathContainer>(), "input file");
bpo::positional_options_description p;
p.add("mode", 1).add("input-file", 3);
// there might be a better way to do this
bpo::options_description all;
all.add(desc).add(hidden);
bpo::variables_map variables;
try
{
bpo::parsed_options valid_opts = bpo::command_line_parser(argc, argv).options(all).positional(p).run();
bpo::store(valid_opts, variables);
}
catch (std::exception& e)
{
std::cout << "ERROR parsing arguments: " << e.what() << "\n\n" << desc << std::endl;
return false;
}
bpo::notify(variables);
if (variables.count("help"))
{
std::cout << desc << std::endl;
return false;
}
if (variables.count("version"))
{
std::cout << "BSATool version " << BSATOOL_VERSION << std::endl;
return false;
}
if (!variables.count("mode"))
{
std::cout << "ERROR: no mode specified!\n\n" << desc << std::endl;
return false;
}
info.mode = variables["mode"].as<std::string>();
if (!(info.mode == "list" || info.mode == "extract" || info.mode == "extractall" || info.mode == "add"
|| info.mode == "create"))
{
std::cout << std::endl << "ERROR: invalid mode \"" << info.mode << "\"\n\n" << desc << std::endl;
return false;
}
if (!variables.count("input-file"))
{
std::cout << "\nERROR: missing BSA archive\n\n" << desc << std::endl;
return false;
}
auto inputFiles = variables["input-file"].as<Files::MaybeQuotedPathContainer>();
info.filename = inputFiles[0].u8string(); // This call to u8string is redundant, but required to build on MSVC 14.26
// due to implementation bugs.
// Default output to the working directory
info.outdir = std::filesystem::current_path();
if (info.mode == "extract")
{
if (inputFiles.size() < 2)
{
std::cout << "\nERROR: file to extract unspecified\n\n" << desc << std::endl;
return false;
}
if (inputFiles.size() > 1)
info.extractfile = inputFiles[1].u8string(); // This call to u8string is redundant, but required to build on
// MSVC 14.26 due to implementation bugs.
if (inputFiles.size() > 2)
info.outdir = inputFiles[2].u8string(); // This call to u8string is redundant, but required to build on
// MSVC 14.26 due to implementation bugs.
}
else if (info.mode == "add")
{
if (inputFiles.empty())
{
std::cout << "\nERROR: file to add unspecified\n\n" << desc << std::endl;
return false;
}
if (inputFiles.size() > 1)
info.addfile = inputFiles[1].u8string(); // This call to u8string is redundant, but required to build on
// MSVC 14.26 due to implementation bugs.
}
else if (inputFiles.size() > 1)
info.outdir = inputFiles[1].u8string(); // This call to u8string is redundant, but required to build on
// MSVC 14.26 due to implementation bugs.
info.longformat = variables.count("long") != 0;
info.fullpath = variables.count("full-path") != 0;
return true;
}
template <typename File>
int list(std::unique_ptr<File>& bsa, Arguments& info)
{
// List all files
const auto& files = bsa->getList();
for (const auto& file : files)
{
if (info.longformat)
{
// Long format
std::ios::fmtflags f(std::cout.flags());
std::cout << std::setw(50) << std::left << file.name();
std::cout << std::setw(8) << std::left << std::dec << file.fileSize;
std::cout << "@ 0x" << std::hex << file.offset << std::endl;
std::cout.flags(f);
}
else
std::cout << file.name() << std::endl;
}
return 0;
}
template <typename File>
int extract(std::unique_ptr<File>& bsa, Arguments& info)
{
auto archivePath = info.extractfile.u8string();
Misc::StringUtils::replaceAll(archivePath, u8"/", u8"\\");
auto extractPath = info.extractfile.u8string();
Misc::StringUtils::replaceAll(extractPath, u8"\\", u8"/");
Files::IStreamPtr stream;
// Get a stream for the file to extract
for (auto it = bsa->getList().rbegin(); it != bsa->getList().rend(); ++it)
{
auto streamPath = Misc::StringUtils::stringToU8String(it->name());
if (Misc::StringUtils::ciEqual(streamPath, archivePath) || Misc::StringUtils::ciEqual(streamPath, extractPath))
{
stream = bsa->getFile(&*it);
break;
}
}
if (!stream)
{
std::cout << "ERROR: file '" << Misc::StringUtils::u8StringToString(archivePath) << "' not found\n";
std::cout << "In archive: " << Files::pathToUnicodeString(info.filename) << std::endl;
return 3;
}
// Get the target path (the path the file will be extracted to)
std::filesystem::path relPath(extractPath);
std::filesystem::path target;
if (info.fullpath)
target = info.outdir / relPath;
else
target = info.outdir / relPath.filename();
// Create the directory hierarchy
std::filesystem::create_directories(target.parent_path());
std::filesystem::file_status s = std::filesystem::status(target.parent_path());
if (!std::filesystem::is_directory(s))
{
std::cout << "ERROR: " << Files::pathToUnicodeString(target.parent_path()) << " is not a directory."
<< std::endl;
return 3;
}
std::ofstream out(target, std::ios::binary);
// Write the file to disk
std::cout << "Extracting " << Files::pathToUnicodeString(info.extractfile) << " to "
<< Files::pathToUnicodeString(target) << std::endl;
out << stream->rdbuf();
out.close();
return 0;
}
template <typename File>
int extractAll(std::unique_ptr<File>& bsa, Arguments& info)
{
for (const auto& file : bsa->getList())
{
std::string extractPath(file.name());
Misc::StringUtils::replaceAll(extractPath, "\\", "/");
// Get the target path (the path the file will be extracted to)
auto target = info.outdir;
target /= Misc::StringUtils::stringToU8String(extractPath);
// Create the directory hierarchy
std::filesystem::create_directories(target.parent_path());
std::filesystem::file_status s = std::filesystem::status(target.parent_path());
if (!std::filesystem::is_directory(s))
{
std::cout << "ERROR: " << target.parent_path() << " is not a directory." << std::endl;
return 3;
}
// Get a stream for the file to extract
Files::IStreamPtr data = bsa->getFile(&file);
std::ofstream out(target, std::ios::binary);
// Write the file to disk
std::cout << "Extracting " << Files::pathToUnicodeString(target) << std::endl;
out << data->rdbuf();
out.close();
}
return 0;
}
template <typename File>
int add(std::unique_ptr<File>& bsa, Arguments& info)
{
std::fstream stream(info.addfile, std::ios_base::binary | std::ios_base::out | std::ios_base::in);
bsa->addFile(Files::pathToUnicodeString(info.addfile), stream);
return 0;
}
template <typename File>
int call(Arguments& info)
{
std::unique_ptr<File> bsa = std::make_unique<File>();
if (info.mode == "create")
{
bsa->open(info.filename);
return 0;
}
bsa->open(info.filename);
if (info.mode == "list")
return list(bsa, info);
else if (info.mode == "extract")
return extract(bsa, info);
else if (info.mode == "extractall")
return extractAll(bsa, info);
else if (info.mode == "add")
return add(bsa, info);
else
{
std::cout << "Unsupported mode. That is not supposed to happen." << std::endl;
return 1;
}
}
int main(int argc, char** argv)
{
try
{
Arguments info;
if (!parseOptions(argc, argv, info))
return 1;
// Open file
// TODO: add a version argument for this mode after compressed BSA writing is a thing
if (info.mode == "create")
return call<Bsa::BSAFile>(info);
Bsa::BsaVersion bsaVersion = Bsa::BSAFile::detectVersion(info.filename);
switch (bsaVersion)
{
case Bsa::BsaVersion::Unknown:
break;
case Bsa::BsaVersion::Uncompressed:
return call<Bsa::BSAFile>(info);
case Bsa::BsaVersion::Compressed:
return call<Bsa::CompressedBSAFile>(info);
case Bsa::BsaVersion::BA2GNRL:
return call<Bsa::BA2GNRLFile>(info);
case Bsa::BsaVersion::BA2DX10:
return call<Bsa::BA2DX10File>(info);
}
throw std::runtime_error("Unrecognised BSA archive");
}
catch (std::exception& e)
{
std::cerr << "ERROR reading BSA archive\nDetails:\n" << e.what() << std::endl;
return 2;
}
}
| 11,368
|
C++
|
.cpp
| 293
| 31.389078
| 120
| 0.60924
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,149
|
main.cpp
|
OpenMW_openmw/apps/navmeshtool/main.cpp
|
#include "navmesh.hpp"
#include "worldspacedata.hpp"
#include <components/debug/debugging.hpp>
#include <components/debug/debuglog.hpp>
#include <components/detournavigator/agentbounds.hpp>
#include <components/detournavigator/collisionshapetype.hpp>
#include <components/detournavigator/navmeshdb.hpp>
#include <components/detournavigator/recastglobalallocator.hpp>
#include <components/detournavigator/settings.hpp>
#include <components/esm3/readerscache.hpp>
#include <components/esm3/variant.hpp>
#include <components/esmloader/esmdata.hpp>
#include <components/esmloader/load.hpp>
#include <components/fallback/fallback.hpp>
#include <components/fallback/validate.hpp>
#include <components/files/collections.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/files/conversion.hpp>
#include <components/files/multidircollection.hpp>
#include <components/platform/platform.hpp>
#include <components/resource/bgsmfilemanager.hpp>
#include <components/resource/bulletshapemanager.hpp>
#include <components/resource/imagemanager.hpp>
#include <components/resource/niffilemanager.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/settings/values.hpp>
#include <components/to_utf8/to_utf8.hpp>
#include <components/version/version.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/registerarchives.hpp>
#include <osg/Vec3f>
#include <boost/program_options.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <iostream>
#include <map>
#include <string>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
#ifdef WIN32
#include <fcntl.h>
#include <io.h>
#endif
namespace NavMeshTool
{
namespace
{
namespace bpo = boost::program_options;
using StringsVector = std::vector<std::string>;
constexpr std::string_view applicationName = "NavMeshTool";
bpo::options_description makeOptionsDescription()
{
using Fallback::FallbackMap;
bpo::options_description result;
auto addOption = result.add_options();
addOption("help", "print help message");
addOption("version", "print version information and quit");
addOption("data",
bpo::value<Files::MaybeQuotedPathContainer>()
->default_value(Files::MaybeQuotedPathContainer(), "data")
->multitoken()
->composing(),
"set data directories (later directories have higher priority)");
addOption("data-local",
bpo::value<Files::MaybeQuotedPathContainer::value_type>()->default_value(
Files::MaybeQuotedPathContainer::value_type(), ""),
"set local data directory (highest priority)");
addOption("fallback-archive",
bpo::value<StringsVector>()
->default_value(StringsVector(), "fallback-archive")
->multitoken()
->composing(),
"set fallback BSA archives (later archives have higher priority)");
addOption("content",
bpo::value<StringsVector>()->default_value(StringsVector(), "")->multitoken()->composing(),
"content file(s): esm/esp, or omwgame/omwaddon/omwscripts");
addOption("encoding", bpo::value<std::string>()->default_value("win1252"),
"Character encoding used in OpenMW game messages:\n"
"\n\twin1250 - Central and Eastern European such as Polish, Czech, Slovak, Hungarian, Slovene, "
"Bosnian, Croatian, Serbian (Latin script), Romanian and Albanian languages\n"
"\n\twin1251 - Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic and other languages\n"
"\n\twin1252 - Western European (Latin) alphabet, used by default");
addOption("fallback",
bpo::value<Fallback::FallbackMap>()
->default_value(Fallback::FallbackMap(), "")
->multitoken()
->composing(),
"fallback values");
addOption("threads",
bpo::value<std::size_t>()->default_value(
std::max<std::size_t>(std::thread::hardware_concurrency() - 1, 1)),
"number of threads for parallel processing");
addOption("process-interior-cells", bpo::value<bool>()->implicit_value(true)->default_value(false),
"build navmesh for interior cells");
addOption("remove-unused-tiles", bpo::value<bool>()->implicit_value(true)->default_value(false),
"remove tiles from cache that will not be used with current content profile");
addOption("write-binary-log", bpo::value<bool>()->implicit_value(true)->default_value(false),
"write progress in binary messages to be consumed by the launcher");
Files::ConfigurationManager::addCommonOptions(result);
return result;
}
int runNavMeshTool(int argc, char* argv[])
{
Platform::init();
bpo::options_description desc = makeOptionsDescription();
bpo::parsed_options options = bpo::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
bpo::variables_map variables;
bpo::store(options, variables);
bpo::notify(variables);
if (variables.find("help") != variables.end())
{
Debug::getRawStdout() << desc << std::endl;
return 0;
}
Files::ConfigurationManager config;
config.readConfiguration(variables, desc);
Debug::setupLogging(config.getLogPath(), applicationName);
const std::string encoding(variables["encoding"].as<std::string>());
Log(Debug::Info) << ToUTF8::encodingUsingMessage(encoding);
ToUTF8::Utf8Encoder encoder(ToUTF8::calculateEncoding(encoding));
Files::PathContainer dataDirs(asPathContainer(variables["data"].as<Files::MaybeQuotedPathContainer>()));
auto local = variables["data-local"].as<Files::MaybeQuotedPathContainer::value_type>();
if (!local.empty())
dataDirs.push_back(std::move(local));
config.filterOutNonExistingPaths(dataDirs);
const auto& resDir = variables["resources"].as<Files::MaybeQuotedPath>();
Log(Debug::Info) << Version::getOpenmwVersionDescription();
dataDirs.insert(dataDirs.begin(), resDir / "vfs");
const Files::Collections fileCollections(dataDirs);
const auto& archives = variables["fallback-archive"].as<StringsVector>();
StringsVector contentFiles{ "builtin.omwscripts" };
const auto& configContentFiles = variables["content"].as<StringsVector>();
contentFiles.insert(contentFiles.end(), configContentFiles.begin(), configContentFiles.end());
const std::size_t threadsNumber = variables["threads"].as<std::size_t>();
if (threadsNumber < 1)
{
std::cerr << "Invalid threads number: " << threadsNumber << ", expected >= 1";
return -1;
}
const bool processInteriorCells = variables["process-interior-cells"].as<bool>();
const bool removeUnusedTiles = variables["remove-unused-tiles"].as<bool>();
const bool writeBinaryLog = variables["write-binary-log"].as<bool>();
#ifdef WIN32
if (writeBinaryLog)
_setmode(_fileno(stderr), _O_BINARY);
#endif
Fallback::Map::init(variables["fallback"].as<Fallback::FallbackMap>().mMap);
VFS::Manager vfs;
VFS::registerArchives(&vfs, fileCollections, archives, true);
Settings::Manager::load(config);
const DetourNavigator::AgentBounds agentBounds{
Settings::game().mActorCollisionShapeType,
Settings::game().mDefaultActorPathfindHalfExtents,
};
const std::uint64_t maxDbFileSize = Settings::navigator().mMaxNavmeshdbFileSize;
const auto dbPath = Files::pathToUnicodeString(config.getUserDataPath() / "navmesh.db");
Log(Debug::Info) << "Using navmeshdb at " << dbPath;
DetourNavigator::NavMeshDb db(dbPath, maxDbFileSize);
ESM::ReadersCache readers;
EsmLoader::Query query;
query.mLoadActivators = true;
query.mLoadCells = true;
query.mLoadContainers = true;
query.mLoadDoors = true;
query.mLoadGameSettings = true;
query.mLoadLands = true;
query.mLoadStatics = true;
const EsmLoader::EsmData esmData
= EsmLoader::loadEsmData(query, contentFiles, fileCollections, readers, &encoder);
constexpr double expiryDelay = 0;
Resource::ImageManager imageManager(&vfs, expiryDelay);
Resource::NifFileManager nifFileManager(&vfs, &encoder.getStatelessEncoder());
Resource::BgsmFileManager bgsmFileManager(&vfs, expiryDelay);
Resource::SceneManager sceneManager(&vfs, &imageManager, &nifFileManager, &bgsmFileManager, expiryDelay);
Resource::BulletShapeManager bulletShapeManager(&vfs, &sceneManager, &nifFileManager, expiryDelay);
DetourNavigator::RecastGlobalAllocator::init();
DetourNavigator::Settings navigatorSettings = DetourNavigator::makeSettingsFromSettingsManager();
navigatorSettings.mRecast.mSwimHeightScale
= EsmLoader::getGameSetting(esmData.mGameSettings, "fSwimHeightScale").getFloat();
WorldspaceData cellsData = gatherWorldspaceData(
navigatorSettings, readers, vfs, bulletShapeManager, esmData, processInteriorCells, writeBinaryLog);
const Status status = generateAllNavMeshTiles(agentBounds, navigatorSettings, threadsNumber,
removeUnusedTiles, writeBinaryLog, cellsData, std::move(db));
switch (status)
{
case Status::Ok:
Log(Debug::Info) << "Done";
break;
case Status::Cancelled:
Log(Debug::Warning) << "Cancelled";
break;
case Status::NotEnoughSpace:
Log(Debug::Warning)
<< "Navmesh generation is cancelled due to running out of disk space or limits "
<< "for navmesh db. Check disk space at the db location \"" << dbPath
<< "\". If there is enough space, adjust \"max navmeshdb file size\" setting (see "
<< "https://openmw.readthedocs.io/en/latest/reference/modding/settings/"
"navigator.html?highlight=navmesh#max-navmeshdb-file-size).";
break;
}
return 0;
}
}
}
#ifdef ANDROID
extern "C" int SDL_main(int argc, char* argv[])
#else
int main(int argc, char* argv[])
#endif
{
return Debug::wrapApplication(NavMeshTool::runNavMeshTool, argc, argv, NavMeshTool::applicationName);
}
| 11,335
|
C++
|
.cpp
| 215
| 41.451163
| 120
| 0.639017
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,150
|
worldspacedata.cpp
|
OpenMW_openmw/apps/navmeshtool/worldspacedata.cpp
|
#include "worldspacedata.hpp"
#include <components/bullethelpers/aabb.hpp>
#include <components/debug/debugging.hpp>
#include <components/debug/debuglog.hpp>
#include <components/detournavigator/debug.hpp>
#include <components/detournavigator/gettilespositions.hpp>
#include <components/detournavigator/objectid.hpp>
#include <components/detournavigator/recastmesh.hpp>
#include <components/detournavigator/settings.hpp>
#include <components/detournavigator/tilecachedrecastmeshmanager.hpp>
#include <components/esm/refid.hpp>
#include <components/esm3/cellref.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/esm3/loadland.hpp>
#include <components/esm3/readerscache.hpp>
#include <components/esmloader/esmdata.hpp>
#include <components/esmloader/lessbyid.hpp>
#include <components/esmloader/record.hpp>
#include <components/misc/resourcehelpers.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/navmeshtool/protocol.hpp>
#include <components/resource/bulletshapemanager.hpp>
#include <components/settings/settings.hpp>
#include <components/vfs/manager.hpp>
#include <LinearMath/btVector3.h>
#include <osg/Vec2i>
#include <osg/ref_ptr>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>
#include <vector>
namespace NavMeshTool
{
namespace
{
using DetourNavigator::CollisionShape;
using DetourNavigator::HeightfieldPlane;
using DetourNavigator::HeightfieldShape;
using DetourNavigator::HeightfieldSurface;
using DetourNavigator::ObjectId;
using DetourNavigator::ObjectTransform;
struct CellRef
{
ESM::RecNameInts mType;
ESM::RefNum mRefNum;
ESM::RefId mRefId;
float mScale;
ESM::Position mPos;
CellRef(
ESM::RecNameInts type, ESM::RefNum refNum, ESM::RefId&& refId, float scale, const ESM::Position& pos)
: mType(type)
, mRefNum(refNum)
, mRefId(std::move(refId))
, mScale(scale)
, mPos(pos)
{
}
};
ESM::RecNameInts getType(const EsmLoader::EsmData& esmData, const ESM::RefId& refId)
{
const auto it = std::lower_bound(
esmData.mRefIdTypes.begin(), esmData.mRefIdTypes.end(), refId, EsmLoader::LessById{});
if (it == esmData.mRefIdTypes.end() || it->mId != refId)
return {};
return it->mType;
}
std::vector<CellRef> loadCellRefs(
const ESM::Cell& cell, const EsmLoader::EsmData& esmData, ESM::ReadersCache& readers)
{
std::vector<EsmLoader::Record<CellRef>> cellRefs;
for (std::size_t i = 0; i < cell.mContextList.size(); i++)
{
ESM::ReadersCache::BusyItem reader = readers.get(static_cast<std::size_t>(cell.mContextList[i].index));
cell.restore(*reader, static_cast<int>(i));
ESM::CellRef cellRef;
bool deleted = false;
while (ESM::Cell::getNextRef(*reader, cellRef, deleted))
{
const ESM::RecNameInts type = getType(esmData, cellRef.mRefID);
if (type == ESM::RecNameInts{})
continue;
cellRefs.emplace_back(
deleted, type, cellRef.mRefNum, std::move(cellRef.mRefID), cellRef.mScale, cellRef.mPos);
}
}
Log(Debug::Debug) << "Loaded " << cellRefs.size() << " cell refs";
const auto getKey = [](const EsmLoader::Record<CellRef>& v) -> ESM::RefNum { return v.mValue.mRefNum; };
std::vector<CellRef> result = prepareRecords(cellRefs, getKey);
Log(Debug::Debug) << "Prepared " << result.size() << " unique cell refs";
return result;
}
template <class F>
void forEachObject(const ESM::Cell& cell, const EsmLoader::EsmData& esmData, const VFS::Manager& vfs,
Resource::BulletShapeManager& bulletShapeManager, ESM::ReadersCache& readers, F&& f)
{
std::vector<CellRef> cellRefs = loadCellRefs(cell, esmData, readers);
Log(Debug::Debug) << "Prepared " << cellRefs.size() << " unique cell refs";
for (CellRef& cellRef : cellRefs)
{
VFS::Path::Normalized model(getModel(esmData, cellRef.mRefId, cellRef.mType));
if (model.empty())
continue;
if (cellRef.mType != ESM::REC_STAT)
model = Misc::ResourceHelpers::correctActorModelPath(model, &vfs);
osg::ref_ptr<const Resource::BulletShape> shape = [&] {
try
{
return bulletShapeManager.getShape(
VFS::Path::toNormalized(Misc::ResourceHelpers::correctMeshPath(model)));
}
catch (const std::exception& e)
{
Log(Debug::Warning) << "Failed to load cell ref \"" << cellRef.mRefId << "\" model \"" << model
<< "\": " << e.what();
return osg::ref_ptr<const Resource::BulletShape>();
}
}();
if (shape == nullptr || shape->mCollisionShape == nullptr)
continue;
osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance(
new Resource::BulletShapeInstance(std::move(shape)));
switch (cellRef.mType)
{
case ESM::REC_ACTI:
case ESM::REC_CONT:
case ESM::REC_DOOR:
case ESM::REC_STAT:
f(BulletObject(std::move(shapeInstance), cellRef.mPos, cellRef.mScale));
break;
default:
break;
}
}
}
struct GetXY
{
osg::Vec2i operator()(const ESM::Land& value) const { return osg::Vec2i(value.mX, value.mY); }
};
struct LessByXY
{
bool operator()(const ESM::Land& lhs, const ESM::Land& rhs) const { return GetXY{}(lhs) < GetXY{}(rhs); }
bool operator()(const ESM::Land& lhs, const osg::Vec2i& rhs) const { return GetXY{}(lhs) < rhs; }
bool operator()(const osg::Vec2i& lhs, const ESM::Land& rhs) const { return lhs < GetXY{}(rhs); }
};
btAABB getAabb(const osg::Vec2i& cellPosition, btScalar minHeight, btScalar maxHeight)
{
btAABB aabb;
aabb.m_min = btVector3(static_cast<btScalar>(cellPosition.x() * ESM::Land::REAL_SIZE),
static_cast<btScalar>(cellPosition.y() * ESM::Land::REAL_SIZE), minHeight);
aabb.m_max = btVector3(static_cast<btScalar>((cellPosition.x() + 1) * ESM::Land::REAL_SIZE),
static_cast<btScalar>((cellPosition.y() + 1) * ESM::Land::REAL_SIZE), maxHeight);
return aabb;
}
void mergeOrAssign(const btAABB& aabb, btAABB& target, bool& initialized)
{
if (initialized)
return target.merge(aabb);
target.m_min = aabb.m_min;
target.m_max = aabb.m_max;
initialized = true;
}
std::tuple<HeightfieldShape, float, float> makeHeightfieldShape(const std::optional<ESM::Land>& land,
const osg::Vec2i& cellPosition, std::vector<std::vector<float>>& heightfields,
std::vector<std::unique_ptr<ESM::Land::LandData>>& landDatas)
{
if (!land.has_value() || osg::Vec2i(land->mX, land->mY) != cellPosition
|| (land->mDataTypes & ESM::Land::DATA_VHGT) == 0)
return { HeightfieldPlane{ ESM::Land::DEFAULT_HEIGHT }, ESM::Land::DEFAULT_HEIGHT,
ESM::Land::DEFAULT_HEIGHT };
ESM::Land::LandData& landData = *landDatas.emplace_back(std::make_unique<ESM::Land::LandData>());
land->loadData(ESM::Land::DATA_VHGT, landData);
heightfields.push_back(std::vector<float>(std::begin(landData.mHeights), std::end(landData.mHeights)));
HeightfieldSurface surface;
surface.mHeights = heightfields.back().data();
surface.mMinHeight = landData.mMinHeight;
surface.mMaxHeight = landData.mMaxHeight;
surface.mSize = static_cast<std::size_t>(ESM::Land::LAND_SIZE);
return { surface, landData.mMinHeight, landData.mMaxHeight };
}
template <class T>
void serializeToStderr(const T& value)
{
const std::vector<std::byte> data = serialize(value);
Debug::getRawStderr().write(
reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
}
std::string makeAddObjectErrorMessage(
ObjectId objectId, DetourNavigator::AreaType areaType, const CollisionShape& shape)
{
std::ostringstream stream;
stream << "Failed to add object to recast mesh objectId=" << objectId.value() << " areaType=" << areaType
<< " fileName=" << shape.getInstance()->mFileName
<< " fileHash=" << Misc::StringUtils::toHex(shape.getInstance()->mFileHash);
return stream.str();
}
}
WorldspaceNavMeshInput::WorldspaceNavMeshInput(
ESM::RefId worldspace, const DetourNavigator::RecastSettings& settings)
: mWorldspace(worldspace)
, mTileCachedRecastMeshManager(settings)
{
mAabb.m_min = btVector3(0, 0, 0);
mAabb.m_max = btVector3(0, 0, 0);
}
WorldspaceData gatherWorldspaceData(const DetourNavigator::Settings& settings, ESM::ReadersCache& readers,
const VFS::Manager& vfs, Resource::BulletShapeManager& bulletShapeManager, const EsmLoader::EsmData& esmData,
bool processInteriorCells, bool writeBinaryLog)
{
Log(Debug::Info) << "Processing " << esmData.mCells.size() << " cells...";
std::unordered_map<ESM::RefId, std::unique_ptr<WorldspaceNavMeshInput>> navMeshInputs;
WorldspaceData data;
std::size_t objectsCounter = 0;
if (writeBinaryLog)
serializeToStderr(ExpectedCells{ static_cast<std::uint64_t>(esmData.mCells.size()) });
for (std::size_t i = 0; i < esmData.mCells.size(); ++i)
{
const ESM::Cell& cell = esmData.mCells[i];
const bool exterior = cell.isExterior();
if (!exterior && !processInteriorCells)
{
if (writeBinaryLog)
serializeToStderr(ProcessedCells{ static_cast<std::uint64_t>(i + 1) });
Log(Debug::Info) << "Skipped interior"
<< " cell (" << (i + 1) << "/" << esmData.mCells.size() << ") \""
<< cell.getDescription() << "\"";
continue;
}
Log(Debug::Debug) << "Processing " << (exterior ? "exterior" : "interior") << " cell (" << (i + 1) << "/"
<< esmData.mCells.size() << ") \"" << cell.getDescription() << "\"";
const osg::Vec2i cellPosition(cell.mData.mX, cell.mData.mY);
const std::size_t cellObjectsBegin = data.mObjects.size();
const ESM::RefId cellWorldspace = cell.isExterior() ? ESM::Cell::sDefaultWorldspaceId : cell.mId;
WorldspaceNavMeshInput& navMeshInput = [&]() -> WorldspaceNavMeshInput& {
auto it = navMeshInputs.find(cellWorldspace);
if (it == navMeshInputs.end())
{
it = navMeshInputs
.emplace(cellWorldspace,
std::make_unique<WorldspaceNavMeshInput>(cellWorldspace, settings.mRecast))
.first;
it->second->mTileCachedRecastMeshManager.setWorldspace(cellWorldspace, nullptr);
}
return *it->second;
}();
const auto guard = navMeshInput.mTileCachedRecastMeshManager.makeUpdateGuard();
if (exterior)
{
const auto it
= std::lower_bound(esmData.mLands.begin(), esmData.mLands.end(), cellPosition, LessByXY{});
const auto [heightfieldShape, minHeight, maxHeight]
= makeHeightfieldShape(it == esmData.mLands.end() ? std::optional<ESM::Land>() : *it, cellPosition,
data.mHeightfields, data.mLandData);
mergeOrAssign(
getAabb(cellPosition, minHeight, maxHeight), navMeshInput.mAabb, navMeshInput.mAabbInitialized);
navMeshInput.mTileCachedRecastMeshManager.addHeightfield(
cellPosition, ESM::Land::REAL_SIZE, heightfieldShape, guard.get());
navMeshInput.mTileCachedRecastMeshManager.addWater(cellPosition, ESM::Land::REAL_SIZE, -1, guard.get());
}
else
{
if ((cell.mData.mFlags & ESM::Cell::HasWater) != 0)
navMeshInput.mTileCachedRecastMeshManager.addWater(
cellPosition, std::numeric_limits<int>::max(), cell.mWater, guard.get());
}
forEachObject(cell, esmData, vfs, bulletShapeManager, readers, [&](BulletObject object) {
if (object.getShapeInstance()->mVisualCollisionType != Resource::VisualCollisionType::None)
return;
const btTransform& transform = object.getCollisionObject().getWorldTransform();
const btAABB aabb = BulletHelpers::getAabb(*object.getCollisionObject().getCollisionShape(), transform);
mergeOrAssign(aabb, navMeshInput.mAabb, navMeshInput.mAabbInitialized);
if (const btCollisionShape* avoid = object.getShapeInstance()->mAvoidCollisionShape.get())
navMeshInput.mAabb.merge(BulletHelpers::getAabb(*avoid, transform));
const ObjectId objectId(++objectsCounter);
const CollisionShape shape(object.getShapeInstance(), *object.getCollisionObject().getCollisionShape(),
object.getObjectTransform());
if (!navMeshInput.mTileCachedRecastMeshManager.addObject(
objectId, shape, transform, DetourNavigator::AreaType_ground, guard.get()))
throw std::logic_error(
makeAddObjectErrorMessage(objectId, DetourNavigator::AreaType_ground, shape));
if (const btCollisionShape* avoid = object.getShapeInstance()->mAvoidCollisionShape.get())
{
const ObjectId avoidObjectId(++objectsCounter);
const CollisionShape avoidShape(object.getShapeInstance(), *avoid, object.getObjectTransform());
if (!navMeshInput.mTileCachedRecastMeshManager.addObject(
avoidObjectId, avoidShape, transform, DetourNavigator::AreaType_null, guard.get()))
throw std::logic_error(
makeAddObjectErrorMessage(avoidObjectId, DetourNavigator::AreaType_null, avoidShape));
}
data.mObjects.emplace_back(std::move(object));
});
const auto cellDescription = cell.getDescription();
if (writeBinaryLog)
serializeToStderr(ProcessedCells{ static_cast<std::uint64_t>(i + 1) });
Log(Debug::Info) << "Processed " << (exterior ? "exterior" : "interior") << " cell (" << (i + 1) << "/"
<< esmData.mCells.size() << ") " << cellDescription << " with "
<< (data.mObjects.size() - cellObjectsBegin) << " objects";
}
data.mNavMeshInputs.reserve(navMeshInputs.size());
std::transform(navMeshInputs.begin(), navMeshInputs.end(), std::back_inserter(data.mNavMeshInputs),
[](auto& v) { return std::move(v.second); });
Log(Debug::Info) << "Processed " << esmData.mCells.size() << " cells, added " << data.mObjects.size()
<< " objects and " << data.mHeightfields.size() << " height fields";
return data;
}
}
| 16,708
|
C++
|
.cpp
| 312
| 39.99359
| 120
| 0.584058
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,151
|
navmesh.cpp
|
OpenMW_openmw/apps/navmeshtool/navmesh.cpp
|
#include "navmesh.hpp"
#include "worldspacedata.hpp"
#include <components/debug/debugging.hpp>
#include <components/debug/debuglog.hpp>
#include <components/detournavigator/generatenavmeshtile.hpp>
#include <components/detournavigator/gettilespositions.hpp>
#include <components/detournavigator/navmeshdb.hpp>
#include <components/detournavigator/navmeshdbutils.hpp>
#include <components/detournavigator/preparednavmeshdata.hpp>
#include <components/detournavigator/recastmesh.hpp>
#include <components/detournavigator/recastmeshprovider.hpp>
#include <components/detournavigator/serialization.hpp>
#include <components/detournavigator/settings.hpp>
#include <components/detournavigator/tileposition.hpp>
#include <components/misc/progressreporter.hpp>
#include <components/navmeshtool/protocol.hpp>
#include <components/sceneutil/workqueue.hpp>
#include <components/sqlite3/transaction.hpp>
#include <osg/Vec3f>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <random>
#include <string_view>
#include <utility>
#include <vector>
namespace NavMeshTool
{
namespace
{
using DetourNavigator::AgentBounds;
using DetourNavigator::GenerateNavMeshTile;
using DetourNavigator::MeshSource;
using DetourNavigator::NavMeshDb;
using DetourNavigator::NavMeshTileInfo;
using DetourNavigator::PreparedNavMeshData;
using DetourNavigator::RecastMeshProvider;
using DetourNavigator::Settings;
using DetourNavigator::ShapeId;
using DetourNavigator::TileId;
using DetourNavigator::TilePosition;
using DetourNavigator::TilesPositionsRange;
using DetourNavigator::TileVersion;
using Sqlite3::Transaction;
void logGeneratedTiles(std::size_t provided, std::size_t expected)
{
Log(Debug::Info) << provided << "/" << expected << " ("
<< (static_cast<double>(provided) / static_cast<double>(expected) * 100)
<< "%) navmesh tiles are generated";
}
template <class T>
void serializeToStderr(const T& value)
{
const std::vector<std::byte> data = serialize(value);
Debug::getLockedRawStderr()->write(
reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
}
void logGeneratedTilesMessage(std::size_t number)
{
serializeToStderr(GeneratedTiles{ static_cast<std::uint64_t>(number) });
}
struct LogGeneratedTiles
{
void operator()(std::size_t provided, std::size_t expected) const { logGeneratedTiles(provided, expected); }
};
class NavMeshTileConsumer final : public DetourNavigator::NavMeshTileConsumer
{
public:
std::atomic_size_t mExpected{ 0 };
explicit NavMeshTileConsumer(NavMeshDb&& db, bool removeUnusedTiles, bool writeBinaryLog)
: mDb(std::move(db))
, mRemoveUnusedTiles(removeUnusedTiles)
, mWriteBinaryLog(writeBinaryLog)
, mTransaction(mDb.startTransaction(Sqlite3::TransactionMode::Immediate))
, mNextTileId(mDb.getMaxTileId() + 1)
, mNextShapeId(mDb.getMaxShapeId() + 1)
{
}
std::size_t getProvided() const { return mProvided.load(); }
std::size_t getInserted() const { return mInserted.load(); }
std::size_t getUpdated() const { return mUpdated.load(); }
std::size_t getDeleted() const
{
const std::lock_guard lock(mMutex);
return mDeleted;
}
std::int64_t resolveMeshSource(const MeshSource& source) override
{
const std::lock_guard lock(mMutex);
return DetourNavigator::resolveMeshSource(mDb, source, mNextShapeId);
}
std::optional<NavMeshTileInfo> find(
ESM::RefId worldspace, const TilePosition& tilePosition, const std::vector<std::byte>& input) override
{
std::optional<NavMeshTileInfo> result;
std::lock_guard lock(mMutex);
if (const auto tile = mDb.findTile(worldspace, tilePosition, input))
{
NavMeshTileInfo info;
info.mTileId = tile->mTileId;
info.mVersion = tile->mVersion;
result.emplace(info);
}
return result;
}
void ignore(ESM::RefId worldspace, const TilePosition& tilePosition) override
{
if (mRemoveUnusedTiles)
{
std::lock_guard lock(mMutex);
mDeleted += static_cast<std::size_t>(mDb.deleteTilesAt(worldspace, tilePosition));
}
report();
}
void identity(ESM::RefId worldspace, const TilePosition& tilePosition, std::int64_t tileId) override
{
if (mRemoveUnusedTiles)
{
std::lock_guard lock(mMutex);
mDeleted += static_cast<std::size_t>(
mDb.deleteTilesAtExcept(worldspace, tilePosition, TileId{ tileId }));
}
report();
}
void insert(ESM::RefId worldspace, const TilePosition& tilePosition, std::int64_t version,
const std::vector<std::byte>& input, PreparedNavMeshData& data) override
{
{
std::lock_guard lock(mMutex);
if (mRemoveUnusedTiles)
mDeleted += static_cast<std::size_t>(mDb.deleteTilesAt(worldspace, tilePosition));
data.mUserId = static_cast<unsigned>(mNextTileId);
mDb.insertTile(
mNextTileId, worldspace, tilePosition, TileVersion{ version }, input, serialize(data));
++mNextTileId;
}
++mInserted;
report();
}
void update(ESM::RefId worldspace, const TilePosition& tilePosition, std::int64_t tileId,
std::int64_t version, PreparedNavMeshData& data) override
{
data.mUserId = static_cast<unsigned>(tileId);
{
std::lock_guard lock(mMutex);
if (mRemoveUnusedTiles)
mDeleted += static_cast<std::size_t>(
mDb.deleteTilesAtExcept(worldspace, tilePosition, TileId{ tileId }));
mDb.updateTile(TileId{ tileId }, TileVersion{ version }, serialize(data));
}
++mUpdated;
report();
}
void cancel(std::string_view reason) override
{
std::unique_lock lock(mMutex);
if (reason.find("database or disk is full") != std::string_view::npos)
mStatus = Status::NotEnoughSpace;
else
mStatus = Status::Cancelled;
mHasTile.notify_one();
}
Status wait()
{
constexpr std::chrono::seconds transactionInterval(1);
std::unique_lock lock(mMutex);
auto start = std::chrono::steady_clock::now();
while (mProvided < mExpected && mStatus == Status::Ok)
{
mHasTile.wait(lock);
const auto now = std::chrono::steady_clock::now();
if (now - start > transactionInterval)
{
mTransaction.commit();
mTransaction = mDb.startTransaction(Sqlite3::TransactionMode::Immediate);
start = now;
}
}
logGeneratedTiles(mProvided, mExpected);
if (mWriteBinaryLog)
logGeneratedTilesMessage(mProvided);
return mStatus;
}
void commit()
{
const std::lock_guard lock(mMutex);
mTransaction.commit();
}
void vacuum()
{
const std::lock_guard lock(mMutex);
mDb.vacuum();
}
void removeTilesOutsideRange(ESM::RefId worldspace, const TilesPositionsRange& range)
{
const std::lock_guard lock(mMutex);
mTransaction.commit();
Log(Debug::Info) << "Removing tiles outside processed range for worldspace \"" << worldspace << "\"...";
mDeleted += static_cast<std::size_t>(mDb.deleteTilesOutsideRange(worldspace, range));
mTransaction = mDb.startTransaction(Sqlite3::TransactionMode::Immediate);
}
private:
std::atomic_size_t mProvided{ 0 };
std::atomic_size_t mInserted{ 0 };
std::atomic_size_t mUpdated{ 0 };
std::size_t mDeleted = 0;
Status mStatus = Status::Ok;
mutable std::mutex mMutex;
NavMeshDb mDb;
const bool mRemoveUnusedTiles;
const bool mWriteBinaryLog;
Transaction mTransaction;
TileId mNextTileId;
std::condition_variable mHasTile;
Misc::ProgressReporter<LogGeneratedTiles> mReporter;
ShapeId mNextShapeId;
std::mutex mReportMutex;
void report()
{
const std::size_t provided = mProvided.fetch_add(1, std::memory_order_relaxed) + 1;
mReporter(provided, mExpected);
mHasTile.notify_one();
if (mWriteBinaryLog)
logGeneratedTilesMessage(provided);
}
};
}
Status generateAllNavMeshTiles(const AgentBounds& agentBounds, const Settings& settings, std::size_t threadsNumber,
bool removeUnusedTiles, bool writeBinaryLog, WorldspaceData& data, NavMeshDb&& db)
{
Log(Debug::Info) << "Generating navmesh tiles by " << threadsNumber << " parallel workers...";
SceneUtil::WorkQueue workQueue(threadsNumber);
auto navMeshTileConsumer
= std::make_shared<NavMeshTileConsumer>(std::move(db), removeUnusedTiles, writeBinaryLog);
std::size_t tiles = 0;
std::mt19937_64 random;
for (const std::unique_ptr<WorldspaceNavMeshInput>& input : data.mNavMeshInputs)
{
const auto range = DetourNavigator::makeTilesPositionsRange(Misc::Convert::toOsgXY(input->mAabb.m_min),
Misc::Convert::toOsgXY(input->mAabb.m_max), settings.mRecast);
if (removeUnusedTiles)
navMeshTileConsumer->removeTilesOutsideRange(input->mWorldspace, range);
std::vector<TilePosition> worldspaceTiles;
DetourNavigator::getTilesPositions(
range, [&](const TilePosition& tilePosition) { worldspaceTiles.push_back(tilePosition); });
tiles += worldspaceTiles.size();
if (writeBinaryLog)
serializeToStderr(ExpectedTiles{ static_cast<std::uint64_t>(tiles) });
navMeshTileConsumer->mExpected = tiles;
std::shuffle(worldspaceTiles.begin(), worldspaceTiles.end(), random);
for (const TilePosition& tilePosition : worldspaceTiles)
workQueue.addWorkItem(new GenerateNavMeshTile(input->mWorldspace, tilePosition,
RecastMeshProvider(input->mTileCachedRecastMeshManager), agentBounds, settings,
navMeshTileConsumer));
}
const Status status = navMeshTileConsumer->wait();
if (status == Status::Ok)
navMeshTileConsumer->commit();
const auto inserted = navMeshTileConsumer->getInserted();
const auto updated = navMeshTileConsumer->getUpdated();
const auto deleted = navMeshTileConsumer->getDeleted();
Log(Debug::Info) << "Generated navmesh for " << navMeshTileConsumer->getProvided() << " tiles, " << inserted
<< " are inserted, " << updated << " updated and " << deleted << " deleted";
if (inserted + updated + deleted > 0)
{
Log(Debug::Info) << "Vacuuming the database...";
navMeshTileConsumer->vacuum();
}
return status;
}
}
| 12,590
|
C++
|
.cpp
| 271
| 33.166052
| 120
| 0.583788
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,152
|
importnpcc.cpp
|
OpenMW_openmw/apps/essimporter/importnpcc.cpp
|
#include "importnpcc.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void NPCC::load(ESM::ESMReader& esm)
{
esm.getHNT("NPDT", mNPDT.mDisposition, mNPDT.unknown, mNPDT.mReputation, mNPDT.unknown2, mNPDT.mIndex);
while (esm.isNextSub("AI_W") || esm.isNextSub("AI_E") || esm.isNextSub("AI_T") || esm.isNextSub("AI_F")
|| esm.isNextSub("AI_A"))
mAiPackages.add(esm);
mInventory.load(esm);
}
}
| 476
|
C++
|
.cpp
| 13
| 30.538462
| 111
| 0.643326
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,153
|
convertplayer.cpp
|
OpenMW_openmw/apps/essimporter/convertplayer.cpp
|
#include "convertplayer.hpp"
#include <cmath>
#include <components/esm3/loadcell.hpp>
#include <components/misc/constants.hpp>
#include <components/misc/strings/lower.hpp>
namespace ESSImport
{
void convertPCDT(const PCDT& pcdt, ESM::Player& out, std::vector<ESM::RefId>& outDialogueTopics,
bool& firstPersonCam, bool& teleportingEnabled, bool& levitationEnabled, ESM::ControlsState& controls)
{
out.mObject.mPosition.rot[0]
= -atan2(pcdt.mPNAM.mVerticalRotation.mData[2][1], pcdt.mPNAM.mVerticalRotation.mData[2][2]);
out.mBirthsign = ESM::RefId::stringRefId(pcdt.mBirthsign);
out.mObject.mNpcStats.mBounty = pcdt.mBounty;
for (const auto& essFaction : pcdt.mFactions)
{
ESM::NpcStats::Faction faction;
faction.mExpelled = (essFaction.mFlags & 0x2) != 0;
faction.mRank = essFaction.mRank;
faction.mReputation = essFaction.mReputation;
out.mObject.mNpcStats.mFactions[ESM::RefId::stringRefId(essFaction.mFactionName.toString())] = faction;
}
for (size_t i = 0; i < out.mObject.mNpcStats.mSpecIncreases.size(); ++i)
out.mObject.mNpcStats.mSpecIncreases[i] = pcdt.mPNAM.mSpecIncreases[i];
for (size_t i = 0; i < out.mObject.mNpcStats.mSkillIncrease.size(); ++i)
out.mObject.mNpcStats.mSkillIncrease[i] = pcdt.mPNAM.mSkillIncreases[i];
for (size_t i = 0; i < out.mObject.mNpcStats.mSkills.size(); ++i)
out.mObject.mNpcStats.mSkills[i].mProgress = pcdt.mPNAM.mSkillProgress[i];
out.mObject.mNpcStats.mLevelProgress = pcdt.mPNAM.mLevelProgress;
if (pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_WeaponDrawn)
out.mObject.mCreatureStats.mDrawState = 1;
if (pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_SpellDrawn)
out.mObject.mCreatureStats.mDrawState = 2;
firstPersonCam = !(pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_ThirdPerson);
teleportingEnabled = !(pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_TeleportingDisabled);
levitationEnabled = !(pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_LevitationDisabled);
for (const auto& knownDialogueTopic : pcdt.mKnownDialogueTopics)
{
outDialogueTopics.push_back(ESM::RefId::stringRefId(knownDialogueTopic));
}
controls.mViewSwitchDisabled = pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_ViewSwitchDisabled;
controls.mControlsDisabled = pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_ControlsDisabled;
controls.mJumpingDisabled = pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_JumpingDisabled;
controls.mLookingDisabled = pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_LookingDisabled;
controls.mVanityModeDisabled = pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_VanityModeDisabled;
controls.mWeaponDrawingDisabled = pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_WeaponDrawingDisabled;
controls.mSpellDrawingDisabled = pcdt.mPNAM.mPlayerFlags & PCDT::PlayerFlags_SpellDrawingDisabled;
if (pcdt.mHasMark)
{
out.mHasMark = 1;
const PCDT::PNAM::MarkLocation& mark = pcdt.mPNAM.mMarkLocation;
// TODO: Figure out a better way to detect interiors. (0, 0) is a valid exterior cell.
bool interior = mark.mCellX == 0 && mark.mCellY == 0;
ESM::RefId cell = ESM::Cell::generateIdForCell(!interior, pcdt.mMNAM, mark.mCellX, mark.mCellY);
out.mMarkedCell = cell;
out.mMarkedPosition.pos[0] = mark.mX;
out.mMarkedPosition.pos[1] = mark.mY;
out.mMarkedPosition.pos[2] = mark.mZ;
out.mMarkedPosition.rot[0] = out.mMarkedPosition.rot[1] = 0.0f;
out.mMarkedPosition.rot[2] = mark.mRotZ;
}
if (pcdt.mHasENAM)
{
out.mLastKnownExteriorPosition[0] = (pcdt.mENAM.mCellX + 0.5f) * Constants::CellSizeInUnits;
out.mLastKnownExteriorPosition[1] = (pcdt.mENAM.mCellY + 0.5f) * Constants::CellSizeInUnits;
out.mLastKnownExteriorPosition[2] = 0.0f;
}
}
}
| 4,139
|
C++
|
.cpp
| 69
| 50.362319
| 115
| 0.68434
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,154
|
convertcrec.cpp
|
OpenMW_openmw/apps/essimporter/convertcrec.cpp
|
#include "convertcrec.hpp"
#include "convertinventory.hpp"
namespace ESSImport
{
void convertCREC(const CREC& crec, ESM::CreatureState& state)
{
convertInventory(crec.mInventory, state.mInventory);
}
}
| 226
|
C++
|
.cpp
| 9
| 21.444444
| 65
| 0.746479
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,155
|
importcntc.cpp
|
OpenMW_openmw/apps/essimporter/importcntc.cpp
|
#include "importcntc.hpp"
#include <components/esm3/esmreader.hpp>
#include <cstdint>
namespace ESSImport
{
void CNTC::load(ESM::ESMReader& esm)
{
mIndex = 0;
esm.getHNT(mIndex, "INDX");
mInventory.load(esm);
}
}
| 254
|
C++
|
.cpp
| 12
| 16.75
| 40
| 0.654008
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,156
|
importer.cpp
|
OpenMW_openmw/apps/essimporter/importer.cpp
|
#include "importer.hpp"
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <osg/ImageUtils>
#include <osgDB/ReadFile>
#include <components/esm/defs.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/player.hpp>
#include <components/esm3/savedgame.hpp>
#include <components/esm3/cellid.hpp>
#include <components/esm3/loadalch.hpp>
#include <components/esm3/loadarmo.hpp>
#include <components/esm3/loadclot.hpp>
#include <components/esm3/loadench.hpp>
#include <components/esm3/loadlevlist.hpp>
#include <components/esm3/loadspel.hpp>
#include <components/esm3/loadweap.hpp>
#include <components/misc/constants.hpp>
#include <components/to_utf8/to_utf8.hpp>
#include "importercontext.hpp"
#include "converter.hpp"
namespace
{
void writeScreenshot(const ESM::Header& fileHeader, ESM::SavedGame& out)
{
if (fileHeader.mSCRS.size() != 128 * 128 * 4)
{
std::cerr << "Error: unexpected screenshot size " << std::endl;
return;
}
osg::ref_ptr<osg::Image> image(new osg::Image);
image->allocateImage(128, 128, 1, GL_RGB, GL_UNSIGNED_BYTE);
// need to convert pixel format from BGRA to RGB as the jpg readerwriter doesn't support it otherwise
auto it = fileHeader.mSCRS.begin();
for (int y = 0; y < 128; ++y)
{
for (int x = 0; x < 128; ++x)
{
assert(image->data(x, y));
*(image->data(x, y) + 2) = *it++;
*(image->data(x, y) + 1) = *it++;
*image->data(x, y) = *it++;
++it; // skip alpha
}
}
image->flipVertical();
std::stringstream ostream;
osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("jpg");
if (!readerwriter)
{
std::cerr << "Error: can't write screenshot: no jpg readerwriter found" << std::endl;
return;
}
osgDB::ReaderWriter::WriteResult result = readerwriter->writeImage(*image, ostream);
if (!result.success())
{
std::cerr << "Error: can't write screenshot: " << result.message() << " code " << result.status()
<< std::endl;
return;
}
std::string data = ostream.str();
out.mScreenshot = std::vector<char>(data.begin(), data.end());
}
}
namespace ESSImport
{
Importer::Importer(
const std::filesystem::path& essfile, const std::filesystem::path& outfile, const std::string& encoding)
: mEssFile(essfile)
, mOutFile(outfile)
, mEncoding(encoding)
{
}
struct File
{
struct Subrecord
{
std::string mName;
size_t mFileOffset;
std::vector<unsigned char> mData;
};
struct Record
{
std::string mName;
size_t mFileOffset;
std::vector<Subrecord> mSubrecords;
};
std::vector<Record> mRecords;
};
void read(const std::filesystem::path& filename, File& file)
{
ESM::ESMReader esm;
esm.open(filename);
while (esm.hasMoreRecs())
{
ESM::NAME n = esm.getRecName();
esm.getRecHeader();
File::Record rec;
rec.mName = n.toString();
rec.mFileOffset = esm.getFileOffset();
while (esm.hasMoreSubs())
{
File::Subrecord sub;
esm.getSubName();
esm.getSubHeader();
sub.mFileOffset = esm.getFileOffset();
sub.mName = esm.retSubName().toString();
sub.mData.resize(esm.getSubSize());
esm.getExact(sub.mData.data(), sub.mData.size());
rec.mSubrecords.push_back(sub);
}
file.mRecords.push_back(rec);
}
}
void Importer::compare()
{
// data that always changes (and/or is already fully decoded) should be blacklisted
std::set<std::pair<std::string, std::string>> blacklist;
blacklist.insert(std::make_pair("GLOB", "FLTV")); // gamehour
blacklist.insert(std::make_pair("REFR", "DATA")); // player position
blacklist.insert(std::make_pair("CELL", "NAM8")); // fog of war
blacklist.insert(std::make_pair("GAME", "GMDT")); // weather data, current time always changes
blacklist.insert(std::make_pair("CELL", "DELE")); // first 3 bytes are uninitialized
// this changes way too often, name suggests some renderer internal data?
blacklist.insert(std::make_pair("CELL", "ND3D"));
blacklist.insert(std::make_pair("REFR", "ND3D"));
File file1;
read(mEssFile, file1);
File file2;
read(mOutFile, file2); // todo rename variable
// FIXME: use max(size1, size2)
for (size_t i = 0; i < file1.mRecords.size(); ++i)
{
File::Record rec = file1.mRecords[i];
if (i >= file2.mRecords.size())
{
std::ios::fmtflags f(std::cout.flags());
std::cout << "Record in file1 not present in file2: (1) 0x" << std::hex << rec.mFileOffset << std::endl;
std::cout.flags(f);
return;
}
File::Record rec2 = file2.mRecords[i];
if (rec.mName != rec2.mName)
{
std::ios::fmtflags f(std::cout.flags());
std::cout << "Different record name at (2) 0x" << std::hex << rec2.mFileOffset << std::endl;
std::cout.flags(f);
return; // TODO: try to recover
}
// FIXME: use max(size1, size2)
for (size_t j = 0; j < rec.mSubrecords.size(); ++j)
{
File::Subrecord sub = rec.mSubrecords[j];
if (j >= rec2.mSubrecords.size())
{
std::ios::fmtflags f(std::cout.flags());
std::cout << "Subrecord in file1 not present in file2: (1) 0x" << std::hex << sub.mFileOffset
<< std::endl;
std::cout.flags(f);
return;
}
File::Subrecord sub2 = rec2.mSubrecords[j];
if (sub.mName != sub2.mName)
{
std::ios::fmtflags f(std::cout.flags());
std::cout << "Different subrecord name (" << rec.mName << "." << sub.mName << " vs. " << sub2.mName
<< ") at (1) 0x" << std::hex << sub.mFileOffset << " (2) 0x" << sub2.mFileOffset
<< std::endl;
std::cout.flags(f);
break; // TODO: try to recover
}
if (sub.mData != sub2.mData)
{
if (blacklist.find(std::make_pair(rec.mName, sub.mName)) != blacklist.end())
continue;
std::ios::fmtflags f(std::cout.flags());
std::cout << "Different subrecord data for " << rec.mName << "." << sub.mName << " at (1) 0x"
<< std::hex << sub.mFileOffset << " (2) 0x" << sub2.mFileOffset << std::endl;
std::cout << "Data 1:" << std::endl;
for (size_t k = 0; k < sub.mData.size(); ++k)
{
bool different = false;
if (k >= sub2.mData.size() || sub2.mData[k] != sub.mData[k])
different = true;
if (different)
std::cout << "\033[033m";
std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)sub.mData[k] << " ";
if (different)
std::cout << "\033[0m";
}
std::cout << std::endl;
std::cout << "Data 2:" << std::endl;
for (size_t k = 0; k < sub2.mData.size(); ++k)
{
bool different = false;
if (k >= sub.mData.size() || sub.mData[k] != sub2.mData[k])
different = true;
if (different)
std::cout << "\033[033m";
std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)sub2.mData[k] << " ";
if (different)
std::cout << "\033[0m";
}
std::cout << std::endl;
std::cout.flags(f);
}
}
}
}
void Importer::run()
{
ToUTF8::Utf8Encoder encoder(ToUTF8::calculateEncoding(mEncoding));
ESM::ESMReader esm;
esm.open(mEssFile);
esm.setEncoder(&encoder);
Context context;
const ESM::Header& header = esm.getHeader();
context.mPlayerCellName = header.mGameData.mCurrentCell.toString();
const unsigned int recREFR = ESM::fourCC("REFR");
const unsigned int recPCDT = ESM::fourCC("PCDT");
const unsigned int recFMAP = ESM::fourCC("FMAP");
const unsigned int recKLST = ESM::fourCC("KLST");
const unsigned int recSTLN = ESM::fourCC("STLN");
const unsigned int recGAME = ESM::fourCC("GAME");
const unsigned int recJOUR = ESM::fourCC("JOUR");
const unsigned int recSPLM = ESM::fourCC("SPLM");
std::map<unsigned int, std::unique_ptr<Converter>> converters;
converters[ESM::REC_GLOB] = std::make_unique<ConvertGlobal>();
converters[ESM::REC_BOOK] = std::make_unique<ConvertBook>();
converters[ESM::REC_NPC_] = std::make_unique<ConvertNPC>();
converters[ESM::REC_CREA] = std::make_unique<ConvertCREA>();
converters[ESM::REC_NPCC] = std::make_unique<ConvertNPCC>();
converters[ESM::REC_CREC] = std::make_unique<ConvertCREC>();
converters[recREFR] = std::make_unique<ConvertREFR>();
converters[recPCDT] = std::make_unique<ConvertPCDT>();
converters[recFMAP] = std::make_unique<ConvertFMAP>();
converters[recKLST] = std::make_unique<ConvertKLST>();
converters[recSTLN] = std::make_unique<ConvertSTLN>();
converters[recGAME] = std::make_unique<ConvertGAME>();
converters[ESM::REC_CELL] = std::make_unique<ConvertCell>();
converters[ESM::REC_ALCH] = std::make_unique<DefaultConverter<ESM::Potion>>();
converters[ESM::REC_CLAS] = std::make_unique<ConvertClass>();
converters[ESM::REC_SPEL] = std::make_unique<DefaultConverter<ESM::Spell>>();
converters[ESM::REC_ARMO] = std::make_unique<DefaultConverter<ESM::Armor>>();
converters[ESM::REC_WEAP] = std::make_unique<DefaultConverter<ESM::Weapon>>();
converters[ESM::REC_CLOT] = std::make_unique<DefaultConverter<ESM::Clothing>>();
converters[ESM::REC_ENCH] = std::make_unique<DefaultConverter<ESM::Enchantment>>();
converters[ESM::REC_WEAP] = std::make_unique<DefaultConverter<ESM::Weapon>>();
converters[ESM::REC_LEVC] = std::make_unique<DefaultConverter<ESM::CreatureLevList>>();
converters[ESM::REC_LEVI] = std::make_unique<DefaultConverter<ESM::ItemLevList>>();
converters[ESM::REC_CNTC] = std::make_unique<ConvertCNTC>();
converters[ESM::REC_FACT] = std::make_unique<ConvertFACT>();
converters[ESM::REC_INFO] = std::make_unique<ConvertINFO>();
converters[ESM::REC_DIAL] = std::make_unique<ConvertDIAL>();
converters[ESM::REC_QUES] = std::make_unique<ConvertQUES>();
converters[recJOUR] = std::make_unique<ConvertJOUR>();
converters[ESM::REC_SCPT] = std::make_unique<ConvertSCPT>();
converters[ESM::REC_PROJ] = std::make_unique<ConvertPROJ>();
converters[recSPLM] = std::make_unique<ConvertSPLM>();
// TODO:
// - REGN (weather in certain regions?)
// - VFXM
// - SPLM (active spell effects)
std::set<unsigned int> unknownRecords;
for (const auto& converter : converters)
{
converter.second->setContext(context);
}
while (esm.hasMoreRecs())
{
ESM::NAME n = esm.getRecName();
esm.getRecHeader();
auto it = converters.find(n.toInt());
if (it != converters.end())
{
it->second->read(esm);
}
else
{
if (unknownRecords.insert(n.toInt()).second)
{
std::ios::fmtflags f(std::cerr.flags());
std::cerr << "Error: unknown record " << n.toString() << " (0x" << std::hex << esm.getFileOffset()
<< ")" << std::endl;
std::cerr.flags(f);
}
esm.skipRecord();
}
}
ESM::ESMWriter writer;
writer.setFormatVersion(ESM::CurrentSaveGameFormatVersion);
std::ofstream stream(mOutFile, std::ios::out | std::ios::binary);
// all unused
writer.setVersion(0);
writer.setType(0);
writer.setAuthor("");
writer.setDescription("");
writer.setRecordCount(0);
for (const auto& master : header.mMaster)
writer.addMaster(master.name, 0); // not using the size information anyway -> use value of 0
writer.save(stream);
ESM::SavedGame profile;
for (const auto& master : header.mMaster)
{
profile.mContentFiles.push_back(master.name);
}
profile.mDescription = esm.getDesc();
profile.mInGameTime.mDay = context.mDay;
profile.mInGameTime.mGameHour = context.mHour;
profile.mInGameTime.mMonth = context.mMonth;
profile.mInGameTime.mYear = context.mYear;
profile.mTimePlayed = 0;
profile.mPlayerCellName = context.mPlayerCellName;
if (context.mPlayerBase.mClass == "NEWCLASSID_CHARGEN")
profile.mPlayerClassName = context.mCustomPlayerClassName;
else
profile.mPlayerClassId = context.mPlayerBase.mClass;
profile.mPlayerLevel = context.mPlayerBase.mNpdt.mLevel;
profile.mPlayerName = header.mGameData.mPlayerName.toString();
writeScreenshot(header, profile);
writer.startRecord(ESM::REC_SAVE);
profile.save(writer);
writer.endRecord(ESM::REC_SAVE);
// Writing order should be Dynamic Store -> Cells -> Player,
// so that references to dynamic records can be recognized when loading
for (auto it = converters.begin(); it != converters.end(); ++it)
{
if (it->second->getStage() != 0)
continue;
it->second->write(writer);
}
writer.startRecord(ESM::REC_NPC_);
context.mPlayerBase.mId = ESM::RefId::stringRefId("Player");
context.mPlayerBase.save(writer);
writer.endRecord(ESM::REC_NPC_);
for (auto it = converters.begin(); it != converters.end(); ++it)
{
if (it->second->getStage() != 1)
continue;
it->second->write(writer);
}
writer.startRecord(ESM::REC_PLAY);
ESM::CellId cellId = ESM::CellId::extractFromRefId(context.mPlayer.mCellId);
int cellX = static_cast<int>(std::floor(context.mPlayer.mObject.mPosition.pos[0] / Constants::CellSizeInUnits));
int cellY = static_cast<int>(std::floor(context.mPlayer.mObject.mPosition.pos[1] / Constants::CellSizeInUnits));
context.mPlayer.mCellId = ESM::Cell::generateIdForCell(cellId.mPaged, cellId.mWorldspace, cellX, cellY);
context.mPlayer.save(writer);
writer.endRecord(ESM::REC_PLAY);
writer.startRecord(ESM::REC_ACTC);
writer.writeHNT("COUN", context.mNextActorId);
writer.endRecord(ESM::REC_ACTC);
// Stage 2 requires cell references to be written / actors IDs assigned
for (auto it = converters.begin(); it != converters.end(); ++it)
{
if (it->second->getStage() != 2)
continue;
it->second->write(writer);
}
writer.startRecord(ESM::REC_DIAS);
context.mDialogueState.save(writer);
writer.endRecord(ESM::REC_DIAS);
writer.startRecord(ESM::REC_INPU);
context.mControlsState.save(writer);
writer.endRecord(ESM::REC_INPU);
}
}
| 16,668
|
C++
|
.cpp
| 368
| 33.483696
| 120
| 0.553063
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,157
|
main.cpp
|
OpenMW_openmw/apps/essimporter/main.cpp
|
#include <filesystem>
#include <iostream>
#include <boost/program_options.hpp>
#include <components/files/configurationmanager.hpp>
#include "importer.hpp"
namespace bpo = boost::program_options;
int main(int argc, char** argv)
{
try
{
bpo::options_description desc(R"(Syntax: openmw-essimporter <options> infile.ess outfile.omwsave
Allowed options)");
bpo::positional_options_description p_desc;
auto addOption = desc.add_options();
addOption("help,h", "produce help message");
addOption("mwsave,m", bpo::value<Files::MaybeQuotedPath>(), "morrowind .ess save file");
addOption("output,o", bpo::value<Files::MaybeQuotedPath>(), "output file (.omwsave)");
addOption("compare,c", "compare two .ess files");
addOption("encoding", boost::program_options::value<std::string>()->default_value("win1252"),
"encoding of the save file");
p_desc.add("mwsave", 1).add("output", 1);
Files::ConfigurationManager::addCommonOptions(desc);
bpo::variables_map variables;
bpo::parsed_options parsed = bpo::command_line_parser(argc, argv).options(desc).positional(p_desc).run();
bpo::store(parsed, variables);
if (variables.count("help") || !variables.count("mwsave") || !variables.count("output"))
{
std::cout << desc;
return 0;
}
bpo::notify(variables);
Files::ConfigurationManager cfgManager(true);
cfgManager.readConfiguration(variables, desc);
const auto& essFile = variables["mwsave"].as<Files::MaybeQuotedPath>();
const auto& outputFile = variables["output"].as<Files::MaybeQuotedPath>();
std::string encoding = variables["encoding"].as<std::string>();
ESSImport::Importer importer(essFile, outputFile, encoding);
if (variables.count("compare"))
importer.compare();
else
{
static constexpr std::u8string_view ext{ u8".omwsave" };
const auto length = outputFile.native().size();
if (std::filesystem::exists(outputFile)
&& (length < ext.size() || outputFile.u8string().substr(length - ext.size()) != ext))
{
throw std::runtime_error(
"Output file already exists and does not end in .omwsave. Did you mean to use --compare?");
}
importer.run();
}
}
catch (std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
| 2,581
|
C++
|
.cpp
| 59
| 35.186441
| 113
| 0.618022
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,158
|
importklst.cpp
|
OpenMW_openmw/apps/essimporter/importklst.cpp
|
#include "importklst.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void KLST::load(ESM::ESMReader& esm)
{
while (esm.isNextSub("KNAM"))
{
std::string refId = esm.getHString();
int32_t count;
esm.getHNT(count, "CNAM");
mKillCounter[refId] = count;
}
mWerewolfKills = 0;
esm.getHNOT(mWerewolfKills, "INTV");
}
}
| 437
|
C++
|
.cpp
| 17
| 18.529412
| 49
| 0.578313
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,159
|
importdial.cpp
|
OpenMW_openmw/apps/essimporter/importdial.cpp
|
#include "importdial.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void DIAL::load(ESM::ESMReader& esm)
{
// See ESM::Dialogue::Type enum, not sure why we would need this here though
int32_t type = 0;
esm.getHNOT(type, "DATA");
// Deleted dialogue in a savefile. No clue what this means...
int32_t deleted = 0;
esm.getHNOT(deleted, "DELE");
mIndex = 0;
// *should* always occur except when the dialogue is deleted, but leaving it optional just in case...
esm.getHNOT(mIndex, "XIDX");
}
}
| 600
|
C++
|
.cpp
| 17
| 29
| 109
| 0.637782
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,160
|
importcrec.cpp
|
OpenMW_openmw/apps/essimporter/importcrec.cpp
|
#include "importcrec.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void CREC::load(ESM::ESMReader& esm)
{
esm.getHNT(mIndex, "INDX");
// equivalent of ESM::Creature XSCL? probably don't have to convert this,
// since the value can't be changed
float scale;
esm.getHNOT(scale, "XSCL");
while (esm.isNextSub("AI_W") || esm.isNextSub("AI_E") || esm.isNextSub("AI_T") || esm.isNextSub("AI_F")
|| esm.isNextSub("AI_A"))
mAiPackages.add(esm);
mInventory.load(esm);
}
}
| 584
|
C++
|
.cpp
| 17
| 27.529412
| 111
| 0.610714
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,161
|
convertnpcc.cpp
|
OpenMW_openmw/apps/essimporter/convertnpcc.cpp
|
#include "convertnpcc.hpp"
#include "convertinventory.hpp"
namespace ESSImport
{
void convertNPCC(const NPCC& npcc, ESM::NpcState& npcState)
{
npcState.mNpcStats.mDisposition = npcc.mNPDT.mDisposition;
npcState.mNpcStats.mReputation = npcc.mNPDT.mReputation;
convertInventory(npcc.mInventory, npcState.mInventory);
}
}
| 359
|
C++
|
.cpp
| 11
| 28
| 66
| 0.75
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,162
|
importinventory.cpp
|
OpenMW_openmw/apps/essimporter/importinventory.cpp
|
#include "importinventory.hpp"
#include <stdexcept>
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void Inventory::load(ESM::ESMReader& esm)
{
while (esm.isNextSub("NPCO"))
{
ContItem contItem;
esm.getHT(contItem.mCount, contItem.mItem.mData);
InventoryItem item;
item.mId = contItem.mItem.toString();
item.mCount = contItem.mCount;
item.mRelativeEquipmentSlot = -1;
item.mLockLevel = 0;
item.mChargeIntRemainder = 0;
unsigned int itemCount = std::abs(item.mCount);
bool separateStacks = false;
for (unsigned int i = 0; i < itemCount; ++i)
{
bool newStack = esm.isNextSub("XIDX");
if (newStack)
{
uint32_t idx;
esm.getHT(idx);
separateStacks = true;
item.mCount = 1;
}
item.mSCRI.load(esm);
// for XSOL and XCHG seen so far, but probably others too
bool isDeleted = false;
item.ESM::CellRef::loadData(esm, isDeleted);
int32_t charge = -1;
esm.getHNOT(charge, "XHLT");
item.mChargeInt = charge;
if (newStack)
mItems.push_back(item);
}
if (!separateStacks)
mItems.push_back(item);
}
// equipped items
while (esm.isNextSub("WIDX"))
{
// note: same item can be equipped 2 items (e.g. 2 rings)
// and will be *stacked* in the NPCO list, unlike openmw!
// this is currently not handled properly.
esm.getSubHeader();
int32_t itemIndex; // index of the item in the NPCO list
esm.getT(itemIndex);
if (itemIndex < 0 || itemIndex >= int(mItems.size()))
esm.fail("equipment item index out of range");
// appears to be a relative index for only the *possible* slots this item can be equipped in,
// i.e. 0 most of the time
int32_t slotIndex;
esm.getT(slotIndex);
mItems[itemIndex].mRelativeEquipmentSlot = slotIndex;
}
}
}
| 2,347
|
C++
|
.cpp
| 61
| 25.655738
| 105
| 0.524019
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,163
|
importgame.cpp
|
OpenMW_openmw/apps/essimporter/importgame.cpp
|
#include "importgame.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void GAME::load(ESM::ESMReader& esm)
{
esm.getSubNameIs("GMDT");
esm.getSubHeader();
bool hasSecundaPhase = esm.getSubSize() == 96;
esm.getT(mGMDT.mCellName);
esm.getT(mGMDT.mFogColour);
esm.getT(mGMDT.mFogDensity);
esm.getT(mGMDT.mCurrentWeather);
esm.getT(mGMDT.mNextWeather);
esm.getT(mGMDT.mWeatherTransition);
esm.getT(mGMDT.mTimeOfNextTransition);
esm.getT(mGMDT.mMasserPhase);
if (hasSecundaPhase)
esm.getT(mGMDT.mSecundaPhase);
mGMDT.mWeatherTransition &= (0x000000ff);
mGMDT.mSecundaPhase &= (0x000000ff);
mGMDT.mMasserPhase &= (0x000000ff);
}
}
| 793
|
C++
|
.cpp
| 24
| 25.833333
| 54
| 0.65445
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,164
|
importscri.cpp
|
OpenMW_openmw/apps/essimporter/importscri.cpp
|
#include "importscri.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void SCRI::load(ESM::ESMReader& esm)
{
mScript = esm.getHNOString("SCRI");
int32_t numShorts = 0, numLongs = 0, numFloats = 0;
if (esm.isNextSub("SLCS"))
{
esm.getSubHeader();
esm.getT(numShorts);
esm.getT(numLongs);
esm.getT(numFloats);
}
if (esm.isNextSub("SLSD"))
{
esm.getSubHeader();
for (int i = 0; i < numShorts; ++i)
{
int16_t val;
esm.getT(val);
mShorts.push_back(val);
}
}
// I haven't seen Longs in a save file yet, but SLLD would make sense for the name
// TODO: test this
if (esm.isNextSub("SLLD"))
{
esm.getSubHeader();
for (int i = 0; i < numLongs; ++i)
{
int32_t val;
esm.getT(val);
mLongs.push_back(val);
}
}
if (esm.isNextSub("SLFD"))
{
esm.getSubHeader();
for (int i = 0; i < numFloats; ++i)
{
float val;
esm.getT(val);
mFloats.push_back(val);
}
}
}
}
| 1,342
|
C++
|
.cpp
| 49
| 16.55102
| 90
| 0.447552
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,165
|
importproj.cpp
|
OpenMW_openmw/apps/essimporter/importproj.cpp
|
#include "importproj.h"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void ESSImport::PROJ::load(ESM::ESMReader& esm)
{
while (esm.isNextSub("PNAM"))
{
PNAM pnam;
esm.getHT(pnam.mAttackStrength, pnam.mSpeed, pnam.mUnknown, pnam.mFlightTime, pnam.mSplmIndex,
pnam.mUnknown2, pnam.mVelocity.mValues, pnam.mPosition.mValues, pnam.mUnknown3, pnam.mActorId.mData,
pnam.mArrowId.mData, pnam.mBowId.mData);
mProjectiles.push_back(pnam);
}
}
}
| 561
|
C++
|
.cpp
| 16
| 27.3125
| 116
| 0.648799
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,166
|
convertcntc.cpp
|
OpenMW_openmw/apps/essimporter/convertcntc.cpp
|
#include "convertcntc.hpp"
#include "convertinventory.hpp"
namespace ESSImport
{
void convertCNTC(const CNTC& cntc, ESM::ContainerState& state)
{
convertInventory(cntc.mInventory, state.mInventory);
}
}
| 227
|
C++
|
.cpp
| 9
| 21.555556
| 66
| 0.747664
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,167
|
importplayer.cpp
|
OpenMW_openmw/apps/essimporter/importplayer.cpp
|
#include "importplayer.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void PCDT::load(ESM::ESMReader& esm)
{
while (esm.isNextSub("DNAM"))
{
mKnownDialogueTopics.push_back(esm.getHString());
}
mHasMark = false;
if (esm.isNextSub("MNAM"))
{
mHasMark = true;
mMNAM = esm.getHString();
}
esm.getHNT("PNAM", mPNAM.mPlayerFlags, mPNAM.mLevelProgress, mPNAM.mSkillProgress, mPNAM.mSkillIncreases,
mPNAM.mTelekinesisRangeBonus, mPNAM.mVisionBonus, mPNAM.mDetectKeyMagnitude,
mPNAM.mDetectEnchantmentMagnitude, mPNAM.mDetectAnimalMagnitude, mPNAM.mMarkLocation.mX,
mPNAM.mMarkLocation.mY, mPNAM.mMarkLocation.mZ, mPNAM.mMarkLocation.mRotZ, mPNAM.mMarkLocation.mCellX,
mPNAM.mMarkLocation.mCellY, mPNAM.mUnknown3, mPNAM.mVerticalRotation.mData, mPNAM.mSpecIncreases,
mPNAM.mUnknown4);
if (esm.isNextSub("SNAM"))
esm.skipHSub();
if (esm.isNextSub("NAM9"))
esm.skipHSub();
// Rest state. You shouldn't even be able to save during rest, but skip just in case.
if (esm.isNextSub("RNAM"))
/*
int hoursLeft;
float x, y, z; // resting position
*/
esm.skipHSub(); // 16 bytes
mBounty = 0;
esm.getHNOT(mBounty, "CNAM");
mBirthsign = esm.getHNOString("BNAM");
// Holds the names of the last used Alchemy apparatus. Don't need to import this ATM,
// because our GUI auto-selects the best apparatus.
if (esm.isNextSub("NAM0"))
esm.skipHSub();
if (esm.isNextSub("NAM1"))
esm.skipHSub();
if (esm.isNextSub("NAM2"))
esm.skipHSub();
if (esm.isNextSub("NAM3"))
esm.skipHSub();
mHasENAM = esm.getHNOT("ENAM", mENAM.mCellX, mENAM.mCellY);
if (esm.isNextSub("LNAM"))
esm.skipHSub();
while (esm.isNextSub("FNAM"))
{
FNAM fnam;
esm.getHT(
fnam.mRank, fnam.mUnknown1, fnam.mReputation, fnam.mFlags, fnam.mUnknown2, fnam.mFactionName.mData);
mFactions.push_back(fnam);
}
mHasAADT = esm.getHNOT("AADT", mAADT.animGroupIndex, mAADT.mUnknown5); // Attack animation data?
if (esm.isNextSub("KNAM"))
esm.skipHSub(); // assigned Quick Keys, I think
if (esm.isNextSub("ANIS"))
esm.skipHSub(); // 16 bytes
if (esm.isNextSub("WERE"))
{
// some werewolf data, 152 bytes
// maybe current skills and attributes for werewolf form
esm.getSubHeader();
esm.skip(152);
}
}
}
| 2,804
|
C++
|
.cpp
| 70
| 29.657143
| 116
| 0.58947
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,168
|
convertacdt.cpp
|
OpenMW_openmw/apps/essimporter/convertacdt.cpp
|
#include <iostream>
#include <limits>
#include <string>
#include <components/misc/strings/lower.hpp>
#include "convertacdt.hpp"
namespace ESSImport
{
int translateDynamicIndex(int mwIndex)
{
if (mwIndex == 1)
return 2;
else if (mwIndex == 2)
return 1;
return mwIndex;
}
void convertACDT(const ACDT& acdt, ESM::CreatureStats& cStats)
{
for (int i = 0; i < 3; ++i)
{
int writeIndex = translateDynamicIndex(i);
cStats.mDynamic[writeIndex].mBase = acdt.mDynamic[i][1];
cStats.mDynamic[writeIndex].mMod = 0.f;
cStats.mDynamic[writeIndex].mCurrent = acdt.mDynamic[i][0];
}
for (int i = 0; i < 8; ++i)
{
cStats.mAttributes[i].mBase = acdt.mAttributes[i][1];
cStats.mAttributes[i].mMod = 0.f;
cStats.mAttributes[i].mCurrent = acdt.mAttributes[i][0];
}
cStats.mGoldPool = acdt.mGoldPool;
cStats.mTalkedTo = (acdt.mFlags & TalkedToPlayer) != 0;
cStats.mAttacked = (acdt.mFlags & Attacked) != 0;
}
void convertACSC(const ACSC& acsc, ESM::CreatureStats& cStats)
{
cStats.mDead = (acsc.mFlags & Dead) != 0;
}
void convertNpcData(const ActorData& actorData, ESM::NpcStats& npcStats)
{
for (int i = 0; i < ESM::Skill::Length; ++i)
{
npcStats.mSkills[i].mMod = 0.f;
npcStats.mSkills[i].mCurrent = actorData.mSkills[i][1];
npcStats.mSkills[i].mBase = actorData.mSkills[i][0];
}
npcStats.mTimeToStartDrowning = actorData.mACDT.mBreathMeter;
}
void convertANIS(const ANIS& anis, ESM::AnimationState& state)
{
static const char* animGroups[] = { "Idle", "Idle2", "Idle3", "Idle4", "Idle5", "Idle6", "Idle7", "Idle8",
"Idle9", "Idlehh", "Idle1h", "Idle2c", "Idle2w", "IdleSwim", "IdleSpell", "IdleCrossbow", "IdleSneak",
"IdleStorm", "Torch", "Hit1", "Hit2", "Hit3", "Hit4", "Hit5", "SwimHit1", "SwimHit2", "SwimHit3", "Death1",
"Death2", "Death3", "Death4", "Death5", "DeathKnockDown", "DeathKnockOut", "KnockDown", "KnockOut",
"SwimDeath", "SwimDeath2", "SwimDeath3", "SwimDeathKnockDown", "SwimDeathKnockOut", "SwimKnockOut",
"SwimKnockDown", "SwimWalkForward", "SwimWalkBack", "SwimWalkLeft", "SwimWalkRight", "SwimRunForward",
"SwimRunBack", "SwimRunLeft", "SwimRunRight", "SwimTurnLeft", "SwimTurnRight", "WalkForward", "WalkBack",
"WalkLeft", "WalkRight", "TurnLeft", "TurnRight", "RunForward", "RunBack", "RunLeft", "RunRight",
"SneakForward", "SneakBack", "SneakLeft", "SneakRight", "Jump", "WalkForwardhh", "WalkBackhh", "WalkLefthh",
"WalkRighthh", "TurnLefthh", "TurnRighthh", "RunForwardhh", "RunBackhh", "RunLefthh", "RunRighthh",
"SneakForwardhh", "SneakBackhh", "SneakLefthh", "SneakRighthh", "Jumphh", "WalkForward1h", "WalkBack1h",
"WalkLeft1h", "WalkRight1h", "TurnLeft1h", "TurnRight1h", "RunForward1h", "RunBack1h", "RunLeft1h",
"RunRight1h", "SneakForward1h", "SneakBack1h", "SneakLeft1h", "SneakRight1h", "Jump1h", "WalkForward2c",
"WalkBack2c", "WalkLeft2c", "WalkRight2c", "TurnLeft2c", "TurnRight2c", "RunForward2c", "RunBack2c",
"RunLeft2c", "RunRight2c", "SneakForward2c", "SneakBack2c", "SneakLeft2c", "SneakRight2c", "Jump2c",
"WalkForward2w", "WalkBack2w", "WalkLeft2w", "WalkRight2w", "TurnLeft2w", "TurnRight2w", "RunForward2w",
"RunBack2w", "RunLeft2w", "RunRight2w", "SneakForward2w", "SneakBack2w", "SneakLeft2w", "SneakRight2w",
"Jump2w", "SpellCast", "SpellTurnLeft", "SpellTurnRight", "Attack1", "Attack2", "Attack3", "SwimAttack1",
"SwimAttack2", "SwimAttack3", "HandToHand", "Crossbow", "BowAndArrow", "ThrowWeapon", "WeaponOneHand",
"WeaponTwoHand", "WeaponTwoWide", "Shield", "PickProbe", "InventoryHandToHand", "InventoryWeaponOneHand",
"InventoryWeaponTwoHand", "InventoryWeaponTwoWide" };
if (anis.mGroupIndex < (sizeof(animGroups) / sizeof(*animGroups)))
{
std::string group(animGroups[anis.mGroupIndex]);
Misc::StringUtils::lowerCaseInPlace(group);
ESM::AnimationState::ScriptedAnimation scriptedAnim;
scriptedAnim.mGroup = std::move(group);
scriptedAnim.mTime = anis.mTime;
scriptedAnim.mAbsolute = true;
// Neither loop count nor queueing seems to be supported by the ess format.
scriptedAnim.mLoopCount = std::numeric_limits<size_t>::max();
state.mScriptedAnims.push_back(scriptedAnim);
}
else
// TODO: Handle 0xFF index, which seems to be used for finished animations.
std::cerr << "unknown animation group index: " << static_cast<unsigned int>(anis.mGroupIndex) << std::endl;
}
}
| 4,976
|
C++
|
.cpp
| 88
| 46.863636
| 120
| 0.624897
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,169
|
convertscri.cpp
|
OpenMW_openmw/apps/essimporter/convertscri.cpp
|
#include "convertscri.hpp"
namespace
{
template <typename T, ESM::VarType VariantType>
void storeVariables(const std::vector<T>& variables, ESM::Locals& locals, const std::string& scriptname)
{
for (const auto& variable : variables)
{
ESM::Variant val(variable);
val.setType(VariantType);
locals.mVariables.emplace_back(std::string(), val);
}
}
}
namespace ESSImport
{
void convertSCRI(const SCRI& scri, ESM::Locals& locals)
{
// order *is* important, as we do not have variable names available in this format
storeVariables<short, ESM::VT_Short>(scri.mShorts, locals, scri.mScript);
storeVariables<int, ESM::VT_Int>(scri.mLongs, locals, scri.mScript);
storeVariables<float, ESM::VT_Float>(scri.mFloats, locals, scri.mScript);
}
}
| 857
|
C++
|
.cpp
| 24
| 29.458333
| 108
| 0.663845
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,170
|
importsplm.cpp
|
OpenMW_openmw/apps/essimporter/importsplm.cpp
|
#include "importsplm.h"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void SPLM::load(ESM::ESMReader& esm)
{
while (esm.isNextSub("NAME"))
{
ActiveSpell spell;
esm.getHT(spell.mIndex);
esm.getHNT("SPDT", spell.mSPDT.mType, spell.mSPDT.mId.mData, spell.mSPDT.mUnknown,
spell.mSPDT.mCasterId.mData, spell.mSPDT.mSourceId.mData, spell.mSPDT.mUnknown2);
spell.mTarget = esm.getHNOString("TNAM");
while (esm.isNextSub("NPDT"))
{
ActiveEffect effect;
esm.getHT(effect.mNPDT.mAffectedActorId.mData, effect.mNPDT.mUnknown, effect.mNPDT.mMagnitude,
effect.mNPDT.mSecondsActive, effect.mNPDT.mUnknown2);
// Effect-specific subrecords can follow:
// - INAM for disintegration and bound effects
// - CNAM for summoning and command effects
// - VNAM for vampirism
// NOTE: There can be multiple INAMs per effect.
// TODO: Needs more research.
esm.skipHSubUntil("NAM0"); // sentinel
esm.getSubName();
esm.skipHSub();
spell.mActiveEffects.push_back(effect);
}
unsigned char xnam; // sentinel
esm.getHNT(xnam, "XNAM");
mActiveSpells.push_back(spell);
}
}
}
| 1,452
|
C++
|
.cpp
| 35
| 29.228571
| 110
| 0.572139
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,171
|
importscpt.cpp
|
OpenMW_openmw/apps/essimporter/importscpt.cpp
|
#include "importscpt.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void SCPT::load(ESM::ESMReader& esm)
{
esm.getHNT("SCHD", mSCHD.mName.mData, mSCHD.mNumShorts, mSCHD.mNumLongs, mSCHD.mNumFloats,
mSCHD.mScriptDataSize, mSCHD.mStringTableSize);
mSCRI.load(esm);
mRefNum = -1;
if (esm.isNextSub("RNAM"))
{
mRunning = true;
esm.getHT(mRefNum);
}
else
mRunning = false;
}
}
| 515
|
C++
|
.cpp
| 19
| 19.684211
| 98
| 0.597959
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,172
|
converter.cpp
|
OpenMW_openmw/apps/essimporter/converter.cpp
|
#include "converter.hpp"
#include <algorithm>
#include <cstdint>
#include <stdexcept>
#include <osgDB/WriteFile>
#include <components/esm3/containerstate.hpp>
#include <components/esm3/creaturestate.hpp>
#include <components/misc/constants.hpp>
#include "convertcntc.hpp"
#include "convertcrec.hpp"
#include "convertscri.hpp"
namespace
{
void convertImage(char* data, int size, int width, int height, GLenum pf, const std::string& out)
{
osg::ref_ptr<osg::Image> image(new osg::Image);
image->allocateImage(width, height, 1, pf, GL_UNSIGNED_BYTE);
memcpy(image->data(), data, size);
image->flipVertical();
osgDB::writeImageFile(*image, out);
}
void convertCellRef(const ESSImport::CellRef& cellref, ESM::ObjectState& objstate)
{
objstate.mEnabled = cellref.mEnabled;
objstate.mPosition = cellref.mPos;
objstate.mRef.mRefNum = cellref.mRefNum;
if (cellref.mDeleted)
objstate.mRef.mCount = 0;
convertSCRI(cellref.mActorData.mSCRI, objstate.mLocals);
objstate.mHasLocals = !objstate.mLocals.mVariables.empty();
if (cellref.mActorData.mHasANIS)
convertANIS(cellref.mActorData.mANIS, objstate.mAnimationState);
}
bool isIndexedRefId(const std::string& indexedRefId)
{
if (indexedRefId.size() <= 8)
return false;
if (indexedRefId.find_first_not_of("0123456789") == std::string::npos)
return false; // entirely numeric refid, this is a reference to
// a dynamically created record e.g. player-enchanted weapon
std::string index = indexedRefId.substr(indexedRefId.size() - 8);
return index.find_first_not_of("0123456789ABCDEF") == std::string::npos;
}
void splitIndexedRefId(const std::string& indexedRefId, int& refIndex, std::string& refId)
{
std::stringstream stream;
stream << std::hex << indexedRefId.substr(indexedRefId.size() - 8, 8);
stream >> refIndex;
refId = indexedRefId.substr(0, indexedRefId.size() - 8);
}
int convertActorId(const std::string& indexedRefId, ESSImport::Context& context)
{
if (isIndexedRefId(indexedRefId))
{
int refIndex = 0;
std::string refId;
splitIndexedRefId(indexedRefId, refIndex, refId);
auto it = context.mActorIdMap.find(std::make_pair(refIndex, ESM::RefId::stringRefId(refId)));
if (it == context.mActorIdMap.end())
return -1;
return it->second;
}
else if (indexedRefId == "PlayerSaveGame")
{
return context.mPlayer.mObject.mCreatureStats.mActorId;
}
return -1;
}
}
namespace ESSImport
{
struct MAPH
{
uint32_t size;
uint32_t value;
};
void ConvertFMAP::read(ESM::ESMReader& esm)
{
MAPH maph;
esm.getHNT("MAPH", maph.size, maph.value);
std::vector<char> data;
esm.getSubNameIs("MAPD");
esm.getSubHeader();
data.resize(esm.getSubSize());
esm.getExact(data.data(), data.size());
mGlobalMapImage = new osg::Image;
mGlobalMapImage->allocateImage(maph.size, maph.size, 1, GL_RGB, GL_UNSIGNED_BYTE);
memcpy(mGlobalMapImage->data(), data.data(), data.size());
// to match openmw size
// FIXME: filtering?
mGlobalMapImage->scaleImage(maph.size * 2, maph.size * 2, 1, GL_UNSIGNED_BYTE);
}
void ConvertFMAP::write(ESM::ESMWriter& esm)
{
int numcells = mGlobalMapImage->s() / 18; // NB truncating, doesn't divide perfectly
// with the 512x512 map the game has by default
int cellSize = mGlobalMapImage->s() / numcells;
// Note the upper left corner of the (0,0) cell should be at (width/2, height/2)
mContext->mGlobalMapState.mBounds.mMinX = -numcells / 2;
mContext->mGlobalMapState.mBounds.mMaxX = (numcells - 1) / 2;
mContext->mGlobalMapState.mBounds.mMinY = -(numcells - 1) / 2;
mContext->mGlobalMapState.mBounds.mMaxY = numcells / 2;
osg::ref_ptr<osg::Image> image2(new osg::Image);
int width = cellSize * numcells;
int height = cellSize * numcells;
std::vector<unsigned char> data;
data.resize(width * height * 4, 0);
image2->allocateImage(width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
memcpy(image2->data(), data.data(), data.size());
for (const auto& exploredCell : mContext->mExploredCells)
{
if (exploredCell.first > mContext->mGlobalMapState.mBounds.mMaxX
|| exploredCell.first < mContext->mGlobalMapState.mBounds.mMinX
|| exploredCell.second > mContext->mGlobalMapState.mBounds.mMaxY
|| exploredCell.second < mContext->mGlobalMapState.mBounds.mMinY)
{
// out of bounds, I think this could happen, since the original engine had a fixed-size map
continue;
}
int imageLeftSrc = mGlobalMapImage->s() / 2;
int imageTopSrc = mGlobalMapImage->t() / 2;
imageLeftSrc += exploredCell.first * cellSize;
imageTopSrc -= exploredCell.second * cellSize;
int imageLeftDst = width / 2;
int imageTopDst = height / 2;
imageLeftDst += exploredCell.first * cellSize;
imageTopDst -= exploredCell.second * cellSize;
for (int x = 0; x < cellSize; ++x)
for (int y = 0; y < cellSize; ++y)
{
unsigned int col = *(unsigned int*)mGlobalMapImage->data(imageLeftSrc + x, imageTopSrc + y, 0);
*(unsigned int*)image2->data(imageLeftDst + x, imageTopDst + y, 0) = col;
}
}
std::stringstream ostream;
osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("png");
if (!readerwriter)
{
std::cerr << "Error: can't write global map image, no png readerwriter found" << std::endl;
return;
}
image2->flipVertical();
osgDB::ReaderWriter::WriteResult result = readerwriter->writeImage(*image2, ostream);
if (!result.success())
{
std::cerr << "Error: can't write global map image: " << result.message() << " code " << result.status()
<< std::endl;
return;
}
std::string outData = ostream.str();
mContext->mGlobalMapState.mImageData = std::vector<char>(outData.begin(), outData.end());
esm.startRecord(ESM::REC_GMAP);
mContext->mGlobalMapState.save(esm);
esm.endRecord(ESM::REC_GMAP);
}
void ConvertCell::read(ESM::ESMReader& esm)
{
ESM::Cell cell;
bool isDeleted = false;
cell.load(esm, isDeleted, false);
// I wonder what 0x40 does?
if (cell.isExterior() && cell.mData.mFlags & 0x20)
{
mContext->mGlobalMapState.mMarkers.insert(std::make_pair(cell.mData.mX, cell.mData.mY));
}
// note if the player is in a nameless exterior cell, we will assign the cellId later based on player position
if (Misc::StringUtils::ciEqual(cell.mName, mContext->mPlayerCellName))
{
mContext->mPlayer.mCellId = cell.mId;
}
Cell newcell;
newcell.mCell = cell;
// fog of war
// seems to be a 1-bit pixel format, 16*16 pixels
// TODO: add bleeding of FOW into neighbouring cells (openmw handles this by writing to the textures,
// MW handles it when rendering only)
unsigned char nam8[32];
// exterior has 1 NAM8, interior can have multiple ones, and have an extra 4 byte flag at the start
// (probably offset of that specific fog texture?)
while (esm.isNextSub("NAM8"))
{
if (cell.isExterior()) // TODO: NAM8 occasionally exists for cells that haven't been explored.
// are there any flags marking explored cells?
mContext->mExploredCells.insert(std::make_pair(cell.mData.mX, cell.mData.mY));
esm.getSubHeader();
if (esm.getSubSize() == 36)
{
// flag on interiors
esm.skip(4);
}
esm.getT(nam8);
newcell.mFogOfWar.reserve(16 * 16);
for (int x = 0; x < 16; ++x)
{
for (int y = 0; y < 16; ++y)
{
size_t pos = x * 16 + y;
size_t bytepos = pos / 8;
assert(bytepos < 32);
int bit = pos % 8;
newcell.mFogOfWar.push_back(((nam8[bytepos] >> bit) & (0x1)) ? 0xffffffff : 0x000000ff);
}
}
if (cell.isExterior())
{
std::ostringstream filename;
filename << "fog_" << cell.mData.mX << "_" << cell.mData.mY << ".tga";
convertImage(
(char*)&newcell.mFogOfWar[0], newcell.mFogOfWar.size() * 4, 16, 16, GL_RGBA, filename.str());
}
}
// moved reference, not handled yet
// NOTE: MVRF can also occur in within normal references (importcellref.cpp)?
// this does not match the ESM file implementation,
// verify if that can happen with ESM files too
while (esm.isNextSub("MVRF"))
{
esm.skipHSub(); // skip MVRF
esm.getSubName();
esm.skipHSub(); // skip CNDT
}
std::vector<CellRef> cellrefs;
while (esm.hasMoreSubs() && esm.peekNextSub("FRMR"))
{
CellRef ref;
ref.load(esm);
cellrefs.push_back(ref);
}
while (esm.isNextSub("MPCD"))
{
float notepos[3];
esm.getHT(notepos);
// Markers seem to be arranged in a 32*32 grid, notepos has grid-indices.
// This seems to be the reason markers can't be placed everywhere in interior cells,
// i.e. when the grid is exceeded.
// Converting the interior markers correctly could be rather tricky, but is probably similar logic
// as used for the FoW texture placement, which we need to figure out anyway
notepos[1] += 31.f;
notepos[0] += 0.5;
notepos[1] += 0.5;
notepos[0] = Constants::CellSizeInUnits * notepos[0] / 32.f;
notepos[1] = Constants::CellSizeInUnits * notepos[1] / 32.f;
if (cell.isExterior())
{
notepos[0] += Constants::CellSizeInUnits * cell.mData.mX;
notepos[1] += Constants::CellSizeInUnits * cell.mData.mY;
}
// TODO: what encoding is this in?
std::string note = esm.getHNString("MPNT");
ESM::CustomMarker marker;
marker.mWorldX = notepos[0];
marker.mWorldY = notepos[1];
marker.mNote = std::move(note);
marker.mCell = cell.mId;
mMarkers.push_back(marker);
}
newcell.mRefs = std::move(cellrefs);
if (cell.isExterior())
mExtCells[std::make_pair(cell.mData.mX, cell.mData.mY)] = std::move(newcell);
else
mIntCells[cell.mName] = std::move(newcell);
}
void ConvertCell::writeCell(const Cell& cell, ESM::ESMWriter& esm)
{
ESM::Cell esmcell = cell.mCell;
esm.startRecord(ESM::REC_CSTA);
ESM::CellState csta;
csta.mHasFogOfWar = 0;
csta.mLastRespawn.mDay = 0;
csta.mLastRespawn.mHour = 0;
csta.mId = esmcell.mId;
csta.mIsInterior = !esmcell.isExterior();
esm.writeCellId(csta.mId);
// TODO csta.mLastRespawn;
// shouldn't be needed if we respawn on global schedule like in original MW
csta.mWaterLevel = esmcell.mWater;
csta.save(esm);
for (const auto& cellref : cell.mRefs)
{
ESM::CellRef out(cellref);
// TODO: use mContext->mCreatures/mNpcs
if (!isIndexedRefId(cellref.mIndexedRefId))
{
// non-indexed RefNum, i.e. no CREC/NPCC/CNTC record associated with it
// this could be any type of object really (even creatures/npcs too)
out.mRefID = ESM::RefId::stringRefId(cellref.mIndexedRefId);
ESM::ObjectState objstate;
objstate.blank();
objstate.mRef = out;
objstate.mRef.mRefID = out.mRefID;
objstate.mHasCustomState = false;
convertCellRef(cellref, objstate);
esm.writeHNT("OBJE", 0);
objstate.save(esm);
continue;
}
else
{
int refIndex = 0;
std::string outStringId;
splitIndexedRefId(cellref.mIndexedRefId, refIndex, outStringId);
out.mRefID = ESM::RefId::stringRefId(outStringId);
auto npccIt = mContext->mNpcChanges.find(std::make_pair(refIndex, out.mRefID));
if (npccIt != mContext->mNpcChanges.end())
{
ESM::NpcState objstate;
objstate.blank();
objstate.mRef = out;
objstate.mRef.mRefID = out.mRefID;
// TODO: need more micromanagement here so we don't overwrite values
// from the ESM with default values
if (cellref.mActorData.mHasACDT)
convertACDT(cellref.mActorData.mACDT, objstate.mCreatureStats);
else
objstate.mCreatureStats.mMissingACDT = true;
if (cellref.mActorData.mHasACSC)
convertACSC(cellref.mActorData.mACSC, objstate.mCreatureStats);
convertNpcData(cellref.mActorData, objstate.mNpcStats);
convertNPCC(npccIt->second, objstate);
convertCellRef(cellref, objstate);
objstate.mCreatureStats.mActorId = mContext->generateActorId();
mContext->mActorIdMap.insert(
std::make_pair(std::make_pair(refIndex, out.mRefID), objstate.mCreatureStats.mActorId));
esm.writeHNT("OBJE", ESM::REC_NPC_);
objstate.save(esm);
continue;
}
auto cntcIt = mContext->mContainerChanges.find(std::make_pair(refIndex, out.mRefID));
if (cntcIt != mContext->mContainerChanges.end())
{
ESM::ContainerState objstate;
objstate.blank();
objstate.mRef = out;
objstate.mRef.mRefID = out.mRefID;
convertCNTC(cntcIt->second, objstate);
convertCellRef(cellref, objstate);
esm.writeHNT("OBJE", ESM::REC_CONT);
objstate.save(esm);
continue;
}
auto crecIt = mContext->mCreatureChanges.find(std::make_pair(refIndex, out.mRefID));
if (crecIt != mContext->mCreatureChanges.end())
{
ESM::CreatureState objstate;
objstate.blank();
objstate.mRef = out;
objstate.mRef.mRefID = out.mRefID;
// TODO: need more micromanagement here so we don't overwrite values
// from the ESM with default values
if (cellref.mActorData.mHasACDT)
convertACDT(cellref.mActorData.mACDT, objstate.mCreatureStats);
else
objstate.mCreatureStats.mMissingACDT = true;
if (cellref.mActorData.mHasACSC)
convertACSC(cellref.mActorData.mACSC, objstate.mCreatureStats);
convertCREC(crecIt->second, objstate);
convertCellRef(cellref, objstate);
objstate.mCreatureStats.mActorId = mContext->generateActorId();
mContext->mActorIdMap.insert(
std::make_pair(std::make_pair(refIndex, out.mRefID), objstate.mCreatureStats.mActorId));
esm.writeHNT("OBJE", ESM::REC_CREA);
objstate.save(esm);
continue;
}
std::stringstream error;
error << "Can't find type for " << cellref.mIndexedRefId << std::endl;
throw std::runtime_error(error.str());
}
}
esm.endRecord(ESM::REC_CSTA);
}
void ConvertCell::write(ESM::ESMWriter& esm)
{
for (const auto& cell : mIntCells)
writeCell(cell.second, esm);
for (const auto& cell : mExtCells)
writeCell(cell.second, esm);
for (const auto& marker : mMarkers)
{
esm.startRecord(ESM::REC_MARK);
marker.save(esm);
esm.endRecord(ESM::REC_MARK);
}
}
void ConvertPROJ::read(ESM::ESMReader& esm)
{
mProj.load(esm);
}
void ConvertPROJ::write(ESM::ESMWriter& esm)
{
for (const PROJ::PNAM& pnam : mProj.mProjectiles)
{
if (!pnam.isMagic())
{
ESM::ProjectileState out;
convertBaseState(out, pnam);
out.mBowId = ESM::RefId::stringRefId(pnam.mBowId.toString());
out.mVelocity = pnam.mVelocity;
out.mAttackStrength = pnam.mAttackStrength;
esm.startRecord(ESM::REC_PROJ);
out.save(esm);
esm.endRecord(ESM::REC_PROJ);
}
else
{
ESM::MagicBoltState out;
convertBaseState(out, pnam);
auto it = std::find_if(mContext->mActiveSpells.begin(), mContext->mActiveSpells.end(),
[&pnam](const SPLM::ActiveSpell& spell) -> bool { return spell.mIndex == pnam.mSplmIndex; });
if (it == mContext->mActiveSpells.end())
{
std::cerr << "Warning: Skipped conversion for magic projectile \"" << pnam.mArrowId.toString()
<< "\" (invalid spell link)" << std::endl;
continue;
}
out.mSpellId = ESM::RefId::stringRefId(it->mSPDT.mId.toString());
out.mSpeed = pnam.mSpeed * 0.001f; // not sure where this factor comes from
out.mItem = ESM::RefNum();
esm.startRecord(ESM::REC_MPRJ);
out.save(esm);
esm.endRecord(ESM::REC_MPRJ);
}
}
}
void ConvertPROJ::convertBaseState(ESM::BaseProjectileState& base, const PROJ::PNAM& pnam)
{
base.mId = ESM::RefId::stringRefId(pnam.mArrowId.toString());
base.mPosition = pnam.mPosition;
osg::Quat orient;
orient.makeRotate(osg::Vec3f(0, 1, 0), pnam.mVelocity);
base.mOrientation = orient;
base.mActorId = convertActorId(pnam.mActorId.toString(), *mContext);
}
void ConvertSPLM::read(ESM::ESMReader& esm)
{
mSPLM.load(esm);
mContext->mActiveSpells = mSPLM.mActiveSpells;
}
void ConvertSPLM::write(ESM::ESMWriter& esm)
{
std::cerr << "Warning: Skipped active spell conversion (not implemented)" << std::endl;
}
}
| 19,818
|
C++
|
.cpp
| 443
| 32.171558
| 118
| 0.563268
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,173
|
importinfo.cpp
|
OpenMW_openmw/apps/essimporter/importinfo.cpp
|
#include "importinfo.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void INFO::load(ESM::ESMReader& esm)
{
mInfo = esm.getHNString("INAM");
mActorRefId = esm.getHNString("ACDT");
}
}
| 236
|
C++
|
.cpp
| 10
| 19.4
| 46
| 0.675676
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,174
|
importques.cpp
|
OpenMW_openmw/apps/essimporter/importques.cpp
|
#include "importques.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void QUES::load(ESM::ESMReader& esm)
{
while (esm.isNextSub("DATA"))
mInfo.push_back(esm.getHString());
}
}
| 233
|
C++
|
.cpp
| 10
| 18.7
| 46
| 0.6621
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,175
|
importjour.cpp
|
OpenMW_openmw/apps/essimporter/importjour.cpp
|
#include "importjour.hpp"
#include <components/esm3/esmreader.hpp>
namespace ESSImport
{
void JOUR::load(ESM::ESMReader& esm)
{
mText = esm.getHNString("NAME");
}
}
| 189
|
C++
|
.cpp
| 9
| 17.333333
| 40
| 0.6875
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,176
|
importcellref.cpp
|
OpenMW_openmw/apps/essimporter/importcellref.cpp
|
#include "importcellref.hpp"
#include <components/esm3/esmreader.hpp>
#include <components/misc/concepts.hpp>
#include <cstdint>
namespace ESSImport
{
template <Misc::SameAsWithoutCvref<ACDT> T>
void decompose(T&& v, const auto& f)
{
f(v.mUnknown, v.mFlags, v.mBreathMeter, v.mUnknown2, v.mDynamic, v.mUnknown3, v.mAttributes, v.mMagicEffects,
v.mUnknown4, v.mGoldPool, v.mCountDown, v.mUnknown5);
}
template <Misc::SameAsWithoutCvref<ACSC> T>
void decompose(T&& v, const auto& f)
{
f(v.mUnknown1, v.mFlags, v.mUnknown2, v.mCorpseClearCountdown, v.mUnknown3);
}
template <Misc::SameAsWithoutCvref<ANIS> T>
void decompose(T&& v, const auto& f)
{
f(v.mGroupIndex, v.mUnknown, v.mTime);
}
void CellRef::load(ESM::ESMReader& esm)
{
blank();
esm.getHNT(mRefNum.mIndex, "FRMR");
// this is required since openmw supports more than 255 content files
int pluginIndex = (mRefNum.mIndex & 0xff000000) >> 24;
mRefNum.mContentFile = pluginIndex - 1;
mRefNum.mIndex &= 0x00ffffff;
mIndexedRefId = esm.getHNString("NAME");
if (esm.isNextSub("ACTN"))
{
/*
Activation flags:
ActivationFlag_UseEnabled = 1
ActivationFlag_OnActivate = 2
ActivationFlag_OnDeath = 10h
ActivationFlag_OnKnockout = 20h
ActivationFlag_OnMurder = 40h
ActivationFlag_DoorOpening = 100h
ActivationFlag_DoorClosing = 200h
ActivationFlag_DoorJammedOpening = 400h
ActivationFlag_DoorJammedClosing = 800h
*/
esm.skipHSub();
}
if (esm.isNextSub("STPR"))
esm.skipHSub();
if (esm.isNextSub("MNAM"))
esm.skipHSub();
bool isDeleted = false;
ESM::CellRef::loadData(esm, isDeleted);
mActorData.mHasACDT = esm.getOptionalComposite("ACDT", mActorData.mACDT);
mActorData.mHasACSC = esm.getOptionalComposite("ACSC", mActorData.mACSC);
if (esm.isNextSub("ACSL"))
esm.skipHSubSize(112);
if (esm.isNextSub("CSTN"))
esm.skipHSub(); // "PlayerSaveGame", link to some object?
if (esm.isNextSub("LSTN"))
esm.skipHSub(); // "PlayerSaveGame", link to some object?
// unsure at which point between LSTN and TGTN
if (esm.isNextSub("CSHN"))
esm.skipHSub(); // "PlayerSaveGame", link to some object?
// unsure if before or after CSTN/LSTN
if (esm.isNextSub("LSHN"))
esm.skipHSub(); // "PlayerSaveGame", link to some object?
while (esm.isNextSub("TGTN"))
esm.skipHSub(); // "PlayerSaveGame", link to some object?
while (esm.isNextSub("FGTN"))
esm.getHString(); // fight target?
// unsure at which point between TGTN and CRED
if (esm.isNextSub("AADT"))
{
// occurred when a creature was in the middle of its attack, 44 bytes
esm.skipHSub();
}
// unsure at which point between FGTN and CHRD
if (esm.isNextSub("PWPC"))
esm.skipHSub();
if (esm.isNextSub("PWPS"))
esm.skipHSub();
if (esm.isNextSub("WNAM"))
{
std::string id = esm.getHString();
if (esm.isNextSub("XNAM"))
mActorData.mSelectedEnchantItem = esm.getHString();
else
mActorData.mSelectedSpell = std::move(id);
if (esm.isNextSub("YNAM"))
esm.skipHSub(); // 4 byte, 0
}
while (esm.isNextSub("APUD"))
{
// used power
esm.getSubHeader();
std::string id = esm.getMaybeFixedStringSize(32);
(void)id;
// timestamp can't be used: this is the total hours passed, calculated by
// timestamp = 24 * (365 * year + cumulativeDays[month] + day)
// unfortunately cumulativeDays[month] is not clearly defined,
// in the (non-MCP) vanilla version the first month was missing, but MCP added it.
double timestamp;
esm.getT(timestamp);
}
// FIXME: not all actors have this, add flag
esm.getHNOT("CHRD", mActorData.mSkills); // npc only
esm.getHNOT("CRED", mActorData.mCombatStats); // creature only
mActorData.mSCRI.load(esm);
if (esm.isNextSub("ND3D"))
esm.skipHSub();
mActorData.mHasANIS = esm.getOptionalComposite("ANIS", mActorData.mANIS);
if (esm.isNextSub("LVCR"))
{
// occurs on levelled creature spawner references
// probably some identifier for the creature that has been spawned?
unsigned char lvcr;
esm.getHT(lvcr);
// std::cout << "LVCR: " << (int)lvcr << std::endl;
}
mEnabled = true;
esm.getHNOT(mEnabled, "ZNAM");
// DATA should occur for all references, except levelled creature spawners
// I've seen DATA *twice* on a creature record, and with the exact same content too! weird
// alarmvoi0000.ess
for (int i = 0; i < 2; ++i)
esm.getOptionalComposite("DATA", mPos);
mDeleted = 0;
if (esm.isNextSub("DELE"))
{
uint32_t deleted;
esm.getHT(deleted);
mDeleted = ((deleted >> 24) & 0x2) != 0; // the other 3 bytes seem to be uninitialized garbage
}
if (esm.isNextSub("MVRF"))
{
esm.skipHSub();
esm.getSubName();
esm.skipHSub();
}
}
}
| 5,719
|
C++
|
.cpp
| 142
| 30.126761
| 117
| 0.58234
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,177
|
convertscpt.cpp
|
OpenMW_openmw/apps/essimporter/convertscpt.cpp
|
#include "convertscpt.hpp"
#include "convertscri.hpp"
#include <components/misc/strings/lower.hpp>
namespace ESSImport
{
void convertSCPT(const SCPT& scpt, ESM::GlobalScript& out)
{
out.mId = ESM::RefId::stringRefId(scpt.mSCHD.mName.toString());
out.mRunning = scpt.mRunning;
out.mTargetRef = ESM::RefNum{}; // TODO: convert target reference of global script
convertSCRI(scpt.mSCRI, out.mLocals);
}
}
| 450
|
C++
|
.cpp
| 13
| 29.846154
| 90
| 0.703704
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,178
|
convertinventory.cpp
|
OpenMW_openmw/apps/essimporter/convertinventory.cpp
|
#include "convertinventory.hpp"
#include <components/misc/strings/lower.hpp>
#include <cstdlib>
namespace ESSImport
{
void convertInventory(const Inventory& inventory, ESM::InventoryState& state)
{
uint32_t index = 0;
for (const auto& item : inventory.mItems)
{
ESM::ObjectState objstate;
objstate.blank();
objstate.mRef = item;
objstate.mRef.mRefID = ESM::RefId::stringRefId(item.mId);
objstate.mRef.mCount = item.mCount;
state.mItems.push_back(objstate);
if (item.mRelativeEquipmentSlot != -1)
// Note we should really write the absolute slot here, which we do not know about
// Not a big deal, OpenMW will auto-correct to a valid slot, the only problem is when
// an item could be equipped in two different slots (e.g. equipped two rings)
state.mEquipmentSlots[index] = item.mRelativeEquipmentSlot;
++index;
}
}
}
| 1,026
|
C++
|
.cpp
| 25
| 31.68
| 101
| 0.625502
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,179
|
main.cpp
|
OpenMW_openmw/apps/bulletobjecttool/main.cpp
|
#include <components/debug/debugging.hpp>
#include <components/debug/debuglog.hpp>
#include <components/esm/defs.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/esm3/readerscache.hpp>
#include <components/esmloader/esmdata.hpp>
#include <components/esmloader/load.hpp>
#include <components/fallback/fallback.hpp>
#include <components/fallback/validate.hpp>
#include <components/files/collections.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/files/multidircollection.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/platform/platform.hpp>
#include <components/resource/bgsmfilemanager.hpp>
#include <components/resource/bulletshape.hpp>
#include <components/resource/bulletshapemanager.hpp>
#include <components/resource/foreachbulletobject.hpp>
#include <components/resource/imagemanager.hpp>
#include <components/resource/niffilemanager.hpp>
#include <components/resource/scenemanager.hpp>
#include <components/settings/settings.hpp>
#include <components/to_utf8/to_utf8.hpp>
#include <components/version/version.hpp>
#include <components/vfs/manager.hpp>
#include <components/vfs/registerarchives.hpp>
#include <boost/program_options.hpp>
#include <charconv>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <iomanip>
#include <limits>
#include <map>
#include <memory>
#include <ostream>
#include <string>
#include <string_view>
#include <system_error>
#include <type_traits>
#include <utility>
#include <vector>
namespace
{
namespace bpo = boost::program_options;
using StringsVector = std::vector<std::string>;
constexpr std::string_view applicationName = "BulletObjectTool";
bpo::options_description makeOptionsDescription()
{
using Fallback::FallbackMap;
bpo::options_description result;
auto addOption = result.add_options();
addOption("help", "print help message");
addOption("version", "print version information and quit");
addOption("data",
bpo::value<Files::MaybeQuotedPathContainer>()
->default_value(Files::MaybeQuotedPathContainer(), "data")
->multitoken()
->composing(),
"set data directories (later directories have higher priority)");
addOption("data-local",
bpo::value<Files::MaybeQuotedPathContainer::value_type>()->default_value(
Files::MaybeQuotedPathContainer::value_type(), ""),
"set local data directory (highest priority)");
addOption("fallback-archive",
bpo::value<StringsVector>()->default_value(StringsVector(), "fallback-archive")->multitoken()->composing(),
"set fallback BSA archives (later archives have higher priority)");
addOption("content", bpo::value<StringsVector>()->default_value(StringsVector(), "")->multitoken()->composing(),
"content file(s): esm/esp, or omwgame/omwaddon/omwscripts");
addOption("encoding", bpo::value<std::string>()->default_value("win1252"),
"Character encoding used in OpenMW game messages:\n"
"\n\twin1250 - Central and Eastern European such as Polish, Czech, Slovak, Hungarian, Slovene, Bosnian, "
"Croatian, Serbian (Latin script), Romanian and Albanian languages\n"
"\n\twin1251 - Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic and other languages\n"
"\n\twin1252 - Western European (Latin) alphabet, used by default");
addOption("fallback", bpo::value<FallbackMap>()->default_value(FallbackMap(), "")->multitoken()->composing(),
"fallback values");
Files::ConfigurationManager::addCommonOptions(result);
return result;
}
struct WriteArray
{
const float (&mValue)[3];
friend std::ostream& operator<<(std::ostream& stream, const WriteArray& value)
{
for (std::size_t i = 0; i < 2; ++i)
stream << std::setprecision(std::numeric_limits<float>::max_exponent10) << value.mValue[i] << ", ";
return stream << std::setprecision(std::numeric_limits<float>::max_exponent10) << value.mValue[2];
}
};
int runBulletObjectTool(int argc, char* argv[])
{
Platform::init();
bpo::options_description desc = makeOptionsDescription();
bpo::parsed_options options = bpo::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
bpo::variables_map variables;
bpo::store(options, variables);
bpo::notify(variables);
if (variables.find("help") != variables.end())
{
Debug::getRawStdout() << desc << std::endl;
return 0;
}
Files::ConfigurationManager config;
config.readConfiguration(variables, desc);
Debug::setupLogging(config.getLogPath(), applicationName);
const std::string encoding(variables["encoding"].as<std::string>());
Log(Debug::Info) << ToUTF8::encodingUsingMessage(encoding);
ToUTF8::Utf8Encoder encoder(ToUTF8::calculateEncoding(encoding));
Files::PathContainer dataDirs(asPathContainer(variables["data"].as<Files::MaybeQuotedPathContainer>()));
auto local = variables["data-local"].as<Files::MaybeQuotedPathContainer::value_type>();
if (!local.empty())
dataDirs.push_back(std::move(local));
config.filterOutNonExistingPaths(dataDirs);
const auto& resDir = variables["resources"].as<Files::MaybeQuotedPath>();
Log(Debug::Info) << Version::getOpenmwVersionDescription();
dataDirs.insert(dataDirs.begin(), resDir / "vfs");
const Files::Collections fileCollections(dataDirs);
const auto& archives = variables["fallback-archive"].as<StringsVector>();
StringsVector contentFiles{ "builtin.omwscripts" };
const auto& configContentFiles = variables["content"].as<StringsVector>();
contentFiles.insert(contentFiles.end(), configContentFiles.begin(), configContentFiles.end());
Fallback::Map::init(variables["fallback"].as<Fallback::FallbackMap>().mMap);
VFS::Manager vfs;
VFS::registerArchives(&vfs, fileCollections, archives, true);
Settings::Manager::load(config);
ESM::ReadersCache readers;
EsmLoader::Query query;
query.mLoadActivators = true;
query.mLoadCells = true;
query.mLoadContainers = true;
query.mLoadDoors = true;
query.mLoadGameSettings = true;
query.mLoadLands = true;
query.mLoadStatics = true;
const EsmLoader::EsmData esmData
= EsmLoader::loadEsmData(query, contentFiles, fileCollections, readers, &encoder);
constexpr double expiryDelay = 0;
Resource::ImageManager imageManager(&vfs, expiryDelay);
Resource::NifFileManager nifFileManager(&vfs, &encoder.getStatelessEncoder());
Resource::BgsmFileManager bgsmFileManager(&vfs, expiryDelay);
Resource::SceneManager sceneManager(&vfs, &imageManager, &nifFileManager, &bgsmFileManager, expiryDelay);
Resource::BulletShapeManager bulletShapeManager(&vfs, &sceneManager, &nifFileManager, expiryDelay);
Resource::forEachBulletObject(
readers, vfs, bulletShapeManager, esmData, [](const ESM::Cell& cell, const Resource::BulletObject& object) {
Log(Debug::Verbose) << "Found bullet object in " << (cell.isExterior() ? "exterior" : "interior")
<< " cell \"" << cell.getDescription() << "\":"
<< " fileName=\"" << object.mShape->mFileName << '"'
<< " fileHash=" << Misc::StringUtils::toHex(object.mShape->mFileHash)
<< " collisionShape=" << std::boolalpha
<< (object.mShape->mCollisionShape == nullptr)
<< " avoidCollisionShape=" << std::boolalpha
<< (object.mShape->mAvoidCollisionShape == nullptr) << " position=("
<< WriteArray{ object.mPosition.pos } << ')' << " rotation=("
<< WriteArray{ object.mPosition.rot } << ')'
<< " scale=" << std::setprecision(std::numeric_limits<float>::max_exponent10)
<< object.mScale;
});
Log(Debug::Info) << "Done";
return 0;
}
}
int main(int argc, char* argv[])
{
return Debug::wrapApplication(runBulletObjectTool, argc, argv, applicationName);
}
| 8,697
|
C++
|
.cpp
| 166
| 43.126506
| 120
| 0.655989
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,180
|
esmtool.cpp
|
OpenMW_openmw/apps/esmtool/esmtool.cpp
|
#include <cmath>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <unordered_set>
#include <vector>
#include <boost/program_options.hpp>
#include <components/esm/format.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/files/configurationmanager.hpp>
#include <components/files/conversion.hpp>
#include <components/files/openfile.hpp>
#include <components/misc/strings/algorithm.hpp>
#include "arguments.hpp"
#include "labels.hpp"
#include "record.hpp"
#include "tes4.hpp"
namespace
{
using namespace EsmTool;
constexpr unsigned majorVersion = 1;
constexpr unsigned minorVersion = 3;
// Create a local alias for brevity
namespace bpo = boost::program_options;
struct ESMData
{
ESM::Header mHeader;
std::deque<std::unique_ptr<EsmTool::RecordBase>> mRecords;
// Value: (Reference, Deleted flag)
std::map<ESM::Cell*, std::deque<std::pair<ESM::CellRef, bool>>> mCellRefs;
std::map<int, int> mRecordStats;
};
bool parseOptions(int argc, char** argv, Arguments& info)
{
bpo::options_description desc(R"(Inspect and extract from Morrowind ES files (ESM, ESP, ESS)
Syntax: esmtool [options] mode infile [outfile]
Allowed modes:
dump Dumps all readable data from the input file.
clone Clones the input file to the output file.
comp Compares the given files.
Allowed options)");
auto addOption = desc.add_options();
addOption("help,h", "print help message.");
addOption("version,v", "print version information and quit.");
addOption("raw,r", bpo::value<std::string>(),
"Show an unformatted list of all records and subrecords of given format:\n"
"\n\tTES3"
"\n\tTES4");
// The intention is that this option would interact better
// with other modes including clone, dump, and raw.
addOption("type,t", bpo::value<std::vector<std::string>>(),
"Show only records of this type (four character record code). May "
"be specified multiple times. Only affects dump mode.");
addOption("name,n", bpo::value<std::string>(), "Show only the record with this name. Only affects dump mode.");
addOption("plain,p",
"Print contents of dialogs, books and scripts. "
"(skipped by default) "
"Only affects dump mode.");
addOption("quiet,q", "Suppress all record information. Useful for speed tests.");
addOption("loadcells,C", "Browse through contents of all cells.");
addOption("encoding,e", bpo::value<std::string>(&(info.encoding))->default_value("win1252"),
"Character encoding used in ESMTool:\n"
"\n\twin1250 - Central and Eastern European such as Polish, Czech, Slovak, Hungarian, Slovene, Bosnian, "
"Croatian, Serbian (Latin script), Romanian and Albanian languages\n"
"\n\twin1251 - Cyrillic alphabet such as Russian, Bulgarian, Serbian Cyrillic and other languages\n"
"\n\twin1252 - Western European (Latin) alphabet, used by default");
std::string finalText
= "\nIf no option is given, the default action is to parse all records in the archive\nand display "
"diagnostic information.";
// input-file is hidden and used as a positional argument
bpo::options_description hidden("Hidden Options");
auto addHiddenOption = hidden.add_options();
addHiddenOption("mode,m", bpo::value<std::string>(), "esmtool mode");
addHiddenOption("input-file,i", bpo::value<Files::MaybeQuotedPathContainer>(), "input file");
bpo::positional_options_description p;
p.add("mode", 1).add("input-file", 2);
// there might be a better way to do this
bpo::options_description all;
all.add(desc).add(hidden);
bpo::variables_map variables;
try
{
bpo::parsed_options valid_opts = bpo::command_line_parser(argc, argv).options(all).positional(p).run();
bpo::store(valid_opts, variables);
}
catch (std::exception& e)
{
std::cout << "ERROR parsing arguments: " << e.what() << std::endl;
return false;
}
bpo::notify(variables);
if (variables.count("help"))
{
std::cout << desc << finalText << std::endl;
return false;
}
if (variables.count("version"))
{
std::cout << "ESMTool version " << majorVersion << '.' << minorVersion << std::endl;
return false;
}
if (!variables.count("mode"))
{
std::cout << "No mode specified!\n\n" << desc << finalText << std::endl;
return false;
}
if (variables.count("type") > 0)
info.types = variables["type"].as<std::vector<std::string>>();
if (variables.count("name") > 0)
info.name = variables["name"].as<std::string>();
info.mode = variables["mode"].as<std::string>();
if (!(info.mode == "dump" || info.mode == "clone" || info.mode == "comp"))
{
std::cout << "\nERROR: invalid mode \"" << info.mode << "\"\n\n" << desc << finalText << std::endl;
return false;
}
if (!variables.count("input-file"))
{
std::cout << "\nERROR: missing ES file\n\n";
std::cout << desc << finalText << std::endl;
return false;
}
// handling gracefully the user adding multiple files
/* if (variables["input-file"].as< std::vector<std::string> >().size() > 1)
{
std::cout << "\nERROR: more than one ES file specified\n\n";
std::cout << desc << finalText << std::endl;
return false;
}*/
const auto& inputFiles = variables["input-file"].as<Files::MaybeQuotedPathContainer>();
info.filename = inputFiles[0].u8string(); // This call to u8string is redundant, but required to build on
// MSVC 14.26 due to implementation bugs.
if (inputFiles.size() > 1)
info.outname = inputFiles[1].u8string(); // This call to u8string is redundant, but required to build on
// MSVC 14.26 due to implementation bugs.
if (const auto it = variables.find("raw"); it != variables.end())
info.mRawFormat = ESM::parseFormat(it->second.as<std::string>());
info.quiet_given = variables.count("quiet") != 0;
info.loadcells_given = variables.count("loadcells") != 0;
info.plain_given = variables.count("plain") != 0;
// Font encoding settings
info.encoding = variables["encoding"].as<std::string>();
if (info.encoding != "win1250" && info.encoding != "win1251" && info.encoding != "win1252")
{
std::cout << info.encoding << " is not a valid encoding option.\n";
info.encoding = "win1252";
}
std::cout << ToUTF8::encodingUsingMessage(info.encoding) << std::endl;
return true;
}
void loadCell(const Arguments& info, ESM::Cell& cell, ESM::ESMReader& esm, ESMData* data);
int load(const Arguments& info, ESMData* data);
int clone(const Arguments& info);
int comp(const Arguments& info);
}
int main(int argc, char** argv)
{
try
{
Arguments info;
if (!parseOptions(argc, argv, info))
return 1;
if (info.mode == "dump")
return load(info, nullptr);
else if (info.mode == "clone")
return clone(info);
else if (info.mode == "comp")
return comp(info);
else
{
std::cout << "Invalid or no mode specified, dying horribly. Have a nice day." << std::endl;
return 1;
}
}
catch (std::exception& e)
{
std::cerr << "ERROR: " << e.what() << std::endl;
return 1;
}
return 0;
}
namespace
{
void loadCell(const Arguments& info, ESM::Cell& cell, ESM::ESMReader& esm, ESMData* data)
{
bool quiet = (info.quiet_given || info.mode == "clone");
bool save = (info.mode == "clone");
// Skip back to the beginning of the reference list
// FIXME: Changes to the references backend required to support multiple plugins have
// almost certainly broken this following line. I'll leave it as is for now, so that
// the compiler does not complain.
cell.restore(esm, 0);
// Loop through all the references
ESM::CellRef ref;
if (!quiet)
std::cout << " References:\n";
bool deleted = false;
ESM::MovedCellRef movedCellRef;
bool moved = false;
while (cell.getNextRef(esm, ref, deleted, movedCellRef, moved))
{
if (data != nullptr && save)
data->mCellRefs[&cell].push_back(std::make_pair(ref, deleted));
if (quiet)
continue;
std::cout << " - Refnum: " << ref.mRefNum.mIndex << '\n';
std::cout << " ID: " << ref.mRefID << '\n';
std::cout << " Position: (" << ref.mPos.pos[0] << ", " << ref.mPos.pos[1] << ", " << ref.mPos.pos[2]
<< ")\n";
if (ref.mScale != 1.f)
std::cout << " Scale: " << ref.mScale << '\n';
if (!ref.mOwner.empty())
std::cout << " Owner: " << ref.mOwner << '\n';
if (!ref.mGlobalVariable.empty())
std::cout << " Global: " << ref.mGlobalVariable << '\n';
if (!ref.mFaction.empty())
std::cout << " Faction: " << ref.mFaction << '\n';
if (!ref.mFaction.empty() || ref.mFactionRank != -2)
std::cout << " Faction rank: " << ref.mFactionRank << '\n';
std::cout << " Enchantment charge: " << ref.mEnchantmentCharge << '\n';
std::cout << " Uses/health: " << ref.mChargeInt << '\n';
std::cout << " Count: " << ref.mCount << '\n';
std::cout << " Blocked: " << static_cast<int>(ref.mReferenceBlocked) << '\n';
std::cout << " Deleted: " << deleted << '\n';
if (!ref.mKey.empty())
std::cout << " Key: " << ref.mKey << '\n';
std::cout << " Lock level: " << ref.mLockLevel << '\n';
if (!ref.mTrap.empty())
std::cout << " Trap: " << ref.mTrap << '\n';
if (!ref.mSoul.empty())
std::cout << " Soul: " << ref.mSoul << '\n';
if (ref.mTeleport)
{
std::cout << " Destination position: (" << ref.mDoorDest.pos[0] << ", " << ref.mDoorDest.pos[1]
<< ", " << ref.mDoorDest.pos[2] << ")\n";
if (!ref.mDestCell.empty())
std::cout << " Destination cell: " << ref.mDestCell << '\n';
}
std::cout << " Moved: " << std::boolalpha << moved << std::noboolalpha << '\n';
if (moved)
{
std::cout << " Moved refnum: " << movedCellRef.mRefNum.mIndex << '\n';
std::cout << " Moved content file: " << movedCellRef.mRefNum.mContentFile << '\n';
std::cout << " Target: " << movedCellRef.mTarget[0] << ", " << movedCellRef.mTarget[1] << '\n';
}
}
}
void printRawTes3(const std::filesystem::path& path)
{
std::cout << "TES3 RAW file listing: " << Files::pathToUnicodeString(path) << '\n';
ESM::ESMReader esm;
esm.openRaw(path);
while (esm.hasMoreRecs())
{
ESM::NAME n = esm.getRecName();
std::cout << "Record: " << n.toStringView() << '\n';
esm.getRecHeader();
while (esm.hasMoreSubs())
{
size_t offs = esm.getFileOffset();
esm.getSubName();
esm.skipHSub();
n = esm.retSubName();
std::ios::fmtflags f(std::cout.flags());
std::cout << " " << n.toStringView() << " - " << esm.getSubSize() << " bytes @ 0x" << std::hex
<< offs << '\n';
std::cout.flags(f);
}
}
}
int loadTes3(const Arguments& info, std::unique_ptr<std::ifstream>&& stream, ESMData* data)
{
std::cout << "Loading TES3 file: " << info.filename << '\n';
ESM::ESMReader esm;
ToUTF8::Utf8Encoder encoder(ToUTF8::calculateEncoding(info.encoding));
esm.setEncoder(&encoder);
std::unordered_set<uint32_t> skipped;
try
{
bool quiet = (info.quiet_given || info.mode == "clone");
bool loadCells = (info.loadcells_given || info.mode == "clone");
bool save = (info.mode == "clone");
esm.open(std::move(stream), info.filename);
if (data != nullptr)
data->mHeader = esm.getHeader();
if (!quiet)
{
std::cout << "Author: " << esm.getAuthor() << '\n'
<< "Description: " << esm.getDesc() << '\n'
<< "File format version: " << esm.esmVersionF() << '\n';
std::vector<ESM::Header::MasterData> masterData = esm.getGameFiles();
if (!masterData.empty())
{
std::cout << "Masters:" << '\n';
for (const auto& master : masterData)
std::cout << " " << master.name << ", " << master.size << " bytes\n";
}
}
// Loop through all records
while (esm.hasMoreRecs())
{
const ESM::NAME n = esm.getRecName();
uint32_t flags;
esm.getRecHeader(flags);
auto record = EsmTool::RecordBase::create(n);
if (record == nullptr)
{
if (!quiet && skipped.count(n.toInt()) == 0)
{
std::cout << "Skipping " << n.toStringView() << " records.\n";
skipped.emplace(n.toInt());
}
esm.skipRecord();
if (quiet)
break;
std::cout << " Skipping\n";
continue;
}
record->setFlags(static_cast<int>(flags));
record->setPrintPlain(info.plain_given);
record->load(esm);
// Is the user interested in this record type?
bool interested = true;
if (!info.types.empty()
&& std::find(info.types.begin(), info.types.end(), n.toStringView()) == info.types.end())
interested = false;
if (!info.name.empty() && !Misc::StringUtils::ciEqual(info.name, record->getId()))
interested = false;
if (!quiet && interested)
{
std::cout << "\nRecord: " << n.toStringView() << " " << record->getId() << "\n"
<< "Record flags: " << recordFlags(record->getFlags()) << '\n';
record->print();
}
if (record->getType().toInt() == ESM::REC_CELL && loadCells && interested)
{
loadCell(info, record->cast<ESM::Cell>()->get(), esm, data);
}
if (data != nullptr)
{
if (save)
data->mRecords.push_back(std::move(record));
++data->mRecordStats[n.toInt()];
}
}
}
catch (const std::exception& e)
{
std::cout << "\nERROR:\n\n " << e.what() << std::endl;
if (data != nullptr)
data->mRecords.clear();
return 1;
}
return 0;
}
int load(const Arguments& info, ESMData* data)
{
if (info.mRawFormat.has_value() && info.mode == "dump")
{
switch (*info.mRawFormat)
{
case ESM::Format::Tes3:
printRawTes3(info.filename);
break;
case ESM::Format::Tes4:
std::cout << "Printing raw TES4 file is not supported: "
<< Files::pathToUnicodeString(info.filename) << "\n";
break;
}
return 0;
}
auto stream = Files::openBinaryInputFileStream(info.filename);
if (!stream->is_open())
{
std::cout << "Failed to open file " << info.filename << ": " << std::generic_category().message(errno)
<< '\n';
return -1;
}
const ESM::Format format = ESM::readFormat(*stream);
stream->seekg(0);
switch (format)
{
case ESM::Format::Tes3:
return loadTes3(info, std::move(stream), data);
case ESM::Format::Tes4:
if (data != nullptr)
{
std::cout << "Collecting data from esm file is not supported for TES4\n";
return -1;
}
return loadTes4(info, std::move(stream));
}
std::cout << "Unsupported ESM format: " << ESM::NAME(format).toStringView() << '\n';
return -1;
}
int clone(const Arguments& info)
{
if (info.outname.empty())
{
std::cout << "You need to specify an output name" << std::endl;
return 1;
}
ESMData data;
if (load(info, &data) != 0)
{
std::cout << "Failed to load, aborting." << std::endl;
return 1;
}
size_t recordCount = data.mRecords.size();
int digitCount = 1; // For a nicer output
if (recordCount > 0)
digitCount = (int)std::log10(recordCount) + 1;
std::cout << "Loaded " << recordCount << " records:\n\n";
int i = 0;
for (std::pair<int, int> stat : data.mRecordStats)
{
ESM::NAME name;
name = stat.first;
int amount = stat.second;
std::cout << std::setw(digitCount) << amount << " " << name.toStringView() << " ";
if (++i % 3 == 0)
std::cout << '\n';
}
if (i % 3 != 0)
std::cout << '\n';
std::cout << "\nSaving records to: " << Files::pathToUnicodeString(info.outname) << "...\n";
ESM::ESMWriter esm;
ToUTF8::Utf8Encoder encoder(ToUTF8::calculateEncoding(info.encoding));
esm.setEncoder(&encoder);
esm.setHeader(data.mHeader);
esm.setVersion(ESM::VER_130);
esm.setRecordCount(recordCount);
std::fstream save(info.outname, std::fstream::out | std::fstream::binary);
esm.save(save);
int saved = 0;
for (auto& record : data.mRecords)
{
if (i <= 0)
break;
const ESM::NAME typeName = record->getType();
esm.startRecord(typeName, record->getFlags());
record->save(esm);
if (typeName.toInt() == ESM::REC_CELL)
{
ESM::Cell* ptr = &record->cast<ESM::Cell>()->get();
if (!data.mCellRefs[ptr].empty())
{
for (std::pair<ESM::CellRef, bool>& ref : data.mCellRefs[ptr])
ref.first.save(esm, ref.second);
}
}
esm.endRecord(typeName);
saved++;
int perc = recordCount == 0 ? 100 : (int)((saved / (float)recordCount) * 100);
if (perc % 10 == 0)
{
std::cerr << "\r" << perc << "%";
}
}
std::cout << "\rDone!" << std::endl;
esm.close();
save.close();
return 0;
}
int comp(const Arguments& info)
{
if (info.filename.empty() || info.outname.empty())
{
std::cout << "You need to specify two input files" << std::endl;
return 1;
}
Arguments fileOne;
Arguments fileTwo;
fileOne.mode = "clone";
fileTwo.mode = "clone";
fileOne.encoding = info.encoding;
fileTwo.encoding = info.encoding;
fileOne.filename = info.filename;
fileTwo.filename = info.outname;
ESMData dataOne;
if (load(fileOne, &dataOne) != 0)
{
std::cout << "Failed to load " << Files::pathToUnicodeString(info.filename) << ", aborting comparison."
<< std::endl;
return 1;
}
ESMData dataTwo;
if (load(fileTwo, &dataTwo) != 0)
{
std::cout << "Failed to load " << Files::pathToUnicodeString(info.outname) << ", aborting comparison."
<< std::endl;
return 1;
}
if (dataOne.mRecords.size() != dataTwo.mRecords.size())
{
std::cout << "Not equal, different amount of records." << std::endl;
return 1;
}
return 0;
}
}
| 21,595
|
C++
|
.cpp
| 506
| 30.950593
| 120
| 0.512956
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,181
|
record.cpp
|
OpenMW_openmw/apps/esmtool/record.cpp
|
#include "record.hpp"
#include "labels.hpp"
#include <iostream>
#include <numeric>
#include <sstream>
#include <components/esm3/cellstate.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/misc/strings/format.hpp>
namespace
{
void printAIPackage(const ESM::AIPackage& p)
{
std::cout << " AI Type: " << aiTypeLabel(p.mType) << " (" << Misc::StringUtils::format("0x%08X", p.mType)
<< ")" << std::endl;
if (p.mType == ESM::AI_Wander)
{
std::cout << " Distance: " << p.mWander.mDistance << std::endl;
std::cout << " Duration: " << p.mWander.mDuration << std::endl;
std::cout << " Time of Day: " << (int)p.mWander.mTimeOfDay << std::endl;
if (p.mWander.mShouldRepeat != 1)
std::cout << " Should repeat: " << static_cast<bool>(p.mWander.mShouldRepeat != 0) << std::endl;
std::cout << " Idle: ";
for (int i = 0; i != 8; i++)
std::cout << (int)p.mWander.mIdle[i] << " ";
std::cout << std::endl;
}
else if (p.mType == ESM::AI_Travel)
{
std::cout << " Travel Coordinates: (" << p.mTravel.mX << "," << p.mTravel.mY << "," << p.mTravel.mZ
<< ")" << std::endl;
std::cout << " Should repeat: " << static_cast<bool>(p.mTravel.mShouldRepeat != 0) << std::endl;
}
else if (p.mType == ESM::AI_Follow || p.mType == ESM::AI_Escort)
{
std::cout << " Follow Coordinates: (" << p.mTarget.mX << "," << p.mTarget.mY << "," << p.mTarget.mZ
<< ")" << std::endl;
std::cout << " Duration: " << p.mTarget.mDuration << std::endl;
std::cout << " Target ID: " << p.mTarget.mId.toString() << std::endl;
std::cout << " Should repeat: " << static_cast<bool>(p.mTarget.mShouldRepeat != 0) << std::endl;
}
else if (p.mType == ESM::AI_Activate)
{
std::cout << " Name: " << p.mActivate.mName.toString() << std::endl;
std::cout << " Should repeat: " << static_cast<bool>(p.mActivate.mShouldRepeat != 0) << std::endl;
}
else
{
std::cout << " BadPackage: " << Misc::StringUtils::format("0x%08X", p.mType) << std::endl;
}
if (!p.mCellName.empty())
std::cout << " Cell Name: " << p.mCellName << std::endl;
}
std::string ruleString(const ESM::DialogueCondition& ss)
{
std::string_view type_str = "INVALID";
std::string_view func_str;
switch (ss.mFunction)
{
case ESM::DialogueCondition::Function_Global:
type_str = "Global";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_Local:
type_str = "Local";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_Journal:
type_str = "Journal";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_Item:
type_str = "Item count";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_Dead:
type_str = "Dead";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_NotId:
type_str = "Not ID";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_NotFaction:
type_str = "Not Faction";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_NotClass:
type_str = "Not Class";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_NotRace:
type_str = "Not Race";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_NotCell:
type_str = "Not Cell";
func_str = ss.mVariable;
break;
case ESM::DialogueCondition::Function_NotLocal:
type_str = "Not Local";
func_str = ss.mVariable;
break;
default:
type_str = "Function";
func_str = ruleFunction(ss.mFunction);
break;
}
std::string_view oper_str = "??";
switch (ss.mComparison)
{
case ESM::DialogueCondition::Comp_Eq:
oper_str = "==";
break;
case ESM::DialogueCondition::Comp_Ne:
oper_str = "!=";
break;
case ESM::DialogueCondition::Comp_Gt:
oper_str = "> ";
break;
case ESM::DialogueCondition::Comp_Ge:
oper_str = ">=";
break;
case ESM::DialogueCondition::Comp_Ls:
oper_str = "< ";
break;
case ESM::DialogueCondition::Comp_Le:
oper_str = "<=";
break;
default:
break;
}
std::ostringstream stream;
std::visit([&](auto value) { stream << value; }, ss.mValue);
std::string result
= Misc::StringUtils::format("%-12s %-32s %2s %s", type_str, func_str, oper_str, stream.str());
return result;
}
void printEffectList(const ESM::EffectList& effects)
{
int i = 0;
for (const ESM::IndexedENAMstruct& effect : effects.mList)
{
std::cout << " Effect[" << i << "]: " << magicEffectLabel(effect.mData.mEffectID) << " ("
<< effect.mData.mEffectID << ")" << std::endl;
if (effect.mData.mSkill != -1)
std::cout << " Skill: " << skillLabel(effect.mData.mSkill) << " (" << (int)effect.mData.mSkill << ")"
<< std::endl;
if (effect.mData.mAttribute != -1)
std::cout << " Attribute: " << attributeLabel(effect.mData.mAttribute) << " ("
<< (int)effect.mData.mAttribute << ")" << std::endl;
std::cout << " Range: " << rangeTypeLabel(effect.mData.mRange) << " (" << effect.mData.mRange << ")"
<< std::endl;
// Area is always zero if range type is "Self"
if (effect.mData.mRange != ESM::RT_Self)
std::cout << " Area: " << effect.mData.mArea << std::endl;
std::cout << " Duration: " << effect.mData.mDuration << std::endl;
std::cout << " Magnitude: " << effect.mData.mMagnMin << "-" << effect.mData.mMagnMax << std::endl;
i++;
}
}
void printTransport(const std::vector<ESM::Transport::Dest>& transport)
{
for (const ESM::Transport::Dest& dest : transport)
{
std::cout << " Destination Position: " << Misc::StringUtils::format("%12.3f", dest.mPos.pos[0]) << ","
<< Misc::StringUtils::format("%12.3f", dest.mPos.pos[1]) << ","
<< Misc::StringUtils::format("%12.3f", dest.mPos.pos[2]) << ")" << std::endl;
std::cout << " Destination Rotation: " << Misc::StringUtils::format("%9.6f", dest.mPos.rot[0]) << ","
<< Misc::StringUtils::format("%9.6f", dest.mPos.rot[1]) << ","
<< Misc::StringUtils::format("%9.6f", dest.mPos.rot[2]) << ")" << std::endl;
if (!dest.mCellName.empty())
std::cout << " Destination Cell: " << dest.mCellName << std::endl;
}
}
}
namespace EsmTool
{
void CellState::load(ESM::ESMReader& reader, bool& deleted)
{
mCellState.mId = reader.getCellId();
mCellState.load(reader);
if (mCellState.mHasFogOfWar)
mFogState.load(reader);
deleted = false;
reader.skipRecord();
}
std::unique_ptr<RecordBase> RecordBase::create(const ESM::NAME type)
{
std::unique_ptr<RecordBase> record;
switch (type.toInt())
{
case ESM::REC_ACTI:
{
record = std::make_unique<EsmTool::Record<ESM::Activator>>();
break;
}
case ESM::REC_ALCH:
{
record = std::make_unique<EsmTool::Record<ESM::Potion>>();
break;
}
case ESM::REC_APPA:
{
record = std::make_unique<EsmTool::Record<ESM::Apparatus>>();
break;
}
case ESM::REC_ARMO:
{
record = std::make_unique<EsmTool::Record<ESM::Armor>>();
break;
}
case ESM::REC_BODY:
{
record = std::make_unique<EsmTool::Record<ESM::BodyPart>>();
break;
}
case ESM::REC_BOOK:
{
record = std::make_unique<EsmTool::Record<ESM::Book>>();
break;
}
case ESM::REC_BSGN:
{
record = std::make_unique<EsmTool::Record<ESM::BirthSign>>();
break;
}
case ESM::REC_CELL:
{
record = std::make_unique<EsmTool::Record<ESM::Cell>>();
break;
}
case ESM::REC_CLAS:
{
record = std::make_unique<EsmTool::Record<ESM::Class>>();
break;
}
case ESM::REC_CLOT:
{
record = std::make_unique<EsmTool::Record<ESM::Clothing>>();
break;
}
case ESM::REC_CONT:
{
record = std::make_unique<EsmTool::Record<ESM::Container>>();
break;
}
case ESM::REC_CREA:
{
record = std::make_unique<EsmTool::Record<ESM::Creature>>();
break;
}
case ESM::REC_DIAL:
{
record = std::make_unique<EsmTool::Record<ESM::Dialogue>>();
break;
}
case ESM::REC_DOOR:
{
record = std::make_unique<EsmTool::Record<ESM::Door>>();
break;
}
case ESM::REC_ENCH:
{
record = std::make_unique<EsmTool::Record<ESM::Enchantment>>();
break;
}
case ESM::REC_FACT:
{
record = std::make_unique<EsmTool::Record<ESM::Faction>>();
break;
}
case ESM::REC_GLOB:
{
record = std::make_unique<EsmTool::Record<ESM::Global>>();
break;
}
case ESM::REC_GMST:
{
record = std::make_unique<EsmTool::Record<ESM::GameSetting>>();
break;
}
case ESM::REC_INFO:
{
record = std::make_unique<EsmTool::Record<ESM::DialInfo>>();
break;
}
case ESM::REC_INGR:
{
record = std::make_unique<EsmTool::Record<ESM::Ingredient>>();
break;
}
case ESM::REC_LAND:
{
record = std::make_unique<EsmTool::Record<ESM::Land>>();
break;
}
case ESM::REC_LEVI:
{
record = std::make_unique<EsmTool::Record<ESM::ItemLevList>>();
break;
}
case ESM::REC_LEVC:
{
record = std::make_unique<EsmTool::Record<ESM::CreatureLevList>>();
break;
}
case ESM::REC_LIGH:
{
record = std::make_unique<EsmTool::Record<ESM::Light>>();
break;
}
case ESM::REC_LOCK:
{
record = std::make_unique<EsmTool::Record<ESM::Lockpick>>();
break;
}
case ESM::REC_LTEX:
{
record = std::make_unique<EsmTool::Record<ESM::LandTexture>>();
break;
}
case ESM::REC_MISC:
{
record = std::make_unique<EsmTool::Record<ESM::Miscellaneous>>();
break;
}
case ESM::REC_MGEF:
{
record = std::make_unique<EsmTool::Record<ESM::MagicEffect>>();
break;
}
case ESM::REC_NPC_:
{
record = std::make_unique<EsmTool::Record<ESM::NPC>>();
break;
}
case ESM::REC_PGRD:
{
record = std::make_unique<EsmTool::Record<ESM::Pathgrid>>();
break;
}
case ESM::REC_PROB:
{
record = std::make_unique<EsmTool::Record<ESM::Probe>>();
break;
}
case ESM::REC_RACE:
{
record = std::make_unique<EsmTool::Record<ESM::Race>>();
break;
}
case ESM::REC_REGN:
{
record = std::make_unique<EsmTool::Record<ESM::Region>>();
break;
}
case ESM::REC_REPA:
{
record = std::make_unique<EsmTool::Record<ESM::Repair>>();
break;
}
case ESM::REC_SCPT:
{
record = std::make_unique<EsmTool::Record<ESM::Script>>();
break;
}
case ESM::REC_SKIL:
{
record = std::make_unique<EsmTool::Record<ESM::Skill>>();
break;
}
case ESM::REC_SNDG:
{
record = std::make_unique<EsmTool::Record<ESM::SoundGenerator>>();
break;
}
case ESM::REC_SOUN:
{
record = std::make_unique<EsmTool::Record<ESM::Sound>>();
break;
}
case ESM::REC_SPEL:
{
record = std::make_unique<EsmTool::Record<ESM::Spell>>();
break;
}
case ESM::REC_STAT:
{
record = std::make_unique<EsmTool::Record<ESM::Static>>();
break;
}
case ESM::REC_WEAP:
{
record = std::make_unique<EsmTool::Record<ESM::Weapon>>();
break;
}
case ESM::REC_SSCR:
{
record = std::make_unique<EsmTool::Record<ESM::StartScript>>();
break;
}
case ESM::REC_CSTA:
{
record = std::make_unique<EsmTool::Record<CellState>>();
break;
}
default:
break;
}
if (record)
{
record->mType = type;
}
return record;
}
template <>
void Record<ESM::Activator>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Potion>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Flags: " << potionFlags(mData.mData.mFlags) << std::endl;
printEffectList(mData.mEffects);
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Armor>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
if (!mData.mEnchant.empty())
std::cout << " Enchantment: " << mData.mEnchant << std::endl;
std::cout << " Type: " << armorTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Health: " << mData.mData.mHealth << std::endl;
std::cout << " Armor: " << mData.mData.mArmor << std::endl;
std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl;
for (const ESM::PartReference& part : mData.mParts.mParts)
{
std::cout << " Body Part: " << bodyPartLabel(part.mPart) << " (" << (int)(part.mPart) << ")" << std::endl;
std::cout << " Male Name: " << part.mMale << std::endl;
if (!part.mFemale.empty())
std::cout << " Female Name: " << part.mFemale << std::endl;
}
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Apparatus>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Type: " << apparatusTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")"
<< std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Quality: " << mData.mData.mQuality << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::BodyPart>::print()
{
std::cout << " Race: " << mData.mRace << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Type: " << meshTypeLabel(mData.mData.mType) << " (" << (int)mData.mData.mType << ")"
<< std::endl;
std::cout << " Flags: " << bodyPartFlags(mData.mData.mFlags) << std::endl;
std::cout << " Part: " << meshPartLabel(mData.mData.mPart) << " (" << (int)mData.mData.mPart << ")"
<< std::endl;
std::cout << " Vampire: " << (int)mData.mData.mVampire << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Book>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
if (!mData.mEnchant.empty())
std::cout << " Enchantment: " << mData.mEnchant << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " IsScroll: " << mData.mData.mIsScroll << std::endl;
std::cout << " SkillId: " << mData.mData.mSkillId << std::endl;
std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl;
if (mPrintPlain)
{
std::cout << " Text:" << std::endl;
std::cout << "START--------------------------------------" << std::endl;
std::cout << mData.mText << std::endl;
std::cout << "END----------------------------------------" << std::endl;
}
else
{
std::cout << " Text: [skipped]" << std::endl;
}
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::BirthSign>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Texture: " << mData.mTexture << std::endl;
std::cout << " Description: " << mData.mDescription << std::endl;
for (const auto& power : mData.mPowers.mList)
std::cout << " Power: " << power << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Cell>::print()
{
// None of the cells have names...
if (!mData.mName.empty())
std::cout << " Name: " << mData.mName << std::endl;
if (!mData.mRegion.empty())
std::cout << " Region: " << mData.mRegion << std::endl;
std::cout << " Flags: " << cellFlags(mData.mData.mFlags) << std::endl;
std::cout << " Coordinates: "
<< " (" << mData.getGridX() << "," << mData.getGridY() << ")" << std::endl;
if (mData.mData.mFlags & ESM::Cell::Interior && !(mData.mData.mFlags & ESM::Cell::QuasiEx))
{
if (mData.hasAmbient())
{
// TODO: see if we can change the integer representation to something more sensible
std::cout << " Ambient Light Color: " << mData.mAmbi.mAmbient << std::endl;
std::cout << " Sunlight Color: " << mData.mAmbi.mSunlight << std::endl;
std::cout << " Fog Color: " << mData.mAmbi.mFog << std::endl;
std::cout << " Fog Density: " << mData.mAmbi.mFogDensity << std::endl;
}
else
{
std::cout << " No Ambient Information" << std::endl;
}
std::cout << " Water Level: " << mData.mWater << std::endl;
}
else
std::cout << " Map Color: " << Misc::StringUtils::format("0x%08X", mData.mMapColor) << std::endl;
std::cout << " RefId counter: " << mData.mRefNumCounter << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Class>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Description: " << mData.mDescription << std::endl;
std::cout << " Playable: " << mData.mData.mIsPlayable << std::endl;
std::cout << " AI Services: " << Misc::StringUtils::format("0x%08X", mData.mData.mServices) << std::endl;
for (size_t i = 0; i < mData.mData.mAttribute.size(); ++i)
std::cout << " Attribute" << (i + 1) << ": " << attributeLabel(mData.mData.mAttribute[i]) << " ("
<< mData.mData.mAttribute[i] << ")" << std::endl;
std::cout << " Specialization: " << specializationLabel(mData.mData.mSpecialization) << " ("
<< mData.mData.mSpecialization << ")" << std::endl;
for (const auto& skills : mData.mData.mSkills)
std::cout << " Minor Skill: " << skillLabel(skills[0]) << " (" << skills[0] << ")" << std::endl;
for (const auto& skills : mData.mData.mSkills)
std::cout << " Major Skill: " << skillLabel(skills[1]) << " (" << skills[1] << ")" << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Clothing>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
if (!mData.mEnchant.empty())
std::cout << " Enchantment: " << mData.mEnchant << std::endl;
std::cout << " Type: " << clothingTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")"
<< std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl;
for (const ESM::PartReference& part : mData.mParts.mParts)
{
std::cout << " Body Part: " << bodyPartLabel(part.mPart) << " (" << (int)(part.mPart) << ")" << std::endl;
std::cout << " Male Name: " << part.mMale << std::endl;
if (!part.mFemale.empty())
std::cout << " Female Name: " << part.mFemale << std::endl;
}
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Container>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Flags: " << containerFlags(mData.mFlags) << std::endl;
std::cout << " Weight: " << mData.mWeight << std::endl;
for (const ESM::ContItem& item : mData.mInventory.mList)
std::cout << " Inventory: Count: " << Misc::StringUtils::format("%4d", item.mCount)
<< " Item: " << item.mItem << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Creature>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Flags: " << creatureFlags((int)mData.mFlags) << std::endl;
std::cout << " Blood Type: " << mData.mBloodType + 1 << std::endl;
std::cout << " Original: " << mData.mOriginal << std::endl;
std::cout << " Scale: " << mData.mScale << std::endl;
std::cout << " Type: " << creatureTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")"
<< std::endl;
std::cout << " Level: " << mData.mData.mLevel << std::endl;
std::cout << " Attributes:" << std::endl;
for (size_t i = 0; i < mData.mData.mAttributes.size(); ++i)
std::cout << " " << ESM::Attribute::indexToRefId(i) << ": " << mData.mData.mAttributes[i] << std::endl;
std::cout << " Health: " << mData.mData.mHealth << std::endl;
std::cout << " Magicka: " << mData.mData.mMana << std::endl;
std::cout << " Fatigue: " << mData.mData.mFatigue << std::endl;
std::cout << " Soul: " << mData.mData.mSoul << std::endl;
std::cout << " Combat: " << mData.mData.mCombat << std::endl;
std::cout << " Magic: " << mData.mData.mMagic << std::endl;
std::cout << " Stealth: " << mData.mData.mStealth << std::endl;
std::cout << " Attack1: " << mData.mData.mAttack[0] << "-" << mData.mData.mAttack[1] << std::endl;
std::cout << " Attack2: " << mData.mData.mAttack[2] << "-" << mData.mData.mAttack[3] << std::endl;
std::cout << " Attack3: " << mData.mData.mAttack[4] << "-" << mData.mData.mAttack[5] << std::endl;
std::cout << " Gold: " << mData.mData.mGold << std::endl;
for (const ESM::ContItem& item : mData.mInventory.mList)
std::cout << " Inventory: Count: " << Misc::StringUtils::format("%4d", item.mCount)
<< " Item: " << item.mItem << std::endl;
for (const auto& spell : mData.mSpells.mList)
std::cout << " Spell: " << spell << std::endl;
printTransport(mData.getTransport());
std::cout << " Artificial Intelligence: " << std::endl;
std::cout << " AI Hello:" << (int)mData.mAiData.mHello << std::endl;
std::cout << " AI Fight:" << (int)mData.mAiData.mFight << std::endl;
std::cout << " AI Flee:" << (int)mData.mAiData.mFlee << std::endl;
std::cout << " AI Alarm:" << (int)mData.mAiData.mAlarm << std::endl;
std::cout << " AI Services:" << Misc::StringUtils::format("0x%08X", mData.mAiData.mServices) << std::endl;
for (const ESM::AIPackage& package : mData.mAiPackage.mList)
printAIPackage(package);
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Dialogue>::print()
{
std::cout << " StringId: " << mData.mStringId << std::endl;
std::cout << " Type: " << dialogTypeLabel(mData.mType) << " (" << (int)mData.mType << ")" << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
// Sadly, there are no DialInfos, because the loader dumps as it
// loads, rather than loading and then dumping. :-( Anyone mind if
// I change this?
for (const ESM::DialInfo& info : mData.mInfo)
std::cout << "INFO!" << info.mId << std::endl;
}
template <>
void Record<ESM::Door>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " OpenSound: " << mData.mOpenSound << std::endl;
std::cout << " CloseSound: " << mData.mCloseSound << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Enchantment>::print()
{
std::cout << " Type: " << enchantTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl;
std::cout << " Cost: " << mData.mData.mCost << std::endl;
std::cout << " Charge: " << mData.mData.mCharge << std::endl;
std::cout << " Flags: " << enchantmentFlags(mData.mData.mFlags) << std::endl;
printEffectList(mData.mEffects);
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Faction>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Hidden: " << mData.mData.mIsHidden << std::endl;
for (size_t i = 0; i < mData.mData.mAttribute.size(); ++i)
std::cout << " Attribute" << (i + 1) << ": " << attributeLabel(mData.mData.mAttribute[i]) << " ("
<< mData.mData.mAttribute[i] << ")" << std::endl;
for (int skill : mData.mData.mSkills)
if (skill != -1)
std::cout << " Skill: " << skillLabel(skill) << " (" << skill << ")" << std::endl;
for (size_t i = 0; i != mData.mData.mRankData.size(); i++)
if (!mData.mRanks[i].empty())
{
std::cout << " Rank: " << mData.mRanks[i] << std::endl;
std::cout << " Attribute1 Requirement: " << mData.mData.mRankData[i].mAttribute1 << std::endl;
std::cout << " Attribute2 Requirement: " << mData.mData.mRankData[i].mAttribute2 << std::endl;
std::cout << " One Skill at Level: " << mData.mData.mRankData[i].mPrimarySkill << std::endl;
std::cout << " Two Skills at Level: " << mData.mData.mRankData[i].mFavouredSkill << std::endl;
std::cout << " Faction Reaction: " << mData.mData.mRankData[i].mFactReaction << std::endl;
}
for (const auto& reaction : mData.mReactions)
std::cout << " Reaction: " << reaction.second << " = " << reaction.first << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Global>::print()
{
std::cout << " " << mData.mValue << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::GameSetting>::print()
{
std::cout << " " << mData.mValue << std::endl;
}
template <>
void Record<ESM::DialInfo>::print()
{
std::cout << " Id: " << mData.mId << std::endl;
if (!mData.mPrev.empty())
std::cout << " Previous ID: " << mData.mPrev << std::endl;
if (!mData.mNext.empty())
std::cout << " Next ID: " << mData.mNext << std::endl;
std::cout << " Text: " << mData.mResponse << std::endl;
if (!mData.mActor.empty())
std::cout << " Actor: " << mData.mActor << std::endl;
if (!mData.mRace.empty())
std::cout << " Race: " << mData.mRace << std::endl;
if (!mData.mClass.empty())
std::cout << " Class: " << mData.mClass << std::endl;
std::cout << " Factionless: " << mData.mFactionLess << std::endl;
if (!mData.mFaction.empty())
std::cout << " NPC Faction: " << mData.mFaction << std::endl;
if (mData.mData.mRank != -1)
std::cout << " NPC Rank: " << (int)mData.mData.mRank << std::endl;
if (!mData.mPcFaction.empty())
std::cout << " PC Faction: " << mData.mPcFaction << std::endl;
// CHANGE? non-standard capitalization mPCrank -> mPCRank (mPcRank?)
if (mData.mData.mPCrank != -1)
std::cout << " PC Rank: " << (int)mData.mData.mPCrank << std::endl;
if (!mData.mCell.empty())
std::cout << " Cell: " << mData.mCell << std::endl;
if (mData.mData.mDisposition > 0)
std::cout << " Disposition/Journal index: " << mData.mData.mDisposition << std::endl;
if (mData.mData.mGender != ESM::DialInfo::NA)
std::cout << " Gender: " << static_cast<int>(mData.mData.mGender) << std::endl;
if (!mData.mSound.empty())
std::cout << " Sound File: " << mData.mSound << std::endl;
std::cout << " Quest Status: " << questStatusLabel(mData.mQuestStatus) << " (" << mData.mQuestStatus << ")"
<< std::endl;
std::cout << " Type: " << dialogTypeLabel(mData.mData.mType) << std::endl;
for (const auto& rule : mData.mSelects)
std::cout << " Select Rule: " << ruleString(rule) << std::endl;
if (!mData.mResultScript.empty())
{
if (mPrintPlain)
{
std::cout << " Result Script:" << std::endl;
std::cout << "START--------------------------------------" << std::endl;
std::cout << mData.mResultScript << std::endl;
std::cout << "END----------------------------------------" << std::endl;
}
else
{
std::cout << " Result Script: [skipped]" << std::endl;
}
}
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Ingredient>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
for (int i = 0; i != 4; i++)
{
// A value of -1 means no effect
if (mData.mData.mEffectID[i] == -1)
continue;
std::cout << " Effect: " << magicEffectLabel(mData.mData.mEffectID[i]) << " (" << mData.mData.mEffectID[i]
<< ")" << std::endl;
std::cout << " Skill: " << skillLabel(mData.mData.mSkills[i]) << " (" << mData.mData.mSkills[i] << ")"
<< std::endl;
std::cout << " Attribute: " << attributeLabel(mData.mData.mAttributes[i]) << " ("
<< mData.mData.mAttributes[i] << ")" << std::endl;
}
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Land>::print()
{
std::cout << " Coordinates: (" << mData.mX << "," << mData.mY << ")" << std::endl;
std::cout << " Flags: " << landFlags(mData.mFlags) << std::endl;
std::cout << " DataTypes: " << mData.mDataTypes << std::endl;
if (const ESM::Land::LandData* data = mData.getLandData(mData.mDataTypes))
{
std::cout << " MinHeight: " << data->mMinHeight << std::endl;
std::cout << " MaxHeight: " << data->mMaxHeight << std::endl;
std::cout << " DataLoaded: " << data->mDataLoaded << std::endl;
}
mData.unloadData();
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::CreatureLevList>::print()
{
std::cout << " Chance for None: " << (int)mData.mChanceNone << std::endl;
std::cout << " Flags: " << creatureListFlags(mData.mFlags) << std::endl;
std::cout << " Number of items: " << mData.mList.size() << std::endl;
for (const ESM::LevelledListBase::LevelItem& item : mData.mList)
std::cout << " Creature: Level: " << item.mLevel << " Creature: " << item.mId << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::ItemLevList>::print()
{
std::cout << " Chance for None: " << (int)mData.mChanceNone << std::endl;
std::cout << " Flags: " << itemListFlags(mData.mFlags) << std::endl;
std::cout << " Number of items: " << mData.mList.size() << std::endl;
for (const ESM::LevelledListBase::LevelItem& item : mData.mList)
std::cout << " Inventory: Level: " << item.mLevel << " Item: " << item.mId << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Light>::print()
{
if (!mData.mName.empty())
std::cout << " Name: " << mData.mName << std::endl;
if (!mData.mModel.empty())
std::cout << " Model: " << mData.mModel << std::endl;
if (!mData.mIcon.empty())
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Flags: " << lightFlags(mData.mData.mFlags) << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Sound: " << mData.mSound << std::endl;
std::cout << " Duration: " << mData.mData.mTime << std::endl;
std::cout << " Radius: " << mData.mData.mRadius << std::endl;
std::cout << " Color: " << mData.mData.mColor << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Lockpick>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Quality: " << mData.mData.mQuality << std::endl;
std::cout << " Uses: " << mData.mData.mUses << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Probe>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Quality: " << mData.mData.mQuality << std::endl;
std::cout << " Uses: " << mData.mData.mUses << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Repair>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Quality: " << mData.mData.mQuality << std::endl;
std::cout << " Uses: " << mData.mData.mUses << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::LandTexture>::print()
{
std::cout << " Id: " << mData.mId << std::endl;
std::cout << " Index: " << mData.mIndex << std::endl;
std::cout << " Texture: " << mData.mTexture << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::MagicEffect>::print()
{
std::cout << " Index: " << magicEffectLabel(mData.mIndex) << " (" << mData.mIndex << ")" << std::endl;
std::cout << " Description: " << mData.mDescription << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
std::cout << " Flags: " << magicEffectFlags(mData.mData.mFlags) << std::endl;
std::cout << " Particle Texture: " << mData.mParticle << std::endl;
if (!mData.mCasting.empty())
std::cout << " Casting Static: " << mData.mCasting << std::endl;
if (!mData.mCastSound.empty())
std::cout << " Casting Sound: " << mData.mCastSound << std::endl;
if (!mData.mBolt.empty())
std::cout << " Bolt Static: " << mData.mBolt << std::endl;
if (!mData.mBoltSound.empty())
std::cout << " Bolt Sound: " << mData.mBoltSound << std::endl;
if (!mData.mHit.empty())
std::cout << " Hit Static: " << mData.mHit << std::endl;
if (!mData.mHitSound.empty())
std::cout << " Hit Sound: " << mData.mHitSound << std::endl;
if (!mData.mArea.empty())
std::cout << " Area Static: " << mData.mArea << std::endl;
if (!mData.mAreaSound.empty())
std::cout << " Area Sound: " << mData.mAreaSound << std::endl;
std::cout << " School: " << schoolLabel(ESM::MagicSchool::skillRefIdToIndex(mData.mData.mSchool)) << " ("
<< mData.mData.mSchool << ")" << std::endl;
std::cout << " Base Cost: " << mData.mData.mBaseCost << std::endl;
std::cout << " Unknown 1: " << mData.mData.mUnknown1 << std::endl;
std::cout << " Speed: " << mData.mData.mSpeed << std::endl;
std::cout << " Unknown 2: " << mData.mData.mUnknown2 << std::endl;
std::cout << " RGB Color: "
<< "(" << mData.mData.mRed << "," << mData.mData.mGreen << "," << mData.mData.mBlue << ")"
<< std::endl;
}
template <>
void Record<ESM::Miscellaneous>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Is Key: " << (mData.mData.mFlags & ESM::Miscellaneous::Key) << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::NPC>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Animation: " << mData.mModel << std::endl;
std::cout << " Hair Model: " << mData.mHair << std::endl;
std::cout << " Head Model: " << mData.mHead << std::endl;
std::cout << " Race: " << mData.mRace << std::endl;
std::cout << " Class: " << mData.mClass << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
if (!mData.mFaction.empty())
std::cout << " Faction: " << mData.mFaction << std::endl;
std::cout << " Flags: " << npcFlags((int)mData.mFlags) << std::endl;
if (mData.mBloodType != 0)
std::cout << " Blood Type: " << mData.mBloodType + 1 << std::endl;
if (mData.mNpdtType == ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
{
std::cout << " Level: " << mData.mNpdt.mLevel << std::endl;
std::cout << " Reputation: " << (int)mData.mNpdt.mReputation << std::endl;
std::cout << " Disposition: " << (int)mData.mNpdt.mDisposition << std::endl;
std::cout << " Rank: " << (int)mData.mNpdt.mRank << std::endl;
std::cout << " Gold: " << mData.mNpdt.mGold << std::endl;
}
else
{
std::cout << " Level: " << mData.mNpdt.mLevel << std::endl;
std::cout << " Reputation: " << (int)mData.mNpdt.mReputation << std::endl;
std::cout << " Disposition: " << (int)mData.mNpdt.mDisposition << std::endl;
std::cout << " Rank: " << (int)mData.mNpdt.mRank << std::endl;
std::cout << " Attributes:" << std::endl;
for (size_t i = 0; i != mData.mNpdt.mAttributes.size(); i++)
std::cout << " " << attributeLabel(i) << ": " << int(mData.mNpdt.mAttributes[i]) << std::endl;
std::cout << " Skills:" << std::endl;
for (size_t i = 0; i != mData.mNpdt.mSkills.size(); i++)
std::cout << " " << skillLabel(i) << ": " << int(mData.mNpdt.mSkills[i]) << std::endl;
std::cout << " Health: " << mData.mNpdt.mHealth << std::endl;
std::cout << " Magicka: " << mData.mNpdt.mMana << std::endl;
std::cout << " Fatigue: " << mData.mNpdt.mFatigue << std::endl;
std::cout << " Gold: " << mData.mNpdt.mGold << std::endl;
}
for (const ESM::ContItem& item : mData.mInventory.mList)
std::cout << " Inventory: Count: " << Misc::StringUtils::format("%4d", item.mCount)
<< " Item: " << item.mItem << std::endl;
for (const auto& spell : mData.mSpells.mList)
std::cout << " Spell: " << spell << std::endl;
printTransport(mData.getTransport());
std::cout << " Artificial Intelligence: " << std::endl;
std::cout << " AI Hello:" << (int)mData.mAiData.mHello << std::endl;
std::cout << " AI Fight:" << (int)mData.mAiData.mFight << std::endl;
std::cout << " AI Flee:" << (int)mData.mAiData.mFlee << std::endl;
std::cout << " AI Alarm:" << (int)mData.mAiData.mAlarm << std::endl;
std::cout << " AI Services:" << Misc::StringUtils::format("0x%08X", mData.mAiData.mServices) << std::endl;
for (const ESM::AIPackage& package : mData.mAiPackage.mList)
printAIPackage(package);
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Pathgrid>::print()
{
std::cout << " Cell: " << mData.mCell << std::endl;
std::cout << " Coordinates: (" << mData.mData.mX << "," << mData.mData.mY << ")" << std::endl;
std::cout << " Granularity: " << mData.mData.mGranularity << std::endl;
if (mData.mData.mPoints != mData.mPoints.size())
std::cout << " Reported Point Count: " << mData.mData.mPoints << std::endl;
std::cout << " Point Count: " << mData.mPoints.size() << std::endl;
std::cout << " Edge Count: " << mData.mEdges.size() << std::endl;
int i = 0;
for (const ESM::Pathgrid::Point& point : mData.mPoints)
{
std::cout << " Point[" << i << "]:" << std::endl;
std::cout << " Coordinates: (" << point.mX << "," << point.mY << "," << point.mZ << ")" << std::endl;
std::cout << " Auto-Generated: " << (int)point.mAutogenerated << std::endl;
std::cout << " Connections: " << (int)point.mConnectionNum << std::endl;
i++;
}
i = 0;
for (const ESM::Pathgrid::Edge& edge : mData.mEdges)
{
std::cout << " Edge[" << i << "]: " << edge.mV0 << " -> " << edge.mV1 << std::endl;
if (edge.mV0 >= mData.mData.mPoints || edge.mV1 >= mData.mData.mPoints)
std::cout << " BAD POINT IN EDGE!" << std::endl;
i++;
}
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Race>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Description: " << mData.mDescription << std::endl;
std::cout << " Flags: " << raceFlags(mData.mData.mFlags) << std::endl;
std::cout << " Male:" << std::endl;
for (int j = 0; j < ESM::Attribute::Length; ++j)
{
ESM::RefId id = ESM::Attribute::indexToRefId(j);
std::cout << " " << id << ": " << mData.mData.getAttribute(id, true) << std::endl;
}
std::cout << " Height: " << mData.mData.mMaleHeight << std::endl;
std::cout << " Weight: " << mData.mData.mMaleWeight << std::endl;
std::cout << " Female:" << std::endl;
for (int j = 0; j < ESM::Attribute::Length; ++j)
{
ESM::RefId id = ESM::Attribute::indexToRefId(j);
std::cout << " " << id << ": " << mData.mData.getAttribute(id, false) << std::endl;
}
std::cout << " Height: " << mData.mData.mFemaleHeight << std::endl;
std::cout << " Weight: " << mData.mData.mFemaleWeight << std::endl;
for (const auto& bonus : mData.mData.mBonus)
// Not all races have 7 skills.
if (bonus.mSkill != -1)
std::cout << " Skill: " << skillLabel(bonus.mSkill) << " (" << bonus.mSkill << ") = " << bonus.mBonus
<< std::endl;
for (const auto& power : mData.mPowers.mList)
std::cout << " Power: " << power << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Region>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Weather:" << std::endl;
std::array<std::string_view, 10> weathers
= { "Clear", "Cloudy", "Fog", "Overcast", "Rain", "Thunder", "Ash", "Blight", "Snow", "Blizzard" };
for (size_t i = 0; i < weathers.size(); ++i)
std::cout << " " << weathers[i] << ": " << static_cast<unsigned>(mData.mData.mProbabilities[i])
<< std::endl;
std::cout << " Map Color: " << mData.mMapColor << std::endl;
if (!mData.mSleepList.empty())
std::cout << " Sleep List: " << mData.mSleepList << std::endl;
for (const ESM::Region::SoundRef& soundref : mData.mSoundList)
std::cout << " Sound: " << (int)soundref.mChance << " = " << soundref.mSound << std::endl;
}
template <>
void Record<ESM::Script>::print()
{
std::cout << " Name: " << mData.mId << std::endl;
std::cout << " Num Shorts: " << mData.mNumShorts << std::endl;
std::cout << " Num Longs: " << mData.mNumLongs << std::endl;
std::cout << " Num Floats: " << mData.mNumFloats << std::endl;
std::cout << " Script Data Size: " << mData.mScriptData.size() << std::endl;
std::cout << " Table Size: " << ESM::computeScriptStringTableSize(mData.mVarNames) << std::endl;
for (const std::string& variable : mData.mVarNames)
std::cout << " Variable: " << variable << std::endl;
std::cout << " ByteCode: ";
for (const unsigned char& byte : mData.mScriptData)
std::cout << Misc::StringUtils::format("%02X", (int)(byte));
std::cout << std::endl;
if (mPrintPlain)
{
std::cout << " Script:" << std::endl;
std::cout << "START--------------------------------------" << std::endl;
std::cout << mData.mScriptText << std::endl;
std::cout << "END----------------------------------------" << std::endl;
}
else
{
std::cout << " Script: [skipped]" << std::endl;
}
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Skill>::print()
{
int index = ESM::Skill::refIdToIndex(mData.mId);
std::cout << " ID: " << skillLabel(index) << " (" << index << ")" << std::endl;
std::cout << " Description: " << mData.mDescription << std::endl;
std::cout << " Governing Attribute: " << attributeLabel(mData.mData.mAttribute) << " ("
<< mData.mData.mAttribute << ")" << std::endl;
std::cout << " Specialization: " << specializationLabel(mData.mData.mSpecialization) << " ("
<< mData.mData.mSpecialization << ")" << std::endl;
for (int i = 0; i != 4; i++)
std::cout << " UseValue[" << i << "]:" << mData.mData.mUseValue[i] << std::endl;
}
template <>
void Record<ESM::SoundGenerator>::print()
{
if (!mData.mCreature.empty())
std::cout << " Creature: " << mData.mCreature << std::endl;
std::cout << " Sound: " << mData.mSound << std::endl;
std::cout << " Type: " << soundTypeLabel(mData.mType) << " (" << mData.mType << ")" << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Sound>::print()
{
std::cout << " Sound: " << mData.mSound << std::endl;
std::cout << " Volume: " << (int)mData.mData.mVolume << std::endl;
if (mData.mData.mMinRange != 0 && mData.mData.mMaxRange != 0)
std::cout << " Range: " << (int)mData.mData.mMinRange << " - " << (int)mData.mData.mMaxRange << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Spell>::print()
{
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Type: " << spellTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl;
std::cout << " Flags: " << spellFlags(mData.mData.mFlags) << std::endl;
std::cout << " Cost: " << mData.mData.mCost << std::endl;
printEffectList(mData.mEffects);
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::StartScript>::print()
{
std::cout << " Start Script: " << mData.mId << std::endl;
std::cout << " Start Data: " << mData.mData << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<ESM::Static>::print()
{
std::cout << " Model: " << mData.mModel << std::endl;
}
template <>
void Record<ESM::Weapon>::print()
{
// No names on VFX bolts
if (!mData.mName.empty())
std::cout << " Name: " << mData.mName << std::endl;
std::cout << " Model: " << mData.mModel << std::endl;
// No icons on VFX bolts or magic bolts
if (!mData.mIcon.empty())
std::cout << " Icon: " << mData.mIcon << std::endl;
if (!mData.mScript.empty())
std::cout << " Script: " << mData.mScript << std::endl;
if (!mData.mEnchant.empty())
std::cout << " Enchantment: " << mData.mEnchant << std::endl;
std::cout << " Type: " << weaponTypeLabel(mData.mData.mType) << " (" << mData.mData.mType << ")" << std::endl;
std::cout << " Flags: " << weaponFlags(mData.mData.mFlags) << std::endl;
std::cout << " Weight: " << mData.mData.mWeight << std::endl;
std::cout << " Value: " << mData.mData.mValue << std::endl;
std::cout << " Health: " << mData.mData.mHealth << std::endl;
std::cout << " Speed: " << mData.mData.mSpeed << std::endl;
std::cout << " Reach: " << mData.mData.mReach << std::endl;
std::cout << " Enchantment Points: " << mData.mData.mEnchant << std::endl;
if (mData.mData.mChop[0] != 0 && mData.mData.mChop[1] != 0)
std::cout << " Chop: " << (int)mData.mData.mChop[0] << "-" << (int)mData.mData.mChop[1] << std::endl;
if (mData.mData.mSlash[0] != 0 && mData.mData.mSlash[1] != 0)
std::cout << " Slash: " << (int)mData.mData.mSlash[0] << "-" << (int)mData.mData.mSlash[1] << std::endl;
if (mData.mData.mThrust[0] != 0 && mData.mData.mThrust[1] != 0)
std::cout << " Thrust: " << (int)mData.mData.mThrust[0] << "-" << (int)mData.mData.mThrust[1] << std::endl;
std::cout << " Deleted: " << mIsDeleted << std::endl;
}
template <>
void Record<CellState>::print()
{
std::cout << " Cell Id: \"" << mData.mCellState.mId.toString() << "\"" << std::endl;
std::cout << " Water Level: " << mData.mCellState.mWaterLevel << std::endl;
std::cout << " Has Fog Of War: " << mData.mCellState.mHasFogOfWar << std::endl;
std::cout << " Last Respawn:" << std::endl;
std::cout << " Day:" << mData.mCellState.mLastRespawn.mDay << std::endl;
std::cout << " Hour:" << mData.mCellState.mLastRespawn.mHour << std::endl;
if (mData.mCellState.mHasFogOfWar)
{
std::cout << " North Marker Angle: " << mData.mFogState.mNorthMarkerAngle << std::endl;
std::cout << " Bounds:" << std::endl;
std::cout << " Min X: " << mData.mFogState.mBounds.mMinX << std::endl;
std::cout << " Min Y: " << mData.mFogState.mBounds.mMinY << std::endl;
std::cout << " Max X: " << mData.mFogState.mBounds.mMaxX << std::endl;
std::cout << " Max Y: " << mData.mFogState.mBounds.mMaxY << std::endl;
for (const ESM::FogTexture& fogTexture : mData.mFogState.mFogTextures)
{
std::cout << " Fog Texture:" << std::endl;
std::cout << " X: " << fogTexture.mX << std::endl;
std::cout << " Y: " << fogTexture.mY << std::endl;
std::cout << " Image Data: (" << fogTexture.mImageData.size() << ")" << std::endl;
}
}
}
template <>
std::string Record<ESM::Cell>::getId() const
{
return std::string(); // No ID for Cell record
}
template <>
std::string Record<ESM::Land>::getId() const
{
return std::string(); // No ID for Land record
}
template <>
std::string Record<ESM::MagicEffect>::getId() const
{
return std::string(); // No ID for MagicEffect record
}
template <>
std::string Record<ESM::Pathgrid>::getId() const
{
return std::string(); // No ID for Pathgrid record
}
template <>
std::string Record<ESM::Skill>::getId() const
{
return std::string(); // No ID for Skill record
}
template <>
std::string Record<CellState>::getId() const
{
return std::string(); // No ID for CellState record
}
} // end namespace
| 60,164
|
C++
|
.cpp
| 1,262
| 36.840729
| 120
| 0.493035
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,182
|
tes4.cpp
|
OpenMW_openmw/apps/esmtool/tes4.cpp
|
#include "tes4.hpp"
#include "arguments.hpp"
#include "labels.hpp"
#include <array>
#include <fstream>
#include <iostream>
#include <type_traits>
#include <components/debug/writeflags.hpp>
#include <components/esm/esmcommon.hpp>
#include <components/esm/refid.hpp>
#include <components/esm/typetraits.hpp>
#include <components/esm4/reader.hpp>
#include <components/esm4/readerutils.hpp>
#include <components/esm4/records.hpp>
#include <components/esm4/typetraits.hpp>
#include <components/to_utf8/to_utf8.hpp>
namespace EsmTool
{
namespace
{
struct Params
{
const bool mQuite;
explicit Params(const Arguments& info)
: mQuite(info.quiet_given || info.mode == "clone")
{
}
};
std::string toString(ESM4::GroupType type)
{
switch (type)
{
case ESM4::Grp_RecordType:
return "RecordType";
case ESM4::Grp_WorldChild:
return "WorldChild";
case ESM4::Grp_InteriorCell:
return "InteriorCell";
case ESM4::Grp_InteriorSubCell:
return "InteriorSubCell";
case ESM4::Grp_ExteriorCell:
return "ExteriorCell";
case ESM4::Grp_ExteriorSubCell:
return "ExteriorSubCell";
case ESM4::Grp_CellChild:
return "CellChild";
case ESM4::Grp_TopicChild:
return "TopicChild";
case ESM4::Grp_CellPersistentChild:
return "CellPersistentChild";
case ESM4::Grp_CellTemporaryChild:
return "CellTemporaryChild";
case ESM4::Grp_CellVisibleDistChild:
return "CellVisibleDistChild";
}
return "Unknown (" + std::to_string(type) + ")";
}
template <class T>
struct WriteArray
{
std::string_view mPrefix;
const T& mValue;
explicit WriteArray(std::string_view prefix, const T& value)
: mPrefix(prefix)
, mValue(value)
{
}
};
template <class T>
struct WriteData
{
const T& mValue;
explicit WriteData(const T& value)
: mValue(value)
{
}
};
template <class T>
std::ostream& operator<<(std::ostream& stream, const WriteArray<T>& write)
{
for (const auto& value : write.mValue)
stream << write.mPrefix << value;
return stream;
}
template <class T>
std::ostream& operator<<(std::ostream& stream, const WriteData<T>& /*write*/)
{
return stream << " ?";
}
std::ostream& operator<<(std::ostream& stream, const std::monostate&)
{
return stream << "[none]";
}
std::ostream& operator<<(std::ostream& stream, const WriteData<ESM4::GameSetting::Data>& write)
{
std::visit([&](const auto& v) { stream << v; }, write.mValue);
return stream;
}
struct WriteCellFlags
{
std::uint16_t mValue;
};
using CellFlagString = Debug::FlagString<std::uint16_t>;
constexpr std::array cellFlags{
CellFlagString{ ESM4::CELL_Interior, "Interior" },
CellFlagString{ ESM4::CELL_HasWater, "HasWater" },
CellFlagString{ ESM4::CELL_NoTravel, "NoTravel" },
CellFlagString{ ESM4::CELL_HideLand, "HideLand" },
CellFlagString{ ESM4::CELL_Public, "Public" },
CellFlagString{ ESM4::CELL_HandChgd, "HandChgd" },
CellFlagString{ ESM4::CELL_QuasiExt, "QuasiExt" },
CellFlagString{ ESM4::CELL_SkyLight, "SkyLight" },
};
std::ostream& operator<<(std::ostream& stream, const WriteCellFlags& write)
{
return Debug::writeFlags(stream, write.mValue, cellFlags);
}
template <class T>
void readTypedRecord(const Params& params, ESM4::Reader& reader)
{
reader.getRecordData();
T value;
value.load(reader);
if (params.mQuite)
return;
std::cout << "\n Record: " << ESM::NAME(reader.hdr().record.typeId).toStringView();
if constexpr (ESM::hasId<T>)
std::cout << "\n Id: " << value.mId;
if constexpr (ESM4::hasFlags<T>)
std::cout << "\n Record flags: " << recordFlags(value.mFlags);
if constexpr (ESM4::hasParent<T>)
std::cout << "\n Parent: " << value.mParent;
if constexpr (ESM4::hasEditorId<T>)
std::cout << "\n EditorId: " << value.mEditorId;
if constexpr (ESM4::hasFullName<T>)
std::cout << "\n FullName: " << value.mFullName;
if constexpr (ESM4::hasCellFlags<T>)
std::cout << "\n CellFlags: " << WriteCellFlags{ value.mCellFlags };
if constexpr (ESM4::hasX<T>)
std::cout << "\n X: " << value.mX;
if constexpr (ESM4::hasY<T>)
std::cout << "\n Y: " << value.mY;
if constexpr (ESM::hasModel<T>)
std::cout << "\n Model: " << value.mModel;
if constexpr (ESM4::hasNif<T>)
std::cout << "\n Nif:" << WriteArray("\n - ", value.mNif);
if constexpr (ESM4::hasKf<T>)
std::cout << "\n Kf:" << WriteArray("\n - ", value.mKf);
if constexpr (ESM4::hasType<T>)
std::cout << "\n Type: " << value.mType;
if constexpr (ESM4::hasValue<T>)
std::cout << "\n Value: " << value.mValue;
if constexpr (ESM4::hasData<T>)
std::cout << "\n Data: " << WriteData(value.mData);
std::cout << '\n';
}
bool readRecord(const Params& params, ESM4::Reader& reader)
{
switch (static_cast<ESM4::RecordTypes>(reader.hdr().record.typeId))
{
case ESM4::REC_AACT:
break;
case ESM4::REC_ACHR:
readTypedRecord<ESM4::ActorCharacter>(params, reader);
return true;
case ESM4::REC_ACRE:
readTypedRecord<ESM4::ActorCreature>(params, reader);
return true;
case ESM4::REC_ACTI:
readTypedRecord<ESM4::Activator>(params, reader);
return true;
case ESM4::REC_ADDN:
break;
case ESM4::REC_ALCH:
readTypedRecord<ESM4::Potion>(params, reader);
return true;
case ESM4::REC_ALOC:
readTypedRecord<ESM4::MediaLocationController>(params, reader);
return true;
case ESM4::REC_AMMO:
readTypedRecord<ESM4::Ammunition>(params, reader);
return true;
case ESM4::REC_ANIO:
readTypedRecord<ESM4::AnimObject>(params, reader);
return true;
case ESM4::REC_APPA:
readTypedRecord<ESM4::Apparatus>(params, reader);
return true;
case ESM4::REC_ARMA:
readTypedRecord<ESM4::ArmorAddon>(params, reader);
return true;
case ESM4::REC_ARMO:
readTypedRecord<ESM4::Armor>(params, reader);
return true;
case ESM4::REC_ARTO:
break;
case ESM4::REC_ASPC:
readTypedRecord<ESM4::AcousticSpace>(params, reader);
return true;
case ESM4::REC_ASTP:
break;
case ESM4::REC_AVIF:
break;
case ESM4::REC_BOOK:
readTypedRecord<ESM4::Book>(params, reader);
return true;
case ESM4::REC_BPTD:
readTypedRecord<ESM4::BodyPartData>(params, reader);
return true;
case ESM4::REC_CAMS:
break;
case ESM4::REC_CCRD:
break;
case ESM4::REC_CELL:
readTypedRecord<ESM4::Cell>(params, reader);
return true;
case ESM4::REC_CLAS:
readTypedRecord<ESM4::Class>(params, reader);
return true;
case ESM4::REC_CLFM:
readTypedRecord<ESM4::Colour>(params, reader);
return true;
case ESM4::REC_CLMT:
break;
case ESM4::REC_CLOT:
readTypedRecord<ESM4::Clothing>(params, reader);
return true;
case ESM4::REC_CMNY:
break;
case ESM4::REC_COBJ:
break;
case ESM4::REC_COLL:
break;
case ESM4::REC_CONT:
readTypedRecord<ESM4::Container>(params, reader);
return true;
case ESM4::REC_CPTH:
break;
case ESM4::REC_CREA:
readTypedRecord<ESM4::Creature>(params, reader);
return true;
case ESM4::REC_CSTY:
break;
case ESM4::REC_DEBR:
break;
case ESM4::REC_DIAL:
readTypedRecord<ESM4::Dialogue>(params, reader);
return true;
case ESM4::REC_DLBR:
break;
case ESM4::REC_DLVW:
break;
case ESM4::REC_DOBJ:
readTypedRecord<ESM4::DefaultObj>(params, reader);
return true;
case ESM4::REC_DOOR:
readTypedRecord<ESM4::Door>(params, reader);
return true;
case ESM4::REC_DUAL:
break;
case ESM4::REC_ECZN:
break;
case ESM4::REC_EFSH:
break;
case ESM4::REC_ENCH:
break;
case ESM4::REC_EQUP:
break;
case ESM4::REC_EXPL:
break;
case ESM4::REC_EYES:
readTypedRecord<ESM4::Eyes>(params, reader);
return true;
case ESM4::REC_FACT:
break;
case ESM4::REC_FLOR:
readTypedRecord<ESM4::Flora>(params, reader);
return true;
case ESM4::REC_FLST:
readTypedRecord<ESM4::FormIdList>(params, reader);
return true;
case ESM4::REC_FSTP:
break;
case ESM4::REC_FSTS:
break;
case ESM4::REC_FURN:
readTypedRecord<ESM4::Furniture>(params, reader);
return true;
case ESM4::REC_GLOB:
readTypedRecord<ESM4::GlobalVariable>(params, reader);
return true;
case ESM4::REC_GMST:
readTypedRecord<ESM4::GameSetting>(params, reader);
return true;
case ESM4::REC_GRAS:
readTypedRecord<ESM4::Grass>(params, reader);
return true;
case ESM4::REC_GRUP:
break;
case ESM4::REC_HAIR:
readTypedRecord<ESM4::Hair>(params, reader);
return true;
case ESM4::REC_HAZD:
break;
case ESM4::REC_HDPT:
readTypedRecord<ESM4::HeadPart>(params, reader);
return true;
case ESM4::REC_IDLE:
readTypedRecord<ESM4::IdleAnimation>(params, reader);
return true;
break;
case ESM4::REC_IDLM:
readTypedRecord<ESM4::IdleMarker>(params, reader);
return true;
case ESM4::REC_IMAD:
break;
case ESM4::REC_IMGS:
break;
case ESM4::REC_IMOD:
readTypedRecord<ESM4::ItemMod>(params, reader);
return true;
case ESM4::REC_INFO:
readTypedRecord<ESM4::DialogInfo>(params, reader);
return true;
case ESM4::REC_INGR:
readTypedRecord<ESM4::Ingredient>(params, reader);
return true;
case ESM4::REC_IPCT:
break;
case ESM4::REC_IPDS:
break;
case ESM4::REC_KEYM:
readTypedRecord<ESM4::Key>(params, reader);
return true;
case ESM4::REC_KYWD:
break;
case ESM4::REC_LAND:
readTypedRecord<ESM4::Land>(params, reader);
return true;
case ESM4::REC_LCRT:
break;
case ESM4::REC_LCTN:
break;
case ESM4::REC_LGTM:
readTypedRecord<ESM4::LightingTemplate>(params, reader);
return true;
case ESM4::REC_LIGH:
readTypedRecord<ESM4::Light>(params, reader);
return true;
case ESM4::REC_LSCR:
break;
case ESM4::REC_LTEX:
readTypedRecord<ESM4::LandTexture>(params, reader);
return true;
case ESM4::REC_LVLC:
readTypedRecord<ESM4::LevelledCreature>(params, reader);
return true;
case ESM4::REC_LVLI:
readTypedRecord<ESM4::LevelledItem>(params, reader);
return true;
case ESM4::REC_LVLN:
readTypedRecord<ESM4::LevelledNpc>(params, reader);
return true;
case ESM4::REC_LVSP:
break;
case ESM4::REC_MATO:
readTypedRecord<ESM4::Material>(params, reader);
return true;
case ESM4::REC_MATT:
break;
case ESM4::REC_MESG:
break;
case ESM4::REC_MGEF:
break;
case ESM4::REC_MISC:
readTypedRecord<ESM4::MiscItem>(params, reader);
return true;
case ESM4::REC_MOVT:
break;
case ESM4::REC_MSET:
readTypedRecord<ESM4::MediaSet>(params, reader);
return true;
case ESM4::REC_MSTT:
readTypedRecord<ESM4::MovableStatic>(params, reader);
return true;
case ESM4::REC_MUSC:
readTypedRecord<ESM4::Music>(params, reader);
return true;
case ESM4::REC_MUST:
break;
case ESM4::REC_NAVI:
readTypedRecord<ESM4::Navigation>(params, reader);
return true;
case ESM4::REC_NAVM:
readTypedRecord<ESM4::NavMesh>(params, reader);
return true;
case ESM4::REC_NOTE:
readTypedRecord<ESM4::Note>(params, reader);
return true;
case ESM4::REC_NPC_:
readTypedRecord<ESM4::Npc>(params, reader);
return true;
case ESM4::REC_OTFT:
readTypedRecord<ESM4::Outfit>(params, reader);
return true;
case ESM4::REC_PACK:
readTypedRecord<ESM4::AIPackage>(params, reader);
return true;
case ESM4::REC_PERK:
break;
case ESM4::REC_PGRD:
readTypedRecord<ESM4::Pathgrid>(params, reader);
return true;
case ESM4::REC_PGRE:
readTypedRecord<ESM4::PlacedGrenade>(params, reader);
return true;
case ESM4::REC_PHZD:
break;
case ESM4::REC_PROJ:
break;
case ESM4::REC_PWAT:
readTypedRecord<ESM4::PlaceableWater>(params, reader);
return true;
case ESM4::REC_QUST:
readTypedRecord<ESM4::Quest>(params, reader);
return true;
case ESM4::REC_RACE:
readTypedRecord<ESM4::Race>(params, reader);
return true;
case ESM4::REC_REFR:
readTypedRecord<ESM4::Reference>(params, reader);
return true;
case ESM4::REC_REGN:
readTypedRecord<ESM4::Region>(params, reader);
return true;
case ESM4::REC_RELA:
break;
case ESM4::REC_REVB:
break;
case ESM4::REC_RFCT:
break;
case ESM4::REC_ROAD:
readTypedRecord<ESM4::Road>(params, reader);
return true;
case ESM4::REC_SBSP:
readTypedRecord<ESM4::SubSpace>(params, reader);
return true;
case ESM4::REC_SCEN:
break;
case ESM4::REC_SCOL:
readTypedRecord<ESM4::StaticCollection>(params, reader);
return true;
case ESM4::REC_SCPT:
readTypedRecord<ESM4::Script>(params, reader);
return true;
case ESM4::REC_SCRL:
readTypedRecord<ESM4::Scroll>(params, reader);
return true;
case ESM4::REC_SGST:
readTypedRecord<ESM4::SigilStone>(params, reader);
return true;
case ESM4::REC_SHOU:
break;
case ESM4::REC_SLGM:
readTypedRecord<ESM4::SoulGem>(params, reader);
return true;
case ESM4::REC_SMBN:
break;
case ESM4::REC_SMEN:
break;
case ESM4::REC_SMQN:
break;
case ESM4::REC_SNCT:
break;
case ESM4::REC_SNDR:
readTypedRecord<ESM4::SoundReference>(params, reader);
return true;
case ESM4::REC_SOPM:
break;
case ESM4::REC_SOUN:
readTypedRecord<ESM4::Sound>(params, reader);
return true;
case ESM4::REC_SPEL:
break;
case ESM4::REC_SPGD:
break;
case ESM4::REC_STAT:
readTypedRecord<ESM4::Static>(params, reader);
return true;
case ESM4::REC_TACT:
readTypedRecord<ESM4::TalkingActivator>(params, reader);
return true;
case ESM4::REC_TERM:
readTypedRecord<ESM4::Terminal>(params, reader);
return true;
case ESM4::REC_TES4:
readTypedRecord<ESM4::Header>(params, reader);
return true;
case ESM4::REC_TREE:
readTypedRecord<ESM4::Tree>(params, reader);
return true;
case ESM4::REC_TXST:
readTypedRecord<ESM4::TextureSet>(params, reader);
return true;
case ESM4::REC_VTYP:
break;
case ESM4::REC_WATR:
break;
case ESM4::REC_WEAP:
readTypedRecord<ESM4::Weapon>(params, reader);
return true;
case ESM4::REC_WOOP:
break;
case ESM4::REC_WRLD:
readTypedRecord<ESM4::World>(params, reader);
return true;
case ESM4::REC_WTHR:
break;
}
if (!params.mQuite)
std::cout << "\n Unsupported record: " << ESM::NAME(reader.hdr().record.typeId).toStringView() << '\n';
return false;
}
}
int loadTes4(const Arguments& info, std::unique_ptr<std::ifstream>&& stream)
{
std::cout << "Loading TES4 file: " << info.filename << '\n';
try
{
const ToUTF8::StatelessUtf8Encoder encoder(ToUTF8::calculateEncoding(info.encoding));
ESM4::Reader reader(std::move(stream), info.filename, nullptr, &encoder, true);
const Params params(info);
if (!params.mQuite)
{
std::cout << "Author: " << reader.getAuthor() << '\n'
<< "Description: " << reader.getDesc() << '\n'
<< "File format version: " << reader.esmVersionF() << '\n';
if (const std::vector<ESM::MasterData>& masterData = reader.getGameFiles(); !masterData.empty())
{
std::cout << "Masters:" << '\n';
for (const auto& master : masterData)
std::cout << " " << master.name << ", " << master.size << " bytes\n";
}
}
auto visitorRec = [¶ms](ESM4::Reader& reader) { return readRecord(params, reader); };
auto visitorGroup = [¶ms](ESM4::Reader& reader) {
if (params.mQuite)
return;
auto groupType = static_cast<ESM4::GroupType>(reader.hdr().group.type);
std::cout << "\nGroup: " << toString(groupType) << " "
<< ESM::NAME(reader.hdr().group.typeId).toStringView() << '\n';
};
ESM4::ReaderUtils::readAll(reader, visitorRec, visitorGroup);
}
catch (const std::exception& e)
{
std::cout << "\nERROR:\n\n " << e.what() << std::endl;
return -1;
}
return 0;
}
}
| 23,182
|
C++
|
.cpp
| 562
| 24.375445
| 120
| 0.46257
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,183
|
labels.cpp
|
OpenMW_openmw/apps/esmtool/labels.cpp
|
#include "labels.hpp"
#include <components/esm3/dialoguecondition.hpp>
#include <components/esm3/loadalch.hpp>
#include <components/esm3/loadbody.hpp>
#include <components/esm3/loadcell.hpp>
#include <components/esm3/loadcont.hpp>
#include <components/esm3/loadcrea.hpp>
#include <components/esm3/loadench.hpp>
#include <components/esm3/loadland.hpp>
#include <components/esm3/loadlevlist.hpp>
#include <components/esm3/loadligh.hpp>
#include <components/esm3/loadmgef.hpp>
#include <components/esm3/loadnpc.hpp>
#include <components/esm3/loadrace.hpp>
#include <components/esm3/loadspel.hpp>
#include <components/esm3/loadweap.hpp>
#include <components/misc/strings/format.hpp>
std::string_view bodyPartLabel(int idx)
{
if (idx >= 0 && idx <= 26)
{
static constexpr std::string_view bodyPartLabels[] = {
"Head",
"Hair",
"Neck",
"Cuirass",
"Groin",
"Skirt",
"Right Hand",
"Left Hand",
"Right Wrist",
"Left Wrist",
"Shield",
"Right Forearm",
"Left Forearm",
"Right Upperarm",
"Left Upperarm",
"Right Foot",
"Left Foot",
"Right Ankle",
"Left Ankle",
"Right Knee",
"Left Knee",
"Right Leg",
"Left Leg",
"Right Shoulder",
"Left Shoulder",
"Weapon",
"Tail",
};
return bodyPartLabels[idx];
}
else
return "Invalid";
}
std::string_view meshPartLabel(int idx)
{
if (idx >= 0 && idx <= ESM::BodyPart::MP_Tail)
{
static constexpr std::string_view meshPartLabels[] = {
"Head",
"Hair",
"Neck",
"Chest",
"Groin",
"Hand",
"Wrist",
"Forearm",
"Upperarm",
"Foot",
"Ankle",
"Knee",
"Upper Leg",
"Clavicle",
"Tail",
};
return meshPartLabels[idx];
}
else
return "Invalid";
}
std::string_view meshTypeLabel(int idx)
{
if (idx >= 0 && idx <= ESM::BodyPart::MT_Armor)
{
static constexpr std::string_view meshTypeLabels[] = {
"Skin",
"Clothing",
"Armor",
};
return meshTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view clothingTypeLabel(int idx)
{
if (idx >= 0 && idx <= 9)
{
static constexpr std::string_view clothingTypeLabels[] = {
"Pants",
"Shoes",
"Shirt",
"Belt",
"Robe",
"Right Glove",
"Left Glove",
"Skirt",
"Ring",
"Amulet",
};
return clothingTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view armorTypeLabel(int idx)
{
if (idx >= 0 && idx <= 10)
{
static constexpr std::string_view armorTypeLabels[] = {
"Helmet",
"Cuirass",
"Left Pauldron",
"Right Pauldron",
"Greaves",
"Boots",
"Left Gauntlet",
"Right Gauntlet",
"Shield",
"Left Bracer",
"Right Bracer",
};
return armorTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view dialogTypeLabel(int idx)
{
if (idx >= 0 && idx <= 4)
{
static constexpr std::string_view dialogTypeLabels[] = {
"Topic",
"Voice",
"Greeting",
"Persuasion",
"Journal",
};
return dialogTypeLabels[idx];
}
else if (idx == -1)
return "Deleted";
else
return "Invalid";
}
std::string_view questStatusLabel(int idx)
{
if (idx >= 0 && idx <= 4)
{
static constexpr std::string_view questStatusLabels[] = {
"None",
"Name",
"Finished",
"Restart",
"Deleted",
};
return questStatusLabels[idx];
}
else
return "Invalid";
}
std::string_view creatureTypeLabel(int idx)
{
if (idx >= 0 && idx <= 3)
{
static constexpr std::string_view creatureTypeLabels[] = {
"Creature",
"Daedra",
"Undead",
"Humanoid",
};
return creatureTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view soundTypeLabel(int idx)
{
if (idx >= 0 && idx <= 7)
{
static constexpr std::string_view soundTypeLabels[] = {
"Left Foot",
"Right Foot",
"Swim Left",
"Swim Right",
"Moan",
"Roar",
"Scream",
"Land",
};
return soundTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view weaponTypeLabel(int idx)
{
if (idx >= 0 && idx <= 13)
{
static constexpr std::string_view weaponTypeLabels[] = {
"Short Blade One Hand",
"Long Blade One Hand",
"Long Blade Two Hand",
"Blunt One Hand",
"Blunt Two Close",
"Blunt Two Wide",
"Spear Two Wide",
"Axe One Hand",
"Axe Two Hand",
"Marksman Bow",
"Marksman Crossbow",
"Marksman Thrown",
"Arrow",
"Bolt",
};
return weaponTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view aiTypeLabel(ESM::AiPackageType type)
{
switch (type)
{
case ESM::AI_Wander:
return "Wander";
case ESM::AI_Travel:
return "Travel";
case ESM::AI_Follow:
return "Follow";
case ESM::AI_Escort:
return "Escort";
case ESM::AI_Activate:
return "Activate";
}
return "Invalid";
}
std::string_view magicEffectLabel(int idx)
{
if (idx >= 0 && idx <= 142)
{
static constexpr std::string_view magicEffectLabels[] = {
"Water Breathing",
"Swift Swim",
"Water Walking",
"Shield",
"Fire Shield",
"Lightning Shield",
"Frost Shield",
"Burden",
"Feather",
"Jump",
"Levitate",
"SlowFall",
"Lock",
"Open",
"Fire Damage",
"Shock Damage",
"Frost Damage",
"Drain Attribute",
"Drain Health",
"Drain Magicka",
"Drain Fatigue",
"Drain Skill",
"Damage Attribute",
"Damage Health",
"Damage Magicka",
"Damage Fatigue",
"Damage Skill",
"Poison",
"Weakness to Fire",
"Weakness to Frost",
"Weakness to Shock",
"Weakness to Magicka",
"Weakness to Common Disease",
"Weakness to Blight Disease",
"Weakness to Corprus Disease",
"Weakness to Poison",
"Weakness to Normal Weapons",
"Disintegrate Weapon",
"Disintegrate Armor",
"Invisibility",
"Chameleon",
"Light",
"Sanctuary",
"Night Eye",
"Charm",
"Paralyze",
"Silence",
"Blind",
"Sound",
"Calm Humanoid",
"Calm Creature",
"Frenzy Humanoid",
"Frenzy Creature",
"Demoralize Humanoid",
"Demoralize Creature",
"Rally Humanoid",
"Rally Creature",
"Dispel",
"Soultrap",
"Telekinesis",
"Mark",
"Recall",
"Divine Intervention",
"Almsivi Intervention",
"Detect Animal",
"Detect Enchantment",
"Detect Key",
"Spell Absorption",
"Reflect",
"Cure Common Disease",
"Cure Blight Disease",
"Cure Corprus Disease",
"Cure Poison",
"Cure Paralyzation",
"Restore Attribute",
"Restore Health",
"Restore Magicka",
"Restore Fatigue",
"Restore Skill",
"Fortify Attribute",
"Fortify Health",
"Fortify Magicka",
"Fortify Fatigue",
"Fortify Skill",
"Fortify Maximum Magicka",
"Absorb Attribute",
"Absorb Health",
"Absorb Magicka",
"Absorb Fatigue",
"Absorb Skill",
"Resist Fire",
"Resist Frost",
"Resist Shock",
"Resist Magicka",
"Resist Common Disease",
"Resist Blight Disease",
"Resist Corprus Disease",
"Resist Poison",
"Resist Normal Weapons",
"Resist Paralysis",
"Remove Curse",
"Turn Undead",
"Summon Scamp",
"Summon Clannfear",
"Summon Daedroth",
"Summon Dremora",
"Summon Ancestral Ghost",
"Summon Skeletal Minion",
"Summon Bonewalker",
"Summon Greater Bonewalker",
"Summon Bonelord",
"Summon Winged Twilight",
"Summon Hunger",
"Summon Golden Saint",
"Summon Flame Atronach",
"Summon Frost Atronach",
"Summon Storm Atronach",
"Fortify Attack",
"Command Creature",
"Command Humanoid",
"Bound Dagger",
"Bound Longsword",
"Bound Mace",
"Bound Battle Axe",
"Bound Spear",
"Bound Longbow",
"EXTRA SPELL",
"Bound Cuirass",
"Bound Helm",
"Bound Boots",
"Bound Shield",
"Bound Gloves",
"Corprus",
"Vampirism",
"Summon Centurion Sphere",
"Sun Damage",
"Stunted Magicka",
"Summon Fabricant",
"sEffectSummonCreature01",
"sEffectSummonCreature02",
"sEffectSummonCreature03",
"sEffectSummonCreature04",
"sEffectSummonCreature05",
};
return magicEffectLabels[idx];
}
else
return "Invalid";
}
std::string_view attributeLabel(int idx)
{
if (idx >= 0 && idx <= 7)
{
static constexpr std::string_view attributeLabels[] = {
"Strength",
"Intelligence",
"Willpower",
"Agility",
"Speed",
"Endurance",
"Personality",
"Luck",
};
return attributeLabels[idx];
}
else
return "Invalid";
}
std::string_view spellTypeLabel(int idx)
{
if (idx >= 0 && idx <= 5)
{
static constexpr std::string_view spellTypeLabels[] = {
"Spells",
"Abilities",
"Blight Disease",
"Disease",
"Curse",
"Powers",
};
return spellTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view specializationLabel(int idx)
{
if (idx >= 0 && idx <= 2)
{
static constexpr std::string_view specializationLabels[] = {
"Combat",
"Magic",
"Stealth",
};
return specializationLabels[idx];
}
else
return "Invalid";
}
std::string_view skillLabel(int idx)
{
if (idx >= 0 && idx <= 26)
{
static constexpr std::string_view skillLabels[] = {
"Block",
"Armorer",
"Medium Armor",
"Heavy Armor",
"Blunt Weapon",
"Long Blade",
"Axe",
"Spear",
"Athletics",
"Enchant",
"Destruction",
"Alteration",
"Illusion",
"Conjuration",
"Mysticism",
"Restoration",
"Alchemy",
"Unarmored",
"Security",
"Sneak",
"Acrobatics",
"Light Armor",
"Short Blade",
"Marksman",
"Mercantile",
"Speechcraft",
"Hand-to-hand",
};
return skillLabels[idx];
}
else
return "Invalid";
}
std::string_view apparatusTypeLabel(int idx)
{
if (idx >= 0 && idx <= 3)
{
static constexpr std::string_view apparatusTypeLabels[] = {
"Mortar",
"Alembic",
"Calcinator",
"Retort",
};
return apparatusTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view rangeTypeLabel(int idx)
{
if (idx >= 0 && idx <= 2)
{
static constexpr std::string_view rangeTypeLabels[] = {
"Self",
"Touch",
"Target",
};
return rangeTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view schoolLabel(int idx)
{
if (idx >= 0 && idx <= 5)
{
static constexpr std::string_view schoolLabels[] = {
"Alteration",
"Conjuration",
"Destruction",
"Illusion",
"Mysticism",
"Restoration",
};
return schoolLabels[idx];
}
else
return "Invalid";
}
std::string_view enchantTypeLabel(int idx)
{
if (idx >= 0 && idx <= 3)
{
static constexpr std::string_view enchantTypeLabels[] = {
"Cast Once",
"Cast When Strikes",
"Cast When Used",
"Constant Effect",
};
return enchantTypeLabels[idx];
}
else
return "Invalid";
}
std::string_view ruleFunction(int idx)
{
if (idx >= ESM::DialogueCondition::Function_FacReactionLowest
&& idx <= ESM::DialogueCondition::Function_PcWerewolfKills)
{
static constexpr std::string_view ruleFunctions[] = {
"Lowest Faction Reaction",
"Highest Faction Reaction",
"Rank Requirement",
"NPC Reputation",
"Health Percent",
"Player Reputation",
"NPC Level",
"Player Health Percent",
"Player Magicka",
"Player Fatigue",
"Player Attribute Strength",
"Player Skill Block",
"Player Skill Armorer",
"Player Skill Medium Armor",
"Player Skill Heavy Armor",
"Player Skill Blunt Weapon",
"Player Skill Long Blade",
"Player Skill Axe",
"Player Skill Spear",
"Player Skill Athletics",
"Player Skill Enchant",
"Player Skill Destruction",
"Player Skill Alteration",
"Player Skill Illusion",
"Player Skill Conjuration",
"Player Skill Mysticism",
"Player SKill Restoration",
"Player Skill Alchemy",
"Player Skill Unarmored",
"Player Skill Security",
"Player Skill Sneak",
"Player Skill Acrobatics",
"Player Skill Light Armor",
"Player Skill Short Blade",
"Player Skill Marksman",
"Player Skill Mercantile",
"Player Skill Speechcraft",
"Player Skill Hand to Hand",
"Player Gender",
"Player Expelled from Faction",
"Player Diseased (Common)",
"Player Diseased (Blight)",
"Player Clothing Modifier",
"Player Crime Level",
"Player Same Sex",
"Player Same Race",
"Player Same Faction",
"Faction Rank Difference",
"Player Detected",
"Alarmed",
"Choice Selected",
"Player Attribute Intelligence",
"Player Attribute Willpower",
"Player Attribute Agility",
"Player Attribute Speed",
"Player Attribute Endurance",
"Player Attribute Personality",
"Player Attribute Luck",
"Player Diseased (Corprus)",
"Weather",
"Player is a Vampire",
"Player Level",
"Attacked",
"NPC Talked to Player",
"Player Health",
"Creature Target",
"Friend Hit",
"Fight",
"Hello",
"Alarm",
"Flee",
"Should Attack",
"Werewolf",
"Werewolf Kills",
};
return ruleFunctions[idx];
}
else
return "Invalid";
}
// The "unused flag bits" should probably be defined alongside the
// defined bits in the ESM component. The names of the flag bits are
// very inconsistent.
std::string bodyPartFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::BodyPart::BPF_Female)
properties += "Female ";
if (flags & ESM::BodyPart::BPF_NotPlayable)
properties += "NotPlayable ";
int unused = (0xFFFFFFFF ^ (ESM::BodyPart::BPF_Female | ESM::BodyPart::BPF_NotPlayable));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string cellFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::Cell::HasWater)
properties += "HasWater ";
if (flags & ESM::Cell::Interior)
properties += "Interior ";
if (flags & ESM::Cell::NoSleep)
properties += "NoSleep ";
if (flags & ESM::Cell::QuasiEx)
properties += "QuasiEx ";
// This used value is not in the ESM component.
if (flags & 0x00000040)
properties += "Unknown ";
int unused = (0xFFFFFFFF
^ (ESM::Cell::HasWater | ESM::Cell::Interior | ESM::Cell::NoSleep | ESM::Cell::QuasiEx | 0x00000040));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string containerFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::Container::Unknown)
properties += "Unknown ";
if (flags & ESM::Container::Organic)
properties += "Organic ";
if (flags & ESM::Container::Respawn)
properties += "Respawn ";
int unused = (0xFFFFFFFF ^ (ESM::Container::Unknown | ESM::Container::Organic | ESM::Container::Respawn));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string creatureFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::Creature::Base)
properties += "Base ";
if (flags & ESM::Creature::Walks)
properties += "Walks ";
if (flags & ESM::Creature::Swims)
properties += "Swims ";
if (flags & ESM::Creature::Flies)
properties += "Flies ";
if (flags & ESM::Creature::Bipedal)
properties += "Bipedal ";
if (flags & ESM::Creature::Respawn)
properties += "Respawn ";
if (flags & ESM::Creature::Weapon)
properties += "Weapon ";
if (flags & ESM::Creature::Essential)
properties += "Essential ";
int unused = (0xFFFFFFFF
^ (ESM::Creature::Base | ESM::Creature::Walks | ESM::Creature::Swims | ESM::Creature::Flies
| ESM::Creature::Bipedal | ESM::Creature::Respawn | ESM::Creature::Weapon | ESM::Creature::Essential));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%02X)", flags);
return properties;
}
std::string enchantmentFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::Enchantment::Autocalc)
properties += "Autocalc ";
if (flags & (0xFFFFFFFF ^ ESM::Enchantment::Autocalc))
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string landFlags(std::uint32_t flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::Land::Flag_HeightsNormals)
properties += "HeightsNormals ";
if (flags & ESM::Land::Flag_Colors)
properties += "Colors ";
if (flags & ESM::Land::Flag_Textures)
properties += "Textures ";
int unused = 0xFFFFFFFF ^ (ESM::Land::Flag_HeightsNormals | ESM::Land::Flag_Colors | ESM::Land::Flag_Textures);
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string itemListFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::ItemLevList::AllLevels)
properties += "AllLevels ";
if (flags & ESM::ItemLevList::Each)
properties += "Each ";
int unused = (0xFFFFFFFF ^ (ESM::ItemLevList::AllLevels | ESM::ItemLevList::Each));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string creatureListFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::CreatureLevList::AllLevels)
properties += "AllLevels ";
int unused = (0xFFFFFFFF ^ ESM::CreatureLevList::AllLevels);
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string lightFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::Light::Dynamic)
properties += "Dynamic ";
if (flags & ESM::Light::Fire)
properties += "Fire ";
if (flags & ESM::Light::Carry)
properties += "Carry ";
if (flags & ESM::Light::Flicker)
properties += "Flicker ";
if (flags & ESM::Light::FlickerSlow)
properties += "FlickerSlow ";
if (flags & ESM::Light::Pulse)
properties += "Pulse ";
if (flags & ESM::Light::PulseSlow)
properties += "PulseSlow ";
if (flags & ESM::Light::Negative)
properties += "Negative ";
if (flags & ESM::Light::OffDefault)
properties += "OffDefault ";
int unused = (0xFFFFFFFF
^ (ESM::Light::Dynamic | ESM::Light::Fire | ESM::Light::Carry | ESM::Light::Flicker | ESM::Light::FlickerSlow
| ESM::Light::Pulse | ESM::Light::PulseSlow | ESM::Light::Negative | ESM::Light::OffDefault));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string magicEffectFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::MagicEffect::TargetAttribute)
properties += "TargetAttribute ";
if (flags & ESM::MagicEffect::TargetSkill)
properties += "TargetSkill ";
if (flags & ESM::MagicEffect::NoDuration)
properties += "NoDuration ";
if (flags & ESM::MagicEffect::NoMagnitude)
properties += "NoMagnitude ";
if (flags & ESM::MagicEffect::Harmful)
properties += "Harmful ";
if (flags & ESM::MagicEffect::ContinuousVfx)
properties += "ContinuousVFX ";
if (flags & ESM::MagicEffect::CastSelf)
properties += "CastSelf ";
if (flags & ESM::MagicEffect::CastTouch)
properties += "CastTouch ";
if (flags & ESM::MagicEffect::CastTarget)
properties += "CastTarget ";
if (flags & ESM::MagicEffect::AppliedOnce)
properties += "AppliedOnce ";
if (flags & ESM::MagicEffect::Stealth)
properties += "Stealth ";
if (flags & ESM::MagicEffect::NonRecastable)
properties += "NonRecastable ";
if (flags & ESM::MagicEffect::IllegalDaedra)
properties += "IllegalDaedra ";
if (flags & ESM::MagicEffect::Unreflectable)
properties += "Unreflectable ";
if (flags & ESM::MagicEffect::CasterLinked)
properties += "CasterLinked ";
if (flags & ESM::MagicEffect::AllowSpellmaking)
properties += "AllowSpellmaking ";
if (flags & ESM::MagicEffect::AllowEnchanting)
properties += "AllowEnchanting ";
if (flags & ESM::MagicEffect::NegativeLight)
properties += "NegativeLight ";
if (flags & 0xFFFC0000)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string npcFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::NPC::Base)
properties += "Base ";
if (flags & ESM::NPC::Autocalc)
properties += "Autocalc ";
if (flags & ESM::NPC::Female)
properties += "Female ";
if (flags & ESM::NPC::Respawn)
properties += "Respawn ";
if (flags & ESM::NPC::Essential)
properties += "Essential ";
// Whether corpses persist is a bit that is unaccounted for,
// however relatively few NPCs have this bit set.
int unused
= (0xFF ^ (ESM::NPC::Base | ESM::NPC::Autocalc | ESM::NPC::Female | ESM::NPC::Respawn | ESM::NPC::Essential));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%02X)", flags);
return properties;
}
std::string raceFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
// All races have the playable flag set in Bethesda files.
if (flags & ESM::Race::Playable)
properties += "Playable ";
if (flags & ESM::Race::Beast)
properties += "Beast ";
int unused = (0xFFFFFFFF ^ (ESM::Race::Playable | ESM::Race::Beast));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string spellFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::Spell::F_Autocalc)
properties += "Autocalc ";
if (flags & ESM::Spell::F_PCStart)
properties += "PCStart ";
if (flags & ESM::Spell::F_Always)
properties += "Always ";
int unused = (0xFFFFFFFF ^ (ESM::Spell::F_Autocalc | ESM::Spell::F_PCStart | ESM::Spell::F_Always));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string weaponFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
// The interpretation of the flags are still unclear to me.
// Apparently you can't be Silver without being Magical? Many of
// the "Magical" weapons don't have enchantments of any sort.
if (flags & ESM::Weapon::Magical)
properties += "Magical ";
if (flags & ESM::Weapon::Silver)
properties += "Silver ";
int unused = (0xFFFFFFFF ^ (ESM::Weapon::Magical | ESM::Weapon::Silver));
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string recordFlags(uint32_t flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::FLAG_Deleted)
properties += "Deleted ";
if (flags & ESM::FLAG_Persistent)
properties += "Persistent ";
if (flags & ESM::FLAG_Ignored)
properties += "Ignored ";
if (flags & ESM::FLAG_Blocked)
properties += "Blocked ";
int unused = ~(ESM::FLAG_Deleted | ESM::FLAG_Persistent | ESM::FLAG_Ignored | ESM::FLAG_Blocked);
if (flags & unused)
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
std::string potionFlags(int flags)
{
std::string properties;
if (flags == 0)
properties += "[None] ";
if (flags & ESM::Potion::Autocalc)
properties += "Autocalc ";
if (flags & (0xFFFFFFFF ^ ESM::Enchantment::Autocalc))
properties += "Invalid ";
properties += Misc::StringUtils::format("(0x%08X)", flags);
return properties;
}
| 28,714
|
C++
|
.cpp
| 964
| 21.279046
| 118
| 0.541557
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
35,184
|
navmeshtilescache.cpp
|
OpenMW_openmw/apps/benchmarks/detournavigator/navmeshtilescache.cpp
|
#include <benchmark/benchmark.h>
#include <components/detournavigator/navmeshtilescache.hpp>
#include <components/detournavigator/stats.hpp>
#include <components/esm3/loadland.hpp>
#include <algorithm>
#include <iterator>
#include <random>
namespace
{
using namespace DetourNavigator;
struct Key
{
AgentBounds mAgentBounds;
TilePosition mTilePosition;
RecastMesh mRecastMesh;
};
struct Item
{
Key mKey;
PreparedNavMeshData mValue;
};
osg::Vec2i generateVec2i(int max, auto& random)
{
std::uniform_int_distribution<int> distribution(0, max);
return osg::Vec2i(distribution(random), distribution(random));
}
osg::Vec3f generateAgentHalfExtents(float min, float max, auto& random)
{
std::uniform_int_distribution<int> distribution(min, max);
return osg::Vec3f(distribution(random), distribution(random), distribution(random));
}
void generateVertices(std::output_iterator<int> auto out, std::size_t number, auto& random)
{
std::uniform_real_distribution<float> distribution(0.0, 1.0);
std::generate_n(out, 3 * (number - number % 3), [&] { return distribution(random); });
}
void generateIndices(std::output_iterator<int> auto out, int max, std::size_t number, auto& random)
{
std::uniform_int_distribution<int> distribution(0, max);
std::generate_n(out, number - number % 3, [&] { return distribution(random); });
}
AreaType toAreaType(int index)
{
switch (index)
{
case 0:
return AreaType_null;
case 1:
return AreaType_water;
case 2:
return AreaType_door;
case 3:
return AreaType_pathgrid;
case 4:
return AreaType_ground;
}
return AreaType_null;
}
AreaType generateAreaType(auto& random)
{
std::uniform_int_distribution<int> distribution(0, 4);
return toAreaType(distribution(random));
}
void generateAreaTypes(std::output_iterator<AreaType> auto out, std::size_t triangles, auto& random)
{
std::generate_n(out, triangles, [&] { return generateAreaType(random); });
}
void generateWater(std::output_iterator<CellWater> auto out, std::size_t count, auto& random)
{
std::uniform_real_distribution<float> distribution(0.0, 1.0);
std::generate_n(out, count, [&] {
return CellWater{ generateVec2i(1000, random), Water{ ESM::Land::REAL_SIZE, distribution(random) } };
});
}
Mesh generateMesh(std::size_t triangles, auto& random)
{
std::uniform_real_distribution<float> distribution(0.0, 1.0);
std::vector<float> vertices;
std::vector<int> indices;
std::vector<AreaType> areaTypes;
if (distribution(random) < 0.939)
{
generateVertices(std::back_inserter(vertices), triangles * 2.467, random);
generateIndices(std::back_inserter(indices), static_cast<int>(vertices.size() / 3) - 1,
vertices.size() * 1.279, random);
generateAreaTypes(std::back_inserter(areaTypes), indices.size() / 3, random);
}
return Mesh(std::move(indices), std::move(vertices), std::move(areaTypes));
}
Heightfield generateHeightfield(auto& random)
{
std::uniform_real_distribution<float> distribution(0.0, 1.0);
Heightfield result;
result.mCellPosition = generateVec2i(1000, random);
result.mCellSize = ESM::Land::REAL_SIZE;
result.mMinHeight = distribution(random);
result.mMaxHeight = result.mMinHeight + 1.0;
result.mLength = static_cast<std::uint8_t>(ESM::Land::LAND_SIZE);
std::generate_n(
std::back_inserter(result.mHeights), ESM::Land::LAND_NUM_VERTS, [&] { return distribution(random); });
result.mOriginalSize = ESM::Land::LAND_SIZE;
result.mMinX = 0;
result.mMinY = 0;
return result;
}
FlatHeightfield generateFlatHeightfield(auto& random)
{
std::uniform_real_distribution<float> distribution(0.0, 1.0);
FlatHeightfield result;
result.mCellPosition = generateVec2i(1000, random);
result.mCellSize = ESM::Land::REAL_SIZE;
result.mHeight = distribution(random);
return result;
}
Key generateKey(std::size_t triangles, auto& random)
{
const CollisionShapeType agentShapeType = CollisionShapeType::Aabb;
const osg::Vec3f agentHalfExtents = generateAgentHalfExtents(0.5, 1.5, random);
const TilePosition tilePosition = generateVec2i(10000, random);
const Version version{
.mGeneration = std::uniform_int_distribution<std::size_t>(0, 100)(random),
.mRevision = std::uniform_int_distribution<std::size_t>(0, 10000)(random),
};
Mesh mesh = generateMesh(triangles, random);
std::vector<CellWater> water;
generateWater(std::back_inserter(water), 1, random);
RecastMesh recastMesh(version, std::move(mesh), std::move(water), { generateHeightfield(random) },
{ generateFlatHeightfield(random) }, {});
return Key{ AgentBounds{ agentShapeType, agentHalfExtents }, tilePosition, std::move(recastMesh) };
}
constexpr std::size_t trianglesPerTile = 239;
void generateKeys(std::output_iterator<Key> auto out, std::size_t count, auto& random)
{
std::generate_n(out, count, [&] { return generateKey(trianglesPerTile, random); });
}
void fillCache(std::output_iterator<Key> auto out, auto& random, NavMeshTilesCache& cache)
{
std::size_t size = cache.getStats().mNavMeshCacheSize;
while (true)
{
Key key = generateKey(trianglesPerTile, random);
cache.set(key.mAgentBounds, key.mTilePosition, key.mRecastMesh, std::make_unique<PreparedNavMeshData>());
*out++ = std::move(key);
const std::size_t newSize = cache.getStats().mNavMeshCacheSize;
if (size >= newSize)
break;
size = newSize;
}
}
template <std::size_t maxCacheSize, int hitPercentage>
void getFromFilledCache(benchmark::State& state)
{
NavMeshTilesCache cache(maxCacheSize);
std::minstd_rand random;
std::vector<Key> keys;
fillCache(std::back_inserter(keys), random, cache);
generateKeys(std::back_inserter(keys), keys.size() * (100 - hitPercentage) / 100, random);
std::size_t n = 0;
for (auto _ : state)
{
const auto& key = keys[n++ % keys.size()];
auto result = cache.get(key.mAgentBounds, key.mTilePosition, key.mRecastMesh);
benchmark::DoNotOptimize(result);
}
}
void getFromFilledCache_1m_100hit(benchmark::State& state)
{
getFromFilledCache<1 * 1024 * 1024, 100>(state);
}
void getFromFilledCache_4m_100hit(benchmark::State& state)
{
getFromFilledCache<4 * 1024 * 1024, 100>(state);
}
void getFromFilledCache_16m_100hit(benchmark::State& state)
{
getFromFilledCache<16 * 1024 * 1024, 100>(state);
}
void getFromFilledCache_64m_100hit(benchmark::State& state)
{
getFromFilledCache<64 * 1024 * 1024, 100>(state);
}
void getFromFilledCache_1m_70hit(benchmark::State& state)
{
getFromFilledCache<1 * 1024 * 1024, 70>(state);
}
void getFromFilledCache_4m_70hit(benchmark::State& state)
{
getFromFilledCache<4 * 1024 * 1024, 70>(state);
}
void getFromFilledCache_16m_70hit(benchmark::State& state)
{
getFromFilledCache<16 * 1024 * 1024, 70>(state);
}
void getFromFilledCache_64m_70hit(benchmark::State& state)
{
getFromFilledCache<64 * 1024 * 1024, 70>(state);
}
template <std::size_t maxCacheSize>
void setToBoundedNonEmptyCache(benchmark::State& state)
{
NavMeshTilesCache cache(maxCacheSize);
std::minstd_rand random;
std::vector<Key> keys;
fillCache(std::back_inserter(keys), random, cache);
generateKeys(std::back_inserter(keys), keys.size() * 2, random);
std::reverse(keys.begin(), keys.end());
std::size_t n = 0;
while (state.KeepRunning())
{
const auto& key = keys[n++ % keys.size()];
auto result = cache.set(
key.mAgentBounds, key.mTilePosition, key.mRecastMesh, std::make_unique<PreparedNavMeshData>());
benchmark::DoNotOptimize(result);
}
}
void setToBoundedNonEmptyCache_1m(benchmark::State& state)
{
setToBoundedNonEmptyCache<1 * 1024 * 1024>(state);
}
void setToBoundedNonEmptyCache_4m(benchmark::State& state)
{
setToBoundedNonEmptyCache<4 * 1024 * 1024>(state);
}
void setToBoundedNonEmptyCache_16m(benchmark::State& state)
{
setToBoundedNonEmptyCache<16 * 1024 * 1024>(state);
}
void setToBoundedNonEmptyCache_64m(benchmark::State& state)
{
setToBoundedNonEmptyCache<64 * 1024 * 1024>(state);
}
} // namespace
BENCHMARK(getFromFilledCache_1m_100hit);
BENCHMARK(getFromFilledCache_4m_100hit);
BENCHMARK(getFromFilledCache_16m_100hit);
BENCHMARK(getFromFilledCache_64m_100hit);
BENCHMARK(getFromFilledCache_1m_70hit);
BENCHMARK(getFromFilledCache_4m_70hit);
BENCHMARK(getFromFilledCache_16m_70hit);
BENCHMARK(getFromFilledCache_64m_70hit);
BENCHMARK(setToBoundedNonEmptyCache_1m);
BENCHMARK(setToBoundedNonEmptyCache_4m);
BENCHMARK(setToBoundedNonEmptyCache_16m);
BENCHMARK(setToBoundedNonEmptyCache_64m);
BENCHMARK_MAIN();
| 9,752
|
C++
|
.cpp
| 245
| 32.261224
| 117
| 0.652936
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,185
|
access.cpp
|
OpenMW_openmw/apps/benchmarks/settings/access.cpp
|
#include <benchmark/benchmark.h>
#include "components/misc/strings/conversion.hpp"
#include "components/settings/parser.hpp"
#include "components/settings/settings.hpp"
#include "components/settings/values.hpp"
namespace
{
void settingsManager(benchmark::State& state)
{
for (auto _ : state)
{
benchmark::DoNotOptimize(Settings::Manager::getFloat("sky blending start", "Fog"));
}
}
void settingsManager2(benchmark::State& state)
{
for (auto _ : state)
{
benchmark::DoNotOptimize(Settings::Manager::getFloat("near clip", "Camera"));
benchmark::DoNotOptimize(Settings::Manager::getBool("transparent postpass", "Post Processing"));
}
}
void settingsManager3(benchmark::State& state)
{
for (auto _ : state)
{
benchmark::DoNotOptimize(Settings::Manager::getFloat("near clip", "Camera"));
benchmark::DoNotOptimize(Settings::Manager::getBool("transparent postpass", "Post Processing"));
benchmark::DoNotOptimize(Settings::Manager::getInt("reflection detail", "Water"));
}
}
void localStatic(benchmark::State& state)
{
for (auto _ : state)
{
static float v = Settings::Manager::getFloat("sky blending start", "Fog");
benchmark::DoNotOptimize(v);
}
}
void localStatic2(benchmark::State& state)
{
for (auto _ : state)
{
static float v1 = Settings::Manager::getFloat("near clip", "Camera");
static bool v2 = Settings::Manager::getBool("transparent postpass", "Post Processing");
benchmark::DoNotOptimize(v1);
benchmark::DoNotOptimize(v2);
}
}
void localStatic3(benchmark::State& state)
{
for (auto _ : state)
{
static float v1 = Settings::Manager::getFloat("near clip", "Camera");
static bool v2 = Settings::Manager::getBool("transparent postpass", "Post Processing");
static int v3 = Settings::Manager::getInt("reflection detail", "Water");
benchmark::DoNotOptimize(v1);
benchmark::DoNotOptimize(v2);
benchmark::DoNotOptimize(v3);
}
}
void settingsStorage(benchmark::State& state)
{
for (auto _ : state)
{
float v = Settings::fog().mSkyBlendingStart.get();
benchmark::DoNotOptimize(v);
}
}
void settingsStorage2(benchmark::State& state)
{
for (auto _ : state)
{
bool v1 = Settings::postProcessing().mTransparentPostpass.get();
float v2 = Settings::camera().mNearClip.get();
benchmark::DoNotOptimize(v1);
benchmark::DoNotOptimize(v2);
}
}
void settingsStorage3(benchmark::State& state)
{
for (auto _ : state)
{
bool v1 = Settings::postProcessing().mTransparentPostpass.get();
float v2 = Settings::camera().mNearClip.get();
int v3 = Settings::water().mReflectionDetail.get();
benchmark::DoNotOptimize(v1);
benchmark::DoNotOptimize(v2);
benchmark::DoNotOptimize(v3);
}
}
void settingsStorageGet(benchmark::State& state)
{
for (auto _ : state)
{
benchmark::DoNotOptimize(Settings::get<float>("Fog", "sky blending start"));
}
}
void settingsStorageGet2(benchmark::State& state)
{
for (auto _ : state)
{
benchmark::DoNotOptimize(Settings::get<bool>("Post Processing", "transparent postpass"));
benchmark::DoNotOptimize(Settings::get<float>("Camera", "near clip"));
}
}
void settingsStorageGet3(benchmark::State& state)
{
for (auto _ : state)
{
benchmark::DoNotOptimize(Settings::get<bool>("Post Processing", "transparent postpass"));
benchmark::DoNotOptimize(Settings::get<float>("Camera", "near clip"));
benchmark::DoNotOptimize(Settings::get<int>("Water", "reflection detail"));
}
}
}
BENCHMARK(settingsManager);
BENCHMARK(localStatic);
BENCHMARK(settingsStorage);
BENCHMARK(settingsStorageGet);
BENCHMARK(settingsManager2);
BENCHMARK(localStatic2);
BENCHMARK(settingsStorage2);
BENCHMARK(settingsStorageGet2);
BENCHMARK(settingsManager3);
BENCHMARK(localStatic3);
BENCHMARK(settingsStorage3);
BENCHMARK(settingsStorageGet3);
int main(int argc, char* argv[])
{
const std::filesystem::path settingsDefaultPath = std::filesystem::path{ OPENMW_PROJECT_SOURCE_DIR } / "files"
/ Misc::StringUtils::stringToU8String("settings-default.cfg");
Settings::SettingsFileParser parser;
parser.loadSettingsFile(settingsDefaultPath, Settings::Manager::mDefaultSettings);
Settings::StaticValues::initDefaults();
Settings::Manager::mUserSettings = Settings::Manager::mDefaultSettings;
Settings::Manager::mUserSettings.erase({ "Camera", "near clip" });
Settings::Manager::mUserSettings.erase({ "Post Processing", "transparent postpass" });
Settings::Manager::mUserSettings.erase({ "Water", "reflection detail" });
Settings::StaticValues::init();
benchmark::Initialize(&argc, argv);
benchmark::RunSpecifiedBenchmarks();
benchmark::Shutdown();
return 0;
}
| 5,368
|
C++
|
.cpp
| 145
| 29.489655
| 114
| 0.640385
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,186
|
benchrefid.cpp
|
OpenMW_openmw/apps/benchmarks/esm/benchrefid.cpp
|
#include <benchmark/benchmark.h>
#include "components/esm/refid.hpp"
#include <algorithm>
#include <cstddef>
#include <random>
#include <string>
#include <vector>
namespace
{
constexpr std::size_t refIdsCount = 64 * 1024;
template <class Random>
std::string generateText(std::size_t size, Random& random)
{
std::uniform_int_distribution<int> distribution('A', 'z');
std::string result;
result.reserve(size);
std::generate_n(std::back_inserter(result), size, [&] { return distribution(random); });
return result;
}
template <class Random>
std::vector<ESM::RefId> generateStringRefIds(std::size_t size, Random& random)
{
std::vector<ESM::RefId> result;
result.reserve(refIdsCount);
std::generate_n(
std::back_inserter(result), refIdsCount, [&] { return ESM::StringRefId(generateText(size, random)); });
return result;
}
template <class Serialize>
std::vector<std::string> generateSerializedRefIds(const std::vector<ESM::RefId>& generated, Serialize&& serialize)
{
std::vector<std::string> result;
result.reserve(generated.size());
for (ESM::RefId refId : generated)
result.push_back(serialize(refId));
return result;
}
template <class Random, class Serialize>
std::vector<std::string> generateSerializedStringRefIds(std::size_t size, Random& random, Serialize&& serialize)
{
return generateSerializedRefIds(generateStringRefIds(size, random), serialize);
}
template <class Random>
std::vector<ESM::RefId> generateIndexRefIds(Random& random)
{
std::vector<ESM::RefId> result;
result.reserve(refIdsCount);
std::uniform_int_distribution<std::uint32_t> distribution(0, std::numeric_limits<std::uint32_t>::max());
std::generate_n(std::back_inserter(result), refIdsCount,
[&] { return ESM::IndexRefId(ESM::REC_ARMO, distribution(random)); });
return result;
}
template <class Random, class Serialize>
std::vector<std::string> generateSerializedIndexRefIds(Random& random, Serialize&& serialize)
{
return generateSerializedRefIds(generateIndexRefIds(random), serialize);
}
template <class Random>
std::vector<ESM::RefId> generateGeneratedRefIds(Random& random)
{
std::vector<ESM::RefId> result;
result.reserve(refIdsCount);
std::uniform_int_distribution<std::uint64_t> distribution(0, std::numeric_limits<std::uint64_t>::max());
std::generate_n(
std::back_inserter(result), refIdsCount, [&] { return ESM::GeneratedRefId(distribution(random)); });
return result;
}
template <class Random, class Serialize>
std::vector<std::string> generateSerializedGeneratedRefIds(Random& random, Serialize&& serialize)
{
return generateSerializedRefIds(generateGeneratedRefIds(random), serialize);
}
template <class Random>
std::vector<ESM::RefId> generateESM3ExteriorCellRefIds(Random& random)
{
std::vector<ESM::RefId> result;
result.reserve(refIdsCount);
std::uniform_int_distribution<std::int32_t> distribution(-100, 100);
std::generate_n(std::back_inserter(result), refIdsCount,
[&] { return ESM::ESM3ExteriorCellRefId(distribution(random), distribution(random)); });
return result;
}
template <class Random, class Serialize>
std::vector<std::string> generateSerializedESM3ExteriorCellRefIds(Random& random, Serialize&& serialize)
{
return generateSerializedRefIds(generateESM3ExteriorCellRefIds(random), serialize);
}
void serializeRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<ESM::RefId> refIds = generateStringRefIds(state.range(0), random);
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(refIds[i].serialize());
if (++i >= refIds.size())
i = 0;
}
}
void deserializeRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<std::string> serializedRefIds
= generateSerializedStringRefIds(state.range(0), random, [](ESM::RefId v) { return v.serialize(); });
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(ESM::RefId::deserialize(serializedRefIds[i]));
if (++i >= serializedRefIds.size())
i = 0;
}
}
void serializeTextStringRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<ESM::RefId> refIds = generateStringRefIds(state.range(0), random);
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(refIds[i].serializeText());
if (++i >= refIds.size())
i = 0;
}
}
void deserializeTextStringRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<std::string> serializedRefIds
= generateSerializedStringRefIds(state.range(0), random, [](ESM::RefId v) { return v.serializeText(); });
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(ESM::RefId::deserializeText(serializedRefIds[i]));
if (++i >= serializedRefIds.size())
i = 0;
}
}
void serializeTextGeneratedRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<ESM::RefId> refIds = generateGeneratedRefIds(random);
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(refIds[i].serializeText());
if (++i >= refIds.size())
i = 0;
}
}
void deserializeTextGeneratedRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<std::string> serializedRefIds
= generateSerializedGeneratedRefIds(random, [](ESM::RefId v) { return v.serializeText(); });
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(ESM::RefId::deserializeText(serializedRefIds[i]));
if (++i >= serializedRefIds.size())
i = 0;
}
}
void serializeTextIndexRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<ESM::RefId> refIds = generateIndexRefIds(random);
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(refIds[i].serializeText());
if (++i >= refIds.size())
i = 0;
}
}
void deserializeTextIndexRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<std::string> serializedRefIds
= generateSerializedIndexRefIds(random, [](ESM::RefId v) { return v.serializeText(); });
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(ESM::RefId::deserializeText(serializedRefIds[i]));
if (++i >= serializedRefIds.size())
i = 0;
}
}
void serializeTextESM3ExteriorCellRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<ESM::RefId> refIds = generateESM3ExteriorCellRefIds(random);
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(refIds[i].serializeText());
if (++i >= refIds.size())
i = 0;
}
}
void deserializeTextESM3ExteriorCellRefId(benchmark::State& state)
{
std::minstd_rand random;
std::vector<std::string> serializedRefIds
= generateSerializedESM3ExteriorCellRefIds(random, [](ESM::RefId v) { return v.serializeText(); });
std::size_t i = 0;
for (auto _ : state)
{
benchmark::DoNotOptimize(ESM::RefId::deserializeText(serializedRefIds[i]));
if (++i >= serializedRefIds.size())
i = 0;
}
}
}
BENCHMARK(serializeRefId)->RangeMultiplier(4)->Range(8, 64);
BENCHMARK(deserializeRefId)->RangeMultiplier(4)->Range(8, 64);
BENCHMARK(serializeTextStringRefId)->RangeMultiplier(4)->Range(8, 64);
BENCHMARK(deserializeTextStringRefId)->RangeMultiplier(4)->Range(8, 64);
BENCHMARK(serializeTextGeneratedRefId);
BENCHMARK(deserializeTextGeneratedRefId);
BENCHMARK(serializeTextIndexRefId);
BENCHMARK(deserializeTextIndexRefId);
BENCHMARK(serializeTextESM3ExteriorCellRefId);
BENCHMARK(deserializeTextESM3ExteriorCellRefId);
BENCHMARK_MAIN();
| 8,674
|
C++
|
.cpp
| 224
| 30.736607
| 118
| 0.631691
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,187
|
main.cpp
|
OpenMW_openmw/apps/components_tests/main.cpp
|
#include <components/debug/debugging.hpp>
#include <components/misc/strings/conversion.hpp>
#include <components/settings/parser.hpp>
#include <components/settings/values.hpp>
#include <gtest/gtest.h>
#include <filesystem>
int main(int argc, char** argv)
{
Log::sMinDebugLevel = Debug::getDebugLevel();
const std::filesystem::path settingsDefaultPath = std::filesystem::path{ OPENMW_PROJECT_SOURCE_DIR } / "files"
/ Misc::StringUtils::stringToU8String("settings-default.cfg");
Settings::SettingsFileParser parser;
parser.loadSettingsFile(settingsDefaultPath, Settings::Manager::mDefaultSettings);
Settings::StaticValues::initDefaults();
Settings::Manager::mUserSettings = Settings::Manager::mDefaultSettings;
Settings::StaticValues::init();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 858
|
C++
|
.cpp
| 19
| 41.368421
| 114
| 0.763855
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,188
|
recastmeshobject.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/recastmeshobject.cpp
|
#include <components/detournavigator/recastmeshobject.hpp>
#include <components/misc/convert.hpp>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <BulletCollision/CollisionShapes/btCompoundShape.h>
#include <gtest/gtest.h>
namespace
{
using namespace testing;
using namespace DetourNavigator;
struct DetourNavigatorRecastMeshObjectTest : Test
{
btBoxShape mBoxShapeImpl{ btVector3(1, 2, 3) };
const ObjectTransform mObjectTransform{ ESM::Position{ { 1, 2, 3 }, { 1, 2, 3 } }, 0.5f };
CollisionShape mBoxShape{ nullptr, mBoxShapeImpl, mObjectTransform };
btCompoundShape mCompoundShapeImpl{ true };
CollisionShape mCompoundShape{ nullptr, mCompoundShapeImpl, mObjectTransform };
btTransform mTransform{ Misc::Convert::makeBulletTransform(mObjectTransform.mPosition) };
DetourNavigatorRecastMeshObjectTest()
{
mCompoundShapeImpl.addChildShape(mTransform, std::addressof(mBoxShapeImpl));
}
};
TEST_F(DetourNavigatorRecastMeshObjectTest, constructed_object_should_have_shape_and_transform)
{
const RecastMeshObject object(mBoxShape, mTransform, AreaType_ground);
EXPECT_EQ(std::addressof(object.getShape()), std::addressof(mBoxShapeImpl));
EXPECT_EQ(object.getTransform(), mTransform);
}
TEST_F(DetourNavigatorRecastMeshObjectTest, update_with_same_transform_for_not_compound_shape_should_return_false)
{
RecastMeshObject object(mBoxShape, mTransform, AreaType_ground);
EXPECT_FALSE(object.update(mTransform, AreaType_ground));
}
TEST_F(DetourNavigatorRecastMeshObjectTest, update_with_different_transform_should_return_true)
{
RecastMeshObject object(mBoxShape, mTransform, AreaType_ground);
EXPECT_TRUE(object.update(btTransform::getIdentity(), AreaType_ground));
}
TEST_F(DetourNavigatorRecastMeshObjectTest, update_with_different_flags_should_return_true)
{
RecastMeshObject object(mBoxShape, mTransform, AreaType_ground);
EXPECT_TRUE(object.update(mTransform, AreaType_null));
}
TEST_F(DetourNavigatorRecastMeshObjectTest,
update_for_compound_shape_with_same_transform_and_not_changed_child_transform_should_return_false)
{
RecastMeshObject object(mCompoundShape, mTransform, AreaType_ground);
EXPECT_FALSE(object.update(mTransform, AreaType_ground));
}
TEST_F(DetourNavigatorRecastMeshObjectTest,
update_for_compound_shape_with_same_transform_and_changed_child_transform_should_return_true)
{
RecastMeshObject object(mCompoundShape, mTransform, AreaType_ground);
mCompoundShapeImpl.updateChildTransform(0, btTransform::getIdentity());
EXPECT_TRUE(object.update(mTransform, AreaType_ground));
}
TEST_F(DetourNavigatorRecastMeshObjectTest, repeated_update_for_compound_shape_without_changes_should_return_false)
{
RecastMeshObject object(mCompoundShape, mTransform, AreaType_ground);
mCompoundShapeImpl.updateChildTransform(0, btTransform::getIdentity());
object.update(mTransform, AreaType_ground);
EXPECT_FALSE(object.update(mTransform, AreaType_ground));
}
TEST_F(DetourNavigatorRecastMeshObjectTest, update_for_changed_local_scaling_should_return_true)
{
RecastMeshObject object(mBoxShape, mTransform, AreaType_ground);
mBoxShapeImpl.setLocalScaling(btVector3(2, 2, 2));
EXPECT_TRUE(object.update(mTransform, AreaType_ground));
}
}
| 3,551
|
C++
|
.cpp
| 70
| 44.042857
| 119
| 0.749928
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,189
|
settingsutils.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/settingsutils.cpp
|
#include <components/detournavigator/settingsutils.hpp>
#include <gtest/gtest.h>
namespace
{
using namespace testing;
using namespace DetourNavigator;
struct DetourNavigatorGetTilePositionTest : Test
{
RecastSettings mSettings;
DetourNavigatorGetTilePositionTest()
{
mSettings.mCellSize = 0.5;
mSettings.mTileSize = 64;
}
};
TEST_F(DetourNavigatorGetTilePositionTest, for_zero_coordinates_should_return_zero_tile_position)
{
EXPECT_EQ(getTilePosition(mSettings, osg::Vec3f(0, 0, 0)), TilePosition(0, 0));
}
TEST_F(DetourNavigatorGetTilePositionTest, tile_size_should_be_multiplied_by_cell_size)
{
EXPECT_EQ(getTilePosition(mSettings, osg::Vec3f(32, 0, 0)), TilePosition(1, 0));
}
TEST_F(DetourNavigatorGetTilePositionTest, tile_position_calculates_by_floor)
{
EXPECT_EQ(getTilePosition(mSettings, osg::Vec3f(31, 0, 0)), TilePosition(0, 0));
}
TEST_F(DetourNavigatorGetTilePositionTest, tile_position_depends_on_x_and_z_coordinates)
{
EXPECT_EQ(getTilePosition(mSettings, osg::Vec3f(32, 64, 128)), TilePosition(1, 4));
}
TEST_F(DetourNavigatorGetTilePositionTest, tile_position_works_for_negative_coordinates)
{
EXPECT_EQ(getTilePosition(mSettings, osg::Vec3f(-31, 0, -32)), TilePosition(-1, -1));
}
struct DetourNavigatorMakeTileBoundsTest : Test
{
RecastSettings mSettings;
DetourNavigatorMakeTileBoundsTest()
{
mSettings.mCellSize = 0.5;
mSettings.mTileSize = 64;
}
};
TEST_F(DetourNavigatorMakeTileBoundsTest, tile_bounds_depend_on_tile_size_and_cell_size)
{
EXPECT_EQ(makeTileBounds(mSettings, TilePosition(0, 0)), (TileBounds{ osg::Vec2f(0, 0), osg::Vec2f(32, 32) }));
}
TEST_F(DetourNavigatorMakeTileBoundsTest, tile_bounds_are_multiplied_by_tile_position)
{
EXPECT_EQ(
makeTileBounds(mSettings, TilePosition(1, 2)), (TileBounds{ osg::Vec2f(32, 64), osg::Vec2f(64, 96) }));
}
}
| 2,094
|
C++
|
.cpp
| 54
| 32.037037
| 119
| 0.684107
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,190
|
recastmeshbuilder.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/recastmeshbuilder.cpp
|
#include "operators.hpp"
#include <components/detournavigator/recastmesh.hpp>
#include <components/detournavigator/recastmeshbuilder.hpp>
#include <BulletCollision/CollisionDispatch/btCollisionObject.h>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h>
#include <BulletCollision/CollisionShapes/btCompoundShape.h>
#include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
#include <BulletCollision/CollisionShapes/btTriangleMesh.h>
#include <DetourCommon.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <array>
namespace DetourNavigator
{
static inline bool operator==(const Water& lhs, const Water& rhs)
{
const auto tie = [](const Water& v) { return std::tie(v.mCellSize, v.mLevel); };
return tie(lhs) == tie(rhs);
}
static inline bool operator==(const CellWater& lhs, const CellWater& rhs)
{
const auto tie = [](const CellWater& v) { return std::tie(v.mCellPosition, v.mWater); };
return tie(lhs) == tie(rhs);
}
static inline bool operator==(const Heightfield& lhs, const Heightfield& rhs)
{
return makeTuple(lhs) == makeTuple(rhs);
}
static inline bool operator==(const FlatHeightfield& lhs, const FlatHeightfield& rhs)
{
const auto tie = [](const FlatHeightfield& v) { return std::tie(v.mCellPosition, v.mCellSize, v.mHeight); };
return tie(lhs) == tie(rhs);
}
}
namespace
{
using namespace testing;
using namespace DetourNavigator;
struct DetourNavigatorRecastMeshBuilderTest : Test
{
TileBounds mBounds;
const Version mVersion{ 0, 0 };
const osg::ref_ptr<const Resource::BulletShape> mSource{ nullptr };
const ObjectTransform mObjectTransform{ ESM::Position{ { 0, 0, 0 }, { 0, 0, 0 } }, 0.0f };
DetourNavigatorRecastMeshBuilderTest()
{
mBounds.mMin = osg::Vec2f(-std::numeric_limits<float>::max() * std::numeric_limits<float>::epsilon(),
-std::numeric_limits<float>::max() * std::numeric_limits<float>::epsilon());
mBounds.mMax = osg::Vec2f(std::numeric_limits<float>::max() * std::numeric_limits<float>::epsilon(),
std::numeric_limits<float>::max() * std::numeric_limits<float>::epsilon());
}
};
TEST_F(DetourNavigatorRecastMeshBuilderTest, create_for_empty_should_return_empty)
{
RecastMeshBuilder builder(mBounds);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(), std::vector<float>());
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>());
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>());
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_bhv_triangle_mesh_shape)
{
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
btBvhTriangleMeshShape shape(&mesh, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape), btTransform::getIdentity(), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
-1, -1, 0, // vertex 0
-1, 1, 0, // vertex 1
1, -1, 0, // vertex 2
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 1, 0 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_transformed_bhv_triangle_mesh_shape)
{
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
btBvhTriangleMeshShape shape(&mesh, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape),
btTransform(btMatrix3x3::getIdentity().scaled(btVector3(1, 2, 3)), btVector3(1, 2, 3)), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
0, 0, 3, // vertex 0
0, 4, 3, // vertex 1
2, 0, 3, // vertex 2
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 1, 0 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_heightfield_terrian_shape)
{
const std::array<btScalar, 4> heightfieldData{ { 0, 0, 0, 0 } };
btHeightfieldTerrainShape shape(2, 2, heightfieldData.data(), 1, 0, 0, 2, PHY_FLOAT, false);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape), btTransform::getIdentity(), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
-0.5, -0.5, 0, // vertex 0
-0.5, 0.5, 0, // vertex 1
0.5, -0.5, 0, // vertex 2
0.5, 0.5, 0, // vertex 3
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 0, 1, 2, 2, 1, 3 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground, AreaType_ground }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_box_shape_should_produce_12_triangles)
{
btBoxShape shape(btVector3(1, 1, 2));
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape), btTransform::getIdentity(), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
-1, -1, -2, // vertex 0
-1, -1, 2, // vertex 1
-1, 1, -2, // vertex 2
-1, 1, 2, // vertex 3
1, -1, -2, // vertex 4
1, -1, 2, // vertex 5
1, 1, -2, // vertex 6
1, 1, 2, // vertex 7
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(),
std::vector<int>({
0, 1, 5, // triangle 0
0, 2, 3, // triangle 1
0, 4, 6, // triangle 2
1, 3, 7, // triangle 3
2, 6, 7, // triangle 4
3, 1, 0, // triangle 5
4, 5, 7, // triangle 6
5, 4, 0, // triangle 7
6, 2, 0, // triangle 8
7, 3, 2, // triangle 9
7, 5, 1, // triangle 10
7, 6, 4, // triangle 11
}))
<< recastMesh->getMesh().getIndices();
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>(12, AreaType_ground));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_compound_shape)
{
btTriangleMesh mesh1;
mesh1.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
btBvhTriangleMeshShape triangle1(&mesh1, true);
btBoxShape box(btVector3(1, 1, 2));
btTriangleMesh mesh2;
mesh2.addTriangle(btVector3(1, 1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
btBvhTriangleMeshShape triangle2(&mesh2, true);
btCompoundShape shape;
shape.addChildShape(btTransform::getIdentity(), &triangle1);
shape.addChildShape(btTransform::getIdentity(), &box);
shape.addChildShape(btTransform::getIdentity(), &triangle2);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape), btTransform::getIdentity(), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
-1, -1, -2, // vertex 0
-1, -1, 0, // vertex 1
-1, -1, 2, // vertex 2
-1, 1, -2, // vertex 3
-1, 1, 0, // vertex 4
-1, 1, 2, // vertex 5
1, -1, -2, // vertex 6
1, -1, 0, // vertex 7
1, -1, 2, // vertex 8
1, 1, -2, // vertex 9
1, 1, 0, // vertex 10
1, 1, 2, // vertex 11
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(),
std::vector<int>({
0, 2, 8, // triangle 0
0, 3, 5, // triangle 1
0, 6, 9, // triangle 2
2, 5, 11, // triangle 3
3, 9, 11, // triangle 4
5, 2, 0, // triangle 5
6, 8, 11, // triangle 6
7, 4, 1, // triangle 7
7, 4, 10, // triangle 8
8, 6, 0, // triangle 9
9, 3, 0, // triangle 10
11, 5, 3, // triangle 11
11, 8, 2, // triangle 12
11, 9, 6, // triangle 13
}))
<< recastMesh->getMesh().getIndices();
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>(14, AreaType_ground));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_transformed_compound_shape)
{
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
btBvhTriangleMeshShape triangle(&mesh, true);
btCompoundShape shape;
shape.addChildShape(btTransform::getIdentity(), &triangle);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape),
btTransform(btMatrix3x3::getIdentity().scaled(btVector3(1, 2, 3)), btVector3(1, 2, 3)), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
0, 0, 3, // vertex 0
0, 4, 3, // vertex 1
2, 0, 3, // vertex 2
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 1, 0 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_transformed_compound_shape_with_transformed_bhv_triangle_shape)
{
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
btBvhTriangleMeshShape triangle(&mesh, true);
btCompoundShape shape;
shape.addChildShape(
btTransform(btMatrix3x3::getIdentity().scaled(btVector3(1, 2, 3)), btVector3(1, 2, 3)), &triangle);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape),
btTransform(btMatrix3x3::getIdentity().scaled(btVector3(1, 2, 3)), btVector3(1, 2, 3)), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
1, 2, 12, // vertex 0
1, 10, 12, // vertex 1
3, 2, 12, // vertex 2
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 1, 0 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, without_bounds_add_bhv_triangle_shape_should_not_filter_by_bounds)
{
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
mesh.addTriangle(btVector3(-3, -3, 0), btVector3(-3, -2, 0), btVector3(-2, -3, 0));
btBvhTriangleMeshShape shape(&mesh, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape), btTransform::getIdentity(), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
-3, -3, 0, // vertex 0
-3, -2, 0, // vertex 1
-2, -3, 0, // vertex 2
-1, -1, 0, // vertex 3
-1, 1, 0, // vertex 4
1, -1, 0, // vertex 5
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 1, 0, 5, 4, 3 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>(2, AreaType_ground));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, with_bounds_add_bhv_triangle_shape_should_filter_by_bounds)
{
mBounds.mMin = osg::Vec2f(-3, -3);
mBounds.mMax = osg::Vec2f(-2, -2);
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
mesh.addTriangle(btVector3(-3, -3, 0), btVector3(-3, -2, 0), btVector3(-2, -3, 0));
btBvhTriangleMeshShape shape(&mesh, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape), btTransform::getIdentity(), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
-3, -3, 0, // vertex 0
-3, -2, 0, // vertex 1
-2, -3, 0, // vertex 2
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 1, 0 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground }));
}
TEST_F(
DetourNavigatorRecastMeshBuilderTest, with_bounds_add_rotated_by_x_bhv_triangle_shape_should_filter_by_bounds)
{
mBounds.mMin = osg::Vec2f(-5, -5);
mBounds.mMax = osg::Vec2f(5, -2);
btTriangleMesh mesh;
mesh.addTriangle(btVector3(0, -1, -1), btVector3(0, -1, -1), btVector3(0, 1, -1));
mesh.addTriangle(btVector3(0, -3, -3), btVector3(0, -3, -2), btVector3(0, -2, -3));
btBvhTriangleMeshShape shape(&mesh, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape),
btTransform(btQuaternion(btVector3(1, 0, 0), static_cast<btScalar>(-osg::PI_4))), AreaType_ground, mSource,
mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_THAT(recastMesh->getMesh().getVertices(),
Pointwise(FloatNear(1e-5f),
std::vector<float>({
0, -4.24264049530029296875f, 4.44089209850062616169452667236328125e-16f, // vertex 0
0, -3.535533905029296875f, -0.707106769084930419921875f, // vertex 1
0, -3.535533905029296875f, 0.707106769084930419921875f, // vertex 2
})))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 1, 2, 0 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground }));
}
TEST_F(
DetourNavigatorRecastMeshBuilderTest, with_bounds_add_rotated_by_y_bhv_triangle_shape_should_filter_by_bounds)
{
mBounds.mMin = osg::Vec2f(-5, -5);
mBounds.mMax = osg::Vec2f(-3, 5);
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, 0, -1), btVector3(-1, 0, 1), btVector3(1, 0, -1));
mesh.addTriangle(btVector3(-3, 0, -3), btVector3(-3, 0, -2), btVector3(-2, 0, -3));
btBvhTriangleMeshShape shape(&mesh, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape),
btTransform(btQuaternion(btVector3(0, 1, 0), static_cast<btScalar>(osg::PI_4))), AreaType_ground, mSource,
mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_THAT(recastMesh->getMesh().getVertices(),
Pointwise(FloatNear(1e-5f),
std::vector<float>({
-4.24264049530029296875f, 0, 4.44089209850062616169452667236328125e-16f, // vertex 0
-3.535533905029296875f, 0, -0.707106769084930419921875f, // vertex 1
-3.535533905029296875f, 0, 0.707106769084930419921875f, // vertex 2
})))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 1, 2, 0 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground }));
}
TEST_F(
DetourNavigatorRecastMeshBuilderTest, with_bounds_add_rotated_by_z_bhv_triangle_shape_should_filter_by_bounds)
{
mBounds.mMin = osg::Vec2f(-5, -5);
mBounds.mMax = osg::Vec2f(-1, -1);
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
mesh.addTriangle(btVector3(-3, -3, 0), btVector3(-3, -2, 0), btVector3(-2, -3, 0));
btBvhTriangleMeshShape shape(&mesh, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape),
btTransform(btQuaternion(btVector3(0, 0, 1), static_cast<btScalar>(osg::PI_4))), AreaType_ground, mSource,
mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_THAT(recastMesh->getMesh().getVertices(),
Pointwise(FloatNear(1e-5f),
std::vector<float>({
-1.41421353816986083984375f, -1.1102230246251565404236316680908203125e-16f, 0, // vertex 0
1.1102230246251565404236316680908203125e-16f, -1.41421353816986083984375f, 0, // vertex 1
1.41421353816986083984375f, 1.1102230246251565404236316680908203125e-16f, 0, // vertex 2
})))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 0, 1 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, flags_values_should_be_corresponding_to_added_objects)
{
btTriangleMesh mesh1;
mesh1.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
btBvhTriangleMeshShape shape1(&mesh1, true);
btTriangleMesh mesh2;
mesh2.addTriangle(btVector3(-3, -3, 0), btVector3(-3, -2, 0), btVector3(-2, -3, 0));
btBvhTriangleMeshShape shape2(&mesh2, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape1), btTransform::getIdentity(), AreaType_ground,
mSource, mObjectTransform);
builder.addObject(static_cast<const btCollisionShape&>(shape2), btTransform::getIdentity(), AreaType_null,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
-3, -3, 0, // vertex 0
-3, -2, 0, // vertex 1
-2, -3, 0, // vertex 2
-1, -1, 0, // vertex 3
-1, 1, 0, // vertex 4
1, -1, 0, // vertex 5
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 1, 0, 5, 4, 3 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_null, AreaType_ground }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_water_then_get_water_should_return_it)
{
RecastMeshBuilder builder(mBounds);
builder.addWater(osg::Vec2i(1, 2), Water{ 1000, 300.0f });
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(
recastMesh->getWater(), std::vector<CellWater>({ CellWater{ osg::Vec2i(1, 2), Water{ 1000, 300.0f } } }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_bhv_triangle_mesh_shape_with_duplicated_vertices)
{
btTriangleMesh mesh;
mesh.addTriangle(btVector3(-1, -1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
mesh.addTriangle(btVector3(1, 1, 0), btVector3(-1, 1, 0), btVector3(1, -1, 0));
btBvhTriangleMeshShape shape(&mesh, true);
RecastMeshBuilder builder(mBounds);
builder.addObject(static_cast<const btCollisionShape&>(shape), btTransform::getIdentity(), AreaType_ground,
mSource, mObjectTransform);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getMesh().getVertices(),
std::vector<float>({
-1, -1, 0, // vertex 0
-1, 1, 0, // vertex 1
1, -1, 0, // vertex 2
1, 1, 0, // vertex 3
}))
<< recastMesh->getMesh().getVertices();
EXPECT_EQ(recastMesh->getMesh().getIndices(), std::vector<int>({ 2, 1, 0, 2, 1, 3 }));
EXPECT_EQ(recastMesh->getMesh().getAreaTypes(), std::vector<AreaType>({ AreaType_ground, AreaType_ground }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_flat_heightfield_should_add_intersection)
{
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 1000;
const float height = 10;
mBounds.mMin = osg::Vec2f(100, 100);
RecastMeshBuilder builder(mBounds);
builder.addHeightfield(cellPosition, cellSize, height);
const auto recastMesh = std::move(builder).create(mVersion);
EXPECT_EQ(recastMesh->getFlatHeightfields(),
std::vector<FlatHeightfield>({
FlatHeightfield{ cellPosition, cellSize, height },
}));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_heightfield_inside_tile)
{
constexpr std::size_t size = 3;
constexpr std::array<float, size * size> heights{ {
0, 1, 2, // row 0
3, 4, 5, // row 1
6, 7, 8, // row 2
} };
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 1000;
const float minHeight = 0;
const float maxHeight = 8;
RecastMeshBuilder builder(mBounds);
builder.addHeightfield(cellPosition, cellSize, heights.data(), size, minHeight, maxHeight);
const auto recastMesh = std::move(builder).create(mVersion);
Heightfield expected;
expected.mCellPosition = cellPosition;
expected.mCellSize = cellSize;
expected.mLength = size;
expected.mMinHeight = minHeight;
expected.mMaxHeight = maxHeight;
expected.mHeights.assign(heights.begin(), heights.end());
expected.mOriginalSize = 3;
expected.mMinX = 0;
expected.mMinY = 0;
EXPECT_EQ(recastMesh->getHeightfields(), std::vector<Heightfield>({ expected }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_heightfield_to_shifted_cell_inside_tile)
{
constexpr std::size_t size = 3;
constexpr std::array<float, size * size> heights{ {
0, 1, 2, // row 0
3, 4, 5, // row 1
6, 7, 8, // row 2
} };
const osg::Vec2i cellPosition(1, 2);
const int cellSize = 1000;
const float minHeight = 0;
const float maxHeight = 8;
RecastMeshBuilder builder(maxCellTileBounds(cellPosition, cellSize));
builder.addHeightfield(cellPosition, cellSize, heights.data(), size, minHeight, maxHeight);
const auto recastMesh = std::move(builder).create(mVersion);
Heightfield expected;
expected.mCellPosition = cellPosition;
expected.mCellSize = cellSize;
expected.mLength = size;
expected.mMinHeight = minHeight;
expected.mMaxHeight = maxHeight;
expected.mHeights.assign(heights.begin(), heights.end());
expected.mOriginalSize = 3;
expected.mMinX = 0;
expected.mMinY = 0;
EXPECT_EQ(recastMesh->getHeightfields(), std::vector<Heightfield>({ expected }));
}
TEST_F(DetourNavigatorRecastMeshBuilderTest, add_heightfield_should_add_intersection)
{
constexpr std::size_t size = 3;
constexpr std::array<float, 3 * 3> heights{ {
0, 1, 2, // row 0
3, 4, 5, // row 1
6, 7, 8, // row 2
} };
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 1000;
const float minHeight = 0;
const float maxHeight = 8;
mBounds.mMin = osg::Vec2f(750, 750);
RecastMeshBuilder builder(mBounds);
builder.addHeightfield(cellPosition, cellSize, heights.data(), size, minHeight, maxHeight);
const auto recastMesh = std::move(builder).create(mVersion);
Heightfield expected;
expected.mCellPosition = cellPosition;
expected.mCellSize = cellSize;
expected.mLength = 2;
expected.mMinHeight = 0;
expected.mMaxHeight = 8;
expected.mHeights = {
4, 5, // row 0
7, 8, // row 1
};
expected.mOriginalSize = 3;
expected.mMinX = 1;
expected.mMinY = 1;
EXPECT_EQ(recastMesh->getHeightfields(), std::vector<Heightfield>({ expected }));
}
}
| 26,599
|
C++
|
.cpp
| 530
| 39.801887
| 119
| 0.601652
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,191
|
tilecachedrecastmeshmanager.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/tilecachedrecastmeshmanager.cpp
|
#include <components/detournavigator/debug.hpp>
#include <components/detournavigator/settingsutils.hpp>
#include <components/detournavigator/tilecachedrecastmeshmanager.hpp>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <osg/io_utils>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace
{
using namespace testing;
using namespace DetourNavigator;
struct DetourNavigatorTileCachedRecastMeshManagerTest : Test
{
RecastSettings mSettings;
const ObjectTransform mObjectTransform{ ESM::Position{ { 0, 0, 0 }, { 0, 0, 0 } }, 0.0f };
const osg::ref_ptr<const Resource::BulletShape> mShape = new Resource::BulletShape;
const osg::ref_ptr<const Resource::BulletShapeInstance> mInstance = new Resource::BulletShapeInstance(mShape);
const ESM::RefId mWorldspace = ESM::RefId::stringRefId("worldspace");
DetourNavigatorTileCachedRecastMeshManagerTest()
{
mSettings.mBorderSize = 16;
mSettings.mCellSize = 0.2f;
mSettings.mRecastScaleFactor = 0.017647058823529415f;
mSettings.mTileSize = 64;
}
};
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, get_mesh_for_empty_should_return_nullptr)
{
TileCachedRecastMeshManager manager(mSettings);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(0, 0)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, get_revision_for_empty_should_return_zero)
{
const TileCachedRecastMeshManager manager(mSettings);
EXPECT_EQ(manager.getRevision(), 0);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, add_object_for_new_object_should_return_true)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
EXPECT_TRUE(manager.addObject(
ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, add_object_for_existing_object_should_return_false)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_FALSE(manager.addObject(
ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, add_object_should_add_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
ASSERT_TRUE(manager.addObject(
ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
for (int x = -1; x < 1; ++x)
for (int y = -1; y < 1; ++y)
ASSERT_NE(manager.getMesh(mWorldspace, TilePosition(x, y)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, add_object_should_return_add_changed_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
const TilesPositionsRange range{
.mBegin = TilePosition(0, 0),
.mEnd = TilePosition(1, 1),
};
manager.setRange(range, nullptr);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_THAT(manager.takeChangedTiles(nullptr), ElementsAre(std::pair(TilePosition(0, 0), ChangeType::add)));
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, update_object_for_changed_object_should_add_changed_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const btTransform transform(
btMatrix3x3::getIdentity(), btVector3(getTileSize(mSettings) / mSettings.mRecastScaleFactor, 0, 0));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
const TilesPositionsRange range{
.mBegin = TilePosition(-1, -1),
.mEnd = TilePosition(2, 2),
};
manager.setRange(range, nullptr);
manager.addObject(ObjectId(&boxShape), shape, transform, AreaType::AreaType_ground, nullptr);
manager.takeChangedTiles(nullptr);
EXPECT_TRUE(
manager.updateObject(ObjectId(&boxShape), btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
EXPECT_THAT(manager.takeChangedTiles(nullptr),
ElementsAre(std::pair(TilePosition(-1, -1), ChangeType::add),
std::pair(TilePosition(-1, 0), ChangeType::add), std::pair(TilePosition(0, -1), ChangeType::update),
std::pair(TilePosition(0, 0), ChangeType::update), std::pair(TilePosition(1, -1), ChangeType::remove),
std::pair(TilePosition(1, 0), ChangeType::remove)));
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
update_object_for_not_changed_object_should_not_add_changed_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
manager.takeChangedTiles(nullptr);
EXPECT_FALSE(
manager.updateObject(ObjectId(&boxShape), btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
EXPECT_THAT(manager.takeChangedTiles(nullptr), IsEmpty());
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, remove_object_should_return_add_changed_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
const TilesPositionsRange range{
.mBegin = TilePosition(0, 0),
.mEnd = TilePosition(1, 1),
};
manager.setRange(range, nullptr);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
manager.takeChangedTiles(nullptr);
manager.removeObject(ObjectId(&boxShape), nullptr);
EXPECT_THAT(manager.takeChangedTiles(nullptr), ElementsAre(std::pair(TilePosition(0, 0), ChangeType::remove)));
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_mesh_after_add_object_should_return_recast_mesh_for_each_used_tile)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(-1, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(-1, 0)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, 0)), nullptr);
}
TEST_F(
DetourNavigatorTileCachedRecastMeshManagerTest, get_mesh_after_add_object_should_return_nullptr_for_unused_tile)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(1, 0)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_mesh_for_moved_object_should_return_recast_mesh_for_each_used_tile)
{
TileCachedRecastMeshManager manager(mSettings);
const TilesPositionsRange range{
.mBegin = TilePosition(-1, -1),
.mEnd = TilePosition(2, 2),
};
manager.setRange(range, nullptr);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const btTransform transform(
btMatrix3x3::getIdentity(), btVector3(getTileSize(mSettings) / mSettings.mRecastScaleFactor, 0, 0));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, transform, AreaType::AreaType_ground, nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, 0)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(1, 0)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(1, -1)), nullptr);
manager.updateObject(ObjectId(&boxShape), btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(-1, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(-1, 0)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, 0)), nullptr);
}
TEST_F(
DetourNavigatorTileCachedRecastMeshManagerTest, get_mesh_for_moved_object_should_return_nullptr_for_unused_tile)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const btTransform transform(
btMatrix3x3::getIdentity(), btVector3(getTileSize(mSettings) / mSettings.mRecastScaleFactor, 0, 0));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, transform, AreaType::AreaType_ground, nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(-1, -1)), nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(-1, 0)), nullptr);
manager.updateObject(ObjectId(&boxShape), btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(1, 0)), nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(1, -1)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_mesh_for_removed_object_should_return_nullptr_for_all_previously_used_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
manager.removeObject(ObjectId(&boxShape), nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(-1, -1)), nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(-1, 0)), nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(0, -1)), nullptr);
EXPECT_EQ(manager.getMesh(mWorldspace, TilePosition(0, 0)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_mesh_for_not_changed_object_after_update_should_return_recast_mesh_for_same_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(-1, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(-1, 0)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, 0)), nullptr);
manager.updateObject(ObjectId(&boxShape), btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(-1, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(-1, 0)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, -1)), nullptr);
EXPECT_NE(manager.getMesh(mWorldspace, TilePosition(0, 0)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_revision_after_add_object_new_should_return_incremented_value)
{
TileCachedRecastMeshManager manager(mSettings);
const auto initialRevision = manager.getRevision();
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_EQ(manager.getRevision(), initialRevision + 1);
}
TEST_F(
DetourNavigatorTileCachedRecastMeshManagerTest, get_revision_after_add_object_existing_should_return_same_value)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
const auto beforeAddRevision = manager.getRevision();
EXPECT_FALSE(manager.addObject(
ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
EXPECT_EQ(manager.getRevision(), beforeAddRevision);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_revision_after_update_moved_object_should_return_incremented_value)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const btTransform transform(
btMatrix3x3::getIdentity(), btVector3(getTileSize(mSettings) / mSettings.mRecastScaleFactor, 0, 0));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, transform, AreaType::AreaType_ground, nullptr);
const auto beforeUpdateRevision = manager.getRevision();
manager.updateObject(ObjectId(&boxShape), btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_EQ(manager.getRevision(), beforeUpdateRevision + 1);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_revision_after_update_not_changed_object_should_return_same_value)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
const auto beforeUpdateRevision = manager.getRevision();
manager.updateObject(ObjectId(&boxShape), btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
EXPECT_EQ(manager.getRevision(), beforeUpdateRevision);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_revision_after_remove_existing_object_should_return_incremented_value)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
const auto beforeRemoveRevision = manager.getRevision();
manager.removeObject(ObjectId(&boxShape), nullptr);
EXPECT_EQ(manager.getRevision(), beforeRemoveRevision + 1);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest,
get_revision_after_remove_absent_object_should_return_same_value)
{
TileCachedRecastMeshManager manager(mSettings);
const auto beforeRemoveRevision = manager.getRevision();
manager.removeObject(ObjectId(&manager), nullptr);
EXPECT_EQ(manager.getRevision(), beforeRemoveRevision);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, add_water_for_new_water_should_add_changed_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 8192;
manager.addWater(cellPosition, cellSize, 0.0f, nullptr);
const auto changedTiles = manager.takeChangedTiles(nullptr);
EXPECT_EQ(changedTiles.begin()->first, TilePosition(-1, -1));
EXPECT_EQ(changedTiles.rbegin()->first, TilePosition(11, 11));
for (const auto& [k, v] : changedTiles)
EXPECT_EQ(v, ChangeType::add) << k;
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, add_water_for_not_max_int_should_add_new_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 8192;
manager.addWater(cellPosition, cellSize, 0.0f, nullptr);
for (int x = -1; x < 12; ++x)
for (int y = -1; y < 12; ++y)
ASSERT_NE(manager.getMesh(mWorldspace, TilePosition(x, y)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, add_water_for_max_int_should_not_add_new_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
ASSERT_TRUE(manager.addObject(
ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
const osg::Vec2i cellPosition(0, 0);
const int cellSize = std::numeric_limits<int>::max();
manager.addWater(cellPosition, cellSize, 0.0f, nullptr);
for (int x = -6; x < 6; ++x)
for (int y = -6; y < 6; ++y)
ASSERT_EQ(manager.getMesh(mWorldspace, TilePosition(x, y)) != nullptr,
-1 <= x && x <= 0 && -1 <= y && y <= 0);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, remove_water_for_absent_cell_should_not_add_changed_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.removeWater(osg::Vec2i(0, 0), nullptr);
EXPECT_THAT(manager.takeChangedTiles(nullptr), ElementsAre());
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, remove_water_for_existing_cell_should_add_changed_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 8192;
manager.addWater(cellPosition, cellSize, 0.0f, nullptr);
manager.takeChangedTiles(nullptr);
manager.removeWater(cellPosition, nullptr);
const auto changedTiles = manager.takeChangedTiles(nullptr);
EXPECT_EQ(changedTiles.begin()->first, TilePosition(-1, -1));
EXPECT_EQ(changedTiles.rbegin()->first, TilePosition(11, 11));
for (const auto& [k, v] : changedTiles)
EXPECT_EQ(v, ChangeType::remove) << k;
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, remove_water_for_existing_cell_should_remove_empty_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 8192;
manager.addWater(cellPosition, cellSize, 0.0f, nullptr);
manager.removeWater(cellPosition, nullptr);
for (int x = -6; x < 6; ++x)
for (int y = -6; y < 6; ++y)
ASSERT_EQ(manager.getMesh(mWorldspace, TilePosition(x, y)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, remove_water_for_existing_cell_should_leave_not_empty_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
ASSERT_TRUE(manager.addObject(
ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 8192;
manager.addWater(cellPosition, cellSize, 0.0f, nullptr);
manager.removeWater(cellPosition, nullptr);
for (int x = -6; x < 6; ++x)
for (int y = -6; y < 6; ++y)
ASSERT_EQ(manager.getMesh(mWorldspace, TilePosition(x, y)) != nullptr,
-1 <= x && x <= 0 && -1 <= y && y <= 0);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, remove_object_should_not_remove_tile_with_water)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const osg::Vec2i cellPosition(0, 0);
const int cellSize = 8192;
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
ASSERT_TRUE(manager.addObject(
ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
manager.addWater(cellPosition, cellSize, 0.0f, nullptr);
manager.removeObject(ObjectId(&boxShape), nullptr);
for (int x = -1; x < 12; ++x)
for (int y = -1; y < 12; ++y)
ASSERT_NE(manager.getMesh(mWorldspace, TilePosition(x, y)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, set_new_worldspace_should_remove_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(nullptr, boxShape, mObjectTransform);
ASSERT_TRUE(manager.addObject(
ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr));
const ESM::RefId otherWorldspace(ESM::FormId::fromUint32(0x1));
manager.setWorldspace(ESM::FormId::fromUint32(0x1), nullptr);
for (int x = -1; x < 1; ++x)
for (int y = -1; y < 1; ++y)
ASSERT_EQ(manager.getMesh(otherWorldspace, TilePosition(x, y)), nullptr);
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, set_range_should_add_changed_tiles)
{
TileCachedRecastMeshManager manager(mSettings);
const btBoxShape boxShape(btVector3(20, 20, 100));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
const TilesPositionsRange range1{
.mBegin = TilePosition(0, 0),
.mEnd = TilePosition(1, 1),
};
manager.setRange(range1, nullptr);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
const TilesPositionsRange range2{
.mBegin = TilePosition(-1, -1),
.mEnd = TilePosition(0, 0),
};
manager.takeChangedTiles(nullptr);
manager.setRange(range2, nullptr);
EXPECT_THAT(manager.takeChangedTiles(nullptr),
ElementsAre(
std::pair(TilePosition(-1, -1), ChangeType::add), std::pair(TilePosition(0, 0), ChangeType::remove)));
}
TEST_F(DetourNavigatorTileCachedRecastMeshManagerTest, set_range_should_remove_cached_recast_meshes_outside_range)
{
TileCachedRecastMeshManager manager(mSettings);
manager.setWorldspace(mWorldspace, nullptr);
const btBoxShape boxShape(btVector3(100, 100, 20));
const CollisionShape shape(mInstance, boxShape, mObjectTransform);
const TilesPositionsRange range1{
.mBegin = TilePosition(0, 0),
.mEnd = TilePosition(1, 1),
};
manager.setRange(range1, nullptr);
manager.addObject(ObjectId(&boxShape), shape, btTransform::getIdentity(), AreaType::AreaType_ground, nullptr);
const TilePosition tilePosition(0, 0);
ASSERT_EQ(manager.getCachedMesh(mWorldspace, tilePosition), nullptr);
ASSERT_NE(manager.getMesh(mWorldspace, tilePosition), nullptr);
ASSERT_NE(manager.getCachedMesh(mWorldspace, tilePosition), nullptr);
const TilesPositionsRange range2{
.mBegin = TilePosition(-1, -1),
.mEnd = TilePosition(0, 0),
};
manager.takeChangedTiles(nullptr);
manager.setRange(range2, nullptr);
ASSERT_EQ(manager.getCachedMesh(mWorldspace, tilePosition), nullptr);
}
}
| 25,746
|
C++
|
.cpp
| 453
| 48.14128
| 120
| 0.700594
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,192
|
gettilespositions.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/gettilespositions.cpp
|
#include <components/detournavigator/debug.hpp>
#include <components/detournavigator/gettilespositions.hpp>
#include <components/detournavigator/settings.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace
{
using namespace testing;
using namespace DetourNavigator;
struct CollectTilesPositions
{
std::vector<TilePosition>& mTilesPositions;
void operator()(const TilePosition& value) { mTilesPositions.push_back(value); }
};
struct DetourNavigatorGetTilesPositionsTest : Test
{
RecastSettings mSettings;
std::vector<TilePosition> mTilesPositions;
CollectTilesPositions mCollect{ mTilesPositions };
DetourNavigatorGetTilesPositionsTest()
{
mSettings.mBorderSize = 0;
mSettings.mCellSize = 0.5;
mSettings.mRecastScaleFactor = 1;
mSettings.mTileSize = 64;
}
};
TEST_F(DetourNavigatorGetTilesPositionsTest, for_object_in_single_tile_should_return_one_tile)
{
getTilesPositions(makeTilesPositionsRange(osg::Vec2f(2, 2), osg::Vec2f(31, 31), mSettings), mCollect);
EXPECT_THAT(mTilesPositions, ElementsAre(TilePosition(0, 0)));
}
TEST_F(DetourNavigatorGetTilesPositionsTest, for_object_with_x_bounds_in_two_tiles_should_return_two_tiles)
{
getTilesPositions(makeTilesPositionsRange(osg::Vec2f(0, 0), osg::Vec2f(32, 31), mSettings), mCollect);
EXPECT_THAT(mTilesPositions, ElementsAre(TilePosition(0, 0), TilePosition(1, 0)));
}
TEST_F(DetourNavigatorGetTilesPositionsTest, for_object_with_y_bounds_in_two_tiles_should_return_two_tiles)
{
getTilesPositions(makeTilesPositionsRange(osg::Vec2f(0, 0), osg::Vec2f(31, 32), mSettings), mCollect);
EXPECT_THAT(mTilesPositions, ElementsAre(TilePosition(0, 0), TilePosition(0, 1)));
}
TEST_F(DetourNavigatorGetTilesPositionsTest, tiling_works_only_for_x_and_y_coordinates)
{
getTilesPositions(makeTilesPositionsRange(osg::Vec2f(0, 0), osg::Vec2f(31, 31), mSettings), mCollect);
EXPECT_THAT(mTilesPositions, ElementsAre(TilePosition(0, 0)));
}
TEST_F(DetourNavigatorGetTilesPositionsTest, tiling_should_work_with_negative_coordinates)
{
getTilesPositions(makeTilesPositionsRange(osg::Vec2f(-31, -31), osg::Vec2f(31, 31), mSettings), mCollect);
EXPECT_THAT(mTilesPositions,
ElementsAre(TilePosition(-1, -1), TilePosition(-1, 0), TilePosition(0, -1), TilePosition(0, 0)));
}
TEST_F(DetourNavigatorGetTilesPositionsTest, border_size_should_extend_tile_bounds)
{
mSettings.mBorderSize = 1;
getTilesPositions(makeTilesPositionsRange(osg::Vec2f(0, 0), osg::Vec2f(31.5, 31.5), mSettings), mCollect);
EXPECT_THAT(mTilesPositions,
ElementsAre(TilePosition(-1, -1), TilePosition(-1, 0), TilePosition(-1, 1), TilePosition(0, -1),
TilePosition(0, 0), TilePosition(0, 1), TilePosition(1, -1), TilePosition(1, 0), TilePosition(1, 1)));
}
TEST_F(DetourNavigatorGetTilesPositionsTest, should_apply_recast_scale_factor)
{
mSettings.mRecastScaleFactor = 0.5;
getTilesPositions(makeTilesPositionsRange(osg::Vec2f(0, 0), osg::Vec2f(32, 32), mSettings), mCollect);
EXPECT_THAT(mTilesPositions, ElementsAre(TilePosition(0, 0)));
}
struct TilesPositionsRangeParams
{
TilesPositionsRange mA;
TilesPositionsRange mB;
TilesPositionsRange mResult;
};
struct DetourNavigatorGetIntersectionTest : TestWithParam<TilesPositionsRangeParams>
{
};
TEST_P(DetourNavigatorGetIntersectionTest, should_return_expected_result)
{
EXPECT_EQ(getIntersection(GetParam().mA, GetParam().mB), GetParam().mResult);
EXPECT_EQ(getIntersection(GetParam().mB, GetParam().mA), GetParam().mResult);
}
const TilesPositionsRangeParams getIntersectionParams[] = {
{ .mA = TilesPositionsRange{}, .mB = TilesPositionsRange{}, .mResult = TilesPositionsRange{} },
{
.mA = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 2, 2 } },
.mB = TilesPositionsRange{ .mBegin = TilePosition{ 1, 1 }, .mEnd = TilePosition{ 3, 3 } },
.mResult = TilesPositionsRange{ .mBegin = TilePosition{ 1, 1 }, .mEnd = TilePosition{ 2, 2 } },
},
{
.mA = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 1, 1 } },
.mB = TilesPositionsRange{ .mBegin = TilePosition{ 2, 2 }, .mEnd = TilePosition{ 3, 3 } },
.mResult = TilesPositionsRange{},
},
{
.mA = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 1, 1 } },
.mB = TilesPositionsRange{ .mBegin = TilePosition{ 1, 1 }, .mEnd = TilePosition{ 2, 2 } },
.mResult = TilesPositionsRange{ .mBegin = TilePosition{ 1, 1 }, .mEnd = TilePosition{ 1, 1 } },
},
{
.mA = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 1, 1 } },
.mB = TilesPositionsRange{ .mBegin = TilePosition{ 0, 2 }, .mEnd = TilePosition{ 3, 3 } },
.mResult = TilesPositionsRange{},
},
{
.mA = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 1, 1 } },
.mB = TilesPositionsRange{ .mBegin = TilePosition{ 2, 0 }, .mEnd = TilePosition{ 3, 3 } },
.mResult = TilesPositionsRange{},
},
};
INSTANTIATE_TEST_SUITE_P(
GetIntersectionParams, DetourNavigatorGetIntersectionTest, ValuesIn(getIntersectionParams));
struct DetourNavigatorGetUnionTest : TestWithParam<TilesPositionsRangeParams>
{
};
TEST_P(DetourNavigatorGetUnionTest, should_return_expected_result)
{
EXPECT_EQ(getUnion(GetParam().mA, GetParam().mB), GetParam().mResult);
EXPECT_EQ(getUnion(GetParam().mB, GetParam().mA), GetParam().mResult);
}
const TilesPositionsRangeParams getUnionParams[] = {
{ .mA = TilesPositionsRange{}, .mB = TilesPositionsRange{}, .mResult = TilesPositionsRange{} },
{
.mA = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 2, 2 } },
.mB = TilesPositionsRange{ .mBegin = TilePosition{ 1, 1 }, .mEnd = TilePosition{ 3, 3 } },
.mResult = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 3, 3 } },
},
{
.mA = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 1, 1 } },
.mB = TilesPositionsRange{ .mBegin = TilePosition{ 1, 1 }, .mEnd = TilePosition{ 2, 2 } },
.mResult = TilesPositionsRange{ .mBegin = TilePosition{ 0, 0 }, .mEnd = TilePosition{ 2, 2 } },
},
};
INSTANTIATE_TEST_SUITE_P(GetUnionParams, DetourNavigatorGetUnionTest, ValuesIn(getUnionParams));
}
| 6,969
|
C++
|
.cpp
| 134
| 43.880597
| 118
| 0.660935
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,193
|
navmeshtilescache.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/navmeshtilescache.cpp
|
#include "generate.hpp"
#include <components/detournavigator/navmeshtilescache.hpp>
#include <components/detournavigator/preparednavmeshdata.hpp>
#include <components/detournavigator/recast.hpp>
#include <components/detournavigator/recastmesh.hpp>
#include <osg/Vec3f>
#include <RecastAlloc.h>
#include <gtest/gtest.h>
#include <random>
#include <stdexcept>
namespace
{
using namespace testing;
using namespace DetourNavigator;
using namespace DetourNavigator::Tests;
template <class T, class Random>
void generateRecastArray(T*& values, int size, Random& random)
{
values = static_cast<T*>(permRecastAlloc(size * sizeof(T)));
generateRange(values, values + static_cast<std::ptrdiff_t>(size), random);
}
template <class Random>
void generate(rcPolyMesh& value, int size, Random& random)
{
value.nverts = size;
value.maxpolys = size;
value.nvp = size;
value.npolys = size;
rcVcopy(value.bmin, osg::Vec3f(-1, -2, -3).ptr());
rcVcopy(value.bmax, osg::Vec3f(3, 2, 1).ptr());
generateValue(value.cs, random);
generateValue(value.ch, random);
generateValue(value.borderSize, random);
generateValue(value.maxEdgeError, random);
generateRecastArray(value.verts, getVertsLength(value), random);
generateRecastArray(value.polys, getPolysLength(value), random);
generateRecastArray(value.regs, getRegsLength(value), random);
generateRecastArray(value.flags, getFlagsLength(value), random);
generateRecastArray(value.areas, getAreasLength(value), random);
}
template <class Random>
void generate(rcPolyMeshDetail& value, int size, Random& random)
{
value.nmeshes = size;
value.nverts = size;
value.ntris = size;
generateRecastArray(value.meshes, getMeshesLength(value), random);
generateRecastArray(value.verts, getVertsLength(value), random);
generateRecastArray(value.tris, getTrisLength(value), random);
}
template <class Random>
void generate(PreparedNavMeshData& value, int size, Random& random)
{
generateValue(value.mUserId, random);
generateValue(value.mCellHeight, random);
generateValue(value.mCellSize, random);
generate(value.mPolyMesh, size, random);
generate(value.mPolyMeshDetail, size, random);
}
std::unique_ptr<PreparedNavMeshData> makePeparedNavMeshData(int size)
{
std::minstd_rand random;
auto result = std::make_unique<PreparedNavMeshData>();
generate(*result, size, random);
return result;
}
std::unique_ptr<PreparedNavMeshData> clone(const PreparedNavMeshData& value)
{
return std::make_unique<PreparedNavMeshData>(value);
}
Mesh makeMesh()
{
std::vector<int> indices{ { 0, 1, 2 } };
std::vector<float> vertices{ { 0, 0, 0, 1, 0, 0, 1, 1, 0 } };
std::vector<AreaType> areaTypes{ 1, AreaType_ground };
return Mesh(std::move(indices), std::move(vertices), std::move(areaTypes));
}
struct DetourNavigatorNavMeshTilesCacheTest : Test
{
const AgentBounds mAgentBounds{ CollisionShapeType::Aabb, { 1, 2, 3 } };
const TilePosition mTilePosition{ 0, 0 };
const Version mVersion{ 0, 0 };
const Mesh mMesh{ makeMesh() };
const std::vector<CellWater> mWater{};
const std::vector<Heightfield> mHeightfields{};
const std::vector<FlatHeightfield> mFlatHeightfields{};
const std::vector<MeshSource> mSources{};
const RecastMesh mRecastMesh{ mVersion, mMesh, mWater, mHeightfields, mFlatHeightfields, mSources };
std::unique_ptr<PreparedNavMeshData> mPreparedNavMeshData{ makePeparedNavMeshData(3) };
const std::size_t mRecastMeshSize = sizeof(mRecastMesh) + getSize(mRecastMesh);
const std::size_t mRecastMeshWithWaterSize = mRecastMeshSize + sizeof(CellWater);
const std::size_t mPreparedNavMeshDataSize = sizeof(*mPreparedNavMeshData) + getSize(*mPreparedNavMeshData);
};
TEST_F(DetourNavigatorNavMeshTilesCacheTest, get_for_empty_cache_should_return_empty_value)
{
const std::size_t maxSize = 0;
NavMeshTilesCache cache(maxSize);
EXPECT_FALSE(cache.get(mAgentBounds, mTilePosition, mRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, set_for_not_enought_cache_size_should_return_empty_value)
{
const std::size_t maxSize = 0;
NavMeshTilesCache cache(maxSize);
EXPECT_FALSE(cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData)));
EXPECT_NE(mPreparedNavMeshData, nullptr);
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, set_should_return_cached_value)
{
const std::size_t maxSize = mRecastMeshSize + mPreparedNavMeshDataSize;
NavMeshTilesCache cache(maxSize);
const auto copy = clone(*mPreparedNavMeshData);
ASSERT_EQ(*mPreparedNavMeshData, *copy);
const auto result = cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
ASSERT_TRUE(result);
EXPECT_EQ(result.get(), *copy);
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, set_existing_element_should_return_cached_element)
{
const std::size_t maxSize = 2 * (mRecastMeshSize + mPreparedNavMeshDataSize);
NavMeshTilesCache cache(maxSize);
auto copy = clone(*mPreparedNavMeshData);
const auto sameCopy = clone(*mPreparedNavMeshData);
cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
EXPECT_EQ(mPreparedNavMeshData, nullptr);
const auto result = cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(copy));
ASSERT_TRUE(result);
EXPECT_EQ(result.get(), *sameCopy);
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, get_should_return_cached_value)
{
const std::size_t maxSize = mRecastMeshSize + mPreparedNavMeshDataSize;
NavMeshTilesCache cache(maxSize);
const auto copy = clone(*mPreparedNavMeshData);
cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
const auto result = cache.get(mAgentBounds, mTilePosition, mRecastMesh);
ASSERT_TRUE(result);
EXPECT_EQ(result.get(), *copy);
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, get_for_cache_miss_by_agent_half_extents_should_return_empty_value)
{
const std::size_t maxSize = 1;
NavMeshTilesCache cache(maxSize);
const AgentBounds absentAgentBounds{ CollisionShapeType::Aabb, { 1, 1, 1 } };
cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
EXPECT_FALSE(cache.get(absentAgentBounds, mTilePosition, mRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, get_for_cache_miss_by_tile_position_should_return_empty_value)
{
const std::size_t maxSize = 1;
NavMeshTilesCache cache(maxSize);
const TilePosition unexistentTilePosition{ 1, 1 };
cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
EXPECT_FALSE(cache.get(mAgentBounds, unexistentTilePosition, mRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, get_for_cache_miss_by_recast_mesh_should_return_empty_value)
{
const std::size_t maxSize = 1;
NavMeshTilesCache cache(maxSize);
const std::vector<CellWater> water(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh unexistentRecastMesh(mVersion, mMesh, water, mHeightfields, mFlatHeightfields, mSources);
cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
EXPECT_FALSE(cache.get(mAgentBounds, mTilePosition, unexistentRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, set_should_replace_unused_value)
{
const std::size_t maxSize = mRecastMeshWithWaterSize + mPreparedNavMeshDataSize;
NavMeshTilesCache cache(maxSize);
const std::vector<CellWater> water(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh anotherRecastMesh(mVersion, mMesh, water, mHeightfields, mFlatHeightfields, mSources);
auto anotherPreparedNavMeshData = makePeparedNavMeshData(3);
const auto copy = clone(*anotherPreparedNavMeshData);
cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
const auto result
= cache.set(mAgentBounds, mTilePosition, anotherRecastMesh, std::move(anotherPreparedNavMeshData));
ASSERT_TRUE(result);
EXPECT_EQ(result.get(), *copy);
EXPECT_FALSE(cache.get(mAgentBounds, mTilePosition, mRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, set_should_not_replace_used_value)
{
const std::size_t maxSize = mRecastMeshWithWaterSize + mPreparedNavMeshDataSize;
NavMeshTilesCache cache(maxSize);
const std::vector<CellWater> water(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh anotherRecastMesh(mVersion, mMesh, water, mHeightfields, mFlatHeightfields, mSources);
auto anotherPreparedNavMeshData = makePeparedNavMeshData(3);
const auto value = cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
EXPECT_FALSE(cache.set(mAgentBounds, mTilePosition, anotherRecastMesh, std::move(anotherPreparedNavMeshData)));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, set_should_replace_unused_least_recently_set_value)
{
const std::size_t maxSize = 2 * (mRecastMeshWithWaterSize + mPreparedNavMeshDataSize);
NavMeshTilesCache cache(maxSize);
const auto copy = clone(*mPreparedNavMeshData);
const std::vector<CellWater> leastRecentlySetWater(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh leastRecentlySetRecastMesh(
mVersion, mMesh, leastRecentlySetWater, mHeightfields, mFlatHeightfields, mSources);
auto leastRecentlySetData = makePeparedNavMeshData(3);
const std::vector<CellWater> mostRecentlySetWater(1, CellWater{ osg::Vec2i(), Water{ 2, 0.0f } });
const RecastMesh mostRecentlySetRecastMesh(
mVersion, mMesh, mostRecentlySetWater, mHeightfields, mFlatHeightfields, mSources);
auto mostRecentlySetData = makePeparedNavMeshData(3);
ASSERT_TRUE(
cache.set(mAgentBounds, mTilePosition, leastRecentlySetRecastMesh, std::move(leastRecentlySetData)));
ASSERT_TRUE(cache.set(mAgentBounds, mTilePosition, mostRecentlySetRecastMesh, std::move(mostRecentlySetData)));
const auto result = cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
EXPECT_EQ(result.get(), *copy);
EXPECT_FALSE(cache.get(mAgentBounds, mTilePosition, leastRecentlySetRecastMesh));
EXPECT_TRUE(cache.get(mAgentBounds, mTilePosition, mostRecentlySetRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, set_should_replace_unused_least_recently_used_value)
{
const std::size_t maxSize = 2 * (mRecastMeshWithWaterSize + mPreparedNavMeshDataSize);
NavMeshTilesCache cache(maxSize);
const std::vector<CellWater> leastRecentlyUsedWater(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh leastRecentlyUsedRecastMesh(
mVersion, mMesh, leastRecentlyUsedWater, mHeightfields, mFlatHeightfields, mSources);
auto leastRecentlyUsedData = makePeparedNavMeshData(3);
const auto leastRecentlyUsedCopy = clone(*leastRecentlyUsedData);
const std::vector<CellWater> mostRecentlyUsedWater(1, CellWater{ osg::Vec2i(), Water{ 2, 0.0f } });
const RecastMesh mostRecentlyUsedRecastMesh(
mVersion, mMesh, mostRecentlyUsedWater, mHeightfields, mFlatHeightfields, mSources);
auto mostRecentlyUsedData = makePeparedNavMeshData(3);
const auto mostRecentlyUsedCopy = clone(*mostRecentlyUsedData);
cache.set(mAgentBounds, mTilePosition, leastRecentlyUsedRecastMesh, std::move(leastRecentlyUsedData));
cache.set(mAgentBounds, mTilePosition, mostRecentlyUsedRecastMesh, std::move(mostRecentlyUsedData));
{
const auto value = cache.get(mAgentBounds, mTilePosition, leastRecentlyUsedRecastMesh);
ASSERT_TRUE(value);
ASSERT_EQ(value.get(), *leastRecentlyUsedCopy);
}
{
const auto value = cache.get(mAgentBounds, mTilePosition, mostRecentlyUsedRecastMesh);
ASSERT_TRUE(value);
ASSERT_EQ(value.get(), *mostRecentlyUsedCopy);
}
const auto copy = clone(*mPreparedNavMeshData);
const auto result = cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
EXPECT_EQ(result.get(), *copy);
EXPECT_FALSE(cache.get(mAgentBounds, mTilePosition, leastRecentlyUsedRecastMesh));
EXPECT_TRUE(cache.get(mAgentBounds, mTilePosition, mostRecentlyUsedRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest,
set_should_not_replace_unused_least_recently_used_value_when_item_does_not_not_fit_cache_max_size)
{
const std::size_t maxSize = 2 * (mRecastMeshWithWaterSize + mPreparedNavMeshDataSize);
NavMeshTilesCache cache(maxSize);
const std::vector<CellWater> water(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh tooLargeRecastMesh(mVersion, mMesh, water, mHeightfields, mFlatHeightfields, mSources);
auto tooLargeData = makePeparedNavMeshData(10);
cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
EXPECT_FALSE(cache.set(mAgentBounds, mTilePosition, tooLargeRecastMesh, std::move(tooLargeData)));
EXPECT_TRUE(cache.get(mAgentBounds, mTilePosition, mRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest,
set_should_not_replace_unused_least_recently_used_value_when_item_does_not_not_fit_size_of_unused_items)
{
const std::size_t maxSize = 2 * (mRecastMeshWithWaterSize + mPreparedNavMeshDataSize);
NavMeshTilesCache cache(maxSize);
const std::vector<CellWater> anotherWater(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh anotherRecastMesh(mVersion, mMesh, anotherWater, mHeightfields, mFlatHeightfields, mSources);
auto anotherData = makePeparedNavMeshData(3);
const std::vector<CellWater> tooLargeWater(1, CellWater{ osg::Vec2i(), Water{ 2, 0.0f } });
const RecastMesh tooLargeRecastMesh(mVersion, mMesh, tooLargeWater, mHeightfields, mFlatHeightfields, mSources);
auto tooLargeData = makePeparedNavMeshData(10);
const auto value = cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
ASSERT_TRUE(value);
ASSERT_TRUE(cache.set(mAgentBounds, mTilePosition, anotherRecastMesh, std::move(anotherData)));
EXPECT_FALSE(cache.set(mAgentBounds, mTilePosition, tooLargeRecastMesh, std::move(tooLargeData)));
EXPECT_TRUE(cache.get(mAgentBounds, mTilePosition, mRecastMesh));
EXPECT_TRUE(cache.get(mAgentBounds, mTilePosition, anotherRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest,
release_used_after_set_then_used_by_get_item_should_left_this_item_available)
{
const std::size_t maxSize = mRecastMeshWithWaterSize + mPreparedNavMeshDataSize;
NavMeshTilesCache cache(maxSize);
const std::vector<CellWater> water(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh anotherRecastMesh(mVersion, mMesh, water, mHeightfields, mFlatHeightfields, mSources);
auto anotherData = makePeparedNavMeshData(3);
const auto firstCopy = cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
ASSERT_TRUE(firstCopy);
{
const auto secondCopy = cache.get(mAgentBounds, mTilePosition, mRecastMesh);
ASSERT_TRUE(secondCopy);
}
EXPECT_FALSE(cache.set(mAgentBounds, mTilePosition, anotherRecastMesh, std::move(anotherData)));
EXPECT_TRUE(cache.get(mAgentBounds, mTilePosition, mRecastMesh));
}
TEST_F(DetourNavigatorNavMeshTilesCacheTest, release_twice_used_item_should_left_this_item_available)
{
const std::size_t maxSize = mRecastMeshWithWaterSize + mPreparedNavMeshDataSize;
NavMeshTilesCache cache(maxSize);
const std::vector<CellWater> water(1, CellWater{ osg::Vec2i(), Water{ 1, 0.0f } });
const RecastMesh anotherRecastMesh(mVersion, mMesh, water, mHeightfields, mFlatHeightfields, mSources);
auto anotherData = makePeparedNavMeshData(3);
cache.set(mAgentBounds, mTilePosition, mRecastMesh, std::move(mPreparedNavMeshData));
const auto firstCopy = cache.get(mAgentBounds, mTilePosition, mRecastMesh);
ASSERT_TRUE(firstCopy);
{
const auto secondCopy = cache.get(mAgentBounds, mTilePosition, mRecastMesh);
ASSERT_TRUE(secondCopy);
}
EXPECT_FALSE(cache.set(mAgentBounds, mTilePosition, anotherRecastMesh, std::move(anotherData)));
EXPECT_TRUE(cache.get(mAgentBounds, mTilePosition, mRecastMesh));
}
}
| 17,500
|
C++
|
.cpp
| 306
| 49.143791
| 120
| 0.717455
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,194
|
asyncnavmeshupdater.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/asyncnavmeshupdater.cpp
|
#include "settings.hpp"
#include <components/detournavigator/asyncnavmeshupdater.hpp>
#include <components/detournavigator/dbrefgeometryobject.hpp>
#include <components/detournavigator/makenavmesh.hpp>
#include <components/detournavigator/navmeshdbutils.hpp>
#include <components/detournavigator/serialization.hpp>
#include <components/loadinglistener/loadinglistener.hpp>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <DetourNavMesh.h>
#include <gtest/gtest.h>
#include <limits>
#include <map>
namespace
{
using namespace testing;
using namespace DetourNavigator;
using namespace DetourNavigator::Tests;
void addHeightFieldPlane(
TileCachedRecastMeshManager& recastMeshManager, const osg::Vec2i cellPosition = osg::Vec2i(0, 0))
{
const int cellSize = 8192;
recastMeshManager.addHeightfield(cellPosition, cellSize, HeightfieldPlane{ 0 }, nullptr);
}
void addObject(const btBoxShape& shape, TileCachedRecastMeshManager& recastMeshManager)
{
const ObjectId id(&shape);
osg::ref_ptr<Resource::BulletShape> bulletShape(new Resource::BulletShape);
constexpr VFS::Path::NormalizedView test("test.nif");
bulletShape->mFileName = test;
bulletShape->mFileHash = "test_hash";
ObjectTransform objectTransform;
std::fill(std::begin(objectTransform.mPosition.pos), std::end(objectTransform.mPosition.pos), 0.1f);
std::fill(std::begin(objectTransform.mPosition.rot), std::end(objectTransform.mPosition.rot), 0.2f);
objectTransform.mScale = 3.14f;
const CollisionShape collisionShape(
osg::ref_ptr<Resource::BulletShapeInstance>(new Resource::BulletShapeInstance(bulletShape)), shape,
objectTransform);
recastMeshManager.addObject(id, collisionShape, btTransform::getIdentity(), AreaType_ground, nullptr);
}
struct DetourNavigatorAsyncNavMeshUpdaterTest : Test
{
Settings mSettings = makeSettings();
TileCachedRecastMeshManager mRecastMeshManager{ mSettings.mRecast };
OffMeshConnectionsManager mOffMeshConnectionsManager{ mSettings.mRecast };
const AgentBounds mAgentBounds{ CollisionShapeType::Aabb, { 29, 29, 66 } };
const TilePosition mPlayerTile{ 0, 0 };
const ESM::RefId mWorldspace = ESM::RefId::stringRefId("sys::default");
const btBoxShape mBox{ btVector3(100, 100, 20) };
Loading::Listener mListener;
};
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, for_all_jobs_done_when_empty_wait_should_terminate)
{
AsyncNavMeshUpdater updater{ mSettings, mRecastMeshManager, mOffMeshConnectionsManager, nullptr };
updater.wait(WaitConditionType::allJobsDone, &mListener);
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, for_required_tiles_present_when_empty_wait_should_terminate)
{
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, nullptr);
updater.wait(WaitConditionType::requiredTilesPresent, &mListener);
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, post_should_generate_navmesh_tile)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, nullptr);
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const std::map<TilePosition, ChangeType> changedTiles{ { TilePosition{ 0, 0 }, ChangeType::add } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_NE(navMeshCacheItem->lockConst()->getImpl().getTileRefAt(0, 0, 0), 0u);
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, repeated_post_should_lead_to_cache_hit)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, nullptr);
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const std::map<TilePosition, ChangeType> changedTiles{ { TilePosition{ 0, 0 }, ChangeType::add } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
{
const auto stats = updater.getStats();
ASSERT_EQ(stats.mCache.mGetCount, 1);
ASSERT_EQ(stats.mCache.mHitCount, 0);
}
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
{
const auto stats = updater.getStats();
EXPECT_EQ(stats.mCache.mGetCount, 2);
EXPECT_EQ(stats.mCache.mHitCount, 1);
}
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, post_for_update_change_type_should_not_update_cache)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, nullptr);
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const std::map<TilePosition, ChangeType> changedTiles{ { TilePosition{ 0, 0 }, ChangeType::update } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
{
const auto stats = updater.getStats();
ASSERT_EQ(stats.mCache.mGetCount, 1);
ASSERT_EQ(stats.mCache.mHitCount, 0);
}
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
{
const auto stats = updater.getStats();
EXPECT_EQ(stats.mCache.mGetCount, 2);
EXPECT_EQ(stats.mCache.mHitCount, 0);
}
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, post_should_write_generated_tile_to_db)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
addObject(mBox, mRecastMeshManager);
auto db = std::make_unique<NavMeshDb>(":memory:", std::numeric_limits<std::uint64_t>::max());
NavMeshDb* const dbPtr = db.get();
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, std::move(db));
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const TilePosition tilePosition{ 0, 0 };
const std::map<TilePosition, ChangeType> changedTiles{ { tilePosition, ChangeType::add } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
updater.stop();
const auto recastMesh = mRecastMeshManager.getMesh(mWorldspace, tilePosition);
ASSERT_NE(recastMesh, nullptr);
ShapeId nextShapeId{ 1 };
const std::vector<DbRefGeometryObject> objects = makeDbRefGeometryObjects(recastMesh->getMeshSources(),
[&](const MeshSource& v) { return resolveMeshSource(*dbPtr, v, nextShapeId); });
const auto tile = dbPtr->findTile(
mWorldspace, tilePosition, serialize(mSettings.mRecast, mAgentBounds, *recastMesh, objects));
ASSERT_TRUE(tile.has_value());
EXPECT_EQ(tile->mTileId, 1);
EXPECT_EQ(tile->mVersion, navMeshFormatVersion);
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, post_when_writing_to_db_disabled_should_not_write_tiles)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
addObject(mBox, mRecastMeshManager);
auto db = std::make_unique<NavMeshDb>(":memory:", std::numeric_limits<std::uint64_t>::max());
NavMeshDb* const dbPtr = db.get();
mSettings.mWriteToNavMeshDb = false;
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, std::move(db));
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const TilePosition tilePosition{ 0, 0 };
const std::map<TilePosition, ChangeType> changedTiles{ { tilePosition, ChangeType::add } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
updater.stop();
const auto recastMesh = mRecastMeshManager.getMesh(mWorldspace, tilePosition);
ASSERT_NE(recastMesh, nullptr);
ShapeId nextShapeId{ 1 };
const std::vector<DbRefGeometryObject> objects = makeDbRefGeometryObjects(recastMesh->getMeshSources(),
[&](const MeshSource& v) { return resolveMeshSource(*dbPtr, v, nextShapeId); });
const auto tile = dbPtr->findTile(
mWorldspace, tilePosition, serialize(mSettings.mRecast, mAgentBounds, *recastMesh, objects));
ASSERT_FALSE(tile.has_value());
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, post_when_writing_to_db_disabled_should_not_write_shapes)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
addObject(mBox, mRecastMeshManager);
auto db = std::make_unique<NavMeshDb>(":memory:", std::numeric_limits<std::uint64_t>::max());
NavMeshDb* const dbPtr = db.get();
mSettings.mWriteToNavMeshDb = false;
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, std::move(db));
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const TilePosition tilePosition{ 0, 0 };
const std::map<TilePosition, ChangeType> changedTiles{ { tilePosition, ChangeType::add } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
updater.stop();
const auto recastMesh = mRecastMeshManager.getMesh(mWorldspace, tilePosition);
ASSERT_NE(recastMesh, nullptr);
const auto objects = makeDbRefGeometryObjects(
recastMesh->getMeshSources(), [&](const MeshSource& v) { return resolveMeshSource(*dbPtr, v); });
EXPECT_TRUE(std::holds_alternative<MeshSource>(objects));
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, post_should_read_from_db_on_cache_miss)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
mSettings.mMaxNavMeshTilesCacheSize = 0;
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager,
std::make_unique<NavMeshDb>(":memory:", std::numeric_limits<std::uint64_t>::max()));
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const std::map<TilePosition, ChangeType> changedTiles{ { TilePosition{ 0, 0 }, ChangeType::add } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
{
const auto stats = updater.getStats();
ASSERT_EQ(stats.mCache.mGetCount, 1);
ASSERT_EQ(stats.mCache.mHitCount, 0);
ASSERT_TRUE(stats.mDb.has_value());
ASSERT_EQ(stats.mDb->mGetTileCount, 1);
ASSERT_EQ(stats.mDbGetTileHits, 0);
}
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
{
const auto stats = updater.getStats();
EXPECT_EQ(stats.mCache.mGetCount, 2);
EXPECT_EQ(stats.mCache.mHitCount, 0);
ASSERT_TRUE(stats.mDb.has_value());
EXPECT_EQ(stats.mDb->mGetTileCount, 2);
EXPECT_EQ(stats.mDbGetTileHits, 1);
}
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, on_changing_player_tile_post_should_remove_tiles_out_of_range)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, nullptr);
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const std::map<TilePosition, ChangeType> changedTilesAdd{ { TilePosition{ 0, 0 }, ChangeType::add } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTilesAdd);
updater.wait(WaitConditionType::allJobsDone, &mListener);
ASSERT_NE(navMeshCacheItem->lockConst()->getImpl().getTileRefAt(0, 0, 0), 0u);
const std::map<TilePosition, ChangeType> changedTilesRemove{ { TilePosition{ 0, 0 }, ChangeType::remove } };
const TilePosition playerTile(100, 100);
updater.post(mAgentBounds, navMeshCacheItem, playerTile, mWorldspace, changedTilesRemove);
updater.wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(navMeshCacheItem->lockConst()->getImpl().getTileRefAt(0, 0, 0), 0u);
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, should_stop_writing_to_db_when_size_limit_is_reached)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
for (int x = -1; x <= 1; ++x)
for (int y = -1; y <= 1; ++y)
addHeightFieldPlane(mRecastMeshManager, osg::Vec2i(x, y));
addObject(mBox, mRecastMeshManager);
auto db = std::make_unique<NavMeshDb>(":memory:", 4097);
NavMeshDb* const dbPtr = db.get();
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, std::move(db));
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
std::map<TilePosition, ChangeType> changedTiles;
for (int x = -5; x <= 5; ++x)
for (int y = -5; y <= 5; ++y)
changedTiles.emplace(TilePosition{ x, y }, ChangeType::add);
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
updater.stop();
std::size_t present = 0;
for (int x = -5; x <= 5; ++x)
{
for (int y = -5; y <= 5; ++y)
{
const TilePosition tilePosition(x, y);
const auto recastMesh = mRecastMeshManager.getMesh(mWorldspace, tilePosition);
ASSERT_NE(recastMesh, nullptr);
const auto objects = makeDbRefGeometryObjects(
recastMesh->getMeshSources(), [&](const MeshSource& v) { return resolveMeshSource(*dbPtr, v); });
if (std::holds_alternative<MeshSource>(objects))
continue;
present += dbPtr
->findTile(mWorldspace, tilePosition,
serialize(mSettings.mRecast, mAgentBounds, *recastMesh,
std::get<std::vector<DbRefGeometryObject>>(objects)))
.has_value();
}
}
EXPECT_EQ(present, 11);
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, next_tile_id_should_be_updated_on_duplicate)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
addHeightFieldPlane(mRecastMeshManager);
addObject(mBox, mRecastMeshManager);
auto db = std::make_unique<NavMeshDb>(":memory:", std::numeric_limits<std::uint64_t>::max());
NavMeshDb* const dbPtr = db.get();
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, std::move(db));
const TileId nextTileId(dbPtr->getMaxTileId() + 1);
ASSERT_EQ(dbPtr->insertTile(nextTileId, mWorldspace, TilePosition{}, TileVersion{ 1 }, {}, {}), 1);
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
const TilePosition tilePosition{ 0, 0 };
const std::map<TilePosition, ChangeType> changedTiles{ { tilePosition, ChangeType::add } };
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
const AgentBounds agentBounds{ CollisionShapeType::Cylinder, { 29, 29, 66 } };
updater.post(agentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
updater.stop();
const auto recastMesh = mRecastMeshManager.getMesh(mWorldspace, tilePosition);
ASSERT_NE(recastMesh, nullptr);
ShapeId nextShapeId{ 1 };
const std::vector<DbRefGeometryObject> objects = makeDbRefGeometryObjects(recastMesh->getMeshSources(),
[&](const MeshSource& v) { return resolveMeshSource(*dbPtr, v, nextShapeId); });
const auto tile = dbPtr->findTile(
mWorldspace, tilePosition, serialize(mSettings.mRecast, agentBounds, *recastMesh, objects));
ASSERT_TRUE(tile.has_value());
EXPECT_EQ(tile->mTileId, 2);
EXPECT_EQ(tile->mVersion, navMeshFormatVersion);
}
TEST_F(DetourNavigatorAsyncNavMeshUpdaterTest, repeated_tile_updates_should_be_delayed)
{
mRecastMeshManager.setWorldspace(mWorldspace, nullptr);
mSettings.mMaxTilesNumber = 9;
mSettings.mMinUpdateInterval = std::chrono::milliseconds(250);
AsyncNavMeshUpdater updater(mSettings, mRecastMeshManager, mOffMeshConnectionsManager, nullptr);
const auto navMeshCacheItem = std::make_shared<GuardedNavMeshCacheItem>(1, mSettings);
std::map<TilePosition, ChangeType> changedTiles;
for (int x = -3; x <= 3; ++x)
for (int y = -3; y <= 3; ++y)
changedTiles.emplace(TilePosition{ x, y }, ChangeType::update);
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
updater.wait(WaitConditionType::allJobsDone, &mListener);
{
const AsyncNavMeshUpdaterStats stats = updater.getStats();
EXPECT_EQ(stats.mJobs, 0);
EXPECT_EQ(stats.mWaiting.mDelayed, 0);
}
updater.post(mAgentBounds, navMeshCacheItem, mPlayerTile, mWorldspace, changedTiles);
{
const AsyncNavMeshUpdaterStats stats = updater.getStats();
EXPECT_EQ(stats.mJobs, 49);
EXPECT_EQ(stats.mWaiting.mDelayed, 49);
}
updater.wait(WaitConditionType::allJobsDone, &mListener);
{
const AsyncNavMeshUpdaterStats stats = updater.getStats();
EXPECT_EQ(stats.mJobs, 0);
EXPECT_EQ(stats.mWaiting.mDelayed, 0);
}
}
struct DetourNavigatorSpatialJobQueueTest : Test
{
const AgentBounds mAgentBounds{ CollisionShapeType::Aabb, osg::Vec3f(1, 1, 1) };
const std::shared_ptr<GuardedNavMeshCacheItem> mNavMeshCacheItemPtr;
const std::weak_ptr<GuardedNavMeshCacheItem> mNavMeshCacheItem = mNavMeshCacheItemPtr;
const ESM::RefId mWorldspace = ESM::RefId::stringRefId("worldspace");
const TilePosition mChangedTile{ 0, 0 };
const std::chrono::steady_clock::time_point mProcessTime{};
const TilePosition mPlayerTile{ 0, 0 };
const int mMaxTiles = 9;
};
TEST_F(DetourNavigatorSpatialJobQueueTest, should_store_multiple_jobs_per_tile)
{
std::list<Job> jobs;
SpatialJobQueue queue;
const ESM::RefId worldspace1 = ESM::RefId::stringRefId("worldspace1");
const ESM::RefId worldspace2 = ESM::RefId::stringRefId("worldspace2");
queue.push(jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, worldspace1, mChangedTile, ChangeType::remove, mProcessTime));
queue.push(jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, worldspace2, mChangedTile, ChangeType::update, mProcessTime));
ASSERT_EQ(queue.size(), 2);
const auto job1 = queue.pop(mChangedTile);
ASSERT_TRUE(job1.has_value());
EXPECT_EQ((*job1)->mWorldspace, worldspace1);
const auto job2 = queue.pop(mChangedTile);
ASSERT_TRUE(job2.has_value());
EXPECT_EQ((*job2)->mWorldspace, worldspace2);
EXPECT_EQ(queue.size(), 0);
}
struct DetourNavigatorJobQueueTest : DetourNavigatorSpatialJobQueueTest
{
};
TEST_F(DetourNavigatorJobQueueTest, pop_should_return_nullptr_from_empty)
{
JobQueue queue;
ASSERT_FALSE(queue.hasJob());
ASSERT_FALSE(queue.pop(mPlayerTile).has_value());
}
TEST_F(DetourNavigatorJobQueueTest, push_on_change_type_remove_should_add_to_removing)
{
const std::chrono::steady_clock::time_point processTime{};
std::list<Job> jobs;
const JobIt job = jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, mChangedTile, ChangeType::remove, processTime);
JobQueue queue;
queue.push(job);
EXPECT_EQ(queue.getStats().mRemoving, 1);
}
TEST_F(DetourNavigatorJobQueueTest, pop_should_return_last_removing)
{
std::list<Job> jobs;
JobQueue queue;
queue.push(jobs.emplace(jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, TilePosition(0, 0),
ChangeType::remove, mProcessTime));
queue.push(jobs.emplace(jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, TilePosition(1, 0),
ChangeType::remove, mProcessTime));
ASSERT_TRUE(queue.hasJob());
const auto job = queue.pop(mPlayerTile);
ASSERT_TRUE(job.has_value());
EXPECT_EQ((*job)->mChangedTile, TilePosition(1, 0));
}
TEST_F(DetourNavigatorJobQueueTest, push_on_change_type_not_remove_should_add_to_updating)
{
std::list<Job> jobs;
const JobIt job = jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, mChangedTile, ChangeType::update, mProcessTime);
JobQueue queue;
queue.push(job);
EXPECT_EQ(queue.getStats().mUpdating, 1);
}
TEST_F(DetourNavigatorJobQueueTest, pop_should_return_nearest_to_player_tile)
{
std::list<Job> jobs;
JobQueue queue;
queue.push(jobs.emplace(jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, TilePosition(0, 0),
ChangeType::update, mProcessTime));
queue.push(jobs.emplace(jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, TilePosition(1, 0),
ChangeType::update, mProcessTime));
ASSERT_TRUE(queue.hasJob());
const auto job = queue.pop(TilePosition(1, 0));
ASSERT_TRUE(job.has_value());
EXPECT_EQ((*job)->mChangedTile, TilePosition(1, 0));
}
TEST_F(DetourNavigatorJobQueueTest, push_on_processing_time_more_than_now_should_add_to_delayed)
{
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
const std::chrono::steady_clock::time_point processTime = now + std::chrono::seconds(1);
std::list<Job> jobs;
const JobIt job = jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, mChangedTile, ChangeType::update, processTime);
JobQueue queue;
queue.push(job, now);
EXPECT_EQ(queue.getStats().mDelayed, 1);
}
TEST_F(DetourNavigatorJobQueueTest, pop_should_return_when_delayed_job_is_ready)
{
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
const std::chrono::steady_clock::time_point processTime = now + std::chrono::seconds(1);
std::list<Job> jobs;
const JobIt job = jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, mChangedTile, ChangeType::update, processTime);
JobQueue queue;
queue.push(job, now);
ASSERT_FALSE(queue.hasJob(now));
ASSERT_FALSE(queue.pop(mPlayerTile, now).has_value());
ASSERT_TRUE(queue.hasJob(processTime));
EXPECT_TRUE(queue.pop(mPlayerTile, processTime).has_value());
}
TEST_F(DetourNavigatorJobQueueTest, update_should_move_ready_delayed_to_updating)
{
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
const std::chrono::steady_clock::time_point processTime = now + std::chrono::seconds(1);
std::list<Job> jobs;
const JobIt job = jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, mChangedTile, ChangeType::update, processTime);
JobQueue queue;
queue.push(job, now);
ASSERT_EQ(queue.getStats().mDelayed, 1);
queue.update(mPlayerTile, mMaxTiles, processTime);
EXPECT_EQ(queue.getStats().mDelayed, 0);
EXPECT_EQ(queue.getStats().mUpdating, 1);
}
TEST_F(DetourNavigatorJobQueueTest, update_should_move_ready_delayed_to_removing_when_out_of_range)
{
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
const std::chrono::steady_clock::time_point processTime = now + std::chrono::seconds(1);
std::list<Job> jobs;
const JobIt job = jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, mChangedTile, ChangeType::update, processTime);
JobQueue queue;
queue.push(job, now);
ASSERT_EQ(queue.getStats().mDelayed, 1);
queue.update(TilePosition(10, 10), mMaxTiles, processTime);
EXPECT_EQ(queue.getStats().mDelayed, 0);
EXPECT_EQ(queue.getStats().mRemoving, 1);
EXPECT_EQ(job->mChangeType, ChangeType::remove);
}
TEST_F(DetourNavigatorJobQueueTest, update_should_move_updating_to_removing_when_out_of_range)
{
std::list<Job> jobs;
JobQueue queue;
queue.push(jobs.emplace(
jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, mChangedTile, ChangeType::update, mProcessTime));
queue.push(jobs.emplace(jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, TilePosition(10, 10),
ChangeType::update, mProcessTime));
ASSERT_EQ(queue.getStats().mUpdating, 2);
queue.update(TilePosition(10, 10), mMaxTiles);
EXPECT_EQ(queue.getStats().mUpdating, 1);
EXPECT_EQ(queue.getStats().mRemoving, 1);
}
TEST_F(DetourNavigatorJobQueueTest, clear_should_remove_all)
{
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
const std::chrono::steady_clock::time_point processTime = now + std::chrono::seconds(1);
std::list<Job> jobs;
const JobIt removing = jobs.emplace(jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace,
TilePosition(0, 0), ChangeType::remove, mProcessTime);
const JobIt updating = jobs.emplace(jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace,
TilePosition(1, 0), ChangeType::update, mProcessTime);
const JobIt delayed = jobs.emplace(jobs.end(), mAgentBounds, mNavMeshCacheItem, mWorldspace, TilePosition(2, 0),
ChangeType::update, processTime);
JobQueue queue;
queue.push(removing);
queue.push(updating);
queue.push(delayed, now);
ASSERT_EQ(queue.getStats().mRemoving, 1);
ASSERT_EQ(queue.getStats().mUpdating, 1);
ASSERT_EQ(queue.getStats().mDelayed, 1);
queue.clear();
EXPECT_EQ(queue.getStats().mRemoving, 0);
EXPECT_EQ(queue.getStats().mUpdating, 0);
EXPECT_EQ(queue.getStats().mDelayed, 0);
}
}
| 28,172
|
C++
|
.cpp
| 506
| 46.539526
| 120
| 0.687366
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,195
|
navigator.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/navigator.cpp
|
#include "operators.hpp"
#include "settings.hpp"
#include <components/bullethelpers/heightfield.hpp>
#include <components/detournavigator/navigatorimpl.hpp>
#include <components/detournavigator/navigatorutils.hpp>
#include <components/detournavigator/navmeshdb.hpp>
#include <components/esm3/loadland.hpp>
#include <components/loadinglistener/loadinglistener.hpp>
#include <components/misc/rng.hpp>
#include <components/resource/bulletshape.hpp>
#include <osg/io_utils>
#include <osg/ref_ptr>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <BulletCollision/CollisionShapes/btCompoundShape.h>
#include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <array>
#include <condition_variable>
#include <deque>
#include <limits>
#include <memory>
#include <mutex>
#include <thread>
MATCHER_P3(Vec3fEq, x, y, z, "")
{
return std::abs(arg.x() - x) < 1e-3 && std::abs(arg.y() - y) < 1e-3 && std::abs(arg.z() - z) < 1e-3;
}
namespace
{
using namespace testing;
using namespace DetourNavigator;
using namespace DetourNavigator::Tests;
constexpr int heightfieldTileSize = ESM::Land::REAL_SIZE / (ESM::Land::LAND_SIZE - 1);
struct DetourNavigatorNavigatorTest : Test
{
Settings mSettings = makeSettings();
std::unique_ptr<Navigator> mNavigator = std::make_unique<NavigatorImpl>(
mSettings, std::make_unique<NavMeshDb>(":memory:", std::numeric_limits<std::uint64_t>::max()));
const osg::Vec3f mPlayerPosition{ 256, 256, 0 };
const ESM::RefId mWorldspace = ESM::RefId::stringRefId("sys::default");
const AgentBounds mAgentBounds{ CollisionShapeType::Aabb, { 29, 29, 66 } };
osg::Vec3f mStart{ 52, 460, 1 };
osg::Vec3f mEnd{ 460, 52, 1 };
std::deque<osg::Vec3f> mPath;
std::back_insert_iterator<std::deque<osg::Vec3f>> mOut{ mPath };
AreaCosts mAreaCosts;
Loading::Listener mListener;
const osg::Vec2i mCellPosition{ 0, 0 };
const float mEndTolerance = 0;
const btTransform mTransform{ btMatrix3x3::getIdentity(), btVector3(256, 256, 0) };
const ObjectTransform mObjectTransform{ ESM::Position{ { 256, 256, 0 }, { 0, 0, 0 } }, 0.0f };
};
constexpr std::array<float, 5 * 5> defaultHeightfieldData{ {
0, 0, 0, 0, 0, // row 0
0, -25, -25, -25, -25, // row 1
0, -25, -100, -100, -100, // row 2
0, -25, -100, -100, -100, // row 3
0, -25, -100, -100, -100, // row 4
} };
constexpr std::array<btScalar, 5 * 5> defaultHeightfieldDataScalar{ {
0, 0, 0, 0, 0, // row 0
0, -25, -25, -25, -25, // row 1
0, -25, -100, -100, -100, // row 2
0, -25, -100, -100, -100, // row 3
0, -25, -100, -100, -100, // row 4
} };
template <std::size_t size>
std::unique_ptr<btHeightfieldTerrainShape> makeSquareHeightfieldTerrainShape(
const std::array<btScalar, size>& values, btScalar heightScale = 1, int upAxis = 2,
PHY_ScalarType heightDataType = PHY_FLOAT, bool flipQuadEdges = false)
{
const int width = static_cast<int>(std::sqrt(size));
const btScalar min = *std::min_element(values.begin(), values.end());
const btScalar max = *std::max_element(values.begin(), values.end());
const btScalar greater = std::max(std::abs(min), std::abs(max));
return std::make_unique<btHeightfieldTerrainShape>(
width, width, values.data(), heightScale, -greater, greater, upAxis, heightDataType, flipQuadEdges);
}
template <std::size_t size>
HeightfieldSurface makeSquareHeightfieldSurface(const std::array<float, size>& values)
{
const auto [min, max] = std::minmax_element(values.begin(), values.end());
const float greater = std::max(std::abs(*min), std::abs(*max));
HeightfieldSurface surface;
surface.mHeights = values.data();
surface.mMinHeight = -greater;
surface.mMaxHeight = greater;
surface.mSize = static_cast<int>(std::sqrt(size));
return surface;
}
template <class T>
osg::ref_ptr<const Resource::BulletShapeInstance> makeBulletShapeInstance(std::unique_ptr<T>&& shape)
{
osg::ref_ptr<Resource::BulletShape> bulletShape(new Resource::BulletShape);
bulletShape->mCollisionShape.reset(std::move(shape).release());
return new Resource::BulletShapeInstance(bulletShape);
}
template <class T>
class CollisionShapeInstance
{
public:
CollisionShapeInstance(std::unique_ptr<T>&& shape)
: mInstance(makeBulletShapeInstance(std::move(shape)))
{
}
T& shape() const { return static_cast<T&>(*mInstance->mCollisionShape); }
const osg::ref_ptr<const Resource::BulletShapeInstance>& instance() const { return mInstance; }
private:
osg::ref_ptr<const Resource::BulletShapeInstance> mInstance;
};
btVector3 getHeightfieldShift(const osg::Vec2i& cellPosition, int cellSize, float minHeight, float maxHeight)
{
return BulletHelpers::getHeightfieldShift(cellPosition.x(), cellPosition.x(), cellSize, minHeight, maxHeight);
}
TEST_F(DetourNavigatorNavigatorTest, find_path_for_empty_should_return_empty)
{
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::NavMeshNotFound);
EXPECT_EQ(mPath, std::deque<osg::Vec3f>());
}
TEST_F(DetourNavigatorNavigatorTest, find_path_for_existing_agent_with_no_navmesh_should_throw_exception)
{
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::StartPolygonNotFound);
}
TEST_F(DetourNavigatorNavigatorTest, add_agent_should_count_each_agent)
{
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->removeAgent(mAgentBounds);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::StartPolygonNotFound);
}
TEST_F(DetourNavigatorNavigatorTest, update_then_find_path_should_return_path)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
auto updateGuard = mNavigator->makeUpdateGuard();
mNavigator->addHeightfield(mCellPosition, cellSize, surface, updateGuard.get());
mNavigator->update(mPlayerPosition, updateGuard.get());
updateGuard.reset();
mNavigator->wait(WaitConditionType::requiredTilesPresent, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, find_path_to_the_start_position_should_contain_single_point)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
auto updateGuard = mNavigator->makeUpdateGuard();
mNavigator->addHeightfield(mCellPosition, cellSize, surface, updateGuard.get());
mNavigator->update(mPlayerPosition, updateGuard.get());
updateGuard.reset();
mNavigator->wait(WaitConditionType::requiredTilesPresent, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mStart, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath, ElementsAre(Vec3fEq(56.66666412353515625, 460, 1.99998295307159423828125))) << mPath;
}
TEST_F(DetourNavigatorNavigatorTest, add_object_should_change_navmesh)
{
mSettings.mWaitUntilMinDistanceToPlayer = 0;
mNavigator.reset(new NavigatorImpl(
mSettings, std::make_unique<NavMeshDb>(":memory:", std::numeric_limits<std::uint64_t>::max())));
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
CollisionShapeInstance compound(std::make_unique<btCompoundShape>());
compound.shape().addChildShape(
btTransform(btMatrix3x3::getIdentity(), btVector3(0, 0, 0)), new btBoxShape(btVector3(20, 20, 100)));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66666412353515625, 460, 1.99998295307159423828125),
Vec3fEq(460, 56.66666412353515625, 1.99998295307159423828125)))
<< mPath;
{
auto updateGuard = mNavigator->makeUpdateGuard();
mNavigator->addObject(ObjectId(&compound.shape()), ObjectShapes(compound.instance(), mObjectTransform),
mTransform, updateGuard.get());
mNavigator->update(mPlayerPosition, updateGuard.get());
}
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mPath.clear();
mOut = std::back_inserter(mPath);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(181.33331298828125, 215.33331298828125, -20.6666717529296875),
Vec3fEq(215.33331298828125, 181.33331298828125, -20.6666717529296875),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, update_changed_object_should_change_navmesh)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
CollisionShapeInstance compound(std::make_unique<btCompoundShape>());
compound.shape().addChildShape(
btTransform(btMatrix3x3::getIdentity(), btVector3(0, 0, 0)), new btBoxShape(btVector3(20, 20, 100)));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->addObject(
ObjectId(&compound.shape()), ObjectShapes(compound.instance(), mObjectTransform), mTransform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(181.33331298828125, 215.33331298828125, -20.6666717529296875),
Vec3fEq(215.33331298828125, 181.33331298828125, -20.6666717529296875),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
compound.shape().updateChildTransform(0, btTransform(btMatrix3x3::getIdentity(), btVector3(1000, 0, 0)));
mNavigator->updateObject(
ObjectId(&compound.shape()), ObjectShapes(compound.instance(), mObjectTransform), mTransform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mPath.clear();
mOut = std::back_inserter(mPath);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, for_overlapping_heightfields_objects_should_use_higher)
{
CollisionShapeInstance heightfield1(makeSquareHeightfieldTerrainShape(defaultHeightfieldDataScalar));
heightfield1.shape().setLocalScaling(btVector3(128, 128, 1));
const std::array<btScalar, 5 * 5> heightfieldData2{ {
-25, -25, -25, -25, -25, // row 0
-25, -25, -25, -25, -25, // row 1
-25, -25, -25, -25, -25, // row 2
-25, -25, -25, -25, -25, // row 3
-25, -25, -25, -25, -25, // row 4
} };
CollisionShapeInstance heightfield2(makeSquareHeightfieldTerrainShape(heightfieldData2));
heightfield2.shape().setLocalScaling(btVector3(128, 128, 1));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addObject(ObjectId(&heightfield1.shape()), ObjectShapes(heightfield1.instance(), mObjectTransform),
mTransform, nullptr);
mNavigator->addObject(ObjectId(&heightfield2.shape()), ObjectShapes(heightfield2.instance(), mObjectTransform),
mTransform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, only_one_heightfield_per_cell_is_allowed)
{
const HeightfieldSurface surface1 = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize1 = heightfieldTileSize * (surface1.mSize - 1);
const std::array<float, 5 * 5> heightfieldData2{ {
-25, -25, -25, -25, -25, // row 0
-25, -25, -25, -25, -25, // row 1
-25, -25, -25, -25, -25, // row 2
-25, -25, -25, -25, -25, // row 3
-25, -25, -25, -25, -25, // row 4
} };
const HeightfieldSurface surface2 = makeSquareHeightfieldSurface(heightfieldData2);
const int cellSize2 = heightfieldTileSize * (surface2.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize1, surface1, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const Version version = mNavigator->getNavMesh(mAgentBounds)->lockConst()->getVersion();
mNavigator->addHeightfield(mCellPosition, cellSize2, surface2, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(mNavigator->getNavMesh(mAgentBounds)->lockConst()->getVersion(), version);
}
TEST_F(DetourNavigatorNavigatorTest, path_should_be_around_avoid_shape)
{
osg::ref_ptr<Resource::BulletShape> bulletShape(new Resource::BulletShape);
std::unique_ptr<btHeightfieldTerrainShape> shapePtr
= makeSquareHeightfieldTerrainShape(defaultHeightfieldDataScalar);
shapePtr->setLocalScaling(btVector3(128, 128, 1));
bulletShape->mCollisionShape.reset(shapePtr.release());
std::array<btScalar, 5 * 5> heightfieldDataAvoid{ {
-25, -25, -25, -25, -25, // row 0
-25, -25, -25, -25, -25, // row 1
-25, -25, -25, -25, -25, // row 2
-25, -25, -25, -25, -25, // row 3
-25, -25, -25, -25, -25, // row 4
} };
std::unique_ptr<btHeightfieldTerrainShape> shapeAvoidPtr
= makeSquareHeightfieldTerrainShape(heightfieldDataAvoid);
shapeAvoidPtr->setLocalScaling(btVector3(128, 128, 1));
bulletShape->mAvoidCollisionShape.reset(shapeAvoidPtr.release());
osg::ref_ptr<const Resource::BulletShapeInstance> instance(new Resource::BulletShapeInstance(bulletShape));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addObject(
ObjectId(instance->mCollisionShape.get()), ObjectShapes(instance, mObjectTransform), mTransform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(158.6666412353515625, 249.3332977294921875, -20.6666717529296875),
Vec3fEq(249.3332977294921875, 158.6666412353515625, -20.6666717529296875),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, path_should_be_over_water_ground_lower_than_water_with_only_swim_flag)
{
std::array<float, 5 * 5> heightfieldData{ {
-50, -50, -50, -50, 0, // row 0
-50, -100, -150, -100, -50, // row 1
-50, -150, -200, -150, -100, // row 2
-50, -100, -150, -100, -100, // row 3
0, -50, -100, -100, -100, // row 4
} };
const HeightfieldSurface surface = makeSquareHeightfieldSurface(heightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addWater(mCellPosition, cellSize, 300, nullptr);
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mStart.x() = 256;
mStart.z() = 300;
mEnd.x() = 256;
mEnd.z() = 300;
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_swim, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(256, 460, 185.3333282470703125), Vec3fEq(256, 56.66664886474609375, 185.3333282470703125)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, path_should_be_over_water_when_ground_cross_water_with_swim_and_walk_flags)
{
std::array<float, 7 * 7> heightfieldData{ {
0, 0, 0, 0, 0, 0, 0, // row 0
0, -100, -100, -100, -100, -100, 0, // row 1
0, -100, -150, -150, -150, -100, 0, // row 2
0, -100, -150, -200, -150, -100, 0, // row 3
0, -100, -150, -150, -150, -100, 0, // row 4
0, -100, -100, -100, -100, -100, 0, // row 5
0, 0, 0, 0, 0, 0, 0, // row 6
} };
const HeightfieldSurface surface = makeSquareHeightfieldSurface(heightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addWater(mCellPosition, cellSize, -25, nullptr);
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mStart.x() = 256;
mEnd.x() = 256;
EXPECT_EQ(
findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_swim | Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(256, 460, -129.4098663330078125), Vec3fEq(256, 56.66664886474609375, -30.0000133514404296875)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest,
path_should_be_over_water_when_ground_cross_water_with_max_int_cells_size_and_swim_and_walk_flags)
{
std::array<float, 7 * 7> heightfieldData{ {
0, 0, 0, 0, 0, 0, 0, // row 0
0, -100, -100, -100, -100, -100, 0, // row 1
0, -100, -150, -150, -150, -100, 0, // row 2
0, -100, -150, -200, -150, -100, 0, // row 3
0, -100, -150, -150, -150, -100, 0, // row 4
0, -100, -100, -100, -100, -100, 0, // row 5
0, 0, 0, 0, 0, 0, 0, // row 6
} };
const HeightfieldSurface surface = makeSquareHeightfieldSurface(heightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->addWater(mCellPosition, std::numeric_limits<int>::max(), -25, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mStart.x() = 256;
mEnd.x() = 256;
EXPECT_EQ(
findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_swim | Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre(
Vec3fEq(256, 460, -129.4098663330078125), Vec3fEq(256, 56.66664886474609375, -30.0000133514404296875)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, path_should_be_over_ground_when_ground_cross_water_with_only_walk_flag)
{
std::array<float, 7 * 7> heightfieldData{ {
0, 0, 0, 0, 0, 0, 0, // row 0
0, -100, -100, -100, -100, -100, 0, // row 1
0, -100, -150, -150, -150, -100, 0, // row 2
0, -100, -150, -200, -150, -100, 0, // row 3
0, -100, -150, -150, -150, -100, 0, // row 4
0, -100, -100, -100, -100, -100, 0, // row 5
0, 0, 0, 0, 0, 0, 0, // row 6
} };
const HeightfieldSurface surface = makeSquareHeightfieldSurface(heightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addWater(mCellPosition, cellSize, -25, nullptr);
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mStart.x() = 256;
mEnd.x() = 256;
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(256, 460, -129.4098663330078125), Vec3fEq(256, 56.66664886474609375, -30.0000133514404296875)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, update_object_remove_and_update_then_find_path_should_return_path)
{
CollisionShapeInstance heightfield(makeSquareHeightfieldTerrainShape(defaultHeightfieldDataScalar));
heightfield.shape().setLocalScaling(btVector3(128, 128, 1));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addObject(ObjectId(&heightfield.shape()), ObjectShapes(heightfield.instance(), mObjectTransform),
mTransform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mNavigator->removeObject(ObjectId(&heightfield.shape()), nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mNavigator->addObject(ObjectId(&heightfield.shape()), ObjectShapes(heightfield.instance(), mObjectTransform),
mTransform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, update_heightfield_remove_and_update_then_find_path_should_return_path)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mNavigator->removeHeightfield(mCellPosition, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, update_then_find_random_point_around_circle_should_return_position)
{
const std::array<float, 6 * 6> heightfieldData{ {
0, 0, 0, 0, 0, 0, // row 0
0, -25, -25, -25, -25, -25, // row 1
0, -25, -1000, -1000, -100, -100, // row 2
0, -25, -1000, -1000, -100, -100, // row 3
0, -25, -100, -100, -100, -100, // row 4
0, -25, -100, -100, -100, -100, // row 5
} };
const HeightfieldSurface surface = makeSquareHeightfieldSurface(heightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
Misc::Rng::init(42);
const auto result = findRandomPointAroundCircle(
*mNavigator, mAgentBounds, mStart, 100.0, Flag_walk, []() { return Misc::Rng::rollClosedProbability(); });
ASSERT_THAT(result, Optional(Vec3fEq(70.35845947265625, 335.592041015625, -2.6667339801788330078125)))
<< (result ? *result : osg::Vec3f());
const auto distance = (*result - mStart).length();
EXPECT_FLOAT_EQ(distance, 125.80865478515625) << distance;
}
TEST_F(DetourNavigatorNavigatorTest, multiple_threads_should_lock_tiles)
{
mSettings.mAsyncNavMeshUpdaterThreads = 2;
mNavigator.reset(new NavigatorImpl(
mSettings, std::make_unique<NavMeshDb>(":memory:", std::numeric_limits<std::uint64_t>::max())));
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
const btVector3 shift = getHeightfieldShift(mCellPosition, cellSize, surface.mMinHeight, surface.mMaxHeight);
std::vector<CollisionShapeInstance<btBoxShape>> boxes;
std::generate_n(
std::back_inserter(boxes), 100, [] { return std::make_unique<btBoxShape>(btVector3(20, 20, 100)); });
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
for (std::size_t i = 0; i < boxes.size(); ++i)
{
const btTransform transform(
btMatrix3x3::getIdentity(), btVector3(shift.x() + i * 10, shift.y() + i * 10, i * 10));
mNavigator->addObject(
ObjectId(&boxes[i].shape()), ObjectShapes(boxes[i].instance(), mObjectTransform), transform, nullptr);
}
std::this_thread::sleep_for(std::chrono::microseconds(1));
for (std::size_t i = 0; i < boxes.size(); ++i)
{
const btTransform transform(
btMatrix3x3::getIdentity(), btVector3(shift.x() + i * 10 + 1, shift.y() + i * 10 + 1, i * 10 + 1));
mNavigator->updateObject(
ObjectId(&boxes[i].shape()), ObjectShapes(boxes[i].instance(), mObjectTransform), transform, nullptr);
}
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 1.99999392032623291015625),
Vec3fEq(181.33331298828125, 215.33331298828125, -20.6666717529296875),
Vec3fEq(215.33331298828125, 181.33331298828125, -20.6666717529296875),
Vec3fEq(460, 56.66664886474609375, 1.99999392032623291015625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, update_changed_multiple_times_object_should_delay_navmesh_change)
{
std::vector<CollisionShapeInstance<btBoxShape>> shapes;
std::generate_n(
std::back_inserter(shapes), 100, [] { return std::make_unique<btBoxShape>(btVector3(64, 64, 64)); });
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
for (std::size_t i = 0; i < shapes.size(); ++i)
{
const btTransform transform(btMatrix3x3::getIdentity(), btVector3(i * 32, i * 32, i * 32));
mNavigator->addObject(
ObjectId(&shapes[i].shape()), ObjectShapes(shapes[i].instance(), mObjectTransform), transform, nullptr);
}
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const auto start = std::chrono::steady_clock::now();
for (std::size_t i = 0; i < shapes.size(); ++i)
{
const btTransform transform(btMatrix3x3::getIdentity(), btVector3(i * 32 + 1, i * 32 + 1, i * 32 + 1));
mNavigator->updateObject(
ObjectId(&shapes[i].shape()), ObjectShapes(shapes[i].instance(), mObjectTransform), transform, nullptr);
}
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
for (std::size_t i = 0; i < shapes.size(); ++i)
{
const btTransform transform(btMatrix3x3::getIdentity(), btVector3(i * 32 + 2, i * 32 + 2, i * 32 + 2));
mNavigator->updateObject(
ObjectId(&shapes[i].shape()), ObjectShapes(shapes[i].instance(), mObjectTransform), transform, nullptr);
}
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const auto duration = std::chrono::steady_clock::now() - start;
EXPECT_GT(duration, mSettings.mMinUpdateInterval)
<< std::chrono::duration_cast<std::chrono::duration<float, std::milli>>(duration).count() << " ms";
}
TEST_F(DetourNavigatorNavigatorTest, update_then_raycast_should_return_position)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const osg::Vec3f start(57, 460, 1);
const osg::Vec3f end(460, 57, 1);
const auto result = raycast(*mNavigator, mAgentBounds, start, end, Flag_walk);
ASSERT_THAT(result, Optional(Vec3fEq(end.x(), end.y(), 1.95257937908172607421875)))
<< (result ? *result : osg::Vec3f());
}
TEST_F(DetourNavigatorNavigatorTest,
update_for_oscillating_object_that_does_not_change_navmesh_should_not_trigger_navmesh_update)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
CollisionShapeInstance oscillatingBox(std::make_unique<btBoxShape>(btVector3(20, 20, 20)));
const btVector3 oscillatingBoxShapePosition(288, 288, 400);
CollisionShapeInstance borderBox(std::make_unique<btBoxShape>(btVector3(50, 50, 50)));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->addObject(ObjectId(&oscillatingBox.shape()),
ObjectShapes(oscillatingBox.instance(), mObjectTransform),
btTransform(btMatrix3x3::getIdentity(), oscillatingBoxShapePosition), nullptr);
// add this box to make navmesh bound box independent from oscillatingBoxShape rotations
mNavigator->addObject(ObjectId(&borderBox.shape()), ObjectShapes(borderBox.instance(), mObjectTransform),
btTransform(btMatrix3x3::getIdentity(), oscillatingBoxShapePosition + btVector3(0, 0, 200)), nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const Version expectedVersion{ 1, 4 };
const auto navMeshes = mNavigator->getNavMeshes();
ASSERT_EQ(navMeshes.size(), 1);
ASSERT_EQ(navMeshes.begin()->second->lockConst()->getVersion(), expectedVersion);
for (int n = 0; n < 10; ++n)
{
const btTransform transform(
btQuaternion(btVector3(0, 0, 1), n * 2 * osg::PI / 10), oscillatingBoxShapePosition);
mNavigator->updateObject(ObjectId(&oscillatingBox.shape()),
ObjectShapes(oscillatingBox.instance(), mObjectTransform), transform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
}
ASSERT_EQ(navMeshes.size(), 1);
ASSERT_EQ(navMeshes.begin()->second->lockConst()->getVersion(), expectedVersion);
}
TEST_F(DetourNavigatorNavigatorTest, should_provide_path_over_flat_heightfield)
{
const HeightfieldPlane plane{ 100 };
const int cellSize = heightfieldTileSize * 4;
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, plane, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::requiredTilesPresent, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, 102), Vec3fEq(460, 56.66664886474609375, 102)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, for_not_reachable_destination_find_path_should_provide_partial_path)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
CollisionShapeInstance compound(std::make_unique<btCompoundShape>());
compound.shape().addChildShape(btTransform(btMatrix3x3::getIdentity(), btVector3(204, -204, 0)),
new btBoxShape(btVector3(200, 200, 1000)));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->addObject(
ObjectId(&compound.shape()), ObjectShapes(compound.instance(), mObjectTransform), mTransform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, mEndTolerance, mOut),
Status::PartialPath);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, -2.5371119976043701171875),
Vec3fEq(222, 290, -71.33342742919921875)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, end_tolerance_should_extent_available_destinations)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
CollisionShapeInstance compound(std::make_unique<btCompoundShape>());
compound.shape().addChildShape(btTransform(btMatrix3x3::getIdentity(), btVector3(204, -204, 0)),
new btBoxShape(btVector3(100, 100, 1000)));
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addHeightfield(mCellPosition, cellSize, surface, nullptr);
mNavigator->addObject(
ObjectId(&compound.shape()), ObjectShapes(compound.instance(), mObjectTransform), mTransform, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const float endTolerance = 1000.0f;
EXPECT_EQ(findPath(*mNavigator, mAgentBounds, mStart, mEnd, Flag_walk, mAreaCosts, endTolerance, mOut),
Status::Success);
EXPECT_THAT(mPath,
ElementsAre( //
Vec3fEq(56.66664886474609375, 460, -2.5371119976043701171875),
Vec3fEq(305.999969482421875, 56.66664886474609375, -2.6667406558990478515625)))
<< mPath;
}
TEST_F(DetourNavigatorNavigatorTest, only_one_water_per_cell_is_allowed)
{
const int cellSize1 = 100;
const float level1 = 1;
const int cellSize2 = 200;
const float level2 = 2;
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addWater(mCellPosition, cellSize1, level1, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const Version version = mNavigator->getNavMesh(mAgentBounds)->lockConst()->getVersion();
mNavigator->addWater(mCellPosition, cellSize2, level2, nullptr);
mNavigator->update(mPlayerPosition, nullptr);
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
EXPECT_EQ(mNavigator->getNavMesh(mAgentBounds)->lockConst()->getVersion(), version);
}
std::pair<TilePosition, TilePosition> getMinMax(const RecastMeshTiles& tiles)
{
const auto lessByX = [](const auto& l, const auto& r) { return l.first.x() < r.first.x(); };
const auto lessByY = [](const auto& l, const auto& r) { return l.first.y() < r.first.y(); };
const auto [minX, maxX] = std::ranges::minmax_element(tiles, lessByX);
const auto [minY, maxY] = std::ranges::minmax_element(tiles, lessByY);
return { TilePosition(minX->first.x(), minY->first.y()), TilePosition(maxX->first.x(), maxY->first.y()) };
}
TEST_F(DetourNavigatorNavigatorTest, update_for_very_big_object_should_be_limited)
{
const float size = static_cast<float>((1 << 22) - 1);
CollisionShapeInstance bigBox(std::make_unique<btBoxShape>(btVector3(size, size, 1)));
const ObjectTransform objectTransform{
.mPosition = ESM::Position{ .pos = { 0, 0, 0 }, .rot{ 0, 0, 0 } },
.mScale = 1.0f,
};
const std::optional<CellGridBounds> cellGridBounds = std::nullopt;
const osg::Vec3f playerPosition(32, 1024, 0);
mNavigator->updateBounds(mWorldspace, cellGridBounds, playerPosition, nullptr);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addObject(ObjectId(&bigBox.shape()), ObjectShapes(bigBox.instance(), objectTransform),
btTransform::getIdentity(), nullptr);
bool updated = false;
std::condition_variable updateFinished;
std::mutex mutex;
std::thread thread([&] {
auto guard = mNavigator->makeUpdateGuard();
mNavigator->update(playerPosition, guard.get());
std::lock_guard lock(mutex);
updated = true;
updateFinished.notify_all();
});
{
std::unique_lock lock(mutex);
updateFinished.wait_for(lock, std::chrono::seconds(10), [&] { return updated; });
ASSERT_TRUE(updated);
}
thread.join();
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const auto recastMeshTiles = mNavigator->getRecastMeshTiles();
ASSERT_EQ(recastMeshTiles.size(), 1033);
EXPECT_EQ(getMinMax(recastMeshTiles), std::pair(TilePosition(-18, -17), TilePosition(18, 19)));
const auto navMesh = mNavigator->getNavMesh(mAgentBounds);
ASSERT_NE(navMesh, nullptr);
std::size_t usedNavMeshTiles = 0;
navMesh->lockConst()->forEachUsedTile([&](const auto&...) { ++usedNavMeshTiles; });
EXPECT_EQ(usedNavMeshTiles, 1024);
}
TEST_F(DetourNavigatorNavigatorTest, update_should_be_limited_by_cell_grid_bounds)
{
const float size = static_cast<float>((1 << 22) - 1);
CollisionShapeInstance bigBox(std::make_unique<btBoxShape>(btVector3(size, size, 1)));
const ObjectTransform objectTransform{
.mPosition = ESM::Position{ .pos = { 0, 0, 0 }, .rot{ 0, 0, 0 } },
.mScale = 1.0f,
};
const CellGridBounds cellGridBounds{
.mCenter = osg::Vec2i(0, 0),
.mHalfSize = 1,
};
const osg::Vec3f playerPosition(32, 1024, 0);
mNavigator->updateBounds(mWorldspace, cellGridBounds, playerPosition, nullptr);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
mNavigator->addObject(ObjectId(&bigBox.shape()), ObjectShapes(bigBox.instance(), objectTransform),
btTransform::getIdentity(), nullptr);
bool updated = false;
std::condition_variable updateFinished;
std::mutex mutex;
std::thread thread([&] {
auto guard = mNavigator->makeUpdateGuard();
mNavigator->update(playerPosition, guard.get());
std::lock_guard lock(mutex);
updated = true;
updateFinished.notify_all();
});
{
std::unique_lock lock(mutex);
updateFinished.wait_for(lock, std::chrono::seconds(10), [&] { return updated; });
ASSERT_TRUE(updated);
}
thread.join();
mNavigator->wait(WaitConditionType::allJobsDone, &mListener);
const auto recastMeshTiles = mNavigator->getRecastMeshTiles();
ASSERT_EQ(recastMeshTiles.size(), 854);
EXPECT_EQ(getMinMax(recastMeshTiles), std::pair(TilePosition(-12, -12), TilePosition(18, 19)));
const auto navMesh = mNavigator->getNavMesh(mAgentBounds);
ASSERT_NE(navMesh, nullptr);
std::size_t usedNavMeshTiles = 0;
navMesh->lockConst()->forEachUsedTile([&](const auto&...) { ++usedNavMeshTiles; });
EXPECT_EQ(usedNavMeshTiles, 854);
}
struct DetourNavigatorNavigatorNotSupportedAgentBoundsTest : TestWithParam<AgentBounds>
{
};
TEST_P(DetourNavigatorNavigatorNotSupportedAgentBoundsTest, on_add_agent)
{
const Settings settings = makeSettings();
NavigatorImpl navigator(settings, nullptr);
EXPECT_FALSE(navigator.addAgent(GetParam()));
}
const std::array notSupportedAgentBounds = {
AgentBounds{ .mShapeType = CollisionShapeType::Aabb, .mHalfExtents = osg::Vec3f(0, 0, 0) },
AgentBounds{ .mShapeType = CollisionShapeType::RotatingBox, .mHalfExtents = osg::Vec3f(0, 0, 0) },
AgentBounds{ .mShapeType = CollisionShapeType::Cylinder, .mHalfExtents = osg::Vec3f(0, 0, 0) },
AgentBounds{ .mShapeType = CollisionShapeType::Aabb, .mHalfExtents = osg::Vec3f(0, 0, 11.34f) },
AgentBounds{ .mShapeType = CollisionShapeType::RotatingBox, .mHalfExtents = osg::Vec3f(0, 11.34f, 11.34f) },
AgentBounds{ .mShapeType = CollisionShapeType::Cylinder, .mHalfExtents = osg::Vec3f(0, 0, 11.34f) },
AgentBounds{ .mShapeType = CollisionShapeType::Aabb, .mHalfExtents = osg::Vec3f(1, 1, 0) },
AgentBounds{ .mShapeType = CollisionShapeType::RotatingBox, .mHalfExtents = osg::Vec3f(1, 1, 0) },
AgentBounds{ .mShapeType = CollisionShapeType::Cylinder, .mHalfExtents = osg::Vec3f(1, 1, 0) },
AgentBounds{ .mShapeType = CollisionShapeType::Aabb, .mHalfExtents = osg::Vec3f(1, 1, 11.33f) },
AgentBounds{ .mShapeType = CollisionShapeType::RotatingBox, .mHalfExtents = osg::Vec3f(1, 1, 11.33f) },
AgentBounds{ .mShapeType = CollisionShapeType::Cylinder, .mHalfExtents = osg::Vec3f(1, 1, 11.33f) },
AgentBounds{ .mShapeType = CollisionShapeType::Aabb, .mHalfExtents = osg::Vec3f(2043.54f, 2043.54f, 11.34f) },
AgentBounds{ .mShapeType = CollisionShapeType::RotatingBox, .mHalfExtents = osg::Vec3f(2890, 1, 11.34f) },
AgentBounds{ .mShapeType = CollisionShapeType::Cylinder, .mHalfExtents = osg::Vec3f(2890, 2890, 11.34f) },
};
INSTANTIATE_TEST_SUITE_P(NotSupportedAgentBounds, DetourNavigatorNavigatorNotSupportedAgentBoundsTest,
ValuesIn(notSupportedAgentBounds));
TEST_F(DetourNavigatorNavigatorTest, find_nearest_nav_mesh_position_should_return_nav_mesh_position)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
auto updateGuard = mNavigator->makeUpdateGuard();
mNavigator->addHeightfield(mCellPosition, cellSize, surface, updateGuard.get());
mNavigator->update(mPlayerPosition, updateGuard.get());
updateGuard.reset();
mNavigator->wait(WaitConditionType::requiredTilesPresent, &mListener);
const osg::Vec3f position(250, 250, 0);
const osg::Vec3f searchAreaHalfExtents(1000, 1000, 1000);
EXPECT_THAT(findNearestNavMeshPosition(*mNavigator, mAgentBounds, position, searchAreaHalfExtents, Flag_walk),
Optional(Vec3fEq(250, 250, -62.5186)));
}
TEST_F(DetourNavigatorNavigatorTest, find_nearest_nav_mesh_position_should_return_nullopt_when_too_far)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
auto updateGuard = mNavigator->makeUpdateGuard();
mNavigator->addHeightfield(mCellPosition, cellSize, surface, updateGuard.get());
mNavigator->update(mPlayerPosition, updateGuard.get());
updateGuard.reset();
mNavigator->wait(WaitConditionType::requiredTilesPresent, &mListener);
const osg::Vec3f position(250, 250, 250);
const osg::Vec3f searchAreaHalfExtents(100, 100, 100);
EXPECT_EQ(findNearestNavMeshPosition(*mNavigator, mAgentBounds, position, searchAreaHalfExtents, Flag_walk),
std::nullopt);
}
TEST_F(DetourNavigatorNavigatorTest, find_nearest_nav_mesh_position_should_return_nullopt_when_flags_do_not_match)
{
const HeightfieldSurface surface = makeSquareHeightfieldSurface(defaultHeightfieldData);
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
ASSERT_TRUE(mNavigator->addAgent(mAgentBounds));
auto updateGuard = mNavigator->makeUpdateGuard();
mNavigator->addHeightfield(mCellPosition, cellSize, surface, updateGuard.get());
mNavigator->update(mPlayerPosition, updateGuard.get());
updateGuard.reset();
mNavigator->wait(WaitConditionType::requiredTilesPresent, &mListener);
const osg::Vec3f position(250, 250, 0);
const osg::Vec3f searchAreaHalfExtents(1000, 1000, 1000);
EXPECT_EQ(findNearestNavMeshPosition(*mNavigator, mAgentBounds, position, searchAreaHalfExtents, Flag_swim),
std::nullopt);
}
struct DetourNavigatorUpdateTest : TestWithParam<std::function<void(Navigator&)>>
{
};
std::vector<TilePosition> getUsedTiles(const NavMeshCacheItem& navMesh)
{
std::vector<TilePosition> result;
navMesh.forEachUsedTile([&](const TilePosition& position, const auto&...) { result.push_back(position); });
return result;
}
TEST_P(DetourNavigatorUpdateTest, update_should_change_covered_area_when_player_moves)
{
Loading::Listener listener;
Settings settings = makeSettings();
settings.mMaxTilesNumber = 5;
NavigatorImpl navigator(settings, nullptr);
const AgentBounds agentBounds{ CollisionShapeType::Aabb, { 29, 29, 66 } };
ASSERT_TRUE(navigator.addAgent(agentBounds));
GetParam()(navigator);
{
auto updateGuard = navigator.makeUpdateGuard();
navigator.update(osg::Vec3f(3000, 3000, 0), updateGuard.get());
}
navigator.wait(WaitConditionType::allJobsDone, &listener);
{
const auto navMesh = navigator.getNavMesh(agentBounds);
ASSERT_NE(navMesh, nullptr);
const TilePosition expectedTiles[] = { { 3, 4 }, { 4, 3 }, { 4, 4 }, { 4, 5 }, { 5, 4 } };
const auto usedTiles = getUsedTiles(*navMesh->lockConst());
EXPECT_THAT(usedTiles, UnorderedElementsAreArray(expectedTiles)) << usedTiles;
}
{
auto updateGuard = navigator.makeUpdateGuard();
navigator.update(osg::Vec3f(4000, 3000, 0), updateGuard.get());
}
navigator.wait(WaitConditionType::allJobsDone, &listener);
{
const auto navMesh = navigator.getNavMesh(agentBounds);
ASSERT_NE(navMesh, nullptr);
const TilePosition expectedTiles[] = { { 4, 4 }, { 5, 3 }, { 5, 4 }, { 5, 5 }, { 6, 4 } };
const auto usedTiles = getUsedTiles(*navMesh->lockConst());
EXPECT_THAT(usedTiles, UnorderedElementsAreArray(expectedTiles)) << usedTiles;
}
}
TEST_P(DetourNavigatorUpdateTest, update_should_change_covered_area_when_player_moves_without_waiting_for_all)
{
Loading::Listener listener;
Settings settings = makeSettings();
settings.mMaxTilesNumber = 1;
settings.mWaitUntilMinDistanceToPlayer = 1;
NavigatorImpl navigator(settings, nullptr);
const AgentBounds agentBounds{ CollisionShapeType::Aabb, { 29, 29, 66 } };
ASSERT_TRUE(navigator.addAgent(agentBounds));
GetParam()(navigator);
{
auto updateGuard = navigator.makeUpdateGuard();
navigator.update(osg::Vec3f(3000, 3000, 0), updateGuard.get());
}
navigator.wait(WaitConditionType::requiredTilesPresent, &listener);
{
const auto navMesh = navigator.getNavMesh(agentBounds);
ASSERT_NE(navMesh, nullptr);
const TilePosition expectedTile(4, 4);
const auto usedTiles = getUsedTiles(*navMesh->lockConst());
EXPECT_THAT(usedTiles, Contains(expectedTile)) << usedTiles;
}
{
auto updateGuard = navigator.makeUpdateGuard();
navigator.update(osg::Vec3f(6000, 3000, 0), updateGuard.get());
}
navigator.wait(WaitConditionType::requiredTilesPresent, &listener);
{
const auto navMesh = navigator.getNavMesh(agentBounds);
ASSERT_NE(navMesh, nullptr);
const TilePosition expectedTile(8, 4);
const auto usedTiles = getUsedTiles(*navMesh->lockConst());
EXPECT_THAT(usedTiles, Contains(expectedTile)) << usedTiles;
}
}
TEST_P(DetourNavigatorUpdateTest, update_should_change_covered_area_when_player_moves_with_db)
{
Loading::Listener listener;
Settings settings = makeSettings();
settings.mMaxTilesNumber = 1;
settings.mWaitUntilMinDistanceToPlayer = 1;
NavigatorImpl navigator(settings, std::make_unique<NavMeshDb>(":memory:", settings.mMaxDbFileSize));
const AgentBounds agentBounds{ CollisionShapeType::Aabb, { 29, 29, 66 } };
ASSERT_TRUE(navigator.addAgent(agentBounds));
GetParam()(navigator);
{
auto updateGuard = navigator.makeUpdateGuard();
navigator.update(osg::Vec3f(3000, 3000, 0), updateGuard.get());
}
navigator.wait(WaitConditionType::requiredTilesPresent, &listener);
{
const auto navMesh = navigator.getNavMesh(agentBounds);
ASSERT_NE(navMesh, nullptr);
const TilePosition expectedTile(4, 4);
const auto usedTiles = getUsedTiles(*navMesh->lockConst());
EXPECT_THAT(usedTiles, Contains(expectedTile)) << usedTiles;
}
{
auto updateGuard = navigator.makeUpdateGuard();
navigator.update(osg::Vec3f(6000, 3000, 0), updateGuard.get());
}
navigator.wait(WaitConditionType::requiredTilesPresent, &listener);
{
const auto navMesh = navigator.getNavMesh(agentBounds);
ASSERT_NE(navMesh, nullptr);
const TilePosition expectedTile(8, 4);
const auto usedTiles = getUsedTiles(*navMesh->lockConst());
EXPECT_THAT(usedTiles, Contains(expectedTile)) << usedTiles;
}
}
struct AddHeightfieldSurface
{
static constexpr std::size_t sSize = 65;
static constexpr float sHeights[sSize * sSize]{};
void operator()(Navigator& navigator) const
{
const osg::Vec2i cellPosition(0, 0);
const HeightfieldSurface surface{
.mHeights = sHeights,
.mSize = sSize,
.mMinHeight = -1,
.mMaxHeight = 1,
};
const int cellSize = heightfieldTileSize * static_cast<int>(surface.mSize - 1);
navigator.addHeightfield(cellPosition, cellSize, surface, nullptr);
}
};
struct AddHeightfieldPlane
{
void operator()(Navigator& navigator) const
{
const osg::Vec2i cellPosition(0, 0);
const HeightfieldPlane plane{ .mHeight = 0 };
const int cellSize = 8192;
navigator.addHeightfield(cellPosition, cellSize, plane, nullptr);
}
};
struct AddWater
{
void operator()(Navigator& navigator) const
{
const osg::Vec2i cellPosition(0, 0);
const float level = 0;
const int cellSize = 8192;
navigator.addWater(cellPosition, cellSize, level, nullptr);
}
};
struct AddObject
{
const float mSize = 8192;
CollisionShapeInstance<btBoxShape> mBox{ std::make_unique<btBoxShape>(btVector3(mSize, mSize, 1)) };
const ObjectTransform mTransform{
.mPosition = ESM::Position{ .pos = { 0, 0, 0 }, .rot{ 0, 0, 0 } },
.mScale = 1.0f,
};
void operator()(Navigator& navigator) const
{
navigator.addObject(ObjectId(&mBox.shape()), ObjectShapes(mBox.instance(), mTransform),
btTransform::getIdentity(), nullptr);
}
};
struct AddAll
{
AddHeightfieldSurface mAddHeightfieldSurface;
AddHeightfieldPlane mAddHeightfieldPlane;
AddWater mAddWater;
AddObject mAddObject;
void operator()(Navigator& navigator) const
{
mAddHeightfieldSurface(navigator);
mAddHeightfieldPlane(navigator);
mAddWater(navigator);
mAddObject(navigator);
}
};
const std::function<void(Navigator&)> addNavMeshData[] = {
AddHeightfieldSurface{},
AddHeightfieldPlane{},
AddWater{},
AddObject{},
AddAll{},
};
INSTANTIATE_TEST_SUITE_P(DifferentNavMeshData, DetourNavigatorUpdateTest, ValuesIn(addNavMeshData));
}
| 57,871
|
C++
|
.cpp
| 1,058
| 45.045369
| 120
| 0.659185
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,196
|
navmeshdb.cpp
|
OpenMW_openmw/apps/components_tests/detournavigator/navmeshdb.cpp
|
#include "generate.hpp"
#include <components/detournavigator/navmeshdb.hpp>
#include <DetourAlloc.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <limits>
#include <random>
namespace
{
using namespace testing;
using namespace DetourNavigator;
using namespace DetourNavigator::Tests;
struct Tile
{
ESM::RefId mWorldspace;
TilePosition mTilePosition;
std::vector<std::byte> mInput;
std::vector<std::byte> mData;
};
struct DetourNavigatorNavMeshDbTest : Test
{
NavMeshDb mDb{ ":memory:", std::numeric_limits<std::uint64_t>::max() };
std::minstd_rand mRandom;
std::vector<std::byte> generateData()
{
std::vector<std::byte> data(32);
generateRange(data.begin(), data.end(), mRandom);
return data;
}
Tile insertTile(TileId tileId, TileVersion version)
{
const ESM::RefId worldspace = ESM::RefId::stringRefId("sys::default");
const TilePosition tilePosition{ 3, 4 };
std::vector<std::byte> input = generateData();
std::vector<std::byte> data = generateData();
EXPECT_EQ(mDb.insertTile(tileId, worldspace, tilePosition, version, input, data), 1);
return { worldspace, tilePosition, std::move(input), std::move(data) };
}
};
TEST_F(DetourNavigatorNavMeshDbTest, get_max_tile_id_for_empty_db_should_return_zero)
{
EXPECT_EQ(mDb.getMaxTileId(), TileId{ 0 });
}
TEST_F(DetourNavigatorNavMeshDbTest, inserted_tile_should_be_found_by_key)
{
const TileId tileId{ 146 };
const TileVersion version{ 1 };
const auto [worldspace, tilePosition, input, data] = insertTile(tileId, version);
const auto result = mDb.findTile(worldspace, tilePosition, input);
ASSERT_TRUE(result.has_value());
EXPECT_EQ(result->mTileId, tileId);
EXPECT_EQ(result->mVersion, version);
}
TEST_F(DetourNavigatorNavMeshDbTest, inserted_tile_should_change_max_tile_id)
{
insertTile(TileId{ 53 }, TileVersion{ 1 });
EXPECT_EQ(mDb.getMaxTileId(), TileId{ 53 });
}
TEST_F(DetourNavigatorNavMeshDbTest, updated_tile_should_change_data)
{
const TileId tileId{ 13 };
const TileVersion version{ 1 };
auto [worldspace, tilePosition, input, data] = insertTile(tileId, version);
generateRange(data.begin(), data.end(), mRandom);
ASSERT_EQ(mDb.updateTile(tileId, version, data), 1);
const auto row = mDb.getTileData(worldspace, tilePosition, input);
ASSERT_TRUE(row.has_value());
EXPECT_EQ(row->mTileId, tileId);
EXPECT_EQ(row->mVersion, version);
ASSERT_FALSE(row->mData.empty());
EXPECT_EQ(row->mData, data);
}
TEST_F(DetourNavigatorNavMeshDbTest, on_inserted_duplicate_should_throw_exception)
{
const TileId tileId{ 53 };
const TileVersion version{ 1 };
const ESM::RefId worldspace = ESM::RefId::stringRefId("sys::default");
const TilePosition tilePosition{ 3, 4 };
const std::vector<std::byte> input = generateData();
const std::vector<std::byte> data = generateData();
ASSERT_EQ(mDb.insertTile(tileId, worldspace, tilePosition, version, input, data), 1);
EXPECT_THROW(mDb.insertTile(tileId, worldspace, tilePosition, version, input, data), std::runtime_error);
}
TEST_F(DetourNavigatorNavMeshDbTest, inserted_duplicate_leaves_db_in_correct_state)
{
const TileId tileId{ 53 };
const TileVersion version{ 1 };
const ESM::RefId worldspace = ESM::RefId::stringRefId("sys::default");
const TilePosition tilePosition{ 3, 4 };
const std::vector<std::byte> input = generateData();
const std::vector<std::byte> data = generateData();
ASSERT_EQ(mDb.insertTile(tileId, worldspace, tilePosition, version, input, data), 1);
EXPECT_THROW(mDb.insertTile(tileId, worldspace, tilePosition, version, input, data), std::runtime_error);
EXPECT_NO_THROW(insertTile(TileId{ 54 }, version));
}
TEST_F(DetourNavigatorNavMeshDbTest, delete_tiles_at_should_remove_all_tiles_with_given_worldspace_and_position)
{
const TileVersion version{ 1 };
const ESM::RefId worldspace = ESM::RefId::stringRefId("sys::default");
const TilePosition tilePosition{ 3, 4 };
const std::vector<std::byte> input1 = generateData();
const std::vector<std::byte> input2 = generateData();
const std::vector<std::byte> data = generateData();
ASSERT_EQ(mDb.insertTile(TileId{ 53 }, worldspace, tilePosition, version, input1, data), 1);
ASSERT_EQ(mDb.insertTile(TileId{ 54 }, worldspace, tilePosition, version, input2, data), 1);
ASSERT_EQ(mDb.deleteTilesAt(worldspace, tilePosition), 2);
EXPECT_FALSE(mDb.findTile(worldspace, tilePosition, input1).has_value());
EXPECT_FALSE(mDb.findTile(worldspace, tilePosition, input2).has_value());
}
TEST_F(DetourNavigatorNavMeshDbTest, delete_tiles_at_except_should_leave_tile_with_given_id)
{
const TileId leftTileId{ 53 };
const TileId removedTileId{ 54 };
const TileVersion version{ 1 };
const ESM::RefId worldspace = ESM::RefId::stringRefId("sys::default");
const TilePosition tilePosition{ 3, 4 };
const std::vector<std::byte> leftInput = generateData();
const std::vector<std::byte> removedInput = generateData();
const std::vector<std::byte> data = generateData();
ASSERT_EQ(mDb.insertTile(leftTileId, worldspace, tilePosition, version, leftInput, data), 1);
ASSERT_EQ(mDb.insertTile(removedTileId, worldspace, tilePosition, version, removedInput, data), 1);
ASSERT_EQ(mDb.deleteTilesAtExcept(worldspace, tilePosition, leftTileId), 1);
const auto left = mDb.findTile(worldspace, tilePosition, leftInput);
ASSERT_TRUE(left.has_value());
EXPECT_EQ(left->mTileId, leftTileId);
EXPECT_FALSE(mDb.findTile(worldspace, tilePosition, removedInput).has_value());
}
TEST_F(DetourNavigatorNavMeshDbTest, delete_tiles_outside_range_should_leave_tiles_inside_given_rectangle)
{
TileId tileId{ 1 };
const TileVersion version{ 1 };
const ESM::RefId worldspace = ESM::RefId::stringRefId("sys::default");
const std::vector<std::byte> input = generateData();
const std::vector<std::byte> data = generateData();
for (int x = -2; x <= 2; ++x)
{
for (int y = -2; y <= 2; ++y)
{
ASSERT_EQ(mDb.insertTile(tileId, worldspace, TilePosition{ x, y }, version, input, data), 1);
++tileId;
}
}
const TilesPositionsRange range{ TilePosition{ -1, -1 }, TilePosition{ 2, 2 } };
ASSERT_EQ(mDb.deleteTilesOutsideRange(worldspace, range), 16);
for (int x = -2; x <= 2; ++x)
for (int y = -2; y <= 2; ++y)
ASSERT_EQ(mDb.findTile(worldspace, TilePosition{ x, y }, input).has_value(),
-1 <= x && x <= 1 && -1 <= y && y <= 1)
<< "x=" << x << " y=" << y;
}
TEST_F(DetourNavigatorNavMeshDbTest, should_support_file_size_limit)
{
mDb = NavMeshDb(":memory:", 4096);
const auto f = [&] {
for (std::int64_t i = 1; i <= 100; ++i)
insertTile(TileId{ i }, TileVersion{ 1 });
};
EXPECT_THROW(f(), std::runtime_error);
}
}
| 7,602
|
C++
|
.cpp
| 160
| 39.16875
| 116
| 0.638556
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,197
|
testgridsampling.cpp
|
OpenMW_openmw/apps/components_tests/esmterrain/testgridsampling.cpp
|
#include <components/esmterrain/gridsampling.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace ESMTerrain
{
namespace
{
using namespace testing;
struct Sample
{
std::size_t mCellX = 0;
std::size_t mCellY = 0;
std::size_t mLocalX = 0;
std::size_t mLocalY = 0;
std::size_t mVertexX = 0;
std::size_t mVertexY = 0;
};
auto tie(const Sample& v)
{
return std::tie(v.mCellX, v.mCellY, v.mLocalX, v.mLocalY, v.mVertexX, v.mVertexY);
}
bool operator==(const Sample& l, const Sample& r)
{
return tie(l) == tie(r);
}
std::ostream& operator<<(std::ostream& stream, const Sample& v)
{
return stream << "Sample{.mCellX = " << v.mCellX << ", .mCellY = " << v.mCellY
<< ", .mLocalX = " << v.mLocalX << ", .mLocalY = " << v.mLocalY
<< ", .mVertexX = " << v.mVertexX << ", .mVertexY = " << v.mVertexY << "}";
}
struct Collect
{
std::vector<Sample>& mSamples;
void operator()(std::size_t cellX, std::size_t cellY, std::size_t localX, std::size_t localY,
std::size_t vertexX, std::size_t vertexY)
{
mSamples.push_back(Sample{
.mCellX = cellX,
.mCellY = cellY,
.mLocalX = localX,
.mLocalY = localY,
.mVertexX = vertexX,
.mVertexY = vertexY,
});
}
};
TEST(ESMTerrainSampleCellGrid, doesNotSupportCellSizeLessThanTwo)
{
const std::size_t cellSize = 2;
EXPECT_THROW(sampleCellGrid(cellSize, 0, 0, 0, 0, [](auto...) {}), std::invalid_argument);
}
TEST(ESMTerrainSampleCellGrid, doesNotSupportCellSizeMinusOneNotPowerOfTwo)
{
const std::size_t cellSize = 4;
EXPECT_THROW(sampleCellGrid(cellSize, 0, 0, 0, 0, [](auto...) {}), std::invalid_argument);
}
TEST(ESMTerrainSampleCellGrid, doesNotSupportZeroSampleSize)
{
const std::size_t cellSize = 1;
const std::size_t sampleSize = 0;
EXPECT_THROW(sampleCellGrid(cellSize, sampleSize, 0, 0, 0, [](auto...) {}), std::invalid_argument);
}
TEST(ESMTerrainSampleCellGrid, doesNotSupportSampleSizeNotPowerOfTwo)
{
const std::size_t cellSize = 1;
const std::size_t sampleSize = 3;
EXPECT_THROW(sampleCellGrid(cellSize, sampleSize, 0, 0, 0, [](auto...) {}), std::invalid_argument);
}
TEST(ESMTerrainSampleCellGrid, doesNotSupportCountLessThanTwo)
{
const std::size_t cellSize = 1;
const std::size_t sampleSize = 1;
const std::size_t distance = 2;
EXPECT_THROW(sampleCellGrid(cellSize, sampleSize, 0, 0, distance, [](auto...) {}), std::invalid_argument);
}
TEST(ESMTerrainSampleCellGrid, doesNotSupportCountMinusOneNotPowerOfTwo)
{
const std::size_t cellSize = 1;
const std::size_t sampleSize = 1;
const std::size_t distance = 4;
EXPECT_THROW(sampleCellGrid(cellSize, sampleSize, 0, 0, distance, [](auto...) {}), std::invalid_argument);
}
TEST(ESMTerrainSampleCellGrid, sampleSizeOneShouldProduceNumberOfSamplesEqualToCellSize)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 1;
const std::size_t beginX = 0;
const std::size_t beginY = 0;
const std::size_t distance = 3;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 2, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 1, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 1, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 1, .mVertexX = 2, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 2, .mVertexX = 0, .mVertexY = 2 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 1, .mVertexY = 2 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 2, .mVertexY = 2 }));
}
TEST(ESMTerrainSampleCellGrid, countShouldLimitScope)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 1;
const std::size_t beginX = 0;
const std::size_t beginY = 0;
const std::size_t distance = 2;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 1, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 1, .mVertexY = 1 }));
}
TEST(ESMTerrainSampleCellGrid, beginXAndCountShouldLimitScope)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 1;
const std::size_t beginX = 1;
const std::size_t beginY = 0;
const std::size_t distance = 2;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 1, .mVertexX = 1, .mVertexY = 1 }));
}
TEST(ESMTerrainSampleCellGrid, beginYAndCountShouldLimitScope)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 1;
const std::size_t beginX = 0;
const std::size_t beginY = 1;
const std::size_t distance = 2;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 1, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 2, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 1, .mVertexY = 1 }));
}
TEST(ESMTerrainSampleCellGrid, beginAndCountShouldLimitScope)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 1;
const std::size_t beginX = 1;
const std::size_t beginY = 1;
const std::size_t distance = 2;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 1, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 1 }));
}
TEST(ESMTerrainSampleCellGrid, beginAndCountShouldLimitScopeInTheMiddleOfCell)
{
const std::size_t cellSize = 5;
const std::size_t sampleSize = 1;
const std::size_t beginX = 1;
const std::size_t beginY = 1;
const std::size_t distance = 2;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 1, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 1 }));
}
TEST(ESMTerrainSampleCellGrid, beginXWithCountLessThanCellSizeShouldLimitScopeAcrossCellBorder)
{
const std::size_t cellSize = 5;
const std::size_t sampleSize = 1;
const std::size_t beginX = 3;
const std::size_t beginY = 0;
const std::size_t distance = 3;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 3, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 4, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 2, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 3, .mLocalY = 1, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 4, .mLocalY = 1, .mVertexX = 1, .mVertexY = 1 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 2, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 3, .mLocalY = 2, .mVertexX = 0, .mVertexY = 2 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 4, .mLocalY = 2, .mVertexX = 1, .mVertexY = 2 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 2, .mVertexY = 2 }));
}
TEST(ESMTerrainSampleCellGrid, beginXWithCountEqualToCellSizeShouldLimitScopeAcrossCellBorder)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 1;
const std::size_t beginX = 1;
const std::size_t beginY = 0;
const std::size_t distance = 3;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 1, .mVertexX = 1, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 0, .mVertexY = 2 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 2 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 2, .mVertexY = 0 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 2, .mVertexY = 1 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 2, .mVertexY = 2 }));
}
TEST(ESMTerrainSampleCellGrid, beginXWithCountGreaterThanCellSizeShouldLimitScopeAcrossCellBorder)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 1;
const std::size_t beginX = 1;
const std::size_t beginY = 0;
const std::size_t distance = 5;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 1, .mVertexX = 1, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 0, .mVertexY = 2 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 2 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 2, .mVertexY = 0 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 3, .mVertexY = 0 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 2, .mVertexY = 1 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 2, .mLocalY = 1, .mVertexX = 3, .mVertexY = 1 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 2, .mVertexY = 2 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 3, .mVertexY = 2 },
Sample{ .mCellX = 2, .mCellY = 0, .mLocalX = 1, .mLocalY = 0, .mVertexX = 4, .mVertexY = 0 },
Sample{ .mCellX = 2, .mCellY = 0, .mLocalX = 1, .mLocalY = 1, .mVertexX = 4, .mVertexY = 1 },
Sample{ .mCellX = 2, .mCellY = 0, .mLocalX = 1, .mLocalY = 2, .mVertexX = 4, .mVertexY = 2 },
Sample{ .mCellX = 0, .mCellY = 1, .mLocalX = 1, .mLocalY = 1, .mVertexX = 0, .mVertexY = 3 },
Sample{ .mCellX = 0, .mCellY = 1, .mLocalX = 2, .mLocalY = 1, .mVertexX = 1, .mVertexY = 3 },
Sample{ .mCellX = 0, .mCellY = 1, .mLocalX = 1, .mLocalY = 2, .mVertexX = 0, .mVertexY = 4 },
Sample{ .mCellX = 0, .mCellY = 1, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 4 },
Sample{ .mCellX = 1, .mCellY = 1, .mLocalX = 1, .mLocalY = 1, .mVertexX = 2, .mVertexY = 3 },
Sample{ .mCellX = 1, .mCellY = 1, .mLocalX = 2, .mLocalY = 1, .mVertexX = 3, .mVertexY = 3 },
Sample{ .mCellX = 1, .mCellY = 1, .mLocalX = 1, .mLocalY = 2, .mVertexX = 2, .mVertexY = 4 },
Sample{ .mCellX = 1, .mCellY = 1, .mLocalX = 2, .mLocalY = 2, .mVertexX = 3, .mVertexY = 4 },
Sample{ .mCellX = 2, .mCellY = 1, .mLocalX = 1, .mLocalY = 1, .mVertexX = 4, .mVertexY = 3 },
Sample{ .mCellX = 2, .mCellY = 1, .mLocalX = 1, .mLocalY = 2, .mVertexX = 4, .mVertexY = 4 }));
}
TEST(ESMTerrainSampleCellGrid, sampleSizeGreaterThanOneShouldSkipPoints)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 2;
const std::size_t beginX = 0;
const std::size_t beginY = 0;
const std::size_t distance = 3;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 2, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 1 }));
}
TEST(ESMTerrainSampleCellGrid, shouldGroupByCell)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 2;
const std::size_t beginX = 0;
const std::size_t beginY = 0;
const std::size_t distance = 5;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 2, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 1 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 2, .mVertexY = 0 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 2, .mLocalY = 2, .mVertexX = 2, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 1, .mLocalX = 0, .mLocalY = 2, .mVertexX = 0, .mVertexY = 2 },
Sample{ .mCellX = 0, .mCellY = 1, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 2 },
Sample{ .mCellX = 1, .mCellY = 1, .mLocalX = 2, .mLocalY = 2, .mVertexX = 2, .mVertexY = 2 }));
}
TEST(ESMTerrainSampleCellGrid, sampleSizeGreaterThanCellSizeShouldPickSinglePointPerCell)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 4;
const std::size_t beginX = 0;
const std::size_t beginY = 0;
const std::size_t distance = 9;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 1, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 3, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 2, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 1, .mLocalX = 0, .mLocalY = 2, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 1, .mCellY = 1, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 1 },
Sample{ .mCellX = 3, .mCellY = 1, .mLocalX = 2, .mLocalY = 2, .mVertexX = 2, .mVertexY = 1 },
Sample{ .mCellX = 0, .mCellY = 3, .mLocalX = 0, .mLocalY = 2, .mVertexX = 0, .mVertexY = 2 },
Sample{ .mCellX = 1, .mCellY = 3, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 2 },
Sample{ .mCellX = 3, .mCellY = 3, .mLocalX = 2, .mLocalY = 2, .mVertexX = 2, .mVertexY = 2 }));
}
TEST(ESMTerrainSampleCellGrid, sampleSizeGreaterThan2CellSizeShouldSkipCells)
{
const std::size_t cellSize = 3;
const std::size_t sampleSize = 8;
const std::size_t beginX = 0;
const std::size_t beginY = 0;
const std::size_t distance = 9;
std::vector<Sample> samples;
sampleCellGrid(cellSize, sampleSize, beginX, beginY, distance, Collect{ samples });
EXPECT_THAT(samples,
ElementsAre( //
Sample{ .mCellX = 0, .mCellY = 0, .mLocalX = 0, .mLocalY = 0, .mVertexX = 0, .mVertexY = 0 },
Sample{ .mCellX = 3, .mCellY = 0, .mLocalX = 2, .mLocalY = 0, .mVertexX = 1, .mVertexY = 0 },
Sample{ .mCellX = 0, .mCellY = 3, .mLocalX = 0, .mLocalY = 2, .mVertexX = 0, .mVertexY = 1 },
Sample{ .mCellX = 3, .mCellY = 3, .mLocalX = 2, .mLocalY = 2, .mVertexX = 1, .mVertexY = 1 }));
}
auto tie(const CellSample& v)
{
return std::tie(v.mCellX, v.mCellY, v.mSrcRow, v.mSrcCol, v.mDstRow, v.mDstCol);
}
}
static bool operator==(const CellSample& l, const CellSample& r)
{
return tie(l) == tie(r);
}
static std::ostream& operator<<(std::ostream& stream, const CellSample& v)
{
return stream << "CellSample{.mCellX = " << v.mCellX << ", .mCellY = " << v.mCellY
<< ", .mSrcRow = " << v.mSrcRow << ", .mSrcCol = " << v.mSrcCol << ", .mDstRow = " << v.mDstRow
<< ", .mDstCol = " << v.mDstCol << "}";
}
namespace
{
struct CollectCellSamples
{
std::vector<CellSample>& mSamples;
void operator()(const CellSample& value) { mSamples.push_back(value); }
};
TEST(ESMTerrainSampleBlendmaps, doesNotSupportNotPositiveSize)
{
const float size = 0;
EXPECT_THROW(sampleBlendmaps(size, 0, 0, 0, [](auto...) {}), std::invalid_argument);
}
TEST(ESMTerrainSampleBlendmaps, doesNotSupportNotPositiveTextureSize)
{
const float size = 1;
const int textureSize = 0;
EXPECT_THROW(sampleBlendmaps(size, 0, 0, textureSize, [](auto...) {}), std::invalid_argument);
}
TEST(ESMTerrainSampleBlendmaps, shouldDecrementBeginRow)
{
const float size = 0.125f;
const float minX = 0.125f;
const float minY = 0.125f;
const int textureSize = 8;
std::vector<CellSample> samples;
sampleBlendmaps(size, minX, minY, textureSize, CollectCellSamples{ samples });
EXPECT_THAT(samples,
ElementsAre( //
CellSample{ .mCellX = 0, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 0, .mDstCol = 0 },
CellSample{ .mCellX = 0, .mCellY = 0, .mSrcRow = 1, .mSrcCol = 1, .mDstRow = 1, .mDstCol = 0 },
CellSample{ .mCellX = 0, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 2, .mDstRow = 0, .mDstCol = 1 },
CellSample{ .mCellX = 0, .mCellY = 0, .mSrcRow = 1, .mSrcCol = 2, .mDstRow = 1, .mDstCol = 1 }));
}
TEST(ESMTerrainSampleBlendmaps, shouldDecrementBeginRowOverCellBorder)
{
const float size = 0.125f;
const float minX = 0;
const float minY = 0;
const int textureSize = 8;
std::vector<CellSample> samples;
sampleBlendmaps(size, minX, minY, textureSize, CollectCellSamples{ samples });
EXPECT_THAT(samples,
ElementsAre( //
CellSample{ .mCellX = -1, .mCellY = 0, .mSrcRow = 7, .mSrcCol = 0, .mDstRow = 0, .mDstCol = 0 },
CellSample{ .mCellX = -1, .mCellY = 0, .mSrcRow = 7, .mSrcCol = 1, .mDstRow = 0, .mDstCol = 1 },
CellSample{ .mCellX = 0, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 0, .mDstRow = 1, .mDstCol = 0 },
CellSample{ .mCellX = 0, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 1, .mDstCol = 1 }));
}
TEST(ESMTerrainSampleBlendmaps, shouldSupportNegativeCoordinates)
{
const float size = 0.125f;
const float minX = -0.5f;
const float minY = -0.5f;
const int textureSize = 8;
std::vector<CellSample> samples;
sampleBlendmaps(size, minX, minY, textureSize, CollectCellSamples{ samples });
EXPECT_THAT(samples,
ElementsAre( //
CellSample{ .mCellX = -1, .mCellY = -1, .mSrcRow = 3, .mSrcCol = 4, .mDstRow = 0, .mDstCol = 0 },
CellSample{ .mCellX = -1, .mCellY = -1, .mSrcRow = 4, .mSrcCol = 4, .mDstRow = 1, .mDstCol = 0 },
CellSample{ .mCellX = -1, .mCellY = -1, .mSrcRow = 3, .mSrcCol = 5, .mDstRow = 0, .mDstCol = 1 },
CellSample{ .mCellX = -1, .mCellY = -1, .mSrcRow = 4, .mSrcCol = 5, .mDstRow = 1, .mDstCol = 1 }));
}
TEST(ESMTerrainSampleBlendmaps, shouldCoverMultipleCells)
{
const float size = 2;
const float minX = -1.5f;
const float minY = -1.5f;
const int textureSize = 2;
std::vector<CellSample> samples;
sampleBlendmaps(size, minX, minY, textureSize, CollectCellSamples{ samples });
EXPECT_THAT(samples,
ElementsAre( //
CellSample{ .mCellX = -2, .mCellY = -2, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 0, .mDstCol = 0 },
CellSample{ .mCellX = -2, .mCellY = -2, .mSrcRow = 1, .mSrcCol = 1, .mDstRow = 1, .mDstCol = 0 },
CellSample{ .mCellX = -1, .mCellY = -2, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 2, .mDstCol = 0 },
CellSample{ .mCellX = -1, .mCellY = -2, .mSrcRow = 1, .mSrcCol = 1, .mDstRow = 3, .mDstCol = 0 },
CellSample{ .mCellX = 0, .mCellY = -2, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 4, .mDstCol = 0 },
CellSample{ .mCellX = -2, .mCellY = -1, .mSrcRow = 0, .mSrcCol = 0, .mDstRow = 0, .mDstCol = 1 },
CellSample{ .mCellX = -2, .mCellY = -1, .mSrcRow = 1, .mSrcCol = 0, .mDstRow = 1, .mDstCol = 1 },
CellSample{ .mCellX = -2, .mCellY = -1, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 0, .mDstCol = 2 },
CellSample{ .mCellX = -2, .mCellY = -1, .mSrcRow = 1, .mSrcCol = 1, .mDstRow = 1, .mDstCol = 2 },
CellSample{ .mCellX = -1, .mCellY = -1, .mSrcRow = 0, .mSrcCol = 0, .mDstRow = 2, .mDstCol = 1 },
CellSample{ .mCellX = -1, .mCellY = -1, .mSrcRow = 1, .mSrcCol = 0, .mDstRow = 3, .mDstCol = 1 },
CellSample{ .mCellX = -1, .mCellY = -1, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 2, .mDstCol = 2 },
CellSample{ .mCellX = -1, .mCellY = -1, .mSrcRow = 1, .mSrcCol = 1, .mDstRow = 3, .mDstCol = 2 },
CellSample{ .mCellX = 0, .mCellY = -1, .mSrcRow = 0, .mSrcCol = 0, .mDstRow = 4, .mDstCol = 1 },
CellSample{ .mCellX = 0, .mCellY = -1, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 4, .mDstCol = 2 },
CellSample{ .mCellX = -2, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 0, .mDstRow = 0, .mDstCol = 3 },
CellSample{ .mCellX = -2, .mCellY = 0, .mSrcRow = 1, .mSrcCol = 0, .mDstRow = 1, .mDstCol = 3 },
CellSample{ .mCellX = -2, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 0, .mDstCol = 4 },
CellSample{ .mCellX = -2, .mCellY = 0, .mSrcRow = 1, .mSrcCol = 1, .mDstRow = 1, .mDstCol = 4 },
CellSample{ .mCellX = -1, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 0, .mDstRow = 2, .mDstCol = 3 },
CellSample{ .mCellX = -1, .mCellY = 0, .mSrcRow = 1, .mSrcCol = 0, .mDstRow = 3, .mDstCol = 3 },
CellSample{ .mCellX = -1, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 2, .mDstCol = 4 },
CellSample{ .mCellX = -1, .mCellY = 0, .mSrcRow = 1, .mSrcCol = 1, .mDstRow = 3, .mDstCol = 4 },
CellSample{ .mCellX = 0, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 0, .mDstRow = 4, .mDstCol = 3 },
CellSample{ .mCellX = 0, .mCellY = 0, .mSrcRow = 0, .mSrcCol = 1, .mDstRow = 4, .mDstCol = 4 }));
}
}
}
| 28,953
|
C++
|
.cpp
| 453
| 49.302428
| 119
| 0.516829
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,198
|
testbulletnifloader.cpp
|
OpenMW_openmw/apps/components_tests/nifloader/testbulletnifloader.cpp
|
#include "../nif/node.hpp"
#include <components/bullethelpers/processtrianglecallback.hpp>
#include <components/nif/data.hpp>
#include <components/nif/extra.hpp>
#include <components/nif/node.hpp>
#include <components/nifbullet/bulletnifloader.hpp>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <BulletCollision/CollisionShapes/btCompoundShape.h>
#include <BulletCollision/CollisionShapes/btTriangleMesh.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <span>
#include <type_traits>
namespace
{
template <class T>
bool compareObjects(const T* lhs, const T* rhs)
{
return (!lhs && !rhs) || (lhs && rhs && *lhs == *rhs);
}
std::vector<btVector3> getTriangles(const btBvhTriangleMeshShape& shape)
{
std::vector<btVector3> result;
auto callback = BulletHelpers::makeProcessTriangleCallback([&](btVector3* triangle, int, int) {
for (std::size_t i = 0; i < 3; ++i)
result.push_back(triangle[i]);
});
btVector3 aabbMin;
btVector3 aabbMax;
shape.getAabb(btTransform::getIdentity(), aabbMin, aabbMax);
shape.processAllTriangles(&callback, aabbMin, aabbMax);
return result;
}
bool isNear(btScalar lhs, btScalar rhs)
{
return std::abs(lhs - rhs) <= 1e-5;
}
bool isNear(const btVector3& lhs, const btVector3& rhs)
{
return std::equal(static_cast<const btScalar*>(lhs), static_cast<const btScalar*>(lhs) + 3,
static_cast<const btScalar*>(rhs), [](btScalar lhs, btScalar rhs) { return isNear(lhs, rhs); });
}
bool isNear(const btMatrix3x3& lhs, const btMatrix3x3& rhs)
{
for (int i = 0; i < 3; ++i)
if (!isNear(lhs[i], rhs[i]))
return false;
return true;
}
bool isNear(const btTransform& lhs, const btTransform& rhs)
{
return isNear(lhs.getOrigin(), rhs.getOrigin()) && isNear(lhs.getBasis(), rhs.getBasis());
}
bool isNear(std::span<const btVector3> lhs, std::span<const btVector3> rhs)
{
if (lhs.size() != rhs.size())
return false;
return std::equal(
lhs.begin(), lhs.end(), rhs.begin(), [](const btVector3& l, const btVector3& r) { return isNear(l, r); });
}
struct WriteVec3f
{
osg::Vec3f mValue;
friend std::ostream& operator<<(std::ostream& stream, const WriteVec3f& value)
{
return stream << "osg::Vec3f {" << std::setprecision(std::numeric_limits<float>::max_exponent10)
<< value.mValue.x() << ", " << std::setprecision(std::numeric_limits<float>::max_exponent10)
<< value.mValue.y() << ", " << std::setprecision(std::numeric_limits<float>::max_exponent10)
<< value.mValue.z() << "}";
}
};
}
static std::ostream& operator<<(std::ostream& stream, const btVector3& value)
{
return stream << "btVector3 {" << std::setprecision(std::numeric_limits<float>::max_exponent10) << value.getX()
<< ", " << std::setprecision(std::numeric_limits<float>::max_exponent10) << value.getY() << ", "
<< std::setprecision(std::numeric_limits<float>::max_exponent10) << value.getZ() << "}";
}
static std::ostream& operator<<(std::ostream& stream, const btMatrix3x3& value)
{
stream << "btMatrix3x3 {";
for (int i = 0; i < 3; ++i)
stream << value.getRow(i) << ", ";
return stream << "}";
}
static std::ostream& operator<<(std::ostream& stream, const btTransform& value)
{
return stream << "btTransform {" << value.getBasis() << ", " << value.getOrigin() << "}";
}
static std::ostream& operator<<(std::ostream& stream, const btCollisionShape* value);
static std::ostream& operator<<(std::ostream& stream, const btCompoundShape& value)
{
stream << "btCompoundShape {" << value.getLocalScaling() << ", ";
stream << "{";
for (int i = 0; i < value.getNumChildShapes(); ++i)
stream << value.getChildShape(i) << ", ";
stream << "},";
stream << "{";
for (int i = 0; i < value.getNumChildShapes(); ++i)
stream << value.getChildTransform(i) << ", ";
stream << "}";
return stream << "}";
}
static std::ostream& operator<<(std::ostream& stream, const btBoxShape& value)
{
return stream << "btBoxShape {" << value.getLocalScaling() << ", " << value.getHalfExtentsWithoutMargin() << "}";
}
namespace Resource
{
static std::ostream& operator<<(std::ostream& stream, const TriangleMeshShape& value)
{
stream << "Resource::TriangleMeshShape {" << value.getLocalScaling() << ", "
<< value.usesQuantizedAabbCompression() << ", " << value.getOwnsBvh() << ", {";
auto callback = BulletHelpers::makeProcessTriangleCallback([&](btVector3* triangle, int, int) {
for (std::size_t i = 0; i < 3; ++i)
stream << triangle[i] << ", ";
});
btVector3 aabbMin;
btVector3 aabbMax;
value.getAabb(btTransform::getIdentity(), aabbMin, aabbMax);
value.processAllTriangles(&callback, aabbMin, aabbMax);
return stream << "}}";
}
static std::ostream& operator<<(std::ostream& stream, const ScaledTriangleMeshShape& value)
{
return stream << "Resource::ScaledTriangleMeshShape {" << value.getLocalScaling() << ", "
<< value.getChildShape() << "}";
}
static bool operator==(const CollisionBox& l, const CollisionBox& r)
{
const auto tie = [](const CollisionBox& v) { return std::tie(v.mExtents, v.mCenter); };
return tie(l) == tie(r);
}
static std::ostream& operator<<(std::ostream& stream, const CollisionBox& value)
{
return stream << "CollisionBox {" << WriteVec3f{ value.mExtents } << ", " << WriteVec3f{ value.mCenter } << "}";
}
}
static std::ostream& operator<<(std::ostream& stream, const btCollisionShape& value)
{
switch (value.getShapeType())
{
case COMPOUND_SHAPE_PROXYTYPE:
return stream << static_cast<const btCompoundShape&>(value);
case BOX_SHAPE_PROXYTYPE:
return stream << static_cast<const btBoxShape&>(value);
case TRIANGLE_MESH_SHAPE_PROXYTYPE:
if (const auto casted = dynamic_cast<const Resource::TriangleMeshShape*>(&value))
return stream << *casted;
break;
case SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE:
if (const auto casted = dynamic_cast<const Resource::ScaledTriangleMeshShape*>(&value))
return stream << *casted;
break;
}
return stream << "btCollisionShape {" << value.getShapeType() << "}";
}
static std::ostream& operator<<(std::ostream& stream, const btCollisionShape* value)
{
return value ? stream << "&" << *value : stream << "nullptr";
}
namespace std
{
static std::ostream& operator<<(std::ostream& stream, const map<int, int>& value)
{
stream << "std::map<int, int> {";
for (const auto& v : value)
stream << "{" << v.first << ", " << v.second << "},";
return stream << "}";
}
}
namespace Resource
{
static bool operator==(const Resource::BulletShape& lhs, const Resource::BulletShape& rhs)
{
return compareObjects(lhs.mCollisionShape.get(), rhs.mCollisionShape.get())
&& compareObjects(lhs.mAvoidCollisionShape.get(), rhs.mAvoidCollisionShape.get())
&& lhs.mCollisionBox == rhs.mCollisionBox && lhs.mVisualCollisionType == rhs.mVisualCollisionType
&& lhs.mAnimatedShapes == rhs.mAnimatedShapes;
}
static std::ostream& operator<<(std::ostream& stream, Resource::VisualCollisionType value)
{
switch (value)
{
case Resource::VisualCollisionType::None:
return stream << "Resource::VisualCollisionType::None";
case Resource::VisualCollisionType::Default:
return stream << "Resource::VisualCollisionType::Default";
case Resource::VisualCollisionType::Camera:
return stream << "Resource::VisualCollisionType::Camera";
}
return stream << static_cast<std::underlying_type_t<Resource::VisualCollisionType>>(value);
}
static std::ostream& operator<<(std::ostream& stream, const Resource::BulletShape& value)
{
return stream << "Resource::BulletShape {" << value.mCollisionShape.get() << ", "
<< value.mAvoidCollisionShape.get() << ", " << value.mCollisionBox << ", "
<< value.mAnimatedShapes << ", " << value.mVisualCollisionType << "}";
}
}
static bool operator==(const btCollisionShape& lhs, const btCollisionShape& rhs);
static bool operator==(const btCompoundShape& lhs, const btCompoundShape& rhs)
{
if (lhs.getNumChildShapes() != rhs.getNumChildShapes() || lhs.getLocalScaling() != rhs.getLocalScaling())
return false;
for (int i = 0; i < lhs.getNumChildShapes(); ++i)
{
if (!compareObjects(lhs.getChildShape(i), rhs.getChildShape(i))
|| !isNear(lhs.getChildTransform(i), rhs.getChildTransform(i)))
return false;
}
return true;
}
static bool operator==(const btBoxShape& lhs, const btBoxShape& rhs)
{
return isNear(lhs.getLocalScaling(), rhs.getLocalScaling())
&& lhs.getHalfExtentsWithoutMargin() == rhs.getHalfExtentsWithoutMargin();
}
static bool operator==(const btBvhTriangleMeshShape& lhs, const btBvhTriangleMeshShape& rhs)
{
return isNear(lhs.getLocalScaling(), rhs.getLocalScaling())
&& lhs.usesQuantizedAabbCompression() == rhs.usesQuantizedAabbCompression()
&& lhs.getOwnsBvh() == rhs.getOwnsBvh() && isNear(getTriangles(lhs), getTriangles(rhs));
}
static bool operator==(const btScaledBvhTriangleMeshShape& lhs, const btScaledBvhTriangleMeshShape& rhs)
{
return isNear(lhs.getLocalScaling(), rhs.getLocalScaling())
&& compareObjects(lhs.getChildShape(), rhs.getChildShape());
}
static bool operator==(const btCollisionShape& lhs, const btCollisionShape& rhs)
{
if (lhs.getShapeType() != rhs.getShapeType())
return false;
switch (lhs.getShapeType())
{
case COMPOUND_SHAPE_PROXYTYPE:
return static_cast<const btCompoundShape&>(lhs) == static_cast<const btCompoundShape&>(rhs);
case BOX_SHAPE_PROXYTYPE:
return static_cast<const btBoxShape&>(lhs) == static_cast<const btBoxShape&>(rhs);
case TRIANGLE_MESH_SHAPE_PROXYTYPE:
if (const auto lhsCasted = dynamic_cast<const Resource::TriangleMeshShape*>(&lhs))
if (const auto rhsCasted = dynamic_cast<const Resource::TriangleMeshShape*>(&rhs))
return *lhsCasted == *rhsCasted;
return false;
case SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE:
if (const auto lhsCasted = dynamic_cast<const Resource::ScaledTriangleMeshShape*>(&lhs))
if (const auto rhsCasted = dynamic_cast<const Resource::ScaledTriangleMeshShape*>(&rhs))
return *lhsCasted == *rhsCasted;
return false;
}
return false;
}
namespace
{
using namespace testing;
using namespace Nif::Testing;
using NifBullet::BulletNifLoader;
void copy(const btTransform& src, Nif::NiTransform& dst)
{
dst.mTranslation = osg::Vec3f(src.getOrigin().x(), src.getOrigin().y(), src.getOrigin().z());
for (int row = 0; row < 3; ++row)
for (int column = 0; column < 3; ++column)
dst.mRotation.mValues[row][column] = src.getBasis().getRow(row)[column];
}
struct TestBulletNifLoader : Test
{
BulletNifLoader mLoader;
Nif::NiAVObject mNode;
Nif::NiAVObject mNode2;
Nif::NiNode mNiNode;
Nif::NiNode mNiNode2;
Nif::NiNode mNiNode3;
Nif::NiTriShapeData mNiTriShapeData;
Nif::NiTriShape mNiTriShape;
Nif::NiTriShapeData mNiTriShapeData2;
Nif::NiTriShape mNiTriShape2;
Nif::NiTriStripsData mNiTriStripsData;
Nif::NiTriStrips mNiTriStrips;
Nif::NiSkinInstance mNiSkinInstance;
Nif::NiStringExtraData mNiStringExtraData;
Nif::NiStringExtraData mNiStringExtraData2;
Nif::NiIntegerExtraData mNiIntegerExtraData;
Nif::NiTimeController mController;
btTransform mTransform{ btMatrix3x3(btQuaternion(btVector3(1, 0, 0), 0.5f)), btVector3(1, 2, 3) };
btTransform mTransformScale2{ btMatrix3x3(btQuaternion(btVector3(1, 0, 0), 0.5f)), btVector3(2, 4, 6) };
btTransform mTransformScale3{ btMatrix3x3(btQuaternion(btVector3(1, 0, 0), 0.5f)), btVector3(3, 6, 9) };
btTransform mTransformScale4{ btMatrix3x3(btQuaternion(btVector3(1, 0, 0), 0.5f)), btVector3(4, 8, 12) };
const std::string mHash = "hash";
TestBulletNifLoader()
{
init(mNode);
init(mNode2);
init(mNiNode);
init(mNiNode2);
init(mNiNode3);
init(mNiTriShape);
init(mNiTriShape2);
init(mNiTriStrips);
init(mNiSkinInstance);
init(mNiStringExtraData);
init(mNiStringExtraData2);
init(mController);
mNiTriShapeData.recType = Nif::RC_NiTriShapeData;
mNiTriShapeData.mVertices = { osg::Vec3f(0, 0, 0), osg::Vec3f(1, 0, 0), osg::Vec3f(1, 1, 0) };
mNiTriShapeData.mNumTriangles = 1;
mNiTriShapeData.mTriangles = { 0, 1, 2 };
mNiTriShape.mData = Nif::NiGeometryDataPtr(&mNiTriShapeData);
mNiTriShapeData2.recType = Nif::RC_NiTriShapeData;
mNiTriShapeData2.mVertices = { osg::Vec3f(0, 0, 1), osg::Vec3f(1, 0, 1), osg::Vec3f(1, 1, 1) };
mNiTriShapeData2.mNumTriangles = 1;
mNiTriShapeData2.mTriangles = { 0, 1, 2 };
mNiTriShape2.mData = Nif::NiGeometryDataPtr(&mNiTriShapeData2);
mNiTriStripsData.recType = Nif::RC_NiTriStripsData;
mNiTriStripsData.mVertices
= { osg::Vec3f(0, 0, 0), osg::Vec3f(1, 0, 0), osg::Vec3f(1, 1, 0), osg::Vec3f(0, 1, 0) };
mNiTriStripsData.mNumTriangles = 2;
mNiTriStripsData.mStrips = { { 0, 1, 2, 3 } };
mNiTriStrips.mData = Nif::NiGeometryDataPtr(&mNiTriStripsData);
}
};
TEST_F(TestBulletNifLoader, for_zero_num_roots_should_return_default)
{
Nif::NIFFile file("test.nif");
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
EXPECT_EQ(result->mFileName, "test.nif");
EXPECT_EQ(result->mFileHash, mHash);
}
TEST_F(TestBulletNifLoader, should_ignore_nullptr_root)
{
Nif::NIFFile file("test.nif");
file.mRoots.push_back(nullptr);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_default_root_nif_node_should_return_default)
{
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_default_root_collision_node_nif_node_should_return_default)
{
mNode.recType = Nif::RC_RootCollisionNode;
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_default_root_nif_node_and_filename_starting_with_x_should_return_default)
{
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_root_bounding_box_should_return_shape_with_bounding_box_data)
{
mNode.mName = "Bounding Box";
mNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNode.mBounds.mBox.mExtents = osg::Vec3f(1, 2, 3);
mNode.mBounds.mBox.mCenter = osg::Vec3f(-1, -2, -3);
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
expected.mCollisionBox.mExtents = osg::Vec3f(1, 2, 3);
expected.mCollisionBox.mCenter = osg::Vec3f(-1, -2, -3);
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_child_bounding_box_should_return_shape_with_bounding_box_data)
{
mNode.mName = "Bounding Box";
mNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNode.mBounds.mBox.mExtents = osg::Vec3f(1, 2, 3);
mNode.mBounds.mBox.mCenter = osg::Vec3f(-1, -2, -3);
mNode.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNode) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
expected.mCollisionBox.mExtents = osg::Vec3f(1, 2, 3);
expected.mCollisionBox.mCenter = osg::Vec3f(-1, -2, -3);
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_root_with_bounds_and_child_bounding_box_should_use_bounding_box)
{
mNode.mName = "Bounding Box";
mNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNode.mBounds.mBox.mExtents = osg::Vec3f(1, 2, 3);
mNode.mBounds.mBox.mCenter = osg::Vec3f(-1, -2, -3);
mNode.mParents.push_back(&mNiNode);
mNiNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNiNode.mBounds.mBox.mExtents = osg::Vec3f(4, 5, 6);
mNiNode.mBounds.mBox.mCenter = osg::Vec3f(-4, -5, -6);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNode) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
expected.mCollisionBox.mExtents = osg::Vec3f(1, 2, 3);
expected.mCollisionBox.mCenter = osg::Vec3f(-1, -2, -3);
EXPECT_EQ(*result, expected);
}
TEST_F(
TestBulletNifLoader, for_root_and_two_children_where_both_with_bounds_but_one_is_bounding_box_use_bounding_box)
{
mNode.mName = "Bounding Box";
mNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNode.mBounds.mBox.mExtents = osg::Vec3f(1, 2, 3);
mNode.mBounds.mBox.mCenter = osg::Vec3f(-1, -2, -3);
mNode.mParents.push_back(&mNiNode);
mNode2.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNode2.mBounds.mBox.mExtents = osg::Vec3f(4, 5, 6);
mNode2.mBounds.mBox.mCenter = osg::Vec3f(-4, -5, -6);
mNode2.mParents.push_back(&mNiNode);
mNiNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNiNode.mBounds.mBox.mExtents = osg::Vec3f(7, 8, 9);
mNiNode.mBounds.mBox.mCenter = osg::Vec3f(-7, -8, -9);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNode), Nif::NiAVObjectPtr(&mNode2) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
expected.mCollisionBox.mExtents = osg::Vec3f(1, 2, 3);
expected.mCollisionBox.mCenter = osg::Vec3f(-1, -2, -3);
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader,
for_root_and_two_children_where_both_with_bounds_but_second_is_bounding_box_use_bounding_box)
{
mNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNode.mBounds.mBox.mExtents = osg::Vec3f(1, 2, 3);
mNode.mBounds.mBox.mCenter = osg::Vec3f(-1, -2, -3);
mNode.mParents.push_back(&mNiNode);
mNode2.mName = "Bounding Box";
mNode2.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNode2.mBounds.mBox.mExtents = osg::Vec3f(4, 5, 6);
mNode2.mBounds.mBox.mCenter = osg::Vec3f(-4, -5, -6);
mNode2.mParents.push_back(&mNiNode);
mNiNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNiNode.mBounds.mBox.mExtents = osg::Vec3f(7, 8, 9);
mNiNode.mBounds.mBox.mCenter = osg::Vec3f(-7, -8, -9);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNode), Nif::NiAVObjectPtr(&mNode2) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
expected.mCollisionBox.mExtents = osg::Vec3f(4, 5, 6);
expected.mCollisionBox.mCenter = osg::Vec3f(-4, -5, -6);
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_root_nif_node_with_bounds_should_return_shape_with_null_collision_shape)
{
mNode.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNode.mBounds.mBox.mExtents = osg::Vec3f(1, 2, 3);
mNode.mBounds.mBox.mCenter = osg::Vec3f(-1, -2, -3);
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_shape_root_node_should_return_static_shape)
{
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiTriShape);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
auto triShape = std::make_unique<Resource::TriangleMeshShape>(triangles.release(), true);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(triShape.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_shape_root_node_with_bounds_should_return_static_shape)
{
mNiTriShape.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNiTriShape.mBounds.mBox.mExtents = osg::Vec3f(1, 2, 3);
mNiTriShape.mBounds.mBox.mCenter = osg::Vec3f(-1, -2, -3);
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiTriShape);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
auto triShape = std::make_unique<Resource::TriangleMeshShape>(triangles.release(), true);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(triShape.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_shape_child_node_should_return_static_shape)
{
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
auto triShape = std::make_unique<Resource::TriangleMeshShape>(triangles.release(), true);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(triShape.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_nested_tri_shape_child_should_return_static_shape)
{
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiNode2) };
mNiNode2.mParents.push_back(&mNiNode);
mNiNode2.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
mNiTriShape.mParents.push_back(&mNiNode2);
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
auto triShape = std::make_unique<Resource::TriangleMeshShape>(triangles.release(), true);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(triShape.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_two_tri_shape_children_should_return_static_shape_with_all_meshes)
{
mNiTriShape.mParents.push_back(&mNiNode);
mNiTriShape2.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape), Nif::NiAVObjectPtr(&mNiTriShape2) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<btTriangleMesh> triangles2(new btTriangleMesh(false));
triangles2->addTriangle(btVector3(0, 0, 1), btVector3(1, 0, 1), btVector3(1, 1, 1));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
auto triShape = std::make_unique<Resource::TriangleMeshShape>(triangles.release(), true);
auto triShape2 = std::make_unique<Resource::TriangleMeshShape>(triangles2.release(), true);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(triShape.release(), btVector3(1, 1, 1)));
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(triShape2.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader,
for_tri_shape_child_node_and_filename_starting_with_x_and_not_empty_skin_should_return_static_shape)
{
mNiTriShape.mSkin = Nif::NiSkinInstancePtr(&mNiSkinInstance);
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
auto triShape = std::make_unique<Resource::TriangleMeshShape>(triangles.release(), true);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(triShape.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_shape_root_node_and_filename_starting_with_x_should_return_animated_shape)
{
copy(mTransform, mNiTriShape.mTransform);
mNiTriShape.mTransform.mScale = 3;
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNiTriShape);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> shape(new btCompoundShape);
shape->addChildShape(mTransform, new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(3, 3, 3)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(shape.release());
expected.mAnimatedShapes = { { -1, 0 } };
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_shape_child_node_and_filename_starting_with_x_should_return_animated_shape)
{
copy(mTransform, mNiTriShape.mTransform);
mNiTriShape.mTransform.mScale = 3;
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
mNiNode.mTransform.mScale = 4;
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> shape(new btCompoundShape);
shape->addChildShape(
mTransformScale4, new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(12, 12, 12)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(shape.release());
expected.mAnimatedShapes = { { -1, 0 } };
EXPECT_EQ(*result, expected);
}
TEST_F(
TestBulletNifLoader, for_two_tri_shape_children_nodes_and_filename_starting_with_x_should_return_animated_shape)
{
copy(mTransform, mNiTriShape.mTransform);
mNiTriShape.mTransform.mScale = 3;
mNiTriShape.mParents.push_back(&mNiNode);
copy(mTransform, mNiTriShape2.mTransform);
mNiTriShape2.mTransform.mScale = 3;
mNiTriShape2.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape), Nif::NiAVObjectPtr(&mNiTriShape2) };
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btTriangleMesh> triangles2(new btTriangleMesh(false));
triangles2->addTriangle(btVector3(0, 0, 1), btVector3(1, 0, 1), btVector3(1, 1, 1));
std::unique_ptr<Resource::TriangleMeshShape> mesh2(new Resource::TriangleMeshShape(triangles2.release(), true));
std::unique_ptr<btCompoundShape> shape(new btCompoundShape);
shape->addChildShape(mTransform, new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(3, 3, 3)));
shape->addChildShape(mTransform, new Resource::ScaledTriangleMeshShape(mesh2.release(), btVector3(3, 3, 3)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(shape.release());
expected.mAnimatedShapes = { { -1, 0 } };
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_shape_child_node_with_controller_should_return_animated_shape)
{
mController.recType = Nif::RC_NiKeyframeController;
mController.mFlags |= Nif::NiTimeController::Flag_Active;
copy(mTransform, mNiTriShape.mTransform);
mNiTriShape.mTransform.mScale = 3;
mNiTriShape.mParents.push_back(&mNiNode);
mNiTriShape.mController = Nif::NiTimeControllerPtr(&mController);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
mNiNode.mTransform.mScale = 4;
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> shape(new btCompoundShape);
shape->addChildShape(
mTransformScale4, new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(12, 12, 12)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(shape.release());
expected.mAnimatedShapes = { { -1, 0 } };
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_two_tri_shape_children_nodes_where_one_with_controller_should_return_animated_shape)
{
mController.recType = Nif::RC_NiKeyframeController;
mController.mFlags |= Nif::NiTimeController::Flag_Active;
copy(mTransform, mNiTriShape.mTransform);
mNiTriShape.mTransform.mScale = 3;
mNiTriShape.mParents.push_back(&mNiNode);
copy(mTransform, mNiTriShape2.mTransform);
mNiTriShape2.mTransform.mScale = 3;
mNiTriShape2.mParents.push_back(&mNiNode);
mNiTriShape2.mController = Nif::NiTimeControllerPtr(&mController);
mNiNode.mChildren = Nif::NiAVObjectList{
Nif::NiAVObjectPtr(&mNiTriShape),
Nif::NiAVObjectPtr(&mNiTriShape2),
};
mNiNode.mTransform.mScale = 4;
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btTriangleMesh> triangles2(new btTriangleMesh(false));
triangles2->addTriangle(btVector3(0, 0, 1), btVector3(1, 0, 1), btVector3(1, 1, 1));
std::unique_ptr<Resource::TriangleMeshShape> mesh2(new Resource::TriangleMeshShape(triangles2.release(), true));
std::unique_ptr<btCompoundShape> shape(new btCompoundShape);
shape->addChildShape(
mTransformScale4, new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(12, 12, 12)));
shape->addChildShape(
mTransformScale4, new Resource::ScaledTriangleMeshShape(mesh2.release(), btVector3(12, 12, 12)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(shape.release());
expected.mAnimatedShapes = { { -1, 1 } };
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, should_add_static_mesh_to_existing_compound_mesh)
{
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNiNode);
file.mRoots.push_back(&mNiTriShape2);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btTriangleMesh> triangles2(new btTriangleMesh(false));
triangles2->addTriangle(btVector3(0, 0, 1), btVector3(1, 0, 1), btVector3(1, 1, 1));
std::unique_ptr<Resource::TriangleMeshShape> mesh2(new Resource::TriangleMeshShape(triangles2.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh2.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
expected.mAnimatedShapes = { { -1, 0 } };
EXPECT_EQ(*result, expected);
}
TEST_F(
TestBulletNifLoader, for_root_avoid_node_and_tri_shape_child_node_should_return_shape_with_null_collision_shape)
{
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
mNiNode.recType = Nif::RC_AvoidNode;
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mAvoidCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_shape_child_node_with_empty_data_should_return_shape_with_null_collision_shape)
{
mNiTriShape.mData = Nif::NiGeometryDataPtr(nullptr);
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader,
for_tri_shape_child_node_with_empty_data_triangles_should_return_shape_with_null_collision_shape)
{
auto data = static_cast<Nif::NiTriShapeData*>(mNiTriShape.mData.getPtr());
data->mTriangles.clear();
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader,
for_root_node_with_extra_data_string_equal_ncc_should_return_shape_with_cameraonly_collision)
{
mNiStringExtraData.mData = "NCC__";
mNiStringExtraData.recType = Nif::RC_NiStringExtraData;
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mExtra = Nif::ExtraPtr(&mNiStringExtraData);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
expected.mVisualCollisionType = Resource::VisualCollisionType::Camera;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader,
for_root_node_with_not_first_extra_data_string_equal_ncc_should_return_shape_with_cameraonly_collision)
{
mNiStringExtraData.mNext = Nif::ExtraPtr(&mNiStringExtraData2);
mNiStringExtraData2.mData = "NCC__";
mNiStringExtraData2.recType = Nif::RC_NiStringExtraData;
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mExtra = Nif::ExtraPtr(&mNiStringExtraData);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
expected.mVisualCollisionType = Resource::VisualCollisionType::Camera;
EXPECT_EQ(*result, expected);
}
TEST_F(
TestBulletNifLoader, for_root_node_with_extra_data_string_starting_with_nc_should_return_shape_with_nocollision)
{
mNiStringExtraData.mData = "NC___";
mNiStringExtraData.recType = Nif::RC_NiStringExtraData;
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mExtra = Nif::ExtraPtr(&mNiStringExtraData);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
expected.mVisualCollisionType = Resource::VisualCollisionType::Default;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader,
for_root_node_with_not_first_extra_data_string_starting_with_nc_should_return_shape_with_nocollision)
{
mNiStringExtraData.mNext = Nif::ExtraPtr(&mNiStringExtraData2);
mNiStringExtraData2.mData = "NC___";
mNiStringExtraData2.recType = Nif::RC_NiStringExtraData;
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mExtra = Nif::ExtraPtr(&mNiStringExtraData);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
expected.mVisualCollisionType = Resource::VisualCollisionType::Default;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_shape_child_node_with_extra_data_string_should_ignore_extra_data)
{
mNiStringExtraData.mData = "NC___";
mNiStringExtraData.recType = Nif::RC_NiStringExtraData;
mNiTriShape.mExtra = Nif::ExtraPtr(&mNiStringExtraData);
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_empty_root_collision_node_without_nc_should_return_shape_with_cameraonly_collision)
{
Nif::NiTriShape niTriShape;
Nif::NiNode emptyCollisionNode;
init(niTriShape);
init(emptyCollisionNode);
niTriShape.mData = Nif::NiGeometryDataPtr(&mNiTriShapeData);
niTriShape.mParents.push_back(&mNiNode);
emptyCollisionNode.recType = Nif::RC_RootCollisionNode;
emptyCollisionNode.mParents.push_back(&mNiNode);
mNiNode.mChildren
= Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&niTriShape), Nif::NiAVObjectPtr(&emptyCollisionNode) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
expected.mVisualCollisionType = Resource::VisualCollisionType::Camera;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, bsx_editor_marker_flag_disables_collision_for_markers)
{
mNiTriShape.mParents.push_back(&mNiNode);
mNiTriShape.mName = "EditorMarker";
mNiIntegerExtraData.mData = 34; // BSXFlags "has collision" | "editor marker"
mNiIntegerExtraData.recType = Nif::RC_BSXFlags;
mNiNode.mExtraList.push_back(Nif::ExtraPtr(&mNiIntegerExtraData));
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
file.mVersion = Nif::NIFStream::generateVersion(10, 0, 1, 0);
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, mrk_editor_marker_flag_disables_collision_for_markers)
{
mNiTriShape.mParents.push_back(&mNiNode);
mNiTriShape.mName = "Tri EditorMarker";
mNiStringExtraData.mData = "MRK";
mNiStringExtraData.recType = Nif::RC_NiStringExtraData;
mNiNode.mExtra = Nif::ExtraPtr(&mNiStringExtraData);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_tri_strips_root_node_should_return_static_shape)
{
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiTriStrips);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
triangles->addTriangle(btVector3(1, 0, 0), btVector3(0, 1, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, should_ignore_tri_strips_data_with_empty_strips)
{
mNiTriStripsData.mStrips.clear();
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiTriStrips);
file.mHash = mHash;
const auto result = mLoader.load(file);
const Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_static_mesh_should_ignore_tri_strips_data_with_less_than_3_strips)
{
mNiTriStripsData.mStrips.front() = { 0, 1 };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiTriStrips);
file.mHash = mHash;
const auto result = mLoader.load(file);
const Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_avoid_collision_mesh_should_ignore_tri_strips_data_with_less_than_3_strips)
{
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
mNiNode.recType = Nif::RC_AvoidNode;
mNiTriStripsData.mStrips.front() = { 0, 1 };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiTriStrips);
file.mHash = mHash;
const auto result = mLoader.load(file);
const Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, for_animated_mesh_should_ignore_tri_strips_data_with_less_than_3_strips)
{
mNiTriStripsData.mStrips.front() = { 0, 1 };
mNiTriStrips.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriStrips) };
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNiNode);
file.mHash = mHash;
const auto result = mLoader.load(file);
const Resource::BulletShape expected;
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, should_not_add_static_mesh_with_no_triangles_to_compound_shape)
{
mNiTriStripsData.mStrips.front() = { 0, 1 };
mNiTriShape.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNiNode);
file.mRoots.push_back(&mNiTriStrips);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles(new btTriangleMesh(false));
triangles->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh(new Resource::TriangleMeshShape(triangles.release(), true));
std::unique_ptr<btCompoundShape> compound(new btCompoundShape);
compound->addChildShape(
btTransform::getIdentity(), new Resource::ScaledTriangleMeshShape(mesh.release(), btVector3(1, 1, 1)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(compound.release());
expected.mAnimatedShapes = { { -1, 0 } };
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, should_handle_node_with_multiple_parents)
{
copy(mTransform, mNiTriShape.mTransform);
mNiTriShape.mTransform.mScale = 4;
mNiTriShape.mParents = { &mNiNode, &mNiNode2 };
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
mNiNode.mTransform.mScale = 2;
mNiNode2.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape) };
mNiNode2.mTransform.mScale = 3;
Nif::NIFFile file("xtest.nif");
file.mRoots.push_back(&mNiNode);
file.mRoots.push_back(&mNiNode2);
file.mHash = mHash;
const auto result = mLoader.load(file);
std::unique_ptr<btTriangleMesh> triangles1(new btTriangleMesh(false));
triangles1->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh1(new Resource::TriangleMeshShape(triangles1.release(), true));
std::unique_ptr<btTriangleMesh> triangles2(new btTriangleMesh(false));
triangles2->addTriangle(btVector3(0, 0, 0), btVector3(1, 0, 0), btVector3(1, 1, 0));
std::unique_ptr<Resource::TriangleMeshShape> mesh2(new Resource::TriangleMeshShape(triangles2.release(), true));
std::unique_ptr<btCompoundShape> shape(new btCompoundShape);
shape->addChildShape(
mTransformScale2, new Resource::ScaledTriangleMeshShape(mesh1.release(), btVector3(8, 8, 8)));
shape->addChildShape(
mTransformScale3, new Resource::ScaledTriangleMeshShape(mesh2.release(), btVector3(12, 12, 12)));
Resource::BulletShape expected;
expected.mCollisionShape.reset(shape.release());
expected.mAnimatedShapes = { { -1, 0 } };
EXPECT_EQ(*result, expected);
}
TEST_F(TestBulletNifLoader, dont_assign_invalid_bounding_box_extents)
{
copy(mTransform, mNiTriShape.mTransform);
mNiTriShape.mTransform.mScale = 10;
mNiTriShape.mParents.push_back(&mNiNode);
mNiTriShape2.mName = "Bounding Box";
mNiTriShape2.mBounds.mType = Nif::BoundingVolume::Type::BOX_BV;
mNiTriShape2.mBounds.mBox.mExtents = osg::Vec3f(-1, -2, -3);
mNiTriShape2.mParents.push_back(&mNiNode);
mNiNode.mChildren = Nif::NiAVObjectList{ Nif::NiAVObjectPtr(&mNiTriShape), Nif::NiAVObjectPtr(&mNiTriShape2) };
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&mNiNode);
const auto result = mLoader.load(file);
const bool extentsUnassigned
= std::ranges::all_of(result->mCollisionBox.mExtents._v, [](float extent) { return extent == 0.f; });
EXPECT_EQ(extentsUnassigned, true);
}
}
| 56,997
|
C++
|
.cpp
| 1,103
| 43.157752
| 120
| 0.664191
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,199
|
toutf8.cpp
|
OpenMW_openmw/apps/components_tests/toutf8/toutf8.cpp
|
#include <components/misc/strings/conversion.hpp>
#include <components/to_utf8/to_utf8.hpp>
#include <gtest/gtest.h>
#include <filesystem>
#include <fstream>
#ifndef OPENMW_PROJECT_SOURCE_DIR
#define OPENMW_PROJECT_SOURCE_DIR "."
#endif
namespace
{
using namespace testing;
using namespace ToUTF8;
struct Params
{
FromType mLegacyEncoding;
std::string mLegacyEncodingFileName;
std::string mUtf8FileName;
};
std::string readContent(const std::string& fileName)
{
std::ifstream file;
file.exceptions(std::ios::failbit | std::ios::badbit);
file.open(std::filesystem::path{ OPENMW_PROJECT_SOURCE_DIR } / "apps" / "components_tests" / "toutf8" / "data"
/ Misc::StringUtils::stringToU8String(fileName));
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
struct Utf8EncoderTest : TestWithParam<Params>
{
};
TEST(Utf8EncoderTest, getUtf8ShouldReturnEmptyAsIs)
{
Utf8Encoder encoder(FromType::CP437);
EXPECT_EQ(encoder.getUtf8(std::string_view()), std::string_view());
}
TEST(Utf8EncoderTest, getUtf8ShouldReturnAsciiOnlyAsIs)
{
std::string input;
for (int c = 1; c <= std::numeric_limits<char>::max(); ++c)
input.push_back(static_cast<char>(c));
Utf8Encoder encoder(FromType::CP437);
const std::string_view result = encoder.getUtf8(input);
EXPECT_EQ(result.data(), input.data());
EXPECT_EQ(result.size(), input.size());
}
TEST(Utf8EncoderTest, getUtf8ShouldLookUpUntilZero)
{
const std::string input("a\0b");
Utf8Encoder encoder(FromType::CP437);
const std::string_view result = encoder.getUtf8(input);
EXPECT_EQ(result, "a");
}
TEST(Utf8EncoderTest, getUtf8ShouldLookUpUntilEndOfInputForAscii)
{
const std::string input("abc");
Utf8Encoder encoder(FromType::CP437);
const std::string_view result = encoder.getUtf8(std::string_view(input.data(), 2));
EXPECT_EQ(result, "ab");
}
TEST(Utf8EncoderTest, getUtf8ShouldLookUpUntilEndOfInputForNonAscii)
{
const std::string input(
"a\x92"
"b");
Utf8Encoder encoder(FromType::WINDOWS_1252);
const std::string_view result = encoder.getUtf8(std::string_view(input.data(), 2));
EXPECT_EQ(result, "a\xE2\x80\x99");
}
TEST_P(Utf8EncoderTest, getUtf8ShouldConvertFromLegacyEncodingToUtf8)
{
const std::string input(readContent(GetParam().mLegacyEncodingFileName));
const std::string expected(readContent(GetParam().mUtf8FileName));
Utf8Encoder encoder(GetParam().mLegacyEncoding);
const std::string_view result = encoder.getUtf8(input);
EXPECT_EQ(result, expected);
}
TEST(Utf8EncoderTest, getLegacyEncShouldReturnEmptyAsIs)
{
Utf8Encoder encoder(FromType::CP437);
EXPECT_EQ(encoder.getLegacyEnc(std::string_view()), std::string_view());
}
TEST(Utf8EncoderTest, getLegacyEncShouldReturnAsciiOnlyAsIs)
{
std::string input;
for (int c = 1; c <= std::numeric_limits<char>::max(); ++c)
input.push_back(static_cast<char>(c));
Utf8Encoder encoder(FromType::CP437);
const std::string_view result = encoder.getLegacyEnc(input);
EXPECT_EQ(result.data(), input.data());
EXPECT_EQ(result.size(), input.size());
}
TEST(Utf8EncoderTest, getLegacyEncShouldLookUpUntilZero)
{
const std::string input("a\0b");
Utf8Encoder encoder(FromType::CP437);
const std::string_view result = encoder.getLegacyEnc(input);
EXPECT_EQ(result, "a");
}
TEST(Utf8EncoderTest, getLegacyEncShouldLookUpUntilEndOfInputForAscii)
{
const std::string input("abc");
Utf8Encoder encoder(FromType::CP437);
const std::string_view result = encoder.getLegacyEnc(std::string_view(input.data(), 2));
EXPECT_EQ(result, "ab");
}
TEST(Utf8EncoderTest, getLegacyEncShouldStripIncompleteCharacters)
{
const std::string input("a\xc3\xa2\xe2\x80\x99");
Utf8Encoder encoder(FromType::WINDOWS_1252);
const std::string_view result = encoder.getLegacyEnc(std::string_view(input.data(), 5));
EXPECT_EQ(result, "a\xe2");
}
TEST_P(Utf8EncoderTest, getLegacyEncShouldConvertFromUtf8ToLegacyEncoding)
{
const std::string input(readContent(GetParam().mUtf8FileName));
const std::string expected(readContent(GetParam().mLegacyEncodingFileName));
Utf8Encoder encoder(GetParam().mLegacyEncoding);
const std::string_view result = encoder.getLegacyEnc(input);
EXPECT_EQ(result, expected);
}
INSTANTIATE_TEST_SUITE_P(Files, Utf8EncoderTest,
Values(Params{ ToUTF8::WINDOWS_1251, "russian-win1251.txt", "russian-utf8.txt" },
Params{ ToUTF8::WINDOWS_1252, "french-win1252.txt", "french-utf8.txt" }));
TEST(StatelessUtf8EncoderTest, shouldCleanupBuffer)
{
std::string buffer;
StatelessUtf8Encoder encoder(FromType::WINDOWS_1252);
encoder.getUtf8(std::string_view("long string\x92"), BufferAllocationPolicy::UseGrowFactor, buffer);
const std::string shortString("short\x92");
ASSERT_GT(buffer.size(), shortString.size());
const std::string_view shortUtf8 = encoder.getUtf8(shortString, BufferAllocationPolicy::UseGrowFactor, buffer);
ASSERT_GE(buffer.size(), shortUtf8.size());
EXPECT_EQ(buffer[shortUtf8.size()], '\0') << buffer;
}
TEST(StatelessUtf8EncoderTest, withFitToRequiredSizeShouldResizeBuffer)
{
std::string buffer;
StatelessUtf8Encoder encoder(FromType::WINDOWS_1252);
const std::string_view utf8
= encoder.getUtf8(std::string_view("long string\x92"), BufferAllocationPolicy::FitToRequiredSize, buffer);
EXPECT_EQ(buffer.size(), utf8.size());
}
}
| 6,031
|
C++
|
.cpp
| 144
| 34.645833
| 119
| 0.67468
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,200
|
testesmwriter.cpp
|
OpenMW_openmw/apps/components_tests/esm3/testesmwriter.cpp
|
#include <components/esm3/esmwriter.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <memory>
#include <random>
namespace ESM
{
namespace
{
using namespace ::testing;
struct Esm3EsmWriterTest : public Test
{
std::minstd_rand mRandom;
std::uniform_int_distribution<short> mRefIdDistribution{ 'a', 'z' };
std::string generateRandomString(std::size_t size)
{
std::string result;
std::generate_n(
std::back_inserter(result), size, [&] { return static_cast<char>(mRefIdDistribution(mRandom)); });
return result;
}
};
TEST_F(Esm3EsmWriterTest, saveShouldThrowExceptionOnWhenTruncatingHeaderStrings)
{
const std::string author = generateRandomString(33);
const std::string description = generateRandomString(257);
std::stringstream stream;
ESMWriter writer;
writer.setAuthor(author);
writer.setDescription(description);
writer.setFormatVersion(MaxLimitedSizeStringsFormatVersion);
EXPECT_THROW(writer.save(stream), std::runtime_error);
}
TEST_F(Esm3EsmWriterTest, writeFixedStringShouldThrowExceptionOnTruncate)
{
std::stringstream stream;
ESMWriter writer;
writer.setFormatVersion(MaxLimitedSizeStringsFormatVersion);
writer.save(stream);
EXPECT_THROW(writer.writeMaybeFixedSizeString(generateRandomString(33), 32), std::runtime_error);
}
struct Esm3EsmWriterRefIdSizeTest : TestWithParam<std::pair<RefId, std::size_t>>
{
};
// If this test failed probably there is a change in RefId format and CurrentSaveGameFormatVersion should be
// incremented, current version should be handled.
TEST_P(Esm3EsmWriterRefIdSizeTest, writeHRefIdShouldProduceCertainNumberOfBytes)
{
const auto [refId, size] = GetParam();
std::ostringstream stream;
{
ESMWriter writer;
writer.setFormatVersion(CurrentSaveGameFormatVersion);
writer.save(stream);
writer.writeHRefId(refId);
}
EXPECT_EQ(stream.str().size(), size);
}
const std::vector<std::pair<RefId, std::size_t>> refIdSizes = {
{ RefId(), 57 },
{ RefId::stringRefId(std::string(32, 'a')), 89 },
{ RefId::formIdRefId({ 0x1f, 0 }), 65 },
{ RefId::generated(0x1f), 65 },
{ RefId::index(REC_INGR, 0x1f), 65 },
{ RefId::esm3ExteriorCell(-42, 42), 65 },
};
INSTANTIATE_TEST_SUITE_P(RefIds, Esm3EsmWriterRefIdSizeTest, ValuesIn(refIdSizes));
}
}
| 2,881
|
C++
|
.cpp
| 70
| 30.485714
| 118
| 0.610236
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,201
|
testsaveload.cpp
|
OpenMW_openmw/apps/components_tests/esm3/testsaveload.cpp
|
#include <components/esm/fourcc.hpp>
#include <components/esm3/aipackage.hpp>
#include <components/esm3/aisequence.hpp>
#include <components/esm3/effectlist.hpp>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/loadcont.hpp>
#include <components/esm3/loaddial.hpp>
#include <components/esm3/loadinfo.hpp>
#include <components/esm3/loadland.hpp>
#include <components/esm3/loadregn.hpp>
#include <components/esm3/loadscpt.hpp>
#include <components/esm3/loadweap.hpp>
#include <components/esm3/player.hpp>
#include <components/esm3/quickkeys.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <array>
#include <iterator>
#include <limits>
#include <memory>
#include <numeric>
#include <random>
namespace ESM
{
namespace
{
auto tie(const ContItem& value)
{
return std::tie(value.mCount, value.mItem);
}
auto tie(const ESM::Region::SoundRef& value)
{
return std::tie(value.mSound, value.mChance);
}
auto tie(const ESM::QuickKeys::QuickKey& value)
{
return std::tie(value.mType, value.mId);
}
}
inline bool operator==(const ESM::ContItem& lhs, const ESM::ContItem& rhs)
{
return tie(lhs) == tie(rhs);
}
inline std::ostream& operator<<(std::ostream& stream, const ESM::ContItem& value)
{
return stream << "ESM::ContItem {.mCount = " << value.mCount << ", .mItem = '" << value.mItem << "'}";
}
inline bool operator==(const ESM::Region::SoundRef& lhs, const ESM::Region::SoundRef& rhs)
{
return tie(lhs) == tie(rhs);
}
inline std::ostream& operator<<(std::ostream& stream, const ESM::Region::SoundRef& value)
{
return stream << "ESM::Region::SoundRef {.mSound = '" << value.mSound << "', .mChance = " << value.mChance
<< "}";
}
inline bool operator==(const ESM::QuickKeys::QuickKey& lhs, const ESM::QuickKeys::QuickKey& rhs)
{
return tie(lhs) == tie(rhs);
}
inline std::ostream& operator<<(std::ostream& stream, const ESM::QuickKeys::QuickKey& value)
{
return stream << "ESM::QuickKeys::QuickKey {.mType = '" << static_cast<std::uint32_t>(value.mType)
<< "', .mId = " << value.mId << "}";
}
namespace
{
using namespace ::testing;
std::vector<ESM::FormatVersion> getFormats()
{
std::vector<ESM::FormatVersion> result({
CurrentContentFormatVersion,
MaxLimitedSizeStringsFormatVersion,
MaxStringRefIdFormatVersion,
});
for (ESM::FormatVersion v = result.back() + 1; v <= ESM::CurrentSaveGameFormatVersion; ++v)
result.push_back(v);
return result;
}
constexpr std::uint32_t fakeRecordId = fourCC("FAKE");
template <class T>
concept HasSave = requires(T v, ESMWriter& w)
{
v.save(w);
};
template <class T>
concept NotHasSave = !HasSave<T>;
template <HasSave T>
auto save(const T& record, ESMWriter& writer)
{
record.save(writer);
}
void save(const CellRef& record, ESMWriter& writer)
{
record.save(writer, true);
}
template <NotHasSave T>
auto save(const T& record, ESMWriter& writer)
{
writer.writeComposite(record);
}
template <typename T>
std::unique_ptr<std::istream> makeEsmStream(const T& record, FormatVersion formatVersion)
{
ESMWriter writer;
auto stream = std::make_unique<std::stringstream>();
writer.setFormatVersion(formatVersion);
writer.save(*stream);
writer.startRecord(fakeRecordId);
save(record, writer);
writer.endRecord(fakeRecordId);
return stream;
}
template <class T>
concept HasLoad = requires(T v, ESMReader& r)
{
v.load(r);
};
template <class T>
concept HasLoadWithDelete = requires(T v, ESMReader& r, bool& d)
{
v.load(r, d);
};
template <class T>
concept NotHasLoad = !HasLoad<T> && !HasLoadWithDelete<T>;
template <HasLoad T>
void load(ESMReader& reader, T& record)
{
record.load(reader);
}
template <HasLoadWithDelete T>
void load(ESMReader& reader, T& record)
{
bool deleted = false;
record.load(reader, deleted);
}
void load(ESMReader& reader, CellRef& record)
{
bool deleted = false;
record.load(reader, deleted, true);
}
template <NotHasLoad T>
void load(ESMReader& reader, T& record)
{
reader.getComposite(record);
}
void load(ESMReader& reader, Land& record)
{
bool deleted = false;
record.load(reader, deleted);
if (deleted)
return;
record.mLandData = std::make_unique<LandRecordData>();
reader.restoreContext(record.mContext);
loadLandRecordData(record.mDataTypes, reader, *record.mLandData);
}
template <typename T>
void saveAndLoadRecord(const T& record, FormatVersion formatVersion, T& result)
{
ESMReader reader;
reader.open(makeEsmStream(record, formatVersion), "stream");
ASSERT_TRUE(reader.hasMoreRecs());
ASSERT_EQ(reader.getRecName().toInt(), fakeRecordId);
reader.getRecHeader();
load(reader, result);
}
struct Esm3SaveLoadRecordTest : public TestWithParam<FormatVersion>
{
std::minstd_rand mRandom;
std::uniform_int_distribution<short> mRefIdDistribution{ 'a', 'z' };
std::string generateRandomString(std::size_t size)
{
std::string value;
while (value.size() < size)
value.push_back(static_cast<char>(mRefIdDistribution(mRandom)));
return value;
}
RefId generateRandomRefId(std::size_t size = 33) { return RefId::stringRefId(generateRandomString(size)); }
template <class T, std::size_t n>
void generateArray(T (&dst)[n])
{
for (auto& v : dst)
v = std::uniform_real_distribution<float>{ -1.0f, 1.0f }(mRandom);
}
void generateBytes(auto iterator, std::size_t count)
{
std::uniform_int_distribution<unsigned short> distribution{ 0,
std::numeric_limits<unsigned char>::max() };
std::generate_n(iterator, count, [&] { return static_cast<unsigned char>(distribution(mRandom)); });
}
void generateStrings(auto iterator, std::size_t count)
{
std::uniform_int_distribution<std::size_t> distribution{ 1, 13 };
std::generate_n(iterator, count, [&] { return generateRandomString(distribution(mRandom)); });
}
};
TEST_F(Esm3SaveLoadRecordTest, headerShouldNotChange)
{
const std::string author = generateRandomString(33);
const std::string description = generateRandomString(257);
auto stream = std::make_unique<std::stringstream>();
ESMWriter writer;
writer.setAuthor(author);
writer.setDescription(description);
writer.setFormatVersion(CurrentSaveGameFormatVersion);
writer.save(*stream);
writer.close();
ESMReader reader;
reader.open(std::move(stream), "stream");
EXPECT_EQ(reader.getAuthor(), author);
EXPECT_EQ(reader.getDesc(), description);
}
TEST_F(Esm3SaveLoadRecordTest, containerContItemShouldSupportRefIdLongerThan32)
{
Container record;
record.blank();
record.mInventory.mList.push_back(ESM::ContItem{ .mCount = 42, .mItem = generateRandomRefId(33) });
record.mInventory.mList.push_back(ESM::ContItem{ .mCount = 13, .mItem = generateRandomRefId(33) });
Container result;
saveAndLoadRecord(record, CurrentSaveGameFormatVersion, result);
EXPECT_EQ(result.mInventory.mList, record.mInventory.mList);
}
TEST_F(Esm3SaveLoadRecordTest, regionSoundRefShouldSupportRefIdLongerThan32)
{
Region record;
record.blank();
record.mSoundList.push_back(ESM::Region::SoundRef{ .mSound = generateRandomRefId(33), .mChance = 42 });
record.mSoundList.push_back(ESM::Region::SoundRef{ .mSound = generateRandomRefId(33), .mChance = 13 });
Region result;
saveAndLoadRecord(record, CurrentSaveGameFormatVersion, result);
EXPECT_EQ(result.mSoundList, record.mSoundList);
}
TEST_F(Esm3SaveLoadRecordTest, scriptSoundRefShouldSupportRefIdLongerThan32)
{
Script record;
record.blank();
record.mId = generateRandomRefId(33);
record.mNumShorts = 42;
Script result;
saveAndLoadRecord(record, CurrentSaveGameFormatVersion, result);
EXPECT_EQ(result.mId, record.mId);
EXPECT_EQ(result.mNumShorts, record.mNumShorts);
}
TEST_P(Esm3SaveLoadRecordTest, playerShouldNotChange)
{
// Player state is not saved to vanilla ESM format.
if (GetParam() == CurrentContentFormatVersion)
return;
std::minstd_rand random;
Player record{};
record.mObject.blank();
record.mBirthsign = generateRandomRefId();
record.mObject.mRef.mRefID = generateRandomRefId();
std::generate_n(std::inserter(record.mPreviousItems, record.mPreviousItems.end()), 2,
[&] { return std::make_pair(generateRandomRefId(), generateRandomRefId()); });
record.mCellId = ESM::RefId::esm3ExteriorCell(0, 0);
generateArray(record.mLastKnownExteriorPosition);
record.mHasMark = true;
record.mMarkedCell = ESM::RefId::esm3ExteriorCell(0, 0);
generateArray(record.mMarkedPosition.pos);
generateArray(record.mMarkedPosition.rot);
record.mCurrentCrimeId = 42;
record.mPaidCrimeId = 13;
Player result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(record.mObject.mRef.mRefID, result.mObject.mRef.mRefID);
EXPECT_EQ(record.mBirthsign, result.mBirthsign);
EXPECT_EQ(record.mPreviousItems, result.mPreviousItems);
EXPECT_EQ(record.mPreviousItems, result.mPreviousItems);
EXPECT_EQ(record.mCellId, result.mCellId);
EXPECT_THAT(record.mLastKnownExteriorPosition, ElementsAreArray(result.mLastKnownExteriorPosition));
EXPECT_EQ(record.mHasMark, result.mHasMark);
EXPECT_EQ(record.mMarkedCell, result.mMarkedCell);
EXPECT_THAT(record.mMarkedPosition.pos, ElementsAreArray(result.mMarkedPosition.pos));
EXPECT_THAT(record.mMarkedPosition.rot, ElementsAreArray(result.mMarkedPosition.rot));
EXPECT_EQ(record.mCurrentCrimeId, result.mCurrentCrimeId);
EXPECT_EQ(record.mPaidCrimeId, result.mPaidCrimeId);
}
TEST_P(Esm3SaveLoadRecordTest, cellRefShouldNotChange)
{
CellRef record;
record.blank();
record.mRefNum.mIndex = std::numeric_limits<unsigned>::max();
record.mRefNum.mContentFile = std::numeric_limits<int>::max();
record.mRefID = generateRandomRefId();
record.mScale = 2;
record.mOwner = generateRandomRefId();
record.mGlobalVariable = generateRandomString(100);
record.mSoul = generateRandomRefId();
record.mFaction = generateRandomRefId();
record.mFactionRank = std::numeric_limits<int>::max();
record.mChargeInt = std::numeric_limits<int>::max();
record.mEnchantmentCharge = std::numeric_limits<float>::max();
record.mCount = std::numeric_limits<int>::max();
record.mTeleport = true;
generateArray(record.mDoorDest.pos);
generateArray(record.mDoorDest.rot);
record.mDestCell = generateRandomString(100);
record.mLockLevel = 0;
record.mIsLocked = true;
record.mKey = generateRandomRefId();
record.mTrap = generateRandomRefId();
record.mReferenceBlocked = std::numeric_limits<signed char>::max();
generateArray(record.mPos.pos);
generateArray(record.mPos.rot);
CellRef result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(record.mRefNum.mIndex, result.mRefNum.mIndex);
EXPECT_EQ(record.mRefNum.mContentFile, result.mRefNum.mContentFile);
EXPECT_EQ(record.mRefID, result.mRefID);
EXPECT_EQ(record.mScale, result.mScale);
EXPECT_EQ(record.mOwner, result.mOwner);
EXPECT_EQ(record.mGlobalVariable, result.mGlobalVariable);
EXPECT_EQ(record.mSoul, result.mSoul);
EXPECT_EQ(record.mFaction, result.mFaction);
EXPECT_EQ(record.mFactionRank, result.mFactionRank);
EXPECT_EQ(record.mChargeInt, result.mChargeInt);
EXPECT_EQ(record.mEnchantmentCharge, result.mEnchantmentCharge);
EXPECT_EQ(record.mCount, result.mCount);
EXPECT_EQ(record.mTeleport, result.mTeleport);
EXPECT_EQ(record.mDoorDest, result.mDoorDest);
EXPECT_EQ(record.mDestCell, result.mDestCell);
EXPECT_EQ(record.mLockLevel, result.mLockLevel);
EXPECT_EQ(record.mIsLocked, result.mIsLocked);
EXPECT_EQ(record.mKey, result.mKey);
EXPECT_EQ(record.mTrap, result.mTrap);
EXPECT_EQ(record.mReferenceBlocked, result.mReferenceBlocked);
EXPECT_EQ(record.mPos, result.mPos);
}
TEST_P(Esm3SaveLoadRecordTest, creatureStatsShouldNotChange)
{
CreatureStats record;
record.blank();
record.mLastHitAttemptObject = generateRandomRefId();
record.mLastHitObject = generateRandomRefId();
CreatureStats result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(record.mLastHitAttemptObject, result.mLastHitAttemptObject);
EXPECT_EQ(record.mLastHitObject, result.mLastHitObject);
}
TEST_P(Esm3SaveLoadRecordTest, containerShouldNotChange)
{
Container record;
record.blank();
record.mId = generateRandomRefId();
record.mInventory.mList.push_back(ESM::ContItem{ .mCount = 42, .mItem = generateRandomRefId(32) });
record.mInventory.mList.push_back(ESM::ContItem{ .mCount = 13, .mItem = generateRandomRefId(32) });
Container result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mId, record.mId);
EXPECT_EQ(result.mInventory.mList, record.mInventory.mList);
}
TEST_P(Esm3SaveLoadRecordTest, regionShouldNotChange)
{
Region record;
record.blank();
record.mId = generateRandomRefId();
record.mSoundList.push_back(ESM::Region::SoundRef{ .mSound = generateRandomRefId(32), .mChance = 42 });
record.mSoundList.push_back(ESM::Region::SoundRef{ .mSound = generateRandomRefId(32), .mChance = 13 });
Region result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mId, record.mId);
EXPECT_EQ(result.mSoundList, record.mSoundList);
}
TEST_P(Esm3SaveLoadRecordTest, scriptShouldNotChange)
{
Script record;
record.blank();
record.mId = generateRandomRefId(32);
record.mNumShorts = 3;
record.mNumFloats = 4;
record.mNumLongs = 5;
generateStrings(
std::back_inserter(record.mVarNames), record.mNumShorts + record.mNumFloats + record.mNumLongs);
generateBytes(std::back_inserter(record.mScriptData), 13);
record.mScriptText = generateRandomString(17);
Script result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mId, record.mId);
EXPECT_EQ(result.mNumShorts, record.mNumShorts);
EXPECT_EQ(result.mNumFloats, record.mNumFloats);
EXPECT_EQ(result.mNumShorts, record.mNumShorts);
EXPECT_EQ(result.mVarNames, record.mVarNames);
EXPECT_EQ(result.mScriptData, record.mScriptData);
EXPECT_EQ(result.mScriptText, record.mScriptText);
}
TEST_P(Esm3SaveLoadRecordTest, quickKeysShouldNotChange)
{
const QuickKeys record {
.mKeys = {
{
.mType = QuickKeys::Type::Magic,
.mId = generateRandomRefId(32),
},
{
.mType = QuickKeys::Type::MagicItem,
.mId = generateRandomRefId(32),
},
},
};
QuickKeys result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mKeys, record.mKeys);
}
TEST_P(Esm3SaveLoadRecordTest, dialogueShouldNotChange)
{
Dialogue record;
record.blank();
record.mStringId = generateRandomString(32);
record.mId = ESM::RefId::stringRefId(record.mStringId);
Dialogue result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mId, record.mId);
EXPECT_EQ(result.mStringId, record.mStringId);
}
TEST_P(Esm3SaveLoadRecordTest, aiSequenceAiWanderShouldNotChange)
{
AiSequence::AiWander record;
record.mData.mDistance = 1;
record.mData.mDuration = 2;
record.mData.mTimeOfDay = 3;
constexpr std::uint8_t idle[8] = { 4, 5, 6, 7, 8, 9, 10, 11 };
static_assert(std::size(idle) == std::size(record.mData.mIdle));
std::copy(std::begin(idle), std::end(idle), record.mData.mIdle);
record.mData.mShouldRepeat = 12;
record.mDurationData.mRemainingDuration = 13;
record.mStoredInitialActorPosition = true;
constexpr float initialActorPosition[3] = { 15, 16, 17 };
static_assert(std::size(initialActorPosition) == std::size(record.mInitialActorPosition.mValues));
std::copy(
std::begin(initialActorPosition), std::end(initialActorPosition), record.mInitialActorPosition.mValues);
AiSequence::AiWander result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mData.mDistance, record.mData.mDistance);
EXPECT_EQ(result.mData.mDuration, record.mData.mDuration);
EXPECT_EQ(result.mData.mTimeOfDay, record.mData.mTimeOfDay);
EXPECT_THAT(result.mData.mIdle, ElementsAreArray(record.mData.mIdle));
EXPECT_EQ(result.mData.mShouldRepeat, record.mData.mShouldRepeat);
EXPECT_EQ(result.mDurationData.mRemainingDuration, record.mDurationData.mRemainingDuration);
EXPECT_EQ(result.mStoredInitialActorPosition, record.mStoredInitialActorPosition);
EXPECT_THAT(result.mInitialActorPosition.mValues, ElementsAreArray(record.mInitialActorPosition.mValues));
}
TEST_P(Esm3SaveLoadRecordTest, aiSequenceAiTravelShouldNotChange)
{
AiSequence::AiTravel record;
record.mData.mX = 1;
record.mData.mY = 2;
record.mData.mZ = 3;
record.mHidden = true;
record.mRepeat = true;
AiSequence::AiTravel result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mData.mX, record.mData.mX);
EXPECT_EQ(result.mData.mY, record.mData.mY);
EXPECT_EQ(result.mData.mZ, record.mData.mZ);
EXPECT_EQ(result.mHidden, record.mHidden);
EXPECT_EQ(result.mRepeat, record.mRepeat);
}
TEST_P(Esm3SaveLoadRecordTest, aiSequenceAiEscortShouldNotChange)
{
AiSequence::AiEscort record;
record.mData.mX = 1;
record.mData.mY = 2;
record.mData.mZ = 3;
record.mData.mDuration = 4;
record.mTargetActorId = 5;
record.mTargetId = generateRandomRefId(32);
record.mCellId = generateRandomString(257);
record.mRemainingDuration = 6;
record.mRepeat = true;
AiSequence::AiEscort result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mData.mX, record.mData.mX);
EXPECT_EQ(result.mData.mY, record.mData.mY);
EXPECT_EQ(result.mData.mZ, record.mData.mZ);
if (GetParam() <= MaxOldAiPackageFormatVersion)
EXPECT_EQ(result.mData.mDuration, record.mRemainingDuration);
else
EXPECT_EQ(result.mData.mDuration, record.mData.mDuration);
EXPECT_EQ(result.mTargetActorId, record.mTargetActorId);
EXPECT_EQ(result.mTargetId, record.mTargetId);
EXPECT_EQ(result.mCellId, record.mCellId);
EXPECT_EQ(result.mRemainingDuration, record.mRemainingDuration);
EXPECT_EQ(result.mRepeat, record.mRepeat);
}
TEST_P(Esm3SaveLoadRecordTest, aiDataShouldNotChange)
{
AIData record = {
.mHello = 1,
.mFight = 2,
.mFlee = 3,
.mAlarm = 4,
.mServices = 5,
};
AIData result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mHello, record.mHello);
EXPECT_EQ(result.mFight, record.mFight);
EXPECT_EQ(result.mFlee, record.mFlee);
EXPECT_EQ(result.mAlarm, record.mAlarm);
EXPECT_EQ(result.mServices, record.mServices);
}
TEST_P(Esm3SaveLoadRecordTest, enamShouldNotChange)
{
EffectList record;
record.mList.emplace_back(IndexedENAMstruct{ {
.mEffectID = 1,
.mSkill = 2,
.mAttribute = 3,
.mRange = 4,
.mArea = 5,
.mDuration = 6,
.mMagnMin = 7,
.mMagnMax = 8,
},
0 });
EffectList result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mList.size(), record.mList.size());
EXPECT_EQ(result.mList[0].mData.mEffectID, record.mList[0].mData.mEffectID);
EXPECT_EQ(result.mList[0].mData.mSkill, record.mList[0].mData.mSkill);
EXPECT_EQ(result.mList[0].mData.mAttribute, record.mList[0].mData.mAttribute);
EXPECT_EQ(result.mList[0].mData.mRange, record.mList[0].mData.mRange);
EXPECT_EQ(result.mList[0].mData.mArea, record.mList[0].mData.mArea);
EXPECT_EQ(result.mList[0].mData.mDuration, record.mList[0].mData.mDuration);
EXPECT_EQ(result.mList[0].mData.mMagnMin, record.mList[0].mData.mMagnMin);
EXPECT_EQ(result.mList[0].mData.mMagnMax, record.mList[0].mData.mMagnMax);
}
TEST_P(Esm3SaveLoadRecordTest, weaponShouldNotChange)
{
Weapon record = {
.mData = {
.mWeight = 0,
.mValue = 1,
.mType = 2,
.mHealth = 3,
.mSpeed = 4,
.mReach = 5,
.mEnchant = 6,
.mChop = { 7, 8 },
.mSlash = { 9, 10 },
.mThrust = { 11, 12 },
.mFlags = 13,
},
.mRecordFlags = 0,
.mId = generateRandomRefId(32),
.mEnchant = generateRandomRefId(32),
.mScript = generateRandomRefId(32),
.mName = generateRandomString(32),
.mModel = generateRandomString(32),
.mIcon = generateRandomString(32),
};
Weapon result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mData.mWeight, record.mData.mWeight);
EXPECT_EQ(result.mData.mValue, record.mData.mValue);
EXPECT_EQ(result.mData.mType, record.mData.mType);
EXPECT_EQ(result.mData.mHealth, record.mData.mHealth);
EXPECT_EQ(result.mData.mSpeed, record.mData.mSpeed);
EXPECT_EQ(result.mData.mReach, record.mData.mReach);
EXPECT_EQ(result.mData.mEnchant, record.mData.mEnchant);
EXPECT_EQ(result.mData.mChop, record.mData.mChop);
EXPECT_EQ(result.mData.mSlash, record.mData.mSlash);
EXPECT_EQ(result.mData.mThrust, record.mData.mThrust);
EXPECT_EQ(result.mData.mFlags, record.mData.mFlags);
EXPECT_EQ(result.mId, record.mId);
EXPECT_EQ(result.mEnchant, record.mEnchant);
EXPECT_EQ(result.mScript, record.mScript);
EXPECT_EQ(result.mName, record.mName);
EXPECT_EQ(result.mModel, record.mModel);
EXPECT_EQ(result.mIcon, record.mIcon);
}
TEST_P(Esm3SaveLoadRecordTest, infoShouldNotChange)
{
DialInfo record = {
.mData = {
.mType = ESM::Dialogue::Topic,
.mDisposition = 1,
.mRank = 2,
.mGender = ESM::DialInfo::NA,
.mPCrank = 3,
},
.mSelects = {
ESM::DialogueCondition{
.mVariable = {},
.mValue = 42,
.mIndex = 0,
.mFunction = ESM::DialogueCondition::Function_Level,
.mComparison = ESM::DialogueCondition::Comp_Eq
},
ESM::DialogueCondition{
.mVariable = generateRandomString(32),
.mValue = 0,
.mIndex = 1,
.mFunction = ESM::DialogueCondition::Function_NotLocal,
.mComparison = ESM::DialogueCondition::Comp_Eq
},
},
.mId = generateRandomRefId(32),
.mPrev = generateRandomRefId(32),
.mNext = generateRandomRefId(32),
.mActor = generateRandomRefId(32),
.mRace = generateRandomRefId(32),
.mClass = generateRandomRefId(32),
.mFaction = generateRandomRefId(32),
.mPcFaction = generateRandomRefId(32),
.mCell = generateRandomRefId(32),
.mSound = generateRandomString(32),
.mResponse = generateRandomString(32),
.mResultScript = generateRandomString(32),
.mFactionLess = false,
.mQuestStatus = ESM::DialInfo::QS_None,
};
DialInfo result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mData.mType, record.mData.mType);
EXPECT_EQ(result.mData.mDisposition, record.mData.mDisposition);
EXPECT_EQ(result.mData.mRank, record.mData.mRank);
EXPECT_EQ(result.mData.mGender, record.mData.mGender);
EXPECT_EQ(result.mData.mPCrank, record.mData.mPCrank);
EXPECT_EQ(result.mId, record.mId);
EXPECT_EQ(result.mPrev, record.mPrev);
EXPECT_EQ(result.mNext, record.mNext);
EXPECT_EQ(result.mActor, record.mActor);
EXPECT_EQ(result.mRace, record.mRace);
EXPECT_EQ(result.mClass, record.mClass);
EXPECT_EQ(result.mFaction, record.mFaction);
EXPECT_EQ(result.mPcFaction, record.mPcFaction);
EXPECT_EQ(result.mCell, record.mCell);
EXPECT_EQ(result.mSound, record.mSound);
EXPECT_EQ(result.mResponse, record.mResponse);
EXPECT_EQ(result.mResultScript, record.mResultScript);
EXPECT_EQ(result.mFactionLess, record.mFactionLess);
EXPECT_EQ(result.mQuestStatus, record.mQuestStatus);
EXPECT_EQ(result.mSelects.size(), record.mSelects.size());
for (size_t i = 0; i < result.mSelects.size(); ++i)
{
const auto& resultS = result.mSelects[i];
const auto& recordS = record.mSelects[i];
EXPECT_EQ(resultS.mVariable, recordS.mVariable);
EXPECT_EQ(resultS.mValue, recordS.mValue);
EXPECT_EQ(resultS.mIndex, recordS.mIndex);
EXPECT_EQ(resultS.mFunction, recordS.mFunction);
EXPECT_EQ(resultS.mComparison, recordS.mComparison);
}
}
TEST_P(Esm3SaveLoadRecordTest, landShouldNotChange)
{
LandRecordData data;
std::iota(data.mHeights.begin(), data.mHeights.end(), 1);
std::for_each(data.mHeights.begin(), data.mHeights.end(), [](float& v) { v *= Land::sHeightScale; });
data.mMinHeight = *std::min_element(data.mHeights.begin(), data.mHeights.end());
data.mMaxHeight = *std::max_element(data.mHeights.begin(), data.mHeights.end());
std::iota(data.mNormals.begin(), data.mNormals.end(), 2);
std::iota(data.mTextures.begin(), data.mTextures.end(), 3);
std::iota(data.mColours.begin(), data.mColours.end(), 4);
data.mDataLoaded = Land::DATA_VNML | Land::DATA_VHGT | Land::DATA_VCLR | Land::DATA_VTEX;
Land record;
record.mFlags = Land::Flag_HeightsNormals | Land::Flag_Colors | Land::Flag_Textures;
record.mX = 2;
record.mY = 3;
record.mDataTypes = Land::DATA_VNML | Land::DATA_VHGT | Land::DATA_WNAM | Land::DATA_VCLR | Land::DATA_VTEX;
generateWnam(data.mHeights, record.mWnam);
record.mLandData = std::make_unique<LandRecordData>(data);
Land result;
saveAndLoadRecord(record, GetParam(), result);
EXPECT_EQ(result.mFlags, record.mFlags);
EXPECT_EQ(result.mX, record.mX);
EXPECT_EQ(result.mY, record.mY);
EXPECT_EQ(result.mDataTypes, record.mDataTypes);
EXPECT_EQ(result.mWnam, record.mWnam);
EXPECT_EQ(result.mLandData->mHeights, record.mLandData->mHeights);
EXPECT_EQ(result.mLandData->mMinHeight, record.mLandData->mMinHeight);
EXPECT_EQ(result.mLandData->mMaxHeight, record.mLandData->mMaxHeight);
EXPECT_EQ(result.mLandData->mNormals, record.mLandData->mNormals);
EXPECT_EQ(result.mLandData->mTextures, record.mLandData->mTextures);
EXPECT_EQ(result.mLandData->mColours, record.mLandData->mColours);
EXPECT_EQ(result.mLandData->mDataLoaded, record.mLandData->mDataLoaded);
}
INSTANTIATE_TEST_SUITE_P(FormatVersions, Esm3SaveLoadRecordTest, ValuesIn(getFormats()));
}
}
| 32,394
|
C++
|
.cpp
| 684
| 34.214912
| 120
| 0.585673
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,202
|
testcstringids.cpp
|
OpenMW_openmw/apps/components_tests/esm3/testcstringids.cpp
|
#include <components/esm3/esmreader.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/loaddial.hpp>
#include <gtest/gtest.h>
namespace ESM
{
namespace
{
TEST(Esm3CStringIdTest, dialNameShouldBeNullTerminated)
{
std::unique_ptr<std::istream> stream;
{
auto ostream = std::make_unique<std::stringstream>();
ESMWriter writer;
writer.setFormatVersion(DefaultFormatVersion);
writer.save(*ostream);
Dialogue record;
record.blank();
record.mStringId = "topic name";
record.mId = RefId::stringRefId(record.mStringId);
record.mType = Dialogue::Topic;
writer.startRecord(Dialogue::sRecordId);
record.save(writer);
writer.endRecord(Dialogue::sRecordId);
stream = std::move(ostream);
}
ESMReader reader;
reader.open(std::move(stream), "stream");
ASSERT_TRUE(reader.hasMoreRecs());
ASSERT_EQ(reader.getRecName(), Dialogue::sRecordId);
reader.getRecHeader();
while (reader.hasMoreSubs())
{
reader.getSubName();
if (reader.retSubName().toInt() == SREC_NAME)
{
reader.getSubHeader();
auto size = reader.getSubSize();
std::string buffer(size, '1');
reader.getExact(buffer.data(), size);
ASSERT_EQ(buffer[size - 1], '\0');
return;
}
else
reader.skipHSub();
}
ASSERT_FALSE(true);
}
}
}
| 1,804
|
C++
|
.cpp
| 50
| 22.78
| 69
| 0.51059
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,203
|
testinfoorder.cpp
|
OpenMW_openmw/apps/components_tests/esm3/testinfoorder.cpp
|
#include <components/esm3/infoorder.hpp>
#include <gtest/gtest.h>
namespace ESM
{
namespace
{
struct Value
{
RefId mId;
RefId mPrev;
Value() = default;
Value(const Value&) = delete;
Value(Value&&) = default;
Value& operator=(const Value&) = delete;
Value& operator=(Value&&) = default;
};
TEST(Esm3InfoOrderTest, insertInfoShouldNotCopyValue)
{
InfoOrder<Value> order;
order.insertInfo(Value{}, false);
}
}
}
| 581
|
C++
|
.cpp
| 23
| 16.782609
| 61
| 0.537906
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,204
|
readerscache.cpp
|
OpenMW_openmw/apps/components_tests/esm3/readerscache.cpp
|
#include <components/esm3/readerscache.hpp>
#include <components/files/collections.hpp>
#include <components/files/multidircollection.hpp>
#include <gtest/gtest.h>
#ifndef OPENMW_DATA_DIR
#error "OPENMW_DATA_DIR is not defined"
#endif
namespace
{
using namespace testing;
using namespace ESM;
TEST(ESM3ReadersCache, onAttemptToRequestTheSameReaderTwiceShouldThrowException)
{
ReadersCache readers(1);
const ReadersCache::BusyItem reader = readers.get(0);
EXPECT_THROW(readers.get(0), std::logic_error);
}
TEST(ESM3ReadersCache, shouldAllowToHaveBusyItemsMoreThanCapacity)
{
ReadersCache readers(1);
const ReadersCache::BusyItem reader0 = readers.get(0);
const ReadersCache::BusyItem reader1 = readers.get(1);
}
TEST(ESM3ReadersCache, shouldKeepClosedReleasedClosedItem)
{
ReadersCache readers(1);
readers.get(0);
const ReadersCache::BusyItem reader = readers.get(0);
EXPECT_FALSE(reader->isOpen());
}
struct ESM3ReadersCacheWithContentFile : Test
{
static constexpr std::size_t sInitialOffset = 324;
static constexpr std::size_t sSkip = 100;
const Files::PathContainer mDataDirs{ { std::filesystem::path{ OPENMW_DATA_DIR } } };
const Files::Collections mFileCollections{ mDataDirs };
const std::string mContentFile = "template.omwgame";
const std::filesystem::path mContentFilePath = mFileCollections.getCollection(".omwgame").getPath(mContentFile);
};
TEST_F(ESM3ReadersCacheWithContentFile, shouldKeepOpenReleasedOpenReader)
{
ReadersCache readers(1);
{
const ReadersCache::BusyItem reader = readers.get(0);
reader->open(mContentFilePath);
ASSERT_TRUE(reader->isOpen());
ASSERT_EQ(reader->getFileOffset(), sInitialOffset);
ASSERT_GT(reader->getFileSize(), sInitialOffset + sSkip);
reader->skip(sSkip);
ASSERT_EQ(reader->getFileOffset(), sInitialOffset + sSkip);
}
{
const ReadersCache::BusyItem reader = readers.get(0);
EXPECT_TRUE(reader->isOpen());
EXPECT_EQ(reader->getName(), mContentFilePath);
EXPECT_EQ(reader->getFileOffset(), sInitialOffset + sSkip);
}
}
TEST_F(ESM3ReadersCacheWithContentFile, shouldCloseFreeReaderWhenReachingCapacityLimit)
{
ReadersCache readers(1);
{
const ReadersCache::BusyItem reader = readers.get(0);
reader->open(mContentFilePath);
ASSERT_TRUE(reader->isOpen());
ASSERT_EQ(reader->getFileOffset(), sInitialOffset);
ASSERT_GT(reader->getFileSize(), sInitialOffset + sSkip);
reader->skip(sSkip);
ASSERT_EQ(reader->getFileOffset(), sInitialOffset + sSkip);
}
{
const ReadersCache::BusyItem reader = readers.get(1);
reader->open(mContentFilePath);
ASSERT_TRUE(reader->isOpen());
}
{
const ReadersCache::BusyItem reader = readers.get(0);
EXPECT_TRUE(reader->isOpen());
EXPECT_EQ(reader->getFileOffset(), sInitialOffset);
}
}
}
| 3,259
|
C++
|
.cpp
| 82
| 31.414634
| 120
| 0.657513
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,205
|
conversion_tests.cpp
|
OpenMW_openmw/apps/components_tests/files/conversion_tests.cpp
|
#include <components/files/conversion.hpp>
#include <components/misc/strings/conversion.hpp>
#include <gtest/gtest.h>
namespace
{
using namespace testing;
using namespace Files;
constexpr auto test_path_u8 = u8"./tmp/ÒĎƎɠˠΏЌԹעڨ/ऊঋਐઊଊ/ஐఋಋഊ/ฎນ༈ႩᄇḮὯ⁂₁₩ℒ/Ⅷ↝∑/☝✌〥ぐズ㌎丕.갔3갛";
constexpr auto test_path = "./tmp/ÒĎƎɠˠΏЌԹעڨ/ऊঋਐઊଊ/ஐఋಋഊ/ฎນ༈ႩᄇḮὯ⁂₁₩ℒ/Ⅷ↝∑/☝✌〥ぐズ㌎丕.갔3갛";
TEST(OpenMWConversion, should_support_unicode_string_to_path)
{
auto p = Files::pathFromUnicodeString(test_path);
EXPECT_EQ(Misc::StringUtils::u8StringToString(p.u8string()), Misc::StringUtils::u8StringToString(test_path_u8));
}
TEST(OpenMWConversion, should_support_path_to_unicode_string)
{
std::filesystem::path p{ test_path_u8 };
EXPECT_EQ(Files::pathToUnicodeString(p), test_path);
}
}
| 975
|
C++
|
.cpp
| 20
| 36.3
| 120
| 0.709273
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,206
|
hash.cpp
|
OpenMW_openmw/apps/components_tests/files/hash.cpp
|
#include <components/files/constrainedfilestream.hpp>
#include <components/files/conversion.hpp>
#include <components/files/hash.hpp>
#include <components/testing/util.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <array>
#include <fstream>
#include <sstream>
#include <string>
namespace
{
using namespace testing;
using namespace TestingOpenMW;
using namespace Files;
struct Params
{
std::size_t mSize;
std::array<std::uint64_t, 2> mHash;
};
struct FilesGetHash : TestWithParam<Params>
{
};
TEST(FilesGetHash, shouldClearErrors)
{
const auto fileName = temporaryFilePath("fileName");
std::string content;
std::fill_n(std::back_inserter(content), 1, 'a');
std::istringstream stream(content);
stream.exceptions(std::ios::failbit | std::ios::badbit);
EXPECT_THAT(getHash(Files::pathToUnicodeString(fileName), stream),
ElementsAre(9607679276477937801ull, 16624257681780017498ull));
}
TEST_P(FilesGetHash, shouldReturnHashForStringStream)
{
const auto fileName = temporaryFilePath("fileName");
std::string content;
std::fill_n(std::back_inserter(content), GetParam().mSize, 'a');
std::istringstream stream(content);
EXPECT_EQ(getHash(Files::pathToUnicodeString(fileName), stream), GetParam().mHash);
}
TEST_P(FilesGetHash, shouldReturnHashForConstrainedFileStream)
{
std::string fileName(UnitTest::GetInstance()->current_test_info()->name());
std::replace(fileName.begin(), fileName.end(), '/', '_');
std::string content;
std::fill_n(std::back_inserter(content), GetParam().mSize, 'a');
const auto file = outputFilePath(fileName);
std::fstream(file, std::ios_base::out | std::ios_base::binary)
.write(content.data(), static_cast<std::streamsize>(content.size()));
const auto stream = Files::openConstrainedFileStream(file, 0, content.size());
EXPECT_EQ(getHash(Files::pathToUnicodeString(file), *stream), GetParam().mHash);
}
INSTANTIATE_TEST_SUITE_P(Params, FilesGetHash,
Values(Params{ 0, { 0, 0 } }, Params{ 1, { 9607679276477937801ull, 16624257681780017498ull } },
Params{ 128, { 15287858148353394424ull, 16818615825966581310ull } },
Params{ 1000, { 11018119256083894017ull, 6631144854802791578ull } },
Params{ 4096, { 11972283295181039100ull, 16027670129106775155ull } },
Params{ 4097, { 16717956291025443060ull, 12856404199748778153ull } },
Params{ 5000, { 15775925571142117787ull, 10322955217889622896ull } }));
}
| 2,701
|
C++
|
.cpp
| 62
| 37
| 103
| 0.68365
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,207
|
test_configuration.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_configuration.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <fstream>
#include <components/esm3/esmreader.hpp>
#include <components/esm3/esmwriter.hpp>
#include <components/esm3/formatversion.hpp>
#include <components/esm3/readerscache.hpp>
#include <components/lua/configuration.hpp>
#include <components/lua/serialization.hpp>
#include <components/testing/expecterror.hpp>
#include <components/testing/util.hpp>
namespace
{
using testing::ElementsAre;
using testing::Pair;
std::vector<std::pair<int, std::string>> asVector(const LuaUtil::ScriptIdsWithInitializationData& d)
{
std::vector<std::pair<int, std::string>> res;
for (const auto& [k, v] : d)
res.emplace_back(k, std::string(v));
return res;
}
TEST(LuaConfigurationTest, ValidOMWScripts)
{
ESM::LuaScriptsCfg cfg;
LuaUtil::parseOMWScripts(cfg, R"X(
# Lines starting with '#' are comments
GLOBAL: my_mod/#some_global_script.lua
# Script that will be automatically attached to the player
PLAYER :my_mod/player.lua
CUSTOM : my_mod/some_other_script.lua
NPC , CREATURE PLAYER : my_mod/some_other_script.lua)X");
LuaUtil::parseOMWScripts(cfg, ":my_mod/player.LUA \r\nCREATURE,CUSTOM: my_mod/creature.lua\r\n");
ASSERT_EQ(cfg.mScripts.size(), 6);
EXPECT_EQ(LuaUtil::scriptCfgToString(cfg.mScripts[0]), "GLOBAL : my_mod/#some_global_script.lua");
EXPECT_EQ(LuaUtil::scriptCfgToString(cfg.mScripts[1]), "PLAYER : my_mod/player.lua");
EXPECT_EQ(LuaUtil::scriptCfgToString(cfg.mScripts[2]), "CUSTOM : my_mod/some_other_script.lua");
EXPECT_EQ(LuaUtil::scriptCfgToString(cfg.mScripts[3]), "PLAYER NPC CREATURE : my_mod/some_other_script.lua");
EXPECT_EQ(LuaUtil::scriptCfgToString(cfg.mScripts[4]), ": my_mod/player.lua");
EXPECT_EQ(LuaUtil::scriptCfgToString(cfg.mScripts[5]), "CUSTOM CREATURE : my_mod/creature.lua");
LuaUtil::ScriptsConfiguration conf;
conf.init(std::move(cfg));
ASSERT_EQ(conf.size(), 4);
EXPECT_EQ(LuaUtil::scriptCfgToString(conf[0]), "GLOBAL : my_mod/#some_global_script.lua");
// cfg.mScripts[1] is overridden by cfg.mScripts[4]
// cfg.mScripts[2] is overridden by cfg.mScripts[3]
EXPECT_EQ(LuaUtil::scriptCfgToString(conf[1]), "PLAYER NPC CREATURE : my_mod/some_other_script.lua");
EXPECT_EQ(LuaUtil::scriptCfgToString(conf[2]), ": my_mod/player.lua");
EXPECT_EQ(LuaUtil::scriptCfgToString(conf[3]), "CUSTOM CREATURE : my_mod/creature.lua");
EXPECT_THAT(asVector(conf.getGlobalConf()), ElementsAre(Pair(0, "")));
EXPECT_THAT(asVector(conf.getPlayerConf()), ElementsAre(Pair(1, "")));
const ESM::RefId something = ESM::RefId::stringRefId("something");
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_CONT, something, ESM::RefNum())), ElementsAre());
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_NPC_, something, ESM::RefNum())), ElementsAre(Pair(1, "")));
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_CREA, something, ESM::RefNum())),
ElementsAre(Pair(1, ""), Pair(3, "")));
// Check that initialization cleans old data
cfg = ESM::LuaScriptsCfg();
conf.init(std::move(cfg));
EXPECT_EQ(conf.size(), 0);
}
TEST(LuaConfigurationTest, InvalidOMWScripts)
{
ESM::LuaScriptsCfg cfg;
EXPECT_ERROR(LuaUtil::parseOMWScripts(cfg, "GLOBAL: something"),
"Lua script should have suffix '.lua', got: GLOBAL: something");
EXPECT_ERROR(LuaUtil::parseOMWScripts(cfg, "something.lua"), "No flags found in: something.lua");
cfg.mScripts.clear();
EXPECT_NO_THROW(LuaUtil::parseOMWScripts(cfg, "GLOBAL, PLAYER: something.lua"));
LuaUtil::ScriptsConfiguration conf;
EXPECT_ERROR(conf.init(std::move(cfg)), "Global script can not have local flags");
}
TEST(LuaConfigurationTest, ConfInit)
{
ESM::LuaScriptsCfg cfg;
ESM::LuaScriptCfg& script1 = cfg.mScripts.emplace_back();
script1.mScriptPath = VFS::Path::Normalized("Script1.lua");
script1.mInitializationData = "data1";
script1.mFlags = ESM::LuaScriptCfg::sPlayer;
script1.mTypes.push_back(ESM::REC_CREA);
script1.mRecords.push_back({ true, ESM::RefId::stringRefId("record1"), "dataRecord1" });
script1.mRefs.push_back({ true, 2, 3, "" });
script1.mRefs.push_back({ true, 2, 4, "" });
ESM::LuaScriptCfg& script2 = cfg.mScripts.emplace_back();
script2.mScriptPath = VFS::Path::Normalized("Script2.lua");
script2.mFlags = ESM::LuaScriptCfg::sCustom;
script2.mTypes.push_back(ESM::REC_CONT);
ESM::LuaScriptCfg& script1Extra = cfg.mScripts.emplace_back();
script1Extra.mScriptPath = VFS::Path::Normalized("script1.LUA");
script1Extra.mFlags = ESM::LuaScriptCfg::sCustom | ESM::LuaScriptCfg::sMerge;
script1Extra.mTypes.push_back(ESM::REC_NPC_);
script1Extra.mRecords.push_back({ false, ESM::RefId::stringRefId("rat"), "" });
script1Extra.mRecords.push_back({ true, ESM::RefId::stringRefId("record2"), "" });
script1Extra.mRefs.push_back({ true, 3, 5, "dataRef35" });
script1Extra.mRefs.push_back({ false, 2, 3, "" });
LuaUtil::ScriptsConfiguration conf;
conf.init(cfg);
ASSERT_EQ(conf.size(), 2);
EXPECT_EQ(LuaUtil::scriptCfgToString(conf[0]),
"CUSTOM PLAYER CREATURE NPC : script1.lua ; data 5 bytes ; 3 records ; 4 objects");
EXPECT_EQ(LuaUtil::scriptCfgToString(conf[1]), "CUSTOM CONTAINER : script2.lua");
EXPECT_THAT(asVector(conf.getPlayerConf()), ElementsAre(Pair(0, "data1")));
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_CONT, ESM::RefId::stringRefId("something"), ESM::RefNum())),
ElementsAre(Pair(1, "")));
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_CREA, ESM::RefId::stringRefId("guar"), ESM::RefNum())),
ElementsAre(Pair(0, "data1")));
EXPECT_THAT(
asVector(conf.getLocalConf(ESM::REC_CREA, ESM::RefId::stringRefId("rat"), ESM::RefNum())), ElementsAre());
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_DOOR, ESM::RefId::stringRefId("record1"), ESM::RefNum())),
ElementsAre(Pair(0, "dataRecord1")));
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_DOOR, ESM::RefId::stringRefId("record2"), ESM::RefNum())),
ElementsAre(Pair(0, "data1")));
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_NPC_, ESM::RefId::stringRefId("record3"), { 1, 1 })),
ElementsAre(Pair(0, "data1")));
EXPECT_THAT(
asVector(conf.getLocalConf(ESM::REC_NPC_, ESM::RefId::stringRefId("record3"), { 2, 3 })), ElementsAre());
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_NPC_, ESM::RefId::stringRefId("record3"), { 3, 5 })),
ElementsAre(Pair(0, "dataRef35")));
EXPECT_THAT(asVector(conf.getLocalConf(ESM::REC_CONT, ESM::RefId::stringRefId("record4"), { 2, 4 })),
ElementsAre(Pair(0, "data1"), Pair(1, "")));
ESM::LuaScriptCfg& script3 = cfg.mScripts.emplace_back();
script3.mScriptPath = VFS::Path::Normalized("script1.lua");
script3.mFlags = ESM::LuaScriptCfg::sGlobal;
EXPECT_ERROR(conf.init(cfg), "Flags mismatch for script1.lua");
}
TEST(LuaConfigurationTest, Serialization)
{
sol::state lua;
LuaUtil::BasicSerializer serializer;
ESM::ESMWriter writer;
writer.setAuthor("");
writer.setDescription("");
writer.setRecordCount(1);
writer.setFormatVersion(ESM::CurrentContentFormatVersion);
writer.setVersion();
writer.addMaster("morrowind.esm", 0);
ESM::LuaScriptsCfg cfg;
std::string luaData;
{
sol::table data(lua, sol::create);
data["number"] = 5;
data["string"] = "some value";
data["fargoth"] = ESM::RefNum{ 128964, 1 };
luaData = LuaUtil::serialize(data, &serializer);
}
{
ESM::LuaScriptCfg& script = cfg.mScripts.emplace_back();
script.mScriptPath = VFS::Path::Normalized("test_global.lua");
script.mFlags = ESM::LuaScriptCfg::sGlobal;
script.mInitializationData = luaData;
}
{
ESM::LuaScriptCfg& script = cfg.mScripts.emplace_back();
script.mScriptPath = VFS::Path::Normalized("test_local.lua");
script.mFlags = ESM::LuaScriptCfg::sMerge;
script.mTypes.push_back(ESM::REC_DOOR);
script.mTypes.push_back(ESM::REC_MISC);
script.mRecords.push_back({ true, ESM::RefId::stringRefId("rat"), luaData });
script.mRecords.push_back({ false, ESM::RefId::stringRefId("chargendoorjournal"), "" });
script.mRefs.push_back({ true, 128964, 1, "" });
script.mRefs.push_back({ true, 128962, 1, luaData });
}
std::stringstream stream;
writer.save(stream);
writer.startRecord(ESM::REC_LUAL);
cfg.save(writer);
writer.endRecord(ESM::REC_LUAL);
writer.close();
std::string serializedOMWAddon = stream.str();
{
// Save for manual testing.
std::ofstream f(TestingOpenMW::outputFilePath("lua_conf_test.omwaddon"), std::ios::binary);
f << serializedOMWAddon;
f.close();
}
ESM::ESMReader reader;
reader.open(std::make_unique<std::istringstream>(serializedOMWAddon), "lua_conf_test.omwaddon");
ASSERT_EQ(reader.getRecordCount(), 1);
ASSERT_EQ(reader.getRecName().toInt(), ESM::REC_LUAL);
reader.getRecHeader();
ESM::LuaScriptsCfg loadedCfg;
loadedCfg.load(reader);
ASSERT_EQ(loadedCfg.mScripts.size(), cfg.mScripts.size());
for (size_t i = 0; i < cfg.mScripts.size(); ++i)
{
EXPECT_EQ(loadedCfg.mScripts[i].mScriptPath, cfg.mScripts[i].mScriptPath);
EXPECT_EQ(loadedCfg.mScripts[i].mFlags, cfg.mScripts[i].mFlags);
EXPECT_EQ(loadedCfg.mScripts[i].mInitializationData, cfg.mScripts[i].mInitializationData);
ASSERT_EQ(loadedCfg.mScripts[i].mTypes.size(), cfg.mScripts[i].mTypes.size());
for (size_t j = 0; j < cfg.mScripts[i].mTypes.size(); ++j)
EXPECT_EQ(loadedCfg.mScripts[i].mTypes[j], cfg.mScripts[i].mTypes[j]);
ASSERT_EQ(loadedCfg.mScripts[i].mRecords.size(), cfg.mScripts[i].mRecords.size());
for (size_t j = 0; j < cfg.mScripts[i].mRecords.size(); ++j)
{
EXPECT_EQ(loadedCfg.mScripts[i].mRecords[j].mAttach, cfg.mScripts[i].mRecords[j].mAttach);
EXPECT_EQ(loadedCfg.mScripts[i].mRecords[j].mRecordId, cfg.mScripts[i].mRecords[j].mRecordId);
EXPECT_EQ(loadedCfg.mScripts[i].mRecords[j].mInitializationData,
cfg.mScripts[i].mRecords[j].mInitializationData);
}
ASSERT_EQ(loadedCfg.mScripts[i].mRefs.size(), cfg.mScripts[i].mRefs.size());
for (size_t j = 0; j < cfg.mScripts[i].mRefs.size(); ++j)
{
EXPECT_EQ(loadedCfg.mScripts[i].mRefs[j].mAttach, cfg.mScripts[i].mRefs[j].mAttach);
EXPECT_EQ(loadedCfg.mScripts[i].mRefs[j].mRefnumIndex, cfg.mScripts[i].mRefs[j].mRefnumIndex);
EXPECT_EQ(
loadedCfg.mScripts[i].mRefs[j].mRefnumContentFile, cfg.mScripts[i].mRefs[j].mRefnumContentFile);
EXPECT_EQ(
loadedCfg.mScripts[i].mRefs[j].mInitializationData, cfg.mScripts[i].mRefs[j].mInitializationData);
}
}
{
ESM::ReadersCache readers(4);
readers.get(0)->openRaw(std::make_unique<std::istringstream>("dummyData"), "a.omwaddon");
readers.get(1)->openRaw(std::make_unique<std::istringstream>("dummyData"), "b.omwaddon");
readers.get(2)->openRaw(std::make_unique<std::istringstream>("dummyData"), "Morrowind.esm");
readers.get(3)->openRaw(std::make_unique<std::istringstream>("dummyData"), "c.omwaddon");
reader.setIndex(3);
reader.resolveParentFileIndices(readers);
}
loadedCfg.adjustRefNums(reader);
EXPECT_EQ(loadedCfg.mScripts[1].mRefs[0].mRefnumIndex, cfg.mScripts[1].mRefs[0].mRefnumIndex);
EXPECT_EQ(loadedCfg.mScripts[1].mRefs[0].mRefnumContentFile, 2);
{
sol::table data = LuaUtil::deserialize(
lua.lua_state(), loadedCfg.mScripts[1].mRefs[1].mInitializationData, &serializer);
ESM::RefNum adjustedRef = data["fargoth"].get<ESM::RefNum>();
EXPECT_EQ(adjustedRef.mIndex, 128964u);
EXPECT_EQ(adjustedRef.mContentFile, 2);
}
}
}
| 12,970
|
C++
|
.cpp
| 231
| 46.212121
| 118
| 0.633703
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,208
|
test_inputactions.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_inputactions.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <components/lua/inputactions.hpp>
#include <components/lua/scriptscontainer.hpp>
#include <components/testing/util.hpp>
namespace
{
using namespace testing;
using namespace TestingOpenMW;
TEST(LuaInputActionsTest, MultiTree)
{
{
LuaUtil::InputAction::MultiTree tree;
auto a = tree.insert();
auto b = tree.insert();
auto c = tree.insert();
auto d = tree.insert();
EXPECT_TRUE(tree.multiEdge(c, { a, b }));
EXPECT_TRUE(tree.multiEdge(a, { d }));
EXPECT_FALSE(tree.multiEdge(d, { c }));
}
{
LuaUtil::InputAction::MultiTree tree;
auto a = tree.insert();
auto b = tree.insert();
auto c = tree.insert();
EXPECT_TRUE(tree.multiEdge(b, { a }));
EXPECT_TRUE(tree.multiEdge(c, { a, b }));
}
}
TEST(LuaInputActionsTest, Registry)
{
sol::state lua;
LuaUtil::InputAction::Registry registry;
LuaUtil::InputAction::Info a({ "a", LuaUtil::InputAction::Type::Boolean, "test", "a_name", "a_description",
sol::make_object(lua, false) });
registry.insert(a);
LuaUtil::InputAction::Info b({ "b", LuaUtil::InputAction::Type::Boolean, "test", "b_name", "b_description",
sol::make_object(lua, false) });
registry.insert(b);
LuaUtil::Callback bindA({ lua.load("return function() return true end")(), sol::table(lua, sol::create) });
LuaUtil::Callback bindBToA(
{ lua.load("return function(_, _, aValue) return aValue end")(), sol::table(lua, sol::create) });
EXPECT_TRUE(registry.bind("a", bindA, {}));
EXPECT_TRUE(registry.bind("b", bindBToA, { "a" }));
registry.update(1.0);
sol::object bValue = registry.valueOfType("b", LuaUtil::InputAction::Type::Boolean);
EXPECT_TRUE(bValue.is<bool>());
LuaUtil::Callback badA(
{ lua.load("return function() return 'not_a_bool' end")(), sol::table(lua, sol::create) });
EXPECT_TRUE(registry.bind("a", badA, {}));
testing::internal::CaptureStderr();
registry.update(1.0);
sol::object aValue = registry.valueOfType("a", LuaUtil::InputAction::Type::Boolean);
EXPECT_TRUE(aValue.is<bool>());
bValue = registry.valueOfType("b", LuaUtil::InputAction::Type::Boolean);
EXPECT_TRUE(bValue.is<bool>() && bValue.as<bool>() == aValue.as<bool>());
}
}
| 2,566
|
C++
|
.cpp
| 59
| 34.813559
| 115
| 0.590328
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,209
|
test_l10n.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_l10n.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <components/files/fixedpath.hpp>
#include <components/l10n/manager.hpp>
#include <components/lua/l10n.hpp>
#include <components/lua/luastate.hpp>
#include <components/testing/util.hpp>
namespace
{
using namespace testing;
using namespace TestingOpenMW;
template <typename T>
T get(sol::state_view& lua, const std::string& luaCode)
{
return lua.safe_script("return " + luaCode).get<T>();
}
constexpr VFS::Path::NormalizedView test1EnPath("l10n/test1/en.yaml");
constexpr VFS::Path::NormalizedView test1EnUsPath("l10n/test1/en_us.yaml");
constexpr VFS::Path::NormalizedView test1DePath("l10n/test1/de.yaml");
constexpr VFS::Path::NormalizedView test2EnPath("l10n/test2/en.yaml");
constexpr VFS::Path::NormalizedView test3EnPath("l10n/test3/en.yaml");
constexpr VFS::Path::NormalizedView test3DePath("l10n/test3/de.yaml");
VFSTestFile invalidScript("not a script");
VFSTestFile incorrectScript(
"return { incorrectSection = {}, engineHandlers = { incorrectHandler = function() end } }");
VFSTestFile emptyScript("");
VFSTestFile test1En(R"X(
good_morning: "Good morning."
you_have_arrows: |-
{count, plural,
=0{You have no arrows.}
one{You have one arrow.}
other{You have {count} arrows.}
}
pc_must_come: |-
{PCGender, select,
male {He is}
female {She is}
other {They are}
} coming with us.
quest_completion: "The quest is {done, number, percent} complete."
ordinal: "You came in {num, ordinal} place."
spellout: "There {num, plural, one{is {num, spellout} thing} other{are {num, spellout} things}}."
duration: "It took {num, duration}"
numbers: "{int} and {double, number, integer} are integers, but {double} is a double"
rounding: "{value, number, :: .00}"
)X");
VFSTestFile test1De(R"X(
good_morning: "Guten Morgen."
you_have_arrows: |-
{count, plural,
one{Du hast ein Pfeil.}
other{Du hast {count} Pfeile.}
}
"Hello {name}!": "Hallo {name}!"
)X");
VFSTestFile test1EnUS(R"X(
currency: "You have {money, number, currency}"
)X");
VFSTestFile test2En(R"X(
good_morning: "Morning!"
you_have_arrows: "Arrows count: {count}"
)X");
struct LuaL10nTest : Test
{
std::unique_ptr<VFS::Manager> mVFS = createTestVFS({
{ test1EnPath, &test1En },
{ test1EnUsPath, &test1EnUS },
{ test1DePath, &test1De },
{ test2EnPath, &test2En },
{ test3EnPath, &test1En },
{ test3DePath, &test1De },
});
LuaUtil::ScriptsConfiguration mCfg;
};
TEST_F(LuaL10nTest, L10n)
{
LuaUtil::LuaState lua{ mVFS.get(), &mCfg };
lua.protectedCall([&](LuaUtil::LuaView& view) {
sol::state_view& l = view.sol();
internal::CaptureStdout();
l10n::Manager l10nManager(mVFS.get());
l10nManager.setPreferredLocales({ "de", "en" });
EXPECT_THAT(internal::GetCapturedStdout(), "Preferred locales: gmst de en\n");
l["l10n"] = LuaUtil::initL10nLoader(l, &l10nManager);
internal::CaptureStdout();
l.safe_script("t1 = l10n('Test1')");
EXPECT_THAT(internal::GetCapturedStdout(),
"Language file \"l10n/Test1/de.yaml\" is enabled\n"
"Language file \"l10n/Test1/en.yaml\" is enabled\n");
internal::CaptureStdout();
l.safe_script("t2 = l10n('Test2')");
{
std::string output = internal::GetCapturedStdout();
EXPECT_THAT(output, HasSubstr("Language file \"l10n/Test2/en.yaml\" is enabled"));
}
EXPECT_EQ(get<std::string>(l, "t1('good_morning')"), "Guten Morgen.");
EXPECT_EQ(get<std::string>(l, "t1('you_have_arrows', {count=1})"), "Du hast ein Pfeil.");
EXPECT_EQ(get<std::string>(l, "t1('you_have_arrows', {count=5})"), "Du hast 5 Pfeile.");
EXPECT_EQ(get<std::string>(l, "t1('Hello {name}!', {name='World'})"), "Hallo World!");
EXPECT_EQ(get<std::string>(l, "t2('good_morning')"), "Morning!");
EXPECT_EQ(get<std::string>(l, "t2('you_have_arrows', {count=3})"), "Arrows count: 3");
internal::CaptureStdout();
l10nManager.setPreferredLocales({ "en", "de" });
EXPECT_THAT(internal::GetCapturedStdout(),
"Preferred locales: gmst en de\n"
"Language file \"l10n/Test1/en.yaml\" is enabled\n"
"Language file \"l10n/Test1/de.yaml\" is enabled\n"
"Language file \"l10n/Test2/en.yaml\" is enabled\n");
EXPECT_EQ(get<std::string>(l, "t1('good_morning')"), "Good morning.");
EXPECT_EQ(get<std::string>(l, "t1('you_have_arrows', {count=1})"), "You have one arrow.");
EXPECT_EQ(get<std::string>(l, "t1('you_have_arrows', {count=5})"), "You have 5 arrows.");
EXPECT_EQ(get<std::string>(l, "t1('pc_must_come', {PCGender=\"male\"})"), "He is coming with us.");
EXPECT_EQ(get<std::string>(l, "t1('pc_must_come', {PCGender=\"female\"})"), "She is coming with us.");
EXPECT_EQ(get<std::string>(l, "t1('pc_must_come', {PCGender=\"blah\"})"), "They are coming with us.");
EXPECT_EQ(get<std::string>(l, "t1('pc_must_come', {PCGender=\"other\"})"), "They are coming with us.");
EXPECT_EQ(get<std::string>(l, "t1('quest_completion', {done=0.1})"), "The quest is 10% complete.");
EXPECT_EQ(get<std::string>(l, "t1('quest_completion', {done=1})"), "The quest is 100% complete.");
EXPECT_EQ(get<std::string>(l, "t1('ordinal', {num=1})"), "You came in 1st place.");
EXPECT_EQ(get<std::string>(l, "t1('ordinal', {num=100})"), "You came in 100th place.");
EXPECT_EQ(get<std::string>(l, "t1('spellout', {num=1})"), "There is one thing.");
EXPECT_EQ(get<std::string>(l, "t1('spellout', {num=100})"), "There are one hundred things.");
EXPECT_EQ(get<std::string>(l, "t1('duration', {num=100})"), "It took 1:40");
EXPECT_EQ(get<std::string>(l, "t1('numbers', {int=123, double=123.456})"),
"123 and 123 are integers, but 123.456 is a double");
EXPECT_EQ(get<std::string>(l, "t1('rounding', {value=123.456789})"), "123.46");
// Check that failed messages display the key instead of an empty string
EXPECT_EQ(get<std::string>(l, "t1('{mismatched_braces')"), "{mismatched_braces");
EXPECT_EQ(get<std::string>(l, "t1('{unknown_arg}')"), "{unknown_arg}");
EXPECT_EQ(get<std::string>(l, "t1('{num, integer}', {num=1})"), "{num, integer}");
// Doesn't give a valid currency symbol with `en`. Not that openmw is designed for real world currency.
l10nManager.setPreferredLocales({ "en-US", "de" });
EXPECT_EQ(get<std::string>(l, "t1('currency', {money=10000.10})"), "You have $10,000.10");
// Note: Not defined in English localisation file, so we fall back to the German before falling back to the
// key
EXPECT_EQ(get<std::string>(l, "t1('Hello {name}!', {name='World'})"), "Hallo World!");
EXPECT_EQ(get<std::string>(l, "t2('good_morning')"), "Morning!");
EXPECT_EQ(get<std::string>(l, "t2('you_have_arrows', {count=3})"), "Arrows count: 3");
// Test that locales with variants and country codes fall back to more generic locales
internal::CaptureStdout();
l10nManager.setPreferredLocales({ "en-GB-oed", "de" });
EXPECT_THAT(internal::GetCapturedStdout(),
"Preferred locales: gmst en_GB_OED de\n"
"Language file \"l10n/Test1/en.yaml\" is enabled\n"
"Language file \"l10n/Test1/de.yaml\" is enabled\n"
"Language file \"l10n/Test2/en.yaml\" is enabled\n");
EXPECT_EQ(get<std::string>(l, "t2('you_have_arrows', {count=3})"), "Arrows count: 3");
// Test setting fallback language
l.safe_script("t3 = l10n('Test3', 'de')");
l10nManager.setPreferredLocales({ "en" });
EXPECT_EQ(get<std::string>(l, "t3('Hello {name}!', {name='World'})"), "Hallo World!");
});
}
}
| 8,333
|
C++
|
.cpp
| 154
| 45.194805
| 119
| 0.597377
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,210
|
test_serialization.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_serialization.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <osg/Matrixf>
#include <osg/Quat>
#include <osg/Vec2f>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include <components/lua/serialization.hpp>
#include <components/lua/utilpackage.hpp>
#include <components/misc/color.hpp>
#include <components/misc/endianness.hpp>
#include <components/testing/expecterror.hpp>
namespace
{
using namespace testing;
TEST(LuaSerializationTest, Nil)
{
sol::state lua;
EXPECT_EQ(LuaUtil::serialize(sol::nil), "");
EXPECT_EQ(LuaUtil::deserialize(lua, ""), sol::nil);
}
TEST(LuaSerializationTest, Number)
{
sol::state lua;
std::string serialized = LuaUtil::serialize(sol::make_object<double>(lua, 3.14));
EXPECT_EQ(serialized.size(), 10); // version, type, 8 bytes value
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<double>());
EXPECT_DOUBLE_EQ(value.as<double>(), 3.14);
}
TEST(LuaSerializationTest, Boolean)
{
sol::state lua;
{
std::string serialized = LuaUtil::serialize(sol::make_object<bool>(lua, true));
EXPECT_EQ(serialized.size(), 3); // version, type, 1 byte value
sol::object value = LuaUtil::deserialize(lua, serialized);
EXPECT_FALSE(value.is<double>());
ASSERT_TRUE(value.is<bool>());
EXPECT_TRUE(value.as<bool>());
}
{
std::string serialized = LuaUtil::serialize(sol::make_object<bool>(lua, false));
EXPECT_EQ(serialized.size(), 3); // version, type, 1 byte value
sol::object value = LuaUtil::deserialize(lua, serialized);
EXPECT_FALSE(value.is<double>());
ASSERT_TRUE(value.is<bool>());
EXPECT_FALSE(value.as<bool>());
}
}
TEST(LuaSerializationTest, String)
{
sol::state lua;
std::string_view emptyString = "";
std::string_view shortString = "abc";
std::string_view longString = "It is a string with more than 32 characters...........................";
{
std::string serialized = LuaUtil::serialize(sol::make_object<std::string_view>(lua, emptyString));
EXPECT_EQ(serialized.size(), 2); // version, type
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<std::string>());
EXPECT_EQ(value.as<std::string>(), emptyString);
}
{
std::string serialized = LuaUtil::serialize(sol::make_object<std::string_view>(lua, shortString));
EXPECT_EQ(serialized.size(), 2 + shortString.size()); // version, type, str data
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<std::string>());
EXPECT_EQ(value.as<std::string>(), shortString);
}
{
std::string serialized = LuaUtil::serialize(sol::make_object<std::string_view>(lua, longString));
EXPECT_EQ(serialized.size(), 6 + longString.size()); // version, type, size, str data
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<std::string>());
EXPECT_EQ(value.as<std::string>(), longString);
}
}
TEST(LuaSerializationTest, Vector)
{
sol::state lua;
osg::Vec2f vec2(1, 2);
osg::Vec3f vec3(1, 2, 3);
osg::Vec4f vec4(1, 2, 3, 4);
{
std::string serialized = LuaUtil::serialize(sol::make_object(lua, vec2));
EXPECT_EQ(serialized.size(), 18); // version, type, 2x double
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<osg::Vec2f>());
EXPECT_EQ(value.as<osg::Vec2f>(), vec2);
}
{
std::string serialized = LuaUtil::serialize(sol::make_object(lua, vec3));
EXPECT_EQ(serialized.size(), 26); // version, type, 3x double
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<osg::Vec3f>());
EXPECT_EQ(value.as<osg::Vec3f>(), vec3);
}
{
std::string serialized = LuaUtil::serialize(sol::make_object(lua, vec4));
EXPECT_EQ(serialized.size(), 34); // version, type, 4x double
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<osg::Vec4f>());
EXPECT_EQ(value.as<osg::Vec4f>(), vec4);
}
}
TEST(LuaSerializationTest, Color)
{
sol::state lua;
Misc::Color color(1, 1, 1, 1);
{
std::string serialized = LuaUtil::serialize(sol::make_object(lua, color));
EXPECT_EQ(serialized.size(), 18); // version, type, 4x float
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<Misc::Color>());
EXPECT_EQ(value.as<Misc::Color>(), color);
}
}
TEST(LuaSerializationTest, Transform)
{
sol::state lua;
osg::Matrixf matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
LuaUtil::TransformM transM = LuaUtil::asTransform(matrix);
osg::Quat quat(1, 2, 3, 4);
LuaUtil::TransformQ transQ = LuaUtil::asTransform(quat);
{
std::string serialized = LuaUtil::serialize(sol::make_object(lua, transM));
EXPECT_EQ(serialized.size(), 130); // version, type, 16x double
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<LuaUtil::TransformM>());
EXPECT_EQ(value.as<LuaUtil::TransformM>().mM, transM.mM);
}
{
std::string serialized = LuaUtil::serialize(sol::make_object(lua, transQ));
EXPECT_EQ(serialized.size(), 34); // version, type, 4x double
sol::object value = LuaUtil::deserialize(lua, serialized);
ASSERT_TRUE(value.is<LuaUtil::TransformQ>());
EXPECT_EQ(value.as<LuaUtil::TransformQ>().mQ, transQ.mQ);
}
}
TEST(LuaSerializationTest, Table)
{
sol::state lua;
sol::table table(lua, sol::create);
table["aa"] = 1;
table["ab"] = true;
table["nested"] = sol::table(lua, sol::create);
table["nested"]["aa"] = 2;
table["nested"]["bb"] = "something";
table["nested"][5] = -0.5;
table["nested_empty"] = sol::table(lua, sol::create);
table[1] = osg::Vec2f(1, 2);
table[2] = osg::Vec2f(2, 1);
std::string serialized = LuaUtil::serialize(table);
EXPECT_EQ(serialized.size(), 139);
sol::table res_table = LuaUtil::deserialize(lua, serialized);
sol::table res_readonly_table = LuaUtil::deserialize(lua, serialized, nullptr, true);
for (auto t : { res_table, res_readonly_table })
{
EXPECT_EQ(t.get<int>("aa"), 1);
EXPECT_EQ(t.get<bool>("ab"), true);
EXPECT_EQ(t.get<sol::table>("nested").get<int>("aa"), 2);
EXPECT_EQ(t.get<sol::table>("nested").get<std::string>("bb"), "something");
EXPECT_DOUBLE_EQ(t.get<sol::table>("nested").get<double>(5), -0.5);
EXPECT_EQ(t.get<osg::Vec2f>(1), osg::Vec2f(1, 2));
EXPECT_EQ(t.get<osg::Vec2f>(2), osg::Vec2f(2, 1));
}
lua["t"] = res_table;
lua["ro_t"] = res_readonly_table;
EXPECT_NO_THROW(lua.safe_script("t.x = 5"));
EXPECT_NO_THROW(lua.safe_script("t.nested.x = 5"));
EXPECT_ERROR(lua.safe_script("ro_t.x = 5"), "userdata value");
EXPECT_ERROR(lua.safe_script("ro_t.nested.x = 5"), "userdata value");
}
struct TestStruct1
{
double a, b;
};
struct TestStruct2
{
int a, b;
};
class TestSerializer final : public LuaUtil::UserdataSerializer
{
bool serialize(LuaUtil::BinaryData& out, const sol::userdata& data) const override
{
if (data.is<TestStruct1>())
{
TestStruct1 t = data.as<TestStruct1>();
t.a = Misc::toLittleEndian(t.a);
t.b = Misc::toLittleEndian(t.b);
append(out, "ts1", &t, sizeof(t));
return true;
}
if (data.is<TestStruct2>())
{
TestStruct2 t = data.as<TestStruct2>();
t.a = Misc::toLittleEndian(t.a);
t.b = Misc::toLittleEndian(t.b);
append(out, "test_struct2", &t, sizeof(t));
return true;
}
return false;
}
bool deserialize(std::string_view typeName, std::string_view binaryData, lua_State* lua) const override
{
if (typeName == "ts1")
{
if (sizeof(TestStruct1) != binaryData.size())
throw std::runtime_error(
"Incorrect binaryData.size() for TestStruct1: " + std::to_string(binaryData.size()));
TestStruct1 t;
std::memcpy(&t, binaryData.data(), sizeof(t));
t.a = Misc::fromLittleEndian(t.a);
t.b = Misc::fromLittleEndian(t.b);
sol::stack::push<TestStruct1>(lua, t);
return true;
}
if (typeName == "test_struct2")
{
if (sizeof(TestStruct2) != binaryData.size())
throw std::runtime_error(
"Incorrect binaryData.size() for TestStruct2: " + std::to_string(binaryData.size()));
TestStruct2 t;
std::memcpy(&t, binaryData.data(), sizeof(t));
t.a = Misc::fromLittleEndian(t.a);
t.b = Misc::fromLittleEndian(t.b);
sol::stack::push<TestStruct2>(lua, t);
return true;
}
return false;
}
};
TEST(LuaSerializationTest, UserdataSerializer)
{
sol::state lua;
sol::table table(lua, sol::create);
table["x"] = TestStruct1{ 1.5, 2.5 };
table["y"] = TestStruct2{ 4, 3 };
TestSerializer serializer;
EXPECT_ERROR(LuaUtil::serialize(table), "Value is not serializable.");
std::string serialized = LuaUtil::serialize(table, &serializer);
EXPECT_ERROR(LuaUtil::deserialize(lua, serialized), "Unknown type in serialized data:");
sol::table res = LuaUtil::deserialize(lua, serialized, &serializer);
TestStruct1 rx = res.get<TestStruct1>("x");
TestStruct2 ry = res.get<TestStruct2>("y");
EXPECT_EQ(rx.a, 1.5);
EXPECT_EQ(rx.b, 2.5);
EXPECT_EQ(ry.a, 4);
EXPECT_EQ(ry.b, 3);
}
}
| 10,789
|
C++
|
.cpp
| 252
| 32.547619
| 111
| 0.563178
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,211
|
test_async.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_async.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <components/lua/asyncpackage.hpp>
#include <components/lua/luastate.hpp>
#include <components/testing/expecterror.hpp>
namespace
{
using namespace testing;
struct LuaCoroutineCallbackTest : Test
{
void SetUp() override
{
mLua.protectedCall([&](LuaUtil::LuaView& view) {
view.sol()["callback"] = [](sol::this_state state, sol::protected_function fn) -> LuaUtil::Callback {
sol::table hiddenData(state, sol::create);
hiddenData[LuaUtil::ScriptsContainer::sScriptIdKey] = LuaUtil::ScriptId{};
return LuaUtil::Callback{ std::move(fn), hiddenData };
};
view.sol()["pass"] = [&](LuaUtil::Callback callback) { mCb = callback; };
});
}
LuaUtil::LuaState mLua{ nullptr, nullptr };
LuaUtil::Callback mCb;
};
TEST_F(LuaCoroutineCallbackTest, CoroutineCallbacks)
{
internal::CaptureStdout();
mLua.protectedCall([&](LuaUtil::LuaView& view) {
view.sol().safe_script(R"X(
local s = 'test'
coroutine.wrap(function()
pass(callback(function(v) print(s) end))
end)()
)X");
view.sol().collect_garbage();
mCb.call();
});
EXPECT_THAT(internal::GetCapturedStdout(), "test\n");
}
TEST_F(LuaCoroutineCallbackTest, ErrorInCoroutineCallbacks)
{
mLua.protectedCall([&](LuaUtil::LuaView& view) {
view.sol().safe_script(R"X(
coroutine.wrap(function()
pass(callback(function() error('COROUTINE CALLBACK') end))
end)()
)X");
view.sol().collect_garbage();
});
EXPECT_ERROR(mCb.call(), "COROUTINE CALLBACK");
}
}
| 1,916
|
C++
|
.cpp
| 52
| 26.653846
| 117
| 0.560818
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,212
|
test_lua.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_lua.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <components/lua/luastate.hpp>
#include <components/testing/expecterror.hpp>
#include <components/testing/util.hpp>
namespace
{
using namespace testing;
constexpr VFS::Path::NormalizedView counterPath("aaa/counter.lua");
TestingOpenMW::VFSTestFile counterFile(R"X(
x = 42
return {
get = function() return x end,
inc = function(v) x = x + v end
}
)X");
constexpr VFS::Path::NormalizedView invalidPath("invalid.lua");
TestingOpenMW::VFSTestFile invalidScriptFile("Invalid script");
constexpr VFS::Path::NormalizedView testsPath("bbb/tests.lua");
TestingOpenMW::VFSTestFile testsFile(R"X(
return {
-- should work
sin = function(x) return math.sin(x) end,
requireMathSin = function(x) return require('math').sin(x) end,
useCounter = function()
local counter = require('aaa.counter')
counter.inc(1)
return counter.get()
end,
callRawset = function()
t = {a = 1, b = 2}
rawset(t, 'b', 3)
return t.b
end,
print = print,
-- should throw an error
incorrectRequire = function() require('counter') end,
modifySystemLib = function() math.sin = 5 end,
modifySystemLib2 = function() math.__index.sin = 5 end,
rawsetSystemLib = function() rawset(math, 'sin', 5) end,
callLoadstring = function() loadstring('print(1)') end,
setSqr = function() require('sqrlib').sqr = math.sin end,
setOmwName = function() require('openmw').name = 'abc' end,
-- should work if API is registered
sqr = function(x) return require('sqrlib').sqr(x) end,
apiName = function() return require('test.api').name end
}
)X");
constexpr VFS::Path::NormalizedView metaIndexErrorPath("metaindexerror.lua");
TestingOpenMW::VFSTestFile metaIndexErrorFile(
"return setmetatable({}, { __index = function(t, key) error('meta index error') end })");
std::string genBigScript()
{
std::stringstream buf;
buf << "return function()\n";
buf << " x = {}\n";
for (int i = 0; i < 1000; ++i)
buf << " x[" << i * 2 << "] = " << i << "\n";
buf << " return x\n";
buf << "end\n";
return buf.str();
}
constexpr VFS::Path::NormalizedView bigPath("big.lua");
TestingOpenMW::VFSTestFile bigScriptFile(genBigScript());
constexpr VFS::Path::NormalizedView requireBigPath("requirebig.lua");
TestingOpenMW::VFSTestFile requireBigScriptFile("local x = require('big') ; return {x}");
struct LuaStateTest : Test
{
std::unique_ptr<VFS::Manager> mVFS = TestingOpenMW::createTestVFS({
{ counterPath, &counterFile },
{ testsPath, &testsFile },
{ invalidPath, &invalidScriptFile },
{ bigPath, &bigScriptFile },
{ requireBigPath, &requireBigScriptFile },
{ metaIndexErrorPath, &metaIndexErrorFile },
});
LuaUtil::ScriptsConfiguration mCfg;
LuaUtil::LuaState mLua{ mVFS.get(), &mCfg };
};
TEST_F(LuaStateTest, Sandbox)
{
const VFS::Path::Normalized path(counterPath);
sol::table script1 = mLua.runInNewSandbox(path);
EXPECT_EQ(LuaUtil::call(script1["get"]).get<int>(), 42);
LuaUtil::call(script1["inc"], 3);
EXPECT_EQ(LuaUtil::call(script1["get"]).get<int>(), 45);
sol::table script2 = mLua.runInNewSandbox(path);
EXPECT_EQ(LuaUtil::call(script2["get"]).get<int>(), 42);
LuaUtil::call(script2["inc"], 1);
EXPECT_EQ(LuaUtil::call(script2["get"]).get<int>(), 43);
EXPECT_EQ(LuaUtil::call(script1["get"]).get<int>(), 45);
}
TEST_F(LuaStateTest, ToString)
{
EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.unsafeState(), 3.14)), "3.14");
EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.unsafeState(), true)), "true");
EXPECT_EQ(LuaUtil::toString(sol::nil), "nil");
EXPECT_EQ(LuaUtil::toString(sol::make_object(mLua.unsafeState(), "something")), "\"something\"");
}
TEST_F(LuaStateTest, Cast)
{
EXPECT_EQ(LuaUtil::cast<int>(sol::make_object(mLua.unsafeState(), 3.14)), 3);
EXPECT_ERROR(LuaUtil::cast<int>(sol::make_object(mLua.unsafeState(), "3.14")),
"Value \"\"3.14\"\" can not be casted to int");
EXPECT_ERROR(LuaUtil::cast<std::string_view>(sol::make_object(mLua.unsafeState(), sol::nil)),
"Value \"nil\" can not be casted to string");
EXPECT_ERROR(LuaUtil::cast<std::string>(sol::make_object(mLua.unsafeState(), sol::nil)),
"Value \"nil\" can not be casted to string");
EXPECT_ERROR(LuaUtil::cast<sol::table>(sol::make_object(mLua.unsafeState(), sol::nil)),
"Value \"nil\" can not be casted to sol::table");
EXPECT_ERROR(LuaUtil::cast<sol::function>(sol::make_object(mLua.unsafeState(), "3.14")),
"Value \"\"3.14\"\" can not be casted to sol::function");
EXPECT_ERROR(LuaUtil::cast<sol::protected_function>(sol::make_object(mLua.unsafeState(), "3.14")),
"Value \"\"3.14\"\" can not be casted to sol::function");
}
TEST_F(LuaStateTest, ErrorHandling)
{
const VFS::Path::Normalized path("invalid.lua");
EXPECT_ERROR(mLua.runInNewSandbox(path), "[string \"invalid.lua\"]:1:");
}
TEST_F(LuaStateTest, CustomRequire)
{
const VFS::Path::Normalized path("bbb/tests.lua");
sol::table script = mLua.runInNewSandbox(path);
EXPECT_FLOAT_EQ(
LuaUtil::call(script["sin"], 1).get<float>(), -LuaUtil::call(script["requireMathSin"], -1).get<float>());
EXPECT_EQ(LuaUtil::call(script["useCounter"]).get<int>(), 43);
EXPECT_EQ(LuaUtil::call(script["useCounter"]).get<int>(), 44);
{
sol::table script2 = mLua.runInNewSandbox(path);
EXPECT_EQ(LuaUtil::call(script2["useCounter"]).get<int>(), 43);
}
EXPECT_EQ(LuaUtil::call(script["useCounter"]).get<int>(), 45);
EXPECT_ERROR(LuaUtil::call(script["incorrectRequire"]), "module not found: counter");
}
TEST_F(LuaStateTest, ReadOnly)
{
const VFS::Path::Normalized path("bbb/tests.lua");
sol::table script = mLua.runInNewSandbox(path);
// rawset itself is allowed
EXPECT_EQ(LuaUtil::call(script["callRawset"]).get<int>(), 3);
// but read-only object can not be modified even with rawset
EXPECT_ERROR(
LuaUtil::call(script["rawsetSystemLib"]), "bad argument #1 to 'rawset' (table expected, got userdata)");
EXPECT_ERROR(LuaUtil::call(script["modifySystemLib"]), "a userdata value");
EXPECT_ERROR(LuaUtil::call(script["modifySystemLib2"]), "a nil value");
EXPECT_EQ(LuaUtil::getMutableFromReadOnly(LuaUtil::makeReadOnly(script)), script);
}
TEST_F(LuaStateTest, Print)
{
const VFS::Path::Normalized path("bbb/tests.lua");
{
sol::table script = mLua.runInNewSandbox(path);
testing::internal::CaptureStdout();
LuaUtil::call(script["print"], 1, 2, 3);
std::string output = testing::internal::GetCapturedStdout();
EXPECT_EQ(output, "unnamed:\t1\t2\t3\n");
}
{
sol::table script = mLua.runInNewSandbox(path, "prefix");
testing::internal::CaptureStdout();
LuaUtil::call(script["print"]); // print with no arguments
std::string output = testing::internal::GetCapturedStdout();
EXPECT_EQ(output, "prefix:\n");
}
}
TEST_F(LuaStateTest, UnsafeFunction)
{
const VFS::Path::Normalized path("bbb/tests.lua");
sol::table script = mLua.runInNewSandbox(path);
EXPECT_ERROR(LuaUtil::call(script["callLoadstring"]), "a nil value");
}
TEST_F(LuaStateTest, ProvideAPI)
{
LuaUtil::LuaState lua(mVFS.get(), &mCfg);
lua.protectedCall([&](LuaUtil::LuaView& view) {
sol::table api1 = LuaUtil::makeReadOnly(view.sol().create_table_with("name", "api1"));
sol::table api2 = LuaUtil::makeReadOnly(view.sol().create_table_with("name", "api2"));
const VFS::Path::Normalized path("bbb/tests.lua");
sol::table script1 = lua.runInNewSandbox(path, "", { { "test.api", api1 } });
lua.addCommonPackage("sqrlib", view.sol().create_table_with("sqr", [](int x) { return x * x; }));
sol::table script2 = lua.runInNewSandbox(path, "", { { "test.api", api2 } });
EXPECT_ERROR(LuaUtil::call(script1["sqr"], 3), "module not found: sqrlib");
EXPECT_EQ(LuaUtil::call(script2["sqr"], 3).get<int>(), 9);
EXPECT_EQ(LuaUtil::call(script1["apiName"]).get<std::string>(), "api1");
EXPECT_EQ(LuaUtil::call(script2["apiName"]).get<std::string>(), "api2");
});
}
TEST_F(LuaStateTest, GetLuaVersion)
{
EXPECT_THAT(LuaUtil::getLuaVersion(), HasSubstr("Lua"));
}
TEST_F(LuaStateTest, RemovedScriptsGarbageCollecting)
{
auto getMem = [&] {
for (int i = 0; i < 5; ++i)
lua_gc(mLua.unsafeState(), LUA_GCCOLLECT, 0);
return mLua.getTotalMemoryUsage();
};
int64_t memWithScript;
const VFS::Path::Normalized path("requireBig.lua");
{
sol::object s = mLua.runInNewSandbox(path);
memWithScript = getMem();
}
for (int i = 0; i < 100; ++i) // run many times to make small memory leaks visible
mLua.runInNewSandbox(path);
int64_t memWithoutScript = getMem();
// At this moment all instances of the script should be garbage-collected.
EXPECT_LT(memWithoutScript, memWithScript);
}
TEST_F(LuaStateTest, SafeIndexMetamethod)
{
const VFS::Path::Normalized path("metaIndexError.lua");
sol::table t = mLua.runInNewSandbox(path);
// without safe get we crash here
EXPECT_ERROR(LuaUtil::safeGet(t, "any key"), "meta index error");
}
}
| 10,111
|
C++
|
.cpp
| 219
| 38.091324
| 117
| 0.617103
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,213
|
test_yaml.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_yaml.cpp
|
#include <gtest/gtest.h>
#include <sol/object.hpp>
#include <sol/state.hpp>
#include <sol/table.hpp>
#include <yaml-cpp/yaml.h>
#include <components/lua/yamlloader.hpp>
namespace
{
template <typename T>
bool checkNumber(sol::state_view& lua, const std::string& inputData, T requiredValue)
{
sol::object result = LuaUtil::loadYaml(inputData, lua);
if (result.get_type() != sol::type::number)
return false;
return result.as<T>() == requiredValue;
}
bool checkBool(sol::state_view& lua, const std::string& inputData, bool requiredValue)
{
sol::object result = LuaUtil::loadYaml(inputData, lua);
if (result.get_type() != sol::type::boolean)
return false;
return result.as<bool>() == requiredValue;
}
bool checkNil(sol::state_view& lua, const std::string& inputData)
{
sol::object result = LuaUtil::loadYaml(inputData, lua);
return result == sol::nil;
}
bool checkNan(sol::state_view& lua, const std::string& inputData)
{
sol::object result = LuaUtil::loadYaml(inputData, lua);
if (result.get_type() != sol::type::number)
return false;
return std::isnan(result.as<double>());
}
bool checkString(sol::state_view& lua, const std::string& inputData, const std::string& requiredValue)
{
sol::object result = LuaUtil::loadYaml(inputData, lua);
if (result.get_type() != sol::type::string)
return false;
return result.as<std::string>() == requiredValue;
}
bool checkString(sol::state_view& lua, const std::string& inputData)
{
sol::object result = LuaUtil::loadYaml(inputData, lua);
if (result.get_type() != sol::type::string)
return false;
return result.as<std::string>() == inputData;
}
TEST(LuaUtilYamlLoader, ScalarTypeDeduction)
{
sol::state lua;
ASSERT_TRUE(checkNil(lua, "null"));
ASSERT_TRUE(checkNil(lua, "Null"));
ASSERT_TRUE(checkNil(lua, "NULL"));
ASSERT_TRUE(checkNil(lua, "~"));
ASSERT_TRUE(checkNil(lua, ""));
ASSERT_FALSE(checkNil(lua, "NUll"));
ASSERT_TRUE(checkString(lua, "NUll"));
ASSERT_TRUE(checkString(lua, "'null'", "null"));
ASSERT_TRUE(checkNumber(lua, "017", 17));
ASSERT_TRUE(checkNumber(lua, "-017", -17));
ASSERT_TRUE(checkNumber(lua, "+017", 17));
ASSERT_TRUE(checkNumber(lua, "17", 17));
ASSERT_TRUE(checkNumber(lua, "-17", -17));
ASSERT_TRUE(checkNumber(lua, "+17", 17));
ASSERT_TRUE(checkNumber(lua, "0o17", 15));
ASSERT_TRUE(checkString(lua, "-0o17"));
ASSERT_TRUE(checkString(lua, "+0o17"));
ASSERT_TRUE(checkString(lua, "0b1"));
ASSERT_TRUE(checkString(lua, "1:00"));
ASSERT_TRUE(checkString(lua, "'17'", "17"));
ASSERT_TRUE(checkNumber(lua, "0x17", 23));
ASSERT_TRUE(checkString(lua, "'-0x17'", "-0x17"));
ASSERT_TRUE(checkString(lua, "'+0x17'", "+0x17"));
ASSERT_TRUE(checkNumber(lua, "2.1e-05", 2.1e-5));
ASSERT_TRUE(checkNumber(lua, "-2.1e-05", -2.1e-5));
ASSERT_TRUE(checkNumber(lua, "+2.1e-05", 2.1e-5));
ASSERT_TRUE(checkNumber(lua, "2.1e+5", 210000));
ASSERT_TRUE(checkNumber(lua, "-2.1e+5", -210000));
ASSERT_TRUE(checkNumber(lua, "+2.1e+5", 210000));
ASSERT_TRUE(checkNumber(lua, "0.27", 0.27));
ASSERT_TRUE(checkNumber(lua, "-0.27", -0.27));
ASSERT_TRUE(checkNumber(lua, "+0.27", 0.27));
ASSERT_TRUE(checkNumber(lua, "2.7", 2.7));
ASSERT_TRUE(checkNumber(lua, "-2.7", -2.7));
ASSERT_TRUE(checkNumber(lua, "+2.7", 2.7));
ASSERT_TRUE(checkNumber(lua, ".27", 0.27));
ASSERT_TRUE(checkNumber(lua, "-.27", -0.27));
ASSERT_TRUE(checkNumber(lua, "+.27", 0.27));
ASSERT_TRUE(checkNumber(lua, "27.", 27.0));
ASSERT_TRUE(checkNumber(lua, "-27.", -27.0));
ASSERT_TRUE(checkNumber(lua, "+27.", 27.0));
ASSERT_TRUE(checkNan(lua, ".nan"));
ASSERT_TRUE(checkNan(lua, ".NaN"));
ASSERT_TRUE(checkNan(lua, ".NAN"));
ASSERT_FALSE(checkNan(lua, "nan"));
ASSERT_FALSE(checkNan(lua, ".nAn"));
ASSERT_TRUE(checkString(lua, "'.nan'", ".nan"));
ASSERT_TRUE(checkString(lua, ".nAn"));
ASSERT_TRUE(checkNumber(lua, "1.7976931348623157E+308", std::numeric_limits<double>::max()));
ASSERT_TRUE(checkNumber(lua, "-1.7976931348623157E+308", std::numeric_limits<double>::lowest()));
ASSERT_TRUE(checkNumber(lua, "2.2250738585072014e-308", std::numeric_limits<double>::min()));
ASSERT_TRUE(checkNumber(lua, ".inf", std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkNumber(lua, "+.inf", std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkNumber(lua, "-.inf", -std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkNumber(lua, ".Inf", std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkNumber(lua, "+.Inf", std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkNumber(lua, "-.Inf", -std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkNumber(lua, ".INF", std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkNumber(lua, "+.INF", std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkNumber(lua, "-.INF", -std::numeric_limits<double>::infinity()));
ASSERT_TRUE(checkString(lua, ".INf"));
ASSERT_TRUE(checkString(lua, "-.INf"));
ASSERT_TRUE(checkString(lua, "+.INf"));
ASSERT_TRUE(checkBool(lua, "true", true));
ASSERT_TRUE(checkBool(lua, "false", false));
ASSERT_TRUE(checkBool(lua, "True", true));
ASSERT_TRUE(checkBool(lua, "False", false));
ASSERT_TRUE(checkBool(lua, "TRUE", true));
ASSERT_TRUE(checkBool(lua, "FALSE", false));
ASSERT_TRUE(checkString(lua, "y"));
ASSERT_TRUE(checkString(lua, "n"));
ASSERT_TRUE(checkString(lua, "On"));
ASSERT_TRUE(checkString(lua, "Off"));
ASSERT_TRUE(checkString(lua, "YES"));
ASSERT_TRUE(checkString(lua, "NO"));
ASSERT_TRUE(checkString(lua, "TrUe"));
ASSERT_TRUE(checkString(lua, "FaLsE"));
ASSERT_TRUE(checkString(lua, "'true'", "true"));
}
TEST(LuaUtilYamlLoader, DepthLimit)
{
sol::state lua;
const std::string input = R"(
array1: &array1_alias
[
<: *array1_alias,
foo
]
)";
bool depthExceptionThrown = false;
try
{
YAML::Node root = YAML::Load(input);
sol::object result = LuaUtil::loadYaml(input, lua);
}
catch (const std::runtime_error& e)
{
ASSERT_EQ(std::string(e.what()), "Maximum layers depth exceeded, probably caused by a circular reference");
depthExceptionThrown = true;
}
ASSERT_TRUE(depthExceptionThrown);
}
TEST(LuaUtilYamlLoader, Collections)
{
sol::state lua;
sol::object map = LuaUtil::loadYaml("{ x: , y: 2, 4: 5 }", lua);
ASSERT_EQ(map.as<sol::table>()["x"], sol::nil);
ASSERT_EQ(map.as<sol::table>()["y"], 2);
ASSERT_EQ(map.as<sol::table>()[4], 5);
sol::object array = LuaUtil::loadYaml("[ 3, 4 ]", lua);
ASSERT_EQ(array.as<sol::table>()[1], 3);
sol::object emptyTable = LuaUtil::loadYaml("{}", lua);
ASSERT_TRUE(emptyTable.as<sol::table>().empty());
sol::object emptyArray = LuaUtil::loadYaml("[]", lua);
ASSERT_TRUE(emptyArray.as<sol::table>().empty());
ASSERT_THROW(LuaUtil::loadYaml("{ null: 1 }", lua), std::runtime_error);
ASSERT_THROW(LuaUtil::loadYaml("{ .nan: 1 }", lua), std::runtime_error);
const std::string scalarArrayInput = R"(
- First Scalar
- 1
- true)";
sol::object scalarArray = LuaUtil::loadYaml(scalarArrayInput, lua);
ASSERT_EQ(scalarArray.as<sol::table>()[1], std::string("First Scalar"));
ASSERT_EQ(scalarArray.as<sol::table>()[2], 1);
ASSERT_EQ(scalarArray.as<sol::table>()[3], true);
const std::string scalarMapWithCommentsInput = R"(
string: 'str' # String value
integer: 65 # Integer value
float: 0.278 # Float value
bool: false # Boolean value)";
sol::object scalarMapWithComments = LuaUtil::loadYaml(scalarMapWithCommentsInput, lua);
ASSERT_EQ(scalarMapWithComments.as<sol::table>()["string"], std::string("str"));
ASSERT_EQ(scalarMapWithComments.as<sol::table>()["integer"], 65);
ASSERT_EQ(scalarMapWithComments.as<sol::table>()["float"], 0.278);
ASSERT_EQ(scalarMapWithComments.as<sol::table>()["bool"], false);
const std::string mapOfArraysInput = R"(
x:
- 2
- 7
- true
y:
- aaa
- false
- 1)";
sol::object mapOfArrays = LuaUtil::loadYaml(mapOfArraysInput, lua);
ASSERT_EQ(mapOfArrays.as<sol::table>()["x"][3], true);
ASSERT_EQ(mapOfArrays.as<sol::table>()["y"][1], std::string("aaa"));
const std::string arrayOfMapsInput = R"(
-
name: Name1
hr: 65
avg: 0.278
-
name: Name2
hr: 63
avg: 0.288)";
sol::object arrayOfMaps = LuaUtil::loadYaml(arrayOfMapsInput, lua);
ASSERT_EQ(arrayOfMaps.as<sol::table>()[1]["avg"], 0.278);
ASSERT_EQ(arrayOfMaps.as<sol::table>()[2]["name"], std::string("Name2"));
const std::string arrayOfArraysInput = R"(
- [Name1, 65, 0.278]
- [Name2 , 63, 0.288])";
sol::object arrayOfArrays = LuaUtil::loadYaml(arrayOfArraysInput, lua);
ASSERT_EQ(arrayOfArrays.as<sol::table>()[1][2], 65);
ASSERT_EQ(arrayOfArrays.as<sol::table>()[2][1], std::string("Name2"));
const std::string mapOfMapsInput = R"(
Name1: {hr: 65, avg: 0.278}
Name2 : {
hr: 63,
avg: 0.288,
})";
sol::object mapOfMaps = LuaUtil::loadYaml(mapOfMapsInput, lua);
ASSERT_EQ(mapOfMaps.as<sol::table>()["Name1"]["hr"], 65);
ASSERT_EQ(mapOfMaps.as<sol::table>()["Name2"]["avg"], 0.288);
}
TEST(LuaUtilYamlLoader, Structures)
{
sol::state lua;
const std::string twoDocumentsInput
= "---\n"
" - First Scalar\n"
" - 2\n"
" - true\n"
"\n"
"---\n"
" - Second Scalar\n"
" - 3\n"
" - false";
sol::object twoDocuments = LuaUtil::loadYaml(twoDocumentsInput, lua);
ASSERT_EQ(twoDocuments.as<sol::table>()[1][1], std::string("First Scalar"));
ASSERT_EQ(twoDocuments.as<sol::table>()[2][3], false);
const std::string anchorInput = R"(---
x:
- Name1
# Following node labeled as "a"
- &a Value1
y:
- *a # Subsequent occurrence
- Name2)";
sol::object anchor = LuaUtil::loadYaml(anchorInput, lua);
ASSERT_EQ(anchor.as<sol::table>()["y"][1], std::string("Value1"));
const std::string compoundKeyInput = R"(
? - String1
- String2
: - 1
? [ String3,
String4 ]
: [ 2, 3, 4 ])";
ASSERT_THROW(LuaUtil::loadYaml(compoundKeyInput, lua), std::runtime_error);
const std::string compactNestedMappingInput = R"(
- item : Item1
quantity: 2
- item : Item2
quantity: 4
- item : Item3
quantity: 11)";
sol::object compactNestedMapping = LuaUtil::loadYaml(compactNestedMappingInput, lua);
ASSERT_EQ(compactNestedMapping.as<sol::table>()[2]["quantity"], 4);
}
TEST(LuaUtilYamlLoader, Scalars)
{
sol::state lua;
const std::string literalScalarInput = R"(--- |
a
b
c)";
ASSERT_TRUE(checkString(lua, literalScalarInput, "a\nb\nc"));
const std::string foldedScalarInput = R"(--- >
a
b
c)";
ASSERT_TRUE(checkString(lua, foldedScalarInput, "a b c"));
const std::string multiLinePlanarScalarsInput = R"(
plain:
This unquoted scalar
spans many lines.
quoted: "So does this
quoted scalar.\n")";
sol::object multiLinePlanarScalars = LuaUtil::loadYaml(multiLinePlanarScalarsInput, lua);
ASSERT_TRUE(
multiLinePlanarScalars.as<sol::table>()["plain"] == std::string("This unquoted scalar spans many lines."));
ASSERT_TRUE(multiLinePlanarScalars.as<sol::table>()["quoted"] == std::string("So does this quoted scalar.\n"));
}
}
| 13,191
|
C++
|
.cpp
| 296
| 34.638514
| 119
| 0.569113
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,214
|
test_storage.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_storage.cpp
|
#include <filesystem>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <components/lua/asyncpackage.hpp>
#include <components/lua/storage.hpp>
namespace
{
using namespace testing;
template <typename T>
T get(sol::state_view& lua, std::string luaCode)
{
return lua.safe_script("return " + luaCode).get<T>();
}
TEST(LuaUtilStorageTest, Subscribe)
{
// Note: LuaUtil::Callback can be used only if Lua is initialized via LuaUtil::LuaState
LuaUtil::LuaState luaState{ nullptr, nullptr };
luaState.protectedCall([](LuaUtil::LuaView& view) {
sol::state_view& lua = view.sol();
LuaUtil::LuaStorage::initLuaBindings(view);
LuaUtil::LuaStorage storage;
storage.setActive(true);
sol::table callbackHiddenData(lua, sol::create);
callbackHiddenData[LuaUtil::ScriptsContainer::sScriptIdKey] = LuaUtil::ScriptId{};
LuaUtil::getAsyncPackageInitializer(
lua.lua_state(), []() { return 0.0; }, []() { return 0.0; })(callbackHiddenData);
lua["async"] = LuaUtil::AsyncPackageId{ nullptr, 0, callbackHiddenData };
lua["mutable"] = storage.getMutableSection(lua, "test");
lua["ro"] = storage.getReadOnlySection(lua, "test");
lua.safe_script(R"(
callbackCalls = {}
ro:subscribe(async:callback(function(section, key)
table.insert(callbackCalls, section .. '_' .. (key or '*'))
end))
)");
lua.safe_script("mutable:set('x', 5)");
EXPECT_EQ(get<int>(lua, "mutable:get('x')"), 5);
EXPECT_EQ(get<int>(lua, "ro:get('x')"), 5);
EXPECT_THROW(lua.safe_script("ro:set('y', 3)"), std::exception);
lua.safe_script("t1 = mutable:asTable()");
lua.safe_script("t2 = ro:asTable()");
EXPECT_EQ(get<int>(lua, "t1.x"), 5);
EXPECT_EQ(get<int>(lua, "t2.x"), 5);
lua.safe_script("mutable:reset()");
EXPECT_TRUE(get<bool>(lua, "ro:get('x') == nil"));
lua.safe_script("mutable:reset({x=4, y=7})");
EXPECT_EQ(get<int>(lua, "ro:get('x')"), 4);
EXPECT_EQ(get<int>(lua, "ro:get('y')"), 7);
EXPECT_THAT(get<std::string>(lua, "table.concat(callbackCalls, ', ')"), "test_x, test_*, test_*");
});
}
TEST(LuaUtilStorageTest, Table)
{
LuaUtil::LuaState luaState{ nullptr, nullptr };
luaState.protectedCall([](LuaUtil::LuaView& view) {
LuaUtil::LuaStorage::initLuaBindings(view);
LuaUtil::LuaStorage storage;
auto& lua = view.sol();
storage.setActive(true);
lua["mutable"] = storage.getMutableSection(lua, "test");
lua["ro"] = storage.getReadOnlySection(lua, "test");
lua.safe_script("mutable:set('x', { y = 'abc', z = 7 })");
EXPECT_EQ(get<int>(lua, "mutable:get('x').z"), 7);
EXPECT_THROW(lua.safe_script("mutable:get('x').z = 3"), std::exception);
EXPECT_NO_THROW(lua.safe_script("mutable:getCopy('x').z = 3"));
EXPECT_EQ(get<int>(lua, "mutable:get('x').z"), 7);
EXPECT_EQ(get<int>(lua, "ro:get('x').z"), 7);
EXPECT_EQ(get<std::string>(lua, "ro:get('x').y"), "abc");
});
}
TEST(LuaUtilStorageTest, Saving)
{
LuaUtil::LuaState luaState{ nullptr, nullptr };
luaState.protectedCall([](LuaUtil::LuaView& view) {
LuaUtil::LuaStorage::initLuaBindings(view);
LuaUtil::LuaStorage storage;
auto& lua = view.sol();
storage.setActive(true);
lua["permanent"] = storage.getMutableSection(lua, "permanent");
lua["temporary"] = storage.getMutableSection(lua, "temporary");
lua.safe_script("temporary:removeOnExit()");
lua.safe_script("permanent:set('x', 1)");
lua.safe_script("temporary:set('y', 2)");
const auto tmpFile = std::filesystem::temp_directory_path() / "test_storage.bin";
storage.save(lua, tmpFile);
EXPECT_EQ(get<int>(lua, "permanent:get('x')"), 1);
EXPECT_EQ(get<int>(lua, "temporary:get('y')"), 2);
storage.clearTemporaryAndRemoveCallbacks();
lua["permanent"] = storage.getMutableSection(lua, "permanent");
lua["temporary"] = storage.getMutableSection(lua, "temporary");
EXPECT_EQ(get<int>(lua, "permanent:get('x')"), 1);
EXPECT_TRUE(get<bool>(lua, "temporary:get('y') == nil"));
lua.safe_script("permanent:set('x', 3)");
lua.safe_script("permanent:set('z', 4)");
LuaUtil::LuaStorage storage2;
storage2.setActive(true);
storage2.load(lua, tmpFile);
lua["permanent"] = storage2.getMutableSection(lua, "permanent");
lua["temporary"] = storage2.getMutableSection(lua, "temporary");
EXPECT_EQ(get<int>(lua, "permanent:get('x')"), 1);
EXPECT_TRUE(get<bool>(lua, "permanent:get('z') == nil"));
EXPECT_TRUE(get<bool>(lua, "temporary:get('y') == nil"));
});
}
}
| 5,263
|
C++
|
.cpp
| 105
| 39.07619
| 110
| 0.567089
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,215
|
test_ui_content.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_ui_content.cpp
|
#include <gtest/gtest.h>
#include <sol/sol.hpp>
#include <components/lua/luastate.hpp>
#include <components/lua_ui/content.hpp>
namespace
{
using namespace testing;
struct LuaUiContentTest : Test
{
LuaUtil::LuaState mLuaState{ nullptr, nullptr };
sol::protected_function mNew;
LuaUiContentTest()
{
mLuaState.addInternalLibSearchPath(
std::filesystem::path{ OPENMW_PROJECT_SOURCE_DIR } / "components" / "lua_ui");
mNew = LuaUi::loadContentConstructor(&mLuaState);
}
LuaUi::ContentView makeContent(sol::table source)
{
auto result = mNew.call(source);
if (result.get_type() != sol::type::table)
throw std::logic_error("Expected table");
return LuaUi::ContentView(result.get<sol::table>());
}
sol::table makeTable() { return sol::table(mLuaState.unsafeState(), sol::create); }
sol::table makeTable(std::string name)
{
auto result = makeTable();
result["name"] = name;
return result;
}
};
TEST_F(LuaUiContentTest, ProtectedMetatable)
{
sol::state_view sol = mLuaState.unsafeState();
sol["makeContent"] = mNew;
sol["M"] = makeContent(makeTable()).getMetatable();
std::string testScript = R"(
assert(not pcall(function() setmetatable(makeContent{}, {}) end), 'Metatable is not protected')
assert(getmetatable(makeContent{}) == false, 'Metatable is not protected')
)";
EXPECT_NO_THROW(sol.safe_script(testScript));
}
TEST_F(LuaUiContentTest, Create)
{
auto table = makeTable();
table.add(makeTable());
table.add(makeTable());
table.add(makeTable());
LuaUi::ContentView content = makeContent(table);
EXPECT_EQ(content.size(), 3);
}
TEST_F(LuaUiContentTest, Insert)
{
auto table = makeTable();
table.add(makeTable());
table.add(makeTable());
table.add(makeTable());
LuaUi::ContentView content = makeContent(table);
content.insert(2, makeTable("inserted"));
EXPECT_EQ(content.size(), 4);
auto inserted = content.at("inserted");
auto index = content.indexOf(inserted);
EXPECT_TRUE(index.has_value());
EXPECT_EQ(index.value(), 2);
}
TEST_F(LuaUiContentTest, MakeHole)
{
auto table = makeTable();
table.add(makeTable());
table.add(makeTable());
LuaUi::ContentView content = makeContent(table);
sol::table t = makeTable();
EXPECT_ANY_THROW(content.assign(3, t));
}
TEST_F(LuaUiContentTest, WrongType)
{
auto table = makeTable();
table.add(makeTable());
table.add("a");
table.add(makeTable());
EXPECT_ANY_THROW(makeContent(table));
}
TEST_F(LuaUiContentTest, NameAccess)
{
auto table = makeTable();
table.add(makeTable());
table.add(makeTable("a"));
LuaUi::ContentView content = makeContent(table);
EXPECT_NO_THROW(content.at("a"));
content.remove("a");
EXPECT_EQ(content.size(), 1);
content.assign(content.size(), makeTable("b"));
content.assign("b", makeTable());
EXPECT_ANY_THROW(content.at("b"));
EXPECT_EQ(content.size(), 2);
content.assign(content.size(), makeTable("c"));
content.assign(content.size(), makeTable("c"));
content.remove("c");
EXPECT_ANY_THROW(content.at("c"));
}
TEST_F(LuaUiContentTest, IndexOf)
{
auto table = makeTable();
table.add(makeTable());
table.add(makeTable());
table.add(makeTable());
LuaUi::ContentView content = makeContent(table);
auto child = makeTable();
content.assign(2, child);
EXPECT_EQ(content.indexOf(child).value(), 2);
EXPECT_TRUE(!content.indexOf(makeTable()).has_value());
}
TEST_F(LuaUiContentTest, BoundsChecks)
{
auto table = makeTable();
LuaUi::ContentView content = makeContent(table);
EXPECT_ANY_THROW(content.at(0));
EXPECT_EQ(content.size(), 0);
content.assign(content.size(), makeTable());
EXPECT_EQ(content.size(), 1);
content.assign(content.size(), makeTable());
EXPECT_EQ(content.size(), 2);
content.assign(content.size(), makeTable());
EXPECT_EQ(content.size(), 3);
EXPECT_ANY_THROW(content.at(3));
EXPECT_ANY_THROW(content.remove(3));
content.remove(2);
EXPECT_EQ(content.size(), 2);
EXPECT_ANY_THROW(content.at(2));
}
}
| 4,727
|
C++
|
.cpp
| 132
| 27.55303
| 107
| 0.597031
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,216
|
test_scriptscontainer.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_scriptscontainer.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <components/esm/luascripts.hpp>
#include <components/lua/asyncpackage.hpp>
#include <components/lua/luastate.hpp>
#include <components/lua/scriptscontainer.hpp>
#include <components/lua/scripttracker.hpp>
#include <components/testing/util.hpp>
namespace
{
using namespace testing;
using namespace TestingOpenMW;
constexpr VFS::Path::NormalizedView invalidPath("invalid.lua");
VFSTestFile invalidScript("not a script");
constexpr VFS::Path::NormalizedView incorrectPath("incorrect.lua");
VFSTestFile incorrectScript(
"return { incorrectSection = {}, engineHandlers = { incorrectHandler = function() end } }");
constexpr VFS::Path::NormalizedView emptyPath("empty.lua");
VFSTestFile emptyScript("");
constexpr VFS::Path::NormalizedView test1Path("test1.lua");
constexpr VFS::Path::NormalizedView test2Path("test2.lua");
VFSTestFile testScript(R"X(
return {
engineHandlers = {
onUpdate = function(dt) print(' update ' .. tostring(dt)) end,
onLoad = function() print('load') end,
},
eventHandlers = {
Event1 = function(eventData) print(' event1 ' .. tostring(eventData.x)) end,
Event2 = function(eventData) print(' event2 ' .. tostring(eventData.x)) end,
Print = function() print('print') end
}
}
)X");
constexpr VFS::Path::NormalizedView stopEventPath("stopevent.lua");
VFSTestFile stopEventScript(R"X(
return {
eventHandlers = {
Event1 = function(eventData)
print(' event1 ' .. tostring(eventData.x))
return eventData.x >= 1
end
}
}
)X");
constexpr VFS::Path::NormalizedView loadSave1Path("loadsave1.lua");
constexpr VFS::Path::NormalizedView loadSave2Path("loadsave2.lua");
VFSTestFile loadSaveScript(R"X(
x = 0
y = 0
return {
engineHandlers = {
onSave = function(state)
return {x = x, y = y}
end,
onLoad = function(state)
x, y = state.x, state.y
end
},
eventHandlers = {
Set = function(eventData)
eventData.n = eventData.n - 1
if eventData.n == 0 then
x, y = eventData.x, eventData.y
end
end,
Print = function()
print(x, y)
end
}
}
)X");
constexpr VFS::Path::NormalizedView testInterfacePath("testinterface.lua");
VFSTestFile interfaceScript(R"X(
return {
interfaceName = "TestInterface",
interface = {
fn = function(x) print('FN', x) end,
value = 3.5
},
}
)X");
constexpr VFS::Path::NormalizedView overrideInterfacePath("overrideinterface.lua");
VFSTestFile overrideInterfaceScript(R"X(
local old = nil
local interface = {
fn = function(x)
print('NEW FN', x)
old.fn(x)
end,
value,
}
return {
interfaceName = "TestInterface",
interface = interface,
engineHandlers = {
onInit = function() print('init') end,
onLoad = function() print('load') end,
onInterfaceOverride = function(oldInterface)
print('override')
old = oldInterface
interface.value = oldInterface.value + 1
end
},
}
)X");
constexpr VFS::Path::NormalizedView useInterfacePath("useinterface.lua");
VFSTestFile useInterfaceScript(R"X(
local interfaces = require('openmw.interfaces')
return {
engineHandlers = {
onUpdate = function()
interfaces.TestInterface.fn(interfaces.TestInterface.value)
end,
},
}
)X");
constexpr VFS::Path::NormalizedView unloadPath("unload.lua");
VFSTestFile unloadScript(R"X(
x = 0
y = 0
z = 0
return {
engineHandlers = {
onSave = function(state)
print('saving', x, y, z)
return {x = x, y = y}
end,
onLoad = function(state)
x, y = state.x, state.y
print('loaded', x, y, z)
end
},
eventHandlers = {
Set = function(eventData)
x, y, z = eventData.x, eventData.y, eventData.z
end
}
}
)X");
constexpr VFS::Path::NormalizedView customDataPath("customdata.lua");
VFSTestFile customDataScript(R"X(
data = nil
return {
engineHandlers = {
onSave = function()
return data
end,
onLoad = function(state)
data = state
end,
onInit = function(state)
data = state
end
},
eventHandlers = {
WakeUp = function()
end
}
}
)X");
struct LuaScriptsContainerTest : Test
{
std::unique_ptr<VFS::Manager> mVFS = createTestVFS({
{ invalidPath, &invalidScript },
{ incorrectPath, &incorrectScript },
{ emptyPath, &emptyScript },
{ test1Path, &testScript },
{ test2Path, &testScript },
{ stopEventPath, &stopEventScript },
{ loadSave1Path, &loadSaveScript },
{ loadSave2Path, &loadSaveScript },
{ testInterfacePath, &interfaceScript },
{ overrideInterfacePath, &overrideInterfaceScript },
{ useInterfacePath, &useInterfaceScript },
{ unloadPath, &unloadScript },
{ customDataPath, &customDataScript },
});
LuaUtil::ScriptsConfiguration mCfg;
LuaUtil::LuaState mLua{ mVFS.get(), &mCfg };
LuaScriptsContainerTest()
{
ESM::LuaScriptsCfg cfg;
LuaUtil::parseOMWScripts(cfg, R"X(
CUSTOM: invalid.lua
CUSTOM: incorrect.lua
CUSTOM: empty.lua
CUSTOM: test1.lua
CUSTOM: stopEvent.lua
CUSTOM: test2.lua
NPC: loadSave1.lua
CUSTOM, NPC: loadSave2.lua
CUSTOM, PLAYER: testInterface.lua
CUSTOM, PLAYER: overrideInterface.lua
CUSTOM, PLAYER: useInterface.lua
CUSTOM: unload.lua
CUSTOM: customdata.lua
)X");
mCfg.init(std::move(cfg));
}
int getId(VFS::Path::NormalizedView path) const
{
const std::optional<int> id = mCfg.findId(path);
if (!id.has_value())
throw std::invalid_argument("Script id is not found: " + std::string(path.value()));
return *id;
}
};
TEST_F(LuaScriptsContainerTest, addCustomScriptShouldNotStartInvalidScript)
{
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
testing::internal::CaptureStdout();
EXPECT_FALSE(scripts.addCustomScript(getId(invalidPath)));
std::string output = testing::internal::GetCapturedStdout();
EXPECT_THAT(output, HasSubstr("Can't start Test[invalid.lua]"));
}
TEST_F(LuaScriptsContainerTest, addCustomScriptShouldNotSuportScriptsWithInvalidHandlerAndSection)
{
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
testing::internal::CaptureStdout();
EXPECT_TRUE(scripts.addCustomScript(getId(incorrectPath)));
std::string output = testing::internal::GetCapturedStdout();
EXPECT_THAT(output, HasSubstr("Not supported handler 'incorrectHandler' in Test[incorrect.lua]"));
EXPECT_THAT(output, HasSubstr("Not supported section 'incorrectSection' in Test[incorrect.lua]"));
}
TEST_F(LuaScriptsContainerTest, addCustomScriptShouldReturnFalseForDuplicates)
{
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
EXPECT_TRUE(scripts.addCustomScript(getId(emptyPath)));
EXPECT_FALSE(scripts.addCustomScript(getId(emptyPath)));
}
TEST_F(LuaScriptsContainerTest, CallHandler)
{
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
testing::internal::CaptureStdout();
EXPECT_TRUE(scripts.addCustomScript(getId(test1Path)));
EXPECT_TRUE(scripts.addCustomScript(getId(stopEventPath)));
EXPECT_TRUE(scripts.addCustomScript(getId(test2Path)));
scripts.update(1.5f);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test1.lua]:\t update 1.5\n"
"Test[test2.lua]:\t update 1.5\n");
}
TEST_F(LuaScriptsContainerTest, CallEvent)
{
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
EXPECT_TRUE(scripts.addCustomScript(getId(test1Path)));
EXPECT_TRUE(scripts.addCustomScript(getId(stopEventPath)));
EXPECT_TRUE(scripts.addCustomScript(getId(test2Path)));
sol::state_view sol = mLua.unsafeState();
std::string X0 = LuaUtil::serialize(sol.create_table_with("x", 0.5));
std::string X1 = LuaUtil::serialize(sol.create_table_with("x", 1.5));
{
testing::internal::CaptureStdout();
scripts.receiveEvent("SomeEvent", X1);
EXPECT_EQ(internal::GetCapturedStdout(), "");
}
{
testing::internal::CaptureStdout();
scripts.receiveEvent("Event1", X1);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test2.lua]:\t event1 1.5\n"
"Test[stopevent.lua]:\t event1 1.5\n"
"Test[test1.lua]:\t event1 1.5\n");
}
{
testing::internal::CaptureStdout();
scripts.receiveEvent("Event2", X1);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test2.lua]:\t event2 1.5\n"
"Test[test1.lua]:\t event2 1.5\n");
}
{
testing::internal::CaptureStdout();
scripts.receiveEvent("Event1", X0);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test2.lua]:\t event1 0.5\n"
"Test[stopevent.lua]:\t event1 0.5\n");
}
{
testing::internal::CaptureStdout();
scripts.receiveEvent("Event2", X0);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test2.lua]:\t event2 0.5\n"
"Test[test1.lua]:\t event2 0.5\n");
}
}
TEST_F(LuaScriptsContainerTest, RemoveScript)
{
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
EXPECT_TRUE(scripts.addCustomScript(getId(test1Path)));
EXPECT_TRUE(scripts.addCustomScript(getId(stopEventPath)));
EXPECT_TRUE(scripts.addCustomScript(getId(test2Path)));
sol::state_view sol = mLua.unsafeState();
std::string X = LuaUtil::serialize(sol.create_table_with("x", 0.5));
{
testing::internal::CaptureStdout();
scripts.update(1.5f);
scripts.receiveEvent("Event1", X);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test1.lua]:\t update 1.5\n"
"Test[test2.lua]:\t update 1.5\n"
"Test[test2.lua]:\t event1 0.5\n"
"Test[stopevent.lua]:\t event1 0.5\n");
}
{
testing::internal::CaptureStdout();
const int stopEventScriptId = getId(stopEventPath);
EXPECT_TRUE(scripts.hasScript(stopEventScriptId));
scripts.removeScript(stopEventScriptId);
EXPECT_FALSE(scripts.hasScript(stopEventScriptId));
scripts.update(1.5f);
scripts.receiveEvent("Event1", X);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test1.lua]:\t update 1.5\n"
"Test[test2.lua]:\t update 1.5\n"
"Test[test2.lua]:\t event1 0.5\n"
"Test[test1.lua]:\t event1 0.5\n");
}
{
testing::internal::CaptureStdout();
scripts.removeScript(getId(test1Path));
scripts.update(1.5f);
scripts.receiveEvent("Event1", X);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test2.lua]:\t update 1.5\n"
"Test[test2.lua]:\t event1 0.5\n");
}
}
TEST_F(LuaScriptsContainerTest, AutoStart)
{
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
scripts.setAutoStartConf(mCfg.getPlayerConf());
testing::internal::CaptureStdout();
scripts.addAutoStartedScripts();
scripts.update(1.5f);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[overrideinterface.lua]:\toverride\n"
"Test[overrideinterface.lua]:\tinit\n"
"Test[overrideinterface.lua]:\tNEW FN\t4.5\n"
"Test[testinterface.lua]:\tFN\t4.5\n");
}
TEST_F(LuaScriptsContainerTest, Interface)
{
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
scripts.setAutoStartConf(mCfg.getLocalConf(ESM::REC_CREA, ESM::RefId(), ESM::RefNum()));
const int addIfaceId = getId(testInterfacePath);
const int overrideIfaceId = getId(overrideInterfacePath);
const int useIfaceId = getId(useInterfacePath);
testing::internal::CaptureStdout();
scripts.addAutoStartedScripts();
scripts.update(1.5f);
EXPECT_EQ(internal::GetCapturedStdout(), "");
testing::internal::CaptureStdout();
EXPECT_TRUE(scripts.addCustomScript(addIfaceId));
EXPECT_TRUE(scripts.addCustomScript(overrideIfaceId));
EXPECT_TRUE(scripts.addCustomScript(useIfaceId));
scripts.update(1.5f);
scripts.removeScript(overrideIfaceId);
scripts.update(1.5f);
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[overrideinterface.lua]:\toverride\n"
"Test[overrideinterface.lua]:\tinit\n"
"Test[overrideinterface.lua]:\tNEW FN\t4.5\n"
"Test[testinterface.lua]:\tFN\t4.5\n"
"Test[testinterface.lua]:\tFN\t3.5\n");
}
TEST_F(LuaScriptsContainerTest, LoadSave)
{
LuaUtil::ScriptsContainer scripts1(&mLua, "Test");
LuaUtil::ScriptsContainer scripts2(&mLua, "Test");
LuaUtil::ScriptsContainer scripts3(&mLua, "Test");
scripts1.setAutoStartConf(mCfg.getLocalConf(ESM::REC_NPC_, ESM::RefId(), ESM::RefNum()));
scripts2.setAutoStartConf(mCfg.getLocalConf(ESM::REC_NPC_, ESM::RefId(), ESM::RefNum()));
scripts3.setAutoStartConf(mCfg.getPlayerConf());
scripts1.addAutoStartedScripts();
EXPECT_TRUE(scripts1.addCustomScript(getId(test1Path)));
sol::state_view sol = mLua.unsafeState();
scripts1.receiveEvent("Set", LuaUtil::serialize(sol.create_table_with("n", 1, "x", 0.5, "y", 3.5)));
scripts1.receiveEvent("Set", LuaUtil::serialize(sol.create_table_with("n", 2, "x", 2.5, "y", 1.5)));
ESM::LuaScripts data;
scripts1.save(data);
{
testing::internal::CaptureStdout();
scripts2.load(data);
scripts2.receiveEvent("Print", "");
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[test1.lua]:\tload\n"
"Test[loadsave2.lua]:\t0.5\t3.5\n"
"Test[loadsave1.lua]:\t2.5\t1.5\n"
"Test[test1.lua]:\tprint\n");
EXPECT_FALSE(scripts2.hasScript(getId(testInterfacePath)));
}
{
testing::internal::CaptureStdout();
scripts3.load(data);
scripts3.receiveEvent("Print", "");
EXPECT_EQ(internal::GetCapturedStdout(),
"Ignoring Test[loadsave1.lua]; this script is not allowed here\n"
"Test[test1.lua]:\tload\n"
"Test[overrideinterface.lua]:\toverride\n"
"Test[overrideinterface.lua]:\tinit\n"
"Test[loadsave2.lua]:\t0.5\t3.5\n"
"Test[test1.lua]:\tprint\n");
EXPECT_TRUE(scripts3.hasScript(getId(testInterfacePath)));
}
}
TEST_F(LuaScriptsContainerTest, Timers)
{
using TimerType = LuaUtil::ScriptsContainer::TimerType;
LuaUtil::ScriptsContainer scripts(&mLua, "Test");
const int test1Id = getId(test1Path);
const int test2Id = getId(test2Path);
testing::internal::CaptureStdout();
EXPECT_TRUE(scripts.addCustomScript(test1Id));
EXPECT_TRUE(scripts.addCustomScript(test2Id));
EXPECT_EQ(internal::GetCapturedStdout(), "");
int counter1 = 0, counter2 = 0, counter3 = 0, counter4 = 0;
sol::function fn1 = sol::make_object(mLua.unsafeState(), [&]() { counter1++; });
sol::function fn2 = sol::make_object(mLua.unsafeState(), [&]() { counter2++; });
sol::function fn3 = sol::make_object(mLua.unsafeState(), [&](int d) { counter3 += d; });
sol::function fn4 = sol::make_object(mLua.unsafeState(), [&](int d) { counter4 += d; });
scripts.registerTimerCallback(test1Id, "A", fn3);
scripts.registerTimerCallback(test1Id, "B", fn4);
scripts.registerTimerCallback(test2Id, "B", fn3);
scripts.registerTimerCallback(test2Id, "A", fn4);
scripts.processTimers(1, 2);
scripts.setupSerializableTimer(
TimerType::SIMULATION_TIME, 10, test1Id, "B", sol::make_object(mLua.unsafeState(), 3));
scripts.setupSerializableTimer(TimerType::GAME_TIME, 10, test2Id, "B", sol::make_object(mLua.unsafeState(), 4));
scripts.setupSerializableTimer(
TimerType::SIMULATION_TIME, 5, test1Id, "A", sol::make_object(mLua.unsafeState(), 1));
scripts.setupSerializableTimer(TimerType::GAME_TIME, 5, test2Id, "A", sol::make_object(mLua.unsafeState(), 2));
scripts.setupSerializableTimer(
TimerType::SIMULATION_TIME, 15, test1Id, "A", sol::make_object(mLua.unsafeState(), 10));
scripts.setupSerializableTimer(
TimerType::SIMULATION_TIME, 15, test1Id, "B", sol::make_object(mLua.unsafeState(), 20));
scripts.setupUnsavableTimer(TimerType::SIMULATION_TIME, 10, test2Id, fn2);
scripts.setupUnsavableTimer(TimerType::GAME_TIME, 10, test1Id, fn2);
scripts.setupUnsavableTimer(TimerType::SIMULATION_TIME, 5, test2Id, fn1);
scripts.setupUnsavableTimer(TimerType::GAME_TIME, 5, test1Id, fn1);
scripts.setupUnsavableTimer(TimerType::SIMULATION_TIME, 15, test2Id, fn1);
EXPECT_EQ(counter1, 0);
EXPECT_EQ(counter3, 0);
scripts.processTimers(6, 4);
EXPECT_EQ(counter1, 1);
EXPECT_EQ(counter3, 1);
EXPECT_EQ(counter4, 0);
scripts.processTimers(6, 8);
EXPECT_EQ(counter1, 2);
EXPECT_EQ(counter2, 0);
EXPECT_EQ(counter3, 1);
EXPECT_EQ(counter4, 2);
scripts.processTimers(11, 12);
EXPECT_EQ(counter1, 2);
EXPECT_EQ(counter2, 2);
EXPECT_EQ(counter3, 5);
EXPECT_EQ(counter4, 5);
testing::internal::CaptureStdout();
ESM::LuaScripts data;
scripts.save(data);
scripts.load(data);
scripts.registerTimerCallback(test1Id, "B", fn4);
EXPECT_EQ(internal::GetCapturedStdout(), "Test[test1.lua]:\tload\nTest[test2.lua]:\tload\n");
testing::internal::CaptureStdout();
scripts.processTimers(20, 20);
EXPECT_EQ(internal::GetCapturedStdout(), "Test[test1.lua] callTimer failed: Callback 'A' doesn't exist\n");
EXPECT_EQ(counter1, 2);
EXPECT_EQ(counter2, 2);
EXPECT_EQ(counter3, 5);
EXPECT_EQ(counter4, 25);
}
TEST_F(LuaScriptsContainerTest, CallbackWrapper)
{
sol::state_view view = mLua.unsafeState();
LuaUtil::Callback callback{ view["print"], sol::table(view, sol::create) };
callback.mHiddenData[LuaUtil::ScriptsContainer::sScriptDebugNameKey] = "some_script.lua";
callback.mHiddenData[LuaUtil::ScriptsContainer::sScriptIdKey] = LuaUtil::ScriptId{ nullptr, 0 };
testing::internal::CaptureStdout();
callback.call(1.5);
EXPECT_EQ(internal::GetCapturedStdout(), "1.5\n");
testing::internal::CaptureStdout();
callback.call(1.5, 2.5);
EXPECT_EQ(internal::GetCapturedStdout(), "1.5\t2.5\n");
const Debug::Level level = std::exchange(Log::sMinDebugLevel, Debug::All);
testing::internal::CaptureStdout();
callback.mHiddenData[LuaUtil::ScriptsContainer::sScriptIdKey] = sol::nil;
callback.call(1.5, 2.5);
EXPECT_EQ(internal::GetCapturedStdout(), "Ignored callback to the removed script some_script.lua\n");
Log::sMinDebugLevel = level;
}
TEST_F(LuaScriptsContainerTest, Unload)
{
LuaUtil::ScriptTracker tracker;
LuaUtil::ScriptsContainer scripts1(&mLua, "Test", &tracker, false);
EXPECT_TRUE(scripts1.addCustomScript(*mCfg.findId(unloadPath)));
EXPECT_EQ(tracker.size(), 1);
mLua.protectedCall([&](LuaUtil::LuaView& lua) {
scripts1.receiveEvent("Set", LuaUtil::serialize(lua.sol().create_table_with("x", 3, "y", 2, "z", 1)));
testing::internal::CaptureStdout();
for (int i = 0; i < 600; ++i)
tracker.unloadInactiveScripts(lua);
EXPECT_EQ(tracker.size(), 0);
scripts1.receiveEvent("Set", LuaUtil::serialize(lua.sol().create_table_with("x", 10, "y", 20, "z", 30)));
EXPECT_EQ(internal::GetCapturedStdout(),
"Test[unload.lua]:\tsaving\t3\t2\t1\n"
"Test[unload.lua]:\tloaded\t3\t2\t0\n");
});
EXPECT_EQ(tracker.size(), 1);
ESM::LuaScripts data;
scripts1.save(data);
EXPECT_EQ(tracker.size(), 1);
mLua.protectedCall([&](LuaUtil::LuaView& lua) {
for (int i = 0; i < 600; ++i)
tracker.unloadInactiveScripts(lua);
});
EXPECT_EQ(tracker.size(), 0);
scripts1.load(data);
EXPECT_EQ(tracker.size(), 0);
}
TEST_F(LuaScriptsContainerTest, LoadOrderChange)
{
LuaUtil::ScriptTracker tracker;
LuaUtil::ScriptsContainer scripts1(&mLua, "Test", &tracker, false);
LuaUtil::BasicSerializer serializer1;
LuaUtil::BasicSerializer serializer2([](int contentFileIndex) -> int {
if (contentFileIndex == 12)
return 34;
else if (contentFileIndex == 37)
return 12;
return contentFileIndex;
});
scripts1.setSerializer(&serializer1);
scripts1.setSavedDataDeserializer(&serializer2);
mLua.protectedCall([&](LuaUtil::LuaView& lua) {
sol::object id1 = sol::make_object_userdata(lua.sol(), ESM::RefNum{ 42, 12 });
sol::object id2 = sol::make_object_userdata(lua.sol(), ESM::RefNum{ 13, 37 });
sol::table table = lua.newTable();
table[id1] = id2;
LuaUtil::BinaryData serialized = LuaUtil::serialize(table, &serializer1);
EXPECT_TRUE(scripts1.addCustomScript(*mCfg.findId(customDataPath), serialized));
EXPECT_EQ(tracker.size(), 1);
for (int i = 0; i < 600; ++i)
tracker.unloadInactiveScripts(lua);
EXPECT_EQ(tracker.size(), 0);
scripts1.receiveEvent("WakeUp", {});
EXPECT_EQ(tracker.size(), 1);
});
ESM::LuaScripts data1;
ESM::LuaScripts data2;
scripts1.save(data1);
scripts1.load(data1);
scripts1.save(data2);
EXPECT_NE(data1.mScripts[0].mData, data2.mScripts[0].mData);
mLua.protectedCall([&](LuaUtil::LuaView& lua) {
sol::object deserialized = LuaUtil::deserialize(lua.sol(), data2.mScripts[0].mData, &serializer1);
EXPECT_TRUE(deserialized.is<sol::table>());
sol::table table = deserialized;
for (const auto& [key, value] : table)
{
EXPECT_TRUE(key.is<ESM::RefNum>());
EXPECT_TRUE(value.is<ESM::RefNum>());
EXPECT_EQ(key.as<ESM::RefNum>(), (ESM::RefNum{ 42, 34 }));
EXPECT_EQ(value.as<ESM::RefNum>(), (ESM::RefNum{ 13, 12 }));
return;
}
EXPECT_FALSE(true);
});
}
}
| 23,709
|
C++
|
.cpp
| 570
| 32.492982
| 120
| 0.616429
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,217
|
test_utilpackage.cpp
|
OpenMW_openmw/apps/components_tests/lua/test_utilpackage.cpp
|
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <components/lua/luastate.hpp>
#include <components/lua/utilpackage.hpp>
#include <components/testing/expecterror.hpp>
namespace
{
using namespace testing;
template <typename T>
T get(sol::state& lua, const std::string& luaCode)
{
return lua.safe_script("return " + luaCode).get<T>();
}
std::string getAsString(sol::state& lua, std::string luaCode)
{
return LuaUtil::toString(lua.safe_script("return " + luaCode));
}
TEST(LuaUtilPackageTest, Vector2)
{
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::math, sol::lib::string);
lua["util"] = LuaUtil::initUtilPackage(lua);
lua.safe_script("v = util.vector2(3, 4)");
EXPECT_FLOAT_EQ(get<float>(lua, "v.x"), 3);
EXPECT_FLOAT_EQ(get<float>(lua, "v.y"), 4);
EXPECT_EQ(get<std::string>(lua, "tostring(v)"), "(3, 4)");
EXPECT_FLOAT_EQ(get<float>(lua, "v:length()"), 5);
EXPECT_FLOAT_EQ(get<float>(lua, "v:length2()"), 25);
EXPECT_FALSE(get<bool>(lua, "util.vector2(1, 2) == util.vector2(1, 3)"));
EXPECT_TRUE(get<bool>(lua, "util.vector2(1, 2) + util.vector2(2, 5) == util.vector2(3, 7)"));
EXPECT_TRUE(get<bool>(lua, "util.vector2(1, 2) - util.vector2(2, 5) == -util.vector2(1, 3)"));
EXPECT_TRUE(get<bool>(lua, "util.vector2(1, 2) == util.vector2(2, 4) / 2"));
EXPECT_TRUE(get<bool>(lua, "util.vector2(1, 2) * 2 == util.vector2(2, 4)"));
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector2(3, 2) * v"), 17);
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector2(3, 2):dot(v)"), 17);
EXPECT_ERROR(lua.safe_script("v2, len = v.normalize()"),
"value is not a valid userdata"); // checks that it doesn't segfault
lua.safe_script("v2, len = v:normalize()");
EXPECT_FLOAT_EQ(get<float>(lua, "len"), 5);
EXPECT_TRUE(get<bool>(lua, "v2 == util.vector2(3/5, 4/5)"));
lua.safe_script("_, len = util.vector2(0, 0):normalize()");
EXPECT_FLOAT_EQ(get<float>(lua, "len"), 0);
lua.safe_script("ediv0 = util.vector2(1, 0):ediv(util.vector2(0, 0))");
EXPECT_TRUE(get<bool>(lua, "ediv0.x == math.huge and ediv0.y ~= ediv0.y"));
EXPECT_TRUE(get<bool>(lua, "util.vector2(1, 2):emul(util.vector2(3, 4)) == util.vector2(3, 8)"));
EXPECT_TRUE(get<bool>(lua, "util.vector2(4, 6):ediv(util.vector2(2, 3)) == util.vector2(2, 2)"));
lua.safe_script("swizzle = util.vector2(1, 2)");
EXPECT_TRUE(get<bool>(lua, "swizzle.xx == util.vector2(1, 1) and swizzle.yy == util.vector2(2, 2)"));
EXPECT_TRUE(get<bool>(lua, "swizzle.y0 == util.vector2(2, 0) and swizzle.x1 == util.vector2(1, 1)"));
EXPECT_TRUE(get<bool>(lua, "swizzle['01'] == util.vector2(0, 1) and swizzle['0y'] == util.vector2(0, 2)"));
}
TEST(LuaUtilPackageTest, Vector3)
{
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::math, sol::lib::string);
lua["util"] = LuaUtil::initUtilPackage(lua);
lua.safe_script("v = util.vector3(5, 12, 13)");
EXPECT_FLOAT_EQ(get<float>(lua, "v.x"), 5);
EXPECT_FLOAT_EQ(get<float>(lua, "v.y"), 12);
EXPECT_FLOAT_EQ(get<float>(lua, "v.z"), 13);
EXPECT_EQ(get<std::string>(lua, "tostring(v)"), "(5, 12, 13)");
EXPECT_EQ(getAsString(lua, "v"), "(5, 12, 13)");
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector3(4, 0, 3):length()"), 5);
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector3(4, 0, 3):length2()"), 25);
EXPECT_FALSE(get<bool>(lua, "util.vector3(1, 2, 3) == util.vector3(1, 3, 2)"));
EXPECT_TRUE(get<bool>(lua, "util.vector3(1, 2, 3) + util.vector3(2, 5, 1) == util.vector3(3, 7, 4)"));
EXPECT_TRUE(get<bool>(lua, "util.vector3(1, 2, 3) - util.vector3(2, 5, 1) == -util.vector3(1, 3, -2)"));
EXPECT_TRUE(get<bool>(lua, "util.vector3(1, 2, 3) == util.vector3(2, 4, 6) / 2"));
EXPECT_TRUE(get<bool>(lua, "util.vector3(1, 2, 3) * 2 == util.vector3(2, 4, 6)"));
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector3(3, 2, 1) * v"), 5 * 3 + 12 * 2 + 13 * 1);
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector3(3, 2, 1):dot(v)"), 5 * 3 + 12 * 2 + 13 * 1);
EXPECT_TRUE(get<bool>(lua, "util.vector3(1, 0, 0) ^ util.vector3(0, 1, 0) == util.vector3(0, 0, 1)"));
EXPECT_ERROR(lua.safe_script("v2, len = util.vector3(3, 4, 0).normalize()"), "value is not a valid userdata");
lua.safe_script("v2, len = util.vector3(3, 4, 0):normalize()");
EXPECT_FLOAT_EQ(get<float>(lua, "len"), 5);
EXPECT_TRUE(get<bool>(lua, "v2 == util.vector3(3/5, 4/5, 0)"));
lua.safe_script("_, len = util.vector3(0, 0, 0):normalize()");
EXPECT_FLOAT_EQ(get<float>(lua, "len"), 0);
lua.safe_script("ediv0 = util.vector3(1, 1, 1):ediv(util.vector3(0, 0, 0))");
EXPECT_TRUE(get<bool>(lua, "ediv0.z == math.huge"));
EXPECT_TRUE(get<bool>(lua, "util.vector3(1, 2, 3):emul(util.vector3(3, 4, 5)) == util.vector3(3, 8, 15)"));
EXPECT_TRUE(get<bool>(lua, "util.vector3(4, 6, 8):ediv(util.vector3(2, 3, 4)) == util.vector3(2, 2, 2)"));
lua.safe_script("swizzle = util.vector3(1, 2, 3)");
EXPECT_TRUE(get<bool>(lua, "swizzle.xxx == util.vector3(1, 1, 1)"));
EXPECT_TRUE(get<bool>(lua, "swizzle.xyz == swizzle.zyx.zyx"));
EXPECT_TRUE(get<bool>(lua, "swizzle.xy0 == util.vector3(1, 2, 0) and swizzle.x11 == util.vector3(1, 1, 1)"));
EXPECT_TRUE(
get<bool>(lua, "swizzle['001'] == util.vector3(0, 0, 1) and swizzle['0yx'] == util.vector3(0, 2, 1)"));
}
TEST(LuaUtilPackageTest, Vector4)
{
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::math, sol::lib::string);
lua["util"] = LuaUtil::initUtilPackage(lua);
lua.safe_script("v = util.vector4(5, 12, 13, 15)");
EXPECT_FLOAT_EQ(get<float>(lua, "v.x"), 5);
EXPECT_FLOAT_EQ(get<float>(lua, "v.y"), 12);
EXPECT_FLOAT_EQ(get<float>(lua, "v.z"), 13);
EXPECT_FLOAT_EQ(get<float>(lua, "v.w"), 15);
EXPECT_EQ(get<std::string>(lua, "tostring(v)"), "(5, 12, 13, 15)");
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector4(4, 0, 0, 3):length()"), 5);
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector4(4, 0, 0, 3):length2()"), 25);
EXPECT_FALSE(get<bool>(lua, "util.vector4(1, 2, 3, 4) == util.vector4(1, 3, 2, 4)"));
EXPECT_TRUE(get<bool>(lua, "util.vector4(1, 2, 3, 4) + util.vector4(2, 5, 1, 2) == util.vector4(3, 7, 4, 6)"));
EXPECT_TRUE(
get<bool>(lua, "util.vector4(1, 2, 3, 4) - util.vector4(2, 5, 1, 7) == -util.vector4(1, 3, -2, 3)"));
EXPECT_TRUE(get<bool>(lua, "util.vector4(1, 2, 3, 4) == util.vector4(2, 4, 6, 8) / 2"));
EXPECT_TRUE(get<bool>(lua, "util.vector4(1, 2, 3, 4) * 2 == util.vector4(2, 4, 6, 8)"));
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector4(3, 2, 1, 4) * v"), 5 * 3 + 12 * 2 + 13 * 1 + 15 * 4);
EXPECT_FLOAT_EQ(get<float>(lua, "util.vector4(3, 2, 1, 4):dot(v)"), 5 * 3 + 12 * 2 + 13 * 1 + 15 * 4);
lua.safe_script("v2, len = util.vector4(3, 0, 0, 4):normalize()");
EXPECT_FLOAT_EQ(get<float>(lua, "len"), 5);
EXPECT_TRUE(get<bool>(lua, "v2 == util.vector4(3/5, 0, 0, 4/5)"));
lua.safe_script("_, len = util.vector4(0, 0, 0, 0):normalize()");
EXPECT_FLOAT_EQ(get<float>(lua, "len"), 0);
lua.safe_script("ediv0 = util.vector4(1, 1, 1, -1):ediv(util.vector4(0, 0, 0, 0))");
EXPECT_TRUE(get<bool>(lua, "ediv0.w == -math.huge"));
EXPECT_TRUE(
get<bool>(lua, "util.vector4(1, 2, 3, 4):emul(util.vector4(3, 4, 5, 6)) == util.vector4(3, 8, 15, 24)"));
EXPECT_TRUE(
get<bool>(lua, "util.vector4(4, 6, 8, 9):ediv(util.vector4(2, 3, 4, 3)) == util.vector4(2, 2, 2, 3)"));
lua.safe_script("swizzle = util.vector4(1, 2, 3, 4)");
EXPECT_TRUE(get<bool>(lua, "swizzle.wwww == util.vector4(4, 4, 4, 4)"));
EXPECT_TRUE(get<bool>(lua, "swizzle.xyzw == util.vector4(1, 2, 3, 4)"));
EXPECT_TRUE(get<bool>(lua, "swizzle.xyzw == swizzle.wzyx.wzyx"));
EXPECT_TRUE(
get<bool>(lua, "swizzle.xyz0 == util.vector4(1, 2, 3, 0) and swizzle.w110 == util.vector4(4, 1, 1, 0)"));
EXPECT_TRUE(get<bool>(
lua, "swizzle['0001'] == util.vector4(0, 0, 0, 1) and swizzle['0yx1'] == util.vector4(0, 2, 1, 1)"));
}
TEST(LuaUtilPackageTest, Color)
{
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::math, sol::lib::string);
lua["util"] = LuaUtil::initUtilPackage(lua);
lua.safe_script("brown = util.color.rgba(0.75, 0.25, 0, 1)");
EXPECT_EQ(get<std::string>(lua, "tostring(brown)"), "(0.75, 0.25, 0, 1)");
lua.safe_script("blue = util.color.rgb(0, 1, 0, 1)");
EXPECT_EQ(get<std::string>(lua, "tostring(blue)"), "(0, 1, 0, 1)");
lua.safe_script("red = util.color.hex('ff0000')");
EXPECT_EQ(get<std::string>(lua, "tostring(red)"), "(1, 0, 0, 1)");
lua.safe_script("green = util.color.hex('00FF00')");
EXPECT_EQ(get<std::string>(lua, "tostring(green)"), "(0, 1, 0, 1)");
lua.safe_script("darkRed = util.color.hex('a01112')");
EXPECT_EQ(get<std::string>(lua, "darkRed:asHex()"), "a01112");
EXPECT_TRUE(get<bool>(lua, "green:asRgba() == util.vector4(0, 1, 0, 1)"));
EXPECT_TRUE(get<bool>(lua, "red:asRgb() == util.vector3(1, 0, 0)"));
}
TEST(LuaUtilPackageTest, Transform)
{
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::math, sol::lib::string);
lua["util"] = LuaUtil::initUtilPackage(lua);
lua["T"] = lua["util"]["transform"];
lua["v"] = lua["util"]["vector3"];
EXPECT_ERROR(lua.safe_script("T.identity = nil"), "attempt to index");
EXPECT_EQ(getAsString(lua, "T.identity * v(3, 4, 5)"), "(3, 4, 5)");
EXPECT_EQ(getAsString(lua, "T.move(1, 2, 3) * v(3, 4, 5)"), "(4, 6, 8)");
EXPECT_EQ(getAsString(lua, "T.scale(1, -2, 3) * v(3, 4, 5)"), "(3, -8, 15)");
EXPECT_EQ(getAsString(lua, "T.scale(v(1, 2, 3)) * v(3, 4, 5)"), "(3, 8, 15)");
lua.safe_script("moveAndScale = T.move(v(1, 2, 3)) * T.scale(0.5, 1, 0.5) * T.move(10, 20, 30)");
EXPECT_EQ(getAsString(lua, "moveAndScale * v(0, 0, 0)"), "(6, 22, 18)");
EXPECT_EQ(getAsString(lua, "moveAndScale * v(300, 200, 100)"), "(156, 222, 68)");
EXPECT_EQ(getAsString(lua, "moveAndScale:apply(v(0, 0, 0))"), "(6, 22, 18)");
EXPECT_EQ(getAsString(lua, "moveAndScale:apply(v(300, 200, 100))"), "(156, 222, 68)");
EXPECT_THAT(getAsString(lua, "moveAndScale"),
AllOf(StartsWith("TransformM{ move(6, 22, 18) scale(0.5, 1, 0.5) "), EndsWith(" }")));
EXPECT_EQ(getAsString(lua, "T.identity"), "TransformQ{ rotation(angle=0, axis=(0, 0, 1)) }");
lua.safe_script("rx = T.rotateX(-math.pi / 2)");
lua.safe_script("ry = T.rotateY(-math.pi / 2)");
lua.safe_script("rz = T.rotateZ(-math.pi / 2)");
EXPECT_LT(get<float>(lua, "(rx * v(1, 2, 3) - v(1, -3, 2)):length()"), 1e-6);
EXPECT_LT(get<float>(lua, "(ry * v(1, 2, 3) - v(3, 2, -1)):length()"), 1e-6);
EXPECT_LT(get<float>(lua, "(rz * v(1, 2, 3) - v(-2, 1, 3)):length()"), 1e-6);
EXPECT_LT(get<float>(lua, "(rz:apply(v(1, 2, 3)) - v(-2, 1, 3)):length()"), 1e-6);
lua.safe_script("rot = T.rotate(math.pi / 2, v(-1, -1, 0)) * T.rotateZ(math.pi / 4)");
EXPECT_THAT(getAsString(lua, "rot"), HasSubstr("TransformQ"));
EXPECT_LT(get<float>(lua, "(rot * v(1, 0, 0) - v(0, 0, 1)):length()"), 1e-6);
EXPECT_LT(get<float>(lua, "(rot * rot:inverse() * v(1, 0, 0) - v(1, 0, 0)):length()"), 1e-6);
lua.safe_script("rz_move_rx = rz * T.move(0, 3, 0) * rx");
EXPECT_LT(get<float>(lua, "(rz_move_rx * v(1, 2, 3) - v(0, 1, 2)):length()"), 1e-6);
EXPECT_LT(get<float>(lua, "(rz_move_rx:inverse() * v(0, 1, 2) - v(1, 2, 3)):length()"), 1e-6);
}
TEST(LuaUtilPackageTest, UtilityFunctions)
{
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::math, sol::lib::string);
lua["util"] = LuaUtil::initUtilPackage(lua);
lua.safe_script("v = util.vector2(1, 0):rotate(math.rad(120))");
EXPECT_FLOAT_EQ(get<float>(lua, "v.x"), -0.5f);
EXPECT_FLOAT_EQ(get<float>(lua, "v.y"), 0.86602539f);
EXPECT_FLOAT_EQ(get<float>(lua, "util.normalizeAngle(math.pi * 10 + 0.1)"), 0.1f);
EXPECT_FLOAT_EQ(get<float>(lua, "util.clamp(0.1, 0, 1.5)"), 0.1f);
EXPECT_FLOAT_EQ(get<float>(lua, "util.clamp(-0.1, 0, 1.5)"), 0);
EXPECT_FLOAT_EQ(get<float>(lua, "util.clamp(2.1, 0, 1.5)"), 1.5f);
lua.safe_script("t = util.makeReadOnly({x = 1})");
EXPECT_FLOAT_EQ(get<float>(lua, "t.x"), 1);
EXPECT_ERROR(lua.safe_script("t.y = 2"), "userdata value");
}
}
| 13,018
|
C++
|
.cpp
| 200
| 56.715
| 119
| 0.561256
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,218
|
testpathutil.cpp
|
OpenMW_openmw/apps/components_tests/vfs/testpathutil.cpp
|
#include <components/vfs/pathutil.hpp>
#include <gtest/gtest.h>
#include <sstream>
namespace VFS::Path
{
namespace
{
using namespace testing;
TEST(NormalizedTest, shouldSupportDefaultConstructor)
{
const Normalized value;
EXPECT_EQ(value.value(), "");
}
TEST(NormalizedTest, shouldSupportConstructorFromString)
{
const std::string string("Foo\\Bar/baz");
const Normalized value(string);
EXPECT_EQ(value.value(), "foo/bar/baz");
}
TEST(NormalizedTest, shouldSupportConstructorFromConstCharPtr)
{
const char* const ptr = "Foo\\Bar/baz";
const Normalized value(ptr);
EXPECT_EQ(value.value(), "foo/bar/baz");
}
TEST(NormalizedTest, shouldSupportConstructorFromStringView)
{
const std::string_view view = "Foo\\Bar/baz";
const Normalized value(view);
EXPECT_EQ(value.view(), "foo/bar/baz");
}
TEST(NormalizedTest, shouldSupportConstructorFromNormalizedView)
{
const NormalizedView view("foo/bar/baz");
const Normalized value(view);
EXPECT_EQ(value.view(), "foo/bar/baz");
}
TEST(NormalizedTest, supportMovingValueOut)
{
Normalized value("Foo\\Bar/baz");
EXPECT_EQ(std::move(value).value(), "foo/bar/baz");
EXPECT_EQ(value.value(), "");
}
TEST(NormalizedTest, isNotEqualToNotNormalized)
{
const Normalized value("Foo\\Bar/baz");
EXPECT_NE(value.value(), "Foo\\Bar/baz");
}
TEST(NormalizedTest, shouldSupportOperatorLeftShiftToOStream)
{
const Normalized value("Foo\\Bar/baz");
std::stringstream stream;
stream << value;
EXPECT_EQ(stream.str(), "foo/bar/baz");
}
TEST(NormalizedTest, shouldSupportOperatorDivEqual)
{
Normalized value("foo/bar");
value /= NormalizedView("baz");
EXPECT_EQ(value.value(), "foo/bar/baz");
}
TEST(NormalizedTest, shouldSupportOperatorDivEqualWithStringView)
{
Normalized value("foo/bar");
value /= std::string_view("BAZ");
EXPECT_EQ(value.value(), "foo/bar/baz");
}
TEST(NormalizedTest, changeExtensionShouldReplaceAfterLastDot)
{
Normalized value("foo/bar.a");
ASSERT_TRUE(value.changeExtension("so"));
EXPECT_EQ(value.value(), "foo/bar.so");
}
TEST(NormalizedTest, changeExtensionShouldNormalizeExtension)
{
Normalized value("foo/bar.a");
ASSERT_TRUE(value.changeExtension("SO"));
EXPECT_EQ(value.value(), "foo/bar.so");
}
TEST(NormalizedTest, changeExtensionShouldIgnorePathWithoutADot)
{
Normalized value("foo/bar");
ASSERT_FALSE(value.changeExtension("so"));
EXPECT_EQ(value.value(), "foo/bar");
}
TEST(NormalizedTest, changeExtensionShouldIgnorePathWithDotBeforeSeparator)
{
Normalized value("foo.bar/baz");
ASSERT_FALSE(value.changeExtension("so"));
EXPECT_EQ(value.value(), "foo.bar/baz");
}
TEST(NormalizedTest, changeExtensionShouldThrowExceptionOnExtensionWithDot)
{
Normalized value("foo.a");
EXPECT_THROW(value.changeExtension(".so"), std::invalid_argument);
}
TEST(NormalizedTest, changeExtensionShouldThrowExceptionOnExtensionWithSeparator)
{
Normalized value("foo.a");
EXPECT_THROW(value.changeExtension("/so"), std::invalid_argument);
}
template <class T>
struct NormalizedOperatorsTest : Test
{
};
TYPED_TEST_SUITE_P(NormalizedOperatorsTest);
TYPED_TEST_P(NormalizedOperatorsTest, supportsEqual)
{
using Type0 = typename TypeParam::Type0;
using Type1 = typename TypeParam::Type1;
const Type0 normalized{ "a/foo/bar/baz" };
const Type1 otherEqual{ "a/foo/bar/baz" };
const Type1 otherNotEqual{ "b/foo/bar/baz" };
EXPECT_EQ(normalized, otherEqual);
EXPECT_EQ(otherEqual, normalized);
EXPECT_NE(normalized, otherNotEqual);
EXPECT_NE(otherNotEqual, normalized);
}
TYPED_TEST_P(NormalizedOperatorsTest, supportsLess)
{
using Type0 = typename TypeParam::Type0;
using Type1 = typename TypeParam::Type1;
const Type0 normalized{ "b/foo/bar/baz" };
const Type1 otherEqual{ "b/foo/bar/baz" };
const Type1 otherLess{ "a/foo/bar/baz" };
const Type1 otherGreater{ "c/foo/bar/baz" };
EXPECT_FALSE(normalized < otherEqual);
EXPECT_FALSE(otherEqual < normalized);
EXPECT_LT(otherLess, normalized);
EXPECT_FALSE(normalized < otherLess);
EXPECT_LT(normalized, otherGreater);
EXPECT_FALSE(otherGreater < normalized);
}
REGISTER_TYPED_TEST_SUITE_P(NormalizedOperatorsTest, supportsEqual, supportsLess);
template <class T0, class T1>
struct TypePair
{
using Type0 = T0;
using Type1 = T1;
};
using TypePairs = Types<TypePair<Normalized, Normalized>, TypePair<Normalized, const char*>,
TypePair<Normalized, std::string>, TypePair<Normalized, std::string_view>,
TypePair<Normalized, NormalizedView>, TypePair<NormalizedView, Normalized>,
TypePair<NormalizedView, const char*>, TypePair<NormalizedView, std::string>,
TypePair<NormalizedView, std::string_view>, TypePair<NormalizedView, NormalizedView>>;
INSTANTIATE_TYPED_TEST_SUITE_P(Typed, NormalizedOperatorsTest, TypePairs);
TEST(NormalizedViewTest, shouldSupportConstructorFromNormalized)
{
const Normalized value("Foo\\Bar/baz");
const NormalizedView view(value);
EXPECT_EQ(view.value(), "foo/bar/baz");
}
TEST(NormalizedViewTest, shouldSupportConstexprConstructorFromNormalizedStringLiteral)
{
constexpr NormalizedView view("foo/bar/baz");
EXPECT_EQ(view.value(), "foo/bar/baz");
}
TEST(NormalizedViewTest, constructorShouldThrowExceptionOnNotNormalized)
{
EXPECT_THROW([] { NormalizedView("Foo\\Bar/baz"); }(), std::invalid_argument);
}
TEST(NormalizedView, shouldSupportOperatorDiv)
{
const NormalizedView a("foo/bar");
const NormalizedView b("baz");
const Normalized result = a / b;
EXPECT_EQ(result.value(), "foo/bar/baz");
}
}
}
| 6,964
|
C++
|
.cpp
| 170
| 30.205882
| 100
| 0.605353
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,219
|
testnifloader.cpp
|
OpenMW_openmw/apps/components_tests/nifosg/testnifloader.cpp
|
#include "../nif/node.hpp"
#include <components/nif/node.hpp>
#include <components/nif/property.hpp>
#include <components/nifosg/nifloader.hpp>
#include <components/resource/bgsmfilemanager.hpp>
#include <components/resource/imagemanager.hpp>
#include <components/sceneutil/serialize.hpp>
#include <components/vfs/manager.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <osgDB/Registry>
#include <array>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
namespace
{
using namespace testing;
using namespace NifOsg;
using namespace Nif::Testing;
struct BaseNifOsgLoaderTest
{
VFS::Manager mVfs;
Resource::ImageManager mImageManager{ &mVfs, 0 };
Resource::BgsmFileManager mMaterialManager{ &mVfs, 0 };
const osgDB::ReaderWriter* mReaderWriter = osgDB::Registry::instance()->getReaderWriterForExtension("osgt");
osg::ref_ptr<osgDB::Options> mOptions = new osgDB::Options;
BaseNifOsgLoaderTest()
{
SceneUtil::registerSerializers();
if (mReaderWriter == nullptr)
throw std::runtime_error("osgt reader writer is not found");
mOptions->setPluginStringData("fileType", "Ascii");
mOptions->setPluginStringData("WriteImageHint", "UseExternal");
}
std::string serialize(const osg::Node& node) const
{
std::stringstream stream;
mReaderWriter->writeNode(node, stream, mOptions);
std::string result;
for (std::string line; std::getline(stream, line);)
{
if (line.starts_with('#'))
continue;
line.erase(line.find_last_not_of(" \t\n\r\f\v") + 1);
result += line;
result += '\n';
}
return result;
}
};
struct NifOsgLoaderTest : Test, BaseNifOsgLoaderTest
{
};
TEST_F(NifOsgLoaderTest, shouldLoadFileWithDefaultNode)
{
Nif::NiAVObject node;
init(node);
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&node);
auto result = Loader::load(file, &mImageManager, &mMaterialManager);
EXPECT_EQ(serialize(*result), R"(
osg::Group {
UniqueID 1
DataVariance STATIC
UserDataContainer TRUE {
osg::DefaultUserDataContainer {
UniqueID 2
UDC_UserObjects 1 {
osg::StringValueObject {
UniqueID 3
Name "fileHash"
}
}
}
}
Children 1 {
osg::Group {
UniqueID 4
DataVariance STATIC
UserDataContainer TRUE {
osg::DefaultUserDataContainer {
UniqueID 5
UDC_UserObjects 1 {
osg::UIntValueObject {
UniqueID 6
Name "recIndex"
Value 4294967295
}
}
}
}
}
}
}
)");
}
std::string formatOsgNodeForBSShaderProperty(std::string_view shaderPrefix)
{
std::ostringstream oss;
oss << R"(
osg::Group {
UniqueID 1
DataVariance STATIC
UserDataContainer TRUE {
osg::DefaultUserDataContainer {
UniqueID 2
UDC_UserObjects 1 {
osg::StringValueObject {
UniqueID 3
Name "fileHash"
}
}
}
}
Children 1 {
osg::Group {
UniqueID 4
DataVariance STATIC
UserDataContainer TRUE {
osg::DefaultUserDataContainer {
UniqueID 5
UDC_UserObjects 3 {
osg::UIntValueObject {
UniqueID 6
Name "recIndex"
Value 4294967295
}
osg::StringValueObject {
UniqueID 7
Name "shaderPrefix"
Value ")"
<< shaderPrefix << R"("
}
osg::BoolValueObject {
UniqueID 8
Name "shaderRequired"
Value TRUE
}
}
}
}
StateSet TRUE {
osg::StateSet {
UniqueID 9
}
}
}
}
}
)";
return oss.str();
}
std::string formatOsgNodeForBSLightingShaderProperty(std::string_view shaderPrefix)
{
std::ostringstream oss;
oss << R"(
osg::Group {
UniqueID 1
DataVariance STATIC
UserDataContainer TRUE {
osg::DefaultUserDataContainer {
UniqueID 2
UDC_UserObjects 1 {
osg::StringValueObject {
UniqueID 3
Name "fileHash"
}
}
}
}
Children 1 {
osg::Group {
UniqueID 4
DataVariance STATIC
UserDataContainer TRUE {
osg::DefaultUserDataContainer {
UniqueID 5
UDC_UserObjects 3 {
osg::UIntValueObject {
UniqueID 6
Name "recIndex"
Value 4294967295
}
osg::StringValueObject {
UniqueID 7
Name "shaderPrefix"
Value ")"
<< shaderPrefix << R"("
}
osg::BoolValueObject {
UniqueID 8
Name "shaderRequired"
Value TRUE
}
}
}
}
StateSet TRUE {
osg::StateSet {
UniqueID 9
ModeList 1 {
GL_DEPTH_TEST ON
}
AttributeList 1 {
osg::Depth {
UniqueID 10
}
Value OFF
}
}
}
}
}
}
)";
return oss.str();
}
struct ShaderPrefixParams
{
unsigned int mShaderType;
std::string_view mExpectedShaderPrefix;
};
struct NifOsgLoaderBSShaderPrefixTest : TestWithParam<ShaderPrefixParams>, BaseNifOsgLoaderTest
{
static constexpr std::array sParams = {
ShaderPrefixParams{ static_cast<unsigned int>(Nif::BSShaderType::ShaderType_Default), "bs/default" },
ShaderPrefixParams{ static_cast<unsigned int>(Nif::BSShaderType::ShaderType_NoLighting), "bs/nolighting" },
ShaderPrefixParams{ static_cast<unsigned int>(Nif::BSShaderType::ShaderType_Tile), "bs/default" },
ShaderPrefixParams{ std::numeric_limits<unsigned int>::max(), "bs/default" },
};
};
TEST_P(NifOsgLoaderBSShaderPrefixTest, shouldAddShaderPrefix)
{
Nif::NiAVObject node;
init(node);
Nif::BSShaderPPLightingProperty property;
property.recType = Nif::RC_BSShaderPPLightingProperty;
property.mTextureSet = nullptr;
property.mController = nullptr;
property.mType = GetParam().mShaderType;
node.mProperties.push_back(Nif::RecordPtrT<Nif::NiProperty>(&property));
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&node);
auto result = Loader::load(file, &mImageManager, &mMaterialManager);
EXPECT_EQ(serialize(*result), formatOsgNodeForBSShaderProperty(GetParam().mExpectedShaderPrefix));
}
INSTANTIATE_TEST_SUITE_P(Params, NifOsgLoaderBSShaderPrefixTest, ValuesIn(NifOsgLoaderBSShaderPrefixTest::sParams));
struct NifOsgLoaderBSLightingShaderPrefixTest : TestWithParam<ShaderPrefixParams>, BaseNifOsgLoaderTest
{
static constexpr std::array sParams = {
ShaderPrefixParams{
static_cast<unsigned int>(Nif::BSLightingShaderType::ShaderType_Default), "bs/default" },
ShaderPrefixParams{ static_cast<unsigned int>(Nif::BSLightingShaderType::ShaderType_Cloud), "bs/default" },
ShaderPrefixParams{ std::numeric_limits<unsigned int>::max(), "bs/default" },
};
};
TEST_P(NifOsgLoaderBSLightingShaderPrefixTest, shouldAddShaderPrefix)
{
Nif::NiAVObject node;
init(node);
Nif::BSLightingShaderProperty property;
property.recType = Nif::RC_BSLightingShaderProperty;
property.mTextureSet = nullptr;
property.mController = nullptr;
property.mType = GetParam().mShaderType;
property.mShaderFlags1 |= Nif::BSShaderFlags1::BSSFlag1_DepthTest;
property.mShaderFlags2 |= Nif::BSShaderFlags2::BSSFlag2_DepthWrite;
node.mProperties.push_back(Nif::RecordPtrT<Nif::NiProperty>(&property));
Nif::NIFFile file("test.nif");
file.mRoots.push_back(&node);
auto result = Loader::load(file, &mImageManager, &mMaterialManager);
EXPECT_EQ(serialize(*result), formatOsgNodeForBSLightingShaderProperty(GetParam().mExpectedShaderPrefix));
}
INSTANTIATE_TEST_SUITE_P(
Params, NifOsgLoaderBSLightingShaderPrefixTest, ValuesIn(NifOsgLoaderBSLightingShaderPrefixTest::sParams));
}
| 8,657
|
C++
|
.cpp
| 279
| 22.641577
| 120
| 0.610745
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,220
|
test_endianness.cpp
|
OpenMW_openmw/apps/components_tests/misc/test_endianness.cpp
|
#include "components/misc/endianness.hpp"
#include <gtest/gtest.h>
struct EndiannessTest : public ::testing::Test
{
};
TEST_F(EndiannessTest, test_swap_endianness_inplace1)
{
uint8_t zero = 0x00;
uint8_t ff = 0xFF;
uint8_t fortytwo = 0x42;
uint8_t half = 128;
Misc::swapEndiannessInplace(zero);
EXPECT_EQ(zero, 0x00);
Misc::swapEndiannessInplace(ff);
EXPECT_EQ(ff, 0xFF);
Misc::swapEndiannessInplace(fortytwo);
EXPECT_EQ(fortytwo, 0x42);
Misc::swapEndiannessInplace(half);
EXPECT_EQ(half, 128);
}
TEST_F(EndiannessTest, test_swap_endianness_inplace2)
{
uint16_t zero = 0x0000;
uint16_t ffff = 0xFFFF;
uint16_t n12 = 0x0102;
uint16_t fortytwo = 0x0042;
Misc::swapEndiannessInplace(zero);
EXPECT_EQ(zero, 0x0000u);
Misc::swapEndiannessInplace(zero);
EXPECT_EQ(zero, 0x0000u);
Misc::swapEndiannessInplace(ffff);
EXPECT_EQ(ffff, 0xFFFFu);
Misc::swapEndiannessInplace(ffff);
EXPECT_EQ(ffff, 0xFFFFu);
Misc::swapEndiannessInplace(n12);
EXPECT_EQ(n12, 0x0201u);
Misc::swapEndiannessInplace(n12);
EXPECT_EQ(n12, 0x0102u);
Misc::swapEndiannessInplace(fortytwo);
EXPECT_EQ(fortytwo, 0x4200u);
Misc::swapEndiannessInplace(fortytwo);
EXPECT_EQ(fortytwo, 0x0042u);
}
TEST_F(EndiannessTest, test_swap_endianness_inplace4)
{
uint32_t zero = 0x00000000;
uint32_t n1234 = 0x01020304;
uint32_t ffff = 0xFFFFFFFF;
Misc::swapEndiannessInplace(zero);
EXPECT_EQ(zero, 0x00000000u);
Misc::swapEndiannessInplace(zero);
EXPECT_EQ(zero, 0x00000000u);
Misc::swapEndiannessInplace(n1234);
EXPECT_EQ(n1234, 0x04030201u);
Misc::swapEndiannessInplace(n1234);
EXPECT_EQ(n1234, 0x01020304u);
Misc::swapEndiannessInplace(ffff);
EXPECT_EQ(ffff, 0xFFFFFFFFu);
Misc::swapEndiannessInplace(ffff);
EXPECT_EQ(ffff, 0xFFFFFFFFu);
}
TEST_F(EndiannessTest, test_swap_endianness_inplace8)
{
uint64_t zero = 0x0000'0000'0000'0000;
uint64_t n1234 = 0x0102'0304'0506'0708;
uint64_t ffff = 0xFFFF'FFFF'FFFF'FFFF;
Misc::swapEndiannessInplace(zero);
EXPECT_EQ(zero, 0x0000'0000'0000'0000u);
Misc::swapEndiannessInplace(zero);
EXPECT_EQ(zero, 0x0000'0000'0000'0000u);
Misc::swapEndiannessInplace(ffff);
EXPECT_EQ(ffff, 0xFFFF'FFFF'FFFF'FFFFu);
Misc::swapEndiannessInplace(ffff);
EXPECT_EQ(ffff, 0xFFFF'FFFF'FFFF'FFFFu);
Misc::swapEndiannessInplace(n1234);
EXPECT_EQ(n1234, 0x0807'0605'0403'0201u);
Misc::swapEndiannessInplace(n1234);
EXPECT_EQ(n1234, 0x0102'0304'0506'0708u);
}
TEST_F(EndiannessTest, test_swap_endianness_inplace_float)
{
const uint32_t original = 0x4023d70a;
const uint32_t expected = 0x0ad72340;
float number;
memcpy(&number, &original, sizeof(original));
Misc::swapEndiannessInplace(number);
EXPECT_TRUE(!memcmp(&number, &expected, sizeof(expected)));
}
TEST_F(EndiannessTest, test_swap_endianness_inplace_double)
{
const uint64_t original = 0x040047ae147ae147ul;
const uint64_t expected = 0x47e17a14ae470004ul;
double number;
memcpy(&number, &original, sizeof(original));
Misc::swapEndiannessInplace(number);
EXPECT_TRUE(!memcmp(&number, &expected, sizeof(expected)));
}
| 3,264
|
C++
|
.cpp
| 97
| 29.319588
| 63
| 0.728662
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
35,221
|
test_stringops.cpp
|
OpenMW_openmw/apps/components_tests/misc/test_stringops.cpp
|
#include <gtest/gtest.h>
#include <components/misc/strings/algorithm.hpp>
#include <components/misc/strings/format.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/misc/algorithm.hpp>
#include <string>
#include <string_view>
#include <type_traits>
struct PartialBinarySearchTest : public ::testing::Test
{
protected:
std::vector<std::string> mDataVec;
void SetUp() override
{
const char* data[] = { "Head", "Chest", "Tri Head", "Tri Chest", "Bip01", "Tri Bip01" };
mDataVec = std::vector<std::string>(data, data + sizeof(data) / sizeof(data[0]));
std::sort(mDataVec.begin(), mDataVec.end(), Misc::StringUtils::ciLess);
}
bool matches(const std::string& keyword)
{
return Misc::partialBinarySearch(mDataVec.begin(), mDataVec.end(), keyword) != mDataVec.end();
}
};
TEST_F(PartialBinarySearchTest, partial_binary_search_test)
{
EXPECT_TRUE(matches("Head 01"));
EXPECT_TRUE(matches("Head"));
EXPECT_TRUE(matches("Tri Head 01"));
EXPECT_TRUE(matches("Tri Head"));
EXPECT_TRUE(matches("tri head"));
EXPECT_TRUE(matches("Tri bip01"));
EXPECT_TRUE(matches("bip01"));
EXPECT_TRUE(matches("bip01 head"));
EXPECT_TRUE(matches("Bip01 L Hand"));
EXPECT_TRUE(matches("BIp01 r Clavicle"));
EXPECT_TRUE(matches("Bip01 SpiNe1"));
EXPECT_FALSE(matches(""));
EXPECT_FALSE(matches("Node Bip01"));
EXPECT_FALSE(matches("Hea"));
EXPECT_FALSE(matches(" Head"));
EXPECT_FALSE(matches("Tri Head"));
}
TEST_F(PartialBinarySearchTest, ci_test)
{
EXPECT_TRUE(Misc::StringUtils::lowerCase("ASD") == "asd");
// test to make sure system locale is not used
std::string unicode1 = "\u04151 \u0418"; // CYRILLIC CAPITAL LETTER IE, CYRILLIC CAPITAL LETTER I
EXPECT_TRUE(Misc::StringUtils::lowerCase(unicode1) == unicode1);
}
namespace
{
using namespace ::Misc::StringUtils;
using namespace ::testing;
template <class T>
struct MiscStringUtilsCiEqualEmptyTest : Test
{
};
TYPED_TEST_SUITE_P(MiscStringUtilsCiEqualEmptyTest);
TYPED_TEST_P(MiscStringUtilsCiEqualEmptyTest, empty_strings_should_be_equal)
{
const typename TypeParam::first_type a{};
const typename TypeParam::second_type b{};
EXPECT_TRUE(ciEqual(a, b));
}
REGISTER_TYPED_TEST_SUITE_P(MiscStringUtilsCiEqualEmptyTest, empty_strings_should_be_equal);
using EmptyStringTypePairsTypes = Types<std::pair<std::string, std::string>,
std::pair<std::string, std::string_view>, std::pair<std::string, const char[1]>,
std::pair<std::string_view, std::string>, std::pair<std::string_view, std::string_view>,
std::pair<std::string_view, const char[1]>, std::pair<const char[1], std::string>,
std::pair<const char[1], std::string_view>, std::pair<const char[1], const char[1]>>;
INSTANTIATE_TYPED_TEST_SUITE_P(EmptyStringTypePairs, MiscStringUtilsCiEqualEmptyTest, EmptyStringTypePairsTypes);
template <class T>
struct MiscStringUtilsCiEqualNotEmptyTest : Test
{
};
TYPED_TEST_SUITE_P(MiscStringUtilsCiEqualNotEmptyTest);
using RawValue = const char[4];
constexpr RawValue foo = "f0#";
constexpr RawValue fooUpper = "F0#";
constexpr RawValue bar = "bar";
template <typename T>
using Value = std::conditional_t<std::is_same_v<T, RawValue>, RawValue&, T>;
TYPED_TEST_P(MiscStringUtilsCiEqualNotEmptyTest, same_strings_should_be_equal)
{
const Value<typename TypeParam::first_type> a{ foo };
const Value<typename TypeParam::second_type> b{ foo };
EXPECT_TRUE(ciEqual(a, b)) << a << "\n" << b;
}
TYPED_TEST_P(MiscStringUtilsCiEqualNotEmptyTest, same_strings_with_different_case_sensetivity_should_be_equal)
{
const Value<typename TypeParam::first_type> a{ foo };
const Value<typename TypeParam::second_type> b{ fooUpper };
EXPECT_TRUE(ciEqual(a, b)) << a << "\n" << b;
}
TYPED_TEST_P(MiscStringUtilsCiEqualNotEmptyTest, different_strings_content_should_not_be_equal)
{
const Value<typename TypeParam::first_type> a{ foo };
const Value<typename TypeParam::second_type> b{ bar };
EXPECT_FALSE(ciEqual(a, b)) << a << "\n" << b;
}
REGISTER_TYPED_TEST_SUITE_P(MiscStringUtilsCiEqualNotEmptyTest, same_strings_should_be_equal,
same_strings_with_different_case_sensetivity_should_be_equal, different_strings_content_should_not_be_equal);
using NotEmptyStringTypePairsTypes = Types<std::pair<std::string, std::string>,
std::pair<std::string, std::string_view>, std::pair<std::string, const char[4]>,
std::pair<std::string_view, std::string>, std::pair<std::string_view, std::string_view>,
std::pair<std::string_view, const char[4]>, std::pair<const char[4], std::string>,
std::pair<const char[4], std::string_view>, std::pair<const char[4], const char[4]>>;
INSTANTIATE_TYPED_TEST_SUITE_P(
NotEmptyStringTypePairs, MiscStringUtilsCiEqualNotEmptyTest, NotEmptyStringTypePairsTypes);
TEST(MiscStringUtilsCiEqualTest, string_with_different_length_should_not_be_equal)
{
EXPECT_FALSE(ciEqual(std::string("a"), std::string("aa")));
}
TEST(MiscStringsCiStartsWith, empty_string_should_start_with_empty_prefix)
{
EXPECT_TRUE(ciStartsWith(std::string_view(), std::string_view()));
}
TEST(MiscStringsCiStartsWith, string_should_start_with_empty_prefix)
{
EXPECT_TRUE(ciStartsWith("foo", std::string_view()));
}
TEST(MiscStringsCiStartsWith, string_should_start_with_own_prefix)
{
std::string string = "some string";
EXPECT_TRUE(ciStartsWith(string, string.substr(0, 4)));
}
TEST(MiscStringsCiStartsWith, string_should_start_with_the_same_value)
{
EXPECT_TRUE(ciStartsWith("foo", "foo"));
}
TEST(MiscStringsCiStartsWith, string_should_not_start_with_not_its_prefix)
{
EXPECT_FALSE(ciStartsWith("some string", "foo"));
}
TEST(MiscStringsCiStartsWith, string_should_not_start_with_longer_string_having_matching_prefix)
{
EXPECT_FALSE(ciStartsWith("foo", "foo bar"));
}
TEST(MiscStringsCiStartsWith, should_be_case_insensitive)
{
EXPECT_TRUE(ciStartsWith("foo bar", "FOO"));
}
TEST(MiscStringsFormat, string_format)
{
std::string f = "1%s2";
EXPECT_EQ(Misc::StringUtils::format(f, ""), "12");
}
TEST(MiscStringsFormat, string_format_arg)
{
std::string arg = "12";
EXPECT_EQ(Misc::StringUtils::format("1%s2", arg), "1122");
}
TEST(MiscStringsFormat, string_view_format_arg)
{
std::string f = "1%s2";
std::string_view view = "12";
EXPECT_EQ(Misc::StringUtils::format(f, view), "1122");
EXPECT_EQ(Misc::StringUtils::format(f, view.substr(0, 1)), "112");
EXPECT_EQ(Misc::StringUtils::format(f, view.substr(1, 1)), "122");
EXPECT_EQ(Misc::StringUtils::format(f, view.substr(2)), "12");
}
TEST(MiscStringsCiFind, should_return_zero_for_2_empty_strings)
{
EXPECT_EQ(ciFind(std::string_view(), std::string_view()), 0);
}
TEST(MiscStringsCiFind, should_return_zero_when_looking_for_empty_string)
{
EXPECT_EQ(ciFind("foo", std::string_view()), 0);
}
TEST(MiscStringsCiFind, should_return_npos_for_longer_substring)
{
EXPECT_EQ(ciFind("a", "aa"), std::string_view::npos);
}
TEST(MiscStringsCiFind, should_return_zero_for_the_same_string)
{
EXPECT_EQ(ciFind("foo", "foo"), 0);
}
TEST(MiscStringsCiFind, should_return_first_position_of_substring)
{
EXPECT_EQ(ciFind("foobar foobar", "bar"), 3);
}
TEST(MiscStringsCiFind, should_be_case_insensitive)
{
EXPECT_EQ(ciFind("foobar", "BAR"), 3);
}
TEST(MiscStringsCiFind, should_return_npos_for_absent_substring)
{
EXPECT_EQ(ciFind("foobar", "baz"), std::string_view::npos);
}
}
| 8,051
|
C++
|
.cpp
| 190
| 36.484211
| 117
| 0.67413
|
OpenMW/openmw
| 5,318
| 933
| 0
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.