Sign in to follow this  
Gumgo

OpenGL Garbled textures with Cg

Recommended Posts

I've been having this issue for a while. At first I thought it was my graphics card, but it's also happening on my new computer which has a Radeon HD 5830 graphics card. What's happening is this. When I try to draw something with a Cg shader, the texture coordinates flicker and change randomly on the object. I've never seen this happen in any Cg apps except for my own, so I'm probably doing something wrong. Here is a video of what is happening. It happens with this simple program:
#include <windows.h>
#include <string>
#include <gl\GLee.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include <cg\cg.h>
#include <cg\cggl.h>

#pragma comment( lib, "GLee.lib" ) // library for GL easy extensions
#pragma comment( lib, "opengl32.lib" ) // library for OpenGL
#pragma comment( lib, "glu32.lib" ) // library for OpenGL Utility Library
#pragma comment( lib, "cg.lib" ) // library for Cg functions
#pragma comment( lib, "cggl.lib" ) // library for Cg with OpenGL functions
#pragma comment( lib, "winmm.lib" ) // library for timing functions

class Window {
	HGLRC hRC;
	HDC hDC;
	HWND hWnd;
	HINSTANCE hInstance;

	bool quit;

	int width;
	int height;
	int numbofbits;
	std::string title;

public:
	friend LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );

	Window() {
		hRC = NULL;
		hDC = NULL;
		hWnd = NULL;
		quit = false;
		width = 0;
		height = 0;
		numbofbits = 0;
		title = "";
	}

	~Window() {
		killWindow();
	}

	bool makeWindow( const std::string & text, int w, int h, int bits ) {
		UINT PixelFormat;
		WNDCLASS wc;
		DWORD dwExStyle, dwStyle;

		width = w;
		height = h;
		numbofbits = bits;
		title = text;

		RECT WindowRect;
		WindowRect.left = (long)0;
		WindowRect.right = (long)w;
		WindowRect.top = (long)0;
		WindowRect.bottom = (long)h;

		hInstance = GetModuleHandle( NULL );
		wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
		wc.lpfnWndProc = (WNDPROC)WndProc;
		wc.cbClsExtra = 0;
		wc.cbWndExtra = 0;
		wc.hInstance = hInstance;
		wc.hIcon = LoadIcon( NULL, IDI_WINLOGO );
		wc.hCursor = LoadCursor( NULL, IDC_ARROW );
		wc.hbrBackground = NULL;
		wc.lpszMenuName = NULL;
		wc.lpszClassName = "OpenGL";

		if (!RegisterClass( &wc ))
			return false;

		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;

		AdjustWindowRectEx( &WindowRect, dwStyle, false, dwExStyle );

		if (!(hWnd = CreateWindowEx( dwExStyle,
									 "OpenGL",
									 title.c_str(),
									 WS_CLIPSIBLINGS | WS_CLIPCHILDREN | dwStyle,
									 0, // x
									 0, // y
									 WindowRect.right - WindowRect.left,
									 WindowRect.bottom - WindowRect.top,
									 NULL,
									 NULL,
									 hInstance,
									 NULL ))) {
			killWindow();
			return false;
		}

		RECT WinPos;
		ULONG NewX, NewY, NewW, NewH, ScreenWidth, ScreenHeight;
		GetWindowRect( hWnd, &WinPos );
		ScreenWidth = GetSystemMetrics( SM_CXSCREEN );
		ScreenHeight = GetSystemMetrics( SM_CYSCREEN );
		NewX = ScreenWidth/2 - (WinPos.right - WinPos.left)/2;
		NewY = ScreenHeight/2 - (WinPos.bottom - WinPos.top)/2;
		NewW = WinPos.right - WinPos.left;
		NewH = WinPos.bottom - WinPos.top;
		MoveWindow( hWnd, NewX, NewY, NewW, NewH, true );

		static PIXELFORMATDESCRIPTOR pfd = {
			sizeof( PIXELFORMATDESCRIPTOR ),
			1,
			PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
			PFD_TYPE_RGBA,
			bits,
			0, 0, 0, 0, 0, 0,
			0,
			0,
			0,
			0, 0, 0, 0,
			16,
			0,
			0,
			PFD_MAIN_PLANE,
			0,
			0, 0, 0
		};

		if (!(hDC = GetDC( hWnd ))) {
			killWindow();
			return false;
		}

		if (!(PixelFormat = ChoosePixelFormat( hDC, &pfd ))) {
			killWindow();
			return false;
		}

		if (!SetPixelFormat( hDC, PixelFormat, &pfd )) {
			killWindow();
			return false;
		}

		if (!(hRC = wglCreateContext( hDC ))) {
			killWindow();
			return false;
		}

		if (!wglMakeCurrent( hDC, hRC )) {
			killWindow();
			return false;
		}

		SetWindowLongPtr( hWnd, GWLP_USERDATA, (long)this );
		ShowWindow( hWnd, SW_SHOW );
		SetForegroundWindow( hWnd );
		SetFocus( hWnd );

		glViewport( 0, 0, w, h );
		return true;
	}

	void killWindow() {
		if (hRC) {
			wglMakeCurrent( NULL, NULL );
			wglDeleteContext( hRC );
			hRC = NULL;
		}

		DestroyWindow( hWnd );
		hWnd = NULL;

		UnregisterClass( "OpenGL", hInstance );
		hInstance = NULL;
	}

	bool getQuit() {
		return quit;
	}

	void update() {
		MSG msg;
		while (PeekMessage( &msg, NULL, 0, 0, PM_REMOVE )) {
			if (msg.message == WM_QUIT)
				quit = true;
			else {
				TranslateMessage( &msg );
				DispatchMessage( &msg );
			}
		}
	}

	void updateDisplay() {
		SwapBuffers( hDC );
	}
};

LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) {
	Window * win = (Window*)GetWindowLongPtr( hWnd, GWLP_USERDATA );
	switch ( uMsg ) {
	case WM_SYSCOMMAND:
		switch (wParam) {
		case SC_SCREENSAVE:
		case SC_MONITORPOWER:
			return 0;
		}
		break;
	case WM_CLOSE:
		PostQuitMessage( 0 );
		return 0;
	case WM_SIZE:
		return 0;
	}
	return DefWindowProc( hWnd, uMsg, wParam, lParam );
}

int main( int argc, char ** argv ) {
	Window * win = new Window();
	win->makeWindow( "test", 640, 480, 16 );

	CGcontext cgContext;
	CGprofile cgVertexProfile;
	CGprogram program;
	CGparameter position;
	CGparameter texCoord;
	CGparameter color;
	CGparameter modelViewMatrix;

	cgContext = cgCreateContext(); // create a cg context
	cgVertexProfile = cgGLGetLatestProfile( CG_GL_VERTEX ); // get the vertex profile
	cgGLSetOptimalOptions( cgVertexProfile );

	program = cgCreateProgramFromFile( cgContext, CG_SOURCE, "./Mesh.cg", cgVertexProfile, "main", NULL );
	cgGLLoadProgram( program );
	position        = cgGetNamedParameter( program, "vtxIn.position" );
	texCoord        = cgGetNamedParameter( program, "vtxIn.texCoord" );
	color           = cgGetNamedParameter( program, "vtxIn.color" );
	modelViewMatrix = cgGetNamedParameter( program, "modelViewMatrix" );
	cgGLBindProgram( program );

	int tex[32][32]; // generate a simple gradient-like texture
	for (int x = 0; x < 32; ++x) {
		for (int y = 0; y < 32; ++y)
			tex[x][y] = ((x*8) << 16) + ((y*8) << 8);
	}

	UINT texID;
	glGenTextures( 1, &texID );
	glBindTexture( GL_TEXTURE_2D, texID );

	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex );

	while (!win->getQuit()) {
		win->update();

		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
		glMatrixMode( GL_PROJECTION );
		glLoadIdentity();
		gluPerspective( 45, 4.0/3.0, 1, 300 );
		glMatrixMode( GL_MODELVIEW );
		glLoadIdentity();

		gluLookAt( 40, 40, 40, 0, 0, 0, 0, 0, 1 );

		//cgGLEnableProfile( cgVertexProfile );
		cgGLBindProgram( program );
		glEnable( GL_TEXTURE_2D );
		glBindTexture( GL_TEXTURE_2D, texID );
		glColor4f( 1, 1, 1, 1 );

		glPushMatrix();
		cgGLSetStateMatrixParameter( modelViewMatrix, CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY );
		glPopMatrix();

		glBegin( GL_QUADS );
		glTexCoord2f( 0,0 );
		glVertex3f( -10,10,0 );
		glTexCoord2f( 1,0 );
		glVertex3f( 10,10,0 );
		glTexCoord2f( 1,1 );
		glVertex3f( 10,-10,0 );
		glTexCoord2f( 0,1 );
		glVertex3f( -10,-10,0 );
		glEnd();

		win->updateDisplay();
		Sleep( 20 );
	}

	delete win;
	return 0;
}

And the shader:
struct input { // vertex model
	float3 position	: POSITION;
	float3 normal	: NORMAL;
	float2 texCoord	: TEXCOORD0;
	float4 color	: COLOR0;
};

struct output {
	float4 position	: POSITION;
	float2 texCoord	: TEXCOORD0;
	float4 color	: COLOR0;
};

void main( input vtxIn,							// vertex in
		   out output vtxOut,					// vertex out
		   uniform float4x4 modelViewMatrix) {	// modelview matrix
	vtxOut.position = mul( modelViewMatrix, float4( vtxIn.position, 1.0f ) );
	vtxOut.texCoord = vtxIn.texCoord;
	vtxOut.color = vtxIn.color;
}



I'm using the Cg libs/headers from the latest Cg toolkit download. I've been trying to solve this for WEEKS! Am I using the wrong version of Cg? Forgetting to initialize something??? Any ideas help! [Edited by - Gumgo on March 6, 2010 3:36:22 AM]

Share this post


Link to post
Share on other sites
Just curious... what are you trying to accomplish by drawing the same quad 30 times?


for (UINT i = 0; i < 30; ++i) {
glTexCoord2f( 0,0 );
glVertex3f( -10,10,0 );
glTexCoord2f( 1,0 );
glVertex3f( 10,10,0 );
glTexCoord2f( 1,1 );
glVertex3f( 10,-10,0 );
glTexCoord2f( 0,1 );
glVertex3f( -10,-10,0 );
}



Kind of looks like a z fighting thing, maybe your quads are fighting over each other.

Can you post an image of what you expect your shape to look like? I'm not totally clear from your function, and it might give more clue as to what's happening.

Share this post


Link to post
Share on other sites
Oh whoops, that loop shouldn't be there. But anyway, the same thing occurs without the loop. Here is a picture of how it should look. Also, it seems to "freeze" on a frame until something changes on the screen (eg. I drag a window, or hover over the close button), and then starts flickering. That's why I was moving the mouse around to make the glitch occur.

Could someone run that code and see if the same thing happens? Or post the bare minimum code for getting texture coordinates working in Cg, and maybe I'll see something different between that and what I've written. Thanks.

[Edited by - Gumgo on March 6, 2010 12:33:04 PM]

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
      628350
    • Total Posts
      2982211
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • 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. 
      Thanks, 
      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!
      Thanks!
    • 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.
      Thanks.
  • Popular Now