Sign in to follow this  

OpenGL texture isn't working. ( first time ogl )

Recommended Posts

Hello guys! I am not doing fanzy 3d stuff.. I am trying to draw a simple quad with a texture using SDL + OpenGl! The problem is that my quad is white.. but I should have the texture on it! uh? :| I don't get error messages when I load the SDL_Surface! Thank you very much! :) Here is the source code: main.cpp

#include "game_header.hpp"

#ifdef _WIN32
#undef main

LogFile LOG("logfile.log");

int main(int argc, char **argv)
	SDL_Surface *screen;
	bool running(true);

        init_SDL_OGL( screen, 640, 480 );
	GL_Texture* texture = new GL_Texture( "galaxien.bmp" );
	Quad quad( texture );
	SDL_Event event;
	while( running == true )

    			case SDL_KEYDOWN:
                    				running = false;
    			case SDL_QUIT:
                    				running = false;
        quad.draw( 300, 300 );

        delete texture;
        return 0;

#include "eng_header.hpp"

#include <SDL.h>
#include <SDL_opengl.h>

#include "eng_logfile.hpp"
#include "eng_init.hpp"
#include "eng_texture.hpp"
#include "eng_quad.hpp"

#ifndef __ENG_INIT_HPP__
#define __ENG_INIT_HPP__

bool init_SDL_OGL( SDL_Surface* screen, const int w, const int h );


#include "eng_header.hpp"

bool init_SDL_OGL( SDL_Surface* screen, const int w, const int h )
    // SDL:
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
		LOG << "Could not init SDL" << ENDL;
		exit( 1 );
	atexit( SDL_Quit );

	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);

	screen = SDL_SetVideoMode( w, h, 0, SDL_OPENGL);
	if ( !screen )
		LOG << "Couldn't set video mode!" << ENDL;
    // OGL:
    glViewport(0, 0, screen->w, screen->h);

	glMatrixMode( GL_PROJECTION );
	glOrtho(0, screen->w, screen->h, 0, -1.0, 1.0);

	glMatrixMode( GL_MODELVIEW );
    return true;   


#ifndef __ENG_TEXTURE_HPP__
#define __ENG_TEXTURE_HPP__

class GL_Texture
              GL_Texture( void );
              GL_Texture( const char* filename );
              ~GL_Texture( void );
              bool init( const char* filename );
              bool initTexture( void );
              int getW( void ) const{ return w; }
              int getH( void ) const{ return h; }
              unsigned getTexture( void ) const{ return texture; }
              SDL_Surface*  sprite;
              unsigned      texture;
              int w, h;

#include "eng_header.hpp"

GL_Texture::GL_Texture( void )
 :w(0), h(0), sprite( NULL )

GL_Texture::GL_Texture( const char* filename )
 :w(0), h(0), sprite( NULL )
    init( filename );

// inits the SDl-surface
bool GL_Texture::init( const char* filename )
    if( sprite != NULL )
		  SDL_FreeSurface( sprite );
		  sprite = NULL;
    // Load the BMP file into a surface
	sprite = SDL_LoadBMP( filename );

    if ( sprite == NULL )
	    LOG << "Couldn't load " << filename << " -- "  << ENDL; 
        return false;
    if( SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB(sprite->format, 255, 0, 255)) < 0)
	    LOG << "Couldn't set the ColorKey for " << filename << " -- "  << ENDL;
		return false;

	w = sprite->w;
	h = sprite->h;
	return true;       

bool GL_Texture::initTexture( void )
    SDL_Surface*  conv;
    // convert to 32-bit RGBA format
  	conv = SDL_CreateRGBSurface( SDL_SWSURFACE, sprite->w, sprite->h, 32,
	   0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
       0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
    SDL_BlitSurface( sprite, 0, conv, 0);
    glGenTextures( 1, &texture );
	glBindTexture( GL_TEXTURE_2D, texture );
    glPixelStorei( GL_UNPACK_ROW_LENGTH, conv->pitch / conv->format->BytesPerPixel );
	glTexImage2D( GL_TEXTURE_2D, 0, 3, conv->w, conv->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, conv->pixels);
	glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );


GL_Texture::~GL_Texture( void )
    if( sprite )
		 SDL_FreeSurface( sprite );
		 sprite = NULL;


#ifndef __ENG_QUAD_HPP__
#define __ENG_QUAD_HPP__

class Quad
             Quad( GL_Texture* const texture ); 
             void draw( const int x, const int y );
             GL_Texture* texture;


#include "eng_header.hpp"

Quad::Quad( GL_Texture* const texture2 )
 :texture( texture2 )

void Quad::draw( const int x, const int y )
    glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, texture->getTexture() );
    // Don't use texture-w / h later
    const int t_w = texture->getW();
    const int t_h = texture->getH();
    glBegin( GL_QUADS );
		glTexCoord2f( 0, 0 );	glVertex2i( x, y );              // x -- y
		glTexCoord2f( 1, 0 );	glVertex2i( x + t_w, y );        // x+w -- y         
  		glTexCoord2f( 1, 1 );	glVertex2i( x + t_w, y + t_h );  // x+w -- y+h
		glTexCoord2f( 0, 1 );	glVertex2i( x, y + t_h );        // x -- y+h  

[Edited by - rakoon2 on September 3, 2004 8:25:12 PM]

Share this post

Link to post
Share on other sites
I don't remember using SDL's built-in bmp loader to load textures. Its probably possible, but you should try a NEHE tutorial and use the GLAUX library first and setup a texture that way. SDL's bitmap loader might not have the data the way OpenGL needs it? Don't quote me on this, just an idea to help troubleshoot.

Share this post

Link to post
Share on other sites
Original post by DerAnged
i dont see a glEnable(GL_TEXTURE_2D); annywhere in there.

its in the quad.cpp file in the Draw(). You should really put a glDisable(GL_TEXTURE_2D); at the end if you are done texturing to avoid issues...

Share this post

Link to post
Share on other sites
Ah! That's it! Thank you! :)

One more question:

How can I let all quads rotate? ( they should rotate around their own center. )

I tried the rotate function.. but then my quads were gone after a sec!

I am using the same function as in the nehe tutorial.
Maybe I must use a different function?! ( ortho mode )


glBegin( GL_QUADS );
glTexCoord2f( 0, 0 ); glVertex2i( x, y ); // x -- y
glTexCoord2f( 1, 0 ); glVertex2i( x, y + t_h ); // x -- y + h
glTexCoord2f( 1, 1 ); glVertex2i( x + t_w, y + t_h ); // x+w -- y+h
glTexCoord2f( 0, 1 ); glVertex2i( x + t_w, y ); // x+w-- y

is this right to make a quad? my quad is not w * h why? :|

[Edited by - rakoon2 on September 4, 2004 3:02:12 AM]

Share this post

Link to post
Share on other sites
its probably because you dont specify things in pixels, its some arbitrary unit, 1 is actually decently sized, but make sure you translate it back say, 10, thats what i always do for my little demos, in case you dont know transformations yet

glTranslatef(0.0f, 0.0f, -10.0f);
//do your rendering

ok wow, i must be tired, im not confident i have the constant for glMatrixMode() right, im pretty sure, but not 100%, i think that means its bed time, but anywho, hope that helps

Share this post

Link to post
Share on other sites
glRotate rotates about the origin, so if you want to rotate the quad about it's center, you have to move it's center to the origin.

Since the quad extends from [x, y] to [x+w, y+h], the center is located at [x+w/2, y+h/2]. So first translate the center to the origin, rotate, and translate back. Something like this.

glTranslate(x+w/2, y+h/2, 0);
glTranslate(-x-w/2, -y-h/2, 0);

Share this post

Link to post
Share on other sites
Thank you! Thank you that works fine if I use single quads! :)

But what about if I want to rotate the full scene?

Here a screenshot what I mean:

Is it possible to do that without those black "holes"?
What must I rotate the quads about? window_w/2 - window_h/2 ? hmm..

how about:
glTranslatef( window_w/2, window_h/2, 0);
glRotatef( angle, 0.0f, 0.0f, 1.0f);
glTranslatef( - window_w/2, -window_h/2, 0);

Thank you again ^^

[Edited by - rakoon2 on September 4, 2004 5:03:08 AM]

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
    • By Abecederia
      So I've recently started learning some GLSL and now I'm toying with a POM shader. I'm trying to optimize it and notice that it starts having issues at high texture sizes, especially with self-shadowing.
      Now I know POM is expensive either way, but would pulling the heightmap out of the normalmap alpha channel and in it's own 8bit texture make doing all those dozens of texture fetches more cheap? Or is everything in the cache aligned to 32bit anyway? I haven't implemented texture compression yet, I think that would help? But regardless, should there be a performance boost from decoupling the heightmap? I could also keep it in a lower resolution than the normalmap if that would improve performance.
      Any help is much appreciated, please keep in mind I'm somewhat of a newbie. Thanks!
  • Popular Now