Sign in to follow this  

OpenGL help with openGL and devC++

Recommended Posts

hi guys iam new to this forum and i have small problem iam following these excellent tutorials at However devC++ is giving me an error when i run the program here are the files the main.h file
#ifndef _MAIN_H
#define _MAIN_H

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gl\gl.h>										// Header File For The OpenGL32 Library
#include <gl\glu.h>										// Header File For The GLu32 Library

#define SCREEN_WIDTH 800								// We want our screen width 800 pixels
#define SCREEN_HEIGHT 600								// We want our screen height 600 pixels
#define SCREEN_DEPTH 16									// We want 16 bits per pixel

#include <vector>
#include <string>
#include <fstream>
#include <gl\glaux.h>
using namespace std;
#define MAX_TEXTURES 1000
class CVector3
	// A default constructor
	CVector3() {}

	// This is our constructor that allows us to initialize our data upon creating an instance
	CVector3(float X, float Y, float Z) 
		x = X; y = Y; z = Z;

	// Here we overload the + operator so we can add vectors together 
	CVector3 operator+(CVector3 vVector)
		// Return the added vectors result.
		return CVector3(vVector.x + x, vVector.y + y, vVector.z + z);

	// Here we overload the - operator so we can subtract vectors 
	CVector3 operator-(CVector3 vVector)
		// Return the subtracted vectors result
		return CVector3(x - vVector.x, y - vVector.y, z - vVector.z);
	// Here we overload the - operator so we can subtract vectors 
	CVector3 operator*(float num)
		// Return the subtracted vectors result
		return CVector3(x * num, y * num, z * num);

	float x, y, z;						

class CVector2 
float x, y;
bool CreateTexture(UINT &texture, LPSTR strFileName); 
struct tFace
int vertIndex[3]; // indicies for the verts that make up this triangle
int coordIndex[3]; // indicies for the tex coords to texture this face
struct tMaterialInfo
char strName[255]; // The texture name
char strFile[255]; // The texture file name (If this is set it's a texture map)
BYTE color[3]; // The color of the object (R, G, B)
int texureId; // the texture ID
float uTile; // u tiling of texture 
float vTile; // v tiling of texture 
float uOffset; // u offset of texture
float vOffset; // v offset of texture
} ;
struct t3DObject 
int numOfVerts; // The number of verts in the model
int numOfFaces; // The number of faces in the model
int numTexVertex; // The number of texture coordinates
int materialID; // The texture ID to use, which is the index into our texture array
bool bHasTexture; // This is TRUE if there is a texture map for this object
char strName[255]; // The name of the object
CVector3 *pVerts; // The object's vertices
CVector3 *pNormals; // The object's normals
CVector2 *pTexVerts; // The texture's UV coordinates
tFace *pFaces; // The faces information of the object
struct tAnimationInfo
char strName[255]; // This stores the name of the animation (I.E. "TORSO_STAND")
int startFrame; // This stores the first frame number for this animation
int endFrame; // This stores the last frame number for this animation
int loopingFrames; // This stores the looping frames for this animation (not used)
int framesPerSecond; // This stores the frames per second that this animation runs
// This our model structure
struct t3DModel 
int numOfObjects; // The number of objects in the model
int numOfMaterials; // The number of materials for the model
vector<tMaterialInfo> pMaterials; // The list of material information (Textures and colors)
vector<t3DObject> pObject; // The object list for our model
intnumOfAnimations; // The number of animations in this model 
int currentAnim; // The current index into pAnimations list 
int currentFrame; // The current frame of the current animation 
int nextFrame; // The next frame of animation to interpolate too
float t; // The ratio of 0.0f to 1.0f between each key frame
float lastTime; // This stores the last time that was stored
vector<tAnimationInfo> pAnimations; // The list of animations
int numOfTags; // This stores the number of tags in the model
t3DModel **pLinks; // This stores a list of pointers that are linked to this model
struct tMd3Tag *pTags; // This stores all the tags for the model animations

// Type this in your main header file (*.h)

struct Model
CVector3 position; // the position of our Model
CVector3 heading; // the heading of our Model
CVector3 speed; // the speed of our Model
float direction; // the direction of our Model

// Extern our global variables so other source files can use them
extern bool  g_bFullScreen;									// Set full screen as default
extern HWND  g_hWnd;										// This is the handle for the window
extern RECT  g_rRect;										// This holds the window dimensions
extern HDC   g_hDC;											// General HDC - (handle to device context)
extern HGLRC g_hRC;											// General OpenGL_DC - Our Rendering Context for OpenGL
extern HINSTANCE g_hInstance;								// This holds our window hInstance

// This is our MAIN() for windows
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int ishow);

// The window proc which handles all of window's messages.
LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

// This controls our main program loop
WPARAM MainLoop();

// This changes the screen to full screen mode
void ChangeToFullScreen();

// This is our own function that makes creating a window modular and easy
HWND CreateMyWindow(LPSTR strWindowName, int width, int height, DWORD dwstyle, bool bFullScreen, HINSTANCE hInstance);

// This allows us to configure our window for OpenGL and backbuffered
bool bSetupPixelFormat(HDC hdc);

// This inits our screen translations and projections
void SizeOpenGLScreen(int width, int height);

// This sets up OpenGL
void InitializeOpenGL(int width, int height);

// This initializes the whole program
void Init(HWND hWnd);

// This draws everything to the screen
void RenderScene();

// This frees all our memory in our program
void DeInit();

// The camera class was taken out of this file and put into camera.h 
// Ben Humphrey (DigiBen)
// Game Programmer
// Co-Web Host of

the main.cpp is below

//																		 //
//		- "Talk to me like I'm a 3 year old!" Programming Lessons -		 //
//                                                                       //
//		$Author:		DigiBen			 //
//																		 //
//		$Program:		Camera5	(strafing)								 //
//																		 //
//		$Description:	Demonstrates camera strafing right and left		 //
//																		 //
//		$Date:			1/1/02											 //
//																		 //

// This is a compiler directive that includes libraries (For Visual Studio)
// You can manually include the libraries in the "Project-&gt;settings" menu under
// the "Link" tab.  You need these libraries to compile this program.
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")

#include "main.h"										// This includes our header file
#define SPEED	0.02f									// This is how fast our camera moves

/////////////////////////////////////////my code

#include "md3.h"
#pragma comment(lib, "glaux.lib")
#define MODEL_PATH "lara" // This stores the folder name the character is in
#define MODEL_NAME "lara" // This stores the prefix for all the character files
#define GUN_NAME "Railgun" // This stores the name of our gun to load
#define PI 3.14159
CModelMD3 g_Model; // This is our global md3 character model instance

///////////////////////my code ends

bool  g_bFullScreen = TRUE;								// Set full screen as default
HWND  g_hWnd;											// This is the handle for the window
RECT  g_rRect;											// This holds the window dimensions
HDC   g_hDC;											// General HDC - (handle to device context)
HGLRC g_hRC;											// General OpenGL_DC - Our Rendering Context for OpenGL
HINSTANCE g_hInstance;									// This holds the global hInstance for UnregisterClass() in DeInit()

Model model; // the model
CVector3 Camera(0.0,5.0,2.0); // the Camera Position Vector
CVector3 View(0.0,2.0,0.0); // the Camera View Vector
CVector3 Heading(0.0,0.0,-1.0); // the Camera Heading Vector

float airdrag = 15.115f; // the the air drag value

float Direction = 0.0; // the direction of the camera

// The code in this tutorial was taken from the Camera4 tutorial.  This is our last camera 
// tutorial.  We might create a bezier curve camera tutorial though in the future.  This 
// tutorial shows how to strafe the camera right or left.  

///////////////////////////////// INIT GAME WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function initializes the game window.
///////////////////////////////// INIT GAME WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

void Init(HWND hWnd)
	g_hWnd = hWnd;										// Assign the window handle to a global window handle
	GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
	InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect

	// Init our camera position
// Position the model , change the vars to what ever you want...

model.position.x = 0.0;
model.position.y = 1.0;
model.position.z = 0.0;

// Position the camera, change the vars to what ever you want...

// We put them this way to get a nice panning effect when the game starts

Camera.x = -20;
Camera.y = 10;
Camera.z = -20;

/////////////////////my code
// Add this into your Init() function
bool bResult = g_Model.LoadModel(MODEL_PATH, MODEL_NAME);
// Load the gun and attach it to our character
bResult = g_Model.LoadWeapon(MODEL_PATH, GUN_NAME);
// Set the standing animation for the torso
// Set the walking animation for the legs

//////////////////my code ends


///////////////////////////////// KEY PRESSED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function handles the input more effectively than in the WinProc()
///////////////////////////////// KEY PRESSED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

void KeyPressed()
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// Check if we hit the Up arrow or the 'w' key
	if(GetKeyState(VK_UP) & 0x80 || GetKeyState('W') & 0x80) {				
if((model.speed.x+model.speed.y+model.speed.z)/3 &lt;= 0.7) // check the Max Speed
model.speed.x += model.heading.x * 0.003 * airdrag; //to increase the max speed, just add to the 0.02 number, don't change anything else!!!
model.speed.y += model.heading.y * 0.003 * airdrag; // ^above^ :It applies to all
model.speed.z += model.heading.z * 0.003 * airdrag;



	// Check if we hit the Down arrow or the 's' key
	if(GetKeyState(VK_DOWN) & 0x80 || GetKeyState('S') & 0x80) {			

if((model.speed.x+model.speed.y+model.speed.z)/3 &gt;= -0.3)
model.speed.x -= model.heading.x * 0.002 * airdrag;
model.speed.y -= model.heading.y * 0.002 * airdrag;
model.speed.z -= model.heading.z * 0.002 * airdrag;

	// Check if we hit the Left arrow or the 'a' key
	if(GetKeyState(VK_LEFT) & 0x80 || GetKeyState('A') & 0x80) {			

model.direction += 0.04;

	// Check if we hit the Right arrow or the 'd' key
	if(GetKeyState(VK_RIGHT) & 0x80 || GetKeyState('D') & 0x80) {			
model.direction -= 0.04;


/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

///////////////////////////////// MAIN GAME LOOP \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function Handles the main game loop
///////////////////////////////// MAIN GAME LOOP \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

WPARAM MainLoop()
	MSG msg;

	while(1)											// Do our infinate loop
	{													// Check if there was a message
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 
			if(msg.message == WM_QUIT)					// If the message wasnt to quit
            TranslateMessage(&msg);						// Find out what the message does
            DispatchMessage(&msg);						// Execute the message
		else											// if there wasn't a message

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

			KeyPressed();								// Check if we pressed a movement key
			RenderScene();								// Render the scene every frame

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *


	DeInit();											// Clean up and free all allocated memory

	return(msg.wParam);									// Return from the program

///////////////////////////////// CREATE PYRAMID \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This creates a pyramid with the center being (X, Y, Z).
/////   The width and height depend on the WIDTH and HEIGHT passed in
///////////////////////////////// CREATE PYRAMID \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

void CreatePyramid(float x, float y, float z, int width, int height)
	// Below we create a pyramid (hence CreatePyramid() :).  This entails
	// 4 triangles for the sides and one QUAD for the bottom.  We could have done
	// 2 triangles instead of a QUAD but it's less code and seemed appropriate.
	// We also assign some different colors to each vertex to add better visibility.
	// The pyramid will be centered around (x, y, z).  This code is also used in the
	// Lighting and Fog tutorial on our site at

	// Start rendering the 4 triangles for the sides
		// These vertices create the Back Side
		glColor3ub(255, 0, 0);   glVertex3f(x, y + height, z);					// Top point
		glColor3ub(0, 255, 255); glVertex3f(x - width, y - height, z - width);	// Bottom left point
		glColor3ub(255, 0, 255); glVertex3f(x + width, y - height, z - width);  // Bottom right point

		// These vertices create the Front Side
		glColor3ub(255, 0, 0);   glVertex3f(x, y + height, z);					// Top point
		glColor3ub(0, 255, 255); glVertex3f(x + width, y - height, z + width);  // Bottom right point
		glColor3ub(255, 0, 255); glVertex3f(x - width, y - height, z + width);	// Bottom left point

		// These vertices create the Front Left Side
		glColor3ub(255, 0, 0);   glVertex3f(x, y + height, z);					// Top point
		glColor3ub(255, 0, 255); glVertex3f(x - width, y - height, z + width);	// Front bottom point
		glColor3ub(0, 255, 255); glVertex3f(x - width, y - height, z - width);	// Bottom back point

		// These vertices create the Front right Side
		glColor3ub(255, 0, 0);   glVertex3f(x, y + height, z);					// Top point
		glColor3ub(255, 0, 255); glVertex3f(x + width, y - height, z - width);	// Bottom back point
		glColor3ub(0, 255, 255); glVertex3f(x + width, y - height, z + width);	// Front bottom point

	// Now render the bottom of our pyramid


		// These vertices create the bottom of the pyramid
		glColor3ub(0, 0, 255); glVertex3f(x - width, y - height, z + width);	// Front left point
		glColor3ub(0, 0, 255); glVertex3f(x + width, y - height, z + width);    // Front right point
		glColor3ub(0, 0, 255); glVertex3f(x + width, y - height, z - width);    // Back right point
		glColor3ub(0, 0, 255); glVertex3f(x - width, y - height, z - width);    // Back left point

///////////////////////////////// DRAW 3D GRID \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function create a simple grid to get a better view of the animation
///////////////////////////////// DRAW 3D GRID \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

void Draw3DSGrid()
	// This function was added to give a better feeling of moving around.
	// A black background just doesn't give it to ya :)  We just draw 100
	// green lines vertical and horizontal along the X and Z axis.

	// Turn the lines GREEN
	glColor3ub(0, 255, 0);

	// Draw a 1x1 grid along the X and Z axis'
	for(float i = -50; i &lt;= 50; i += 1)
		// Start drawing some lines

			// Do the horizontal lines (along the X)
			glVertex3f(-50, 0, i);
			glVertex3f(50, 0, i);

			// Do the vertical lines (along the Z)
			glVertex3f(i, 0, -50);
			glVertex3f(i, 0, 50);

		// Stop drawing lines

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

///////////////////////////////// DRAW SPIRAL TOWERS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This draws a spiral of pyramids to maneuver around
///////////////////////////////// DRAW SPIRAL TOWERS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

/*void DrawSpiralTowers()
	const float PI = 3.14159f;							// Create a constant for PI
	const float kIncrease = PI / 16.0f;					// This is the angle we increase by in radians
	const float kMaxRotation = PI * 6;					// This is 1080 degrees of rotation in radians (3 circles)
	float radius = 40;									// We start with a radius of 40 and decrease towards the center

	// Keep looping until we go past the max degrees of rotation (which is 3 full rotations)
	for(float degree = 0; degree &lt; kMaxRotation; degree += kIncrease)
		// Here we use polar coordinates for the rotations, but we swap the y with the z
		float x = float(radius * cos(degree));			// Get the x position for the current rotation and radius
		float z = float(radius * sin(degree));			// Get the z position for the current rotation and radius

		// Create a pyramid for every degree in our spiral with a width of 1 and height of 3 
		CreatePyramid(x, 3, z, 1, 3);
		// Decrease the radius by the constant amount so the pyramids spirals towards the center
		radius -= 40 / (kMaxRotation / kIncrease);

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

///////////////////////////////// RENDER SCENE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function renders the entire scene.
///////////////////////////////// RENDER SCENE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

void RenderScene() 
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear The Screen And The Depth Buffer
	glLoadIdentity();									// Reset The matrix

Direction += (model.direction-Direction)/15; // experiment with other values ;) 

// some little math :)

Heading.x = cos(90-Direction);
Heading.z = sin(90-Direction); 

model.heading.x = cos(90-model.direction);
model .heading.z = sin(90-model.direction);

Camera.x += ((View.x + Heading.x * -6) - Camera.x) / 3;
Camera.y += ((View.y + Heading.y * -6 + 1) - Camera.y) / 3; //okay,if you have a terrain or bsp engine, comment out this whole line...
Camera.z += ((View.z + Heading.z * -6) - Camera.z) / 3;

// some more math :) 
model.position.x += model.speed.x; 
model.position.y += model.speed.y;
model.position.z += model.speed.z; 
View.x = model.position.x;
View.y = model.position.y + 1;
View.z = model.position.z;


// here we put the airdrag force in action :) and affect our model's speed

model.speed.x /= airdrag;
model .speed.y /= airdrag;
model .speed.z /= airdrag;

gluLookAt(Camera.x, Camera.y, Camera.z, // the position 
View.x, View.y, View.z, //the View
0.0f,1.0f,0.0f); //the Up-Vector

	// Draw a grid so we can get a good idea of movement around the world		

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// Draw the pyramids that spiral in to the center

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

	// Swap the backbuffers to the foreground

///////////////////////////////// WIN PROC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function handles the window messages.
///////////////////////////////// WIN PROC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

    LONG    lRet = 0; 
    PAINTSTRUCT    ps;

    switch (uMsg)
    case WM_SIZE:										// If the window is resized
		if(!g_bFullScreen)								// Do this only if we are in window mode
			SizeOpenGLScreen(LOWORD(lParam),HIWORD(lParam));// LoWord=Width, HiWord=Height
			GetClientRect(hWnd, &g_rRect);					// Get the window rectangle
	case WM_PAINT:										// If we need to repaint the scene
		BeginPaint(hWnd, &ps);							// Init the paint struct		
		EndPaint(hWnd, &ps);							// EndPaint, Clean up


		switch(wParam) {								// Check if we hit a key
			case VK_ESCAPE:								// If we hit the escape key
				PostQuitMessage(0);						// Send a QUIT message to the window

    case WM_CLOSE:										// If the window is being closes
        PostQuitMessage(0);								// Send a QUIT Message to the window
    default:											// Return by default
        lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); 
    return lRet;										// Return by default

// This tutorial was taken from the Camera4 tutorial.  This is our last camera tutorial.
// We might create a bezier curve camera tutorial though in the future.  This tutorial
// shows how to strafe the camera right or left.  This might seem easy when you think to
// attempt it, but if you don't know your linear algebra it can be tricky.  Strafing the
// camera is moving the camera 90 degrees left or right from the current view.  In other
// words, it's as if you were side stepping while you look forward.  This is used in most
// first person shooters games, and comes in handy when peering around corners or running
// past a hallway while firing off some rounds.  It's also a great way to move diagonal
// while doing a shootout at close ranges to avoid being hit.
// Since we understand what strafing is and what it does, let me actually explain how it works.
// We know that we want to walk in the direction that is 90 degrees from the view vector (with
// the view vector being m_vView - m_vPosition).  So how do we then get the vector that is 90
// degrees from our view vector?  If you know what the cross product is, you can easily see how
// this would be done.  The cross product is a mathematical formula that takes 2 vectors and
// returns the vector 90 degrees from those 2 vectors.  This is how you find the normal to a plane.
// Well, we have a view vector, but what would the other vector be?  Does the up vector come to mind?
// That's it!  We want to take the cross product between the up vector and the view vector.  This
// will return the vector (or direction) that we want to strafe in.  In games like Descent, the
// up vector will change because you can go upside down and spin in crazy directions.  The cross
// product will ensure that we will always strafe correctly no matter what orientation the camera is in.
// Once we have the strafe vector, we need to add it to the position and view points.
// Here are the controls for this tutorial:
// w, s, UP_ARROW, DOWN_ARROW - Move the camera forward and backward
// a, d, RIGHT_ARROW, LEFT_ARROW - Strafe the camera left and right
// Mouse movement - Moves the view for first person mode
// ESCAPE - Quits the program
// You may notice that we don't use all the methods in the camera class.  I decided to leave
// them in there because since this is the last camera tutorial it would be nice to just use
// this in your projects without having to cut and paste code.  That's also why I finally
// added a camera.h so you don't have the camera class in main.h.
// Enjoy!
// Ben Humphrey (DigiBen)
// Game Programmer
// Co-Web Host of

and the init.cpp

//																		 //
//		- "Talk to me like I'm a 3 year old!" Programming Lessons -		 //
//                                                                       //
//		$Author:		DigiBen			 //
//																		 //
//		$Program:		Camera5	(strafing)								 //
//																		 //
//		$Description:	Demonstrates camera strafing right and left		 //
//																		 //
//		$Date:			1/1/02											 //
//																		 //

#include "main.h"

/////////////////////////////////////my code

bool CreateTexture(UINT &texture, LPSTR strFileName)
AUX_RGBImageRec *pImage = NULL;
FILE *pFile = NULL; 
return false; // Open a file pointer to the BMP file and check if it was found and opened 
if((pFile = fopen(strFileName, "rb")) == NULL) 
// Display an error message saying the file was not found, then return NULL
MessageBox(g_hWnd, "Unable to load BMP File!", "Error", MB_OK);
return NULL;
} // Load the bitmap using the aux function stored in glaux.lib
pImage = auxDIBImageLoad(strFileName); // Make sure valid image data was given to pImage, otherwise return false
if(pImage == NULL) 
return false; // Generate a texture with the associative texture ID stored in the array
glGenTextures(1, &texture); // This sets the alignment requirements for the start of each pixel row in memory.
glPixelStorei (GL_UNPACK_ALIGNMENT, 1); // Bind the texture to the texture arrays index and init the texture
glBindTexture(GL_TEXTURE_2D, texture);

// Build Mipmaps (builds different versions of the picture for distances - looks better)
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, pImage-&gt;sizeX, 
pImage-&gt;sizeY, GL_RGB, GL_UNSIGNED_BYTE, pImage-&gt;data);
//Assign the mip map levels and texture info
// Now we need to free the image data that we loaded since openGL stored it as a texture
if (pImage) // If we loaded the image
if (pImage-&gt;data) // If there is texture data
free(pImage-&gt;data); // Free the texture data, we don't need it anymore
free(pImage); // Free the image structure
// Return a success
return true;

////////////////////////////////my code ends

///////////////////////////////// CHANGE TO FULL SCREEN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This changes the screen to FULL SCREEN
///////////////////////////////// CHANGE TO FULL SCREEN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

void ChangeToFullScreen()
	DEVMODE dmSettings;									// Device Mode variable

	memset(&dmSettings,0,sizeof(dmSettings));			// Makes Sure Memory's Cleared

	// Get current settings -- This function fills our the settings
	// This makes sure NT and Win98 machines change correctly
		// Display error message if we couldn't get display settings
		MessageBox(NULL, "Could Not Enum Display Settings", "Error", MB_OK);

	dmSettings.dmPelsWidth	= SCREEN_WIDTH;				// Selected Screen Width
	dmSettings.dmPelsHeight	= SCREEN_HEIGHT;			// Selected Screen Height
	// This function actually changes the screen to full screen
	// CDS_FULLSCREEN Gets Rid Of Start Bar.
	// We always want to get a result from this function to check if we failed
	int result = ChangeDisplaySettings(&dmSettings,CDS_FULLSCREEN);	

	// Check if we didn't recieved a good return message From the function
		// Display the error message and quit the program
		MessageBox(NULL, "Display Mode Not Compatible", "Error", MB_OK);

///////////////////////////////// CREATE MY WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function creates a window, but doesn't have a message loop
///////////////////////////////// CREATE MY WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

HWND CreateMyWindow(LPSTR strWindowName, int width, int height, DWORD dwstyle, bool bFullScreen, HINSTANCE hInstance)
	HWND hWnd;
	WNDCLASS wndclass;
	memset(&wndclass, 0, sizeof(WNDCLASS));				// Init the size of the class = CS_HREDRAW | CS_VREDRAW;			// Regular drawing capabilities
	wndclass.lpfnWndProc = WinProc;						// Pass our function pointer as the window procedure
	wndclass.hInstance = hInstance;						// Assign our hInstance
	wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);	// General icon
	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);		// An arrow for the cursor
	wndclass.hbrBackground = (HBRUSH) (COLOR_WINDOW+1);	// A white window
	wndclass.lpszClassName = "GameTutorials";			// Assign the class name

	RegisterClass(&wndclass);							// Register the class
	if(bFullScreen && !dwstyle) 						// Check if we wanted full screen mode
	{													// Set the window properties for full screen mode
		ChangeToFullScreen();							// Go to full screen
		ShowCursor(FALSE);								// Hide the cursor
	else if(!dwstyle)									// Assign styles to the window depending on the choice
	g_hInstance = hInstance;							// Assign our global hInstance to the window's hInstance

	RECT rWindow;
	rWindow.left	= 0;								// Set Left Value To 0
	rWindow.right	= width;							// Set Right Value To Requested Width	    = 0;								// Set Top Value To 0
	rWindow.bottom	= height;							// Set Bottom Value To Requested Height

	AdjustWindowRect( &rWindow, dwstyle, false);		// Adjust Window To True Requested Size

														// Create the window
	hWnd = CreateWindow("GameTutorials", strWindowName, dwstyle, 0, 0,
						rWindow.right  - rWindow.left, rWindow.bottom -, 
						NULL, NULL, hInstance, NULL);

	if(!hWnd) return NULL;								// If we could get a handle, return NULL

	ShowWindow(hWnd, SW_SHOWNORMAL);					// Show the window
	UpdateWindow(hWnd);									// Draw the window

	SetFocus(hWnd);										// Sets Keyboard Focus To The Window	

	return hWnd;

///////////////////////////////// SET UP PIXEL FORMAT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function sets the pixel format for OpenGL.
///////////////////////////////// SET UP PIXEL FORMAT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

bool bSetupPixelFormat(HDC hdc) 
    int pixelformat; 
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);			// Set the size of the structure
    pfd.nVersion = 1;									// Always set this to 1
														// Pass in the appropriate OpenGL flags
    pfd.dwLayerMask = PFD_MAIN_PLANE;					// We want the standard mask (this is ignored anyway)
    pfd.iPixelType = PFD_TYPE_RGBA;						// We want RGB and Alpha pixel type
    pfd.cColorBits = SCREEN_DEPTH;						// Here we use our #define for the color bits
    pfd.cDepthBits = SCREEN_DEPTH;						// Depthbits is ignored for RGBA, but we do it anyway
    pfd.cAccumBits = 0;									// No special bitplanes needed
    pfd.cStencilBits = 0;								// We desire no stencil bits
	// This gets us a pixel format that best matches the one passed in from the device
    if ( (pixelformat = ChoosePixelFormat(hdc, &pfd)) == FALSE ) 
        MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK); 
        return FALSE; 
	// This sets the pixel format that we extracted from above
    if (SetPixelFormat(hdc, pixelformat, &pfd) == FALSE) 
        MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK); 
        return FALSE; 
    return TRUE;										// Return a success!

//////////////////////////// RESIZE OPENGL SCREEN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function resizes the viewport for OpenGL.
//////////////////////////// RESIZE OPENGL SCREEN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
void SizeOpenGLScreen(int width, int height)			// Initialize The GL Window
	if (height==0)										// Prevent A Divide By Zero error
		height=1;										// Make the Height Equal One

	glViewport(0,0,width,height);						// Make our viewport the whole window
														// We could make the view smaller inside
														// Our window if we wanted too.
														// The glViewport takes (x, y, width, height)
														// This basically means, what our our drawing boundries

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

														// Calculate The Aspect Ratio Of The Window
														// The parameters are:
														// (view angle, aspect ration of the width to the height, 
														//  The closest distance to the camera before it clips, 
				  // FOV		// Ratio				//  The farthest distance before it stops drawing)
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height, .5f ,150.0f);

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix

///////////////////////////////// INITIALIZE GL \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function handles all the initialization for OpenGL.
///////////////////////////////// INITIALIZE GL \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

void InitializeOpenGL(int width, int height) 
    g_hDC = GetDC(g_hWnd);								// This sets our global HDC
														// We don't free this hdc until the end of our program
    if (!bSetupPixelFormat(g_hDC))						// This sets our pixel format/information
        PostQuitMessage (0);							// If there's an error, quit

    g_hRC = wglCreateContext(g_hDC);					// This creates a rendering context from our hdc
    wglMakeCurrent(g_hDC, g_hRC);						// This makes the rendering context we just created the one we want to use

//////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** ////////////////////
	// Since we have more than ONE primative (shape), we need to do some depth testing.
	// If we do NOT have this line, you will see through all the shapes when you go behind them.
	// Comment out this line and then go behind all the triangles.  It's a cool effect though :)

	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing

//////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** ////////////////////

	SizeOpenGLScreen(width, height);					// Setup the screen translations and viewport

///////////////////////////////// DE INIT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function cleans up and then posts a quit message to the window
///////////////////////////////// DE INIT \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

void DeInit()
	if (g_hRC)											
		wglMakeCurrent(NULL, NULL);						// This frees our rendering memory and sets everything back to normal
		wglDeleteContext(g_hRC);						// Delete our OpenGL Rendering Context	
	if (g_hDC) 
		ReleaseDC(g_hWnd, g_hDC);						// Release our HDC from memory
	if(g_bFullScreen)									// If we were in full screen
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		ShowCursor(TRUE);								// Show Mouse Pointer

	UnregisterClass("GameTutorials", g_hInstance);		// Free the window class

	PostQuitMessage (0);								// Post a QUIT message to the window

///////////////////////////////// WIN MAIN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////	This function handles registering and creating the window.
///////////////////////////////// WIN MAIN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int ishow)
	HWND hWnd;

	// Check if we want full screen or not
	if(MessageBox(NULL, "Click Yes to go to full screen (Recommended)", "Options", MB_YESNO | MB_ICONQUESTION) == IDNO)
		g_bFullScreen = false;
	// Create our window with our function we create that passes in the:
	// Name, width, height, any flags for the window, if we want fullscreen of not, and the hInstance
	hWnd = CreateMyWindow(" - Camera Strafing", SCREEN_WIDTH, SCREEN_HEIGHT, 0, g_bFullScreen, hInstance);

	// If we never got a valid window handle, quit the program
	if(hWnd == NULL) return TRUE;

	// INIT OpenGL

	// Run our message loop and after it's done, return the result
	return MainLoop();						

// Nothing new was added to this file since the Camera2 tutorial.
// Ben Humphrey (DigiBen)
// Game Programmer
// Co-Web Host of

the above are the files the error i get is this
E:\Dev-CppPortable\App\devcpp\Bin\..\lib\gcc\mingw32\3.4.2\..\..\..\..\mingw32\bin\ld.exe: cannot find -lib32
collect2: ld returned 1 exit status

make.exe: *** [Camera5.exe] Error 1

if i remove -lib32 from the project options i get these errors
Init.o(.text+0x17d):Init.cpp: undefined reference to `auxDIBImageLoadA@4'
Init.o(.text+0x1a8):Init.cpp: undefined reference to `glGenTextures@8'
Init.o(.text+0x1bf):Init.cpp: undefined reference to `glPixelStorei@8'
Init.o(.text+0x1d7):Init.cpp: undefined reference to `glBindTexture@8'
Init.o(.text+0x21b):Init.cpp: undefined reference to `gluBuild2DMipmaps@28'
Init.o(.text+0x23a):Init.cpp: undefined reference to `glTexParameteri@12'
Init.o(.text+0x25a):Init.cpp: undefined reference to `glTexEnvf@12'
Init.o(.text+0x647):Init.cpp: undefined reference to `glViewport@16'

Init.o(.text+0x656):Init.cpp: undefined reference to `glMatrixMode@4'
Init.o(.text+0x65e):Init.cpp: undefined reference to `glLoadIdentity@0'

Init.o(.text+0x68c):Init.cpp: undefined reference to `gluPerspective@32'
Init.o(.text+0x69b):Init.cpp: undefined reference to `glMatrixMode@4'
Init.o(.text+0x6a3):Init.cpp: undefined reference to `glLoadIdentity@0'
Init.o(.text+0x6ee):Init.cpp: undefined reference to `wglCreateContext@4'
Init.o(.text+0x70c):Init.cpp: undefined reference to `wglMakeCurrent@8'
Init.o(.text+0x71b):Init.cpp: undefined reference to `glEnable@4'
Init.o(.text+0x755):Init.cpp: undefined reference to `wglMakeCurrent@8'
Init.o(.text+0x765):Init.cpp: undefined reference to `wglDeleteContext@4'
Main.o(.text+0x190):Main.cpp: undefined reference to `CModelMD3::LoadModel(char*, char*)'

Main.o(.text+0x1af):Main.cpp: undefined reference to `CModelMD3::LoadWeapon(char*, char*)'
Main.o(.text+0x1c6):Main.cpp: undefined reference to `CModelMD3::SetTorsoAnimation(char*)'
Main.o(.text+0x1da):Main.cpp: undefined reference to `CModelMD3::SetLegsAnimation(char*)'
Main.o(.text+0x49c):Main.cpp: undefined reference to `glBegin@4'
Main.o(.text+0x4bb):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x4da):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x4f9):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x524):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x543):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x56c):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x58b):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x5aa):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x5c9):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x5f0):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x60f):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x638):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x657):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x676):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x695):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x6be):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x6dd):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x708):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x727):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x746):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x765):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x78e):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x7ad):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x7d4):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x7dc):Main.cpp: undefined reference to `glEnd@0'
Main.o(.text+0x7e8):Main.cpp: undefined reference to `glBegin@4'
Main.o(.text+0x807):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x830):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x84f):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x876):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x895):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x8be):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x8dd):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x908):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x910):Main.cpp: undefined reference to `glEnd@0'
Main.o(.text+0x934):Main.cpp: undefined reference to `glColor3ub@12'
Main.o(.text+0x960):Main.cpp: undefined reference to `glBegin@4'
Main.o(.text+0x980):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x9a0):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x9c0):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x9e0):Main.cpp: undefined reference to `glVertex3f@12'
Main.o(.text+0x9e8):Main.cpp: undefined reference to `glEnd@0'
Main.o(.text+0xa0c):Main.cpp: undefined reference to `glClear@4'
Main.o(.text+0xa14):Main.cpp: undefined reference to `glLoadIdentity@0'
Main.o(.text+0xc14):Main.cpp: undefined reference to `gluLookAt@72'
Main.o(.text+0xd57):Main.cpp: undefined reference to `CModelMD3::CModelMD3()'
Main.o(.text+0xe2f):Main.cpp: undefined reference to `CModelMD3::~CModelMD3()'
collect2: ld returned 1 exit status

make.exe: *** [Camera5.exe] Error 1

Execution terminated

please help me on these errors [Edited by - wabbz111 on February 19, 2008 11:42:08 PM]

Share this post

Link to post
Share on other sites
Looks like you'll also need -lglaux.lib. Also, where is the definition of the CModelMD3 class?

And please, for the love of god, edit your post to use source tags (see the FAQ for how to do this).

Share this post

Link to post
Share on other sites
thanks for the reply and sorry about the post i have now edited it properly.I put the links but i still get the error cannot find -lglaux.lib.Also how do i link the model i want to load to devC++? i have used the resource directories tab but im not sure.Thanks

Share this post

Link to post
Share on other sites
Do you have the necessary files in place?

Try downloading this "glaux-1-1mol.DevPak" devpak using the Tools --> Check for Updates/Packages

Once installed, open a sample project. This will setup your project with the right parameters.

Share this post

Link to post
Share on other sites
i believe the .exe for it is something like opengl95.exe or something. It has the glaux library and header file(s). Google glaux library download to find it, and when you run the exe, copy the files to correct directory (i believe it should be in program files/microsoft sdk or something along that sort).

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 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!
    • By test opty
      I'm trying to learn OpenGL through a website and have proceeded until this page of it. The output is a simple triangle. The problem is the complexity.
      I have read that page several times and tried to analyse the code but I haven't understood the code properly and completely yet. This is the code:
      #include <glad/glad.h> #include <GLFW/glfw3.h> #include <C:\Users\Abbasi\Desktop\std_lib_facilities_4.h> using namespace std; //****************************************************************************** void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; const char *vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" "}\0"; const char *fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n" "}\n\0"; //******************************* int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "My First Triangle", nullptr, nullptr); if (window == nullptr) { cout << "Failed to create GLFW window" << endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { cout << "Failed to initialize GLAD" << endl; return -1; } // build and compile our shader program // vertex shader int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr); glCompileShader(vertexShader); // check for shader compile errors int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog); cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << endl; } // fragment shader int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog); cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << endl; } // link shaders int shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog); cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // set up vertex data (and buffer(s)) and configure vertex attributes float vertices[] = { -0.5f, -0.5f, 0.0f, // left 0.5f, -0.5f, 0.0f, // right 0.0f, 0.5f, 0.0f // top }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), //and then configure vertex attributes(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // note that this is allowed, the call to glVertexAttribPointer registered VBO // as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind glBindBuffer(GL_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally // modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind // VAOs (nor VBOs) when it's not directly necessary. glBindVertexArray(0); // uncomment this call to draw in wireframe polygons. //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render loop while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // draw our first triangle glUseProgram(shaderProgram); glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to // bind it every time, but we'll do so to keep things a bit more organized glDrawArrays(GL_TRIANGLES, 0, 3); // glBindVertexArray(0); // no need to unbind it every time // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. glfwTerminate(); return 0; } //************************************************** // process all input: query GLFW whether relevant keys are pressed/released // this frame and react accordingly void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } //******************************************************************** // glfw: whenever the window size changed (by OS or user resize) this callback function executes void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } As you see, about 200 lines of complicated code only for a simple triangle. 
      I don't know what parts are necessary for that output. And also, what the correct order of instructions for such an output or programs is, generally. That start point is too complex for a beginner of OpenGL like me and I don't know how to make the issue solved. What are your ideas please? What is the way to figure both the code and the whole program out correctly please?
      I wish I'd read a reference that would teach me OpenGL through a step-by-step method. 
  • Popular Now