2012-07-30 50 views
2

只是學習一些與delphi的OpenGL,並嘗試一些簡單但沒有得到結果,我相信我應該得到一個深綠色的形式。但是,當我運行這個我什麼也得不到。沒有錯誤。也許錯過了什麼?簡單的OpenGL代碼不工作

unit First1; 

interface 

uses 
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, 
    Vcl.Controls,OpenGL, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; 

type 
    TForm2 = class(TForm) 
    procedure FormCreate(Sender: TObject); 
    procedure FormDestroy(Sender: TObject); 
    procedure FormPaint(Sender: TObject); 
    private 
    { Private declarations } 
    GLContext : HGLRC; 
    ErrorCode: GLenum; 
    public 
    { Public declarations } 
    end; 

var 
    Form2: TForm2; 

implementation 

{$R *.dfm} 

procedure TForm2.FormCreate(Sender: TObject); 
var 
    pfd: TPixelFormatDescriptor; 
    FormatIndex: integer; 
begin 
    fillchar(pfd,SizeOf(pfd),0); 
    with pfd do 
    begin 
     nSize := SizeOf(pfd); 
     nVersion := 1; {The current version of the desccriptor is 1} 
     dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL; 
     iPixelType := PFD_TYPE_RGBA; 
     cColorBits := 24; {support 24-bit color} 
     cDepthBits := 32; {depth of z-axis} 
     iLayerType := PFD_MAIN_PLANE; 
    end; {with} 
    FormatIndex := ChoosePixelFormat(Canvas.Handle,@pfd); 
    SetPixelFormat(Canvas.Handle,FormatIndex,@pfd); 
    GLContext := wglCreateContext(Canvas.Handle); 
    wglMakeCurrent(Canvas.Handle,GLContext); 
end; {FormCreate} 

procedure TForm2.FormDestroy(Sender: TObject); 
begin 
    wglMakeCurrent(Canvas.Handle,0); 
    wglDeleteContext(GLContext); 
end; 

procedure TForm2.FormPaint(Sender: TObject); 
begin 
    {background} 
    glClearColor(0.0,0.4,0.0,0.0); 
    glClear(GL_COLOR_BUFFER_BIT); 
{error checking} 
    errorCode := glGetError; 
    if errorCode<>GL_NO_ERROR then 
     raise Exception.Create('Error in Paint'#13+ 
    gluErrorString(errorCode)); 
end; 

end. 
+0

不是專家,因此是一個評論:再次調用'wglMakeCurrent'作爲兩個參數來使渲染上下文*不是當前*,這將刷新你所繪製的。這可能意味着你必須在OnPaint中創建上下文(和刪除)。在MSDN上搜索「呈現上下文」。 – 2012-07-31 00:19:19

回答

5

既然你要求一個緩衝的情況下,你必須在渲染代碼的末尾調用glFinish,提交你的繪圖命令來實現。不過,我強烈建議你切換到使用雙緩衝上下文,而不是glFinish-你發出一個wglSwapBuffers這意味着完成。

+0

我想學習一本書,但很高興知道。我儘快加入glfinish,只要我回家。歡呼 – 2012-07-31 08:14:13

+0

GLFinish工作,但現在iam有興趣知道這個wglswapBuffers .. – 2012-08-02 06:54:34

+1

@GlenMorse:你可以通過添加標誌PFD_DOUBLEBUFFER到PFD.dwFlags位來啓用雙緩衝。這應該給你一個雙緩衝窗口。然後像往常一樣執行OpenGL,但是用'wglSwapBuffers'完成。順便說一句:您創建OpenGL上下文的方式嚴重過時,您通常希望使用wglCreateContextAttribsARB來使用該方法 - Google會爲您找到大量教程。 – datenwolf 2012-08-02 09:33:50