ine 5341 

Programa

OpenGL

Links

Bibliografia

Plano de Ensino

Tutorial de OpenGL: Usando Borland C++ e GLUT

Por  Tiago Stein D'Agostini <stein@inf.ufsc.br>

Aqui vão os arquivos que o pessoal deve usar nos seus projetos de OpenGL com C Builder. Eles foram feitos e testados na versão 5, portanto não granto nenhuma compatibilidade com outras versões.
 
DICA: para usá-los abra o exemplo de OpenGL do próprio CBuilder e substitua os arquivos homônimos a estes que estào nesta página e salve como um outro projeto.
 
Na verdade estes arquivos são baseados nos arquivos dos exemplos do Builder para garantir a compatibilidade. Observem entretanto que foram radicalmente mudados, para excluir tópicos avançados como pré-T&L e Texturização.
 
Como os exemplos do Builder são linkados à biblioteca da Microsoft, não será necessário instalar o OpeGL da SGI, com o revés de ter um desempenho bem pior.

Voce vai precisar de tres arquivos: GlSkel.h, GlSkel.cpp e GlSkel.dfm.

Abaixo vai a listagem dos arquivos:



Arquivo GlSkel.h


//---------------------------------------------------------------------------
#ifndef GlSkelH
#define GlSkelH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <gl\gl.h>
#include <gl\glu.h>
//---------------------------------------------------------------------------
class TFormMain : public TForm
{
__published: 
    void __fastcall FormResize(TObject *Sender);
    void __fastcall FormPaint(TObject *Sender);
    void __fastcall FormDestroy(TObject *Sender);
    void __fastcall FormCreate(TObject *Sender);
    void __fastcall FormKeyDown(TObject *Sender, WORD &Key,
          TShiftState Shift);
private:
    HDC hdc;
    HGLRC hrc;
    float w,h;
    int PixelFormat;

   
public:
    __fastcall TFormMain(TComponent* Owner);
    void __fastcall IdleLoop(TObject*, bool&);
    void __fastcall RenderGLScene();
    void __fastcall SetPixelFormatDescriptor();
    void __fastcall DrawObjects();
    void __fastcall SetupLighting();
};
//---------------------------------------------------------------------------
extern PACKAGE TFormMain *FormMain;
//---------------------------------------------------------------------------
#endif



Arquivo GlSkel.cpp


//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "GlSkel.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TFormMain *FormMain;
//---------------------------------------------------------------------------
__fastcall TFormMain::TFormMain(TComponent* Owner)
    : TForm(Owner)
{
    Application->OnIdle = IdleLoop;
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::IdleLoop(TObject*, bool& done)
{
    done = false;
    RenderGLScene();
    SwapBuffers(hdc);    // USADO PARA DOUBLE BUFFERING
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::FormCreate(TObject *Sender)
{
    hdc = GetDC(Handle);
    SetPixelFormatDescriptor();
    hrc = wglCreateContext(hdc);
    if(hrc == NULL)
     ShowMessage("Deu pau na obtenção do hrc!!");
    if(wglMakeCurrent(hdc, hrc) == false)
     ShowMessage("Could not MakeCurrent");
    w = ClientWidth;
    h = ClientHeight;

    glEnable(GL_DEPTH_TEST);
    //glEnable(GL_CULL_FACE);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f); //cor de limpeza
    SetupLighting();     //comentar para desabilitar luzes
}
//---------------------------------------------------------------------------
//   SetPixelFormatDescriptor()
//---------------------------------------------------------------------------
// Descreve as características de pixel que o hdc utilizará no programa
// IMPORTANTE: Algumas implementações em hardware, especialmente as mais antigas
// podem não suportar este descriptor
//---------------------------------------------------------------------------
void __fastcall TFormMain::SetPixelFormatDescriptor()
{
    PIXELFORMATDESCRIPTOR pfd = {
     sizeof(PIXELFORMATDESCRIPTOR),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
        PFD_TYPE_RGBA,
        24,   //Bit color; Mudar para 16 ou 32 dependendo da placa de vídeo
        0,0,0,0,0,0,
        0,0,
        0,0,0,0,0,
        16,   //tamanho do depth buffer; Usar 32 em placas modernas
        0,
        0,
        PFD_MAIN_PLANE,
        0,
        0,0,
    };
    PixelFormat = ChoosePixelFormat(hdc, &pfd); //retorna o resultado do pedido
                                        //sobre a avaliabilidade do pixel format
    SetPixelFormat(hdc, PixelFormat, &pfd);//determina que hdc use &pdf
}
//---------------------------------------------------------------------------
// FormResize()
//---------------------------------------------------------------------------
//IMPORTANTE! NÃO MEXA SE NÃO SOUBER OQ ESTÁ FAZENDO
//---------------------------------------------------------------------------
void __fastcall TFormMain::FormResize(TObject *Sender)
{
    GLfloat nRange = 50.0;
    w = ClientWidth;
    h = ClientHeight;

    if(h == 0)
     h = 1;
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    if (w <= h)
        glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
    else
 glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);

    //Projecao perspectiva
    //GLfloat aspect = (GLfloat)w/(GLfloat)h;
    //gluPerspective(30.0f, aspect, 1.0, 50.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::RenderGLScene()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    DrawObjects();
    glFlush();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::DrawObjects()
{
  //COLOCAR CÒDIGO PARA DESENHO DE GEOMETRIA AQUI
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::FormPaint(TObject *Sender)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glFlush();
    DrawObjects();
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::FormDestroy(TObject *Sender)
{

    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(hrc);
}

//---------------------------------------------------------------------------
void __fastcall TFormMain::FormKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
    if(Key == VK_UP)
        glRotatef(-5, 1.0, 0.0, 0.0);
    if(Key == VK_DOWN)
        glRotatef(5, 1.0, 0.0, 0.0);
    if(Key == VK_LEFT)
        glRotatef(-5, 0.0, 1.0, 0.0);
    if(Key == VK_RIGHT)
        glRotatef(5, 0.0, 1.0, 0.0);
}
//---------------------------------------------------------------------------
//  SetupLighting()
//---------------------------------------------------------------------------
// habilita e determina os parâmetros de uma fonte de luz
//---------------------------------------------------------------------------
void __fastcall TFormMain::SetupLighting()
{
    GLfloat MaterialAmbient[] = {0.5, 0.5, 0.5, 1.0};
    GLfloat MaterialDiffuse[] = {1.0, 1.0, 1.0, 1.0};
    GLfloat MaterialSpecular[] = {1.0, 1.0, 1.0, 1.0};
    GLfloat MaterialShininess[] = {50.0};
    GLfloat AmbientLightPosition[] = {0.5, 1.0, 1.0, 0.0};
    GLfloat LightAmbient[] = {0.5, 0.5, 0.5, 1.0};

    glMaterialfv(GL_FRONT, GL_AMBIENT, MaterialAmbient);
    glMaterialfv(GL_FRONT, GL_DIFFUSE, MaterialDiffuse);
    glMaterialfv(GL_FRONT, GL_SPECULAR, MaterialSpecular);
    glMaterialfv(GL_FRONT, GL_SHININESS, MaterialShininess);
    glLightfv(GL_LIGHT0, GL_POSITION, AmbientLightPosition);
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LightAmbient);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
    glShadeModel(GL_SMOOTH);
}
//---------------------------------------------------------------------------



Arquivo GlSkel.dfm