Search result for 'opengl'
(0.0415470600128 seconds)
3 pages : 1 2 3 Next › Last»

antonmills/OpenGL Triangle3D ( Other)

typedef struct {
    Vertex3D v1;
    Vertex3D v2;
    Vertex3D v3;
} Triangle3D;

A C struct that supports 3 Vertex3D for use with OpenGL triangles

antonmills/OpenGL Distance to object ( Other)

static inline GLfloat Vertex3DCalculateDistanceBetweenVertices (Vertex3D first, Vertex3D second)
{
    GLfloat deltaX = second.x - first.x;
    GLfloat deltaY = second.y - first.y;
    GLfloat deltaZ = second.z - first.z;
    return sqrtf(deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ );
};

Works out the distance between two objects in 3D space, you'll need the Vertex3D struct also in my snipppets

autofasurer/Elastic Spheres ( C++)

#include <GLUT/glut.h>
#include <iostream>
using namespace std;

//initialising variables
float x_positie = 0.0, x_doel = 0.0, x_doel2, x_kracht = 0.02, x_versnelling = -0.001, weerstand = 0.99, doeldist = 0.0;
float y_positie = 0.0, y_doel = 0.0, y_doel2, y_kracht = 0.02, y_versnelling = -0.001, rot = 0.0;
float z_positie = 0.0, z_doel = 0.0, z_doel2, z_kracht = 0.02, z_versnelling = -0.001, t = 0.0;
//initialising states 
void init()
{
	glClearColor(0.0,0.0,0.0,1.0);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
}

//reshaping the viewport and projection
void reshape(int width, int height)
{
	glViewport(0, 0, 1024, 768);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(60.,(GLfloat) width/(GLfloat) height,0.1, 800.0);
	glMatrixMode(GL_MODELVIEW);
	gluLookAt(0.0,0.0,200.0, 0.0, 0.0, 0.0, 0,1,0);

}

//reading the keyboard input
void key(unsigned char key, int x, int y){
	switch (key){
		case 32:
		x_doel2 = (rand()%160-80);
		y_doel2 = (rand()%160-80);
		z_doel2 = (rand()%160-80);
		doeldist = sqrt (pow((x_doel-x_doel2),2.0) + pow((y_doel-y_doel2),2.0) + pow((z_doel-z_doel2),2.0));
		break;
		}
}

//drawing and displaying 
void display()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		//glRotatef(0.5,0,1,0);
	
		glPushMatrix();
			x_positie += x_kracht ; 
			y_positie += y_kracht ;
			z_positie += z_kracht ;
			x_versnelling = (x_doel2 - x_positie)*0.0003;
			y_versnelling = (y_doel2 - y_positie)*0.0003;
			z_versnelling = (z_doel2 - z_positie)*0.0003;
			x_kracht += x_versnelling;
			y_kracht += y_versnelling;
			z_kracht += z_versnelling;
			x_kracht *= weerstand;
			y_kracht *= weerstand;
			z_kracht *= weerstand;

			glBegin(GL_LINES);
				glVertex3f(x_doel,y_doel,z_doel);
				glVertex3f(x_positie,y_positie,z_positie);
			glEnd();

			glTranslatef(x_positie, y_positie, z_positie);
			glColor4f(0.6, 0.0, 0.0, 1.0);
			glutSolidSphere(2.0,9,9);
		glPopMatrix();

		glPushMatrix();
		glTranslatef(x_positie+sin(t)*9,y_positie+cos(t)*9,z_positie);
		glutSolidSphere(2.0,9,9);
		        if (t > 6.2829){
			    t = 0;
			}
		t += 0.02;
		glPopMatrix();

		glPushMatrix();
		        glTranslatef(x_doel, y_doel, z_doel);
		        glColor4f(0.3,0.3,0.3,0.3);
		        glutSolidSphere(5.0,15,15);
		glPopMatrix();
		glutSwapBuffers();
}

//main loop with initialising of window and glut, assigning functions
int main(int argc, char** argv)
{
	srand(time(NULL));
	glutInit(&amp;argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutGameModeString("1024x768:32");
	glutEnterGameMode();
	init();
	glutDisplayFunc(display);
	glutIdleFunc(display);
	glutReshapeFunc(reshape);
	glutKeyboardFunc(key);
	glutMainLoop();
	return 0;	
}

Little test to control separate objects in OpenGL using pushMatrix() and popMatrix()

autofasurer/Spirograph ( C++)

/*
 *  harmonograph.cpp
 *
 *  Created by Brecht Debackere on 02/04/10.
 *  Copyright 2010 Autofasurer. All rights reserved.
 *
 */

#include <GLUT/glut.h>
#include <iostream>
using namespace std;

//initialising variables
float fRed = 1.0, fGreen = 1.0, fBlue =1.0, fXpos = 0.0, fYpos = 0.0, fFrequency = 0.0, fAmplitude = 0.0, fPhase = 0.0, fTime = 0.0, fPointsize = 1.0;


//initialising states 
void init()
{
	glClearColor(0.0,0.0,0.0,0.7);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
}

//reshaping the viewport and projection
void reshape(int width, int height)
{
	glViewport(0, 0, 1440, 900);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.,(GLfloat) width/(GLfloat) height,0.1, 800.0);
	glMatrixMode(GL_MODELVIEW);
	gluLookAt(0.0,0.0,10.0, 0.0, 0.0, 0.0, 0,1,0);
	
}

//reading the keyboard input
void key(unsigned char key, int x, int y){
	switch (key){
		case 32:
			fFrequency = (rand()%500-250)/5.0;
			fPhase = (rand()%500-250)/5.0;
			fAmplitude = (rand()%500-250)/5.0; 
			fTime = 0.0;
			break;
	}
}


//drawing and displaying 
void display()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glBegin(GL_LINE_STRIP); 
	while (fTime < 400.0) {
		glColor3d(fRed, fGreen, fBlue);
		fXpos = 4*(cos(fFrequency * fTime) + cos(fPhase * fTime)*0.5 + cos(fAmplitude * fTime)*0.33);
		fYpos = 4*(sin(fFrequency * fTime) + sin(fPhase * fTime)*0.5 + sin(fAmplitude * fTime)*0.33);
		glVertex3f(fXpos, fYpos, 0);
		fTime += 0.002;	
	}
	glEnd();
	fFrequency -= 0.0001;	
	fAmplitude += 0.0001;	
	fPhase += 0.0001;
	fTime = 0.0;
	glutSwapBuffers();
	fRed = (rand()%100)/400.0;
	fGreen = (rand()%100)/400.0;
	fBlue = (rand()%100)/400.0;
}

//main loop with initialising of window and glut, assigning functions
int main(int argc, char** argv)
{
	srand(time(NULL));
	glutInit(&amp;argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutGameModeString("1440x900:32");
	glutEnterGameMode();
	init();
	glutDisplayFunc(display);
	glutIdleFunc(display);
	glutReshapeFunc(reshape);
	glutKeyboardFunc(key);
	glutMainLoop();
	return 0;	
}

GLUT / OpenGL / C++ (although not much happening there). The finished app is available at the above link. Haven't tested on anything but my own Macbook Pro, so use at your own risk :)

waldir/gluProject command sequence ( C++)

double modelview[16];
double projection[16];
int viewport[4];
double screenX, screenY, screenZ;

glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);

//you'll probably want to put this inside a loop, to get all the model's points
gluProject(modelPointX, modelPointY, modelPointZ,
           modelview, projection, viewport,
           &amp;screenX, &amp;screenY, &amp;screenZ);

This is the full sequence of commands needed to make a gluProject call to get the 2D projections of 3D points with the current scene parameters (projection, transformations, etc). Note that the coordinates are given in pixels relative to the viewport's location, not the computer screen!

If you need for further processing, you can access the viewport's dimensions by fetching viewport[0] (xOrigin, relative to the OpenGL window), viewport[1] (yOrigin), viewport[2] (width) and viewport[3] (height).

patelmitra/roll camera, no error in code, error when code runs ( Visual Basic)

#include <windows.h> ;
#include "../gl/glut.h";
#include<assert.h>;
#include <math.h>;
#include <gl/GL.h>;
#include <gl/GLU.h>;


//#include "camera.h"
Camera cam;  //global camera object

void teaPot(void);

class Point3 {

public:
	float x,y,z;
	void set(float dx, float dy, float dz) {x = dx; y = dy; z = dz;}
	void set(Point3& p){x = p.x; y = p.y; z = p.z;}
	Point3(float xx, float yy, float zz) {x = xx; y = yy; z = zz;}
	Point3(){x = y = z = 0;}
	void build4tuple(float v[])
	{
		v[0] = x; v[1] = y; v[2] = z; v[3] = 1.0f;
	}
};

class Vector3{
public:
	float x,y,z;
	void set(float dx, float dy, float dz) 
	{ x = dx; y = dy; z = dz;}
	void set(Vector3& v){x = v.x; y = v.y; z = v.z;}
	void flip() {x = -x; y = -y; z = -z;}
	void setDiff(Point3& a, Point3& b) {x = a.x - b.x; y = a.y - b.y; z = a.z - b.z;}
	void normalize();
	Vector3(float xx, float yy, float zz) {x = xx; y = yy; z = zz;}
	Vector3 (Vector3& v) {x = v.x; y = v.y; z = v.z;}
	Vector3() {x = y = z = 0;}
	Vector3 cross(Vector3 b);
	float dot(Vector3 b);
};


class Camera {

private:
	Point3 eye;
	Vector3 u,v,n;
	double viewAngle, aspect, nearDist, farDist;
	void setModelViewMatrix();

public:
	Camera();
	void set(Point3 Eye, Point3 look, Vector3 up);
	void roll(float angle);
	void pitch(float angle);
	void yaw(float angle);
	void slide(float delU, float delV, float delN);
	void setShape(float vAng, float asp, float nearD, float farD);

};

void Camera :: setModelViewMatrix(void)
{
	float m[16];
	Vector3 eVec(eye.x, eye.y, eye.z);
	m[0] = u.x;
	m[1] = v.x;
	m[2] = n.x;
	m[3] = 0;
	m[4] = u.y;
	m[5] = v.y;
	m[6] = n.y;
	m[7] = 0;
	m[8] = u.z;
	m[9] = v.z;
	m[10] = n.z;
	m[11] = 0;
	m[12] = -eVec.dot(u);
	m[13] = -eVec.dot(v);
	m[14] = -eVec.dot(n);
	m[15] = 1.0;
	glMatrixMode(GL_MODELVIEW);
	glLoadMatrixf(m);
}

void Camera :: set(Point3 Eye, Point3 look, Vector3 up)
{
	eye.set(Eye);
	n.set(eye.x - look.x, eye.y - look.y, eye.z - look.z);
	u.set(up.cross(n));
	n.normalize();
	u.normalize();
	v.set(n.cross(u));
	setModelViewMatrix();
}

void Camera :: slide(float delU, float delV, float delN)
{
	eye.x += delU * u.x + delV * v.x + delN * n.x;
	eye.y += delU * u.y + delV * v.y + delN * n.y;
	eye.z += delU * u.z + delV * v.z + delN * n.z;
	setModelViewMatrix();
}

void Camera :: roll(float angle)
{
	float cs = cos(3.14159265/180 * angle);
	float sn = sin(3.14159265/180 * angle);
	Vector3 t = u;
	u.set(cs*t.x - sn*v.x, cs*t.y - sn*v.y, cs*t.z - sn*v.z);
	v.set(sn*t.x + cs*v.x, sn*t.y + cs*v.y, sn*t.z + cs*v.z);
	setModelViewMatrix();
}

void axis(double length)
{   // draw a z-axis
       glPushMatrix();
       glBegin(GL_LINES);
            glVertex3d(0, 0, 0); 
            glVertex3d(0,0,length); // along the z-axis
       glEnd();
   // draw a cone at end
       glTranslated(0, 0,length -0.2);
       glutWireCone(0.04, 0.2, 12, 9);
       glPopMatrix();
}  



void myKeyboard(unsigned char key, int x, int y)
{
	switch(key)
	{
	case 'f':
		cam.slide(0, 0, 0.2);
		break;

	case 'f'-64:
		cam.slide(0, 0, -0.2);
		break;

	case 'p':
		cam.roll(-1.0);
		break;

	case 'p'-64:
		cam.roll(1.0);
		break;
	}
	glutPostRedisplay();

}

//<<<<<<<<<< displayWire >>>>>>>>>>>>>>>>>>>>>>
void displaySceen(void)
{
// set the view volume shape and size
       glMatrixMode(GL_PROJECTION); 
       glLoadIdentity();
       glOrtho(-2.0*64/48.0, 2.0*64/48.0, -2.0, 2.0, 0.1, 100);
// To Do: Change the view volume

	   // position and aim the camera       
	   glMatrixMode(GL_PROJECTION);
	   glLoadIdentity();
	   double winHt = 1.0;
	   glOrtho(-winHt*64/48.0, winHt*64/48.0, -winHt, winHt, 0.1, 100.0);	   
	   glMatrixMode(GL_MODELVIEW); 
       glLoadIdentity();
       gluLookAt(2.3, 1.3, 2, 0.30, 0.25, 0.30, 0.0, 1.0, 0.25);
       //start drawing
	   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	   glPushMatrix();
	   glTranslated(0.4, 0.4, 0.6);
	   glScaled(0.5, 0.5, 0.5);

	   //set properties of the surface material
	   GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f};
	   GLfloat mat_diffuse[] = {0.6f, 0.6f, 0.6f, 1.0f};
	   GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f};
	   GLfloat mat_shininess[] = {50.0f};

	   glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
	   glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
	   glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
	   glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);

	   //set the light source properties
	   GLfloat lightIntensity[] = {0.7f, 0.7f, 0.7f, 1.0f};
	   GLfloat light_position[] = {2.0f, 6.0f, 3.0f, 0.0f};
	   glLightfv(GL_LIGHT0, GL_POSITION, light_position);
	   glLightfv(GL_LIGHT0, GL_DIFFUSE, lightIntensity);
// To Do: Change the position of the camera

// Draw the coordinate system 
       glPushMatrix();
	   glColor3d(1,0,0); // draw red line: z-axis
       axis(2);                         
       glRotated(90, 0, 1.0, 0);
       glColor3d(0,1,0); // draw green line: y-axis
       axis(2);                         
       glRotated(-90.0, 1, 0, 0);
       glColor3d(0,0,1); // draw blue line: x-axis
       axis(2);                         
       glPopMatrix();
 

	   teaPot();
	   
       glFlush();

}

// tableleg
	   void tableLeg(double thick, double len)
	   {
		glPushMatrix();
		glTranslated(0, len/2, 0);
		glScaled(thick, len, thick);
		glutSolidCube(1.0);
		glPopMatrix();
	   
	   }

	   void table(double topWid, double topThick, double legThick, double legLen)
	   {
		glPushMatrix();
		glTranslated(0, legLen, 0);
		glScaled(topWid, topThick, topWid);
		glutSolidCube(1.0);
		glPopMatrix();
		double dist = 0.95 * topWid/2.0 - legThick / 2.0;
		glPushMatrix();
		glTranslated(dist, 0, dist);
		tableLeg(legThick, legLen);
		glTranslated(0, 0, -2 * dist);
		tableLeg(legThick, legLen);
		glTranslated(-2 * dist, 0, 2*dist);
		tableLeg(legThick, legLen);
		glTranslated(0, 0, -2*dist);
		tableLeg(legThick, legLen);
		glPopMatrix();
	   }

void teaPot(void)
{
	glClear(GL_COLOR_BUFFER_BIT||GL_DEPTH_BUFFER_BIT);
	glPushMatrix();
	glPopMatrix();
	//glBegin();
	glTranslated(0.60, 0.50, 0.20);
	glRotated(20, 0, 1, 0);
	glColor3d(1,0,1);
	glutSolidTeapot(0.5);
	
	glPopMatrix();
	glPushMatrix();
	glTranslated(0.4, 0, 0.4);
	table(0.6, 0.02, 0.02, 0.3);

	glFlush();
	glutSwapBuffers();
}


void main(int argc, char **argv)
{
       glutInit(&argc, argv);
       glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
       glutInitWindowSize(640,480);
       glutInitWindowPosition(100, 100);
       glutCreateWindow("The Teapot");
	   glutKeyboardFunc(myKeyboard);
       glutDisplayFunc(displaySceen);
	   glEnable(GL_LIGHTING);
	   glEnable(GL_LIGHT0);
	   glShadeModel(GL_SMOOTH);
	   glEnable(GL_DEPTH_TEST);
	   glEnable(GL_NORMALIZE);
	   glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
	   glViewport(0, 0, 640, 480);
	   cam.set(4, 0, 1);
	   cam.setShape(30.0f, 64.0f/48.0f, 0.5f, 50.0f);
       glutMainLoop();
}

I am trying to roll and slide the camera around 3d object using openGL. There is no error in code but when i run it shows following errors: c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(2): warning C4067: unexpected tokens following preprocessor directive - expected a newline 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(3): warning C4067: unexpected tokens following preprocessor directive - expected a newline 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(4): warning C4067: unexpected tokens following preprocessor directive - expected a newline 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(5): warning C4067: unexpected tokens following preprocessor directive - expected a newline 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(6): warning C4067: unexpected tokens following preprocessor directive - expected a newline 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(7): warning C4067: unexpected tokens following preprocessor directive - expected a newline 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(11): error C2146: syntax error : missing ';' before identifier 'cam' 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(181): error C2228: left of '.slide' must have class/struct/union 1> type is 'int' 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(185): error C2228: left of '.slide' must have class/struct/union 1> type is 'int' 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(189): error C2228: left of '.roll' must have class/struct/union 1> type is 'int' 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(193): error C2228: left of '.roll' must have class/struct/union 1> type is 'int' 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(328): error C2228: left of '.set' must have class/struct/union 1> type is 'int' 1>c:\mitradocs\graphicsassignment\computergraphics\final\final.cpp(329): error C2228: left of '.setShape' must have class/struct/union 1> type is 'int'

nesium/3D to 2D coordinates ( Other)

static void __gluMultMatrixVecd(const GLdouble matrix[16], const GLdouble in[4],
		      GLdouble out[4])
{
    int i;

    for (i=0; i<4; i++) {
	out[i] = 
	    in[0] * matrix[0*4+i] +
	    in[1] * matrix[1*4+i] +
	    in[2] * matrix[2*4+i] +
	    in[3] * matrix[3*4+i];
    }
}

GLint GLAPIENTRY
gluProject(GLdouble objx, GLdouble objy, GLdouble objz, 
	      const GLdouble modelMatrix[16], 
	      const GLdouble projMatrix[16],
              const GLint viewport[4],
	      GLdouble *winx, GLdouble *winy, GLdouble *winz)
{
    double in[4];
    double out[4];

    in[0]=objx;
    in[1]=objy;
    in[2]=objz;
    in[3]=1.0;
    __gluMultMatrixVecd(modelMatrix, in, out);
    __gluMultMatrixVecd(projMatrix, out, in);
    if (in[3] == 0.0) return(GL_FALSE);
    in[0] /= in[3];
    in[1] /= in[3];
    in[2] /= in[3];
    /* Map x, y and z to range 0-1 */
    in[0] = in[0] * 0.5 + 0.5;
    in[1] = in[1] * 0.5 + 0.5;
    in[2] = in[2] * 0.5 + 0.5;

    /* Map x,y to viewport */
    in[0] = in[0] * viewport[2] + viewport[0];
    in[1] = in[1] * viewport[3] + viewport[1];

    *winx=in[0];
    *winy=in[1];
    *winz=in[2];
    return(GL_TRUE);
}

iamok/simple pyglet window for opengl ( Python)

from pyglet.gl import *

# Direct OpenGL commands to this window.
window = pyglet.window.Window()

@window.event
def on_draw():
    glClear(GL_COLOR_BUFFER_BIT)
    glLoadIdentity()
    glBegin(GL_TRIANGLES)
    glVertex2f(0, 0)
    glVertex2f(window.width, 0)
    glVertex2f(window.width, window.height)
    glEnd()

pyglet.app.run()

ozkriff/sdl+opengl test ( C++)

/*This source code copyrighted by Lazy Foo' Productions (2004-2008) and may not

be redestributed without written permission.*/





/*compillig on riff's system:

	g++ main.cpp -lGL -lGLU -lSDL -I/usr/include/SDL -o test

*/



//The headers

#include "SDL/SDL.h"

#include "SDL/SDL_opengl.h"



//Screen attributes

const int SCREEN_WIDTH = 800;

const int SCREEN_HEIGHT = 600;

const int SCREEN_BPP = 32;



//The frame rate

const int FRAMES_PER_SECOND = 60;



//The attributes of the square

const int SQUARE_WIDTH = 20;

const int SQUARE_HEIGHT = 20;



//Event handler

SDL_Event event;



//The square

class Square

{

    private:

    //The offsets

    int x, y;



    //The velocity of the square

    int xVel, yVel;



    public:

    //Initializes

    Square();



    //Handles key presses

    void handle_input();



    //Moves the square

    void move();



    //Shows the square on the screen

    void show();

};



//The timer

class Timer

{

    private:

    //The clock time when the timer started

    int startTicks;



    //The ticks stored when the timer was paused

    int pausedTicks;



    //The timer status

    bool paused;

    bool started;



    public:

    //Initializes variables

    Timer();



    //The various clock actions

    void start();

    void stop();

    void pause();

    void unpause();



    //Gets the timer's time

    int get_ticks();



    //Checks the status of the timer

    bool is_started();

    bool is_paused();

};



bool init_GL()

{

    //Set clear color

    glClearColor( 0, 0, 0, 0 );



    //Set projection

    glMatrixMode( GL_PROJECTION );

    glLoadIdentity();

    glOrtho( 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1 );



    //Initialize modelview matrix

    glMatrixMode( GL_MODELVIEW );

    glLoadIdentity();



    //If there was any errors

    if( glGetError() != GL_NO_ERROR )

    {

        return false;

    }



    //If everything initialized

    return true;

}



bool init()

{

    //Initialize SDL

    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )

    {

        return false;

    }



    //Create Window

    if( SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL ) == NULL )

    {

        return false;

    }



    //Initialize OpenGL

    if( init_GL() == false )

    {

        return false;

    }



    //Set caption

    SDL_WM_SetCaption( "OpenGL Test", NULL );



    return true;

}



void clean_up()

{

    //Quit SDL

    SDL_Quit();

}



Square::Square()

{

    //Initialize offsets

    x = 0;

    y = 0;



    //Initialize velocity

    xVel = 0;

    yVel = 0;

}



void Square::handle_input()

{

    //If a key was pressed

    if( event.type == SDL_KEYDOWN )

    {

        //Adjust the velocity

        switch( event.key.keysym.sym )

        {

            case SDLK_UP: yVel -= SQUARE_HEIGHT / 2; break;

            case SDLK_DOWN: yVel += SQUARE_HEIGHT / 2; break;

            case SDLK_LEFT: xVel -= SQUARE_WIDTH / 2; break;

            case SDLK_RIGHT: xVel += SQUARE_WIDTH / 2; break;

        }

    }

    //If a key was released

    else if( event.type == SDL_KEYUP )

    {

        //Adjust the velocity

        switch( event.key.keysym.sym )

        {

            case SDLK_UP: yVel += SQUARE_HEIGHT / 2; break;

            case SDLK_DOWN: yVel -= SQUARE_HEIGHT / 2; break;

            case SDLK_LEFT: xVel += SQUARE_WIDTH / 2; break;

            case SDLK_RIGHT: xVel -= SQUARE_WIDTH / 2; break;

        }

    }

}



void Square::move()

{

    //Move the square left or right

    x += xVel;



    //If the square went too far

    if( ( x < 0 ) || ( x + SQUARE_WIDTH > SCREEN_WIDTH ) )

    {

        //Move back

        x -= xVel;

    }



    //Move the square up or down

    y += yVel;



    //If the square went too far

    if( ( y < 0 ) || ( y + SQUARE_HEIGHT > SCREEN_HEIGHT ) )

    {

        //Move back

        y -= yVel;

    }

}



void Square::show()

{

    //Move to offset

    glTranslatef( x, y, 0 );



    //Start quad

    glBegin( GL_QUADS );



        //Set color to white

        glColor4f( 1.0, 1.0, 1.0, 1.0 );



        //Draw square

	    glVertex3f( 0,            0,             0 );

	    glVertex3f( SQUARE_WIDTH, 0,             0 );

	    glVertex3f( SQUARE_WIDTH, SQUARE_HEIGHT, 0 );

	    glVertex3f( 0,            SQUARE_HEIGHT, 0 );



    //End quad

    glEnd();



    //Reset

    glLoadIdentity();

}



Timer::Timer()

{

    //Initialize the variables

    startTicks = 0;

    pausedTicks = 0;

    paused = false;

    started = false;

}



void Timer::start()

{

    //Start the timer

    started = true;



    //Unpause the timer

    paused = false;



    //Get the current clock time

    startTicks = SDL_GetTicks();

}



void Timer::stop()

{

    //Stop the timer

    started = false;



    //Unpause the timer

    paused = false;

}



void Timer::pause()

{

    //If the timer is running and isn't already paused

    if( ( started == true ) &amp;&amp; ( paused == false ) )

    {

        //Pause the timer

        paused = true;



        //Calculate the paused ticks

        pausedTicks = SDL_GetTicks() - startTicks;

    }

}



void Timer::unpause()

{

    //If the timer is paused

    if( paused == true )

    {

        //Unpause the timer

        paused = false;



        //Reset the starting ticks

        startTicks = SDL_GetTicks() - pausedTicks;



        //Reset the paused ticks

        pausedTicks = 0;

    }

}



int Timer::get_ticks()

{

    //If the timer is running

    if( started == true )

    {

        //If the timer is paused

        if( paused == true )

        {

            //Return the number of ticks when the timer was paused

            return pausedTicks;

        }

        else

        {

            //Return the current time minus the start time

            return SDL_GetTicks() - startTicks;

        }

    }



    //If the timer isn't running

    return 0;

}



bool Timer::is_started()

{

    return started;

}



bool Timer::is_paused()

{

    return paused;

}



int main( int argc, char *argv[] )

{

    //Quit flag

    bool quit = false;



    //Initialize

    if( init() == false )

    {

        return 1;

    }



    //Our square object

    Square square;



    //The frame rate regulator

    Timer fps;



	//Wait for user exit

	while( quit == false )

	{

        //Start the frame timer

        fps.start();



        //While there are events to handle

		while( SDL_PollEvent( &amp;event ) )

		{

            //Handle key presses

            square.handle_input();



			if( event.type == SDL_QUIT )

			{

                quit = true;

            }

		}



	    //Move the square

	    square.move();



	    //Clear the screen

	    glClear( GL_COLOR_BUFFER_BIT );



	    //Show the square

	    square.show();



	    //Update screen

	    SDL_GL_SwapBuffers();



        //Cap the frame rate

        if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )

        {

            SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );

        }

	}



	//Clean up

	clean_up();



	return 0;

}

ozkriff/other_sdl_opengl ( C)

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
#include <math.h>

const int SCREEN_WIDTH 	= 640;
const int SCREEN_HEIGHT = 480;

//The attributes of the square
const int SQUARE_SIZE 	= 20;
const int SQUARE_SPEED 	= 100;

short int ROT_MOVE = 0; // must we move? [-1; 0; 1]
short int QUIT = 0; //QUIT flag [0; 1]

//The square
float
	x = 0, y = 0, 		//The offsets of the square
	xVel = 0, yVel = 0, 	//The velocity of the square
	rVel = 0, rotation = 0; //The rotation of the square

/* ------------------------------------------------------------------------- */
struct unit {
	float	x, y,
		rot_vel, rot,
		size,
		speed;
	short int
		move, // must we move? [-1; 0; 1]
		live;
};

/* ------------------------------------------------------------------------- */
int init_GL()
{
	glClearColor( 0, 0, 0, 0 ); //Set clear color

	//Set projection
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	glOrtho( 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1 );

	//Initialize modelview matrix
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();


	if ( glGetError() != GL_NO_ERROR ) { //If there was any errors
		return 1;
	}

	return 0; //If everything initialized
}

/* ------------------------------------------------------------------------- */
int init()
{
	if ( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) {
		return 1;
	}

	//Create Window
	if ( SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT,
			32, SDL_OPENGL ) == NULL ) {
		return 2;
	}

	if ( init_GL() != 0 ) {
		return 3;
	}

	SDL_WM_SetCaption( "OpenGL Test", NULL );

	return 0;
}

/* ------------------------------------------------------------------------- */
void square_handle_input ( SDL_Event event )
{
	if ( event.type == SDL_KEYDOWN )      //If a key was pressed
		switch ( event.key.keysym.sym )        {
			case SDLK_UP:   yVel -= SQUARE_SPEED; break;
			case SDLK_DOWN: yVel += SQUARE_SPEED; break;
			case SDLK_LEFT: xVel -= SQUARE_SPEED; break;
			case SDLK_RIGHT:xVel += SQUARE_SPEED; break;

			case SDLK_w:    ROT_MOVE = 1;         break;
			case SDLK_a:    rVel -= 120;          break;
			case SDLK_s:    ROT_MOVE = -1;        break;
			case SDLK_d:    rVel += 120;          break;

			case SDLK_q:    QUIT = 1;             break;

			default: break;
		}
	else if ( event.type == SDL_KEYUP )     //If a key was released
		switch ( event.key.keysym.sym ) {
			case SDLK_UP:   yVel += SQUARE_SPEED; break;
			case SDLK_DOWN: yVel -= SQUARE_SPEED; break;
			case SDLK_LEFT: xVel += SQUARE_SPEED; break;
			case SDLK_RIGHT:xVel -= SQUARE_SPEED; break;

			case SDLK_w:    ROT_MOVE = 0;         break;
			case SDLK_a:    rVel += 120;          break;
			case SDLK_s:    ROT_MOVE = 0;         break;
			case SDLK_d:    rVel -= 120;          break;

			default: break;
		}
}

/* ------------------------------------------------------------------------- */
void square_move ( Uint32 d_time )
{
	rotation += rVel * ( d_time / 1000.f );
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#if 0
	x += xVel * ( d_time / 1000.f );     //Move the square <->
	if ( ( x < 0 ) || ( x + SQUARE_SIZE > SCREEN_WIDTH ) ) //If too far
		x -= xVel* ( d_time / 1000.f ); //Move back

	y += yVel * ( d_time / 1000.f ); //Move the square up or down
	if ( ( y < 0 ) || ( y + SQUARE_SIZE > SCREEN_HEIGHT ) ) //If too far
		y -= yVel* ( d_time / 1000.f ); //Move back
#endif
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
	x += ( SQUARE_SPEED * sinf(rotation*M_PI/180.0f) )
			* ( d_time / 1000.f )  * ROT_MOVE;

	y -= ( SQUARE_SPEED * cosf(rotation*M_PI/180.0f) )
			* ( d_time / 1000.f )  * ROT_MOVE;
}

/* ------------------------------------------------------------------------- */
void square_show()
{
	//Move to offset
	glTranslatef( x, y, 0 );
	glRotatef( rotation, 0, 0, 1);

	glBegin( GL_QUADS );
	{
		glColor4f( 1.0, 1.0, 1.0, 1.0 ); //Set color to white

		glVertex3f( -SQUARE_SIZE, -SQUARE_SIZE, 0 );
		glVertex3f(  SQUARE_SIZE, -SQUARE_SIZE, 0 );
		glVertex3f(  SQUARE_SIZE,  SQUARE_SIZE, 0 );
		glVertex3f( -SQUARE_SIZE,  SQUARE_SIZE, 0 );
	}
	glEnd();

	glLoadIdentity(); //Reset
}


/* ------------------------------------------------------------------------- */
int main ( int argc, char *argv[] )
{
	//Initialize
	if ( init() != 0 )
		return 1;

	SDL_Event event; //Event handler

	int timer = 0;
	timer = SDL_GetTicks();
	struct unit player;

	player.x=0,
	player.y=0,
	player.rot_vel=0,
	player.rot=0,
	player.size=15,
	player.speed=120;
	player.move=0, // must we move? [-1; 0; 1]
	player.live=1; // [0;1]


	while ( QUIT == 0 ) {
		/* While there are events to handle. */
		while ( SDL_PollEvent(&amp;event) ) {
			square_handle_input(event); //Handle key presses
			if ( event.type == SDL_QUIT )
				QUIT = 1;
		}
		square_move( SDL_GetTicks() - timer );
		timer = SDL_GetTicks();

		glClear( GL_COLOR_BUFFER_BIT ); //Clear the screen

		square_show();

		SDL_GL_SwapBuffers(); //Update screen
	}

	SDL_QUIT();

	return 0;
}

strange, but it's working.

ozkriff/sdl_opengl_2 ( C)

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
#include <math.h>

int SCREEN_WIDTH  = 640;
int SCREEN_HEIGHT = 480;

int QUIT = 0;


#define	DEAD	0
#define	NORMAL	1
#define INJURED 2

#define	PLAYER	0
#define	ENEMY	1
#define BULLET	2


/* -------------------------------<  UNIT  >-------------------------------- */

typedef struct 
{
	float	x, y,
		rot_vel, rot,
		size,
		speed;
	short int
		type,
		state;
	struct node
		next;
} struct node;


/* -----------------------------<  LIST_ADD  >------------------------------ */

struct node* list_add ( 
		struct node** p,
		const float x, 
		const float y,
		const float rot_vel, 
		const float rot,
		const float size,
		const float speed;
		const short int type,
		const short int state ) 
{
	struct node* n = malloc( sizeof(struct node) );
	if (n == NULL) {
		puts( "Can't add new item. Something with memory." );
		return NULL;
	}

	n->next = *p; /* The previous elm (*p) becomes the "next" element. */
	*p = n;       /* Add new empty element to the head of the list.    */

	n->x		= x;
        n->y		= y;
        n->rot_vel	= rot_vel;
        n->rot		= rot;
	n->size		= size;    
        n->speed	= speed;
	n->type		= type;
	n->state	= state;

	return *p;
}      

/* ---------------------------<  LIST_REMOVE  >----------------------------- */

void list_remove ( struct node** p )
{
	if (*p != NULL) {
		struct node* n = *p;
		*p = (*p)->next;
		free (n);
	}
}


/* -----------------------------<  INIT_GL  >------------------------------- */

int init_GL ()
{
	glClearColor ( 0, 0, 0, 0 );

	/* Set projection. */
	glMatrixMode ( GL_PROJECTION );
	glLoadIdentity ();
	glOrtho ( 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1 );

	/* Initialize modelview matrix. */
	glMatrixMode ( GL_MODELVIEW );
	glLoadIdentity ();


	if ( glGetError() != GL_NO_ERROR ) { /* If there was any errors. */
		return 1;
	}

	return 0; /* If everything initialized. */
}


/* -------------------------------<  INIT  >-------------------------------- */

int init ()
{
	if ( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) {
		return 1;
	}

	/* Create Window. */
	if ( SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT,
			32, SDL_OPENGL ) == NULL ) {
		return 2;
	}

	if ( init_GL() != 0 ) {
		return 3;
	}

	SDL_WM_SetCaption( "OpenGL Test", NULL );

	return 0;
}


/* ------------------------------<  SHOOT  >-------------------------------- */

int shoot ()
{
	return 0;
}


/* ---------------------------<  HANDLE_INPUT  >---------------------------- */

void handle_input ( SDL_Event event, struct struct node* object )
{
	if ( event.type == SDL_KEYDOWN )      /* If a key was pressed. */
		switch ( event.key.keysym.sym ) {
			case SDLK_w:	object->speed	= 60;	break;
			case SDLK_a:	object->rot_vel	-= 120;	break;
			case SDLK_s:	object->speed	= -60;	break;
			case SDLK_d:	object->rot_vel	+= 120;	break;

			case SDLK_q:	QUIT		= 1;	break;
			case SDLK_e:	object->shooting= 1;	break;

			default: break;
		}
	else if ( event.type == SDL_KEYUP )     /* If a key was released. */
		switch ( event.key.keysym.sym ) {
			case SDLK_w:	object->speed	= 0;	break;
			case SDLK_a:	object->rot_vel	+= 120;	break;
			case SDLK_s:	object->speed	= 0;	break;
			case SDLK_d:	object->rot_vel	-= 120;	break;

			case SDLK_e:    object->shooting= 0;	break;

			default: break;
		}
}


/* ---------------------------<  MOVE_OBJECT  >----------------------------- */

void move_object ( Uint32 d_time, struct struct node* object )
{
	object->rot += object->rot_vel * ( d_time / 1000.f );

	object->x += ( object->speed * sinf(object->rot*M_PI/180.0f) )
			* (d_time/1000.f);
	if 	( object->x < 0 )		object->x = 0;
	else if ( object->x > SCREEN_WIDTH )	object->x = SCREEN_WIDTH;

	object->y -= ( object->speed * cosf(object->rot*M_PI/180.0f) )
			* (d_time/1000.f);
	if 	( object->y < 0 )		object->y = 0;
	else if ( object->y > SCREEN_HEIGHT )	object->y = SCREEN_HEIGHT;
}


/* --------------------------<  PROCESS_SHOOTS  >--------------------------- */

void process_shoots ( struct struct node* object, struct struct node* bullet, struct struct node* enemy )
{
	if ( object->shooting == 1 ) {
		bullet->rot 	= object->rot;
		bullet->x 	= object->x;
		bullet->y 	= object->y;	float	x, y,
		rot_vel, rot,
		size,
		speed;
		bullet->speed 	= object->speed + 60;
		bullet->live	= 1;
	}

	if ( ( enemy->x == bullet->x ) &amp;&amp; ( enemy->y == bullet->y ) )
		enemy->live = 0;
}

/* ---------------------------<  DRAW_OBJECT  >----------------------------- */

void draw_object ( node* object )
{
	glTranslatef ( object->x, object->y, 0 );
	glRotatef ( object->rot, 0, 0, 1);

	if ( object->live == 0 )
		return;

	glBegin ( GL_QUADS );
	{
		if ( object->type == 0 )
			glColor4f ( 1.0, 1.0, 1.0, 1.0 );
		if ( object->type == 1 ) /* enemy. */
			glColor4f ( 1.0, 0.0, 1.0, 1.0 );
		else
			glColor4f ( 1.0, 0.5, 0.5, 1 );

		glVertex2f ( -object->size, -object->size );
		glVertex2f (  object->size, -object->size );
		glVertex2f (  object->size,  object->size );
		glVertex2f ( -object->size,  object->size );
	}
	glEnd ();

	glLoadIdentity (); /* Reset. */
}


/* -------------------------------<  MAIN  >-------------------------------- */

int main ( int argc, char *argv[] )
{

	SDL_Event event; /* Event handler. */
	Uint32	timer = 0,
		d_time = 0;
	timer = SDL_GetTicks();

	struct node* enemy  = NULL;
	struct node* bullet = NULL;
	struct node  player = {
		100, 100,	/* x, y		*/
		0, 0,		/* rot_vel, rot	*/
		15,		/* size		*/
		0,		/* speed	*/
		PLAYER,		/* type		*/
		NORMAL,		/* state 	*/
		NULL 		/* NEXT		*/
	};
/* -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - */



/* -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - */
	if ( init() != 0 )
		return 1;

	while ( QUIT == 0 ) {
		/* While there are events to handle. */
		while ( SDL_PollEvent(&amp;event) ) {
			handle_input ( event, &amp;player );
			if ( event.type == SDL_QUIT )
				QUIT = 1;
		}
		d_time = SDL_GetTicks () - timer;
		move_object ( d_time, &amp; player );
		move_object ( d_time, &amp; enemy  );
		move_object ( d_time, &amp; bullet );

		process_shoots ( &amp; player, &amp; bullet, &amp; enemy );
		timer = SDL_GetTicks ();

		glClear ( GL_COLOR_BUFFER_BIT ); /* Clear the screen. */
		draw_object ( &amp; player );
		draw_object ( &amp; enemy  );
		draw_object ( &amp; bullet );
		SDL_GL_SwapBuffers (); /* Update screen. */
	}

	SDL_Quit ();

	return 0;
}

модульность++;

ozkriff/sdl_opengl ( C)

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
/* #include "SDL/SDL_image.h" */
#include <math.h>
#include <stdio.h>

#define SCREEN_WIDTH  640
#define SCREEN_HEIGHT 480
#define SCREEN_BPP     16

#define V_COUNT	 5000
#define VT_COUNT 5000
#define F_COUNT	 5000

int v_count = 0;
int vt_count = 0;
int f_count = 0;

typedef struct
{
	struct { float x, y, z; } vertexes[V_COUNT]; 
	struct { float u, v; } text_coords[VT_COUNT]; 
	struct { int v1, v2, v3, vt1, vt2 , vt3; } faces[F_COUNT];
} model;
model mdl;

SDL_Surface *surface;
int video_flags; /* Flags to pass to SDL_SetVideoMode */

int done = 0; /* Main loop variable. */

GLfloat	x_rot;
GLfloat	y_rot;
GLfloat	z_rot;

GLuint texture[1]; /* Storage for one texture. */

void
quit (int return_code)
{
	SDL_Quit();		/* clean up the window    */
	exit(return_code);	/* and exit appropriately */
}


int load_gl_textures () /* load in bitmap as a GL texture */
{
	int Status = 0; 	/* Status indicator */

	SDL_Surface *TextureImage[1];

	/* Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit */
	TextureImage[0] = SDL_LoadBMP("soldat.bmp");
	if (TextureImage[0]) 
	{
		Status = 1; 
		glGenTextures ( 1, &amp;texture[0] );  /* Create The Texture */
		/* Typical Texture Generation Using Data From The Bitmap */
		glBindTexture ( GL_TEXTURE_2D, texture[0] );
		/* Generate The Texture */
		glTexImage2D ( GL_TEXTURE_2D, 0, 3, TextureImage[0]->w,
				TextureImage[0]->h, 0, GL_BGR,
				GL_UNSIGNED_BYTE, TextureImage[0]->pixels );
		/* Linear Filtering */
		glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
				GL_LINEAR );
		glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
				GL_LINEAR );
	}

	if ( TextureImage[0] )
		SDL_FreeSurface ( TextureImage[0] );

	return Status;
}


/* reset viewport after a window resize */
int resize_window ( int width, int height )
{
	GLfloat ratio;
	if ( height == 0 ) 
		height = 1;
	ratio = (GLfloat) width / (GLfloat) height;

	glViewport ( 0, 0, (GLint) width, (GLint) height );

	glMatrixMode ( GL_PROJECTION ); /* Change to the projection matrix */
	glLoadIdentity ();
	gluPerspective ( 45.0f, ratio, 0.1f, 100.0f ); /* set viewing volume. */

	/* Make sure we're chaning the model view and not the projection */
	glMatrixMode ( GL_MODELVIEW ); /* just to make sure */
	glLoadIdentity ();

	return 1;
}


void hanlde_events ( SDL_Event event )
{
	switch ( event.type ) {
		case SDL_VIDEORESIZE:
			surface = SDL_SetVideoMode ( event.resize.w,
					event.resize.h,
					16, video_flags );
			if ( !surface ) {
				fprintf ( stderr, "no surface after resize: %s\n",
						SDL_GetError() );
				quit (1);
			}
			resize_window ( event.resize.w, event.resize.h );
			break;
		case SDL_KEYDOWN:
			switch ( event.key.keysym.sym ) {
				case SDLK_q:
				case SDLK_ESCAPE:
					done = 1;
					quit (0);
					break;
				case SDLK_F1:
					SDL_WM_ToggleFullScreen ( surface );
					break;
				default:
					break;
			}
			break;
		case SDL_QUIT:
			done = 1;
			break;
		default:
			puts ("unknown event!");
			break;
	}
}


int init_opengl ( GLvoid )
{
	if (!load_gl_textures())
		return 0;

	glEnable ( GL_TEXTURE_2D );
	glShadeModel ( GL_SMOOTH );
	glClearColor ( 0.0f, 0.0f, 0.0f, 0.5f );
	glClearDepth ( 1.0f );
	glEnable ( GL_DEPTH_TEST );
	glDepthFunc ( GL_LEQUAL );  /* The Type Of Depth Test To Do */
	/* Really Nice Perspective Calculations */
	glHint ( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );

	return 1;
}


/* --- */
int read_obj_file () 
{
	float resize_coefficient;
	// char filename[] = "cube.obj";
	char filename[] = "soldat.obj";
	// char filename[] = "elephav.obj";
	char buffer[100];
	FILE* obj_file = NULL;
	obj_file = fopen ( filename, "r" );

	if ( obj_file == NULL )
		return 1;

	while ( fgets (buffer, 100, obj_file) ) {
		/* puts(buffer); */

		/* vertex coords */
		if ( buffer[0] == 'v' &amp;&amp; buffer [1] == ' ' ) {
			sscanf ( buffer, "v %f %f %f",
					 &amp;mdl.vertexes[v_count].x,
					 &amp;mdl.vertexes[v_count].y,
					 &amp;mdl.vertexes[v_count].z );

#if 1
			//resize_coefficient = 0.002;
			resize_coefficient = 0.6;
			mdl.vertexes[v_count].x *= resize_coefficient;
			mdl.vertexes[v_count].y *= resize_coefficient;
			mdl.vertexes[v_count].z *= resize_coefficient;
#endif
			v_count++;
		}

		/* vertex normals */
		else if ( buffer[0] == 'v' &amp;&amp; buffer[1] == 'n' ) {
			/* TODO */
		}


		/* texture coords */
		else if ( buffer[0] == 'v' &amp;&amp; buffer[1] == 't' ) {
			sscanf ( buffer, "vt %f %f",
					 &amp;mdl.text_coords[vt_count].v,
					 &amp;mdl.text_coords[vt_count].u );
			vt_count++;
		}

		/* faces */
		else if ( buffer[0] == 'f' &amp;&amp; buffer [1] == ' ' ) {
			// sscanf ( buffer, "f %i %i %i",
			sscanf ( buffer, "f %i/%i %i/%i %i/%i",
			// sscanf ( buffer, "f %i//%i %i//%i %i//%i",
					 &amp;mdl.faces[f_count].v1,
					 &amp;mdl.faces[f_count].vt1,
					 &amp;mdl.faces[f_count].v2,
					 &amp;mdl.faces[f_count].vt2,
					 &amp;mdl.faces[f_count].v3,
					 &amp;mdl.faces[f_count].vt3 );
			f_count++;
		}
	}

#if 1
	printf ( "vertex_count: %i\n", v_count );
	printf ( "text_coords_count: %i\n", vt_count );
	printf ( "f_count: %i\n", f_count );
#endif

	fclose ( obj_file );
	return 0;
}


int draw ( GLvoid )
{
	int ii = 0;
	/* These are to calculate our fps */
	static GLint T0     = 0;
	static GLint Frames = 0;

	glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	glLoadIdentity ();
	glTranslatef ( 0.0f, 0.0f, -5.0f ); /* Move Into The Screen 5 Units */
	glRotatef ( x_rot, 1.0f, 0.0f, 0.0f );
	glRotatef ( y_rot, 0.0f, 1.0f, 0.0f );
	glRotatef ( z_rot, 0.0f, 0.0f, 1.0f );

	glBindTexture ( GL_TEXTURE_2D, texture[0] ); /* Select Texture */

	/* NOTE:
	 *   The x coordinates of the glTexCoord2f function need to inverted
	 * for SDL because of the way SDL_LoadBmp loads the data. So where
	 * it has glTexCoord2f( 1.0f, 0.0f ); it should now read 
	 * glTexCoord2f( 0.0f, 0.0f );
	 */

	glBegin ( GL_TRIANGLES );
	{
		for ( ii = 0; ii < f_count; ii++ ) {
			/* TODO: remake whole structure */
			glTexCoord2f ( mdl.text_coords[ mdl.faces[ii].vt1 ].u,
					mdl.text_coords[ mdl.faces[ii].vt1 ].v );
			glVertex3f ( mdl.vertexes[ mdl.faces[ii].v1 ].x,
					mdl.vertexes[ mdl.faces[ii].v1 ].y,
					mdl.vertexes[ mdl.faces[ii].v1 ].z );

			glTexCoord2f ( mdl.text_coords[ mdl.faces[ii].vt2 ].u,
					mdl.text_coords[ mdl.faces[ii].vt2 ].v );
			glVertex3f ( mdl.vertexes[ mdl.faces[ii].v2 ].x,
					mdl.vertexes[ mdl.faces[ii].v2 ].y,
					mdl.vertexes[ mdl.faces[ii].v2 ].z );

			glTexCoord2f ( mdl.text_coords[ mdl.faces[ii].vt3 ].u,
					mdl.text_coords[ mdl.faces[ii].vt3 ].v );
			glVertex3f ( mdl.vertexes[ mdl.faces[ii].v3 ].x,
					mdl.vertexes[ mdl.faces[ii].v3 ].y,
					mdl.vertexes[ mdl.faces[ii].v3 ].z );
		}
	}
	glEnd ();

	SDL_GL_SwapBuffers (); 	/* Draw it to the screen */

	/* Gather FPS */
	Frames++;
	{
		GLint t = SDL_GetTicks ();

		if ( t - T0 >= 5000 ) {
			GLfloat seconds = ( t - T0 ) / 1000.0;
			GLfloat fps = Frames / seconds;
			printf ( "%d frames in %g seconds = %g FPS\n", 
					Frames, seconds, fps );
			T0 = t;
			Frames = 0;
		}
	}

	x_rot += 0.03f;
	y_rot += 0.03f;
	z_rot += 0.03f;

	return 1;
}


int init_sdl ()
{
	const SDL_VideoInfo *videoInfo; /*  holds info about display */

	if ( SDL_Init ( SDL_INIT_VIDEO ) < 0 ) {
		fprintf ( stderr, "Video initialization failed: %s\n",
				  SDL_GetError () );
		quit (1);
	}

	videoInfo = SDL_GetVideoInfo ();	/* Fetch the video info */

	if ( !videoInfo ) {
		fprintf ( stderr, "Video query failed: %s\n",
				  SDL_GetError() );
		quit (1);
	}

	/* the flags to pass to SDL_SetVideoMode */
	video_flags  = SDL_OPENGL;
	video_flags |= SDL_GL_DOUBLEBUFFER;
	video_flags |= SDL_HWPALETTE;       /* Store the palette in hardware */
	// video_flags |= SDL_RESIZABLE;       /* Enable window resizing */

	if ( videoInfo->hw_available )
		video_flags |= SDL_HWSURFACE;
	else
		video_flags |= SDL_SWSURFACE;

	if ( videoInfo->blit_hw ) /* checks if hardware blits can be done */
		video_flags |= SDL_HWACCEL;

	/* OpenGL double buffering */
	SDL_GL_SetAttribute ( SDL_GL_DOUBLEBUFFER, 1 );

	/* get a SDL surface */
	surface = SDL_SetVideoMode ( SCREEN_WIDTH, SCREEN_HEIGHT, 
			SCREEN_BPP, video_flags );

	if ( !surface ) {	/* Verify there is a surface */
		fprintf ( stderr,  "Video mode set failed: %s\n", 
				SDL_GetError() );
		quit (1);
	}

	resize_window ( SCREEN_WIDTH, SCREEN_HEIGHT );

	return 1;
}


int main ( int argc, char **argv )
{
	SDL_Event event; /* used to collect events */

	init_sdl ();
	init_opengl ();
	read_obj_file ();

	while ( !done ) {
		while ( SDL_PollEvent ( &amp;event ) ) 
			hanlde_events ( event ); 
		draw ();
	}

	quit (0); /* clean ourselves up and exit */

	return 0;
}

:'-(

balajeerc/Simple OpenGL ( C)

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "glew.h"
#include <GLUT/GLUT.h>
#include <cml/cml.h> 

#define DWASSERT(condition,printstatement)  if(!condition){ printf(printstatement); assert(condition); }

//We use some ugly globals for the time being

//Window Dimensions
int currentWindowWidth = 500;
int currentWindowHeight = 500;

cml::matrix44f *g_pModelViewProjMatrix;

//Function to assert any OpenGL errors
void DWGLErrorAssert()
{
	GLint err = glGetError();
	if (err == GL_NO_ERROR)
		return;
	
	printf("DW_ERROR: OpenGL error encountered!"
		   "Error Code: %d\n",err);	
	DWASSERT(false,"");
}

/////////////////////////////////////////////////////////////////
//	Shaders: Source, Compling and Linking
/////////////////////////////////////////////////////////////////
const char vertexShaderSrc[] = 
"uniform mat4 ProjectionModelviewMatrix;\n"
"attribute vec4 InVertex;\n"
"void main()\n"
"{\n"
"	gl_Position = ProjectionModelviewMatrix * InVertex;\n"
"}\n"
;

const char fragmentShaderSrc[] =
"void main()\n"
"{\n"
"	gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n"
"}\n"
;

struct Shader
{
	GLuint vertexShaderId;
	GLuint fragmentShaderId;
	GLuint shaderProgramId;
};

//Global shader pointer
Shader* g_pShader;

void GetErrorLog(int shaderId)
{
	GLint log_length;
    char *log;
	
	//glGetShaderiv returns a parameter from a shader object
	//We use it to get information regarding the log string
    glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &amp;log_length);
    
	//Allocate memory for the log error string
	log = new char[log_length+1];
	
	//Now we get the shader log string itself
    glGetShaderInfoLog(shaderId, log_length, NULL, log);
	
	//Dump the error to console
    printf("%s\n", log);
    delete [] log;
}

void LoadAndCompileShader(const char* shaderSource, GLuint* shaderId, GLenum shaderType)
{
	//Obtain length of source
	int shaderSourceLen = strlen(shaderSource);
	
	//Create shader
	*shaderId = glCreateShader(shaderType);	
	DWASSERT(shaderId!=0,"Unable to create shader\n");
	
	//Specify the shader source
    glShaderSource(*shaderId,					//Shader Id
				   1,							//Number of shaders required			
				   &amp;shaderSource,				//Shader source
				   &amp;shaderSourceLen);			//Character length of the source
	DWGLErrorAssert();
	
	//Compile the shader
    glCompileShader(*shaderId);	
	
	//We now check compilation status
	GLint shader_ok;
	glGetShaderiv(*shaderId, GL_COMPILE_STATUS, &amp;shader_ok);
    if (!shader_ok)
	{
		//Compilation failed
        printf("ERROR: Shader failed to compile. Error log follows:\n");
		GetErrorLog(*shaderId);
        glDeleteShader(*shaderId);
        DWASSERT(false,"");
    }
	DWGLErrorAssert();
}

void AttachAndLinkShaders(GLuint vertShaderId, GLuint fragShaderId, GLuint *shaderProgramId)
{
	//Create a new program ID
	*shaderProgramId = glCreateProgram();
	
	glAttachShader(*shaderProgramId, vertShaderId);
	glAttachShader(*shaderProgramId, fragShaderId);
	DWGLErrorAssert();
	
	//We can bind attribute variables here in case we are specifying 
	//the indices to bind to. Since we don't do that, and let GL implementation
	//assign the indices for attribute variables, we can bind buffers *after* linking the shader.
	//We query the ids bound during rendering via glGetAttribLocation
	glLinkProgram(*shaderProgramId);
	
	GLint program_ok;
	glGetProgramiv(*shaderProgramId, GL_LINK_STATUS, &amp;program_ok);
	if (!program_ok)
	{
		printf("Failed to link program with vertex and fragment shaders\n");
		GLint log_length;
		char *log;
		
		glGetProgramiv(*shaderProgramId, GL_INFO_LOG_LENGTH, &amp;log_length);
		log = new char[log_length+1];
		
		glGetProgramInfoLog(*shaderProgramId, log_length, NULL, log);
		
		//Dump the error to console
		printf("%s\n", log);
		
		delete [] log;
		
		glDeleteProgram(*shaderProgramId);
		DWASSERT(false,"");
	}
}

/////////////////////////////////////////////////////////////////
//	Plane: Geometry to be rendered on Scene using VBO
/////////////////////////////////////////////////////////////////
float planeHeight = 10;
float planeWidth = 10;

float planeVertices[] =
{
	-planeWidth/2, -planeHeight/2, 0.f,
	planeWidth/2, -planeHeight/2, 0.f,
	planeWidth/2,  planeHeight/2, 0.f,
	-planeWidth/2,  planeHeight/2, 0.f 
};

//Draw the rectanglular plane as two triangles
unsigned int planeIndices[] = 
{
	0, 3, 1,
	3, 2, 1
};

struct Plane
{
	GLuint vertexBufferId;
	GLuint elementBufferId;
};

//Global Plane pointer
Plane* g_pPlane;

void GenerateBuffers(Plane* pPlane)
{
	//First bind the vertex coordinates
	glGenBuffers(1, &amp;(pPlane->vertexBufferId));
	glBindBuffer(GL_ARRAY_BUFFER, pPlane->vertexBufferId);
	glBufferData(GL_ARRAY_BUFFER, 12*sizeof(float), planeVertices, GL_STATIC_DRAW);
	DWGLErrorAssert();
	
	//Now bind the indices
	glGenBuffers(1,&amp;(pPlane->elementBufferId));
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pPlane->elementBufferId);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6*sizeof(unsigned int), planeIndices, GL_STATIC_DRAW);	
	DWGLErrorAssert();
	
	// bind with 0 so that no buffers are left active/selected until necessary
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void DrawPlane(Plane* pPlane,Shader* pShader,cml::matrix44f *modelViewProjMatrix)
{	
	int shaderId = pShader->shaderProgramId;
	glUseProgram(shaderId);
	DWGLErrorAssert();
	
	int loc;
	loc = glGetUniformLocation(shaderId, "ProjectionModelviewMatrix");
	glUniformMatrix4fv(loc, 1, GL_FALSE, modelViewProjMatrix->data());
	
	int vertexLoc = glGetAttribLocation(shaderId, "InVertex");
	
	//Specify the vertex coordinates
	glBindBuffer(GL_ARRAY_BUFFER, pPlane->vertexBufferId);
	glVertexAttribPointer(
						  vertexLoc,			//attribute
						  3,                    //size 
						  GL_FLOAT,             //type
						  GL_FALSE,             //not normalized 
						  sizeof(GLfloat)*3,    //stride
						  (void*)0              //array buffer offset
						  );
	glEnableVertexAttribArray(vertexLoc);
	
	//Bind the index buffer before initiating draw
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pPlane->elementBufferId);
	DWGLErrorAssert();
	
	// Draw 2 triangles using just bound(activated) index array
	glDrawElements(GL_TRIANGLES, 24, GL_UNSIGNED_INT, 0);
	DWGLErrorAssert();
	
	//Deactivate array buffers
	glDisableVertexAttribArray(vertexLoc);		
	
	// bind with 0, so, switch back to normal pointer operation
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	DWGLErrorAssert();
}

//////////////////////////////////////////////////////////////////////////
//	GLUT specific code and callback functions
//////////////////////////////////////////////////////////////////////////
void display(void)
{
	DWGLErrorAssert();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	//Render Scene Code
	DrawPlane(g_pPlane, g_pShader,g_pModelViewProjMatrix);
	
	glutSwapBuffers();
}

void reshape(int width, int height)
{
    glViewport(0, 0, (GLsizei)width,(GLsizei)height);
	currentWindowWidth  = width;
	currentWindowHeight = height; 
}

void idle(void)
{
    glutPostRedisplay();
}

//////////////////////////////////////////////////////////////////////////
//	Application/Scene Setup and Initialisation
//////////////////////////////////////////////////////////////////////////
void InitApplication(Plane* pPlane,Shader* pShader)
{	
	glFrontFace(GL_CW);
	glDisable(GL_CULL_FACE);	
	glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
	glColor3f(1.f, 1.f, 1.f);
	glClearColor(0.f, 0.f, 1.f, 1.f);
		
	//Generate buffers for plane
	GenerateBuffers(pPlane);
	
	//Compile shader source
	LoadAndCompileShader(vertexShaderSrc, &amp;(pShader->vertexShaderId), GL_VERTEX_SHADER);
	LoadAndCompileShader(fragmentShaderSrc, &amp;(pShader->fragmentShaderId), GL_FRAGMENT_SHADER);
	
	//Link and attach shaders
	AttachAndLinkShaders(pShader->vertexShaderId, pShader->fragmentShaderId, &amp;(pShader->shaderProgramId));
	
	
	//Setup camera projection matrix
	cml::matrix44f projection;	//projection matrix (row major type)
	cml::matrix_perspective(projection,			//Projection matrix to set
							-1.0f,				//Left
							1.0f,				//Right
							-1.0f,				//Bottom
							1.0f,				//Top	
							1.0f,				//Near
							100.0f,				//Far
							cml::right_handed,	//Handedness
							cml::z_clip_neg_one //enum specifying near clipping range of the
							);					//canonical view volume for projection matrices	
	
	//Setup the camera view matrix
	//Setup view matrix
	cml::matrix44f view;		//view matrix (row major type)	
	cml::vector3f eye, target, up;
	eye.set(0.f,0.f,10.f);		// Set 'eye' to (0.f,0.f,10.f)
	target.set(0.f,0.f,0.f);    // Set 'target' to (0.f,0.f,0.f)
	up.set(0.f,1.f,0.f);		// Set 'up' to (0,1,0), the cardinal Y axis
	cml::matrix_look_at_RH(view, eye, target, up);	
		
	//Set the global pointers
	g_pPlane = pPlane;
	g_pShader = pShader;
	g_pModelViewProjMatrix = new cml::matrix44f();
	*g_pModelViewProjMatrix = projection*view;
	
	for (int i=0; i<4; i++)
	{
		for(int j=0;j<4;j++)
			printf("%f ", (*g_pModelViewProjMatrix)(i,j));
		
		printf("\n");
	}
	
}


int main(int argc, char** argv)
{	
	//Initialising GLUT
    glutInit(&amp;argc, argv);    
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(currentWindowWidth,currentWindowHeight);    
    glutCreateWindow("Trial GL");
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutIdleFunc(idle);
	DWGLErrorAssert();
	
	//Create a valid OpenGL rendering context and call glewInit()
	//to initialize the extension entry points. If glewInit() returns GLEW_OK,
	//the initialization succeeded and we can use the available extensions as
	//well as core OpenGL functionality.
	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		//Problem: glewInit failed, something is seriously wrong.
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
	}
	fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
	
	//Send message to console
    printf("Starting Application...\n");
	
	//Create plane
	struct Plane newPlane;
 	
	//Create shader
	struct Shader newShader;
	
	InitApplication(&amp;newPlane,&amp;newShader);
	
	//Start main loop
	glutMainLoop();
	
    return 0;
}

Sijo Mathew/OpenGL Error Printing ( C++)

GLenum errCode;
const GLubyte *errString;
if ((errCode = glGetError()) != GL_NO_ERROR)
{
    errString = gluErrorString(errCode);
    printf ("OpenGL Error: %s\n", errString);
}

To print the openGL Erorr in console

Desoxena/openGL particle system ( C++)

#include <time.h>
#include <cmath>
#include <Windows.h>
#include <glut.h>
#include <GL\GLU.h>
float limits = .4;
float X=0, Y=1;
const int MAX_PARTICLES = 2000;
const int MIN_PARTICLES = 10;
int currentParticle = 2000;
float posX[MAX_PARTICLES], posY[MAX_PARTICLES];
void moveParticles(int amount_of_particles) {
	srand (time (NULL) );
	float myX, myY;
	Sleep(150);
	for (int i = 0; i < amount_of_particles; i++) {
		myX = rand() % 3 + 1;
		myY = rand() % 3 + 1;
		if(myX==1 &amp;&amp; posX[i]<=limits ){posX[i]+=.01;}
		if(myX==2){posX[i]+=.00;}
		if(myX==3 &amp;&amp; posX[i]>=-limits){posX[i]-=.01;}
		if(myY==1 &amp;&amp; posY[i]<=limits){posY[i]+=.01;}
		if(myY==2){posY[i]+=.00;}
		if(myY==3 &amp;&amp; posY[i]>=-limits){posY[i]-=.01;}
		///////////////////////////////////////////
		if(myX==1 &amp;&amp; posX[i]>=limits ){posX[i]=0;}
		if(myX==2 &amp;&amp; posX[i]==limits){posX[i]=0;}
		if(myX==3 &amp;&amp; posX[i]<=-limits){posX[i]=0;}
		if(myY==1 &amp;&amp; posY[i]>=limits){posY[i]=0;}
		if(myY==2 &amp;&amp; posY[i]==limits){posY[i]=0;}
		if(myY==3 &amp;&amp; posY[i]<=-limits){posY[i]=0;}
	}
}
void Reshape(int height, int width) {
	glViewport(0, 0, width, height);
	glClearColor(0, 0, 0, 1);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(60, (float)height/(float)width, 1, 100);
	glMatrixMode(GL_MODELVIEW);
}
void Draw(void) {
	int thingy = 1;
	bool check = false;
	glClear(GL_COLOR_BUFFER_BIT);	
	if (check == false) {
		float R, G, B;
		glPushMatrix();
		glBegin(GL_POINTS);
		for (int i = 0; i < MAX_PARTICLES; i++) {
			R = rand() % 100 + 1;
			G = rand() % 100 + 1;
			B = rand() % 100 + 1;
			glColor3d(R*.01, G*.01, B*.01);
			glVertex3f(X, Y, -2);
			X = posX[i];
			Y = posY[i];
		}
		glEnd();
		glPopMatrix();
		check = true;
	}
	switch(thingy){
		case 1:
			moveParticles(currentParticle);
			glutPostRedisplay();
		break;
	}
	glutSwapBuffers();
}
void Keyboard(unsigned char key, int x, int y) {
	switch(key){
		case's': Y-=.01; glutPostRedisplay(); break;
	}
}
int main(int argc, char **argv) {
	glutInitDisplayMode(GLUT_DOUBLE);
	glutInit(&amp;argc, argv);
	glutInitWindowSize(500, 500);
	glutInitWindowPosition(100, 100);
	glutCreateWindow("SOME OPENGL PROJECTS");
	glutReshapeFunc(Reshape);
	glutDisplayFunc(Draw);
	glutKeyboardFunc(Keyboard);
	glutMainLoop();
}

Very simple openGL system; outputs points of random color, that wander randomly till they reach a certain point, and when they reach that certain point, the are taken back to the origin.