1
0
Fork 0
mirror of https://github.com/OpenMW/openmw.git synced 2025-11-30 12:34:30 +00:00

Address more engine conversion warnings

This commit is contained in:
Evil Eye 2025-09-21 23:21:08 +02:00
parent bcad4a7fd5
commit 478df08433
112 changed files with 476 additions and 503 deletions

View file

@ -319,7 +319,7 @@ bool OMW::Engine::frame(unsigned frameNumber, float frametime)
const bool reportResource = stats->collectStats("resource"); const bool reportResource = stats->collectStats("resource");
if (reportResource) if (reportResource)
stats->setAttribute(frameNumber, "UnrefQueue", mUnrefQueue->getSize()); stats->setAttribute(frameNumber, "UnrefQueue", static_cast<double>(mUnrefQueue->getSize()));
mUnrefQueue->flush(*mWorkQueue); mUnrefQueue->flush(*mWorkQueue);
@ -329,8 +329,8 @@ bool OMW::Engine::frame(unsigned frameNumber, float frametime)
mResourceSystem->reportStats(frameNumber, stats); mResourceSystem->reportStats(frameNumber, stats);
stats->setAttribute(frameNumber, "WorkQueue", mWorkQueue->getNumItems()); stats->setAttribute(frameNumber, "WorkQueue", static_cast<double>(mWorkQueue->getNumItems()));
stats->setAttribute(frameNumber, "WorkThread", mWorkQueue->getNumActiveThreads()); stats->setAttribute(frameNumber, "WorkThread", static_cast<double>(mWorkQueue->getNumActiveThreads()));
mMechanicsManager->reportStats(frameNumber, *stats); mMechanicsManager->reportStats(frameNumber, *stats);
mWorld->reportStats(frameNumber, *stats); mWorld->reportStats(frameNumber, *stats);
@ -740,7 +740,8 @@ void OMW::Engine::prepareEngine()
mResourceSystem->getSceneManager()->setUnRefImageDataAfterApply( mResourceSystem->getSceneManager()->setUnRefImageDataAfterApply(
false); // keep to Off for now to allow better state sharing false); // keep to Off for now to allow better state sharing
mResourceSystem->getSceneManager()->setFilterSettings(Settings::general().mTextureMagFilter, mResourceSystem->getSceneManager()->setFilterSettings(Settings::general().mTextureMagFilter,
Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap, Settings::general().mAnisotropy); Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap,
static_cast<float>(Settings::general().mAnisotropy));
mEnvironment.setResourceSystem(*mResourceSystem); mEnvironment.setResourceSystem(*mResourceSystem);
mWorkQueue = new SceneUtil::WorkQueue(Settings::cells().mPreloadNumThreads); mWorkQueue = new SceneUtil::WorkQueue(Settings::cells().mPreloadNumThreads);
@ -1039,7 +1040,7 @@ void OMW::Engine::go()
const unsigned frameNumber = mViewer->getFrameStamp()->getFrameNumber(); const unsigned frameNumber = mViewer->getFrameStamp()->getFrameNumber();
if (!frame(frameNumber, dt)) if (!frame(frameNumber, static_cast<float>(dt)))
{ {
std::this_thread::sleep_for(std::chrono::milliseconds(5)); std::this_thread::sleep_for(std::chrono::milliseconds(5));
continue; continue;

View file

@ -100,7 +100,7 @@ namespace MWBase
/// @note Controlled by an option, gets discarded when dialogue ends by default /// @note Controlled by an option, gets discarded when dialogue ends by default
virtual void applyBarterDispositionChange(int delta) = 0; virtual void applyBarterDispositionChange(int delta) = 0;
virtual int countSavedGameRecords() const = 0; virtual size_t countSavedGameRecords() const = 0;
virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) const = 0;

View file

@ -86,7 +86,7 @@ namespace MWBase
virtual std::string getControllerButtonIcon(int button) = 0; virtual std::string getControllerButtonIcon(int button) = 0;
virtual std::string getControllerAxisIcon(int axis) = 0; virtual std::string getControllerAxisIcon(int axis) = 0;
virtual int countSavedGameRecords() const = 0; virtual size_t countSavedGameRecords() const = 0;
virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0;
virtual void readRecord(ESM::ESMReader& reader, uint32_t type) = 0; virtual void readRecord(ESM::ESMReader& reader, uint32_t type) = 0;

View file

@ -74,7 +74,7 @@ namespace MWBase
virtual const TQuestContainer& getQuests() const = 0; virtual const TQuestContainer& getQuests() const = 0;
virtual int countSavedGameRecords() const = 0; virtual size_t countSavedGameRecords() const = 0;
virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) const = 0;

View file

@ -141,7 +141,7 @@ namespace MWBase
virtual void setupPlayer(const MWWorld::Ptr&) = 0; virtual void setupPlayer(const MWWorld::Ptr&) = 0;
// Saving // Saving
int countSavedGameRecords() const { return 1; } size_t countSavedGameRecords() const { return 1; }
virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0;
virtual void saveLocalScripts(const MWWorld::Ptr& ptr, ESM::LuaScripts& data) = 0; virtual void saveLocalScripts(const MWWorld::Ptr& ptr, ESM::LuaScripts& data) = 0;

View file

@ -245,7 +245,7 @@ namespace MWBase
virtual void playerLoaded() = 0; virtual void playerLoaded() = 0;
virtual int countSavedGameRecords() const = 0; virtual size_t countSavedGameRecords() const = 0;
virtual void write(ESM::ESMWriter& writer, Loading::Listener& listener) const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& listener) const = 0;

View file

@ -311,7 +311,7 @@ namespace MWBase
virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& progress) = 0;
virtual void readRecord(ESM::ESMReader& reader, uint32_t type) = 0; virtual void readRecord(ESM::ESMReader& reader, uint32_t type) = 0;
virtual int countSavedGameRecords() const = 0; virtual size_t countSavedGameRecords() const = 0;
/// Does the current stack of GUI-windows permit saving? /// Does the current stack of GUI-windows permit saving?
virtual bool isSavingAllowed() const = 0; virtual bool isSavingAllowed() const = 0;

View file

@ -120,7 +120,7 @@ namespace MWBase
World() {} World() {}
virtual ~World() {} virtual ~World() = default;
virtual void setRandomSeed(uint32_t seed) = 0; virtual void setRandomSeed(uint32_t seed) = 0;
///< \param seed The seed used when starting a new game. ///< \param seed The seed used when starting a new game.
@ -130,8 +130,8 @@ namespace MWBase
virtual void clear() = 0; virtual void clear() = 0;
virtual int countSavedGameRecords() const = 0; virtual size_t countSavedGameRecords() const = 0;
virtual int countSavedGameCells() const = 0; virtual size_t countSavedGameCells() const = 0;
virtual void write(ESM::ESMWriter& writer, Loading::Listener& listener) const = 0; virtual void write(ESM::ESMWriter& writer, Loading::Listener& listener) const = 0;

View file

@ -653,7 +653,7 @@ namespace MWDialogue
return info != nullptr; return info != nullptr;
} }
int DialogueManager::countSavedGameRecords() const size_t DialogueManager::countSavedGameRecords() const
{ {
return 1; // known topics return 1; // known topics
} }

View file

@ -112,7 +112,7 @@ namespace MWDialogue
/// @note Controlled by an option, gets discarded when dialogue ends by default /// @note Controlled by an option, gets discarded when dialogue ends by default
void applyBarterDispositionChange(int delta) override; void applyBarterDispositionChange(int delta) override;
int countSavedGameRecords() const override; size_t countSavedGameRecords() const override;
void write(ESM::ESMWriter& writer, Loading::Listener& progress) const override; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const override;

View file

@ -151,7 +151,7 @@ namespace MWDialogue
return iter->second.getIndex(); return iter->second.getIndex();
} }
int Journal::countSavedGameRecords() const size_t Journal::countSavedGameRecords() const
{ {
std::size_t count = mQuests.size(); std::size_t count = mQuests.size();
@ -163,7 +163,7 @@ namespace MWDialogue
for (const auto& [_, topic] : mTopics) for (const auto& [_, topic] : mTopics)
count += topic.size(); count += topic.size();
return static_cast<int>(count); return count;
} }
void Journal::write(ESM::ESMWriter& writer, Loading::Listener& progress) const void Journal::write(ESM::ESMWriter& writer, Loading::Listener& progress) const

View file

@ -53,7 +53,7 @@ namespace MWDialogue
const TQuestContainer& getQuests() const override { return mQuests; } const TQuestContainer& getQuests() const override { return mQuests; }
int countSavedGameRecords() const override; size_t countSavedGameRecords() const override;
void write(ESM::ESMWriter& writer, Loading::Listener& progress) const override; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const override;

View file

@ -670,7 +670,7 @@ namespace MWGui
{ {
int top = mLine ? mLine->mRect.top : mBook->mRect.bottom; int top = mLine ? mLine->mRect.top : mBook->mRect.bottom;
append_run(i->mStyle, i->mBegin, i->mEnd, 0, left + i->mWidth, top + fontHeight); appendRun(i->mStyle, i->mBegin, i->mEnd, 0, left + i->mWidth, top + fontHeight);
left = mLine->mRect.right; left = mLine->mRect.right;
} }
@ -679,8 +679,8 @@ namespace MWGui
for (PartialTextConstIterator i = mPartialWord.begin(); i != mPartialWord.end(); ++i) for (PartialTextConstIterator i = mPartialWord.begin(); i != mPartialWord.end(); ++i)
{ {
int top = mLine ? mLine->mRect.top : mBook->mRect.bottom; int top = mLine ? mLine->mRect.top : mBook->mRect.bottom;
const int numChars = static_cast<int>(i->mEnd - i->mBegin);
append_run(i->mStyle, i->mBegin, i->mEnd, i->mEnd - i->mBegin, left + i->mWidth, top + fontHeight); appendRun(i->mStyle, i->mBegin, i->mEnd, numChars, left + i->mWidth, top + fontHeight);
left = mLine->mRect.right; left = mLine->mRect.right;
} }
@ -689,7 +689,7 @@ namespace MWGui
mPartialWord.clear(); mPartialWord.clear();
} }
void append_run(StyleImpl* style, Utf8Stream::Point begin, Utf8Stream::Point end, int pc, int right, int bottom) void appendRun(StyleImpl* style, Utf8Stream::Point begin, Utf8Stream::Point end, int pc, int right, int bottom)
{ {
if (mSection == nullptr) if (mSection == nullptr)
{ {

View file

@ -151,7 +151,7 @@ namespace MWGui
mReviewDialog->onFrame(duration); mReviewDialog->onFrame(duration);
} }
void CharacterCreation::spawnDialog(const char id) void CharacterCreation::spawnDialog(const GuiMode id)
{ {
try try
{ {

View file

@ -7,6 +7,7 @@
#include <memory> #include <memory>
#include <vector> #include <vector>
#include "mode.hpp"
#include "statswatcher.hpp" #include "statswatcher.hpp"
namespace osg namespace osg
@ -42,7 +43,7 @@ namespace MWGui
virtual ~CharacterCreation(); virtual ~CharacterCreation();
// Show a dialog // Show a dialog
void spawnDialog(const char id); void spawnDialog(const GuiMode id);
void setAttribute(ESM::RefId id, const MWMechanics::AttributeValue& value) override; void setAttribute(ESM::RefId id, const MWMechanics::AttributeValue& value) override;
void setValue(std::string_view id, const MWMechanics::DynamicStat<float>& value) override; void setValue(std::string_view id, const MWMechanics::DynamicStat<float>& value) override;

View file

@ -14,9 +14,9 @@ namespace MWGui
: WindowBase("openmw_inventory_tabs.layout") : WindowBase("openmw_inventory_tabs.layout")
{ {
MyGUI::Button* tab; MyGUI::Button* tab;
static const char* kTabIds[] = { "TabMap", "TabInventory", "TabSpells", "TabStats" }; constexpr std::string_view kTabIds[] = { "TabMap", "TabInventory", "TabSpells", "TabStats" };
for (const char* id : kTabIds) for (const std::string_view id : kTabIds)
{ {
getWidget(tab, id); getWidget(tab, id);
tab->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryTabsOverlay::onTabClicked); tab->eventMouseButtonClick += MyGUI::newDelegate(this, &InventoryTabsOverlay::onTabClicked);
@ -44,7 +44,7 @@ namespace MWGui
if (!MWBase::Environment::get().getWindowManager()->getJournalAllowed()) if (!MWBase::Environment::get().getWindowManager()->getJournalAllowed())
return; return;
for (int i = 0; i < static_cast<int>(mTabs.size()); i++) for (size_t i = 0; i < mTabs.size(); ++i)
{ {
if (mTabs[i] == sender) if (mTabs[i] == sender)
{ {
@ -55,9 +55,9 @@ namespace MWGui
} }
} }
void InventoryTabsOverlay::setTab(int index) void InventoryTabsOverlay::setTab(size_t index)
{ {
for (int i = 0; i < static_cast<int>(mTabs.size()); i++) for (size_t i = 0; i < mTabs.size(); ++i)
mTabs[i]->setStateSelected(i == index); mTabs[i]->setStateSelected(i == index);
} }
} }

View file

@ -16,7 +16,7 @@ namespace MWGui
InventoryTabsOverlay(); InventoryTabsOverlay();
int getHeight(); int getHeight();
void setTab(int index); void setTab(size_t index);
private: private:
std::vector<MyGUI::Button*> mTabs; std::vector<MyGUI::Button*> mTabs;

View file

@ -748,10 +748,10 @@ namespace MWGui
{ {
MWWorld::Ptr player = MWMechanics::getPlayer(); MWWorld::Ptr player = MWMechanics::getPlayer();
float capacity = player.getClass().getCapacity(player); int capacity = static_cast<int>(player.getClass().getCapacity(player));
float encumbrance = player.getClass().getEncumbrance(player); float encumbrance = player.getClass().getEncumbrance(player);
mTradeModel->adjustEncumbrance(encumbrance); mTradeModel->adjustEncumbrance(encumbrance);
mEncumbranceBar->setValue(std::ceil(encumbrance), static_cast<int>(capacity)); mEncumbranceBar->setValue(static_cast<int>(std::ceil(encumbrance)), capacity);
} }
void InventoryWindow::onFrame(float dt) void InventoryWindow::onFrame(float dt)

View file

@ -172,11 +172,8 @@ namespace MWGui
mModel->mKeywordSearch.highlightKeywords(utf8text.begin(), utf8text.end(), matches); mModel->mKeywordSearch.highlightKeywords(utf8text.begin(), utf8text.end(), matches);
std::string::const_iterator i = utf8text.begin(); std::string::const_iterator i = utf8text.begin();
for (std::vector<KeywordSearchT::Match>::const_iterator it = matches.begin(); it != matches.end(); for (const KeywordSearchT::Match& match : matches)
++it)
{ {
const KeywordSearchT::Match& match = *it;
if (i != match.mBeg) if (i != match.mBeg)
visitor(0, i - utf8text.begin(), match.mBeg - utf8text.begin()); visitor(0, i - utf8text.begin(), match.mBeg - utf8text.begin());

View file

@ -209,8 +209,7 @@ namespace MWGui
{ {
if (!mSplashScreens.empty()) if (!mSplashScreens.empty())
{ {
std::string const& randomSplash std::string const& randomSplash = mSplashScreens.at(Misc::Rng::rollDice(mSplashScreens.size()));
= mSplashScreens.at(Misc::Rng::rollDice(static_cast<int>(mSplashScreens.size())));
// TODO: add option (filename pattern?) to use image aspect ratio instead of 4:3 // TODO: add option (filename pattern?) to use image aspect ratio instead of 4:3
// we can't do this by default, because the Morrowind splash screens are 1024x1024, but should be displayed // we can't do this by default, because the Morrowind splash screens are 1024x1024, but should be displayed

View file

@ -1004,7 +1004,8 @@ namespace MWGui
for (auto& [marker, col] : mGlobalMapMarkers) for (auto& [marker, col] : mGlobalMapMarkers)
{ {
marker.widget->setCoord(createMarkerCoords(marker.position.x(), marker.position.y(), col.size())); marker.widget->setCoord(
createMarkerCoords(marker.position.x(), marker.position.y(), static_cast<float>(col.size())));
marker.widget->setVisible(marker.widget->getHeight() >= 6); marker.widget->setVisible(marker.widget->getHeight() >= 6);
} }
} }
@ -1036,10 +1037,10 @@ namespace MWGui
// Restore the window to pinned size. // Restore the window to pinned size.
MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(); MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>();
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize(); MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
const float x = Settings::windows().mMapX * viewSize.width; const int x = static_cast<int>(Settings::windows().mMapX * viewSize.width);
const float y = Settings::windows().mMapY * viewSize.height; const int y = static_cast<int>(Settings::windows().mMapY * viewSize.height);
const float w = Settings::windows().mMapW * viewSize.width; const int w = static_cast<int>(Settings::windows().mMapW * viewSize.width);
const float h = Settings::windows().mMapH * viewSize.height; const int h = static_cast<int>(Settings::windows().mMapH * viewSize.height);
window->setCoord(x, y, w, h); window->setCoord(x, y, w, h);
} }
} }
@ -1063,10 +1064,10 @@ namespace MWGui
worldPosToGlobalMapImageSpace( worldPosToGlobalMapImageSpace(
(x + 0.5f) * Constants::CellSizeInUnits, (y + 0.5f) * Constants::CellSizeInUnits, worldX, worldY); (x + 0.5f) * Constants::CellSizeInUnits, (y + 0.5f) * Constants::CellSizeInUnits, worldX, worldY);
const float markerSize = getMarkerSize(agregatedWeight); const float markerSize = getMarkerSize(static_cast<size_t>(agregatedWeight));
const float halfMarkerSize = markerSize / 2.0f; const float halfMarkerSize = markerSize / 2.0f;
return MyGUI::IntCoord(static_cast<int>(worldX - halfMarkerSize), static_cast<int>(worldY - halfMarkerSize), return MyGUI::IntCoord(static_cast<int>(worldX - halfMarkerSize), static_cast<int>(worldY - halfMarkerSize),
markerSize, markerSize); static_cast<int>(markerSize), static_cast<int>(markerSize));
} }
MyGUI::Widget* MapWindow::createMarker(const std::string& name, float x, float y, float agregatedWeight) MyGUI::Widget* MapWindow::createMarker(const std::string& name, float x, float y, float agregatedWeight)
@ -1075,7 +1076,7 @@ namespace MWGui
"MarkerButton", createMarkerCoords(x, y, agregatedWeight), MyGUI::Align::Default); "MarkerButton", createMarkerCoords(x, y, agregatedWeight), MyGUI::Align::Default);
markerWidget->setVisible(markerWidget->getHeight() >= 6.0); markerWidget->setVisible(markerWidget->getHeight() >= 6.0);
markerWidget->setUserString("Caption_TextOneLine", "#{sCell=" + name + "}"); markerWidget->setUserString("Caption_TextOneLine", "#{sCell=" + name + "}");
setGlobalMapMarkerTooltip(markerWidget, x, y); setGlobalMapMarkerTooltip(markerWidget, static_cast<int>(x), static_cast<int>(y));
markerWidget->setUserString("ToolTipLayout", "TextToolTipOneLine"); markerWidget->setUserString("ToolTipLayout", "TextToolTipOneLine");
@ -1098,14 +1099,15 @@ namespace MWGui
cell.second = y; cell.second = y;
if (mMarkers.insert(cell).second) if (mMarkers.insert(cell).second)
{ {
MapMarkerType mapMarkerWidget = { osg::Vec2f(x, y), createMarker(name, x, y, 0) }; const osg::Vec2f pos(static_cast<float>(x), static_cast<float>(y));
MapMarkerType mapMarkerWidget = { pos, createMarker(name, pos.x(), pos.y(), 0) };
mGlobalMapMarkers.emplace(mapMarkerWidget, std::vector<MapMarkerType>()); mGlobalMapMarkers.emplace(mapMarkerWidget, std::vector<MapMarkerType>());
const std::string markerName = name.substr(0, name.find(',')); const std::string markerName = name.substr(0, name.find(','));
auto& entry = mGlobalMapMarkersByName[markerName]; auto& entry = mGlobalMapMarkersByName[markerName];
if (!entry.widget) if (!entry.widget)
{ {
entry = { osg::Vec2f(x, y), entry.widget }; // update the coords entry = { pos, entry.widget }; // update the coords
entry.widget = createMarker(markerName, entry.position.x(), entry.position.y(), 1); entry.widget = createMarker(markerName, entry.position.x(), entry.position.y(), 1);
mGlobalMapMarkers.emplace(entry, std::vector<MapMarkerType>{ entry }); mGlobalMapMarkers.emplace(entry, std::vector<MapMarkerType>{ entry });
@ -1123,7 +1125,8 @@ namespace MWGui
[](const auto& left, const auto& right) { return left + right.position; }) [](const auto& left, const auto& right) { return left + right.position; })
/ float(elements.size()); / float(elements.size());
marker.widget->setCoord(createMarkerCoords(marker.position.x(), marker.position.y(), elements.size())); marker.widget->setCoord(
createMarkerCoords(marker.position.x(), marker.position.y(), static_cast<float>(elements.size())));
marker.widget->setVisible(marker.widget->getHeight() >= 6); marker.widget->setVisible(marker.widget->getHeight() >= 6);
} }
} }
@ -1167,16 +1170,16 @@ namespace MWGui
{ {
float markerSize = 12.f * mGlobalMapZoom; float markerSize = 12.f * mGlobalMapZoom;
if (mGlobalMapZoom < 1) if (mGlobalMapZoom < 1)
return markerSize * std::sqrt(agregatedWeight); // we want to see agregated object return static_cast<float>(markerSize * std::sqrt(agregatedWeight)); // we want to see agregated object
return agregatedWeight ? 0 : markerSize; // we want to see only original markers (i.e. non agregated) return agregatedWeight ? 0 : markerSize; // we want to see only original markers (i.e. non agregated)
} }
void MapWindow::resizeGlobalMap() void MapWindow::resizeGlobalMap()
{ {
mGlobalMap->setCanvasSize( int width = static_cast<int>(mGlobalMapRender->getWidth() * mGlobalMapZoom);
mGlobalMapRender->getWidth() * mGlobalMapZoom, mGlobalMapRender->getHeight() * mGlobalMapZoom); int height = static_cast<int>(mGlobalMapRender->getHeight() * mGlobalMapZoom);
mGlobalMapImage->setSize( mGlobalMap->setCanvasSize(width, height);
mGlobalMapRender->getWidth() * mGlobalMapZoom, mGlobalMapRender->getHeight() * mGlobalMapZoom); mGlobalMapImage->setSize(width, height);
} }
void MapWindow::worldPosToGlobalMapImageSpace(float x, float y, float& imageX, float& imageY) const void MapWindow::worldPosToGlobalMapImageSpace(float x, float y, float& imageX, float& imageY) const
@ -1191,7 +1194,8 @@ namespace MWGui
LocalMapBase::updateCustomMarkers(); LocalMapBase::updateCustomMarkers();
for (auto& [widgetPair, ignore] : mGlobalMapMarkers) for (auto& [widgetPair, ignore] : mGlobalMapMarkers)
setGlobalMapMarkerTooltip(widgetPair.widget, widgetPair.position.x(), widgetPair.position.y()); setGlobalMapMarkerTooltip(widgetPair.widget, static_cast<int>(widgetPair.position.x()),
static_cast<int>(widgetPair.position.y()));
} }
void MapWindow::onDragStart(MyGUI::Widget* /*sender*/, int left, int top, MyGUI::MouseButton id) void MapWindow::onDragStart(MyGUI::Widget* /*sender*/, int left, int top, MyGUI::MouseButton id)

View file

@ -279,7 +279,7 @@ namespace MWGui
void PostProcessorHud::notifyMouseWheel(MyGUI::Widget* /*sender*/, int rel) void PostProcessorHud::notifyMouseWheel(MyGUI::Widget* /*sender*/, int rel)
{ {
int offset = mConfigLayout->getViewOffset().top + rel * 0.3; double offset = mConfigLayout->getViewOffset().top + rel * 0.3;
if (offset > 0) if (offset > 0)
mConfigLayout->setViewOffset(MyGUI::IntPoint(0, 0)); mConfigLayout->setViewOffset(MyGUI::IntPoint(0, 0));
else else

View file

@ -333,8 +333,8 @@ namespace MWGui
if (texture) if (texture)
scale = texture->getHeight() / 64.f; scale = texture->getHeight() / 64.f;
mSelected->button->setFrame( const int diameter = static_cast<int>(44 * scale);
"textures\\menu_icon_select_magic.dds", MyGUI::IntCoord(0, 0, 44 * scale, 44 * scale)); mSelected->button->setFrame("textures\\menu_icon_select_magic.dds", MyGUI::IntCoord(0, 0, diameter, diameter));
mSelected->button->setIcon(path); mSelected->button->setIcon(path);
if (mMagicSelectionDialog) if (mMagicSelectionDialog)

View file

@ -241,7 +241,7 @@ namespace MWGui
SettingsWindow::SettingsWindow(Files::ConfigurationManager& cfgMgr) SettingsWindow::SettingsWindow(Files::ConfigurationManager& cfgMgr)
: WindowBase("openmw_settings_window.layout") : WindowBase("openmw_settings_window.layout")
, mKeyboardMode(true) , mKeyboardMode(true)
, mCurrentPage(-1) , mCurrentPage(static_cast<size_t>(-1))
, mCfgMgr(cfgMgr) , mCfgMgr(cfgMgr)
{ {
const bool terrain = Settings::terrain().mDistantTerrain; const bool terrain = Settings::terrain().mDistantTerrain;
@ -629,7 +629,7 @@ namespace MWGui
void SettingsWindow::onMaxLightsChanged(MyGUI::ComboBox* /*sender*/, size_t pos) void SettingsWindow::onMaxLightsChanged(MyGUI::ComboBox* /*sender*/, size_t pos)
{ {
Settings::shaders().mMaxLights.set(8 * (pos + 1)); Settings::shaders().mMaxLights.set(8 * static_cast<int>(pos + 1));
apply(); apply();
configureWidgets(mMainWidget, false); configureWidgets(mMainWidget, false);
} }
@ -752,7 +752,7 @@ namespace MWGui
} }
else else
{ {
Settings::get<int>(getSettingCategory(scroller), getSettingName(scroller)).set(pos); Settings::get<int>(getSettingCategory(scroller), getSettingName(scroller)).set(static_cast<int>(pos));
valueStr = MyGUI::utility::toString(pos); valueStr = MyGUI::utility::toString(pos);
} }
updateSliderLabel(scroller, valueStr); updateSliderLabel(scroller, valueStr);
@ -927,12 +927,12 @@ namespace MWGui
const int h = Settings::gui().mFontSize + 2; const int h = Settings::gui().mFontSize + 2;
const int w = mControlsBox->getWidth() - 28; const int w = mControlsBox->getWidth() - 28;
const int noWidgetsInRow = 2; const int noWidgetsInRow = 2;
const int totalH = mControlsBox->getChildCount() / noWidgetsInRow * h; const int totalH = static_cast<int>(mControlsBox->getChildCount() / noWidgetsInRow) * h;
for (size_t i = 0; i < mControlsBox->getChildCount(); i++) for (size_t i = 0; i < mControlsBox->getChildCount(); i++)
{ {
MyGUI::Widget* widget = mControlsBox->getChildAt(i); MyGUI::Widget* widget = mControlsBox->getChildAt(i);
widget->setCoord(0, i / noWidgetsInRow * h, w, h); widget->setCoord(0, static_cast<int>(i / noWidgetsInRow * h), w, h);
} }
// Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the // Canvas size must be expressed with VScroll disabled, otherwise MyGUI would expand the scroll area when the
@ -1030,7 +1030,7 @@ namespace MWGui
void SettingsWindow::onScriptListSelection(MyGUI::ListBox*, size_t index) void SettingsWindow::onScriptListSelection(MyGUI::ListBox*, size_t index)
{ {
mScriptAdapter->detach(); mScriptAdapter->detach();
mCurrentPage = -1; mCurrentPage = static_cast<size_t>(-1);
if (index < mScriptList->getItemCount()) if (index < mScriptList->getItemCount())
{ {
mCurrentPage = *mScriptList->getItemDataAt<size_t>(index); mCurrentPage = *mScriptList->getItemDataAt<size_t>(index);

View file

@ -72,7 +72,7 @@ namespace MWGui
MyGUI::Widget* mScriptDisabled; MyGUI::Widget* mScriptDisabled;
MyGUI::ScrollView* mScriptView; MyGUI::ScrollView* mScriptView;
LuaUi::LuaAdapter* mScriptAdapter; LuaUi::LuaAdapter* mScriptAdapter;
int mCurrentPage; size_t mCurrentPage;
void onTabChanged(MyGUI::TabControl* sender, size_t index); void onTabChanged(MyGUI::TabControl* sender, size_t index);
void onOkButtonClicked(MyGUI::Widget* sender); void onOkButtonClicked(MyGUI::Widget* sender);

View file

@ -382,7 +382,7 @@ namespace MWGui
void EditEffectDialog::onAreaChanged(MyGUI::ScrollBar* sender, size_t pos) void EditEffectDialog::onAreaChanged(MyGUI::ScrollBar* sender, size_t pos)
{ {
mAreaValue->setCaption(MyGUI::utility::toString(pos)); mAreaValue->setCaption(MyGUI::utility::toString(pos));
mEffect.mArea = pos; mEffect.mArea = static_cast<int32_t>(pos);
eventEffectModified(mEffect); eventEffectModified(mEffect);
} }
@ -1014,7 +1014,7 @@ namespace MWGui
void EffectEditorBase::onEffectAdded(ESM::ENAMstruct effect) void EffectEditorBase::onEffectAdded(ESM::ENAMstruct effect)
{ {
mEffects.push_back(effect); mEffects.push_back(effect);
mSelectedEffect = mEffects.size() - 1; mSelectedEffect = static_cast<int>(mEffects.size() - 1);
updateEffectsView(); updateEffectsView();
} }

View file

@ -28,7 +28,7 @@ namespace MWGui
{ {
MYGUI_RTTI_DERIVED(SpellView) MYGUI_RTTI_DERIVED(SpellView)
public: public:
SpellView() {}; SpellView() {}
/// Register needed components with MyGUI's factory manager /// Register needed components with MyGUI's factory manager
static void registerComponents(); static void registerComponents();

View file

@ -961,8 +961,7 @@ namespace MWGui
const std::string& name = ESM::MagicEffect::indexToGmstString(id); const std::string& name = ESM::MagicEffect::indexToGmstString(id);
std::string icon = effect->mIcon; std::string icon = effect->mIcon;
int slashPos = icon.rfind('\\'); icon.insert(icon.rfind('\\') + 1, "b_");
icon.insert(slashPos + 1, "b_");
icon = Misc::ResourceHelpers::correctIconPath(icon, MWBase::Environment::get().getResourceSystem()->getVFS()); icon = Misc::ResourceHelpers::correctIconPath(icon, MWBase::Environment::get().getResourceSystem()->getVFS());
widget->setUserString("ToolTipType", "Layout"); widget->setUserString("ToolTipType", "Layout");

View file

@ -439,7 +439,7 @@ namespace MWGui
MWBase::Environment::get().getWindowManager()->messageBox(msg); MWBase::Environment::get().getWindowManager()->messageBox(msg);
MWBase::Environment::get().getMechanicsManager()->confiscateStolenItemToOwner( MWBase::Environment::get().getMechanicsManager()->confiscateStolenItemToOwner(
player, itemStack.mBase, mPtr, itemStack.mCount); player, itemStack.mBase, mPtr, static_cast<int>(itemStack.mCount));
onCancelButtonClicked(mCancelButton); onCancelButtonClicked(mCancelButton);
MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode(); MWBase::Environment::get().getWindowManager()->exitCurrentGuiMode();

View file

@ -203,14 +203,13 @@ namespace MWGui
if (mPtr.getCell()->isExterior()) if (mPtr.getCell()->isExterior())
{ {
ESM::Position playerPos = player.getRefData().getPosition(); ESM::Position playerPos = player.getRefData().getPosition();
float d float d = (osg::Vec2f(pos.pos[0], pos.pos[1]) - osg::Vec2f(playerPos.pos[0], playerPos.pos[1])).length();
= (osg::Vec3f(pos.pos[0], pos.pos[1], 0) - osg::Vec3f(playerPos.pos[0], playerPos.pos[1], 0)).length(); const float fTravelTimeMult = MWBase::Environment::get()
int hours = static_cast<int>(d .getESMStore()
/ MWBase::Environment::get() ->get<ESM::GameSetting>()
.getESMStore() .find("fTravelTimeMult")
->get<ESM::GameSetting>() ->mValue.getFloat();
.find("fTravelTimeMult") int hours = static_cast<int>(d / fTravelTimeMult);
->mValue.getFloat());
MWBase::Environment::get().getMechanicsManager()->rest(hours, true); MWBase::Environment::get().getMechanicsManager()->rest(hours, true);
MWBase::Environment::get().getWorld()->advanceTime(hours); MWBase::Environment::get().getWorld()->advanceTime(hours);
} }

View file

@ -492,7 +492,7 @@ namespace MWGui
if (!mResourceSystem->getVFS()->exists(hitFaderTexture)) if (!mResourceSystem->getVFS()->exists(hitFaderTexture))
{ {
hitFaderTexture = "textures\\player_hit_01.dds"; hitFaderTexture = "textures\\player_hit_01.dds";
hitFaderCoord = MyGUI::FloatCoord(0.2, 0.25, 0.6, 0.5); hitFaderCoord = MyGUI::FloatCoord(0.2f, 0.25f, 0.6f, 0.5f);
} }
auto hitFader = std::make_unique<ScreenFader>(hitFaderTexture, hitFaderLayout, hitFaderCoord); auto hitFader = std::make_unique<ScreenFader>(hitFaderTexture, hitFaderLayout, hitFaderCoord);
mHitFader = hitFader.get(); mHitFader = hitFader.get();
@ -790,8 +790,8 @@ namespace MWGui
while (mMessageBoxManager->readPressedButton(false) == -1 while (mMessageBoxManager->readPressedButton(false) == -1
&& !MWBase::Environment::get().getStateManager()->hasQuitRequest()) && !MWBase::Environment::get().getStateManager()->hasQuitRequest())
{ {
const double dt const float dt
= std::chrono::duration_cast<std::chrono::duration<double>>(frameRateLimiter.getLastFrameDuration()) = std::chrono::duration_cast<std::chrono::duration<float>>(frameRateLimiter.getLastFrameDuration())
.count(); .count();
mKeyboardNavigation->onFrame(); mKeyboardNavigation->onFrame();
@ -906,8 +906,7 @@ namespace MWGui
if (state.mWindows.empty()) if (state.mWindows.empty())
return nullptr; return nullptr;
size_t activeIndex size_t activeIndex = std::clamp<size_t>(mActiveControllerWindows[mode], 0, state.mWindows.size() - 1);
= std::clamp<size_t>(mActiveControllerWindows[mode], 0, state.mWindows.size() - 1);
// If the active window is no longer visible, find the next visible window. // If the active window is no longer visible, find the next visible window.
if (!state.mWindows[activeIndex]->isVisible()) if (!state.mWindows[activeIndex]->isVisible())
@ -1920,10 +1919,10 @@ namespace MWGui
const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mRegular : settings.mMaximized; const WindowRectSettingValues& rect = settings.mIsMaximized ? settings.mRegular : settings.mMaximized;
MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize(); MyGUI::IntSize viewSize = MyGUI::RenderManager::getInstance().getViewSize();
const float x = rect.mX * viewSize.width; const int x = static_cast<int>(rect.mX * viewSize.width);
const float y = rect.mY * viewSize.height; const int y = static_cast<int>(rect.mY * viewSize.height);
const float w = rect.mW * viewSize.width; const int w = static_cast<int>(rect.mW * viewSize.width);
const float h = rect.mH * viewSize.height; const int h = static_cast<int>(rect.mH * viewSize.height);
window->setCoord(x, y, w, h); window->setCoord(x, y, w, h);
settings.mIsMaximized.set(!settings.mIsMaximized.get()); settings.mIsMaximized.set(!settings.mIsMaximized.get());
@ -1997,11 +1996,10 @@ namespace MWGui
writer.endRecord(ESM::REC_ASPL); writer.endRecord(ESM::REC_ASPL);
} }
for (CustomMarkerCollection::ContainerType::const_iterator it = mCustomMarkers.begin(); for (const auto& [_, marker] : mCustomMarkers)
it != mCustomMarkers.end(); ++it)
{ {
writer.startRecord(ESM::REC_MARK); writer.startRecord(ESM::REC_MARK);
it->second.save(writer); marker.save(writer);
writer.endRecord(ESM::REC_MARK); writer.endRecord(ESM::REC_MARK);
} }
} }
@ -2027,7 +2025,7 @@ namespace MWGui
} }
} }
int WindowManager::countSavedGameRecords() const size_t WindowManager::countSavedGameRecords() const
{ {
return 1 // Global map return 1 // Global map
+ 1 // QuickKeysMenu + 1 // QuickKeysMenu
@ -2075,8 +2073,8 @@ namespace MWGui
= Misc::makeFrameRateLimiter(MWBase::Environment::get().getFrameRateLimit()); = Misc::makeFrameRateLimiter(MWBase::Environment::get().getFrameRateLimit());
while (mVideoWidget->update() && !MWBase::Environment::get().getStateManager()->hasQuitRequest()) while (mVideoWidget->update() && !MWBase::Environment::get().getStateManager()->hasQuitRequest())
{ {
const double dt const float dt
= std::chrono::duration_cast<std::chrono::duration<double>>(frameRateLimiter.getLastFrameDuration()) = std::chrono::duration_cast<std::chrono::duration<float>>(frameRateLimiter.getLastFrameDuration())
.count(); .count();
MWBase::Environment::get().getInputManager()->update(dt, true, false); MWBase::Environment::get().getInputManager()->update(dt, true, false);
@ -2425,8 +2423,8 @@ namespace MWGui
if (image.valid()) if (image.valid())
{ {
// everything looks good, send it to the cursor manager // everything looks good, send it to the cursor manager
const Uint8 hotspotX = imgSetPointer->getHotSpot().left; const Uint8 hotspotX = static_cast<Uint8>(imgSetPointer->getHotSpot().left);
const Uint8 hotspotY = imgSetPointer->getHotSpot().top; const Uint8 hotspotY = static_cast<Uint8>(imgSetPointer->getHotSpot().top);
int rotation = imgSetPointer->getRotation(); int rotation = imgSetPointer->getRotation();
MyGUI::IntSize pointerSize = imgSetPointer->getSize(); MyGUI::IntSize pointerSize = imgSetPointer->getSize();

View file

@ -331,7 +331,7 @@ namespace MWGui
void write(ESM::ESMWriter& writer, Loading::Listener& progress) override; void write(ESM::ESMWriter& writer, Loading::Listener& progress) override;
void readRecord(ESM::ESMReader& reader, uint32_t type) override; void readRecord(ESM::ESMReader& reader, uint32_t type) override;
int countSavedGameRecords() const override; size_t countSavedGameRecords() const override;
/// Does the current stack of GUI-windows permit saving? /// Does the current stack of GUI-windows permit saving?
bool isSavingAllowed() const override; bool isSavingAllowed() const override;

View file

@ -78,7 +78,7 @@ namespace MWInput
set("playermagic", !controls.mSpellDrawingDisabled); set("playermagic", !controls.mSpellDrawingDisabled);
} }
int ControlSwitch::countSavedGameRecords() const size_t ControlSwitch::countSavedGameRecords() const
{ {
return 1; return 1;
} }

View file

@ -31,7 +31,7 @@ namespace MWInput
void write(ESM::ESMWriter& writer, Loading::Listener& progress); void write(ESM::ESMWriter& writer, Loading::Listener& progress);
void readRecord(ESM::ESMReader& reader, uint32_t type); void readRecord(ESM::ESMReader& reader, uint32_t type);
int countSavedGameRecords() const; size_t countSavedGameRecords() const;
private: private:
std::map<std::string, bool, std::less<>> mSwitches; std::map<std::string, bool, std::less<>> mSwitches;

View file

@ -211,7 +211,7 @@ namespace MWInput
mBindingsManager->enableDetectingBindingMode(action, keyboard); mBindingsManager->enableDetectingBindingMode(action, keyboard);
} }
int InputManager::countSavedGameRecords() const size_t InputManager::countSavedGameRecords() const
{ {
return mControlSwitch->countSavedGameRecords(); return mControlSwitch->countSavedGameRecords();
} }

View file

@ -95,7 +95,7 @@ namespace MWInput
std::string getControllerButtonIcon(int button) override; std::string getControllerButtonIcon(int button) override;
std::string getControllerAxisIcon(int axis) override; std::string getControllerAxisIcon(int axis) override;
int countSavedGameRecords() const override; size_t countSavedGameRecords() const override;
void write(ESM::ESMWriter& writer, Loading::Listener& progress) override; void write(ESM::ESMWriter& writer, Loading::Listener& progress) override;
void readRecord(ESM::ESMReader& reader, uint32_t type) override; void readRecord(ESM::ESMReader& reader, uint32_t type) override;

View file

@ -105,14 +105,14 @@ namespace MWLua
double fovTan = std::tan(osg::DegreesToRadians(renderingManager->getFieldOfView()) / 2); double fovTan = std::tan(osg::DegreesToRadians(renderingManager->getFieldOfView()) / 2);
osg::Matrixf invertedViewMatrix; osg::Matrixf invertedViewMatrix;
invertedViewMatrix.invert(camera->getViewMatrix()); invertedViewMatrix.invert(camera->getViewMatrix());
float x = (pos.x() * 2 - 1) * aspect * fovTan; float x = static_cast<float>((pos.x() * 2 - 1) * aspect * fovTan);
float y = (1 - pos.y() * 2) * fovTan; float y = static_cast<float>((1 - pos.y() * 2) * fovTan);
return invertedViewMatrix.preMult(osg::Vec3f(x, y, -1)) - camera->getPosition(); return invertedViewMatrix.preMult(osg::Vec3f(x, y, -1)) - camera->getPosition();
}; };
api["worldToViewportVector"] = [camera](osg::Vec3f pos) { api["worldToViewportVector"] = [camera](osg::Vec3f pos) {
const double width = Settings::video().mResolutionX; const int width = Settings::video().mResolutionX;
const double height = Settings::video().mResolutionY; const int height = Settings::video().mResolutionY;
osg::Matrix windowMatrix osg::Matrix windowMatrix
= osg::Matrix::translate(1.0, 1.0, 1.0) * osg::Matrix::scale(0.5 * width, 0.5 * height, 0.5); = osg::Matrix::translate(1.0, 1.0, 1.0) * osg::Matrix::scale(0.5 * width, 0.5 * height, 0.5);

View file

@ -40,6 +40,8 @@
#include <components/esm4/loadtree.hpp> #include <components/esm4/loadtree.hpp>
#include <components/esm4/loadweap.hpp> #include <components/esm4/loadweap.hpp>
#include <components/misc/convert.hpp>
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
#include "../mwworld/cellstore.hpp" #include "../mwworld/cellstore.hpp"
@ -307,7 +309,7 @@ namespace MWLua
{ {
sol::table table(lua, sol::create); sol::table table(lua, sol::create);
table["autoGenerated"] = point.mAutogenerated == 0; table["autoGenerated"] = point.mAutogenerated == 0;
table["relativePosition"] = osg::Vec3f(point.mX, point.mY, point.mZ); table["relativePosition"] = Misc::Convert::makeOsgVec3f(point);
sol::table edges(lua, sol::create); sol::table edges(lua, sol::create);
table["connections"] = edges; table["connections"] = edges;
points.add(table); points.add(table);

View file

@ -41,10 +41,10 @@ namespace MWLua
list[LuaUtil::toLuaIndex(i)] = Misc::StringUtils::lowerCase(contentList[i]); list[LuaUtil::toLuaIndex(i)] = Misc::StringUtils::lowerCase(contentList[i]);
sol::table res(lua, sol::create); sol::table res(lua, sol::create);
res["list"] = LuaUtil::makeReadOnly(list); res["list"] = LuaUtil::makeReadOnly(list);
res["indexOf"] = [&contentList](std::string_view contentFile) -> sol::optional<int> { res["indexOf"] = [&contentList](std::string_view contentFile) -> sol::optional<int64_t> {
for (size_t i = 0; i < contentList.size(); ++i) for (size_t i = 0; i < contentList.size(); ++i)
if (Misc::StringUtils::ciEqual(contentList[i], contentFile)) if (Misc::StringUtils::ciEqual(contentList[i], contentFile))
return LuaUtil::toLuaIndex(i); return LuaUtil::toLuaIndex(static_cast<int64_t>(i));
return sol::nullopt; return sol::nullopt;
}; };
res["has"] = [&contentList](std::string_view contentFile) -> bool { res["has"] = [&contentList](std::string_view contentFile) -> bool {

View file

@ -220,7 +220,7 @@ namespace
return rec.mFaction.serializeText(); return rec.mFaction.serializeText();
}); });
recordInfoBindingsClass["filterActorFactionRank"] recordInfoBindingsClass["filterActorFactionRank"]
= sol::readonly_property([](const ESM::DialInfo& rec) -> sol::optional<int> { = sol::readonly_property([](const ESM::DialInfo& rec) -> sol::optional<int64_t> {
if (rec.mData.mType == ESM::Dialogue::Type::Journal || rec.mData.mRank == -1) if (rec.mData.mType == ESM::Dialogue::Type::Journal || rec.mData.mRank == -1)
{ {
return sol::nullopt; return sol::nullopt;
@ -260,7 +260,7 @@ namespace
return rec.mPcFaction.serializeText(); return rec.mPcFaction.serializeText();
}); });
recordInfoBindingsClass["filterPlayerFactionRank"] recordInfoBindingsClass["filterPlayerFactionRank"]
= sol::readonly_property([](const ESM::DialInfo& rec) -> sol::optional<int> { = sol::readonly_property([](const ESM::DialInfo& rec) -> sol::optional<int64_t> {
if (rec.mData.mType == ESM::Dialogue::Type::Journal || rec.mData.mPCrank == -1) if (rec.mData.mType == ESM::Dialogue::Type::Journal || rec.mData.mPCrank == -1)
{ {
return sol::nullopt; return sol::nullopt;

View file

@ -130,7 +130,7 @@ namespace MWLua
{ {
// if the value set is less than 0, chargeInt and chargeIntRemainder is set to 0 // if the value set is less than 0, chargeInt and chargeIntRemainder is set to 0
ptr.getCellRef().setChargeIntRemainder(std::max(0.f, std::modf(cond, &cond))); ptr.getCellRef().setChargeIntRemainder(std::max(0.f, std::modf(cond, &cond)));
ptr.getCellRef().setCharge(std::max(0.f, cond)); ptr.getCellRef().setCharge(std::max(0, static_cast<int>(cond)));
} }
} }
else else

View file

@ -89,8 +89,8 @@ namespace MWLua
if (worldspace != ESM::Cell::sDefaultWorldspaceId) if (worldspace != ESM::Cell::sDefaultWorldspaceId)
return values; return values;
const float cellSize = ESM::getCellSize(worldspace); const int cellSize = ESM::getCellSize(worldspace);
const float offset = (cellSize / ESM::LandRecordData::sLandTextureSize) * 0.25; const float offset = (cellSize / ESM::LandRecordData::sLandTextureSize) * 0.25f;
const osg::Vec3f correctedPos = pos + osg::Vec3f{ -offset, +offset, 0.0f }; const osg::Vec3f correctedPos = pos + osg::Vec3f{ -offset, +offset, 0.0f };
const ESM::Land* land = nullptr; const ESM::Land* land = nullptr;
@ -110,7 +110,7 @@ namespace MWLua
return values; return values;
const ESMTerrain::UniqueTextureId textureId const ESMTerrain::UniqueTextureId textureId
= getTextureAt(landData->mTextures, land->getPlugin(), correctedPos, cellSize); = getTextureAt(landData->mTextures, land->getPlugin(), correctedPos, static_cast<float>(cellSize));
// Need to check for 0, 0 so that we can safely subtract 1 later, as per documentation on UniqueTextureId // Need to check for 0, 0 so that we can safely subtract 1 later, as per documentation on UniqueTextureId
if (textureId.first != 0) if (textureId.first != 0)

View file

@ -281,8 +281,8 @@ namespace MWLua
} }
mInputEvents.clear(); mInputEvents.clear();
mLuaEvents.callMenuEventHandlers(); mLuaEvents.callMenuEventHandlers();
double frameDuration = MWBase::Environment::get().getWorld()->getTimeManager()->isPaused() float frameDuration = MWBase::Environment::get().getWorld()->getTimeManager()->isPaused()
? 0.0 ? 0.f
: MWBase::Environment::get().getFrameDuration(); : MWBase::Environment::get().getFrameDuration();
mInputActions.update(frameDuration); mInputActions.update(frameDuration);
mMenuScripts.onFrame(frameDuration); mMenuScripts.onFrame(frameDuration);
@ -826,7 +826,7 @@ namespace MWLua
void LuaManager::reportStats(unsigned int frameNumber, osg::Stats& stats) const void LuaManager::reportStats(unsigned int frameNumber, osg::Stats& stats) const
{ {
stats.setAttribute(frameNumber, "Lua UsedMemory", mLua.getTotalMemoryUsage()); stats.setAttribute(frameNumber, "Lua UsedMemory", static_cast<double>(mLua.getTotalMemoryUsage()));
} }
std::string LuaManager::formatResourceUsageStats() const std::string LuaManager::formatResourceUsageStats() const
@ -836,11 +836,11 @@ namespace MWLua
std::stringstream out; std::stringstream out;
constexpr int nameW = 50; constexpr unsigned nameW = 50;
constexpr int valueW = 12; constexpr int valueW = 12;
auto outMemSize = [&](int64_t bytes) { auto outMemSize = [&](size_t bytes) {
constexpr int64_t limit = 10000; constexpr size_t limit = 10000;
out << std::right << std::setw(valueW - 3); out << std::right << std::setw(valueW - 3);
if (bytes < limit) if (bytes < limit)
out << bytes << " B "; out << bytes << " B ";
@ -924,21 +924,22 @@ namespace MWLua
out << "\n " << std::setw(nameW) << ""; // if path is too long, break line out << "\n " << std::setw(nameW) << ""; // if path is too long, break line
out << std::right; out << std::right;
out << std::setw(valueW) << static_cast<int64_t>(activeStats[i].mAvgInstructionCount); out << std::setw(valueW) << static_cast<int64_t>(activeStats[i].mAvgInstructionCount);
outMemSize(activeStats[i].mMemoryUsage); outMemSize(static_cast<size_t>(activeStats[i].mMemoryUsage));
outMemSize(mLua.getMemoryUsageByScriptIndex(i) - activeStats[i].mMemoryUsage); outMemSize(mLua.getMemoryUsageByScriptIndex(static_cast<unsigned>(i))
- static_cast<uint64_t>(activeStats[i].mMemoryUsage));
if (isGlobal) if (isGlobal)
out << std::setw(valueW * 2) << "NA (global script)"; out << std::setw(valueW * 2) << "NA (global script)";
else if (isMenu && (!selectedScripts || !selectedScripts->hasScript(i))) else if (isMenu && (!selectedScripts || !selectedScripts->hasScript(static_cast<int>(i))))
out << std::setw(valueW * 2) << "NA (menu script)"; out << std::setw(valueW * 2) << "NA (menu script)";
else if (selectedPtr.isEmpty()) else if (selectedPtr.isEmpty())
out << std::setw(valueW * 2) << "NA (not selected) "; out << std::setw(valueW * 2) << "NA (not selected) ";
else if (!selectedScripts || !selectedScripts->hasScript(i)) else if (!selectedScripts || !selectedScripts->hasScript(static_cast<int>(i)))
out << std::setw(valueW * 2) << "NA"; out << std::setw(valueW * 2) << "NA";
else else
{ {
out << std::setw(valueW) << static_cast<int64_t>(selectedStats[i].mAvgInstructionCount); out << std::setw(valueW) << static_cast<int64_t>(selectedStats[i].mAvgInstructionCount);
outMemSize(selectedStats[i].mMemoryUsage); outMemSize(static_cast<size_t>(selectedStats[i].mMemoryUsage));
} }
out << "\n"; out << "\n";
} }

View file

@ -770,7 +770,7 @@ namespace MWLua
resetEnchantItem(); resetEnchantItem();
if (objPtr == MWBase::Environment::get().getWorld()->getPlayerPtr()) if (objPtr == MWBase::Environment::get().getWorld()->getPlayerPtr())
{ {
int chance = MWMechanics::getSpellSuccessChance(spellId, objPtr); int chance = static_cast<int>(MWMechanics::getSpellSuccessChance(spellId, objPtr));
MWBase::Environment::get().getWindowManager()->setSelectedSpell(spellId, chance); MWBase::Environment::get().getWindowManager()->setSelectedSpell(spellId, chance);
} }
else else
@ -963,9 +963,9 @@ namespace MWLua
effect.mEffectId = enam.mData.mEffectID; effect.mEffectId = enam.mData.mEffectID;
effect.mArg = MWMechanics::EffectKey(enam.mData).mArg; effect.mArg = MWMechanics::EffectKey(enam.mData).mArg;
effect.mMagnitude = 0.f; effect.mMagnitude = 0.f;
effect.mMinMagnitude = enam.mData.mMagnMin; effect.mMinMagnitude = static_cast<float>(enam.mData.mMagnMin);
effect.mMaxMagnitude = enam.mData.mMagnMax; effect.mMaxMagnitude = static_cast<float>(enam.mData.mMagnMax);
effect.mEffectIndex = enam.mIndex; effect.mEffectIndex = static_cast<int32_t>(enam.mIndex);
effect.mFlags = ESM::ActiveEffect::Flag_None; effect.mFlags = ESM::ActiveEffect::Flag_None;
if (ignoreReflect) if (ignoreReflect)
effect.mFlags |= ESM::ActiveEffect::Flag_Ignore_Reflect; effect.mFlags |= ESM::ActiveEffect::Flag_Ignore_Reflect;
@ -1089,7 +1089,7 @@ namespace MWLua
throw std::runtime_error("Local scripts can modify effect only on the actor they are attached to."); throw std::runtime_error("Local scripts can modify effect only on the actor they are attached to.");
MWMechanics::EffectKey key = getEffectKey(idStr, argStr); MWMechanics::EffectKey key = getEffectKey(idStr, argStr);
int currentValue = effects.getStore()->getOrDefault(key).getMagnitude(); int currentValue = static_cast<int>(effects.getStore()->getOrDefault(key).getMagnitude());
effects.getStore()->modifyBase(key, value - currentValue); effects.getStore()->modifyBase(key, value - currentValue);
}; };

View file

@ -90,7 +90,7 @@ namespace MWLua
} }
else if (varType == 's' || varType == 'l') else if (varType == 's' || varType == 'l')
{ {
MWBase::Environment::get().getWorld()->setGlobalInt(globalId, value); MWBase::Environment::get().getWorld()->setGlobalInt(globalId, static_cast<int>(value));
} }
} }

View file

@ -356,9 +356,9 @@ namespace MWLua
if (!searchAreaHalfExtents.has_value()) if (!searchAreaHalfExtents.has_value())
{ {
const bool isEsm4 = MWBase::Environment::get().getWorldScene()->getCurrentCell()->getCell()->isEsm4(); const bool isEsm4 = MWBase::Environment::get().getWorldScene()->getCurrentCell()->getCell()->isEsm4();
const float halfExtents = isEsm4 const float halfExtents = static_cast<float>(isEsm4
? (1 + 2 * Constants::ESM4CellGridRadius) * Constants::ESM4CellSizeInUnits ? (1 + 2 * Constants::ESM4CellGridRadius) * Constants::ESM4CellSizeInUnits
: (1 + 2 * Constants::CellGridRadius) * Constants::CellSizeInUnits; : (1 + 2 * Constants::CellGridRadius) * Constants::CellSizeInUnits);
searchAreaHalfExtents = osg::Vec3f(halfExtents, halfExtents, halfExtents); searchAreaHalfExtents = osg::Vec3f(halfExtents, halfExtents, halfExtents);
} }

View file

@ -259,16 +259,17 @@ namespace MWLua
}; };
ownerT["factionId"] = sol::property(getOwnerFactionId, setOwnerFactionId); ownerT["factionId"] = sol::property(getOwnerFactionId, setOwnerFactionId);
auto getOwnerFactionRank = [](const OwnerT& o) -> sol::optional<size_t> { auto getOwnerFactionRank = [](const OwnerT& o) -> sol::optional<int64_t> {
int rank = o.mObj.ptr().getCellRef().getFactionRank(); int rank = o.mObj.ptr().getCellRef().getFactionRank();
if (rank < 0) if (rank < 0)
return sol::nullopt; return sol::nullopt;
return LuaUtil::toLuaIndex(rank); return LuaUtil::toLuaIndex(rank);
}; };
auto setOwnerFactionRank = [](const OwnerT& o, sol::optional<size_t> factionRank) { auto setOwnerFactionRank = [](const OwnerT& o, sol::optional<int64_t> factionRank) {
if (std::is_same_v<ObjectT, LObject> && !dynamic_cast<const SelfObject*>(&o.mObj)) if (std::is_same_v<ObjectT, LObject> && !dynamic_cast<const SelfObject*>(&o.mObj))
throw std::runtime_error("Local scripts can set an owner faction rank only on self"); throw std::runtime_error("Local scripts can set an owner faction rank only on self");
o.mObj.ptr().getCellRef().setFactionRank(LuaUtil::fromLuaIndex(factionRank.value_or(0))); int64_t rank = std::max(0, LuaUtil::fromLuaIndex(factionRank.value_or(0)));
o.mObj.ptr().getCellRef().setFactionRank(static_cast<int>(rank));
}; };
ownerT["factionRank"] = sol::property(getOwnerFactionRank, setOwnerFactionRank); ownerT["factionRank"] = sol::property(getOwnerFactionRank, setOwnerFactionRank);

View file

@ -243,7 +243,8 @@ namespace MWLua
return luaManager->uiResourceManager()->registerTexture(std::move(data)); return luaManager->uiResourceManager()->registerTexture(std::move(data));
}; };
api["screenSize"] = []() { return osg::Vec2f(Settings::video().mResolutionX, Settings::video().mResolutionY); }; api["screenSize"]
= []() { return osg::Vec2f(float(Settings::video().mResolutionX), float(Settings::video().mResolutionY)); };
api["_getAllUiModes"] = [](sol::this_state thisState) { api["_getAllUiModes"] = [](sol::this_state thisState) {
sol::table res(thisState, sol::create); sol::table res(thisState, sol::create);
@ -269,16 +270,16 @@ namespace MWLua
if (arg.has_value()) if (arg.has_value())
ptr = arg->ptr(); ptr = arg->ptr();
const std::vector<MWGui::GuiMode>& stack = windowManager->getGuiModeStack(); const std::vector<MWGui::GuiMode>& stack = windowManager->getGuiModeStack();
unsigned common = 0; size_t common = 0;
while (common < std::min(stack.size(), newStack.size()) && stack[common] == newStack[common]) while (common < std::min(stack.size(), newStack.size()) && stack[common] == newStack[common])
common++; common++;
// TODO: Maybe disallow opening/closing special modes (main menu, settings, loading screen) // TODO: Maybe disallow opening/closing special modes (main menu, settings, loading screen)
// from player scripts. Add new Lua context "menu" that can do it. // from player scripts. Add new Lua context "menu" that can do it.
for (unsigned i = stack.size() - common; i > 0; i--) for (size_t i = stack.size() - common; i > 0; i--)
windowManager->popGuiMode(true); windowManager->popGuiMode(true);
if (common == newStack.size() && !newStack.empty() && arg.has_value()) if (common == newStack.size() && !newStack.empty() && arg.has_value())
windowManager->pushGuiMode(newStack.back(), ptr); windowManager->pushGuiMode(newStack.back(), ptr);
for (unsigned i = common; i < newStack.size(); ++i) for (size_t i = common; i < newStack.size(); ++i)
windowManager->pushGuiMode(newStack[i], ptr); windowManager->pushGuiMode(newStack[i], ptr);
}, },
"Set UI modes"); "Set UI modes");

View file

@ -58,9 +58,9 @@ namespace
effect.mEffectId = enam.mData.mEffectID; effect.mEffectId = enam.mData.mEffectID;
effect.mArg = MWMechanics::EffectKey(enam.mData).mArg; effect.mArg = MWMechanics::EffectKey(enam.mData).mArg;
effect.mMagnitude = 0.f; effect.mMagnitude = 0.f;
effect.mMinMagnitude = enam.mData.mMagnMin; effect.mMinMagnitude = static_cast<float>(enam.mData.mMagnMin);
effect.mMaxMagnitude = enam.mData.mMagnMax; effect.mMaxMagnitude = static_cast<float>(enam.mData.mMagnMax);
effect.mEffectIndex = enam.mIndex; effect.mEffectIndex = static_cast<int32_t>(enam.mIndex);
effect.mFlags = ESM::ActiveEffect::Flag_None; effect.mFlags = ESM::ActiveEffect::Flag_None;
if (ignoreResistances) if (ignoreResistances)
effect.mFlags |= ESM::ActiveEffect::Flag_Ignore_Resistances; effect.mFlags |= ESM::ActiveEffect::Flag_Ignore_Resistances;

View file

@ -584,8 +584,8 @@ namespace MWMechanics
float to = dir.y(); float to = dir.y();
float angle = std::atan2(from, to); float angle = std::atan2(from, to);
actorState.setAngleToPlayer(angle); actorState.setAngleToPlayer(angle);
float deltaAngle = Misc::normalizeAngle(angle - actor.getRefData().getPosition().rot[2]); double deltaAngle = Misc::normalizeAngle(angle - actor.getRefData().getPosition().rot[2]);
if (!Settings::game().mSmoothMovement || std::abs(deltaAngle) > osg::DegreesToRadians(60.f)) if (!Settings::game().mSmoothMovement || std::abs(deltaAngle) > osg::DegreesToRadians(60.0))
actorState.setTurningToPlayer(true); actorState.setTurningToPlayer(true);
} }
} }
@ -849,7 +849,7 @@ namespace MWMechanics
const auto [health, magicka] = getRestorationPerHourOfSleep(ptr); const auto [health, magicka] = getRestorationPerHourOfSleep(ptr);
DynamicStat<float> stat = stats.getHealth(); DynamicStat<float> stat = stats.getHealth();
stat.setCurrent(stat.getCurrent() + health * hours); stat.setCurrent(static_cast<float>(stat.getCurrent() + health * hours));
stats.setHealth(stat); stats.setHealth(stat);
double restoreHours = hours; double restoreHours = hours;
@ -876,7 +876,7 @@ namespace MWMechanics
if (restoreHours > 0) if (restoreHours > 0)
{ {
stat = stats.getMagicka(); stat = stats.getMagicka();
stat.setCurrent(stat.getCurrent() + magicka * restoreHours); stat.setCurrent(static_cast<float>(stat.getCurrent() + magicka * restoreHours));
stats.setMagicka(stat); stats.setMagicka(stat);
} }
} }
@ -901,7 +901,7 @@ namespace MWMechanics
const float x const float x
= (fFatigueReturnBase + fFatigueReturnMult * (1 - normalizedEncumbrance)) * (fEndFatigueMult * endurance); = (fFatigueReturnBase + fFatigueReturnMult * (1 - normalizedEncumbrance)) * (fEndFatigueMult * endurance);
fatigue.setCurrent(fatigue.getCurrent() + 3600 * x * hours); fatigue.setCurrent(static_cast<float>(fatigue.getCurrent() + 3600 * x * hours));
stats.setFatigue(fatigue); stats.setFatigue(fatigue);
} }
@ -1156,9 +1156,8 @@ namespace MWMechanics
if (playerStats.getBounty() >= cutoff * iCrimeThresholdMultiplier) if (playerStats.getBounty() >= cutoff * iCrimeThresholdMultiplier)
{ {
mechanicsManager->startCombat(ptr, player, &cachedAllies.getActorsSidingWith(player)); mechanicsManager->startCombat(ptr, player, &cachedAllies.getActorsSidingWith(player));
creatureStats.setHitAttemptActorId( // Stops the guard from quitting combat if player is unreachable
playerClass.getCreatureStats(player) creatureStats.setHitAttemptActorId(playerClass.getCreatureStats(player).getActorId());
.getActorId()); // Stops the guard from quitting combat if player is unreachable
} }
else else
creatureStats.getAiSequence().stack(AiPursue(player), ptr); creatureStats.getAiSequence().stack(AiPursue(player), ptr);
@ -1234,7 +1233,7 @@ namespace MWMechanics
// Fade away actors on large distance (>90% of actor's processing distance) // Fade away actors on large distance (>90% of actor's processing distance)
float visibilityRatio = 1.0; float visibilityRatio = 1.0;
const float fadeStartDistance = actorsProcessingRange * 0.9f; const float fadeStartDistance = actorsProcessingRange * 0.9f;
const float fadeEndDistance = actorsProcessingRange; const float fadeEndDistance = static_cast<float>(actorsProcessingRange);
const float fadeRatio = (dist - fadeStartDistance) / (fadeEndDistance - fadeStartDistance); const float fadeRatio = (dist - fadeStartDistance) / (fadeEndDistance - fadeStartDistance);
if (fadeRatio > 0) if (fadeRatio > 0)
visibilityRatio -= std::max(0.f, fadeRatio); visibilityRatio -= std::max(0.f, fadeRatio);
@ -1278,7 +1277,7 @@ namespace MWMechanics
// Otherwise check if any actor in AI processing range sees the target actor // Otherwise check if any actor in AI processing range sees the target actor
std::vector<MWWorld::Ptr> neighbors; std::vector<MWWorld::Ptr> neighbors;
osg::Vec3f position(actor.getRefData().getPosition().asVec3()); osg::Vec3f position(actor.getRefData().getPosition().asVec3());
getObjectsInRange(position, Settings::game().mActorsProcessingRange, neighbors); getObjectsInRange(position, static_cast<float>(Settings::game().mActorsProcessingRange), neighbors);
for (const MWWorld::Ptr& neighbor : neighbors) for (const MWWorld::Ptr& neighbor : neighbors)
{ {
if (neighbor == actor) if (neighbor == actor)
@ -1877,7 +1876,7 @@ namespace MWMechanics
void Actors::rest(double hours, bool sleep) const void Actors::rest(double hours, bool sleep) const
{ {
float duration = hours * 3600.f; float duration = static_cast<float>(hours * 3600);
const float timeScale = MWBase::Environment::get().getWorld()->getTimeManager()->getGameTimeScale(); const float timeScale = MWBase::Environment::get().getWorld()->getTimeManager()->getGameTimeScale();
if (timeScale != 0.f) if (timeScale != 0.f)
duration /= timeScale; duration /= timeScale;
@ -1952,7 +1951,7 @@ namespace MWMechanics
std::vector<MWWorld::Ptr> observers; std::vector<MWWorld::Ptr> observers;
const osg::Vec3f position(player.getRefData().getPosition().asVec3()); const osg::Vec3f position(player.getRefData().getPosition().asVec3());
const float radius = std::min<float>(fSneakUseDist, Settings::game().mActorsProcessingRange); const float radius = std::min(fSneakUseDist, static_cast<float>(Settings::game().mActorsProcessingRange));
getObjectsInRange(position, radius, observers); getObjectsInRange(position, radius, observers);
std::set<MWWorld::Ptr> sidingActors; std::set<MWWorld::Ptr> sidingActors;
@ -2256,7 +2255,7 @@ namespace MWMechanics
std::vector<MWWorld::Ptr> list; std::vector<MWWorld::Ptr> list;
std::vector<MWWorld::Ptr> neighbors; std::vector<MWWorld::Ptr> neighbors;
const osg::Vec3f position(actor.getRefData().getPosition().asVec3()); const osg::Vec3f position(actor.getRefData().getPosition().asVec3());
getObjectsInRange(position, Settings::game().mActorsProcessingRange, neighbors); getObjectsInRange(position, static_cast<float>(Settings::game().mActorsProcessingRange), neighbors);
for (const MWWorld::Ptr& neighbor : neighbors) for (const MWWorld::Ptr& neighbor : neighbors)
{ {
if (neighbor == actor) if (neighbor == actor)
@ -2277,7 +2276,7 @@ namespace MWMechanics
std::vector<MWWorld::Ptr> list; std::vector<MWWorld::Ptr> list;
std::vector<MWWorld::Ptr> neighbors; std::vector<MWWorld::Ptr> neighbors;
osg::Vec3f position(actor.getRefData().getPosition().asVec3()); osg::Vec3f position(actor.getRefData().getPosition().asVec3());
getObjectsInRange(position, Settings::game().mActorsProcessingRange, neighbors); getObjectsInRange(position, static_cast<float>(Settings::game().mActorsProcessingRange), neighbors);
std::set<MWWorld::Ptr> followers; std::set<MWWorld::Ptr> followers;
getActorsFollowing(actor, followers); getActorsFollowing(actor, followers);

View file

@ -88,5 +88,5 @@ void MWMechanics::AiAvoidDoor::adjustDirection()
float MWMechanics::AiAvoidDoor::getAdjustedAngle() const float MWMechanics::AiAvoidDoor::getAdjustedAngle() const
{ {
return 2 * osg::PI / MAX_DIRECTIONS * mDirection; return 2 * osg::PIf / MAX_DIRECTIONS * mDirection;
} }

View file

@ -432,7 +432,7 @@ namespace MWMechanics
storage.mFleeBlindRunTimer += duration; storage.mFleeBlindRunTimer += duration;
storage.mMovement.mRotation[0] = -actor.getRefData().getPosition().rot[0]; storage.mMovement.mRotation[0] = -actor.getRefData().getPosition().rot[0];
storage.mMovement.mRotation[2] = osg::PI storage.mMovement.mRotation[2] = osg::PIf
+ getZAngleToDir( + getZAngleToDir(
target.getRefData().getPosition().asVec3() - actor.getRefData().getPosition().asVec3()); target.getRefData().getPosition().asVec3() - actor.getRefData().getPosition().asVec3());
storage.mMovement.mPosition[1] = 1; storage.mMovement.mPosition[1] = 1;
@ -486,7 +486,7 @@ namespace MWMechanics
actorMovementSettings.mRotation[axis] = 0; actorMovementSettings.mRotation[axis] = 0;
bool isRangedCombat = false; bool isRangedCombat = false;
storage.mCurrentAction->getCombatRange(isRangedCombat); storage.mCurrentAction->getCombatRange(isRangedCombat);
float eps = isRangedCombat ? osg::DegreesToRadians(0.5) : osg::DegreesToRadians(3.f); float eps = isRangedCombat ? osg::DegreesToRadians(0.5f) : osg::DegreesToRadians(3.f);
float targetAngleRadians = storage.mMovement.mRotation[axis]; float targetAngleRadians = storage.mMovement.mRotation[axis];
storage.mRotateMove = !smoothTurn(actor, targetAngleRadians, axis, eps); storage.mRotateMove = !smoothTurn(actor, targetAngleRadians, axis, eps);
} }
@ -567,7 +567,7 @@ namespace MWMechanics
else if (actor.getClass().isBipedal(actor) && !isDistantCombat) else if (actor.getClass().isBipedal(actor) && !isDistantCombat)
{ {
float moveDuration = 0; float moveDuration = 0;
float angleToTarget double angleToTarget
= Misc::normalizeAngle(mMovement.mRotation[2] - actor.getRefData().getPosition().rot[2]); = Misc::normalizeAngle(mMovement.mRotation[2] - actor.getRefData().getPosition().rot[2]);
// Apply a big side step if enemy tries to get around and come from behind. // Apply a big side step if enemy tries to get around and come from behind.
// Otherwise apply a random side step (kind of dodging) with some probability // Otherwise apply a random side step (kind of dodging) with some probability
@ -683,7 +683,7 @@ namespace MWMechanics
MWBase::Environment::get().getDialogueManager()->say(actor, ESM::RefId::stringRefId("attack")); MWBase::Environment::get().getDialogueManager()->say(actor, ESM::RefId::stringRefId("attack"));
} }
} }
mAttackCooldown = std::min(baseDelay + 0.01 * Misc::Rng::roll0to99(prng), baseDelay + 0.9); mAttackCooldown = std::min(baseDelay + 0.01f * Misc::Rng::roll0to99(prng), baseDelay + 0.9f);
} }
else else
mAttackCooldown -= AI_REACTION_TIME; mAttackCooldown -= AI_REACTION_TIME;

View file

@ -514,7 +514,7 @@ namespace MWMechanics
const int flee = stats.getAiSetting(AiSetting::Flee).getModified(); const int flee = stats.getAiSetting(AiSetting::Flee).getModified();
if (flee >= 100) if (flee >= 100)
return flee; return static_cast<float>(flee);
static const float fAIFleeHealthMult = gmst.find("fAIFleeHealthMult")->mValue.getFloat(); static const float fAIFleeHealthMult = gmst.find("fAIFleeHealthMult")->mValue.getFloat();
static const float fAIFleeFleeMult = gmst.find("fAIFleeFleeMult")->mValue.getFloat(); static const float fAIFleeFleeMult = gmst.find("fAIFleeFleeMult")->mValue.getFloat();
@ -529,7 +529,7 @@ namespace MWMechanics
if (enemy.getClass().getNpcStats(enemy).isWerewolf() && stats.getLevel() < iWereWolfLevelToAttack) if (enemy.getClass().getNpcStats(enemy).isWerewolf() && stats.getLevel() < iWereWolfLevelToAttack)
{ {
static const int iWereWolfFleeMod = gmst.find("iWereWolfFleeMod")->mValue.getInteger(); static const int iWereWolfFleeMod = gmst.find("iWereWolfFleeMod")->mValue.getInteger();
rating = iWereWolfFleeMod; rating = static_cast<float>(iWereWolfFleeMod);
} }
} }

View file

@ -29,7 +29,7 @@ namespace MWMechanics
, mX(x) , mX(x)
, mY(y) , mY(y)
, mZ(z) , mZ(z)
, mDuration(duration) , mDuration(static_cast<float>(duration))
, mRemainingDuration(static_cast<float>(duration)) , mRemainingDuration(static_cast<float>(duration))
{ {
mTargetActorRefId = actorId; mTargetActorRefId = actorId;
@ -42,7 +42,7 @@ namespace MWMechanics
, mX(x) , mX(x)
, mY(y) , mY(y)
, mZ(z) , mZ(z)
, mDuration(duration) , mDuration(static_cast<float>(duration))
, mRemainingDuration(static_cast<float>(duration)) , mRemainingDuration(static_cast<float>(duration))
{ {
mTargetActorRefId = actorId; mTargetActorRefId = actorId;
@ -129,7 +129,7 @@ namespace MWMechanics
escort->mData.mX = mX; escort->mData.mX = mX;
escort->mData.mY = mY; escort->mData.mY = mY;
escort->mData.mZ = mZ; escort->mData.mZ = mZ;
escort->mData.mDuration = mDuration; escort->mData.mDuration = static_cast<int16_t>(mDuration);
escort->mTargetId = mTargetActorRefId; escort->mTargetId = mTargetActorRefId;
escort->mTargetActorId = mTargetActorId; escort->mTargetActorId = mTargetActorId;
escort->mRemainingDuration = mRemainingDuration; escort->mRemainingDuration = mRemainingDuration;

View file

@ -244,7 +244,7 @@ namespace MWMechanics
follow->mData.mX = mX; follow->mData.mX = mX;
follow->mData.mY = mY; follow->mData.mY = mY;
follow->mData.mZ = mZ; follow->mData.mZ = mZ;
follow->mData.mDuration = mDuration; follow->mData.mDuration = static_cast<int16_t>(mDuration);
follow->mTargetId = mTargetActorRefId; follow->mTargetId = mTargetActorRefId;
follow->mTargetActorId = mTargetActorId; follow->mTargetActorId = mTargetActorId;
follow->mRemainingDuration = mRemainingDuration; follow->mRemainingDuration = mRemainingDuration;

View file

@ -37,7 +37,7 @@ namespace
float getPointTolerance(float speed, float duration, const osg::Vec3f& halfExtents) float getPointTolerance(float speed, float duration, const osg::Vec3f& halfExtents)
{ {
const float actorTolerance = 2 * speed * duration + 1.2 * std::max(halfExtents.x(), halfExtents.y()); const float actorTolerance = 2 * speed * duration + 1.2f * std::max(halfExtents.x(), halfExtents.y());
return std::max(MWMechanics::MIN_TOLERANCE, actorTolerance); return std::max(MWMechanics::MIN_TOLERANCE, actorTolerance);
} }

View file

@ -65,10 +65,10 @@ namespace MWMechanics
osg::Vec3f getRandomPointAround(const osg::Vec3f& position, const float distance) osg::Vec3f getRandomPointAround(const osg::Vec3f& position, const float distance)
{ {
auto& prng = MWBase::Environment::get().getWorld()->getPrng(); auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const float randomDirection = Misc::Rng::rollClosedProbability(prng) * 2.0f * osg::PI; const float randomDirection = Misc::Rng::rollClosedProbability(prng) * 2.f * osg::PIf;
osg::Matrixf rotation; osg::Matrixf rotation;
rotation.makeRotate(randomDirection, osg::Vec3f(0.0, 0.0, 1.0)); rotation.makeRotate(randomDirection, osg::Vec3f(0.f, 0.f, 1.f));
return position + osg::Vec3f(distance, 0.0, 0.0) * rotation; return position + osg::Vec3f(distance, 0.f, 0.f) * rotation;
} }
bool isDestinationHidden(const MWWorld::ConstPtr& actor, const osg::Vec3f& destination) bool isDestinationHidden(const MWWorld::ConstPtr& actor, const osg::Vec3f& destination)
@ -158,13 +158,11 @@ namespace MWMechanics
: TypedAiPackage<AiWander>(repeat) : TypedAiPackage<AiWander>(repeat)
, mDistance(static_cast<unsigned>(std::max(0, distance))) , mDistance(static_cast<unsigned>(std::max(0, distance)))
, mDuration(static_cast<unsigned>(std::max(0, duration))) , mDuration(static_cast<unsigned>(std::max(0, duration)))
, mRemainingDuration(duration) , mRemainingDuration(static_cast<float>(duration))
, mTimeOfDay(timeOfDay) , mTimeOfDay(timeOfDay)
, mIdle(getInitialIdle(idle)) , mIdle(getInitialIdle(idle))
, mStoredInitialActorPosition(false) , mStoredInitialActorPosition(false)
, mInitialActorPosition(osg::Vec3f(0, 0, 0))
, mHasDestination(false) , mHasDestination(false)
, mDestination(osg::Vec3f(0, 0, 0))
, mUsePathgrid(false) , mUsePathgrid(false)
{ {
} }
@ -283,7 +281,7 @@ namespace MWMechanics
{ {
stopWalking(actor); stopWalking(actor);
// Reset package so it can be used again // Reset package so it can be used again
mRemainingDuration = mDuration; mRemainingDuration = static_cast<float>(mDuration);
return true; return true;
} }
@ -628,8 +626,7 @@ namespace MWMechanics
{ {
MWBase::World& world = *MWBase::Environment::get().getWorld(); MWBase::World& world = *MWBase::Environment::get().getWorld();
Misc::Rng::Generator& prng = world.getPrng(); Misc::Rng::Generator& prng = world.getPrng();
const std::size_t randomAllowedPositionIndex const std::size_t randomAllowedPositionIndex = Misc::Rng::rollDice(storage.mAllowedPositions.size(), prng);
= static_cast<std::size_t>(Misc::Rng::rollDice(storage.mAllowedPositions.size(), prng));
const osg::Vec3f randomAllowedPosition = storage.mAllowedPositions[randomAllowedPositionIndex]; const osg::Vec3f randomAllowedPosition = storage.mAllowedPositions[randomAllowedPositionIndex];
const osg::Vec3f start = actorPos.asVec3(); const osg::Vec3f start = actorPos.asVec3();
@ -734,7 +731,7 @@ namespace MWMechanics
} }
} }
int AiWander::getRandomIdle() const unsigned short AiWander::getRandomIdle() const
{ {
MWBase::World* world = MWBase::Environment::get().getWorld(); MWBase::World* world = MWBase::Environment::get().getWorld();
static const float fIdleChanceMultiplier static const float fIdleChanceMultiplier
@ -742,14 +739,14 @@ namespace MWMechanics
if (Misc::Rng::rollClosedProbability(world->getPrng()) > fIdleChanceMultiplier) if (Misc::Rng::rollClosedProbability(world->getPrng()) > fIdleChanceMultiplier)
return 0; return 0;
int newIdle = 0; unsigned short newIdle = 0;
float maxRoll = 0.f; float maxRoll = 0.f;
for (size_t i = 0; i < mIdle.size(); i++) for (size_t i = 0; i < mIdle.size(); i++)
{ {
float roll = Misc::Rng::rollClosedProbability(world->getPrng()) * 100.f; float roll = Misc::Rng::rollClosedProbability(world->getPrng()) * 100.f;
if (roll <= mIdle[i] && roll > maxRoll) if (roll <= mIdle[i] && roll > maxRoll)
{ {
newIdle = GroupIndex_MinIdle + i; newIdle = static_cast<unsigned short>(GroupIndex_MinIdle + i);
maxRoll = roll; maxRoll = roll;
} }
} }
@ -772,7 +769,7 @@ namespace MWMechanics
return; return;
auto& prng = MWBase::Environment::get().getWorld()->getPrng(); auto& prng = MWBase::Environment::get().getWorld()->getPrng();
int index = Misc::Rng::rollDice(storage.mAllowedPositions.size(), prng); size_t index = Misc::Rng::rollDice(storage.mAllowedPositions.size(), prng);
const osg::Vec3f worldDest = storage.mAllowedPositions[index]; const osg::Vec3f worldDest = storage.mAllowedPositions[index];
const Misc::CoordinateConverter converter = Misc::makeCoordinateConverter(*actor.getCell()->getCell()); const Misc::CoordinateConverter converter = Misc::makeCoordinateConverter(*actor.getCell()->getCell());
osg::Vec3f dest = converter.toLocalVec3(worldDest); osg::Vec3f dest = converter.toLocalVec3(worldDest);
@ -794,7 +791,7 @@ namespace MWMechanics
// AI will try to move the NPC towards every neighboring node until suitable place will be found // AI will try to move the NPC towards every neighboring node until suitable place will be found
while (!points.empty()) while (!points.empty())
{ {
int randomIndex = Misc::Rng::rollDice(points.size(), prng); size_t randomIndex = Misc::Rng::rollDice(points.size(), prng);
const ESM::Pathgrid::Point& connDest = points[randomIndex]; const ESM::Pathgrid::Point& connDest = points[randomIndex];
// add an offset towards random neighboring node // add an offset towards random neighboring node
@ -940,7 +937,7 @@ namespace MWMechanics
// must not travel longer than distance between waypoints or NPC goes past waypoint // must not travel longer than distance between waypoints or NPC goes past waypoint
distance = std::min(distance, static_cast<unsigned>(length)); distance = std::min(distance, static_cast<unsigned>(length));
delta *= distance; delta *= static_cast<float>(distance);
storage.mAllowedPositions.push_back(vectorStart + delta); storage.mAllowedPositions.push_back(vectorStart + delta);
} }
@ -968,12 +965,12 @@ namespace MWMechanics
if (mRemainingDuration > 0 && mRemainingDuration < 24) if (mRemainingDuration > 0 && mRemainingDuration < 24)
remainingDuration = mRemainingDuration; remainingDuration = mRemainingDuration;
else else
remainingDuration = mDuration; remainingDuration = static_cast<float>(mDuration);
auto wander = std::make_unique<ESM::AiSequence::AiWander>(); auto wander = std::make_unique<ESM::AiSequence::AiWander>();
wander->mData.mDistance = mDistance; wander->mData.mDistance = static_cast<int16_t>(mDistance);
wander->mData.mDuration = mDuration; wander->mData.mDuration = static_cast<int16_t>(mDuration);
wander->mData.mTimeOfDay = mTimeOfDay; wander->mData.mTimeOfDay = static_cast<uint8_t>(mTimeOfDay);
wander->mDurationData.mRemainingDuration = remainingDuration; wander->mDurationData.mRemainingDuration = remainingDuration;
assert(mIdle.size() == 8); assert(mIdle.size() == 8);
for (int i = 0; i < 8; ++i) for (int i = 0; i < 8; ++i)
@ -998,12 +995,11 @@ namespace MWMechanics
, mIdle(getInitialIdle(wander->mData.mIdle)) , mIdle(getInitialIdle(wander->mData.mIdle))
, mStoredInitialActorPosition(wander->mStoredInitialActorPosition) , mStoredInitialActorPosition(wander->mStoredInitialActorPosition)
, mHasDestination(false) , mHasDestination(false)
, mDestination(osg::Vec3f(0, 0, 0))
, mUsePathgrid(false) , mUsePathgrid(false)
{ {
if (mStoredInitialActorPosition) if (mStoredInitialActorPosition)
mInitialActorPosition = wander->mInitialActorPosition; mInitialActorPosition = wander->mInitialActorPosition;
if (mRemainingDuration <= 0 || mRemainingDuration >= 24) if (mRemainingDuration <= 0 || mRemainingDuration >= 24)
mRemainingDuration = mDuration; mRemainingDuration = static_cast<float>(mDuration);
} }
} }

View file

@ -131,7 +131,7 @@ namespace MWMechanics
/// @return Success or error /// @return Success or error
bool playIdle(const MWWorld::Ptr& actor, unsigned short idleSelect); bool playIdle(const MWWorld::Ptr& actor, unsigned short idleSelect);
bool checkIdle(const MWWorld::Ptr& actor, unsigned short idleSelect); bool checkIdle(const MWWorld::Ptr& actor, unsigned short idleSelect);
int getRandomIdle() const; unsigned short getRandomIdle() const;
void setPathToAnAllowedPosition( void setPathToAnAllowedPosition(
const MWWorld::Ptr& actor, AiWanderStorage& storage, const ESM::Position& actorPos); const MWWorld::Ptr& actor, AiWanderStorage& storage, const ESM::Position& actorPos);
void evadeObstacles(const MWWorld::Ptr& actor, AiWanderStorage& storage); void evadeObstacles(const MWWorld::Ptr& actor, AiWanderStorage& storage);

View file

@ -217,15 +217,15 @@ void MWMechanics::Alchemy::updateEffects()
if (magnitude > 0 && duration > 0) if (magnitude > 0 && duration > 0)
{ {
ESM::ENAMstruct effect; ESM::ENAMstruct effect;
effect.mEffectID = effectKey.mId; effect.mEffectID = static_cast<int16_t>(effectKey.mId);
effect.mAttribute = -1; effect.mAttribute = -1;
effect.mSkill = -1; effect.mSkill = -1;
if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetSkill) if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetSkill)
effect.mSkill = ESM::Skill::refIdToIndex(effectKey.mArg); effect.mSkill = static_cast<signed char>(ESM::Skill::refIdToIndex(effectKey.mArg));
else if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetAttribute) else if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetAttribute)
effect.mAttribute = ESM::Attribute::refIdToIndex(effectKey.mArg); effect.mAttribute = static_cast<signed char>(ESM::Attribute::refIdToIndex(effectKey.mArg));
effect.mRange = 0; effect.mRange = 0;
effect.mArea = 0; effect.mArea = 0;
@ -395,8 +395,7 @@ void MWMechanics::Alchemy::setAlchemist(const MWWorld::Ptr& npc)
MWWorld::ContainerStore& store = npc.getClass().getContainerStore(npc); MWWorld::ContainerStore& store = npc.getClass().getContainerStore(npc);
for (MWWorld::ContainerStoreIterator iter(store.begin(MWWorld::ContainerStore::Type_Apparatus)); for (auto iter(store.begin(MWWorld::ContainerStore::Type_Apparatus)); iter != store.end(); ++iter)
iter != store.end(); ++iter)
{ {
MWWorld::LiveCellRef<ESM::Apparatus>* ref = iter->get<ESM::Apparatus>(); MWWorld::LiveCellRef<ESM::Apparatus>* ref = iter->get<ESM::Apparatus>();
@ -604,7 +603,8 @@ std::string MWMechanics::Alchemy::suggestPotionName()
return effects.begin()->toString(); return effects.begin()->toString();
} }
std::vector<std::string> MWMechanics::Alchemy::effectsDescription(const MWWorld::ConstPtr& ptr, const float alchemySkill) std::vector<std::string> MWMechanics::Alchemy::effectsDescription(
const MWWorld::ConstPtr& ptr, const float alchemySkill)
{ {
std::vector<std::string> effects; std::vector<std::string> effects;

View file

@ -278,10 +278,10 @@ namespace MWMechanics
.find("fEffectCostMult") .find("fEffectCostMult")
->mValue.getFloat(); ->mValue.getFloat();
float x = 0.5 * (std::max(1, minMagn) + std::max(1, maxMagn)); float x = 0.5f * (std::max(1, minMagn) + std::max(1, maxMagn));
x *= 0.1 * magicEffect->mData.mBaseCost; x *= 0.1f * magicEffect->mData.mBaseCost;
x *= 1 + duration; x *= 1 + duration;
x += 0.05 * std::max(1, effect.mData.mArea) * magicEffect->mData.mBaseCost; x += 0.05f * std::max(1, effect.mData.mArea) * magicEffect->mData.mBaseCost;
x *= fEffectCostMult; x *= fEffectCostMult;
if (effect.mData.mRange == ESM::RT_Target) if (effect.mData.mRange == ESM::RT_Target)

View file

@ -131,7 +131,7 @@ namespace MWMechanics
static const int iBlockMaxChance = gmst.find("iBlockMaxChance")->mValue.getInteger(); static const int iBlockMaxChance = gmst.find("iBlockMaxChance")->mValue.getInteger();
static const int iBlockMinChance = gmst.find("iBlockMinChance")->mValue.getInteger(); static const int iBlockMinChance = gmst.find("iBlockMinChance")->mValue.getInteger();
int x = std::clamp<int>(blockerTerm - attackerTerm, iBlockMinChance, iBlockMaxChance); int x = std::clamp(static_cast<int>(blockerTerm - attackerTerm), iBlockMinChance, iBlockMaxChance);
auto& prng = MWBase::Environment::get().getWorld()->getPrng(); auto& prng = MWBase::Environment::get().getWorld()->getPrng();
if (Misc::Rng::roll0to99(prng) < x) if (Misc::Rng::roll0to99(prng) < x)
@ -237,7 +237,7 @@ namespace MWMechanics
if (attacker == getPlayer()) if (attacker == getPlayer())
MWBase::Environment::get().getWindowManager()->setEnemy(victim); MWBase::Environment::get().getWindowManager()->setEnemy(victim);
int skillValue = attacker.getClass().getSkill(attacker, weaponSkill); int skillValue = static_cast<int>(attacker.getClass().getSkill(attacker, weaponSkill));
if (Misc::Rng::roll0to99(world->getPrng()) >= getHitChance(attacker, victim, skillValue)) if (Misc::Rng::roll0to99(world->getPrng()) >= getHitChance(attacker, victim, skillValue))
{ {
@ -373,7 +373,7 @@ namespace MWMechanics
float x = std::max(0.f, saveTerm - Misc::Rng::roll0to99(prng)); float x = std::max(0.f, saveTerm - Misc::Rng::roll0to99(prng));
int element = ESM::MagicEffect::FireDamage; short element = ESM::MagicEffect::FireDamage;
if (i == 1) if (i == 1)
element = ESM::MagicEffect::ShockDamage; element = ESM::MagicEffect::ShockDamage;
if (i == 2) if (i == 2)
@ -627,7 +627,7 @@ namespace MWMechanics
actor.getClass().getCreatureStats(actor).getAiSequence().getCombatTargets(targets); actor.getClass().getCreatureStats(actor).getAiSequence().getCombatTargets(targets);
else else
MWBase::Environment::get().getMechanicsManager()->getActorsInRange( MWBase::Environment::get().getMechanicsManager()->getActorsInRange(
actorPos, Settings::game().mActorsProcessingRange, targets); actorPos, static_cast<float>(Settings::game().mActorsProcessingRange), targets);
for (MWWorld::Ptr& target : targets) for (MWWorld::Ptr& target : targets)
{ {

View file

@ -407,8 +407,8 @@ namespace MWMechanics
else else
base = world->getStore().get<ESM::GameSetting>().find("fNPCbaseMagickaMult")->mValue.getFloat(); base = world->getStore().get<ESM::GameSetting>().find("fNPCbaseMagickaMult")->mValue.getFloat();
double magickaFactor = base float magickaFactor = base
+ mMagicEffects.getOrDefault(EffectKey(ESM::MagicEffect::FortifyMaximumMagicka)).getMagnitude() * 0.1; + mMagicEffects.getOrDefault(EffectKey(ESM::MagicEffect::FortifyMaximumMagicka)).getMagnitude() * 0.1f;
DynamicStat<float> magicka = getMagicka(); DynamicStat<float> magicka = getMagicka();
float currentToBaseRatio = magicka.getBase() > 0 ? magicka.getCurrent() / magicka.getBase() : 0; float currentToBaseRatio = magicka.getBase() > 0 ? magicka.getCurrent() / magicka.getBase() : 0;
@ -507,7 +507,7 @@ namespace MWMechanics
void CreatureStats::writeState(ESM::CreatureStats& state) const void CreatureStats::writeState(ESM::CreatureStats& state) const
{ {
for (size_t i = 0; i < state.mAttributes.size(); ++i) for (size_t i = 0; i < state.mAttributes.size(); ++i)
getAttribute(ESM::Attribute::indexToRefId(i)).writeState(state.mAttributes[i]); getAttribute(ESM::Attribute::indexToRefId(static_cast<int>(i))).writeState(state.mAttributes[i]);
for (size_t i = 0; i < state.mDynamic.size(); ++i) for (size_t i = 0; i < state.mDynamic.size(); ++i)
mDynamic[i].writeState(state.mDynamic[i]); mDynamic[i].writeState(state.mDynamic[i]);
@ -564,7 +564,7 @@ namespace MWMechanics
if (!state.mMissingACDT) if (!state.mMissingACDT)
{ {
for (size_t i = 0; i < state.mAttributes.size(); ++i) for (size_t i = 0; i < state.mAttributes.size(); ++i)
mAttributes[ESM::Attribute::indexToRefId(i)].readState(state.mAttributes[i]); mAttributes[ESM::Attribute::indexToRefId(static_cast<int>(i))].readState(state.mAttributes[i]);
for (size_t i = 0; i < state.mDynamic.size(); ++i) for (size_t i = 0; i < state.mDynamic.size(); ++i)
mDynamic[i].readState(state.mDynamic[i]); mDynamic[i].readState(state.mDynamic[i]);

View file

@ -300,7 +300,7 @@ namespace MWMechanics
->mValue.getFloat(); ->mValue.getFloat();
int price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer( int price = MWBase::Environment::get().getMechanicsManager()->getBarterOffer(
mEnchanter, static_cast<int>(finalEffectCost * priceMultipler), true); mEnchanter, static_cast<int>(finalEffectCost * priceMultipler), true);
price *= count * getTypeMultiplier(); price *= static_cast<int>(count * getTypeMultiplier());
return std::max(1, price); return std::max(1, price);
} }
@ -381,8 +381,9 @@ namespace MWMechanics
{ {
MWWorld::Ptr player = getPlayer(); MWWorld::Ptr player = getPlayer();
count = player.getClass().getContainerStore(player).count(mOldItemPtr.getCellRef().getRefId()); count = player.getClass().getContainerStore(player).count(mOldItemPtr.getCellRef().getRefId());
count = std::clamp<int>( count = std::clamp(
getGemCharge() * Settings::game().mProjectilesEnchantMultiplier / enchantPoints, 1, count); static_cast<int>(getGemCharge() * Settings::game().mProjectilesEnchantMultiplier / enchantPoints),
1, count);
} }
} }

View file

@ -135,10 +135,10 @@ namespace MWMechanics
creatureStats.getActiveSpells().clear(ptr); creatureStats.getActiveSpells().clear(ptr);
for (size_t i = 0; i < player->mNpdt.mSkills.size(); ++i) for (size_t i = 0; i < player->mNpdt.mSkills.size(); ++i)
npcStats.getSkill(ESM::Skill::indexToRefId(i)).setBase(player->mNpdt.mSkills[i]); npcStats.getSkill(ESM::Skill::indexToRefId(static_cast<int>(i))).setBase(player->mNpdt.mSkills[i]);
for (size_t i = 0; i < player->mNpdt.mAttributes.size(); ++i) for (size_t i = 0; i < player->mNpdt.mAttributes.size(); ++i)
npcStats.setAttribute(ESM::Attribute::indexToRefId(i), player->mNpdt.mSkills[i]); npcStats.setAttribute(ESM::Attribute::indexToRefId(static_cast<int>(i)), player->mNpdt.mSkills[i]);
const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore(); const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore();
@ -150,7 +150,8 @@ namespace MWMechanics
bool male = (player->mFlags & ESM::NPC::Female) == 0; bool male = (player->mFlags & ESM::NPC::Female) == 0;
for (const ESM::Attribute& attribute : esmStore.get<ESM::Attribute>()) for (const ESM::Attribute& attribute : esmStore.get<ESM::Attribute>())
creatureStats.setAttribute(attribute.mId, race->mData.getAttribute(attribute.mId, male)); creatureStats.setAttribute(
attribute.mId, static_cast<float>(race->mData.getAttribute(attribute.mId, male)));
for (const ESM::Skill& skill : esmStore.get<ESM::Skill>()) for (const ESM::Skill& skill : esmStore.get<ESM::Skill>())
{ {
@ -161,7 +162,7 @@ namespace MWMechanics
if (bonusIt != race->mData.mBonus.end()) if (bonusIt != race->mData.mBonus.end())
bonus = bonusIt->mBonus; bonus = bonusIt->mBonus;
npcStats.getSkill(skill.mId).setBase(5 + bonus); npcStats.getSkill(skill.mId).setBase(5.f + bonus);
} }
for (const ESM::RefId& power : race->mPowers.mList) for (const ESM::RefId& power : race->mPowers.mList)
@ -566,7 +567,7 @@ namespace MWMechanics
.getMagnitude(); .getMagnitude();
if (clamp) if (clamp)
return std::clamp<int>(x, 0, 100); //, normally clamped to [0..100] when used return std::clamp(static_cast<int>(x), 0, 100); //, normally clamped to [0..100] when used
return static_cast<int>(x); return static_cast<int>(x);
} }
@ -1733,10 +1734,8 @@ namespace MWMechanics
// if guard starts combat with player, guards pursuing player should do the same // if guard starts combat with player, guards pursuing player should do the same
if (ptr.getClass().isClass(ptr, "Guard")) if (ptr.getClass().isClass(ptr, "Guard"))
{ {
stats.setHitAttemptActorId( // Stops guard from ending combat if player is unreachable
target.getClass() stats.setHitAttemptActorId(target.getClass().getCreatureStats(target).getActorId());
.getCreatureStats(target)
.getActorId()); // Stops guard from ending combat if player is unreachable
for (const Actor& actor : mActors) for (const Actor& actor : mActors)
{ {
if (actor.isInvalid()) if (actor.isInvalid())
@ -1749,13 +1748,11 @@ namespace MWMechanics
{ {
aiSeq.stopPursuit(); aiSeq.stopPursuit();
aiSeq.stack(MWMechanics::AiCombat(target), ptr); aiSeq.stack(MWMechanics::AiCombat(target), ptr);
// Stops guard from ending combat if player is unreachable
actor.getPtr() actor.getPtr()
.getClass() .getClass()
.getCreatureStats(actor.getPtr()) .getCreatureStats(actor.getPtr())
.setHitAttemptActorId( .setHitAttemptActorId(target.getClass().getCreatureStats(target).getActorId());
target.getClass()
.getCreatureStats(target)
.getActorId()); // Stops guard from ending combat if player is unreachable
} }
} }
} }
@ -1830,7 +1827,7 @@ namespace MWMechanics
mActors.getActorsSidingWith(actor, out); mActors.getActorsSidingWith(actor, out);
} }
int MechanicsManager::countSavedGameRecords() const size_t MechanicsManager::countSavedGameRecords() const
{ {
return 1 // Death counter return 1 // Death counter
+ 1; // Stolen items + 1; // Stolen items
@ -2051,8 +2048,8 @@ namespace MWMechanics
void MechanicsManager::reportStats(unsigned int frameNumber, osg::Stats& stats) const void MechanicsManager::reportStats(unsigned int frameNumber, osg::Stats& stats) const
{ {
stats.setAttribute(frameNumber, "Mechanics Actors", mActors.size()); stats.setAttribute(frameNumber, "Mechanics Actors", static_cast<double>(mActors.size()));
stats.setAttribute(frameNumber, "Mechanics Objects", mObjects.size()); stats.setAttribute(frameNumber, "Mechanics Objects", static_cast<double>(mObjects.size()));
} }
int MechanicsManager::getGreetingTimer(const MWWorld::Ptr& ptr) const int MechanicsManager::getGreetingTimer(const MWWorld::Ptr& ptr) const

View file

@ -182,7 +182,7 @@ namespace MWMechanics
bool onOpen(const MWWorld::Ptr& ptr) override; bool onOpen(const MWWorld::Ptr& ptr) override;
void onClose(const MWWorld::Ptr& ptr) override; void onClose(const MWWorld::Ptr& ptr) override;
int countSavedGameRecords() const override; size_t countSavedGameRecords() const override;
void write(ESM::ESMWriter& writer, Loading::Listener& listener) const override; void write(ESM::ESMWriter& writer, Loading::Listener& listener) const override;

View file

@ -493,7 +493,7 @@ void MWMechanics::NpcStats::readState(const ESM::NpcStats& state)
for (size_t i = 0; i < state.mSkills.size(); ++i) for (size_t i = 0; i < state.mSkills.size(); ++i)
{ {
// TODO extend format // TODO extend format
ESM::RefId id = ESM::Skill::indexToRefId(i); ESM::RefId id = ESM::Skill::indexToRefId(static_cast<int>(i));
assert(!id.empty()); assert(!id.empty());
mSkills[id].readState(state.mSkills[i]); mSkills[id].readState(state.mSkills[i]);
} }
@ -507,7 +507,7 @@ void MWMechanics::NpcStats::readState(const ESM::NpcStats& state)
mLevelProgress = state.mLevelProgress; mLevelProgress = state.mLevelProgress;
for (size_t i = 0; i < state.mSkillIncrease.size(); ++i) for (size_t i = 0; i < state.mSkillIncrease.size(); ++i)
mSkillIncreases[ESM::Attribute::indexToRefId(i)] = state.mSkillIncrease[i]; mSkillIncreases[ESM::Attribute::indexToRefId(static_cast<int>(i))] = state.mSkillIncrease[i];
for (size_t i = 0; i < state.mSpecIncreases.size(); ++i) for (size_t i = 0; i < state.mSpecIncreases.size(); ++i)
mSpecIncreases[i] = state.mSpecIncreases[i]; mSpecIncreases[i] = state.mSpecIncreases[i];

View file

@ -80,7 +80,7 @@ namespace
{ {
const auto world = MWBase::Environment::get().getWorld(); const auto world = MWBase::Environment::get().getWorld();
const auto halfExtents = world->getHalfExtents(actor); const auto halfExtents = world->getHalfExtents(actor);
return 2.0 * halfExtents.z(); return 2.f * halfExtents.z();
} }
// Returns true if turn in `p2` is less than 10 degrees and all the 3 points are almost on one line. // Returns true if turn in `p2` is less than 10 degrees and all the 3 points are almost on one line.
@ -93,7 +93,7 @@ namespace
float crossProduct = v1.x() * v3.y() - v1.y() * v3.x(); float crossProduct = v1.x() * v3.y() - v1.y() * v3.x();
// Check that the angle between v1 and v3 is less or equal than 5 degrees. // Check that the angle between v1 and v3 is less or equal than 5 degrees.
static const float cos175 = std::cos(osg::PI * (175.0 / 180)); static const float cos175 = std::cos(osg::PIf * (175.f / 180));
bool checkAngle = dotProduct <= cos175 * v1.length() * v3.length(); bool checkAngle = dotProduct <= cos175 * v1.length() * v3.length();
// Check that distance from p2 to the line (p1, p3) is less or equal than `pointTolerance`. // Check that distance from p2 to the line (p1, p3) is less or equal than `pointTolerance`.
@ -246,12 +246,11 @@ namespace MWMechanics
// Add Z offset since path node can overlap with other objects. // Add Z offset since path node can overlap with other objects.
// Also ignore doors in raytesting. // Also ignore doors in raytesting.
const int mask = MWPhysics::CollisionType_World; const int mask = MWPhysics::CollisionType_World;
bool isPathClear = !MWBase::Environment::get() const osg::Vec3f zOffset(0.f, 0.f, 16.f);
.getWorld() const osg::Vec3f from = startPoint + zOffset;
->getRayCasting() const osg::Vec3f to = Misc::Convert::makeOsgVec3f(temp) + zOffset;
->castRay(osg::Vec3f(startPoint.x(), startPoint.y(), startPoint.z() + 16), bool isPathClear
osg::Vec3f(temp.mX, temp.mY, temp.mZ + 16), mask) = !MWBase::Environment::get().getWorld()->getRayCasting()->castRay(from, to, mask).mHit;
.mHit;
if (isPathClear) if (isPathClear)
path.pop_front(); path.pop_front();
} }

View file

@ -92,7 +92,7 @@ namespace MWMechanics
} }
// Get the actors in range of the effect // Get the actors in range of the effect
std::vector<MWWorld::Ptr> objects; std::vector<MWWorld::Ptr> objects;
static const int unitsPerFoot = ceil(Constants::UnitsPerFoot); static const int unitsPerFoot = static_cast<int>(std::ceil(Constants::UnitsPerFoot));
MWBase::Environment::get().getMechanicsManager()->getObjectsInRange( MWBase::Environment::get().getMechanicsManager()->getObjectsInRange(
mHitPosition, static_cast<float>(effectInfo.mData.mArea * unitsPerFoot), objects); mHitPosition, static_cast<float>(effectInfo.mData.mArea * unitsPerFoot), objects);
for (const MWWorld::Ptr& affected : objects) for (const MWWorld::Ptr& affected : objects)
@ -204,8 +204,8 @@ namespace MWMechanics
effect.mEffectId = enam.mData.mEffectID; effect.mEffectId = enam.mData.mEffectID;
effect.mArg = MWMechanics::EffectKey(enam.mData).mArg; effect.mArg = MWMechanics::EffectKey(enam.mData).mArg;
effect.mMagnitude = 0.f; effect.mMagnitude = 0.f;
effect.mMinMagnitude = enam.mData.mMagnMin; effect.mMinMagnitude = static_cast<float>(enam.mData.mMagnMin);
effect.mMaxMagnitude = enam.mData.mMagnMax; effect.mMaxMagnitude = static_cast<float>(enam.mData.mMagnMax);
effect.mTimeLeft = 0.f; effect.mTimeLeft = 0.f;
effect.mEffectIndex = enam.mIndex; effect.mEffectIndex = enam.mIndex;
effect.mFlags = ESM::ActiveEffect::Flag_None; effect.mFlags = ESM::ActiveEffect::Flag_None;

View file

@ -41,7 +41,8 @@ namespace
if (effect.mMinMagnitude == effect.mMaxMagnitude) if (effect.mMinMagnitude == effect.mMaxMagnitude)
return effect.mMinMagnitude; return effect.mMinMagnitude;
auto& prng = MWBase::Environment::get().getWorld()->getPrng(); auto& prng = MWBase::Environment::get().getWorld()->getPrng();
return effect.mMinMagnitude + Misc::Rng::rollDice(effect.mMaxMagnitude - effect.mMinMagnitude + 1, prng); return effect.mMinMagnitude
+ Misc::Rng::rollDice(static_cast<int>(effect.mMaxMagnitude - effect.mMinMagnitude + 1), prng);
} }
void modifyAiSetting(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, void modifyAiSetting(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect,
@ -365,8 +366,8 @@ namespace
{ {
const ESM::Spell* spell const ESM::Spell* spell
= spellParams.hasFlag(ESM::ActiveSpells::Flag_Temporary) ? spellParams.getSpell() : nullptr; = spellParams.hasFlag(ESM::ActiveSpells::Flag_Temporary) ? spellParams.getSpell() : nullptr;
float magnitudeMult float magnitudeMult = MWMechanics::getEffectMultiplier(
= MWMechanics::getEffectMultiplier(effect.mEffectId, target, caster, spell, &magnitudes); static_cast<short>(effect.mEffectId), target, caster, spell, &magnitudes);
if (magnitudeMult == 0) if (magnitudeMult == 0)
{ {
// Fully resisted, show message // Fully resisted, show message

View file

@ -75,10 +75,10 @@ namespace MWMechanics
costMult = iAlchemyMod; costMult = iAlchemyMod;
} }
float x = 0.5 * (minMagn + maxMagn); float x = 0.5f * (minMagn + maxMagn);
x *= 0.1 * magicEffect->mData.mBaseCost; x *= 0.1f * magicEffect->mData.mBaseCost;
x *= durationOffset + duration; x *= durationOffset + duration;
x += 0.05 * std::max(minArea, effect.mArea) * magicEffect->mData.mBaseCost; x += 0.05f * std::max(minArea, effect.mArea) * magicEffect->mData.mBaseCost;
return x * costMult; return x * costMult;
} }
@ -90,7 +90,7 @@ namespace MWMechanics
float cost = getTotalCost(spell.mEffects); float cost = getTotalCost(spell.mEffects);
return std::round(cost); return static_cast<int>(std::round(cost));
} }
int getEffectiveEnchantmentCastCost(float castCost, const MWWorld::Ptr& actor) int getEffectiveEnchantmentCastCost(float castCost, const MWWorld::Ptr& actor)
@ -99,7 +99,7 @@ namespace MWMechanics
* Each point of enchant skill above/under 10 subtracts/adds * Each point of enchant skill above/under 10 subtracts/adds
* one percent of enchantment cost while minimum is 1. * one percent of enchantment cost while minimum is 1.
*/ */
int eSkill = actor.getClass().getSkill(actor, ESM::Skill::Enchant); float eSkill = actor.getClass().getSkill(actor, ESM::Skill::Enchant);
const float result = castCost - (castCost / 100) * (eSkill - 10); const float result = castCost - (castCost / 100) * (eSkill - 10);
return static_cast<int>((result < 1) ? 1 : result); return static_cast<int>((result < 1) ? 1 : result);
@ -154,7 +154,7 @@ namespace MWMechanics
if (potion.mData.mFlags & ESM::Potion::Autocalc) if (potion.mData.mFlags & ESM::Potion::Autocalc)
{ {
float cost = getTotalCost(potion.mEffects, EffectCostMethod::GamePotion); float cost = getTotalCost(potion.mEffects, EffectCostMethod::GamePotion);
return std::round(cost); return static_cast<int>(std::round(cost));
} }
return potion.mData.mValue; return potion.mData.mValue;
} }
@ -166,9 +166,9 @@ namespace MWMechanics
throw std::range_error("Index out of range"); throw std::range_error("Index out of range");
ESM::ENAMstruct effect; ESM::ENAMstruct effect;
effect.mEffectID = ingredient->mData.mEffectID[index]; effect.mEffectID = static_cast<int16_t>(ingredient->mData.mEffectID[index]);
effect.mSkill = ingredient->mData.mSkills[index]; effect.mSkill = static_cast<signed char>(ingredient->mData.mSkills[index]);
effect.mAttribute = ingredient->mData.mAttributes[index]; effect.mAttribute = static_cast<signed char>(ingredient->mData.mAttributes[index]);
effect.mRange = ESM::RT_Self; effect.mRange = ESM::RT_Self;
effect.mArea = 0; effect.mArea = 0;
@ -275,22 +275,22 @@ namespace MWMechanics
CreatureStats& stats = actor.getClass().getCreatureStats(actor); CreatureStats& stats = actor.getClass().getCreatureStats(actor);
if (spell->mData.mType == ESM::Spell::ST_Power) if (spell->mData.mType == ESM::Spell::ST_Power)
return stats.getSpells().canUsePower(spell) ? 100 : 0; return stats.getSpells().canUsePower(spell) ? 100.f : 0.f;
if (godmode) if (godmode)
return 100; return 100.f;
if (stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Silence).getMagnitude()) if (stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Silence).getMagnitude())
return 0; return 0.f;
if (spell->mData.mType != ESM::Spell::ST_Spell) if (spell->mData.mType != ESM::Spell::ST_Spell)
return 100; return 100.f;
if (checkMagicka && calcSpellCost(*spell) > 0 && stats.getMagicka().getCurrent() < calcSpellCost(*spell)) if (checkMagicka && calcSpellCost(*spell) > 0 && stats.getMagicka().getCurrent() < calcSpellCost(*spell))
return 0; return 0.f;
if (spell->mData.mFlags & ESM::Spell::F_Always) if (spell->mData.mFlags & ESM::Spell::F_Always)
return 100; return 100.f;
float castBonus = -stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Sound).getMagnitude(); float castBonus = -stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Sound).getMagnitude();
float castChance = baseChance + castBonus; float castChance = baseChance + castBonus;

View file

@ -16,7 +16,8 @@ namespace MWMechanics
bool smoothTurn(const MWWorld::Ptr& actor, float targetAngleRadians, int axis, float epsilonRadians) bool smoothTurn(const MWWorld::Ptr& actor, float targetAngleRadians, int axis, float epsilonRadians)
{ {
MWMechanics::Movement& movement = actor.getClass().getMovementSettings(actor); MWMechanics::Movement& movement = actor.getClass().getMovementSettings(actor);
float diff = Misc::normalizeAngle(targetAngleRadians - actor.getRefData().getPosition().rot[axis]); float diff
= static_cast<float>(Misc::normalizeAngle(targetAngleRadians - actor.getRefData().getPosition().rot[axis]));
float absDiff = std::abs(diff); float absDiff = std::abs(diff);
// The turning animation actually moves you slightly, so the angle will be wrong again. // The turning animation actually moves you slightly, so the angle will be wrong again.
@ -27,7 +28,7 @@ namespace MWMechanics
float limit float limit
= getAngularVelocity(actor.getClass().getMaxSpeed(actor)) * MWBase::Environment::get().getFrameDuration(); = getAngularVelocity(actor.getClass().getMaxSpeed(actor)) * MWBase::Environment::get().getFrameDuration();
if (Settings::game().mSmoothMovement) if (Settings::game().mSmoothMovement)
limit *= std::min(absDiff / osg::PI + 0.1, 0.5); limit *= std::min(absDiff / osg::PIf + 0.1f, 0.5f);
if (absDiff > limit) if (absDiff > limit)
diff = osg::sign(diff) * limit; diff = osg::sign(diff) * limit;

View file

@ -117,12 +117,12 @@ namespace MWMechanics
} }
} }
int value = 50.f; int value = 50;
ESM::RefId skill = item.getClass().getEquipmentSkill(item); ESM::RefId skill = item.getClass().getEquipmentSkill(item);
if (!skill.empty()) if (!skill.empty())
value = actor.getClass().getSkill(actor, skill); value = static_cast<int>(actor.getClass().getSkill(actor, skill));
// Prefer hand-to-hand if our skill is 0 (presumably due to magic) // Prefer hand-to-hand if our skill is 0 (presumably due to magic)
if (value <= 0.f) if (value <= 0)
return 0.f; return 0.f;
// Note that a creature with a dagger and 0 Stealth will forgo the weapon despite using Combat for hit chance. // Note that a creature with a dagger and 0 Stealth will forgo the weapon despite using Combat for hit chance.
// The same creature will use a sword provided its Combat stat isn't 0. We're using the "skill" value here to // The same creature will use a sword provided its Combat stat isn't 0. We're using the "skill" value here to

View file

@ -458,10 +458,10 @@ namespace MWPhysics
thread.join(); thread.join();
} }
std::tuple<int, float> PhysicsTaskScheduler::calculateStepConfig(float timeAccum) const std::tuple<unsigned, float> PhysicsTaskScheduler::calculateStepConfig(float timeAccum) const
{ {
int maxAllowedSteps = 2; unsigned maxAllowedSteps = 2;
int numSteps = timeAccum / mDefaultPhysicsDt; unsigned numSteps = static_cast<unsigned>(timeAccum / mDefaultPhysicsDt);
// adjust maximum step count based on whether we're likely physics bottlenecked or not // adjust maximum step count based on whether we're likely physics bottlenecked or not
// if maxAllowedSteps ends up higher than numSteps, we will not invoke delta time // if maxAllowedSteps ends up higher than numSteps, we will not invoke delta time
@ -478,13 +478,13 @@ namespace MWPhysics
// ensure sane minimum value // ensure sane minimum value
budgetMeasurement = std::max(0.00001f, budgetMeasurement); budgetMeasurement = std::max(0.00001f, budgetMeasurement);
// we're spending almost or more than realtime per physics frame; limit to a single step // we're spending almost or more than realtime per physics frame; limit to a single step
if (budgetMeasurement > 0.95) if (budgetMeasurement > 0.95f)
maxAllowedSteps = 1; maxAllowedSteps = 1;
// physics is fairly cheap; limit based on expense // physics is fairly cheap; limit based on expense
if (budgetMeasurement < 0.5) if (budgetMeasurement < 0.5f)
maxAllowedSteps = std::ceil(1.0 / budgetMeasurement); maxAllowedSteps = static_cast<unsigned>(std::ceil(1.f / budgetMeasurement));
// limit to a reasonable amount // limit to a reasonable amount
maxAllowedSteps = std::min(10, maxAllowedSteps); maxAllowedSteps = std::min(10u, maxAllowedSteps);
// fall back to delta time for this frame if fixed timestep physics would fall behind // fall back to delta time for this frame if fixed timestep physics would fall behind
float actualDelta = mDefaultPhysicsDt; float actualDelta = mDefaultPhysicsDt;
@ -523,7 +523,7 @@ namespace MWPhysics
MaybeExclusiveLock lock(mSimulationMutex, mLockingPolicy); MaybeExclusiveLock lock(mSimulationMutex, mLockingPolicy);
double timeStart = mTimer->tick(); auto timeStart = mTimer->tick();
// start by finishing previous background computation // start by finishing previous background computation
if (mNumThreads != 0) if (mNumThreads != 0)
@ -550,7 +550,7 @@ namespace MWPhysics
mPhysicsDt = newDelta; mPhysicsDt = newDelta;
mSimulations = &simulations; mSimulations = &simulations;
mAdvanceSimulation = (mRemainingSteps != 0); mAdvanceSimulation = (mRemainingSteps != 0);
mNumJobs = mSimulations->size(); mNumJobs = static_cast<int>(mSimulations->size());
mNextLOS.store(0, std::memory_order_relaxed); mNextLOS.store(0, std::memory_order_relaxed);
mNextJob.store(0, std::memory_order_release); mNextJob.store(0, std::memory_order_release);
@ -699,7 +699,7 @@ namespace MWPhysics
{ {
MaybeSharedLock lock(mLOSCacheMutex, mLockingPolicy); MaybeSharedLock lock(mLOSCacheMutex, mLockingPolicy);
int job = 0; int job = 0;
int numLOS = mLOSCache.size(); int numLOS = static_cast<int>(mLOSCache.size());
while ((job = mNextLOS.fetch_add(1, std::memory_order_relaxed)) < numLOS) while ((job = mNextLOS.fetch_add(1, std::memory_order_relaxed)) < numLOS)
{ {
auto& req = mLOSCache[job]; auto& req = mLOSCache[job];
@ -764,9 +764,9 @@ namespace MWPhysics
bool PhysicsTaskScheduler::hasLineOfSight(const Actor* actor1, const Actor* actor2) bool PhysicsTaskScheduler::hasLineOfSight(const Actor* actor1, const Actor* actor2)
{ {
btVector3 pos1 = Misc::Convert::toBullet( btVector3 pos1 = Misc::Convert::toBullet(
actor1->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor1->getHalfExtents().z() * 0.9)); // eye level actor1->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor1->getHalfExtents().z() * 0.9f)); // eye level
btVector3 pos2 = Misc::Convert::toBullet( btVector3 pos2 = Misc::Convert::toBullet(
actor2->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor2->getHalfExtents().z() * 0.9)); actor2->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor2->getHalfExtents().z() * 0.9f));
btCollisionWorld::ClosestRayResultCallback resultCallback(pos1, pos2); btCollisionWorld::ClosestRayResultCallback resultCallback(pos1, pos2);
resultCallback.m_collisionFilterGroup = CollisionType_AnyPhysical; resultCallback.m_collisionFilterGroup = CollisionType_AnyPhysical;

View file

@ -83,7 +83,7 @@ namespace MWPhysics
void updateAabbs(); void updateAabbs();
void updatePtrAabb(const std::shared_ptr<PtrHolder>& ptr); void updatePtrAabb(const std::shared_ptr<PtrHolder>& ptr);
void updateStats(osg::Timer_t frameStart, unsigned int frameNumber, osg::Stats& stats); void updateStats(osg::Timer_t frameStart, unsigned int frameNumber, osg::Stats& stats);
std::tuple<int, float> calculateStepConfig(float timeAccum) const; std::tuple<unsigned, float> calculateStepConfig(float timeAccum) const;
void afterPreStep(); void afterPreStep();
void afterPostStep(); void afterPostStep();
void afterPostSim(); void afterPostSim();
@ -111,7 +111,7 @@ namespace MWPhysics
LockingPolicy mLockingPolicy; LockingPolicy mLockingPolicy;
unsigned mNumThreads; unsigned mNumThreads;
int mNumJobs; int mNumJobs;
int mRemainingSteps; unsigned mRemainingSteps;
int mLOSCacheExpiry; int mLOSCacheExpiry;
bool mAdvanceSimulation; bool mAdvanceSimulation;
std::atomic<int> mNextJob; std::atomic<int> mNextJob;
@ -126,7 +126,7 @@ namespace MWPhysics
unsigned int mFrameNumber; unsigned int mFrameNumber;
const osg::Timer* mTimer; const osg::Timer* mTimer;
int mPrevStepCount; unsigned mPrevStepCount;
Misc::BudgetMeasurement mBudget; Misc::BudgetMeasurement mBudget;
Misc::BudgetMeasurement mAsyncBudget; Misc::BudgetMeasurement mAsyncBudget;
unsigned int mBudgetCursor; unsigned int mBudgetCursor;

View file

@ -865,10 +865,10 @@ namespace MWPhysics
void PhysicsSystem::reportStats(unsigned int frameNumber, osg::Stats& stats) const void PhysicsSystem::reportStats(unsigned int frameNumber, osg::Stats& stats) const
{ {
stats.setAttribute(frameNumber, "Physics Actors", mActors.size()); stats.setAttribute(frameNumber, "Physics Actors", static_cast<double>(mActors.size()));
stats.setAttribute(frameNumber, "Physics Objects", mObjects.size()); stats.setAttribute(frameNumber, "Physics Objects", static_cast<double>(mObjects.size()));
stats.setAttribute(frameNumber, "Physics Projectiles", mProjectiles.size()); stats.setAttribute(frameNumber, "Physics Projectiles", static_cast<double>(mProjectiles.size()));
stats.setAttribute(frameNumber, "Physics HeightFields", mHeightFields.size()); stats.setAttribute(frameNumber, "Physics HeightFields", static_cast<double>(mHeightFields.size()));
} }
void PhysicsSystem::reportCollision(const btVector3& position, const btVector3& normal) void PhysicsSystem::reportCollision(const btVector3& position, const btVector3& normal)

View file

@ -67,10 +67,10 @@ namespace MWPhysics
// Copy the hit data over to our trace results struct: // Copy the hit data over to our trace results struct:
if (traceCallback.hasHit()) if (traceCallback.hasHit())
{ {
mFraction = traceCallback.m_closestHitFraction; mFraction = static_cast<float>(traceCallback.m_closestHitFraction);
// ensure fraction is correct (covers intended distance traveled instead of actual distance traveled) // ensure fraction is correct (covers intended distance traveled instead of actual distance traveled)
if (doingShortTrace && (end - start).length2() > 0.0) if (doingShortTrace && (end - start).length2() > 0.0)
mFraction *= (btend - btstart).length() / (end - start).length(); mFraction *= static_cast<float>((btend - btstart).length() / (end - start).length());
mPlaneNormal = Misc::Convert::toOsg(traceCallback.m_hitNormalWorld); mPlaneNormal = Misc::Convert::toOsg(traceCallback.m_hitNormalWorld);
mEndPos = (end - start) * mFraction + start; mEndPos = (end - start) * mFraction + start;
mHitPoint = Misc::Convert::toOsg(traceCallback.m_hitPointWorld); mHitPoint = Misc::Convert::toOsg(traceCallback.m_hitPointWorld);
@ -85,7 +85,7 @@ namespace MWPhysics
if (newTraceCallback.hasHit()) if (newTraceCallback.hasHit())
{ {
mFraction = newTraceCallback.m_closestHitFraction; mFraction = static_cast<float>(newTraceCallback.m_closestHitFraction);
mPlaneNormal = Misc::Convert::toOsg(newTraceCallback.m_hitNormalWorld); mPlaneNormal = Misc::Convert::toOsg(newTraceCallback.m_hitNormalWorld);
mEndPos = (end - start) * mFraction + start; mEndPos = (end - start) * mFraction + start;
mHitPoint = Misc::Convert::toOsg(newTraceCallback.m_hitPointWorld); mHitPoint = Misc::Convert::toOsg(newTraceCallback.m_hitPointWorld);
@ -109,7 +109,7 @@ namespace MWPhysics
actor->getCollisionObject(), Misc::Convert::toBullet(start), Misc::Convert::toBullet(end), world, true); actor->getCollisionObject(), Misc::Convert::toBullet(start), Misc::Convert::toBullet(end), world, true);
if (traceCallback.hasHit()) if (traceCallback.hasHit())
{ {
mFraction = traceCallback.m_closestHitFraction; mFraction = static_cast<float>(traceCallback.m_closestHitFraction);
mPlaneNormal = Misc::Convert::toOsg(traceCallback.m_hitNormalWorld); mPlaneNormal = Misc::Convert::toOsg(traceCallback.m_hitNormalWorld);
mEndPos = (end - start) * mFraction + start; mEndPos = (end - start) * mFraction + start;
} }

View file

@ -516,7 +516,7 @@ namespace MWRender
double duration = newTime - mStartingTime; double duration = newTime - mStartingTime;
mStartingTime = newTime; mStartingTime = newTime;
mParams.mAnimTime->addTime(duration); mParams.mAnimTime->addTime(static_cast<float>(duration));
if (mParams.mAnimTime->getTime() >= mParams.mMaxControllerLength) if (mParams.mAnimTime->getTime() >= mParams.mMaxControllerLength)
{ {
if (mParams.mLoop) if (mParams.mLoop)

View file

@ -261,7 +261,7 @@ namespace MWRender
for (const osg::Callback* callback = node->getCullCallback(); callback != nullptr; for (const osg::Callback* callback = node->getCullCallback(); callback != nullptr;
callback = callback->getNestedCallback()) callback = callback->getNestedCallback())
{ {
if (callback->className() == std::string("BillboardCallback")) if (callback->className() == std::string_view("BillboardCallback"))
{ {
if (mOptimizeBillboards) if (mOptimizeBillboards)
{ {
@ -310,8 +310,8 @@ namespace MWRender
const osg::Matrix& oldMatrix = matrixTransform->getMatrix(); const osg::Matrix& oldMatrix = matrixTransform->getMatrix();
float mag[3]; // attempt to preserve scale float mag[3]; // attempt to preserve scale
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
mag[i] = std::sqrt(oldMatrix(0, i) * oldMatrix(0, i) + oldMatrix(1, i) * oldMatrix(1, i) mag[i] = static_cast<float>(std::sqrt(oldMatrix(0, i) * oldMatrix(0, i)
+ oldMatrix(2, i) * oldMatrix(2, i)); + oldMatrix(1, i) * oldMatrix(1, i) + oldMatrix(2, i) * oldMatrix(2, i)));
osg::Matrix newMatrix; osg::Matrix newMatrix;
worldToLocal.setTrans(0, 0, 0); worldToLocal.setTrans(0, 0, 0);
newMatrix *= worldToLocal; newMatrix *= worldToLocal;
@ -651,7 +651,8 @@ namespace MWRender
osg::ref_ptr<osg::Node> ObjectPaging::createChunk(float size, const osg::Vec2f& center, bool activeGrid, osg::ref_ptr<osg::Node> ObjectPaging::createChunk(float size, const osg::Vec2f& center, bool activeGrid,
const osg::Vec3f& viewPoint, bool compile, unsigned char lod) const osg::Vec3f& viewPoint, bool compile, unsigned char lod)
{ {
const osg::Vec2i startCell(std::floor(center.x() - size / 2.f), std::floor(center.y() - size / 2.f)); const osg::Vec2i startCell(static_cast<int>(std::floor(center.x() - size / 2.f)),
static_cast<int>(std::floor(center.y() - size / 2.f)));
const MWBase::World& world = *MWBase::Environment::get().getWorld(); const MWBase::World& world = *MWBase::Environment::get().getWorld();
const MWWorld::ESMStore& store = world.getStore(); const MWWorld::ESMStore& store = world.getStore();
@ -683,8 +684,10 @@ namespace MWRender
const osg::Vec2f minBound = (center - osg::Vec2f(size / 2.f, size / 2.f)); const osg::Vec2f minBound = (center - osg::Vec2f(size / 2.f, size / 2.f));
const osg::Vec2f maxBound = (center + osg::Vec2f(size / 2.f, size / 2.f)); const osg::Vec2f maxBound = (center + osg::Vec2f(size / 2.f, size / 2.f));
const osg::Vec2i floorMinBound(std::floor(minBound.x()), std::floor(minBound.y())); const osg::Vec2i floorMinBound(
const osg::Vec2i ceilMaxBound(std::ceil(maxBound.x()), std::ceil(maxBound.y())); static_cast<int>(std::floor(minBound.x())), static_cast<int>(std::floor(minBound.y())));
const osg::Vec2i ceilMaxBound(
static_cast<int>(std::ceil(maxBound.x())), static_cast<int>(std::ceil(maxBound.y())));
struct InstanceList struct InstanceList
{ {
std::vector<const PagedCellRef*> mInstances; std::vector<const PagedCellRef*> mInstances;
@ -712,7 +715,7 @@ namespace MWRender
{ {
if (size < 1.f) if (size < 1.f)
{ {
const osg::Vec3f cellPos = ref.mPosition / cellSize; const osg::Vec3f cellPos = ref.mPosition / static_cast<float>(cellSize);
if ((minBound.x() > floorMinBound.x() && cellPos.x() < minBound.x()) if ((minBound.x() > floorMinBound.x() && cellPos.x() < minBound.x())
|| (minBound.y() > floorMinBound.y() && cellPos.y() < minBound.y()) || (minBound.y() > floorMinBound.y() && cellPos.y() < minBound.y())
|| (maxBound.x() < ceilMaxBound.x() && cellPos.x() >= maxBound.x()) || (maxBound.x() < ceilMaxBound.x() && cellPos.x() >= maxBound.x())
@ -808,7 +811,8 @@ namespace MWRender
emplaced.first->second.mInstances.push_back(&ref); emplaced.first->second.mInstances.push_back(&ref);
} }
const osg::Vec3f worldCenter = osg::Vec3f(center.x(), center.y(), 0) * getCellSize(mWorldspace); const osg::Vec3f worldCenter
= osg::Vec3f(center.x(), center.y(), 0) * static_cast<float>(getCellSize(mWorldspace));
osg::ref_ptr<osg::Group> group = new osg::Group; osg::ref_ptr<osg::Group> group = new osg::Group;
osg::ref_ptr<osg::Group> mergeGroup = new osg::Group; osg::ref_ptr<osg::Group> mergeGroup = new osg::Group;
osg::ref_ptr<Resource::TemplateMultiRef> templateRefs = new Resource::TemplateMultiRef; osg::ref_ptr<Resource::TemplateMultiRef> templateRefs = new Resource::TemplateMultiRef;
@ -980,8 +984,8 @@ namespace MWRender
{ {
osg::Vec2f clampToCell(const osg::Vec3f& cellPos, const osg::Vec2i& cell) osg::Vec2f clampToCell(const osg::Vec3f& cellPos, const osg::Vec2i& cell)
{ {
return osg::Vec2f(std::clamp<float>(cellPos.x(), cell.x(), cell.x() + 1), return osg::Vec2f(std::clamp(cellPos.x(), static_cast<float>(cell.x()), cell.x() + 1.f),
std::clamp<float>(cellPos.y(), cell.y(), cell.y() + 1)); std::clamp(cellPos.y(), static_cast<float>(cell.y()), cell.y() + 1.f));
} }
class CollectIntersecting class CollectIntersecting
@ -990,7 +994,7 @@ namespace MWRender
explicit CollectIntersecting( explicit CollectIntersecting(
bool activeGridOnly, const osg::Vec3f& position, const osg::Vec2i& cell, ESM::RefId worldspace) bool activeGridOnly, const osg::Vec3f& position, const osg::Vec2i& cell, ESM::RefId worldspace)
: mActiveGridOnly(activeGridOnly) : mActiveGridOnly(activeGridOnly)
, mPosition(clampToCell(position / getCellSize(worldspace), cell)) , mPosition(clampToCell(position / static_cast<float>(getCellSize(worldspace)), cell))
{ {
} }

View file

@ -135,7 +135,7 @@ namespace MWRender
mHUDCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); mHUDCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
mHUDCamera->setRenderOrder(osg::Camera::POST_RENDER); mHUDCamera->setRenderOrder(osg::Camera::POST_RENDER);
mHUDCamera->setClearColor(osg::Vec4(0.45, 0.45, 0.14, 1.0)); mHUDCamera->setClearColor(osg::Vec4(0.45f, 0.45f, 0.14f, 1.f));
mHUDCamera->setClearMask(0); mHUDCamera->setClearMask(0);
mHUDCamera->setProjectionMatrix(osg::Matrix::ortho2D(0, 1, 0, 1)); mHUDCamera->setProjectionMatrix(osg::Matrix::ortho2D(0, 1, 0, 1));
mHUDCamera->setAllowEventFocus(false); mHUDCamera->setAllowEventFocus(false);
@ -205,7 +205,7 @@ namespace MWRender
else else
Log(Debug::Error) << "'glDisablei' unsupported, pass normals will not be available to shaders."; Log(Debug::Error) << "'glDisablei' unsupported, pass normals will not be available to shaders.";
mGLSLVersion = ext->glslLanguageVersion * 100; mGLSLVersion = static_cast<int>(ext->glslLanguageVersion * 100);
mUBO = ext->isUniformBufferObjectSupported && mGLSLVersion >= 330; mUBO = ext->isUniformBufferObjectSupported && mGLSLVersion >= 330;
mStateUpdater = new Fx::StateUpdater(mUBO); mStateUpdater = new Fx::StateUpdater(mUBO);
@ -275,7 +275,7 @@ namespace MWRender
void PostProcessor::traverse(osg::NodeVisitor& nv) void PostProcessor::traverse(osg::NodeVisitor& nv)
{ {
size_t frameId = nv.getTraversalNumber() % 2; unsigned frameId = nv.getTraversalNumber() % 2;
if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR) if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR)
cull(frameId, static_cast<osgUtil::CullVisitor*>(&nv)); cull(frameId, static_cast<osgUtil::CullVisitor*>(&nv));
@ -285,7 +285,7 @@ namespace MWRender
osg::Group::traverse(nv); osg::Group::traverse(nv);
} }
void PostProcessor::cull(size_t frameId, osgUtil::CullVisitor* cv) void PostProcessor::cull(unsigned frameId, osgUtil::CullVisitor* cv)
{ {
if (const auto& fbo = getFbo(FBO_Intercept, frameId)) if (const auto& fbo = getFbo(FBO_Intercept, frameId))
{ {
@ -312,7 +312,8 @@ namespace MWRender
size_t frame = cv->getTraversalNumber(); size_t frame = cv->getTraversalNumber();
mStateUpdater->setResolution(osg::Vec2f(cv->getViewport()->width(), cv->getViewport()->height())); mStateUpdater->setResolution(osg::Vec2f(
static_cast<float>(cv->getViewport()->width()), static_cast<float>(cv->getViewport()->height())));
// per-frame data // per-frame data
if (frame != mLastFrameNumber) if (frame != mLastFrameNumber)
@ -467,8 +468,8 @@ namespace MWRender
textures[Tex_Distortion]->setSourceFormat(GL_RGB); textures[Tex_Distortion]->setSourceFormat(GL_RGB);
textures[Tex_Distortion]->setInternalFormat(GL_RGB); textures[Tex_Distortion]->setInternalFormat(GL_RGB);
Stereo::setMultiviewCompatibleTextureSize( Stereo::setMultiviewCompatibleTextureSize(textures[Tex_Distortion], static_cast<int>(width * DistortionRatio),
textures[Tex_Distortion], width * DistortionRatio, height * DistortionRatio); static_cast<int>(height * DistortionRatio));
textures[Tex_Distortion]->dirtyTextureObject(); textures[Tex_Distortion]->dirtyTextureObject();
auto setupDepth = [](osg::Texture* tex) { auto setupDepth = [](osg::Texture* tex) {
@ -632,7 +633,7 @@ namespace MWRender
if (auto type = uniform->getType()) if (auto type = uniform->getType())
uniform->setUniform(node.mRootStateSet->getOrCreateUniform( uniform->setUniform(node.mRootStateSet->getOrCreateUniform(
uniform->mName.c_str(), *type, uniform->getNumElements())); uniform->mName, *type, static_cast<unsigned>(uniform->getNumElements())));
} }
for (const auto& pass : technique->getPasses()) for (const auto& pass : technique->getPasses())
@ -724,7 +725,7 @@ namespace MWRender
disableTechnique(technique, false); disableTechnique(technique, false);
int pos = std::min<int>(location.value_or(mTechniques.size()) + mInternalTechniques.size(), mTechniques.size()); size_t pos = std::min(location.value_or(mTechniques.size()) + mInternalTechniques.size(), mTechniques.size());
mTechniques.insert(mTechniques.begin() + pos, technique); mTechniques.insert(mTechniques.begin() + pos, technique);
dirtyTechniques(Settings::ShaderManager::get().getMode() == Settings::ShaderManager::Mode::Debug); dirtyTechniques(Settings::ShaderManager::get().getMode() == Settings::ShaderManager::Mode::Debug);

View file

@ -220,7 +220,7 @@ namespace MWRender
void updateLiveReload(); void updateLiveReload();
void cull(size_t frameId, osgUtil::CullVisitor* cv); void cull(unsigned frameId, osgUtil::CullVisitor* cv);
osg::ref_ptr<osg::Group> mRootNode; osg::ref_ptr<osg::Group> mRootNode;
osg::ref_ptr<osg::Camera> mHUDCamera; osg::ref_ptr<osg::Camera> mHUDCamera;
@ -241,7 +241,7 @@ namespace MWRender
size_t mDirtyFrameId = 0; size_t mDirtyFrameId = 0;
size_t mLastFrameNumber = 0; size_t mLastFrameNumber = 0;
float mLastSimulationTime = 0.f; double mLastSimulationTime = 0.0;
bool mDirty = false; bool mDirty = false;
bool mReload = true; bool mReload = true;

View file

@ -711,9 +711,9 @@ namespace MWRender
if (needsAdjusting) if (needsAdjusting)
{ {
constexpr float pR = 0.2126; constexpr float pR = 0.2126f;
constexpr float pG = 0.7152; constexpr float pG = 0.7152f;
constexpr float pB = 0.0722; constexpr float pB = 0.0722f;
// we already work in linear RGB so no conversions are needed for the luminosity function // we already work in linear RGB so no conversions are needed for the luminosity function
float relativeLuminance = pR * ambient.r() + pG * ambient.g() + pB * ambient.b(); float relativeLuminance = pR * ambient.r() + pG * ambient.g() + pB * ambient.b();
@ -1053,14 +1053,13 @@ namespace MWRender
PtrHolder* ptrHolder = nullptr; PtrHolder* ptrHolder = nullptr;
std::vector<RefnumMarker*> refnumMarkers; std::vector<RefnumMarker*> refnumMarkers;
bool hitNonObjectWorld = false; bool hitNonObjectWorld = false;
for (osg::NodePath::const_iterator it = intersection.nodePath.begin(); it != intersection.nodePath.end(); for (osg::Node* node : intersection.nodePath)
++it)
{ {
const auto& nodeMask = (*it)->getNodeMask(); const auto& nodeMask = node->getNodeMask();
if (!hitNonObjectWorld) if (!hitNonObjectWorld)
hitNonObjectWorld = nodeMask & nonObjectWorldMask; hitNonObjectWorld = nodeMask & nonObjectWorldMask;
osg::UserDataContainer* userDataContainer = (*it)->getUserDataContainer(); osg::UserDataContainer* userDataContainer = node->getUserDataContainer();
if (!userDataContainer) if (!userDataContainer)
continue; continue;
for (unsigned int i = 0; i < userDataContainer->getNumUserObjects(); ++i) for (unsigned int i = 0; i < userDataContainer->getNumUserObjects(); ++i)
@ -1110,7 +1109,7 @@ namespace MWRender
result.mHit = true; result.mHit = true;
result.mHitPointWorld = intersection.getWorldIntersectPoint(); result.mHitPointWorld = intersection.getWorldIntersectPoint();
result.mHitNormalWorld = intersection.getWorldIntersectNormal(); result.mHitNormalWorld = intersection.getWorldIntersectNormal();
result.mRatio = intersection.ratio; result.mRatio = static_cast<float>(intersection.ratio);
} }
}; };
@ -1385,12 +1384,12 @@ namespace MWRender
if (Stereo::getStereo()) if (Stereo::getStereo())
{ {
auto res = Stereo::Manager::instance().eyeResolution(); auto res = Stereo::Manager::instance().eyeResolution();
mSharedUniformStateUpdater->setScreenRes(res.x(), res.y()); setScreenRes(res.x(), res.y());
Stereo::Manager::instance().setMasterProjectionMatrix(mPerViewUniformStateUpdater->getProjectionMatrix()); Stereo::Manager::instance().setMasterProjectionMatrix(mPerViewUniformStateUpdater->getProjectionMatrix());
} }
else else
{ {
mSharedUniformStateUpdater->setScreenRes(width, height); mSharedUniformStateUpdater->setScreenRes(static_cast<float>(width), static_cast<float>(height));
} }
// Since our fog is not radial yet, we should take FOV in account, otherwise terrain near viewing distance may // Since our fog is not radial yet, we should take FOV in account, otherwise terrain near viewing distance may
@ -1407,7 +1406,7 @@ namespace MWRender
void RenderingManager::setScreenRes(int width, int height) void RenderingManager::setScreenRes(int width, int height)
{ {
mSharedUniformStateUpdater->setScreenRes(width, height); mSharedUniformStateUpdater->setScreenRes(static_cast<float>(width), static_cast<float>(height));
} }
void RenderingManager::updateTextureFiltering() void RenderingManager::updateTextureFiltering()
@ -1415,7 +1414,8 @@ namespace MWRender
mViewer->stopThreading(); mViewer->stopThreading();
mResourceSystem->getSceneManager()->setFilterSettings(Settings::general().mTextureMagFilter, mResourceSystem->getSceneManager()->setFilterSettings(Settings::general().mTextureMagFilter,
Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap, Settings::general().mAnisotropy); Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap,
static_cast<float>(Settings::general().mAnisotropy));
mTerrain->updateTextureFiltering(); mTerrain->updateTextureFiltering();
mWater->processChangedSettings({}); mWater->processChangedSettings({});
@ -1428,7 +1428,7 @@ namespace MWRender
osg::Vec4f color = mAmbientColor; osg::Vec4f color = mAmbientColor;
if (mNightEyeFactor > 0.f) if (mNightEyeFactor > 0.f)
color += osg::Vec4f(0.7, 0.7, 0.7, 0.0) * mNightEyeFactor; color += osg::Vec4f(0.7f, 0.7f, 0.7f, 0.0f) * mNightEyeFactor;
mPostProcessor->getStateUpdater()->setAmbientColor(color); mPostProcessor->getStateUpdater()->setAmbientColor(color);
mStateUpdater->setAmbientColor(color); mStateUpdater->setAmbientColor(color);
@ -1456,7 +1456,7 @@ namespace MWRender
{ {
const int compMapResolution = Settings::terrain().mCompositeMapResolution; const int compMapResolution = Settings::terrain().mCompositeMapResolution;
const int compMapPower = Settings::terrain().mCompositeMapLevel; const int compMapPower = Settings::terrain().mCompositeMapLevel;
const float compMapLevel = std::pow(2, compMapPower); const float compMapLevel = static_cast<float>(std::pow(2, compMapPower));
const int vertexLodMod = Settings::terrain().mVertexLodMod; const int vertexLodMod = Settings::terrain().mVertexLodMod;
const float maxCompGeometrySize = Settings::terrain().mMaxCompositeGeometrySize; const float maxCompGeometrySize = Settings::terrain().mMaxCompositeGeometrySize;
const bool debugChunks = Settings::terrain().mDebugChunks; const bool debugChunks = Settings::terrain().mDebugChunks;

View file

@ -226,7 +226,7 @@ namespace MWScript
{ {
if (!repeat) if (!repeat)
repeat = true; repeat = true;
Interpreter::Type_Integer idleValue = std::clamp(runtime[0].mInteger, 0, 255); auto idleValue = static_cast<unsigned char>(std::clamp(runtime[0].mInteger, 0, 255));
idleList.push_back(idleValue); idleList.push_back(idleValue);
runtime.pop(); runtime.pop();
--arg0; --arg0;

View file

@ -217,7 +217,7 @@ namespace MWScript
} }
} }
int GlobalScripts::countSavedGameRecords() const size_t GlobalScripts::countSavedGameRecords() const
{ {
return mScripts.size(); return mScripts.size();
} }

View file

@ -76,7 +76,7 @@ namespace MWScript
void addStartup(); void addStartup();
///< Add startup script ///< Add startup script
int countSavedGameRecords() const; size_t countSavedGameRecords() const;
void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const;

View file

@ -95,7 +95,7 @@ namespace
if (stateset) if (stateset)
{ {
const osg::StateSet::TextureAttributeList& texAttributes = stateset->getTextureAttributeList(); const osg::StateSet::TextureAttributeList& texAttributes = stateset->getTextureAttributeList();
for (size_t i = 0; i < texAttributes.size(); i++) for (unsigned i = 0; i < static_cast<unsigned>(texAttributes.size()); i++)
{ {
const osg::StateAttribute* attr = stateset->getTextureAttribute(i, osg::StateAttribute::TEXTURE); const osg::StateAttribute* attr = stateset->getTextureAttribute(i, osg::StateAttribute::TEXTURE);
if (!attr) if (!attr)
@ -115,7 +115,7 @@ namespace
} }
}; };
void addToLevList(ESM::LevelledListBase* list, const ESM::RefId& itemId, int level) void addToLevList(ESM::LevelledListBase* list, const ESM::RefId& itemId, uint16_t level)
{ {
for (auto& levelItem : list->mList) for (auto& levelItem : list->mList)
{ {
@ -1578,7 +1578,7 @@ namespace MWScript
ESM::CreatureLevList listCopy ESM::CreatureLevList listCopy
= *MWBase::Environment::get().getESMStore()->get<ESM::CreatureLevList>().find(levId); = *MWBase::Environment::get().getESMStore()->get<ESM::CreatureLevList>().find(levId);
addToLevList(&listCopy, creatureId, level); addToLevList(&listCopy, creatureId, static_cast<uint16_t>(level));
MWBase::Environment::get().getESMStore()->overrideRecord(listCopy); MWBase::Environment::get().getESMStore()->overrideRecord(listCopy);
} }
}; };
@ -1616,7 +1616,7 @@ namespace MWScript
ESM::ItemLevList listCopy ESM::ItemLevList listCopy
= *MWBase::Environment::get().getESMStore()->get<ESM::ItemLevList>().find(levId); = *MWBase::Environment::get().getESMStore()->get<ESM::ItemLevList>().find(levId);
addToLevList(&listCopy, itemId, level); addToLevList(&listCopy, itemId, static_cast<uint16_t>(level));
MWBase::Environment::get().getESMStore()->overrideRecord(listCopy); MWBase::Environment::get().getESMStore()->overrideRecord(listCopy);
} }
}; };

View file

@ -311,7 +311,7 @@ namespace MWSound
bool isPlaying(); bool isPlaying();
double getStreamDelay() const; double getStreamDelay() const;
double getStreamOffset() const; float getStreamOffset() const;
float getCurrentLoudness() const; float getCurrentLoudness() const;
@ -469,7 +469,7 @@ namespace MWSound
OpenAL_SoundStream::~OpenAL_SoundStream() OpenAL_SoundStream::~OpenAL_SoundStream()
{ {
if (mBuffers[0] && alIsBuffer(mBuffers[0])) if (mBuffers[0] && alIsBuffer(mBuffers[0]))
alDeleteBuffers(mBuffers.size(), mBuffers.data()); alDeleteBuffers(static_cast<ALsizei>(mBuffers.size()), mBuffers.data());
alGetError(); alGetError();
mDecoder->close(); mDecoder->close();
@ -477,7 +477,7 @@ namespace MWSound
bool OpenAL_SoundStream::init(bool getLoudnessData) bool OpenAL_SoundStream::init(bool getLoudnessData)
{ {
alGenBuffers(mBuffers.size(), mBuffers.data()); alGenBuffers(static_cast<ALsizei>(mBuffers.size()), mBuffers.data());
ALenum err = getALError(); ALenum err = getALError();
if (err != AL_NO_ERROR) if (err != AL_NO_ERROR)
return false; return false;
@ -509,7 +509,7 @@ namespace MWSound
break; break;
} }
mFrameSize = framesToBytes(1, chans, type); mFrameSize = static_cast<ALuint>(framesToBytes(1, chans, type));
mBufferSize = static_cast<ALuint>(sBufferLength * mSampleRate); mBufferSize = static_cast<ALuint>(sBufferLength * mSampleRate);
mBufferSize *= mFrameSize; mBufferSize *= mFrameSize;
@ -552,11 +552,11 @@ namespace MWSound
return d; return d;
} }
double OpenAL_SoundStream::getStreamOffset() const float OpenAL_SoundStream::getStreamOffset() const
{ {
ALint state = AL_STOPPED; ALint state = AL_STOPPED;
ALint offset; ALint offset;
double t; float t;
alGetSourcei(mSource, AL_SAMPLE_OFFSET, &offset); alGetSourcei(mSource, AL_SAMPLE_OFFSET, &offset);
alGetSourcei(mSource, AL_SOURCE_STATE, &state); alGetSourcei(mSource, AL_SOURCE_STATE, &state);
@ -565,13 +565,13 @@ namespace MWSound
ALint queued; ALint queued;
alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued);
ALint inqueue = mBufferSize / mFrameSize * queued - offset; ALint inqueue = mBufferSize / mFrameSize * queued - offset;
t = (double)(mDecoder->getSampleOffset() - inqueue) / (double)mSampleRate; t = (mDecoder->getSampleOffset() - inqueue) / static_cast<float>(mSampleRate);
} }
else else
{ {
/* Underrun, or not started yet. The decoder offset is where we'll play /* Underrun, or not started yet. The decoder offset is where we'll play
* next. */ * next. */
t = (double)mDecoder->getSampleOffset() / (double)mSampleRate; t = mDecoder->getSampleOffset() / static_cast<float>(mSampleRate);
} }
getALError(); getALError();
@ -642,7 +642,7 @@ namespace MWSound
mLoudnessAnalyzer->analyzeLoudness(data); mLoudnessAnalyzer->analyzeLoudness(data);
ALuint bufid = mBuffers[mCurrentBufIdx]; ALuint bufid = mBuffers[mCurrentBufIdx];
alBufferData(bufid, mFormat, data.data(), data.size(), mSampleRate); alBufferData(bufid, mFormat, data.data(), static_cast<ALsizei>(data.size()), mSampleRate);
alSourceQueueBuffers(mSource, 1, &bufid); alSourceQueueBuffers(mSource, 1, &bufid);
mCurrentBufIdx = (mCurrentBufIdx + 1) % mBuffers.size(); mCurrentBufIdx = (mCurrentBufIdx + 1) % mBuffers.size();
} }
@ -801,7 +801,7 @@ namespace MWSound
if (alEventControlSOFT) if (alEventControlSOFT)
{ {
static const std::array<ALenum, 1> events{ { AL_EVENT_TYPE_DISCONNECTED_SOFT } }; static const std::array<ALenum, 1> events{ { AL_EVENT_TYPE_DISCONNECTED_SOFT } };
alEventControlSOFT(events.size(), events.data(), AL_TRUE); alEventControlSOFT(static_cast<ALsizei>(events.size()), events.data(), AL_TRUE);
alEventCallbackSOFT(&OpenALOutput::eventCallback, this); alEventCallbackSOFT(&OpenALOutput::eventCallback, this);
} }
else else
@ -1065,7 +1065,7 @@ namespace MWSound
ALint size; ALint size;
ALuint buf = 0; ALuint buf = 0;
alGenBuffers(1, &buf); alGenBuffers(1, &buf);
alBufferData(buf, format, data.data(), data.size(), srate); alBufferData(buf, format, data.data(), static_cast<ALsizei>(data.size()), srate);
alGetBufferi(buf, AL_SIZE, &size); alGetBufferi(buf, AL_SIZE, &size);
if (getALError() != AL_NO_ERROR) if (getALError() != AL_NO_ERROR)
{ {
@ -1412,10 +1412,10 @@ namespace MWSound
return stream->getStreamDelay(); return stream->getStreamDelay();
} }
double OpenALOutput::getStreamOffset(Stream* sound) float OpenALOutput::getStreamOffset(Stream* sound)
{ {
if (!sound->mHandle) if (!sound->mHandle)
return 0.0; return 0.f;
OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle);
std::lock_guard<std::mutex> lock(mStreamThread->mMutex); std::lock_guard<std::mutex> lock(mStreamThread->mMutex);
return stream->getStreamOffset(); return stream->getStreamOffset();
@ -1523,7 +1523,7 @@ namespace MWSound
} }
if (!sources.empty()) if (!sources.empty())
{ {
alSourcePausev(sources.size(), sources.data()); alSourcePausev(static_cast<ALsizei>(sources.size()), sources.data());
getALError(); getALError();
} }
} }
@ -1578,7 +1578,7 @@ namespace MWSound
} }
if (!sources.empty()) if (!sources.empty())
{ {
alSourcePlayv(sources.size(), sources.data()); alSourcePlayv(static_cast<ALsizei>(sources.size()), sources.data());
getALError(); getALError();
} }
} }

View file

@ -101,7 +101,7 @@ namespace MWSound
bool streamSound3D(DecoderPtr decoder, Stream* sound, bool getLoudnessData) override; bool streamSound3D(DecoderPtr decoder, Stream* sound, bool getLoudnessData) override;
void finishStream(Stream* sound) override; void finishStream(Stream* sound) override;
double getStreamDelay(Stream* sound) override; double getStreamDelay(Stream* sound) override;
double getStreamOffset(Stream* sound) override; float getStreamOffset(Stream* sound) override;
float getStreamLoudness(Stream* sound) override; float getStreamLoudness(Stream* sound) override;
bool isStreamPlaying(Stream* sound) override; bool isStreamPlaying(Stream* sound) override;
void updateStream(Stream* sound) override; void updateStream(Stream* sound) override;

View file

@ -53,7 +53,7 @@ namespace MWSound
virtual bool streamSound3D(DecoderPtr decoder, Stream* sound, bool getLoudnessData) = 0; virtual bool streamSound3D(DecoderPtr decoder, Stream* sound, bool getLoudnessData) = 0;
virtual void finishStream(Stream* sound) = 0; virtual void finishStream(Stream* sound) = 0;
virtual double getStreamDelay(Stream* sound) = 0; virtual double getStreamDelay(Stream* sound) = 0;
virtual double getStreamOffset(Stream* sound) = 0; virtual float getStreamOffset(Stream* sound) = 0;
virtual float getStreamLoudness(Stream* sound) = 0; virtual float getStreamLoudness(Stream* sound) = 0;
virtual bool isStreamPlaying(Stream* sound) = 0; virtual bool isStreamPlaying(Stream* sound) = 0;
virtual void updateStream(Stream* sound) = 0; virtual void updateStream(Stream* sound) = 0;

View file

@ -289,7 +289,7 @@ void MWState::StateManager::saveGame(std::string_view description, const Slot* s
writer.setAuthor(""); writer.setAuthor("");
writer.setDescription(""); writer.setDescription("");
int recordCount = 1 // saved game header size_t recordCount = 1 // saved game header
+ MWBase::Environment::get().getJournal()->countSavedGameRecords() + MWBase::Environment::get().getJournal()->countSavedGameRecords()
+ MWBase::Environment::get().getLuaManager()->countSavedGameRecords() + MWBase::Environment::get().getLuaManager()->countSavedGameRecords()
+ MWBase::Environment::get().getWorld()->countSavedGameRecords() + MWBase::Environment::get().getWorld()->countSavedGameRecords()
@ -298,7 +298,7 @@ void MWState::StateManager::saveGame(std::string_view description, const Slot* s
+ MWBase::Environment::get().getMechanicsManager()->countSavedGameRecords() + MWBase::Environment::get().getMechanicsManager()->countSavedGameRecords()
+ MWBase::Environment::get().getInputManager()->countSavedGameRecords() + MWBase::Environment::get().getInputManager()->countSavedGameRecords()
+ MWBase::Environment::get().getWindowManager()->countSavedGameRecords(); + MWBase::Environment::get().getWindowManager()->countSavedGameRecords();
writer.setRecordCount(recordCount); writer.setRecordCount(static_cast<int>(recordCount));
writer.save(stream); writer.save(stream);
@ -325,7 +325,7 @@ void MWState::StateManager::saveGame(std::string_view description, const Slot* s
MWBase::Environment::get().getWindowManager()->write(writer, listener); MWBase::Environment::get().getWindowManager()->write(writer, listener);
// Ensure we have written the number of records that was estimated // Ensure we have written the number of records that was estimated
if (writer.getRecordCount() != recordCount + 1) // 1 extra for TES3 record if (static_cast<size_t>(writer.getRecordCount()) != recordCount + 1) // 1 extra for TES3 record
Log(Debug::Warning) << "Warning: number of written savegame records does not match. Estimated: " Log(Debug::Warning) << "Warning: number of written savegame records does not match. Estimated: "
<< recordCount + 1 << ", written: " << writer.getRecordCount(); << recordCount + 1 << ", written: " << writer.getRecordCount();

View file

@ -402,7 +402,7 @@ namespace MWWorld
mTerrainViews.resize(positions.size()); mTerrainViews.resize(positions.size());
else if (mTerrainViews.size() < positions.size()) else if (mTerrainViews.size() < positions.size())
{ {
for (unsigned int i = mTerrainViews.size(); i < positions.size(); ++i) for (size_t i = mTerrainViews.size(); i < positions.size(); ++i)
mTerrainViews.emplace_back(mTerrain->createView()); mTerrainViews.emplace_back(mTerrain->createView());
} }
@ -456,10 +456,10 @@ namespace MWWorld
void CellPreloader::reportStats(unsigned int frameNumber, osg::Stats& stats) const void CellPreloader::reportStats(unsigned int frameNumber, osg::Stats& stats) const
{ {
stats.setAttribute(frameNumber, "CellPreloader Count", mPreloadCells.size()); stats.setAttribute(frameNumber, "CellPreloader Count", static_cast<double>(mPreloadCells.size()));
stats.setAttribute(frameNumber, "CellPreloader Added", mAdded); stats.setAttribute(frameNumber, "CellPreloader Added", static_cast<double>(mAdded));
stats.setAttribute(frameNumber, "CellPreloader Evicted", mEvicted); stats.setAttribute(frameNumber, "CellPreloader Evicted", static_cast<double>(mEvicted));
stats.setAttribute(frameNumber, "CellPreloader Loaded", mLoaded); stats.setAttribute(frameNumber, "CellPreloader Loaded", static_cast<double>(mLoaded));
stats.setAttribute(frameNumber, "CellPreloader Expired", mExpired); stats.setAttribute(frameNumber, "CellPreloader Expired", static_cast<double>(mExpired));
} }
} }

View file

@ -308,7 +308,7 @@ namespace MWWorld
{ {
mChanged = true; mChanged = true;
std::visit(ESM::VisitOverload{ std::visit(ESM::VisitOverload{
[&](ESM4::Reference& ref) { ref.mLockLevel = lockLevel; }, [&](ESM4::Reference& ref) { ref.mLockLevel = static_cast<int8_t>(lockLevel); },
[&](ESM4::ActorCharacter&) {}, [&](ESM4::ActorCharacter&) {},
[&](ESM::CellRef& ref) { ref.mLockLevel = lockLevel; }, [&](ESM::CellRef& ref) { ref.mLockLevel = lockLevel; },
}, },

View file

@ -681,7 +681,7 @@ namespace MWWorld
} }
} }
int ESMStore::countSavedGameRecords() const size_t ESMStore::countSavedGameRecords() const
{ {
return 1 // DYNA (dynamic name counter) return 1 // DYNA (dynamic name counter)
+ get<ESM::Potion>().getDynamicSize() + get<ESM::Armor>().getDynamicSize() + get<ESM::Potion>().getDynamicSize() + get<ESM::Armor>().getDynamicSize()

View file

@ -286,7 +286,7 @@ namespace MWWorld
void setUp(); void setUp();
void validateRecords(ESM::ReadersCache& readers); void validateRecords(ESM::ReadersCache& readers);
int countSavedGameRecords() const; size_t countSavedGameRecords() const;
void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const;

View file

@ -72,7 +72,7 @@ namespace MWWorld
} }
} }
int Globals::countSavedGameRecords() const size_t Globals::countSavedGameRecords() const
{ {
return mVariables.size(); return mVariables.size();
} }

View file

@ -64,7 +64,7 @@ namespace MWWorld
void fill(const MWWorld::ESMStore& store); void fill(const MWWorld::ESMStore& store);
///< Replace variables with variables from \a store with default values. ///< Replace variables with variables from \a store with default values.
int countSavedGameRecords() const; size_t countSavedGameRecords() const;
void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const;

View file

@ -64,7 +64,7 @@ void MWWorld::InventoryStore::readEquipmentState(
if (index == inventory.mSelectedEnchantItem) if (index == inventory.mSelectedEnchantItem)
mSelectedEnchantItem = iter; mSelectedEnchantItem = iter;
auto found = inventory.mEquipmentSlots.find(index); auto found = inventory.mEquipmentSlots.find(static_cast<uint32_t>(index));
if (found != inventory.mEquipmentSlots.end()) if (found != inventory.mEquipmentSlots.end())
{ {
if (found->second < 0 || found->second >= MWWorld::InventoryStore::Slots) if (found->second < 0 || found->second >= MWWorld::InventoryStore::Slots)

View file

@ -144,8 +144,8 @@ namespace
= MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(enam.mData.mEffectID); = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(enam.mData.mEffectID);
lightDiffuseColor += magicEffect->getColor(); lightDiffuseColor += magicEffect->getColor();
} }
int numberOfEffects = effects.mList.size(); size_t numberOfEffects = effects.mList.size();
lightDiffuseColor /= numberOfEffects; lightDiffuseColor /= static_cast<float>(numberOfEffects);
return lightDiffuseColor; return lightDiffuseColor;
} }
@ -793,7 +793,7 @@ namespace MWWorld
return false; return false;
} }
int ProjectileManager::countSavedGameRecords() const size_t ProjectileManager::countSavedGameRecords() const
{ {
return mMagicBolts.size() + mProjectiles.size(); return mMagicBolts.size() + mProjectiles.size();
} }

View file

@ -67,7 +67,7 @@ namespace MWWorld
void write(ESM::ESMWriter& writer, Loading::Listener& progress) const; void write(ESM::ESMWriter& writer, Loading::Listener& progress) const;
bool readRecord(ESM::ESMReader& reader, uint32_t type); bool readRecord(ESM::ESMReader& reader, uint32_t type);
int countSavedGameRecords() const; size_t countSavedGameRecords() const;
private: private:
osg::ref_ptr<osg::Group> mParent; osg::ref_ptr<osg::Group> mParent;

View file

@ -460,8 +460,6 @@ namespace MWWorld
if (const auto heightField = mPhysics->getHeightField(cellX, cellY)) if (const auto heightField = mPhysics->getHeightField(cellX, cellY))
{ {
const osg::Vec2i cellPosition(cellX, cellY); const osg::Vec2i cellPosition(cellX, cellY);
const btVector3& origin = heightField->getCollisionObject()->getWorldTransform().getOrigin();
const osg::Vec3f shift(origin.x(), origin.y(), origin.z());
const HeightfieldShape shape = [&]() -> HeightfieldShape { const HeightfieldShape shape = [&]() -> HeightfieldShape {
if (data == nullptr) if (data == nullptr)
{ {
@ -562,7 +560,7 @@ namespace MWWorld
const osg::Vec2f center = ESM::indexToPosition( const osg::Vec2f center = ESM::indexToPosition(
ESM::ExteriorCellLocation(currentGridCenter->x(), currentGridCenter->y(), worldspace), true); ESM::ExteriorCellLocation(currentGridCenter->x(), currentGridCenter->y(), worldspace), true);
float distance = std::max(std::abs(center.x() - pos.x()), std::abs(center.y() - pos.y())); float distance = std::max(std::abs(center.x() - pos.x()), std::abs(center.y() - pos.y()));
float cellSize = ESM::getCellSize(worldspace); int cellSize = ESM::getCellSize(worldspace);
const float maxDistance = cellSize / 2 + mCellLoadingThreshold; // 1/2 cell size + threshold const float maxDistance = cellSize / 2 + mCellLoadingThreshold; // 1/2 cell size + threshold
if (distance <= maxDistance) if (distance <= maxDistance)
return *currentGridCenter; return *currentGridCenter;
@ -1226,7 +1224,7 @@ namespace MWWorld
cellY = mCurrentGridCenter.y(); cellY = mCurrentGridCenter.y();
ESM::RefId extWorldspace = mWorld.getCurrentWorldspace(); ESM::RefId extWorldspace = mWorld.getCurrentWorldspace();
float cellSize = ESM::getCellSize(extWorldspace); int cellSize = ESM::getCellSize(extWorldspace);
for (int dx = -halfGridSizePlusOne; dx <= halfGridSizePlusOne; ++dx) for (int dx = -halfGridSizePlusOne; dx <= halfGridSizePlusOne; ++dx)
{ {

View file

@ -81,7 +81,7 @@ namespace MWWorld
mStatic.insert_or_assign(idx, std::move(record)); mStatic.insert_or_assign(idx, std::move(record));
} }
template <typename T> template <typename T>
int IndexedStore<T>::getSize() const size_t IndexedStore<T>::getSize() const
{ {
return mStatic.size(); return mStatic.size();
} }
@ -255,7 +255,7 @@ namespace MWWorld
} }
template <class T, class Id> template <class T, class Id>
int TypedDynamicStore<T, Id>::getDynamicSize() const size_t TypedDynamicStore<T, Id>::getDynamicSize() const
{ {
return mDynamic.size(); return mDynamic.size();
} }

Some files were not shown because too many files have changed in this diff Show more