Use constants instead of widely used magic numbers (task #4645)

pull/541/head
Andrei Kortunov 6 years ago
parent 06b2a23e74
commit 70ed8fd1a9

@ -162,6 +162,7 @@
Task #4613: Incomplete type errors when compiling with g++ on OSX 10.9 Task #4613: Incomplete type errors when compiling with g++ on OSX 10.9
Task #4621: Optimize combat AI Task #4621: Optimize combat AI
Task #4643: Revise editor record verifying functionality Task #4643: Revise editor record verifying functionality
Task #4645: Use constants instead of widely used magic numbers
0.44.0 0.44.0
------ ------

@ -8,6 +8,8 @@
#include <components/esm/creaturestate.hpp> #include <components/esm/creaturestate.hpp>
#include <components/esm/containerstate.hpp> #include <components/esm/containerstate.hpp>
#include <components/misc/constants.hpp>
#include "convertcrec.hpp" #include "convertcrec.hpp"
#include "convertcntc.hpp" #include "convertcntc.hpp"
#include "convertscri.hpp" #include "convertscri.hpp"
@ -288,12 +290,12 @@ namespace ESSImport
notepos[1] += 31.f; notepos[1] += 31.f;
notepos[0] += 0.5; notepos[0] += 0.5;
notepos[1] += 0.5; notepos[1] += 0.5;
notepos[0] = 8192 * notepos[0] / 32.f; notepos[0] = Constants::CellSizeInUnits * notepos[0] / 32.f;
notepos[1] = 8192 * notepos[1] / 32.f; notepos[1] = Constants::CellSizeInUnits * notepos[1] / 32.f;
if (cell.isExterior()) if (cell.isExterior())
{ {
notepos[0] += 8192 * cell.mData.mX; notepos[0] += Constants::CellSizeInUnits * cell.mData.mX;
notepos[1] += 8192 * cell.mData.mY; notepos[1] += Constants::CellSizeInUnits * cell.mData.mY;
} }
// TODO: what encoding is this in? // TODO: what encoding is this in?
std::string note = esm.getHNString("MPNT"); std::string note = esm.getHNString("MPNT");

@ -1,5 +1,6 @@
#include "convertplayer.hpp" #include "convertplayer.hpp"
#include <components/misc/constants.hpp>
#include <components/misc/stringops.hpp> #include <components/misc/stringops.hpp>
namespace ESSImport namespace ESSImport
@ -78,9 +79,8 @@ namespace ESSImport
if (pcdt.mHasENAM) if (pcdt.mHasENAM)
{ {
const int cellSize = 8192; out.mLastKnownExteriorPosition[0] = (pcdt.mENAM.mCellX + 0.5f) * Constants::CellSizeInUnits;
out.mLastKnownExteriorPosition[0] = (pcdt.mENAM.mCellX + 0.5f) * cellSize; out.mLastKnownExteriorPosition[1] = (pcdt.mENAM.mCellY + 0.5f) * Constants::CellSizeInUnits;
out.mLastKnownExteriorPosition[1] = (pcdt.mENAM.mCellY + 0.5f) * cellSize;
out.mLastKnownExteriorPosition[2] = 0.0f; out.mLastKnownExteriorPosition[2] = 0.0f;
} }
} }

@ -25,6 +25,8 @@
#include <components/esm/loadlevlist.hpp> #include <components/esm/loadlevlist.hpp>
#include <components/esm/loadglob.hpp> #include <components/esm/loadglob.hpp>
#include <components/misc/constants.hpp>
#include <components/to_utf8/to_utf8.hpp> #include <components/to_utf8/to_utf8.hpp>
#include "importercontext.hpp" #include "importercontext.hpp"
@ -413,9 +415,8 @@ namespace ESSImport
if (context.mPlayer.mCellId.mPaged) if (context.mPlayer.mCellId.mPaged)
{ {
// exterior cell -> determine cell coordinates based on position // exterior cell -> determine cell coordinates based on position
const int cellSize = 8192; int cellX = static_cast<int>(std::floor(context.mPlayer.mObject.mPosition.pos[0] / Constants::CellSizeInUnits));
int cellX = static_cast<int>(std::floor(context.mPlayer.mObject.mPosition.pos[0]/cellSize)); int cellY = static_cast<int>(std::floor(context.mPlayer.mObject.mPosition.pos[1] / Constants::CellSizeInUnits));
int cellY = static_cast<int>(std::floor(context.mPlayer.mObject.mPosition.pos[1] / cellSize));
context.mPlayer.mCellId.mIndex.mX = cellX; context.mPlayer.mCellId.mIndex.mX = cellX;
context.mPlayer.mCellId.mIndex.mY = cellY; context.mPlayer.mCellId.mIndex.mY = cellY;
} }

@ -5,6 +5,8 @@
#include <ostream> #include <ostream>
#include <sstream> #include <sstream>
#include <components/misc/constants.hpp>
CSMWorld::CellCoordinates::CellCoordinates() : mX (0), mY (0) {} CSMWorld::CellCoordinates::CellCoordinates() : mX (0), mY (0) {}
CSMWorld::CellCoordinates::CellCoordinates (int x, int y) : mX (x), mY (y) {} CSMWorld::CellCoordinates::CellCoordinates (int x, int y) : mX (x), mY (y) {}
@ -61,9 +63,7 @@ std::pair<CSMWorld::CellCoordinates, bool> CSMWorld::CellCoordinates::fromId (
std::pair<int, int> CSMWorld::CellCoordinates::coordinatesToCellIndex (float x, float y) std::pair<int, int> CSMWorld::CellCoordinates::coordinatesToCellIndex (float x, float y)
{ {
const int cellSize = 8192; return std::make_pair (std::floor (x / Constants::CellSizeInUnits), std::floor (y / Constants::CellSizeInUnits));
return std::make_pair (std::floor (x/cellSize), std::floor (y/cellSize));
} }
bool CSMWorld::operator== (const CellCoordinates& left, const CellCoordinates& right) bool CSMWorld::operator== (const CellCoordinates& left, const CellCoordinates& right)

@ -445,16 +445,14 @@ void CSMWorld::UpdateCellCommand::redo()
int cellColumn = mModel.searchColumnIndex (Columns::ColumnId_Cell); int cellColumn = mModel.searchColumnIndex (Columns::ColumnId_Cell);
mIndex = mModel.index (mRow, cellColumn); mIndex = mModel.index (mRow, cellColumn);
const int cellSize = 8192;
QModelIndex xIndex = mModel.index ( QModelIndex xIndex = mModel.index (
mRow, mModel.findColumnIndex (Columns::ColumnId_PositionXPos)); mRow, mModel.findColumnIndex (Columns::ColumnId_PositionXPos));
QModelIndex yIndex = mModel.index ( QModelIndex yIndex = mModel.index (
mRow, mModel.findColumnIndex (Columns::ColumnId_PositionYPos)); mRow, mModel.findColumnIndex (Columns::ColumnId_PositionYPos));
int x = std::floor (mModel.data (xIndex).toFloat() / cellSize); int x = std::floor (mModel.data (xIndex).toFloat() / Constants::CellSizeInUnits);
int y = std::floor (mModel.data (yIndex).toFloat() / cellSize); int y = std::floor (mModel.data (yIndex).toFloat() / Constants::CellSizeInUnits);
std::ostringstream stream; std::ostringstream stream;

@ -10,6 +10,8 @@
#include "../../model/prefs/state.hpp" #include "../../model/prefs/state.hpp"
#include "../../model/prefs/shortcutmanager.hpp" #include "../../model/prefs/shortcutmanager.hpp"
#include <components/misc/constants.hpp>
#include "mask.hpp" #include "mask.hpp"
CSVRender::CellArrowTag::CellArrowTag (CellArrow *arrow) CSVRender::CellArrowTag::CellArrowTag (CellArrow *arrow)
@ -57,7 +59,7 @@ QString CSVRender::CellArrowTag::getToolTip (bool hideBasics) const
void CSVRender::CellArrow::adjustTransform() void CSVRender::CellArrow::adjustTransform()
{ {
// position // position
const int cellSize = 8192; const int cellSize = Constants::CellSizeInUnits;
const int offset = cellSize / 2 + 800; const int offset = cellSize / 2 + 800;
int x = mCoordinates.getX()*cellSize + cellSize/2; int x = mCoordinates.getX()*cellSize + cellSize/2;

@ -5,6 +5,8 @@
#include <osg/Geode> #include <osg/Geode>
#include <osgText/Text> #include <osgText/Text>
#include <components/misc/constants.hpp>
CSVRender::CellMarkerTag::CellMarkerTag(CellMarker *marker) CSVRender::CellMarkerTag::CellMarkerTag(CellMarker *marker)
: TagBase(Mask_CellMarker), mMarker(marker) : TagBase(Mask_CellMarker), mMarker(marker)
{} {}
@ -49,7 +51,7 @@ void CSVRender::CellMarker::buildMarker()
void CSVRender::CellMarker::positionMarker() void CSVRender::CellMarker::positionMarker()
{ {
const int cellSize = 8192; const int cellSize = Constants::CellSizeInUnits;
const int markerHeight = 0; const int markerHeight = 0;
// Move marker to center of cell. // Move marker to center of cell.

@ -29,15 +29,13 @@ int CSVRender::InstanceMode::getSubModeFromId (const std::string& id) const
osg::Vec3f CSVRender::InstanceMode::quatToEuler(const osg::Quat& rot) const osg::Vec3f CSVRender::InstanceMode::quatToEuler(const osg::Quat& rot) const
{ {
const float Pi = 3.14159265f;
float x, y, z; float x, y, z;
float test = 2 * (rot.w() * rot.y() + rot.x() * rot.z()); float test = 2 * (rot.w() * rot.y() + rot.x() * rot.z());
if (std::abs(test) >= 1.f) if (std::abs(test) >= 1.f)
{ {
x = atan2(rot.x(), rot.w()); x = atan2(rot.x(), rot.w());
y = (test > 0) ? (Pi / 2) : (-Pi / 2); y = (test > 0) ? (osg::PI / 2) : (-osg::PI / 2);
z = 0; z = 0;
} }
else else

@ -313,20 +313,18 @@ osg::ref_ptr<osg::Node> CSVRender::Object::makeMoveOrScaleMarker (int axis)
osg::ref_ptr<osg::Node> CSVRender::Object::makeRotateMarker (int axis) osg::ref_ptr<osg::Node> CSVRender::Object::makeRotateMarker (int axis)
{ {
const float Pi = 3.14159265f;
const float InnerRadius = std::max(MarkerShaftBaseLength, mBaseNode->getBound().radius()); const float InnerRadius = std::max(MarkerShaftBaseLength, mBaseNode->getBound().radius());
const float OuterRadius = InnerRadius + MarkerShaftWidth; const float OuterRadius = InnerRadius + MarkerShaftWidth;
const float SegmentDistance = 100.f; const float SegmentDistance = 100.f;
const size_t SegmentCount = std::min(64, std::max(24, (int)(OuterRadius * 2 * Pi / SegmentDistance))); const size_t SegmentCount = std::min(64, std::max(24, (int)(OuterRadius * 2 * osg::PI / SegmentDistance)));
const size_t VerticesPerSegment = 4; const size_t VerticesPerSegment = 4;
const size_t IndicesPerSegment = 24; const size_t IndicesPerSegment = 24;
const size_t VertexCount = SegmentCount * VerticesPerSegment; const size_t VertexCount = SegmentCount * VerticesPerSegment;
const size_t IndexCount = SegmentCount * IndicesPerSegment; const size_t IndexCount = SegmentCount * IndicesPerSegment;
const float Angle = 2 * Pi / SegmentCount; const float Angle = 2 * osg::PI / SegmentCount;
const unsigned short IndexPattern[IndicesPerSegment] = const unsigned short IndexPattern[IndicesPerSegment] =
{ {

@ -8,6 +8,8 @@
#include <components/esm/loadland.hpp> #include <components/esm/loadland.hpp>
#include <components/misc/constants.hpp>
#include "../../model/prefs/shortcut.hpp" #include "../../model/prefs/shortcut.hpp"
#include "../../model/world/tablemimedata.hpp" #include "../../model/world/tablemimedata.hpp"
@ -506,13 +508,11 @@ void CSVRender::PagedWorldspaceWidget::moveCellSelection (int x, int y)
void CSVRender::PagedWorldspaceWidget::addCellToSceneFromCamera (int offsetX, int offsetY) void CSVRender::PagedWorldspaceWidget::addCellToSceneFromCamera (int offsetX, int offsetY)
{ {
const int CellSize = 8192;
osg::Vec3f eye, center, up; osg::Vec3f eye, center, up;
getCamera()->getViewMatrixAsLookAt(eye, center, up); getCamera()->getViewMatrixAsLookAt(eye, center, up);
int cellX = (int)std::floor(center.x() / CellSize) + offsetX; int cellX = (int)std::floor(center.x() / Constants::CellSizeInUnits) + offsetX;
int cellY = (int)std::floor(center.y() / CellSize) + offsetY; int cellY = (int)std::floor(center.y() / Constants::CellSizeInUnits) + offsetY;
CSMWorld::CellCoordinates cellCoordinates(cellX, cellY); CSMWorld::CellCoordinates cellCoordinates(cellX, cellY);
@ -738,22 +738,18 @@ void CSVRender::PagedWorldspaceWidget::selectAllWithSameParentId (int elementMas
std::string CSVRender::PagedWorldspaceWidget::getCellId (const osg::Vec3f& point) const std::string CSVRender::PagedWorldspaceWidget::getCellId (const osg::Vec3f& point) const
{ {
const int cellSize = 8192;
CSMWorld::CellCoordinates cellCoordinates ( CSMWorld::CellCoordinates cellCoordinates (
static_cast<int> (std::floor (point.x()/cellSize)), static_cast<int> (std::floor (point.x() / Constants::CellSizeInUnits)),
static_cast<int> (std::floor (point.y()/cellSize))); static_cast<int> (std::floor (point.y() / Constants::CellSizeInUnits)));
return cellCoordinates.getId (mWorldspace); return cellCoordinates.getId (mWorldspace);
} }
CSVRender::Cell* CSVRender::PagedWorldspaceWidget::getCell(const osg::Vec3d& point) const CSVRender::Cell* CSVRender::PagedWorldspaceWidget::getCell(const osg::Vec3d& point) const
{ {
const int cellSize = 8192;
CSMWorld::CellCoordinates coords( CSMWorld::CellCoordinates coords(
static_cast<int> (std::floor (point.x()/cellSize)), static_cast<int> (std::floor (point.x() / Constants::CellSizeInUnits)),
static_cast<int> (std::floor (point.y()/cellSize))); static_cast<int> (std::floor (point.y() / Constants::CellSizeInUnits)));
std::map<CSMWorld::CellCoordinates, Cell*>::const_iterator searchResult = mCells.find(coords); std::map<CSMWorld::CellCoordinates, Cell*>::const_iterator searchResult = mCells.find(coords);
if (searchResult != mCells.end()) if (searchResult != mCells.end())

@ -213,7 +213,7 @@ namespace MWClass
closeSound, 0.5f); closeSound, 0.5f);
// Doors rotate at 90 degrees per second, so start the sound at // Doors rotate at 90 degrees per second, so start the sound at
// where it would be at the current rotation. // where it would be at the current rotation.
float offset = doorRot/(3.14159265f * 0.5f); float offset = doorRot/(osg::PI * 0.5f);
action->setSoundOffset(offset); action->setSoundOffset(offset);
action->setSound(openSound); action->setSound(openSound);
} }
@ -221,7 +221,7 @@ namespace MWClass
{ {
MWBase::Environment::get().getSoundManager()->fadeOutSound3D(ptr, MWBase::Environment::get().getSoundManager()->fadeOutSound3D(ptr,
openSound, 0.5f); openSound, 0.5f);
float offset = 1.0f - doorRot/(3.14159265f * 0.5f); float offset = 1.0f - doorRot/(osg::PI * 0.5f);
action->setSoundOffset(std::max(offset, 0.0f)); action->setSoundOffset(std::max(offset, 0.0f));
action->setSound(closeSound); action->setSound(closeSound);
} }

@ -2,6 +2,7 @@
#include <memory> #include <memory>
#include <components/misc/constants.hpp>
#include <components/misc/rng.hpp> #include <components/misc/rng.hpp>
#include <components/debug/debuglog.hpp> #include <components/debug/debuglog.hpp>
@ -1020,7 +1021,7 @@ namespace MWClass
if(stats.getStance(MWMechanics::CreatureStats::Stance_Run)) if(stats.getStance(MWMechanics::CreatureStats::Stance_Run))
x *= gmst.fJumpRunMultiplier->mValue.getFloat(); x *= gmst.fJumpRunMultiplier->mValue.getFloat();
x *= npcdata->mNpcStats.getFatigueTerm(); x *= npcdata->mNpcStats.getFatigueTerm();
x -= -627.2f;/*gravity constant*/ x -= -Constants::GravityConst * Constants::UnitsPerMeter;
x /= 3.0f; x /= 3.0f;
return x; return x;

@ -1,6 +1,7 @@
#include "weapon.hpp" #include "weapon.hpp"
#include <components/esm/loadweap.hpp> #include <components/esm/loadweap.hpp>
#include <components/misc/constants.hpp>
#include <components/settings/settings.hpp> #include <components/settings/settings.hpp>
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
@ -328,9 +329,9 @@ namespace MWClass
// add reach and attack speed for melee weapon // add reach and attack speed for melee weapon
if (ref->mBase->mData.mType < 9 && Settings::Manager::getBool("show melee info", "Game")) if (ref->mBase->mData.mType < 9 && Settings::Manager::getBool("show melee info", "Game"))
{ {
// 64 game units = 1 yard = 3 ft, display value in feet // display value in feet
const float combatDistance = store.get<ESM::GameSetting>().find("fCombatDistance")->mValue.getFloat() * ref->mBase->mData.mReach; const float combatDistance = store.get<ESM::GameSetting>().find("fCombatDistance")->mValue.getFloat() * ref->mBase->mData.mReach;
text += MWGui::ToolTips::getWeightString(combatDistance*3/64, "#{sRange}"); text += MWGui::ToolTips::getWeightString(combatDistance / Constants::UnitsPerFoot, "#{sRange}");
text += " #{sFeet}"; text += " #{sFeet}";
text += MWGui::ToolTips::getPercentString(ref->mBase->mData.mSpeed, "#{sAttributeSpeed}"); text += MWGui::ToolTips::getPercentString(ref->mBase->mData.mSpeed, "#{sAttributeSpeed}");

@ -33,7 +33,7 @@
namespace namespace
{ {
const int cellSize = 8192; const int cellSize = Constants::CellSizeInUnits;
enum LocalMapWidgetDepth enum LocalMapWidgetDepth
{ {

@ -212,7 +212,7 @@ namespace MWGui
void RaceDialog::onHeadRotate(MyGUI::ScrollBar* scroll, size_t _position) void RaceDialog::onHeadRotate(MyGUI::ScrollBar* scroll, size_t _position)
{ {
float angle = (float(_position) / (scroll->getScrollRange()-1) - 0.5f) * 3.14f * 2; float angle = (float(_position) / (scroll->getScrollRange()-1) - 0.5f) * osg::PI * 2;
mPreview->setAngle (angle); mPreview->setAngle (angle);
mCurrentAngle = angle; mCurrentAngle = angle;

@ -33,9 +33,9 @@ bool MWMechanics::AiAvoidDoor::execute (const MWWorld::Ptr& actor, CharacterCont
float distance = x * x + y * y + z * z; float distance = x * x + y * y + z * z;
if(distance < 10 * 10) { //Got stuck, didn't move if(distance < 10 * 10) { //Got stuck, didn't move
if(mAdjAngle == 0) //Try going in various directions if(mAdjAngle == 0) //Try going in various directions
mAdjAngle = 1.57079632679f; //pi/2 mAdjAngle = osg::PI / 2;
else if (mAdjAngle == 1.57079632679f) else if (mAdjAngle == osg::PI / 2)
mAdjAngle = -1.57079632679f; mAdjAngle = -osg::PI / 2;
else else
mAdjAngle = 0; mAdjAngle = 0;
mDuration = 1; //reset timer mDuration = 1; //reset timer

@ -300,9 +300,8 @@ namespace MWMechanics
bool isWaterCreature = actor.getClass().isPureWaterCreature(actor); bool isWaterCreature = actor.getClass().isPureWaterCreature(actor);
do { do {
// Determine a random location within radius of original position // Determine a random location within radius of original position
const float pi = 3.14159265359f;
const float wanderRadius = (0.2f + Misc::Rng::rollClosedProbability() * 0.8f) * wanderDistance; const float wanderRadius = (0.2f + Misc::Rng::rollClosedProbability() * 0.8f) * wanderDistance;
const float randomDirection = Misc::Rng::rollClosedProbability() * 2.0f * pi; const float randomDirection = Misc::Rng::rollClosedProbability() * 2.0f * osg::PI;
const float destinationX = mInitialActorPosition.x() + wanderRadius * std::cos(randomDirection); const float destinationX = mInitialActorPosition.x() + wanderRadius * std::cos(randomDirection);
const float destinationY = mInitialActorPosition.y() + wanderRadius * std::sin(randomDirection); const float destinationY = mInitialActorPosition.y() + wanderRadius * std::sin(randomDirection);
const float destinationZ = mInitialActorPosition.z(); const float destinationZ = mInitialActorPosition.z();

@ -21,6 +21,7 @@
#include <components/resource/bulletshapemanager.hpp> #include <components/resource/bulletshapemanager.hpp>
#include <components/debug/debuglog.hpp> #include <components/debug/debuglog.hpp>
#include <components/esm/loadgmst.hpp> #include <components/esm/loadgmst.hpp>
#include <components/misc/constants.hpp>
#include <components/sceneutil/positionattitudetransform.hpp> #include <components/sceneutil/positionattitudetransform.hpp>
#include <components/sceneutil/unrefqueue.hpp> #include <components/sceneutil/unrefqueue.hpp>
@ -486,7 +487,7 @@ namespace MWPhysics
physicActor->setInertialForce(osg::Vec3f(0.f, 0.f, 0.f)); physicActor->setInertialForce(osg::Vec3f(0.f, 0.f, 0.f));
else else
{ {
inertia.z() += time * -627.2f; inertia.z() -= time * Constants::GravityConst * Constants::UnitsPerMeter;
if (inertia.z() < 0) if (inertia.z() < 0)
inertia.z() *= slowFall; inertia.z() *= slowFall;
if (slowFall < 1.f) { if (slowFall < 1.f) {

@ -273,9 +273,9 @@ namespace MWRender
void GlobalMap::worldPosToImageSpace(float x, float z, float& imageX, float& imageY) void GlobalMap::worldPosToImageSpace(float x, float z, float& imageX, float& imageY)
{ {
imageX = float(x / 8192.f - mMinX) / (mMaxX - mMinX + 1); imageX = float(x / float(Constants::CellSizeInUnits) - mMinX) / (mMaxX - mMinX + 1);
imageY = 1.f-float(z / 8192.f - mMinY) / (mMaxY - mMinY + 1); imageY = 1.f-float(z / float(Constants::CellSizeInUnits) - mMinY) / (mMaxY - mMinY + 1);
} }
void GlobalMap::cellTopLeftCornerToImageSpace(int x, int y, float& imageX, float& imageY) void GlobalMap::cellTopLeftCornerToImageSpace(int x, int y, float& imageX, float& imageY)

@ -14,6 +14,7 @@
#include <components/debug/debuglog.hpp> #include <components/debug/debuglog.hpp>
#include <components/esm/fogstate.hpp> #include <components/esm/fogstate.hpp>
#include <components/esm/loadcell.hpp> #include <components/esm/loadcell.hpp>
#include <components/misc/constants.hpp>
#include <components/settings/settings.hpp> #include <components/settings/settings.hpp>
#include <components/sceneutil/visitor.hpp> #include <components/sceneutil/visitor.hpp>
#include <components/files/memorystream.hpp> #include <components/files/memorystream.hpp>
@ -71,7 +72,7 @@ namespace MWRender
LocalMap::LocalMap(osg::Group* root) LocalMap::LocalMap(osg::Group* root)
: mRoot(root) : mRoot(root)
, mMapResolution(Settings::Manager::getInt("local map resolution", "Map")) , mMapResolution(Settings::Manager::getInt("local map resolution", "Map"))
, mMapWorldSize(8192.f) , mMapWorldSize(Constants::CellSizeInUnits)
, mCellDistance(Settings::Manager::getInt("local map cell distance", "Map")) , mCellDistance(Settings::Manager::getInt("local map cell distance", "Map"))
, mAngle(0.f) , mAngle(0.f)
, mInterior(false) , mInterior(false)

@ -27,6 +27,8 @@
#include <components/sceneutil/waterutil.hpp> #include <components/sceneutil/waterutil.hpp>
#include <components/misc/constants.hpp>
#include <components/nifosg/controller.hpp> #include <components/nifosg/controller.hpp>
#include <components/shader/shadermanager.hpp> #include <components/shader/shadermanager.hpp>
@ -401,7 +403,7 @@ Water::Water(osg::Group *parent, osg::Group* sceneRoot, Resource::ResourceSystem
{ {
mSimulation.reset(new RippleSimulation(parent, resourceSystem, fallback)); mSimulation.reset(new RippleSimulation(parent, resourceSystem, fallback));
mWaterGeom = SceneUtil::createWaterGeometry(CELL_SIZE*150, 40, 900); mWaterGeom = SceneUtil::createWaterGeometry(Constants::CellSizeInUnits*150, 40, 900);
mWaterGeom->setDrawCallback(new DepthClampCallback); mWaterGeom->setDrawCallback(new DepthClampCallback);
mWaterGeom->setNodeMask(Mask_Water); mWaterGeom->setNodeMask(Mask_Water);
@ -679,7 +681,8 @@ bool Water::isUnderwater(const osg::Vec3f &pos) const
osg::Vec3f Water::getSceneNodeCoordinates(int gridX, int gridY) osg::Vec3f Water::getSceneNodeCoordinates(int gridX, int gridY)
{ {
return osg::Vec3f(static_cast<float>(gridX * CELL_SIZE + (CELL_SIZE / 2)), static_cast<float>(gridY * CELL_SIZE + (CELL_SIZE / 2)), mTop); return osg::Vec3f(static_cast<float>(gridX * Constants::CellSizeInUnits + (Constants::CellSizeInUnits / 2)),
static_cast<float>(gridY * Constants::CellSizeInUnits + (Constants::CellSizeInUnits / 2)), mTop);
} }
void Water::addEmitter (const MWWorld::Ptr& ptr, float scale, float force) void Water::addEmitter (const MWWorld::Ptr& ptr, float scale, float force)

@ -50,8 +50,6 @@ namespace MWRender
/// Water rendering /// Water rendering
class Water class Water
{ {
static const int CELL_SIZE = 8192;
osg::ref_ptr<osg::Uniform> mRainIntensityUniform; osg::ref_ptr<osg::Uniform> mRainIntensityUniform;
osg::ref_ptr<osg::Group> mParent; osg::ref_ptr<osg::Group> mParent;

@ -8,6 +8,7 @@
#include <stdint.h> #include <stdint.h>
#include <components/debug/debuglog.hpp> #include <components/debug/debuglog.hpp>
#include <components/misc/constants.hpp>
#include <components/vfs/manager.hpp> #include <components/vfs/manager.hpp>
#include <OpenThreads/Thread> #include <OpenThreads/Thread>
@ -34,10 +35,6 @@
namespace namespace
{ {
// The game uses 64 units per yard, or approximately 69.99125109 units per meter.
// Should this be defined publically somewhere?
const float UnitsPerMeter = 69.99125109f;
const int sLoudnessFPS = 20; // loudness values per second of audio const int sLoudnessFPS = 20; // loudness values per second of audio
ALCenum checkALCError(ALCdevice *device, const char *func, int line) ALCenum checkALCError(ALCdevice *device, const char *func, int line)
@ -818,13 +815,13 @@ bool OpenAL_Output::init(const std::string &devname, const std::string &hrtfname
LoadEffect(mWaterEffect, EFX_REVERB_PRESET_UNDERWATER); LoadEffect(mWaterEffect, EFX_REVERB_PRESET_UNDERWATER);
} }
alListenerf(AL_METERS_PER_UNIT, 1.0f / UnitsPerMeter); alListenerf(AL_METERS_PER_UNIT, 1.0f / Constants::UnitsPerMeter);
} }
skip_efx: skip_efx:
alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
// Speed of sound is in units per second. Given the default speed of sound is 343.3 (assumed // Speed of sound is in units per second. Take the sound speed in air (assumed
// meters per second), multiply by the units per meter to get the speed in u/s. // meters per second), multiply by the units per meter to get the speed in u/s.
alSpeedOfSound(343.3f * UnitsPerMeter); alSpeedOfSound(Constants::SoundSpeedInAir * Constants::UnitsPerMeter);
alGetError(); alGetError();
mInitialized = true; mInitialized = true;
@ -1400,8 +1397,7 @@ void OpenAL_Output::updateListener(const osg::Vec3f &pos, const osg::Vec3f &atdi
if(env != mListenerEnv) if(env != mListenerEnv)
{ {
// Speed of sound in water is 1484m/s, and in air is 343.3m/s (roughly) alSpeedOfSound(((env == Env_Underwater) ? Constants::SoundSpeedUnderwater : Constants::SoundSpeedInAir) * Constants::UnitsPerMeter);
alSpeedOfSound(((env == Env_Underwater) ? 1484.0f : 343.3f) * UnitsPerMeter);
// Update active sources with the environment's direct filter // Update active sources with the environment's direct filter
if(mWaterFilter) if(mWaterFilter)

@ -10,6 +10,8 @@
#include <components/esm/esmwriter.hpp> #include <components/esm/esmwriter.hpp>
#include <components/esm/projectilestate.hpp> #include <components/esm/projectilestate.hpp>
#include <components/misc/constants.hpp>
#include <components/resource/resourcesystem.hpp> #include <components/resource/resourcesystem.hpp>
#include <components/resource/scenemanager.hpp> #include <components/resource/scenemanager.hpp>
@ -460,7 +462,7 @@ namespace MWWorld
{ {
// gravity constant - must be way lower than the gravity affecting actors, since we're not // gravity constant - must be way lower than the gravity affecting actors, since we're not
// simulating aerodynamics at all // simulating aerodynamics at all
it->mVelocity -= osg::Vec3f(0, 0, 627.2f * 0.1f) * duration; it->mVelocity -= osg::Vec3f(0, 0, Constants::GravityConst * Constants::UnitsPerMeter * 0.1f) * duration;
osg::Vec3f pos(it->mNode->getPosition()); osg::Vec3f pos(it->mNode->getPosition());
osg::Vec3f newPos = pos + it->mVelocity * duration; osg::Vec3f newPos = pos + it->mVelocity * duration;

@ -345,7 +345,7 @@ namespace MWWorld
getGridCenter(cellX, cellY); getGridCenter(cellX, cellY);
float centerX, centerY; float centerX, centerY;
MWBase::Environment::get().getWorld()->indexToPosition(cellX, cellY, centerX, centerY, true); MWBase::Environment::get().getWorld()->indexToPosition(cellX, cellY, centerX, centerY, true);
const float maxDistance = 8192/2 + mCellLoadingThreshold; // 1/2 cell size + threshold const float maxDistance = Constants::CellSizeInUnits / 2 + mCellLoadingThreshold; // 1/2 cell size + threshold
float distance = std::max(std::abs(centerX-pos.x()), std::abs(centerY-pos.y())); float distance = std::max(std::abs(centerX-pos.x()), std::abs(centerY-pos.y()));
if (distance > maxDistance) if (distance > maxDistance)
{ {
@ -793,7 +793,7 @@ namespace MWWorld
float dist = std::max(std::abs(thisCellCenterX - playerPos.x()), std::abs(thisCellCenterY - playerPos.y())); float dist = std::max(std::abs(thisCellCenterX - playerPos.x()), std::abs(thisCellCenterY - playerPos.y()));
dist = std::min(dist,std::max(std::abs(thisCellCenterX - predictedPos.x()), std::abs(thisCellCenterY - predictedPos.y()))); dist = std::min(dist,std::max(std::abs(thisCellCenterX - predictedPos.x()), std::abs(thisCellCenterY - predictedPos.y())));
float loadDist = 8192/2 + 8192 - mCellLoadingThreshold + mPreloadDistance; float loadDist = Constants::CellSizeInUnits / 2 + Constants::CellSizeInUnits - mCellLoadingThreshold + mPreloadDistance;
if (dist < loadDist) if (dist < loadDist)
preloadCell(MWBase::Environment::get().getWorld()->getExterior(cellX+dx, cellY+dy)); preloadCell(MWBase::Environment::get().getWorld()->getExterior(cellX+dx, cellY+dy));

@ -9,6 +9,7 @@
#include <components/esm/esmwriter.hpp> #include <components/esm/esmwriter.hpp>
#include <components/esm/cellid.hpp> #include <components/esm/cellid.hpp>
#include <components/misc/constants.hpp>
#include <components/misc/resourcehelpers.hpp> #include <components/misc/resourcehelpers.hpp>
#include <components/misc/rng.hpp> #include <components/misc/rng.hpp>
@ -260,7 +261,7 @@ namespace MWWorld
if (!getPlayerPtr().isInCell()) if (!getPlayerPtr().isInCell())
{ {
ESM::Position pos; ESM::Position pos;
const int cellSize = 8192; const int cellSize = Constants::CellSizeInUnits;
pos.pos[0] = cellSize/2; pos.pos[0] = cellSize/2;
pos.pos[1] = cellSize/2; pos.pos[1] = cellSize/2;
pos.pos[2] = 0; pos.pos[2] = 0;
@ -1434,7 +1435,7 @@ namespace MWWorld
void World::indexToPosition (int cellX, int cellY, float &x, float &y, bool centre) const void World::indexToPosition (int cellX, int cellY, float &x, float &y, bool centre) const
{ {
const int cellSize = 8192; const int cellSize = Constants::CellSizeInUnits;
x = static_cast<float>(cellSize * cellX); x = static_cast<float>(cellSize * cellX);
y = static_cast<float>(cellSize * cellY); y = static_cast<float>(cellSize * cellY);
@ -1448,10 +1449,8 @@ namespace MWWorld
void World::positionToIndex (float x, float y, int &cellX, int &cellY) const void World::positionToIndex (float x, float y, int &cellX, int &cellY) const
{ {
const int cellSize = 8192; cellX = static_cast<int>(std::floor(x / Constants::CellSizeInUnits));
cellY = static_cast<int>(std::floor(y / Constants::CellSizeInUnits));
cellX = static_cast<int>(std::floor(x / cellSize));
cellY = static_cast<int>(std::floor(y / cellSize));
} }
void World::queueMovement(const Ptr &ptr, const osg::Vec3f &velocity) void World::queueMovement(const Ptr &ptr, const osg::Vec3f &velocity)
@ -3245,9 +3244,9 @@ namespace MWWorld
float World::feetToGameUnits(float feet) float World::feetToGameUnits(float feet)
{ {
// Looks like there is no GMST for this. This factor was determined in experiments // Original engine rounds size upward
// with the Telekinesis effect. static const int unitsPerFoot = ceil(Constants::UnitsPerFoot);
return feet * 22; return feet * unitsPerFoot;
} }
float World::getActivationDistancePlusTelekinesis() float World::getActivationDistancePlusTelekinesis()

@ -85,7 +85,7 @@ add_component_dir (esmterrain
) )
add_component_dir (misc add_component_dir (misc
utf8stream stringops resourcehelpers rng messageformatparser constants utf8stream stringops resourcehelpers rng messageformatparser
) )
add_component_dir (debug add_component_dir (debug

@ -3,6 +3,8 @@
#include <stdint.h> #include <stdint.h>
#include <components/misc/constants.hpp>
#include "esmcommon.hpp" #include "esmcommon.hpp"
namespace ESM namespace ESM
@ -53,7 +55,7 @@ struct Land
static const int LAND_SIZE = 65; static const int LAND_SIZE = 65;
// cell terrain size in world coords // cell terrain size in world coords
static const int REAL_SIZE = 8192; static const int REAL_SIZE = Constants::CellSizeInUnits;
// total number of vertices // total number of vertices
static const int LAND_NUM_VERTS = LAND_SIZE * LAND_SIZE; static const int LAND_NUM_VERTS = LAND_SIZE * LAND_SIZE;

@ -267,8 +267,8 @@ namespace ESMTerrain
height = heightData->mHeights[col*ESM::Land::LAND_SIZE + row]; height = heightData->mHeights[col*ESM::Land::LAND_SIZE + row];
(*positions)[static_cast<unsigned int>(vertX*numVerts + vertY)] (*positions)[static_cast<unsigned int>(vertX*numVerts + vertY)]
= osg::Vec3f((vertX / float(numVerts - 1) - 0.5f) * size * 8192, = osg::Vec3f((vertX / float(numVerts - 1) - 0.5f) * size * Constants::CellSizeInUnits,
(vertY / float(numVerts - 1) - 0.5f) * size * 8192, (vertY / float(numVerts - 1) - 0.5f) * size * Constants::CellSizeInUnits,
height); height);
if (normalData) if (normalData)
@ -477,8 +477,8 @@ namespace ESMTerrain
float Storage::getHeightAt(const osg::Vec3f &worldPos) float Storage::getHeightAt(const osg::Vec3f &worldPos)
{ {
int cellX = static_cast<int>(std::floor(worldPos.x() / 8192.f)); int cellX = static_cast<int>(std::floor(worldPos.x() / float(Constants::CellSizeInUnits)));
int cellY = static_cast<int>(std::floor(worldPos.y() / 8192.f)); int cellY = static_cast<int>(std::floor(worldPos.y() / float(Constants::CellSizeInUnits)));
osg::ref_ptr<const LandObject> land = getLand(cellX, cellY); osg::ref_ptr<const LandObject> land = getLand(cellX, cellY);
if (!land) if (!land)
@ -491,8 +491,8 @@ namespace ESMTerrain
// Mostly lifted from Ogre::Terrain::getHeightAtTerrainPosition // Mostly lifted from Ogre::Terrain::getHeightAtTerrainPosition
// Normalized position in the cell // Normalized position in the cell
float nX = (worldPos.x() - (cellX * 8192))/8192.f; float nX = (worldPos.x() - (cellX * Constants::CellSizeInUnits)) / float(Constants::CellSizeInUnits);
float nY = (worldPos.y() - (cellY * 8192))/8192.f; float nY = (worldPos.y() - (cellY * Constants::CellSizeInUnits)) / float(Constants::CellSizeInUnits);
// get left / bottom points (rounded down) // get left / bottom points (rounded down)
float factor = ESM::Land::LAND_SIZE - 1.0f; float factor = ESM::Land::LAND_SIZE - 1.0f;
@ -524,10 +524,10 @@ namespace ESMTerrain
*/ */
// Build all 4 positions in normalized cell space, using point-sampled height // Build all 4 positions in normalized cell space, using point-sampled height
osg::Vec3f v0 (startXTS, startYTS, getVertexHeight(data, startX, startY) / 8192.f); osg::Vec3f v0 (startXTS, startYTS, getVertexHeight(data, startX, startY) / float(Constants::CellSizeInUnits));
osg::Vec3f v1 (endXTS, startYTS, getVertexHeight(data, endX, startY) / 8192.f); osg::Vec3f v1 (endXTS, startYTS, getVertexHeight(data, endX, startY) / float(Constants::CellSizeInUnits));
osg::Vec3f v2 (endXTS, endYTS, getVertexHeight(data, endX, endY) / 8192.f); osg::Vec3f v2 (endXTS, endYTS, getVertexHeight(data, endX, endY) / float(Constants::CellSizeInUnits));
osg::Vec3f v3 (startXTS, endYTS, getVertexHeight(data, startX, endY) / 8192.f); osg::Vec3f v3 (startXTS, endYTS, getVertexHeight(data, startX, endY) / float(Constants::CellSizeInUnits));
// define this plane in terrain space // define this plane in terrain space
osg::Plane plane; osg::Plane plane;
// FIXME: deal with differing triangle alignment // FIXME: deal with differing triangle alignment
@ -555,7 +555,7 @@ namespace ESMTerrain
// Solve plane equation for z // Solve plane equation for z
return (-plane.getNormal().x() * nX return (-plane.getNormal().x() * nX
-plane.getNormal().y() * nY -plane.getNormal().y() * nY
- plane[3]) / plane.getNormal().z() * 8192; - plane[3]) / plane.getNormal().z() * Constants::CellSizeInUnits;
} }

@ -0,0 +1,27 @@
#ifndef OPENMW_CONSTANTS_H
#define OPENMW_CONSTANTS_H
namespace Constants
{
// The game uses 64 units per yard
const float UnitsPerMeter = 69.99125109f;
const float UnitsPerFoot = 21.33333333f;
// Sound speed in meters per second
const float SoundSpeedInAir = 343.3f;
const float SoundSpeedUnderwater = 1484.0f;
// Gravity constant in m/sec^2
// Note: 8.96 m/sec^2 = 9.8 yards/sec^2
// Probaly original engine's developers just forgot
// that their engine uses yards instead of meters
// and used standart gravity value as it is
const float GravityConst = 8.96f;
// Size of one exterior cell in game units
const int CellSizeInUnits = 8192;
}
#endif

@ -4,6 +4,8 @@
#include <sstream> #include <sstream>
#include <components/misc/constants.hpp>
#include "quadtreenode.hpp" #include "quadtreenode.hpp"
#include "storage.hpp" #include "storage.hpp"
#include "viewdata.hpp" #include "viewdata.hpp"
@ -81,7 +83,7 @@ public:
{ {
float dist = distanceToBox(node->getBoundingBox(), eyePoint); float dist = distanceToBox(node->getBoundingBox(), eyePoint);
int nativeLodLevel = Log2(static_cast<unsigned int>(node->getSize()/mMinSize)); int nativeLodLevel = Log2(static_cast<unsigned int>(node->getSize()/mMinSize));
int lodLevel = Log2(static_cast<unsigned int>(dist/(8192*mMinSize))); int lodLevel = Log2(static_cast<unsigned int>(dist/(Constants::CellSizeInUnits*mMinSize)));
return nativeLodLevel <= lodLevel; return nativeLodLevel <= lodLevel;
} }

Loading…
Cancel
Save