Add misc-const-correctness
clang-tidy check
This commit is contained in:
parent
29863b14a5
commit
fb1cfdc48d
@ -24,7 +24,6 @@ Checks: >
|
|||||||
-clang-analyzer-optin.osx.*,
|
-clang-analyzer-optin.osx.*,
|
||||||
-clang-analyzer-osx.*,
|
-clang-analyzer-osx.*,
|
||||||
-clang-analyzer-unix.Malloc,
|
-clang-analyzer-unix.Malloc,
|
||||||
-misc-const-correctness,
|
|
||||||
-misc-misplaced-const,
|
-misc-misplaced-const,
|
||||||
-misc-no-recursion,
|
-misc-no-recursion,
|
||||||
-misc-non-private-member-variables-in-classes,
|
-misc-non-private-member-variables-in-classes,
|
||||||
|
@ -36,8 +36,8 @@ int main()
|
|||||||
} while (!address.has_value());
|
} while (!address.has_value());
|
||||||
|
|
||||||
// Connect to the server
|
// Connect to the server
|
||||||
sf::Ftp server;
|
sf::Ftp server;
|
||||||
sf::Ftp::Response connectResponse = server.connect(address.value());
|
const sf::Ftp::Response connectResponse = server.connect(address.value());
|
||||||
std::cout << connectResponse << std::endl;
|
std::cout << connectResponse << std::endl;
|
||||||
if (!connectResponse.isOk())
|
if (!connectResponse.isOk())
|
||||||
return EXIT_FAILURE;
|
return EXIT_FAILURE;
|
||||||
@ -51,7 +51,7 @@ int main()
|
|||||||
std::cin >> password;
|
std::cin >> password;
|
||||||
|
|
||||||
// Login to the server
|
// Login to the server
|
||||||
sf::Ftp::Response loginResponse = server.login(user, password);
|
const sf::Ftp::Response loginResponse = server.login(user, password);
|
||||||
std::cout << loginResponse << std::endl;
|
std::cout << loginResponse << std::endl;
|
||||||
if (!loginResponse.isOk())
|
if (!loginResponse.isOk())
|
||||||
return EXIT_FAILURE;
|
return EXIT_FAILURE;
|
||||||
@ -93,7 +93,7 @@ int main()
|
|||||||
case 1:
|
case 1:
|
||||||
{
|
{
|
||||||
// Print the current server directory
|
// Print the current server directory
|
||||||
sf::Ftp::DirectoryResponse response = server.getWorkingDirectory();
|
const sf::Ftp::DirectoryResponse response = server.getWorkingDirectory();
|
||||||
std::cout << response << '\n' << "Current directory is " << response.getDirectory() << std::endl;
|
std::cout << response << '\n' << "Current directory is " << response.getDirectory() << std::endl;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -101,7 +101,7 @@ int main()
|
|||||||
case 2:
|
case 2:
|
||||||
{
|
{
|
||||||
// Print the contents of the current server directory
|
// Print the contents of the current server directory
|
||||||
sf::Ftp::ListingResponse response = server.getDirectoryListing();
|
const sf::Ftp::ListingResponse response = server.getDirectoryListing();
|
||||||
std::cout << response << '\n';
|
std::cout << response << '\n';
|
||||||
for (const std::string& name : response.getListing())
|
for (const std::string& name : response.getListing())
|
||||||
std::cout << name << '\n';
|
std::cout << name << '\n';
|
||||||
|
@ -96,11 +96,11 @@ int main()
|
|||||||
return EXIT_FAILURE;
|
return EXIT_FAILURE;
|
||||||
|
|
||||||
// Create all of our graphics resources
|
// Create all of our graphics resources
|
||||||
sf::Text hudText(font);
|
sf::Text hudText(font);
|
||||||
sf::Text statusText(font);
|
sf::Text statusText(font);
|
||||||
sf::Shader terrainShader;
|
sf::Shader terrainShader;
|
||||||
sf::RenderStates terrainStates(&terrainShader);
|
const sf::RenderStates terrainStates(&terrainShader);
|
||||||
sf::VertexBuffer terrain(sf::PrimitiveType::Triangles, sf::VertexBuffer::Static);
|
sf::VertexBuffer terrain(sf::PrimitiveType::Triangles, sf::VertexBuffer::Static);
|
||||||
|
|
||||||
// Set up our text drawables
|
// Set up our text drawables
|
||||||
statusText.setCharacterSize(28);
|
statusText.setCharacterSize(28);
|
||||||
@ -223,7 +223,7 @@ int main()
|
|||||||
if (prerequisitesSupported)
|
if (prerequisitesSupported)
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
std::lock_guard lock(workQueueMutex);
|
const std::lock_guard lock(workQueueMutex);
|
||||||
|
|
||||||
// Don't bother updating/drawing the VertexBuffer while terrain is being regenerated
|
// Don't bother updating/drawing the VertexBuffer while terrain is being regenerated
|
||||||
if (!pendingWorkCount)
|
if (!pendingWorkCount)
|
||||||
@ -266,7 +266,7 @@ int main()
|
|||||||
|
|
||||||
// Shut down our thread pool
|
// Shut down our thread pool
|
||||||
{
|
{
|
||||||
std::lock_guard lock(workQueueMutex);
|
const std::lock_guard lock(workQueueMutex);
|
||||||
workPending = false;
|
workPending = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -302,9 +302,9 @@ float getElevation(float x, float y)
|
|||||||
|
|
||||||
elevation = (elevation + 1.f) / 2.f;
|
elevation = (elevation + 1.f) / 2.f;
|
||||||
|
|
||||||
float distance = 2.0f * std::sqrt(x * x + y * y);
|
const float distance = 2.0f * std::sqrt(x * x + y * y);
|
||||||
elevation = (elevation + heightBase) * (1.0f - edgeFactor * std::pow(distance, edgeDropoffExponent));
|
elevation = (elevation + heightBase) * (1.0f - edgeFactor * std::pow(distance, edgeDropoffExponent));
|
||||||
elevation = std::clamp(elevation, 0.0f, 1.0f);
|
elevation = std::clamp(elevation, 0.0f, 1.0f);
|
||||||
|
|
||||||
return elevation;
|
return elevation;
|
||||||
}
|
}
|
||||||
@ -324,7 +324,7 @@ float getMoisture(float x, float y)
|
|||||||
x = x / resolutionX - 0.5f;
|
x = x / resolutionX - 0.5f;
|
||||||
y = y / resolutionY - 0.5f;
|
y = y / resolutionY - 0.5f;
|
||||||
|
|
||||||
float moisture = stb_perlin_noise3(x * 4.f + 0.5f, y * 4.f + 0.5f, 0, 0, 0, 0);
|
const float moisture = stb_perlin_noise3(x * 4.f + 0.5f, y * 4.f + 0.5f, 0, 0, 0, 0);
|
||||||
|
|
||||||
return (moisture + 1.f) / 2.f;
|
return (moisture + 1.f) / 2.f;
|
||||||
}
|
}
|
||||||
@ -369,14 +369,14 @@ sf::Color getLowlandsTerrainColor(float moisture)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
sf::Color getHighlandsTerrainColor(float elevation, float moisture)
|
sf::Color getHighlandsTerrainColor(float elevation, float moisture)
|
||||||
{
|
{
|
||||||
sf::Color lowlandsColor = getLowlandsTerrainColor(moisture);
|
const sf::Color lowlandsColor = getLowlandsTerrainColor(moisture);
|
||||||
|
|
||||||
sf::Color color = moisture < 0.6f ? sf::Color(112, 128, 144)
|
sf::Color color = moisture < 0.6f ? sf::Color(112, 128, 144)
|
||||||
: colorFromFloats(112 + (110 * (moisture - 0.6f) / 0.4f),
|
: colorFromFloats(112 + (110 * (moisture - 0.6f) / 0.4f),
|
||||||
128 + (56 * (moisture - 0.6f) / 0.4f),
|
128 + (56 * (moisture - 0.6f) / 0.4f),
|
||||||
144 - (9 * (moisture - 0.6f) / 0.4f));
|
144 - (9 * (moisture - 0.6f) / 0.4f));
|
||||||
|
|
||||||
float factor = std::min((elevation - 0.4f) / 0.1f, 1.f);
|
const float factor = std::min((elevation - 0.4f) / 0.1f, 1.f);
|
||||||
|
|
||||||
color.r = static_cast<std::uint8_t>(lowlandsColor.r * (1.f - factor) + color.r * factor);
|
color.r = static_cast<std::uint8_t>(lowlandsColor.r * (1.f - factor) + color.r * factor);
|
||||||
color.g = static_cast<std::uint8_t>(lowlandsColor.g * (1.f - factor) + color.g * factor);
|
color.g = static_cast<std::uint8_t>(lowlandsColor.g * (1.f - factor) + color.g * factor);
|
||||||
@ -393,11 +393,11 @@ sf::Color getHighlandsTerrainColor(float elevation, float moisture)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
sf::Color getSnowcapTerrainColor(float elevation, float moisture)
|
sf::Color getSnowcapTerrainColor(float elevation, float moisture)
|
||||||
{
|
{
|
||||||
sf::Color highlandsColor = getHighlandsTerrainColor(elevation, moisture);
|
const sf::Color highlandsColor = getHighlandsTerrainColor(elevation, moisture);
|
||||||
|
|
||||||
sf::Color color = sf::Color::White;
|
sf::Color color = sf::Color::White;
|
||||||
|
|
||||||
float factor = std::min((elevation - snowcapHeight) / 0.05f, 1.f);
|
const float factor = std::min((elevation - snowcapHeight) / 0.05f, 1.f);
|
||||||
|
|
||||||
color.r = static_cast<std::uint8_t>(highlandsColor.r * (1.f - factor) + color.r * factor);
|
color.r = static_cast<std::uint8_t>(highlandsColor.r * (1.f - factor) + color.r * factor);
|
||||||
color.g = static_cast<std::uint8_t>(highlandsColor.g * (1.f - factor) + color.g * factor);
|
color.g = static_cast<std::uint8_t>(highlandsColor.g * (1.f - factor) + color.g * factor);
|
||||||
@ -440,8 +440,8 @@ sf::Color getTerrainColor(float elevation, float moisture)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
sf::Vector2f computeNormal(float left, float right, float bottom, float top)
|
sf::Vector2f computeNormal(float left, float right, float bottom, float top)
|
||||||
{
|
{
|
||||||
sf::Vector3f deltaX(1, 0, (std::pow(right, heightFlatten) - std::pow(left, heightFlatten)) * heightFactor);
|
const sf::Vector3f deltaX(1, 0, (std::pow(right, heightFlatten) - std::pow(left, heightFlatten)) * heightFactor);
|
||||||
sf::Vector3f deltaY(0, 1, (std::pow(top, heightFlatten) - std::pow(bottom, heightFlatten)) * heightFactor);
|
const sf::Vector3f deltaY(0, 1, (std::pow(top, heightFlatten) - std::pow(bottom, heightFlatten)) * heightFactor);
|
||||||
|
|
||||||
sf::Vector3f crossProduct(deltaX.y * deltaY.z - deltaX.z * deltaY.y,
|
sf::Vector3f crossProduct(deltaX.y * deltaY.z - deltaX.z * deltaY.y,
|
||||||
deltaX.z * deltaY.x - deltaX.x * deltaY.z,
|
deltaX.z * deltaY.x - deltaX.x * deltaY.z,
|
||||||
@ -463,14 +463,14 @@ sf::Vector2f computeNormal(float left, float right, float bottom, float top)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void processWorkItem(std::vector<sf::Vertex>& vertices, const WorkItem& workItem)
|
void processWorkItem(std::vector<sf::Vertex>& vertices, const WorkItem& workItem)
|
||||||
{
|
{
|
||||||
unsigned int rowBlockSize = (resolutionY / blockCount) + 1;
|
const unsigned int rowBlockSize = (resolutionY / blockCount) + 1;
|
||||||
unsigned int rowStart = rowBlockSize * workItem.index;
|
const unsigned int rowStart = rowBlockSize * workItem.index;
|
||||||
|
|
||||||
if (rowStart >= resolutionY)
|
if (rowStart >= resolutionY)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
unsigned int rowEnd = std::min(rowStart + rowBlockSize, resolutionY);
|
const unsigned int rowEnd = std::min(rowStart + rowBlockSize, resolutionY);
|
||||||
unsigned int rowCount = rowEnd - rowStart;
|
const unsigned int rowCount = rowEnd - rowStart;
|
||||||
|
|
||||||
const float scalingFactorX = static_cast<float>(windowWidth) / static_cast<float>(resolutionX);
|
const float scalingFactorX = static_cast<float>(windowWidth) / static_cast<float>(resolutionX);
|
||||||
const float scalingFactorY = static_cast<float>(windowHeight) / static_cast<float>(resolutionY);
|
const float scalingFactorY = static_cast<float>(windowHeight) / static_cast<float>(resolutionY);
|
||||||
@ -479,7 +479,7 @@ void processWorkItem(std::vector<sf::Vertex>& vertices, const WorkItem& workItem
|
|||||||
{
|
{
|
||||||
for (unsigned int x = 0; x < resolutionX; ++x)
|
for (unsigned int x = 0; x < resolutionX; ++x)
|
||||||
{
|
{
|
||||||
unsigned int arrayIndexBase = ((y - rowStart) * resolutionX + x) * 6;
|
const unsigned int arrayIndexBase = ((y - rowStart) * resolutionX + x) * 6;
|
||||||
|
|
||||||
// Top left corner (first triangle)
|
// Top left corner (first triangle)
|
||||||
if (x > 0)
|
if (x > 0)
|
||||||
@ -565,7 +565,7 @@ void processWorkItem(std::vector<sf::Vertex>& vertices, const WorkItem& workItem
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void threadFunction()
|
void threadFunction()
|
||||||
{
|
{
|
||||||
unsigned int rowBlockSize = (resolutionY / blockCount) + 1;
|
const unsigned int rowBlockSize = (resolutionY / blockCount) + 1;
|
||||||
|
|
||||||
std::vector<sf::Vertex> vertices(resolutionX * rowBlockSize * 6);
|
std::vector<sf::Vertex> vertices(resolutionX * rowBlockSize * 6);
|
||||||
|
|
||||||
@ -578,7 +578,7 @@ void threadFunction()
|
|||||||
|
|
||||||
// Check if there are new work items in the queue
|
// Check if there are new work items in the queue
|
||||||
{
|
{
|
||||||
std::lock_guard lock(workQueueMutex);
|
const std::lock_guard lock(workQueueMutex);
|
||||||
|
|
||||||
if (!workPending)
|
if (!workPending)
|
||||||
return;
|
return;
|
||||||
@ -601,7 +601,7 @@ void threadFunction()
|
|||||||
processWorkItem(vertices, workItem);
|
processWorkItem(vertices, workItem);
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard lock(workQueueMutex);
|
const std::lock_guard lock(workQueueMutex);
|
||||||
|
|
||||||
--pendingWorkCount;
|
--pendingWorkCount;
|
||||||
}
|
}
|
||||||
@ -623,7 +623,7 @@ void generateTerrain(sf::Vertex* buffer)
|
|||||||
for (;;)
|
for (;;)
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
std::lock_guard lock(workQueueMutex);
|
const std::lock_guard lock(workQueueMutex);
|
||||||
|
|
||||||
if (workQueue.empty())
|
if (workQueue.empty())
|
||||||
break;
|
break;
|
||||||
@ -634,11 +634,11 @@ void generateTerrain(sf::Vertex* buffer)
|
|||||||
|
|
||||||
// Queue all the new work items
|
// Queue all the new work items
|
||||||
{
|
{
|
||||||
std::lock_guard lock(workQueueMutex);
|
const std::lock_guard lock(workQueueMutex);
|
||||||
|
|
||||||
for (unsigned int i = 0; i < blockCount; ++i)
|
for (unsigned int i = 0; i < blockCount; ++i)
|
||||||
{
|
{
|
||||||
WorkItem workItem = {buffer, i};
|
const WorkItem workItem = {buffer, i};
|
||||||
workQueue.push_back(workItem);
|
workQueue.push_back(workItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -56,7 +56,7 @@ int main()
|
|||||||
backgroundTexture.setSrgb(sRgb);
|
backgroundTexture.setSrgb(sRgb);
|
||||||
if (!backgroundTexture.loadFromFile(resourcesDir() / "background.jpg"))
|
if (!backgroundTexture.loadFromFile(resourcesDir() / "background.jpg"))
|
||||||
return EXIT_FAILURE;
|
return EXIT_FAILURE;
|
||||||
sf::Sprite background(backgroundTexture);
|
const sf::Sprite background(backgroundTexture);
|
||||||
|
|
||||||
// Create some text to draw on top of our OpenGL object
|
// Create some text to draw on top of our OpenGL object
|
||||||
sf::Font font;
|
sf::Font font;
|
||||||
@ -115,7 +115,7 @@ int main()
|
|||||||
// Setup a perspective projection
|
// Setup a perspective projection
|
||||||
glMatrixMode(GL_PROJECTION);
|
glMatrixMode(GL_PROJECTION);
|
||||||
glLoadIdentity();
|
glLoadIdentity();
|
||||||
GLfloat ratio = static_cast<float>(window.getSize().x) / static_cast<float>(window.getSize().y);
|
const GLfloat ratio = static_cast<float>(window.getSize().x) / static_cast<float>(window.getSize().y);
|
||||||
#ifdef SFML_OPENGL_ES
|
#ifdef SFML_OPENGL_ES
|
||||||
glFrustumf(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
|
glFrustumf(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
|
||||||
#else
|
#else
|
||||||
@ -193,7 +193,7 @@ int main()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create a clock for measuring the time elapsed
|
// Create a clock for measuring the time elapsed
|
||||||
sf::Clock clock;
|
const sf::Clock clock;
|
||||||
|
|
||||||
// Flag to track whether mipmapping is currently enabled
|
// Flag to track whether mipmapping is currently enabled
|
||||||
bool mipmapEnabled = true;
|
bool mipmapEnabled = true;
|
||||||
@ -245,7 +245,7 @@ int main()
|
|||||||
// Adjust the viewport when the window is resized
|
// Adjust the viewport when the window is resized
|
||||||
if (event.type == sf::Event::Resized)
|
if (event.type == sf::Event::Resized)
|
||||||
{
|
{
|
||||||
sf::Vector2u textureSize = backgroundTexture.getSize();
|
const sf::Vector2u textureSize = backgroundTexture.getSize();
|
||||||
|
|
||||||
// Make the window the active window for OpenGL calls
|
// Make the window the active window for OpenGL calls
|
||||||
if (!window.setActive(true))
|
if (!window.setActive(true))
|
||||||
@ -257,7 +257,7 @@ int main()
|
|||||||
glViewport(0, 0, static_cast<GLsizei>(event.size.width), static_cast<GLsizei>(event.size.height));
|
glViewport(0, 0, static_cast<GLsizei>(event.size.width), static_cast<GLsizei>(event.size.height));
|
||||||
glMatrixMode(GL_PROJECTION);
|
glMatrixMode(GL_PROJECTION);
|
||||||
glLoadIdentity();
|
glLoadIdentity();
|
||||||
GLfloat newRatio = static_cast<float>(event.size.width) / static_cast<float>(event.size.height);
|
const GLfloat newRatio = static_cast<float>(event.size.width) / static_cast<float>(event.size.height);
|
||||||
#ifdef SFML_OPENGL_ES
|
#ifdef SFML_OPENGL_ES
|
||||||
glFrustumf(-newRatio, newRatio, -1.f, 1.f, 1.f, 500.f);
|
glFrustumf(-newRatio, newRatio, -1.f, 1.f, 1.f, 500.f);
|
||||||
#else
|
#else
|
||||||
@ -303,8 +303,8 @@ int main()
|
|||||||
pos = sf::Mouse::getPosition(window);
|
pos = sf::Mouse::getPosition(window);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
float x = static_cast<float>(pos.x) * 200.f / static_cast<float>(window.getSize().x) - 100.f;
|
const float x = static_cast<float>(pos.x) * 200.f / static_cast<float>(window.getSize().x) - 100.f;
|
||||||
float y = -static_cast<float>(pos.y) * 200.f / static_cast<float>(window.getSize().y) + 100.f;
|
const float y = -static_cast<float>(pos.y) * 200.f / static_cast<float>(window.getSize().y) + 100.f;
|
||||||
|
|
||||||
// Apply some transformations
|
// Apply some transformations
|
||||||
glMatrixMode(GL_MODELVIEW);
|
glMatrixMode(GL_MODELVIEW);
|
||||||
|
@ -139,11 +139,11 @@ public:
|
|||||||
m_points.setPrimitiveType(sf::PrimitiveType::Points);
|
m_points.setPrimitiveType(sf::PrimitiveType::Points);
|
||||||
for (int i = 0; i < 40000; ++i)
|
for (int i = 0; i < 40000; ++i)
|
||||||
{
|
{
|
||||||
auto x = xDistribution(rng);
|
const auto x = xDistribution(rng);
|
||||||
auto y = yDistribution(rng);
|
const auto y = yDistribution(rng);
|
||||||
auto r = static_cast<std::uint8_t>(colorDistribution(rng));
|
const auto r = static_cast<std::uint8_t>(colorDistribution(rng));
|
||||||
auto g = static_cast<std::uint8_t>(colorDistribution(rng));
|
const auto g = static_cast<std::uint8_t>(colorDistribution(rng));
|
||||||
auto b = static_cast<std::uint8_t>(colorDistribution(rng));
|
const auto b = static_cast<std::uint8_t>(colorDistribution(rng));
|
||||||
m_points.append(sf::Vertex(sf::Vector2f(x, y), sf::Color(r, g, b)));
|
m_points.append(sf::Vertex(sf::Vector2f(x, y), sf::Color(r, g, b)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -153,7 +153,7 @@ public:
|
|||||||
|
|
||||||
void onUpdate(float time, float x, float y) override
|
void onUpdate(float time, float x, float y) override
|
||||||
{
|
{
|
||||||
float radius = 200 + std::cos(time) * 150;
|
const float radius = 200 + std::cos(time) * 150;
|
||||||
m_shader.setUniform("storm_position", sf::Vector2f(x * 800, y * 600));
|
m_shader.setUniform("storm_position", sf::Vector2f(x * 800, y * 600));
|
||||||
m_shader.setUniform("storm_inner_radius", radius / 3);
|
m_shader.setUniform("storm_inner_radius", radius / 3);
|
||||||
m_shader.setUniform("storm_total_radius", radius);
|
m_shader.setUniform("storm_total_radius", radius);
|
||||||
@ -205,7 +205,7 @@ public:
|
|||||||
// Load the moving entities
|
// Load the moving entities
|
||||||
for (int i = 0; i < 6; ++i)
|
for (int i = 0; i < 6; ++i)
|
||||||
{
|
{
|
||||||
sf::Sprite entity(m_entityTexture, sf::IntRect({96 * i, 0}, {96, 96}));
|
const sf::Sprite entity(m_entityTexture, sf::IntRect({96 * i, 0}, {96, 96}));
|
||||||
m_entities.push_back(entity);
|
m_entities.push_back(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -308,7 +308,7 @@ public:
|
|||||||
m_transform.rotate(sf::degrees(x * 360.f));
|
m_transform.rotate(sf::degrees(x * 360.f));
|
||||||
|
|
||||||
// Adjust billboard size to scale between 25 and 75
|
// Adjust billboard size to scale between 25 and 75
|
||||||
float size = 25 + std::abs(y) * 50;
|
const float size = 25 + std::abs(y) * 50;
|
||||||
|
|
||||||
// Update the shader parameter
|
// Update the shader parameter
|
||||||
m_shader.setUniform("size", sf::Vector2f(size, size));
|
m_shader.setUniform("size", sf::Vector2f(size, size));
|
||||||
@ -387,7 +387,7 @@ int main()
|
|||||||
instructions.setFillColor(sf::Color(80, 80, 80));
|
instructions.setFillColor(sf::Color(80, 80, 80));
|
||||||
|
|
||||||
// Start the game loop
|
// Start the game loop
|
||||||
sf::Clock clock;
|
const sf::Clock clock;
|
||||||
while (window.isOpen())
|
while (window.isOpen())
|
||||||
{
|
{
|
||||||
// Process events
|
// Process events
|
||||||
|
@ -33,10 +33,10 @@ int main()
|
|||||||
std::mt19937 rng(rd());
|
std::mt19937 rng(rd());
|
||||||
|
|
||||||
// Define some constants
|
// Define some constants
|
||||||
const float gameWidth = 800;
|
const float gameWidth = 800;
|
||||||
const float gameHeight = 600;
|
const float gameHeight = 600;
|
||||||
sf::Vector2f paddleSize(25, 100);
|
const sf::Vector2f paddleSize(25, 100);
|
||||||
float ballRadius = 10.f;
|
const float ballRadius = 10.f;
|
||||||
|
|
||||||
// Create the window of the application
|
// Create the window of the application
|
||||||
sf::RenderWindow window(sf::VideoMode({static_cast<unsigned int>(gameWidth), static_cast<unsigned int>(gameHeight)}, 32),
|
sf::RenderWindow window(sf::VideoMode({static_cast<unsigned int>(gameWidth), static_cast<unsigned int>(gameHeight)}, 32),
|
||||||
@ -157,7 +157,7 @@ int main()
|
|||||||
|
|
||||||
if (isPlaying)
|
if (isPlaying)
|
||||||
{
|
{
|
||||||
float deltaTime = clock.restart().asSeconds();
|
const float deltaTime = clock.restart().asSeconds();
|
||||||
|
|
||||||
// Move the player's paddle
|
// Move the player's paddle
|
||||||
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && (leftPaddle.getPosition().y - paddleSize.y / 2 > 5.f))
|
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && (leftPaddle.getPosition().y - paddleSize.y / 2 > 5.f))
|
||||||
@ -172,8 +172,8 @@ int main()
|
|||||||
|
|
||||||
if (sf::Touch::isDown(0))
|
if (sf::Touch::isDown(0))
|
||||||
{
|
{
|
||||||
sf::Vector2i pos = sf::Touch::getPosition(0);
|
const sf::Vector2i pos = sf::Touch::getPosition(0);
|
||||||
sf::Vector2f mappedPos = window.mapPixelToCoords(pos);
|
const sf::Vector2f mappedPos = window.mapPixelToCoords(pos);
|
||||||
leftPaddle.setPosition({leftPaddle.getPosition().x, mappedPos.y});
|
leftPaddle.setPosition({leftPaddle.getPosition().x, mappedPos.y});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -83,7 +83,7 @@ private:
|
|||||||
// Copy samples into a local buffer to avoid synchronization problems
|
// Copy samples into a local buffer to avoid synchronization problems
|
||||||
// (don't forget that we run in two separate threads)
|
// (don't forget that we run in two separate threads)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_mutex);
|
const std::lock_guard lock(m_mutex);
|
||||||
m_tempBuffer.assign(m_samples.begin() + static_cast<std::vector<std::int16_t>::difference_type>(m_offset),
|
m_tempBuffer.assign(m_samples.begin() + static_cast<std::vector<std::int16_t>::difference_type>(m_offset),
|
||||||
m_samples.end());
|
m_samples.end());
|
||||||
}
|
}
|
||||||
@ -127,13 +127,13 @@ private:
|
|||||||
if (id == serverAudioData)
|
if (id == serverAudioData)
|
||||||
{
|
{
|
||||||
// Extract audio samples from the packet, and append it to our samples buffer
|
// Extract audio samples from the packet, and append it to our samples buffer
|
||||||
std::size_t sampleCount = (packet.getDataSize() - 1) / sizeof(std::int16_t);
|
const std::size_t sampleCount = (packet.getDataSize() - 1) / sizeof(std::int16_t);
|
||||||
|
|
||||||
// Don't forget that the other thread can access the sample array at any time
|
// Don't forget that the other thread can access the sample array at any time
|
||||||
// (so we protect any operation on it with the mutex)
|
// (so we protect any operation on it with the mutex)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_mutex);
|
const std::lock_guard lock(m_mutex);
|
||||||
std::size_t oldSize = m_samples.size();
|
const std::size_t oldSize = m_samples.size();
|
||||||
m_samples.resize(oldSize + sampleCount);
|
m_samples.resize(oldSize + sampleCount);
|
||||||
std::memcpy(&(m_samples[oldSize]),
|
std::memcpy(&(m_samples[oldSize]),
|
||||||
static_cast<const char*>(packet.getData()) + 1,
|
static_cast<const char*>(packet.getData()) + 1,
|
||||||
|
@ -46,10 +46,10 @@ void matrixMultiply(Matrix& result, const Matrix& left, const Matrix& right)
|
|||||||
// Rotate a matrix around the x-axis
|
// Rotate a matrix around the x-axis
|
||||||
void matrixRotateX(Matrix& result, sf::Angle angle)
|
void matrixRotateX(Matrix& result, sf::Angle angle)
|
||||||
{
|
{
|
||||||
float rad = angle.asRadians();
|
const float rad = angle.asRadians();
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
Matrix matrix = {
|
const Matrix matrix = {
|
||||||
{1.f, 0.f, 0.f, 0.f},
|
{1.f, 0.f, 0.f, 0.f},
|
||||||
{0.f, std::cos(rad), std::sin(rad), 0.f},
|
{0.f, std::cos(rad), std::sin(rad), 0.f},
|
||||||
{0.f, -std::sin(rad), std::cos(rad), 0.f},
|
{0.f, -std::sin(rad), std::cos(rad), 0.f},
|
||||||
@ -63,10 +63,10 @@ void matrixRotateX(Matrix& result, sf::Angle angle)
|
|||||||
// Rotate a matrix around the y-axis
|
// Rotate a matrix around the y-axis
|
||||||
void matrixRotateY(Matrix& result, sf::Angle angle)
|
void matrixRotateY(Matrix& result, sf::Angle angle)
|
||||||
{
|
{
|
||||||
float rad = angle.asRadians();
|
const float rad = angle.asRadians();
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
Matrix matrix = {
|
const Matrix matrix = {
|
||||||
{ std::cos(rad), 0.f, std::sin(rad), 0.f},
|
{ std::cos(rad), 0.f, std::sin(rad), 0.f},
|
||||||
{ 0.f, 1.f, 0.f, 0.f},
|
{ 0.f, 1.f, 0.f, 0.f},
|
||||||
{-std::sin(rad), 0.f, std::cos(rad), 0.f},
|
{-std::sin(rad), 0.f, std::cos(rad), 0.f},
|
||||||
@ -80,10 +80,10 @@ void matrixRotateY(Matrix& result, sf::Angle angle)
|
|||||||
// Rotate a matrix around the z-axis
|
// Rotate a matrix around the z-axis
|
||||||
void matrixRotateZ(Matrix& result, sf::Angle angle)
|
void matrixRotateZ(Matrix& result, sf::Angle angle)
|
||||||
{
|
{
|
||||||
float rad = angle.asRadians();
|
const float rad = angle.asRadians();
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
Matrix matrix = {
|
const Matrix matrix = {
|
||||||
{ std::cos(rad), std::sin(rad), 0.f, 0.f},
|
{ std::cos(rad), std::sin(rad), 0.f, 0.f},
|
||||||
{-std::sin(rad), std::cos(rad), 0.f, 0.f},
|
{-std::sin(rad), std::cos(rad), 0.f, 0.f},
|
||||||
{ 0.f, 0.f, 1.f, 0.f},
|
{ 0.f, 0.f, 1.f, 0.f},
|
||||||
@ -711,7 +711,7 @@ public:
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
float queuePriority = 1.0f;
|
const float queuePriority = 1.0f;
|
||||||
|
|
||||||
VkDeviceQueueCreateInfo deviceQueueCreateInfo = VkDeviceQueueCreateInfo();
|
VkDeviceQueueCreateInfo deviceQueueCreateInfo = VkDeviceQueueCreateInfo();
|
||||||
deviceQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
deviceQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
||||||
@ -774,7 +774,7 @@ public:
|
|||||||
}
|
}
|
||||||
else if (!surfaceFormats.empty())
|
else if (!surfaceFormats.empty())
|
||||||
{
|
{
|
||||||
for (VkSurfaceFormatKHR& surfaceFormat : surfaceFormats)
|
for (const VkSurfaceFormatKHR& surfaceFormat : surfaceFormats)
|
||||||
{
|
{
|
||||||
if ((surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) &&
|
if ((surfaceFormat.format == VK_FORMAT_B8G8R8A8_UNORM) &&
|
||||||
(surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR))
|
(surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR))
|
||||||
@ -815,7 +815,7 @@ public:
|
|||||||
// Prefer mailbox over FIFO if it is available
|
// Prefer mailbox over FIFO if it is available
|
||||||
VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
|
VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
|
||||||
|
|
||||||
for (VkPresentModeKHR& i : presentModes)
|
for (const VkPresentModeKHR& i : presentModes)
|
||||||
{
|
{
|
||||||
if (i == VK_PRESENT_MODE_MAILBOX_KHR)
|
if (i == VK_PRESENT_MODE_MAILBOX_KHR)
|
||||||
{
|
{
|
||||||
@ -840,7 +840,7 @@ public:
|
|||||||
surfaceCapabilities.minImageExtent.height,
|
surfaceCapabilities.minImageExtent.height,
|
||||||
surfaceCapabilities.maxImageExtent.height);
|
surfaceCapabilities.maxImageExtent.height);
|
||||||
|
|
||||||
auto imageCount = std::clamp(2u, surfaceCapabilities.minImageCount, surfaceCapabilities.maxImageCount);
|
const auto imageCount = std::clamp(2u, surfaceCapabilities.minImageCount, surfaceCapabilities.maxImageCount);
|
||||||
|
|
||||||
VkSwapchainCreateInfoKHR swapchainCreateInfo = VkSwapchainCreateInfoKHR();
|
VkSwapchainCreateInfoKHR swapchainCreateInfo = VkSwapchainCreateInfoKHR();
|
||||||
swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
|
swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
|
||||||
@ -1809,7 +1809,7 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create a staging buffer to transfer the data with
|
// Create a staging buffer to transfer the data with
|
||||||
VkDeviceSize imageSize = imageData.getSize().x * imageData.getSize().y * 4;
|
const VkDeviceSize imageSize = imageData.getSize().x * imageData.getSize().y * 4;
|
||||||
|
|
||||||
VkBuffer stagingBuffer = {};
|
VkBuffer stagingBuffer = {};
|
||||||
VkDeviceMemory stagingBufferMemory = {};
|
VkDeviceMemory stagingBufferMemory = {};
|
||||||
@ -2305,7 +2305,7 @@ public:
|
|||||||
vkCmdBindPipeline(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);
|
vkCmdBindPipeline(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);
|
||||||
|
|
||||||
// Bind our vertex buffer
|
// Bind our vertex buffer
|
||||||
VkDeviceSize offset = 0;
|
const VkDeviceSize offset = 0;
|
||||||
|
|
||||||
vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, &vertexBuffer, &offset);
|
vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, &vertexBuffer, &offset);
|
||||||
|
|
||||||
@ -2403,10 +2403,10 @@ public:
|
|||||||
matrixRotateZ(model, sf::degrees(elapsed * 109.0f));
|
matrixRotateZ(model, sf::degrees(elapsed * 109.0f));
|
||||||
|
|
||||||
// Translate the model based on the mouse position
|
// Translate the model based on the mouse position
|
||||||
sf::Vector2f mousePosition = sf::Vector2f(sf::Mouse::getPosition(window));
|
const sf::Vector2f mousePosition = sf::Vector2f(sf::Mouse::getPosition(window));
|
||||||
sf::Vector2f windowSize = sf::Vector2f(window.getSize());
|
const sf::Vector2f windowSize = sf::Vector2f(window.getSize());
|
||||||
float x = std::clamp(mousePosition.x * 2.f / windowSize.x - 1.f, -1.0f, 1.0f) * 2.0f;
|
const float x = std::clamp(mousePosition.x * 2.f / windowSize.x - 1.f, -1.0f, 1.0f) * 2.0f;
|
||||||
float y = std::clamp(-mousePosition.y * 2.f / windowSize.y + 1.f, -1.0f, 1.0f) * 1.5f;
|
const float y = std::clamp(-mousePosition.y * 2.f / windowSize.y + 1.f, -1.0f, 1.0f) * 1.5f;
|
||||||
|
|
||||||
model[3][0] -= x;
|
model[3][0] -= x;
|
||||||
model[3][2] += y;
|
model[3][2] += y;
|
||||||
@ -2458,12 +2458,12 @@ public:
|
|||||||
|
|
||||||
{
|
{
|
||||||
// Get the next image in the swapchain
|
// Get the next image in the swapchain
|
||||||
VkResult result = vkAcquireNextImageKHR(device,
|
const VkResult result = vkAcquireNextImageKHR(device,
|
||||||
swapchain,
|
swapchain,
|
||||||
std::numeric_limits<std::uint64_t>::max(),
|
std::numeric_limits<std::uint64_t>::max(),
|
||||||
imageAvailableSemaphores[currentFrame],
|
imageAvailableSemaphores[currentFrame],
|
||||||
VK_NULL_HANDLE,
|
VK_NULL_HANDLE,
|
||||||
&imageIndex);
|
&imageIndex);
|
||||||
|
|
||||||
// Check if we need to re-create the swapchain (e.g. if the window was resized)
|
// Check if we need to re-create the swapchain (e.g. if the window was resized)
|
||||||
if (result == VK_ERROR_OUT_OF_DATE_KHR)
|
if (result == VK_ERROR_OUT_OF_DATE_KHR)
|
||||||
@ -2482,7 +2482,7 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Wait for the swapchain image to be available in the color attachment stage before submitting the queue
|
// Wait for the swapchain image to be available in the color attachment stage before submitting the queue
|
||||||
VkPipelineStageFlags waitStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
const VkPipelineStageFlags waitStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
||||||
|
|
||||||
// Signal the render finished semaphore once the queue has been processed
|
// Signal the render finished semaphore once the queue has been processed
|
||||||
VkSubmitInfo submitInfo = VkSubmitInfo();
|
VkSubmitInfo submitInfo = VkSubmitInfo();
|
||||||
@ -2514,7 +2514,7 @@ public:
|
|||||||
|
|
||||||
{
|
{
|
||||||
// Queue presentation
|
// Queue presentation
|
||||||
VkResult result = vkQueuePresentKHR(queue, &presentInfo);
|
const VkResult result = vkQueuePresentKHR(queue, &presentInfo);
|
||||||
|
|
||||||
// Check if we need to re-create the swapchain (e.g. if the window was resized)
|
// Check if we need to re-create the swapchain (e.g. if the window was resized)
|
||||||
if ((result == VK_ERROR_OUT_OF_DATE_KHR) || (result == VK_SUBOPTIMAL_KHR) || swapchainOutOfDate)
|
if ((result == VK_ERROR_OUT_OF_DATE_KHR) || (result == VK_SUBOPTIMAL_KHR) || swapchainOutOfDate)
|
||||||
@ -2535,7 +2535,7 @@ public:
|
|||||||
|
|
||||||
void run()
|
void run()
|
||||||
{
|
{
|
||||||
sf::Clock clock;
|
const sf::Clock clock;
|
||||||
|
|
||||||
// Start game loop
|
// Start game loop
|
||||||
while (window.isOpen())
|
while (window.isOpen())
|
||||||
|
@ -122,7 +122,7 @@ int main()
|
|||||||
sprite1.setPosition(sprite1.getOrigin());
|
sprite1.setPosition(sprite1.getOrigin());
|
||||||
|
|
||||||
// Create a clock for measuring elapsed time
|
// Create a clock for measuring elapsed time
|
||||||
sf::Clock clock;
|
const sf::Clock clock;
|
||||||
|
|
||||||
// Loop until a WM_QUIT message is received
|
// Loop until a WM_QUIT message is received
|
||||||
MSG message;
|
MSG message;
|
||||||
@ -137,7 +137,7 @@ int main()
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
float time = clock.getElapsedTime().asSeconds();
|
const float time = clock.getElapsedTime().asSeconds();
|
||||||
|
|
||||||
// Clear views
|
// Clear views
|
||||||
sfmlView1.clear();
|
sfmlView1.clear();
|
||||||
|
@ -68,7 +68,7 @@ int main()
|
|||||||
// Setup a perspective projection
|
// Setup a perspective projection
|
||||||
glMatrixMode(GL_PROJECTION);
|
glMatrixMode(GL_PROJECTION);
|
||||||
glLoadIdentity();
|
glLoadIdentity();
|
||||||
GLfloat ratio = static_cast<float>(window.getSize().x) / static_cast<float>(window.getSize().y);
|
const GLfloat ratio = static_cast<float>(window.getSize().x) / static_cast<float>(window.getSize().y);
|
||||||
#ifdef SFML_OPENGL_ES
|
#ifdef SFML_OPENGL_ES
|
||||||
glFrustumf(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
|
glFrustumf(-ratio, ratio, -1.f, 1.f, 1.f, 500.f);
|
||||||
#else
|
#else
|
||||||
@ -135,7 +135,7 @@ int main()
|
|||||||
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
|
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
|
||||||
|
|
||||||
// Create a clock for measuring the time elapsed
|
// Create a clock for measuring the time elapsed
|
||||||
sf::Clock clock;
|
const sf::Clock clock;
|
||||||
|
|
||||||
// Start the game loop
|
// Start the game loop
|
||||||
while (window.isOpen())
|
while (window.isOpen())
|
||||||
@ -157,7 +157,7 @@ int main()
|
|||||||
glViewport(0, 0, static_cast<GLsizei>(event.size.width), static_cast<GLsizei>(event.size.height));
|
glViewport(0, 0, static_cast<GLsizei>(event.size.width), static_cast<GLsizei>(event.size.height));
|
||||||
glMatrixMode(GL_PROJECTION);
|
glMatrixMode(GL_PROJECTION);
|
||||||
glLoadIdentity();
|
glLoadIdentity();
|
||||||
GLfloat newRatio = static_cast<float>(event.size.width) / static_cast<float>(event.size.height);
|
const GLfloat newRatio = static_cast<float>(event.size.width) / static_cast<float>(event.size.height);
|
||||||
#ifdef SFML_OPENGL_ES
|
#ifdef SFML_OPENGL_ES
|
||||||
glFrustumf(-newRatio, newRatio, -1.f, 1.f, 1.f, 500.f);
|
glFrustumf(-newRatio, newRatio, -1.f, 1.f, 1.f, 500.f);
|
||||||
#else
|
#else
|
||||||
|
@ -53,9 +53,9 @@ constexpr Transform Transform::getInverse() const
|
|||||||
{
|
{
|
||||||
// clang-format off
|
// clang-format off
|
||||||
// Compute the determinant
|
// Compute the determinant
|
||||||
float det = m_matrix[0] * (m_matrix[15] * m_matrix[5] - m_matrix[7] * m_matrix[13]) -
|
const float det = m_matrix[0] * (m_matrix[15] * m_matrix[5] - m_matrix[7] * m_matrix[13]) -
|
||||||
m_matrix[1] * (m_matrix[15] * m_matrix[4] - m_matrix[7] * m_matrix[12]) +
|
m_matrix[1] * (m_matrix[15] * m_matrix[4] - m_matrix[7] * m_matrix[12]) +
|
||||||
m_matrix[3] * (m_matrix[13] * m_matrix[4] - m_matrix[5] * m_matrix[12]);
|
m_matrix[3] * (m_matrix[13] * m_matrix[4] - m_matrix[5] * m_matrix[12]);
|
||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
// Compute the inverse if the determinant is not zero
|
// Compute the inverse if the determinant is not zero
|
||||||
@ -145,9 +145,9 @@ constexpr Transform& Transform::combine(const Transform& transform)
|
|||||||
constexpr Transform& Transform::translate(const Vector2f& offset)
|
constexpr Transform& Transform::translate(const Vector2f& offset)
|
||||||
{
|
{
|
||||||
// clang-format off
|
// clang-format off
|
||||||
Transform translation(1, 0, offset.x,
|
const Transform translation(1, 0, offset.x,
|
||||||
0, 1, offset.y,
|
0, 1, offset.y,
|
||||||
0, 0, 1);
|
0, 0, 1);
|
||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
return combine(translation);
|
return combine(translation);
|
||||||
@ -158,9 +158,9 @@ constexpr Transform& Transform::translate(const Vector2f& offset)
|
|||||||
constexpr Transform& Transform::scale(const Vector2f& factors)
|
constexpr Transform& Transform::scale(const Vector2f& factors)
|
||||||
{
|
{
|
||||||
// clang-format off
|
// clang-format off
|
||||||
Transform scaling(factors.x, 0, 0,
|
const Transform scaling(factors.x, 0, 0,
|
||||||
0, factors.y, 0,
|
0, factors.y, 0,
|
||||||
0, 0, 1);
|
0, 0, 1);
|
||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
return combine(scaling);
|
return combine(scaling);
|
||||||
@ -171,9 +171,9 @@ constexpr Transform& Transform::scale(const Vector2f& factors)
|
|||||||
constexpr Transform& Transform::scale(const Vector2f& factors, const Vector2f& center)
|
constexpr Transform& Transform::scale(const Vector2f& factors, const Vector2f& center)
|
||||||
{
|
{
|
||||||
// clang-format off
|
// clang-format off
|
||||||
Transform scaling(factors.x, 0, center.x * (1 - factors.x),
|
const Transform scaling(factors.x, 0, center.x * (1 - factors.x),
|
||||||
0, factors.y, center.y * (1 - factors.y),
|
0, factors.y, center.y * (1 - factors.y),
|
||||||
0, 0, 1);
|
0, 0, 1);
|
||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
return combine(scaling);
|
return combine(scaling);
|
||||||
|
@ -68,7 +68,7 @@ In Utf<8>::decode(In begin, In end, std::uint32_t& output, std::uint32_t replace
|
|||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
// decode the character
|
// decode the character
|
||||||
int trailingBytes = trailing[static_cast<std::uint8_t>(*begin)];
|
const int trailingBytes = trailing[static_cast<std::uint8_t>(*begin)];
|
||||||
if (trailingBytes < std::distance(begin, end))
|
if (trailingBytes < std::distance(begin, end))
|
||||||
{
|
{
|
||||||
output = 0;
|
output = 0;
|
||||||
@ -177,8 +177,8 @@ Out Utf<8>::fromAnsi(In begin, In end, Out output, const std::locale& locale)
|
|||||||
{
|
{
|
||||||
while (begin < end)
|
while (begin < end)
|
||||||
{
|
{
|
||||||
std::uint32_t codepoint = Utf<32>::decodeAnsi(*begin++, locale);
|
const std::uint32_t codepoint = Utf<32>::decodeAnsi(*begin++, locale);
|
||||||
output = encode(codepoint, output);
|
output = encode(codepoint, output);
|
||||||
}
|
}
|
||||||
|
|
||||||
return output;
|
return output;
|
||||||
@ -301,14 +301,14 @@ Out Utf<8>::toUtf32(In begin, In end, Out output)
|
|||||||
template <typename In>
|
template <typename In>
|
||||||
In Utf<16>::decode(In begin, In end, std::uint32_t& output, std::uint32_t replacement)
|
In Utf<16>::decode(In begin, In end, std::uint32_t& output, std::uint32_t replacement)
|
||||||
{
|
{
|
||||||
std::uint16_t first = *begin++;
|
const std::uint16_t first = *begin++;
|
||||||
|
|
||||||
// If it's a surrogate pair, first convert to a single UTF-32 character
|
// If it's a surrogate pair, first convert to a single UTF-32 character
|
||||||
if ((first >= 0xD800) && (first <= 0xDBFF))
|
if ((first >= 0xD800) && (first <= 0xDBFF))
|
||||||
{
|
{
|
||||||
if (begin < end)
|
if (begin < end)
|
||||||
{
|
{
|
||||||
std::uint32_t second = *begin++;
|
const std::uint32_t second = *begin++;
|
||||||
if ((second >= 0xDC00) && (second <= 0xDFFF))
|
if ((second >= 0xDC00) && (second <= 0xDFFF))
|
||||||
{
|
{
|
||||||
// The second element is valid: convert the two elements to a UTF-32 character
|
// The second element is valid: convert the two elements to a UTF-32 character
|
||||||
|
@ -52,7 +52,7 @@ namespace sf::priv
|
|||||||
void alCheckError(const std::filesystem::path& file, unsigned int line, std::string_view expression)
|
void alCheckError(const std::filesystem::path& file, unsigned int line, std::string_view expression)
|
||||||
{
|
{
|
||||||
// Get the last error
|
// Get the last error
|
||||||
ALenum errorCode = alGetError();
|
const ALenum errorCode = alGetError();
|
||||||
|
|
||||||
if (errorCode != AL_NO_ERROR)
|
if (errorCode != AL_NO_ERROR)
|
||||||
{
|
{
|
||||||
|
@ -51,7 +51,7 @@ namespace sf
|
|||||||
AlResource::AlResource()
|
AlResource::AlResource()
|
||||||
{
|
{
|
||||||
// Protect from concurrent access
|
// Protect from concurrent access
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// If this is the very first resource, trigger the global device initialization
|
// If this is the very first resource, trigger the global device initialization
|
||||||
if (count == 0)
|
if (count == 0)
|
||||||
@ -66,7 +66,7 @@ AlResource::AlResource()
|
|||||||
AlResource::~AlResource()
|
AlResource::~AlResource()
|
||||||
{
|
{
|
||||||
// Protect from concurrent access
|
// Protect from concurrent access
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// Decrement the resources counter
|
// Decrement the resources counter
|
||||||
--count;
|
--count;
|
||||||
|
@ -155,8 +155,8 @@ void Music::setLoopPoints(TimeSpan timePoints)
|
|||||||
// When we apply this change, we need to "reset" this instance and its buffer
|
// When we apply this change, we need to "reset" this instance and its buffer
|
||||||
|
|
||||||
// Get old playing status and position
|
// Get old playing status and position
|
||||||
Status oldStatus = getStatus();
|
const Status oldStatus = getStatus();
|
||||||
Time oldPos = getPlayingOffset();
|
const Time oldPos = getPlayingOffset();
|
||||||
|
|
||||||
// Unload
|
// Unload
|
||||||
stop();
|
stop();
|
||||||
@ -177,11 +177,11 @@ void Music::setLoopPoints(TimeSpan timePoints)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool Music::onGetData(SoundStream::Chunk& data)
|
bool Music::onGetData(SoundStream::Chunk& data)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_mutex);
|
const std::lock_guard lock(m_mutex);
|
||||||
|
|
||||||
std::size_t toFill = m_samples.size();
|
std::size_t toFill = m_samples.size();
|
||||||
std::uint64_t currentOffset = m_file.getSampleOffset();
|
std::uint64_t currentOffset = m_file.getSampleOffset();
|
||||||
std::uint64_t loopEnd = m_loopSpan.offset + m_loopSpan.length;
|
const std::uint64_t loopEnd = m_loopSpan.offset + m_loopSpan.length;
|
||||||
|
|
||||||
// If the loop end is enabled and imminent, request less data.
|
// If the loop end is enabled and imminent, request less data.
|
||||||
// This will trip an "onLoop()" call from the underlying SoundStream,
|
// This will trip an "onLoop()" call from the underlying SoundStream,
|
||||||
@ -203,7 +203,7 @@ bool Music::onGetData(SoundStream::Chunk& data)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Music::onSeek(Time timeOffset)
|
void Music::onSeek(Time timeOffset)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_mutex);
|
const std::lock_guard lock(m_mutex);
|
||||||
m_file.seek(timeOffset);
|
m_file.seek(timeOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -212,8 +212,8 @@ void Music::onSeek(Time timeOffset)
|
|||||||
std::int64_t Music::onLoop()
|
std::int64_t Music::onLoop()
|
||||||
{
|
{
|
||||||
// Called by underlying SoundStream so we can determine where to loop.
|
// Called by underlying SoundStream so we can determine where to loop.
|
||||||
std::lock_guard lock(m_mutex);
|
const std::lock_guard lock(m_mutex);
|
||||||
std::uint64_t currentOffset = m_file.getSampleOffset();
|
const std::uint64_t currentOffset = m_file.getSampleOffset();
|
||||||
if (getLoop() && (m_loopSpan.length != 0) && (currentOffset == m_loopSpan.offset + m_loopSpan.length))
|
if (getLoop() && (m_loopSpan.length != 0) && (currentOffset == m_loopSpan.offset + m_loopSpan.length))
|
||||||
{
|
{
|
||||||
// Looping is enabled, and either we're at the loop end, or we're at the EOF
|
// Looping is enabled, and either we're at the loop end, or we're at the EOF
|
||||||
|
@ -223,9 +223,9 @@ SoundBuffer& SoundBuffer::operator=(const SoundBuffer& right)
|
|||||||
bool SoundBuffer::initialize(InputSoundFile& file)
|
bool SoundBuffer::initialize(InputSoundFile& file)
|
||||||
{
|
{
|
||||||
// Retrieve the sound parameters
|
// Retrieve the sound parameters
|
||||||
std::uint64_t sampleCount = file.getSampleCount();
|
const std::uint64_t sampleCount = file.getSampleCount();
|
||||||
unsigned int channelCount = file.getChannelCount();
|
const unsigned int channelCount = file.getChannelCount();
|
||||||
unsigned int sampleRate = file.getSampleRate();
|
const unsigned int sampleRate = file.getSampleRate();
|
||||||
|
|
||||||
// Read the samples from the provided file
|
// Read the samples from the provided file
|
||||||
m_samples.resize(static_cast<std::size_t>(sampleCount));
|
m_samples.resize(static_cast<std::size_t>(sampleCount));
|
||||||
@ -249,7 +249,7 @@ bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate)
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
// Find the good format according to the number of channels
|
// Find the good format according to the number of channels
|
||||||
ALenum format = priv::AudioDevice::getFormatFromChannelCount(channelCount);
|
const ALenum format = priv::AudioDevice::getFormatFromChannelCount(channelCount);
|
||||||
|
|
||||||
// Check if the format is valid
|
// Check if the format is valid
|
||||||
if (format == 0)
|
if (format == 0)
|
||||||
@ -259,14 +259,14 @@ bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// First make a copy of the list of sounds so we can reattach later
|
// First make a copy of the list of sounds so we can reattach later
|
||||||
SoundList sounds(m_sounds);
|
const SoundList sounds(m_sounds);
|
||||||
|
|
||||||
// Detach the buffer from the sounds that use it (to avoid OpenAL errors)
|
// Detach the buffer from the sounds that use it (to avoid OpenAL errors)
|
||||||
for (Sound* soundPtr : sounds)
|
for (Sound* soundPtr : sounds)
|
||||||
soundPtr->resetBuffer();
|
soundPtr->resetBuffer();
|
||||||
|
|
||||||
// Fill the buffer
|
// Fill the buffer
|
||||||
auto size = static_cast<ALsizei>(m_samples.size() * sizeof(std::int16_t));
|
const auto size = static_cast<ALsizei>(m_samples.size() * sizeof(std::int16_t));
|
||||||
alCheck(alBufferData(m_buffer, format, m_samples.data(), size, static_cast<ALsizei>(sampleRate)));
|
alCheck(alBufferData(m_buffer, format, m_samples.data(), size, static_cast<ALsizei>(sampleRate)));
|
||||||
|
|
||||||
// Compute the duration
|
// Compute the duration
|
||||||
|
@ -41,7 +41,7 @@ FLAC__StreamDecoderReadStatus streamRead(const FLAC__StreamDecoder*, FLAC__byte
|
|||||||
{
|
{
|
||||||
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
||||||
|
|
||||||
std::int64_t count = data->stream->read(buffer, static_cast<std::int64_t>(*bytes));
|
const std::int64_t count = data->stream->read(buffer, static_cast<std::int64_t>(*bytes));
|
||||||
if (count > 0)
|
if (count > 0)
|
||||||
{
|
{
|
||||||
*bytes = static_cast<std::size_t>(count);
|
*bytes = static_cast<std::size_t>(count);
|
||||||
@ -61,7 +61,7 @@ FLAC__StreamDecoderSeekStatus streamSeek(const FLAC__StreamDecoder*, FLAC__uint6
|
|||||||
{
|
{
|
||||||
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
||||||
|
|
||||||
std::int64_t position = data->stream->seek(static_cast<std::int64_t>(absoluteByteOffset));
|
const std::int64_t position = data->stream->seek(static_cast<std::int64_t>(absoluteByteOffset));
|
||||||
if (position >= 0)
|
if (position >= 0)
|
||||||
return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
|
return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
|
||||||
else
|
else
|
||||||
@ -72,7 +72,7 @@ FLAC__StreamDecoderTellStatus streamTell(const FLAC__StreamDecoder*, FLAC__uint6
|
|||||||
{
|
{
|
||||||
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
||||||
|
|
||||||
std::int64_t position = data->stream->tell();
|
const std::int64_t position = data->stream->tell();
|
||||||
if (position >= 0)
|
if (position >= 0)
|
||||||
{
|
{
|
||||||
*absoluteByteOffset = static_cast<FLAC__uint64>(position);
|
*absoluteByteOffset = static_cast<FLAC__uint64>(position);
|
||||||
@ -88,7 +88,7 @@ FLAC__StreamDecoderLengthStatus streamLength(const FLAC__StreamDecoder*, FLAC__u
|
|||||||
{
|
{
|
||||||
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
||||||
|
|
||||||
std::int64_t count = data->stream->getSize();
|
const std::int64_t count = data->stream->getSize();
|
||||||
if (count >= 0)
|
if (count >= 0)
|
||||||
{
|
{
|
||||||
*streamLength = static_cast<FLAC__uint64>(count);
|
*streamLength = static_cast<FLAC__uint64>(count);
|
||||||
@ -115,7 +115,7 @@ FLAC__StreamDecoderWriteStatus streamWrite(const FLAC__StreamDecoder*,
|
|||||||
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
auto* data = static_cast<sf::priv::SoundFileReaderFlac::ClientData*>(clientData);
|
||||||
|
|
||||||
// Reserve memory if we're going to use the leftovers buffer
|
// Reserve memory if we're going to use the leftovers buffer
|
||||||
unsigned int frameSamples = frame->header.blocksize * frame->header.channels;
|
const unsigned int frameSamples = frame->header.blocksize * frame->header.channels;
|
||||||
if (data->remaining < frameSamples)
|
if (data->remaining < frameSamples)
|
||||||
data->leftovers.reserve(static_cast<std::size_t>(frameSamples - data->remaining));
|
data->leftovers.reserve(static_cast<std::size_t>(frameSamples - data->remaining));
|
||||||
|
|
||||||
@ -208,7 +208,7 @@ bool SoundFileReaderFlac::check(InputStream& stream)
|
|||||||
&data);
|
&data);
|
||||||
|
|
||||||
// Read the header
|
// Read the header
|
||||||
bool valid = FLAC__stream_decoder_process_until_end_of_metadata(decoder) != 0;
|
const bool valid = FLAC__stream_decoder_process_until_end_of_metadata(decoder) != 0;
|
||||||
|
|
||||||
// Destroy the decoder
|
// Destroy the decoder
|
||||||
FLAC__stream_decoder_finish(decoder);
|
FLAC__stream_decoder_finish(decoder);
|
||||||
@ -303,7 +303,7 @@ std::uint64_t SoundFileReaderFlac::read(std::int16_t* samples, std::uint64_t max
|
|||||||
assert(m_decoder);
|
assert(m_decoder);
|
||||||
|
|
||||||
// If there are leftovers from previous call, use it first
|
// If there are leftovers from previous call, use it first
|
||||||
std::size_t left = m_clientData.leftovers.size();
|
const std::size_t left = m_clientData.leftovers.size();
|
||||||
if (left > 0)
|
if (left > 0)
|
||||||
{
|
{
|
||||||
if (left > maxCount)
|
if (left > maxCount)
|
||||||
|
@ -69,8 +69,8 @@ std::size_t readCallback(void* ptr, std::size_t size, void* data)
|
|||||||
|
|
||||||
int seekCallback(std::uint64_t offset, void* data)
|
int seekCallback(std::uint64_t offset, void* data)
|
||||||
{
|
{
|
||||||
auto* stream = static_cast<sf::InputStream*>(data);
|
auto* stream = static_cast<sf::InputStream*>(data);
|
||||||
std::int64_t position = stream->seek(static_cast<std::int64_t>(offset));
|
const std::int64_t position = stream->seek(static_cast<std::int64_t>(offset));
|
||||||
return position < 0 ? -1 : 0;
|
return position < 0 ? -1 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -105,7 +105,7 @@ SoundFileReaderOgg::~SoundFileReaderOgg()
|
|||||||
bool SoundFileReaderOgg::open(InputStream& stream, Info& info)
|
bool SoundFileReaderOgg::open(InputStream& stream, Info& info)
|
||||||
{
|
{
|
||||||
// Open the Vorbis stream
|
// Open the Vorbis stream
|
||||||
int status = ov_open_callbacks(&stream, &m_vorbis, nullptr, 0, callbacks);
|
const int status = ov_open_callbacks(&stream, &m_vorbis, nullptr, 0, callbacks);
|
||||||
if (status < 0)
|
if (status < 0)
|
||||||
{
|
{
|
||||||
err() << "Failed to open Vorbis file for reading" << std::endl;
|
err() << "Failed to open Vorbis file for reading" << std::endl;
|
||||||
@ -143,11 +143,11 @@ std::uint64_t SoundFileReaderOgg::read(std::int16_t* samples, std::uint64_t maxC
|
|||||||
std::uint64_t count = 0;
|
std::uint64_t count = 0;
|
||||||
while (count < maxCount)
|
while (count < maxCount)
|
||||||
{
|
{
|
||||||
int bytesToRead = static_cast<int>(maxCount - count) * static_cast<int>(sizeof(std::int16_t));
|
const int bytesToRead = static_cast<int>(maxCount - count) * static_cast<int>(sizeof(std::int16_t));
|
||||||
long bytesRead = ov_read(&m_vorbis, reinterpret_cast<char*>(samples), bytesToRead, 0, 2, 1, nullptr);
|
const long bytesRead = ov_read(&m_vorbis, reinterpret_cast<char*>(samples), bytesToRead, 0, 2, 1, nullptr);
|
||||||
if (bytesRead > 0)
|
if (bytesRead > 0)
|
||||||
{
|
{
|
||||||
long samplesRead = bytesRead / static_cast<long>(sizeof(std::int16_t));
|
const long samplesRead = bytesRead / static_cast<long>(sizeof(std::int16_t));
|
||||||
count += static_cast<std::uint64_t>(samplesRead);
|
count += static_cast<std::uint64_t>(samplesRead);
|
||||||
samples += samplesRead;
|
samples += samplesRead;
|
||||||
}
|
}
|
||||||
|
@ -152,7 +152,7 @@ std::uint64_t SoundFileReaderWav::read(std::int16_t* samples, std::uint64_t maxC
|
|||||||
assert(m_stream);
|
assert(m_stream);
|
||||||
|
|
||||||
std::uint64_t count = 0;
|
std::uint64_t count = 0;
|
||||||
auto startPos = static_cast<std::uint64_t>(m_stream->tell());
|
const auto startPos = static_cast<std::uint64_t>(m_stream->tell());
|
||||||
|
|
||||||
// Tracking of m_dataEnd is important to prevent sf::Music from reading
|
// Tracking of m_dataEnd is important to prevent sf::Music from reading
|
||||||
// data until EOF, as WAV files may have metadata at the end.
|
// data until EOF, as WAV files may have metadata at the end.
|
||||||
@ -238,7 +238,7 @@ bool SoundFileReaderWav::parseHeader(Info& info)
|
|||||||
std::uint32_t subChunkSize = 0;
|
std::uint32_t subChunkSize = 0;
|
||||||
if (!decode(*m_stream, subChunkSize))
|
if (!decode(*m_stream, subChunkSize))
|
||||||
return false;
|
return false;
|
||||||
std::int64_t subChunkStart = m_stream->tell();
|
const std::int64_t subChunkStart = m_stream->tell();
|
||||||
if (subChunkStart == -1)
|
if (subChunkStart == -1)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
@ -96,7 +96,7 @@ void SoundFileWriterFlac::write(const std::int16_t* samples, std::uint64_t count
|
|||||||
while (count > 0)
|
while (count > 0)
|
||||||
{
|
{
|
||||||
// Make sure that we don't process too many samples at once
|
// Make sure that we don't process too many samples at once
|
||||||
unsigned int frames = std::min(static_cast<unsigned int>(count / m_channelCount), 10000u);
|
const unsigned int frames = std::min(static_cast<unsigned int>(count / m_channelCount), 10000u);
|
||||||
|
|
||||||
// Convert the samples to 32-bits
|
// Convert the samples to 32-bits
|
||||||
m_samples32.assign(samples, samples + frames * m_channelCount);
|
m_samples32.assign(samples, samples + frames * m_channelCount);
|
||||||
|
@ -133,27 +133,27 @@ bool SoundFileWriterWav::writeHeader(unsigned int sampleRate, unsigned int chann
|
|||||||
// Write the sub-chunk 1 ("format") id and size
|
// Write the sub-chunk 1 ("format") id and size
|
||||||
char fmtChunkId[4] = {'f', 'm', 't', ' '};
|
char fmtChunkId[4] = {'f', 'm', 't', ' '};
|
||||||
m_file.write(fmtChunkId, sizeof(fmtChunkId));
|
m_file.write(fmtChunkId, sizeof(fmtChunkId));
|
||||||
std::uint32_t fmtChunkSize = 16;
|
const std::uint32_t fmtChunkSize = 16;
|
||||||
encode(m_file, fmtChunkSize);
|
encode(m_file, fmtChunkSize);
|
||||||
|
|
||||||
// Write the format (PCM)
|
// Write the format (PCM)
|
||||||
std::uint16_t format = 1;
|
const std::uint16_t format = 1;
|
||||||
encode(m_file, format);
|
encode(m_file, format);
|
||||||
|
|
||||||
// Write the sound attributes
|
// Write the sound attributes
|
||||||
encode(m_file, static_cast<std::uint16_t>(channelCount));
|
encode(m_file, static_cast<std::uint16_t>(channelCount));
|
||||||
encode(m_file, sampleRate);
|
encode(m_file, sampleRate);
|
||||||
std::uint32_t byteRate = sampleRate * channelCount * 2;
|
const std::uint32_t byteRate = sampleRate * channelCount * 2;
|
||||||
encode(m_file, byteRate);
|
encode(m_file, byteRate);
|
||||||
auto blockAlign = static_cast<std::uint16_t>(channelCount * 2);
|
const auto blockAlign = static_cast<std::uint16_t>(channelCount * 2);
|
||||||
encode(m_file, blockAlign);
|
encode(m_file, blockAlign);
|
||||||
std::uint16_t bitsPerSample = 16;
|
const std::uint16_t bitsPerSample = 16;
|
||||||
encode(m_file, bitsPerSample);
|
encode(m_file, bitsPerSample);
|
||||||
|
|
||||||
// Write the sub-chunk 2 ("data") id and size
|
// Write the sub-chunk 2 ("data") id and size
|
||||||
char dataChunkId[4] = {'d', 'a', 't', 'a'};
|
char dataChunkId[4] = {'d', 'a', 't', 'a'};
|
||||||
m_file.write(dataChunkId, sizeof(dataChunkId));
|
m_file.write(dataChunkId, sizeof(dataChunkId));
|
||||||
std::uint32_t dataChunkSize = 0; // placeholder, will be written later
|
const std::uint32_t dataChunkSize = 0; // placeholder, will be written later
|
||||||
encode(m_file, dataChunkSize);
|
encode(m_file, dataChunkSize);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@ -169,7 +169,7 @@ void SoundFileWriterWav::close()
|
|||||||
m_file.flush();
|
m_file.flush();
|
||||||
|
|
||||||
// Update the main chunk size and data sub-chunk size
|
// Update the main chunk size and data sub-chunk size
|
||||||
std::uint32_t fileSize = static_cast<std::uint32_t>(m_file.tellp());
|
const std::uint32_t fileSize = static_cast<std::uint32_t>(m_file.tellp());
|
||||||
m_file.seekp(4);
|
m_file.seekp(4);
|
||||||
encode(m_file, fileSize - 8); // 8 bytes RIFF header
|
encode(m_file, fileSize - 8); // 8 bytes RIFF header
|
||||||
m_file.seekp(40);
|
m_file.seekp(40);
|
||||||
|
@ -90,7 +90,7 @@ bool SoundRecorder::start(unsigned int sampleRate)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Determine the recording format
|
// Determine the recording format
|
||||||
ALCenum format = (m_channelCount == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
|
const ALCenum format = (m_channelCount == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
|
||||||
|
|
||||||
// Open the capture device for capturing 16 bits samples
|
// Open the capture device for capturing 16 bits samples
|
||||||
captureDevice = alcCaptureOpenDevice(m_deviceName.c_str(), sampleRate, format, static_cast<ALCsizei>(sampleRate));
|
captureDevice = alcCaptureOpenDevice(m_deviceName.c_str(), sampleRate, format, static_cast<ALCsizei>(sampleRate));
|
||||||
@ -184,7 +184,7 @@ bool SoundRecorder::setDevice(const std::string& name)
|
|||||||
awaitCapturingThread();
|
awaitCapturingThread();
|
||||||
|
|
||||||
// Determine the recording format
|
// Determine the recording format
|
||||||
ALCenum format = (m_channelCount == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
|
const ALCenum format = (m_channelCount == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
|
||||||
|
|
||||||
// Open the requested capture device for capturing 16 bits samples
|
// Open the requested capture device for capturing 16 bits samples
|
||||||
captureDevice = alcCaptureOpenDevice(m_deviceName.c_str(), m_sampleRate, format, static_cast<ALCsizei>(m_sampleRate));
|
captureDevice = alcCaptureOpenDevice(m_deviceName.c_str(), m_sampleRate, format, static_cast<ALCsizei>(m_sampleRate));
|
||||||
|
@ -69,7 +69,7 @@ void SoundStream::initialize(unsigned int channelCount, unsigned int sampleRate)
|
|||||||
m_samplesProcessed = 0;
|
m_samplesProcessed = 0;
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
m_isStreaming = false;
|
m_isStreaming = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -101,7 +101,7 @@ void SoundStream::play()
|
|||||||
Status threadStartState = Stopped;
|
Status threadStartState = Stopped;
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
|
|
||||||
isStreaming = m_isStreaming;
|
isStreaming = m_isStreaming;
|
||||||
threadStartState = m_threadStartState;
|
threadStartState = m_threadStartState;
|
||||||
@ -111,7 +111,7 @@ void SoundStream::play()
|
|||||||
if (isStreaming && (threadStartState == Paused))
|
if (isStreaming && (threadStartState == Paused))
|
||||||
{
|
{
|
||||||
// If the sound is paused, resume it
|
// If the sound is paused, resume it
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
m_threadStartState = Playing;
|
m_threadStartState = Playing;
|
||||||
alCheck(alSourcePlay(m_source));
|
alCheck(alSourcePlay(m_source));
|
||||||
return;
|
return;
|
||||||
@ -138,7 +138,7 @@ void SoundStream::pause()
|
|||||||
{
|
{
|
||||||
// Handle pause() being called before the thread has started
|
// Handle pause() being called before the thread has started
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
|
|
||||||
if (!m_isStreaming)
|
if (!m_isStreaming)
|
||||||
return;
|
return;
|
||||||
@ -183,7 +183,7 @@ SoundStream::Status SoundStream::getStatus() const
|
|||||||
// To compensate for the lag between play() and alSourceplay()
|
// To compensate for the lag between play() and alSourceplay()
|
||||||
if (status == Stopped)
|
if (status == Stopped)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
|
|
||||||
if (m_isStreaming)
|
if (m_isStreaming)
|
||||||
status = m_threadStartState;
|
status = m_threadStartState;
|
||||||
@ -197,7 +197,7 @@ SoundStream::Status SoundStream::getStatus() const
|
|||||||
void SoundStream::setPlayingOffset(Time timeOffset)
|
void SoundStream::setPlayingOffset(Time timeOffset)
|
||||||
{
|
{
|
||||||
// Get old playing status
|
// Get old playing status
|
||||||
Status oldStatus = getStatus();
|
const Status oldStatus = getStatus();
|
||||||
|
|
||||||
// Stop the stream
|
// Stop the stream
|
||||||
stop();
|
stop();
|
||||||
@ -267,7 +267,7 @@ void SoundStream::streamData()
|
|||||||
bool requestStop = false;
|
bool requestStop = false;
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
|
|
||||||
// Check if the thread was launched Stopped
|
// Check if the thread was launched Stopped
|
||||||
if (m_threadStartState == Stopped)
|
if (m_threadStartState == Stopped)
|
||||||
@ -289,7 +289,7 @@ void SoundStream::streamData()
|
|||||||
alCheck(alSourcePlay(m_source));
|
alCheck(alSourcePlay(m_source));
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
|
|
||||||
// Check if the thread was launched Paused
|
// Check if the thread was launched Paused
|
||||||
if (m_threadStartState == Paused)
|
if (m_threadStartState == Paused)
|
||||||
@ -299,7 +299,7 @@ void SoundStream::streamData()
|
|||||||
for (;;)
|
for (;;)
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
if (!m_isStreaming)
|
if (!m_isStreaming)
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -315,7 +315,7 @@ void SoundStream::streamData()
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
// End streaming
|
// End streaming
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
m_isStreaming = false;
|
m_isStreaming = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -360,7 +360,7 @@ void SoundStream::streamData()
|
|||||||
<< "and initialize() has been called correctly" << std::endl;
|
<< "and initialize() has been called correctly" << std::endl;
|
||||||
|
|
||||||
// Abort streaming (exit main loop)
|
// Abort streaming (exit main loop)
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
m_isStreaming = false;
|
m_isStreaming = false;
|
||||||
requestStop = true;
|
requestStop = true;
|
||||||
break;
|
break;
|
||||||
@ -383,7 +383,7 @@ void SoundStream::streamData()
|
|||||||
if (alGetLastError() != AL_NO_ERROR)
|
if (alGetLastError() != AL_NO_ERROR)
|
||||||
{
|
{
|
||||||
// Abort streaming (exit main loop)
|
// Abort streaming (exit main loop)
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
m_isStreaming = false;
|
m_isStreaming = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -449,10 +449,10 @@ bool SoundStream::fillAndPushBuffer(unsigned int bufferNum, bool immediateLoop)
|
|||||||
// Fill the buffer if some data was returned
|
// Fill the buffer if some data was returned
|
||||||
if (data.samples && data.sampleCount)
|
if (data.samples && data.sampleCount)
|
||||||
{
|
{
|
||||||
unsigned int buffer = m_buffers[bufferNum];
|
const unsigned int buffer = m_buffers[bufferNum];
|
||||||
|
|
||||||
// Fill the buffer
|
// Fill the buffer
|
||||||
auto size = static_cast<ALsizei>(data.sampleCount * sizeof(std::int16_t));
|
const auto size = static_cast<ALsizei>(data.sampleCount * sizeof(std::int16_t));
|
||||||
alCheck(alBufferData(buffer, m_format, data.samples, size, static_cast<ALsizei>(m_sampleRate)));
|
alCheck(alBufferData(buffer, m_format, data.samples, size, static_cast<ALsizei>(m_sampleRate)));
|
||||||
|
|
||||||
// Push it into the sound queue
|
// Push it into the sound queue
|
||||||
@ -503,7 +503,7 @@ void SoundStream::clearQueue()
|
|||||||
void SoundStream::launchStreamingThread(Status threadStartState)
|
void SoundStream::launchStreamingThread(Status threadStartState)
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
m_isStreaming = true;
|
m_isStreaming = true;
|
||||||
m_threadStartState = threadStartState;
|
m_threadStartState = threadStartState;
|
||||||
}
|
}
|
||||||
@ -518,7 +518,7 @@ void SoundStream::awaitStreamingThread()
|
|||||||
{
|
{
|
||||||
// Request the thread to join
|
// Request the thread to join
|
||||||
{
|
{
|
||||||
std::lock_guard lock(m_threadMutex);
|
const std::lock_guard lock(m_threadMutex);
|
||||||
m_isStreaming = false;
|
m_isStreaming = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -71,7 +71,7 @@ std::size_t CircleShape::getPointCount() const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Vector2f CircleShape::getPoint(std::size_t index) const
|
Vector2f CircleShape::getPoint(std::size_t index) const
|
||||||
{
|
{
|
||||||
Angle angle = static_cast<float>(index) / static_cast<float>(m_pointCount) * sf::degrees(360) - sf::degrees(90);
|
const Angle angle = static_cast<float>(index) / static_cast<float>(m_pointCount) * sf::degrees(360) - sf::degrees(90);
|
||||||
return Vector2f(m_radius, m_radius) + Vector2f(m_radius, angle);
|
return Vector2f(m_radius, m_radius) + Vector2f(m_radius, angle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -54,8 +54,8 @@ namespace
|
|||||||
// FreeType callbacks that operate on a sf::InputStream
|
// FreeType callbacks that operate on a sf::InputStream
|
||||||
unsigned long read(FT_Stream rec, unsigned long offset, unsigned char* buffer, unsigned long count)
|
unsigned long read(FT_Stream rec, unsigned long offset, unsigned char* buffer, unsigned long count)
|
||||||
{
|
{
|
||||||
auto convertedOffset = static_cast<std::int64_t>(offset);
|
const auto convertedOffset = static_cast<std::int64_t>(offset);
|
||||||
auto* stream = static_cast<sf::InputStream*>(rec->descriptor.pointer);
|
auto* stream = static_cast<sf::InputStream*>(rec->descriptor.pointer);
|
||||||
if (stream->seek(convertedOffset) == convertedOffset)
|
if (stream->seek(convertedOffset) == convertedOffset)
|
||||||
{
|
{
|
||||||
if (count > 0)
|
if (count > 0)
|
||||||
@ -350,12 +350,12 @@ const Glyph& Font::getGlyph(std::uint32_t codePoint, unsigned int characterSize,
|
|||||||
GlyphTable& glyphs = loadPage(characterSize).glyphs;
|
GlyphTable& glyphs = loadPage(characterSize).glyphs;
|
||||||
|
|
||||||
// Build the key by combining the glyph index (based on code point), bold flag, and outline thickness
|
// Build the key by combining the glyph index (based on code point), bold flag, and outline thickness
|
||||||
std::uint64_t key = combine(outlineThickness,
|
const std::uint64_t key = combine(outlineThickness,
|
||||||
bold,
|
bold,
|
||||||
FT_Get_Char_Index(m_fontHandles ? m_fontHandles->face : nullptr, codePoint));
|
FT_Get_Char_Index(m_fontHandles ? m_fontHandles->face : nullptr, codePoint));
|
||||||
|
|
||||||
// Search the glyph into the cache
|
// Search the glyph into the cache
|
||||||
if (auto it = glyphs.find(key); it != glyphs.end())
|
if (const auto it = glyphs.find(key); it != glyphs.end())
|
||||||
{
|
{
|
||||||
// Found: just return it
|
// Found: just return it
|
||||||
return it->second;
|
return it->second;
|
||||||
@ -363,7 +363,7 @@ const Glyph& Font::getGlyph(std::uint32_t codePoint, unsigned int characterSize,
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Not found: we have to load it
|
// Not found: we have to load it
|
||||||
Glyph glyph = loadGlyph(codePoint, characterSize, bold, outlineThickness);
|
const Glyph glyph = loadGlyph(codePoint, characterSize, bold, outlineThickness);
|
||||||
return glyphs.emplace(key, glyph).first->second;
|
return glyphs.emplace(key, glyph).first->second;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -388,12 +388,12 @@ float Font::getKerning(std::uint32_t first, std::uint32_t second, unsigned int c
|
|||||||
if (face && setCurrentSize(characterSize))
|
if (face && setCurrentSize(characterSize))
|
||||||
{
|
{
|
||||||
// Convert the characters to indices
|
// Convert the characters to indices
|
||||||
FT_UInt index1 = FT_Get_Char_Index(face, first);
|
const FT_UInt index1 = FT_Get_Char_Index(face, first);
|
||||||
FT_UInt index2 = FT_Get_Char_Index(face, second);
|
const FT_UInt index2 = FT_Get_Char_Index(face, second);
|
||||||
|
|
||||||
// Retrieve position compensation deltas generated by FT_LOAD_FORCE_AUTOHINT flag
|
// Retrieve position compensation deltas generated by FT_LOAD_FORCE_AUTOHINT flag
|
||||||
auto firstRsbDelta = static_cast<float>(getGlyph(first, characterSize, bold).rsbDelta);
|
const auto firstRsbDelta = static_cast<float>(getGlyph(first, characterSize, bold).rsbDelta);
|
||||||
auto secondLsbDelta = static_cast<float>(getGlyph(second, characterSize, bold).lsbDelta);
|
const auto secondLsbDelta = static_cast<float>(getGlyph(second, characterSize, bold).lsbDelta);
|
||||||
|
|
||||||
// Get the kerning vector if present
|
// Get the kerning vector if present
|
||||||
FT_Vector kerning;
|
FT_Vector kerning;
|
||||||
@ -573,8 +573,8 @@ Glyph Font::loadGlyph(std::uint32_t codePoint, unsigned int characterSize, bool
|
|||||||
return glyph;
|
return glyph;
|
||||||
|
|
||||||
// Apply bold and outline (there is no fallback for outline) if necessary -- first technique using outline (highest quality)
|
// Apply bold and outline (there is no fallback for outline) if necessary -- first technique using outline (highest quality)
|
||||||
FT_Pos weight = 1 << 6;
|
const FT_Pos weight = 1 << 6;
|
||||||
bool outline = (glyphDesc->format == FT_GLYPH_FORMAT_OUTLINE);
|
const bool outline = (glyphDesc->format == FT_GLYPH_FORMAT_OUTLINE);
|
||||||
if (outline)
|
if (outline)
|
||||||
{
|
{
|
||||||
if (bold)
|
if (bold)
|
||||||
@ -676,7 +676,7 @@ Glyph Font::loadGlyph(std::uint32_t codePoint, unsigned int characterSize, bool
|
|||||||
for (unsigned int x = padding; x < width - padding; ++x)
|
for (unsigned int x = padding; x < width - padding; ++x)
|
||||||
{
|
{
|
||||||
// The color channels remain white, just fill the alpha channel
|
// The color channels remain white, just fill the alpha channel
|
||||||
std::size_t index = x + y * width;
|
const std::size_t index = x + y * width;
|
||||||
m_pixelBuffer[index * 4 + 3] = ((pixels[(x - padding) / 8]) & (1 << (7 - ((x - padding) % 8)))) ? 255 : 0;
|
m_pixelBuffer[index * 4 + 3] = ((pixels[(x - padding) / 8]) & (1 << (7 - ((x - padding) % 8)))) ? 255 : 0;
|
||||||
}
|
}
|
||||||
pixels += bitmap.pitch;
|
pixels += bitmap.pitch;
|
||||||
@ -690,7 +690,7 @@ Glyph Font::loadGlyph(std::uint32_t codePoint, unsigned int characterSize, bool
|
|||||||
for (unsigned int x = padding; x < width - padding; ++x)
|
for (unsigned int x = padding; x < width - padding; ++x)
|
||||||
{
|
{
|
||||||
// The color channels remain white, just fill the alpha channel
|
// The color channels remain white, just fill the alpha channel
|
||||||
std::size_t index = x + y * width;
|
const std::size_t index = x + y * width;
|
||||||
m_pixelBuffer[index * 4 + 3] = pixels[x - padding];
|
m_pixelBuffer[index * 4 + 3] = pixels[x - padding];
|
||||||
}
|
}
|
||||||
pixels += bitmap.pitch;
|
pixels += bitmap.pitch;
|
||||||
@ -698,10 +698,10 @@ Glyph Font::loadGlyph(std::uint32_t codePoint, unsigned int characterSize, bool
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Write the pixels to the texture
|
// Write the pixels to the texture
|
||||||
unsigned int x = static_cast<unsigned int>(glyph.textureRect.left) - padding;
|
const unsigned int x = static_cast<unsigned int>(glyph.textureRect.left) - padding;
|
||||||
unsigned int y = static_cast<unsigned int>(glyph.textureRect.top) - padding;
|
const unsigned int y = static_cast<unsigned int>(glyph.textureRect.top) - padding;
|
||||||
unsigned int w = static_cast<unsigned int>(glyph.textureRect.width) + 2 * padding;
|
const unsigned int w = static_cast<unsigned int>(glyph.textureRect.width) + 2 * padding;
|
||||||
unsigned int h = static_cast<unsigned int>(glyph.textureRect.height) + 2 * padding;
|
const unsigned int h = static_cast<unsigned int>(glyph.textureRect.height) + 2 * padding;
|
||||||
page.texture.update(m_pixelBuffer.data(), {w, h}, {x, y});
|
page.texture.update(m_pixelBuffer.data(), {w, h}, {x, y});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -721,7 +721,7 @@ IntRect Font::findGlyphRect(Page& page, const Vector2u& size) const
|
|||||||
float bestRatio = 0;
|
float bestRatio = 0;
|
||||||
for (auto it = page.rows.begin(); it != page.rows.end() && !row; ++it)
|
for (auto it = page.rows.begin(); it != page.rows.end() && !row; ++it)
|
||||||
{
|
{
|
||||||
float ratio = static_cast<float>(size.y) / static_cast<float>(it->height);
|
const float ratio = static_cast<float>(size.y) / static_cast<float>(it->height);
|
||||||
|
|
||||||
// Ignore rows that are either too small or too high
|
// Ignore rows that are either too small or too high
|
||||||
if ((ratio < 0.7f) || (ratio > 1.f))
|
if ((ratio < 0.7f) || (ratio > 1.f))
|
||||||
@ -743,11 +743,11 @@ IntRect Font::findGlyphRect(Page& page, const Vector2u& size) const
|
|||||||
// If we didn't find a matching row, create a new one (10% taller than the glyph)
|
// If we didn't find a matching row, create a new one (10% taller than the glyph)
|
||||||
if (!row)
|
if (!row)
|
||||||
{
|
{
|
||||||
unsigned int rowHeight = size.y + size.y / 10;
|
const unsigned int rowHeight = size.y + size.y / 10;
|
||||||
while ((page.nextRow + rowHeight >= page.texture.getSize().y) || (size.x >= page.texture.getSize().x))
|
while ((page.nextRow + rowHeight >= page.texture.getSize().y) || (size.x >= page.texture.getSize().x))
|
||||||
{
|
{
|
||||||
// Not enough space: resize the texture if possible
|
// Not enough space: resize the texture if possible
|
||||||
Vector2u textureSize = page.texture.getSize();
|
const Vector2u textureSize = page.texture.getSize();
|
||||||
if ((textureSize.x * 2 <= Texture::getMaximumSize()) && (textureSize.y * 2 <= Texture::getMaximumSize()))
|
if ((textureSize.x * 2 <= Texture::getMaximumSize()) && (textureSize.y * 2 <= Texture::getMaximumSize()))
|
||||||
{
|
{
|
||||||
// Make the texture 2 times bigger
|
// Make the texture 2 times bigger
|
||||||
@ -794,12 +794,12 @@ bool Font::setCurrentSize(unsigned int characterSize) const
|
|||||||
// only when necessary to avoid killing performances
|
// only when necessary to avoid killing performances
|
||||||
|
|
||||||
// m_fontHandles and m_fontHandles->face are checked to be non-null before calling this method
|
// m_fontHandles and m_fontHandles->face are checked to be non-null before calling this method
|
||||||
FT_Face face = m_fontHandles->face;
|
FT_Face face = m_fontHandles->face;
|
||||||
FT_UShort currentSize = face->size->metrics.x_ppem;
|
const FT_UShort currentSize = face->size->metrics.x_ppem;
|
||||||
|
|
||||||
if (currentSize != characterSize)
|
if (currentSize != characterSize)
|
||||||
{
|
{
|
||||||
FT_Error result = FT_Set_Pixel_Sizes(face, 0, characterSize);
|
const FT_Error result = FT_Set_Pixel_Sizes(face, 0, characterSize);
|
||||||
|
|
||||||
if (result == FT_Err_Invalid_Pixel_Size)
|
if (result == FT_Err_Invalid_Pixel_Size)
|
||||||
{
|
{
|
||||||
|
@ -39,7 +39,7 @@ namespace sf::priv
|
|||||||
void glCheckError(const std::filesystem::path& file, unsigned int line, std::string_view expression)
|
void glCheckError(const std::filesystem::path& file, unsigned int line, std::string_view expression)
|
||||||
{
|
{
|
||||||
// Get the last error
|
// Get the last error
|
||||||
GLenum errorCode = glGetError();
|
const GLenum errorCode = glGetError();
|
||||||
|
|
||||||
if (errorCode != GL_NO_ERROR)
|
if (errorCode != GL_NO_ERROR)
|
||||||
{
|
{
|
||||||
|
@ -227,9 +227,9 @@ void Image::createMaskFromColor(const Color& color, std::uint8_t alpha)
|
|||||||
std::uint8_t* dst = dstPixels + j * 4;
|
std::uint8_t* dst = dstPixels + j * 4;
|
||||||
|
|
||||||
// Interpolate RGBA components using the alpha values of the destination and source pixels
|
// Interpolate RGBA components using the alpha values of the destination and source pixels
|
||||||
std::uint8_t srcAlpha = src[3];
|
const std::uint8_t srcAlpha = src[3];
|
||||||
std::uint8_t dstAlpha = dst[3];
|
const std::uint8_t dstAlpha = dst[3];
|
||||||
auto outAlpha = static_cast<std::uint8_t>(srcAlpha + dstAlpha - srcAlpha * dstAlpha / 255);
|
const auto outAlpha = static_cast<std::uint8_t>(srcAlpha + dstAlpha - srcAlpha * dstAlpha / 255);
|
||||||
|
|
||||||
dst[3] = outAlpha;
|
dst[3] = outAlpha;
|
||||||
|
|
||||||
@ -299,7 +299,7 @@ void Image::flipHorizontally()
|
|||||||
{
|
{
|
||||||
if (!m_pixels.empty())
|
if (!m_pixels.empty())
|
||||||
{
|
{
|
||||||
std::size_t rowSize = m_size.x * 4;
|
const std::size_t rowSize = m_size.x * 4;
|
||||||
|
|
||||||
for (std::size_t y = 0; y < m_size.y; ++y)
|
for (std::size_t y = 0; y < m_size.y; ++y)
|
||||||
{
|
{
|
||||||
@ -324,7 +324,7 @@ void Image::flipVertically()
|
|||||||
{
|
{
|
||||||
if (!m_pixels.empty())
|
if (!m_pixels.empty())
|
||||||
{
|
{
|
||||||
auto rowSize = static_cast<std::vector<std::uint8_t>::iterator::difference_type>(m_size.x * 4);
|
const auto rowSize = static_cast<std::vector<std::uint8_t>::iterator::difference_type>(m_size.x * 4);
|
||||||
|
|
||||||
auto top = m_pixels.begin();
|
auto top = m_pixels.begin();
|
||||||
auto bottom = m_pixels.end() - rowSize;
|
auto bottom = m_pixels.end() - rowSize;
|
||||||
|
@ -286,8 +286,8 @@ bool ImageLoader::saveImageToMemory(const std::string& format,
|
|||||||
{
|
{
|
||||||
// Choose function based on format
|
// Choose function based on format
|
||||||
|
|
||||||
std::string specified = toLower(format);
|
const std::string specified = toLower(format);
|
||||||
const Vector2i convertedSize = Vector2i(size);
|
const Vector2i convertedSize = Vector2i(size);
|
||||||
|
|
||||||
if (specified == "bmp")
|
if (specified == "bmp")
|
||||||
{
|
{
|
||||||
|
@ -59,7 +59,7 @@ std::recursive_mutex mutex;
|
|||||||
// tracking the currently active RenderTarget within a given context
|
// tracking the currently active RenderTarget within a given context
|
||||||
std::uint64_t getUniqueId()
|
std::uint64_t getUniqueId()
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
static std::uint64_t id = 1; // start at 1, zero is "no RenderTarget"
|
static std::uint64_t id = 1; // start at 1, zero is "no RenderTarget"
|
||||||
|
|
||||||
@ -74,7 +74,7 @@ ContextRenderTargetMap contextRenderTargetMap;
|
|||||||
// Check if a RenderTarget with the given ID is active in the current context
|
// Check if a RenderTarget with the given ID is active in the current context
|
||||||
bool isActive(std::uint64_t id)
|
bool isActive(std::uint64_t id)
|
||||||
{
|
{
|
||||||
auto it = contextRenderTargetMap.find(sf::Context::getActiveContextId());
|
const auto it = contextRenderTargetMap.find(sf::Context::getActiveContextId());
|
||||||
|
|
||||||
return (it != contextRenderTargetMap.end()) && (it->second == id);
|
return (it != contextRenderTargetMap.end()) && (it->second == id);
|
||||||
}
|
}
|
||||||
@ -213,10 +213,10 @@ Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point) const
|
|||||||
Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point, const View& view) const
|
Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point, const View& view) const
|
||||||
{
|
{
|
||||||
// First, convert from viewport coordinates to homogeneous coordinates
|
// First, convert from viewport coordinates to homogeneous coordinates
|
||||||
Vector2f normalized;
|
Vector2f normalized;
|
||||||
FloatRect viewport = FloatRect(getViewport(view));
|
const FloatRect viewport = FloatRect(getViewport(view));
|
||||||
normalized.x = -1.f + 2.f * (static_cast<float>(point.x) - viewport.left) / viewport.width;
|
normalized.x = -1.f + 2.f * (static_cast<float>(point.x) - viewport.left) / viewport.width;
|
||||||
normalized.y = 1.f - 2.f * (static_cast<float>(point.y) - viewport.top) / viewport.height;
|
normalized.y = 1.f - 2.f * (static_cast<float>(point.y) - viewport.top) / viewport.height;
|
||||||
|
|
||||||
// Then transform by the inverse of the view matrix
|
// Then transform by the inverse of the view matrix
|
||||||
return view.getInverseTransform().transformPoint(normalized);
|
return view.getInverseTransform().transformPoint(normalized);
|
||||||
@ -234,13 +234,13 @@ Vector2i RenderTarget::mapCoordsToPixel(const Vector2f& point) const
|
|||||||
Vector2i RenderTarget::mapCoordsToPixel(const Vector2f& point, const View& view) const
|
Vector2i RenderTarget::mapCoordsToPixel(const Vector2f& point, const View& view) const
|
||||||
{
|
{
|
||||||
// First, transform the point by the view matrix
|
// First, transform the point by the view matrix
|
||||||
Vector2f normalized = view.getTransform().transformPoint(point);
|
const Vector2f normalized = view.getTransform().transformPoint(point);
|
||||||
|
|
||||||
// Then convert to viewport coordinates
|
// Then convert to viewport coordinates
|
||||||
Vector2i pixel;
|
Vector2i pixel;
|
||||||
FloatRect viewport = FloatRect(getViewport(view));
|
const FloatRect viewport = FloatRect(getViewport(view));
|
||||||
pixel.x = static_cast<int>((normalized.x + 1.f) / 2.f * viewport.width + viewport.left);
|
pixel.x = static_cast<int>((normalized.x + 1.f) / 2.f * viewport.width + viewport.left);
|
||||||
pixel.y = static_cast<int>((-normalized.y + 1.f) / 2.f * viewport.height + viewport.top);
|
pixel.y = static_cast<int>((-normalized.y + 1.f) / 2.f * viewport.height + viewport.top);
|
||||||
|
|
||||||
return pixel;
|
return pixel;
|
||||||
}
|
}
|
||||||
@ -263,7 +263,7 @@ void RenderTarget::draw(const Vertex* vertices, std::size_t vertexCount, Primiti
|
|||||||
if (RenderTargetImpl::isActive(m_id) || setActive(true))
|
if (RenderTargetImpl::isActive(m_id) || setActive(true))
|
||||||
{
|
{
|
||||||
// Check if the vertex count is low enough so that we can pre-transform them
|
// Check if the vertex count is low enough so that we can pre-transform them
|
||||||
bool useVertexCache = (vertexCount <= StatesCache::VertexCacheSize);
|
const bool useVertexCache = (vertexCount <= StatesCache::VertexCacheSize);
|
||||||
|
|
||||||
if (useVertexCache)
|
if (useVertexCache)
|
||||||
{
|
{
|
||||||
@ -280,7 +280,7 @@ void RenderTarget::draw(const Vertex* vertices, std::size_t vertexCount, Primiti
|
|||||||
setupDraw(useVertexCache, states);
|
setupDraw(useVertexCache, states);
|
||||||
|
|
||||||
// Check if texture coordinates array is needed, and update client state accordingly
|
// Check if texture coordinates array is needed, and update client state accordingly
|
||||||
bool enableTexCoordsArray = (states.texture || states.shader);
|
const bool enableTexCoordsArray = (states.texture || states.shader);
|
||||||
if (!m_cache.enable || (enableTexCoordsArray != m_cache.texCoordsArrayEnabled))
|
if (!m_cache.enable || (enableTexCoordsArray != m_cache.texCoordsArrayEnabled))
|
||||||
{
|
{
|
||||||
if (enableTexCoordsArray)
|
if (enableTexCoordsArray)
|
||||||
@ -392,12 +392,12 @@ bool RenderTarget::setActive(bool active)
|
|||||||
{
|
{
|
||||||
// Mark this RenderTarget as active or no longer active in the tracking map
|
// Mark this RenderTarget as active or no longer active in the tracking map
|
||||||
{
|
{
|
||||||
std::lock_guard lock(RenderTargetImpl::mutex);
|
const std::lock_guard lock(RenderTargetImpl::mutex);
|
||||||
|
|
||||||
std::uint64_t contextId = Context::getActiveContextId();
|
const std::uint64_t contextId = Context::getActiveContextId();
|
||||||
|
|
||||||
using RenderTargetImpl::contextRenderTargetMap;
|
using RenderTargetImpl::contextRenderTargetMap;
|
||||||
auto it = contextRenderTargetMap.find(contextId);
|
const auto it = contextRenderTargetMap.find(contextId);
|
||||||
|
|
||||||
if (active)
|
if (active)
|
||||||
{
|
{
|
||||||
@ -435,7 +435,7 @@ void RenderTarget::pushGLStates()
|
|||||||
{
|
{
|
||||||
#ifdef SFML_DEBUG
|
#ifdef SFML_DEBUG
|
||||||
// make sure that the user didn't leave an unchecked OpenGL error
|
// make sure that the user didn't leave an unchecked OpenGL error
|
||||||
GLenum error = glGetError();
|
const GLenum error = glGetError();
|
||||||
if (error != GL_NO_ERROR)
|
if (error != GL_NO_ERROR)
|
||||||
{
|
{
|
||||||
err() << "OpenGL error (" << error << ") detected in user code, "
|
err() << "OpenGL error (" << error << ") detected in user code, "
|
||||||
@ -482,8 +482,8 @@ void RenderTarget::popGLStates()
|
|||||||
void RenderTarget::resetGLStates()
|
void RenderTarget::resetGLStates()
|
||||||
{
|
{
|
||||||
// Check here to make sure a context change does not happen after activate(true)
|
// Check here to make sure a context change does not happen after activate(true)
|
||||||
bool shaderAvailable = Shader::isAvailable();
|
const bool shaderAvailable = Shader::isAvailable();
|
||||||
bool vertexBufferAvailable = VertexBuffer::isAvailable();
|
const bool vertexBufferAvailable = VertexBuffer::isAvailable();
|
||||||
|
|
||||||
// Workaround for states not being properly reset on
|
// Workaround for states not being properly reset on
|
||||||
// macOS unless a context switch really takes place
|
// macOS unless a context switch really takes place
|
||||||
@ -561,8 +561,8 @@ void RenderTarget::initialize()
|
|||||||
void RenderTarget::applyCurrentView()
|
void RenderTarget::applyCurrentView()
|
||||||
{
|
{
|
||||||
// Set the viewport
|
// Set the viewport
|
||||||
IntRect viewport = getViewport(m_view);
|
const IntRect viewport = getViewport(m_view);
|
||||||
int top = static_cast<int>(getSize().y) - (viewport.top + viewport.height);
|
const int top = static_cast<int>(getSize().y) - (viewport.top + viewport.height);
|
||||||
glCheck(glViewport(viewport.left, top, viewport.width, viewport.height));
|
glCheck(glViewport(viewport.left, top, viewport.width, viewport.height));
|
||||||
|
|
||||||
// Set the projection matrix
|
// Set the projection matrix
|
||||||
@ -706,7 +706,7 @@ void RenderTarget::setupDraw(bool useVertexCache, const RenderStates& states)
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
std::uint64_t textureId = states.texture ? states.texture->m_cacheId : 0;
|
const std::uint64_t textureId = states.texture ? states.texture->m_cacheId : 0;
|
||||||
if (textureId != m_cache.lastTextureId)
|
if (textureId != m_cache.lastTextureId)
|
||||||
applyTexture(states.texture);
|
applyTexture(states.texture);
|
||||||
}
|
}
|
||||||
@ -722,7 +722,7 @@ void RenderTarget::drawPrimitives(PrimitiveType type, std::size_t firstVertex, s
|
|||||||
{
|
{
|
||||||
// Find the OpenGL primitive type
|
// Find the OpenGL primitive type
|
||||||
static constexpr GLenum modes[] = {GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN};
|
static constexpr GLenum modes[] = {GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN};
|
||||||
GLenum mode = modes[static_cast<std::size_t>(type)];
|
const GLenum mode = modes[static_cast<std::size_t>(type)];
|
||||||
|
|
||||||
// Draw the primitives
|
// Draw the primitives
|
||||||
glCheck(glDrawArrays(mode, static_cast<GLint>(firstVertex), static_cast<GLsizei>(vertexCount)));
|
glCheck(glDrawArrays(mode, static_cast<GLint>(firstVertex), static_cast<GLsizei>(vertexCount)));
|
||||||
|
@ -86,7 +86,7 @@ bool RenderTextureImplDefault::isSrgb() const
|
|||||||
void RenderTextureImplDefault::updateTexture(unsigned int textureId)
|
void RenderTextureImplDefault::updateTexture(unsigned int textureId)
|
||||||
{
|
{
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
// Copy the rendered pixels to the texture
|
// Copy the rendered pixels to the texture
|
||||||
glCheck(glBindTexture(GL_TEXTURE_2D, textureId));
|
glCheck(glBindTexture(GL_TEXTURE_2D, textureId));
|
||||||
|
@ -65,13 +65,13 @@ std::recursive_mutex mutex;
|
|||||||
// might trigger deletion of its contained stale FBOs
|
// might trigger deletion of its contained stale FBOs
|
||||||
void destroyStaleFBOs()
|
void destroyStaleFBOs()
|
||||||
{
|
{
|
||||||
std::uint64_t contextId = sf::Context::getActiveContextId();
|
const std::uint64_t contextId = sf::Context::getActiveContextId();
|
||||||
|
|
||||||
for (auto it = staleFrameBuffers.begin(); it != staleFrameBuffers.end();)
|
for (auto it = staleFrameBuffers.begin(); it != staleFrameBuffers.end();)
|
||||||
{
|
{
|
||||||
if (it->first == contextId)
|
if (it->first == contextId)
|
||||||
{
|
{
|
||||||
auto frameBuffer = static_cast<GLuint>(it->second);
|
const auto frameBuffer = static_cast<GLuint>(it->second);
|
||||||
glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer));
|
glCheck(GLEXT_glDeleteFramebuffers(1, &frameBuffer));
|
||||||
|
|
||||||
staleFrameBuffers.erase(it++);
|
staleFrameBuffers.erase(it++);
|
||||||
@ -86,9 +86,9 @@ void destroyStaleFBOs()
|
|||||||
// Callback that is called every time a context is destroyed
|
// Callback that is called every time a context is destroyed
|
||||||
void contextDestroyCallback(void* /*arg*/)
|
void contextDestroyCallback(void* /*arg*/)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
std::uint64_t contextId = sf::Context::getActiveContextId();
|
const std::uint64_t contextId = sf::Context::getActiveContextId();
|
||||||
|
|
||||||
// Destroy active frame buffer objects
|
// Destroy active frame buffer objects
|
||||||
for (auto* frameBuffer : frameBuffers)
|
for (auto* frameBuffer : frameBuffers)
|
||||||
@ -97,7 +97,7 @@ void contextDestroyCallback(void* /*arg*/)
|
|||||||
{
|
{
|
||||||
if (it->first == contextId)
|
if (it->first == contextId)
|
||||||
{
|
{
|
||||||
GLuint frameBufferId = it->second;
|
const GLuint frameBufferId = it->second;
|
||||||
glCheck(GLEXT_glDeleteFramebuffers(1, &frameBufferId));
|
glCheck(GLEXT_glDeleteFramebuffers(1, &frameBufferId));
|
||||||
|
|
||||||
// Erase the entry from the RenderTextureImplFBO's map
|
// Erase the entry from the RenderTextureImplFBO's map
|
||||||
@ -119,7 +119,7 @@ namespace sf::priv
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
RenderTextureImplFBO::RenderTextureImplFBO()
|
RenderTextureImplFBO::RenderTextureImplFBO()
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// Register the context destruction callback
|
// Register the context destruction callback
|
||||||
registerContextDestroyCallback(contextDestroyCallback, nullptr);
|
registerContextDestroyCallback(contextDestroyCallback, nullptr);
|
||||||
@ -133,9 +133,9 @@ RenderTextureImplFBO::RenderTextureImplFBO()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
RenderTextureImplFBO::~RenderTextureImplFBO()
|
RenderTextureImplFBO::~RenderTextureImplFBO()
|
||||||
{
|
{
|
||||||
TransientContextLock contextLock;
|
const TransientContextLock contextLock;
|
||||||
|
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// Remove the frame buffer mapping from the set of all active mappings
|
// Remove the frame buffer mapping from the set of all active mappings
|
||||||
frameBuffers.erase(&m_frameBuffers);
|
frameBuffers.erase(&m_frameBuffers);
|
||||||
@ -144,14 +144,14 @@ RenderTextureImplFBO::~RenderTextureImplFBO()
|
|||||||
// Destroy the color buffer
|
// Destroy the color buffer
|
||||||
if (m_colorBuffer)
|
if (m_colorBuffer)
|
||||||
{
|
{
|
||||||
GLuint colorBuffer = m_colorBuffer;
|
const GLuint colorBuffer = m_colorBuffer;
|
||||||
glCheck(GLEXT_glDeleteRenderbuffers(1, &colorBuffer));
|
glCheck(GLEXT_glDeleteRenderbuffers(1, &colorBuffer));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destroy the depth/stencil buffer
|
// Destroy the depth/stencil buffer
|
||||||
if (m_depthStencilBuffer)
|
if (m_depthStencilBuffer)
|
||||||
{
|
{
|
||||||
GLuint depthStencilBuffer = m_depthStencilBuffer;
|
const GLuint depthStencilBuffer = m_depthStencilBuffer;
|
||||||
glCheck(GLEXT_glDeleteRenderbuffers(1, &depthStencilBuffer));
|
glCheck(GLEXT_glDeleteRenderbuffers(1, &depthStencilBuffer));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -170,7 +170,7 @@ RenderTextureImplFBO::~RenderTextureImplFBO()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool RenderTextureImplFBO::isAvailable()
|
bool RenderTextureImplFBO::isAvailable()
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
priv::ensureExtensionsInit();
|
priv::ensureExtensionsInit();
|
||||||
@ -182,7 +182,7 @@ bool RenderTextureImplFBO::isAvailable()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
unsigned int RenderTextureImplFBO::getMaximumAntialiasingLevel()
|
unsigned int RenderTextureImplFBO::getMaximumAntialiasingLevel()
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
GLint samples = 0;
|
GLint samples = 0;
|
||||||
|
|
||||||
@ -210,7 +210,7 @@ bool RenderTextureImplFBO::create(const Vector2u& size, unsigned int textureId,
|
|||||||
m_size = size;
|
m_size = size;
|
||||||
|
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
priv::ensureExtensionsInit();
|
priv::ensureExtensionsInit();
|
||||||
@ -468,7 +468,7 @@ bool RenderTextureImplFBO::createFrameBuffer()
|
|||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// Insert the FBO into our map
|
// Insert the FBO into our map
|
||||||
m_frameBuffers.emplace(Context::getActiveContextId(), frameBuffer);
|
m_frameBuffers.emplace(Context::getActiveContextId(), frameBuffer);
|
||||||
@ -525,7 +525,7 @@ bool RenderTextureImplFBO::createFrameBuffer()
|
|||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// Insert the FBO into our map
|
// Insert the FBO into our map
|
||||||
m_multisampleFrameBuffers.emplace(Context::getActiveContextId(), multisampleFrameBuffer);
|
m_multisampleFrameBuffers.emplace(Context::getActiveContextId(), multisampleFrameBuffer);
|
||||||
@ -576,7 +576,7 @@ bool RenderTextureImplFBO::activate(bool active)
|
|||||||
// If none is found, there is no FBO corresponding to the
|
// If none is found, there is no FBO corresponding to the
|
||||||
// currently active context so we will have to create a new FBO
|
// currently active context so we will have to create a new FBO
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
std::unordered_map<std::uint64_t, unsigned int>::iterator it;
|
std::unordered_map<std::uint64_t, unsigned int>::iterator it;
|
||||||
|
|
||||||
@ -628,12 +628,12 @@ void RenderTextureImplFBO::updateTexture(unsigned int)
|
|||||||
// are already available within the current context
|
// are already available within the current context
|
||||||
if (m_multisample && m_size.x && m_size.y && activate(true))
|
if (m_multisample && m_size.x && m_size.y && activate(true))
|
||||||
{
|
{
|
||||||
std::uint64_t contextId = Context::getActiveContextId();
|
const std::uint64_t contextId = Context::getActiveContextId();
|
||||||
|
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
auto frameBufferIt = m_frameBuffers.find(contextId);
|
const auto frameBufferIt = m_frameBuffers.find(contextId);
|
||||||
auto multisampleIt = m_multisampleFrameBuffers.find(contextId);
|
const auto multisampleIt = m_multisampleFrameBuffers.find(contextId);
|
||||||
|
|
||||||
if ((frameBufferIt != m_frameBuffers.end()) && (multisampleIt != m_multisampleFrameBuffers.end()))
|
if ((frameBufferIt != m_frameBuffers.end()) && (multisampleIt != m_multisampleFrameBuffers.end()))
|
||||||
{
|
{
|
||||||
|
@ -74,7 +74,7 @@ GLint checkMaxTextureUnits()
|
|||||||
// Retrieve the maximum number of texture units available
|
// Retrieve the maximum number of texture units available
|
||||||
std::size_t getMaxTextureUnits()
|
std::size_t getMaxTextureUnits()
|
||||||
{
|
{
|
||||||
static GLint maxUnits = checkMaxTextureUnits();
|
static const GLint maxUnits = checkMaxTextureUnits();
|
||||||
return static_cast<std::size_t>(maxUnits);
|
return static_cast<std::size_t>(maxUnits);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,7 +85,7 @@ bool getFileContents(const std::filesystem::path& filename, std::vector<char>& b
|
|||||||
if (file)
|
if (file)
|
||||||
{
|
{
|
||||||
file.seekg(0, std::ios_base::end);
|
file.seekg(0, std::ios_base::end);
|
||||||
std::ifstream::pos_type size = file.tellg();
|
const std::ifstream::pos_type size = file.tellg();
|
||||||
if (size > 0)
|
if (size > 0)
|
||||||
{
|
{
|
||||||
file.seekg(0, std::ios_base::beg);
|
file.seekg(0, std::ios_base::beg);
|
||||||
@ -104,8 +104,8 @@ bool getFileContents(const std::filesystem::path& filename, std::vector<char>& b
|
|||||||
// Read the contents of a stream into an array of char
|
// Read the contents of a stream into an array of char
|
||||||
bool getStreamContents(sf::InputStream& stream, std::vector<char>& buffer)
|
bool getStreamContents(sf::InputStream& stream, std::vector<char>& buffer)
|
||||||
{
|
{
|
||||||
bool success = true;
|
bool success = true;
|
||||||
std::int64_t size = stream.getSize();
|
const std::int64_t size = stream.getSize();
|
||||||
if (size > 0)
|
if (size > 0)
|
||||||
{
|
{
|
||||||
buffer.resize(static_cast<std::size_t>(size));
|
buffer.resize(static_cast<std::size_t>(size));
|
||||||
@ -116,8 +116,8 @@ bool getStreamContents(sf::InputStream& stream, std::vector<char>& buffer)
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::int64_t read = stream.read(buffer.data(), size);
|
const std::int64_t read = stream.read(buffer.data(), size);
|
||||||
success = (read == size);
|
success = (read == size);
|
||||||
}
|
}
|
||||||
buffer.push_back('\0');
|
buffer.push_back('\0');
|
||||||
return success;
|
return success;
|
||||||
@ -240,7 +240,7 @@ Shader::Shader() = default;
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Shader::~Shader()
|
Shader::~Shader()
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Destroy effect program
|
// Destroy effect program
|
||||||
if (m_shaderProgram)
|
if (m_shaderProgram)
|
||||||
@ -267,7 +267,7 @@ Shader& Shader::operator=(Shader&& right) noexcept
|
|||||||
// Explicit scope for RAII
|
// Explicit scope for RAII
|
||||||
{
|
{
|
||||||
// Destroy effect program
|
// Destroy effect program
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
if (m_shaderProgram)
|
if (m_shaderProgram)
|
||||||
glCheck(GLEXT_glDeleteObject(castToGlHandle(m_shaderProgram)));
|
glCheck(GLEXT_glDeleteObject(castToGlHandle(m_shaderProgram)));
|
||||||
}
|
}
|
||||||
@ -469,7 +469,7 @@ bool Shader::loadFromStream(InputStream& vertexShaderStream, InputStream& geomet
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, float x)
|
void Shader::setUniform(const std::string& name, float x)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform1f(binder.location, x));
|
glCheck(GLEXT_glUniform1f(binder.location, x));
|
||||||
}
|
}
|
||||||
@ -478,7 +478,7 @@ void Shader::setUniform(const std::string& name, float x)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, const Glsl::Vec2& v)
|
void Shader::setUniform(const std::string& name, const Glsl::Vec2& v)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform2f(binder.location, v.x, v.y));
|
glCheck(GLEXT_glUniform2f(binder.location, v.x, v.y));
|
||||||
}
|
}
|
||||||
@ -487,7 +487,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Vec2& v)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, const Glsl::Vec3& v)
|
void Shader::setUniform(const std::string& name, const Glsl::Vec3& v)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform3f(binder.location, v.x, v.y, v.z));
|
glCheck(GLEXT_glUniform3f(binder.location, v.x, v.y, v.z));
|
||||||
}
|
}
|
||||||
@ -496,7 +496,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Vec3& v)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, const Glsl::Vec4& v)
|
void Shader::setUniform(const std::string& name, const Glsl::Vec4& v)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform4f(binder.location, v.x, v.y, v.z, v.w));
|
glCheck(GLEXT_glUniform4f(binder.location, v.x, v.y, v.z, v.w));
|
||||||
}
|
}
|
||||||
@ -505,7 +505,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Vec4& v)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, int x)
|
void Shader::setUniform(const std::string& name, int x)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform1i(binder.location, x));
|
glCheck(GLEXT_glUniform1i(binder.location, x));
|
||||||
}
|
}
|
||||||
@ -514,7 +514,7 @@ void Shader::setUniform(const std::string& name, int x)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, const Glsl::Ivec2& v)
|
void Shader::setUniform(const std::string& name, const Glsl::Ivec2& v)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform2i(binder.location, v.x, v.y));
|
glCheck(GLEXT_glUniform2i(binder.location, v.x, v.y));
|
||||||
}
|
}
|
||||||
@ -523,7 +523,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Ivec2& v)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, const Glsl::Ivec3& v)
|
void Shader::setUniform(const std::string& name, const Glsl::Ivec3& v)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform3i(binder.location, v.x, v.y, v.z));
|
glCheck(GLEXT_glUniform3i(binder.location, v.x, v.y, v.z));
|
||||||
}
|
}
|
||||||
@ -532,7 +532,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Ivec3& v)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, const Glsl::Ivec4& v)
|
void Shader::setUniform(const std::string& name, const Glsl::Ivec4& v)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform4i(binder.location, v.x, v.y, v.z, v.w));
|
glCheck(GLEXT_glUniform4i(binder.location, v.x, v.y, v.z, v.w));
|
||||||
}
|
}
|
||||||
@ -569,7 +569,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Bvec4& v)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, const Glsl::Mat3& matrix)
|
void Shader::setUniform(const std::string& name, const Glsl::Mat3& matrix)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniformMatrix3fv(binder.location, 1, GL_FALSE, matrix.array));
|
glCheck(GLEXT_glUniformMatrix3fv(binder.location, 1, GL_FALSE, matrix.array));
|
||||||
}
|
}
|
||||||
@ -578,7 +578,7 @@ void Shader::setUniform(const std::string& name, const Glsl::Mat3& matrix)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniform(const std::string& name, const Glsl::Mat4& matrix)
|
void Shader::setUniform(const std::string& name, const Glsl::Mat4& matrix)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniformMatrix4fv(binder.location, 1, GL_FALSE, matrix.array));
|
glCheck(GLEXT_glUniformMatrix4fv(binder.location, 1, GL_FALSE, matrix.array));
|
||||||
}
|
}
|
||||||
@ -589,14 +589,14 @@ void Shader::setUniform(const std::string& name, const Texture& texture)
|
|||||||
{
|
{
|
||||||
if (m_shaderProgram)
|
if (m_shaderProgram)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Find the location of the variable in the shader
|
// Find the location of the variable in the shader
|
||||||
int location = getUniformLocation(name);
|
const int location = getUniformLocation(name);
|
||||||
if (location != -1)
|
if (location != -1)
|
||||||
{
|
{
|
||||||
// Store the location -> texture mapping
|
// Store the location -> texture mapping
|
||||||
auto it = m_textures.find(location);
|
const auto it = m_textures.find(location);
|
||||||
if (it == m_textures.end())
|
if (it == m_textures.end())
|
||||||
{
|
{
|
||||||
// New entry, make sure there are enough texture units
|
// New entry, make sure there are enough texture units
|
||||||
@ -624,7 +624,7 @@ void Shader::setUniform(const std::string& name, CurrentTextureType)
|
|||||||
{
|
{
|
||||||
if (m_shaderProgram)
|
if (m_shaderProgram)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Find the location of the variable in the shader
|
// Find the location of the variable in the shader
|
||||||
m_currentTexture = getUniformLocation(name);
|
m_currentTexture = getUniformLocation(name);
|
||||||
@ -635,7 +635,7 @@ void Shader::setUniform(const std::string& name, CurrentTextureType)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::setUniformArray(const std::string& name, const float* scalarArray, std::size_t length)
|
void Shader::setUniformArray(const std::string& name, const float* scalarArray, std::size_t length)
|
||||||
{
|
{
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform1fv(binder.location, static_cast<GLsizei>(length), scalarArray));
|
glCheck(GLEXT_glUniform1fv(binder.location, static_cast<GLsizei>(length), scalarArray));
|
||||||
}
|
}
|
||||||
@ -646,7 +646,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Vec2* vectorAr
|
|||||||
{
|
{
|
||||||
std::vector<float> contiguous = flatten(vectorArray, length);
|
std::vector<float> contiguous = flatten(vectorArray, length);
|
||||||
|
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform2fv(binder.location, static_cast<GLsizei>(length), contiguous.data()));
|
glCheck(GLEXT_glUniform2fv(binder.location, static_cast<GLsizei>(length), contiguous.data()));
|
||||||
}
|
}
|
||||||
@ -657,7 +657,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Vec3* vectorAr
|
|||||||
{
|
{
|
||||||
std::vector<float> contiguous = flatten(vectorArray, length);
|
std::vector<float> contiguous = flatten(vectorArray, length);
|
||||||
|
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform3fv(binder.location, static_cast<GLsizei>(length), contiguous.data()));
|
glCheck(GLEXT_glUniform3fv(binder.location, static_cast<GLsizei>(length), contiguous.data()));
|
||||||
}
|
}
|
||||||
@ -668,7 +668,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Vec4* vectorAr
|
|||||||
{
|
{
|
||||||
std::vector<float> contiguous = flatten(vectorArray, length);
|
std::vector<float> contiguous = flatten(vectorArray, length);
|
||||||
|
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniform4fv(binder.location, static_cast<GLsizei>(length), contiguous.data()));
|
glCheck(GLEXT_glUniform4fv(binder.location, static_cast<GLsizei>(length), contiguous.data()));
|
||||||
}
|
}
|
||||||
@ -683,7 +683,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Mat3* matrixAr
|
|||||||
for (std::size_t i = 0; i < length; ++i)
|
for (std::size_t i = 0; i < length; ++i)
|
||||||
priv::copyMatrix(matrixArray[i].array, matrixSize, &contiguous[matrixSize * i]);
|
priv::copyMatrix(matrixArray[i].array, matrixSize, &contiguous[matrixSize * i]);
|
||||||
|
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniformMatrix3fv(binder.location, static_cast<GLsizei>(length), GL_FALSE, contiguous.data()));
|
glCheck(GLEXT_glUniformMatrix3fv(binder.location, static_cast<GLsizei>(length), GL_FALSE, contiguous.data()));
|
||||||
}
|
}
|
||||||
@ -698,7 +698,7 @@ void Shader::setUniformArray(const std::string& name, const Glsl::Mat4* matrixAr
|
|||||||
for (std::size_t i = 0; i < length; ++i)
|
for (std::size_t i = 0; i < length; ++i)
|
||||||
priv::copyMatrix(matrixArray[i].array, matrixSize, &contiguous[matrixSize * i]);
|
priv::copyMatrix(matrixArray[i].array, matrixSize, &contiguous[matrixSize * i]);
|
||||||
|
|
||||||
UniformBinder binder(*this, name);
|
const UniformBinder binder(*this, name);
|
||||||
if (binder.location != -1)
|
if (binder.location != -1)
|
||||||
glCheck(GLEXT_glUniformMatrix4fv(binder.location, static_cast<GLsizei>(length), GL_FALSE, contiguous.data()));
|
glCheck(GLEXT_glUniformMatrix4fv(binder.location, static_cast<GLsizei>(length), GL_FALSE, contiguous.data()));
|
||||||
}
|
}
|
||||||
@ -714,7 +714,7 @@ unsigned int Shader::getNativeHandle() const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shader::bind(const Shader* shader)
|
void Shader::bind(const Shader* shader)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that we can use shaders
|
// Make sure that we can use shaders
|
||||||
if (!isAvailable())
|
if (!isAvailable())
|
||||||
@ -747,7 +747,7 @@ void Shader::bind(const Shader* shader)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool Shader::isAvailable()
|
bool Shader::isAvailable()
|
||||||
{
|
{
|
||||||
std::lock_guard lock(isAvailableMutex);
|
const std::lock_guard lock(isAvailableMutex);
|
||||||
|
|
||||||
static bool checked = false;
|
static bool checked = false;
|
||||||
static bool available = false;
|
static bool available = false;
|
||||||
@ -756,7 +756,7 @@ bool Shader::isAvailable()
|
|||||||
{
|
{
|
||||||
checked = true;
|
checked = true;
|
||||||
|
|
||||||
TransientContextLock contextLock;
|
const TransientContextLock contextLock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
sf::priv::ensureExtensionsInit();
|
sf::priv::ensureExtensionsInit();
|
||||||
@ -772,7 +772,7 @@ bool Shader::isAvailable()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool Shader::isGeometryAvailable()
|
bool Shader::isGeometryAvailable()
|
||||||
{
|
{
|
||||||
std::lock_guard lock(isAvailableMutex);
|
const std::lock_guard lock(isAvailableMutex);
|
||||||
|
|
||||||
static bool checked = false;
|
static bool checked = false;
|
||||||
static bool available = false;
|
static bool available = false;
|
||||||
@ -781,7 +781,7 @@ bool Shader::isGeometryAvailable()
|
|||||||
{
|
{
|
||||||
checked = true;
|
checked = true;
|
||||||
|
|
||||||
TransientContextLock contextLock;
|
const TransientContextLock contextLock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
sf::priv::ensureExtensionsInit();
|
sf::priv::ensureExtensionsInit();
|
||||||
@ -796,7 +796,7 @@ bool Shader::isGeometryAvailable()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCode, const char* fragmentShaderCode)
|
bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCode, const char* fragmentShaderCode)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// First make sure that we can use shaders
|
// First make sure that we can use shaders
|
||||||
if (!isAvailable())
|
if (!isAvailable())
|
||||||
@ -861,7 +861,7 @@ bool Shader::compile(const char* vertexShaderCode, const char* geometryShaderCod
|
|||||||
if (geometryShaderCode)
|
if (geometryShaderCode)
|
||||||
{
|
{
|
||||||
// Create and compile the shader
|
// Create and compile the shader
|
||||||
GLEXT_GLhandle geometryShader = GLEXT_glCreateShaderObject(GLEXT_GL_GEOMETRY_SHADER);
|
const GLEXT_GLhandle geometryShader = GLEXT_glCreateShaderObject(GLEXT_GL_GEOMETRY_SHADER);
|
||||||
glCheck(GLEXT_glShaderSource(geometryShader, 1, &geometryShaderCode, nullptr));
|
glCheck(GLEXT_glShaderSource(geometryShader, 1, &geometryShaderCode, nullptr));
|
||||||
glCheck(GLEXT_glCompileShader(geometryShader));
|
glCheck(GLEXT_glCompileShader(geometryShader));
|
||||||
|
|
||||||
@ -941,7 +941,7 @@ void Shader::bindTextures() const
|
|||||||
auto it = m_textures.begin();
|
auto it = m_textures.begin();
|
||||||
for (std::size_t i = 0; i < m_textures.size(); ++i)
|
for (std::size_t i = 0; i < m_textures.size(); ++i)
|
||||||
{
|
{
|
||||||
auto index = static_cast<GLsizei>(i + 1);
|
const auto index = static_cast<GLsizei>(i + 1);
|
||||||
glCheck(GLEXT_glUniform1i(it->first, index));
|
glCheck(GLEXT_glUniform1i(it->first, index));
|
||||||
glCheck(GLEXT_glActiveTexture(GLEXT_GL_TEXTURE0 + static_cast<GLenum>(index)));
|
glCheck(GLEXT_glActiveTexture(GLEXT_GL_TEXTURE0 + static_cast<GLenum>(index)));
|
||||||
Texture::bind(it->second);
|
Texture::bind(it->second);
|
||||||
@ -957,7 +957,7 @@ void Shader::bindTextures() const
|
|||||||
int Shader::getUniformLocation(const std::string& name)
|
int Shader::getUniformLocation(const std::string& name)
|
||||||
{
|
{
|
||||||
// Check the cache
|
// Check the cache
|
||||||
if (auto it = m_uniforms.find(name); it != m_uniforms.end())
|
if (const auto it = m_uniforms.find(name); it != m_uniforms.end())
|
||||||
{
|
{
|
||||||
// Already in cache, return it
|
// Already in cache, return it
|
||||||
return it->second;
|
return it->second;
|
||||||
@ -965,7 +965,7 @@ int Shader::getUniformLocation(const std::string& name)
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Not in cache, request the location from OpenGL
|
// Not in cache, request the location from OpenGL
|
||||||
int location = GLEXT_glGetUniformLocation(castToGlHandle(m_shaderProgram), name.c_str());
|
const int location = GLEXT_glGetUniformLocation(castToGlHandle(m_shaderProgram), name.c_str());
|
||||||
m_uniforms.emplace(name, location);
|
m_uniforms.emplace(name, location);
|
||||||
|
|
||||||
if (location == -1)
|
if (location == -1)
|
||||||
|
@ -38,7 +38,7 @@ namespace
|
|||||||
sf::Vector2f computeNormal(const sf::Vector2f& p1, const sf::Vector2f& p2)
|
sf::Vector2f computeNormal(const sf::Vector2f& p1, const sf::Vector2f& p2)
|
||||||
{
|
{
|
||||||
sf::Vector2f normal = (p2 - p1).perpendicular();
|
sf::Vector2f normal = (p2 - p1).perpendicular();
|
||||||
float length = normal.length();
|
const float length = normal.length();
|
||||||
if (length != 0.f)
|
if (length != 0.f)
|
||||||
normal /= length;
|
normal /= length;
|
||||||
return normal;
|
return normal;
|
||||||
@ -152,7 +152,7 @@ Shape::Shape() = default;
|
|||||||
void Shape::update()
|
void Shape::update()
|
||||||
{
|
{
|
||||||
// Get the total number of points of the shape
|
// Get the total number of points of the shape
|
||||||
std::size_t count = getPointCount();
|
const std::size_t count = getPointCount();
|
||||||
if (count < 3)
|
if (count < 3)
|
||||||
{
|
{
|
||||||
m_vertices.resize(0);
|
m_vertices.resize(0);
|
||||||
@ -217,13 +217,16 @@ void Shape::updateFillColors()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Shape::updateTexCoords()
|
void Shape::updateTexCoords()
|
||||||
{
|
{
|
||||||
FloatRect convertedTextureRect(m_textureRect);
|
const FloatRect convertedTextureRect(m_textureRect);
|
||||||
|
|
||||||
for (std::size_t i = 0; i < m_vertices.getVertexCount(); ++i)
|
for (std::size_t i = 0; i < m_vertices.getVertexCount(); ++i)
|
||||||
{
|
{
|
||||||
float xratio = m_insideBounds.width > 0 ? (m_vertices[i].position.x - m_insideBounds.left) / m_insideBounds.width : 0;
|
const float xratio = m_insideBounds.width > 0
|
||||||
float yratio = m_insideBounds.height > 0 ? (m_vertices[i].position.y - m_insideBounds.top) / m_insideBounds.height
|
? (m_vertices[i].position.x - m_insideBounds.left) / m_insideBounds.width
|
||||||
: 0;
|
: 0;
|
||||||
|
const float yratio = m_insideBounds.height > 0
|
||||||
|
? (m_vertices[i].position.y - m_insideBounds.top) / m_insideBounds.height
|
||||||
|
: 0;
|
||||||
m_vertices[i].texCoords.x = convertedTextureRect.left + convertedTextureRect.width * xratio;
|
m_vertices[i].texCoords.x = convertedTextureRect.left + convertedTextureRect.width * xratio;
|
||||||
m_vertices[i].texCoords.y = convertedTextureRect.top + convertedTextureRect.height * yratio;
|
m_vertices[i].texCoords.y = convertedTextureRect.top + convertedTextureRect.height * yratio;
|
||||||
}
|
}
|
||||||
@ -241,17 +244,17 @@ void Shape::updateOutline()
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::size_t count = m_vertices.getVertexCount() - 2;
|
const std::size_t count = m_vertices.getVertexCount() - 2;
|
||||||
m_outlineVertices.resize((count + 1) * 2);
|
m_outlineVertices.resize((count + 1) * 2);
|
||||||
|
|
||||||
for (std::size_t i = 0; i < count; ++i)
|
for (std::size_t i = 0; i < count; ++i)
|
||||||
{
|
{
|
||||||
std::size_t index = i + 1;
|
const std::size_t index = i + 1;
|
||||||
|
|
||||||
// Get the two segments shared by the current point
|
// Get the two segments shared by the current point
|
||||||
Vector2f p0 = (i == 0) ? m_vertices[count].position : m_vertices[index - 1].position;
|
const Vector2f p0 = (i == 0) ? m_vertices[count].position : m_vertices[index - 1].position;
|
||||||
Vector2f p1 = m_vertices[index].position;
|
const Vector2f p1 = m_vertices[index].position;
|
||||||
Vector2f p2 = m_vertices[index + 1].position;
|
const Vector2f p2 = m_vertices[index + 1].position;
|
||||||
|
|
||||||
// Compute their normal
|
// Compute their normal
|
||||||
Vector2f n1 = computeNormal(p0, p1);
|
Vector2f n1 = computeNormal(p0, p1);
|
||||||
@ -265,8 +268,8 @@ void Shape::updateOutline()
|
|||||||
n2 = -n2;
|
n2 = -n2;
|
||||||
|
|
||||||
// Combine them to get the extrusion direction
|
// Combine them to get the extrusion direction
|
||||||
float factor = 1.f + (n1.x * n2.x + n1.y * n2.y);
|
const float factor = 1.f + (n1.x * n2.x + n1.y * n2.y);
|
||||||
Vector2f normal = (n1 + n2) / factor;
|
const Vector2f normal = (n1 + n2) / factor;
|
||||||
|
|
||||||
// Update the outline points
|
// Update the outline points
|
||||||
m_outlineVertices[i * 2 + 0].position = p1;
|
m_outlineVertices[i * 2 + 0].position = p1;
|
||||||
|
@ -113,8 +113,8 @@ const Color& Sprite::getColor() const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
FloatRect Sprite::getLocalBounds() const
|
FloatRect Sprite::getLocalBounds() const
|
||||||
{
|
{
|
||||||
auto width = static_cast<float>(std::abs(m_textureRect.width));
|
const auto width = static_cast<float>(std::abs(m_textureRect.width));
|
||||||
auto height = static_cast<float>(std::abs(m_textureRect.height));
|
const auto height = static_cast<float>(std::abs(m_textureRect.height));
|
||||||
|
|
||||||
return FloatRect({0.f, 0.f}, {width, height});
|
return FloatRect({0.f, 0.f}, {width, height});
|
||||||
}
|
}
|
||||||
@ -143,7 +143,7 @@ void Sprite::draw(RenderTarget& target, const RenderStates& states) const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Sprite::updatePositions()
|
void Sprite::updatePositions()
|
||||||
{
|
{
|
||||||
FloatRect bounds = getLocalBounds();
|
const FloatRect bounds = getLocalBounds();
|
||||||
|
|
||||||
m_vertices[0].position = Vector2f(0, 0);
|
m_vertices[0].position = Vector2f(0, 0);
|
||||||
m_vertices[1].position = Vector2f(0, bounds.height);
|
m_vertices[1].position = Vector2f(0, bounds.height);
|
||||||
@ -155,12 +155,12 @@ void Sprite::updatePositions()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Sprite::updateTexCoords()
|
void Sprite::updateTexCoords()
|
||||||
{
|
{
|
||||||
FloatRect convertedTextureRect(m_textureRect);
|
const FloatRect convertedTextureRect(m_textureRect);
|
||||||
|
|
||||||
float left = convertedTextureRect.left;
|
const float left = convertedTextureRect.left;
|
||||||
float right = left + convertedTextureRect.width;
|
const float right = left + convertedTextureRect.width;
|
||||||
float top = convertedTextureRect.top;
|
const float top = convertedTextureRect.top;
|
||||||
float bottom = top + convertedTextureRect.height;
|
const float bottom = top + convertedTextureRect.height;
|
||||||
|
|
||||||
m_vertices[0].texCoords = Vector2f(left, top);
|
m_vertices[0].texCoords = Vector2f(left, top);
|
||||||
m_vertices[1].texCoords = Vector2f(left, bottom);
|
m_vertices[1].texCoords = Vector2f(left, bottom);
|
||||||
|
@ -47,8 +47,8 @@ void addLine(sf::VertexArray& vertices,
|
|||||||
float thickness,
|
float thickness,
|
||||||
float outlineThickness = 0)
|
float outlineThickness = 0)
|
||||||
{
|
{
|
||||||
float top = std::floor(lineTop + offset - (thickness / 2) + 0.5f);
|
const float top = std::floor(lineTop + offset - (thickness / 2) + 0.5f);
|
||||||
float bottom = top + std::floor(thickness + 0.5f);
|
const float bottom = top + std::floor(thickness + 0.5f);
|
||||||
|
|
||||||
vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1)));
|
vertices.append(sf::Vertex(sf::Vector2f(-outlineThickness, top - outlineThickness), color, sf::Vector2f(1, 1)));
|
||||||
vertices.append(
|
vertices.append(
|
||||||
@ -64,17 +64,17 @@ void addLine(sf::VertexArray& vertices,
|
|||||||
// Add a glyph quad to the vertex array
|
// Add a glyph quad to the vertex array
|
||||||
void addGlyphQuad(sf::VertexArray& vertices, sf::Vector2f position, const sf::Color& color, const sf::Glyph& glyph, float italicShear)
|
void addGlyphQuad(sf::VertexArray& vertices, sf::Vector2f position, const sf::Color& color, const sf::Glyph& glyph, float italicShear)
|
||||||
{
|
{
|
||||||
float padding = 1.0;
|
const float padding = 1.0;
|
||||||
|
|
||||||
float left = glyph.bounds.left - padding;
|
const float left = glyph.bounds.left - padding;
|
||||||
float top = glyph.bounds.top - padding;
|
const float top = glyph.bounds.top - padding;
|
||||||
float right = glyph.bounds.left + glyph.bounds.width + padding;
|
const float right = glyph.bounds.left + glyph.bounds.width + padding;
|
||||||
float bottom = glyph.bounds.top + glyph.bounds.height + padding;
|
const float bottom = glyph.bounds.top + glyph.bounds.height + padding;
|
||||||
|
|
||||||
float u1 = static_cast<float>(glyph.textureRect.left) - padding;
|
const float u1 = static_cast<float>(glyph.textureRect.left) - padding;
|
||||||
float v1 = static_cast<float>(glyph.textureRect.top) - padding;
|
const float v1 = static_cast<float>(glyph.textureRect.top) - padding;
|
||||||
float u2 = static_cast<float>(glyph.textureRect.left + glyph.textureRect.width) + padding;
|
const float u2 = static_cast<float>(glyph.textureRect.left + glyph.textureRect.width) + padding;
|
||||||
float v2 = static_cast<float>(glyph.textureRect.top + glyph.textureRect.height) + padding;
|
const float v2 = static_cast<float>(glyph.textureRect.top + glyph.textureRect.height) + padding;
|
||||||
|
|
||||||
vertices.append(
|
vertices.append(
|
||||||
sf::Vertex(sf::Vector2f(position.x + left - italicShear * top, position.y + top), color, sf::Vector2f(u1, v1)));
|
sf::Vertex(sf::Vector2f(position.x + left - italicShear * top, position.y + top), color, sf::Vector2f(u1, v1)));
|
||||||
@ -304,18 +304,18 @@ Vector2f Text::findCharacterPos(std::size_t index) const
|
|||||||
index = m_string.getSize();
|
index = m_string.getSize();
|
||||||
|
|
||||||
// Precompute the variables needed by the algorithm
|
// Precompute the variables needed by the algorithm
|
||||||
bool isBold = m_style & Bold;
|
const bool isBold = m_style & Bold;
|
||||||
float whitespaceWidth = m_font->getGlyph(U' ', m_characterSize, isBold).advance;
|
float whitespaceWidth = m_font->getGlyph(U' ', m_characterSize, isBold).advance;
|
||||||
float letterSpacing = (whitespaceWidth / 3.f) * (m_letterSpacingFactor - 1.f);
|
const float letterSpacing = (whitespaceWidth / 3.f) * (m_letterSpacingFactor - 1.f);
|
||||||
whitespaceWidth += letterSpacing;
|
whitespaceWidth += letterSpacing;
|
||||||
float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor;
|
const float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor;
|
||||||
|
|
||||||
// Compute the position
|
// Compute the position
|
||||||
Vector2f position;
|
Vector2f position;
|
||||||
std::uint32_t prevChar = 0;
|
std::uint32_t prevChar = 0;
|
||||||
for (std::size_t i = 0; i < index; ++i)
|
for (std::size_t i = 0; i < index; ++i)
|
||||||
{
|
{
|
||||||
std::uint32_t curChar = m_string[i];
|
const std::uint32_t curChar = m_string[i];
|
||||||
|
|
||||||
// Apply the kerning offset
|
// Apply the kerning offset
|
||||||
position.x += m_font->getKerning(prevChar, curChar, m_characterSize, isBold);
|
position.x += m_font->getKerning(prevChar, curChar, m_characterSize, isBold);
|
||||||
@ -404,26 +404,26 @@ void Text::ensureGeometryUpdate() const
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
// Compute values related to the text style
|
// Compute values related to the text style
|
||||||
bool isBold = m_style & Bold;
|
const bool isBold = m_style & Bold;
|
||||||
bool isUnderlined = m_style & Underlined;
|
const bool isUnderlined = m_style & Underlined;
|
||||||
bool isStrikeThrough = m_style & StrikeThrough;
|
const bool isStrikeThrough = m_style & StrikeThrough;
|
||||||
float italicShear = (m_style & Italic) ? sf::degrees(12).asRadians() : 0.f;
|
const float italicShear = (m_style & Italic) ? sf::degrees(12).asRadians() : 0.f;
|
||||||
float underlineOffset = m_font->getUnderlinePosition(m_characterSize);
|
const float underlineOffset = m_font->getUnderlinePosition(m_characterSize);
|
||||||
float underlineThickness = m_font->getUnderlineThickness(m_characterSize);
|
const float underlineThickness = m_font->getUnderlineThickness(m_characterSize);
|
||||||
|
|
||||||
// Compute the location of the strike through dynamically
|
// Compute the location of the strike through dynamically
|
||||||
// We use the center point of the lowercase 'x' glyph as the reference
|
// We use the center point of the lowercase 'x' glyph as the reference
|
||||||
// We reuse the underline thickness as the thickness of the strike through as well
|
// We reuse the underline thickness as the thickness of the strike through as well
|
||||||
FloatRect xBounds = m_font->getGlyph(U'x', m_characterSize, isBold).bounds;
|
const FloatRect xBounds = m_font->getGlyph(U'x', m_characterSize, isBold).bounds;
|
||||||
float strikeThroughOffset = xBounds.top + xBounds.height / 2.f;
|
const float strikeThroughOffset = xBounds.top + xBounds.height / 2.f;
|
||||||
|
|
||||||
// Precompute the variables needed by the algorithm
|
// Precompute the variables needed by the algorithm
|
||||||
float whitespaceWidth = m_font->getGlyph(U' ', m_characterSize, isBold).advance;
|
float whitespaceWidth = m_font->getGlyph(U' ', m_characterSize, isBold).advance;
|
||||||
float letterSpacing = (whitespaceWidth / 3.f) * (m_letterSpacingFactor - 1.f);
|
const float letterSpacing = (whitespaceWidth / 3.f) * (m_letterSpacingFactor - 1.f);
|
||||||
whitespaceWidth += letterSpacing;
|
whitespaceWidth += letterSpacing;
|
||||||
float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor;
|
const float lineSpacing = m_font->getLineSpacing(m_characterSize) * m_lineSpacingFactor;
|
||||||
float x = 0.f;
|
float x = 0.f;
|
||||||
auto y = static_cast<float>(m_characterSize);
|
auto y = static_cast<float>(m_characterSize);
|
||||||
|
|
||||||
// Create one quad for each character
|
// Create one quad for each character
|
||||||
auto minX = static_cast<float>(m_characterSize);
|
auto minX = static_cast<float>(m_characterSize);
|
||||||
@ -433,7 +433,7 @@ void Text::ensureGeometryUpdate() const
|
|||||||
std::uint32_t prevChar = 0;
|
std::uint32_t prevChar = 0;
|
||||||
for (std::size_t i = 0; i < m_string.getSize(); ++i)
|
for (std::size_t i = 0; i < m_string.getSize(); ++i)
|
||||||
{
|
{
|
||||||
std::uint32_t curChar = m_string[i];
|
const std::uint32_t curChar = m_string[i];
|
||||||
|
|
||||||
// Skip the \r char to avoid weird graphical issues
|
// Skip the \r char to avoid weird graphical issues
|
||||||
if (curChar == U'\r')
|
if (curChar == U'\r')
|
||||||
@ -507,10 +507,10 @@ void Text::ensureGeometryUpdate() const
|
|||||||
addGlyphQuad(m_vertices, Vector2f(x, y), m_fillColor, glyph, italicShear);
|
addGlyphQuad(m_vertices, Vector2f(x, y), m_fillColor, glyph, italicShear);
|
||||||
|
|
||||||
// Update the current bounds
|
// Update the current bounds
|
||||||
float left = glyph.bounds.left;
|
const float left = glyph.bounds.left;
|
||||||
float top = glyph.bounds.top;
|
const float top = glyph.bounds.top;
|
||||||
float right = glyph.bounds.left + glyph.bounds.width;
|
const float right = glyph.bounds.left + glyph.bounds.width;
|
||||||
float bottom = glyph.bounds.top + glyph.bounds.height;
|
const float bottom = glyph.bounds.top + glyph.bounds.height;
|
||||||
|
|
||||||
minX = std::min(minX, x + left - italicShear * bottom);
|
minX = std::min(minX, x + left - italicShear * bottom);
|
||||||
maxX = std::max(maxX, x + right - italicShear * top);
|
maxX = std::max(maxX, x + right - italicShear * top);
|
||||||
@ -524,7 +524,7 @@ void Text::ensureGeometryUpdate() const
|
|||||||
// If we're using outline, update the current bounds
|
// If we're using outline, update the current bounds
|
||||||
if (m_outlineThickness != 0)
|
if (m_outlineThickness != 0)
|
||||||
{
|
{
|
||||||
float outline = std::abs(std::ceil(m_outlineThickness));
|
const float outline = std::abs(std::ceil(m_outlineThickness));
|
||||||
minX -= outline;
|
minX -= outline;
|
||||||
maxX += outline;
|
maxX += outline;
|
||||||
minY -= outline;
|
minY -= outline;
|
||||||
|
@ -96,9 +96,9 @@ Texture::~Texture()
|
|||||||
// Destroy the OpenGL texture
|
// Destroy the OpenGL texture
|
||||||
if (m_texture)
|
if (m_texture)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
GLuint texture = m_texture;
|
const GLuint texture = m_texture;
|
||||||
glCheck(glDeleteTextures(1, &texture));
|
glCheck(glDeleteTextures(1, &texture));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -128,9 +128,9 @@ Texture& Texture::operator=(Texture&& right) noexcept
|
|||||||
// Destroy the OpenGL texture
|
// Destroy the OpenGL texture
|
||||||
if (m_texture)
|
if (m_texture)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
GLuint texture = m_texture;
|
const GLuint texture = m_texture;
|
||||||
glCheck(glDeleteTextures(1, &texture));
|
glCheck(glDeleteTextures(1, &texture));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -157,16 +157,16 @@ bool Texture::create(const Vector2u& size)
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
priv::ensureExtensionsInit();
|
priv::ensureExtensionsInit();
|
||||||
|
|
||||||
// Compute the internal texture dimensions depending on NPOT textures support
|
// Compute the internal texture dimensions depending on NPOT textures support
|
||||||
Vector2u actualSize(getValidSize(size.x), getValidSize(size.y));
|
const Vector2u actualSize(getValidSize(size.x), getValidSize(size.y));
|
||||||
|
|
||||||
// Check the maximum texture size
|
// Check the maximum texture size
|
||||||
unsigned int maxSize = getMaximumSize();
|
const unsigned int maxSize = getMaximumSize();
|
||||||
if ((actualSize.x > maxSize) || (actualSize.y > maxSize))
|
if ((actualSize.x > maxSize) || (actualSize.y > maxSize))
|
||||||
{
|
{
|
||||||
err() << "Failed to create texture, its internal size is too high "
|
err() << "Failed to create texture, its internal size is too high "
|
||||||
@ -190,10 +190,10 @@ bool Texture::create(const Vector2u& size)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
static bool textureEdgeClamp = GLEXT_texture_edge_clamp || GLEXT_GL_VERSION_1_2 ||
|
static const bool textureEdgeClamp = GLEXT_texture_edge_clamp || GLEXT_GL_VERSION_1_2 ||
|
||||||
Context::isExtensionAvailable("GL_EXT_texture_edge_clamp");
|
Context::isExtensionAvailable("GL_EXT_texture_edge_clamp");
|
||||||
|
|
||||||
if (!m_isRepeated && !textureEdgeClamp)
|
if (!m_isRepeated && !textureEdgeClamp)
|
||||||
{
|
{
|
||||||
@ -209,7 +209,7 @@ bool Texture::create(const Vector2u& size)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool textureSrgb = GLEXT_texture_sRGB;
|
static const bool textureSrgb = GLEXT_texture_sRGB;
|
||||||
|
|
||||||
if (m_sRgb && !textureSrgb)
|
if (m_sRgb && !textureSrgb)
|
||||||
{
|
{
|
||||||
@ -321,10 +321,10 @@ bool Texture::loadFromImage(const Image& image, const IntRect& area)
|
|||||||
// Create the texture and upload the pixels
|
// Create the texture and upload the pixels
|
||||||
if (create(Vector2u(rectangle.getSize())))
|
if (create(Vector2u(rectangle.getSize())))
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
// Copy the pixels to the texture, row by row
|
// Copy the pixels to the texture, row by row
|
||||||
const std::uint8_t* pixels = image.getPixelsPtr() + 4 * (rectangle.left + (width * rectangle.top));
|
const std::uint8_t* pixels = image.getPixelsPtr() + 4 * (rectangle.left + (width * rectangle.top));
|
||||||
@ -366,10 +366,10 @@ Image Texture::copyToImage() const
|
|||||||
if (!m_texture)
|
if (!m_texture)
|
||||||
return Image();
|
return Image();
|
||||||
|
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
// Create an array of pixels
|
// Create an array of pixels
|
||||||
std::vector<std::uint8_t> pixels(m_size.x * m_size.y * 4);
|
std::vector<std::uint8_t> pixels(m_size.x * m_size.y * 4);
|
||||||
@ -414,7 +414,7 @@ Image Texture::copyToImage() const
|
|||||||
const std::uint8_t* src = allPixels.data();
|
const std::uint8_t* src = allPixels.data();
|
||||||
std::uint8_t* dst = pixels.data();
|
std::uint8_t* dst = pixels.data();
|
||||||
int srcPitch = static_cast<int>(m_actualSize.x * 4);
|
int srcPitch = static_cast<int>(m_actualSize.x * 4);
|
||||||
unsigned int dstPitch = m_size.x * 4;
|
const unsigned int dstPitch = m_size.x * 4;
|
||||||
|
|
||||||
// Handle the case where source pixels are flipped vertically
|
// Handle the case where source pixels are flipped vertically
|
||||||
if (m_pixelsFlipped)
|
if (m_pixelsFlipped)
|
||||||
@ -457,10 +457,10 @@ void Texture::update(const std::uint8_t* pixels, const Vector2u& size, const Vec
|
|||||||
|
|
||||||
if (pixels && m_texture)
|
if (pixels && m_texture)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
// Copy pixels from the given array to the texture
|
// Copy pixels from the given array to the texture
|
||||||
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
||||||
@ -505,7 +505,7 @@ void Texture::update(const Texture& texture, const Vector2u& dest)
|
|||||||
#ifndef SFML_OPENGL_ES
|
#ifndef SFML_OPENGL_ES
|
||||||
|
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
priv::ensureExtensionsInit();
|
priv::ensureExtensionsInit();
|
||||||
@ -513,7 +513,7 @@ void Texture::update(const Texture& texture, const Vector2u& dest)
|
|||||||
|
|
||||||
if (GLEXT_framebuffer_object && GLEXT_framebuffer_blit)
|
if (GLEXT_framebuffer_object && GLEXT_framebuffer_blit)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Save the current bindings so we can restore them after we are done
|
// Save the current bindings so we can restore them after we are done
|
||||||
GLint readFramebuffer = 0;
|
GLint readFramebuffer = 0;
|
||||||
@ -582,7 +582,7 @@ void Texture::update(const Texture& texture, const Vector2u& dest)
|
|||||||
glCheck(GLEXT_glDeleteFramebuffers(1, &destFrameBuffer));
|
glCheck(GLEXT_glDeleteFramebuffers(1, &destFrameBuffer));
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
// Set the parameters of this texture
|
// Set the parameters of this texture
|
||||||
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
||||||
@ -634,10 +634,10 @@ void Texture::update(const Window& window, const Vector2u& dest)
|
|||||||
|
|
||||||
if (m_texture && window.setActive(true))
|
if (m_texture && window.setActive(true))
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
// Copy pixels from the back-buffer to the texture
|
// Copy pixels from the back-buffer to the texture
|
||||||
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
||||||
@ -670,10 +670,10 @@ void Texture::setSmooth(bool smooth)
|
|||||||
|
|
||||||
if (m_texture)
|
if (m_texture)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
||||||
glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST));
|
glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST));
|
||||||
@ -723,12 +723,12 @@ void Texture::setRepeated(bool repeated)
|
|||||||
|
|
||||||
if (m_texture)
|
if (m_texture)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
static bool textureEdgeClamp = GLEXT_texture_edge_clamp;
|
static const bool textureEdgeClamp = GLEXT_texture_edge_clamp;
|
||||||
|
|
||||||
if (!m_isRepeated && !textureEdgeClamp)
|
if (!m_isRepeated && !textureEdgeClamp)
|
||||||
{
|
{
|
||||||
@ -771,7 +771,7 @@ bool Texture::generateMipmap()
|
|||||||
if (!m_texture)
|
if (!m_texture)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
priv::ensureExtensionsInit();
|
priv::ensureExtensionsInit();
|
||||||
@ -780,7 +780,7 @@ bool Texture::generateMipmap()
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
||||||
glCheck(GLEXT_glGenerateMipmap(GL_TEXTURE_2D));
|
glCheck(GLEXT_glGenerateMipmap(GL_TEXTURE_2D));
|
||||||
@ -800,10 +800,10 @@ void Texture::invalidateMipmap()
|
|||||||
if (!m_hasMipmap)
|
if (!m_hasMipmap)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
// Make sure that the current texture binding will be preserved
|
// Make sure that the current texture binding will be preserved
|
||||||
priv::TextureSaver save;
|
const priv::TextureSaver save;
|
||||||
|
|
||||||
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
|
||||||
glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST));
|
glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST));
|
||||||
@ -815,7 +815,7 @@ void Texture::invalidateMipmap()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void Texture::bind(const Texture* texture, CoordinateType coordinateType)
|
void Texture::bind(const Texture* texture, CoordinateType coordinateType)
|
||||||
{
|
{
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
if (texture && texture->m_texture)
|
if (texture && texture->m_texture)
|
||||||
{
|
{
|
||||||
@ -875,7 +875,7 @@ unsigned int Texture::getMaximumSize()
|
|||||||
{
|
{
|
||||||
static const unsigned int size = []()
|
static const unsigned int size = []()
|
||||||
{
|
{
|
||||||
TransientContextLock transientLock;
|
const TransientContextLock transientLock;
|
||||||
|
|
||||||
GLint value = 0;
|
GLint value = 0;
|
||||||
|
|
||||||
|
@ -37,14 +37,14 @@ namespace sf
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Transform& Transform::rotate(Angle angle)
|
Transform& Transform::rotate(Angle angle)
|
||||||
{
|
{
|
||||||
float rad = angle.asRadians();
|
const float rad = angle.asRadians();
|
||||||
float cos = std::cos(rad);
|
const float cos = std::cos(rad);
|
||||||
float sin = std::sin(rad);
|
const float sin = std::sin(rad);
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
Transform rotation(cos, -sin, 0,
|
const Transform rotation(cos, -sin, 0,
|
||||||
sin, cos, 0,
|
sin, cos, 0,
|
||||||
0, 0, 1);
|
0, 0, 1);
|
||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
return combine(rotation);
|
return combine(rotation);
|
||||||
@ -54,14 +54,14 @@ Transform& Transform::rotate(Angle angle)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Transform& Transform::rotate(Angle angle, const Vector2f& center)
|
Transform& Transform::rotate(Angle angle, const Vector2f& center)
|
||||||
{
|
{
|
||||||
float rad = angle.asRadians();
|
const float rad = angle.asRadians();
|
||||||
float cos = std::cos(rad);
|
const float cos = std::cos(rad);
|
||||||
float sin = std::sin(rad);
|
const float sin = std::sin(rad);
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
Transform rotation(cos, -sin, center.x * (1 - cos) + center.y * sin,
|
const Transform rotation(cos, -sin, center.x * (1 - cos) + center.y * sin,
|
||||||
sin, cos, center.y * (1 - cos) - center.x * sin,
|
sin, cos, center.y * (1 - cos) - center.x * sin,
|
||||||
0, 0, 1);
|
0, 0, 1);
|
||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
return combine(rotation);
|
return combine(rotation);
|
||||||
|
@ -132,15 +132,15 @@ const Transform& Transformable::getTransform() const
|
|||||||
// Recompute the combined transform if needed
|
// Recompute the combined transform if needed
|
||||||
if (m_transformNeedUpdate)
|
if (m_transformNeedUpdate)
|
||||||
{
|
{
|
||||||
float angle = -m_rotation.asRadians();
|
const float angle = -m_rotation.asRadians();
|
||||||
float cosine = std::cos(angle);
|
const float cosine = std::cos(angle);
|
||||||
float sine = std::sin(angle);
|
const float sine = std::sin(angle);
|
||||||
float sxc = m_scale.x * cosine;
|
const float sxc = m_scale.x * cosine;
|
||||||
float syc = m_scale.y * cosine;
|
const float syc = m_scale.y * cosine;
|
||||||
float sxs = m_scale.x * sine;
|
const float sxs = m_scale.x * sine;
|
||||||
float sys = m_scale.y * sine;
|
const float sys = m_scale.y * sine;
|
||||||
float tx = -m_origin.x * sxc - m_origin.y * sys + m_position.x;
|
const float tx = -m_origin.x * sxc - m_origin.y * sys + m_position.x;
|
||||||
float ty = m_origin.x * sxs - m_origin.y * syc + m_position.y;
|
const float ty = m_origin.x * sxs - m_origin.y * syc + m_position.y;
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
m_transform = Transform( sxc, sys, tx,
|
m_transform = Transform( sxc, sys, tx,
|
||||||
|
@ -109,7 +109,7 @@ FloatRect VertexArray::getBounds() const
|
|||||||
|
|
||||||
for (std::size_t i = 1; i < m_vertices.size(); ++i)
|
for (std::size_t i = 1; i < m_vertices.size(); ++i)
|
||||||
{
|
{
|
||||||
Vector2f position = m_vertices[i].position;
|
const Vector2f position = m_vertices[i].position;
|
||||||
|
|
||||||
// Update left and right
|
// Update left and right
|
||||||
if (position.x < left)
|
if (position.x < left)
|
||||||
|
@ -105,7 +105,7 @@ VertexBuffer::~VertexBuffer()
|
|||||||
{
|
{
|
||||||
if (m_buffer)
|
if (m_buffer)
|
||||||
{
|
{
|
||||||
TransientContextLock contextLock;
|
const TransientContextLock contextLock;
|
||||||
|
|
||||||
glCheck(GLEXT_glDeleteBuffers(1, &m_buffer));
|
glCheck(GLEXT_glDeleteBuffers(1, &m_buffer));
|
||||||
}
|
}
|
||||||
@ -118,7 +118,7 @@ bool VertexBuffer::create(std::size_t vertexCount)
|
|||||||
if (!isAvailable())
|
if (!isAvailable())
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
TransientContextLock contextLock;
|
const TransientContextLock contextLock;
|
||||||
|
|
||||||
if (!m_buffer)
|
if (!m_buffer)
|
||||||
glCheck(GLEXT_glGenBuffers(1, &m_buffer));
|
glCheck(GLEXT_glGenBuffers(1, &m_buffer));
|
||||||
@ -169,7 +169,7 @@ bool VertexBuffer::update(const Vertex* vertices, std::size_t vertexCount, unsig
|
|||||||
if (offset && (offset + vertexCount > m_size))
|
if (offset && (offset + vertexCount > m_size))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
TransientContextLock contextLock;
|
const TransientContextLock contextLock;
|
||||||
|
|
||||||
glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, m_buffer));
|
glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, m_buffer));
|
||||||
|
|
||||||
@ -207,7 +207,7 @@ bool VertexBuffer::update([[maybe_unused]] const VertexBuffer& vertexBuffer)
|
|||||||
if (!m_buffer || !vertexBuffer.m_buffer)
|
if (!m_buffer || !vertexBuffer.m_buffer)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
TransientContextLock contextLock;
|
const TransientContextLock contextLock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
sf::priv::ensureExtensionsInit();
|
sf::priv::ensureExtensionsInit();
|
||||||
@ -295,7 +295,7 @@ void VertexBuffer::bind(const VertexBuffer* vertexBuffer)
|
|||||||
if (!isAvailable())
|
if (!isAvailable())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
TransientContextLock lock;
|
const TransientContextLock lock;
|
||||||
|
|
||||||
glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, vertexBuffer ? vertexBuffer->m_buffer : 0));
|
glCheck(GLEXT_glBindBuffer(GLEXT_GL_ARRAY_BUFFER, vertexBuffer ? vertexBuffer->m_buffer : 0));
|
||||||
}
|
}
|
||||||
@ -334,7 +334,7 @@ bool VertexBuffer::isAvailable()
|
|||||||
{
|
{
|
||||||
static const bool available = []() -> bool
|
static const bool available = []() -> bool
|
||||||
{
|
{
|
||||||
TransientContextLock contextLock;
|
const TransientContextLock contextLock;
|
||||||
|
|
||||||
// Make sure that extensions are initialized
|
// Make sure that extensions are initialized
|
||||||
sf::priv::ensureExtensionsInit();
|
sf::priv::ensureExtensionsInit();
|
||||||
|
@ -157,17 +157,17 @@ const Transform& View::getTransform() const
|
|||||||
if (!m_transformUpdated)
|
if (!m_transformUpdated)
|
||||||
{
|
{
|
||||||
// Rotation components
|
// Rotation components
|
||||||
float angle = m_rotation.asRadians();
|
const float angle = m_rotation.asRadians();
|
||||||
float cosine = std::cos(angle);
|
const float cosine = std::cos(angle);
|
||||||
float sine = std::sin(angle);
|
const float sine = std::sin(angle);
|
||||||
float tx = -m_center.x * cosine - m_center.y * sine + m_center.x;
|
const float tx = -m_center.x * cosine - m_center.y * sine + m_center.x;
|
||||||
float ty = m_center.x * sine - m_center.y * cosine + m_center.y;
|
const float ty = m_center.x * sine - m_center.y * cosine + m_center.y;
|
||||||
|
|
||||||
// Projection components
|
// Projection components
|
||||||
float a = 2.f / m_size.x;
|
const float a = 2.f / m_size.x;
|
||||||
float b = -2.f / m_size.y;
|
const float b = -2.f / m_size.y;
|
||||||
float c = -a * m_center.x;
|
const float c = -a * m_center.x;
|
||||||
float d = -b * m_center.y;
|
const float d = -b * m_center.y;
|
||||||
|
|
||||||
// Rebuild the projection matrix
|
// Rebuild the projection matrix
|
||||||
// clang-format off
|
// clang-format off
|
||||||
|
@ -113,9 +113,9 @@ Ftp::DirectoryResponse::DirectoryResponse(const Ftp::Response& response) : Ftp::
|
|||||||
if (isOk())
|
if (isOk())
|
||||||
{
|
{
|
||||||
// Extract the directory from the server response
|
// Extract the directory from the server response
|
||||||
std::string::size_type begin = getMessage().find('"', 0);
|
const std::string::size_type begin = getMessage().find('"', 0);
|
||||||
std::string::size_type end = getMessage().find('"', begin + 1);
|
const std::string::size_type end = getMessage().find('"', begin + 1);
|
||||||
m_directory = getMessage().substr(begin + 1, end - begin - 1);
|
m_directory = getMessage().substr(begin + 1, end - begin - 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -330,8 +330,8 @@ Ftp::Response Ftp::upload(const std::string& localFile, const std::string& remot
|
|||||||
return Response(Response::Status::InvalidFile);
|
return Response(Response::Status::InvalidFile);
|
||||||
|
|
||||||
// Extract the filename from the file path
|
// Extract the filename from the file path
|
||||||
std::string filename = localFile;
|
std::string filename = localFile;
|
||||||
std::string::size_type pos = filename.find_last_of("/\\");
|
const std::string::size_type pos = filename.find_last_of("/\\");
|
||||||
if (pos != std::string::npos)
|
if (pos != std::string::npos)
|
||||||
filename = filename.substr(pos + 1);
|
filename = filename.substr(pos + 1);
|
||||||
|
|
||||||
@ -537,7 +537,7 @@ Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode)
|
|||||||
if (response.isOk())
|
if (response.isOk())
|
||||||
{
|
{
|
||||||
// Extract the connection address and port from the response
|
// Extract the connection address and port from the response
|
||||||
std::string::size_type begin = response.getMessage().find_first_of("0123456789");
|
const std::string::size_type begin = response.getMessage().find_first_of("0123456789");
|
||||||
if (begin != std::string::npos)
|
if (begin != std::string::npos)
|
||||||
{
|
{
|
||||||
std::uint8_t data[6] = {0, 0, 0, 0, 0, 0};
|
std::uint8_t data[6] = {0, 0, 0, 0, 0, 0};
|
||||||
@ -558,8 +558,8 @@ Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Reconstruct connection port and address
|
// Reconstruct connection port and address
|
||||||
auto port = static_cast<std::uint16_t>(data[4] * 256 + data[5]);
|
const auto port = static_cast<std::uint16_t>(data[4] * 256 + data[5]);
|
||||||
IpAddress address(data[0], data[1], data[2], data[3]);
|
const IpAddress address(data[0], data[1], data[2], data[3]);
|
||||||
|
|
||||||
// Connect the data channel to the server
|
// Connect the data channel to the server
|
||||||
if (m_dataSocket.connect(address, port) == Socket::Status::Done)
|
if (m_dataSocket.connect(address, port) == Socket::Status::Done)
|
||||||
|
@ -144,7 +144,7 @@ bool Http::Request::hasField(const std::string& field) const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
const std::string& Http::Response::getField(const std::string& field) const
|
const std::string& Http::Response::getField(const std::string& field) const
|
||||||
{
|
{
|
||||||
if (auto it = m_fields.find(toLower(field)); it != m_fields.end())
|
if (const auto it = m_fields.find(toLower(field)); it != m_fields.end())
|
||||||
{
|
{
|
||||||
return it->second;
|
return it->second;
|
||||||
}
|
}
|
||||||
@ -244,8 +244,8 @@ void Http::Response::parse(const std::string& data)
|
|||||||
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
|
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
|
||||||
|
|
||||||
// Copy the actual content data
|
// Copy the actual content data
|
||||||
std::istreambuf_iterator<char> it(in);
|
std::istreambuf_iterator<char> it(in);
|
||||||
std::istreambuf_iterator<char> itEnd;
|
const std::istreambuf_iterator<char> itEnd;
|
||||||
for (std::size_t i = 0; ((i < length) && (it != itEnd)); ++i)
|
for (std::size_t i = 0; ((i < length) && (it != itEnd)); ++i)
|
||||||
{
|
{
|
||||||
m_body.push_back(*it);
|
m_body.push_back(*it);
|
||||||
@ -268,12 +268,12 @@ void Http::Response::parseFields(std::istream& in)
|
|||||||
std::string line;
|
std::string line;
|
||||||
while (std::getline(in, line) && (line.size() > 2))
|
while (std::getline(in, line) && (line.size() > 2))
|
||||||
{
|
{
|
||||||
std::string::size_type pos = line.find(": ");
|
const std::string::size_type pos = line.find(": ");
|
||||||
if (pos != std::string::npos)
|
if (pos != std::string::npos)
|
||||||
{
|
{
|
||||||
// Extract the field name and its value
|
// Extract the field name and its value
|
||||||
std::string field = line.substr(0, pos);
|
const std::string field = line.substr(0, pos);
|
||||||
std::string value = line.substr(pos + 2);
|
std::string value = line.substr(pos + 2);
|
||||||
|
|
||||||
// Remove any trailing \r
|
// Remove any trailing \r
|
||||||
if (!value.empty() && (*value.rbegin() == '\r'))
|
if (!value.empty() && (*value.rbegin() == '\r'))
|
||||||
@ -368,7 +368,7 @@ Http::Response Http::sendRequest(const Http::Request& request, Time timeout)
|
|||||||
if (m_connection.connect(m_host.value(), m_port, timeout) == Socket::Status::Done)
|
if (m_connection.connect(m_host.value(), m_port, timeout) == Socket::Status::Done)
|
||||||
{
|
{
|
||||||
// Convert the request to string and send it through the connected socket
|
// Convert the request to string and send it through the connected socket
|
||||||
std::string requestStr = toSend.prepare();
|
const std::string requestStr = toSend.prepare();
|
||||||
|
|
||||||
if (!requestStr.empty())
|
if (!requestStr.empty())
|
||||||
{
|
{
|
||||||
|
@ -124,7 +124,7 @@ std::optional<IpAddress> IpAddress::getLocalAddress()
|
|||||||
// UDP connection will not send anything to the network, so this function won't cause any overhead.
|
// UDP connection will not send anything to the network, so this function won't cause any overhead.
|
||||||
|
|
||||||
// Create the socket
|
// Create the socket
|
||||||
SocketHandle sock = socket(PF_INET, SOCK_DGRAM, 0);
|
const SocketHandle sock = socket(PF_INET, SOCK_DGRAM, 0);
|
||||||
if (sock == priv::SocketImpl::invalidSocket())
|
if (sock == priv::SocketImpl::invalidSocket())
|
||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
|
|
||||||
@ -161,9 +161,9 @@ std::optional<IpAddress> IpAddress::getPublicAddress(Time timeout)
|
|||||||
// and parse the result to extract our IP address
|
// and parse the result to extract our IP address
|
||||||
// (not very hard: the web page contains only our IP address).
|
// (not very hard: the web page contains only our IP address).
|
||||||
|
|
||||||
Http server("www.sfml-dev.org");
|
Http server("www.sfml-dev.org");
|
||||||
Http::Request request("/ip-provider.php", Http::Request::Method::Get);
|
const Http::Request request("/ip-provider.php", Http::Request::Method::Get);
|
||||||
Http::Response page = server.sendRequest(request, timeout);
|
const Http::Response page = server.sendRequest(request, timeout);
|
||||||
if (page.getStatus() == Http::Response::Status::Ok)
|
if (page.getStatus() == Http::Response::Status::Ok)
|
||||||
return IpAddress::resolve(page.getBody());
|
return IpAddress::resolve(page.getBody());
|
||||||
|
|
||||||
|
@ -65,7 +65,7 @@ void Packet::append(const void* data, std::size_t sizeInBytes)
|
|||||||
{
|
{
|
||||||
if (data && (sizeInBytes > 0))
|
if (data && (sizeInBytes > 0))
|
||||||
{
|
{
|
||||||
std::size_t start = m_data.size();
|
const std::size_t start = m_data.size();
|
||||||
m_data.resize(start + sizeInBytes);
|
m_data.resize(start + sizeInBytes);
|
||||||
std::memcpy(&m_data[start], data, sizeInBytes);
|
std::memcpy(&m_data[start], data, sizeInBytes);
|
||||||
}
|
}
|
||||||
@ -510,7 +510,7 @@ Packet& Packet::operator<<(double data)
|
|||||||
Packet& Packet::operator<<(const char* data)
|
Packet& Packet::operator<<(const char* data)
|
||||||
{
|
{
|
||||||
// First insert string length
|
// First insert string length
|
||||||
auto length = static_cast<std::uint32_t>(std::strlen(data));
|
const auto length = static_cast<std::uint32_t>(std::strlen(data));
|
||||||
*this << length;
|
*this << length;
|
||||||
|
|
||||||
// Then insert characters
|
// Then insert characters
|
||||||
@ -524,7 +524,7 @@ Packet& Packet::operator<<(const char* data)
|
|||||||
Packet& Packet::operator<<(const std::string& data)
|
Packet& Packet::operator<<(const std::string& data)
|
||||||
{
|
{
|
||||||
// First insert string length
|
// First insert string length
|
||||||
auto length = static_cast<std::uint32_t>(data.size());
|
const auto length = static_cast<std::uint32_t>(data.size());
|
||||||
*this << length;
|
*this << length;
|
||||||
|
|
||||||
// Then insert characters
|
// Then insert characters
|
||||||
@ -539,7 +539,7 @@ Packet& Packet::operator<<(const std::string& data)
|
|||||||
Packet& Packet::operator<<(const wchar_t* data)
|
Packet& Packet::operator<<(const wchar_t* data)
|
||||||
{
|
{
|
||||||
// First insert string length
|
// First insert string length
|
||||||
auto length = static_cast<std::uint32_t>(std::wcslen(data));
|
const auto length = static_cast<std::uint32_t>(std::wcslen(data));
|
||||||
*this << length;
|
*this << length;
|
||||||
|
|
||||||
// Then insert characters
|
// Then insert characters
|
||||||
@ -554,13 +554,13 @@ Packet& Packet::operator<<(const wchar_t* data)
|
|||||||
Packet& Packet::operator<<(const std::wstring& data)
|
Packet& Packet::operator<<(const std::wstring& data)
|
||||||
{
|
{
|
||||||
// First insert string length
|
// First insert string length
|
||||||
auto length = static_cast<std::uint32_t>(data.size());
|
const auto length = static_cast<std::uint32_t>(data.size());
|
||||||
*this << length;
|
*this << length;
|
||||||
|
|
||||||
// Then insert characters
|
// Then insert characters
|
||||||
if (length > 0)
|
if (length > 0)
|
||||||
{
|
{
|
||||||
for (wchar_t c : data)
|
for (const wchar_t c : data)
|
||||||
*this << static_cast<std::uint32_t>(c);
|
*this << static_cast<std::uint32_t>(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -572,13 +572,13 @@ Packet& Packet::operator<<(const std::wstring& data)
|
|||||||
Packet& Packet::operator<<(const String& data)
|
Packet& Packet::operator<<(const String& data)
|
||||||
{
|
{
|
||||||
// First insert the string length
|
// First insert the string length
|
||||||
auto length = static_cast<std::uint32_t>(data.getSize());
|
const auto length = static_cast<std::uint32_t>(data.getSize());
|
||||||
*this << length;
|
*this << length;
|
||||||
|
|
||||||
// Then insert characters
|
// Then insert characters
|
||||||
if (length > 0)
|
if (length > 0)
|
||||||
{
|
{
|
||||||
for (unsigned int datum : data)
|
for (const unsigned int datum : data)
|
||||||
*this << datum;
|
*this << datum;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -80,7 +80,7 @@ void Socket::create()
|
|||||||
// Don't create the socket if it already exists
|
// Don't create the socket if it already exists
|
||||||
if (m_socket == priv::SocketImpl::invalidSocket())
|
if (m_socket == priv::SocketImpl::invalidSocket())
|
||||||
{
|
{
|
||||||
SocketHandle handle = socket(PF_INET, m_type == Type::Tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
|
const SocketHandle handle = socket(PF_INET, m_type == Type::Tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
|
||||||
|
|
||||||
if (handle == priv::SocketImpl::invalidSocket())
|
if (handle == priv::SocketImpl::invalidSocket())
|
||||||
{
|
{
|
||||||
|
@ -73,7 +73,7 @@ SocketSelector::~SocketSelector() = default;
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void SocketSelector::add(Socket& socket)
|
void SocketSelector::add(Socket& socket)
|
||||||
{
|
{
|
||||||
SocketHandle handle = socket.getHandle();
|
const SocketHandle handle = socket.getHandle();
|
||||||
if (handle != priv::SocketImpl::invalidSocket())
|
if (handle != priv::SocketImpl::invalidSocket())
|
||||||
{
|
{
|
||||||
|
|
||||||
@ -115,7 +115,7 @@ void SocketSelector::add(Socket& socket)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void SocketSelector::remove(Socket& socket)
|
void SocketSelector::remove(Socket& socket)
|
||||||
{
|
{
|
||||||
SocketHandle handle = socket.getHandle();
|
const SocketHandle handle = socket.getHandle();
|
||||||
if (handle != priv::SocketImpl::invalidSocket())
|
if (handle != priv::SocketImpl::invalidSocket())
|
||||||
{
|
{
|
||||||
|
|
||||||
@ -163,7 +163,7 @@ bool SocketSelector::wait(Time timeout)
|
|||||||
|
|
||||||
// Wait until one of the sockets is ready for reading, or timeout is reached
|
// Wait until one of the sockets is ready for reading, or timeout is reached
|
||||||
// The first parameter is ignored on Windows
|
// The first parameter is ignored on Windows
|
||||||
int count = select(m_impl->maxSocket + 1, &m_impl->socketsReady, nullptr, nullptr, timeout != Time::Zero ? &time : nullptr);
|
const int count = select(m_impl->maxSocket + 1, &m_impl->socketsReady, nullptr, nullptr, timeout != Time::Zero ? &time : nullptr);
|
||||||
|
|
||||||
return count > 0;
|
return count > 0;
|
||||||
}
|
}
|
||||||
@ -172,7 +172,7 @@ bool SocketSelector::wait(Time timeout)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool SocketSelector::isReady(Socket& socket) const
|
bool SocketSelector::isReady(Socket& socket) const
|
||||||
{
|
{
|
||||||
SocketHandle handle = socket.getHandle();
|
const SocketHandle handle = socket.getHandle();
|
||||||
if (handle != priv::SocketImpl::invalidSocket())
|
if (handle != priv::SocketImpl::invalidSocket())
|
||||||
{
|
{
|
||||||
|
|
||||||
|
@ -116,7 +116,7 @@ Socket::Status TcpListener::accept(TcpSocket& socket)
|
|||||||
// Accept a new connection
|
// Accept a new connection
|
||||||
sockaddr_in address;
|
sockaddr_in address;
|
||||||
priv::SocketImpl::AddrLength length = sizeof(address);
|
priv::SocketImpl::AddrLength length = sizeof(address);
|
||||||
SocketHandle remote = ::accept(getHandle(), reinterpret_cast<sockaddr*>(&address), &length);
|
const SocketHandle remote = ::accept(getHandle(), reinterpret_cast<sockaddr*>(&address), &length);
|
||||||
|
|
||||||
// Check for errors
|
// Check for errors
|
||||||
if (remote == priv::SocketImpl::invalidSocket())
|
if (remote == priv::SocketImpl::invalidSocket())
|
||||||
|
@ -145,7 +145,7 @@ Socket::Status TcpSocket::connect(const IpAddress& remoteAddress, unsigned short
|
|||||||
// ----- We're using a timeout: we'll need a few tricks to make it work -----
|
// ----- We're using a timeout: we'll need a few tricks to make it work -----
|
||||||
|
|
||||||
// Save the previous blocking state
|
// Save the previous blocking state
|
||||||
bool blocking = isBlocking();
|
const bool blocking = isBlocking();
|
||||||
|
|
||||||
// Switch to non-blocking to enable our connection timeout
|
// Switch to non-blocking to enable our connection timeout
|
||||||
if (blocking)
|
if (blocking)
|
||||||
@ -257,7 +257,7 @@ Socket::Status TcpSocket::send(const void* data, std::size_t size, std::size_t&
|
|||||||
// Check for errors
|
// Check for errors
|
||||||
if (result < 0)
|
if (result < 0)
|
||||||
{
|
{
|
||||||
Status status = priv::SocketImpl::getErrorStatus();
|
const Status status = priv::SocketImpl::getErrorStatus();
|
||||||
|
|
||||||
if ((status == Status::NotReady) && sent)
|
if ((status == Status::NotReady) && sent)
|
||||||
return Status::Partial;
|
return Status::Partial;
|
||||||
@ -286,7 +286,7 @@ Socket::Status TcpSocket::receive(void* data, std::size_t size, std::size_t& rec
|
|||||||
#pragma GCC diagnostic push
|
#pragma GCC diagnostic push
|
||||||
#pragma GCC diagnostic ignored "-Wuseless-cast"
|
#pragma GCC diagnostic ignored "-Wuseless-cast"
|
||||||
// Receive a chunk of bytes
|
// Receive a chunk of bytes
|
||||||
int sizeReceived = static_cast<int>(
|
const int sizeReceived = static_cast<int>(
|
||||||
recv(getHandle(), static_cast<char*>(data), static_cast<priv::SocketImpl::Size>(size), flags));
|
recv(getHandle(), static_cast<char*>(data), static_cast<priv::SocketImpl::Size>(size), flags));
|
||||||
#pragma GCC diagnostic pop
|
#pragma GCC diagnostic pop
|
||||||
|
|
||||||
@ -345,10 +345,10 @@ Socket::Status TcpSocket::send(Packet& packet)
|
|||||||
#pragma GCC diagnostic push
|
#pragma GCC diagnostic push
|
||||||
#pragma GCC diagnostic ignored "-Wsign-conversion"
|
#pragma GCC diagnostic ignored "-Wsign-conversion"
|
||||||
// Send the data block
|
// Send the data block
|
||||||
std::size_t sent;
|
std::size_t sent;
|
||||||
Status status = send(m_blockToSendBuffer.data() + packet.m_sendPos,
|
const Status status = send(m_blockToSendBuffer.data() + packet.m_sendPos,
|
||||||
static_cast<priv::SocketImpl::Size>(m_blockToSendBuffer.size() - packet.m_sendPos),
|
static_cast<priv::SocketImpl::Size>(m_blockToSendBuffer.size() - packet.m_sendPos),
|
||||||
sent);
|
sent);
|
||||||
#pragma GCC diagnostic pop
|
#pragma GCC diagnostic pop
|
||||||
#pragma GCC diagnostic pop
|
#pragma GCC diagnostic pop
|
||||||
|
|
||||||
@ -381,8 +381,8 @@ Socket::Status TcpSocket::receive(Packet& packet)
|
|||||||
// (even a 4 byte variable may be received in more than one call)
|
// (even a 4 byte variable may be received in more than one call)
|
||||||
while (m_pendingPacket.SizeReceived < sizeof(m_pendingPacket.Size))
|
while (m_pendingPacket.SizeReceived < sizeof(m_pendingPacket.Size))
|
||||||
{
|
{
|
||||||
char* data = reinterpret_cast<char*>(&m_pendingPacket.Size) + m_pendingPacket.SizeReceived;
|
char* data = reinterpret_cast<char*>(&m_pendingPacket.Size) + m_pendingPacket.SizeReceived;
|
||||||
Status status = receive(data, sizeof(m_pendingPacket.Size) - m_pendingPacket.SizeReceived, received);
|
const Status status = receive(data, sizeof(m_pendingPacket.Size) - m_pendingPacket.SizeReceived, received);
|
||||||
m_pendingPacket.SizeReceived += received;
|
m_pendingPacket.SizeReceived += received;
|
||||||
|
|
||||||
if (status != Status::Done)
|
if (status != Status::Done)
|
||||||
@ -403,8 +403,8 @@ Socket::Status TcpSocket::receive(Packet& packet)
|
|||||||
while (m_pendingPacket.Data.size() < packetSize)
|
while (m_pendingPacket.Data.size() < packetSize)
|
||||||
{
|
{
|
||||||
// Receive a chunk of data
|
// Receive a chunk of data
|
||||||
std::size_t sizeToGet = std::min(packetSize - m_pendingPacket.Data.size(), sizeof(buffer));
|
const std::size_t sizeToGet = std::min(packetSize - m_pendingPacket.Data.size(), sizeof(buffer));
|
||||||
Status status = receive(buffer, sizeToGet, received);
|
const Status status = receive(buffer, sizeToGet, received);
|
||||||
if (status != Status::Done)
|
if (status != Status::Done)
|
||||||
return status;
|
return status;
|
||||||
|
|
||||||
|
@ -117,7 +117,7 @@ Socket::Status UdpSocket::send(const void* data, std::size_t size, const IpAddre
|
|||||||
#pragma GCC diagnostic push
|
#pragma GCC diagnostic push
|
||||||
#pragma GCC diagnostic ignored "-Wuseless-cast"
|
#pragma GCC diagnostic ignored "-Wuseless-cast"
|
||||||
// Send the data (unlike TCP, all the data is always sent in one call)
|
// Send the data (unlike TCP, all the data is always sent in one call)
|
||||||
int sent = static_cast<int>(
|
const int sent = static_cast<int>(
|
||||||
sendto(getHandle(),
|
sendto(getHandle(),
|
||||||
static_cast<const char*>(data),
|
static_cast<const char*>(data),
|
||||||
static_cast<priv::SocketImpl::Size>(size),
|
static_cast<priv::SocketImpl::Size>(size),
|
||||||
@ -160,7 +160,7 @@ Socket::Status UdpSocket::receive(void* data,
|
|||||||
#pragma GCC diagnostic ignored "-Wuseless-cast"
|
#pragma GCC diagnostic ignored "-Wuseless-cast"
|
||||||
// Receive a chunk of bytes
|
// Receive a chunk of bytes
|
||||||
priv::SocketImpl::AddrLength addressSize = sizeof(address);
|
priv::SocketImpl::AddrLength addressSize = sizeof(address);
|
||||||
int sizeReceived = static_cast<int>(
|
const int sizeReceived = static_cast<int>(
|
||||||
recvfrom(getHandle(),
|
recvfrom(getHandle(),
|
||||||
static_cast<char*>(data),
|
static_cast<char*>(data),
|
||||||
static_cast<priv::SocketImpl::Size>(size),
|
static_cast<priv::SocketImpl::Size>(size),
|
||||||
@ -208,8 +208,8 @@ Socket::Status UdpSocket::receive(Packet& packet, std::optional<IpAddress>& remo
|
|||||||
// See the detailed comment in send(Packet) above.
|
// See the detailed comment in send(Packet) above.
|
||||||
|
|
||||||
// Receive the datagram
|
// Receive the datagram
|
||||||
std::size_t received = 0;
|
std::size_t received = 0;
|
||||||
Status status = receive(m_buffer.data(), m_buffer.size(), received, remoteAddress, remotePort);
|
const Status status = receive(m_buffer.data(), m_buffer.size(), received, remoteAddress, remotePort);
|
||||||
|
|
||||||
// If we received valid data, we can copy it to the user packet
|
// If we received valid data, we can copy it to the user packet
|
||||||
packet.clear();
|
packet.clear();
|
||||||
|
@ -71,7 +71,7 @@ void SocketImpl::close(SocketHandle sock)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void SocketImpl::setBlocking(SocketHandle sock, bool block)
|
void SocketImpl::setBlocking(SocketHandle sock, bool block)
|
||||||
{
|
{
|
||||||
int status = fcntl(sock, F_GETFL);
|
const int status = fcntl(sock, F_GETFL);
|
||||||
if (block)
|
if (block)
|
||||||
{
|
{
|
||||||
if (fcntl(sock, F_SETFL, status & ~O_NONBLOCK) == -1)
|
if (fcntl(sock, F_SETFL, status & ~O_NONBLOCK) == -1)
|
||||||
|
@ -84,7 +84,7 @@ private:
|
|||||||
if (pbase() != pptr())
|
if (pbase() != pptr())
|
||||||
{
|
{
|
||||||
// Print the contents of the write buffer into the standard error output
|
// Print the contents of the write buffer into the standard error output
|
||||||
auto size = static_cast<std::size_t>(pptr() - pbase());
|
const auto size = static_cast<std::size_t>(pptr() - pbase());
|
||||||
fwrite(pbase(), 1, size, stderr);
|
fwrite(pbase(), 1, size, stderr);
|
||||||
|
|
||||||
// Reset the pointer position to the beginning of the write buffer
|
// Reset the pointer position to the beginning of the write buffer
|
||||||
|
@ -134,9 +134,9 @@ std::int64_t FileInputStream::getSize()
|
|||||||
#else
|
#else
|
||||||
if (m_file)
|
if (m_file)
|
||||||
{
|
{
|
||||||
std::int64_t position = tell();
|
const std::int64_t position = tell();
|
||||||
std::fseek(m_file.get(), 0, SEEK_END);
|
std::fseek(m_file.get(), 0, SEEK_END);
|
||||||
std::int64_t size = tell();
|
const std::int64_t size = tell();
|
||||||
|
|
||||||
if (seek(position) == -1)
|
if (seek(position) == -1)
|
||||||
return -1;
|
return -1;
|
||||||
|
@ -51,8 +51,8 @@ std::int64_t MemoryInputStream::read(void* data, std::int64_t size)
|
|||||||
if (!m_data)
|
if (!m_data)
|
||||||
return -1;
|
return -1;
|
||||||
|
|
||||||
std::int64_t endPosition = m_offset + size;
|
const std::int64_t endPosition = m_offset + size;
|
||||||
std::int64_t count = endPosition <= m_size ? size : m_size - m_offset;
|
const std::int64_t count = endPosition <= m_size ? size : m_size - m_offset;
|
||||||
|
|
||||||
if (count > 0)
|
if (count > 0)
|
||||||
{
|
{
|
||||||
|
@ -70,7 +70,7 @@ String::String(const char* ansiString, const std::locale& locale)
|
|||||||
{
|
{
|
||||||
if (ansiString)
|
if (ansiString)
|
||||||
{
|
{
|
||||||
std::size_t length = strlen(ansiString);
|
const std::size_t length = strlen(ansiString);
|
||||||
if (length > 0)
|
if (length > 0)
|
||||||
{
|
{
|
||||||
m_string.reserve(length + 1);
|
m_string.reserve(length + 1);
|
||||||
@ -93,7 +93,7 @@ String::String(const wchar_t* wideString)
|
|||||||
{
|
{
|
||||||
if (wideString)
|
if (wideString)
|
||||||
{
|
{
|
||||||
std::size_t length = std::wcslen(wideString);
|
const std::size_t length = std::wcslen(wideString);
|
||||||
if (length > 0)
|
if (length > 0)
|
||||||
{
|
{
|
||||||
m_string.reserve(length + 1);
|
m_string.reserve(length + 1);
|
||||||
@ -276,9 +276,9 @@ void String::replace(std::size_t position, std::size_t length, const String& rep
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void String::replace(const String& searchFor, const String& replaceWith)
|
void String::replace(const String& searchFor, const String& replaceWith)
|
||||||
{
|
{
|
||||||
std::size_t step = replaceWith.getSize();
|
const std::size_t step = replaceWith.getSize();
|
||||||
std::size_t len = searchFor.getSize();
|
const std::size_t len = searchFor.getSize();
|
||||||
std::size_t pos = find(searchFor);
|
std::size_t pos = find(searchFor);
|
||||||
|
|
||||||
// Replace each occurrence of search
|
// Replace each occurrence of search
|
||||||
while (pos != InvalidPos)
|
while (pos != InvalidPos)
|
||||||
|
@ -68,7 +68,7 @@ Context::~Context()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool Context::setActive(bool active)
|
bool Context::setActive(bool active)
|
||||||
{
|
{
|
||||||
bool result = m_context->setActive(active);
|
const bool result = m_context->setActive(active);
|
||||||
|
|
||||||
if (result)
|
if (result)
|
||||||
ContextImpl::currentContext = (active ? this : nullptr);
|
ContextImpl::currentContext = (active ? this : nullptr);
|
||||||
|
@ -334,7 +334,7 @@ void loadExtensions()
|
|||||||
// Helper to parse OpenGL version strings
|
// Helper to parse OpenGL version strings
|
||||||
bool parseVersionString(const char* version, const char* prefix, unsigned int& major, unsigned int& minor)
|
bool parseVersionString(const char* version, const char* prefix, unsigned int& major, unsigned int& minor)
|
||||||
{
|
{
|
||||||
std::size_t prefixLength = std::strlen(prefix);
|
const std::size_t prefixLength = std::strlen(prefix);
|
||||||
|
|
||||||
if ((std::strlen(version) >= (prefixLength + 3)) && (std::strncmp(version, prefix, prefixLength) == 0) &&
|
if ((std::strlen(version) >= (prefixLength + 3)) && (std::strncmp(version, prefix, prefixLength) == 0) &&
|
||||||
std::isdigit(version[prefixLength]) && (version[prefixLength + 1] == '.') &&
|
std::isdigit(version[prefixLength]) && (version[prefixLength + 1] == '.') &&
|
||||||
@ -363,7 +363,7 @@ void GlContext::initResource()
|
|||||||
using GlContextImpl::sharedContext;
|
using GlContextImpl::sharedContext;
|
||||||
|
|
||||||
// Protect from concurrent access
|
// Protect from concurrent access
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// If this is the very first resource, trigger the global context initialization
|
// If this is the very first resource, trigger the global context initialization
|
||||||
if (resourceCount == 0)
|
if (resourceCount == 0)
|
||||||
@ -400,7 +400,7 @@ void GlContext::cleanupResource()
|
|||||||
using GlContextImpl::sharedContext;
|
using GlContextImpl::sharedContext;
|
||||||
|
|
||||||
// Protect from concurrent access
|
// Protect from concurrent access
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// Decrement the resources counter
|
// Decrement the resources counter
|
||||||
--resourceCount;
|
--resourceCount;
|
||||||
@ -481,7 +481,7 @@ std::unique_ptr<GlContext> GlContext::create()
|
|||||||
// Make sure that there's an active context (context creation may need extensions, and thus a valid context)
|
// Make sure that there's an active context (context creation may need extensions, and thus a valid context)
|
||||||
assert(sharedContext != nullptr);
|
assert(sharedContext != nullptr);
|
||||||
|
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
std::unique_ptr<GlContext> context;
|
std::unique_ptr<GlContext> context;
|
||||||
|
|
||||||
@ -514,7 +514,7 @@ std::unique_ptr<GlContext> GlContext::create(const ContextSettings& settings, co
|
|||||||
// Make sure that there's an active context (context creation may need extensions, and thus a valid context)
|
// Make sure that there's an active context (context creation may need extensions, and thus a valid context)
|
||||||
assert(sharedContext != nullptr);
|
assert(sharedContext != nullptr);
|
||||||
|
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// If resourceCount is 1 we know that we are inside sf::Context or sf::Window
|
// If resourceCount is 1 we know that we are inside sf::Context or sf::Window
|
||||||
// Only in this situation we allow the user to indirectly re-create the shared context as a core context
|
// Only in this situation we allow the user to indirectly re-create the shared context as a core context
|
||||||
@ -524,7 +524,7 @@ std::unique_ptr<GlContext> GlContext::create(const ContextSettings& settings, co
|
|||||||
!(sharedContext->m_settings.attributeFlags & ContextSettings::Core))
|
!(sharedContext->m_settings.attributeFlags & ContextSettings::Core))
|
||||||
{
|
{
|
||||||
// Re-create our shared context as a core context
|
// Re-create our shared context as a core context
|
||||||
ContextSettings sharedSettings(0, 0, 0, settings.majorVersion, settings.minorVersion, settings.attributeFlags);
|
const ContextSettings sharedSettings(0, 0, 0, settings.majorVersion, settings.minorVersion, settings.attributeFlags);
|
||||||
|
|
||||||
sharedContext = std::make_unique<ContextType>(nullptr, sharedSettings, Vector2u(1, 1));
|
sharedContext = std::make_unique<ContextType>(nullptr, sharedSettings, Vector2u(1, 1));
|
||||||
sharedContext->initialize(sharedSettings);
|
sharedContext->initialize(sharedSettings);
|
||||||
@ -565,7 +565,7 @@ std::unique_ptr<GlContext> GlContext::create(const ContextSettings& settings, co
|
|||||||
// Make sure that there's an active context (context creation may need extensions, and thus a valid context)
|
// Make sure that there's an active context (context creation may need extensions, and thus a valid context)
|
||||||
assert(sharedContext != nullptr);
|
assert(sharedContext != nullptr);
|
||||||
|
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// If resourceCount is 1 we know that we are inside sf::Context or sf::Window
|
// If resourceCount is 1 we know that we are inside sf::Context or sf::Window
|
||||||
// Only in this situation we allow the user to indirectly re-create the shared context as a core context
|
// Only in this situation we allow the user to indirectly re-create the shared context as a core context
|
||||||
@ -575,7 +575,7 @@ std::unique_ptr<GlContext> GlContext::create(const ContextSettings& settings, co
|
|||||||
!(sharedContext->m_settings.attributeFlags & ContextSettings::Core))
|
!(sharedContext->m_settings.attributeFlags & ContextSettings::Core))
|
||||||
{
|
{
|
||||||
// Re-create our shared context as a core context
|
// Re-create our shared context as a core context
|
||||||
ContextSettings sharedSettings(0, 0, 0, settings.majorVersion, settings.minorVersion, settings.attributeFlags);
|
const ContextSettings sharedSettings(0, 0, 0, settings.majorVersion, settings.minorVersion, settings.attributeFlags);
|
||||||
|
|
||||||
sharedContext = std::make_unique<ContextType>(nullptr, sharedSettings, Vector2u(1, 1));
|
sharedContext = std::make_unique<ContextType>(nullptr, sharedSettings, Vector2u(1, 1));
|
||||||
sharedContext->initialize(sharedSettings);
|
sharedContext->initialize(sharedSettings);
|
||||||
@ -616,7 +616,7 @@ bool GlContext::isExtensionAvailable(const char* name)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
GlFunctionPointer GlContext::getFunction(const char* name)
|
GlFunctionPointer GlContext::getFunction(const char* name)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(GlContextImpl::mutex);
|
const std::lock_guard lock(GlContextImpl::mutex);
|
||||||
|
|
||||||
return ContextType::getFunction(name);
|
return ContextType::getFunction(name);
|
||||||
}
|
}
|
||||||
@ -670,7 +670,7 @@ bool GlContext::setActive(bool active)
|
|||||||
{
|
{
|
||||||
if (m_id != currentContext.id)
|
if (m_id != currentContext.id)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// Activate the context
|
// Activate the context
|
||||||
if (makeCurrent(true))
|
if (makeCurrent(true))
|
||||||
@ -695,7 +695,7 @@ bool GlContext::setActive(bool active)
|
|||||||
{
|
{
|
||||||
if (m_id == currentContext.id)
|
if (m_id == currentContext.id)
|
||||||
{
|
{
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
// Deactivate the context
|
// Deactivate the context
|
||||||
if (makeCurrent(false))
|
if (makeCurrent(false))
|
||||||
@ -947,8 +947,8 @@ void GlContext::initialize(const ContextSettings& requestedSettings)
|
|||||||
void GlContext::checkSettings(const ContextSettings& requestedSettings) const
|
void GlContext::checkSettings(const ContextSettings& requestedSettings) const
|
||||||
{
|
{
|
||||||
// Perform checks to inform the user if they are getting a context they might not have expected
|
// Perform checks to inform the user if they are getting a context they might not have expected
|
||||||
int version = static_cast<int>(m_settings.majorVersion * 10u + m_settings.minorVersion);
|
const int version = static_cast<int>(m_settings.majorVersion * 10u + m_settings.minorVersion);
|
||||||
int requestedVersion = static_cast<int>(requestedSettings.majorVersion * 10u + requestedSettings.minorVersion);
|
const int requestedVersion = static_cast<int>(requestedSettings.majorVersion * 10u + requestedSettings.minorVersion);
|
||||||
|
|
||||||
if ((m_settings.attributeFlags != requestedSettings.attributeFlags) || (version < requestedVersion) ||
|
if ((m_settings.attributeFlags != requestedSettings.attributeFlags) || (version < requestedVersion) ||
|
||||||
(m_settings.stencilBits < requestedSettings.stencilBits) ||
|
(m_settings.stencilBits < requestedSettings.stencilBits) ||
|
||||||
|
@ -38,12 +38,12 @@ namespace sf::priv
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
String ClipboardImpl::getString()
|
String ClipboardImpl::getString()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
NSPasteboard* pboard = [NSPasteboard generalPasteboard];
|
NSPasteboard* const pboard = [NSPasteboard generalPasteboard];
|
||||||
NSString* data = [pboard stringForType:NSPasteboardTypeString];
|
NSString* const data = [pboard stringForType:NSPasteboardTypeString];
|
||||||
|
|
||||||
char const* utf8 = [data cStringUsingEncoding:NSUTF8StringEncoding];
|
char const* utf8 = [data cStringUsingEncoding:NSUTF8StringEncoding];
|
||||||
NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
|
const NSUInteger length = [data lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
|
||||||
|
|
||||||
return String::fromUtf8(utf8, utf8 + length);
|
return String::fromUtf8(utf8, utf8 + length);
|
||||||
}
|
}
|
||||||
@ -52,11 +52,14 @@ String ClipboardImpl::getString()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void ClipboardImpl::setString(const String& text)
|
void ClipboardImpl::setString(const String& text)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
std::basic_string<std::uint8_t> utf8 = text.toUtf8();
|
std::basic_string<std::uint8_t> utf8 = text.toUtf8();
|
||||||
NSString* data = [[NSString alloc] initWithBytes:utf8.data() length:utf8.length() encoding:NSUTF8StringEncoding];
|
NSString* const data = [[NSString alloc]
|
||||||
|
initWithBytes:utf8.data()
|
||||||
|
length:utf8.length()
|
||||||
|
encoding:NSUTF8StringEncoding];
|
||||||
|
|
||||||
NSPasteboard* pboard = [NSPasteboard generalPasteboard];
|
NSPasteboard* const pboard = [NSPasteboard generalPasteboard];
|
||||||
[pboard declareTypes:@[NSPasteboardTypeString] owner:nil];
|
[pboard declareTypes:@[NSPasteboardTypeString] owner:nil];
|
||||||
[pboard setString:data forType:NSPasteboardTypeString];
|
[pboard setString:data forType:NSPasteboardTypeString];
|
||||||
|
|
||||||
|
@ -57,7 +57,7 @@ CursorImpl::CursorImpl() = default;
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
CursorImpl::~CursorImpl()
|
CursorImpl::~CursorImpl()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_cursor release];
|
[m_cursor release];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,16 +65,16 @@ CursorImpl::~CursorImpl()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vector2u hotspot)
|
bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vector2u hotspot)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
if (m_cursor)
|
if (m_cursor)
|
||||||
{
|
{
|
||||||
[m_cursor release];
|
[m_cursor release];
|
||||||
m_cursor = nil;
|
m_cursor = nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSSize nssize = NSMakeSize(size.x, size.y);
|
const NSSize nssize = NSMakeSize(size.x, size.y);
|
||||||
NSImage* image = [NSImage imageWithRawData:pixels andSize:nssize];
|
NSImage* const image = [NSImage imageWithRawData:pixels andSize:nssize];
|
||||||
NSPoint nshotspot = NSMakePoint(hotspot.x, hotspot.y);
|
const NSPoint nshotspot = NSMakePoint(hotspot.x, hotspot.y);
|
||||||
|
|
||||||
m_cursor = [[NSCursor alloc] initWithImage:image hotSpot:nshotspot];
|
m_cursor = [[NSCursor alloc] initWithImage:image hotSpot:nshotspot];
|
||||||
|
|
||||||
@ -84,8 +84,8 @@ bool CursorImpl::loadFromPixels(const std::uint8_t* pixels, Vector2u size, Vecto
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool CursorImpl::loadFromSystem(Cursor::Type type)
|
bool CursorImpl::loadFromSystem(Cursor::Type type)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
NSCursor* newCursor = nil;
|
NSCursor* newCursor = nil;
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
switch (type)
|
switch (type)
|
||||||
|
@ -689,7 +689,7 @@ String HIDInputManager::getDescription(Keyboard::Scancode code)
|
|||||||
default:
|
default:
|
||||||
{
|
{
|
||||||
// Phase 2: Try to convert the key to unicode
|
// Phase 2: Try to convert the key to unicode
|
||||||
UniChar unicode = toUnicode(localize(code));
|
const UniChar unicode = toUnicode(localize(code));
|
||||||
if (unicode != 0x00)
|
if (unicode != 0x00)
|
||||||
return String(static_cast<char32_t>(unicode));
|
return String(static_cast<char32_t>(unicode));
|
||||||
}
|
}
|
||||||
@ -705,8 +705,8 @@ String HIDInputManager::getDescription(Keyboard::Scancode code)
|
|||||||
HIDInputManager::HIDInputManager()
|
HIDInputManager::HIDInputManager()
|
||||||
{
|
{
|
||||||
// Create an HID Manager reference
|
// Create an HID Manager reference
|
||||||
m_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
|
m_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
|
||||||
IOReturn openStatus = IOHIDManagerOpen(m_manager, kIOHIDOptionsTypeNone);
|
const IOReturn openStatus = IOHIDManagerOpen(m_manager, kIOHIDOptionsTypeNone);
|
||||||
|
|
||||||
if (openStatus != kIOReturnSuccess)
|
if (openStatus != kIOReturnSuccess)
|
||||||
{
|
{
|
||||||
@ -754,7 +754,7 @@ void HIDInputManager::initializeKeyboard()
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto* keyboards = static_cast<NSSet*>(underlying); // Toll-Free Bridge
|
auto* const keyboards = static_cast<NSSet*>(underlying); // Toll-Free Bridge
|
||||||
for (id keyboard in keyboards)
|
for (id keyboard in keyboards)
|
||||||
loadKeyboard(static_cast<IOHIDDeviceRef>(keyboard));
|
loadKeyboard(static_cast<IOHIDDeviceRef>(keyboard));
|
||||||
|
|
||||||
@ -775,7 +775,7 @@ void HIDInputManager::loadKeyboard(IOHIDDeviceRef keyboard)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto* keys = static_cast<NSArray*>(underlying); // Toll-Free Bridge
|
auto* const keys = static_cast<NSArray*>(underlying); // Toll-Free Bridge
|
||||||
for (id key in keys)
|
for (id key in keys)
|
||||||
{
|
{
|
||||||
auto* elem = static_cast<IOHIDElementRef>(key);
|
auto* elem = static_cast<IOHIDElementRef>(key);
|
||||||
@ -790,8 +790,8 @@ void HIDInputManager::loadKeyboard(IOHIDDeviceRef keyboard)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void HIDInputManager::loadKey(IOHIDElementRef key)
|
void HIDInputManager::loadKey(IOHIDElementRef key)
|
||||||
{
|
{
|
||||||
std::uint32_t usage = IOHIDElementGetUsage(key);
|
const std::uint32_t usage = IOHIDElementGetUsage(key);
|
||||||
Keyboard::Scancode code = usageToScancode(usage);
|
const Keyboard::Scancode code = usageToScancode(usage);
|
||||||
if (code != Keyboard::Scan::Unknown)
|
if (code != Keyboard::Scan::Unknown)
|
||||||
{
|
{
|
||||||
CFRetain(key);
|
CFRetain(key);
|
||||||
@ -826,8 +826,8 @@ void HIDInputManager::buildMappings()
|
|||||||
// virtual code to a localized Key.
|
// virtual code to a localized Key.
|
||||||
for (int i = 0; i < static_cast<int>(Keyboard::Scan::ScancodeCount); ++i)
|
for (int i = 0; i < static_cast<int>(Keyboard::Scan::ScancodeCount); ++i)
|
||||||
{
|
{
|
||||||
auto scan = static_cast<Keyboard::Scancode>(i);
|
const auto scan = static_cast<Keyboard::Scancode>(i);
|
||||||
std::uint8_t virtualCode = scanToVirtualCode(scan);
|
const std::uint8_t virtualCode = scanToVirtualCode(scan);
|
||||||
|
|
||||||
if (virtualCode == unknownVirtualCode)
|
if (virtualCode == unknownVirtualCode)
|
||||||
continue;
|
continue;
|
||||||
@ -871,16 +871,16 @@ void HIDInputManager::buildMappings()
|
|||||||
std::uint32_t const modifiers = 0x100; // no modifiers
|
std::uint32_t const modifiers = 0x100; // no modifiers
|
||||||
|
|
||||||
// Use current layout for translation
|
// Use current layout for translation
|
||||||
OSStatus error = UCKeyTranslate(layout,
|
const OSStatus error = UCKeyTranslate(layout,
|
||||||
virtualCode,
|
virtualCode,
|
||||||
kUCKeyActionDown,
|
kUCKeyActionDown,
|
||||||
modifiers,
|
modifiers,
|
||||||
LMGetKbdType(),
|
LMGetKbdType(),
|
||||||
kUCKeyTranslateNoDeadKeysMask,
|
kUCKeyTranslateNoDeadKeysMask,
|
||||||
&deadKeyState,
|
&deadKeyState,
|
||||||
maxLength,
|
maxLength,
|
||||||
&length,
|
&length,
|
||||||
string);
|
string);
|
||||||
|
|
||||||
if (error != noErr)
|
if (error != noErr)
|
||||||
{
|
{
|
||||||
|
@ -55,7 +55,7 @@ namespace sf::priv
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window)
|
SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window)
|
||||||
{
|
{
|
||||||
id nsHandle = static_cast<id>(window.getSystemHandle());
|
const id nsHandle = static_cast<id>(window.getSystemHandle());
|
||||||
|
|
||||||
// Get our SFOpenGLView from ...
|
// Get our SFOpenGLView from ...
|
||||||
SFOpenGLView* view = nil;
|
SFOpenGLView* view = nil;
|
||||||
@ -70,7 +70,7 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window)
|
|||||||
{
|
{
|
||||||
if ([view isKindOfClass:[NSView class]])
|
if ([view isKindOfClass:[NSView class]])
|
||||||
{
|
{
|
||||||
NSArray* subviews = [view subviews];
|
NSArray* const subviews = [view subviews];
|
||||||
for (NSView* subview in subviews)
|
for (NSView* subview in subviews)
|
||||||
{
|
{
|
||||||
if ([subview isKindOfClass:[SFOpenGLView class]])
|
if ([subview isKindOfClass:[SFOpenGLView class]])
|
||||||
@ -91,7 +91,7 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window)
|
|||||||
else if ([nsHandle isKindOfClass:[NSView class]])
|
else if ([nsHandle isKindOfClass:[NSView class]])
|
||||||
{
|
{
|
||||||
// If system handle is a view then from a subview of kind SFOpenGLView.
|
// If system handle is a view then from a subview of kind SFOpenGLView.
|
||||||
NSArray* subviews = [nsHandle subviews];
|
NSArray* const subviews = [nsHandle subviews];
|
||||||
for (NSView* subview in subviews)
|
for (NSView* subview in subviews)
|
||||||
{
|
{
|
||||||
if ([subview isKindOfClass:[SFOpenGLView class]])
|
if ([subview isKindOfClass:[SFOpenGLView class]])
|
||||||
@ -120,7 +120,7 @@ SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const WindowBase& window)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool InputImpl::isKeyPressed(Keyboard::Key key)
|
bool InputImpl::isKeyPressed(Keyboard::Key key)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
return HIDInputManager::getInstance().isKeyPressed(key);
|
return HIDInputManager::getInstance().isKeyPressed(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -163,9 +163,9 @@ void InputImpl::setVirtualKeyboardVisible(bool /*visible*/)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool InputImpl::isMouseButtonPressed(Mouse::Button button)
|
bool InputImpl::isMouseButtonPressed(Mouse::Button button)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
NSUInteger state = [NSEvent pressedMouseButtons];
|
const NSUInteger state = [NSEvent pressedMouseButtons];
|
||||||
NSUInteger flag = 1 << button;
|
const NSUInteger flag = 1 << button;
|
||||||
return (state & flag) != 0;
|
return (state & flag) != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -173,12 +173,12 @@ bool InputImpl::isMouseButtonPressed(Mouse::Button button)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Vector2i InputImpl::getMousePosition()
|
Vector2i InputImpl::getMousePosition()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Reverse Y axis to match SFML coord.
|
// Reverse Y axis to match SFML coord.
|
||||||
NSPoint pos = [NSEvent mouseLocation];
|
NSPoint pos = [NSEvent mouseLocation];
|
||||||
pos.y = sf::VideoMode::getDesktopMode().size.y - pos.y;
|
pos.y = sf::VideoMode::getDesktopMode().size.y - pos.y;
|
||||||
|
|
||||||
int scale = static_cast<int>([[NSScreen mainScreen] backingScaleFactor]);
|
const int scale = static_cast<int>([[NSScreen mainScreen] backingScaleFactor]);
|
||||||
return Vector2i(static_cast<int>(pos.x), static_cast<int>(pos.y)) * scale;
|
return Vector2i(static_cast<int>(pos.x), static_cast<int>(pos.y)) * scale;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -186,17 +186,17 @@ Vector2i InputImpl::getMousePosition()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Vector2i InputImpl::getMousePosition(const WindowBase& relativeTo)
|
Vector2i InputImpl::getMousePosition(const WindowBase& relativeTo)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo);
|
SFOpenGLView* const view = getSFOpenGLViewFromSFMLWindow(relativeTo);
|
||||||
|
|
||||||
// No view ?
|
// No view ?
|
||||||
if (view == nil)
|
if (view == nil)
|
||||||
return Vector2i();
|
return Vector2i();
|
||||||
|
|
||||||
// Use -cursorPositionFromEvent: with nil.
|
// Use -cursorPositionFromEvent: with nil.
|
||||||
NSPoint pos = [view cursorPositionFromEvent:nil];
|
const NSPoint pos = [view cursorPositionFromEvent:nil];
|
||||||
|
|
||||||
int scale = static_cast<int>([view displayScaleFactor]);
|
const int scale = static_cast<int>([view displayScaleFactor]);
|
||||||
return Vector2i(static_cast<int>(pos.x), static_cast<int>(pos.y)) * scale;
|
return Vector2i(static_cast<int>(pos.x), static_cast<int>(pos.y)) * scale;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -204,10 +204,10 @@ Vector2i InputImpl::getMousePosition(const WindowBase& relativeTo)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void InputImpl::setMousePosition(const Vector2i& position)
|
void InputImpl::setMousePosition(const Vector2i& position)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Here we don't need to reverse the coordinates.
|
// Here we don't need to reverse the coordinates.
|
||||||
int scale = static_cast<int>([[NSScreen mainScreen] backingScaleFactor]);
|
const int scale = static_cast<int>([[NSScreen mainScreen] backingScaleFactor]);
|
||||||
CGPoint pos = CGPointMake(position.x / scale, position.y / scale);
|
const CGPoint pos = CGPointMake(position.x / scale, position.y / scale);
|
||||||
|
|
||||||
// Place the cursor.
|
// Place the cursor.
|
||||||
CGEventRef event = CGEventCreateMouseEvent(nullptr,
|
CGEventRef event = CGEventCreateMouseEvent(nullptr,
|
||||||
@ -223,17 +223,17 @@ void InputImpl::setMousePosition(const Vector2i& position)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void InputImpl::setMousePosition(const Vector2i& position, const WindowBase& relativeTo)
|
void InputImpl::setMousePosition(const Vector2i& position, const WindowBase& relativeTo)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo);
|
SFOpenGLView* const view = getSFOpenGLViewFromSFMLWindow(relativeTo);
|
||||||
|
|
||||||
// No view ?
|
// No view ?
|
||||||
if (view == nil)
|
if (view == nil)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// Let SFOpenGLView compute the position in global coordinate
|
// Let SFOpenGLView compute the position in global coordinate
|
||||||
int scale = static_cast<int>([view displayScaleFactor]);
|
const int scale = static_cast<int>([view displayScaleFactor]);
|
||||||
NSPoint p = NSMakePoint(position.x / scale, position.y / scale);
|
NSPoint p = NSMakePoint(position.x / scale, position.y / scale);
|
||||||
p = [view computeGlobalPositionOfRelativePoint:p];
|
p = [view computeGlobalPositionOfRelativePoint:p];
|
||||||
setMousePosition(sf::Vector2i(static_cast<int>(p.x), static_cast<int>(p.y)) * scale);
|
setMousePosition(sf::Vector2i(static_cast<int>(p.x), static_cast<int>(p.y)) * scale);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -46,9 +46,9 @@ bool joystickButtonSortPredicate(IOHIDElementRef b1, IOHIDElementRef b2)
|
|||||||
// Convert a CFStringRef to std::string
|
// Convert a CFStringRef to std::string
|
||||||
std::string stringFromCFString(CFStringRef cfString)
|
std::string stringFromCFString(CFStringRef cfString)
|
||||||
{
|
{
|
||||||
CFIndex length = CFStringGetLength(cfString);
|
const CFIndex length = CFStringGetLength(cfString);
|
||||||
std::vector<char> str(static_cast<std::size_t>(length));
|
std::vector<char> str(static_cast<std::size_t>(length));
|
||||||
CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
|
const CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
|
||||||
CFStringGetCString(cfString, str.data(), maxSize, kCFStringEncodingUTF8);
|
CFStringGetCString(cfString, str.data(), maxSize, kCFStringEncodingUTF8);
|
||||||
return str.data();
|
return str.data();
|
||||||
}
|
}
|
||||||
@ -110,8 +110,8 @@ void JoystickImpl::cleanup()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool JoystickImpl::isConnected(unsigned int index)
|
bool JoystickImpl::isConnected(unsigned int index)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
bool state = false; // Is the index-th joystick connected?
|
bool state = false; // Is the index-th joystick connected?
|
||||||
|
|
||||||
// First, let's check if the device was previously detected:
|
// First, let's check if the device was previously detected:
|
||||||
if (m_locationIDs[index] != 0)
|
if (m_locationIDs[index] != 0)
|
||||||
@ -134,7 +134,7 @@ bool JoystickImpl::isConnected(unsigned int index)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
unsigned int connectedCount = HIDJoystickManager::getInstance().getJoystickCount();
|
const unsigned int connectedCount = HIDJoystickManager::getInstance().getJoystickCount();
|
||||||
|
|
||||||
if (connectedCount > openedCount)
|
if (connectedCount > openedCount)
|
||||||
{
|
{
|
||||||
@ -143,7 +143,7 @@ bool JoystickImpl::isConnected(unsigned int index)
|
|||||||
|
|
||||||
if (devices != nullptr)
|
if (devices != nullptr)
|
||||||
{
|
{
|
||||||
CFIndex size = CFSetGetCount(devices);
|
const CFIndex size = CFSetGetCount(devices);
|
||||||
if (size > 0)
|
if (size > 0)
|
||||||
{
|
{
|
||||||
std::vector<CFTypeRef> array(static_cast<std::size_t>(size)); // array of IOHIDDeviceRef
|
std::vector<CFTypeRef> array(static_cast<std::size_t>(size)); // array of IOHIDDeviceRef
|
||||||
@ -155,7 +155,7 @@ bool JoystickImpl::isConnected(unsigned int index)
|
|||||||
for (CFIndex didx(0); !state && didx < size; ++didx)
|
for (CFIndex didx(0); !state && didx < size; ++didx)
|
||||||
{
|
{
|
||||||
auto* d = static_cast<IOHIDDeviceRef>(const_cast<void*>(array[static_cast<std::size_t>(didx)]));
|
auto* d = static_cast<IOHIDDeviceRef>(const_cast<void*>(array[static_cast<std::size_t>(didx)]));
|
||||||
Location dloc = HIDInputManager::getLocationID(d);
|
const Location dloc = HIDInputManager::getLocationID(d);
|
||||||
|
|
||||||
bool foundJ = false;
|
bool foundJ = false;
|
||||||
for (unsigned int j(0); !foundJ && j < Joystick::Count; ++j)
|
for (unsigned int j(0); !foundJ && j < Joystick::Count; ++j)
|
||||||
@ -186,10 +186,10 @@ bool JoystickImpl::isConnected(unsigned int index)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool JoystickImpl::open(unsigned int index)
|
bool JoystickImpl::open(unsigned int index)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
m_index = index;
|
m_index = index;
|
||||||
m_hat = nullptr;
|
m_hat = nullptr;
|
||||||
Location deviceLoc = m_locationIDs[index]; // The device we need to load
|
const Location deviceLoc = m_locationIDs[index]; // The device we need to load
|
||||||
|
|
||||||
// Get all devices
|
// Get all devices
|
||||||
CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks();
|
CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks();
|
||||||
@ -197,7 +197,7 @@ bool JoystickImpl::open(unsigned int index)
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
// Get a usable copy of the joysticks devices.
|
// Get a usable copy of the joysticks devices.
|
||||||
CFIndex joysticksCount = CFSetGetCount(devices);
|
const CFIndex joysticksCount = CFSetGetCount(devices);
|
||||||
std::vector<CFTypeRef> devicesArray(static_cast<std::size_t>(joysticksCount));
|
std::vector<CFTypeRef> devicesArray(static_cast<std::size_t>(joysticksCount));
|
||||||
CFSetGetValues(devices, devicesArray.data());
|
CFSetGetValues(devices, devicesArray.data());
|
||||||
|
|
||||||
@ -230,7 +230,7 @@ bool JoystickImpl::open(unsigned int index)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Go through all connected elements.
|
// Go through all connected elements.
|
||||||
CFIndex elementsCount = CFArrayGetCount(elements);
|
const CFIndex elementsCount = CFArrayGetCount(elements);
|
||||||
for (int i = 0; i < elementsCount; ++i)
|
for (int i = 0; i < elementsCount; ++i)
|
||||||
{
|
{
|
||||||
auto* element = static_cast<IOHIDElementRef>(const_cast<void*>(CFArrayGetValueAtIndex(elements, i)));
|
auto* element = static_cast<IOHIDElementRef>(const_cast<void*>(CFArrayGetValueAtIndex(elements, i)));
|
||||||
@ -270,8 +270,8 @@ bool JoystickImpl::open(unsigned int index)
|
|||||||
// We assume this model here as well. Hence, with 4 switches and intermediate
|
// We assume this model here as well. Hence, with 4 switches and intermediate
|
||||||
// positions we have 8 values (0-7) plus the "null" state (8).
|
// positions we have 8 values (0-7) plus the "null" state (8).
|
||||||
{
|
{
|
||||||
CFIndex min = IOHIDElementGetLogicalMin(element);
|
const CFIndex min = IOHIDElementGetLogicalMin(element);
|
||||||
CFIndex max = IOHIDElementGetLogicalMax(element);
|
const CFIndex max = IOHIDElementGetLogicalMax(element);
|
||||||
|
|
||||||
if (min != 0 || max != 7)
|
if (min != 0 || max != 7)
|
||||||
{
|
{
|
||||||
@ -346,7 +346,7 @@ bool JoystickImpl::open(unsigned int index)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void JoystickImpl::close()
|
void JoystickImpl::close()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
|
|
||||||
for (IOHIDElementRef iohidElementRef : m_buttons)
|
for (IOHIDElementRef iohidElementRef : m_buttons)
|
||||||
CFRelease(iohidElementRef);
|
CFRelease(iohidElementRef);
|
||||||
@ -371,8 +371,8 @@ void JoystickImpl::close()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
JoystickCaps JoystickImpl::getCapabilities() const
|
JoystickCaps JoystickImpl::getCapabilities() const
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
JoystickCaps caps;
|
JoystickCaps caps;
|
||||||
|
|
||||||
// Buttons:
|
// Buttons:
|
||||||
caps.buttonCount = static_cast<unsigned int>(m_buttons.size());
|
caps.buttonCount = static_cast<unsigned int>(m_buttons.size());
|
||||||
@ -391,7 +391,7 @@ JoystickCaps JoystickImpl::getCapabilities() const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Joystick::Identification JoystickImpl::getIdentification() const
|
Joystick::Identification JoystickImpl::getIdentification() const
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
return m_identification;
|
return m_identification;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -399,7 +399,7 @@ Joystick::Identification JoystickImpl::getIdentification() const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
JoystickState JoystickImpl::update()
|
JoystickState JoystickImpl::update()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
static constexpr JoystickState disconnectedState; // return this if joystick was disconnected
|
static constexpr JoystickState disconnectedState; // return this if joystick was disconnected
|
||||||
JoystickState state; // otherwise return that
|
JoystickState state; // otherwise return that
|
||||||
state.connected = true;
|
state.connected = true;
|
||||||
@ -408,7 +408,7 @@ JoystickState JoystickImpl::update()
|
|||||||
// by the joystick manager. So we don't release buttons nor axes here.
|
// by the joystick manager. So we don't release buttons nor axes here.
|
||||||
|
|
||||||
// First, let's determine if the joystick is still connected
|
// First, let's determine if the joystick is still connected
|
||||||
Location selfLoc = m_locationIDs[m_index];
|
const Location selfLoc = m_locationIDs[m_index];
|
||||||
|
|
||||||
// Get all devices
|
// Get all devices
|
||||||
CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks();
|
CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks();
|
||||||
@ -416,7 +416,7 @@ JoystickState JoystickImpl::update()
|
|||||||
return disconnectedState;
|
return disconnectedState;
|
||||||
|
|
||||||
// Get a usable copy of the joysticks devices.
|
// Get a usable copy of the joysticks devices.
|
||||||
CFIndex joysticksCount = CFSetGetCount(devices);
|
const CFIndex joysticksCount = CFSetGetCount(devices);
|
||||||
std::vector<CFTypeRef> devicesArray(static_cast<std::size_t>(joysticksCount));
|
std::vector<CFTypeRef> devicesArray(static_cast<std::size_t>(joysticksCount));
|
||||||
CFSetGetValues(devices, devicesArray.data());
|
CFSetGetValues(devices, devicesArray.data());
|
||||||
|
|
||||||
@ -475,12 +475,12 @@ JoystickState JoystickImpl::update()
|
|||||||
// This method might not be very accurate (the "0 position" can be
|
// This method might not be very accurate (the "0 position" can be
|
||||||
// slightly shift with some device) but we don't care because most
|
// slightly shift with some device) but we don't care because most
|
||||||
// of devices are so sensitive that this is not relevant.
|
// of devices are so sensitive that this is not relevant.
|
||||||
auto physicalMax = static_cast<double>(IOHIDElementGetPhysicalMax(iohidElementRef));
|
const auto physicalMax = static_cast<double>(IOHIDElementGetPhysicalMax(iohidElementRef));
|
||||||
auto physicalMin = static_cast<double>(IOHIDElementGetPhysicalMin(iohidElementRef));
|
const auto physicalMin = static_cast<double>(IOHIDElementGetPhysicalMin(iohidElementRef));
|
||||||
double scaledMin = -100;
|
const double scaledMin = -100;
|
||||||
double scaledMax = 100;
|
const double scaledMax = 100;
|
||||||
double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical);
|
const double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical);
|
||||||
auto scaledValue = static_cast<float>(
|
const auto scaledValue = static_cast<float>(
|
||||||
(((physicalValue - physicalMin) * (scaledMax - scaledMin)) / (physicalMax - physicalMin)) + scaledMin);
|
(((physicalValue - physicalMin) * (scaledMax - scaledMin)) / (physicalMax - physicalMin)) + scaledMin);
|
||||||
state.axes[axis] = scaledValue;
|
state.axes[axis] = scaledValue;
|
||||||
}
|
}
|
||||||
@ -502,7 +502,7 @@ JoystickState JoystickImpl::update()
|
|||||||
return disconnectedState;
|
return disconnectedState;
|
||||||
}
|
}
|
||||||
|
|
||||||
CFIndex raw = IOHIDValueGetIntegerValue(value);
|
const CFIndex raw = IOHIDValueGetIntegerValue(value);
|
||||||
|
|
||||||
// Load PovX
|
// Load PovX
|
||||||
switch (raw)
|
switch (raw)
|
||||||
|
@ -43,7 +43,7 @@ namespace sf::priv
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
SFContext::SFContext(SFContext* shared)
|
SFContext::SFContext(SFContext* shared)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Create the context
|
// Create the context
|
||||||
createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, ContextSettings(0, 0, 0));
|
createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, ContextSettings(0, 0, 0));
|
||||||
}
|
}
|
||||||
@ -52,7 +52,7 @@ SFContext::SFContext(SFContext* shared)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel)
|
SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const WindowImpl& owner, unsigned int bitsPerPixel)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Create the context.
|
// Create the context.
|
||||||
createContext(shared, bitsPerPixel, settings);
|
createContext(shared, bitsPerPixel, settings);
|
||||||
|
|
||||||
@ -65,7 +65,7 @@ SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const W
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const Vector2u& size)
|
SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const Vector2u& size)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Ensure the process is setup in order to create a valid window.
|
// Ensure the process is setup in order to create a valid window.
|
||||||
WindowImplCocoa::setUpProcess();
|
WindowImplCocoa::setUpProcess();
|
||||||
|
|
||||||
@ -88,7 +88,7 @@ SFContext::SFContext(SFContext* shared, const ContextSettings& settings, const V
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
SFContext::~SFContext()
|
SFContext::~SFContext()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Notify unshared OpenGL resources of context destruction
|
// Notify unshared OpenGL resources of context destruction
|
||||||
cleanupUnsharedResources();
|
cleanupUnsharedResources();
|
||||||
|
|
||||||
@ -107,8 +107,8 @@ SFContext::~SFContext()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
GlFunctionPointer SFContext::getFunction(const char* name)
|
GlFunctionPointer SFContext::getFunction(const char* name)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
static void* image = nullptr;
|
static void* image = nullptr;
|
||||||
|
|
||||||
if (!image)
|
if (!image)
|
||||||
image = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
|
image = dlopen("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
|
||||||
@ -120,7 +120,7 @@ GlFunctionPointer SFContext::getFunction(const char* name)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool SFContext::makeCurrent(bool current)
|
bool SFContext::makeCurrent(bool current)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
if (current)
|
if (current)
|
||||||
{
|
{
|
||||||
[m_context makeCurrentContext];
|
[m_context makeCurrentContext];
|
||||||
@ -137,7 +137,7 @@ bool SFContext::makeCurrent(bool current)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void SFContext::display()
|
void SFContext::display()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_context flushBuffer];
|
[m_context flushBuffer];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -145,8 +145,8 @@ void SFContext::display()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void SFContext::setVerticalSyncEnabled(bool enabled)
|
void SFContext::setVerticalSyncEnabled(bool enabled)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
GLint swapInterval = enabled ? 1 : 0;
|
const GLint swapInterval = enabled ? 1 : 0;
|
||||||
|
|
||||||
[m_context setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
|
[m_context setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
|
||||||
}
|
}
|
||||||
@ -155,7 +155,7 @@ void SFContext::setVerticalSyncEnabled(bool enabled)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings)
|
void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Save the settings. (OpenGL version is updated elsewhere.)
|
// Save the settings. (OpenGL version is updated elsewhere.)
|
||||||
m_settings = settings;
|
m_settings = settings;
|
||||||
|
|
||||||
@ -215,7 +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.
|
// 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.
|
// >=3.0 are mapped to a 3.2 core profile.
|
||||||
bool legacy = m_settings.majorVersion < 3;
|
const bool legacy = m_settings.majorVersion < 3;
|
||||||
|
|
||||||
if (legacy)
|
if (legacy)
|
||||||
{
|
{
|
||||||
@ -250,7 +250,7 @@ void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, cons
|
|||||||
m_settings.sRgbCapable = true;
|
m_settings.sRgbCapable = true;
|
||||||
|
|
||||||
// Create the pixel format.
|
// Create the pixel format.
|
||||||
NSOpenGLPixelFormat* pixFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs.data()];
|
NSOpenGLPixelFormat* const pixFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs.data()];
|
||||||
|
|
||||||
if (pixFmt == nil)
|
if (pixFmt == nil)
|
||||||
{
|
{
|
||||||
@ -259,7 +259,7 @@ void SFContext::createContext(SFContext* shared, unsigned int bitsPerPixel, cons
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Use the shared context if one is given.
|
// Use the shared context if one is given.
|
||||||
NSOpenGLContext* sharedContext = shared != nullptr ? shared->m_context : nil;
|
NSOpenGLContext* const sharedContext = shared != nullptr ? shared->m_context : nil;
|
||||||
|
|
||||||
if (sharedContext != nil)
|
if (sharedContext != nil)
|
||||||
{
|
{
|
||||||
|
@ -133,7 +133,7 @@ void initialiseKeyboardHelper()
|
|||||||
if (isStateInitialized)
|
if (isStateInitialized)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
NSUInteger modifiers = [[NSApp currentEvent] modifierFlags];
|
const NSUInteger modifiers = [[NSApp currentEvent] modifierFlags];
|
||||||
|
|
||||||
// Load current keyboard state
|
// Load current keyboard state
|
||||||
state.leftShiftWasDown = isKeyMaskActive(modifiers, NSLeftShiftKeyMask);
|
state.leftShiftWasDown = isKeyMaskActive(modifiers, NSLeftShiftKeyMask);
|
||||||
@ -245,10 +245,10 @@ void processOneModifier(NSUInteger modifiers,
|
|||||||
sf::priv::WindowImplCocoa& requester)
|
sf::priv::WindowImplCocoa& requester)
|
||||||
{
|
{
|
||||||
// Setup a potential event key.
|
// Setup a potential event key.
|
||||||
sf::Event::KeyEvent event = keyEventWithModifiers(modifiers, key, code);
|
const sf::Event::KeyEvent event = keyEventWithModifiers(modifiers, key, code);
|
||||||
|
|
||||||
// State
|
// State
|
||||||
BOOL isDown = isKeyMaskActive(modifiers, mask);
|
const BOOL isDown = isKeyMaskActive(modifiers, mask);
|
||||||
|
|
||||||
// Check for key pressed event
|
// Check for key pressed event
|
||||||
if (isDown && !wasDown)
|
if (isDown && !wasDown)
|
||||||
|
@ -51,7 +51,7 @@ std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
|
|||||||
return modes;
|
return modes;
|
||||||
}
|
}
|
||||||
|
|
||||||
VideoMode desktop = getDesktopMode();
|
const VideoMode desktop = getDesktopMode();
|
||||||
|
|
||||||
// Loop on each mode and convert it into a sf::VideoMode object.
|
// Loop on each mode and convert it into a sf::VideoMode object.
|
||||||
const CFIndex modesCount = CFArrayGetCount(cgmodes);
|
const CFIndex modesCount = CFArrayGetCount(cgmodes);
|
||||||
@ -59,7 +59,7 @@ std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
|
|||||||
{
|
{
|
||||||
auto* cgmode = static_cast<CGDisplayModeRef>(const_cast<void*>(CFArrayGetValueAtIndex(cgmodes, i)));
|
auto* cgmode = static_cast<CGDisplayModeRef>(const_cast<void*>(CFArrayGetValueAtIndex(cgmodes, i)));
|
||||||
|
|
||||||
VideoMode mode = convertCGModeToSFMode(cgmode);
|
const VideoMode mode = convertCGModeToSFMode(cgmode);
|
||||||
|
|
||||||
// Skip if bigger than desktop as we currently don't perform hard resolution switch
|
// Skip if bigger than desktop as we currently don't perform hard resolution switch
|
||||||
if ((mode.size.x > desktop.size.x) || (mode.size.y > desktop.size.y))
|
if ((mode.size.x > desktop.size.x) || (mode.size.y > desktop.size.y))
|
||||||
@ -85,8 +85,8 @@ VideoMode VideoModeImpl::getDesktopMode()
|
|||||||
// Rely exclusively on mode and convertCGModeToSFMode
|
// Rely exclusively on mode and convertCGModeToSFMode
|
||||||
// instead of display id and CGDisplayPixelsHigh/Wide.
|
// instead of display id and CGDisplayPixelsHigh/Wide.
|
||||||
|
|
||||||
CGDirectDisplayID display = CGMainDisplayID();
|
const CGDirectDisplayID display = CGMainDisplayID();
|
||||||
CGDisplayModeRef cgmode = CGDisplayCopyDisplayMode(display);
|
CGDisplayModeRef cgmode = CGDisplayCopyDisplayMode(display);
|
||||||
|
|
||||||
mode = convertCGModeToSFMode(cgmode);
|
mode = convertCGModeToSFMode(cgmode);
|
||||||
|
|
||||||
|
@ -60,7 +60,7 @@ bool isCursorHidden = false; // initially, the cursor is visible
|
|||||||
////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////
|
||||||
void hideMouseCursor()
|
void hideMouseCursor()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
if (!isCursorHidden)
|
if (!isCursorHidden)
|
||||||
{
|
{
|
||||||
[NSCursor hide];
|
[NSCursor hide];
|
||||||
@ -72,7 +72,7 @@ void hideMouseCursor()
|
|||||||
////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////
|
||||||
void showMouseCursor()
|
void showMouseCursor()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
if (isCursorHidden)
|
if (isCursorHidden)
|
||||||
{
|
{
|
||||||
[NSCursor unhide];
|
[NSCursor unhide];
|
||||||
@ -86,9 +86,9 @@ void showMouseCursor()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
WindowImplCocoa::WindowImplCocoa(WindowHandle handle)
|
WindowImplCocoa::WindowImplCocoa(WindowHandle handle)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Treat the handle as it real type
|
// Treat the handle as it real type
|
||||||
id nsHandle = static_cast<id>(handle);
|
const id nsHandle = static_cast<id>(handle);
|
||||||
if ([nsHandle isKindOfClass:[NSWindow class]])
|
if ([nsHandle isKindOfClass:[NSWindow class]])
|
||||||
{
|
{
|
||||||
// We have a window.
|
// We have a window.
|
||||||
@ -119,7 +119,7 @@ WindowImplCocoa::WindowImplCocoa(WindowHandle handle)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
WindowImplCocoa::WindowImplCocoa(VideoMode mode, const String& title, unsigned long style, const ContextSettings& /*settings*/)
|
WindowImplCocoa::WindowImplCocoa(VideoMode mode, const String& title, unsigned long style, const ContextSettings& /*settings*/)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
// Transform the app process.
|
// Transform the app process.
|
||||||
setUpProcess();
|
setUpProcess();
|
||||||
|
|
||||||
@ -135,7 +135,7 @@ WindowImplCocoa::WindowImplCocoa(VideoMode mode, const String& title, unsigned l
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
WindowImplCocoa::~WindowImplCocoa()
|
WindowImplCocoa::~WindowImplCocoa()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_delegate closeWindow];
|
[m_delegate closeWindow];
|
||||||
// Tell the window/view controller (and the OpenGL view) that the delegate
|
// Tell the window/view controller (and the OpenGL view) that the delegate
|
||||||
// (this object) no longer exists to prevent events being sent to the window
|
// (this object) no longer exists to prevent events being sent to the window
|
||||||
@ -144,10 +144,10 @@ WindowImplCocoa::~WindowImplCocoa()
|
|||||||
[m_delegate release];
|
[m_delegate release];
|
||||||
|
|
||||||
// Put the next window in front, if any.
|
// Put the next window in front, if any.
|
||||||
NSArray* windows = [NSApp orderedWindows];
|
NSArray* const windows = [NSApp orderedWindows];
|
||||||
if ([windows count] > 0)
|
if ([windows count] > 0)
|
||||||
{
|
{
|
||||||
NSWindow* nextWindow = [windows objectAtIndex:0];
|
NSWindow* const nextWindow = [windows objectAtIndex:0];
|
||||||
if ([nextWindow isVisible])
|
if ([nextWindow isVisible])
|
||||||
[nextWindow makeKeyAndOrderFront:nil];
|
[nextWindow makeKeyAndOrderFront:nil];
|
||||||
}
|
}
|
||||||
@ -157,7 +157,7 @@ WindowImplCocoa::~WindowImplCocoa()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::applyContext(NSOpenGLContextRef context) const
|
void WindowImplCocoa::applyContext(NSOpenGLContextRef context) const
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_delegate applyContext:context];
|
[m_delegate applyContext:context];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -165,8 +165,8 @@ void WindowImplCocoa::applyContext(NSOpenGLContextRef context) const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setUpProcess()
|
void WindowImplCocoa::setUpProcess()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
static bool isTheProcessSetAsApplication = false;
|
static bool isTheProcessSetAsApplication = false;
|
||||||
|
|
||||||
if (!isTheProcessSetAsApplication)
|
if (!isTheProcessSetAsApplication)
|
||||||
{
|
{
|
||||||
@ -381,7 +381,7 @@ void WindowImplCocoa::textEntered(unichar charcode)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::processEvents()
|
void WindowImplCocoa::processEvents()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_delegate processEvent];
|
[m_delegate processEvent];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -391,7 +391,7 @@ void WindowImplCocoa::processEvents()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
WindowHandle WindowImplCocoa::getSystemHandle() const
|
WindowHandle WindowImplCocoa::getSystemHandle() const
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
return [m_delegate getSystemHandle];
|
return [m_delegate getSystemHandle];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -399,9 +399,9 @@ WindowHandle WindowImplCocoa::getSystemHandle() const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Vector2i WindowImplCocoa::getPosition() const
|
Vector2i WindowImplCocoa::getPosition() const
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
NSPoint pos = [m_delegate position];
|
const NSPoint pos = [m_delegate position];
|
||||||
sf::Vector2i ret(static_cast<int>(pos.x), static_cast<int>(pos.y));
|
sf::Vector2i ret(static_cast<int>(pos.x), static_cast<int>(pos.y));
|
||||||
scaleOutXY(ret, m_delegate);
|
scaleOutXY(ret, m_delegate);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
@ -410,8 +410,8 @@ Vector2i WindowImplCocoa::getPosition() const
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setPosition(const Vector2i& position)
|
void WindowImplCocoa::setPosition(const Vector2i& position)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
sf::Vector2i backingPosition = position;
|
sf::Vector2i backingPosition = position;
|
||||||
scaleInXY(backingPosition, m_delegate);
|
scaleInXY(backingPosition, m_delegate);
|
||||||
[m_delegate setWindowPositionToX:backingPosition.x Y:backingPosition.y];
|
[m_delegate setWindowPositionToX:backingPosition.x Y:backingPosition.y];
|
||||||
}
|
}
|
||||||
@ -420,9 +420,9 @@ void WindowImplCocoa::setPosition(const Vector2i& position)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
Vector2u WindowImplCocoa::getSize() const
|
Vector2u WindowImplCocoa::getSize() const
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
NSSize size = [m_delegate size];
|
const NSSize size = [m_delegate size];
|
||||||
Vector2u ret(static_cast<unsigned int>(size.width), static_cast<unsigned int>(size.height));
|
Vector2u ret(static_cast<unsigned int>(size.width), static_cast<unsigned int>(size.height));
|
||||||
scaleOutXY(ret, m_delegate);
|
scaleOutXY(ret, m_delegate);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
@ -440,7 +440,7 @@ void WindowImplCocoa::setSize(const Vector2u& size)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setTitle(const String& title)
|
void WindowImplCocoa::setTitle(const String& title)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_delegate changeTitle:sfStringToNSString(title)];
|
[m_delegate changeTitle:sfStringToNSString(title)];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -448,7 +448,7 @@ void WindowImplCocoa::setTitle(const String& title)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setIcon(const Vector2u& size, const std::uint8_t* pixels)
|
void WindowImplCocoa::setIcon(const Vector2u& size, const std::uint8_t* pixels)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_delegate setIconTo:size.x by:size.y with:pixels];
|
[m_delegate setIconTo:size.x by:size.y with:pixels];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -456,7 +456,7 @@ void WindowImplCocoa::setIcon(const Vector2u& size, const std::uint8_t* pixels)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setVisible(bool visible)
|
void WindowImplCocoa::setVisible(bool visible)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
if (visible)
|
if (visible)
|
||||||
[m_delegate showWindow];
|
[m_delegate showWindow];
|
||||||
else
|
else
|
||||||
@ -467,7 +467,7 @@ void WindowImplCocoa::setVisible(bool visible)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setMouseCursorVisible(bool visible)
|
void WindowImplCocoa::setMouseCursorVisible(bool visible)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
m_showCursor = visible;
|
m_showCursor = visible;
|
||||||
|
|
||||||
// If the mouse is over the window, we apply the new setting
|
// If the mouse is over the window, we apply the new setting
|
||||||
@ -484,7 +484,7 @@ void WindowImplCocoa::setMouseCursorVisible(bool visible)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setMouseCursorGrabbed(bool grabbed)
|
void WindowImplCocoa::setMouseCursorGrabbed(bool grabbed)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_delegate setCursorGrabbed:grabbed];
|
[m_delegate setCursorGrabbed:grabbed];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -492,7 +492,7 @@ void WindowImplCocoa::setMouseCursorGrabbed(bool grabbed)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setMouseCursor(const CursorImpl& cursor)
|
void WindowImplCocoa::setMouseCursor(const CursorImpl& cursor)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_delegate setCursor:cursor.m_cursor];
|
[m_delegate setCursor:cursor.m_cursor];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -500,7 +500,7 @@ void WindowImplCocoa::setMouseCursor(const CursorImpl& cursor)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::setKeyRepeatEnabled(bool enabled)
|
void WindowImplCocoa::setKeyRepeatEnabled(bool enabled)
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
if (enabled)
|
if (enabled)
|
||||||
[m_delegate enableKeyRepeat];
|
[m_delegate enableKeyRepeat];
|
||||||
else
|
else
|
||||||
@ -511,7 +511,7 @@ void WindowImplCocoa::setKeyRepeatEnabled(bool enabled)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WindowImplCocoa::requestFocus()
|
void WindowImplCocoa::requestFocus()
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
[m_delegate requestFocus];
|
[m_delegate requestFocus];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -519,7 +519,7 @@ void WindowImplCocoa::requestFocus()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool WindowImplCocoa::hasFocus() const
|
bool WindowImplCocoa::hasFocus() const
|
||||||
{
|
{
|
||||||
AutoreleasePool pool;
|
const AutoreleasePool pool;
|
||||||
return [m_delegate hasFocus];
|
return [m_delegate hasFocus];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -38,7 +38,7 @@ NSString* stringToNSString(const std::string& string)
|
|||||||
std::string utf8;
|
std::string utf8;
|
||||||
utf8.reserve(string.size() + 1);
|
utf8.reserve(string.size() + 1);
|
||||||
sf::Utf8::fromAnsi(string.begin(), string.end(), std::back_inserter(utf8));
|
sf::Utf8::fromAnsi(string.begin(), string.end(), std::back_inserter(utf8));
|
||||||
NSString* str = [NSString stringWithCString:utf8.c_str() encoding:NSUTF8StringEncoding];
|
NSString* const str = [NSString stringWithCString:utf8.c_str() encoding:NSUTF8StringEncoding];
|
||||||
|
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
@ -46,7 +46,7 @@ NSString* stringToNSString(const std::string& string)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
NSString* sfStringToNSString(const sf::String& string)
|
NSString* sfStringToNSString(const sf::String& string)
|
||||||
{
|
{
|
||||||
auto length = static_cast<std::uint32_t>(string.getSize() * sizeof(std::uint32_t));
|
const auto length = static_cast<std::uint32_t>(string.getSize() * sizeof(std::uint32_t));
|
||||||
const void* data = reinterpret_cast<const void*>(string.getData());
|
const void* data = reinterpret_cast<const void*>(string.getData());
|
||||||
|
|
||||||
NSStringEncoding encoding;
|
NSStringEncoding encoding;
|
||||||
@ -55,6 +55,6 @@ NSString* sfStringToNSString(const sf::String& string)
|
|||||||
else
|
else
|
||||||
encoding = NSUTF32BigEndianStringEncoding;
|
encoding = NSUTF32BigEndianStringEncoding;
|
||||||
|
|
||||||
NSString* str = [[NSString alloc] initWithBytes:data length:length encoding:encoding];
|
NSString* const str = [[NSString alloc] initWithBytes:data length:length encoding:encoding];
|
||||||
return [str autorelease];
|
return [str autorelease];
|
||||||
}
|
}
|
||||||
|
@ -86,8 +86,8 @@ void ClipboardImpl::setString(const String& text)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create a Win32-compatible string
|
// Create a Win32-compatible string
|
||||||
std::size_t stringSize = (text.getSize() + 1) * sizeof(WCHAR);
|
const std::size_t stringSize = (text.getSize() + 1) * sizeof(WCHAR);
|
||||||
HANDLE stringHandle = GlobalAlloc(GMEM_MOVEABLE, stringSize);
|
HANDLE stringHandle = GlobalAlloc(GMEM_MOVEABLE, stringSize);
|
||||||
|
|
||||||
if (stringHandle)
|
if (stringHandle)
|
||||||
{
|
{
|
||||||
|
@ -489,7 +489,7 @@ WORD sfScanToWinScanExtended(Keyboard::Scancode code)
|
|||||||
|
|
||||||
UINT sfScanToVirtualKey(Keyboard::Scancode code)
|
UINT sfScanToVirtualKey(Keyboard::Scancode code)
|
||||||
{
|
{
|
||||||
WORD winScancode = sfScanToWinScan(code);
|
const WORD winScancode = sfScanToWinScan(code);
|
||||||
|
|
||||||
// Manually map non-extended key codes
|
// Manually map non-extended key codes
|
||||||
// clang-format off
|
// clang-format off
|
||||||
@ -544,9 +544,9 @@ void InputImpl::ensureMappings()
|
|||||||
// Phase 2: Translate scancode to virtual code to key names
|
// Phase 2: Translate scancode to virtual code to key names
|
||||||
for (int i = 0; i < static_cast<int>(Keyboard::Scan::ScancodeCount); ++i)
|
for (int i = 0; i < static_cast<int>(Keyboard::Scan::ScancodeCount); ++i)
|
||||||
{
|
{
|
||||||
auto scan = static_cast<Keyboard::Scancode>(i);
|
const auto scan = static_cast<Keyboard::Scancode>(i);
|
||||||
UINT virtualKey = sfScanToVirtualKey(scan);
|
const UINT virtualKey = sfScanToVirtualKey(scan);
|
||||||
Keyboard::Key key = virtualKeyToSfKey(virtualKey);
|
const Keyboard::Key key = virtualKeyToSfKey(virtualKey);
|
||||||
if (key != Keyboard::Unknown && m_keyToScancodeMapping[key] == Keyboard::Scan::Unknown)
|
if (key != Keyboard::Unknown && m_keyToScancodeMapping[key] == Keyboard::Scan::Unknown)
|
||||||
m_keyToScancodeMapping[key] = scan;
|
m_keyToScancodeMapping[key] = scan;
|
||||||
m_scancodeToKeyMapping[static_cast<std::size_t>(scan)] = key;
|
m_scancodeToKeyMapping[static_cast<std::size_t>(scan)] = key;
|
||||||
@ -558,14 +558,14 @@ void InputImpl::ensureMappings()
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool InputImpl::isKeyPressed(Keyboard::Key key)
|
bool InputImpl::isKeyPressed(Keyboard::Key key)
|
||||||
{
|
{
|
||||||
int virtualKey = sfKeyToVirtualKey(key);
|
const int virtualKey = sfKeyToVirtualKey(key);
|
||||||
return (GetAsyncKeyState(virtualKey) & 0x8000) != 0;
|
return (GetAsyncKeyState(virtualKey) & 0x8000) != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
bool InputImpl::isKeyPressed(Keyboard::Scancode code)
|
bool InputImpl::isKeyPressed(Keyboard::Scancode code)
|
||||||
{
|
{
|
||||||
UINT virtualKey = sfScanToVirtualKey(code);
|
const UINT virtualKey = sfScanToVirtualKey(code);
|
||||||
return (GetAsyncKeyState(static_cast<int>(virtualKey)) & KF_UP) != 0;
|
return (GetAsyncKeyState(static_cast<int>(virtualKey)) & KF_UP) != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -594,10 +594,10 @@ Keyboard::Scancode InputImpl::delocalize(Keyboard::Key key)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
String InputImpl::getDescription(Keyboard::Scancode code)
|
String InputImpl::getDescription(Keyboard::Scancode code)
|
||||||
{
|
{
|
||||||
WORD winCode = sfScanToWinScanExtended(code);
|
const WORD winCode = sfScanToWinScanExtended(code);
|
||||||
const int bufSize = 1024;
|
const int bufSize = 1024;
|
||||||
WCHAR name[bufSize];
|
WCHAR name[bufSize];
|
||||||
int result = GetKeyNameText(winCode << 16, name, bufSize);
|
const int result = GetKeyNameText(winCode << 16, name, bufSize);
|
||||||
if (result > 0)
|
if (result > 0)
|
||||||
{
|
{
|
||||||
return name;
|
return name;
|
||||||
|
@ -132,7 +132,7 @@ std::string getErrorString(DWORD error)
|
|||||||
nullptr) == 0)
|
nullptr) == 0)
|
||||||
return "Unknown error.";
|
return "Unknown error.";
|
||||||
|
|
||||||
sf::String message = buffer;
|
const sf::String message = buffer;
|
||||||
LocalFree(buffer);
|
LocalFree(buffer);
|
||||||
return message.toAnsiString();
|
return message.toAnsiString();
|
||||||
}
|
}
|
||||||
@ -299,7 +299,7 @@ bool JoystickImpl::open(unsigned int index)
|
|||||||
m_index = JOYSTICKID1 + index;
|
m_index = JOYSTICKID1 + index;
|
||||||
|
|
||||||
// Store the joystick capabilities
|
// Store the joystick capabilities
|
||||||
bool success = joyGetDevCaps(m_index, &m_caps, sizeof(m_caps)) == JOYERR_NOERROR;
|
const bool success = joyGetDevCaps(m_index, &m_caps, sizeof(m_caps)) == JOYERR_NOERROR;
|
||||||
|
|
||||||
if (success)
|
if (success)
|
||||||
{
|
{
|
||||||
@ -395,7 +395,7 @@ JoystickState JoystickImpl::update()
|
|||||||
// Special case for POV, it is given as an angle
|
// Special case for POV, it is given as an angle
|
||||||
if (pos.dwPOV != 0xFFFF)
|
if (pos.dwPOV != 0xFFFF)
|
||||||
{
|
{
|
||||||
float angle = static_cast<float>(pos.dwPOV) / 18000.f * 3.141592654f;
|
const float angle = static_cast<float>(pos.dwPOV) / 18000.f * 3.141592654f;
|
||||||
state.axes[Joystick::PovX] = std::sin(angle) * 100;
|
state.axes[Joystick::PovX] = std::sin(angle) * 100;
|
||||||
state.axes[Joystick::PovY] = std::cos(angle) * 100;
|
state.axes[Joystick::PovY] = std::cos(angle) * 100;
|
||||||
}
|
}
|
||||||
@ -430,11 +430,11 @@ void JoystickImpl::initializeDInput()
|
|||||||
if (directInput8Create)
|
if (directInput8Create)
|
||||||
{
|
{
|
||||||
// Try to acquire a DirectInput 8.x interface
|
// Try to acquire a DirectInput 8.x interface
|
||||||
HRESULT result = directInput8Create(GetModuleHandleW(nullptr),
|
const HRESULT result = directInput8Create(GetModuleHandleW(nullptr),
|
||||||
0x0800,
|
0x0800,
|
||||||
guids::IID_IDirectInput8W,
|
guids::IID_IDirectInput8W,
|
||||||
reinterpret_cast<void**>(&directInput),
|
reinterpret_cast<void**>(&directInput),
|
||||||
nullptr);
|
nullptr);
|
||||||
|
|
||||||
if (FAILED(result))
|
if (FAILED(result))
|
||||||
{
|
{
|
||||||
@ -490,10 +490,10 @@ void JoystickImpl::updateConnectionsDInput()
|
|||||||
record.plugged = false;
|
record.plugged = false;
|
||||||
|
|
||||||
// Enumerate devices
|
// Enumerate devices
|
||||||
HRESULT result = directInput->EnumDevices(DI8DEVCLASS_GAMECTRL,
|
const HRESULT result = directInput->EnumDevices(DI8DEVCLASS_GAMECTRL,
|
||||||
&JoystickImpl::deviceEnumerationCallback,
|
&JoystickImpl::deviceEnumerationCallback,
|
||||||
nullptr,
|
nullptr,
|
||||||
DIEDFL_ATTACHEDONLY);
|
DIEDFL_ATTACHEDONLY);
|
||||||
|
|
||||||
// Remove devices that were not connected during the enumeration
|
// Remove devices that were not connected during the enumeration
|
||||||
for (auto i = joystickList.begin(); i != joystickList.end();)
|
for (auto i = joystickList.begin(); i != joystickList.end();)
|
||||||
@ -730,7 +730,7 @@ bool JoystickImpl::openDInput(unsigned int index)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set device's axis mode to absolute if the device reports having at least one axis
|
// Set device's axis mode to absolute if the device reports having at least one axis
|
||||||
for (int axis : m_axes)
|
for (const int axis : m_axes)
|
||||||
{
|
{
|
||||||
if (axis != -1)
|
if (axis != -1)
|
||||||
{
|
{
|
||||||
@ -867,7 +867,7 @@ JoystickCaps JoystickImpl::getCapabilitiesDInput() const
|
|||||||
// Count how many buttons have valid offsets
|
// Count how many buttons have valid offsets
|
||||||
caps.buttonCount = 0;
|
caps.buttonCount = 0;
|
||||||
|
|
||||||
for (int button : m_buttons)
|
for (const int button : m_buttons)
|
||||||
{
|
{
|
||||||
if (button != -1)
|
if (button != -1)
|
||||||
++caps.buttonCount;
|
++caps.buttonCount;
|
||||||
@ -931,11 +931,11 @@ JoystickState JoystickImpl::updateDInputBuffered()
|
|||||||
{
|
{
|
||||||
if ((j == Joystick::PovX) || (j == Joystick::PovY))
|
if ((j == Joystick::PovX) || (j == Joystick::PovY))
|
||||||
{
|
{
|
||||||
unsigned short value = LOWORD(events[i].dwData);
|
const unsigned short value = LOWORD(events[i].dwData);
|
||||||
|
|
||||||
if (value != 0xFFFF)
|
if (value != 0xFFFF)
|
||||||
{
|
{
|
||||||
float angle = (static_cast<float>(value)) * 3.141592654f / DI_DEGREES / 180.f;
|
const float angle = (static_cast<float>(value)) * 3.141592654f / DI_DEGREES / 180.f;
|
||||||
|
|
||||||
m_state.axes[Joystick::PovX] = std::sin(angle) * 100.f;
|
m_state.axes[Joystick::PovX] = std::sin(angle) * 100.f;
|
||||||
m_state.axes[Joystick::PovY] = std::cos(angle) * 100.f;
|
m_state.axes[Joystick::PovY] = std::cos(angle) * 100.f;
|
||||||
@ -1020,12 +1020,12 @@ JoystickState JoystickImpl::updateDInputPolled()
|
|||||||
{
|
{
|
||||||
if ((i == Joystick::PovX) || (i == Joystick::PovY))
|
if ((i == Joystick::PovX) || (i == Joystick::PovY))
|
||||||
{
|
{
|
||||||
unsigned short value = LOWORD(
|
const unsigned short value = LOWORD(
|
||||||
*reinterpret_cast<const DWORD*>(reinterpret_cast<const char*>(&joystate) + m_axes[i]));
|
*reinterpret_cast<const DWORD*>(reinterpret_cast<const char*>(&joystate) + m_axes[i]));
|
||||||
|
|
||||||
if (value != 0xFFFF)
|
if (value != 0xFFFF)
|
||||||
{
|
{
|
||||||
float angle = (static_cast<float>(value)) * 3.141592654f / DI_DEGREES / 180.f;
|
const float angle = (static_cast<float>(value)) * 3.141592654f / DI_DEGREES / 180.f;
|
||||||
|
|
||||||
state.axes[Joystick::PovX] = std::sin(angle) * 100.f;
|
state.axes[Joystick::PovX] = std::sin(angle) * 100.f;
|
||||||
state.axes[Joystick::PovY] = std::cos(angle) * 100.f;
|
state.axes[Joystick::PovY] = std::cos(angle) * 100.f;
|
||||||
@ -1055,7 +1055,7 @@ JoystickState JoystickImpl::updateDInputPolled()
|
|||||||
{
|
{
|
||||||
if (m_buttons[i] != -1)
|
if (m_buttons[i] != -1)
|
||||||
{
|
{
|
||||||
BYTE value = *reinterpret_cast<const BYTE*>(reinterpret_cast<const char*>(&joystate) + m_buttons[i]);
|
const BYTE value = *reinterpret_cast<const BYTE*>(reinterpret_cast<const char*>(&joystate) + m_buttons[i]);
|
||||||
|
|
||||||
state.buttons[i] = ((value & 0x80) != 0);
|
state.buttons[i] = ((value & 0x80) != 0);
|
||||||
}
|
}
|
||||||
@ -1085,7 +1085,7 @@ BOOL CALLBACK JoystickImpl::deviceEnumerationCallback(const DIDEVICEINSTANCE* de
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
JoystickRecord record = {deviceInstance->guidInstance, sf::Joystick::Count, true};
|
const JoystickRecord record = {deviceInstance->guidInstance, sf::Joystick::Count, true};
|
||||||
joystickList.push_back(record);
|
joystickList.push_back(record);
|
||||||
|
|
||||||
return DIENUM_CONTINUE;
|
return DIENUM_CONTINUE;
|
||||||
@ -1131,7 +1131,7 @@ BOOL CALLBACK JoystickImpl::deviceObjectEnumerationCallback(const DIDEVICEOBJECT
|
|||||||
propertyRange.lMin = -32768;
|
propertyRange.lMin = -32768;
|
||||||
propertyRange.lMax = 32767;
|
propertyRange.lMax = 32767;
|
||||||
|
|
||||||
HRESULT result = joystick.m_device->SetProperty(DIPROP_RANGE, &propertyRange.diph);
|
const HRESULT result = joystick.m_device->SetProperty(DIPROP_RANGE, &propertyRange.diph);
|
||||||
|
|
||||||
if (result != DI_OK)
|
if (result != DI_OK)
|
||||||
err() << "Failed to set DirectInput device axis property range: " << result << std::endl;
|
err() << "Failed to set DirectInput device axis property range: " << result << std::endl;
|
||||||
|
@ -46,7 +46,7 @@ std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
|
|||||||
for (int count = 0; EnumDisplaySettings(nullptr, static_cast<DWORD>(count), &win32Mode); ++count)
|
for (int count = 0; EnumDisplaySettings(nullptr, static_cast<DWORD>(count), &win32Mode); ++count)
|
||||||
{
|
{
|
||||||
// Convert to sf::VideoMode
|
// Convert to sf::VideoMode
|
||||||
VideoMode mode({win32Mode.dmPelsWidth, win32Mode.dmPelsHeight}, win32Mode.dmBitsPerPel);
|
const VideoMode mode({win32Mode.dmPelsWidth, win32Mode.dmPelsHeight}, win32Mode.dmBitsPerPel);
|
||||||
|
|
||||||
// Add it only if it is not already in the array
|
// Add it only if it is not already in the array
|
||||||
if (std::find(modes.begin(), modes.end(), mode) == modes.end())
|
if (std::find(modes.begin(), modes.end(), mode) == modes.end())
|
||||||
|
@ -297,7 +297,7 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix
|
|||||||
// Let's check how many formats are supporting our requirements
|
// Let's check how many formats are supporting our requirements
|
||||||
int formats[512];
|
int formats[512];
|
||||||
UINT nbFormats = 0; // We must initialize to 0 otherwise broken drivers might fill with garbage in the following call
|
UINT nbFormats = 0; // We must initialize to 0 otherwise broken drivers might fill with garbage in the following call
|
||||||
bool isValid = wglChoosePixelFormatARB(deviceContext, intAttributes, nullptr, 512, formats, &nbFormats) != FALSE;
|
const bool isValid = wglChoosePixelFormatARB(deviceContext, intAttributes, nullptr, 512, formats, &nbFormats) != FALSE;
|
||||||
|
|
||||||
if (!isValid)
|
if (!isValid)
|
||||||
err() << "Failed to enumerate pixel formats: " << getErrorString(GetLastError()).toAnsiString() << std::endl;
|
err() << "Failed to enumerate pixel formats: " << getErrorString(GetLastError()).toAnsiString() << std::endl;
|
||||||
@ -372,15 +372,15 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Evaluate the current configuration
|
// Evaluate the current configuration
|
||||||
int color = values[0] + values[1] + values[2] + values[3];
|
const int color = values[0] + values[1] + values[2] + values[3];
|
||||||
int score = evaluateFormat(bitsPerPixel,
|
const int score = evaluateFormat(bitsPerPixel,
|
||||||
settings,
|
settings,
|
||||||
color,
|
color,
|
||||||
values[4],
|
values[4],
|
||||||
values[5],
|
values[5],
|
||||||
sampleValues[0] ? sampleValues[1] : 0,
|
sampleValues[0] ? sampleValues[1] : 0,
|
||||||
values[6] == WGL_FULL_ACCELERATION_ARB,
|
values[6] == WGL_FULL_ACCELERATION_ARB,
|
||||||
sRgbCapableValue == TRUE);
|
sRgbCapableValue == TRUE);
|
||||||
|
|
||||||
// Keep it if it's better than the current best
|
// Keep it if it's better than the current best
|
||||||
if (score < bestScore)
|
if (score < bestScore)
|
||||||
@ -423,7 +423,7 @@ int WglContext::selectBestPixelFormat(HDC deviceContext, unsigned int bitsPerPix
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WglContext::setDevicePixelFormat(unsigned int bitsPerPixel)
|
void WglContext::setDevicePixelFormat(unsigned int bitsPerPixel)
|
||||||
{
|
{
|
||||||
int bestFormat = selectBestPixelFormat(m_deviceContext, bitsPerPixel, m_settings);
|
const int bestFormat = selectBestPixelFormat(m_deviceContext, bitsPerPixel, m_settings);
|
||||||
|
|
||||||
if (bestFormat == 0)
|
if (bestFormat == 0)
|
||||||
{
|
{
|
||||||
@ -452,7 +452,7 @@ void WglContext::setDevicePixelFormat(unsigned int bitsPerPixel)
|
|||||||
////////////////////////////////////////////////////////////
|
////////////////////////////////////////////////////////////
|
||||||
void WglContext::updateSettingsFromPixelFormat()
|
void WglContext::updateSettingsFromPixelFormat()
|
||||||
{
|
{
|
||||||
int format = GetPixelFormat(m_deviceContext);
|
const int format = GetPixelFormat(m_deviceContext);
|
||||||
|
|
||||||
if (format == 0)
|
if (format == 0)
|
||||||
{
|
{
|
||||||
@ -562,7 +562,7 @@ void WglContext::createSurface(WglContext* shared, const Vector2u& size, unsigne
|
|||||||
// Check if the shared context already exists and pbuffers are supported
|
// Check if the shared context already exists and pbuffers are supported
|
||||||
if (shared && shared->m_deviceContext && SF_GLAD_WGL_ARB_pbuffer)
|
if (shared && shared->m_deviceContext && SF_GLAD_WGL_ARB_pbuffer)
|
||||||
{
|
{
|
||||||
int bestFormat = selectBestPixelFormat(shared->m_deviceContext, bitsPerPixel, m_settings, true);
|
const int bestFormat = selectBestPixelFormat(shared->m_deviceContext, bitsPerPixel, m_settings, true);
|
||||||
|
|
||||||
if (bestFormat > 0)
|
if (bestFormat > 0)
|
||||||
{
|
{
|
||||||
@ -649,7 +649,7 @@ void WglContext::createContext(WglContext* shared)
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
// Get a working copy of the context settings
|
// Get a working copy of the context settings
|
||||||
ContextSettings settings = m_settings;
|
const ContextSettings settings = m_settings;
|
||||||
|
|
||||||
// Get the context to share display lists with
|
// Get the context to share display lists with
|
||||||
HGLRC sharedContext = shared ? shared->m_context : nullptr;
|
HGLRC sharedContext = shared ? shared->m_context : nullptr;
|
||||||
@ -673,10 +673,10 @@ void WglContext::createContext(WglContext* shared)
|
|||||||
// Check if setting the profile is supported
|
// Check if setting the profile is supported
|
||||||
if (SF_GLAD_WGL_ARB_create_context_profile)
|
if (SF_GLAD_WGL_ARB_create_context_profile)
|
||||||
{
|
{
|
||||||
int profile = (m_settings.attributeFlags & ContextSettings::Core)
|
const int profile = (m_settings.attributeFlags & ContextSettings::Core)
|
||||||
? WGL_CONTEXT_CORE_PROFILE_BIT_ARB
|
? WGL_CONTEXT_CORE_PROFILE_BIT_ARB
|
||||||
: WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
|
: WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
|
||||||
int debug = (m_settings.attributeFlags & ContextSettings::Debug) ? WGL_CONTEXT_DEBUG_BIT_ARB : 0;
|
const int debug = (m_settings.attributeFlags & ContextSettings::Debug) ? WGL_CONTEXT_DEBUG_BIT_ARB : 0;
|
||||||
|
|
||||||
attributes.push_back(WGL_CONTEXT_PROFILE_MASK_ARB);
|
attributes.push_back(WGL_CONTEXT_PROFILE_MASK_ARB);
|
||||||
attributes.push_back(profile);
|
attributes.push_back(profile);
|
||||||
@ -700,7 +700,7 @@ void WglContext::createContext(WglContext* shared)
|
|||||||
if (sharedContext)
|
if (sharedContext)
|
||||||
{
|
{
|
||||||
static std::recursive_mutex mutex;
|
static std::recursive_mutex mutex;
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
if (WglContextImpl::currentContext == shared)
|
if (WglContextImpl::currentContext == shared)
|
||||||
{
|
{
|
||||||
@ -772,7 +772,7 @@ void WglContext::createContext(WglContext* shared)
|
|||||||
{
|
{
|
||||||
// wglShareLists doesn't seem to be thread-safe
|
// wglShareLists doesn't seem to be thread-safe
|
||||||
static std::recursive_mutex mutex;
|
static std::recursive_mutex mutex;
|
||||||
std::lock_guard lock(mutex);
|
const std::lock_guard lock(mutex);
|
||||||
|
|
||||||
if (WglContextImpl::currentContext == shared)
|
if (WglContextImpl::currentContext == shared)
|
||||||
{
|
{
|
||||||
|
@ -163,9 +163,9 @@ m_cursorGrabbed(m_fullscreen)
|
|||||||
registerWindowClass();
|
registerWindowClass();
|
||||||
|
|
||||||
// Compute position and size
|
// Compute position and size
|
||||||
HDC screenDC = GetDC(nullptr);
|
HDC screenDC = GetDC(nullptr);
|
||||||
int left = (GetDeviceCaps(screenDC, HORZRES) - static_cast<int>(mode.size.x)) / 2;
|
const int left = (GetDeviceCaps(screenDC, HORZRES) - static_cast<int>(mode.size.x)) / 2;
|
||||||
int top = (GetDeviceCaps(screenDC, VERTRES) - static_cast<int>(mode.size.y)) / 2;
|
const int top = (GetDeviceCaps(screenDC, VERTRES) - static_cast<int>(mode.size.y)) / 2;
|
||||||
auto [width, height] = Vector2i(mode.size);
|
auto [width, height] = Vector2i(mode.size);
|
||||||
ReleaseDC(nullptr, screenDC);
|
ReleaseDC(nullptr, screenDC);
|
||||||
|
|
||||||
@ -333,8 +333,8 @@ void WindowImplWin32::setSize(const Vector2u& size)
|
|||||||
// so we have to compute it
|
// so we have to compute it
|
||||||
RECT rectangle = {0, 0, static_cast<long>(size.x), static_cast<long>(size.y)};
|
RECT rectangle = {0, 0, static_cast<long>(size.x), static_cast<long>(size.y)};
|
||||||
AdjustWindowRect(&rectangle, static_cast<DWORD>(GetWindowLongPtr(m_handle, GWL_STYLE)), false);
|
AdjustWindowRect(&rectangle, static_cast<DWORD>(GetWindowLongPtr(m_handle, GWL_STYLE)), false);
|
||||||
int width = rectangle.right - rectangle.left;
|
const int width = rectangle.right - rectangle.left;
|
||||||
int height = rectangle.bottom - rectangle.top;
|
const int height = rectangle.bottom - rectangle.top;
|
||||||
|
|
||||||
SetWindowPos(m_handle, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER);
|
SetWindowPos(m_handle, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER);
|
||||||
}
|
}
|
||||||
@ -1044,8 +1044,8 @@ void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam)
|
|||||||
case WM_MOUSEMOVE:
|
case WM_MOUSEMOVE:
|
||||||
{
|
{
|
||||||
// Extract the mouse local coordinates
|
// Extract the mouse local coordinates
|
||||||
int x = static_cast<std::int16_t>(LOWORD(lParam));
|
const int x = static_cast<std::int16_t>(LOWORD(lParam));
|
||||||
int y = static_cast<std::int16_t>(HIWORD(lParam));
|
const int y = static_cast<std::int16_t>(HIWORD(lParam));
|
||||||
|
|
||||||
// Get the client area of the window
|
// Get the client area of the window
|
||||||
RECT area;
|
RECT area;
|
||||||
@ -1135,8 +1135,8 @@ Keyboard::Key WindowImplWin32::virtualKeyCodeToSF(WPARAM key, LPARAM flags)
|
|||||||
// Check the scancode to distinguish between left and right shift
|
// Check the scancode to distinguish between left and right shift
|
||||||
case VK_SHIFT:
|
case VK_SHIFT:
|
||||||
{
|
{
|
||||||
static UINT lShift = MapVirtualKeyW(VK_LSHIFT, MAPVK_VK_TO_VSC);
|
static const UINT lShift = MapVirtualKeyW(VK_LSHIFT, MAPVK_VK_TO_VSC);
|
||||||
UINT scancode = static_cast<UINT>((flags & (0xFF << 16)) >> 16);
|
const UINT scancode = static_cast<UINT>((flags & (0xFF << 16)) >> 16);
|
||||||
return scancode == lShift ? Keyboard::LShift : Keyboard::RShift;
|
return scancode == lShift ? Keyboard::LShift : Keyboard::RShift;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -198,11 +198,11 @@ void WindowImpl::processJoystickEvents()
|
|||||||
for (unsigned int i = 0; i < Joystick::Count; ++i)
|
for (unsigned int i = 0; i < Joystick::Count; ++i)
|
||||||
{
|
{
|
||||||
// Copy the previous state of the joystick and get the new one
|
// Copy the previous state of the joystick and get the new one
|
||||||
JoystickState previousState = m_joystickStatesImpl->m_states[i];
|
const JoystickState previousState = m_joystickStatesImpl->m_states[i];
|
||||||
m_joystickStatesImpl->m_states[i] = JoystickManager::getInstance().getState(i);
|
m_joystickStatesImpl->m_states[i] = JoystickManager::getInstance().getState(i);
|
||||||
|
|
||||||
// Connection state
|
// Connection state
|
||||||
bool connected = m_joystickStatesImpl->m_states[i].connected;
|
const bool connected = m_joystickStatesImpl->m_states[i].connected;
|
||||||
if (previousState.connected ^ connected)
|
if (previousState.connected ^ connected)
|
||||||
{
|
{
|
||||||
Event event;
|
Event event;
|
||||||
@ -217,16 +217,16 @@ void WindowImpl::processJoystickEvents()
|
|||||||
|
|
||||||
if (connected)
|
if (connected)
|
||||||
{
|
{
|
||||||
JoystickCaps caps = JoystickManager::getInstance().getCapabilities(i);
|
const JoystickCaps caps = JoystickManager::getInstance().getCapabilities(i);
|
||||||
|
|
||||||
// Axes
|
// Axes
|
||||||
for (unsigned int j = 0; j < Joystick::AxisCount; ++j)
|
for (unsigned int j = 0; j < Joystick::AxisCount; ++j)
|
||||||
{
|
{
|
||||||
if (caps.axes[j])
|
if (caps.axes[j])
|
||||||
{
|
{
|
||||||
auto axis = static_cast<Joystick::Axis>(j);
|
const auto axis = static_cast<Joystick::Axis>(j);
|
||||||
float prevPos = m_previousAxes[i][axis];
|
const float prevPos = m_previousAxes[i][axis];
|
||||||
float currPos = m_joystickStatesImpl->m_states[i].axes[axis];
|
const float currPos = m_joystickStatesImpl->m_states[i].axes[axis];
|
||||||
if (std::abs(currPos - prevPos) >= m_joystickThreshold)
|
if (std::abs(currPos - prevPos) >= m_joystickThreshold)
|
||||||
{
|
{
|
||||||
Event event;
|
Event event;
|
||||||
@ -244,8 +244,8 @@ void WindowImpl::processJoystickEvents()
|
|||||||
// Buttons
|
// Buttons
|
||||||
for (unsigned int j = 0; j < caps.buttonCount; ++j)
|
for (unsigned int j = 0; j < caps.buttonCount; ++j)
|
||||||
{
|
{
|
||||||
bool prevPressed = previousState.buttons[j];
|
const bool prevPressed = previousState.buttons[j];
|
||||||
bool currPressed = m_joystickStatesImpl->m_states[i].buttons[j];
|
const bool currPressed = m_joystickStatesImpl->m_states[i].buttons[j];
|
||||||
|
|
||||||
if (prevPressed ^ currPressed)
|
if (prevPressed ^ currPressed)
|
||||||
{
|
{
|
||||||
@ -269,14 +269,14 @@ void WindowImpl::processSensorEvents()
|
|||||||
|
|
||||||
for (unsigned int i = 0; i < Sensor::Count; ++i)
|
for (unsigned int i = 0; i < Sensor::Count; ++i)
|
||||||
{
|
{
|
||||||
auto sensor = static_cast<Sensor::Type>(i);
|
const auto sensor = static_cast<Sensor::Type>(i);
|
||||||
|
|
||||||
// Only process enabled sensors
|
// Only process enabled sensors
|
||||||
if (SensorManager::getInstance().isEnabled(sensor))
|
if (SensorManager::getInstance().isEnabled(sensor))
|
||||||
{
|
{
|
||||||
// Copy the previous value of the sensor and get the new one
|
// Copy the previous value of the sensor and get the new one
|
||||||
Vector3f previousValue = m_sensorValue[i];
|
const Vector3f previousValue = m_sensorValue[i];
|
||||||
m_sensorValue[i] = SensorManager::getInstance().getValue(sensor);
|
m_sensorValue[i] = SensorManager::getInstance().getValue(sensor);
|
||||||
|
|
||||||
// If the value has changed, trigger an event
|
// If the value has changed, trigger an event
|
||||||
if (m_sensorValue[i] != previousValue) // @todo use a threshold?
|
if (m_sensorValue[i] != previousValue) // @todo use a threshold?
|
||||||
|
@ -168,8 +168,8 @@ TEST_CASE("[Graphics] sf::Image")
|
|||||||
|
|
||||||
SUBCASE("Copy (Empty image)")
|
SUBCASE("Copy (Empty image)")
|
||||||
{
|
{
|
||||||
sf::Image image1;
|
const sf::Image image1;
|
||||||
sf::Image image2;
|
sf::Image image2;
|
||||||
|
|
||||||
image2.create(sf::Vector2u(10, 10), sf::Color::Red);
|
image2.create(sf::Vector2u(10, 10), sf::Color::Red);
|
||||||
CHECK(!image2.copy(image1, sf::Vector2u(0, 0), sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(9, 9))));
|
CHECK(!image2.copy(image1, sf::Vector2u(0, 0), sf::IntRect(sf::Vector2i(0, 0), sf::Vector2i(9, 9))));
|
||||||
|
@ -18,7 +18,7 @@ TEST_CASE("[Graphics] sf::Rect")
|
|||||||
{
|
{
|
||||||
SUBCASE("Default constructor")
|
SUBCASE("Default constructor")
|
||||||
{
|
{
|
||||||
sf::IntRect rectangle;
|
const sf::IntRect rectangle;
|
||||||
CHECK(rectangle.left == 0);
|
CHECK(rectangle.left == 0);
|
||||||
CHECK(rectangle.top == 0);
|
CHECK(rectangle.top == 0);
|
||||||
CHECK(rectangle.width == 0);
|
CHECK(rectangle.width == 0);
|
||||||
@ -27,7 +27,7 @@ TEST_CASE("[Graphics] sf::Rect")
|
|||||||
|
|
||||||
SUBCASE("(left, top, width, height) constructor")
|
SUBCASE("(left, top, width, height) constructor")
|
||||||
{
|
{
|
||||||
sf::IntRect rectangle({1, 2}, {3, 4});
|
const sf::IntRect rectangle({1, 2}, {3, 4});
|
||||||
CHECK(rectangle.left == 1);
|
CHECK(rectangle.left == 1);
|
||||||
CHECK(rectangle.top == 2);
|
CHECK(rectangle.top == 2);
|
||||||
CHECK(rectangle.width == 3);
|
CHECK(rectangle.width == 3);
|
||||||
@ -36,9 +36,9 @@ TEST_CASE("[Graphics] sf::Rect")
|
|||||||
|
|
||||||
SUBCASE("(Vector2, Vector2) constructor")
|
SUBCASE("(Vector2, Vector2) constructor")
|
||||||
{
|
{
|
||||||
sf::Vector2i position(1, 2);
|
const sf::Vector2i position(1, 2);
|
||||||
sf::Vector2i dimension(3, 4);
|
const sf::Vector2i dimension(3, 4);
|
||||||
sf::IntRect rectangle(position, dimension);
|
const sf::IntRect rectangle(position, dimension);
|
||||||
|
|
||||||
CHECK(rectangle.left == 1);
|
CHECK(rectangle.left == 1);
|
||||||
CHECK(rectangle.top == 2);
|
CHECK(rectangle.top == 2);
|
||||||
@ -48,8 +48,8 @@ TEST_CASE("[Graphics] sf::Rect")
|
|||||||
|
|
||||||
SUBCASE("Conversion constructor")
|
SUBCASE("Conversion constructor")
|
||||||
{
|
{
|
||||||
sf::FloatRect sourceRectangle({1.0f, 2.0f}, {3.0f, 4.0f});
|
const sf::FloatRect sourceRectangle({1.0f, 2.0f}, {3.0f, 4.0f});
|
||||||
sf::IntRect rectangle(sourceRectangle);
|
const sf::IntRect rectangle(sourceRectangle);
|
||||||
|
|
||||||
CHECK(rectangle.left == static_cast<int>(sourceRectangle.left));
|
CHECK(rectangle.left == static_cast<int>(sourceRectangle.left));
|
||||||
CHECK(rectangle.top == static_cast<int>(sourceRectangle.top));
|
CHECK(rectangle.top == static_cast<int>(sourceRectangle.top));
|
||||||
@ -60,7 +60,7 @@ TEST_CASE("[Graphics] sf::Rect")
|
|||||||
|
|
||||||
SUBCASE("contains(Vector2)")
|
SUBCASE("contains(Vector2)")
|
||||||
{
|
{
|
||||||
sf::IntRect rectangle({0, 0}, {10, 10});
|
const sf::IntRect rectangle({0, 0}, {10, 10});
|
||||||
|
|
||||||
CHECK(rectangle.contains(sf::Vector2i(0, 0)) == true);
|
CHECK(rectangle.contains(sf::Vector2i(0, 0)) == true);
|
||||||
CHECK(rectangle.contains(sf::Vector2i(9, 0)) == true);
|
CHECK(rectangle.contains(sf::Vector2i(9, 0)) == true);
|
||||||
|
@ -18,7 +18,7 @@ TEST_CASE("[Graphics] sf::Texture" * doctest::skip(skipDisplayTests))
|
|||||||
{
|
{
|
||||||
SUBCASE("Construction")
|
SUBCASE("Construction")
|
||||||
{
|
{
|
||||||
sf::Texture texture;
|
const sf::Texture texture;
|
||||||
CHECK(texture.getSize() == sf::Vector2u());
|
CHECK(texture.getSize() == sf::Vector2u());
|
||||||
CHECK(!texture.isSmooth());
|
CHECK(!texture.isSmooth());
|
||||||
CHECK(!texture.isSrgb());
|
CHECK(!texture.isSrgb());
|
||||||
@ -204,8 +204,8 @@ TEST_CASE("[Graphics] sf::Texture" * doctest::skip(skipDisplayTests))
|
|||||||
CHECK_FALSE(texture2.isSmooth());
|
CHECK_FALSE(texture2.isSmooth());
|
||||||
CHECK(texture2.isRepeated());
|
CHECK(texture2.isRepeated());
|
||||||
|
|
||||||
sf::Image image1 = texture1.copyToImage();
|
const sf::Image image1 = texture1.copyToImage();
|
||||||
sf::Image image2 = texture2.copyToImage();
|
const sf::Image image2 = texture2.copyToImage();
|
||||||
REQUIRE(image1.getSize() == sf::Vector2u(2, 1));
|
REQUIRE(image1.getSize() == sf::Vector2u(2, 1));
|
||||||
REQUIRE(image2.getSize() == sf::Vector2u(1, 1));
|
REQUIRE(image2.getSize() == sf::Vector2u(1, 1));
|
||||||
CHECK(image1.getPixel(sf::Vector2u(1, 0)) == sf::Color::Green);
|
CHECK(image1.getPixel(sf::Vector2u(1, 0)) == sf::Color::Green);
|
||||||
|
@ -21,7 +21,7 @@ TEST_CASE("[System] sf::err")
|
|||||||
auto* const defaultStreamBuffer = sf::err().rdbuf();
|
auto* const defaultStreamBuffer = sf::err().rdbuf();
|
||||||
CHECK(defaultStreamBuffer != nullptr);
|
CHECK(defaultStreamBuffer != nullptr);
|
||||||
|
|
||||||
std::stringstream stream;
|
const std::stringstream stream;
|
||||||
sf::err().rdbuf(stream.rdbuf());
|
sf::err().rdbuf(stream.rdbuf());
|
||||||
sf::err() << "Something went wrong!\n";
|
sf::err() << "Something went wrong!\n";
|
||||||
CHECK(stream.str() == "Something went wrong!\n");
|
CHECK(stream.str() == "Something went wrong!\n");
|
||||||
|
@ -83,7 +83,7 @@ TEST_CASE("[System] sf::FileInputStream")
|
|||||||
{
|
{
|
||||||
const std::string fileContents = "hello world";
|
const std::string fileContents = "hello world";
|
||||||
|
|
||||||
TemporaryFile tmpFile(fileContents);
|
const TemporaryFile tmpFile(fileContents);
|
||||||
sf::FileInputStream fis;
|
sf::FileInputStream fis;
|
||||||
|
|
||||||
REQUIRE(fis.open(tmpFile.getPath()));
|
REQUIRE(fis.open(tmpFile.getPath()));
|
||||||
|
@ -19,7 +19,10 @@ TEST_CASE("[Window] sf::Window" * doctest::skip(skipDisplayTests))
|
|||||||
{
|
{
|
||||||
SUBCASE("Construction")
|
SUBCASE("Construction")
|
||||||
{
|
{
|
||||||
sf::Window window(sf::VideoMode(sf::Vector2u(256, 256), 32), "Window Title", sf::Style::Default, sf::ContextSettings());
|
const sf::Window window(sf::VideoMode(sf::Vector2u(256, 256), 32),
|
||||||
|
"Window Title",
|
||||||
|
sf::Style::Default,
|
||||||
|
sf::ContextSettings());
|
||||||
CHECK(window.getSize() == sf::Vector2u(256, 256));
|
CHECK(window.getSize() == sf::Vector2u(256, 256));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,32 +8,32 @@
|
|||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
// Audio
|
// Audio
|
||||||
[[maybe_unused]] sf::InputSoundFile inputSoundFile;
|
[[maybe_unused]] const sf::InputSoundFile inputSoundFile;
|
||||||
[[maybe_unused]] sf::SoundBufferRecorder soundBufferRecorder;
|
[[maybe_unused]] const sf::SoundBufferRecorder soundBufferRecorder;
|
||||||
[[maybe_unused]] sf::Music music;
|
[[maybe_unused]] const sf::Music music;
|
||||||
[[maybe_unused]] sf::Sound sound;
|
[[maybe_unused]] const sf::Sound sound;
|
||||||
|
|
||||||
// Graphics
|
// Graphics
|
||||||
[[maybe_unused]] sf::Color color;
|
[[maybe_unused]] const sf::Color color;
|
||||||
[[maybe_unused]] sf::Font font;
|
[[maybe_unused]] const sf::Font font;
|
||||||
[[maybe_unused]] sf::RenderWindow renderWindow;
|
[[maybe_unused]] const sf::RenderWindow renderWindow;
|
||||||
[[maybe_unused]] sf::RectangleShape rectangleShape;
|
[[maybe_unused]] const sf::RectangleShape rectangleShape;
|
||||||
[[maybe_unused]] sf::Vertex vertex;
|
[[maybe_unused]] const sf::Vertex vertex;
|
||||||
|
|
||||||
// Network
|
// Network
|
||||||
[[maybe_unused]] sf::Ftp ftp;
|
[[maybe_unused]] const sf::Ftp ftp;
|
||||||
[[maybe_unused]] sf::Http http;
|
[[maybe_unused]] const sf::Http http;
|
||||||
[[maybe_unused]] sf::Packet packet;
|
[[maybe_unused]] const sf::Packet packet;
|
||||||
[[maybe_unused]] sf::UdpSocket udpSocket;
|
[[maybe_unused]] const sf::UdpSocket udpSocket;
|
||||||
|
|
||||||
// System
|
// System
|
||||||
[[maybe_unused]] sf::Angle angle;
|
[[maybe_unused]] const sf::Angle angle;
|
||||||
[[maybe_unused]] sf::FileInputStream fileInputStream;
|
[[maybe_unused]] const sf::FileInputStream fileInputStream;
|
||||||
[[maybe_unused]] sf::String string;
|
[[maybe_unused]] const sf::String string;
|
||||||
[[maybe_unused]] sf::Time time;
|
[[maybe_unused]] const sf::Time time;
|
||||||
|
|
||||||
// Window
|
// Window
|
||||||
[[maybe_unused]] sf::Context context;
|
[[maybe_unused]] const sf::Context context;
|
||||||
[[maybe_unused]] sf::VideoMode videoMode;
|
[[maybe_unused]] const sf::VideoMode videoMode;
|
||||||
[[maybe_unused]] sf::Window window;
|
[[maybe_unused]] const sf::Window window;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user