OpenGL – C++ Bài 2: Vẽ các hình học cơ bản trong opengl

Hi. Chào mừng các bạn đến chủ đề học lập trình opengl tại blog: Phát Triển Phần Mềm 123-az
1. Vẽ các điểm trong OpenGL.

Sử dụng glBegin(GL_POINTS) glEnd và các verterx như sau đây

void RenderScene()
{
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();

glBegin(GL_POINTS);
glPointSize(2.0);
glVertex3f(0.0, 0.0, 0.0);
glEnd();

glPopMatrix();
glFlush();
}
2. Vẽ một đường thằng trong OpenGL .
 glBegin(GL_LINES);
 glVertex3f(0.0, 0.0, 0.0);
 glVertex3f(5.0, 0.0, 0.0);
 glEnd();

Nhìn hình minh họa dưới dây, bạn có thể vẽ được nhiều dạng line khác nhau với nhiều lựa chọn khác nhau

3. Sử dụng các hàm có sẵn trong OpenGL để vẽ các đối tượng solid/wire frame sẵn có như sau:

glutSolidTeapot; glutWireTeapot; glutSolidTeapot; glutWireTeapot;

#include <stdio.h>
#include <GL/glut.h> 


void DrawCoodinate()
{
    glColor3f(1.0,0.0,0.0); 
    glBegin(GL_LINES); 
    glVertex3f(100.0,0.0,0.0);
    glVertex3f(-100.0,0.0,0.0);
    glVertex3f(10.0,0.0,0.0);
    glEnd();

    glColor3f(0.0,1.0,0.0);
    glBegin(GL_LINES); 
    glVertex3f(0.0,100.0,0.0);
    glVertex3f(0.0,-100.0,0.0);
    glEnd();

    glColor3f(0.0,0.0,1.0);
    glBegin(GL_LINES);
    glVertex3f(0.0,0.0,100.0);
    glVertex3f(0.0,0.0,-100.0);
    glVertex3f(0.0,0.0,10.0);
    glEnd();
}


void RenderScene()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    gluLookAt(0.5,0.0,0.5, 0.0,0.0,0.0, 0.0,1.0,0.0); 
    DrawCoodinate();
    glPushMatrix();
    glTranslatef(-2.0, 0.0, 0.0);
    glColor3f(1.0, 0.5, 0.5);
    glutWireTeapot(0.1);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(-1.0, 0.0, 0.0);
    glRotatef(-90.0, 1.0, 0.0, 0.0);
    glColor3f(1.0, 0.0, 0.5);
    glutWireCone(0.1, 0.2, 16, 64);
    glPopMatrix();

    glPushMatrix();
    glTranslatef(-0.2, 0.0, 0.0);
    glColor3f(1.0, 0.8, 0.3);
    glutWireTorus(0.05, 0.1, 16, 64);
    glPopMatrix();

    glutSwapBuffers();
    glFlush();
}

void ReShape(int width, int height)
{
    if (height == 0)
    {
        height = 1;
    }

    float ratio = (float)width/(float)height;

    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    gluPerspective(45.0, ratio, 0.1, 100.0);
    glMatrixMode(GL_MODELVIEW);
}



void main()
{
	glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
	glutInitWindowSize(1200,600);
	glutInitWindowPosition(100,100);
	glutCreateWindow ("Phat Trien Phan Mem 123AZ");
	glutReshapeFunc(ReShape);
	glutDisplayFunc(RenderScene);
	glutMainLoop();
}

 

 

 

Lưu

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.