Rectangular Texture

Notes:

Load a rectangular texture and, more importantly, create an orthographic view to render it to.

Vertex Shader:

#version 330 core
 
// Incoming per vertex... position and texture coord
in vec4 vVertex;
in vec2 vTexCoord;

uniform mat4	mvpMatrix;

smooth out vec2 vVaryingTexCoord;

void main(void) 
{ 
    // Pass on the texture coordinates
    vVaryingTexCoord = vTexCoord;

    // Transform the geometry
    gl_Position = mvpMatrix * vVertex;
}

Fragment Shader:

#version 330 core

out vec4 vFragColor;

uniform sampler2DRect rectangleImage; 

smooth in vec2 vVaryingTexCoord;

void main(void)
{ 
    vFragColor = texture(rectangleImage,vVaryingTexCoord); 
}

Source:

// RexTex.cpp
//
// Loading a rectangular texture

#include <GLTools.h>	// OpenGL toolkit
#include <GLShaderManager.h>
#include <GLFrustum.h>
#include <GLBatch.h>
#include <GLMatrixStack.h>
#include <GLGeometryTransform.h>
#include <math.h>

#include <stdio.h>
#include <GL/glew.h>    // glew likes to be before other GL stuff
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <GL/glu.h>

// OGLSB5 variables
GLShaderManager         shaderManager;
GLMatrixStack           modelViewMatrix;
GLMatrixStack           projectionMatrix;
GLFrustum               viewFrustum;
GLGeometryTransform     transformPipeline;
GLFrame                 cameraFrame;

GLTriangleBatch         torusBatch;
GLBatch                 logoBatch;

GLuint                  uiTextures[2];
GLuint                  rectReplaceShader;
GLint                   locRectMVP;
GLint                   locRectTexture;

//Screen dimension constants
//const int SCREEN_WIDTH = 256;
//const int SCREEN_HEIGHT = 256;
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

//Starts up SDL, creates window, and initializes OpenGL
bool init();

//Initializes rendering program and clear color
bool initGL();

//Input handler
int handleKeys(unsigned char key, int x, int y);

//Per frame update
void update();

//Frees media and shuts down SDL
void close();

bool LoadTGATextureRect(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
    GLbyte *pBits;
    int nWidth, nHeight, nComponents;
    GLenum eFormat;

    // Read the texture bits
    pBits = gltReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat);
    if (pBits == NULL)
    {
        return false;
    }
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, wrapMode);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, wrapMode);

    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, minFilter);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, magFilter);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_RECTANGLE, 0, nComponents, nWidth, nHeight, 0, eFormat, GL_UNSIGNED_BYTE, pBits);

    free(pBits);

    return true;
}

void DrawTorus()
{
    // Set polugon mode
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    modelViewMatrix.PushMatrix();
    modelViewMatrix.Translate( 0.0f, 0.0f,-4.0f);
    modelViewMatrix.PushMatrix();

    //glDisable(GL_BLEND);
    glDisable(GL_POLYGON_STIPPLE);
    glEnable(GL_DEPTH_TEST);

    modelViewMatrix.Rotate(SDL_GetTicks() * 0.2f, 0.0f, 1.0f, 0.0f); // modified for SDL

    static GLfloat vTorusColor[] = { 1.0f, 0.0f, 0.0f, 1.0f };
    shaderManager.UseStockShader(GLT_SHADER_FLAT, transformPipeline.GetModelViewProjectionMatrix(), vTorusColor);

    torusBatch.Draw();

    modelViewMatrix.PopMatrix();
    modelViewMatrix.PopMatrix();
}

void DrawLogo()
{
    // Set polygon mode
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    // Prepare orthographic matrix
    M3DMatrix44f mScreenSpace;
    m3dMakeOrthographicMatrix(mScreenSpace, 0.0f, 800, 0.0f, 600, -1.0f, 1.0f);

    // Turn on blending and depth testing off
    glEnable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);

    // blend
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glUseProgram(rectReplaceShader);
    glUniform1i(locRectTexture, 0);
    glUniformMatrix4fv(locRectMVP, 1, GL_FALSE, mScreenSpace);
    glBindTexture(GL_TEXTURE_RECTANGLE, uiTextures[1]);

    logoBatch.Draw();
}

void render()
{
    //Clear color buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Prepare the Camera
    modelViewMatrix.PushMatrix();
    M3DMatrix44f mCamera;
    modelViewMatrix.GetMatrix(mCamera);
    modelViewMatrix.MultMatrix(mCamera);

    DrawTorus();

    DrawLogo();

    modelViewMatrix.PopMatrix();
}

//The window we'll be rendering to
SDL_Window* gWindow = NULL;

//OpenGL context
SDL_GLContext gContext;

bool init()
{
	//Initialization flag
	bool success = true;

	//Initialize SDL
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
		success = false;
	}
	else
	{
		//Use OpenGL 3.3 core
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

		//Create window
		gWindow = SDL_CreateWindow("Texture Rectangle", 
                                    SDL_WINDOWPOS_UNDEFINED, 
                                    SDL_WINDOWPOS_UNDEFINED, 
                                    SCREEN_WIDTH, 
                                    SCREEN_HEIGHT, 
                                    SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
		if(gWindow == NULL)
		{
			printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
			success = false;
		}
		else
		{
			//Create context
			gContext = SDL_GL_CreateContext(gWindow);
			if(gContext == NULL)
			{
				printf("OpenGL context could not be created! SDL Error: %s\n", SDL_GetError());
				success = false;
			}
			else
			{
				//Initialize GLEW
				glewExperimental = GL_TRUE; 
				GLenum glewError = glewInit();
				if(glewError != GLEW_OK)
				{
					printf("Error initializing GLEW! %s\n", glewGetErrorString(glewError));
				}

				//Use Vsync
				if(SDL_GL_SetSwapInterval(1) < 0)
				{
					printf("Warning: Unable to set VSync! SDL Error: %s\n", SDL_GetError());
				}

				//Initialize OpenGL
				if(!initGL())
				{
					printf("Unable to initialize OpenGL!\n");
					success = false;
				}
			}
		}
	}

	return success;
}

bool initGL()
{
    //Success flag
    bool success = true;

    // Initialize the shader manger
    shaderManager.InitializeStockShaders();

    // Enable depth testing
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    // Set the object forward
    //viewFrame.MoveForward(4.0f);

    //Initialize clear color (background)
    glClearColor(0.2f, 0.2f, 0.2f, 1.0f);

    // Make the Torus
    gltMakeTorus(torusBatch, 0.8f, 0.25f, 52, 26);

    // Make logo square
    int x = 500;
    int y = 155;
    int width = 300;
    int height = 155;
    logoBatch.Begin(GL_TRIANGLE_FAN, 4, 1);

    // Upper left corner
    logoBatch.MultiTexCoord2f(0, 0.0f, height);
    logoBatch.Vertex3f(x, y, 0.0f);

    // Lower left corner
    logoBatch.MultiTexCoord2f(0, 0.0f, 0.0f);
    logoBatch.Vertex3f(x, y - height, 0.0f);

    // Lower right corner
    logoBatch.MultiTexCoord2f(0, width, 0.0f);
    logoBatch.Vertex3f(x + width, y - height, 0.0f);

    // Upper right corner
    logoBatch.MultiTexCoord2f(0, width, height);
    logoBatch.Vertex3f(x + width, y, 0.0f);

    logoBatch.End();

    // Make 2 texture objects
    glGenTextures(2, uiTextures);

    // Load 4 texture objects
    glBindTexture(GL_TEXTURE_2D, uiTextures[0]);
    LoadTGATextureRect("Clouds.tga", GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_RECTANGLE, uiTextures[1]);
    LoadTGATextureRect("OpenGL-Logo.tga", GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE);

	//Generate program
    rectReplaceShader = gltLoadShaderPairWithAttributes("glsl.vs", 
                                                       "glsl.fs", 
                                                       2, 
                                                       GLT_ATTRIBUTE_VERTEX, 
                                                       "vVertex",
                                                       GLT_ATTRIBUTE_TEXTURE0,
                                                       "vTexCoord");

    locRectMVP          =   glGetUniformLocation(rectReplaceShader, "mvpMatrix");
    locRectTexture      =   glGetUniformLocation(rectReplaceShader, "rectangleImage");


    viewFrustum.SetPerspective(35.0f, float(SCREEN_WIDTH) / float(SCREEN_HEIGHT), 1.0f, 100.0f);
    projectionMatrix.LoadMatrix(viewFrustum.GetProjectionMatrix());
    transformPipeline.SetMatrixStacks(modelViewMatrix, projectionMatrix);

    return success;
}

int handleKeys(unsigned char key, int x, int y)
{
	//Toggle triangle
	if(key == 'q')
	{
        return 1;
	}
    
	return 0;
}

void update()
{
	//No per frame update needed
}

void close()
{
	// clear textures
	glDeleteTextures(2, uiTextures);

	//Deallocate program
	glDeleteProgram(rectReplaceShader);

	//Destroy window	
	SDL_DestroyWindow(gWindow);
	gWindow = NULL;

	//Quit SDL subsystems
	SDL_Quit();
}

int main(int argc, char* args[])
{
	//Start up SDL and create window
	if(!init())
	{
		printf("Failed to initialize!\n");
	}
	else
	{
		//Main loop flag
		bool quit = false;

        // Time variables
        unsigned int lastTime = 0, currentTime = 0;

		//Event handler
		SDL_Event e;
		
		//Enable text input
		SDL_StartTextInput();

		//While application is running
		while(!quit)
		{
			//Handle events on queue
			while(SDL_PollEvent(&e) != 0)
			{
				//User requests quit
				if(e.type == SDL_QUIT)
				{
					quit = true;
				}
				//Handle keypress with current mouse position
				else if(e.type == SDL_TEXTINPUT)
				{
					int x = 0, y = 0;
					SDL_GetMouseState(&x, &y);
					if (handleKeys(e.text.text[0], x, y))
					{
					    quit = true;
					}
				}
			}

			//Render
			render();
			
			//Update screen
			SDL_GL_SwapWindow(gWindow);
		}
		
		//Disable text input
		SDL_StopTextInput();
	}

	//Free resources and close SDL
	close();

	return 0;
}

Answer:


Back to index