Пост ориентирован на новичков. В нем не рассматривается настройка Visual Studio. Он научит вас настраивать некоторые текстовые редакторы на компиляцию OpenGL приложений, либо выполнять это из консоли вручную.
Недавно, наконец, вышло 8-е издание книги OpenGL programming guide, которую я ждал уже более чем 2 года. Чуть раньше я познакомился с замечательным текстовым редактором Sublime Text 2 и решил настроить его вместо установки тяжелой Visual Studio.
Итак, для начала нам нужен компилятор — я остановился на G++. Он является частью GCC, а его порт под Windows называется MinGW. С него и начнем:
MinGW
Качаем с официального сайта инсталлятор и запускаем его. Можно выбрать выкачивание свежих пакетов сразу при установке, либо обновить их вручную позже. Компиляторы Fortran, Ada и ObjC нам не понадобятся, их можно не ставить. MSYS Basic System может пригодится, его ставим. В качестве адреса я указал «C:\MinGW
«, но если вас это смущает — можете выбрать другой, например, «C:\Program Files\Common Files\MinGW
«.
После установки следует добавить к системной переменной PATH две новые папки: «MinGW\bin
» и «MinGW\msys\1.0\bin
«. Для этого заходим в Пуск -> Панель управления -> Система -> Дополнительные параметры системы; Во вкладке Дополнительно тыкаем внизу кнопку Переменные среды. Из списка системных переменных выбираем Path, и через точку с запятой дописываем полные адреса к папкам «MinGW\bin
» и «MinGW\msys\1.0\bin
«.
Если вы не выбирали выкачивание свежих пакетов при установке, следует обновить нужные пакеты вручную. Для этого открываем консоль (Win+R -> cmd
), и пишем следующие команды:
mingw-get update
Обновит информацию о доступных пакетах,
mingw-get show gсс
mingw-get show g++
Отобразит полные имена пакетов gcc и g++,
mingw-get upgrade mingw32-gcc
mingw-get upgrade mingw32-gcc-g++
Обновит эти пакеты до последних доступных для MinGW версий.
Теперь, когда у нас есть компилятор, мы можем приступить к установке необходимых OpenGL библиотек.
Freeglut
Поскольку OpenGL это API, которое относится исключительно к графике — в него не входят функции по созданию окон или обработки устройств ввода. Тем более, решение этой задачи зависит от операционной системы. По-этому ее вынесли в отдельную библиотеку и назвали GLUT — OpenGL Utility Toolkit. Однако, последний релиз этой библиотеки был очень давно и сейчас ее подменила freeglut.
Качаем с официального сайта бинарники под MinGW. Распаковываем, freeglut.dll
из папки bin
кидаем в «C:\Windows\System32
» (для х86) или «C:\Windows\SysWOW64
» (для х64), или любую другую папку, которая указана в PATH. Содержимое папок include
и lib
можно скопировать либо в «MinGW\include
» и «MinGW\lib
» (так будет проще), либо в отдельные созданые папки «MinGW\freeglut\include
» и «MinGW\freeglut\lib
«.
На этом с freeglut все. Для его подключения нужно добавить #include <GL/freeglut.h>
glew
Библиотека glew позволяет определять что видеокарта поддерживает, а что — нет. Ее установка немного сложнее для нашего случая.
Качаем с официального сайта исходники, поскольку бинарники заточены под Visual Studio и нам не подойдут. Теперь эти исходники нужно скомпилировать. Я в этом практически ничего не понимаю, по-этому обратился к гуглу и нашел помощь здесь:
Распаковываем скачанный архив, открываем консоль, заходим в полученную папку и пишем следующие команды:
gcc -DGLEW_NO_GLU -O2 -Wall -W -Iinclude -DGLEW_BUILD -o src/glew.o -c src/glew.c
gcc -shared -Wl,-soname,libglew32.dll -Wl,--out-implib,lib/libglew32.dll.a -o lib/glew32.dll src/glew.o -L/mingw/lib -lglu32 -lopengl32 -lgdi32 -luser32 -lkernel32
ar cr lib/libglew32.a src/glew.o
В результате в папке lib появилось 3 файла: glew32.dll
, glew32.dll.a
и glew32.a
.
glew32.dll
копируем туда же, куда ранее скопировали freeglut.dll
, остальные 2 — в папку «MinGW\lib
» либо «MinGW\glew\lib
«.
Из папки include
копируем содерижмое в «MinGW\include
» или «MinGW\glew\include
«.
На этом с glew все. Для его подключения нужно добавить #include <GL/glew.h>
, но сделать это необходимо перед подключением других gl библиотек.
Проверяем работоспособность
Создаем минимальный test.cpp:
#include <iostream>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <GL/gl.h>
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(512, 512);
glutInitContextVersion(4, 1); // Версия OpenGL, которую вы хотите использовать
glutInitContextProfile(GLUT_CORE_PROFILE);
glutCreateWindow(argv[0]);
if (glewInit()) {
std::cerr << "Unable to initialize GLEW ... exiting\n";
exit(EXIT_FAILURE);
}
glutMainLoop();
}
Обратите внимание на функцию glutInitContextVersion — она завершит выполнение программы если ей не удалось создать контекст для указаной версии OpenGL. Чтобы узнать версию OpenGL, которую поддерживает ваша видеокарта, можно заглянуть в ее спецификацию либо скачать бинарники glew с официального сайта и запустить glewinfo.exe
из папки bin
. Он сгенерирует файл glewinfo.txt
, в котором будет детально расписано что ваша видеокарта поддерживает, а что — нет. Иногда функционал можно расширить установкой более свежего видеодрайвера.
Открываем консоль, заходим в папку с test.cpp
и пишем следующую команду:
g++ -o test.exe test.cpp -lglew32 -lfreeglut -lopengl32 -lglu32 -Wl,--subsystem,windows
В случае, если вы создавали отдельные папки freeglut
и glew
, здесь необходимо дополнительно указать соответствующие дополнительные папки include
и lib
. Тогда пример команды выглядит так:
g++ -o test.exe test.cpp -lglew32 -lfreeglut -lopengl32 -lglu32 -Wl,--subsystem,windows -I"C:\MinGW\freeglut\include" -L"C:\MinGW\freeglut\lib" -I"C:\MinGW\glew\include" -L"C:\MinGW\glew\lib"
Флаг -Wl,--subsystem,windows
указывает компилятору что он должен создать графическое приложение, а не консольное.
Если все получилось, должен получится файл test.exe
, который при запуске создает белое окно 512х512.
Когда вы захотите поделится своим приложением, убедитесь что вместе с исполняемым файлом передаете используемые библиотеки — freeglut.dll
и glew32.dll
.
Sublime Text 2
Ну и напоследок, приведу пример настройки Sublime. Скачать его можно отсюда, вводные видео-уроки на английском языке можно глянуть здесь.
После установки открываем файл настройки билда С++:
«C:\Users\%Username%\AppData\Roaming\Sublime Text 2\Packages\C++\C++.sublime-build
«
Сохраняем его копию как
«C:\Users\%Username%\AppData\Roaming\Sublime Text 2\Packages\User\C++\С++ OpenGL.sublime-build
«
Строчку
"cmd": ["g++", "${file}", "-o", "${file_path}/${file_base_name}"],
дополняем подключением библиотек:
"cmd": ["g++", "${file}", "-o", "${file_path}/${file_base_name}", "-lfreeglut -lopengl32 -lglew32 -Wl,--subsystem,windows"],
Аналогично, строчку
"cmd": ["bash", "-c", "g++ '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'"]
дополняем до
"cmd": ["bash", "-c", "g++ '${file}' -o '${file_path}/${file_base_name}' -lglew32 -lfreeglut -lopengl32 -lglu32 -Wl,--subsystem,windows && '${file_path}/${file_base_name}'"]
Если вы создавали отдельные папки под freeglut и glew, эти команды следует дополнить указанием адресов дополнительных папок include
и lib
.
Для того чтобы Sublime не отказывался выводить кириллицу в свою консоль, после
"selector": "source.c, source.c++",
добавляем
"encoding": "cp1251",
Теперь, когда у нас открыт test.cpp
, выбираем Tools -> Build system -> C++ OpenGL.
Нажимаем Ctrl+B для компиляции, Ctrl+Shift+B для компиляции и запуска.
На этом все!
UPD: Когда дело дошло до кода с gl-функциями из последних версий, выяснилось, что подключение заголовочного файла GL/gl.h
недостаточно. В нем содержится устаревшая версия 1.1, и этот файл больше не обновляется. В дополнение к нему необходимо подключить GL/glext.h
(последнюю версию которого надо скачать отсюда) и GL/wglext.h
(отсюда). Для линукса последний файл заменяется GL/glxext.h
(ссылка). Скачанными файлами нужно заменить их устаревшие версии по адресу «MinGW/include/GL/
«.
Running GLUT on Windows using VS Code
A guide to installing and running GLUT programs in Windows using VS Code and in WSL/Linux.
Guide for Linux / WSL users
- Open terminal
- Run this command to install GLUT
sudo apt-get install freeglut3-dev
- Now create a
.c
file and write your code. - Now run the command
gcc filename.c -lGL -lGLU -lglut -lm
- Now execute the output using
./a.out
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
«version»: «2.0.0«, | |
«tasks»: [ | |
{ | |
«label»: «Build1«, | |
«type»: «shell«, | |
«command»: «C:/msys64/mingw64/bin/gcc.exe«, | |
«args»: [ | |
«-c«, | |
«-o«, | |
«${fileBasenameNoExtension}.o«, | |
«${file}«, | |
«-I\»C:\\msys64\\mingw64\\include\»« | |
] | |
}, | |
{ | |
«label»: «Build2«, | |
«type»: «shell«, | |
«command»: «C:/msys64/mingw64/bin/gcc.exe«, | |
«args»: [ | |
«-o«, | |
«${fileBasenameNoExtension}.exe«, | |
«${fileBasenameNoExtension}.o«, | |
«-L\»C:\\msys64\\mingw64\\lib\»«, | |
«-lfreeglut«, | |
«-lopengl32«, | |
«-lglu32«, | |
«-Wl,—subsystem,windows« | |
], | |
«dependsOn»: [ | |
«Build1« | |
] | |
}, | |
{ | |
«label»: «Run«, | |
«type»: «shell«, | |
«command»: «${fileBasenameNoExtension}.exe«, | |
«dependsOn»: [ | |
«Build2« | |
] | |
} | |
] | |
} |
Guide for Windows 10 / Windows 11
-
If your system has MSYS2 MSYS installed already then follow the steps below:
- Launch MSYS2 MSYS terminal (purple icon) from Start menu.
- Run this command
pacman -S mingw-w64-x86_64-freeglut
- Now exit the MSYS2 window.
- Launch VS Code in your assignment folder.
- Create a file
.vscode/tasks.json
- Copy paste the code given below in that file.
- Edit the paths according to your system. (pay attention to the \include and \bin folders and also the path to your compiler)
- To know the path to your compiler run
where gcc
in command prompt in Windows.
-
If you don’t have MSYS2 then follow the steps below:
- Download this file
- Extract the file to any folder.
- Now Launch VS Code in your assignment folder.
- Create a file
.vscode/tasks.json
- Copy paste the code given below in that file.
- Edit the paths to match the
\bin
and\include
folders from the extracted zip file (pay attention to the \include and \bin folders and also the path to your compiler) - To know the path to your compiler run
where gcc
in command prompt in Windows.
-
Now press
Ctrl+Shift+P
and typetasks
. -
Now select
Run Task
option from the list. -
Now select the first option.
-
Wait for the task to finish execution.
-
Done!
I was following a tutorial on OpenGL based in GLUT which is an auxiliary library created by Mark Kilgard to create a window in an easy way so that one can focus in learning OpenGL.
GLUT can be found at the URL http://opengl.org/resources/libraries/glut/glut_downloads.php
The problem is that GLUT has been abandoned and the last version runs on Windows XP and it isn’t an open source project either so no one can develop it on.
Fortunately Pawel W. Olszta, Andreas Umbach and Steve Baker developed an Open Source alternative called Free GLUT which is compatible with GLUT and replaces it in modern operating systems.
In this article I’m going to explain how to install it in Code::Blocks and on Windows 10.
The project is hosted at this URL: http://freeglut.sourceforge.net/ where you can download the sources and compile them yourself but it also links to Martin Payne’s web where the library is already compiled and available for MinGW which is Code::Block’s compiler or for Microsoft Visual Studio.
The URL of Martin Payne for the compiled library is https://www.transmissionzero.co.uk/software/freeglut-devel/
We click on the link Download freeglut 3.0.0 for MinGW, it’s a zip file which contains a folder called freeglut. I unzipped it in the path C:\freeglut
At this point you can create a project in Code::Blocks and manually add the pats to the folders include and lib plus the linker flags.
In order to do that we click the right button of the mouse on the project and in the menu we select Build Options… This will open a window.
In this window, in the profile Debug move onto the the tab Search directories and search for the sub tab compiler. In it enter the path C:\freeglut\include
Now move onto the sub tab Linker and add the path to C:\freeglut\lib\x64
Afterwards go to the tab Linker settings which is next to Search directories and inside it there is a vertical textbox titled Other linker Options: and enter the flags: -lfreeglut -lopengl32 -lglu32
To compile in Release you need to do the same setting as for Debug.
Lastly you need to copy the file C:\freeglut\bin\x64\freeglut.dll in the folder with the executable file that it’s created in the paths bin\Debug or bin\Release in your project.
At this stage you can now compile your OpenGL program making use of the auxiliary library FreeGLUT.
You’ll need to do the same configuration every time you start a new project but it doesn’t have to be so.
Code::Blocks has a template out of the box to create GLUT project but this template is broken because it’s designed to do it with the original library which as I said it won’t work in Windows 10.
What we need to do however is to make some changes to generate project that use FreeGLUT.
In order to do that we need fist to edit the file C:\Program Files\CodeBlocks\share\CodeBlocks\templates\glut.cbp with Notepad or any other text editor and replace any occurrence of the word glut32 for freeglut.
Then we go to the file C:\Program Files\CodeBlocks\share\CodeBlocks\templates\wizard\glut\wizard.script and also there we replace all the occurrences of glut32 for freeglut.
Now, if when creating a new project we select GLUT, a wizard will pop up asking things like the project name and the path.
Then it will ask the path to the GLUT library. Here you need to provide the path to the folder C:\freeglut and then finish creating the project.
This Wizard will create a demonstration project which you can compile and run.
I hope you find this tutorial useful.
Installing GLUT for MinGW
1 Introduction
OpenGL is independent of any windowing system. As a result, it contains
no functions for opening windows or interacting with the user.
Each windowing systems that supports OpenGL has its own library
that procides the support.
GLUT, the OpenGL Utility Toolkit, is a simple windowing system that
has been ported to several different operating systems. It is commonly
used when teaching OpenGL.
This document describes the installation of GLUT for
developing on MS-Windows using MinGW. It assumes that you have already
installed MinGW.
2 Getting Started
The first thing you need to do is download the binaries for the Win32
port of GLUT.
3 Putting Files in the Right Place
You need to copy three files from the .ZIP file.
-
Copy
glut.h
to the MinGW\include\GL directory. -
Copy
glut32.lib
to your build directory (i.e., the directory
that you compile into and link from). -
Copy
glut32.dll
to the same directory where your executable
will be created.(You can actually put
glut32.dll
in any directory in
your path.)
4 Building an Executable
You need to be aware of the following:
-
You must
#include <windows.h>
before
you#include <"GL/glut.h">
-
When you link, you must explicitly link-in
glut32.lib
(and not
use the-lglut32
option). -
You may get some warnings like the following:
ignoring #pragma comment
warning: 'int glutCreateMenu_ATEXIT_HACK(void (*)(int))' defined but not used
You can ignore them.
Help resolving other problems is available at
the MinGWiki.
5 Testing Your Installation
You can use the following small program (named test.c
)
to test your installation:
#include <windows.h> #include "GL/glut.h" void display() { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glFlush(); } void init() { glClearColor(0.000, 0.110, 0.392, 0.0); // JMU Gold glColor3f(0.314, 0.314, 0.000); // JMU Purple glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-1.0, 1.0, -1.0, 1.0); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(0, 0); glutCreateWindow("Test"); glutDisplayFunc(display); init(); glutMainLoop(); }
You should be able to build this program from the command line as follows:
g++ -o test -Wall test.c -mwindows glut32.lib -lopengl32 -lglu32
6 Using jGrasp
Some of you may have used MinGW under jGrasp in the past.
You can do so with GLUT but you will have to change some settings
in jGrasp.
In jGrasp, choose Settings on the main menu,
pull down to Compiler Settings, and then
pull down to either Workspace or
Project.
Next, click on the Compiler tab and change the «Language»
to C.
From here, you can set the «FLAGS or ARGS» for «Make», the «Compiler»,
etc… See, for example, the flags and arguments used in the
example above.
#include <GL/glut.h>
#include<iostream>
using
namespace
std;
int
rx = 100, ry = 125;
int
xCenter = 250, yCenter = 250;
void
myinit(
void
)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void
setPixel(GLint x, GLint y)
{
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
void
ellipseMidPoint()
{
float
x = 0;
float
y = ry;
float
p1 = ry * ry - (rx * rx) * ry + (rx * rx) * (0.25);
float
dx = 2 * (ry * ry) * x;
float
dy = 2 * (rx * rx) * y;
glColor3ub(
rand
() % 255,
rand
() % 255,
rand
() % 255);
while
(dx < dy)
{
setPixel(xCenter + x, yCenter + y);
setPixel(xCenter - x, yCenter + y);
setPixel(xCenter + x, yCenter - y);
setPixel(xCenter - x, yCenter - y);
if
(p1 < 0)
{
x = x + 1;
dx = 2 * (ry * ry) * x;
p1 = p1 + dx + (ry * ry);
}
else
{
x = x + 1;
y = y - 1;
dx = 2 * (ry * ry) * x;
dy = 2 * (rx * rx) * y;
p1 = p1 + dx - dy + (ry * ry);
}
}
glFlush();
float
p2 = (ry * ry) * (x + 0.5) * (x + 0.5) + (rx * rx) * (y
- 1) * (y - 1) - (rx * rx) * (ry * ry);
glColor3ub(
rand
() % 255,
rand
() % 255,
rand
() % 255);
while
(y > 0)
{
setPixel(xCenter + x, yCenter + y);
setPixel(xCenter - x, yCenter + y);
setPixel(xCenter + x, yCenter - y);
setPixel(xCenter - x, yCenter - y);
if
(p2 > 0)
{
x = x;
y = y - 1;
dy = 2 * (rx * rx) * y;
p2 = p2 - dy + (rx * rx);
}
else
{
x = x + 1;
y = y - 1;
dy = dy - 2 * (rx * rx);
dx = dx + 2 * (ry * ry);
p2 = p2 + dx -
dy + (rx * rx);
}
}
glFlush();
}
void
display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
glPointSize(2.0);
ellipseMidPoint();
glFlush();
}
int
main(
int
argc,
char
** argv)
{
glutInit(&argc, argv);
glutInitWindowSize(640, 480);
glutInitWindowPosition(10, 10);
glutCreateWindow(
"User_Name"
);
myinit();
glutDisplayFunc(display);
glutMainLoop();
return
0;
}