Using glfw and glew - c++

I have problem understanding some opengl stuff using GLFW and GLEW.
i have 3 files shown below:
main.cpp:
#include "gamewindow.h"
int main() {
GameWindow *gameWindow = new GameWindow(1024, 768, "FirstOpenGLGame");
/* Loop until the user closes the window */
while (gameWindow->getRunning()) {
/* Render here */
gameWindow->render();
gameWindow->update();
gameWindow->setRunning();
}
delete gameWindow;
glfwTerminate();
return 0;
}
This is where the problem is, gamewindow.cpp:
#include "gamewindow.h"
GameWindow::GameWindow(int width, int height, const char* title) : _running(true), _height(1024), _width(1024 * (16/9))
{
/* Initialize the library */
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(width, height, title, NULL, NULL);
if(!window) {
glfwTerminate();
exit(0);
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
if(!glewInit()){ // <-- problem is this
glfwTerminate();
exit(EXIT_FAILURE);
}
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
coordSettings();
}
void GameWindow::setRunning() {
_running = !glfwWindowShouldClose(window);
}
bool GameWindow::getRunning() {
return _running;
}
void GameWindow::render() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_QUADS);
glVertex2d(0.0f, 0.0f);
glVertex2d(100.0f, 0.0f);
glVertex2d(100.0f, 800.0f);
glVertex2d(0.0f, 800.0f);
glEnd();
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
void GameWindow::update() {
}
void GameWindow::coordSettings() {
glViewport( 0, 0, _width, _height );
glMatrixMode(GL_PROJECTION);
glOrtho(0.0, _width, 0.0, _height, 0.0, -1.0);
glMatrixMode(GL_MODELVIEW);
}
and last the header file gamewindow.h:
#ifndef GAMEWINDOW_H
#define GAMEWINDOW_H
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
class GameWindow
{
private:
GLFWwindow* window;
bool _running;
GLfloat _width;
GLfloat _height;
void coordSettings();
public:
GameWindow(int width, int height, const char* title);
void setRunning();
bool getRunning();
void render();
void update();
};
#endif // GAMEWINDOW_H
everything works fine, but then i try to call glewInit() (without really understanding is i need to, or when i need to) but then nothing works. the program starts, but there is no window with a quad in it, like before. why is this? how is GLEW even used, and do i need it?

Related

Cannot set Window Icon in GLFW C++ Visual Studio 2019

I've tried to set the window icon from the scripts within the stackoverflow questions below, but nothing did work to my solution
GLFW SetWindowIcon
https://learn.microsoft.com/en-us/windows/win32/menurc/using-icons
My entire main.cpp from my solution:
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include <string>
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <Windows.h>
#include <WinUser.h>
#include <WinNls32.h>
int main()
{
// Create a custom icon at run time.
// Initialize GLFW
glfwInit();
// Tell GLFW what version of OpenGL we are using
// In this case we are using OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// Tell GLFW we are using the CORE profile
// So that means we only have the modern functions
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create a GLFWwindow object of 800 by 800 pixels, naming it "YoutubeOpenGL"
GLFWwindow* window = glfwCreateWindow(1200, 700, "Dessor 0.1.0c", NULL, NULL);
// Error check if the window fails to create
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
// Introduce the window into the current context
glfwMakeContextCurrent(window);
//Load GLAD so it configures OpenGL
gladLoadGL();
// Specify the viewport of OpenGL in the Window
// In this case the viewport goes from x = 0, y = 0, to x = 800, y = 800
glViewport(0, 0, 1200, 700);
// Initialize ImGUI
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 330");
// Variables to be changed in the ImGUI window
bool drawCube = false;
float size = 1.0f;
float color[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
// Main while loop
while (!glfwWindowShouldClose(window))
{
// Specify the color of the background
glClearColor(0.11f, 0.11f, 0.11f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Clean the back buffer and assign the new color to it
// Tell OpenGL a new frame is about to begin
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
if (drawCube)
glClearColor(0.01f, 0.01f, 0.01f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// ImGUI window creation
// Particular widget styling
static int i2 = 3;
static int ifov = 60;
static float size = 3.0;
static char name[128] = "5";
static const ImVec4 edge_color = ImVec4(0.25f, 0.25f, 0.90f, 1.00f);
static const ImVec4 inside_color = ImVec4(0.55f, 0.55f, 0.90f, 1.00f);
const ImVec2 size2 = ImVec2(250, 200);
ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 0, 0, 255));
ImGui::Begin("Drawing HyperCube Options", NULL, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::PopStyleColor();
ImGui::Checkbox("Draw Shape", &drawCube);
ImGui::SliderInt("D", &i2, 0, atoi(name), "%d-dimensional hypercube");
ImGui::InputText("", name, 7, ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_EnterReturnsTrue);
ImGui::SameLine();
ImGui::TextColored(ImVec4(255, 0, 255, 255), name);
ImGui::NewLine();
ImGui::SliderFloat("SIZE", &size, 1.0, 10.0);
ImGui::SliderInt("FOV", &ifov, 30, 120, "%d");
ImGui::NewLine();
ImGui::Button("Render", ImVec2(250, 60));
ImGui::BeginChild("Inside color", size2);
ImGui::TextColored(inside_color, "INSIDE COLOR");
ImGui::ColorPicker3("", (float*)&inside_color);
ImGui::TextColored(edge_color, "EDGE COLOR");
ImGui::ColorEdit3("", (float*)&edge_color);
ImGui::EndChild();
ImGui::NewLine();
ImGui::End();
// Checkbox that appears in the window
// Renders the ImGUI elements
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// Swap the back buffer with the front buffer
glfwSwapBuffers(window);
// Take care of all GLFW events
glfwPollEvents();
}
// Deletes all ImGUI instances
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
// Delete window before ending the program
glfwDestroyWindow(window);
// Terminate GLFW before ending the program
glfwTerminate();
return 0;
}
How can I use the glfwSetWindowIcon() or there's another way for change window icon in native c++?

using a global glfw window in multiple functions

I Have a int main(); function and a int Game(); function where in the main function I have a window I use in both functions. I have defined the window in the global scope and when I try to run the Game(); function before GLFW loop in main function the window opens for a second and then closes. I then get
Error: The GLFW library is not initialised
printed from error_callback();
Here's My Code
#include <GLFW/glfw3.h>
#include <GL/freeglut.h>
#include <GL/GL.h>
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
void drawText(const char *text, int length, int x, int y);
void framebuffer_size_callback(GLFWwindow* wndow, int width, int height);
void DrawCube(GLfloat centerPosX, GLfloat centerPosY, GLfloat centerPosZ, GLfloat edgeLength);
void button(GLfloat red, GLfloat green, GLfloat blue, int x, int y, int width, int height);
void error_callback(int error, const char* description);
int Game();
int width = 860, height = 490;
GLFWwindow* window;
int main(int argc, char **argv) {
//GLTtext* text = gltCreateText();
//gltSetText(text, "ElectroCraft");
//GLFWwindow* window;
int width = 860, height = 490;
if (!glfwInit()) {
printf("failed to init glfw");
return -1;
}
glutInit(&argc, argv);
window = glfwCreateWindow(width, height, "ElectroCraft", NULL, NULL);
glfwMakeContextCurrent(window);
if (!window) {
printf("failed to start window");
glfwTerminate();
return -1;
}
Game();
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, 0, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
string text;
glfwSetErrorCallback(error_callback);
while (!glfwWindowShouldClose(window)) {
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glClearColor(53.0f / 255.0f, 81.0f / 255.0f, 92.0f / 255.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2f(0, height-80);
glVertex2f(width, height - 80);
glEnd();
button(192.0f / 255.0f, 192.0f / 255.0f, 192.0f / 255.0f, width / 2 - 70, height / 2, 260, 50);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 1;
}
void error_callback(int error, const char* description) {
fprintf(stderr, "Error: %s\n", description);
}
int Game() {
//glfwMakeContextCurrent(window);
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, 0, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
while (!glfwWindowShouldClose) {
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glClearColor(62.0f / 255.0f, 85.9f / 255.0f, 255.0 / 255.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 1;
}
This could be because I didn't initiate the GLFW library globally but I couldn't seem to do this as I got an error if a if statement was outside of a function
the window opens for a second and then closes
Of course, because glfwWindowShouldClose in not a function call in the function Game. glfwWindowShouldClose is a function pointer, so !glfwWindowShouldClose evaluates to false and the loop never runs:
while (!glfwWindowShouldClose) {
while (!glfwWindowShouldClose(window)) {
I then get Error: The GLFW library is not initialised
This is because GLFW is terminated by glfwTerminate() in the function Game. Delete glfwTerminate() from the function Game.
But note, once you've closed a window, you've to create a new window. An option would be to hide glfwHideWindow and show glfwShowWindow a window.

OpenGL - Not getting background color

I am trying to build a simple OpenGL application in C++. I am using FLTK to build a Window, and within that I am drawing using OpenGL. The following is my code:
// Make the GUI here
#define WIN32
#include <GL/glew.h>
#include <GL/glut.h>
#include <FL/gl.h>
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Color_Chooser.H>
#include <FL/Fl_Gl_Window.H>
#include <FL/Fl_Menu_Bar.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Button.H>
class Block
{
public:
Block(int x, int y, int z)
{
xyz[0] = x;
xyz[1] = y;
xyz[2] = z;
}
int getX(){ return xyz[0];}
int getY(){ return xyz[1];}
int getZ(){ return xyz[2];}
void setX(int x){ xyz[0]=x;}
void setY(int y){ xyz[1]=y;}
void setZ(int z){ xyz[2]=z;}
private:
int xyz[3];
};
// Snake is an array blocks.
Block* snake;
// Mouse is a single block
Block* mouse;
void renderEverything();
class GlWindow : public Fl_Gl_Window
{
public:
// Call back for draw
void draw()
{
glTranslatef(0.0f,0.0f, -10.0f);
// Get the current state of the universe and draw it
glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // Clear the background of our window to red
glClear(GL_COLOR_BUFFER_BIT); //Clear the colour buffer (more buffers later on)
glLoadIdentity(); // Load the Identity Matrix to reset our drawing locations
// Render everything
renderEverything();
//glutSolidCube(5);
glFlush(); // Flush the OpenGL buffers to the window
}
// To handle key-events
void handle()
{
}
// Constructor
GlWindow(int X, int Y, int W, int H, const char* L=0): Fl_Gl_Window(X,Y,W,H,L)
{
}
};
void renderEverything()
{
glBegin(GL_QUADS);
glVertex3f(-1.0f,-1.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glEnd();
}
void buildGUI(int argc, char** argv)
{
// Main Window
Fl_Double_Window *window = new Fl_Double_Window(800,500);
window->label("Snake3D");
window->color(FL_LIGHT3);
window->begin();
// Menu Bar
Fl_Menu_Bar* menubar = new Fl_Menu_Bar(0,0,800,30);
menubar->color(FL_LIGHT3);
menubar->down_color(fl_rgb_color(0,145,255));
menubar->box(FL_THIN_UP_BOX);
menubar->add("File/Exit");
menubar->add("Help/About");
// OpenGL Window
GlWindow* gameWindow = new GlWindow(200,30,600,470);
// Start Button
Fl_Button* startButton = new Fl_Button(50,200,100,30,"Start");
Fl_Button* pauseButton = new Fl_Button(50,300,100,30,"Pause");
window->show();
window->end();
Fl::run();
}
int main(int argc, char ** argv)
{
// Build GUI
buildGUI(argc,argv);
}
According to the tutorial I am following, I should get a red background. But only half of my screen is colored
What might be going wrong?

C++ OpenGL LNK2001 when header is included

I am getting 28
error LNK2001: unresolved external symbol
messages. I know for a fact, for example, that
glBindVertexArray
is in _int_gl_exts.h, and sure enough I am including it.
#include <glload\_int_gl_exts.h>
I don't know if this is a problem, but there are three underscore characters in my error message
symbol ___gleBindVertexArray
Whereas in the file, there is only two underscores before it. This is the exact line inside the include file
extern PFNGLBINDVERTEXARRAYPROC __gleBindVertexArray;
#define glBindVertexArray __gleBindVertexArray
I am pulling much of my stuff directly from a tutorial, and even when my includes and functions are the same, I still have problems. I'll post full code if necessary, but I am out of ideas after about 2 days stuck here.
EDIT: I do in fact have both
#pragma comment(lib, "opengl32.lib")
as well as I tried changing the Project Properties in Linker to add this to additional libraries.
My entire code is as follows. I understand there's a lot of other stuff that needs changed, but this is what I'm trying to get past first.
#include <algorithm>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <exception>
#include <stdexcept>
#include <string.h>
#include <glload/gl_3_3.h>
#include <glload/gll.hpp>
#include <glutil/Shader.h>
#include <GL/freeglut.h>
#include "framework.h"
#include "directories.h"
#include <glload/_int_gl_exts.h>
#ifdef LOAD_X11
#define APIENTRY
#endif
namespace Framework
{
GLuint LoadShader(GLenum eShaderType, const std::string &strShaderFilename)
{
std::string strFilename = FindFileOrThrow(strShaderFilename);
std::ifstream shaderFile(strFilename.c_str());
std::stringstream shaderData;
shaderData << shaderFile.rdbuf();
shaderFile.close();
try
{
return glutil::CompileShader(eShaderType, shaderData.str());
}
catch(std::exception &e)
{
fprintf(stderr, "%s\n", e.what());
throw;
}
}
GLuint CreateProgram(const std::vector<GLuint> &shaderList)
{
try
{
GLuint prog = glutil::LinkProgram(shaderList);
std::for_each(shaderList.begin(), shaderList.end(), glDeleteShader);
return prog;
}
catch(std::exception &e)
{
std::for_each(shaderList.begin(), shaderList.end(), glDeleteShader);
fprintf(stderr, "%s\n", e.what());
throw;
}
}
float DegToRad(float fAngDeg)
{
const float fDegToRad = 3.14159f * 2.0f / 360.0f;
return fAngDeg * fDegToRad;
}
std::string FindFileOrThrow( const std::string &strBasename )
{
std::string strFilename = LOCAL_FILE_DIR + strBasename;
std::ifstream testFile(strFilename.c_str());
if(testFile.is_open())
return strFilename;
strFilename = GLOBAL_FILE_DIR + strBasename;
testFile.open(strFilename.c_str());
if(testFile.is_open())
return strFilename;
throw std::runtime_error("Could not find the file " + strBasename);
}
}
void init();
void display();
void reshape(int w, int h);
void keyboard(unsigned char key, int x, int y);
unsigned int defaults(unsigned int displayMode, int &width, int &height);
void APIENTRY DebugFunc(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
const GLchar* message, GLvoid* userParam)
{
std::string srcName;
switch(source)
{
case GL_DEBUG_SOURCE_API_ARB: srcName = "API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: srcName = "Window System"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: srcName = "Shader Compiler"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: srcName = "Third Party"; break;
case GL_DEBUG_SOURCE_APPLICATION_ARB: srcName = "Application"; break;
case GL_DEBUG_SOURCE_OTHER_ARB: srcName = "Other"; break;
}
std::string errorType;
switch(type)
{
case GL_DEBUG_TYPE_ERROR_ARB: errorType = "Error"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: errorType = "Deprecated Functionality"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: errorType = "Undefined Behavior"; break;
case GL_DEBUG_TYPE_PORTABILITY_ARB: errorType = "Portability"; break;
case GL_DEBUG_TYPE_PERFORMANCE_ARB: errorType = "Performance"; break;
case GL_DEBUG_TYPE_OTHER_ARB: errorType = "Other"; break;
}
std::string typeSeverity;
switch(severity)
{
case GL_DEBUG_SEVERITY_HIGH_ARB: typeSeverity = "High"; break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB: typeSeverity = "Medium"; break;
case GL_DEBUG_SEVERITY_LOW_ARB: typeSeverity = "Low"; break;
}
printf("%s from %s,\t%s priority\nMessage: %s\n",
errorType.c_str(), srcName.c_str(), typeSeverity.c_str(), message);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
int width = 500;
int height = 500;
unsigned int displayMode = GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH | GLUT_STENCIL;
displayMode = defaults(displayMode, width, height);
glutInitDisplayMode (displayMode);
glutInitContextVersion (3, 3);
glutInitContextProfile(GLUT_CORE_PROFILE);
#ifdef DEBUG
glutInitContextFlags(GLUT_DEBUG);
#endif
glutInitWindowSize (width, height);
glutInitWindowPosition (300, 200);
int window = glutCreateWindow (argv[0]);
glload::LoadFunctions();
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
if(!glload::IsVersionGEQ(3, 3))
{
printf("Your OpenGL version is %i, %i. You must have at least OpenGL 3.3 to run this tutorial.\n",
glload::GetMajorVersion(), glload::GetMinorVersion());
glutDestroyWindow(window);
return 0;
}
if(glext_ARB_debug_output)
{
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
glDebugMessageCallbackARB(DebugFunc, (void*)15);
}
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
#pragma comment(lib, "opengl32.lib")
#include <string>
#include <vector>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <glload/gl_3_3.h>
#include <glload\_int_gl_exts.h>
#include <GL/freeglut.h>
#include <glload\_int_gl_1_5.h>
#include <glload\_int_gl_1_1_rem_3_1.h>
#include "../../framework/framework.h"
#define GL_GLEXT_PROTOTYPES
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
GLuint theProgram;
GLuint elapsedTimeUniform;
void InitializeProgram()
{
std::vector<GLuint> shaderList;
shaderList.push_back(Framework::LoadShader(GL_VERTEX_SHADER, "calcOffset.vert"));
shaderList.push_back(Framework::LoadShader(GL_FRAGMENT_SHADER, "calcColor.frag"));
theProgram = Framework::CreateProgram(shaderList);
elapsedTimeUniform = glGetUniformLocation(theProgram, "time");
GLuint loopDurationUnf = glGetUniformLocation(theProgram, "loopDuration");
GLuint fragLoopDurUnf = glGetUniformLocation(theProgram, "fragLoopDuration");
glUseProgram(theProgram);
glUniform1f(loopDurationUnf, 5.0f);
glUniform1f(fragLoopDurUnf, 10.0f);
glUseProgram(0);
}
const float vertexPositions[] = {
0.25f, 0.25f, 0.0f, 1.0f,
0.25f, -0.25f, 0.0f, 1.0f,
-0.25f, -0.25f, 0.0f, 1.0f,
};
GLuint positionBufferObject;
GLuint vao;
void createCube() {
glBegin(GL_LINES);
glLineWidth(99.0);
glColor3f( 1.0, 0.0, 1.0 );
glVertex3f( 0.5,0.5,0.5 );
glVertex3f( 0.5,0.5,-0.5 );
glVertex3f( 0.5,0.5,-0.5 );
glVertex3f( -0.5,0.5,-0.5 );
glVertex3f( -0.5,0.5,-0.5 );
glVertex3f( -0.5,0.5,0.5 );
glVertex3f( -0.5,0.5,0.5 );
glVertex3f( 0.5,0.5,0.5 );
glVertex3f( 0.5,-0.5,0.5 );
glVertex3f( 0.5,-0.5,-0.5 );
glVertex3f( 0.5,-0.5,-0.5 );
glVertex3f( -0.5,-0.5,-0.5 );
glVertex3f( -0.5,-0.5,-0.5 );
glVertex3f( -0.5,-0.5,0.5 );
glVertex3f( -0.5,-0.5,0.5 );
glVertex3f( 0.5,-0.5,0.5 );
glVertex3f( 0.5,0.5,0.5 );
glVertex3f( 0.5,-0.5,0.5 );
glVertex3f( -0.5,-0.5,-0.5 );
glVertex3f( -0.5,0.5,-0.5 );
glVertex3f( 0.5,0.5,-0.5 );
glVertex3f( 0.5,-0.5,-0.5 );
glVertex3f( -0.5,0.5,0.5 );
glVertex3f( -0.5,-0.5,0.5 );
glEnd();
}
void InitializeVertexBuffer()
{
glGenBuffers(1, &positionBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions, GL_STREAM_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
//Called after the window and OpenGL are initialized. Called exactly once, before the main loop.
void init()
{
InitializeProgram();
InitializeVertexBuffer();
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
}
//Called to update the display.
//You should call glutSwapBuffers after all of your rendering to display what you rendered.
//If you need continuous updates of the screen, call glutPostRedisplay() at the end of the function.
void display()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(theProgram);
glUniform1f(elapsedTimeUniform, glutGet(GLUT_ELAPSED_TIME) / 1000.0f);
glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
createCube();
glColor3f(1.0,0.0,0.0);
glutSolidSphere(0.04,10,10);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glUseProgram(0);
glutSwapBuffers();
glutPostRedisplay();
}
//Called whenever the window is resized. The new window size is given, in pixels.
//This is an opportunity to call glViewport or glScissor to keep up with the change in size.
void reshape (int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
}
//Called whenever a key on the keyboard was pressed.
//The key is given by the ''key'' parameter, which is in ASCII.
//It's often a good idea to have the escape key (ASCII value 27) call glutLeaveMainLoop() to
//exit the program.
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 27:
glutLeaveMainLoop();
return;
}
}
unsigned int defaults(unsigned int displayMode, int &width, int &height) {return displayMode;}
It would be good if you actually stated what library you were trying to link to. The only reason I know which one it is is because I recognize my own work ;)
In any case, the documentation makes it clear what library you should link to. If you're using the Premake4 build system, then you should just have UseLibs {"glload"} in your premake4.lua project. If you're using something else, then you need to manually link to glloadD or glload in debug and release respectively. On Windows, you need a .lib suffix; on Linux, you would use libglloadD and such.
Whether you link with a pragma or use the project settings is irrelevant.
Including the declarations is one thing; their definitions are another.
You must link against the OpenGL library when you build your executable.
Follow the instructions in your OpenGL book or reference, but typically you'll pass something like -lopengl32 to your build command; it looks like you might be using Visual Studio, which handles the specific build command for you, in which case you should add the OpenGL libraries to your project properties or use #pragma:
#pragma comment(lib, "opengl32.lib")
You probably didn't link the opengl lib file.
In your compiler settings, add to the list of included libraries "opengl32.lib".

Display images on a transparent background with no border in C++ / OpenGL

I am looking for a way to display two png images (in fact, it will be numbers, my aim is to create an overlay for live streaming to display players score and some further additional content) on a window with transparent background with no border. So that we just see the score over the window placed behind.
Is there any way to do something like that ? I have already tried many things with SDL, textures, but nothing led me to any satisfying result. The best I found was some dirty code almost working but completely unusable.
If possible, the solution may let possible to add the functionality that when you click left or right on one of the 2 scores, it is incremented or decremented.
Edit: Here is my current code. I started new without any bit of the dirty code I had before, because I would like to understand what I am doing. I have my 2 numbers displayed as textures, now I would like to remove borders and title bar of my window, and make my background transparent.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <windows.h>
#include <windowsx.h>
#include <math.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include "sdlglutils.h"
#include <assert.h>
#include <tchar.h>
using namespace std;
int overlay;
int TimerEnabled;
GLfloat posX, posY, posZ;
GLuint texture_0, texture_1, texture_2, texture_3;
void Initialize()
{
glEnable(GL_ALPHA_TEST);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0, 0, 0, 0);
glEnable(GL_TEXTURE_2D);
}
void Reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)w/(GLfloat)h,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
texture_0 = loadTexture("0.png");
texture_1 = loadTexture("1.png");
texture_2 = loadTexture("2.png");
texture_3 = loadTexture("3.png");
return;
}
void Draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glTranslatef(posX,posY,posZ);
glScalef(1.0f,1.0f,1.0f);
glPushMatrix();
glTranslated(-6, 8, 0);
glBindTexture(GL_TEXTURE_2D, texture_1);
glBegin(GL_QUADS);
glTexCoord2d(0,0); glVertex2d(0,0);
glTexCoord2d(1,0); glVertex2d(1,0);
glTexCoord2d(1,1); glVertex2d(1,1);
glTexCoord2d(0,1); glVertex2d(0,1);
glEnd();
glPopMatrix();
glPushMatrix();
glTranslated(6, 8, 0);
glBindTexture(GL_TEXTURE_2D, texture_2);
glBegin(GL_QUADS);
glTexCoord2d(0,0); glVertex2d(0,0);
glTexCoord2d(1,0); glVertex2d(1,0);
glTexCoord2d(1,1); glVertex2d(1,1);
glTexCoord2d(0,1); glVertex2d(0,1);
glEnd();
glPopMatrix();
glFlush();
}
void Display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
Draw();
glutSwapBuffers();
}
void KeyboardSpecialEvent( int key, int x, int y)
{
switch(key)
{
case(GLUT_KEY_UP) :
{
posY += 0.3;
}break;
case(GLUT_KEY_DOWN) :
{
posY -= 0.3;
}break;
case(GLUT_KEY_LEFT) :
{
posX -= 0.3;
}break;
case(GLUT_KEY_RIGHT) :
{
posX += 0.3;
}break;
}
}
void MouseEvent( int button, int state, int x, int y){ };
void MotionMouseEvent( int x, int y ){ };
void IdleEvent(){ };
void TimerEvent(int time)
{
glutPostRedisplay();
if(TimerEnabled)
glutTimerFunc(10, TimerEvent, time);
}
void KeyboardEvent( unsigned char key, int x, int y)
{
switch(key)
{
case ' ' :
{
TimerEnabled = !TimerEnabled;
if (TimerEnabled)
glutTimerFunc(40, TimerEvent, 0);
}
break;
case 'q' :
{
exit(0);
}
break;
}
}
int main(int argc, char** argv)
{
posX = 0;
posY = 0;
posZ = -25;
TimerEnabled = 1;
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(1600,900);
glutInitWindowPosition(0,0);
overlay = glutCreateWindow("ScoreOverlay");
//glutFullScreen();
Initialize();
glutDisplayFunc(Display);
glutReshapeFunc(Reshape);
glutKeyboardFunc(KeyboardEvent);
glutSpecialFunc(KeyboardSpecialEvent);
glutMouseFunc(MouseEvent);
glutMotionFunc(MotionMouseEvent);
glutIdleFunc(IdleEvent);
glutTimerFunc(40, TimerEvent, 0);
glutMainLoop();
return 0;
}
Here is a working base sample (using c++ with clr support) that could help you.
You need to adapt it to your need (for example use DrawImage instead of FillEllipse)
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
ref class MyForm : public Form
{
public:
MyForm()
{
this->m_brush = gcnew SolidBrush(Color::Blue);
this->m_canvas = gcnew System::Windows::Forms::Panel();
this->m_canvas->BackColor = Color::Pink;
this->m_canvas->Dock = System::Windows::Forms::DockStyle::Fill;
this->m_canvas->Location = System::Drawing::Point(0, 0);
this->m_canvas->Margin = System::Windows::Forms::Padding(0);
this->m_canvas->Name = "Canvas";
this->m_canvas->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MyForm::canvas_Paint);
this->m_canvas->TabIndex = 0;
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = Color::Pink;
this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;
this->ClientSize = System::Drawing::Size(200, 200);
this->Controls->Add(this->m_canvas);
this->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &MyForm::form_KeyDown);
this->TransparencyKey = Color::Pink;
this->Name = "MyForm";
this->Text = "MyForm";
}
private:
void canvas_Paint(Object^ sender, PaintEventArgs^ e) {
e->Graphics->FillEllipse(this->m_brush, Rectangle(50, 50, 100, 100));
}
void form_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
// Test key ...
this->m_canvas->Invalidate();
// ...
}
Brush^ m_brush;
Panel^ m_canvas;
};
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew MyForm());
return 0;
}
It looks like you need this on Windows. Have you looked at Layered Windows?
Unless you need OpenGL for the graphics for some reason I think you'll be better off loading your images as regular bitmaps and blitting them to the layered window directly. Using OpenGL you would need to draw to a texture map, then take that texture and blit it to the layered window.