PDA

View Full Version : question over sine wave



ArmStrong
07-28-2009, 09:04 PM
I am a newbie of OpenGL, here is my code desired to draw a sine wave in [0,2*pi), but there is only a line between (0,0)and(0,1), any advice is appreciated!

here is my code

//************************************************//
#include <glut.h>
#define PI 3.14159265 // _USE_MATH_DEFINES
#include <math.h>
#include <iostream>
#define SIZE 2000

void drawline(float x1, float y1, float x2, float y2);
void sinewave();

int main(int argc, char ** argv)
{ glutInit(&amp;argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(400,400);
glutInitWindowPosition(200,200);

glutCreateWindow(" sinusoidal wave ");
glutDisplayFunc(sinewave);
glutMainLoop();
return 0;
}

void sinewave()
{
float x1, x2, y1, y2;
for (int i=0;i<SIZE;i++)
{
x1=i/SIZE;x2=(i+1)/SIZE;
y1=sin(x1*2*PI);
y2=sin(x2*2*PI);
drawline(x1,y1,x2,y2);
glutSwapBuffers();
}

}

void drawline(float x1, float y1, float x2, float y2)
{
glBegin(GL_LINE_STRIP); // LINE_STRIP | POINTS
glColor3f(1.0,0,0);
glVertex2f(x1,y1);
glVertex2f(x2,y2);
glEnd();
}

matchStickMan
07-28-2009, 11:06 PM
you are almost there.

Just change this line:

x1=i/SIZE;x2=(i+1)/SIZE;


to something like:

x1=(float)i/SIZE;
x2=((float)i+1.0)/SIZE;


You get a straight line because you are dividing integers.

thekend
07-28-2009, 11:08 PM
Hi,

The problem is with integer division:

x1=i/SIZE;x2=(i+1)/SIZE
will always give you 0 or 1 for x0 and x2. You have to cast to float (either i or SIZE or both).

ArmStrong
07-29-2009, 06:33 AM
thanks a lot, I thought I was missing some window-configuration lines.