• Advertisement
Sign in to follow this  

OpenGL please help with simple code to display textured quad?

This topic is 3931 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I'm trying to draw a 2D textured quad (the size of the screen) using opengl. I'm filling the texture with RED pixes, but it always draws in BLACK (no matter what value I set the "colour" variable to). If anyone can see the mistake(s) I'm making please help - I've been pulling my hair out over this! Thanks jimbogd
#include <iostream>
#ifdef WIN32
#include <windows.h>
#endif
#include <sdl/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>

#define		GL_CLAMP_TO_EDGE		0x812F
#define		SCREEN_WIDTH			640
#define		SCREEN_HEIGHT			480

unsigned int rgba_to_int(unsigned char r, unsigned char g, unsigned char b, unsigned char a);

int main(int nArgs, char** args)
{
	// init sdl video with opengl
	SDL_Init( SDL_INIT_VIDEO );
	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 0 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
	SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 0, SDL_OPENGL );

	// setup opengl context
	glViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	glOrtho( 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1 );
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();
	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
	glEnable( GL_TEXTURE_2D );
	glEnable( GL_BLEND );
	glDisable( GL_DEPTH_TEST );
	glDisable( GL_CULL_FACE );

	// build the texture data in memory
	unsigned int	colour		= rgba_to_int(255, 0, 0, 0);
	unsigned int	tex_width	= 1024;
	unsigned int	tex_height	= 512;
	unsigned int	data_size	= tex_width * tex_height * 4;
	unsigned char *	data		= new unsigned char[sizeof( unsigned char ) * data_size];
	std::fill( reinterpret_cast<unsigned int *>( data ), reinterpret_cast<unsigned int *>( data + data_size ), colour );

	// generate a texture for it, bind the data and set the texture attributes
	unsigned int texture_id;
	glGenTextures( 1, &texture_id );
	glBindTexture( GL_TEXTURE_2D, texture_id );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height , 0, GL_RGBA, GL_UNSIGNED_BYTE, data );

	// main loop
	SDL_Event e;
	bool is_running = true;
	while(is_running)
	{
		// check for quit event
		SDL_PollEvent(&e);
		if(e.type == SDL_QUIT)
			is_running = false;

		// draw the texture to the back buffer

		// texture coordinates
		double tx1 = 0.0f;
		double tx2 = static_cast<double>( SCREEN_WIDTH ) / static_cast<double>( tex_width );
		double ty1 = 0.0f / static_cast<double>( tex_height );
		double ty2 = static_cast<double>( SCREEN_HEIGHT ) / static_cast<double>( tex_height );
	
		// vertex coordinates
		double x1 = 0.0f;
		double x2 = static_cast<double>( SCREEN_WIDTH );
		double y1 = 0.0f;
		double y2 = static_cast<double>( SCREEN_HEIGHT );
	
		// draw the textured quad (clockwise winding)
		glBegin(GL_QUADS);
			glTexCoord2d( tx1, ty1 ); glVertex2d( x1, y1 );
			glTexCoord2d( tx2, ty1 ); glVertex2d( x2, y1 );
			glTexCoord2d( tx2, ty2 ); glVertex2d( x2, y2 );
			glTexCoord2d( tx1, ty2 ); glVertex2d( x1, y2 );
		glEnd();

		// update the screen
		SDL_GL_SwapBuffers();
	}

	// clean up
	glDeleteTextures( 1, &texture_id );
	delete [] data;
	SDL_Quit();
	return 0;
}

unsigned int rgba_to_int(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
	unsigned int col;
	unsigned char *byte_ptr = reinterpret_cast<unsigned char *>( &col );
	byte_ptr[0] = r;
	byte_ptr[1] = g;
	byte_ptr[2] = b;
	byte_ptr[3] = a;
	return col;
}

Share this post


Link to post
Share on other sites
Advertisement
Its been a while since 3D but, maybe some help...

// vertex coordinates
double x1 = 0.0f;
double x2 = static_cast<double>( SCREEN_WIDTH );
double y1 = 0.0f;
double y2 = static_cast<double>( SCREEN_HEIGHT );

Your using the SCREEN_WIDTH and SCREEN_HEIGHT as max dimensions, but as with a default view, the screen coordinates go from -1.0f to 1.0f.

With texturing, min and max values go from 0.0f to 1.0f (without wrapping, tiling, etc)

If your wanting to use screen coordinates, I know DirectX uses RHW as a Vertex Definition. not sure how OpenGL rolls.

Hope this helps..


Edit, well, after re-re-reading your post (sorry, bit tired, just got off work) this actually might not be your problem. But I know Nehe has a tutorial on Ortho...

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=21

Share this post


Link to post
Share on other sites
Use of screen coordinates has already been enabled with the glOrtho() command. The problem is that you have colour = rgba_to_int(255, 0, 0, 0). You have blending enabled and you are giving an alpha value of zero to the vertices so they are transparent. Change the colour variable to rgba_to_int(255, 0, 0, 255). That will make the vertices opaque and they'll show up on the screen. :D

Share this post


Link to post
Share on other sites
Some aesthetic pointers:

unsigned char *	data		= new unsigned char[sizeof( unsigned char ) * data_size];


The sizeof operator is redundant, since the new operator allocates per "unsigned char".

double ty1 = 0.0f / static_cast<double>( tex_height );


will always yield 0.0 (or a division by zero).

EDIT: what Jakenaattori said :-)

Share this post


Link to post
Share on other sites
Hi

Aaah the alpha value, of course!!! (/me feels dumb)

Thanks for your help,

jimbogd

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By LifeArtist
      Good Evening,
      I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
      First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
      I am really stucked right now because of the fundamental question:
      Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
      If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on. 
      In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
      Should I treat those debug objects as entities/components?
      For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
      Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
      Regards,
      LifeArtist
    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
  • Advertisement