I am tring to load the model and display it using OpenGL. The code runs fine with no errors but nothing is displayed. Can someone help me regarding this issue?
The source code:
int cube;
int number_faces;
int number_vertices;
struct coordinate {
float x, y, z;
coordinate(float a, float b, float c): x(a), y(b), z(c) {};
};
struct face {
int faces[3];
face (int f1, int f2, int f3){
faces[0] = f1;
faces[1] = f2;
faces[2] = f3;
};
};
// function prototype
bool loadObject(const char * file_name);
int main(int argc, char ** argv)
{
//initialize Glut
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(w_x_position, w_y_position);
glutInitWindowSize(w_width, w_height);
glutCreateWindow("Assignment 1");
//function call
init();
glutDisplayFunc(display);
//loop main
glutMainLoop();
return 0;
}
bool loadObject(const char * file_name){
//initialize stuff
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//create the vectors that will hold the file coordinates
std::vector<std::string*> points;
std::vector<coordinate*> vertex;
std::vector<face*> faces;
//check if the file opens
if ( !file_name ) {
return false;
}
// open file
FILE *fp = fopen( file_name, "r" );
if ( !fp ) {
return false;
}
// num of vertices and indices
fscanf( fp, "data%d%d", &number_vertices, &number_faces);
//push the content into the vertexs
for(int i=0;i<number_vertices;i++) {
float x_temp, y_temp, z_temp;
fscanf( fp, "%f%f%f", &x_temp, &y_temp,&z_temp );
vertex.push_back(new coordinate(x_temp, y_temp, z_temp));
}
for (int y=0; y<number_faces;y++){
int a,b,c;
fscanf( fp, "%d%d%d", &a, &b, &c);
faces.push_back(new face(a, b, c));
}
//draw the modle
int number;
number = glGenLists(1);
glNewList(number, GL_COMPILE);
for(int i =0; i <faces.size();i++){
glBegin(GL_TRIANGLES);
glVertex3f(vertex[faces[i]->faces[0]-1]->x, vertex[faces[i]->faces[0]-1]->y,vertex[faces[i]->faces[0]-1]->z);
glVertex3f(vertex[faces[i]->faces[1]-1]->x, vertex[faces[i]->faces[1]-1]->y,vertex[faces[i]->faces[1]-1]->z);
glVertex3f(vertex[faces[i]->faces[2]-1]->x, vertex[faces[i]->faces[2]-1]->y,vertex[faces[i]->faces[2]-1]->z);
glEnd();
}
glEndList();
//delete the poiters for memory space
for(int i=0;i<points.size();i++){
delete points[i];
}
for(int i=0;i<faces.size();i++){
delete faces[i];
}
for(int i=0;i<vertex.size();i++){
delete vertex[i];
}
return number;
}
First of all I guess you are mixing something up.
The steps should be:
Start the programm
Create everything that is needed for OpenGL
Load your model. You just need to do this once. For modern openGL you can create a so called VertexBuffer for storing you vertices.
Start the GameLoop which normally should have at least three parts
parse the input from the player like KeyBoard and Mouse
Update the scene corresponding to your game logic and the input of the user
Draw everything to the screen
If the user decided so, close the program and clean everything up.
Using glut you can provide function pointer to glut which calls your input, update and reder method, There is also an idle method and various other you can provide, so you do not need to make your own loop.
The 2nd problem I can see in your code beside the not so good structure is that you are missing to set a Modelview Matrix. You've just set a projection matrix and no modelMatrix. But for a better understanding just let me explain a bit more about the render part of the gameLoop.
The render method will draw everything to the screen/window. For each model you have to provide a modelview matrix which will translate, rotate and scale the mesh/model and a projectionmatrix which will bring the 3D world to a 2D screen (There is a bit more about math and a lot more details but we will keep it short and easy here). In older versions of OpenGL there is already a stack implemented on which you can push or pop the matrices. The matrix on top of the stack will be used to draw the mesh. If you want another projection and/or modelmatrix for a 2nd or 3rd mesh just change the matrix on top of the stack. During the loading of a mesh you do not need to priovide any other information. Just position, uv or color for each vertex.
You drawing will be roughly like this (pseudocode):
ClearEverythingFromLastCall();
glMatrixMode(GL_PROJECTION);
SetProjectionMatrixOnStack(); (pushMatrix)
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
ChangeMatrixForCurrentObject();
drawObject();
glutSwapBuffers(); // This shpuld be the last line of you method
drawObject depends on what technique you are using (fixedFunctionPipeline from older OpenGL versions, or the programmable pipeline from OpenGL 3.0 and newer (which I think is the better one)).
So there are a lot of errors in you code and not the "one" little bug which breaks you code. I highly recommend to start with a good tutorial. For older OpenGL I recommend http://nehe.gamedev.net/ or http://videotutorialsrock.com/ (If you are able to speak german I can give you some tutorials in german also). Both start from the very beginning with the fixed pipeline.
Related
A Project I am working on involves me using glScissor, in some cases i need to perform a scissor on an area twice (or more), with the goal of only rendering what is within both scissor boxes.
The issue im running into is that the second scissor box just overrides the previous one, meaning only the last box set is used instead of both.
I have tried existing solutions such as setting scissor1, push matrix, enable scissor_test, set scissor2, disable scissor_test, popmatrix, disable scissor_test. As proposed here: glScissor() call inside another glScissor()
I could not get these to produce any difference, I had also tried glPushAttrib instead of matrix but still no difference.
Here is an example program I wrote for scissor testing, its compiled by g++ and uses freeglut, the scissoring takes place in display():
/*
Compile: g++ .\scissor.cpp -lglu32 -lfreeglut -lopengl32
*/
#include <GL/gl.h>//standard from mingw, already in glut.h - header library
#include <GL/glu.h>//standard from mingw, already in glut.h - utility library
#include <GL/glut.h>//glut/freeglut - more utilities, utility tool kit
void display();
void reshape(int, int);
void timer(int);
void init(){
glClearColor(0, 0, 0, 1);
}
int main(int argc, char **argv){
glutInit(&argc, argv);//init glut
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);//init display mode, add double buffer mode
//init window
glutInitWindowPosition(200, 100);//if not specified, it will display in a random spot
glutInitWindowSize(500, 500);//size
//create window
glutCreateWindow("Window 1");
//give glut a function pointer so it can call that function later
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutTimerFunc(0, timer, 0);//call certain function after a specified amount of time
init();
glutMainLoop();//once this loop runs your program has started running, when the loop ends the program terminates
}
float xPos = -10;
int state = 1;//1 = right, -1 = left
//our rendering happens here
void display(){
//clear previous frame
glClear(GL_COLOR_BUFFER_BIT);//pass in flag of frame buffer
//draw next frame below
glLoadIdentity();//reset rotations, transformations, ect. (resets coordinate system)
//we are using a model view matrix by default
//TEST
glEnable(GL_SCISSOR_TEST);
glScissor(0, 0, 100, 1000);
glPushMatrix();
glEnable(GL_SCISSOR_TEST);
glScissor(50, 0, 1000, 1000);
//assuming both scissors intersect, we should only see the square between 50 and 100 pixels
//draw
glBegin(GL_QUADS);//every set of 3 verticies is a triangle
//GL_TRIANGLES = 3 points
//GL_QUADS = 4 points
//GL_POLYGON = any amount of points
glVertex2f(xPos, 1);//the 2 is the amount of args we pass in, the f means theyr floats
glVertex2f(xPos, -1);
glVertex2f(xPos+2, -1);
glVertex2f(xPos+2, 1);
glEnd();//tell opengl your done drawing verticies
glDisable(GL_SCISSOR_TEST);
glPopMatrix();
glDisable(GL_SCISSOR_TEST);
//display frame buffer on screen
//glFlush();
glutSwapBuffers();//if double buffering, call swap buffers instead of flush
}
//gets called when window is reshaped
void reshape(int width, int hight){
//set viewport and projection
//viewport is a rectangle where everything is drawn, like its the window
glViewport(0, 0, width, hight);
//matrix modes: there is model view and projection, projection has depth
glMatrixMode(GL_PROJECTION);
glLoadIdentity();//reset current matrix after changing matrix mode
gluOrtho2D(-10, 10, -10, 10);//specify 2d projection, set opengl's coordinate system
glMatrixMode(GL_MODELVIEW);//change back to model view
}
//this like makes a loop
void timer(int a){
glutPostRedisplay();//opengl will call the display function the next time it gets the chance
glutTimerFunc(1000/60, timer, 0);
//update positions and stuff
//this can be done here or in the display function
switch(state){
case 1:
if(xPos < 8)
xPos += 0.15;
else
state = -1;
break;
case -1:
if(xPos > -10)
xPos -= 0.15;
else
state = 1;
break;
}
}
I tried following example solutions, such as push/pop matrix/attrib, but couldnt get anything to work
There is no first or second scissor box. There is just the scissor box. You can change the scissor box and that change will affect subsequent rendering. But at any one time, there is only one.
What you want is to use the stencil buffer to discard fragments outside of an area defined by rendering certain values into the stencil buffer.
I'm attempting to incorporate a path finding algorithm I made into code but I'm running into a problem. I am trying to be flexible with my code and allow data sets of different lengths and then draw the points using openGL. My problem is that for the points I am using an array of pointers to accomplish the variable length and openGL doesn't like that when trying to convert data types. With the function glVertex2i() it wants GLint as its two parameters but when I try and convert my array to GLint I get a blank window. I understand this is a typedef but it wont take the regular int from the array. Please help!
struct Points { int x, y; }; //My struct to hold the x,y cords
int size; //This is the size of the array
Points *crds = new Points[size]; //The data for this array was input in another function
for (int i = 0; i < size; i++)
{
//These are some things to help configure the look of the points
glEnable(GL_POINT_SMOOTH);
glPointSize(100);
glColor3f(250, 250, 250);
glBegin(GL_POINTS);
for (int i = 0; i < size; i++)
{
glVertex2i((GLint)crds[i].x, (GLint)crds[i].y);
}
glEnd();
use GLint for the coords
because int is not guaranteed to be 32bit it differs from compiler to compiler and platform and can be 16/32/64 bit these days. Your solution should work too but if you use GLint then You do not need to cast the (GLint) in glVertex and also can use the vector version like this:
GLint pnt[100][2];
glVertex2iv(pnt[i]);
or like this:
GLint pnt[100<<1];
glVertex2iv(pnt[i<<1]);
But the real problem lies in following bullets...
matrices
we do not see any matrices nor the range of your points. The OpenGL uses unit matrices by default which means your points should be <-1,+1> to be visible which is not practical on integers. So if your points are in pixels and your screen is xs,ys resolution you should add this before your render:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-1.0,-1.0,0.0);
glScalef(2.0/float(xs),2.0/float(ys),0.0);
glColor3f(250,250,250)
The floating point range of colors in OpenGL is <0.0,1.0> so you are setting wrong colors. Try this instead:
glColor3f(1.0,1.0,1.0);
glPointSize(100)
100 is too big as the size is in pixels try:
glPointSize(8);
That is all I can think of what could be wrong... Look here:
Drawing a line using individual pixels in OpenGl core
the related QA contains working example for both old and new API.
I'm using NeHe's tutorial on FreeType and OpenGL, and I'm having a problem defining members of
struct font_data within namespace freetype. It doesn't recognize font_data as a struct when I define its members in the namespace.
CE_Text.h:
#ifndef CE_TEXT
#define CE_TEXT
#include <Common/Headers.h>
/////////////////// MAJOR CREDIT TO NeHe FOR HIS TUTORIAL ON FREETPYE ///////////////////
///Wrap everything in a namespace, that we can use common
///function names like "print" without worrying about
///overlapping with anyone else's code.
namespace freetype {
//Inside of this namespace, give ourselves the ability
//to write just "vector" instead of "std::vector"
using std::vector;
//Ditto for string.
using std::string;
//This holds all of the information related to any
//freetype font that we want to create.
struct font_data{
float h; ///< Holds the height of the font.
GLuint * textures; ///< Holds the texture id's
GLuint list_base; ///< Holds the first display list id
//The init function will create a font of
//of the height h from the file fname.
void init(const char * fname, unsigned int h);
//Free all the resources assosiated with the font.
void clean();
};
//The flagship function of the library - this thing will print
//out text at window coordinates x,y, using the font ft_font.
//The current modelview matrix will also be applied to the text.
void print(const font_data &ft_font, float x, float y, const char *fmt) ;
}
#endif
CE_Text.cpp (my problem is at void font_data::init):
#include <Common/Headers.h>
using namespace freetype;
namespace freetype {
///This function gets the first power of 2 >= the
///int that we pass it.
inline int next_p2 ( int a )
{
int rval=1;
while(rval<a) rval<<=1;
return rval;
}
///Create a display list coresponding to the give character.
void make_dlist ( FT_Face face, char ch, GLuint list_base, GLuint * tex_base ) {
//The first thing we do is get FreeType to render our character
//into a bitmap. This actually requires a couple of FreeType commands:
//Load the Glyph for our character.
if(FT_Load_Glyph( face, FT_Get_Char_Index( face, ch ), FT_LOAD_DEFAULT ))
throw std::runtime_error("FT_Load_Glyph failed");
//Move the face's glyph into a Glyph object.
FT_Glyph glyph;
if(FT_Get_Glyph( face->glyph, &glyph ))
throw std::runtime_error("FT_Get_Glyph failed");
//Convert the glyph to a bitmap.
FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1 );
FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph;
//This reference will make accessing the bitmap easier
FT_Bitmap& bitmap=bitmap_glyph->bitmap;
//Use our helper function to get the widths of
//the bitmap data that we will need in order to create
//our texture.
int width = next_p2( bitmap.width );
int height = next_p2( bitmap.rows );
//Allocate memory for the texture data.
GLubyte* expanded_data = new GLubyte[ 2 * width * height];
//Here we fill in the data for the expanded bitmap.
//Notice that we are using two channel bitmap (one for
//luminocity and one for alpha), but we assign
//both luminocity and alpha to the value that we
//find in the FreeType bitmap.
//We use the ?: operator so that value which we use
//will be 0 if we are in the padding zone, and whatever
//is the the Freetype bitmap otherwise.
for(int j=0; j <height;j++) {
for(int i=0; i < width; i++){
expanded_data[2*(i+j*width)]= expanded_data[2*(i+j*width)+1] =
(i>=bitmap.width || j>=bitmap.rows) ?
0 : bitmap.buffer[i + bitmap.width*j];
}
}
//Now we just setup some texture paramaters.
glBindTexture( GL_TEXTURE_2D, tex_base[ch]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
//Here we actually create the texture itself, notice
//that we are using GL_LUMINANCE_ALPHA to indicate that
//we are using 2 channel data.
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expanded_data );
//With the texture created, we don't need to expanded data anymore
delete [] expanded_data;
//So now we can create the display list
glNewList(list_base+ch,GL_COMPILE);
glBindTexture(GL_TEXTURE_2D,tex_base[ch]);
glPushMatrix();
//first we need to move over a little so that
//the character has the right amount of space
//between it and the one before it.
glTranslatef(bitmap_glyph->left,0,0);
//Now we move down a little in the case that the
//bitmap extends past the bottom of the line
//(this is only true for characters like 'g' or 'y'.
glTranslatef(0,bitmap_glyph->top-bitmap.rows,0);
//Now we need to account for the fact that many of
//our textures are filled with empty padding space.
//We figure what portion of the texture is used by
//the actual character and store that information in
//the x and y variables, then when we draw the
//quad, we will only reference the parts of the texture
//that we contain the character itself.
float x=(float)bitmap.width / (float)width,
y=(float)bitmap.rows / (float)height;
//Here we draw the texturemaped quads.
//The bitmap that we got from FreeType was not
//oriented quite like we would like it to be,
//so we need to link the texture to the quad
//so that the result will be properly aligned.
glBegin(GL_QUADS);
glTexCoord2d(0,0); glVertex2f(0,bitmap.rows);
glTexCoord2d(0,y); glVertex2f(0,0);
glTexCoord2d(x,y); glVertex2f(bitmap.width,0);
glTexCoord2d(x,0); glVertex2f(bitmap.width,bitmap.rows);
glEnd();
glPopMatrix();
glTranslatef(face->glyph->advance.x >> 6 ,0,0);
//increment the raster position as if we were a bitmap font.
//(only needed if you want to calculate text length)
//glBitmap(0,0,0,0,face->glyph->advance.x >> 6,0,NULL);
//Finnish the display list
glEndList();
}
void font_data::init(const char * fname, unsigned int h) {
//Allocate some memory to store the texture ids.
textures = new GLuint[128];
this->h=h;
//Create and initilize a freetype font library.
FT_Library library;
if (FT_Init_FreeType( &library ))
throw std::runtime_error("FT_Init_FreeType failed");
//The object in which Freetype holds information on a given
//font is called a "face".
FT_Face face;
//This is where we load in the font information from the file.
//Of all the places where the code might die, this is the most likely,
//as FT_New_Face will die if the font file does not exist or is somehow broken.
if (FT_New_Face( library, fname, 0, &face ))
throw std::runtime_error("FT_New_Face failed (there is probably a problem with your font file)");
//For some twisted reason, Freetype measures font size
//in terms of 1/64ths of pixels. Thus, to make a font
//h pixels high, we need to request a size of h*64.
//(h << 6 is just a prettier way of writting h*64)
FT_Set_Char_Size( face, h << 6, h << 6, 96, 96);
//Here we ask opengl to allocate resources for
//all the textures and displays lists which we
//are about to create.
list_base=glGenLists(128);
glGenTextures( 128, textures );
//This is where we actually create each of the fonts display lists.
for(unsigned char i=0;i<128;i++)
make_dlist(face,i,list_base,textures);
//We don't need the face information now that the display
//lists have been created, so we free the assosiated resources.
FT_Done_Face(face);
//Ditto for the library.
FT_Done_FreeType(library);
}
void font_data::clean() {
glDeleteLists(list_base,128);
glDeleteTextures(128,textures);
delete [] textures;
}
/// A fairly straight forward function that pushes
/// a projection matrix that will make object world
/// coordinates identical to window coordinates.
inline void pushScreenCoordinateMatrix() {
glPushAttrib(GL_TRANSFORM_BIT);
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(viewport[0],viewport[2],viewport[1],viewport[3]);
glPopAttrib();
}
/// Pops the projection matrix without changing the current
/// MatrixMode.
inline void pop_projection_matrix() {
glPushAttrib(GL_TRANSFORM_BIT);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
}
///Much like Nehe's glPrint function, but modified to work
///with freetype fonts.
void print(const font_data &ft_font, float x, float y, const char *fmt, ...) {
// We want a coordinate system where things coresponding to window pixels.
pushScreenCoordinateMatrix();
GLuint font=ft_font.list_base;
float h=ft_font.h/.63f; //We make the height about 1.5* that of
char text[256]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (fmt == NULL) // If There's No Text
*text=0; // Do Nothing
else {
va_start(ap, fmt); // Parses The String For Variables
vsprintf(text, fmt, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
}
//Here is some code to split the text that we have been
//given into a set of lines.
//This could be made much neater by using
//a regular expression library such as the one avliable from
//boost.org (I've only done it out by hand to avoid complicating
//this tutorial with unnecessary library dependencies).
const char *start_line=text;
vector<string> lines;
for(const char *c=text;*c;c++) {
if(*c=='\n') {
string line;
for(const char *n=start_line;n<c;n++) line.append(1,*n);
lines.push_back(line);
start_line=c+1;
}
}
if(start_line) {
string line;
for(const char *n=start_line;n<c;n++) line.append(1,*n);
lines.push_back(line);
}
glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glMatrixMode(GL_MODELVIEW);
glDisable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glListBase(font);
float modelview_matrix[16];
glGetFloatv(GL_MODELVIEW_MATRIX, modelview_matrix);
//This is where the text display actually happens.
//For each line of text we reset the modelview matrix
//so that the line's text will start in the correct position.
//Notice that we need to reset the matrix, rather than just translating
//down by h. This is because when each character is
//draw it modifies the current matrix so that the next character
//will be drawn immediatly after it.
for(int i=0;i<lines.size();i++) {
glPushMatrix();
glLoadIdentity();
glTranslatef(x,y-h*i,0);
glMultMatrixf(modelview_matrix);
// The commented out raster position stuff can be useful if you need to
// know the length of the text that you are creating.
// If you decide to use it make sure to also uncomment the glBitmap command
// in make_dlist().
// glRasterPos2f(0,0);
glCallLists(lines[i].length(), GL_UNSIGNED_BYTE, lines[i].c_str());
// float rpos[4];
// glGetFloatv(GL_CURRENT_RASTER_POSITION ,rpos);
// float len=x-rpos[0];
glPopMatrix();
}
glPopAttrib();
pop_projection_matrix();
}
}
struct freetype::font_data{
should be
struct font_data{
The fact that font_data is in namespace freetype is already covered by the surrounding namespace freetype { }.
So, in fact, in your code it is true that you never did declare any freetype::font_data type! It's as if you were attempting to declare a freetype::freetype::font_data type instead.
This is analagous to how you do not write:
struct T
{
void T::foo();
};
but instead:
struct T
{
void foo();
};
You have to include CE_Text.h into CE_Text.cpp for that to work. Without seeing the definition for font_data class, the compiler will not allow you to define its members.
That's what it is telling you by "not recognizing font_data as a struct". Of course, it is not recognizing it, since it is completely unknown in CE_Text.cpp.
According to your comments, you included your header files in circular fashion. This is your problem right there. Never include header files circularly. Granted, your include guards make sure that the inclusion cycle gets broken in some way. But that does not in any way help your code to compile, as you can see in your example.
Until you completely remove any inclusion cycles from your code, trying to fix it is a crapshoot.
I have written a c++ program in Xcode to implement Symbolic Regression & Genetic Programming. I'd like to create a window to visualize the reference data (an array of 2d points) and the best function that the program generates each generation.
To put it simply, I'd like the window to show 2 graphs, and have it be updated with a for loop. From what I understand, GLUT seems like a good framework, and I've written a function to display the reference data (std::vector is how I'm storing the "referenceDataSet" variable):
void renderScene(){
// The min/max variables are just for scaling & centering the graph
double minX, maxX, minY, maxY;
minX = referenceDataSet[0].first;
maxX = referenceDataSet[0].first;
minY = referenceDataSet[0].second;
maxY = referenceDataSet[0].second;
for (int i = 0; i < referenceDataSet.size(); i++) {
minX = min(minX, referenceDataSet[i].first);
maxX = max(maxX, referenceDataSet[i].first);
minY = min(minY, referenceDataSet[i].second);
maxY = max(maxY, referenceDataSet[i].second);
}
glLoadIdentity ();
glClear(GL_COLOR_BUFFER_BIT);
glBegin( GL_LINE_STRIP );
glColor4f( 1.0, 0.0, 0.0, 1.0);
for (int i = 0; i < referenceDataSet.size(); i++) {
glVertex2f((referenceDataSet[i].first-minX)/(maxX-minX)-0.5, (referenceDataSet[i].second-minY)/(maxY-minY)-0.5);
}
glEnd();
glFlush();
}
void renderInit(int argc, char **argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(600, 600);
glutCreateWindow("");
glutDisplayFunc(renderScene);
glutCheckLoop();
}
The problem with this is that I'm not sure how I should go about updating the window, or drawing a second graph that constantly changes.
Also, this is my first question on Stack Overflow, so I apologize if I'm not doing something correctly here, or if any of this is difficult to understand. I searched as best I could for the answer, but couldn't really find anything relevant.
In glut or OpenGL, glutIdleFunc(void (*func)(void)) is used to update the scene.
The idle func will call the glutDisplayFunc every time the scene refreshes.
Reference is here http://www.opengl.org/resources/libraries/glut/spec3/node63.html
I guess renderScene() is your glutDisplayFunc. And you need to register an idle function using glutIdleFunc. In the idle function, you can change the parameters for the second graph that constantly changes, and renderScene() will be called again after changes in the idle function are done.
i am drawing an array of pool balls in opengl using c++
the problem i am facing is the array draws in a straight line.
when i use gltranslate the balls still only translate along the line when i edit the z and y axis
what i want to do is set the balls up in a triangle shape like the breaking of a pool match
how do i use the array code to set the balls up like this?
any help would be much appreciated
balls[7];
for (int x = ball-start; x<ball-end;x++)
{
glTranslatef(0,0,0.5);
glColor3f(1,0,0);
ball[x].drawball();
}
assuming:
struct Ball {
double x,y,z;
void drawball(void);
/* ... */
} ball[7];
try:
for(int i=0; i<7 ;i++)
{
glPushMatrix();
glTranslated(ball[i].x,ball[i].y,ball[i].z);
glColor3f(1,0,0);
ball[i].drawball();
glPopMatrix();
}
details probably vary, but hopefully you get the idea.
Do something like this:
// first of all, include the x,y position (assuming 2D, since pool) in the Ball object:
class Ball
{
//...
private:
float xpos, ypos;
//...
};
Then when you construct the array of balls, rather than just making 8 balls, you're going to want to allocate the memory on the heap so that it will last throughout your entire game. So do this:
Ball *ball= new Ball*[8];
ball[0] = new Ball(x0,y0);
ball[1] = new Ball(x1,y1);
ball[2] = new Ball(x2,y2);
ball[3] = new Ball(x3,y3);
// ...
Make sure that when your game is over, you clean up after yourself.
for (int i = 0; i < 8; i++)
delete ball[i];
delete [] ball;
Then in your Ball::draw() do something like this:
Ball::draw()
{
glColor3f(/*yellow*/); // Set the color to yellow
glTranslatef(-xpos, -ypos, 0); // Move to the position of the ball
// Draw the ball
glTranslatef(xpos, ypos, 0); // Move back to the default position
}
All you have to do is come up with the correct (x0,y0),(x1,y1),(x2,y2)... to form a triangle! Does this make sense/answer your question?