Home > Software design >  Why is my texture getting rotated by 90 degrees?
Why is my texture getting rotated by 90 degrees?

Time:10-25

I am trying to draw a simple quad with a texture. I am using gluOrtho2d to set up an orthographic projection. I am unable to understand why the texture inside the quad is getting rotated 90° clockwise. The texture is a simple PNG file.

This is the problematic code :-

#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <SFML/Graphics.hpp>
#include <iostream>


using namespace std;


const int WINDOW_WIDTH = 800, WINDOW_HEIGHT = 600;
sf::Texture texture;


void draw() {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    float x = 0;
    float y = 0;

    sf::Texture::bind(&texture);

    glBegin(GL_QUADS);
    glVertex2f(x, y);
    glTexCoord2f(0, 0);
    glVertex2f(x   400, y);
    glTexCoord2f(1, 0);
    glVertex2f(x   400, y   400);
    glTexCoord2f(1, 1);
    glVertex2f(x, y   400);
    glTexCoord2f(0, 1);
    glEnd();
}


int main() {
    sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "problem");
    window.setActive(true);


    texture.loadFromFile("texture.png");

    glewInit();
    glEnable(GL_TEXTURE_2D);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    gluOrtho2D(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT);
    glMatrixMode(GL_MODELVIEW);

    bool isRunning = true;
    while(isRunning) {
        sf::Event event;
        while(window.pollEvent(event)) {
            if(event.type == sf::Event::Closed) {
                isRunning = false;
            }
        }
        draw();
        window.display();
    }
}

This is the output. Here you can see the texture is rotated by 90°

enter image description here

CodePudding user response:

glVertex*() calls "lock in" the current color/texture-coordinates/position for a vertex and hand off those values to the GL driver:

glVertex commands are used within glBegin/glEnd pairs to specify point, line, and polygon vertices. The current color, normal, texture coordinates, and fog coordinate are associated with the vertex when glVertex is called.

The way you have it now:

glVertex2f(x, y);
glTexCoord2f(0, 0);

...that first glVertex() call is re-using the most recently set texture coordinates, those from the previous frame: glTexCoord2f(0, 1)

So you need to set texture coordinates for a vertex before the position.

glTexCoord2f(0, 0);
glVertex2f(x, y);
glTexCoord2f(1, 0);
glVertex2f(x   400, y);
glTexCoord2f(1, 1);
glVertex2f(x   400, y   400);
glTexCoord2f(0, 1);
glVertex2f(x, y   400);
  • Related