Installation
To use the shared library version of GLEW, you need to copy the headers and libraries into their destination directories. On Windows this typically boils down to copying:
| bin/glew32.dll | to | %SystemRoot%/system32 |
| lib/glew32.lib | to | |
| include/GL/glew.h | to | |
| include/GL/wglew.h | to |
where is the Visual C++ root directory, typically C:/Program Files/Microsoft Visual Studio/VC98 for Visual Studio 6.0 or C:/Program Files/Microsoft Visual Studio .NET 2003/Vc7/PlatformSDK for Visual Studio .NET.
On Unix, typing make install will attempt to install GLEW into /usr/include/GL and /usr/lib. You can customize the installation target via the GLEW_DEST environment variable if you do not have write access to these directories.
Building Your Project with GLEW
There are two ways to build your project with GLEW.
Including the source files / project file
The simpler but less flexible way is to include glew.h and glew.c into your project. On Windows, you also need to define the GLEW_STATIC preprocessor token when building a static library or executable, and the GLEW_BUILD preprocessor token when building a dll. You also need to replace and with in your code and set the appropriate include flag (-I) to tell the compiler where to look for it. For example:
Depending on where you put glew.h you may also need to change the include directives in glew.c. Note that if you are using GLEW together with GLUT, you have to include glew.h first. In addition, glew.h includes glu.h, so you do not need to include it separately.
On Windows, you also have the option of adding the supplied project file glew_static.dsp to your workspace (solution) and compile it together with your other projects. In this case you also need to change the GLEW_BUILD preprocessor constant to GLEW_STATIC when building a static library or executable, otherwise you get build errors.
Note that GLEW does not use the C runtime library, so it does not matter which version (single-threaded, multi-threaded or multi-threaded DLL) it is linked with (without debugging information). It is, however, always a good idea to compile all your projects including GLEW with the same C runtime settings.
Не секрет, что для серьезного использования OpenGL сейчас необходимо пользоваться различными расширениями (по крайней мере под форточками, где до сих пор OpenGL 1.1).
Использование расширений дает как доступ к таким стандартным уже возможностям, как шейдеры, так и к довольно специфическим возможностям конкретным видеокарточек.
Существует довольно много различных библиотек, предназначенных для работы с расширениями OpenGL (одна из них - мою libExt - постоянно используется в примерах с данного сайта).
В этой статье я хочу рассмотреть одну из самых популярных таких библиотек - (вошедшую в состав OpenGL SDK) - библиотеку OpenGL Extension Wrangler Library - GLew.
Это простая в использовании кроссплатформенная (в числе поддерживаемых платформ - M$ Windoze, Linux, Mac OS X, Solaris и другие ) библиотека обеспечивает удобство в использовании расширений OpenGL.
Для M$ Windoze (как и многих других платформ) можно скачать уже откомпилированную версию, состоящую из заголовочного файла glew.h, динамической библиотеки glew32.dll и двух библиотек glew32.lib и glew32s.lib.
При этом вы можете для компиляции своих программ использовать как статическую версию (т.е. не требующую динамической библиотеки glew32.dll, библиотечный файл glew32s.lib), так и динамическую (библиотека glew32.lib). В последнем случае для выполнения потребуется glew32.dll, но размер выполняемого файла будет меньше.
Для использования библиотеки необходимо подключить ее заголовочный файл glew.h вместо файла gl.h (он сам подключает все, что надо).
Далее для инициализации библиотеки необходимо вызвать функцию glewInit, возвращающую значение GL_TRUE при успешной инициализации библиотеки.
Обратите внимание, что данная функция должна быть вызвана уже после того, как будет создан и настроен контекст OpenGL, например в программах, использующих GLUT, после вызова функции glutCreateWindow.
Самый простой способ проверить поддержку расширения с заданным именем заключается в проверке значения глобальной переменной с именем вида GLEW_имя-расширения (т.е. в названии расширения GL заменяется на GLEW).
Так расширению GL_ARB_vertex_program соответствует глобальная переменная GLEW_ARB_vertex_program. Если она отлична от нуля, то данное расширение поддерживается и Вы можете напрямую обращаться к функциям, вводимым этим расширением.
Также можно проверить поддержку расширения по строке, содержащей его имя, при помощи функции glewIsSupported.
Для работы с расширениями, специфичными для определенной платформы дополнительно включите заголовочный файл wglew.h (для платформы M$ Windoze) или glxew.h (для Linux).
Аналогичным способом можно проверить поддержку заданной версии OpenGL - каждой версии соответствует глобальная переменная вида GLEW_VERSION_n_m (через n и m обозначены старший и младший номера версии, например 1.4).
Так следующий фрагмент кода проверяет поддержку OpenGL 1.4.
Этого же можно добиться и используя функцию glewIsSupported:
Для поддержки ряда экспериментальных расширений следует перед вызовом glewInit установить значение глобальной переменной glewExperimental в GL_TRUE.
Ниже приводится исходный текст простого примера, использующего библиотеку GLew для работы с шейдерами в OpenGL (обратите внимание, что данной программе кроме библиотек GLUT и GLew больше ничего не нужно).
По этой ссылке можно скачать весь исходный код к этой статье. Также доступны для скачивания откомпилированные версии для M$ Windows, Linux и Mac OS X.
Copyright © Alexey V. Boreskov 2003-2007
So I'm trying to move my OpenGL code from Main() into a specific class that will handle the 3D graphics only when necessary. Previously, the top of my main.cpp file looked like this:
This worked well enough. What I tried to do was move all the OpenGL-relevant code into methods of the Game class. So I removed #define GLEW_STATIC and #include from the above, and put them into Game.h, such that the top of Game.h now looks like this:
When I try to compile, I get the title error, #error gl.h included before glew.h .
Why is this happening, and how can I use OpenGL code (almost) entirely inside the functions of a specific class without this happening?
I have also tried this configuration in main.cpp, in an attempt to make sure that nothing includes SFML before GLEW.
Unfortunately, that doesn't help (there's nothing else being included that I'm not mentioning here).