Reduce the scope of variables

This commit is contained in:
Chris Thrasher 2024-10-12 10:39:19 -06:00 committed by Vittorio Romeo
parent 56f9ee2b40
commit cabc36b8a4
21 changed files with 64 additions and 125 deletions

View File

@ -240,11 +240,10 @@ sf::Vector2f computeNormal(float left, float right, float bottom, float top)
/// coordinates.
///
////////////////////////////////////////////////////////////
const auto scalingFactors = sf::Vector2f(windowSize).componentWiseDiv(sf::Vector2f(resolution));
sf::Vertex computeVertex(sf::Vector2u position)
{
sf::Vertex vertex;
static const auto scalingFactors = sf::Vector2f(windowSize).componentWiseDiv(sf::Vector2f(resolution));
sf::Vertex vertex;
vertex.position = sf::Vector2f(position).componentWiseMul(scalingFactors);
vertex.color = getTerrainColor(getElevation(position), getMoisture(position));
vertex.texCoords = computeNormal(getElevation(position - sf::Vector2u(1, 0)),

View File

@ -398,7 +398,7 @@ int main()
std::optional edgeEffect = tryLoadEdge();
std::optional geometryEffect = tryLoadGeometry();
const auto optionalToPtr = [&](auto& effect) -> Effect* { return effect.has_value() ? &*effect : nullptr; };
const auto optionalToPtr = [](auto& effect) -> Effect* { return effect.has_value() ? &*effect : nullptr; };
const std::array<Effect*, 5> effects{optionalToPtr(pixelateEffect),
optionalToPtr(waveBlurEffect),

View File

@ -462,9 +462,9 @@ std::optional<ma_device_id> AudioDevice::getSelectedDeviceId() const
if (!deviceName)
deviceName = PlaybackDevice::getDefaultDevice();
auto iter = std::find_if(devices.begin(),
devices.end(),
[&](const auto& device) { return device.name == deviceName; });
const auto iter = std::find_if(devices.begin(),
devices.end(),
[&deviceName](const auto& device) { return device.name == deviceName; });
if (iter != devices.end())
return iter->id;

View File

@ -66,8 +66,8 @@ bool setDevice(const std::string& name)
{
// Perform a sanity check to make sure the user isn't passing us a non-existent device name
const auto devices = priv::AudioDevice::getAvailableDevices();
if (auto iter = std::find_if(devices.begin(), devices.end(), [&](const auto& device) { return device.name == name; });
iter == devices.end())
if (std::find_if(devices.begin(), devices.end(), [&name](const auto& device) { return device.name == name; }) ==
devices.end())
return false;
return priv::AudioDevice::setDevice(name);

View File

@ -213,12 +213,10 @@ bool Image::loadFromFile(const std::filesystem::path& filename)
m_pixels.clear();
// Load the image and get a pointer to the pixels in memory
int width = 0;
int height = 0;
int channels = 0;
const auto ptr = StbPtr(stbi_load(filename.string().c_str(), &width, &height, &channels, STBI_rgb_alpha));
if (ptr)
int width = 0;
int height = 0;
int channels = 0;
if (const auto ptr = StbPtr(stbi_load(filename.string().c_str(), &width, &height, &channels, STBI_rgb_alpha)))
{
// Assign the image properties
m_size = Vector2u(Vector2i(width, height));
@ -251,10 +249,8 @@ bool Image::loadFromMemory(const void* data, std::size_t size)
int height = 0;
int channels = 0;
const auto* buffer = static_cast<const unsigned char*>(data);
const auto ptr = StbPtr(
stbi_load_from_memory(buffer, static_cast<int>(size), &width, &height, &channels, STBI_rgb_alpha));
if (ptr)
if (const auto ptr = StbPtr(
stbi_load_from_memory(buffer, static_cast<int>(size), &width, &height, &channels, STBI_rgb_alpha)))
{
// Assign the image properties
m_size = Vector2u(Vector2i(width, height));
@ -296,12 +292,10 @@ bool Image::loadFromStream(InputStream& stream)
callbacks.eof = eof;
// Load the image and get a pointer to the pixels in memory
int width = 0;
int height = 0;
int channels = 0;
const auto ptr = StbPtr(stbi_load_from_callbacks(&callbacks, &stream, &width, &height, &channels, STBI_rgb_alpha));
if (ptr)
int width = 0;
int height = 0;
int channels = 0;
if (const auto ptr = StbPtr(stbi_load_from_callbacks(&callbacks, &stream, &width, &height, &channels, STBI_rgb_alpha)))
{
// Assign the image properties
m_size = Vector2u(Vector2i(width, height));

View File

@ -82,8 +82,7 @@ std::size_t getMaxTextureUnits()
// Read the contents of a file into an array of char
bool getFileContents(const std::filesystem::path& filename, std::vector<char>& buffer)
{
std::ifstream file(filename, std::ios_base::binary);
if (file)
if (auto file = std::ifstream(filename, std::ios_base::binary))
{
file.seekg(0, std::ios_base::end);
const std::ifstream::pos_type size = file.tellg();

View File

@ -225,10 +225,8 @@ std::uint32_t findCrtcForConnector(const sf::priv::Drm& drm, const drmModeRes& r
{
for (int i = 0; i < connector.count_encoders; ++i)
{
const std::uint32_t encoderId = connector.encoders[i];
const drmModeEncoderPtr encoder = drmModeGetEncoder(drm.fileDescriptor, encoderId);
if (encoder)
const std::uint32_t encoderId = connector.encoders[i];
if (auto* encoder = drmModeGetEncoder(drm.fileDescriptor, encoderId))
{
const std::uint32_t crtcId = findCrtcForEncoder(resources, *encoder);
@ -450,11 +448,9 @@ void checkInit()
// Use environment variable "SFML_DRM_REFRESH" (or 0 if not set)
// Use in combination with mode to request specific refresh rate for the mode
// if multiple refresh rates for same mode might be supported
unsigned int refreshRate = 0;
char* refreshString = std::getenv("SFML_DRM_REFRESH");
if (refreshString)
refreshRate = static_cast<unsigned int>(atoi(refreshString));
unsigned int refreshRate = 0;
if (const char* refreshString = std::getenv("SFML_DRM_REFRESH"))
refreshRate = static_cast<unsigned int>(std::atoi(refreshString));
if (initDrm(drmNode,
deviceString, // device

View File

@ -38,10 +38,7 @@ std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
{
std::vector<VideoMode> modes;
const Drm& drm = DRMContext::getDRM();
drmModeConnectorPtr conn = drm.savedConnector;
if (conn)
if (const auto* conn = DRMContext::getDRM().savedConnector)
{
for (int i = 0; i < conn->count_modes; i++)
modes.push_back(VideoMode({conn->modes[i].hdisplay, conn->modes[i].vdisplay}));
@ -56,9 +53,7 @@ std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
////////////////////////////////////////////////////////////
VideoMode VideoModeImpl::getDesktopMode()
{
const Drm& drm = DRMContext::getDRM();
drmModeModeInfoPtr ptr = drm.mode;
if (ptr)
if (const auto* ptr = DRMContext::getDRM().mode)
return VideoMode({ptr->hdisplay, ptr->vdisplay});
return VideoMode({0, 0});

View File

@ -111,9 +111,7 @@ void updatePluggedList()
* and check if they are joysticks. The index of JoystickImpl::open
* does not match the /dev/uhid<index> device!
*/
DIR* directory = opendir("/dev");
if (directory)
if (DIR* directory = opendir("/dev"))
{
unsigned int joystickCount = 0;
struct dirent* directoryEntry = readdir(directory);

View File

@ -269,9 +269,7 @@ struct GlContext::SharedContext
if (glGetErrorFunc() == GL_INVALID_ENUM || !majorVersion || !glGetStringiFunc)
{
// Try to load the < 3.0 way
const char* extensionString = reinterpret_cast<const char*>(glGetStringFunc(GL_EXTENSIONS));
if (extensionString)
if (const char* extensionString = reinterpret_cast<const char*>(glGetStringFunc(GL_EXTENSIONS)))
{
extensions.clear();
@ -297,12 +295,8 @@ struct GlContext::SharedContext
extensions.clear();
for (unsigned int i = 0; i < static_cast<unsigned int>(numExtensions); ++i)
{
const char* extensionString = reinterpret_cast<const char*>(glGetStringiFunc(GL_EXTENSIONS, i));
if (extensionString)
if (const char* extensionString = reinterpret_cast<const char*>(glGetStringiFunc(GL_EXTENSIONS, i)))
extensions.emplace_back(extensionString);
}
}
}
}
@ -496,7 +490,7 @@ void GlContext::unregisterUnsharedGlObject(std::shared_ptr<void> object)
// in unshared objects should be the only one existing
const auto iter = std::find_if(unsharedGlObjects->begin(),
unsharedGlObjects->end(),
[&](const Impl::UnsharedGlObject& obj) {
[&object](const Impl::UnsharedGlObject& obj) {
return (obj.object == object) &&
(obj.contextId == GlContextImpl::CurrentContext::get().id);
});
@ -917,8 +911,7 @@ void GlContext::initialize(const ContextSettings& requestedSettings)
m_settings.majorVersion = 1;
m_settings.minorVersion = 1;
const char* version = reinterpret_cast<const char*>(glGetStringFunc(GL_VERSION));
if (version)
if (const char* version = reinterpret_cast<const char*>(glGetStringFunc(GL_VERSION)))
{
// OpenGL ES Common Lite profile: The beginning of the returned string is "OpenGL ES-CL major.minor"
// OpenGL ES Common profile: The beginning of the returned string is "OpenGL ES-CM major.minor"

View File

@ -112,9 +112,7 @@ void updatePluggedList()
* and check if they are joysticks. The index of JoystickImpl::open
* does not match the /dev/uhid<index> device!
*/
DIR* directory = opendir("/dev");
if (directory)
if (DIR* directory = opendir("/dev"))
{
unsigned int joystickCount = 0;
struct dirent* directoryEntry = readdir(directory);

View File

@ -299,9 +299,8 @@ XVisualInfo GlxContext::selectBestVisual(::Display* display, unsigned int bitsPe
const int screen = DefaultScreen(display);
// Retrieve all the visuals
int count = 0;
const auto visuals = X11Ptr<XVisualInfo[]>(XGetVisualInfo(display, 0, nullptr, &count));
if (visuals)
int count = 0;
if (const auto visuals = X11Ptr<XVisualInfo[]>(XGetVisualInfo(display, 0, nullptr, &count)))
{
// Evaluate all the returned visuals, and pick the best one
int bestScore = 0x7FFFFFFF;

View File

@ -139,8 +139,7 @@ Vector2i getMousePosition()
////////////////////////////////////////////////////////////
Vector2i getMousePosition(const WindowBase& relativeTo)
{
const WindowHandle handle = relativeTo.getNativeHandle();
if (handle)
if (const WindowHandle handle = relativeTo.getNativeHandle())
{
// Open a connection with the X server
const auto display = openDisplay();
@ -180,8 +179,7 @@ void setMousePosition(Vector2i position, const WindowBase& relativeTo)
// Open a connection with the X server
const auto display = openDisplay();
const WindowHandle handle = relativeTo.getNativeHandle();
if (handle)
if (const WindowHandle handle = relativeTo.getNativeHandle())
{
XWarpPointer(display.get(), None, handle, 0, 0, 0, 0, position.x, position.y);
XFlush(display.get());

View File

@ -120,9 +120,7 @@ bool isJoystick(udev_device* udevDevice)
// On some platforms (older udev), ID_INPUT_ properties are not present, instead
// the system makes use of the ID_CLASS property to identify the device class
const char* idClass = udev_device_get_property_value(udevDevice, "ID_CLASS");
if (idClass)
if (const char* idClass = udev_device_get_property_value(udevDevice, "ID_CLASS"))
{
// Check if the device class matches joystick
if (std::strstr(idClass, "joystick"))
@ -144,9 +142,7 @@ void updatePluggedList(udev_device* udevDevice = nullptr)
{
if (udevDevice)
{
const char* action = udev_device_get_action(udevDevice);
if (action)
if (const char* action = udev_device_get_action(udevDevice))
{
if (isJoystick(udevDevice))
{
@ -300,13 +296,10 @@ unsigned int getUsbAttributeUint(udev_device* udevDevice, const std::string& att
if (!udevDevice)
return 0;
const char* attribute = getUsbAttribute(udevDevice, attributeName);
unsigned int value = 0;
if (const char* attribute = getUsbAttribute(udevDevice, attributeName))
return static_cast<unsigned int>(std::strtoul(attribute, nullptr, 16));
if (attribute)
value = static_cast<unsigned int>(std::strtoul(attribute, nullptr, 16));
return value;
return 0;
}
// Get a udev property value for a joystick as an unsigned int
@ -315,13 +308,10 @@ unsigned int getUdevAttributeUint(udev_device* udevDevice, const std::string& at
if (!udevDevice)
return 0;
const char* attribute = getUdevAttribute(udevDevice, attributeName);
unsigned int value = 0;
if (const char* attribute = getUdevAttribute(udevDevice, attributeName))
return static_cast<unsigned int>(std::strtoul(attribute, nullptr, 16));
if (attribute)
value = static_cast<unsigned int>(std::strtoul(attribute, nullptr, 16));
return value;
return 0;
}
// Get the joystick vendor id
@ -408,14 +398,10 @@ std::string getJoystickName(unsigned int index)
// Fall back to manual USB chain walk via udev
if (udevContext)
{
const auto udevDevice = UdevPtr<udev_device>(
udev_device_new_from_syspath(udevContext.get(), joystickList[index].systemPath.c_str()));
if (udevDevice)
if (const auto udevDevice = UdevPtr<udev_device>(
udev_device_new_from_syspath(udevContext.get(), joystickList[index].systemPath.c_str())))
if (const char* product = getUsbAttribute(udevDevice.get(), "product"))
return {product};
}
sf::err() << "Unable to get name for joystick " << devnode << std::endl;

View File

@ -67,9 +67,8 @@ std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
if (XQueryExtension(display.get(), "RANDR", &version, &version, &version))
{
// Get the current configuration
const auto config = X11Ptr<XRRScreenConfiguration>(
XRRGetScreenInfo(display.get(), RootWindow(display.get(), screen)));
if (config)
if (const auto config = X11Ptr<XRRScreenConfiguration>(
XRRGetScreenInfo(display.get(), RootWindow(display.get(), screen))))
{
// Get the available screen sizes
int nbSizes = 0;
@ -144,9 +143,8 @@ VideoMode VideoModeImpl::getDesktopMode()
if (XQueryExtension(display.get(), "RANDR", &version, &version, &version))
{
// Get the current configuration
const auto config = X11Ptr<XRRScreenConfiguration>(
XRRGetScreenInfo(display.get(), RootWindow(display.get(), screen)));
if (config)
if (const auto config = X11Ptr<XRRScreenConfiguration>(
XRRGetScreenInfo(display.get(), RootWindow(display.get(), screen))))
{
// Get the current video mode
Rotation currentRotation = 0;

View File

@ -88,8 +88,6 @@ std::bitset<256> isKeyFiltered;
std::recursive_mutex allWindowsMutex;
sf::String windowManagerName;
sf::String wmAbsPosGood[] = {"Enlightenment", "FVWM", "i3"};
constexpr unsigned long eventMask = FocusChangeMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask |
PointerMotionMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask |
EnterWindowMask | LeaveWindowMask | VisibilityChangeMask | PropertyChangeMask;
@ -365,9 +363,10 @@ bool isWMAbsolutePositionGood()
if (!ewmhSupported())
return false;
return std::any_of(std::begin(wmAbsPosGood),
std::end(wmAbsPosGood),
[&](const sf::String& name) { return name == windowManagerName; });
static const std::array<sf::String, 3> wmAbsPosGood = {"Enlightenment", "FVWM", "i3"};
return std::any_of(wmAbsPosGood.begin(),
wmAbsPosGood.end(),
[](const sf::String& name) { return name == windowManagerName; });
}
// Initialize raw mouse input
@ -569,8 +568,7 @@ m_cursorGrabbed(m_fullscreen)
// change our window's decorations and functions according to the requested style)
if (!m_fullscreen)
{
const Atom wmHintsAtom = getAtom("_MOTIF_WM_HINTS", false);
if (wmHintsAtom)
if (const Atom wmHintsAtom = getAtom("_MOTIF_WM_HINTS", false))
{
// NOLINTBEGIN(readability-identifier-naming)
// Disable naming check so these better match the contents of the Motif library
@ -1430,9 +1428,7 @@ void WindowImplX11::switchToFullscreen()
if (ewmhSupported())
{
const Atom netWmBypassCompositor = getAtom("_NET_WM_BYPASS_COMPOSITOR");
if (netWmBypassCompositor)
if (const Atom netWmBypassCompositor = getAtom("_NET_WM_BYPASS_COMPOSITOR"))
{
constexpr unsigned long bypassCompositor = 1;

View File

@ -90,10 +90,8 @@ void ClipboardImpl::setString(const String& text)
}
// Create a Win32-compatible string
const std::size_t stringSize = (text.getSize() + 1) * sizeof(WCHAR);
HANDLE stringHandle = GlobalAlloc(GMEM_MOVEABLE, stringSize);
if (stringHandle)
const std::size_t stringSize = (text.getSize() + 1) * sizeof(WCHAR);
if (const HANDLE stringHandle = GlobalAlloc(GMEM_MOVEABLE, stringSize))
{
std::memcpy(GlobalLock(stringHandle), text.toWideString().data(), stringSize);
GlobalUnlock(stringHandle);

View File

@ -703,8 +703,7 @@ Vector2i getMousePosition()
////////////////////////////////////////////////////////////
Vector2i getMousePosition(const WindowBase& relativeTo)
{
WindowHandle handle = relativeTo.getNativeHandle();
if (handle)
if (const WindowHandle handle = relativeTo.getNativeHandle())
{
POINT point;
GetCursorPos(&point);
@ -726,8 +725,7 @@ void setMousePosition(Vector2i position)
////////////////////////////////////////////////////////////
void setMousePosition(Vector2i position, const WindowBase& relativeTo)
{
WindowHandle handle = relativeTo.getNativeHandle();
if (handle)
if (const WindowHandle handle = relativeTo.getNativeHandle())
{
POINT point = {position.x, position.y};
ClientToScreen(handle, &point);

View File

@ -69,9 +69,7 @@ const GUID guidDevinterfaceHid = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00,
void setProcessDpiAware()
{
// Try SetProcessDpiAwareness first
HINSTANCE shCoreDll = LoadLibrary(L"Shcore.dll");
if (shCoreDll)
if (const HINSTANCE shCoreDll = LoadLibrary(L"Shcore.dll"))
{
enum ProcessDpiAwareness
{
@ -109,9 +107,7 @@ void setProcessDpiAware()
// Fall back to SetProcessDPIAware if SetProcessDpiAwareness
// is not available on this system
HINSTANCE user32Dll = LoadLibrary(L"user32.dll");
if (user32Dll)
if (const HINSTANCE user32Dll = LoadLibrary(L"user32.dll"))
{
using SetProcessDPIAwareFuncType = BOOL(WINAPI*)();
auto setProcessDPIAwareFunc = reinterpret_cast<SetProcessDPIAwareFuncType>(

View File

@ -228,7 +228,7 @@ void WindowImpl::setMaximumSize(const std::optional<Vector2u>& maximumSize)
////////////////////////////////////////////////////////////
std::optional<Event> WindowImpl::waitEvent(Time timeout)
{
const auto timedOut = [&, startTime = std::chrono::steady_clock::now()]
const auto timedOut = [timeout, startTime = std::chrono::steady_clock::now()]
{
const bool infiniteTimeout = timeout == Time::Zero;
return !infiniteTimeout && (std::chrono::steady_clock::now() - startTime) >= timeout.toDuration();

View File

@ -215,9 +215,7 @@ void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, cons
// 1.x/2.x are mapped to 2.1 since Apple only support that legacy version.
// >=3.0 are mapped to a 3.2 core profile.
const bool legacy = m_settings.majorVersion < 3;
if (legacy)
if (m_settings.majorVersion < 3)
{
m_settings.attributeFlags &= ~static_cast<unsigned int>(ContextSettings::Core);
m_settings.majorVersion = 2;