why this error become (C2664 error c++ Visual Studio) - c++

I am trying to modify an program.implemented in 2015 visual studio. After opening the project in Visual Studio 2019 there are many errors of the type below.
Severity Code Description Project File Line Suppression State
Error C2664 'Model::Model(Model &&)': cannot convert argument 1 from 'const > char [24]' to 'GLchar *' OpenGl
Severity Code Description Project File Line Suppression State
Message Conversion from string literal loses const qualifier (see /Zc:strictStrings) OpenGl
Error formed in that line:
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow *window = glfwCreateWindow( WIDTH, HEIGHT, "LearnOpenGL",
nullptr, nullptr );
if ( nullptr == window )
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate( );
return EXIT_FAILURE;
}
glfwMakeContextCurrent( window );
glfwGetFramebufferSize( window, &SCREEN_WIDTH, &SCREEN_HEIGHT );
// Set the required callback functions
glfwSetKeyCallback( window, KeyCallback );
glfwSetCursorPosCallback( window, MouseCallback );
// GLFW Options
glfwSetInputMode( window, GLFW_CURSOR, GLFW_CURSOR_DISABLED );
// Set this to true so GLEW knows to use a modern approach to retrieving
function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if ( GLEW_OK != glewInit( ) )
{
std::cout << "Failed to initialize GLEW" << std::endl;
return EXIT_FAILURE;
}
// Define the viewport dimensions
glViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
// OpenGL options
glEnable( GL_DEPTH_TEST );
// Setup and compile our shaders
Shader shader( "res/shaders/modelLoading.vert",
"res/shaders/modelLoading.frag" );
// Load models
Model ourModel("res/models/nanosuit.obj");
// Draw in wireframe
//glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glm::mat4 projection = glm::perspective( camera.GetZoom( ), ( float
)SCREEN_WIDTH/( float )SCREEN_HEIGHT, 0.1f, 100.0f );
// Game loop
while( !glfwWindowShouldClose( window ) )
{
// Set frame time
GLfloat currentFrame = glfwGetTime( );
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// Check and call events
glfwPollEvents( );
DoMovement( );
// Clear the colorbuffer
glClearColor( 0.05f, 0.05f, 0.05f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
shader.Use( );
glm::mat4 view = camera.GetViewMatrix( );
glUniformMatrix4fv( glGetUniformLocation( shader.Program, "projection"
), 1, GL_FALSE, glm::value_ptr( projection ) );
glUniformMatrix4fv( glGetUniformLocation( shader.Program, "view" ),
1,
GL_FALSE, glm::value_ptr( view ) );
// Draw the loaded model
glm::mat4 model;
model = glm::translate( model, glm::vec3( 0.0f, -1.75f, 0.0f ) ); //
Translate it down a bit so it's at the center of the scene
model = glm::scale( model, glm::vec3( 0.2f, 0.2f, 0.2f ) ); // It's a
bit too big for our scene, so scale it down
glUniformMatrix4fv( glGetUniformLocation( shader.Program, "model" ),
1, GL_FALSE, glm::value_ptr( model ) );
ourModel.Draw( shader );
// Swap the buffers
glfwSwapBuffers( window );
}
glfwTerminate( );
return 0;
}
// Moves/alters the camera positions based on user input
void DoMovement( )
{
// Camera controls
if ( keys[GLFW_KEY_W] || keys[GLFW_KEY_UP] )
{
camera.ProcessKeyboard( FORWARD, deltaTime );
}
if ( keys[GLFW_KEY_S] || keys[GLFW_KEY_DOWN] )
{
camera.ProcessKeyboard( BACKWARD, deltaTime );
}
if ( keys[GLFW_KEY_A] || keys[GLFW_KEY_LEFT] )
{
camera.ProcessKeyboard( LEFT, deltaTime );
}
if ( keys[GLFW_KEY_D] || keys[GLFW_KEY_RIGHT] )
{
camera.ProcessKeyboard( RIGHT, deltaTime );
**strong text** }
}
// Is called whenever a key is pressed/released via GLFW
void KeyCallback( GLFWwindow *window, int key, int scancode, int
action, int mode )
{
if ( GLFW_KEY_ESCAPE == key && GLFW_PRESS == action )
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
if ( key >= 0 && key < 1024 )
{
if ( action == GLFW_PRESS )
{
keys[key] = true;
}
else if ( action == GLFW_RELEASE )
{
keys[key] = false;
}
}
}
void MouseCallback( GLFWwindow *window, double xPos, double yPos )
{
if ( firstMouse )
{
lastX = xPos;
lastY = yPos;
firstMouse = false;
}
GLfloat xOffset = xPos - lastX;
GLfloat yOffset = lastY - yPos; // Reversed since y-coordinates go from
bottom to left
lastX = xPos;
lastY = yPos;
camera.ProcessMouseMovement( xOffset, yOffset );
}
the Error exactly in
// Load models
Model ourModel("res/models/nanosuit.obj");

You could pass the model name as a non-const C string:
char tmp[] = "res/models/nanosuit.obj";
Model ourModel(tmp);

Related

Perform continuous animation with GLFW

I want to use OpenGL to implement an animation that can be started and paused with mouse clicks. Since I am currently using the GLFW, the functions in GLUT are no longer applicable.
In GLUT, the implementation can be like this:
void windowMouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
// start
glutIdleFunc(idleFunction);
}
else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
// pause
glutIdleFunc(NULL);
}
}
However, glutIdleFunc() does not work in GLFW. I just wrote a coding frame to perform my goal but got stuck in finding the proper function to replace glutIdleFunc().
void mouse_button_callback(GLFWwindow* window, int button, int action, int mode)
{
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
{
// start
}
else if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS)
{
// pause
}
}
Is there any function in GLFW that can replace the previous one? Or is there any way to perform continuous animation with GLFW?
Get creative with glfwPostEmptyEvent() and glfwWaitEventsTimeout():
// g++ main.cpp `pkg-config --cflags --libs glfw3 gl`
#include <GLFW/glfw3.h>
void (*idleFunc)(GLFWwindow*) = nullptr;
void idle( GLFWwindow* aWindow )
{
static float angle = 0.0f;
static double prvTime = glfwGetTime();
const double curTime = glfwGetTime();
const double dt = (curTime - prvTime);
prvTime = curTime;
angle += 60.0 * dt;
int w, h;
glfwGetFramebufferSize( aWindow, &w, &h );
glViewport( 0, 0, w, h );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPushMatrix();
glRotatef( angle, 0, 0, 1 );
glBegin(GL_TRIANGLES);
glColor3ub( 0, 255, 0 );
glVertex2f( -0.5, -0.5 );
glVertex2f( 0.5, -0.5 );
glVertex2f( 0.0, 0.5 );
glEnd();
glPopMatrix();
glfwSwapBuffers( aWindow );
}
void display( GLFWwindow* aWindow )
{
int w, h;
glfwGetFramebufferSize( aWindow, &w, &h );
glViewport( 0, 0, w, h );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glBegin(GL_TRIANGLES);
glColor3ub( 255, 0, 0 );
glVertex2f( -0.5, -0.5 );
glVertex2f( 0.5, -0.5 );
glVertex2f( 0.0, 0.5 );
glEnd();
glfwSwapBuffers( aWindow );
}
void button( GLFWwindow* window, int button, int action, int mode )
{
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
{
idleFunc = idle;
glfwPostEmptyEvent();
}
else if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS)
{
idleFunc = nullptr;
glfwPostEmptyEvent();
}
}
int main( int, char** )
{
glfwInit();
GLFWwindow* window = glfwCreateWindow( 640, 480, "GLFW", NULL, NULL );
glfwMakeContextCurrent( window );
glfwSetMouseButtonCallback( window, button );
while( !glfwWindowShouldClose( window ) )
{
if(idleFunc)
{
idleFunc(window);
glfwWaitEventsTimeout(0.016);
}
else
{
display(window);
glfwWaitEvents();
}
}
glfwTerminate();
}
The glfwPostEmptyEvent() along with the structure of the glfwWindowShouldClose() loop in main() lets you simulate the behavior of glutPostRedisplay() and the glfwWaitEventsTimeout() lets the idleFunc() (if any) run every 16 milliseconds or so.

GIF dramatically lowers FPS

Today I finally figured out what I needed to do to animate my GIF but now that I have it animated the FPS on my program lowered dramatically. I have my GIF in a serperate function so it doesn't have to reload every texture whenever I try to update the frames of the GIF. I also plan on loading more GIFs if there is a way to fix my FPS drop issue so I need a way to reduce lag on all of them. Is there any easy way to fix this?
My code:
LUtil.cpp:
#include "LUtil.h"
#include <IL/il.h>
#include <IL/ilu.h>
#include "LSpriteSheet.h"
int add = 0;
int zoom = 0;
double leftzoom = -SCREEN_WIDTH;
double topzoom = -SCREEN_HEIGHT;
double rightzoom = SCREEN_WIDTH;
double bottomzoom = SCREEN_HEIGHT;
float sy = 0.f;
int scroll = 0;
GLfloat gCameraX = 0.f, gCameraY = 0.f, gCameraZ = 0.f;
//Sprite texture
LSpriteSheet gArrowSprites;
LSpriteSheet gSamusSprites;
LSpriteSheet jSamusSprites;
bool initGL()
{
//Initialize GLEW
GLenum glewError = glewInit();
if( glewError != GLEW_OK )
{
printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
return false;
}
//Make sure OpenGL 2.1 is supported
if( !GLEW_VERSION_2_1 )
{
printf( "OpenGL 2.1 not supported!\n" );
return false;
}
//Set the viewport
glViewport( 0.f, -0.f, SCREEN_WIDTH, SCREEN_HEIGHT );
//Initialize Projection Matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( leftzoom, rightzoom, bottomzoom, topzoom, 1.0, -1.0 );
//Initialize Modelview Matrix
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPushMatrix();
//Initialize clear color
glClearColor( 0.f, 0.f, 0.f, 1.f );
//Enable texturing
glEnable( GL_TEXTURE_2D );
glEnable( GL_BLEND );
glDisable( GL_DEPTH_TEST );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
//Check for error
GLenum error = glGetError();
if( error != GL_NO_ERROR )
{
printf( "Error initializing OpenGL! %s\n", gluErrorString(error));
return false;
}
//Initialize DevIL
ilInit();
ilClearColour( 255, 255, 255, 000 );
//Check for error
ILenum ilError = ilGetError();
if( ilError != IL_NO_ERROR )
{
printf( "Error initializing DevIL! %s\n", iluErrorString(ilError) );
return false;
}
return true;
}
LFRect clip;
bool loadMedia()
{
//Load texture
if( !gArrowSprites.loadTextureFromFile( "Textures/SamusM.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
clip = { 0.f, 0.f, 330.f, 355.f };
//Top left
clip.x = 0.f;
clip.y = 0.f;
gArrowSprites.addClipSprite( clip );
//Top right
clip = {0.f, 0.f, 310.f, 480.f};
clip.x = 331.f;
clip.y = 0.f;
gArrowSprites.addClipSprite( clip );
clip = {0.f, 0.f, 330.f, 125.f};
//Bottom left
clip.x = 0.f;
clip.y = 355.f;
gArrowSprites.addClipSprite( clip );
clip = { 0.f, 0.f, 330.f, 355.f };
//Top left
clip.x = 0.f;
clip.y = 480.f;
gArrowSprites.addClipSprite( clip );
//Top right
clip = {0.f, 0.f, 310.f, 480.f};
clip.x = 331.f;
clip.y = 480.f;
gArrowSprites.addClipSprite( clip );
clip = {0.f, 0.f, 330.f, 125.f};
//Bottom left
clip.x = 0.f;
clip.y = 835.f;
gArrowSprites.addClipSprite( clip );
//Generate VBO
if( !gArrowSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
if( !jSamusSprites.loadTextureFromFile( "Textures/SamusAran.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
clip = { 0.f, 0.f, 375.f, 562.f };
//Top left
clip.x = 0.f;
clip.y = 0.f;
jSamusSprites.addClipSprite( clip );
if( !jSamusSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
return true;
}
bool textureLoaded = false;
bool loadGif(){
if(textureLoaded == false){
if( !gSamusSprites.loadTextureFromFile( "Textures/SamusG.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
textureLoaded = true;
}
sy += 214.f;
if(sy == 8988.f){
sy = 0.f;
}
clip = {0.f, 0.f, 213.f, 214.f};
clip.x = 0.f;
clip.y = sy;
gSamusSprites.addClipSprite( clip );
if( !gSamusSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
return true;
}
void update()
{
}
void render()
{
//Clear color buffer
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPushMatrix();
if(add == 0){
if(zoom < 100){
double const f_zoom = 1.0 - 0.01 * zoom;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(leftzoom * f_zoom, rightzoom * f_zoom, bottomzoom * f_zoom, topzoom * f_zoom, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
if(zoom < -102){
double const f_zoom = 1.0 + 0.01 * zoom;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(leftzoom * f_zoom, rightzoom * f_zoom, bottomzoom * f_zoom, topzoom * f_zoom, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
glTranslatef( -1080.f, -782.f, 0.f );
gArrowSprites.renderSprite( 0 );
//Render top right arrow
glTranslatef( +1080.f, +782.f, 0.f );
glTranslatef( 1085.f, -120.f, 0.f );
gArrowSprites.renderSprite( 1 );
//Render bottom left arrow
glTranslatef( -1085.f, +120.f, 0.f );
glTranslatef( 0.f, 885.f ,0.f );
gArrowSprites.renderSprite( 2 );
glTranslatef(0.f, -885.f, 0.f);
jSamusSprites.renderSprite( 0 );
glTranslatef( -620.f, -855.f, 0.f );
glTranslatef( 620.f, 0.f , 0.f );
gSamusSprites.renderSprite( 0 );
}
if(add == 1){
if(zoom < 100){
double const f_zoom = 1.0 - 0.01 * zoom;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(leftzoom * f_zoom, rightzoom * f_zoom, bottomzoom * f_zoom, topzoom * f_zoom, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
if(zoom < -102){
double const f_zoom = 1.0 + 0.01 * zoom;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(leftzoom * f_zoom, rightzoom * f_zoom, bottomzoom * f_zoom, topzoom * f_zoom, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
glTranslatef( -1080.f, -782.f, 0.f );
gArrowSprites.renderSprite( 3 );
glTranslatef( +1080.f, +782.f, 0.f );
glTranslatef( 1085.f, -120.f, 0.f );
gArrowSprites.renderSprite( 4 );
glTranslatef( -1085.f, +120.f, 0.f );
glTranslatef( 0.f, 885.f ,0.f );
gArrowSprites.renderSprite( 5 );
glTranslatef(0.f, -885.f, 0.f);
jSamusSprites.renderSprite( 0 );
glTranslatef( -620.f, -855.f, 0.f );
glTranslatef( 620.f, 0.f , 0.f );
gSamusSprites.renderSprite( 0 );
}
glLoadIdentity();
glutSwapBuffers();
}
void handleKeys( unsigned char key, int x, int y )
{
//If the user presses q
if( key == 'q' && add == 0 )
{
add++;
}
else if( key == 'q' && add == 1)
{
add--;
}
//Update the sprite rectangles so the texture change takes effect
if( key == 27 ) {
exit(0);
}
if(key == 'a') {
gCameraX += 8.f;
}
else if (key == 'd') {
gCameraX -= 8.f;
}
else if (key == 'w') {
gCameraY += 8.f;
}
else if (key == 's') {
gCameraY -= 8.f;
}
else if (key == '+' && zoom != 99) {
zoom += 1;
}
else if (key == '-' && zoom != -101) {
zoom -= 1;
}
//Take saved matrix off the stack and reset it
glMatrixMode( GL_MODELVIEW );
glPopMatrix();
glLoadIdentity();
//Move camera to position
glTranslatef( gCameraX, gCameraY, gCameraZ );
//Save default matrix again with camera translation
glPushMatrix();
}
Main.cpp:
#include "LUtil.h"
void runMainLoop( int val );
void runGifLoop( int val2 );
int main( int argc, char* args[] )
{
glutInit( &argc, args );
glutInitContextVersion( 2, 1 );
glutInitDisplayMode( GLUT_DOUBLE );
glutInitWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );
glutCreateWindow( "Samus" );
if( !initGL() )
{
printf( "Unable to initialize graphics library!\n" );
return 1;
}
if( !loadMedia() )
{
printf( "Unable to load media!\n" );
return 2;
}
glutKeyboardFunc( handleKeys );
glutDisplayFunc( render );
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, 0 );
glutTimerFunc( 1000 / SCREEN_FPS, runGifLoop, 0 );
glutMainLoop();
return 0;
}
void runMainLoop( int val )
{
update();
render();
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, val );
}
void runGifLoop( int val2 )
{
loadGif();
glutTimerFunc( 1000 / SCREEN_FPS, runGifLoop, val2 );
}

How to animate my GIF tilesheet (OpenGL, DevIL, C++)

I'm trying to animate a gif in my window by making it scroll to each frame on my tilesheet but it currently stays on only one frame. I assume it's because I'm not limiting the fps on the gif but I have no clue how to do that. Anyone?
#max66 I'm trying to obtain an animation by doing this. I'm trying to make it go down the y axis on the texture(which is a sprite tile sheet) which works without the if statement so far but it freezes on the last frame.
My (newish) code:
#include "LUtil.h"
#include <IL/il.h>
#include <IL/ilu.h>
#include "LSpriteSheet.h"
int add = 0;
int zoom = 0;
int factor = 0;
int factor2 = 0;
float y = 0.f;
int scroll = 0;
GLfloat gCameraX = 0.f, gCameraY = 0.f, gCameraZ = 0.f;
//Sprite texture
LSpriteSheet gArrowSprites;
LSpriteSheet gSamusSprites;
bool initGL()
{
//Initialize GLEW
GLenum glewError = glewInit();
if( glewError != GLEW_OK )
{
printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
return false;
}
//Make sure OpenGL 2.1 is supported
if( !GLEW_VERSION_2_1 )
{
printf( "OpenGL 2.1 not supported!\n" );
return false;
}
//Set the viewport
glViewport( 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT );
//Initialize Projection Matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 5.0, -5.0 );
//Initialize Modelview Matrix
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPushMatrix();
//Initialize clear color
glClearColor( 0.f, 0.f, 0.f, 1.f );
//Enable texturing
glEnable( GL_TEXTURE_2D );
glEnable( GL_BLEND );
glDisable( GL_DEPTH_TEST );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
//Check for error
GLenum error = glGetError();
if( error != GL_NO_ERROR )
{
printf( "Error initializing OpenGL! %s\n", gluErrorString(error));
return false;
}
//Initialize DevIL
ilInit();
ilClearColour( 255, 255, 255, 000 );
//Check for error
ILenum ilError = ilGetError();
if( ilError != IL_NO_ERROR )
{
printf( "Error initializing DevIL! %s\n", iluErrorString(ilError) );
return false;
}
return true;
}
bool loadMedia()
{
//Load texture
if( !gArrowSprites.loadTextureFromFile( "SamusM.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
LFRect clip = { 0.f, 0.f, 330.f, 355.f };
//Top left
clip.x = 0.f;
clip.y = 0.f;
gArrowSprites.addClipSprite( clip );
//Top right
clip = {0.f, 0.f, 310.f, 480.f};
clip.x = 331.f;
clip.y = 0.f;
gArrowSprites.addClipSprite( clip );
clip = {0.f, 0.f, 330.f, 125.f};
//Bottom left
clip.x = 0.f;
clip.y = 355.f;
gArrowSprites.addClipSprite( clip );
clip = { 0.f, 0.f, 330.f, 355.f };
//Top left
clip.x = 0.f;
clip.y = 480.f;
gArrowSprites.addClipSprite( clip );
//Top right
clip = {0.f, 0.f, 310.f, 480.f};
clip.x = 331.f;
clip.y = 480.f;
gArrowSprites.addClipSprite( clip );
clip = {0.f, 0.f, 330.f, 125.f};
//Bottom left
clip.x = 0.f;
clip.y = 835.f;
gArrowSprites.addClipSprite( clip );
//Generate VBO
if( !gArrowSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
if( !gSamusSprites.loadTextureFromFile( "SamusG.png" ) )
{
printf( "Unable to load texture!\n" );
return false;
}
while(scroll != 40){
y += 214.f;
scroll++;
if(scroll == 40){
scroll = 0;
}
}
clip = {0.f, 0.f, 213.f, 214.f};
clip.x = 0.f;
clip.y = y;
gSamusSprites.addClipSprite( clip );
if( !gSamusSprites.generateDataBuffer() )
{
printf( "Unable to clip sprite sheet!\n" );
return false;
}
return true;
}
void update()
{
}
void render()
{
//Clear color buffer
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPushMatrix();
if(add == 0){
if(zoom < 101){
double const f_zoom = 1.0 + 0.1 * zoom;
glScaled(f_zoom, f_zoom, f_zoom);
}
if(zoom < -10){
double const f_zoom = 1.0 - 0.1 * zoom;
glScaled(f_zoom, f_zoom, f_zoom);
}
glTranslatef( -100.f, 178.f, 0.f );
gArrowSprites.renderSprite( 0 );
//Render top right arrow
glTranslatef( +100.f, -178.f, 0.f );
glTranslatef( 1240.f, 240.f, 0.f );
gArrowSprites.renderSprite( 1 );
//Render bottom left arrow
glTranslatef( -1240.f, +240.f, 0.f );
glTranslatef( 620.f, 500.f ,0.f );
gArrowSprites.renderSprite( 2 );
glTranslatef( -620.f, -500.f, 0.f );
glTranslatef( 620.f, 0.f , 0.f );
gSamusSprites.renderSprite( 0 );
}
if(add == 1){
if(zoom < 101){
double const f_zoom = 1.0 + 0.1 * zoom;
glScaled(f_zoom, f_zoom, f_zoom);
}
if(zoom < -10){
double const f_zoom = 1.0 - 0.1 * zoom;
glScaled(f_zoom, f_zoom, f_zoom);
}
glTranslatef( -100.f, 178.f, 0.f );
gArrowSprites.renderSprite( 3 );
glTranslatef( +100.f, -178.f, 0.f );
glTranslatef( 1240.f, 240.f, 0.f );
gArrowSprites.renderSprite( 4 );
glTranslatef( -1240.f, +240.f, 0.f );
glTranslatef( 620.f, 500.f ,0.f );
gArrowSprites.renderSprite( 5 );
}
glLoadIdentity();
glutSwapBuffers();
}
void handleKeys( unsigned char key, int x, int y )
{
//If the user presses q
if( key == 'q' && add == 0)
{
add++;
}
else if( key == 'q' && add == 1)
{
add--;
}
//Update the sprite rectangles so the texture change takes effect
if( key == 27 ) {
exit(0);
}
if(key == 'a') {
gCameraX += 8.f;
factor--;
factor2++;
}
else if (key == 'd') {
gCameraX -= 8.f;
factor++;
factor2--;
}
else if (key == 'w') {
gCameraY += 8.f;
}
else if (key == 's') {
gCameraY -= 8.f;
}
else if (key == '+' && zoom != 100) {
zoom += 1;
if(factor >= 19) {
gCameraX -= 64.f;
}
if(factor2 >= 33){
gCameraX += 16.f;
}
else{
gCameraX -= 64.f;
gCameraY -= 50.f;
}
}
else if (key == '-' && zoom != -9) {
zoom -= 1;
if(factor >= 19){
gCameraX += 64.f;
}
if(factor2 >= 33){
gCameraX -= 32.f;
}
else{
gCameraX += 64.f;
gCameraY += 50.f;
}
}
//Take saved matrix off the stack and reset it
glMatrixMode( GL_MODELVIEW );
glPopMatrix();
glLoadIdentity();
//Move camera to position
glTranslatef( gCameraX, gCameraY, gCameraZ );
//Save default matrix again with camera translation
glPushMatrix();
}
EDIT: I just tried adjusting the y coordinate value in the for loop and nothing was happening so I tried removing the if statement and still nothing. But if I adjust the y value at the top of my file the texture will change. So why isn't my loop adding to my y value?
I suppose it's because in your for
for(int scroll; scroll > 40; scroll++){
you declare the scroll variable but you don't initialize it.
So scroll start with an undefined value that can be greather than 40.
Solution (I suppose): initialize scroll.
p.s.: sorry for my bad English.
--- EDIT 2016.05.23 ---
Look at this code
while(scroll != 40){
y += 214.f;
scroll++;
if(scroll == 40){
scroll = 0;
}
}
clip = {0.f, 0.f, 213.f, 214.f};
clip.x = 0.f;
clip.y = y;
gSamusSprites.addClipSprite( clip );
If scrool reach the while with a value different from 40, the while never exit and you only increment (forever) y.
I suppose you intention was to call gSamusSprites.addClipSprite() (or a similar function) for every iteration of the while.
I suppose your intention was to iterate the cycle only 40 times and exit.
If my suppositions are correct, you can try something like [caution: not tested]
clip = {0.f, 0.f, 213.f, 214.f};
for (scroll = 0; scroll < 40; ++scroll, clip.y += 214.f )
gSamusSprites.addClipSprite( clip ); // or a different function?

Opengl macos fail

I have problem. I wrote the code on clear opengl and c++ without any libraries(glut, glew...) but it doesnt work.
Function displayCB display polygon with
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(-0.5f, -0.5f);
glVertex2f( 0.5f, -0.5f);
glVertex2f( 0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
and dont display two polygone with
glColor3f(1.0f, 0.0f, 0.0f);
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glVertex3f( 0.0f, 1.0f, 0.0f); // Top
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glEnd(); // Finished Drawing The Triangle
glTranslatef(3.0f,0.0f,0.0f); // Move Right 3 Units
glBegin(GL_QUADS); // Draw A Quad
glVertex3f(-1.0f, 1.0f, 0.0f); // Top Left
glVertex3f( 1.0f, 1.0f, 0.0f); // Top Right
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glEnd();
Can you help me?
COMPILE WITH: g++ -g -o opengl1 opengl1.cxx -lGLU -lGL -lX11
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/time.h>
#define GL_GLEXT_PROTOTYPES
#define GLX_GLXEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
struct MyWin
{
Display *display;
Window win;
bool displayed;
int width;
int height;
};
const int WIN_XPOS = 256;
const int WIN_YPOS = 64;
const int WIN_XRES = 600;
const int WIN_YRES = 600;
const int NUM_SAMPLES = 4;
MyWin Win;
double elapsedMsec( const struct timeval &start, const struct timeval &stop )
{
return ( ( stop.tv_sec - start.tv_sec ) * 1000.0 +
( stop.tv_usec - start.tv_usec ) / 1000.0 );
}
double elapsedUsec( const struct timeval &start, const struct timeval &stop )
{
return ( ( stop.tv_sec - start.tv_sec ) * 1000000.0 +
( stop.tv_usec - start.tv_usec ) );
}
/// check() - Check for GL errors, and report any queued
void check( const char hdr[] = "" )
{
int err;
while ( ( err = glGetError() ) != GL_NO_ERROR )
fprintf( stderr, "OpenGL Error at %s: %s\n", hdr, gluErrorString(err) );
}
void displayCB()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
//---------------------------------------------------
// FIXME: Insert GL draw code here
//---------------------------------------------------
glColor3f(1.0f, 0.0f, 0.0f);
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glVertex3f( 0.0f, 1.0f, 0.0f); // Top
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glEnd(); // Finished Drawing The Triangle
glTranslatef(3.0f,0.0f,0.0f); // Move Right 3 Units
glBegin(GL_QUADS); // Draw A Quad
glVertex3f(-1.0f, 1.0f, 0.0f); // Top Left
glVertex3f( 1.0f, 1.0f, 0.0f); // Top Right
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glEnd();
// glBegin(GL_POLYGON);
// glVertex2f(-0.5f, -0.5f);
// glVertex2f( 0.5f, -0.5f);
// glVertex2f( 0.5f, 0.5f);
// glVertex2f(-0.5f, 0.5f);
// glEnd();
// Display it
glXSwapBuffers( Win.display, Win.win );
check( "displayCB()" );
}
//----------------------------------------------------------------------------
void keyboardCB( KeySym sym, unsigned char key, int x, int y,
bool &setting_change )
{
switch ( tolower( key ) )
{
case 27:
// ESCape - We're done!
exit (0);
break;
case 'k':
printf( "You hit the 'k' key\n" );
break;
case 0:
switch ( sym )
{
case XK_Left :
printf( "You hit the Left Arrow key\n" );
break;
case XK_Right :
printf( "You hit the Right Arrow key\n" );
break;
}
break;
}
}
//----------------------------------------------------------------------------
void reshapeCB( int width, int height )
{
Win.width = width;
Win.height = height;
}
//----------------------------------------------------------------------------
XVisualInfo *chooseVisual( Display *display )
{
int attribs [ 100 ] ;
int n = 0 ;
// Request 24-bit color with alpha
attribs [n++] = GLX_RGBA ;
attribs [n++] = GLX_RED_SIZE ; attribs [n++] = 8 ;
attribs [n++] = GLX_GREEN_SIZE ; attribs [n++] = 8 ;
attribs [n++] = GLX_BLUE_SIZE ; attribs [n++] = 8 ;
// Request 24-bit depth buffer
attribs [n++] = GLX_DEPTH_SIZE ; attribs [n++] = 24 ;
// Request 4 multisamples per pixel
attribs [n++] = GLX_SAMPLE_BUFFERS ; attribs [n++] = 1 ;
attribs [n++] = GLX_SAMPLES ; attribs [n++] = NUM_SAMPLES ;
// Request double-buffering
attribs [n++] = GLX_DOUBLEBUFFER ;
attribs [n++] = None ;
return glXChooseVisual( display, DefaultScreen( display ), attribs );
}
//----------------------------------------------------------------------------
void createWindow()
{
// Init X and GLX
Win.displayed = false;
Display *display = Win.display = XOpenDisplay( ":0.0" );
if ( !display )
printf( "Cannot open X display\n" );
int screen = DefaultScreen( display );
Window root_win = RootWindow( display, screen );
if ( !glXQueryExtension( display, 0, 0 ) )
printf( "X Server doesn't support GLX extension\n" );
// Pick a visual
XVisualInfo *visinfo = chooseVisual( display );
if ( visinfo == 0 )
printf( "glXChooseVisual failed\n" );
// Describe the visual
printf( "Window Visual 0x%.2x\n", unsigned( visinfo->visualid ) );
// Create the X window
XSetWindowAttributes winAttr ;
winAttr.event_mask = StructureNotifyMask | KeyPressMask ;
winAttr.background_pixmap = None ;
winAttr.background_pixel = 0 ;
winAttr.border_pixel = 0 ;
winAttr.colormap = XCreateColormap( display, root_win,
visinfo->visual, AllocNone );
unsigned int mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
Window win = Win.win = XCreateWindow ( display, root_win,
WIN_XPOS, WIN_YPOS,
WIN_XRES, WIN_YRES, 0,
visinfo->depth, InputOutput,
visinfo->visual, mask, &winAttr ) ;
XStoreName( Win.display, win, "My GLX Window");
// Create an OpenGL context and attach it to our X window
GLXContext context = glXCreateContext( display, visinfo, NULL, 1 ) ;
if ( ! glXMakeCurrent( display, win, context ) )
printf( "glXMakeCurrent failed.\n" );
if ( ! glXIsDirect ( display, glXGetCurrentContext() ) )
printf( "Indirect GLX rendering context obtained\n" );
// Display the window
XMapWindow( display, win );
if ( ! glXMakeCurrent( display, win, context ) )
printf( "glXMakeCurrent failed.\n" );
check( "createWindow()" );
printf( "Window Size = %d x %d\n", WIN_XRES, WIN_YRES );
printf( "Window Samples = %d\n", NUM_SAMPLES );
}
//----------------------------------------------------------------------------
void processXEvents( Atom wm_protocols, Atom wm_delete_window )
{
bool setting_change = false;
while ( XEventsQueued( Win.display, QueuedAfterFlush ) )
{
XEvent event;
XNextEvent( Win.display, &event );
if( event.xany.window != Win.win )
continue;
switch ( event.type )
{
case MapNotify:
{
Win.displayed = true;
break;
}
case ConfigureNotify:
{
XConfigureEvent &cevent = event.xconfigure;
reshapeCB( cevent.width, cevent.height );
break;
}
case KeyPress:
{
char chr;
KeySym symbol;
XComposeStatus status;
XLookupString( &event.xkey, &chr, 1, &symbol, &status );
keyboardCB( symbol, chr, event.xkey.x, event.xkey.y,
setting_change );
break;
}
case ClientMessage:
{
if ( event.xclient.message_type == wm_protocols &&
Atom( event.xclient.data.l[0] ) == wm_delete_window )
{
//printf( "Received WM_DELETE_WINDOW\n" );
exit(0);
}
break;
}
}
}
}
//----------------------------------------------------------------------------
void mainLoop()
{
// Register to receive window close events (the "X" window manager button)
Atom wm_protocols = XInternAtom( Win.display, "WM_PROTOCOLS" , False);
Atom wm_delete_window = XInternAtom( Win.display, "WM_DELETE_WINDOW", False);
XSetWMProtocols( Win.display, Win.win, &wm_delete_window, True );
while (1)
{
// Redraw window (after it's mapped)
if ( Win.displayed )
displayCB();
// Update frame rate
static timeval last_xcheck = {0,0};
struct timeval now;
gettimeofday( &now, 0 );
// Check X events every 1/10 second
if ( elapsedMsec( last_xcheck, now ) > 100 )
{
processXEvents( wm_protocols, wm_delete_window );
last_xcheck = now;
}
}
}
//----------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
// Init globals
Win.width = WIN_XRES, Win.height = WIN_YRES;
// Create context and window
createWindow();
// Init OpenGL
glViewport ( 0, 0, Win.width, Win.height );
glColorMask ( 1,1,1,1 );
glClearColor( 0,0,1,1 );
glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// Go
printf( "Valid keys: Left, Right, k, ESC\n" );
printf( "Press ESC to quit\n" );
mainLoop();
return 0;
}
There are three problems here.
First: you haven't set up a GL viewport (e.g, using glFrustum() or gluPerspective()), so the perspective matrix isn't set up appropriately to do 3D graphics. As such, trying to draw a model in 3D won't work properly.
Second: The code that you've got here is written against the X11 windowing system, not Mac OS X. While it'll compile and sort-of-run on Mac OS, it will not run natively, nor will it perform particularly well. You will really want to use some interface which allows you to interface with the native Mac OS X GL implementation, such as SDL, GLUT/GLEW, or AGL.
(Keep in mind that there is no such thing as using GL "without libraries". OpenGL is itself a library, as is libX11; there's nothing at all wrong with using extra utility libraries to cut out some of the OS-specific setup and make your application easier to port.)
Third: You are currently learning how to use OpenGL immediate mode, which was used prior to OpenGL 3.0. Modern OpenGL — that is, OpenGL 3.0 or later, as well as OpenGL ES — uses a significantly different API which has very little in common with immediate mode. I'd strongly recommend that you skip immediate mode entirely; it's a dead technology at this point. There are a number of good tutorials out there for OpenGL 3+, including:
http://www.opengl-tutorial.org/
http://www.arcsynthesis.org/gltut/
https://open.gl/

opengl rubberbanded box not showing

I'm trying to draw a selection box over an image drawn using glDrawPixels, but I cannot get it to show. In order to represent the coordinates of the box, I have 4 global integers that I update on mouse actions (the first 2 on click, the others when the mouse is dragged), which I then use in the drawing function. I'm sure that the drawing function is called when the mouse gets dragged, and that the four values at least get updated, since I tried printing them every time the drawing function gets called.
The OpenGL calls I have in the main are:
glutInit(&argc, argv);
glutInitWindowSize(WINDOW_DIM, WINDOW_DIM);
glutInitWindowPosition(0, 0);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE);
glutCreateWindow("Window");
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glClearColor(0.0, 0.0, 0.0, 1.0);
glDisable(GL_DEPTH_TEST);
glutMainLoop();
and my display function:
void display()
{
printf("calling display\n");
for(unsigned int i=0; i<WINDOW_DIM*WINDOW_DIM; ++i)
{
pixels[i]=colors[img[i]];
}
glClear(GL_COLOR_BUFFER_BIT);
glDrawPixels(WINDOW_DIM, WINDOW_DIM, GL_RGB, GL_FLOAT, (float*)pixels);
glutSwapBuffers();
if(upd_xmin!=0 || upd_ymin!=0 || upd_xmax!=0 || upd_ymax!=0)
{
glDrawBuffer(GL_FRONT);
glLogicOp(GL_XOR);
glEnable(GL_COLOR_LOGIC_OP);
printf("drawing selection\n");
printf("coords %d %d %d %d\n", upd_xmin, upd_ymin, upd_xmax, upd_ymax);
glColor3f(1.0, 1.0, 1.0);
glLineWidth(3.0);
glBegin(GL_LINE_LOOP);
glVertex2i(upd_xmin, upd_ymin);
glVertex2i(upd_xmin, upd_ymax);
glVertex2i(upd_xmax, upd_ymax);
glVertex2i(upd_xmax, upd_ymin);
glEnd();
glDisable(GL_COLOR_LOGIC_OP);
glDrawBuffer(GL_BACK);
}
}
As I said, I don't think the problem is with the mouse and motion function, seeing how the coordinates of the box (the upd_x and upd_y variables in the code above) get updated when there's a mouse event, but if needed I can post those as well.
Don't swap the buffers in the middle. Just draw the selection box on the back-buffer like everything else:
#include <GL/glut.h>
int StartX = -1;
int StartY = -1;
int EndX = -1;
int EndY = -1;
void mouse( int button, int state, int x, int y )
{
if( button == GLUT_LEFT && state == GLUT_DOWN )
{
StartX = x;
StartY = y;
}
if( button == GLUT_LEFT && state == GLUT_UP )
{
StartX = -1;
StartY = -1;
EndX = -1;
EndY = -1;
}
}
void motion( int x, int y )
{
EndX = x;
EndY = y;
glutPostRedisplay();
}
void display()
{
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double ar = w / h;
glOrtho( -2 * ar, 2 * ar, -2, 2, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glBegin( GL_TRIANGLES );
glColor3ub( 255, 0, 0 );
glVertex2i( -1, -1 );
glColor3ub( 0, 255, 0 );
glVertex2i( 1, -1 );
glColor3ub( 0, 0, 255 );
glVertex2i( 0, 1 );
glEnd();
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0, w, h, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
if( StartX > 0 && StartY > 0 && EndX > 0 && EndY > 0 )
{
glLogicOp(GL_XOR);
glEnable(GL_COLOR_LOGIC_OP);
glColor3f(1.0, 1.0, 1.0);
glLineWidth(3.0);
glBegin(GL_LINE_LOOP);
glVertex2i(StartX, StartY);
glVertex2i(EndX, StartY);
glVertex2i(EndX, EndY);
glVertex2i(StartX, EndY);
glEnd();
glDisable(GL_COLOR_LOGIC_OP);
}
glutSwapBuffers();
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 640, 480 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutMouseFunc( mouse );
glutMotionFunc( motion );
glutMainLoop();
return 0;
}
Since you weren't specifying them I added projection and modelview matrices.
I believe the problem lies here:
glClear(GL_COLOR_BUFFER_BIT);
glDrawPixels(WINDOW_DIM, WINDOW_DIM, GL_RGB, GL_FLOAT, (float*)pixels);
glutSwapBuffers();
rest of drawing
Your render call should look like:
clear
render
swap buffers
Where render is all of your draw calls (including glDrawPixels).
Also, glDrawPixels was removed in OpenGL 3.2. Unless you absolutely need to use that particular method, why not use an orthographic projection to draw GUI elements (which the selection box can be though of as)?
Edit: Also, be aware that if you make draw calls after glDrawPixels, those may overwrite what you drew with glDrawPixels.