sfml
3.0.0#1
Simple and fast multimedia library
Features
audio — Use sfml-audio library
graphics — Use sfml-graphics library
network — Use sfml-network library
window — Use sfml-window library
Available Versions
- 3.0.0#1
- 3.0.0#0
- 2.6.2#0
- 2.6.1#1
- 2.6.1#0
- 2.6.0#19
- 2.6.0#18
- 2.6.0#17
- 2.5.1#16
- 2.5.1#15
- 2.5.1#14
- 2.5.1#13
- 2.5.1#12
- 2.5.1#11
- 2.5.1#10
- 2.5.1#9
- 2.5.1#8
- 2.5.1-7#0
- 2.5.1-6#0
- 2.5.1-5#0
- 2.5.1-4#0
- 2.5.1-3#0
- 2.5.1-2#0
- 2.5.1-1#0
- 2.5.1#0
- 2.5.0-2#0
- 2.5.0-1#0
- 2.5.0#0
- 2.4.2-3#0
- 2.4.2-2#0
- 2.4.2-1#0
- 2.4.2#0
- 2.4.1#0
Существует довольно много библиотек, которые способны отображать окна для Opengl — SDL, Glut (freeglut), QT, SFML, можно даже использовать нативные API операционной системы (вроде Winapi для Windows). Но SFML имеет ряд важных преимуществ, это мультимедийная библиотека, представляющая из себя объектно ориентированный аналог SDL, что делает её гораздо удобнее последней, но при этом более многофункциональной чем, например, Glut. В частности, SFML имеет интерфейс для управления текстурами, тогда как при использовании glut пришлось бы подключать дополнительные библиотеки, такие как SOIL2. Помимо этого, у SFML очень хорошая и удобная документация на официальном сайте.
Установка
Установить SFML и Opengl можно разными способами, но удобно воспользоваться для этого пакетными менеджерами. Для работы в Visual Studio можно воспользоваться nuget, но мне для c++ проектов показался удобнее vcpkg, относительно недавно появившийся мультиплатформенный пакетный менеджер от Microsoft.
Установка vcpkg производится слегка необычным образом, для этого необходимо клонировать репозиторий vcpkg (желательно чтобы в путях установки не было кириллицы, иначе могут возникнуть проблемы)
git clone https://github.com/Microsoft/vcpkg.git
И затем вызвать скрипт загрузки
.\vcpkg\bootstrap-vcpkg.bat
После этого можно устанавливать библиотеки
vcpkg install sfml
vcpkg install opengl
vcpkg install glew
Установка занимает довольно продолжительное время
Чтобы установленные пакеты были видны из Visual Studio, надо написать следующее
vcpkg integrate install
Обратите внимание, что по умолчанию устанавливаются пакеты 32-битной разрядности, для установки 64-битной версии пакета необходимо явно задать версию.
vcpkg install sfml:x64-windows
vcpkg install opengl:x64-windows
vcpkg install glew:x64-windows
Работа с SFML и OpenGL
Простая программа на SFMl выглядит следующим образом
#include <SFML/Graphics.hpp>
int main()
{
// Создаём окно
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML window");
// Главный цикл
while (window.isOpen())
{
sf::Event event;
// Цикл обработки событий
while (window.pollEvent(event))
{
// Событие закрытия окна,
if (event.type == sf::Event::Closed)
window.close();
}
// Перерисовка окна
window.display();
}
return 0;
}
Здесь просто создаётся окно, и до тех пор, пока оно открыто, происходит перерисовка.
Теперь запустим простую программу для работы с OpenGL, которая выводит на экран окно с разноцветным крутящимся квадратом.
ВАЖНО!!! СЛЕДУЮЩИЙ КОД НАПИСАН С ИСПОЛЬЗОВАНИЕМ УСТАРЕВШЕГО API OPENGL И СЛУЖИТ ИСКЛЮЧИТЕЛЬНО ДЛЯ ПРОВЕРКИ РАБОТОСПОСОБНОСТИ OPENGL И SFML. ОН НЕ ЯВЛЯЕТСЯ ПРИМЕРОМ ИЛИ ЗАГОТОВКОЙ ДЛЯ ВЫПОЛНЕНИЯ ЛАБОРАТОРНЫХ РАБОТ!
#include <SFML/OpenGL.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
void SetIcon(sf::Window& wnd);
void Init();
void Draw();
int main() {
// Создаём окно
sf::Window window(sf::VideoMode(600, 600), "My OpenGL window", sf::Style::Default, sf::ContextSettings(32));
// Ставим иконку (окна с дефолтной картинкой это некрасиво)
SetIcon(window);
// Включаем вертикальную синхронизацию (синхронизация частоты отрисовки с частотой кадров монитора, чтобы картинка не фризила, делать это не обязательно)
window.setVerticalSyncEnabled(true);
// Активируем окно
window.setActive(true);
// Инициализация
Init();
// Главный цикл окна
while (window.isOpen()) {
sf::Event event;
// Цикл обработки событий окна, тут можно ловить нажатия клавиш, движения мышки и всякое такое
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
// Окно закрыто, выходим из цикла
window.close();
}
else if (event.type == sf::Event::Resized) {
// Изменён размер окна, надо поменять и размер области Opengl отрисовки
glViewport(0, 0, event.size.width, event.size.height);
}
}
// Очистка буферов
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Рисуем сцену
Draw();
// Отрисовывает кадр - меняет передний и задний буфер местами
window.display();
}
return 0;
}
// В момент инициализации разумно произвести загрузку текстур, моделей и других вещей
void Init() {
// Очистка буфера тёмно жёлтым цветом
glClearColor(0.5f, 0.5f, 0.0f, 1.0f);
}
// Глобальные переменные это плохо, тут это сделано просто для примера
GLfloat rotate_z = 0;
// Функция непосредственно отрисовки сцены
void Draw() {
rotate_z += 0.5;
// Используем устаревшую функциональность установки единичной матрицы преобразования
glLoadIdentity();
// С использованием устаревшей функции glRotate домножаем на матрицу поворота
glRotatef(rotate_z, 0.0, 0.0, 1.0);
// Используем устаревшую конструкцию glBegin-glEnd для рисования квадрата
glBegin(GL_QUADS);
glColor3f(1.0, 0.0, 0.0); glVertex2f(-0.5f, -0.5f);
glColor3f(0.0, 1.0, 0.0); glVertex2f(-0.5f, 0.5f);
glColor3f(0.0, 0.0, 1.0); glVertex2f(0.5f, 0.5f);
glColor3f(1.0, 1.0, 1.0); glVertex2f(0.5f, -0.5f);
glEnd();
// Отправляем набор команд отрисовываться
glFlush();
}
void SetIcon(sf::Window& wnd)
{
sf::Image image;
// Вместо рисования пикселей, можно загрузить иконку из файла (image.loadFromFile("icon.png"))
image.create(16, 16);
for (int i = 0; i < 16; ++i)
for (int j = 0; j < 16; ++j)
image.setPixel(i, j, {
(sf::Uint8) (i * 16), (sf::Uint8)(j * 16), 0 });
wnd.setIcon(image.getSize().x, image.getSize().y, image.getPixelsPtr());
}
Getting SFML to work with Visual Studio
Here’s a video that walks you through this process: https://watch.screencastify.com/v/VDdqsobi8ZyQUnQKNREP
An Automated Option
SFMLInstall written by Kyle.
Install Git
Git is a version control system that lets you manage and keep track of your source code history. If you’re familiar with GitHub, the difference is that GitHub is a cloud-based hosting service that lets you manage Git repositories.
Download and install Git. On the git site, find the latest source release, and click «download for windows».
Install vcpkg
Vcpkg is a C/C++ package manager for acquiring and managing libraries.
Open command prompt by pressing Win + R, typing cmd
and pressing enter, or searching cmd
via the windows search bar.
Once command prompt is open, type git clone https://github.com/microsoft/vcpkg
Then type cd vcpkg
Then type bootstrap-vcpkg.bat
Use vcpkg to get SFML
In command prompt, type vcpkg install SFML:x64-windows
.
Then, to get SFML useable by all your IDE’s including Visual studio, type
vcpkg integrate install
Writing your first graphical SFML Program
Here’s a basic SFML program that draws a green circle to a small game screen:
Temporary SFML Template Code
#include<SFML/Graphics.hpp>
using namespace std;
int main() {
sf::RenderWindow window(sf::VideoMode(1920,1080), "Window", sf::Style::Fullscreen);
window.setFramerateLimit(60);
sf::Event event;
while (window.isOpen()) {
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
window.clear((sf::Color::Black));
window.display();
}
}
In this blog post, I will cover the set up of a project using CMake, Visual Studio and vcpkg to create a basic SFML project.
Note: I assume you have basic familiarity with CMake and Visual Studio. Please look at my previous blog post for a small introduction to CMake and Visual Studio.
Prerequisites
- Visual Studio 15+ (2017)
- CMake 3.6+
- vcpkg
Set Up
However, first we must install Microsoft’s vcpkg tool. First, go to the repository of vcpkg and follow the instructions there to get vcpkg installed on your system. The instructions are pretty detailed and will get you set up without a hitch.
vcpkg might ask you to download CMake if the version on your system is not high enough (3.6+) or you don’t have CMake installed.
Once you have vcpkg set up, we will run it to set up SFML.
Note: vcpkg doesn’t configure the PATH environment variable, so you will have to run it from the directory you installed it in.
Now we need to run this command so let’s type it in:
vcpkg.exe install sfml
vcpkg will begin installation of SFML. vcpkg pulls the source code (where applicable) and builds the project and it’s dependencies from scratch so this may take a while. Best to relax and wait while it builds.
vcpkg will notify you when it has finished.
CMakeLists.txt
Once that is complete, we need to set up our CMakeLists.txt. Type this in:
cmake_minimum_required(VERSION 3.6) project(simple_sfml) set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH}) find_package(SFML 2.4.2 REQUIRED system window graphics) include_directories(${SFML_INCLUDE_DIR}) # Add MSVC compiler options if (WIN32) if (MSVC) add_compile_options(/W3 /Za /TP /permissive-) endif (MSVC) endif (WIN32) add_executable(simple_sfml src/main.cpp) target_link_libraries(simple_sfml ${SFML_LIBRARIES})
The first line specifies which version of CMake to use and the second line declares the project name which will also set the executable name.
In order for CMake to find SFML on your system, you need a findSFML.cmake file. This is provided by the SFML authors and you just need to include it (for example, in a cmake_modules directory) and tell CMake to load it. That’s basically what line 4 does. It appends our cmake_modules directory to CMake’s existing CMAKE_MODULE_PATH variable.
Now CMake will know where to look for SFML by using the findSFML.cmake to find the headers, *.lib‘s and *.dll‘s (including SFML’s dependencies).
Line 8 tells CMake to find SFML version 2.4.2 or higher and to load up the system, window and graphics modules of SFML. This will load and copy the correct .lib or .dll files and CMake will be able to load up debug versions when you’re debugging and release versions when you want to release your code. find_package in the background invokes SFMLconfig.cmake which sets up all this for you. SFMLconfig.cmake is provided by vcpkg and passed to CMake. We will set that up soon.
Line 10 ensures that we add (and have access to) the necessary header files which we will use in our source code.
Now, line 12 to line 17 is not necessary. I like to add these to just MSVC to get rid of any extras Microsoft has added to C++ and to be explicit on what I am compiling and linking. I will go over a quick summary of the four flags:
- /W3 – sets the warning level for C++. I’ve read you shouldn’t use /W4 and /Wall as the former is far too picky on some warnings and the latter is broken.
- /Za – disable Microsoft’s extensions to C++[*].
- /TP – compile as C++ code.
- /permissive- – makes MSVC conformant to ISO C++ as much as possible.
Line 19 we specify the executable and the source (.cpp) files to link with.
Line 21 we link the executable with the .dll files. Unfortunately, this blog post only covers dynamic linking to the “bin” directory to which the .dll files will be copied by CMake (to be honest, I haven’t figured out how to do the static linking with this approach ). Note that only the .dll files corresponding to what we asked for (the modules of SFML) in find_package will be copied over and linked.
Now we can set up the CMakeSettings.json.
CMakeSettings.json
Our CMakeSettings.json will look similar to how we set it up in my previous blog post except for one bit. We need to add a toolchain file to CMake so that CMake will know how to handle SFML. This is essentially passing the SFMLconfig.cmake file to CMake. Type in the following:
{ "configurations": [ { "name": "x86-Debug", "generator": "Visual Studio 15 2017", "configurationType": "Debug", "buildRoot": "${projectDir}\\build\\${name}", "cmakeCommandArgs": "", "buildCommandArgs": "-m -v:minimal", "variables": [ { "name": "CMAKE_TOOLCHAIN_FILE", "value": "C:\\Microsoft\\vcpkg\\scripts\\buildsystems\\vcpkg.cmake" } ] }, { "name": "x86-Release", "generator": "Visual Studio 15 2017", "configurationType": "Release", "buildRoot": "${projectDir}\\build\\${name}", "cmakeCommandArgs": "", "buildCommandArgs": "-m -v:minimal", "variables": [ { "name": "CMAKE_TOOLCHAIN_FILE", "value": "C:\\Microsoft\\vcpkg\\scripts\\buildsystems\\vcpkg.cmake" } ] } ] }
Take note that we need to do this for both debug and release. The “value” part will differ if you have installed vcpkg to a different location. The SFMLconfig.cmake is what sets the SFML_INCLUDE_DIR and SFML_LIBRARIES variables.
main.cpp
The main.cpp is fairly straight forward. It just creates a window which waits until it is closed [1]:
#include <SFML/Window.hpp> int main() { sf::Window window(sf::VideoMode(640, 480), "Simple SFML Example"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } } return 0; }
Nothing too fancy
Putting it all together
Now we have everything in place to build the project. So let’s do that by pressing F7 or by clicking “Build Solution” under “Build” in the menu bar. Compilation should succeed and we can now press F5 or clicking “Start” under “Debug” in the menu bar. We’ll see a command prompt window come up followed by our SFML window with a white background. Success!
Conclusion
In conclusion, this was quite a battle for me to get it right the first time. Mainly with the CMakeLists.txt and figuring out that findSFML.cmake is not provided by vcpkg. But once that was sorted, everything worked perfectly.
This is the general format to get most libraries going with CMake and vcpkg. You need the toolchain file and to know which targets get set by the library you’re trying to use. Take note that this approach does not hold for some libraries [2].
Link to github repository
References
[1] – https://www.sfml-dev.org/tutorials/2.4/window-window.php
[2] – https://github.com/Microsoft/vcpkg/blob/master/docs/examples/using-sqlite.md#handling-libraries-without-native-cmake-support
Resources
SFML – https://www.sfml-dev.org/learn.php
Using vcpkg – https://github.com/Microsoft/vcpkg/blob/master/docs/examples/using-sqlite.md
[*] – I have recently discovered that /Za is discouraged and that /permissive- is the recommended (and maintained) option. I will phase out this option in future usages.
Game-sfml
Обзор
Тестовый проект представляет собой 2D игру.
Cуть игры
После расстановки фигур на шахматной доске по очереди ходит игрок и AI.
Во время хода каждый может переместить одну фигуру. Фигуры можно перемещать только на одну клетку (вверх, вниз, влево, вправо).
В одну клетку можно поставить только одну фигуру. Побеждает тот, кто первый расставит все свои фигуры на место фигур противника.
Расстановка фигур в начале игры:
Управление фигурами с помощью мыши.
Использованные технологии
- С++ 17
- SFML
Установка библиотеки SFML через пакетный менеджер vcpkg:
1. Установить vcpkg
Шаг 1. Клонируйте репозиторий vcpkg
git clone https://github.com/Microsoft/vcpkg.git
Шаг 2. Запустите скрипт начальной загрузки для сборки vcpkg.
.\vcpkg\bootstrap-vcpkg.bat
2. Установите библиотеку для вашего проекта x86 или x64
x86:
x64:
vcpkg install sfml:x64-windows
3. Использование vcpkg с MSBuild/Visual Studio (может потребоваться повышение прав)
Более подробная инструкция здесь https://vcpkg.io/en/getting-started.html