How to load (.m) file with Glui opengl? - opengl

I have looked through the examples in the Glui package, but I need help with loading (.m) file which is 3D model
this is the sample codes....
#include <iostream>
#include <GL/glut.h>
#include <cstdlib>
using namespace std;
void createMenu(void);
void menu(int value);
void disp(void);
static int win;
static int menid;
static int submenid;
static int primitive = 0; // global variable for the geometric primitive
int main(int argc, char **argv){
// normal initialisation
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
win = glutCreateWindow("GLUT MENU");
// put all the menu functions in one nice procedure
createMenu();
// set the clearcolor and the callback
glClearColor(0.0,0.0,0.0,0.0);
// register your drawing function
glutDisplayFunc(disp);
// enter the main loop
glutMainLoop();
return 1;
}
//#define USE_SUB_MENU
void createMenu(void){
//#ifdef USE_SUB_MENU
// step 1: Create a submenu, this has to be done first.
submenid = glutCreateMenu(menu); // pass the function "menu" to glutCreateMenu
// Add sub menu entry
glutAddMenuEntry("Teapot", 2);
glutAddMenuEntry("Cube", 3);
glutAddMenuEntry("Torus", 4);
// step 2: Create the main menu, this menu becomes the current menu
menid = glutCreateMenu(menu);
// Create an entry
glutAddMenuEntry("Clear", 1);
glutAddSubMenu("Draw", submenid);
// Create an entry
glutAddMenuEntry("Quit", 0);
// Let the menu respond on the right mouse button
glutAttachMenu(GLUT_RIGHT_BUTTON);
//#else
menid = glutCreateMenu(menu);
// Create an entry
glutAddMenuEntry("Clear", 1);
glutAddMenuEntry("Teapot", 2);
glutAddMenuEntry("Cube", 3);
glutAddMenuEntry("Torus", 4);
// Create an entry
glutAddMenuEntry("Quit", 0);
// Let the menu respond on the right mouse button
glutAttachMenu(GLUT_RIGHT_BUTTON);
//#endif
}
void disp(void){
// Just clean the screen
// this has to be called everytime when you draw sth
glClear(GL_COLOR_BUFFER_BIT);
// draw what the user asked
if(primitive == 1){ // clear the screen
glutPostRedisplay();
}else if(primitive == 2){ // draw the teapot
glutWireTeapot(0.5);
}else if(primitive == 3){ // draw the cube
glutWireCube(0.5);
}else if(primitive == 4){ // draw the torus
glutWireTorus(0.3,0.6,100,100);
}
glFlush();
}
void menu(int value){
if(value == 0){ // the user clicks 'quit'
glutDestroyWindow(win);
exit(0);
}else{
primitive=value; // set the geometric primitive
}
// you would want to redraw now
glutPostRedisplay();
}
I really don't know how to do T_T, requirment is to load .m files using opengl, glut, glui.... So, I need help to load it with opengl without crashing then done.

You'll need a parser for your .M files.
I couldn't find a spec anywhere so I've taken a guess at the format:
#include <glm/glm.hpp>
using namespace glm;
struct Vertex
{
vec3 position;
vec3 normal;
};
vector< Vertex > LoadM( istream& in )
{
vector< Vertex > verts;
map< int, vec3 > positions;
map< int, vec3 > normals;
string lineStr;
while( getline( in, lineStr ) )
{
istringstream lineSS( lineStr );
string lineType;
lineSS >> lineType;
// vertex
if( lineType == "Vertex" )
{
int idx;
float x = 0, y = 0, z = 0;
lineSS >> idx >> x >> y >> z;
positions[ idx ] = vec3( x, y, z );
}
// face
if( lineType == "Face" )
{
int indexes[ 3 ];
int idx;
lineSS >> idx >> indexes[0] >> indexes[1] >> indexes[2];
// http://www.opengl.org/wiki/Calculating_a_Surface_Normal
vec3 U( positions[ indexes[1] ] - positions[ indexes[0] ] );
vec3 V( positions[ indexes[2] ] - positions[ indexes[0] ] );
vec3 faceNormal = normalize( cross( U, V ) );
for( size_t j = 0; j < 3; ++j )
{
Vertex vert;
vert.position = vec3( positions[ indexes[j] ] );
vert.normal = faceNormal;
verts.push_back( vert );
}
}
}
return verts;
}
Used in context:
#include <GL/glut.h>
#include <glm/glm.hpp>
#include <glm/gtx/component_wise.hpp>
#include <vector>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
using namespace glm;
struct Vertex
{
vec3 position;
vec3 normal;
};
vector< Vertex > LoadM( istream& in )
{
vector< Vertex > verts;
map< int, vec3 > positions;
string lineStr;
while( getline( in, lineStr ) )
{
istringstream lineSS( lineStr );
string lineType;
lineSS >> lineType;
// parse vertex line
if( lineType == "Vertex" )
{
int idx = 0;
float x = 0, y = 0, z = 0;
lineSS >> idx >> x >> y >> z;
positions.insert( make_pair( idx, vec3( x, y, z ) ) );
}
// parse face line
if( lineType == "Face" )
{
int indexes[ 3 ] = { 0 };
int idx = 0;
lineSS >> idx >> indexes[0] >> indexes[1] >> indexes[2];
// http://www.opengl.org/wiki/Calculating_a_Surface_Normal
vec3 U( positions[ indexes[1] ] - positions[ indexes[0] ] );
vec3 V( positions[ indexes[2] ] - positions[ indexes[0] ] );
vec3 faceNormal = normalize( cross( U, V ) );
for( size_t j = 0; j < 3; ++j )
{
Vertex vert;
vert.position = vec3( positions[ indexes[j] ] );
vert.normal = faceNormal;
verts.push_back( vert );
}
}
}
return verts;
}
// mouse state
int btn;
ivec2 startMouse;
ivec2 startRot, curRot;
ivec2 startTrans, curTrans;
void mouse(int button, int state, int x, int y )
{
y = glutGet( GLUT_WINDOW_HEIGHT ) - y;
if( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN )
{
btn = button;
startMouse = ivec2( x, y );
startRot = curRot;
}
if( button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN )
{
btn = button;
startMouse = ivec2( x, y );
startTrans = curTrans;
}
}
void motion( int x, int y )
{
y = glutGet( GLUT_WINDOW_HEIGHT ) - y;
ivec2 curMouse( x, y );
if( btn == GLUT_LEFT_BUTTON )
{
curRot = startRot + ( curMouse - startMouse );
}
else if( btn == GLUT_RIGHT_BUTTON )
{
curTrans = startTrans + ( curMouse - startMouse );
}
glutPostRedisplay();
}
vector< Vertex > model;
void display()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
double ar = w / h;
// "pan"
glTranslatef( curTrans.x / w * 2, curTrans.y / h * 2, 0 );
gluPerspective( 60, ar, 0.1, 20 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glTranslatef( 0, 0, -10 );
glPushMatrix();
// apply mouse rotation
glRotatef( curRot.x % 360, 0, 1, 0 );
glRotatef( -curRot.y % 360, 1, 0, 0 );
glColor3ub( 255, 0, 0 );
// draw model
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_NORMAL_ARRAY );
glVertexPointer( 3, GL_FLOAT, sizeof(Vertex), &model[0].position );
glNormalPointer( GL_FLOAT, sizeof(Vertex), &model[0].normal );
glDrawArrays( GL_TRIANGLES, 0, model.size() );
glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_NORMAL_ARRAY );
// draw bounding cube
glDisable( GL_LIGHTING );
glColor3ub( 255, 255, 255 );
glutWireCube( 7 );
glEnable( GL_LIGHTING );
glPopMatrix();
glutSwapBuffers();
}
// return the x/y/z min/max of some geometry
template< typename Vec >
pair< Vec, Vec > GetExtents
(
const Vec* pts,
size_t stride,
size_t count
)
{
typedef typename Vec::value_type Scalar;
Vec pmin( std::numeric_limits< Scalar >::max() );
Vec pmax( std::min( std::numeric_limits< Scalar >::min(),
(Scalar)-std::numeric_limits< Scalar >::max() ) );
// find extents
unsigned char* base = (unsigned char*)pts;
for( size_t i = 0; i < count; ++i )
{
const Vec& pt = *(Vec*)base;
pmin = glm::min( pmin, pt );
pmax = glm::max( pmax, pt );
base += stride;
}
return make_pair( pmin, pmax );
}
// centers geometry around the origin
// and scales it to fit in a size^3 box
template< typename Vec >
void CenterAndScale
(
Vec* pts,
size_t stride,
size_t count,
const typename Vec::value_type& size
)
{
typedef typename Vec::value_type Scalar;
// get min/max extents
pair< Vec, Vec > exts = GetExtents( pts, stride, count );
// center and scale
const Vec center = ( exts.first * Scalar( 0.5 ) ) + ( exts.second * Scalar( 0.5f ) );
const Scalar factor = size / glm::compMax( exts.second - exts.first );
unsigned char* base = (unsigned char*)pts;
for( size_t i = 0; i < count; ++i )
{
Vec& pt = *(Vec*)base;
pt = ((pt - center) * factor);
base += stride;
}
}
int main( int argc, char **argv )
{
ifstream ifile( "bunny.m" );
model = LoadM( ifile );
if( model.empty() )
{
cerr << "Empty model!" << endl;
return -1;
}
CenterAndScale( &model[0].position, sizeof( Vertex ), model.size(), 7 );
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 640, 480 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutMouseFunc( mouse );
glutMotionFunc( motion );
glEnable( GL_DEPTH_TEST );
// set up "headlamp"-like light
glShadeModel( GL_SMOOTH );
glEnable( GL_COLOR_MATERIAL );
glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE ) ;
glEnable( GL_LIGHTING );
glEnable( GL_LIGHT0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
GLfloat position[] = { 0, 0, 1, 0 };
glLightfv( GL_LIGHT0, GL_POSITION, position );
glPolygonMode( GL_FRONT, GL_FILL );
glPolygonMode( GL_BACK, GL_LINE );
glutMainLoop();
return 0;
}

Related

OpenGL Ball is too slow and getting bugged

I'm trying to do an animation which ball starts dropping with affects of gravity but unfortunately the ball is too slow. I actually found a way for it which is to change
double dt = (cur - last) / 1000.0;
to
double dt = (cur - last) / 100.0;
but that time, the bug is that position of the ball is kind of wrong because the ball starts dying :). If you work the animation you may understand what I'm trying to say!
The main code is there :
#include <GL/glut.h>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
#include <glm/glm.hpp>
#include <glm/gtx/norm.hpp>
using namespace glm;
int seconds_past = 0;
struct Ball{
int radius;
dvec3 pos;
dvec3 vel;
double acc = -9.8;
bool last, made = false;
dvec3 last_vel;
void Integrate(double cur, double dt){
static int count = 0;
count++;
vel += dvec3{vel[0], acc * dt, 0};
pos = pos + vel * dt;
std::cout << vel[1] << " " << count << std::endl;
}
void HandleCollisions(){
if(pos[1] - 10 < -100){
std::cout << "true" << std::endl;
vel = -vel;
}
}
};
void Integrate( vector< Ball >& particles, double cur, double dt)
{
for( size_t i = 0; i < particles.size(); ++i )
{
particles[i].Integrate( cur, dt );
particles[i].HandleCollisions();
}
}
vector< Ball > particles;
void display()
{
// use last frame time to calculate delta-t
static int last = glutGet( GLUT_ELAPSED_TIME );
int cur = glutGet( GLUT_ELAPSED_TIME );
double dt = ( cur - last ) / 1000.0;
last = cur;
Integrate( particles, cur, dt);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
double ar = w / h;
glOrtho( -100 * ar, 100 * ar, -100, 100, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
// draw particles
glPointSize( 50 );
glEnableClientState( GL_VERTEX_ARRAY );
glVertexPointer( 3, GL_DOUBLE, sizeof( Ball ), &particles[0].pos[0] );
glDrawArrays( GL_POINTS, 0, particles.size() );
glDisableClientState( GL_VERTEX_ARRAY );
glutSwapBuffers();
}
void timer( int value )
{
glutPostRedisplay();
glutTimerFunc( 1000.0/60.0, timer, value );
}
int main(int argc, char **argv)
{
particles.resize(1);
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}

BCD Counter C++

I have an assignment to build a 7 segment BCD counter. The idea is to generate binary numbers 000, 001, etc all the way up to 9, and then feed them into a BCD decoder and the display will be a 7 segment display that counts 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, etc. I know this is typically done with an FPGA board, but since we're distance learning the task is to perform this using simple C++ graphics. I had a previous project where the user would input a binary number and the display would display the number in the seven seg, so I built off of that. However, I'm getting a floating point fault and the program crashes and I cannot for the life of me figure out why. Any help would be appreciated.
#include <GL/glut.h>
#include <stdio.h>
#include <string.h>
#include <deque>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include "dec2baser.cpp"
using namespace std;
deque<char>textQ; // holding a message
int bits[100]; // holding bits entered
bool enter = false;
class Point {
public:
float v[2];
Point() { v[0] = v[1] = 0;}
Point( float x0, float y0 ){
v[0] = x0;
v[1] = y0;
}
Point( float v0[] ){
v[0] = v0[0];
v[1] = v0[1];
}
void move ( float dx, float dy )
{
v[0] += dx;
v[1] += dy;
}
};
void aLine ( Point p0, Point p1, int thick ) //modifies width based on what segment is activated
{
if ( !thick ) // thin line
glLineWidth ( 1 );
else // thick line
glLineWidth ( 4 );
glBegin( GL_LINES );
glVertex2fv ( p0.v );
glVertex2fv ( p1.v );
glEnd();
}
void text ( char *s )
{
char *p;
for ( p = s; *p; p++ )
glutBitmapCharacter ( GLUT_BITMAP_TIMES_ROMAN_24, (int) *p );
// glutBitmapCharacter ( GLUT_BITMAP_HELVETICA_18, *p );
}
/*bool getBits()
{
char s[400], s1[400];
float x = -9, y = 9;
int i, n;
static bool first = true;
enter = false;
glColor3f (0, 0, 0);
strcpy ( s, "Press'q' to quit: \n");
if ( first ) {
glRasterPos2f ( x, y );
text ( s );
first = false;
return enter;
}
n = strlen( s );
i = 0;
deque <char> :: iterator it;
for (it = textQ.begin(); it != textQ.end(); ++it) {
if ( i > 100 ) break;
s[i+n] = s1[i] = *it;
if ( s1[i] == '\r' ) {
s[i+n] = s1[i] = 0;
enter = true;
break;
}
i++;
}
s[i+n] = 0;
s1[i] = 0;
glRasterPos2f ( x, y );
text ( s );
if ( enter ) {
glRasterPos2f ( 0, 0 );
text ( s1 );
i = 0;
while ( s1[i] != 0 ) {
bits[i] = s1[i] - '0';
i++;
}
bits[i] = -1; //signals end of bits
textQ.erase(textQ.begin(), textQ.end() );
}
return enter;
}
void printBits()
{
int i = 0;
while ( bits[i] != -1 )
cout << bits[i++];
cout << endl;
}*/
void drawLines()
{
Point p0, p1;
p0 = Point ( -2, 2);
p1 = Point ( 4, 2 );
aLine ( p0, p1, 0 ); // thin horizontal
p0.move ( 0, -1 );
p1.move ( 0, -1 );
aLine ( p0, p1, 1 ); // thick horizontal
p0 = Point ( -2, 0);
p1 = Point ( -2, -5 );
aLine ( p0, p1, 0 ); // thin vertical
p0.move ( 4, 0 );
p1.move ( 4, 0 );
aLine ( p0, p1, 1 ); // thick vertical
}
void display()
{
glClear( GL_COLOR_BUFFER_BIT ); //clear screen
//if ( getBits() ) commented out because user is not inputing any bits
char res[100];
unsigned int microsecond = 1000000;
for ( int i = 0; i < 9; i ++ )
{
binaryGen(res, i, 2);
drawLines();
usleep( 1 * microsecond); //wait for 1 second
}
glFlush(); //send all output to screen
}
void keyboard ( unsigned char key, int mousex, int mousey )
{
switch ( key ) {
case 27: // escape
case 'q':
exit ( -1 );
}
if ( key == '\b' ) // back space
textQ.pop_back();
else
textQ.push_back( key );
glutPostRedisplay();
return;
}
As you can see I have the getbits function commented out because that was for my previous project where the user would input the values and the program would display that value. That's the drawing source code, now here's my main source code.
#include <GL/glut.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
//function call protos
void init(void);
void display (void);
void keyboard ( unsigned char key, int mousex, int mousey );
//modified to initialize our display
void init(void)
{
const char *version;
glClearColor( 1.0, 1.0, 1.0, 0.0 ); //get white background color
glColor3f( 0.0f, 0.0f, 0.0f ); //set drawing color
glPointSize( 4.0 ); //a dot is 4x4
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( -10.0, 10.0, -10.0, 10.0 );
}
/* Main Loop
* Open window with initial window size, title bar,
* RGBA drawLines mode, depth buffer.
*/
int main(int argc, char** argv)
{
glutInit(&argc, argv); //initialize toolkit
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB ); //set drawLines mode
glutInitWindowSize(500, 500); //set window size on screen
glutInitWindowPosition( 100, 150 ); //set window position on screen
glutCreateWindow(argv[0]); //open screen widow
init();
glutKeyboardFunc ( keyboard );
glutDisplayFunc (display ); //points to drawLines function
glutMainLoop(); //go into perpetual loop
return 0;
}
Any and all help is appreciated, I'm relatively new to coding so if there's any obvious errors you see let me know. Thank you!

Why does my glDrawArrays is not drawing the points I have stored?

I'm trying to just create a simple program that draws points where I click.
I declare a struct that holds the coordinates and the color of each point.
I declare a global vector< Point > that holds the list of points. The mouse input is well recorded and printed on the cout, but the points are not draw.
Any idea why I am missing in the initialization of GLUT?
#include <GL/freeglut_std.h>
#include <GL/gl.h>
#include <vector>
#include <iostream>
using namespace std;
struct Point
{
float x, y;
unsigned char r, g, b, a;
};
vector< Point > points;
void drawPoints()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-50, 50, -50, 50, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// draw
glColor3ub( 255, 255, 255 );
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );
glVertexPointer( 2, GL_FLOAT, sizeof(Point), &points[0].x );
glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(Point), &points[0].r );
glPointSize( 3.0 );
glDrawArrays( GL_POINTS, 0, points.size() );
glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );
glFlush();
glutSwapBuffers();
}
void OnMouseClick(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
//store the x,y value where the click happened
Point p = Point();
p.x = (float)x;
p.y = (float)y;
p.r = 255;
p.g = 255;
p.b = 255;
p.a = 255;
points.push_back(p);
for (vector<Point>::iterator it = points.begin(); it != points.end(); ++it)
{
cout << it->x << " " << it->y << " " << flush;
}
cout << endl;
glutPostRedisplay();
}
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("OpenGL - Drawing points");
glutDisplayFunc(drawPoints);
glutMouseFunc(OnMouseClick);
glutMainLoop();
return 0;
}
Coordinate system mismatch, either transform GLUT's mouse coordinates into your chosen glOrhto() coordinate system or change that call to match GLUT's mouse coordinate system.
Example of the second way:
#include <GL/glut.h>
#include <vector>
using namespace std;
struct Point
{
float x, y;
unsigned char r, g, b, a;
};
vector< Point > points;
void drawPoints()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
GLdouble w = glutGet( GLUT_WINDOW_WIDTH );
GLdouble h = glutGet( GLUT_WINDOW_HEIGHT );
glOrtho( 0, w, h, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
// draw
if( !points.empty() )
{
glColor3ub( 255, 255, 255 );
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );
glVertexPointer( 2, GL_FLOAT, sizeof( Point ), &points[ 0 ].x );
glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( Point ), &points[ 0 ].r );
glPointSize( 3.0 );
glDrawArrays( GL_POINTS, 0, points.size() );
glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );
}
glutSwapBuffers();
}
void OnMouseClick( int button, int state, int x, int y )
{
if( button == GLUT_LEFT_BUTTON && state == GLUT_UP )
{
//store the x,y value where the click happened
Point p = Point();
p.x = (float)x;
p.y = (float)y;
p.r = 255;
p.g = 255;
p.b = 255;
p.a = 255;
points.push_back( p );
glutPostRedisplay();
}
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 500, 500 );
glutInitWindowPosition( 100, 100 );
glutCreateWindow( "OpenGL - Drawing points" );
glutDisplayFunc( drawPoints );
glutMouseFunc( OnMouseClick );
glutMainLoop();
return 0;
}

can't migrate from visual studio to linux with c++ and opengl

I'm having classes of computer graphics on OpenGL. There we study and work with Visual Studio 2015 while I run Linux on my laptop. So there some differences between composing a program in our classes and in lessons I found on Wikibooks. I tried to run one tutorial code from there and everything was fine, while I couldn't run my code I wrote at my lesson.
So I tried manipulating with my and tutorial code. I succeeded a few. The program runs but not shows my figures. So it actually must show a chesstable. But, for my regret, it shows a background color only. What may be wrong with that?
The first part on onDisplay() is not displayed. The commented part is from tutorial which works and shows a triangle.
Full code:
#include <stdio.h>
#include <stdlib.h>
/* Use glew.h instead of gl.h to get all the GL prototypes declared */
#include <GL/glew.h>
/* Using the GLUT library for the base windowing setup */
#include <GL/freeglut.h>
GLuint program;
GLint attribute_coord2d;
int init_resources()
{
GLint compile_ok = GL_FALSE, link_ok = GL_FALSE;
GLuint vs = glCreateShader( GL_VERTEX_SHADER );
const char *vs_source =
#ifdef GL_ES_VERSION_2_0
"#version 100\n" // OpenGL ES 2.0
#else
"#version 120\n" // OpenGL 2.1
#endif
"attribute vec2 coord2d; "
"void main(void) { "
" gl_Position = vec4(coord2d, 0.0, 1.0); "
"}";
glShaderSource( vs, 1, &vs_source, NULL );
glCompileShader( vs );
glGetShaderiv( vs, GL_COMPILE_STATUS, &compile_ok );
if( !compile_ok )
{
fprintf( stderr, "Error in vertex shader\n" );
return 0;
}
GLuint fs = glCreateShader( GL_FRAGMENT_SHADER );
const char *fs_source =
#ifdef GL_ES_VERSION_2_0
"#version 100\n" // OpenGL ES 2.0
#else
"#version 120\n" // OpenGL 2.1
#endif
"void main(void) { "
" gl_FragColor[0] = 0.0; "
" gl_FragColor[1] = 0.0; "
" gl_FragColor[2] = 1.0; "
"}";
glShaderSource( fs, 1, &fs_source, NULL );
glCompileShader( fs );
glGetShaderiv( fs, GL_COMPILE_STATUS, &compile_ok );
if( !compile_ok )
{
fprintf( stderr, "Error in fragment shader\n" );
return 0;
}
program = glCreateProgram();
glAttachShader( program, vs );
glAttachShader( program, fs );
glLinkProgram( program );
glGetProgramiv( program, GL_LINK_STATUS, &link_ok );
if( !link_ok )
{
fprintf( stderr, "glLinkProgram:" );
return 0;
}
const char* attribute_name = "coord2d";
attribute_coord2d = glGetAttribLocation( program, attribute_name );
if( attribute_coord2d == -1 )
{
fprintf( stderr, "Could not bind attribute %s\n", attribute_name );
return 0;
}
return 1;
}
void chess( double x, double y, double w, double h, int k )
{
glColor3f( 0.6, 0.6, 0.6 );
glRecti( 20, 20, 480, 480 );
for( int i = 0; i < 8; i++ )
{
glRasterPos2i( ( i + 1 )*x + 20, 30 );
glutBitmapCharacter( GLUT_BITMAP_9_BY_15, 'A' + i );
}
for( int j = 0; j < 8; j++ )
{
for( int i = 0; i < 8; i++ )
{
if( k % 2 == 0 )
{
glColor3f( 1, 1, 1 );
}
else glColor3f( 0, 0, 0 );
glRecti( x + w*i, y + h*j, 2 * x + w*i, 2 * y + h*j );
k++;
}
k++;
}
}
void onDisplay()
{
glClearColor( 0.5, 1.0, 1.0, 1.0 );
glClear( GL_COLOR_BUFFER_BIT );
glUseProgram( program );
glEnableVertexAttribArray( attribute_coord2d );
double x, y, w, h;
int k;
x = 50;
y = 50;
h = 50;
w = 50;
k = 1;
chess( x, y, w, h, k );
glFlush();
/*
GLfloat triangle_vertices[] = {
0.0, 0.8,
-0.8, -0.8,
0.8, -0.8,
};
// Describe our vertices array to OpenGL (it can't guess its format automatically)
glVertexAttribPointer(
attribute_coord2d, // attribute
2, // number of elements per vertex, here (x,y)
GL_FLOAT, // the type of each element
GL_FALSE, // take our values as-is
0, // no extra data between each position
triangle_vertices // pointer to the C array
);
// Push each element in buffer_vertices to the vertex shader
glDrawArrays(GL_TRIANGLES, 0, 3);
*/
glDisableVertexAttribArray( attribute_coord2d );
glutSwapBuffers();
}
void free_resources()
{
glDeleteProgram( program );
}
int main( int argc, char* argv[] )
{
glutInit( &argc, argv );
glutInitContextVersion( 2, 0 );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
glutInitWindowSize( 640, 640 );
glutCreateWindow( "chesstable" );
GLenum glew_status = glewInit();
if( glew_status != GLEW_OK )
{
fprintf( stderr, "Error: %s\n", glewGetErrorString( glew_status ) );
return 1;
}
if( init_resources() )
{
glutDisplayFunc( onDisplay );
glutMainLoop();
}
free_resources();
return 0;
}

Draw a polygon QUADS when mouse is clicked?

how can drawing like square or TRIANGLES when clicked on any position on screen show the shape this is my Attempt i do't know what doing
...........................................................................
.......................................................................................
#include <windows.h>
#include <gl/Gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
GLsizei wh=500,ww=500;
GLfloat size=3.0;
void drawsquare( int x, int y)
{
y=wh-y;
glBegin(GL_POLYGON);
glVertex2f(x+size,y+size);
glVertex2f(x-size,y+size);
glVertex2f(x-size,y-size);
glVertex2f(x+size,y-size);
glEnd();
glFlush();
}
void mymose(int button,int state,int x,int y)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN)
drawsquare(x,y);
//if(button==GLUT_RIGHT_BUTTON_BUTTON && state==GLUT_UP)
// exit();
}
void myInit(){
glViewport(0,0,ww,wh);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,(GLdouble)ww,0.0,(GLdouble)wh);
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0,0.0,0.0,1.0);
glColor3f(1.0,0.0,0.0);
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(ww,wh);
glutInitWindowPosition(100,100);
glutCreateWindow("GLUT");
glutMouseFunc(mymose);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
You need a vector to store the points in.
Add points in the mouse callback and request a redraw via glutPostRedisplay().
Then in display() you can spin over all the points in the vector and draw quads around them:
#include <GL/glut.h>
#include <vector>
struct Point
{
Point( float x, float y ) : x(x), y(y) {}
float x, y;
};
std::vector< Point > points;
void mouse( int button, int state, int x, int y )
{
if( button == GLUT_LEFT_BUTTON && state == GLUT_UP )
{
points.push_back( Point( x, y ) );
}
if( button == GLUT_RIGHT_BUTTON && state == GLUT_UP )
{
points.clear();
}
glutPostRedisplay();
}
void display()
{
glClearColor( 0, 0, 0, 1 );
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
int w = glutGet( GLUT_WINDOW_WIDTH );
int h = glutGet( GLUT_WINDOW_HEIGHT );
glOrtho( 0, w, h, 0, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glColor3ub( 255, 0, 0 );
glBegin( GL_QUADS );
for( size_t i = 0; i < points.size(); ++i )
{
const unsigned int SIZE = 20;
const Point& pt = points[ i ];
glVertex2i( pt.x - SIZE, pt.y - SIZE );
glVertex2i( pt.x + SIZE, pt.y - SIZE );
glVertex2i( pt.x + SIZE, pt.y + SIZE );
glVertex2i( pt.x - SIZE, pt.y + SIZE );
}
glEnd();
glutSwapBuffers();
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 640, 480 );
glutCreateWindow( "GLUT" );
glutMouseFunc( mouse );
glutDisplayFunc( display );
glutMainLoop();
return 0;
}