アットウィキロゴ

OpenGLのサンプルプログラム



二次元グラフ

#include <iostream>
#include <cmath>
#include <GL/glut.h>
 
//------------ 各種外部変数 ---------------------//
struct GRAPH
{
        double Left,Right;
        double Top,Buttom;
        double unit; //x座標をどれだけの間隔で見て行くか?
};
GRAPH graph = {-180,180,1,-1,5};
 
const double PI_OVER_180 = 0.0174532925;//ラジアン変換用
 
 
//------------ プロトタイプ宣言 ----------------//
void display();
void reshape(int w, int h);
void ShowInfomation(GRAPH &graph);
void DrawGraph();
void DrawAxis();
 
//---------- 描画したい関数 -----------//
inline double function(double x) 
{
	return 0.5*x*PI_OVER_180*sin(x*PI_OVER_180);
}
 
//------------- OpenGLの初期設定 -----------------------//
void GLUT_INIT()
{
        glutInitDisplayMode(GLUT_RGBA| GLUT_DOUBLE);
        glutInitWindowSize(640,480);
        glutCreateWindow("Draw Graph");
}
 
 
void GLUT_CALL_FUNC()
{
        glutDisplayFunc(display);
        glutReshapeFunc(reshape);
}
 
void MY_INIT()
{
        glClearColor(1.0, 1.0, 1.0, 1.0);
        ShowInfomation(graph);
}
 
 
//-------------- メイン関数 ---------------------//
int main(int argc, char *argv[])
{
        glutInit(&argc,argv);
        GLUT_INIT();
 
        GLUT_CALL_FUNC();
        MY_INIT();
 
        glutMainLoop();
 
        return 0;
}
 
 
//--------------- ここから各種コールバック -------------------------//
void display(void)
{
        glClear(GL_COLOR_BUFFER_BIT);
        //軸描画
        DrawAxis();
 
        glLineWidth(1);
        glColor3f(1,0,1);
        DrawGraph();
        glColor3f(1,1,1);
        glLineWidth(1);
 
        glutSwapBuffers();
}
 
void reshape(int w, int h)
{
        glClear(GL_COLOR_BUFFER_BIT);
 
        glViewport(0, 0, w, h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(graph.Left, graph.Right, graph.Buttom, graph.Top); //仮想3D空間のスクリーンサイズ決定
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
		display();
}
 
 
//---------------- ここから、各種関数 -----------------------//
void ShowInfomation(GRAPH &graph)
{
        std::cout << "RangeX: [" << graph.Left << " , " << graph.Right << "]\n";
        std::cout << "RangeY : [" << graph.Buttom <<" , "<< graph.Top << "]\n";
}
 
void DrawGraph()
{
        static double x = 0;
        glBegin(GL_LINE_STRIP);
        for(x = graph.Left ;x <= graph.Right; x += graph.unit)
        {
                glVertex2f(x,function(x)); //描画したい関数
        }
 
        glEnd();
}
 
void DrawAxis()
{
        glBegin(GL_LINES);
        glColor3f(1,0,0);
        glVertex2f(graph.Left,0);
        glVertex2f(graph.Right,0);
        glColor3f(0,0,1);
        glVertex2f(0, graph.Buttom);
        glVertex2f(0, graph.Top);
        glEnd();
        glColor3f(1,1,1);
}
 
 

タグ:

+ タグ編集
  • タグ:
最終更新:2013年09月20日 02:08