OpenGL曲线绘制:线段

以线段方式绘制曲线。例如:正弦曲线。
 glBegin(GL_LINE_STRIP);
 for(i=0;i {
  glVertex2f(XSTART+i*XSTEP*XSCALE, YSTART+sin(i*XSTEP)*XSCALE);
 }
 glEnd();
说明:XSTEP是横坐标点的间隔。XSCALE是为了适应屏幕大小,将图形放大。XSTART,YSTART是将曲线起点移动到左下角。

附:源码

///////////////////////////// 主程序 ///////////////////////////
// 等价无穷小的曲线绘制

#include "stdafx.h"

#include "windows.h"
#include "gl/gl.h"
#include "gl/glu.h"
#include "gl/glaux.h"
#include "conio.h"
#include "math.h"
#include "math01.h"

#define XSTEP (3.14/40)
#define POINTNUM 30
#define XSCALE 10
#define XSTART -10
#define YSTART -10

void DrawPoint2(GLfloat x, GLfloat y);
void CALLBACK myReshape(GLsizei w,GLsizei h);
void CALLBACK display(void);

int main(int argc, char* argv[])
{
 auxInitDisplayMode(AUX_SINGLE|AUX_RGBA);
 auxInitPosition(0,0,500,500);
 auxInitWindow("simple");
 
 glClearColor(0.0,0.0,0.0,0.0);
 glClear(GL_COLOR_BUFFER_BIT);

 auxReshapeFunc(myReshape);
 auxMainLoop(display);
 return 0;
}

void DrawPoint2(GLfloat x, GLfloat y)
{
 glBegin(GL_POINTS);
 glVertex2f(x,y);
 glEnd();
}

void CALLBACK myReshape(GLsizei w,GLsizei h)
{
 glViewport(0,0,w,h);
 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 if(w<=h)
  glOrtho(-15,15,-15*(GLfloat)h/(GLfloat)w,
   15*(GLfloat)h/(GLfloat)w,-10.0,10.0);
 else
  glOrtho(-15*(GLfloat)h/(GLfloat)w,
   15*(GLfloat)h/(GLfloat)w,-15,15,-10.0,10.0);

 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();
}


void CALLBACK display(void)
{
 int i;

 glColor3f(0.0,0.1,0.0);
 glRectf(-14,-14,14,14);

 // 两条坐标
 glColor3f(0.0,1.0,0.0);
 for(i=0;i { 
  DrawPoint2(YSTART+i*XSTEP*XSCALE, XSTART);
 }
 for(i=0;i { 
  DrawPoint2(XSTART,YSTART+i*XSTEP*XSCALE);
 }

 //sin
 glBegin(GL_LINE_STRIP);
 glColor3f(1.0,0.0,0.0);
 for(i=0;i {
  glVertex2f(XSTART+i*XSTEP*XSCALE,
   YSTART+sin(i*XSTEP)*XSCALE);
 }
 glEnd();

 //y=x
 glBegin(GL_LINE_STRIP);
 glColor3f(1.0,1.0,0.0);
 for(i=0;i {
  glVertex2f(XSTART+i*XSTEP*XSCALE,
   YSTART+(i*XSTEP)*XSCALE);
 }
 glEnd(); 
 //y=e(x)
 glBegin(GL_LINE_STRIP);
 glColor3f(1.0,0.0,0.5);
 for(i=0;i {
  glVertex2f(XSTART+i*XSTEP*XSCALE,
   YSTART+(E_Exp(i*XSTEP)-1)*XSCALE);
 }
 glEnd();

 glFlush(); 
}

///////////////////////////// 头文件 /////////////////////
//math01.h
//数学计算公式

#ifndef MYMATH01_H
#define MYMATH01_H

//x的n次方
float Mul(float x,int n);
int Jie(int n);
float E_Exp(float x);

float Mul(float x,int n)
{
 int i=0;
 float k=1;

 if(0==n)
  return 1;
 for(i=0;i {
  k*=x;
 }
 return k;
}

//n的阶乘
int Jie(int n)
{
 int k=1;

 if(0==n)
  return 1;
 for(;n>0;n--)
 {
  k*=n;
 }
 return k;

}

//e的x次方 麦克劳林级数,没有余项
float E_Exp(float x)
{
 int i;
 float sum=0;

 for(i=0;i<20;i++)
 {
  sum+=Mul(x,i)/Jie(i);
 }
 return sum;

}

#endif

你可能感兴趣的:(编程技术)