پاسخ : برنامه هایی گرافیكی ( OpenGL )
کد:
// TexGen.c
// OpenGL SuperBible
// Demonstrates OpenGL Texture Coordinate Generation
// Program by Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/gltools.h" // gltools library
// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;
GLuint toTextures[2]; // Two texture objects
int iRenderMode = 3; // Sphere Mapped is default
///////////////////////////////////////////////////////////////////////////////
// Reset flags as appropriate in response to menu selections
void ProcessMenu(int value)
{
// Projection plane
GLfloat zPlane[] = { 0.0f, 0.0f, 1.0f, 0.0f };
// Store render mode
iRenderMode = value;
// Set up textgen based on menu selection
switch(value)
{
case 1:
// Object Linear
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGenfv(GL_S, GL_OBJECT_PLANE, zPlane);
glTexGenfv(GL_T, GL_OBJECT_PLANE, zPlane);
break;
case 2:
// Eye Linear
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGenfv(GL_S, GL_EYE_PLANE, zPlane);
glTexGenfv(GL_T, GL_EYE_PLANE, zPlane);
break;
case 3:
default:
// Sphere Map
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
break;
}
glutPostRedisplay(); // Redisplay
}
///////////////////////////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Switch to orthographic view for background drawing
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0.0f, 1.0f, 0.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glBindTexture(GL_TEXTURE_2D, toTextures[1]); // Background texture
// We will specify texture coordinates
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
// No depth buffer writes for background
glDepthMask(GL_FALSE);
// Background image
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(0.0f, 1.0f);
glEnd();
// Back to 3D land
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
// Turn texgen and depth writing back on
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glDepthMask(GL_TRUE);
// May need to swtich to stripe texture
if(iRenderMode != 3)
glBindTexture(GL_TEXTURE_2D, toTextures[0]);
// Save the matrix state and do the rotations
glPushMatrix();
glTranslatef(0.0f, 0.0f, -2.0f);
glRotatef(xRot, 1.0f, 0.0f, 0.0f);
glRotatef(yRot, 0.0f, 1.0f, 0.0f);
// Draw the tours
gltDrawTorus(0.35, 0.15, 61, 37);
// Restore the matrix state
glPopMatrix();
// Display the results
glutSwapBuffers();
}
///////////////////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
GLbyte *pBytes; // Texture bytes
GLint iComponents, iWidth, iHeight; // Texture sizes
GLenum eFormat; // Texture format
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
glEnable(GL_CULL_FACE); // Do not calculate inside of jet
// White background
glClearColor(1.0f, 1.0f, 1.0f, 1.0f );
// Decal texture environment
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
// Two textures
glGenTextures(2, toTextures);
///////////////////////////////////////////
// Load the main texture
glBindTexture(GL_TEXTURE_2D, toTextures[0]);
pBytes = gltLoadTGA("stripes.tga", &iWidth, &iHeight, &iComponents, &eFormat);
glTexImage2D(GL_TEXTURE_2D, 0, iComponents, iWidth, iHeight, 0, eFormat, GL_UNSIGNED_BYTE, (void *)pBytes);
free(pBytes);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);
///////////////////////////////////////////
// Load environment map
glBindTexture(GL_TEXTURE_2D, toTextures[1]);
pBytes = gltLoadTGA("Environment.tga", &iWidth, &iHeight, &iComponents, &eFormat);
glTexImage2D(GL_TEXTURE_2D, 0, iComponents, iWidth, iHeight, 0, eFormat, GL_UNSIGNED_BYTE, (void *)pBytes);
free(pBytes);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glEnable(GL_TEXTURE_2D);
// Turn on texture coordiante generation
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
// Sphere Map will be the default
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
}
/////////////////////////////////////////////////////
// Handle arrow keys
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
xRot-= 5.0f;
if(key == GLUT_KEY_DOWN)
xRot += 5.0f;
if(key == GLUT_KEY_LEFT)
yRot -= 5.0f;
if(key == GLUT_KEY_RIGHT)
yRot += 5.0f;
if(key > 356.0f)
xRot = 0.0f;
if(key < -1.0f)
xRot = 355.0f;
if(key > 356.0f)
yRot = 0.0f;
if(key < -1.0f)
yRot = 355.0f;
// Refresh the Window
glutPostRedisplay();
}
//////////////////////////////////////////////////////////
// Reset projection and light position
void ChangeSize(int w, int h)
{
GLfloat fAspect;
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
// Reset coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
fAspect = (GLfloat) w / (GLfloat) h;
gluPerspective(45.0f, fAspect, 1.0f, 225.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
///////////////////////////////////////////////////////////////////////////////
// Program Entry Point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Texture Coordinate Generation");
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
glutDisplayFunc(RenderScene);
SetupRC();
// Create the Menu
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("Object Linear",1);
glutAddMenuEntry("Eye Linear",2);
glutAddMenuEntry("Sphere Map",3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
// Don't forget the texture objects
glDeleteTextures(2, toTextures);
return 0;
}
پاسخ : برنامه هایی گرافیكی ( OpenGL )
کد:
// Bezlit.c
// OpenGL SuperBible
// Program by Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // GLTools
// The number of control points for this curve
GLint nNumPoints = 3;
GLfloat ctrlPoints[3][3][3]= {{{ -4.0f, 0.0f, 4.0f},
{ -2.0f, 4.0f, 4.0f},
{ 4.0f, 0.0f, 4.0f }},
{{ -4.0f, 0.0f, 0.0f},
{ -2.0f, 4.0f, 0.0f},
{ 4.0f, 0.0f, 0.0f }},
{{ -4.0f, 0.0f, -4.0f},
{ -2.0f, 4.0f, -4.0f},
{ 4.0f, 0.0f, -4.0f }}};
// This function is used to superimpose the control points over the curve
void DrawPoints(void)
{
int i,j; // Counting variables
// Set point size larger to make more visible
glPointSize(5.0f);
// Loop through all control points for this example
glBegin(GL_POINTS);
for(i = 0; i < nNumPoints; i++)
for(j = 0; j < 3; j++)
glVertex3fv(ctrlPoints[i][j]);
glEnd();
}
// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Save the modelview matrix stack
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// Rotate the mesh around to make it easier to see
glRotatef(45.0f, 0.0f, 1.0f, 0.0f);
glRotatef(60.0f, 1.0f, 0.0f, 0.0f);
// Sets up the bezier
// This actually only needs to be called once and could go in
// the setup function
glMap2f(GL_MAP2_VERTEX_3, // Type of data generated
0.0f, // Lower u range
10.0f, // Upper u range
3, // Distance between points in the data
3, // Dimension in u direction (order)
0.0f, // Lover v range
10.0f, // Upper v range
9, // Distance between points in the data
3, // Dimension in v direction (order)
&ctrlPoints[0][0][0]); // array of control points
// Enable the evaluator
glEnable(GL_MAP2_VERTEX_3);
// Use higher level functions to map to a grid, then evaluate the
// entire thing.
// Map a grid of 10 points from 0 to 10
glMapGrid2f(10,0.0f,10.0f,10,0.0f,10.0f);
// Evaluate the grid, using lines
glEvalMesh2(GL_FILL,0,10,0,10);
// Restore the modelview matrix
glPopMatrix();
// Dispalay the image
glutSwapBuffers();
}
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Light values and coordinates
GLfloat ambientLight[] = { 0.3f, 0.3f, 0.3f, 1.0f };
GLfloat diffuseLight[] = { 0.7f, 0.7f, 0.7f, 1.0f };
GLfloat lightPos[] = { 20.0f, 0.0f, 0.0f, 0.0f };
// Clear Window to white
glClearColor(1.0f, 1.0f, 1.0f, 1.0f );
glEnable(GL_DEPTH_TEST); // Hidden surface removal
// Enable lighting
glEnable(GL_LIGHTING);
// Setup light 0
glLightfv(GL_LIGHT0,GL_AMBIENT,ambientLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuseLight);
// Position and turn on the light
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);
// Enable color tracking
glEnable(GL_COLOR_MATERIAL);
// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
// Automatically generate normals for evaluated surfaces
glEnable(GL_AUTO_NORMAL);
// Draw in Blue
glColor3f(0.0f, 0.0f, 1.0f);
}
void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0f, 10.0f, -10.0f, 10.0f, -10.0f, 10.0f);
// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Lit 3D Bezier Surface");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();
return 0;
}
پاسخ : برنامه هایی گرافیكی ( OpenGL )
کد:
// Bezier.c
// OpenGL SuperBible
// Demonstrates OpenGL evaluators to draw bezier curve
// Program by Richard S. Wright Jr.
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // GLTools
// The number of control points for this curve
GLint nNumPoints = 4;
GLfloat ctrlPoints[4][3]= {{ -4.0f, 0.0f, 0.0f}, // End Point
{ -6.0f, 4.0f, 0.0f}, // Control Point
{ 6.0f, -4.0f, 0.0f}, // Control Point
{ 4.0f, 0.0f, 0.0f }}; // End Point
// This function is used to superimpose the control points over the curve
void DrawPoints(void)
{
int i; // Counting variable
// Set point size larger to make more visible
glPointSize(5.0f);
// Loop through all control points for this example
glBegin(GL_POINTS);
for(i = 0; i < nNumPoints; i++)
glVertex2fv(ctrlPoints[i]);
glEnd();
}
// Called to draw scene
void RenderScene(void)
{
int i;
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT);
// Sets up the bezier
// This actually only needs to be called once and could go in
// the setup function
glMap1f(GL_MAP1_VERTEX_3, // Type of data generated
0.0f, // Lower u range
100.0f, // Upper u range
3, // Distance between points in the data
nNumPoints, // number of control points
&ctrlPoints[0][0]); // array of control points
// Enable the evaluator
glEnable(GL_MAP1_VERTEX_3);
// Use a line strip to "connect-the-dots"
glBegin(GL_LINE_STRIP);
for(i = 0; i <= 100; i++)
{
// Evaluate the curve at this point
glEvalCoord1f((GLfloat) i);
}
glEnd();
// Use higher level functions to map to a grid, then evaluate the
// entire thing.
// Put these two functions in to replace above loop
// Map a grid of 100 points from 0 to 100
//glMapGrid1d(100,0.0,100.0);
// Evaluate the grid, using lines
//glEvalMesh1(GL_LINE,0,100);
// Draw the Control Points
DrawPoints();
// Flush drawing commands
glutSwapBuffers();
}
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Clear Window to white
glClearColor(1.0f, 1.0f, 1.0f, 1.0f );
// Draw in Blue
glColor3f(0.0f, 0.0f, 1.0f);
}
///////////////////////////////////////
// Set 2D Projection
void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-10.0f, 10.0f, -10.0f, 10.0f);
// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("2D Bezier Curve");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();
return 0;
}
پاسخ : برنامه هایی گرافیكی ( OpenGL )
برنامه ی Select کردن اشیا.
کد:
// Planets.c
// OpenGL SuperBible, 3rd Edition
// Richard S. Wright Jr.
// rwright@starstonesoftware.com
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include <math.h>
struct Rectangle
{
int top;
int bottom;
int left;
int right;
};
///////////////////////////
// Object Names
#define TORUS 1
#define SPHERE 2
struct Rectangle boundingRect; // Bounding rectangle
GLuint selectedObject = 0; // Who is selected
float fAspect; // Display aspect ratio
#if !defined(M_PI)
#define M_PI 3.14159265f
#endif
///////////////////////////////////////////////////////////
// Draw a torus (doughnut)
// at z = 0... torus aligns with xy plane
void DrawTorus(int numMajor, int numMinor)
{
float majorRadius = 0.35F;
float minorRadius = 0.15F;
double majorStep = 2.0F*M_PI / numMajor;
double minorStep = 2.0F*M_PI / numMinor;
int i, j;
float c, r, z;
glEnable(GL_NORMALIZE);
for (i=0; i<numMajor; ++i)
{
double a0 = i * majorStep;
double a1 = a0 + majorStep;
GLfloat x0 = (GLfloat) cos(a0);
GLfloat y0 = (GLfloat) sin(a0);
GLfloat x1 = (GLfloat) cos(a1);
GLfloat y1 = (GLfloat) sin(a1);
glBegin(GL_TRIANGLE_STRIP);
for (j=0; j<=numMinor; ++j)
{
double b = j * minorStep;
c = (float) cos(b);
r = minorRadius * c + majorRadius;
z = minorRadius * (GLfloat) sin(b);
glTexCoord2f((float)i/(float)numMajor, (float)j/(float)numMinor);
glNormal3f(x0*c, y0*c, z/minorRadius);
glVertex3f(x0*r, y0*r, z);
glTexCoord2f((float)(i+1)/(float)numMajor, (float)j/(float)numMinor);
glNormal3f(x1*c, y1*c, z/minorRadius);
glVertex3f(x1*r, y1*r, z);
}
glEnd();
}
glDisable(GL_NORMALIZE);
}
///////////////////////////////////////////////////////////
// Just draw a sphere of some given radius
void DrawSphere(float radius)
{
GLUquadricObj *pObj;
pObj = gluNewQuadric();
gluQuadricNormals(pObj, GLU_SMOOTH);
gluSphere(pObj, radius, 26, 13);
gluDeleteQuadric(pObj);
}
///////////////////////////////////////////////////////////
// Render the torus and sphere
void DrawObjects(void)
{
// Save the matrix state and do the rotations
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// Translate the whole scene out and into view
glTranslatef(-0.75f, 0.0f, -2.5f);
// Initialize the names stack
glInitNames();
glPushName(0);
// Set material color, Yellow
// torus
glColor3f(1.0f, 1.0f, 0.0f);
glLoadName(TORUS);
glPassThrough((GLfloat)TORUS);
DrawTorus(40, 20);
// Draw Sphere
glColor3f(0.5f, 0.0f, 0.0f);
glTranslatef(1.5f, 0.0f, 0.0f);
glLoadName(SPHERE);
glPassThrough((GLfloat)SPHERE);
DrawSphere(0.5f);
// Restore the matrix state
glPopMatrix(); // Modelview matrix
}
///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw the objects in the scene
DrawObjects();
// If something is selected, draw a bounding box around it
if(selectedObject != 0)
{
int viewport[4];
// Get the viewport
glGetIntegerv(GL_VIEWPORT, viewport);
// Remap the viewing volume to match window coordinates (approximately)
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
// Establish clipping volume (left, right, bottom, top, near, far)
glOrtho(viewport[0], viewport[2], viewport[3], viewport[1], -1, 1);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_LIGHTING);
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_LINE_LOOP);
glVertex2i(boundingRect.left, boundingRect.top);
glVertex2i(boundingRect.left, boundingRect.bottom);
glVertex2i(boundingRect.right, boundingRect.bottom);
glVertex2i(boundingRect.right, boundingRect.top);
glEnd();
glEnable(GL_LIGHTING);
}
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glutSwapBuffers();
}
///////////////////////////////////////////////////////////
// Go into feedback mode and draw a rectangle around the object
#define FEED_BUFF_SIZE 32768
void MakeSelection(int nChoice)
{
// Space for the feedback buffer
static GLfloat feedBackBuff[FEED_BUFF_SIZE];
// Storage for counters, etc.
int size,i,j,count;
// Initial minimum and maximum values
boundingRect.right = boundingRect.bottom = -999999.0f;
boundingRect.left = boundingRect.top = 999999.0f;
// Set the feedback buffer
glFeedbackBuffer(FEED_BUFF_SIZE,GL_2D, feedBackBuff);
// Enter feedback mode
glRenderMode(GL_FEEDBACK);
// Redraw the scene
DrawObjects();
// Leave feedback mode
size = glRenderMode(GL_RENDER);
// Parse the feedback buffer and get the
// min and max X and Y window coordinates
i = 0;
while(i < size)
{
// Search for appropriate token
if(feedBackBuff[i] == GL_PASS_THROUGH_TOKEN)
if(feedBackBuff[i+1] == (GLfloat)nChoice)
{
i+= 2;
// Loop until next token is reached
while(i < size && feedBackBuff[i] != GL_PASS_THROUGH_TOKEN)
{
// Just get the polygons
if(feedBackBuff[i] == GL_POLYGON_TOKEN)
{
// Get all the values for this polygon
count = (int)feedBackBuff[++i]; // How many vertices
i++;
for(j = 0; j < count; j++) // Loop for each vertex
{
// Min and Max X
if(feedBackBuff[i] > boundingRect.right)
boundingRect.right = feedBackBuff[i];
if(feedBackBuff[i] < boundingRect.left)
boundingRect.left = feedBackBuff[i];
i++;
// Min and Max Y
if(feedBackBuff[i] > boundingRect.bottom)
boundingRect.bottom = feedBackBuff[i];
if(feedBackBuff[i] < boundingRect.top)
boundingRect.top = feedBackBuff[i];
i++;
}
}
else
i++; // Get next index and keep looking
}
break;
}
i++;
}
}
///////////////////////////////////////////////////////////
// Process the selection, which is triggered by a right mouse
// click at (xPos, yPos).
#define BUFFER_LENGTH 64
void ProcessSelection(int xPos, int yPos)
{
// Space for selection buffer
static GLuint selectBuff[BUFFER_LENGTH];
// Hit counter and viewport storage
GLint hits, viewport[4];
// Setup selection buffer
glSelectBuffer(BUFFER_LENGTH, selectBuff);
// Get the viewport
glGetIntegerv(GL_VIEWPORT, viewport);
// Switch to projection and save the matrix
glMatrixMode(GL_PROJECTION);
glPushMatrix();
// Change render mode
glRenderMode(GL_SELECT);
// Establish new clipping volume to be unit cube around
// mouse cursor point (xPos, yPos) and extending two pixels
// in the vertical and horizontal direction
glLoadIdentity();
gluPickMatrix(xPos, viewport[3] - yPos, 2,2, viewport);
// Apply perspective matrix
gluPerspective(60.0f, fAspect, 1.0, 425.0);
// Draw the scene
DrawObjects();
// Collect the hits
hits = glRenderMode(GL_RENDER);
// Restore the projection matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
// Go back to modelview for normal rendering
glMatrixMode(GL_MODELVIEW);
// If a single hit occurred, display the info.
if(hits == 1)
{
MakeSelection(selectBuff[3]);
if(selectedObject == selectBuff[3])
selectedObject = 0;
else
selectedObject = selectBuff[3];
}
glutPostRedisplay();
}
///////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context. Here it sets up and initializes the lighting for
// the scene.
void SetupRC()
{
// Lighting values
GLfloat dimLight[] = { 0.1f, 0.1f, 0.1f, 1.0f };
GLfloat sourceLight[] = { 0.65f, 0.65f, 0.65f, 1.0f };
GLfloat lightPos[] = { 0.0f, 0.0f, 0.0f, 1.0f };
// Light values and coordinates
glEnable(GL_DEPTH_TEST); // Hidden surface removal
glFrontFace(GL_CCW); // Counter clock-wise polygons face out
//glEnable(GL_CULL_FACE); // Do not calculate insides
// Enable lighting
glEnable(GL_LIGHTING);
// Setup and enable light 0
glLightfv(GL_LIGHT0,GL_AMBIENT,dimLight);
glLightfv(GL_LIGHT0,GL_DIFFUSE,sourceLight);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);
// Enable color tracking
glEnable(GL_COLOR_MATERIAL);
// Set Material properties to follow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
// Gray background
glClearColor(0.60f, 0.60f, 0.60f, 1.0f );
glLineWidth(2.0f);
}
///////////////////////////////////////////////////////////
// Set viewport and projection
void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
// Calculate aspect ratio of the window
fAspect = (GLfloat)w/(GLfloat)h;
// Set the perspective coordinate system
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Field of view of 45 degrees, near and far planes 1.0 and 425
gluPerspective(60.0f, fAspect, 1.0, 425.0);
// Modelview matrix reset
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
///////////////////////////////////////////////////////////
// Process the mouse click
void MouseCallback(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
ProcessSelection(x, y);
}
///////////////////////////////////////////////////////////
// Program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Select an Object");
glutReshapeFunc(ChangeSize);
glutMouseFunc(MouseCallback);
glutDisplayFunc(RenderScene);
SetupRC();
glutMainLoop();
return 0;
}
پاسخ : برنامه هایی گرافیكی ( OpenGL )
کد:
// GLPalette.c
// OpenGL SuperBible,
// Program by Richard S. Wright Jr.
// This program demonstrates creation and use of a 332 palette for OpenGL
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include "resource.h"
// Palette Handle
HPALETTE hPalette = NULL;
static LPCTSTR lpszAppName = "GLPalette";
// Declaration for Window procedure
LRESULT CALLBACK WndProc( HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam);
// Set Pixel Format function - forward declaration
void SetDCPixelFormat(HDC hDC);
BYTE* gltResourceBMPBits(UINT nResource, int *nWidth, int *nHeight)
{
HINSTANCE hInstance; // Instance Handle
HANDLE hBitmap; // Handle to bitmap resource
BITMAPINFO bmInfo;
BYTE *pData;
// Find the bitmap resource
hInstance = GetModuleHandle(NULL);
hBitmap = LoadBitmap(hInstance,MAKEINTRESOURCE(nResource));
if(hBitmap == NULL)
return NULL;
GetObject(hBitmap,sizeof(BITMAPINFO),&bmInfo);
DeleteObject(hBitmap);
hBitmap = LoadResource(hInstance,
FindResource(hInstance,MAKEINTRESOURCE(nResource), RT_BITMAP));
if(hBitmap == NULL)
return NULL;
pData = (BYTE *)LockResource(hBitmap);
pData += sizeof(BITMAPINFO)-1;
*nWidth = bmInfo.bmiHeader.biWidth; //bm.bmWidth;
*nHeight = bmInfo.bmiHeader.biHeight;//bm.bmHeight;
return pData;
}
void ChangeSize(GLsizei w, GLsizei h)
{
GLfloat nRange = 100.0f;
GLfloat fAspect;
// Prevent a divide by zero
if(h == 0)
h = 1;
fAspect = (GLfloat)w/(GLfloat)h;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
// Reset coordinate system
glLoadIdentity();
// Setup perspective for viewing
gluPerspective(17.5f,fAspect,60,300);
// Viewing transformation
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -250.0f);
}
void RenderScene(void)
{
static float fX = 0.0f;
static float fY = 0.0f;
float fSize = 20.0f;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
fX += 0.15f;
fY += 0.1f;
if(fX > 360.0f)
fX = 0.15f;
if(fY > 360.0f)
fY = 0.1f;
glPushMatrix();
glRotatef(fX, 1.0f, 0.0f, 0.0f);
glRotatef(fY, 0.0f, 1.0f, 0.0f);
// Front face of Cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-fSize, fSize, fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-fSize, -fSize, fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(fSize,-fSize, fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(fSize,fSize, fSize);
glEnd();
// Back face of Cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(fSize,fSize, -fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(fSize,-fSize, -fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-fSize, -fSize, -fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-fSize, fSize, -fSize);
glEnd();
// Top Face of Cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-fSize, fSize, fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(fSize, fSize, fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(fSize, fSize, -fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-fSize, fSize, -fSize);
glEnd();
// Bottom Face of Cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-fSize, -fSize, -fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(fSize, -fSize, -fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(fSize, -fSize, fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-fSize, -fSize, fSize);
glEnd();
// Left hand side of cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-fSize, fSize, -fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-fSize, -fSize, -fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-fSize, -fSize, fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-fSize, fSize, fSize);
glEnd();
// Right hand side of cube
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(fSize, fSize, fSize);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(fSize, -fSize, fSize);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(fSize, -fSize, -fSize);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(fSize, fSize, -fSize);
glEnd();
glPopMatrix();
}
void SetupRC(void)
{
BYTE *pBytes;
int nWidth, nHeight;
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
// Load the texture
pBytes = gltResourceBMPBits(IDB_MONA, &nWidth, &nHeight);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,nWidth, nHeight, 0,
GL_BGR_EXT, GL_UNSIGNED_BYTE, pBytes);
}
// If necessary, creates a 3-3-2 palette for the device context listed.
HPALETTE GetOpenGLPalette(HDC hDC)
{
HPALETTE hRetPal = NULL; // Handle to palette to be created
PIXELFORMATDESCRIPTOR pfd; // Pixel Format Descriptor
LOGPALETTE *pPal; // Pointer to memory for logical palette
int nPixelFormat; // Pixel format index
int nColors; // Number of entries in palette
int i; // Counting variable
BYTE RedRange,GreenRange,BlueRange;
// Range for each color entry (7,7,and 3)
// Get the pixel format index and retrieve the pixel format description
nPixelFormat = GetPixelFormat(hDC);
DescribePixelFormat(hDC, nPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
// Does this pixel format require a palette? If not, do not create a
// palette and just return NULL
if(!(pfd.dwFlags & PFD_NEED_PALETTE))
return NULL;
// Number of entries in palette. 8 bits yeilds 256 entries
nColors = 1 << pfd.cColorBits;
// Allocate space for a logical palette structure plus all the palette entries
pPal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) +nColors*sizeof(PALETTEENTRY));
// Fill in palette header
pPal->palVersion = 0x300; // Windows 3.0
pPal->palNumEntries = nColors; // table size
// Build mask of all 1's. This creates a number represented by having
// the low order x bits set, where x = pfd.cRedBits, pfd.cGreenBits, and
// pfd.cBlueBits.
RedRange = (1 << pfd.cRedBits) -1;
GreenRange = (1 << pfd.cGreenBits) - 1;
BlueRange = (1 << pfd.cBlueBits) -1;
// Loop through all the palette entries
for(i = 0; i < nColors; i++)
{
// Fill in the 8-bit equivalents for each component
pPal->palPalEntry[i].peRed = (i >> pfd.cRedShift) & RedRange;
pPal->palPalEntry[i].peRed = (unsigned char)(
(double) pPal->palPalEntry[i].peRed * 255.0 / RedRange);
pPal->palPalEntry[i].peGreen = (i >> pfd.cGreenShift) & GreenRange;
pPal->palPalEntry[i].peGreen = (unsigned char)(
(double)pPal->palPalEntry[i].peGreen * 255.0 / GreenRange);
pPal->palPalEntry[i].peBlue = (i >> pfd.cBlueShift) & BlueRange;
pPal->palPalEntry[i].peBlue = (unsigned char)(
(double)pPal->palPalEntry[i].peBlue * 255.0 / BlueRange);
pPal->palPalEntry[i].peFlags = (unsigned char) NULL;
}
// Create the palette
hRetPal = CreatePalette(pPal);
// Go ahead and select and realize the palette for this device context
SelectPalette(hDC,hRetPal,FALSE);
RealizePalette(hDC);
// Free the memory used for the logical palette structure
free(pPal);
// Return the handle to the new palette
return hRetPal;
}
// Select the pixel format for a given device context
void SetDCPixelFormat(HDC hDC)
{
int nPixelFormat;
static PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), // Size of this structure
1, // Version of this structure
PFD_DRAW_TO_WINDOW | // Draw to Window (not to bitmap)
PFD_SUPPORT_OPENGL | // Support OpenGL calls in window
PFD_DOUBLEBUFFER, // Double buffered mode
PFD_TYPE_RGBA, // RGBA Color mode
8, // Want 8 bit color
0,0,0,0,0,0, // Not used to select mode
0,0, // Not used to select mode
0,0,0,0,0, // Not used to select mode
16, // Size of depth buffer
0, // Not used to select mode
0, // Not used to select mode
PFD_MAIN_PLANE, // Draw in main plane
0, // Not used to select mode
0,0,0 }; // Not used to select mode
// Choose a pixel format that best matches that described in pfd
nPixelFormat = ChoosePixelFormat(hDC, &pfd);
// Set the pixel format for the device context
SetPixelFormat(hDC, nPixelFormat, &pfd);
}
// Entry point of all Windows programs
int APIENTRY WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg; // Windows message structure
WNDCLASS wc; // Windows class structure
HWND hWnd; // Storeage for window handle
// Register Window style
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
// No need for background brush for OpenGL window
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = lpszAppName;
// Register the window class
if(RegisterClass(&wc) == 0)
return FALSE;
// Create the main application window
hWnd = CreateWindow(
lpszAppName,
lpszAppName,
// OpenGL requires WS_CLIPCHILDREN and WS_CLIPSIBLINGS
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
// Window position and size
100, 100,
250, 250,
NULL,
NULL,
hInstance,
NULL);
// If window was not created, quit
if(hWnd == NULL)
return FALSE;
// Display the window
ShowWindow(hWnd,SW_SHOW);
UpdateWindow(hWnd);
// Process application messages until the application closes
while( GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
// Window procedure, handles all messages for this program
LRESULT CALLBACK WndProc( HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
static HGLRC hRC; // Permenant Rendering context
static HDC hDC; // Private GDI Device context
switch (message)
{
// Window creation, setup for OpenGL
case WM_CREATE:
// Store the device context
hDC = GetDC(hWnd);
// Select the pixel format
SetDCPixelFormat(hDC);
// Create the rendering context and make it current
hRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hRC);
// Create the palette
hPalette = GetOpenGLPalette(hDC);
// Create a timer that fires 30 times a second
SetTimer(hWnd,33,1,NULL);
SetupRC();
break;
// Window is being destroyed, cleanup
case WM_DESTROY:
// Kill the timer that we created
KillTimer(hWnd,101);
// Deselect the current rendering context and delete it
wglMakeCurrent(hDC,NULL);
wglDeleteContext(hRC);
// Delete the palette
if(hPalette != NULL)
DeleteObject(hPalette);
// Tell the application to terminate after the window
// is gone.
PostQuitMessage(0);
break;
// Window is resized.
case WM_SIZE:
// Call our function which modifies the clipping
// volume and viewport
ChangeSize(LOWORD(lParam), HIWORD(lParam));
break;
// The painting function. This message sent by Windows
// whenever the screen needs updating.
case WM_PAINT:
{
// Call OpenGL drawing code
RenderScene();
// Call function to swap the buffers
SwapBuffers(hDC);
}
break;
// Windows is telling the application that it may modify
// the system palette. This message in essance asks the
// application for a new palette.
case WM_QUERYNEWPALETTE:
// If the palette was created.
if(hPalette)
{
int nRet;
// Selects the palette into the current device context
SelectPalette(hDC, hPalette, FALSE);
// Map entries from the currently selected palette to
// the system palette. The return value is the number
// of palette entries modified.
nRet = RealizePalette(hDC);
// Repaint, forces remap of palette in current window
InvalidateRect(hWnd,NULL,FALSE);
return nRet;
}
break;
// This window may set the palette, even though it is not the
// currently active window.
case WM_PALETTECHANGED:
// Don't do anything if the palette does not exist, or if
// this is the window that changed the palette.
if((hPalette != NULL) && ((HWND)wParam != hWnd))
{
// Select the palette into the device context
SelectPalette(hDC,hPalette,FALSE);
// Map entries to system palette
RealizePalette(hDC);
// Remap the current colors to the newly realized palette
UpdateColors(hDC);
return 0;
}
break;
default: // Passes it on if unproccessed
return (DefWindowProc(hWnd, message, wParam, lParam));
}
return (0L);
}
پاسخ : برنامه هایی گرافیكی ( OpenGL )
کاوه جان من سورسها رو چطوری بگیرم.
پاسخ : برنامه هایی گرافیكی ( OpenGL )
نقل قول:
کاوه جان من سورسها رو چطوری بگیرم.
سورس ها به صورت کد قرار داده شده اند.
شما با دیدن نمونه ی برنامه ، می تونید سورس اون رو کپی کنید و در کامپایلر خودتون اجرا کنید..!
البته Include ها رو از یاد نبری ..! ;)
پاسخ : برنامه هایی گرافیكی ( OpenGL )
سلام
کسی از دوستان میتونه منبعی رو برای یادگیری مقدماتی OpenGL معزفی کنه ؟
پاسخ : برنامه هایی گرافیكی ( OpenGL )
نقل قول:
سلام
کسی از دوستان میتونه منبعی رو برای یادگیری مقدماتی opengl معزفی کنه ؟
من در این مورد کتابی به زبان اصلی دارم.
اگه به دردتون می خوره بگید آپلود کنم.
موفق باشید
پاسخ : برنامه هایی گرافیكی ( OpenGL )
اگر لطف کنید و اپلود کنید ممنون می شم