Browse Source

chore: clang-tidy cleanup part 1

pull/8333/merge
Anders Jenbo 1 week ago
parent
commit
005e7dcc23
  1. 2
      Source/DiabloUI/credits.cpp
  2. 4
      Source/DiabloUI/diabloui.cpp
  3. 4
      Source/DiabloUI/hero/selhero.cpp
  4. 2
      Source/DiabloUI/multi/selconn.cpp
  5. 2
      Source/DiabloUI/settingsmenu.cpp
  6. 32
      Source/automap.cpp
  7. 4
      Source/control/control_chat.cpp
  8. 2
      Source/control/control_chat_commands.cpp
  9. 8
      Source/control/control_infobox.cpp
  10. 4
      Source/control/control_panel.cpp
  11. 4
      Source/controls/controller_motion.cpp
  12. 16
      Source/controls/modifier_hints.cpp
  13. 19
      Source/controls/plrctrls.cpp
  14. 22
      Source/controls/touch/gamepad.cpp
  15. 6
      Source/debug.cpp
  16. 13
      Source/diablo.cpp
  17. 8
      Source/diablo_msg.cpp
  18. 2
      Source/dvlnet/base.cpp
  19. 4
      Source/dvlnet/frame_queue.cpp
  20. 4
      Source/dvlnet/tcp_client.cpp
  21. 2
      Source/dvlnet/tcp_server.cpp
  22. 2
      Source/dvlnet/zerotier_native.cpp
  23. 4
      Source/encrypt.cpp
  24. 4
      Source/engine/actor_position.cpp
  25. 2
      Source/engine/animationinfo.cpp
  26. 4
      Source/engine/demomode.cpp
  27. 2
      Source/engine/dx.cpp
  28. 10
      Source/engine/palette.cpp
  29. 4
      Source/engine/path.cpp
  30. 2
      Source/engine/random.cpp
  31. 4
      Source/engine/render/clx_render.cpp
  32. 84
      Source/engine/render/dun_render.cpp
  33. 12
      Source/engine/render/light_render.cpp
  34. 4
      Source/engine/render/primitive_render.cpp
  35. 4
      Source/engine/render/scrollrt.cpp
  36. 4
      Source/engine/render/text_render.cpp
  37. 12
      Source/gmenu.cpp
  38. 8
      Source/help.cpp
  39. 2
      Source/interfac.cpp
  40. 32
      Source/inv.cpp
  41. 6
      Source/items.cpp
  42. 9
      Source/items/validation.cpp
  43. 16
      Source/levels/drlg_l1.cpp
  44. 4
      Source/levels/drlg_l2.cpp
  45. 12
      Source/levels/drlg_l3.cpp
  46. 24
      Source/levels/drlg_l4.cpp
  47. 10
      Source/levels/gendung.cpp
  48. 2
      Source/levels/reencode_dun_cels.cpp
  49. 2
      Source/levels/town.cpp
  50. 6
      Source/lighting.cpp
  51. 22
      Source/loadsave.cpp
  52. 2
      Source/lua/autocomplete.cpp
  53. 2
      Source/lua/lua_global.cpp
  54. 2
      Source/lua/modules/dev/items.cpp
  55. 2
      Source/lua/modules/dev/player/spells.cpp
  56. 4
      Source/lua/modules/player.cpp
  57. 2
      Source/lua/repl.cpp
  58. 4
      Source/minitext.cpp
  59. 14
      Source/missiles.cpp
  60. 2
      Source/monster.cpp
  61. 10
      Source/monsters/validation.cpp
  62. 34
      Source/msg.cpp
  63. 4
      Source/multi.cpp
  64. 36
      Source/objects.cpp
  65. 2
      Source/objects.h
  66. 4
      Source/pack.cpp
  67. 6
      Source/panels/charpanel.cpp
  68. 16
      Source/panels/console.cpp
  69. 8
      Source/panels/mainpanel.cpp
  70. 4
      Source/panels/spell_book.cpp
  71. 12
      Source/panels/spell_list.cpp
  72. 8
      Source/pfile.cpp
  73. 2
      Source/platform/locale.cpp
  74. 6
      Source/player.cpp
  75. 2
      Source/portals/validation.cpp
  76. 10
      Source/qol/chatlog.cpp
  77. 2
      Source/qol/floatingnumbers.cpp
  78. 4
      Source/qol/itemlabels.cpp
  79. 2
      Source/qol/monhealthbar.cpp
  80. 6
      Source/qol/stash.cpp
  81. 5
      Source/qol/stash.h
  82. 10
      Source/qol/xpbar.cpp
  83. 10
      Source/quests.cpp
  84. 14
      Source/stores.cpp
  85. 2
      Source/storm/storm_net.cpp
  86. 4
      Source/storm/storm_svid.cpp
  87. 2
      Source/tables/itemdat.cpp
  88. 2
      Source/tables/monstdat.cpp
  89. 14
      Source/tables/playerdat.cpp
  90. 2
      Source/tmsg.cpp
  91. 8
      Source/utils/cel_to_clx.cpp
  92. 8
      Source/utils/cl2_to_clx.cpp
  93. 12
      Source/utils/display.cpp
  94. 4
      Source/utils/format_int.cpp
  95. 2
      Source/utils/push_aulib_decoder.cpp
  96. 46
      Source/utils/sdl2_to_1_2_backports.cpp
  97. 4
      Source/utils/sdl_bilinear_scale.cpp
  98. 72
      test/stash_test.cpp

2
Source/DiabloUI/credits.cpp

@ -131,7 +131,7 @@ void CreditsRenderer::Render()
ScaleOutputRect(&viewport);
// We use unscaled coordinates for calculation throughout.
Sint16 destY = static_cast<Sint16>(uiPosition.y + VIEWPORT.y - (offsetY - linesBegin * LINE_H));
auto destY = static_cast<Sint16>(uiPosition.y + VIEWPORT.y - (offsetY - linesBegin * LINE_H));
for (std::size_t i = linesBegin; i < linesEnd; ++i, destY += LINE_H) {
const Sint16 destX = uiPosition.x + VIEWPORT.x + 31;

4
Source/DiabloUI/diabloui.cpp

@ -357,12 +357,12 @@ void UiFocusPageUp()
void UiFocusPageDown()
{
if (listOffset + ListViewportSize > static_cast<std::size_t>(SelectedItemMax)) {
if (listOffset + ListViewportSize > SelectedItemMax) {
UiFocus(SelectedItemMax, false, true);
} else {
const std::size_t relpos = SelectedItem - listOffset;
std::size_t nextPageEnd = SelectedItem + (ListViewportSize - relpos - 1);
if (nextPageEnd + ListViewportSize <= static_cast<std::size_t>(SelectedItemMax))
if (nextPageEnd + ListViewportSize <= SelectedItemMax)
nextPageEnd += ListViewportSize;
else
nextPageEnd = SelectedItemMax;

4
Source/DiabloUI/hero/selhero.cpp

@ -175,7 +175,7 @@ void SelheroListSelect(size_t value)
vecSelHeroDlgItems.clear();
int itemH = 33;
for (size_t i = 0; i < GetNumPlayerClasses(); ++i) {
const HeroClass heroClass = static_cast<HeroClass>(i);
const auto heroClass = static_cast<HeroClass>(i);
if (heroClass == HeroClass::Monk && !gbIsHellfire) {
continue;
@ -194,7 +194,7 @@ void SelheroListSelect(size_t value)
}
if (vecSelHeroDlgItems.size() > 4)
itemH = 26;
const int itemY = static_cast<int>(246 + (176 - std::min<size_t>(vecSelHeroDlgItems.size(), 6) * itemH) / 2);
const int itemY = static_cast<int>(246 + ((176 - std::min<size_t>(vecSelHeroDlgItems.size(), 6) * itemH) / 2));
vecSelDlgItems.push_back(std::make_unique<UiList>(vecSelHeroDlgItems, std::min<size_t>(vecSelHeroDlgItems.size(), 6), uiPosition.x + 264, (uiPosition.y + itemY), 320, itemH, UiFlags::AlignCenter | UiFlags::FontSize24 | UiFlags::ColorUiGold));
const SDL_Rect rectScrollBar = { (Sint16)(uiPosition.x + 585), (Sint16)(uiPosition.y + 244), 25, 178 };

2
Source/DiabloUI/multi/selconn.cpp

@ -69,7 +69,7 @@ void SelconnLoad()
const Point uiPosition = GetUIRectangle().position;
const SDL_Rect rect1 = { (Sint16)(uiPosition.x + 24), (Sint16)(Sint16)(uiPosition.y + 161), 590, 35 };
const SDL_Rect rect1 = { (Sint16)(uiPosition.x + 24), ((Sint16)(uiPosition.y + 161)), 590, 35 };
vecSelConnDlg.push_back(std::make_unique<UiArtText>(_("Multi Player Game").data(), rect1, UiFlags::AlignCenter | UiFlags::FontSize30 | UiFlags::ColorUiSilver, 3));
const SDL_Rect rect2 = { (Sint16)(uiPosition.x + 35), (Sint16)(uiPosition.y + 218), DESCRIPTION_WIDTH, 21 };

2
Source/DiabloUI/settingsmenu.cpp

@ -167,7 +167,7 @@ void UpdatePadEntryTimerText()
StopPadEntryTimer();
return;
}
padEntryTimerText = StrCat(_("Press gamepad buttons to change."), " ", 10 - elapsed / 1000);
padEntryTimerText = StrCat(_("Press gamepad buttons to change."), " ", 10 - (elapsed / 1000));
vecDialogItems[IndexPadTimerText]->m_text = padEntryTimerText;
}

32
Source/automap.cpp

@ -216,7 +216,7 @@ void DrawMapVerticalDoor(const Surface &out, Point center, AutomapTile neTile, u
default:
app_fatal("Invalid leveltype");
}
if (!(neTile.hasFlag(AutomapTile::Flags::VerticalPassage) && leveltype == DTYPE_CATHEDRAL))
if (!neTile.hasFlag(AutomapTile::Flags::VerticalPassage) || leveltype != DTYPE_CATHEDRAL)
DrawMapLineNE(out, center + AmOffset(lWidthOffset, lHeightOffset), AmLine(length), colorDim);
DrawDiamond(out, center + AmOffset(dWidthOffset, dHeightOffset), colorBright);
}
@ -265,7 +265,7 @@ void DrawMapHorizontalDoor(const Surface &out, Point center, AutomapTile nwTile,
default:
app_fatal("Invalid leveltype");
}
if (!(nwTile.hasFlag(AutomapTile::Flags::HorizontalPassage) && leveltype == DTYPE_CATHEDRAL))
if (!nwTile.hasFlag(AutomapTile::Flags::HorizontalPassage) || leveltype != DTYPE_CATHEDRAL)
DrawMapLineSE(out, center + AmOffset(lWidthOffset, lHeightOffset), AmLine(length), colorDim);
DrawDiamond(out, center + AmOffset(dWidthOffset, dHeightOffset), colorBright);
}
@ -747,7 +747,7 @@ void DrawVertical(const Surface &out, Point center, AutomapTile tile, AutomapTil
* @brief Draw half-tile length lines to connect walls to any walls to the south-west and/or south-east
* (For caves the horizontal/vertical flags are swapped)
*/
void DrawCaveWallConnections(const Surface &out, Point center, AutomapTile sTile, AutomapTile swTile, AutomapTile seTile, uint8_t colorDim)
void DrawCaveWallConnections(const Surface &out, Point center, AutomapTile swTile, AutomapTile seTile, uint8_t colorDim)
{
if (IsAnyOf(swTile.type, AutomapTile::Types::CaveVerticalWallLava, AutomapTile::Types::CaveVertical, AutomapTile::Types::CaveVerticalWood, AutomapTile::Types::CaveCross, AutomapTile::Types::CaveWoodCross, AutomapTile::Types::CaveRightWoodCross, AutomapTile::Types::CaveLeftWoodCross, AutomapTile::Types::CaveRightCorner)) {
DrawMapLineNE(out, center + AmOffset(AmWidthOffset::QuarterTileLeft, AmHeightOffset::ThreeQuartersTileDown), AmLine(AmLineLength::HalfTile), colorDim);
@ -850,7 +850,7 @@ void DrawMapEllipse(const Surface &out, Point from, int radius, uint8_t colorInd
SetMapPixel(out, { from.x, from.y - b }, colorIndex);
// Initialize the parameters
int p1 = (b * b) - (a * a * b) + (a * a) / 4;
int p1 = (b * b) - (a * a * b) + ((a * a) / 4);
// Region 1
while ((b * b * x) < (a * a * y)) {
@ -1056,7 +1056,7 @@ void DrawAutomapTile(const Surface &out, Point center, Point map)
if (!noConnect) {
if (IsAnyOf(leveltype, DTYPE_TOWN, DTYPE_CAVES, DTYPE_NEST)) {
DrawCaveWallConnections(out, center, sTile, swTile, seTile, colorDim);
DrawCaveWallConnections(out, center, swTile, seTile, colorDim);
}
DrawWallConnections(out, center, tile, nwTile, neTile, colorBright, colorDim);
}
@ -1259,8 +1259,8 @@ Displacement GetAutomapScreen()
if (GetAutomapType() == AutomapType::Minimap) {
screen = {
MinimapRect.position.x + MinimapRect.size.width / 2,
MinimapRect.position.y + MinimapRect.size.height / 2
MinimapRect.position.x + (MinimapRect.size.width / 2),
MinimapRect.position.y + (MinimapRect.size.height / 2)
};
} else {
screen = {
@ -1298,12 +1298,12 @@ void SearchAutomapItem(const Surface &out, const Displacement &myPlayerOffset, i
if (!highlightTile({ i, j }))
continue;
const int px = i - 2 * AutomapOffset.deltaX - ViewPosition.x;
const int py = j - 2 * AutomapOffset.deltaY - ViewPosition.y;
const int px = i - (2 * AutomapOffset.deltaX) - ViewPosition.x;
const int py = j - (2 * AutomapOffset.deltaY) - ViewPosition.y;
Point screen = {
(myPlayerOffset.deltaX * scale / 100 / 2) + (px - py) * AmLine(AmLineLength::DoubleTile),
(myPlayerOffset.deltaY * scale / 100 / 2) + (px + py) * AmLine(AmLineLength::FullTile),
(myPlayerOffset.deltaX * scale / 100 / 2) + ((px - py) * AmLine(AmLineLength::DoubleTile)),
(myPlayerOffset.deltaY * scale / 100 / 2) + ((px + py) * AmLine(AmLineLength::FullTile)),
};
screen += GetAutomapScreen();
@ -1345,8 +1345,8 @@ void DrawAutomapPlr(const Surface &out, const Displacement &myPlayerOffset, cons
const Point tile = player.position.tile;
const int px = tile.x - 2 * AutomapOffset.deltaX - ViewPosition.x;
const int py = tile.y - 2 * AutomapOffset.deltaY - ViewPosition.y;
const int px = tile.x - (2 * AutomapOffset.deltaX) - ViewPosition.x;
const int py = tile.y - (2 * AutomapOffset.deltaY) - ViewPosition.y;
Displacement playerOffset = {};
if (player.isWalking())
@ -1355,8 +1355,8 @@ void DrawAutomapPlr(const Surface &out, const Displacement &myPlayerOffset, cons
const int scale = (GetAutomapType() == AutomapType::Minimap) ? MinimapScale : AutoMapScale;
Point base = {
((playerOffset.deltaX + myPlayerOffset.deltaX) * scale / 100 / 2) + (px - py) * AmLine(AmLineLength::DoubleTile),
((playerOffset.deltaY + myPlayerOffset.deltaY) * scale / 100 / 2) + (px + py) * AmLine(AmLineLength::FullTile) + AmOffset(AmWidthOffset::None, AmHeightOffset::HalfTileUp).deltaY
((playerOffset.deltaX + myPlayerOffset.deltaX) * scale / 100 / 2) + ((px - py) * AmLine(AmLineLength::DoubleTile)),
((playerOffset.deltaY + myPlayerOffset.deltaY) * scale / 100 / 2) + ((px + py) * AmLine(AmLineLength::FullTile)) + AmOffset(AmWidthOffset::None, AmHeightOffset::HalfTileUp).deltaY
};
base += GetAutomapScreen();
@ -1775,7 +1775,7 @@ void DrawAutomap(const Surface &out)
const int scale = (GetAutomapType() == AutomapType::Minimap) ? MinimapScale : AutoMapScale;
const int d = (scale * 64) / 100;
int cells = 2 * (gnScreenWidth / 2 / d) + 1;
int cells = (2 * (gnScreenWidth / 2 / d)) + 1;
if (((gnScreenWidth / 2) % d) != 0)
cells++;
if (((gnScreenWidth / 2) % d) >= (scale * 32) / 100)

4
Source/control/control_chat.cpp

@ -127,7 +127,7 @@ void DrawChatBox(const Surface &out)
continue;
const UiFlags color = player.friendlyMode ? UiFlags::ColorWhitegold : UiFlags::ColorRed;
const Point talkPanPosition = mainPanelPosition + Displacement { 172, 84 + 18 * talkBtn };
const Point talkPanPosition = mainPanelPosition + Displacement { 172, 84 + (18 * talkBtn) };
if (WhisperList[i]) {
// the normal (unpressed) voice button is pre-rendered on the panel, only need to draw over it when the button is held
if (TalkButtonsDown[talkBtn]) {
@ -149,7 +149,7 @@ void DrawChatBox(const Surface &out)
RenderClxSprite(out, (*TalkButton)[TalkButtonsDown[talkBtn] ? 1 : 0], talkPanPosition + Displacement { 4, -15 });
}
if (player.plractive) {
DrawString(out, player._pName, { { x, y + 60 + talkBtn * 18 }, { 204, 0 } }, { .flags = color });
DrawString(out, player._pName, { { x, y + 60 + (talkBtn * 18) }, { 204, 0 } }, { .flags = color });
}
talkBtn++;

2
Source/control/control_chat_commands.cpp

@ -173,7 +173,7 @@ bool IsQuestEnabled(const Quest &quest)
}
}
std::string TextCmdLevelSeed(const std::string_view parameter)
std::string TextCmdLevelSeed(const std::string_view /*parameter*/)
{
const std::string_view levelType = setlevel ? "set level" : "dungeon level";

8
Source/control/control_infobox.cpp

@ -211,14 +211,14 @@ int GetHoverSpriteHeight()
&& pcursinvitem < INVITEM_INV_FIRST + InventoryGridCells) {
const int idx = pcursinvitem - INVITEM_INV_FIRST;
auto &it = (*InspectPlayer).InvList[idx];
return GetInventorySize(it).height * (InventorySlotSizeInPixels.height + 1)
return (GetInventorySize(it).height * (InventorySlotSizeInPixels.height + 1))
- InventorySlotSizeInPixels.height;
}
if (pcursinvitem >= INVITEM_BELT_FIRST
&& pcursinvitem < INVITEM_BELT_FIRST + MaxBeltItems) {
const int idx = pcursinvitem - INVITEM_BELT_FIRST;
auto &it = (*InspectPlayer).SpdList[idx];
return GetInventorySize(it).height * (InventorySlotSizeInPixels.height + 1)
return (GetInventorySize(it).height * (InventorySlotSizeInPixels.height + 1))
- InventorySlotSizeInPixels.height - 1;
}
if (pcursstashitem != StashStruct::EmptyCell) {
@ -236,7 +236,7 @@ int GetHoverSpriteHeight()
int ClampAboveOrBelow(int anchorY, int spriteH, int boxH, int pad, int linePad)
{
const int yAbove = anchorY - spriteH - boxH - pad;
const int yBelow = anchorY + linePad / 2 + pad;
const int yBelow = anchorY + (linePad / 2) + pad;
return (yAbove >= 0) ? yAbove : yBelow;
}
@ -267,7 +267,7 @@ void PrintFloatingInfo(const Surface &out)
SpeakText(FloatingInfoString);
for (int i = 0; i < 3; i++)
DrawHalfTransparentRectTo(out, floatingInfoBox.position.x - hPadding, floatingInfoBox.position.y - vPadding, floatingInfoBox.size.width + hPadding * 2, floatingInfoBox.size.height + vPadding * 2);
DrawHalfTransparentRectTo(out, floatingInfoBox.position.x - hPadding, floatingInfoBox.position.y - vPadding, floatingInfoBox.size.width + (hPadding * 2), floatingInfoBox.size.height + (vPadding * 2));
DrawHalfTransparentVerticalLine(out, { floatingInfoBox.position.x - hPadding - 1, floatingInfoBox.position.y - vPadding - 1 }, floatingInfoBox.size.height + (vPadding * 2) + 2, PAL16_GRAY + 10);
DrawHalfTransparentVerticalLine(out, { floatingInfoBox.position.x + hPadding + floatingInfoBox.size.width, floatingInfoBox.position.y - vPadding - 1 }, floatingInfoBox.size.height + (vPadding * 2) + 2, PAL16_GRAY + 10);
DrawHalfTransparentHorizontalLine(out, { floatingInfoBox.position.x - hPadding, floatingInfoBox.position.y - vPadding - 1 }, floatingInfoBox.size.width + (hPadding * 2), PAL16_GRAY + 10);

4
Source/control/control_panel.cpp

@ -378,7 +378,7 @@ tl::expected<void, std::string> InitMainPanel()
if (!HeadlessMode) {
{
ASSIGN_OR_RETURN(const OwnedClxSpriteList sprite, LoadCelWithStatus("ctrlpan\\talkpanl", GetMainPanel().size.width));
ClxDraw(*BottomBuffer, { 0, (GetMainPanel().size.height + PanelPaddingHeight) * 2 - 1 }, sprite[0]);
ClxDraw(*BottomBuffer, { 0, ((GetMainPanel().size.height + PanelPaddingHeight) * 2) - 1 }, sprite[0]);
}
multiButtons = LoadCel("ctrlpan\\p8but2", 33);
talkButtons = LoadCel("ctrlpan\\talkbutt", 61);
@ -794,7 +794,7 @@ void DrawDeathText(const Surface &out)
};
std::string text;
const int verticalPadding = 42;
Point linePosition { 0, gnScreenHeight / 2 - (verticalPadding * 2) };
Point linePosition { 0, (gnScreenHeight / 2) - (verticalPadding * 2) };
text = _("You have died");
DrawString(out, text, linePosition, largeTextOptions);

4
Source/controls/controller_motion.cpp

@ -52,7 +52,7 @@ void ScaleJoystickAxes(float *x, float *y, float deadzone)
float analogY = *y;
const float deadZone = deadzone * maximum;
const float magnitude = std::sqrt(analogX * analogX + analogY * analogY);
const float magnitude = std::sqrt((analogX * analogX) + (analogY * analogY));
if (magnitude >= deadZone) {
// find scaled axis values with magnitudes between zero and maximum
const float scalingFactor = 1.F / magnitude * (magnitude - deadZone) / (maximum - deadZone);
@ -210,7 +210,7 @@ void ProcessControllerMotion(const SDL_Event &event)
AxisDirection GetAnalogStickDirection(float stickX, float stickY)
{
// avoid sqrt() by comparing squared magnitudes
const float magnitudeSquared = stickX * stickX + stickY * stickY;
const float magnitudeSquared = (stickX * stickX) + (stickY * stickY);
const float thresholdSquared = StickDirectionThreshold * StickDirectionThreshold;
if (magnitudeSquared < thresholdSquared)
return { AxisDirectionX_NONE, AxisDirectionY_NONE };

16
Source/controls/modifier_hints.cpp

@ -73,12 +73,12 @@ struct CircleMenuHint {
*/
void DrawCircleMenuHint(const Surface &out, const CircleMenuHint &hint, const Point &origin)
{
const Displacement backgroundDisplacement = { (HintBoxSize - IconSize) / 2 + 1, (HintBoxSize - IconSize) / 2 - 1 };
const Displacement backgroundDisplacement = { ((HintBoxSize - IconSize) / 2) + 1, ((HintBoxSize - IconSize) / 2) - 1 };
const Point hintBoxPositions[4] = {
origin + Displacement { 0, LineHeight - HintBoxSize },
origin + Displacement { HintBoxSize + HintBoxMargin, LineHeight - HintBoxSize * 2 - HintBoxMargin },
origin + Displacement { HintBoxSize + HintBoxMargin, LineHeight - (HintBoxSize * 2) - HintBoxMargin },
origin + Displacement { HintBoxSize + HintBoxMargin, LineHeight + HintBoxMargin },
origin + Displacement { HintBoxSize * 2 + HintBoxMargin * 2, LineHeight - HintBoxSize }
origin + Displacement { (HintBoxSize * 2) + (HintBoxMargin * 2), LineHeight - HintBoxSize }
};
const Point iconPositions[4] = {
hintBoxPositions[0] + backgroundDisplacement,
@ -106,12 +106,12 @@ void DrawCircleMenuHint(const Surface &out, const CircleMenuHint &hint, const Po
void DrawSpellsCircleMenuHint(const Surface &out, const Point &origin)
{
const Player &myPlayer = *MyPlayer;
const Displacement spellIconDisplacement = { (HintBoxSize - IconSize) / 2 + 1, HintBoxSize - (HintBoxSize - IconSize) / 2 - 1 };
const Displacement spellIconDisplacement = { ((HintBoxSize - IconSize) / 2) + 1, HintBoxSize - ((HintBoxSize - IconSize) / 2) - 1 };
const Point hintBoxPositions[4] = {
origin + Displacement { 0, LineHeight - HintBoxSize },
origin + Displacement { HintBoxSize + HintBoxMargin, LineHeight - HintBoxSize * 2 - HintBoxMargin },
origin + Displacement { HintBoxSize + HintBoxMargin, LineHeight - (HintBoxSize * 2) - HintBoxMargin },
origin + Displacement { HintBoxSize + HintBoxMargin, LineHeight + HintBoxMargin },
origin + Displacement { HintBoxSize * 2 + HintBoxMargin * 2, LineHeight - HintBoxSize }
origin + Displacement { (HintBoxSize * 2) + (HintBoxMargin * 2), LineHeight - HintBoxSize }
};
const Point spellIconPositions[4] = {
hintBoxPositions[0] + spellIconDisplacement,
@ -147,7 +147,7 @@ void DrawGamepadMenuNavigator(const Surface &out)
static const CircleMenuHint Buttons(/*top=*/HintIcon::IconNull, /*right=*/HintIcon::IconNull, /*bottom=*/HintIcon::IconSpells, /*left=*/HintIcon::IconQuests);
const Rectangle &mainPanel = GetMainPanel();
DrawCircleMenuHint(out, DPad, { mainPanel.position.x + CircleMarginX, mainPanel.position.y - CircleTop });
DrawCircleMenuHint(out, Buttons, { mainPanel.position.x + mainPanel.size.width - HintBoxSize * 3 - CircleMarginX - HintBoxMargin * 2, mainPanel.position.y - CircleTop });
DrawCircleMenuHint(out, Buttons, { mainPanel.position.x + mainPanel.size.width - (HintBoxSize * 3) - CircleMarginX - (HintBoxMargin * 2), mainPanel.position.y - CircleTop });
}
void DrawGamepadHotspellMenu(const Surface &out)
@ -156,7 +156,7 @@ void DrawGamepadHotspellMenu(const Surface &out)
return;
const Rectangle &mainPanel = GetMainPanel();
DrawSpellsCircleMenuHint(out, { mainPanel.position.x + mainPanel.size.width - HintBoxSize * 3 - CircleMarginX - HintBoxMargin * 2, mainPanel.position.y - CircleTop });
DrawSpellsCircleMenuHint(out, { mainPanel.position.x + mainPanel.size.width - (HintBoxSize * 3) - CircleMarginX - (HintBoxMargin * 2), mainPanel.position.y - CircleTop });
}
} // namespace

19
Source/controls/plrctrls.cpp

@ -265,10 +265,7 @@ bool CanTargetMonster(const Monster &monster)
const int mx = monster.position.tile.x;
const int my = monster.position.tile.y;
if (dMonster[mx][my] == 0)
return false;
return true;
return dMonster[mx][my] != 0;
}
void FindRangedTarget()
@ -855,7 +852,7 @@ void LiftInventoryItem()
return 0;
for (int x = 0; x < cursorSizeInCells.width; x++) {
for (int y = 0; y < cursorSizeInCells.height; y++) {
const int slotUnderCursor = inventorySlot + x + y * INV_ROW_SLOT_SIZE;
const int slotUnderCursor = inventorySlot + x + (y * INV_ROW_SLOT_SIZE);
if (slotUnderCursor > SLOTXY_INV_LAST)
continue;
const int itemId = GetItemIdOnSlot(slotUnderCursor);
@ -1087,7 +1084,7 @@ void VisualStoreMove(AxisDirection dir)
const Point slotPos = GetSlotCoord(slot);
// Exaggerate the vertical difference so that moving from the top rows of the
// visual store is more likely to land on a body slot
return std::abs(mousePos.y - slotPos.y) * 3 + std::abs(mousePos.x - slotPos.x);
return (std::abs(mousePos.y - slotPos.y) * 3) + std::abs(mousePos.x - slotPos.x);
});
VisualStoreSlot = { -1, -1 }; // Invalidate visual store slot
BeltReturnsToVisualStore = false;
@ -1355,10 +1352,10 @@ void InventoryMove(AxisDirection dir)
if (itemId != 0) {
for (int i = 1; i < 5; i++) {
if (Slot - i * INV_ROW_SLOT_SIZE < SLOTXY_INV_ROW1_FIRST) {
Slot = InventoryMoveToBody(Slot - (i - 1) * INV_ROW_SLOT_SIZE);
Slot = InventoryMoveToBody(Slot - ((i - 1) * INV_ROW_SLOT_SIZE));
break;
}
if (itemId != GetItemIdOnSlot(Slot - i * INV_ROW_SLOT_SIZE)) {
if (itemId != GetItemIdOnSlot(Slot - (i * INV_ROW_SLOT_SIZE))) {
Slot -= i * INV_ROW_SLOT_SIZE;
break;
}
@ -1410,7 +1407,7 @@ void InventoryMove(AxisDirection dir)
const int8_t itemId = GetItemIdOnSlot(Slot);
if (itemId != 0) {
for (int i = 1; i < 5 && Slot + i * INV_ROW_SLOT_SIZE <= SLOTXY_BELT_LAST; i++) {
if (itemId != GetItemIdOnSlot(Slot + i * INV_ROW_SLOT_SIZE)) {
if (itemId != GetItemIdOnSlot(Slot + (i * INV_ROW_SLOT_SIZE))) {
Slot += i * INV_ROW_SLOT_SIZE;
break;
}
@ -1598,7 +1595,7 @@ void StashMove(AxisDirection dir)
// empty-handed while 4 causes the amulet to be preferenced (due to less vertical
// distance) and 2 causes the left hand to be preferenced (due to less horizontal
// distance).
return std::abs(mousePos.y - slotPos.y) * 3 + std::abs(mousePos.x - slotPos.x);
return (std::abs(mousePos.y - slotPos.y) * 3) + std::abs(mousePos.x - slotPos.x);
});
ActiveStashSlot = InvalidStashPoint;
BeltReturnsToStash = false;
@ -1893,7 +1890,7 @@ struct RightStickAccumulator {
bool IsStickMovementSignificant()
{
// avoid sqrt() by comparing squared magnitudes
const float leftStickMagnitudeSquared = leftStickX * leftStickX + leftStickY * leftStickY;
const float leftStickMagnitudeSquared = (leftStickX * leftStickX) + (leftStickY * leftStickY);
const float thresholdSquared = StickDirectionThreshold * StickDirectionThreshold;
return leftStickMagnitudeSquared >= thresholdSquared

22
Source/controls/touch/gamepad.cpp

@ -29,24 +29,24 @@ int roundToInt(float value)
constexpr bool PointsUp(float angle)
{
constexpr float UpAngle = Pi / 2;
constexpr float MinAngle = UpAngle - 3 * Pi / 8;
constexpr float MaxAngle = UpAngle + 3 * Pi / 8;
constexpr float MinAngle = UpAngle - (3 * Pi / 8);
constexpr float MaxAngle = UpAngle + (3 * Pi / 8);
return MinAngle <= angle && angle <= MaxAngle;
}
constexpr bool PointsDown(float angle)
{
constexpr float DownAngle = -Pi / 2;
constexpr float MinAngle = DownAngle - 3 * Pi / 8;
constexpr float MaxAngle = DownAngle + 3 * Pi / 8;
constexpr float MinAngle = DownAngle - (3 * Pi / 8);
constexpr float MaxAngle = DownAngle + (3 * Pi / 8);
return MinAngle <= angle && angle <= MaxAngle;
}
constexpr bool PointsLeft(float angle)
{
constexpr float MaxAngle = Pi - 3 * Pi / 8;
constexpr float MinAngle = -Pi + 3 * Pi / 8;
return !(MinAngle < angle && angle < MaxAngle);
constexpr float MaxAngle = Pi - (3 * Pi / 8);
constexpr float MinAngle = -Pi + (3 * Pi / 8);
return MinAngle >= angle || angle >= MaxAngle;
}
constexpr bool PointsRight(float angle)
@ -109,9 +109,9 @@ void InitializeVirtualGamepad()
const int padButtonAreaWidth = roundToInt(sqrt2 * (padButtonSize + padButtonSpacing));
const int padButtonRight = gnScreenWidth - inputMargin - padButtonSize / 2;
const int padButtonRight = gnScreenWidth - inputMargin - (padButtonSize / 2);
const int padButtonLeft = padButtonRight - padButtonAreaWidth;
const int padButtonBottom = gnScreenHeight - inputMargin - padButtonSize / 2;
const int padButtonBottom = gnScreenHeight - inputMargin - (padButtonSize / 2);
const int padButtonTop = padButtonBottom - padButtonAreaWidth;
Rectangle &charButtonArea = VirtualGamepadState.menuPanel.charButton.area;
@ -151,7 +151,7 @@ void InitializeVirtualGamepad()
directionPadArea.radius = directionPadSize / 2;
directionPad.position = directionPadArea.position;
const int standButtonDiagonalOffset = directionPadArea.radius + padButtonSpacing / 2 + padButtonSize / 2;
const int standButtonDiagonalOffset = directionPadArea.radius + (padButtonSpacing / 2) + (padButtonSize / 2);
const int standButtonOffset = roundToInt(standButtonDiagonalOffset / sqrt2);
Circle &standButtonArea = VirtualGamepadState.standButton.area;
standButtonArea.position.x = directionPadArea.position.x - standButtonOffset;
@ -245,7 +245,7 @@ void VirtualDirectionPad::UpdatePosition(Point touchCoordinates)
if (!area.contains(position)) {
int x = diff.deltaX;
int y = diff.deltaY;
const float dist = sqrtf(static_cast<float>(x * x + y * y));
const float dist = sqrtf(static_cast<float>((x * x) + (y * y)));
x = roundToInt(x * area.radius / dist);
y = roundToInt(y * area.radius / dist);
position.x = area.position.x + x;

6
Source/debug.cpp

@ -183,8 +183,7 @@ bool GetDebugGridText(Point dungeonCoords, std::string &debugGridText)
case TileType::RightTrapezoid: StrAppend(debugGridText, "/"); break;
}
}
if (debugGridText.empty()) return false;
return true;
return !debugGridText.empty();
} break;
case DebugGridTextItem::dPiece:
info = dPiece[dungeonCoords.x][dungeonCoords.y];
@ -216,8 +215,7 @@ bool GetDebugGridText(Point dungeonCoords, std::string &debugGridText)
debugGridText.append(std::to_string((int)missile._mitype));
}
}
if (debugGridText.empty()) return false;
return true;
return !debugGridText.empty();
} break;
case DebugGridTextItem::dCorpse:
info = dCorpse[dungeonCoords.x][dungeonCoords.y];

13
Source/diablo.cpp

@ -990,7 +990,7 @@ void PrintHelpOption(std::string_view flags, std::string_view description)
#if SDL_VERSION_ATLEAST(2, 0, 0)
FILE *SdlLogFile = nullptr;
extern "C" void SdlLogToFile(void *userdata, int category, SDL_LogPriority priority, const char *message)
extern "C" void SdlLogToFile(void *userdata, int /*category*/, SDL_LogPriority priority, const char *message)
{
FILE *file = reinterpret_cast<FILE *>(userdata);
static const char *const LogPriorityPrefixes[SDL_LOG_PRIORITY_COUNT] = {
@ -1578,7 +1578,7 @@ void TimeoutCursor(bool bTimeout)
for (uint8_t i = 0; i < Players.size(); i++) {
bool isConnected = (player_state[i] & PS_CONNECTED) != 0;
bool isActive = (player_state[i] & PS_ACTIVE) != 0;
if (!(isConnected && !isActive)) continue;
if (!isConnected || isActive) continue;
DvlNetLatencies latencies = DvlNet_GetLatencies(i);
@ -1791,12 +1791,9 @@ bool CanPlayerTakeAction()
bool CanAutomapBeToggledOff()
{
// check if every window is closed - if yes, automap can be toggled off
if (!QuestLogIsOpen && !IsWithdrawGoldOpen && !IsStashOpen && !IsVisualStoreOpen && !CharFlag
return !QuestLogIsOpen && !IsWithdrawGoldOpen && !IsStashOpen && !IsVisualStoreOpen && !CharFlag
&& !SpellbookFlag && !invflag && !isGameMenuOpen && !qtextflag && !SpellSelectFlag
&& !ChatLogFlag && !HelpFlag)
return true;
return false;
&& !ChatLogFlag && !HelpFlag;
}
void OptionLanguageCodeChanged()
@ -3012,7 +3009,7 @@ bool PressEscKey()
return rv;
}
void DisableInputEventHandler(const SDL_Event &event, uint16_t modState)
void DisableInputEventHandler(const SDL_Event &event, uint16_t /*modState*/)
{
switch (event.type) {
case SDL_EVENT_MOUSE_MOTION:

8
Source/diablo_msg.cpp

@ -176,10 +176,10 @@ void DrawDiabloMsg(const Surface &out)
const int borderThickness = 3;
const int outerHeight = std::min<int>(out.h(), OuterHeight);
const int outerWidth = std::min<int>(out.w(), LineWidth + 2 * borderThickness + textPaddingX);
const int innerWidth = outerWidth - 2 * borderThickness;
const int outerWidth = std::min<int>(out.w(), LineWidth + (2 * borderThickness) + textPaddingX);
const int innerWidth = outerWidth - (2 * borderThickness);
const int lineWidth = innerWidth - textPaddingX;
const int innerHeight = outerHeight - 2 * borderThickness;
const int innerHeight = outerHeight - (2 * borderThickness);
const Point topLeft { (out.w() - outerWidth) / 2, (out.h() - outerHeight) / 2 };
@ -209,7 +209,7 @@ void DrawDiabloMsg(const Surface &out)
DrawHalfTransparentRectTo(out, innerXBegin, innerYBegin, innerWidth, innerHeight);
const int textX = innerXBegin + textPaddingX;
int textY = innerYBegin + (innerHeight - LineHeight * static_cast<int>(TextLines.size())) / 2;
int textY = innerYBegin + ((innerHeight - LineHeight * static_cast<int>(TextLines.size())) / 2);
for (const std::string &line : TextLines) {
DrawString(out, line, { { textX, textY }, { lineWidth, LineHeight } },
{ .flags = UiFlags::AlignCenter, .lineHeight = LineHeight });

2
Source/dvlnet/base.cpp

@ -500,7 +500,7 @@ bool base::SNetLeaveGame(net::leaveinfo_t type)
bool base::SNetDropPlayer(int playerid, net::leaveinfo_t flags)
{
const plr_t plr = static_cast<plr_t>(playerid);
const auto plr = static_cast<plr_t>(playerid);
tl::expected<std::unique_ptr<packet>, PacketError> pkt
= pktfty->make_packet<PT_DISCONNECT>(
plr_self,

4
Source/dvlnet/frame_queue.cpp

@ -31,7 +31,7 @@ tl::expected<buffer_t, PacketError> frame_queue::Read(framesize_t s)
return tl::make_unexpected(FrameQueueError());
buffer_t ret;
while (s > 0 && s >= buffer_deque.front().size()) {
const framesize_t bufferSize = static_cast<framesize_t>(buffer_deque.front().size());
const auto bufferSize = static_cast<framesize_t>(buffer_deque.front().size());
s -= bufferSize;
current_size -= bufferSize;
ret.insert(ret.end(),
@ -90,7 +90,7 @@ tl::expected<buffer_t, PacketError> frame_queue::ReadPacket()
tl::expected<buffer_t, PacketError> frame_queue::MakeFrame(buffer_t packetbuf, uint16_t flags)
{
buffer_t ret;
const framesize_t size = static_cast<framesize_t>(packetbuf.size());
const auto size = static_cast<framesize_t>(packetbuf.size());
if (size > max_frame_size)
return tl::make_unexpected("Buffer exceeds maximum frame size");
static_assert(sizeof(size) == 4, "framesize_t is not 4 bytes");

4
Source/dvlnet/tcp_client.cpp

@ -191,7 +191,7 @@ void tcp_client::StartReceive()
std::bind(&tcp_client::HandleReceive, this, std::placeholders::_1, std::placeholders::_2));
}
void tcp_client::HandleSend(const asio::error_code &error, size_t bytesSent)
void tcp_client::HandleSend(const asio::error_code &error, size_t /*bytesSent*/)
{
if (error)
RaiseIoHandlerError(error.message());
@ -211,7 +211,7 @@ void tcp_client::HandleTcpErrorCode()
return;
}
PacketError::ErrorCode code = static_cast<PacketError::ErrorCode>(pktData[0]);
auto code = static_cast<PacketError::ErrorCode>(pktData[0]);
if (code == PacketError::ErrorCode::DecryptionFailed)
RaiseIoHandlerError(_("Server failed to decrypt your packet. Check if you typed the password correctly."));
else

2
Source/dvlnet/tcp_server.cpp

@ -208,7 +208,7 @@ tl::expected<void, PacketError> tcp_server::StartSend(const scc &con, buffer_t p
}
void tcp_server::HandleSend(const scc &con, const asio::error_code &ec,
size_t bytesSent)
size_t /*bytesSent*/)
{
if (ec) {
Log("Network error: {}", ec.message());

2
Source/dvlnet/zerotier_native.cpp

@ -140,7 +140,7 @@ std::string ToZTCompliantPath(std::string_view configPath)
void Callback(void *ptr)
{
zts_event_msg_t *msg = reinterpret_cast<zts_event_msg_t *>(ptr);
auto *msg = reinterpret_cast<zts_event_msg_t *>(ptr);
switch (msg->event_code) {
case ZTS_EVENT_NODE_ONLINE:

4
Source/encrypt.cpp

@ -18,10 +18,10 @@ uint32_t PkwareCompress(std::byte *srcData, uint32_t size)
{
// Stack buffer covers typical network messages and MPQ sectors (≤ 4096).
// Falls back to heap for larger payloads.
constexpr size_t StackBufSize = 4096 * 2 + 64;
constexpr size_t StackBufSize = (4096 * 2) + 64;
uint8_t stackBuf[StackBufSize];
size_t dstCap = static_cast<size_t>(size) * 2 + 64;
size_t dstCap = (static_cast<size_t>(size) * 2) + 64;
uint8_t *dst;
std::unique_ptr<uint8_t[]> heapBuf;

4
Source/engine/actor_position.cpp

@ -22,7 +22,7 @@ struct RoundedWalkVelocity {
int16_t half;
int16_t full;
int16_t getVelocity(VelocityToUse velocityToUse) const
[[nodiscard]] int16_t getVelocity(VelocityToUse velocityToUse) const
{
switch (velocityToUse) {
case VelocityToUse::Quarter:
@ -77,7 +77,7 @@ constexpr RoundedWalkVelocity WalkVelocityForFrames[24] = {
struct WalkParameter {
VelocityToUse VelocityX;
VelocityToUse VelocityY;
DisplacementOf<int16_t> getVelocity(int8_t numberOfFrames) const
[[nodiscard]] DisplacementOf<int16_t> getVelocity(int8_t numberOfFrames) const
{
const RoundedWalkVelocity &walkVelocity = WalkVelocityForFrames[numberOfFrames - 1];
auto velocity = DisplacementOf<int16_t> {

2
Source/engine/animationinfo.cpp

@ -36,7 +36,7 @@ int8_t AnimationInfo::getFrameToUseForRendering() const
// we don't use the processed game ticks alone but also the fraction of the next game tick (if a rendering happens between game ticks). This helps to smooth the animations.
const int32_t totalTicksForCurrentAnimationSequence = getProgressToNextGameTick() + ticksSinceSequenceStarted;
int8_t absoluteAnimationFrame = static_cast<int8_t>(totalTicksForCurrentAnimationSequence * tickModifier_ / baseValueFraction / baseValueFraction);
auto absoluteAnimationFrame = static_cast<int8_t>(totalTicksForCurrentAnimationSequence * tickModifier_ / baseValueFraction / baseValueFraction);
if (skippedFramesFromPreviousAnimation_ > 0) {
// absoluteAnimationFrames contains also the Frames from the previous Animation, so if we want to get the current Frame we have to remove them
absoluteAnimationFrame -= skippedFramesFromPreviousAnimation_;

4
Source/engine/demomode.cpp

@ -541,7 +541,7 @@ std::optional<DemoMsg> ReadDemoMessage()
// to encode `progressToNextGameTick` inline.
if ((typeNum & 0b10000000) != 0) {
DemoModeLastTick = SDL_GetTicks();
return DemoMsg { DemoMsg::Rendering, static_cast<uint8_t>(typeNum & 0b01111111u), {} };
return DemoMsg { DemoMsg::Rendering, static_cast<uint8_t>(typeNum & 0b01111111U), {} };
}
const uint8_t progressToNextGameTick = ReadByte(DemoFile);
@ -703,7 +703,7 @@ bool GetRunGameLoop(bool &drawGame, bool &processInput)
} else {
int32_t fraction = ticksElapsed * AnimationInfo::baseValueFraction / gnTickDelay;
fraction = std::clamp<int32_t>(fraction, 0, AnimationInfo::baseValueFraction);
const uint8_t progressToNextGameTick = static_cast<uint8_t>(fraction);
const auto progressToNextGameTick = static_cast<uint8_t>(fraction);
if (dmsg.type == DemoMsg::GameTick || dmsg.progressToNextGameTick > progressToNextGameTick) {
// we are ahead of the replay => add a additional rendering for smoothness
if (gbRunGame && PauseMode == 0 && (gbIsMultiplayer || !gmenu_is_active()) && gbProcessPlayers) // if game is not running or paused there is no next gametick in the near future

2
Source/engine/dx.cpp

@ -93,7 +93,7 @@ void LimitFrameRate()
uint32_t v = 0;
if (frameDeadline > tc) {
v = tc % refreshDelay;
SDL_Delay(v / 1000 + 1); // ceil
SDL_Delay((v / 1000) + 1); // ceil
}
frameDeadline = tc + v + refreshDelay;
}

10
Source/engine/palette.cpp

@ -45,7 +45,7 @@ void LoadBrightness()
{
int brightnessValue = *GetOptions().Graphics.brightness;
brightnessValue = std::clamp(brightnessValue, 0, 100);
GetOptions().Graphics.brightness.SetValue(brightnessValue - brightnessValue % 5);
GetOptions().Graphics.brightness.SetValue(brightnessValue - (brightnessValue % 5));
}
/**
@ -96,15 +96,15 @@ constexpr float CalculateToneMappingParameter(int brightness)
{
// Maximum adjustment factor (tweak this constant to change the effect strength)
constexpr float MaxAdjustment = 2.0F;
return -(brightness / 100.0f) * MaxAdjustment;
return -(brightness / 100.0F) * MaxAdjustment;
}
constexpr uint8_t MapTone(float a, uint8_t color)
{
const auto x = static_cast<float>(color / 255.0f);
const auto x = static_cast<float>(color / 255.0F);
// Our quadratic tone mapping: f(x) = a*x^2 + (1-a)*x.
const float y = std::clamp(a * x * x + (1.0f - a) * x, 0.0f, 1.0f);
return static_cast<uint8_t>(y * 255.0f + 0.5f);
const float y = std::clamp((a * x * x) + ((1.0F - a) * x), 0.0F, 1.0F);
return static_cast<uint8_t>((y * 255.0F) + 0.5F);
}
void ApplyGlobalBrightnessSingleColor(SDL_Color &dst, const SDL_Color &src)

4
Source/engine/path.cpp

@ -149,7 +149,7 @@ CostType GetHeuristicCost(PointT startPosition, PointT destinationPosition)
// We then still need to take the remaining steps:
// max(dx, dy) - diagSteps = max(dx, dy) - min(dx, dy) = abs(dx - dy)
const int axisAlignedSteps = std::abs(dx - dy);
return diagSteps * PathDiagonalStepCost + axisAlignedSteps * PathAxisAlignedStepCost;
return (diagSteps * PathDiagonalStepCost) + (axisAlignedSteps * PathAxisAlignedStepCost);
}
int ReconstructPath(const ExploredNodes &explored, PointT dest, int8_t *path, size_t maxPathLength)
@ -178,7 +178,7 @@ int ReconstructPath(const ExploredNodes &explored, PointT dest, int8_t *path, si
int8_t GetPathDirection(Point startPosition, Point destinationPosition)
{
constexpr int8_t PathDirections[9] = { 5, 1, 6, 2, 0, 3, 8, 4, 7 };
return PathDirections[3 * (destinationPosition.y - startPosition.y) + 4 + destinationPosition.x - startPosition.x];
return PathDirections[(3 * (destinationPosition.y - startPosition.y)) + 4 + destinationPosition.x - startPosition.x];
}
int FindPath(tl::function_ref<bool(Point, Point)> canStep, tl::function_ref<bool(Point)> posOk, Point startPosition, Point destinationPosition, int8_t *path, size_t maxPathLength)

2
Source/engine/random.cpp

@ -88,7 +88,7 @@ uint32_t GenerateRandomNumber()
int32_t AdvanceRndSeed()
{
const int32_t seed = static_cast<int32_t>(GenerateRandomNumber());
const auto seed = static_cast<int32_t>(GenerateRandomNumber());
// since abs(INT_MIN) is undefined behavior, handle this value specially
return seed == std::numeric_limits<int32_t>::min() ? std::numeric_limits<int32_t>::min() : std::abs(seed);
}

4
Source/engine/render/clx_render.cpp

@ -59,7 +59,7 @@ struct ClipX {
DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT ClipX CalculateClipX(int_fast16_t x, std::size_t w, const Surface &out)
{
ClipX clip;
clip.left = static_cast<int_fast16_t>(x < 0 ? -x : 0);
clip.left = (x < 0 ? -x : 0);
clip.right = static_cast<int_fast16_t>(static_cast<int_fast16_t>(x + w) > out.w() ? x + w - out.w() : 0);
clip.width = static_cast<int_fast16_t>(w - clip.left - clip.right);
return clip;
@ -236,7 +236,7 @@ void DoRenderBackwards(
constexpr size_t MaxOutlinePixels = 4096;
constexpr size_t MaxOutlineSpriteWidth = 253;
using OutlinePixels = StaticVector<PointOf<uint8_t>, MaxOutlinePixels>;
using OutlineRowSolidRuns = StaticVector<std::pair<uint8_t, uint8_t>, MaxOutlineSpriteWidth / 2 + 1>;
using OutlineRowSolidRuns = StaticVector<std::pair<uint8_t, uint8_t>, (MaxOutlineSpriteWidth / 2) + 1>;
struct OutlinePixelsCacheEntry {
OutlinePixels outlinePixels;

84
Source/engine/render/dun_render.cpp

@ -42,7 +42,7 @@ constexpr int_fast16_t Height = DunFrameHeight;
constexpr int_fast16_t LowerHeight = DunFrameHeight / 2;
/** Height of the upper triangle of a triangular tile. */
constexpr int_fast16_t TriangleUpperHeight = DunFrameHeight / 2 - 1;
constexpr int_fast16_t TriangleUpperHeight = (DunFrameHeight / 2) - 1;
/** Height of the upper rectangle of a trapezoid tile. */
constexpr int_fast16_t TrapezoidUpperHeight = DunFrameHeight / 2;
@ -436,28 +436,28 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT std::size_t CalculateTriangleSourceSkipLower
DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT std::size_t CalculateTriangleSourceSkipUpperBottom(int_fast16_t numLines)
{
return 2 * TriangleUpperHeight * numLines - numLines * (numLines - 1);
return (2 * TriangleUpperHeight * numLines) - (numLines * (numLines - 1));
}
template <LightType Light, bool Transparent>
DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderTriangleLower(uint8_t *DVL_RESTRICT &dst, ptrdiff_t dstLineOffset, const uint8_t *DVL_RESTRICT &src, const uint8_t *DVL_RESTRICT tbl, const Lightmap *lightmap)
{
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 0 * dstLineOffset, src + 0, 2, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 1 * dstLineOffset, src + 2, 4, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 2 * dstLineOffset, src + 6, 6, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 3 * dstLineOffset, src + 12, 8, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 4 * dstLineOffset, src + 20, 10, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 5 * dstLineOffset, src + 30, 12, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 6 * dstLineOffset, src + 42, 14, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 7 * dstLineOffset, src + 56, 16, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 8 * dstLineOffset, src + 72, 18, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 9 * dstLineOffset, src + 90, 20, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 10 * dstLineOffset, src + 110, 22, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 11 * dstLineOffset, src + 132, 24, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 12 * dstLineOffset, src + 156, 26, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 13 * dstLineOffset, src + 182, 28, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 14 * dstLineOffset, src + 210, 30, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 15 * dstLineOffset, src + 240, 32, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (0 * dstLineOffset), src + 0, 2, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (1 * dstLineOffset), src + 2, 4, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (2 * dstLineOffset), src + 6, 6, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (3 * dstLineOffset), src + 12, 8, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (4 * dstLineOffset), src + 20, 10, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (5 * dstLineOffset), src + 30, 12, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (6 * dstLineOffset), src + 42, 14, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (7 * dstLineOffset), src + 56, 16, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (8 * dstLineOffset), src + 72, 18, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (9 * dstLineOffset), src + 90, 20, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (10 * dstLineOffset), src + 110, 22, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (11 * dstLineOffset), src + 132, 24, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (12 * dstLineOffset), src + 156, 26, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (13 * dstLineOffset), src + 182, 28, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (14 * dstLineOffset), src + 210, 30, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (15 * dstLineOffset), src + 240, 32, tbl, lightmap);
src += 272;
dst -= 16 * dstLineOffset;
}
@ -477,21 +477,21 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderTriangleLower<LightType::FullyDar
template <LightType Light, bool Transparent>
DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderTriangleUpper(uint8_t *DVL_RESTRICT dst, ptrdiff_t dstLineOffset, const uint8_t *DVL_RESTRICT src, const uint8_t *DVL_RESTRICT tbl, const Lightmap *lightmap)
{
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 0 * dstLineOffset, src + 0, 30, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 1 * dstLineOffset, src + 30, 28, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 2 * dstLineOffset, src + 58, 26, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 3 * dstLineOffset, src + 84, 24, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 4 * dstLineOffset, src + 108, 22, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 5 * dstLineOffset, src + 130, 20, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 6 * dstLineOffset, src + 150, 18, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 7 * dstLineOffset, src + 168, 16, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 8 * dstLineOffset, src + 184, 14, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 9 * dstLineOffset, src + 198, 12, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 10 * dstLineOffset, src + 210, 10, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 11 * dstLineOffset, src + 220, 8, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 12 * dstLineOffset, src + 228, 6, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 13 * dstLineOffset, src + 234, 4, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - 14 * dstLineOffset, src + 238, 2, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (0 * dstLineOffset), src + 0, 30, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (1 * dstLineOffset), src + 30, 28, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (2 * dstLineOffset), src + 58, 26, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (3 * dstLineOffset), src + 84, 24, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (4 * dstLineOffset), src + 108, 22, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (5 * dstLineOffset), src + 130, 20, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (6 * dstLineOffset), src + 150, 18, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (7 * dstLineOffset), src + 168, 16, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (8 * dstLineOffset), src + 184, 14, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (9 * dstLineOffset), src + 198, 12, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (10 * dstLineOffset), src + 210, 10, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (11 * dstLineOffset), src + 220, 8, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (12 * dstLineOffset), src + 228, 6, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (13 * dstLineOffset), src + 234, 4, tbl, lightmap);
RenderLineTransparentOrOpaque<Light, Transparent>(dst - (14 * dstLineOffset), src + 238, 2, tbl, lightmap);
}
template <>
@ -533,7 +533,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderLeftTriangleLowerClipLeftAndVerti
const auto lowerMax = LowerHeight - clipY.lowerTop;
for (auto i = 1 + clipY.lowerBottom; i <= lowerMax; ++i, dst -= dstPitch + XStep) {
const auto width = XStep * i;
const auto startX = Width - XStep * i;
const auto startX = Width - (XStep * i);
const auto skip = startX < clipLeft ? clipLeft - startX : 0;
if (width > skip)
RenderLineTransparentOrOpaque<Light, Transparent>(dst + skip, src + skip, width - skip, tbl, lightmap);
@ -572,7 +572,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderLeftTriangleClipVertical(uint8_t
dst += 2 * XStep + XStep * clipY.upperBottom;
const auto upperMax = TriangleUpperHeight - clipY.upperTop;
for (auto i = 1 + clipY.upperBottom; i <= upperMax; ++i, dst -= dstPitch - XStep) {
const auto width = Width - XStep * i;
const auto width = Width - (XStep * i);
RenderLineTransparentOrOpaque<Light, Transparent>(dst, src, width, tbl, lightmap);
src += width;
}
@ -588,7 +588,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderLeftTriangleClipLeftAndVertical(u
dst += 2 * XStep + XStep * clipY.upperBottom;
const auto upperMax = TriangleUpperHeight - clipY.upperTop;
for (auto i = 1 + clipY.upperBottom; i <= upperMax; ++i, dst -= dstPitch - XStep) {
const auto width = Width - XStep * i;
const auto width = Width - (XStep * i);
const auto startX = XStep * i;
const auto skip = startX < clipLeft ? clipLeft - startX : 0;
RenderLineTransparentOrOpaque<Light, Transparent>(dst + skip, src + skip, width > skip ? width - skip : 0, tbl, lightmap);
@ -606,7 +606,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderLeftTriangleClipRightAndVertical(
dst += 2 * XStep + XStep * clipY.upperBottom;
const auto upperMax = TriangleUpperHeight - clipY.upperTop;
for (auto i = 1 + clipY.upperBottom; i <= upperMax; ++i, dst -= dstPitch - XStep) {
const auto width = Width - XStep * i;
const auto width = Width - (XStep * i);
if (width <= clipRight)
break;
RenderLineTransparentOrOpaque<Light, Transparent>(dst, src, width - clipRight, tbl, lightmap);
@ -690,7 +690,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderRightTriangleClipVertical(uint8_t
src += CalculateTriangleSourceSkipUpperBottom(clipY.upperBottom);
const auto upperMax = TriangleUpperHeight - clipY.upperTop;
for (auto i = 1 + clipY.upperBottom; i <= upperMax; ++i, dst -= dstPitch) {
const auto width = Width - XStep * i;
const auto width = Width - (XStep * i);
RenderLineTransparentOrOpaque<Light, Transparent>(dst, src, width, tbl, lightmap);
src += width;
}
@ -705,7 +705,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderRightTriangleClipLeftAndVertical(
src += CalculateTriangleSourceSkipUpperBottom(clipY.upperBottom);
const auto upperMax = TriangleUpperHeight - clipY.upperTop;
for (auto i = 1 + clipY.upperBottom; i <= upperMax; ++i, dst -= dstPitch) {
const auto width = Width - XStep * i;
const auto width = Width - (XStep * i);
if (width <= clipLeft)
break;
RenderLineTransparentOrOpaque<Light, Transparent>(dst, src + clipLeft, width - clipLeft, tbl, lightmap);
@ -722,7 +722,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderRightTriangleClipRightAndVertical
src += CalculateTriangleSourceSkipUpperBottom(clipY.upperBottom);
const auto upperMax = TriangleUpperHeight - clipY.upperTop;
for (auto i = 1 + clipY.upperBottom; i <= upperMax; ++i, dst -= dstPitch) {
const auto width = Width - XStep * i;
const auto width = Width - (XStep * i);
const auto skip = Width - width < clipRight ? clipRight - (Width - width) : 0;
RenderLineTransparentOrOpaque<Light, Transparent>(dst, src, width > skip ? width - skip : 0, tbl, lightmap);
src += width;
@ -751,7 +751,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderTrapezoidUpperHalf(uint8_t *DVL_R
if constexpr (Mask == MaskType::Left || Mask == MaskType::Right) {
// The first line is always fully opaque.
// We handle it specially to avoid calling the blitter with width=0.
const uint8_t *srcEnd = src + Width * TrapezoidUpperHeight;
const uint8_t *srcEnd = src + (Width * TrapezoidUpperHeight);
RenderLineOpaque<Light>(dst, src, Width, tbl, &lightmap);
src += Width;
dst -= dstPitch;
@ -763,7 +763,7 @@ DVL_ALWAYS_INLINE DVL_ATTRIBUTE_HOT void RenderTrapezoidUpperHalf(uint8_t *DVL_R
dst -= dstPitch;
} while (src != srcEnd);
} else { // Mask == MaskType::Solid || Mask == MaskType::Transparent
const uint8_t *srcEnd = src + Width * TrapezoidUpperHeight;
const uint8_t *srcEnd = src + (Width * TrapezoidUpperHeight);
do {
RenderLineTransparentOrOpaque<Light, /*Transparent=*/Mask == MaskType::Transparent>(dst, src, Width, tbl, &lightmap);
src += Width;

12
Source/engine/render/light_render.cpp

@ -22,8 +22,8 @@ std::vector<uint8_t> LightmapBuffer;
void RenderFullTile(Point position, uint8_t lightLevel, uint8_t *lightmap, uint16_t pitch)
{
uint8_t *top = lightmap + (position.y + 1) * pitch + position.x - TILE_WIDTH / 2;
uint8_t *bottom = top + (TILE_HEIGHT - 2) * pitch;
uint8_t *top = lightmap + ((position.y + 1) * pitch) + position.x - (TILE_WIDTH / 2);
uint8_t *bottom = top + ((TILE_HEIGHT - 2) * pitch);
for (int y = 0, w = 4; y < TILE_HEIGHT / 2 - 1; y++, w += 4) {
const int x = (TILE_WIDTH - w) / 2;
memset(top + x, lightLevel, w);
@ -425,7 +425,7 @@ void BuildLightmap(Point tilePosition, Point targetBufferPosition, uint16_t view
{
// Since light may need to bleed up to the top of wall tiles,
// expand the buffer space to include the full base diamond of the tallest tile graphics
const uint16_t bufferHeight = viewportHeight + TILE_HEIGHT * (microTileLen / 2 + 1);
const uint16_t bufferHeight = viewportHeight + (TILE_HEIGHT * (microTileLen / 2 + 1));
rows += microTileLen + 2;
const size_t totalPixels = static_cast<size_t>(viewportWidth) * bufferHeight;
@ -539,13 +539,13 @@ Lightmap Lightmap::bleedUp(bool perPixelLighting, const Lightmap &source, Point
const uint16_t lightmapHeight = TILE_HEIGHT - clipTop - clipBottom;
// Find the left edge of the last row in the tile
const int outOffset = std::max(0, (targetBufferPosition.y - clipBottom) * source.outPitch + targetBufferPosition.x + clipLeft);
const int outOffset = std::max(0, ((targetBufferPosition.y - clipBottom) * source.outPitch) + targetBufferPosition.x + clipLeft);
const uint8_t *outLoc = source.outBuffer + outOffset;
const uint8_t *outBuffer = outLoc - (lightmapHeight - 1) * source.outPitch;
const uint8_t *outBuffer = outLoc - ((lightmapHeight - 1) * source.outPitch);
// Start copying bytes from the bottom row of the tile
const uint8_t *src = source.getLightingAt(outLoc);
uint8_t *dst = lightmapBuffer.data() + (lightmapHeight - 1) * lightmapPitch;
uint8_t *dst = lightmapBuffer.data() + ((lightmapHeight - 1) * lightmapPitch);
int rowCount = clipBottom;
while (src >= source.lightmapBuffer.data() && dst >= lightmapBuffer.data()) {

4
Source/engine/render/primitive_render.cpp

@ -54,7 +54,7 @@ void DrawHalfTransparentBlendedRectTo(const Surface &out, unsigned sx, unsigned
// First, draw the leading unaligned part.
if (sx % 4 != 0) {
const unsigned w = 4 - sx % 4;
const unsigned w = 4 - (sx % 4);
DrawHalfTransparentUnalignedBlendedRectTo(out, sx, sy, w, height, 0);
sx += w;
width -= w;
@ -66,7 +66,7 @@ void DrawHalfTransparentBlendedRectTo(const Surface &out, unsigned sx, unsigned
} else if (width % 4 != 0) {
// Draw the trailing unaligned part.
const unsigned w = width % 4;
DrawHalfTransparentUnalignedBlendedRectTo(out, sx + (width / 4) * 4, sy, w, height, 0);
DrawHalfTransparentUnalignedBlendedRectTo(out, sx + ((width / 4) * 4), sy, w, height, 0);
width -= w;
}

4
Source/engine/render/scrollrt.cpp

@ -1002,7 +1002,7 @@ void DrawTileContent(const Surface &out, const Lightmap &lightmap, Point tilePos
if (InDungeonBounds(tilePosition)) {
bool skipNext = false;
#ifdef _DEBUG
DebugCoordsMap[tilePosition.x + tilePosition.y * MAXDUNX] = targetBufferPosition;
DebugCoordsMap[tilePosition.x + (tilePosition.y * MAXDUNX)] = targetBufferPosition;
#endif
if (tilePosition.x + 1 < MAXDUNX && tilePosition.y - 1 >= 0 && targetBufferPosition.x + TILE_WIDTH <= gnScreenWidth) {
// Render objects behind walls first to prevent sprites, that are moving
@ -1707,7 +1707,7 @@ void CalcViewportGeometry()
// Location of the bottom-left corner of the bounding box around the
// tile from which to start rendering, relative to the viewport origin
tileOffset = { startPosition.x - TILE_WIDTH / 2, startPosition.y + TILE_HEIGHT / 2 - 1 };
tileOffset = { startPosition.x - (TILE_WIDTH / 2), startPosition.y + (TILE_HEIGHT / 2) - 1 };
// Compute the number of rows to be rendered as well as
// the number of columns to be rendered in the first row

4
Source/engine/render/text_render.cpp

@ -349,7 +349,7 @@ public:
return result;
}
size_t offset() const
[[nodiscard]] size_t offset() const
{
return next_;
}
@ -430,7 +430,7 @@ void MaybeWrap(Point &characterPosition, int characterWidth, int rightMargin, in
int GetLineStartX(UiFlags flags, const Rectangle &rect, int lineWidth)
{
if (HasAnyOf(flags, UiFlags::AlignCenter)) {
return std::max(rect.position.x, rect.position.x + (rect.size.width - lineWidth) / 2);
return std::max(rect.position.x, rect.position.x + ((rect.size.width - lineWidth) / 2));
}
if (HasAnyOf(flags, UiFlags::AlignRight))
return rect.position.x + rect.size.width - lineWidth;

12
Source/gmenu.cpp

@ -44,18 +44,18 @@ namespace {
constexpr int SliderItemWidth = 490;
// Horizontal dimensions of the slider value
constexpr int SliderValueBoxLeft = 16 + SliderItemWidth / 2;
constexpr int SliderValueBoxLeft = 16 + (SliderItemWidth / 2);
constexpr int SliderValueBoxWidth = 287;
constexpr int SliderValueBorderWidth = 2;
constexpr int SliderValueLeft = SliderValueBoxLeft + SliderValueBorderWidth;
constexpr int SliderValueWidth = SliderValueBoxWidth - 2 * SliderValueBorderWidth;
constexpr int SliderValueWidth = SliderValueBoxWidth - (2 * SliderValueBorderWidth);
constexpr int SliderValueHeight = 29;
constexpr int SliderValuePaddingTop = 10;
constexpr int SliderMarkerWidth = 27;
constexpr int SliderFillMin = SliderMarkerWidth / 2;
constexpr int SliderFillMax = SliderValueWidth - SliderMarkerWidth / 2 - 1;
constexpr int SliderFillMax = SliderValueWidth - (SliderMarkerWidth / 2) - 1;
constexpr int GMenuTop = 117;
constexpr int GMenuItemHeight = 45;
@ -134,10 +134,10 @@ void GmenuDrawMenuItem(const Surface &out, TMenuItem *pItem, int y)
ClxDraw(out, { SliderValueBoxLeft + uiPositionX, y + 40 }, (*optbar_cel)[0]);
const uint16_t step = pItem->dwFlags & 0xFFF;
const uint16_t steps = std::max<uint16_t>(pItem->sliderSteps(), 2);
const uint16_t pos = SliderFillMin + step * (SliderFillMax - SliderFillMin) / steps;
const uint16_t pos = SliderFillMin + (step * (SliderFillMax - SliderFillMin) / steps);
SDL_Rect rect = MakeSdlRect(SliderValueLeft + uiPositionX, y + SliderValuePaddingTop, pos, SliderValueHeight);
SDL_FillSurfaceRect(out.surface, &rect, 205);
ClxDraw(out, { SliderValueLeft + pos - SliderMarkerWidth / 2 + uiPositionX, y + SliderValuePaddingTop + SliderValueHeight - 1 }, (*option_cel)[0]);
ClxDraw(out, { SliderValueLeft + pos - (SliderMarkerWidth / 2) + uiPositionX, y + SliderValuePaddingTop + SliderValueHeight - 1 }, (*option_cel)[0]);
}
const int x = (gnScreenWidth - w) / 2;
@ -383,7 +383,7 @@ int gmenu_slider_get(TMenuItem *pItem, int min, int max)
{
const uint16_t step = pItem->sliderStep();
const uint16_t steps = std::max<uint16_t>(pItem->sliderSteps(), 2);
return min + (step * (max - min) + (steps - 1) / 2) / steps;
return min + ((step * (max - min) + (steps - 1) / 2) / steps);
}
void gmenu_slider_steps(TMenuItem *pItem, int steps)

8
Source/help.cpp

@ -121,7 +121,7 @@ int DividerLineMarginY()
int HeaderHeight()
{
return PaddingTop + LineHeight() + 2 * BlankLineHeight() + DividerLineMarginY();
return PaddingTop + LineHeight() + (2 * BlankLineHeight()) + DividerLineMarginY();
}
int ContentPaddingY()
@ -131,12 +131,12 @@ int ContentPaddingY()
int ContentsTextHeight()
{
return PanelHeight - HeaderHeight() - DividerLineMarginY() - 2 * ContentPaddingY() - BlankLineHeight();
return PanelHeight - HeaderHeight() - DividerLineMarginY() - (2 * ContentPaddingY()) - BlankLineHeight();
}
int NumVisibleLines()
{
return (ContentsTextHeight() - 1) / LineHeight() + 1; // Ceil
return ((ContentsTextHeight() - 1) / LineHeight()) + 1; // Ceil
}
void DrawHelpSlider(const Surface &out)
@ -227,7 +227,7 @@ void DrawHelp(const Surface &out)
style = UiFlags::ColorBlue;
}
DrawString(out, line.substr(offset), { { sx, contentY + i * lineHeight }, { ContentTextWidth, lineHeight } },
DrawString(out, line.substr(offset), { { sx, contentY + (i * lineHeight) }, { ContentTextWidth, lineHeight } },
{ .flags = style, .lineHeight = lineHeight });
}

2
Source/interfac.cpp

@ -229,7 +229,7 @@ void DrawCutsceneBackground()
SDL_FillSurfaceRect(out.surface, nullptr, 0);
if (ArtCutsceneWidescreen) {
const ClxSprite sprite = (*ArtCutsceneWidescreen)[0];
RenderClxSprite(out, sprite, { uiRectangle.position.x - (sprite.width() - uiRectangle.size.width) / 2, uiRectangle.position.y });
RenderClxSprite(out, sprite, { uiRectangle.position.x - ((sprite.width() - uiRectangle.size.width) / 2), uiRectangle.position.y });
}
ClxDraw(out, { uiRectangle.position.x, 480 - 1 + uiRectangle.position.y }, (*sgpBackCel)[0]);
}

32
Source/inv.cpp

@ -152,7 +152,7 @@ void AddItemToInvGrid(Player &player, int invGridIndex, int invListIndex, Size i
{
const int pitch = 10;
for (int y = 0; y < itemSize.height; y++) {
const int rowGridIndex = invGridIndex + pitch * y;
const int rowGridIndex = invGridIndex + (pitch * y);
for (int x = 0; x < itemSize.width; x++) {
if (x == 0 && y == itemSize.height - 1)
player.InvGrid[rowGridIndex + x] = invListIndex;
@ -328,7 +328,7 @@ int FindTargetSlotUnderItemCursor(Point cursorPosition, Size itemSize)
const int hotPixelCell = r - SLOTXY_INV_FIRST;
const int targetRow = std::clamp((hotPixelCell / InventorySizeInSlots.width) - hotPixelCellOffset.deltaY, 0, InventorySizeInSlots.height - itemSize.height);
const int targetColumn = std::clamp((hotPixelCell % InventorySizeInSlots.width) - hotPixelCellOffset.deltaX, 0, InventorySizeInSlots.width - itemSize.width);
return SLOTXY_INV_FIRST + targetRow * InventorySizeInSlots.width + targetColumn;
return SLOTXY_INV_FIRST + (targetRow * InventorySizeInSlots.width) + targetColumn;
}
}
@ -421,7 +421,7 @@ void ChangeTwoHandItem(Player &player)
int8_t CheckOverlappingItems(int slot, const Player &player, Size itemSize)
{
// check that the item we're pasting only overlaps one other item (or is going into empty space)
const unsigned originCell = static_cast<unsigned>(slot - SLOTXY_INV_FIRST);
const auto originCell = static_cast<unsigned>(slot - SLOTXY_INV_FIRST);
int8_t overlappingId = 0;
for (unsigned rowOffset = 0; rowOffset < static_cast<unsigned>(itemSize.height * InventorySizeInSlots.width); rowOffset += InventorySizeInSlots.width) {
@ -538,7 +538,7 @@ void ChangeBeltItem(Player &player, int slot)
RedrawComponent(PanelDrawComponent::Belt);
}
item_equip_type GetItemEquipType(const Player &player, int slot, item_equip_type desiredLocation)
item_equip_type GetItemEquipType(int slot, item_equip_type desiredLocation)
{
if (slot == SLOTXY_HEAD)
return ILOC_HELM;
@ -568,7 +568,7 @@ void CheckInvPaste(Player &player, Point cursorPosition)
return;
const item_equip_type desiredLocation = player.GetItemLocation(player.HoldItem);
const item_equip_type location = GetItemEquipType(player, slot, desiredLocation);
const item_equip_type location = GetItemEquipType(slot, desiredLocation);
if (location == ILOC_BELT) {
if (!CanBePlacedOnBelt(player, player.HoldItem)) return;
@ -630,7 +630,7 @@ inv_body_loc MapSlotToInvBodyLoc(inv_xy_slot slot)
std::optional<inv_xy_slot> FindSlotUnderCursor(Point cursorPosition)
{
Point testPosition = static_cast<Point>(cursorPosition - GetRightPanel().position);
auto testPosition = static_cast<Point>(cursorPosition - GetRightPanel().position);
for (std::underlying_type_t<inv_xy_slot> r = SLOTXY_EQUIPPED_FIRST; r != SLOTXY_BELT_FIRST; r++) {
// check which body/inventory rectangle the mouse is in, if any
if (InvRect[r].contains(testPosition)) {
@ -667,7 +667,7 @@ bool CheckItemFitsInInventorySlot(const Player &player, int slotIndex, const Siz
}
int xx = (slotIndex > 0) ? (slotIndex % 10) : 0;
for (int i = 0; i < itemSize.width; i++) {
if (xx >= 10 || !(player.InvGrid[xx + yy] == 0 || std::abs(player.InvGrid[xx + yy]) - 1 == itemIndexToIgnore)) {
if (xx >= 10 || (player.InvGrid[xx + yy] != 0 && std::abs(player.InvGrid[xx + yy]) - 1 != itemIndexToIgnore)) {
// The item is too wide to fit in the specified column, or one of the cells is occupied (and not by the item we're planning on removing)
return false;
}
@ -694,8 +694,8 @@ std::optional<int> FindSlotForItem(const Player &player, const Size &itemSize, i
}
for (int x = 9; x >= 0; x--) {
for (int y = 2; y >= 0; y--) {
if (CheckItemFitsInInventorySlot(player, 10 * y + x, itemSize, itemIndexToIgnore))
return 10 * y + x;
if (CheckItemFitsInInventorySlot(player, (10 * y) + x, itemSize, itemIndexToIgnore))
return (10 * y) + x;
}
}
return {};
@ -704,8 +704,8 @@ std::optional<int> FindSlotForItem(const Player &player, const Size &itemSize, i
if (itemSize.height == 2) {
for (int x = 10 - itemSize.width; x >= 0; x--) {
for (int y = 0; y < 3; y++) {
if (CheckItemFitsInInventorySlot(player, 10 * y + x, itemSize, itemIndexToIgnore))
return 10 * y + x;
if (CheckItemFitsInInventorySlot(player, (10 * y) + x, itemSize, itemIndexToIgnore))
return (10 * y) + x;
}
}
return {};
@ -1533,7 +1533,7 @@ int AddGoldToInventory(Player &player, int value)
// Remaining inventory in columns, bottom to top, right to left
for (int x = 9; x >= 0 && value > 0; x--) {
for (int y = 2; y >= 0 && value > 0; y--) {
value = CreateGoldItemInInventorySlot(player, 10 * y + x, value);
value = CreateGoldItemInInventorySlot(player, (10 * y) + x, value);
}
}
@ -1577,7 +1577,7 @@ void CheckInvSwap(Player &player, const Item &item, int invGridIndex)
const int pitch = 10;
const int invListIndex = [&]() -> int {
for (int y = 0; y < itemSize.height; y++) {
const int rowGridIndex = invGridIndex + pitch * y;
const int rowGridIndex = invGridIndex + (pitch * y);
for (int x = 0; x < itemSize.width; x++) {
const int gridIndex = rowGridIndex + x;
if (player.InvGrid[gridIndex] != 0)
@ -1600,7 +1600,7 @@ void CheckInvSwap(Player &player, const Item &item, int invGridIndex)
player.InvList[invListIndex - 1] = item;
for (int y = 0; y < itemSize.height; y++) {
const int rowGridIndex = invGridIndex + pitch * y;
const int rowGridIndex = invGridIndex + (pitch * y);
for (int x = 0; x < itemSize.width; x++) {
if (x == 0 && y == itemSize.height - 1)
player.InvGrid[rowGridIndex + x] = invListIndex;
@ -1628,7 +1628,7 @@ void TransferItemToStash(Player &player, int location)
}
const Item &item = GetInventoryItem(player, location);
if (!AutoPlaceItemInStash(player, item, true)) {
if (!AutoPlaceItemInStash(item, true)) {
player.SaySpecific(HeroSpeech::WhereWouldIPutThis);
return;
}
@ -2249,7 +2249,7 @@ void CloseStash()
} else {
if (!AutoPlaceItemInBelt(myPlayer, myPlayer.HoldItem, true, true)
&& !AutoPlaceItemInInventory(myPlayer, myPlayer.HoldItem, true)
&& !AutoPlaceItemInStash(myPlayer, myPlayer.HoldItem, true)) {
&& !AutoPlaceItemInStash(myPlayer.HoldItem, true)) {
// This can fail for max gold, arena potions and a stash that has been arranged
// to not have room for the item all 3 cases are extremely unlikely
app_fatal(_("No room for item"));

6
Source/items.cpp

@ -1396,9 +1396,7 @@ _item_indexes RndAllItems()
int itemMaxLevel = ItemsGetCurrlevel() * 2;
return GetItemIndexForDroppableItem(false, [&itemMaxLevel](const ItemData &item) {
if (itemMaxLevel < item.iMinMLvl)
return false;
return true;
return itemMaxLevel >= item.iMinMLvl;
});
}
@ -4637,7 +4635,7 @@ void SpawnHealer(int lvl)
{
constexpr size_t PinnedItemCount = NumHealerPinnedItems;
constexpr std::array<_item_indexes, PinnedItemCount + 1> PinnedItemTypes = { IDI_HEAL, IDI_FULLHEAL, IDI_RESURRECT };
const size_t itemCount = static_cast<size_t>(RandomIntBetween(10, gbIsHellfire ? NumHealerItemsHf : NumHealerItems));
const auto itemCount = static_cast<size_t>(RandomIntBetween(10, gbIsHellfire ? NumHealerItemsHf : NumHealerItems));
HealerItems.clear();
for (size_t i = 0; i < itemCount; i++) {

9
Source/items/validation.cpp

@ -72,13 +72,10 @@ bool IsShopPriceValid(const Item &item)
const uint16_t smithOrWitch = CF_SMITH | CF_WITCH;
const int smithAndWitchPriceLimit = gbIsHellfire ? MaxVendorValueHf : MaxVendorValue;
if ((item._iCreateInfo & smithOrWitch) != 0 && item._iIvalue > smithAndWitchPriceLimit)
return false;
return true;
return !((item._iCreateInfo & smithOrWitch) != 0 && item._iIvalue > smithAndWitchPriceLimit);
}
bool IsUniqueMonsterItemValid(uint16_t iCreateInfo, uint32_t dwBuff)
bool IsUniqueMonsterItemValid(uint16_t iCreateInfo, uint32_t /*dwBuff*/)
{
const uint8_t level = iCreateInfo & CF_LEVEL;
@ -185,7 +182,7 @@ bool IsItemDeltaValid(const TCmdPItem &itemDelta)
return false;
if (!InDungeonBounds({ itemDelta.x, itemDelta.y }))
return false;
const _item_indexes idx = static_cast<_item_indexes>(Swap16LE(itemDelta.def.wIndx));
const auto idx = static_cast<_item_indexes>(Swap16LE(itemDelta.def.wIndx));
if (idx == IDI_EAR)
return true;
if (!IsItemAvailable(idx))

16
Source/levels/drlg_l1.cpp

@ -356,14 +356,10 @@ bool CanReplaceTile(uint8_t replace, Point tile)
&& (p2.x >= 0 && p2.x < DMAXX && p2.y >= 0 && p2.y < DMAXY)
&& (dungeon[p1.x][p1.y] >= VWallEnd2 && dungeon[p2.x][p2.y] <= VWall8);
};
if (ComparisonWithBoundsCheck(tile + Direction::NorthWest, tile + Direction::NorthWest)
return !(ComparisonWithBoundsCheck(tile + Direction::NorthWest, tile + Direction::NorthWest)
|| ComparisonWithBoundsCheck(tile + Direction::SouthEast, tile + Direction::NorthWest)
|| ComparisonWithBoundsCheck(tile + Direction::SouthWest, tile + Direction::NorthWest)
|| ComparisonWithBoundsCheck(tile + Direction::NorthEast, tile + Direction::NorthWest)) {
return false;
}
return true;
|| ComparisonWithBoundsCheck(tile + Direction::NorthEast, tile + Direction::NorthWest));
}
void FillFloor()
@ -471,10 +467,10 @@ void GenerateRoom(Rectangle area, bool verticalLayout)
room1.size = { randomWidth, randomHeight };
room1.position = area.position;
if (verticalLayout) {
room1.position += Displacement { -room1.size.width, area.size.height / 2 - room1.size.height / 2 };
room1.position += Displacement { -room1.size.width, (area.size.height / 2) - (room1.size.height / 2) };
placeRoom1 = CheckRoom({ room1.position + Displacement { -1, -1 }, { room1.size.height + 2, room1.size.width + 1 } }); /// BUGFIX: swap height and width ({ room1.size.width + 1, room1.size.height + 2 }) (workaround applied below)
} else {
room1.position += Displacement { area.size.width / 2 - room1.size.width / 2, -room1.size.height };
room1.position += Displacement { (area.size.width / 2) - (room1.size.width / 2), -room1.size.height };
placeRoom1 = CheckRoom({ room1.position + Displacement { -1, -1 }, { room1.size.width + 2, room1.size.height + 1 } });
}
if (placeRoom1)
@ -1202,8 +1198,8 @@ void GenerateLevel(lvl_entry entry)
for (int j = 0; j < DMAXY; j++) {
for (int i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == EntranceStairs) {
const int xx = 2 * i + 16; /* todo: fix loop */
const int yy = 2 * j + 16;
const int xx = (2 * i) + 16; /* todo: fix loop */
const int yy = (2 * j) + 16;
DRLG_CopyTrans(xx, yy + 1, xx, yy);
DRLG_CopyTrans(xx + 1, yy + 1, xx + 1, yy);
}

4
Source/levels/drlg_l2.cpp

@ -1608,8 +1608,8 @@ void PlaceMiniSetRandom(const Miniset &miniset, int rndper)
if (!miniset.matches({ sx, sy }))
continue;
bool found = true;
for (int yy = std::max(sy - sh, 0); yy < std::min(sy + 2 * sh, DMAXY) && found; yy++) {
for (int xx = std::max(sx - sw, 0); xx < std::min(sx + 2 * sw, DMAXX); xx++) {
for (int yy = std::max(sy - sh, 0); yy < std::min(sy + (2 * sh), DMAXY) && found; yy++) {
for (int xx = std::max(sx - sw, 0); xx < std::min(sx + (2 * sw), DMAXX); xx++) {
if (dungeon[xx][yy] == miniset.replace[0][0]) {
found = false;
break;

12
Source/levels/drlg_l3.cpp

@ -851,7 +851,7 @@ void FillDiagonals()
{
for (int j = 0; j < DMAXY - 1; j++) {
for (int i = 0; i < DMAXX - 1; i++) {
const int v = dungeon[i + 1][j + 1] + 2 * dungeon[i][j + 1] + 4 * dungeon[i + 1][j] + 8 * dungeon[i][j];
const int v = dungeon[i + 1][j + 1] + (2 * dungeon[i][j + 1]) + (4 * dungeon[i + 1][j]) + (8 * dungeon[i][j]);
if (v == 6) {
if (FlipCoin()) {
dungeon[i][j] = 1;
@ -994,7 +994,7 @@ void MakeMegas()
{
for (int j = 0; j < DMAXY - 1; j++) {
for (int i = 0; i < DMAXX - 1; i++) {
int v = dungeon[i + 1][j + 1] + 2 * dungeon[i][j + 1] + 4 * dungeon[i + 1][j] + 8 * dungeon[i][j];
int v = dungeon[i + 1][j + 1] + (2 * dungeon[i][j + 1]) + (4 * dungeon[i + 1][j]) + (8 * dungeon[i][j]);
if (v == 6) {
v = PickRandomlyAmong({ 12, 5 });
}
@ -1376,14 +1376,10 @@ bool CanReplaceTile(uint8_t replace, Point tile)
&& (p2.x >= 0 && p2.x < DMAXX && p2.y >= 0 && p2.y < DMAXY)
&& (dungeon[p1.x][p1.y] >= 84 && dungeon[p2.x][p2.y] <= 100);
};
if (ComparisonWithBoundsCheck(tile + Direction::NorthWest, tile + Direction::NorthWest)
return !(ComparisonWithBoundsCheck(tile + Direction::NorthWest, tile + Direction::NorthWest)
|| ComparisonWithBoundsCheck(tile + Direction::SouthEast, tile + Direction::NorthWest)
|| ComparisonWithBoundsCheck(tile + Direction::SouthWest, tile + Direction::NorthWest)
|| ComparisonWithBoundsCheck(tile + Direction::NorthEast, tile + Direction::NorthWest)) {
return false;
}
return true;
|| ComparisonWithBoundsCheck(tile + Direction::NorthEast, tile + Direction::NorthWest));
}
/**

24
Source/levels/drlg_l4.cpp

@ -227,10 +227,10 @@ void GenerateRoom(WorldTileRectangle area, bool verticalLayout)
room1.size = WorldTileSize(randomWidth, randomHeight);
room1.position = area.position;
if (verticalLayout) {
room1.position += WorldTileDisplacement(-room1.size.width, area.size.height / 2 - room1.size.height / 2);
room1.position += WorldTileDisplacement(-room1.size.width, (area.size.height / 2) - (room1.size.height / 2));
placeRoom1 = CheckRoom({ room1.position + WorldTileDisplacement { -1, -1 }, WorldTileSize(room1.size.height + 2, room1.size.width + 1) }); /// BUGFIX: swap height and width ({ room1.size.width + 1, room1.size.height + 2 }) (workaround applied below)
} else {
room1.position += WorldTileDisplacement(area.size.width / 2 - room1.size.width / 2, -room1.size.height);
room1.position += WorldTileDisplacement((area.size.width / 2) - (room1.size.width / 2), -room1.size.height);
placeRoom1 = CheckRoom({ room1.position + WorldTileDisplacement { -1, -1 }, WorldTileSize(room1.size.width + 2, room1.size.height + 1) });
}
if (placeRoom1)
@ -274,9 +274,9 @@ void FirstRoom()
}
const int xmin = (DMAXX / 2 - room.size.width) / 2;
const int xmax = DMAXX / 2 - 1 - room.size.width;
const int xmax = (DMAXX / 2) - 1 - room.size.width;
const int ymin = (DMAXY / 2 - room.size.height) / 2;
const int ymax = DMAXY / 2 - 1 - room.size.height;
const int ymax = (DMAXY / 2) - 1 - room.size.height;
const int32_t randomX = GenerateRnd(xmax - xmin + 1) + xmin;
const int32_t randomY = GenerateRnd(ymax - ymin + 1) + ymin;
room.position = WorldTilePosition(randomX, randomY);
@ -868,8 +868,8 @@ void Substitution()
*/
void PrepareInnerBorders()
{
for (int y = DMAXY / 2 - 1; y >= 0; y--) {
for (int x = DMAXX / 2 - 1; x >= 0; x--) {
for (int y = (DMAXY / 2) - 1; y >= 0; y--) {
for (int x = (DMAXX / 2) - 1; x >= 0; x--) {
if (!DungeonMask.test(x, y)) {
hallok[y] = false;
} else {
@ -881,10 +881,10 @@ void PrepareInnerBorders()
}
}
int ry = GenerateRnd(DMAXY / 2 - 1) + 1;
int ry = GenerateRnd((DMAXY / 2) - 1) + 1;
do {
if (hallok[ry]) {
for (int x = DMAXX / 2 - 1; x >= 0; x--) {
for (int x = (DMAXX / 2) - 1; x >= 0; x--) {
if (DungeonMask.test(x, ry)) {
x = -1;
ry = 0;
@ -901,8 +901,8 @@ void PrepareInnerBorders()
}
} while (ry != 0);
for (int x = DMAXX / 2 - 1; x >= 0; x--) {
for (int y = DMAXY / 2 - 1; y >= 0; y--) {
for (int x = (DMAXX / 2) - 1; x >= 0; x--) {
for (int y = (DMAXY / 2) - 1; y >= 0; y--) {
if (!DungeonMask.test(x, y)) {
hallok[x] = false;
} else {
@ -914,10 +914,10 @@ void PrepareInnerBorders()
}
}
int rx = GenerateRnd(DMAXX / 2 - 1) + 1;
int rx = GenerateRnd((DMAXX / 2) - 1) + 1;
do {
if (hallok[rx]) {
for (int y = DMAXY / 2 - 1; y >= 0; y--) {
for (int y = (DMAXY / 2) - 1; y >= 0; y--) {
if (DungeonMask.test(rx, y)) {
y = -1;
rx = 0;

10
Source/levels/gendung.cpp

@ -599,12 +599,12 @@ void LoadTransparency(const uint16_t *dunData)
{
WorldTileSize size = GetDunSize(dunData);
const int layer2Offset = 2 + size.width * size.height;
const int layer2Offset = 2 + (size.width * size.height);
// The rest of the layers are at dPiece scale
size *= static_cast<WorldTileCoord>(2);
const uint16_t *transparentLayer = &dunData[layer2Offset + size.width * size.height * 3];
const uint16_t *transparentLayer = &dunData[layer2Offset + (size.width * size.height * 3)];
for (WorldTileCoord j = 0; j < size.height; j++) {
for (WorldTileCoord i = 0; i < size.width; i++) {
@ -695,7 +695,7 @@ void PlaceDunTiles(const uint16_t *dunData, Point position, int floorId)
for (WorldTileCoord j = 0; j < size.height; j++) {
for (WorldTileCoord i = 0; i < size.width; i++) {
auto tileId = static_cast<uint8_t>(Swap16LE(tileLayer[j * size.width + i]));
auto tileId = static_cast<uint8_t>(Swap16LE(tileLayer[(j * size.width) + i]));
if (tileId != 0) {
dungeon[position.x + i][position.y + j] = tileId;
Protected.set(position.x + i, position.y + j);
@ -749,8 +749,8 @@ void DRLG_HoldThemeRooms()
for (int i = 0; i < themeCount; i++) {
for (int y = themeLoc[i].room.position.y; y < themeLoc[i].room.position.y + themeLoc[i].room.size.height - 1; y++) {
for (int x = themeLoc[i].room.position.x; x < themeLoc[i].room.position.x + themeLoc[i].room.size.width - 1; x++) {
const int xx = 2 * x + 16;
const int yy = 2 * y + 16;
const int xx = (2 * x) + 16;
const int yy = (2 * y) + 16;
dFlags[xx][yy] |= DungeonFlag::Populated;
dFlags[xx + 1][yy] |= DungeonFlag::Populated;
dFlags[xx][yy + 1] |= DungeonFlag::Populated;

2
Source/levels/reencode_dun_cels.cpp

@ -254,7 +254,7 @@ void ReencodeDungeonCels(std::unique_ptr<std::byte[]> &dungeonCels, std::span<st
auto *const resultPtr = reinterpret_cast<uint8_t *>(result.get());
WriteLE32(resultPtr, static_cast<uint32_t>(frames.size()));
uint8_t *lookup = resultPtr + 4;
uint8_t *out = resultPtr + (2 + frames.size()) * 4; // number of frames, frame offsets, file size
uint8_t *out = resultPtr + ((2 + frames.size()) * 4); // number of frames, frame offsets, file size
for (const auto &[frame, info] : frames) {
WriteLE32(lookup, static_cast<uint32_t>(out - resultPtr));
lookup += 4;

2
Source/levels/town.cpp

@ -38,7 +38,7 @@ void FillSector(const char *path, int xi, int yy)
int v3 = 218;
int v4 = 218;
const int tileId = Swap16LE(tileLayer[j * size.width + i]) - 1;
const int tileId = Swap16LE(tileLayer[(j * size.width) + i]) - 1;
if (tileId >= 0) {
const MegaTile mega = pMegaTiles[tileId];
v1 = Swap16LE(mega.micro1);

6
Source/lighting.cpp

@ -318,9 +318,9 @@ void MakeLightTable()
for (int offsetX = 0; offsetX < 8; offsetX++) {
for (int y = 0; y < 16; y++) {
for (int x = 0; x < 16; x++) {
const int a = (8 * x - offsetX);
const int b = (8 * y - offsetY);
LightConeInterpolations[offsetX][offsetY][x][y] = static_cast<uint8_t>(sqrt(a * a + b * b));
const int a = ((8 * x) - offsetX);
const int b = ((8 * y) - offsetY);
LightConeInterpolations[offsetX][offsetY][x][y] = static_cast<uint8_t>(sqrt((a * a) + (b * b)));
}
}
}

22
Source/loadsave.cpp

@ -129,7 +129,7 @@ public:
&& m_size_ >= (m_cur_ + size);
}
size_t Size() const
[[nodiscard]] size_t Size() const
{
return m_size_;
}
@ -324,7 +324,7 @@ struct LevelConversionData {
item._iRequest = file.NextBool8();
file.Skip(2); // Alignment
const int32_t uniqueMappingId = file.NextLE<int32_t>();
const auto uniqueMappingId = file.NextLE<int32_t>();
if (item._iMagical == ITEM_QUALITY_UNIQUE) {
const auto findIt = UniqueItemMappingIdsToIndices.find(uniqueMappingId);
if (findIt == UniqueItemMappingIdsToIndices.end()) {
@ -355,7 +355,7 @@ struct LevelConversionData {
file.Skip(1); // Alignment
item._iStatFlag = file.NextBool32();
int32_t itemMappingId = file.NextLE<int32_t>();
auto itemMappingId = file.NextLE<int32_t>();
if (gbIsSpawn && itemMappingId < IDI_NUM_DEFAULT_ITEMS) {
itemMappingId = RemapItemIdxFromSpawn(static_cast<_item_indexes>(itemMappingId));
}
@ -366,7 +366,7 @@ struct LevelConversionData {
if (findIt == ItemMappingIdsToIndices.end()) {
return false;
}
const _item_indexes itemIndex = static_cast<_item_indexes>(findIt->second);
const auto itemIndex = static_cast<_item_indexes>(findIt->second);
item.IDidx = itemIndex;
item.dwBuff = file.NextLE<uint32_t>();
@ -523,8 +523,8 @@ void LoadPlayer(LoadHelper &file, Player &player)
player._pGold = file.NextLE<int32_t>();
player._pInfraFlag = file.NextBool32();
int32_t tempPositionX = file.NextLE<int32_t>();
int32_t tempPositionY = file.NextLE<int32_t>();
auto tempPositionX = file.NextLE<int32_t>();
auto tempPositionY = file.NextLE<int32_t>();
if (player._pmode == PM_WALK_NORTHWARDS) {
// These values are saved as offsets to remain consistent with old savefiles
tempPositionX += player.position.tile.x;
@ -2115,9 +2115,9 @@ bool IsStashSizeValid(size_t stashSize, uint32_t pages, uint32_t itemCount)
const size_t expectedSize = sizeof(uint8_t)
+ sizeof(uint32_t)
+ sizeof(uint32_t)
+ (sizeof(uint32_t) + 10 * 10 * sizeof(uint16_t)) * pages
+ ((sizeof(uint32_t) + 10 * 10 * sizeof(uint16_t)) * pages)
+ sizeof(uint32_t)
+ itemSize * itemCount
+ (itemSize * itemCount)
+ sizeof(uint32_t);
return stashSize == expectedSize;
@ -2690,7 +2690,7 @@ tl::expected<void, std::string> LoadGame(bool firstflag)
void SaveHeroItems(SaveWriter &saveWriter, Player &player)
{
const size_t itemCount = static_cast<size_t>(NUM_INVLOC) + InventoryGridCells + MaxBeltItems;
SaveHelper file(saveWriter, "heroitems", itemCount * (gbIsHellfire ? HellfireItemSaveSize : DiabloItemSaveSize) + sizeof(uint8_t));
SaveHelper file(saveWriter, "heroitems", (itemCount * (gbIsHellfire ? HellfireItemSaveSize : DiabloItemSaveSize)) + sizeof(uint8_t));
file.WriteLE<uint8_t>(gbIsHellfire ? 1 : 0);
@ -2718,9 +2718,9 @@ void SaveStash(SaveWriter &stashWriter)
sizeof(uint8_t)
+ sizeof(uint32_t)
+ sizeof(uint32_t)
+ (sizeof(uint32_t) + 10 * 10 * sizeof(uint16_t)) * Stash.stashGrids.size()
+ ((sizeof(uint32_t) + 10 * 10 * sizeof(uint16_t)) * Stash.stashGrids.size())
+ sizeof(uint32_t)
+ itemSize * Stash.stashList.size()
+ (itemSize * Stash.stashList.size())
+ sizeof(uint32_t));
file.WriteLE<uint8_t>(StashVersion);

2
Source/lua/autocomplete.cpp

@ -274,7 +274,7 @@ void GetLuaAutocompleteSuggestions(std::string_view text, size_t cursorPos, cons
for (const std::string_view partDot : SplitByChar(token, '.')) {
for (const std::string_view part : SplitByChar(partDot, ':')) {
obj = obj->as<sol::table>().get<std::optional<sol::object>>(part);
if (!obj.has_value() || !(obj->get_type() == sol::type::table || obj->get_type() == sol::type::userdata)) {
if (!obj.has_value() || (obj->get_type() != sol::type::table && obj->get_type() != sol::type::userdata)) {
return;
}
}

2
Source/lua/lua_global.cpp

@ -118,7 +118,7 @@ int LuaPrint(lua_State *state)
return 0;
}
void LuaWarn(void *userData, const char *message, int continued)
void LuaWarn(void * /*userData*/, const char *message, int continued)
{
static std::string warnBuffer;
warnBuffer.append(message);

2
Source/lua/modules/dev/items.cpp

@ -95,7 +95,7 @@ std::string DebugSpawnItem(std::string itemName)
if (i > max_iter)
return StrCat("Item not found in ", max_iter, " tries!");
const int8_t monsterLevel = dist(BetterRng) % CF_LEVEL + 1;
const int8_t monsterLevel = (dist(BetterRng) % CF_LEVEL) + 1;
_item_indexes idx = RndItemForMonsterLevel(monsterLevel);
if (IsAnyOf(idx, IDI_NONE, IDI_GOLD))
continue;

2
Source/lua/modules/dev/player/spells.cpp

@ -16,7 +16,7 @@ namespace devilution {
namespace {
std::string DebugCmdSetSpellsLevel(uint8_t level)
{
for (uint8_t i = static_cast<uint8_t>(SpellID::Firebolt); i < SpellsData.size(); i++) {
for (auto i = static_cast<uint8_t>(SpellID::Firebolt); i < SpellsData.size(); i++) {
if (GetSpellBookLevel(static_cast<SpellID>(i)) != -1) {
NetSendCmdParam2(true, CMD_CHANGE_SPELL_LEVEL, i, level);
}

4
Source/lua/modules/player.cpp

@ -47,7 +47,7 @@ void InitPlayerUserType(sol::state_view &lua)
LuaSetDocFn(playerType, "addItem", "(itemId: integer, count: integer = 1)",
"Add an item to the player's inventory",
[](Player &player, int itemId, std::optional<int> count) -> bool {
const _item_indexes itemIndex = static_cast<_item_indexes>(itemId);
const auto itemIndex = static_cast<_item_indexes>(itemId);
const int itemCount = count.value_or(1);
for (int i = 0; i < itemCount; i++) {
Item tempItem {};
@ -67,7 +67,7 @@ void InitPlayerUserType(sol::state_view &lua)
LuaSetDocFn(playerType, "removeItem", "(itemId: integer, count: integer = 1)",
"Remove an item from the player's inventory",
[](Player &player, int itemId, std::optional<int> count) -> int {
const _item_indexes targetId = static_cast<_item_indexes>(itemId);
const auto targetId = static_cast<_item_indexes>(itemId);
const int itemCount = count.value_or(1);
int removed = 0;

2
Source/lua/repl.cpp

@ -20,7 +20,7 @@ namespace {
std::optional<sol::environment> replEnv;
void LuaConsoleWarn(void *userData, const char *message, int continued)
void LuaConsoleWarn(void * /*userData*/, const char *message, int continued)
{
static std::string warnBuffer;
warnBuffer.append(message);

4
Source/minitext.cpp

@ -84,7 +84,7 @@ int CalculateTextPosition()
{
const uint32_t currTime = GetMillisecondsSinceStartup();
const int y = (currTime - ScrollStart) / qtextSpd - 260;
const int y = ((currTime - ScrollStart) / qtextSpd) - 260;
const auto textHeight = static_cast<int>(LineHeight * TextLines.size());
if (y >= textHeight)
@ -116,7 +116,7 @@ void DrawQTextContent(const Surface &out)
continue;
}
DrawString(out, line, { { sx, sy + i * LineHeight }, { 543, LineHeight } },
DrawString(out, line, { { sx, sy + (i * LineHeight) }, { 543, LineHeight } },
{ .flags = UiFlags::FontSize30 | UiFlags::ColorGold });
}
}

14
Source/missiles.cpp

@ -542,7 +542,7 @@ void CheckMissileCol(Missile &missile, DamageType damageType, int minDamage, int
if (IsMissileBlockedByTile(position)) {
Object *object = FindObjectAtPosition(position);
if (object != nullptr && object->IsBreakable()) {
BreakObjectMissile(missile.sourcePlayer(), *object);
BreakObjectMissile(*object);
}
if (!dontDeleteOnCollision)
@ -929,7 +929,7 @@ DamageRange GetDamageAmt(SpellID spell, int spellLevel)
case SpellID::FireWall:
case SpellID::LightningWall:
case SpellID::RingOfFire: {
const int min = 2 * myPlayer.getCharacterLevel() + 4;
const int min = (2 * myPlayer.getCharacterLevel()) + 4;
return { min, min + 36 };
}
case SpellID::Fireball:
@ -973,15 +973,15 @@ DamageRange GetDamageAmt(SpellID spell, int spellLevel)
case SpellID::Elemental:
/// BUGFIX: Divide min and max by 2
return {
ScaleSpellEffect(2 * myPlayer.getCharacterLevel() + 4, spellLevel),
ScaleSpellEffect(2 * myPlayer.getCharacterLevel() + 40, spellLevel)
ScaleSpellEffect((2 * myPlayer.getCharacterLevel()) + 4, spellLevel),
ScaleSpellEffect((2 * myPlayer.getCharacterLevel()) + 40, spellLevel)
};
case SpellID::ChargedBolt:
return { 1, 1 + (myPlayer._pMagic / 4) };
case SpellID::HolyBolt:
return { myPlayer.getCharacterLevel() + 9, myPlayer.getCharacterLevel() + 18 };
case SpellID::BloodStar: {
const int min = (myPlayer._pMagic / 2) + 3 * spellLevel - (myPlayer._pMagic / 8);
const int min = (myPlayer._pMagic / 2) + (3 * spellLevel) - (myPlayer._pMagic / 8);
return { min, min };
}
default:
@ -3809,8 +3809,8 @@ void ProcessWallControl(Missile &missile)
const Point leftPosition = { missile.var1, missile.var2 };
const Point rightPosition = { missile.var5, missile.var6 };
const Direction leftDirection = static_cast<Direction>(missile.var3);
const Direction rightDirection = static_cast<Direction>(missile.var4);
const auto leftDirection = static_cast<Direction>(missile.var3);
const auto rightDirection = static_cast<Direction>(missile.var4);
bool isStart = leftPosition == rightPosition;

2
Source/monster.cpp

@ -3765,7 +3765,7 @@ tl::expected<void, std::string> SetMapMonsters(const uint16_t *dunData, Point st
for (WorldTileCoord j = 0; j < size.height; j++) {
for (WorldTileCoord i = 0; i < size.width; i++) {
auto monsterId = static_cast<uint8_t>(Swap16LE(monsterLayer[j * size.width + i]));
auto monsterId = static_cast<uint8_t>(Swap16LE(monsterLayer[(j * size.width) + i]));
if (monsterId != 0) {
ASSIGN_OR_RETURN(const size_t typeIndex, AddMonsterType(MonstConvTbl[monsterId - 1], PLACE_SPECIAL));
PlaceMonster(ActiveMonsterCount++, typeIndex, startPosition + Displacement { i, j });

10
Source/monsters/validation.cpp

@ -43,7 +43,7 @@ bool IsMonsterValid(const Monster &monster)
{
const CMonster &monsterType = LevelMonsterTypes[monster.levelType];
const _monster_id monsterId = monsterType.type;
const size_t monsterIndex = static_cast<size_t>(monsterId);
const auto monsterIndex = static_cast<size_t>(monsterId);
if (monsterIndex >= MonstersData.size()) {
return false;
@ -60,7 +60,7 @@ bool IsUniqueMonsterValid(const Monster &monster)
{
assert(monster.isUnique());
const size_t uniqueMonsterIndex = static_cast<size_t>(monster.uniqueType);
const auto uniqueMonsterIndex = static_cast<size_t>(monster.uniqueType);
if (uniqueMonsterIndex >= UniqueMonstersData.size()) {
return false;
}
@ -68,11 +68,7 @@ bool IsUniqueMonsterValid(const Monster &monster)
const CMonster &monsterType = LevelMonsterTypes[monster.levelType];
const _monster_id monsterId = monsterType.type;
const UniqueMonsterData &uniqueMonsterData = UniqueMonstersData.at(uniqueMonsterIndex);
if (monsterId != uniqueMonsterData.mtype) {
return false;
}
return true;
return monsterId == uniqueMonsterData.mtype;
}
} // namespace devilution

34
Source/msg.cpp

@ -283,14 +283,14 @@ uint8_t sbLastCmd;
/**
* @brief buffer used to receive level deltas, size is the worst expected case assuming every object on a level was touched
*/
std::byte sgRecvBuf[1U /* marker byte, always 0 */
+ sizeof(uint8_t) /* level id */
+ sizeof(DLevel::item) /* items spawned during dungeon generation which have been picked up, and items dropped by a player during a game */
+ sizeof(uint8_t) /* count of object interactions which caused a state change since dungeon generation */
+ (sizeof(WorldTilePosition) + sizeof(_cmd_id)) * MAXOBJECTS /* location/action pairs for the object interactions */
+ sizeof(DLevel::monster) /* latest monster state */
+ sizeof(uint16_t) /* spawned monster count */
+ (sizeof(uint16_t) + sizeof(DSpawnedMonster)) * MaxMonsters]; /* spawned monsters */
std::byte sgRecvBuf[1U /* marker byte, always 0 */
+ sizeof(uint8_t) /* level id */
+ sizeof(DLevel::item) /* items spawned during dungeon generation which have been picked up, and items dropped by a player during a game */
+ sizeof(uint8_t) /* count of object interactions which caused a state change since dungeon generation */
+ ((sizeof(WorldTilePosition) + sizeof(_cmd_id)) * MAXOBJECTS) /* location/action pairs for the object interactions */
+ sizeof(DLevel::monster) /* latest monster state */
+ sizeof(uint16_t) /* spawned monster count */
+ ((sizeof(uint16_t) + sizeof(DSpawnedMonster)) * MaxMonsters)]; /* spawned monsters */
_cmd_id sgbRecvCmd;
ankerl::unordered_dense::map<uint8_t, LocalLevel> LocalLevels;
@ -2755,14 +2755,14 @@ void run_delta_info()
void DeltaExportData(uint8_t pnum)
{
for (const auto &[levelNum, deltaLevel] : DeltaLevels) {
const size_t bufferSize = 1U /* marker byte, always 0 */
+ sizeof(uint8_t) /* level id */
+ sizeof(deltaLevel.item) /* items spawned during dungeon generation which have been picked up, and items dropped by a player during a game */
+ sizeof(uint8_t) /* count of object interactions which caused a state change since dungeon generation */
+ (sizeof(WorldTilePosition) + sizeof(DObjectStr)) * deltaLevel.object.size() /* location/action pairs for the object interactions */
+ sizeof(deltaLevel.monster) /* latest monster state */
+ sizeof(uint16_t) /* spawned monster count */
+ (sizeof(uint16_t) + sizeof(DSpawnedMonster)) * deltaLevel.spawnedMonsters.size(); /* spawned monsters */
const size_t bufferSize = 1U /* marker byte, always 0 */
+ sizeof(uint8_t) /* level id */
+ sizeof(deltaLevel.item) /* items spawned during dungeon generation which have been picked up, and items dropped by a player during a game */
+ sizeof(uint8_t) /* count of object interactions which caused a state change since dungeon generation */
+ ((sizeof(WorldTilePosition) + sizeof(DObjectStr)) * deltaLevel.object.size()) /* location/action pairs for the object interactions */
+ sizeof(deltaLevel.monster) /* latest monster state */
+ sizeof(uint16_t) /* spawned monster count */
+ ((sizeof(uint16_t) + sizeof(DSpawnedMonster)) * deltaLevel.spawnedMonsters.size()); /* spawned monsters */
const std::unique_ptr<std::byte[]> dst { new std::byte[bufferSize] };
std::byte *dstEnd = &dst.get()[1];
@ -2882,7 +2882,7 @@ void DeltaAddItem(int ii)
if (item.bCmd != CMD_INVALID
&& static_cast<_item_indexes>(Swap16LE(item.def.wIndx)) == Items[ii].IDidx
&& Swap16LE(item.def.wCI) == Items[ii]._iCreateInfo
&& static_cast<uint32_t>(Swap32LE(item.def.dwSeed)) == Items[ii]._iSeed
&& Swap32LE(item.def.dwSeed) == Items[ii]._iSeed
&& IsAnyOf(item.bCmd, TCmdPItem::PickedUpItem, TCmdPItem::FloorItem)) {
return;
}

4
Source/multi.cpp

@ -440,7 +440,7 @@ void HandleEvents(_SNETEVENT *pEvt)
std::memcpy(&leftReasonRaw, pEvt->data, sizeof(leftReasonRaw));
leftReasonRaw = Swap32LE(leftReasonRaw);
}
leaveinfo_t leftReason = static_cast<leaveinfo_t>(leftReasonRaw);
auto leftReason = static_cast<leaveinfo_t>(leftReasonRaw);
sgdwPlayerLeftReasonTbl[playerId] = leftReason;
if (leftReason == leaveinfo_t::LEAVE_ENDING)
gbSomebodyWonGameKludge = true;
@ -730,7 +730,7 @@ void ProcessGameMessagePackets()
if (player.isOnActiveLevel() && !player._pLvlChanging) {
const uint8_t rawDir = pkt->pdir;
if (rawDir <= static_cast<uint8_t>(Direction::SouthEast)) {
const Direction newDir = static_cast<Direction>(rawDir);
const auto newDir = static_cast<Direction>(rawDir);
if (player._pdir != newDir && player._pmode == PM_STAND) {
player._pdir = newDir;
StartStand(player, newDir);

36
Source/objects.cpp

@ -298,7 +298,7 @@ void InitRndLocBigObj(int min, int max, _object_id objtype)
bool CanPlaceRandomObject(Point position, Displacement standoff)
{
return IsAreaOk(Rectangle { position - standoff,
Size { standoff.deltaX * 2 + 1, standoff.deltaY * 2 + 1 } });
Size { (standoff.deltaX * 2) + 1, (standoff.deltaY * 2) + 1 } });
}
std::optional<Point> GetRandomObjectPosition(Displacement standoff)
@ -564,16 +564,16 @@ void LoadMapObjects(const char *path, Point start, WorldTileRectangle mapRange =
WorldTileSize size = GetDunSize(dunData.get());
const int layer2Offset = 2 + size.width * size.height;
const int layer2Offset = 2 + (size.width * size.height);
// The rest of the layers are at dPiece scale
size *= static_cast<WorldTileCoord>(2);
const uint16_t *objectLayer = &dunData[layer2Offset + size.width * size.height * 2];
const uint16_t *objectLayer = &dunData[layer2Offset + (size.width * size.height * 2)];
for (WorldTileCoord j = 0; j < size.height; j++) {
for (WorldTileCoord i = 0; i < size.width; i++) {
auto objectId = static_cast<uint8_t>(Swap16LE(objectLayer[j * size.width + i]));
auto objectId = static_cast<uint8_t>(Swap16LE(objectLayer[(j * size.width) + i]));
if (objectId != 0) {
const Point mapPos = start + Displacement { i, j };
Object *mapObject = AddObject(ObjTypeConv[objectId], mapPos);
@ -824,9 +824,9 @@ void AddStoryBooks()
void AddHookedBodies(int freq)
{
for (WorldTileCoord j = 0; j < DMAXY; j++) {
const WorldTileCoord jj = 16 + j * 2;
const WorldTileCoord jj = 16 + (j * 2);
for (WorldTileCoord i = 0; i < DMAXX; i++) {
const WorldTileCoord ii = 16 + i * 2;
const WorldTileCoord ii = 16 + (i * 2);
if (dungeon[i][j] != 1 && dungeon[i][j] != 2)
continue;
if (!FlipCoin(freq))
@ -1232,7 +1232,7 @@ void AddTrap(Object &trap)
else if (leveltype == DTYPE_CRYPT)
effectiveLevel -= 8;
const int missileType = GenerateRnd(effectiveLevel / 3 + 1);
const int missileType = GenerateRnd((effectiveLevel / 3) + 1);
if (missileType == 0)
trap._oVar3 = static_cast<int8_t>(MissileID::Arrow);
if (missileType == 1)
@ -2456,9 +2456,9 @@ void OperateShrineEnchanted(DiabloGenerator &rng, Player &player)
} while ((player._pMemSpells & GetSpellBitmask(static_cast<SpellID>(spellToReduce))) == 0);
spell = 1;
for (uint8_t j = static_cast<uint8_t>(SpellID::Firebolt); j < SpellsData.size(); j++) {
for (auto j = static_cast<uint8_t>(SpellID::Firebolt); j < SpellsData.size(); j++) {
if ((player._pMemSpells & spell) != 0 && player._pSplLvl[j] < MaxSpellLevel && j != spellToReduce) {
const uint8_t newSpellLevel = static_cast<uint8_t>(player._pSplLvl[j] + 1);
const auto newSpellLevel = static_cast<uint8_t>(player._pSplLvl[j] + 1);
player._pSplLvl[j] = newSpellLevel;
NetSendCmdParam2(true, CMD_CHANGE_SPELL_LEVEL, j, newSpellLevel);
}
@ -2466,7 +2466,7 @@ void OperateShrineEnchanted(DiabloGenerator &rng, Player &player)
}
if (player._pSplLvl[spellToReduce] > 0) {
const uint8_t newSpellLevel = static_cast<uint8_t>(player._pSplLvl[spellToReduce] - 1);
const auto newSpellLevel = static_cast<uint8_t>(player._pSplLvl[spellToReduce] - 1);
player._pSplLvl[spellToReduce] = newSpellLevel;
NetSendCmdParam2(true, CMD_CHANGE_SPELL_LEVEL, spellToReduce, newSpellLevel);
}
@ -2659,7 +2659,7 @@ void OperateShrineSpiritual(DiabloGenerator &rng, Player &player)
for (int8_t &itemIndex : player.InvGrid) {
if (itemIndex == 0) {
Item &goldItem = player.InvList[player._pNumInv];
MakeGoldStack(goldItem, 5 * leveltype + rng.generateRnd(10 * leveltype));
MakeGoldStack(goldItem, (5 * leveltype) + rng.generateRnd(10 * leveltype));
player._pNumInv++;
itemIndex = player._pNumInv;
@ -2832,7 +2832,7 @@ void OperateShrineOily(Player &player, Point spawnPosition)
MissileID::FireWall,
TARGET_PLAYERS,
-1,
2 * currlevel + 2,
(2 * currlevel) + 2,
0);
InitDiabloMsg(EMSG_SHRINE_OILY);
@ -2891,7 +2891,7 @@ void OperateShrineSparkling(Player &player, Point spawnPosition)
MissileID::FlashBottom,
TARGET_PLAYERS,
-1,
3 * currlevel + 2,
(3 * currlevel) + 2,
0);
RedrawEverything();
@ -3976,16 +3976,16 @@ void SetMapObjects(const uint16_t *dunData, int startx, int starty)
WorldTileSize size = GetDunSize(dunData);
const int layer2Offset = 2 + size.width * size.height;
const int layer2Offset = 2 + (size.width * size.height);
// The rest of the layers are at dPiece scale
size *= static_cast<WorldTileCoord>(2);
const uint16_t *objectLayer = &dunData[layer2Offset + size.width * size.height * 2];
const uint16_t *objectLayer = &dunData[layer2Offset + (size.width * size.height * 2)];
for (WorldTileCoord j = 0; j < size.height; j++) {
for (WorldTileCoord i = 0; i < size.width; i++) {
auto objectId = static_cast<uint8_t>(Swap16LE(objectLayer[j * size.width + i]));
auto objectId = static_cast<uint8_t>(Swap16LE(objectLayer[(j * size.width) + i]));
if (objectId != 0) {
const ObjectData &objectData = AllObjects[ObjTypeConv[objectId]];
filesWidths[objectData.ofindex] = objectData.animWidth;
@ -3997,7 +3997,7 @@ void SetMapObjects(const uint16_t *dunData, int startx, int starty)
for (WorldTileCoord j = 0; j < size.height; j++) {
for (WorldTileCoord i = 0; i < size.width; i++) {
auto objectId = static_cast<uint8_t>(Swap16LE(objectLayer[j * size.width + i]));
auto objectId = static_cast<uint8_t>(Swap16LE(objectLayer[(j * size.width) + i]));
if (objectId != 0) {
AddObject(ObjTypeConv[objectId], { startx + 16 + i, starty + 16 + j });
}
@ -4686,7 +4686,7 @@ void SyncOpObject(Player &player, int cmd, Object &object)
}
}
void BreakObjectMissile(const Player *player, Object &object)
void BreakObjectMissile(Object &object)
{
if (object.IsCrux())
BreakCrux(object, true);

2
Source/objects.h

@ -353,7 +353,7 @@ void ObjChangeMapResync(int x1, int y1, int x2, int y2);
_item_indexes ItemMiscIdIdx(item_misc_id imiscid);
void OperateObject(Player &player, Object &object);
void SyncOpObject(Player &player, int cmd, Object &object);
void BreakObjectMissile(const Player *player, Object &object);
void BreakObjectMissile(Object &object);
void BreakObject(const Player &player, Object &object);
void DeltaSyncOpObject(Object &object);
void DeltaSyncCloseObj(Object &object);

4
Source/pack.cpp

@ -437,7 +437,7 @@ void UnPackPlayer(const PlayerPack &packed, Player &player)
bool UnPackNetItem(const Player &player, const ItemNetPack &packedItem, Item &item)
{
item = {};
const _item_indexes idx = static_cast<_item_indexes>(Swap16LE(packedItem.def.wIndx));
const auto idx = static_cast<_item_indexes>(Swap16LE(packedItem.def.wIndx));
if (idx < 0 || idx >= static_cast<_item_indexes>(AllItemsList.size()))
return true;
if (idx == IDI_EAR) {
@ -572,7 +572,7 @@ bool UnPackNetPlayer(const PlayerNetPack &packed, Player &player)
if (item.isEmpty())
continue;
const Size beltItemSize = GetInventorySize(item);
const int8_t beltItemType = static_cast<int8_t>(item._itype);
const auto beltItemType = static_cast<int8_t>(item._itype);
const bool beltItemUsable = item.isUsable();
ValidateFields(beltItemSize.width, beltItemSize.height, (beltItemSize == Size { 1, 1 }));
ValidateField(beltItemType, item._itype != ItemType::Gold);

6
Source/panels/charpanel.cpp

@ -95,8 +95,8 @@ std::pair<int, int> GetDamage()
} else {
damageMod += InspectPlayer->_pDamageMod;
}
const int mindam = InspectPlayer->_pIMinDam + InspectPlayer->_pIBonusDam * InspectPlayer->_pIMinDam / 100 + damageMod;
const int maxdam = InspectPlayer->_pIMaxDam + InspectPlayer->_pIBonusDam * InspectPlayer->_pIMaxDam / 100 + damageMod;
const int mindam = InspectPlayer->_pIMinDam + (InspectPlayer->_pIBonusDam * InspectPlayer->_pIMinDam / 100) + damageMod;
const int maxdam = InspectPlayer->_pIMaxDam + (InspectPlayer->_pIBonusDam * InspectPlayer->_pIMaxDam / 100) + damageMod;
return { mindam, maxdam };
}
@ -172,7 +172,7 @@ PanelEntry panelEntries[] = {
[]() { return StyledText { UiFlags::ColorWhite, FormatInteger(InspectPlayer->_pGold) }; } },
{ N_("Armor class"), { RightColumnLabelX, 163 }, 57, RightColumnLabelWidth,
[]() { return StyledText { GetValueColor(InspectPlayer->_pIBonusAC), StrCat(InspectPlayer->GetArmor() + InspectPlayer->getCharacterLevel() * 2) }; } },
[]() { return StyledText { GetValueColor(InspectPlayer->_pIBonusAC), StrCat(InspectPlayer->GetArmor() + (InspectPlayer->getCharacterLevel() * 2)) }; } },
{ N_("Chance To Hit"), { RightColumnLabelX, 191 }, 57, RightColumnLabelWidth,
[]() { return StyledText { GetValueColor(InspectPlayer->_pIBonusToHit), StrCat(InspectPlayer->InvBody[INVLOC_HAND_LEFT]._itype == ItemType::Bow ? InspectPlayer->GetRangedToHit() : InspectPlayer->GetMeleeToHit(), "%") }; } },
{ N_("Damage"), { RightColumnLabelX, 219 }, 57, RightColumnLabelWidth,

16
Source/panels/console.cpp

@ -149,7 +149,7 @@ void CloseConsole()
int GetConsoleLinesInnerWidth()
{
return OuterRect.size.width - 2 * TextPaddingX;
return OuterRect.size.width - (2 * TextPaddingX);
}
void PrepareForRender(ConsoleLine &consoleLine)
@ -174,7 +174,7 @@ void SendInput()
void DrawAutocompleteSuggestions(const Surface &out, const std::vector<LuaAutocompleteSuggestion> &suggestions, Point position)
{
const int maxInnerWidth = out.w() - TextPaddingX * 2;
const int maxInnerWidth = out.w() - (TextPaddingX * 2);
if (AutocompleteSuggestionsMaxWidth == -1) {
int maxWidth = 0;
for (const LuaAutocompleteSuggestion &suggestion : suggestions) {
@ -183,12 +183,12 @@ void DrawAutocompleteSuggestions(const Surface &out, const std::vector<LuaAutoco
AutocompleteSuggestionsMaxWidth = std::min(maxWidth, maxInnerWidth);
}
const int outerWidth = AutocompleteSuggestionsMaxWidth + TextPaddingX * 2;
const int outerWidth = AutocompleteSuggestionsMaxWidth + (TextPaddingX * 2);
if (position.x + outerWidth > out.w()) {
position.x = out.w() - outerWidth;
}
const int height = static_cast<int>(suggestions.size()) * LineHeight + TextPaddingYBottom + TextPaddingYTop;
const int height = (static_cast<int>(suggestions.size()) * LineHeight) + TextPaddingYBottom + TextPaddingYTop;
position.y -= height;
position.y = std::max(LineHeight, position.y);
@ -288,7 +288,7 @@ void DrawConsoleLines(const Surface &out)
// NOLINTNEXTLINE(modernize-loop-convert)
for (auto it = ConsoleLines.rbegin(), itEnd = ConsoleLines.rend(); it != itEnd; ++it) {
ConsoleLine &consoleLine = *it;
const int linesYBegin = lineYEnd - LineHeight * consoleLine.numLines;
const int linesYBegin = lineYEnd - (LineHeight * consoleLine.numLines);
if (linesYBegin > innerHeight) {
lineYEnd = linesYBegin;
continue;
@ -567,7 +567,7 @@ void DrawConsole(const Surface &out)
const std::string_view originalInputText = ConsoleInputState.value();
if (CurrentInputTextState != InputTextState::UpToDate) {
WrappedInputText = WordWrapString(StrCat(Prompt, originalInputText), OuterRect.size.width - 2 * TextPaddingX, TextFontSize, TextSpacing);
WrappedInputText = WordWrapString(StrCat(Prompt, originalInputText), OuterRect.size.width - (2 * TextPaddingX), TextFontSize, TextSpacing);
if (CurrentInputTextState == InputTextState::RestoredFromHistory) {
AutocompleteSuggestions.clear();
} else {
@ -579,14 +579,14 @@ void DrawConsole(const Surface &out)
}
const int numLines = static_cast<int>(c_count(WrappedInputText, '\n')) + 1;
InputRectHeight = std::min(OuterRect.size.height, numLines * LineHeight + TextPaddingYTop + TextPaddingYBottom);
InputRectHeight = std::min(OuterRect.size.height, (numLines * LineHeight) + TextPaddingYTop + TextPaddingYBottom);
const int inputTextHeight = InputRectHeight - (TextPaddingYTop + TextPaddingYBottom);
InputRect.position = { 0, OuterRect.size.height - InputRectHeight };
InputRect.size = { OuterRect.size.width, InputRectHeight };
const Rectangle inputTextRect {
{ InputRect.position.x + TextPaddingX, InputRect.position.y + TextPaddingYTop },
{ InputRect.size.width - 2 * TextPaddingX, inputTextHeight }
{ InputRect.size.width - (2 * TextPaddingX), inputTextHeight }
};
if (FirstRender) {

8
Source/panels/mainpanel.cpp

@ -46,7 +46,7 @@ void DrawButtonOnPanel(Point position, std::string_view text, int frame)
spacing = 1;
width = std::min<int>(GetLineWidth(text, GameFont12, spacing), (*PanelButton)[0].width());
}
RenderClxSprite(BottomBuffer->subregion(position.x + ((*PanelButton)[0].width() - width) / 2, position.y + 7, width, BottomBuffer->h() - 7), (*PanelButtonGrime)[frame], { 0, 0 });
RenderClxSprite(BottomBuffer->subregion(position.x + (((*PanelButton)[0].width() - width) / 2), position.y + 7, width, BottomBuffer->h() - 7), (*PanelButtonGrime)[frame], { 0, 0 });
DrawButtonText(*BottomBuffer, text, { position, { (*PanelButton)[0].width(), 0 } }, UiFlags::ColorButtonface, spacing);
}
@ -64,7 +64,7 @@ void RenderMainButton(const Surface &out, int buttonId, std::string_view text, i
spacing = 1;
width = std::min<int>(GetLineWidth(text, GameFont12, spacing), (*PanelButton)[0].width());
}
RenderClxSprite(out.subregion(position.x + ((*PanelButton)[0].width() - width) / 2, position.y + 9, width, out.h() - position.y - 9), (*PanelButtonDownGrime)[frame], { 0, 0 });
RenderClxSprite(out.subregion(position.x + (((*PanelButton)[0].width() - width) / 2), position.y + 9, width, out.h() - position.y - 9), (*PanelButtonDownGrime)[frame], { 0, 0 });
DrawButtonText(out, text, { position + Displacement { 0, 2 }, { out.w(), 0 } }, UiFlags::ColorButtonpushed, spacing);
}
@ -106,10 +106,10 @@ tl::expected<void, std::string> LoadMainPanel()
const std::string_view text = _("voice");
const int textWidth = GetLineWidth(text, GameFont12, 1);
for (size_t i = 0; i < NumOtherPlayers; ++i) {
const Point position { 176, static_cast<int>(GetMainPanel().size.height + 101 + 18 * i) };
const Point position { 176, static_cast<int>(GetMainPanel().size.height + 101 + (18 * i)) };
RenderClxSprite(*BottomBuffer, (*talkButton)[0], position);
const int width = std::min<int>(textWidth, (*PanelButton)[0].width());
RenderClxSprite(BottomBuffer->subregion(position.x + (talkButtonWidth - width) / 2, position.y + 6, width, 9), (*PanelButtonGrime)[1], { 0, 0 });
RenderClxSprite(BottomBuffer->subregion(position.x + ((talkButtonWidth - width) / 2), position.y + 6, width, 9), (*PanelButtonGrime)[1], { 0, 0 });
DrawButtonText(*BottomBuffer, text, { position, { talkButtonWidth, 0 } }, UiFlags::ColorButtonface);
}

4
Source/panels/spell_book.cpp

@ -140,7 +140,7 @@ void DrawSpellBook(const Surface &out)
ClxDraw(out, GetPanelPosition(UiPanels::Spell, { 0, 351 }), (*spellBookBackground)[0]);
const int buttonX = gbIsHellfire && SpellbookTab < 5
? SpellBookButtonWidthHellfire * SpellbookTab
: SpellBookButtonWidthDiablo * SpellbookTab
: (SpellBookButtonWidthDiablo * SpellbookTab)
// BUGFIX: rendering of page 3 and page 4 buttons are both off-by-one pixel (fixed).
+ (SpellbookTab == 2 || SpellbookTab == 3 ? 1 : 0);
@ -196,7 +196,7 @@ void CheckSBook()
// Spell icons/buttons are 37x38 pixels, laid out from 11,18 with a 5 pixel margin between each icon. This is close
// enough to the height of the space given to spell descriptions that we can reuse that value and subtract the
// padding from the end of the area.
const Rectangle iconArea = { GetPanelPosition(UiPanels::Spell, { 11, 18 }), Size { 37, SpellBookDescription.height * 7 - 5 } };
const Rectangle iconArea = { GetPanelPosition(UiPanels::Spell, { 11, 18 }), Size { 37, (SpellBookDescription.height * 7) - 5 } };
if (iconArea.contains(MousePosition) && !IsInspectingPlayer()) {
const SpellID sn = GetSpellFromSpellPage(SpellbookTab, (MousePosition.y - iconArea.position.y) / SpellBookDescription.height);
Player &player = *InspectPlayer;

12
Source/panels/spell_list.cpp

@ -32,7 +32,7 @@ void PrintSBookSpellType(const Surface &out, Point position, std::string_view te
DrawLargeSpellIconBorder(out, position, rectColorIndex);
// Align the spell type text with bottom of spell icon
position += Displacement { SPLICONLENGTH / 2 - GetLineWidth(text) / 2, (IsSmallFontTall() ? -19 : -15) };
position += Displacement { (SPLICONLENGTH / 2) - (GetLineWidth(text) / 2), (IsSmallFontTall() ? -19 : -15) };
// Then draw the text over the top
DrawString(out, text, position, { .flags = UiFlags::ColorWhite | UiFlags::Outlined });
@ -203,7 +203,7 @@ std::vector<SpellListItem> GetSpellListItems()
uint64_t mask;
const Point mainPanelPosition = GetMainPanel().position;
int x = mainPanelPosition.x + 12 + SPLICONLENGTH * SPLROWICONLS;
int x = mainPanelPosition.x + 12 + (SPLICONLENGTH * SPLROWICONLS);
int y = mainPanelPosition.y - 17;
for (auto i : enum_values<SpellType>()) {
@ -224,7 +224,7 @@ std::vector<SpellListItem> GetSpellListItems()
default:
continue;
}
int8_t j = static_cast<int8_t>(SpellID::Firebolt);
auto j = static_cast<int8_t>(SpellID::Firebolt);
for (uint64_t spl = 1; static_cast<size_t>(j) < SpellsData.size(); spl <<= 1, j++) {
if ((mask & spl) == 0)
continue;
@ -335,10 +335,10 @@ void DoSpeedBook()
{
SpellSelectFlag = true;
const Point mainPanelPosition = GetMainPanel().position;
int xo = mainPanelPosition.x + 12 + SPLICONLENGTH * 10;
int xo = mainPanelPosition.x + 12 + (SPLICONLENGTH * 10);
int yo = mainPanelPosition.y - 17;
int x = xo + SPLICONLENGTH / 2;
int y = yo - SPLICONLENGTH / 2;
int x = xo + (SPLICONLENGTH / 2);
int y = yo - (SPLICONLENGTH / 2);
const Player &myPlayer = *MyPlayer;

8
Source/pfile.cpp

@ -264,7 +264,7 @@ struct CompareInfo {
struct CompareCounter {
int reference;
int actual;
int max() const
[[nodiscard]] int max() const
{
return std::max(reference, actual);
}
@ -295,7 +295,7 @@ void CreateDetailDiffs(std::string_view prefix, std::string_view memoryMapFile,
return;
}
const size_t readBytes = static_cast<size_t>(SDL_GetIOSize(handle));
const auto readBytes = static_cast<size_t>(SDL_GetIOSize(handle));
const std::unique_ptr<std::byte[]> memoryMapFileData { new std::byte[readBytes] };
SDL_ReadIO(handle, memoryMapFileData.get(), readBytes);
SDL_CloseIO(handle);
@ -392,7 +392,7 @@ void CreateDetailDiffs(std::string_view prefix, std::string_view memoryMapFile,
const ParseIntResult<size_t> parsedBytes = ParseInt<size_t>(bitsAsString);
if (!parsedBytes.has_value())
app_fatal(StrCat("Failed to parse ", bitsAsString, " as size_t"));
const size_t bytes = static_cast<size_t>(parsedBytes.value() / 8);
const auto bytes = static_cast<size_t>(parsedBytes.value() / 8);
if (command == "LT") {
const int32_t valueReference = read32BitInt(compareInfoReference, false);
@ -421,7 +421,7 @@ void CreateDetailDiffs(std::string_view prefix, std::string_view memoryMapFile,
const ParseIntResult<size_t> parsedBytes = ParseInt<size_t>(bitsAsString);
if (!parsedBytes.has_value())
app_fatal(StrCat("Failed to parse ", bitsAsString, " as size_t"));
const size_t bytes = static_cast<size_t>(parsedBytes.value() / 8);
const auto bytes = static_cast<size_t>(parsedBytes.value() / 8);
for (int i = 0; i < count.max(); i++) {
count.checkIfDataExists(i, compareInfoReference, compareInfoActual);
if (!compareBytes(bytes)) {

2
Source/platform/locale.cpp

@ -198,7 +198,7 @@ std::vector<std::string> GetLocales()
do {
const size_t separatorPos = languages.find_first_of(":");
if (separatorPos != 0)
locales.emplace_back(std::string(languages.substr(0, separatorPos)));
locales.emplace_back(languages.substr(0, separatorPos));
if (separatorPos != languages.npos)
languages.remove_prefix(separatorPos + 1);

6
Source/player.cpp

@ -1073,7 +1073,7 @@ void TryDisarm(const Player &player, Object &object)
if (!object._oTrapFlag) {
return;
}
const int trapdisper = 2 * player._pDexterity - 5 * currlevel;
const int trapdisper = (2 * player._pDexterity) - (5 * currlevel);
if (GenerateRnd(100) > trapdisper) {
return;
}
@ -1455,7 +1455,7 @@ void ValidatePlayer()
}
uint64_t msk = 0;
for (size_t b = static_cast<size_t>(SpellID::Firebolt); b < SpellsData.size(); b++) {
for (auto b = static_cast<size_t>(SpellID::Firebolt); b < SpellsData.size(); b++) {
if (GetSpellBookLevel((SpellID)b) != -1) {
msk |= GetSpellBitmask(static_cast<SpellID>(b));
if (myPlayer._pSplLvl[b] > MaxSpellLevel)
@ -1736,7 +1736,7 @@ bool Player::isWalking() const
int Player::GetManaShieldDamageReduction()
{
constexpr uint8_t Max = 7;
return 24 - std::min(_pSplLvl[static_cast<int8_t>(SpellID::ManaShield)], Max) * 3;
return 24 - (std::min(_pSplLvl[static_cast<int8_t>(SpellID::ManaShield)], Max) * 3);
}
void Player::RestorePartialLife()

2
Source/portals/validation.cpp

@ -38,7 +38,7 @@ bool IsPortalDeltaValid(WorldTilePosition location, uint8_t level, uint8_t ltype
{
if (!InDungeonBounds(location))
return false;
const dungeon_type levelType = static_cast<dungeon_type>(ltype);
const auto levelType = static_cast<dungeon_type>(ltype);
if (levelType == DTYPE_NONE)
return false;
if (isOnSetLevel)

10
Source/qol/chatlog.cpp

@ -69,7 +69,7 @@ int DividerLineMarginY()
int HeaderHeight()
{
return PaddingTop + LineHeight() + 2 * BlankLineHeight() + DividerLineMarginY();
return PaddingTop + LineHeight() + (2 * BlankLineHeight()) + DividerLineMarginY();
}
int ContentPaddingY()
@ -79,12 +79,12 @@ int ContentPaddingY()
int ContentsTextHeight()
{
return PanelHeight - HeaderHeight() - DividerLineMarginY() - 2 * ContentPaddingY() - BlankLineHeight();
return PanelHeight - HeaderHeight() - DividerLineMarginY() - (2 * ContentPaddingY()) - BlankLineHeight();
}
int NumVisibleLines()
{
return (ContentsTextHeight() - 1) / LineHeight() + 1; // Ceil
return ((ContentsTextHeight() - 1) / LineHeight()) + 1; // Ceil
}
} // namespace
@ -193,9 +193,9 @@ void DrawChatLog(const Surface &out)
std::vector<DrawStringFormatArg> args;
for (auto &x : text.colors) {
args.emplace_back(DrawStringFormatArg { x.text, x.color });
args.emplace_back(x.text, x.color);
}
DrawStringWithColors(out, line, args, { { sx, contentY + i * lineHeight }, { ContentTextWidth, lineHeight } },
DrawStringWithColors(out, line, args, { { sx, contentY + (i * lineHeight) }, { ContentTextWidth, lineHeight } },
{ .flags = UiFlags::ColorWhite, .lineHeight = lineHeight });
}

2
Source/qol/floatingnumbers.cpp

@ -97,7 +97,7 @@ void DrawFloatingNumbers(const Surface &out, Point viewPosition, Displacement of
const int lineWidth = GetLineWidth(floatingNum.text, GetGameFontSize(floatingNum.style));
screenPosition.x -= lineWidth / 2;
const uint32_t timeLeft = floatingNum.time - SDL_GetTicks();
const float mul = 1 - (timeLeft / 2500.0f);
const float mul = 1 - (timeLeft / 2500.0F);
screenPosition += floatingNum.endOffset * mul;
DrawString(out, floatingNum.text, Rectangle { screenPosition, { lineWidth, 0 } },

4
Source/qol/itemlabels.cpp

@ -165,8 +165,8 @@ void DrawItemNameLabels(const Surface &out)
ItemLabel &a = labelQueue[i];
const ItemLabel &b = labelQueue[j];
if (std::abs(b.pos.y - a.pos.y) < labelHeight + BorderY) {
const int widthA = a.width + BorderX + MarginX * 2;
const int widthB = b.width + BorderX + MarginX * 2;
const int widthA = a.width + BorderX + (MarginX * 2);
const int widthB = b.width + BorderX + (MarginX * 2);
int newpos = b.pos.x;
if (b.pos.x >= a.pos.x && b.pos.x - a.pos.x < widthA) {
newpos -= widthA;

2
Source/qol/monhealthbar.cpp

@ -165,7 +165,7 @@ void DrawMonsterHealthBar(const Surface &out)
int resOffset = 5;
for (size_t i = 0; i < 3; i++) {
if ((monster.resistance & immunes[i]) != 0) {
RenderClxSprite(out, (*resistance)[i * 2 + 1], position + Displacement { resOffset, height - 6 });
RenderClxSprite(out, (*resistance)[(i * 2) + 1], position + Displacement { resOffset, height - 6 });
resOffset += (*resistance)[0].width() + 2;
} else if ((monster.resistance & resists[i]) != 0) {
RenderClxSprite(out, (*resistance)[i * 2], position + Displacement { resOffset, height - 6 });

6
Source/qol/stash.cpp

@ -538,7 +538,7 @@ void StashStruct::RemoveStashItem(StashStruct::StashCell iv)
}
// If the item at the end of stash array isn't the one we removed, we need to swap its position in the array with the removed item
const StashStruct::StashCell lastItemIndex = static_cast<StashStruct::StashCell>(stashList.size() - 1);
const auto lastItemIndex = static_cast<StashStruct::StashCell>(stashList.size() - 1);
if (lastItemIndex != iv) {
stashList[iv] = stashList[lastItemIndex];
@ -686,7 +686,7 @@ bool HandleGoldWithdrawTextInputEvent(const SDL_Event &event)
return HandleNumberInputEvent(event, *GoldWithdrawInputState);
}
bool AutoPlaceItemInStash(Player &player, const Item &item, bool persistItem)
bool AutoPlaceItemInStash(const Item &item, bool persistItem)
{
if (!IsItemAllowedInStash(item))
return false;
@ -724,7 +724,7 @@ bool AutoPlaceItemInStash(Player &player, const Item &item, bool persistItem)
continue;
if (persistItem) {
Stash.stashList.push_back(item);
const uint16_t stashIndex = static_cast<uint16_t>(Stash.stashList.size() - 1);
const auto stashIndex = static_cast<uint16_t>(Stash.stashList.size() - 1);
Stash.stashList[stashIndex].position = stashPosition + Displacement { 0, itemSize.height - 1 };
AddItemToStashGrid(pageIndex, stashPosition, stashIndex, itemSize);
Stash.dirty = true;

5
Source/qol/stash.h

@ -99,13 +99,12 @@ void CloseGoldWithdraw();
bool HandleGoldWithdrawTextInputEvent(const SDL_Event &event);
/**
* @brief Checks whether the given item can be placed on the specified player's stash.
* @brief Checks whether the given item can be placed on the stash.
* If 'persistItem' is 'True', the item is also placed in the inventory.
* @param player The player to check.
* @param item The item to be checked.
* @param persistItem Pass 'True' to actually place the item in the inventory. The default is 'False'.
* @return 'True' in case the item can be placed on the player's inventory and 'False' otherwise.
*/
bool AutoPlaceItemInStash(Player &player, const Item &item, bool persistItem);
bool AutoPlaceItemInStash(const Item &item, bool persistItem);
} // namespace devilution

10
Source/qol/xpbar.cpp

@ -39,9 +39,9 @@ OptionalOwnedClxSpriteList xpbarArt;
void DrawBar(const Surface &out, Point screenPosition, int width, const ColorGradient &gradient)
{
UnsafeDrawHorizontalLine(out, screenPosition + Displacement { 0, 1 }, width, gradient[gradient.size() * 3 / 4 - 1]);
UnsafeDrawHorizontalLine(out, screenPosition + Displacement { 0, 1 }, width, gradient[(gradient.size() * 3 / 4) - 1]);
UnsafeDrawHorizontalLine(out, screenPosition + Displacement { 0, 2 }, width, gradient[gradient.size() - 1]);
UnsafeDrawHorizontalLine(out, screenPosition + Displacement { 0, 3 }, width, gradient[gradient.size() / 2 - 1]);
UnsafeDrawHorizontalLine(out, screenPosition + Displacement { 0, 3 }, width, gradient[(gradient.size() / 2) - 1]);
}
void DrawEndCap(const Surface &out, Point point, int idx, const ColorGradient &gradient)
@ -85,7 +85,7 @@ void DrawXPBar(const Surface &out)
const Player &player = *MyPlayer;
const Rectangle &mainPanel = GetMainPanel();
const Point back = { mainPanel.position.x + mainPanel.size.width / 2 - 155, mainPanel.position.y + mainPanel.size.height - 11 };
const Point back = { mainPanel.position.x + (mainPanel.size.width / 2) - 155, mainPanel.position.y + mainPanel.size.height - 11 };
const Point position = back + Displacement { 3, 2 };
RenderClxSprite(out, (*xpbarArt)[0], back);
@ -108,7 +108,7 @@ void DrawXPBar(const Surface &out)
const uint64_t fullBar = BarWidth * prevXpDelta1 / prevXpDelta;
// Figure out how much to fill the last pixel of the XP bar, to make it gradually appear with gained XP
const uint64_t onePx = prevXpDelta / BarWidth + 1;
const uint64_t onePx = (prevXpDelta / BarWidth) + 1;
const uint64_t lastFullPx = fullBar * prevXpDelta / BarWidth;
const uint64_t fade = (prevXpDelta1 - lastFullPx) * (SilverGradient.size() - 1) / onePx;
@ -126,7 +126,7 @@ bool CheckXPBarInfo()
return false;
const Rectangle &mainPanel = GetMainPanel();
const int backX = mainPanel.position.x + mainPanel.size.width / 2 - 155;
const int backX = mainPanel.position.x + (mainPanel.size.width / 2) - 155;
const int backY = mainPanel.position.y + mainPanel.size.height - 11;
if (MousePosition.x < backX || MousePosition.x >= backX + BackWidth || MousePosition.y < backY || MousePosition.y >= backY + BackHeight)

10
Source/quests.cpp

@ -128,7 +128,7 @@ void DrawLTBanner(Point position)
for (WorldTileCoord j = 0; j < size.height; j++) {
for (WorldTileCoord i = 0; i < size.width; i++) {
auto tileId = static_cast<uint8_t>(Swap16LE(tileLayer[j * size.width + i]));
auto tileId = static_cast<uint8_t>(Swap16LE(tileLayer[(j * size.width) + i]));
if (tileId != 0) {
pdungeon[position.x + i][position.y + j] = tileId;
}
@ -594,7 +594,7 @@ void ResyncQuests()
SyncObjectAnim(Objects[ActiveObjects[i]]);
auto tren = TransVal;
TransVal = 9;
DRLG_MRectTrans({ SetPiece.position, WorldTileSize(SetPiece.size.width / 2 + 4, SetPiece.size.height / 2) });
DRLG_MRectTrans({ SetPiece.position, WorldTileSize((SetPiece.size.width / 2) + 4, SetPiece.size.height / 2) });
TransVal = tren;
if (gbIsMultiplayer && snotSpill != nullptr && snotSpill->talkMsg != TEXT_BANNER12) {
snotSpill->goal = MonsterGoal::Inquiring;
@ -608,7 +608,7 @@ void ResyncQuests()
SyncObjectAnim(Objects[ActiveObjects[i]]);
auto tren = TransVal;
TransVal = 9;
DRLG_MRectTrans({ SetPiece.position, WorldTileSize(SetPiece.size.width / 2 + 4, SetPiece.size.height / 2) });
DRLG_MRectTrans({ SetPiece.position, WorldTileSize((SetPiece.size.width / 2) + 4, SetPiece.size.height / 2) });
TransVal = tren;
if (gbIsMultiplayer && snotSpill != nullptr) {
snotSpill->goal = MonsterGoal::Normal;
@ -809,7 +809,7 @@ void StartQuestlog()
ListYOffset = 0;
FinishedQuestOffset = !twoBlocks ? 0 : LineHeight / 2;
const int overallMinHeight = EncounteredQuestCount * LineHeight + FinishedQuestOffset;
const int overallMinHeight = (EncounteredQuestCount * LineHeight) + FinishedQuestOffset;
const int space = InnerPanel.size.height;
if (EncounteredQuestCount > 0) {
@ -823,7 +823,7 @@ void StartQuestlog()
FinishedQuestOffset = std::max(4, additionalSepSpace);
}
const int overallHeight = EncounteredQuestCount * LineSpacing + FinishedQuestOffset;
const int overallHeight = (EncounteredQuestCount * LineSpacing) + FinishedQuestOffset;
ListYOffset += (space - overallHeight) / 2;
}

14
Source/stores.cpp

@ -207,8 +207,8 @@ void DrawSTextBack(const Surface &out)
void DrawSSlider(const Surface &out, int y1, int y2)
{
const Point uiPosition = GetUIRectangle().position;
int yd1 = y1 * 12 + 44 + uiPosition.y;
const int yd2 = y2 * 12 + 44 + uiPosition.y;
int yd1 = (y1 * 12) + 44 + uiPosition.y;
const int yd2 = (y2 * 12) + 44 + uiPosition.y;
if (CountdownScrollUp != -1)
ClxDraw(out, { uiPosition.x + 601, yd1 }, (*pSTextSlidCels)[11]);
else
@ -230,7 +230,7 @@ void DrawSSlider(const Surface &out, int y1, int y2)
yd3 = 1000 * (ScrollPos + ((yd3 - PreviousScrollPos) / 4)) / (CurrentItemIndex - 1) * (y2 * 12 - y1 * 12 - 24) / 1000;
else
yd3 = 0;
ClxDraw(out, { uiPosition.x + 601, (y1 + 1) * 12 + 44 + uiPosition.y + yd3 }, (*pSTextSlidCels)[12]);
ClxDraw(out, { uiPosition.x + 601, ((y1 + 1) * 12) + 44 + uiPosition.y + yd3 }, (*pSTextSlidCels)[12]);
}
void AddSLine(size_t y)
@ -355,7 +355,7 @@ void ScrollVendorStore(std::span<Item> itemData, int storeLimit, int idx, int se
if (CurrentTextLine != -1 && !TextLine[CurrentTextLine].isSelectable() && CurrentTextLine != BackButtonLine())
CurrentTextLine = NextScrollPos;
} else {
NumTextLines = std::max(static_cast<int>(storeLimit) - 4, 0);
NumTextLines = std::max(storeLimit - 4, 0);
}
}
@ -2140,8 +2140,8 @@ void PrintSString(const Surface &out, int margin, int line, std::string_view tex
? (useRed ? GetHalfSizeItemSpriteRed(cursId) : GetHalfSizeItemSprite(cursId))
: GetInvItemSprite(static_cast<int>(CURSOR_FIRSTITEM) + cursId);
const Point position {
rect.position.x + (HalfCursWidth - sprite.width()) / 2,
rect.position.y + (TextHeight() * 3 + sprite.height()) / 2
rect.position.x + ((HalfCursWidth - sprite.width()) / 2),
rect.position.y + ((TextHeight() * 3 + sprite.height()) / 2)
};
if (useHalfSize || !useRed) {
ClxDraw(out, position, sprite);
@ -2379,7 +2379,7 @@ void DrawSText(const Surface &out)
const Point uiPosition = GetUIRectangle().position;
for (int i = 0; i < NumStoreLines; i++) {
if (TextLine[i].isDivider())
DrawSLine(out, uiPosition.y + PaddingTop + TextLine[i].y + TextHeight() / 2);
DrawSLine(out, uiPosition.y + PaddingTop + TextLine[i].y + (TextHeight() / 2));
else if (TextLine[i].hasText())
PrintSString(out, TextLine[i]._sx, i, TextLine[i].text, TextLine[i].flags, TextLine[i]._sval, TextLine[i].cursId, TextLine[i].cursIndent);
}

2
Source/storm/storm_net.cpp

@ -174,7 +174,7 @@ bool SNetCreateGame(const char *pszGameName, const char *pszGamePassword, char *
std::transform(upperGameName.begin(), upperGameName.end(), upperGameName.begin(), ::toupper);
const char *privacy = GameIsPublic ? "public" : "private";
if (gameTemplateData != nullptr && gameTemplateSize >= static_cast<int>(sizeof(GameData))) {
const GameData *gameData = reinterpret_cast<const GameData *>(gameTemplateData);
const auto *gameData = reinterpret_cast<const GameData *>(gameTemplateData);
LogInfo("Created {} {} multiplayer game '{}' (player id: {}, seed: {})",
privacy, ConnectionNames[provider], upperGameName, createdPlayerId,
FormatGameSeed(gameData->gameSeed));

4
Source/storm/storm_svid.cpp

@ -188,8 +188,8 @@ void UpdatePalette()
SDL_Color *colors = SVidPalette->colors;
for (unsigned i = 0; i < NumColors; ++i) {
colors[i].r = paletteData[i * 3];
colors[i].g = paletteData[i * 3 + 1];
colors[i].b = paletteData[i * 3 + 2];
colors[i].g = paletteData[(i * 3) + 1];
colors[i].b = paletteData[(i * 3) + 2];
#ifndef USE_SDL1
colors[i].a = SDL_ALPHA_OPAQUE;
#endif

2
Source/tables/itemdat.cpp

@ -370,7 +370,7 @@ tl::expected<unique_base_item, std::string> ParseOrAddUniqueBaseItem(std::string
return tl::make_unexpected(fmt::format("Could not define new unique base item \"{}\", since the maximum number of {} has already been reached.", value, static_cast<size_t>(NUM_MAX_UITYPES)));
}
const unique_base_item newUniqueBaseItem = static_cast<unique_base_item>(newUniqueBaseItemIndex);
const auto newUniqueBaseItem = static_cast<unique_base_item>(newUniqueBaseItemIndex);
AdditionalUniqueBaseItemStringsToIndices[std::string(value)] = newUniqueBaseItem;
return newUniqueBaseItem;
}

2
Source/tables/monstdat.cpp

@ -357,7 +357,7 @@ void LoadMonstDatFromFile(DataFile &dataFile, const std::string_view filename, b
monster.spriteId = static_cast<uint16_t>(findIt - MonsterSpritePaths.begin());
} else {
monster.spriteId = static_cast<uint16_t>(MonsterSpritePaths.size());
MonsterSpritePaths.push_back(std::string(assetsSuffix));
MonsterSpritePaths.emplace_back(assetsSuffix);
}
}
reader.readString("soundSuffix", monster.soundSuffix);

14
Source/tables/playerdat.cpp

@ -36,7 +36,7 @@ class ExperienceData {
std::vector<uint32_t> levelThresholds;
public:
uint8_t getMaxLevel() const
[[nodiscard]] uint8_t getMaxLevel() const
{
return static_cast<uint8_t>(std::min<size_t>(levelThresholds.size(), std::numeric_limits<uint8_t>::max()));
}
@ -383,7 +383,7 @@ void LoadPlayerDataFiles()
SfxID GetHeroSound(HeroClass clazz, HeroSpeech speech)
{
const size_t playerClassIndex = static_cast<size_t>(clazz);
const auto playerClassIndex = static_cast<size_t>(clazz);
assert(playerClassIndex < herosounds.size());
const auto findIt = herosounds[playerClassIndex].find(speech);
if (findIt != herosounds[playerClassIndex].end()) {
@ -410,35 +410,35 @@ size_t GetNumPlayerClasses()
const PlayerData &GetPlayerDataForClass(HeroClass playerClass)
{
const size_t playerClassIndex = static_cast<size_t>(playerClass);
const auto playerClassIndex = static_cast<size_t>(playerClass);
assert(playerClassIndex < PlayersData.size());
return PlayersData[playerClassIndex];
}
const PlayerCombatData &GetPlayerCombatDataForClass(HeroClass pClass)
{
const size_t playerClassIndex = static_cast<size_t>(pClass);
const auto playerClassIndex = static_cast<size_t>(pClass);
assert(playerClassIndex < PlayersCombatData.size());
return PlayersCombatData[playerClassIndex];
}
const PlayerStartingLoadoutData &GetPlayerStartingLoadoutForClass(HeroClass pClass)
{
const size_t playerClassIndex = static_cast<size_t>(pClass);
const auto playerClassIndex = static_cast<size_t>(pClass);
assert(playerClassIndex < PlayersStartingLoadoutData.size());
return PlayersStartingLoadoutData[playerClassIndex];
}
const PlayerSpriteData &GetPlayerSpriteDataForClass(HeroClass pClass)
{
const size_t playerClassIndex = static_cast<size_t>(pClass);
const auto playerClassIndex = static_cast<size_t>(pClass);
assert(playerClassIndex < PlayersSpriteData.size());
return PlayersSpriteData[playerClassIndex];
}
const PlayerAnimData &GetPlayerAnimDataForClass(HeroClass pClass)
{
const size_t playerClassIndex = static_cast<size_t>(pClass);
const auto playerClassIndex = static_cast<size_t>(pClass);
assert(playerClassIndex < PlayersAnimData.size());
return PlayersAnimData[playerClassIndex];
}

2
Source/tmsg.cpp

@ -54,7 +54,7 @@ uint8_t tmsg_get(std::unique_ptr<std::byte[]> *msg)
void tmsg_add(const std::byte *msg, uint8_t len)
{
const uint32_t time = SDL_GetTicks() + gnTickDelay * 10;
const uint32_t time = SDL_GetTicks() + (gnTickDelay * 10);
TimedMsgList.emplace_back(time, msg, len);
}

8
Source/utils/cel_to_clx.cpp

@ -48,7 +48,7 @@ OwnedClxSpriteListOrSheet CelToClx(const uint8_t *data, size_t size, PointerOrVa
cl2Data.reserve(size + 4445);
// If it is a number of frames, then the last frame offset will be equal to the size of the file.
if (LoadLE32(&data[maybeNumFrames * 4 + 4]) != size) {
if (LoadLE32(&data[(maybeNumFrames * 4) + 4]) != size) {
// maybeNumFrames is the address of the first group, right after
// the list of group offsets.
numGroups = maybeNumFrames / 4;
@ -68,14 +68,14 @@ OwnedClxSpriteListOrSheet CelToClx(const uint8_t *data, size_t size, PointerOrVa
// CL2 header: frame count, frame offset for each frame, file size
const size_t cl2DataOffset = cl2Data.size();
cl2Data.resize(cl2Data.size() + 4 * (2 + static_cast<size_t>(numFrames)));
cl2Data.resize(cl2Data.size() + (4 * (2 + static_cast<size_t>(numFrames))));
WriteLE32(&cl2Data[cl2DataOffset], numFrames);
const uint8_t *srcEnd = &data[LoadLE32(&data[4])];
for (size_t frame = 1; frame <= numFrames; ++frame) {
const uint8_t *src = srcEnd;
srcEnd = &data[LoadLE32(&data[4 * (frame + 1)])];
WriteLE32(&cl2Data[cl2DataOffset + 4 * frame], static_cast<uint32_t>(cl2Data.size() - cl2DataOffset));
WriteLE32(&cl2Data[cl2DataOffset + (4 * frame)], static_cast<uint32_t>(cl2Data.size() - cl2DataOffset));
// Skip CEL frame header if there is one.
constexpr size_t CelFrameHeaderSize = 10;
@ -114,7 +114,7 @@ OwnedClxSpriteListOrSheet CelToClx(const uint8_t *data, size_t size, PointerOrVa
AppendClxTransparentRun(transparentRunWidth, cl2Data);
}
WriteLE32(&cl2Data[cl2DataOffset + 4 * (1 + static_cast<size_t>(numFrames))], static_cast<uint32_t>(cl2Data.size() - cl2DataOffset));
WriteLE32(&cl2Data[cl2DataOffset + (4 * (1 + static_cast<size_t>(numFrames)))], static_cast<uint32_t>(cl2Data.size() - cl2DataOffset));
data = srcEnd;
}

8
Source/utils/cl2_to_clx.cpp

@ -20,7 +20,7 @@ uint16_t Cl2ToClx(const uint8_t *data, size_t size,
const uint8_t *groupBegin = data;
// If it is a number of frames, then the last frame offset will be equal to the size of the file.
if (LoadLE32(&data[maybeNumFrames * 4 + 4]) != size) {
if (LoadLE32(&data[(maybeNumFrames * 4) + 4]) != size) {
// maybeNumFrames is the address of the first group, right after
// the list of group offsets.
numGroups = maybeNumFrames / 4;
@ -43,12 +43,12 @@ uint16_t Cl2ToClx(const uint8_t *data, size_t size,
// CLX header: frame count, frame offset for each frame, file size
const size_t clxDataOffset = clxData.size();
clxData.resize(clxData.size() + 4 * (2 + static_cast<size_t>(numFrames)));
clxData.resize(clxData.size() + (4 * (2 + static_cast<size_t>(numFrames))));
WriteLE32(&clxData[clxDataOffset], numFrames);
const uint8_t *frameEnd = &groupBegin[LoadLE32(&groupBegin[4])];
for (size_t frame = 1; frame <= numFrames; ++frame) {
WriteLE32(&clxData[clxDataOffset + 4 * frame],
WriteLE32(&clxData[clxDataOffset + (4 * frame)],
static_cast<uint32_t>(clxData.size() - clxDataOffset));
const uint8_t *frameBegin = frameEnd;
@ -106,7 +106,7 @@ uint16_t Cl2ToClx(const uint8_t *data, size_t size,
WriteLE16(&clxData[frameHeaderPos + 4], static_cast<uint16_t>(frameHeight));
}
WriteLE32(&clxData[clxDataOffset + 4 * (1 + static_cast<size_t>(numFrames))], static_cast<uint32_t>(clxData.size() - clxDataOffset));
WriteLE32(&clxData[clxDataOffset + (4 * (1 + static_cast<size_t>(numFrames)))], static_cast<uint32_t>(clxData.size() - clxDataOffset));
}
return numGroups == 1 ? 0 : numGroups;
}

12
Source/utils/display.cpp

@ -216,9 +216,9 @@ void UpdateAvailableResolutions()
if (mode.w < mode.h) {
std::swap(mode.w, mode.h);
}
sizes.emplace_back(Size {
sizes.emplace_back(
static_cast<int>(mode.w * scaleFactor),
static_cast<int>(mode.h * scaleFactor) });
static_cast<int>(mode.h * scaleFactor));
}
supportsAnyResolution = *GetOptions().Graphics.upscale;
#else
@ -246,9 +246,9 @@ void UpdateAvailableResolutions()
for (const int commonHeight : commonHeights) {
if (commonHeight > height)
break;
sizes.emplace_back(Size { commonHeight * 4 / 3, commonHeight });
sizes.emplace_back(commonHeight * 4 / 3, commonHeight);
if (commonHeight * width % height == 0)
sizes.emplace_back(Size { commonHeight * width / height, commonHeight });
sizes.emplace_back(commonHeight * width / height, commonHeight);
}
}
@ -257,10 +257,10 @@ void UpdateAvailableResolutions()
// Ensures that the ini specified resolution is present in resolution list even if it doesn't match a monitor resolution (for example if played in window mode)
sizes.push_back(configuredSize);
// Ensures that the platform's preferred default resolution is always present
sizes.emplace_back(Size { DEFAULT_WIDTH, DEFAULT_HEIGHT });
sizes.emplace_back(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// Ensures that the vanilla Diablo resolution is present on systems that would support it
if (supportsAnyResolution)
sizes.emplace_back(Size { 640, 480 });
sizes.emplace_back(640, 480);
#ifndef USE_SDL1
if (*graphicsOptions.fitToScreen) {

4
Source/utils/format_int.cpp

@ -26,7 +26,7 @@ std::string FormatInteger(int n)
}
const std::string_view separator = _(/* TRANSLATORS: Thousands separator */ ",");
out.reserve(len + separator.size() * (numLen - 1) / GroupSize);
out.reserve(len + (separator.size() * (numLen - 1) / GroupSize));
if (n < 0) {
out += '-';
++begin;
@ -62,7 +62,7 @@ std::string FormatInteger(uint32_t n)
}
const std::string_view separator = _(/* TRANSLATORS: Thousands separator */ ",");
out.reserve(len + separator.size() * (numLen - 1) / GroupSize);
out.reserve(len + (separator.size() * (numLen - 1) / GroupSize));
size_t mlen = numLen % GroupSize;
if (mlen == 0)

2
Source/utils/push_aulib_decoder.cpp

@ -78,7 +78,7 @@ int PushAulibDecoder::doDecoding(float buf[], int len, bool &callAgain)
const auto lock = std::lock_guard(queue_mutex_);
AudioQueueItem *item;
while ((item = Next()) != nullptr) {
if (static_cast<unsigned>(remaining) <= item->len) {
if (remaining <= item->len) {
WriteFloats(*item, buf, remaining);
item->pos += remaining;
item->len -= remaining;

46
Source/utils/sdl2_to_1_2_backports.cpp

@ -229,7 +229,7 @@ int SDL_SoftStretch(SDL_Surface *src, const SDL_Rect *srcrect,
int pos, inc;
int dst_maxrow;
int src_row, dst_row;
Uint8 *srcp = NULL;
Uint8 *srcp = nullptr;
Uint8 *dstp;
SDL_Rect full_src;
SDL_Rect full_dst;
@ -357,7 +357,7 @@ int SDL_BlitScaled(SDL_Surface *src, SDL_Rect *srcrect,
return -1;
}
if (NULL == srcrect) {
if (nullptr == srcrect) {
src_w = src->w;
src_h = src->h;
} else {
@ -365,7 +365,7 @@ int SDL_BlitScaled(SDL_Surface *src, SDL_Rect *srcrect,
src_h = srcrect->h;
}
if (NULL == dstrect) {
if (nullptr == dstrect) {
dst_w = dst->w;
dst_h = dst->h;
} else {
@ -381,7 +381,7 @@ int SDL_BlitScaled(SDL_Surface *src, SDL_Rect *srcrect,
scaling_w = (float)dst_w / src_w;
scaling_h = (float)dst_h / src_h;
if (NULL == dstrect) {
if (nullptr == dstrect) {
dst_x0 = 0;
dst_y0 = 0;
dst_x1 = static_cast<float>(dst_w - 1);
@ -393,7 +393,7 @@ int SDL_BlitScaled(SDL_Surface *src, SDL_Rect *srcrect,
dst_y1 = dst_y0 + dst_h - 1;
}
if (NULL == srcrect) {
if (nullptr == srcrect) {
src_x0 = 0;
src_y0 = 0;
src_x1 = static_cast<float>(src_w - 1);
@ -706,13 +706,13 @@ namespace {
char *readSymLink(const char *path)
{
// From sdl2-2.0.9/src/filesystem/unix/SDL_sysfilesystem.c
char *retval = NULL;
char *retval = nullptr;
ssize_t len = 64;
ssize_t rc = -1;
while (1) {
char *ptr = (char *)SDL_realloc(retval, (size_t)len);
if (ptr == NULL) {
if (ptr == nullptr) {
SDL_OutOfMemory();
break;
}
@ -731,7 +731,7 @@ char *readSymLink(const char *path)
}
SDL_free(retval);
return NULL;
return nullptr;
}
#endif
} // namespace
@ -740,11 +740,11 @@ extern "C" char *SDL_GetBasePath()
{
// From sdl2-2.0.9/src/filesystem/unix/SDL_sysfilesystem.c
char *retval = NULL;
char *retval = nullptr;
#if defined(WINVER) && WINVER <= 0x0500 && (!defined(_WIN32_WINNT) || _WIN32_WINNT == 0)
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName(NULL, buffer, MAX_PATH);
GetModuleFileName(nullptr, buffer, MAX_PATH);
size_t len = std::string_view(buffer).size();
while (len > 0) {
if (buffer[len - 1] == '\\') {
@ -812,10 +812,10 @@ extern "C" char *SDL_GetBasePath()
#elif defined(__NETBSD__)
retval = readSymLink("/proc/curproc/exe");
#elif defined(__QNXNTO__)
retval = SDL_LoadFile("/proc/self/exefile", NULL);
retval = SDL_LoadFile("/proc/self/exefile", nullptr);
#else
retval = readSymLink("/proc/self/exe"); /* linux. */
if (retval == NULL) {
if (retval == nullptr) {
/* older kernels don't have /proc/self ... try PID version... */
char path[64];
const int rc = (int)SDL_snprintf(path, sizeof(path),
@ -831,20 +831,20 @@ extern "C" char *SDL_GetBasePath()
/* If we had access to argv[0] here, we could check it for a path,
or troll through $PATH looking for it, too. */
if (retval != NULL) { /* chop off filename. */
if (retval != nullptr) { /* chop off filename. */
char *ptr = SDL_strrchr(retval, '/');
if (ptr != NULL) {
if (ptr != nullptr) {
*(ptr + 1) = '\0';
} else { /* shouldn't happen, but just in case... */
SDL_free(retval);
retval = NULL;
retval = nullptr;
}
}
if (retval != NULL) {
if (retval != nullptr) {
/* try to shrink buffer... */
char *ptr = (char *)SDL_realloc(retval, strlen(retval) + 1);
if (ptr != NULL)
if (ptr != nullptr)
retval = ptr; /* oh well if it failed. */
}
#endif
@ -869,8 +869,8 @@ extern "C" char *SDL_GetPrefPath(const char *org, const char *app)
#else
const char *envr = SDL_getenv("XDG_DATA_HOME");
const char *append;
char *retval = NULL;
char *ptr = NULL;
char *retval = nullptr;
char *ptr = nullptr;
size_t len = 0;
#if defined(__3DS__)
@ -883,7 +883,7 @@ extern "C" char *SDL_GetPrefPath(const char *org, const char *app)
if (!app) {
SDL_InvalidParamError("app");
return NULL;
return nullptr;
}
if (!org) {
org = "";
@ -895,7 +895,7 @@ extern "C" char *SDL_GetPrefPath(const char *org, const char *app)
if (!envr) {
/* we could take heroic measures with /etc/passwd, but oh well. */
SDL_SetError("neither XDG_DATA_HOME nor HOME environment is set");
return NULL;
return nullptr;
}
#if defined(__unix__) || defined(__unix)
append = "/.local/share/";
@ -914,7 +914,7 @@ extern "C" char *SDL_GetPrefPath(const char *org, const char *app)
retval = (char *)SDL_malloc(len);
if (!retval) {
SDL_OutOfMemory();
return NULL;
return nullptr;
}
if (*org) {
@ -935,7 +935,7 @@ extern "C" char *SDL_GetPrefPath(const char *org, const char *app)
error:
SDL_SetError("Couldn't create directory '%s': '%s'", retval, strerror(errno));
SDL_free(retval);
return NULL;
return nullptr;
}
// Append trailing /

4
Source/utils/sdl_bilinear_scale.cpp

@ -70,7 +70,7 @@ uint8_t MixColorsWithAlpha(uint8_t first, uint8_t firstAlpha,
// so we do the rounding-up integer division for each term (instead of a truncating one):
//
// (a + (b - 1)) / b
return ToInt((secondWithAlpha - firstWithAlpha) * ((ratio + (mixedAlpha - 1)) / mixedAlpha)) + (firstWithAlpha + (mixedAlpha - 1)) / mixedAlpha;
return ToInt((secondWithAlpha - firstWithAlpha) * ((ratio + (mixedAlpha - 1)) / mixedAlpha)) + ((firstWithAlpha + (mixedAlpha - 1)) / mixedAlpha);
}
} // namespace
@ -80,7 +80,7 @@ void BilinearScale32(SDL_Surface *src, SDL_Surface *dst)
const std::unique_ptr<int[]> mixXs = CreateMixFactors(src->w, dst->w);
const std::unique_ptr<int[]> mixYs = CreateMixFactors(src->h, dst->h);
const unsigned dgap = dst->pitch - dst->w * 4;
const unsigned dgap = dst->pitch - (dst->w * 4);
auto *srcPixels = static_cast<uint8_t *>(src->pixels);
auto *dstPixels = static_cast<uint8_t *>(dst->pixels);

72
test/stash_test.cpp

@ -89,7 +89,7 @@ protected:
for (int y = 0; y < 10; y++) {
Item item = MakeSmallItem();
Stash.SetPage(page);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true))
ASSERT_TRUE(AutoPlaceItemInStash(item, true))
<< "Failed to place item at logical position on page " << page;
}
}
@ -104,7 +104,7 @@ TEST_F(StashTest, PlaceItem_EmptyStash)
{
Item item = MakeSmallItem();
bool placed = AutoPlaceItemInStash(*MyPlayer, item, true);
bool placed = AutoPlaceItemInStash(item, true);
EXPECT_TRUE(placed);
EXPECT_FALSE(Stash.stashList.empty());
@ -116,7 +116,7 @@ TEST_F(StashTest, PlaceItem_DryRunDoesNotMutate)
{
Item item = MakeSmallItem();
bool canPlace = AutoPlaceItemInStash(*MyPlayer, item, false);
bool canPlace = AutoPlaceItemInStash(item, false);
EXPECT_TRUE(canPlace);
EXPECT_TRUE(Stash.stashList.empty()) << "Dry-run should not add item to stashList";
@ -127,7 +127,7 @@ TEST_F(StashTest, PlaceItem_GridCellOccupied)
{
Item item = MakeSmallItem();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
// The item should occupy at least one cell on the current page.
const auto &grid = Stash.stashGrids[Stash.GetPage()];
@ -140,9 +140,9 @@ TEST_F(StashTest, PlaceItem_MultipleItemsOnSamePage)
Item item2 = MakeSmallItem();
Item item3 = MakeSword();
EXPECT_TRUE(AutoPlaceItemInStash(*MyPlayer, item1, true));
EXPECT_TRUE(AutoPlaceItemInStash(*MyPlayer, item2, true));
EXPECT_TRUE(AutoPlaceItemInStash(*MyPlayer, item3, true));
EXPECT_TRUE(AutoPlaceItemInStash(item1, true));
EXPECT_TRUE(AutoPlaceItemInStash(item2, true));
EXPECT_TRUE(AutoPlaceItemInStash(item3, true));
EXPECT_EQ(Stash.stashList.size(), 3u);
}
@ -159,7 +159,7 @@ TEST_F(StashTest, PlaceItem_FullPageOverflowsToNextPage)
// Page 0 should be completely full now. Placing another item should go to page 1.
Item overflow = MakeSmallItem();
Stash.SetPage(0); // Reset to page 0 so AutoPlace starts searching from page 0.
EXPECT_TRUE(AutoPlaceItemInStash(*MyPlayer, overflow, true));
EXPECT_TRUE(AutoPlaceItemInStash(overflow, true));
EXPECT_EQ(Stash.stashList.size(), itemsAfterPage0 + 1);
@ -178,7 +178,7 @@ TEST_F(StashTest, PlaceItem_SwordOccupiesCorrectArea)
Item sword = MakeSword();
const Size swordSize = GetInventorySize(sword);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, sword, true));
ASSERT_TRUE(AutoPlaceItemInStash(sword, true));
const auto &grid = Stash.stashGrids[Stash.GetPage()];
int occupiedCells = CountOccupiedCells(grid);
@ -194,7 +194,7 @@ TEST_F(StashTest, PlaceGold_AddsToStashGold)
{
Item gold = MakeGold(5000);
EXPECT_TRUE(AutoPlaceItemInStash(*MyPlayer, gold, true));
EXPECT_TRUE(AutoPlaceItemInStash(gold, true));
EXPECT_EQ(Stash.gold, 5000);
EXPECT_TRUE(Stash.stashList.empty()) << "Gold should not be added to stashList";
@ -205,7 +205,7 @@ TEST_F(StashTest, PlaceGold_DryRunDoesNotMutate)
{
Item gold = MakeGold(3000);
EXPECT_TRUE(AutoPlaceItemInStash(*MyPlayer, gold, false));
EXPECT_TRUE(AutoPlaceItemInStash(gold, false));
EXPECT_EQ(Stash.gold, 0) << "Dry-run should not change stash gold";
EXPECT_FALSE(Stash.dirty);
@ -216,8 +216,8 @@ TEST_F(StashTest, PlaceGold_AccumulatesMultipleDeposits)
Item gold1 = MakeGold(1000);
Item gold2 = MakeGold(2500);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, gold1, true));
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, gold2, true));
ASSERT_TRUE(AutoPlaceItemInStash(gold1, true));
ASSERT_TRUE(AutoPlaceItemInStash(gold2, true));
EXPECT_EQ(Stash.gold, 3500);
}
@ -228,7 +228,7 @@ TEST_F(StashTest, PlaceGold_RejectsOverflow)
Item gold = MakeGold(200);
EXPECT_FALSE(AutoPlaceItemInStash(*MyPlayer, gold, true))
EXPECT_FALSE(AutoPlaceItemInStash(gold, true))
<< "Should reject gold that would cause integer overflow";
EXPECT_EQ(Stash.gold, std::numeric_limits<int>::max() - 100)
<< "Stash gold should be unchanged after rejected deposit";
@ -241,7 +241,7 @@ TEST_F(StashTest, PlaceGold_RejectsOverflow)
TEST_F(StashTest, RemoveItem_ClearsGridAndList)
{
Item item = MakeSmallItem();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
ASSERT_EQ(Stash.stashList.size(), 1u);
Stash.dirty = false;
@ -260,8 +260,8 @@ TEST_F(StashTest, RemoveItem_LastItemSwap)
Item item1 = MakeSmallItem();
Item item2 = MakeSword();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item1, true));
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item2, true));
ASSERT_TRUE(AutoPlaceItemInStash(item1, true));
ASSERT_TRUE(AutoPlaceItemInStash(item2, true));
ASSERT_EQ(Stash.stashList.size(), 2u);
// Remember the type of the second item.
@ -295,9 +295,9 @@ TEST_F(StashTest, RemoveItem_MiddleOfThree)
Item item2 = MakeSmallItem();
Item item3 = MakeSmallItem();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item1, true));
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item2, true));
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item3, true));
ASSERT_TRUE(AutoPlaceItemInStash(item1, true));
ASSERT_TRUE(AutoPlaceItemInStash(item2, true));
ASSERT_TRUE(AutoPlaceItemInStash(item3, true));
ASSERT_EQ(Stash.stashList.size(), 3u);
Stash.RemoveStashItem(1);
@ -423,7 +423,7 @@ TEST_F(StashTest, GetItemIdAtPosition_OccupiedCell)
{
Item item = MakeSmallItem();
Stash.SetPage(0);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
// The first item should be placed at (0,0) in an empty stash.
StashStruct::StashCell id = Stash.GetItemIdAtPosition({ 0, 0 });
@ -435,7 +435,7 @@ TEST_F(StashTest, IsItemAtPosition_OccupiedCell)
{
Item item = MakeSmallItem();
Stash.SetPage(0);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
EXPECT_TRUE(Stash.IsItemAtPosition({ 0, 0 }));
}
@ -451,7 +451,7 @@ TEST_F(StashTest, TransferToInventory_Success)
Item item = MakeSmallItem();
Stash.SetPage(0);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
ASSERT_EQ(Stash.stashList.size(), 1u);
TransferItemToInventory(*MyPlayer, 0);
@ -493,7 +493,7 @@ TEST_F(StashTest, TransferToInventory_InventoryFull)
Item item = MakeSmallItem();
Stash.SetPage(0);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
ASSERT_EQ(Stash.stashList.size(), 1u);
TransferItemToInventory(*MyPlayer, 0);
@ -546,7 +546,7 @@ TEST_F(StashTest, DirtyFlag_SetOnPlaceItem)
Stash.dirty = false;
Item item = MakeSmallItem();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
EXPECT_TRUE(Stash.dirty);
}
@ -556,7 +556,7 @@ TEST_F(StashTest, DirtyFlag_SetOnPlaceGold)
Stash.dirty = false;
Item gold = MakeGold(100);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, gold, true));
ASSERT_TRUE(AutoPlaceItemInStash(gold, true));
EXPECT_TRUE(Stash.dirty);
}
@ -564,7 +564,7 @@ TEST_F(StashTest, DirtyFlag_SetOnPlaceGold)
TEST_F(StashTest, DirtyFlag_SetOnRemoveItem)
{
Item item = MakeSmallItem();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
Stash.dirty = false;
Stash.RemoveStashItem(0);
@ -586,7 +586,7 @@ TEST_F(StashTest, DirtyFlag_NotSetOnDryRun)
Stash.dirty = false;
Item item = MakeSmallItem();
AutoPlaceItemInStash(*MyPlayer, item, false);
AutoPlaceItemInStash(item, false);
EXPECT_FALSE(Stash.dirty);
}
@ -620,7 +620,7 @@ TEST_F(StashTest, PlaceItem_CurrentPagePreferred)
Stash.dirty = false;
Item item = MakeSmallItem();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
EXPECT_TRUE(Stash.stashGrids.count(5) > 0)
<< "Item should be placed on the current page (5)";
@ -636,7 +636,7 @@ TEST_F(StashTest, PlaceItem_WrapsAroundPages)
Item overflow = MakeSmallItem();
Stash.SetPage(99); // Reset to page 99 so search starts there.
EXPECT_TRUE(AutoPlaceItemInStash(*MyPlayer, overflow, true));
EXPECT_TRUE(AutoPlaceItemInStash(overflow, true));
// The item should have been placed on page 0 (wrapped around).
EXPECT_TRUE(Stash.stashGrids.count(0) > 0)
@ -651,8 +651,8 @@ TEST_F(StashTest, MultipleItemTypes_CoexistOnSamePage)
Item potion = MakeSmallItem();
Item sword = MakeSword();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, potion, true));
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, sword, true));
ASSERT_TRUE(AutoPlaceItemInStash(potion, true));
ASSERT_TRUE(AutoPlaceItemInStash(sword, true));
EXPECT_EQ(Stash.stashList.size(), 2u);
@ -668,14 +668,14 @@ TEST_F(StashTest, RemoveItem_ThenPlaceNew)
// Place an item, remove it, then place a new one. The stash should
// reuse the slot correctly.
Item item1 = MakeSmallItem();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item1, true));
ASSERT_TRUE(AutoPlaceItemInStash(item1, true));
ASSERT_EQ(Stash.stashList.size(), 1u);
Stash.RemoveStashItem(0);
ASSERT_TRUE(Stash.stashList.empty());
Item item2 = MakeSword();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item2, true));
ASSERT_TRUE(AutoPlaceItemInStash(item2, true));
EXPECT_EQ(Stash.stashList.size(), 1u);
}
@ -685,10 +685,10 @@ TEST_F(StashTest, GoldStorageIndependentOfItems)
Stash.SetPage(0);
Item gold = MakeGold(5000);
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, gold, true));
ASSERT_TRUE(AutoPlaceItemInStash(gold, true));
Item item = MakeSmallItem();
ASSERT_TRUE(AutoPlaceItemInStash(*MyPlayer, item, true));
ASSERT_TRUE(AutoPlaceItemInStash(item, true));
EXPECT_EQ(Stash.gold, 5000) << "Gold should be tracked separately";
EXPECT_EQ(Stash.stashList.size(), 1u) << "Only the non-gold item should be in stashList";

Loading…
Cancel
Save