全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:2028
推到 Plurk!
推到 Facebook!

(徵求) openGL應用於可視化元件之最精簡程式碼

缺席
yangkissktop
一般會員


發表:13
回覆:29
積分:8
註冊:2003-10-25

發送簡訊給我
#1 引用回覆 回覆 發表時間:2005-10-02 22:00:12 IP:59.104.xxx.xxx 未訂閱
個人使用OpenGL的經驗已有好多年了,但是因個人才疏學淺,不是從Win32 API出身,長年心中一直有個問題,該項技術一直未研發出來收錄在個人筆記中,故希望徵求openGL應用於可視化元件之精簡程式碼,其限制條件如下 : 0. 目標為使用OpenGL技術於TPanel,TPaintBox,... 1. 使用 "全螢幕" 顯示OpenGL畫面者非正解 2. 使用 "GLUT,GLAUX開視窗技術" 顯示OpenGL畫面者非正解 3. 使用 "整個FORM" 顯示OpenGL畫面者非正解 4. 使用 "他人研發之component" 來顯示OpenGL畫面者非正解 5. 使用 "整個FORM客戶區繪圖並浮搭TPanel裝控制項" 者非正解 6. WGL類之函數使用必須節制,只使用必要程式碼達成使用OpenGL之目的,而非求OpenGL環境之完整,亦可使用繼承方式建構最簡單之OpenGL控制項 如有高手能一解小弟心中疑惑,僅致上12萬分謝意!!!!!!!!!!!!!!!! yangkissktop
------
yangkissktop
yangkissktop
一般會員


發表:13
回覆:29
積分:8
註冊:2003-10-25

發送簡訊給我
#2 引用回覆 回覆 發表時間:2005-10-07 05:47:39 IP:59.104.xxx.xxx 未訂閱
本問題貼上已一周尚無人回應,僅貼上NEHE教學網站第一課參考程式碼做個起頭,原先視窗是可執行的,但改成PANEL則不可執行,原因可能出在裝置內容DC或RC上
//---------------------------------------------------------------------------    #include 
#include     // Header file for windows
#include       // Header file for the OpenGL32 library
#include      // Header file for the GLu32 library
#include    // Header file for the GLaux library
#pragma hdrstop    //---------------------------------------------------------------------------
#pragma argsused    HGLRC hRC = NULL;               // Permanent rendering context
HDC hDC = NULL;                 // Private GDI device context
HWND hWnd = NULL;               // Holds our window handle
HINSTANCE hInstance = NULL;     // Holds the instance of the application    bool keys[256];                 // Array used for the keyboard routine
bool active = true;             // Window active flag set to true by default
bool fullscreen = true;         // Fullscreen flag set to fullscreen mode by default    LRESULT        CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);   // Declaration for WndProc    GLvoid ReSizeGLScene(GLsizei width, GLsizei height)     // Resize and initialize the GL window
{
        if (height == 0)                        // Prevent a divide by zero by
        {
                height = 1;                     // Making height equal One
        }            glViewport(0, 0, width, height);        // Reset the current viewport            glMatrixMode(GL_PROJECTION);            // Select the projection matrix
        glLoadIdentity();                       // Reset the projection matrix            // Calculate the aspect ratio of the window
        gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);            glMatrixMode(GL_MODELVIEW);             // Select the modelview matrix
        glLoadIdentity();                       // Reset the modelview matrix
}    int InitGL(GLvoid)      // All setup for OpenGL goes here
{
        glShadeModel(GL_SMOOTH);                // Enable smooth shading
        glClearColor(0.0f, 0.0f, 0.0f, 0.5f);   // Black background
        glClearDepth(1.0f);                     // Depth buffer setup
        glEnable(GL_DEPTH_TEST);                // Enables depth testing
        glDepthFunc(GL_LEQUAL);                 // The type of depth testing to do
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);      // Really nice perspective calculations
        return true;                            // Initialization went OK
}    int DrawGLScene(GLvoid)         // Here's where we do all the drawing
{
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);        // clear screen and depth buffer
        glLoadIdentity();       // Reset the current modelview matrix
        
        return true;            // Everything went OK
}    GLvoid KillGLWindow(GLvoid)     // Properly kill the window
{
        if (fullscreen)         // Are we in fullscreen mode?
        {
                ChangeDisplaySettings(NULL,0);  // If so switch back to the desktop
                ShowCursor(true);               // Show mouse pointer
        }            if (hRC)        // Do we have a rendering context?
        {
                if (!wglMakeCurrent(NULL,NULL))         // Are we able to release the DC and RC contexts?
                {
                        MessageBox(NULL,"Release of DC and RC failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
                }                    if (!wglDeleteContext(hRC))             // Are we able to delete the RC?
                {
                        MessageBox(NULL,"Release rendering context failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
                }
                hRC = NULL;             // Set RC to NULL
        }            if (hDC && !ReleaseDC(hWnd,hDC))        // Are we able to release the DC
        {
                MessageBox(NULL,"Release device context failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
                hDC = NULL;             // Set DC to NULL
        }            if (hWnd && !DestroyWindow(hWnd))       // Are we able to destroy the window?
        {
                MessageBox(NULL,"Could not release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
                hWnd = NULL;            // Set hWnd to NULL
        }            if (!UnregisterClass("OpenGL",hInstance))       // Are we able to unregister class
        {
                MessageBox(NULL,"Could not unregister class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
                hInstance = NULL;       // Set hInstance to NULL
        }
}    /*        This Code Creates Our OpenGL Window.  Parameters Are:
 *        title                        - Title To Appear At The Top Of The Window
 *        width                        - Width Of The GL Window Or Fullscreen Mode
 *        height                        - Height Of The GL Window Or Fullscreen Mode
 *        bits                        - Number Of Bits To Use For Color (8/16/24/32)
 *        fullscreenflag        - Use Fullscreen Mode (true) Or Windowed Mode (false)*/
 
bool CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
        GLuint                PixelFormat;                // Holds the results after searching for a match
        WNDCLASS        wc;                        // Windows class structure
        DWORD                dwExStyle;              // Window extended style
        DWORD                dwStyle;                // Window style
        RECT                WindowRect;             // Grabs rctangle upper left / lower right values
        WindowRect.left = (long)0;              // Set left value to 0
        WindowRect.right = (long)width;                // Set right value to requested width
        WindowRect.top = (long)0;               // Set top value to 0
        WindowRect.bottom = (long)height;       // Set bottom value to requested height            fullscreen = fullscreenflag;              // Set the global fullscreen flag            hInstance               = GetModuleHandle(NULL);                // Grab an instance for our window
        wc.style                = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;   // Redraw on size, and own DC for window
        wc.lpfnWndProc          = (WNDPROC) WndProc;                        // WndProc handles messages
        wc.cbClsExtra           = 0;                                        // No extra window data
        wc.cbWndExtra           = 0;                                        // No extra window data
        wc.hInstance            = hInstance;                                // Set the Instance
        wc.hIcon                = LoadIcon(NULL, IDI_WINLOGO);                // Load the default icon
        wc.hCursor              = LoadCursor(NULL, IDC_ARROW);                // Load the arrow pointer
        wc.hbrBackground        = NULL;                                        // No background required for GL
        wc.lpszMenuName                = NULL;                                        // We don't want a menu
        wc.lpszClassName        = "OpenGL";                                // Set the class name            if (!RegisterClass(&wc))                                        // Attempt to register the window class
        {
                MessageBox(NULL,"Failed to register the window class.","Error",MB_OK|MB_ICONEXCLAMATION);                    return false;   // Return false
        }
        
        if (fullscreen)         // Attempt fullscreen mode?
        {
                DEVMODE dmScreenSettings;                                       // Device mode
                memset(&dmScreenSettings,0,sizeof(dmScreenSettings));                // Makes sure memory's cleared
                dmScreenSettings.dmSize         = sizeof(dmScreenSettings);     // Size of the devmode structure
                dmScreenSettings.dmPelsWidth        = width;                        // Selected screen width
                dmScreenSettings.dmPelsHeight        = height;                       // Selected screen height
                dmScreenSettings.dmBitsPerPel        = bits;                                // Selected bits per pixel
                dmScreenSettings.dmFields       = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;                    // Try to set selected mode and get results. NOTE: CDS_FULLSCREEN gets rid of start bar.
                if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
                {
                        // If the mode fails, offer two options. Quit or use windowed mode.
                        if (MessageBox(NULL,"The requested fullscreen mode is not supported by\nyour video card. Use windowed mode instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION) == IDYES)
                        {
                                fullscreen = false;       // Windowed mode selected. Fullscreen = false
                        }
                        else
                        {
                                // Pop up a message box letting user know the program is closing.
                                MessageBox(NULL,"Program will now close.","ERROR",MB_OK|MB_ICONSTOP);
                                return false;           // Return false
                        }
                }
        }            if (fullscreen)                         // Are We Still In Fullscreen Mode?
        {
                dwExStyle = WS_EX_APPWINDOW;    // Window extended style
                dwStyle = WS_POPUP;                // Windows style
                ShowCursor(false);                // Hide mouse pointer
        }
        else
        {
                dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;           // Window extended style
                dwStyle = WS_OVERLAPPEDWINDOW;                            // Windows style
        }            AdjustWindowRectEx(&WindowRect,dwStyle,false,dwExStyle);        // Adjust window to true requested size            // Create the window
        if (!(hWnd = CreateWindowEx(dwExStyle,          // Extended Style For The Window
                "OpenGL",                                // Class name
                title,                                        // Window title
                dwStyle |                                // Defined window style
                WS_CLIPSIBLINGS |                        // Required window style
                WS_CLIPCHILDREN,                        // Required window style
                0, 0,                                        // Window position
                WindowRect.right-WindowRect.left,        // Calculate window width
                WindowRect.bottom-WindowRect.top,        // Calculate window height
                NULL,                                        // No parent window
                NULL,                                        // No menu
                hInstance,                                // Instance
                NULL)))                                        // Dont pass anything to WM_CREATE
        {
                KillGLWindow();                         // Reset the display
                MessageBox(NULL,"Window creation error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
                return false;                           // Return false
        }            static        PIXELFORMATDESCRIPTOR pfd =             // pfd tells windows how we want things to be
        {
                sizeof(PIXELFORMATDESCRIPTOR),          // Size of this pixel format descriptor
                1,                                        // Version number
                PFD_DRAW_TO_WINDOW |                        // Format must support window
                PFD_SUPPORT_OPENGL |                        // Format must support OpenGL
                PFD_DOUBLEBUFFER,                        // Must support double buffering
                PFD_TYPE_RGBA,                                // Request an RGBA format
                bits,                                        // Select our color depth
                0, 0, 0, 0, 0, 0,                        // Color bits ignored
                0,                                        // No alpha buffer
                0,                                        // Shift bit ignored
                0,                                        // No accumulation buffer
                0, 0, 0, 0,                                // Accumulation bits ignored
                16,                                        // 16Bit Z-Buffer (Depth buffer)
                0,                                        // No stencil buffer
                0,                                        // No auxiliary buffer
                PFD_MAIN_PLANE,                                // Main drawing layer
                0,                                        // Reserved
                0, 0, 0                                        // Layer masks ignored
        };
        
        if (!(hDC = GetDC(hWnd)))         // Did we get a device context?
        {
                KillGLWindow();         // Reset the display
                MessageBox(NULL,"Can't create a GL device context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
                return false;           // Return false
        }            if (!(PixelFormat = ChoosePixelFormat(hDC,&pfd)))        // Did windows find a matching pixel format?
        {
                KillGLWindow();         // Reset the display
                MessageBox(NULL,"Can't find a suitable pixelformat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
                return false;           // Return false
        }            if(!SetPixelFormat(hDC,PixelFormat,&pfd))       // Are we able to set the pixel format?
        {
                KillGLWindow();         // Reset the display
                MessageBox(NULL,"Can't set the pixelformat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
                return false;           // Return false
        }            if (!(hRC = wglCreateContext(hDC)))               // Are we able to get a rendering context?
        {
                KillGLWindow();         // Reset the display
                MessageBox(NULL,"Can't create a GL rendering context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
                return false;           // Return false
        }            if(!wglMakeCurrent(hDC,hRC))    // Try to activate the rendering context
        {
                KillGLWindow();         // Reset the display
                MessageBox(NULL,"Can't activate the GL rendering context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
                return false;           // Return false
        }            ShowWindow(hWnd,SW_SHOW);       // Show the window
        SetForegroundWindow(hWnd);      // Slightly higher priority
        SetFocus(hWnd);                 // Sets keyboard focus to the window
        ReSizeGLScene(width, height);   // Set up our perspective GL screen            if (!InitGL())                  // Initialize our newly created GL window
        {
                KillGLWindow();         // Reset the display
                MessageBox(NULL,"Initialization failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
                return false;           // Return false
        }            return true;                    // Success
}    LRESULT CALLBACK WndProc(HWND hWnd,     // Handle for this window
                        UINT uMsg,      // Message for this window
                        WPARAM wParam,  // Additional message information
                        LPARAM lParam)  // Additional message information
{
        switch (uMsg)                           // Check for windows messages
        {
                case WM_ACTIVATE:               // Watch for window activate message
                {
                        if (!HIWORD(wParam))    // Check minimization state
                        {
                                active = true;  // Program is active
                        }
                        else
                        {
                                active = false; // Program is no longer active
                        }                            return 0;               // Return to the message loop
                }                    case WM_SYSCOMMAND:             // Intercept system commands
                {
                        switch (wParam)         // Check system calls
                        {
                                case SC_SCREENSAVE:     // Screensaver trying to start?
                                case SC_MONITORPOWER:        // Monitor trying to enter powersave?
                                return 0;       // Prevent from happening
                        }
                        break;                  // Exit
                }                    case WM_CLOSE:                  // Did we receive a close message?
                {
                        PostQuitMessage(0);     // Send a quit message
                        return 0;               // Jump back
                }                    case WM_KEYDOWN:                // Is a key being held down?
                {
                        keys[wParam] = true;    // If so, mark it as true
                        return 0;               // Jump back
                }                    case WM_KEYUP:                  // Has a key been released?
                {
                        keys[wParam] = false;   // If so, mark it as false
                        return 0;               // Jump back
                }                    case WM_SIZE:                   // Resize the OpenGL window
                {
                        ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord = Width, HiWord = Height
                        return 0;               // Jump back
                }
        }            // Pass all unhandled messages to DefWindowProc
        return DefWindowProc(hWnd,uMsg,wParam,lParam);
}    WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
        MSG msg;                // Windows message structure
        bool done = false;      // bool variable to exit loop            // Ask the user which screen mode they prefer
        if (MessageBox(NULL,"Would you like to run in fullscreen mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION) == IDNO)
        {
                fullscreen = false;       // Windowed mode
        }            // Create our OpenGL window
        if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
        {
                return 0;               // Quit if window was not created
        }            while(!done)                    // Loop that runs while done = false
        {
                if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))        // Is there a message waiting?
                {
                        if (msg.message == WM_QUIT)             // Have we received a quit message?
                        {
                                done = true;                    // If so done = true
                        }
                        else                                    // If not, deal with window messages
                        {
                                TranslateMessage(&msg);         // Translate the message
                                DispatchMessage(&msg);          // Dispatch the message
                        }
                }
                else            // If there are no messages
                {
                        // Draw the scene.  Watch for ESC key and quit messages from DrawGLScene()
                        if (active)                             // Program active?
                        {
                                if (keys[VK_ESCAPE])            // Was ESC pressed?
                                {
                                        done = true;            // ESC signalled a quit
                                }
                                else                            // Not time to quit, Update screen
                                {
                                        DrawGLScene();          // Draw the scene
                                        SwapBuffers(hDC);       // Swap buffers (Double buffering)
                                }
                        }                            if (keys[VK_F1])                        // Is F1 being pressed?
                        {
                                keys[VK_F1] = false;            // If so make key false
                                KillGLWindow();                 // Kill our current window
                                fullscreen =! fullscreen;       // Toggle fullscreen / windowed mode
                                // Recreate our OpenGL window
                                if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
                                {
                                        return 0;               // Quit if window was not created
                                }
                        }
                }
        }            // Shutdown
        KillGLWindow();         // Kill the window
        return (msg.wParam);    // Exit the program
}
//---------------------------------------------------------------------------
. yangkissktop
------
yangkissktop
yangkissktop
一般會員


發表:13
回覆:29
積分:8
註冊:2003-10-25

發送簡訊給我
#3 引用回覆 回覆 發表時間:2005-10-07 06:24:35 IP:59.104.xxx.xxx 未訂閱
若各位覺得上述WINMAIN程式太繁雜,不妨試試下面較精簡之FORM
載入Lib函式庫到專案:
Project ? Add to Project
  ? 檔案類型選「*.lib」
  ? opengl32.lib、glu32.lib、glut32.lib    (一)Unit1.h:
#ifndef Unit1H
#define Unit1H
#include 
#include 
#include 
#include <Forms.hpp>
//---------------------------------------------------------------------------
#include 
#include 
#include 
#include 
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
   __published:
     void __fastcall FormCreate (TObject *Sender);
     void __fastcall FormResize (TObject *Sender);
     void __fastcall FormPaint  (TObject *Sender);
     void __fastcall FormDestroy(TObject *Sender);       private:
     HDC                myDc;
     int                myPf;
     HGLRC        myRc;         void  myDraw();       public:
     __fastcall TForm1(TComponent* Owner);
};    (二)Unit1.cpp:
#include 
#pragma hdrstop
#include "Unit1.h"
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
//   this->ClientWidth  = 300;
//   this->ClientHeight = 300;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
   myDc = GetDC( this->Handle );
   PIXELFORMATDESCRIPTOR  myPfd =
   {        sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW  |  PFD_SUPPORT_OPENGL  |  PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0,0, 0,0, 0,0,
0,0,
0, 0,0,0,0,
32,
0, 0,
PFD_MAIN_PLANE,
0,
0,0,0
   };
   myPf = ChoosePixelFormat(myDc, &myPfd);
   SetPixelFormat(myDc, myPf, &myPfd);
   myRc = wglCreateContext( myDc );
   wglMakeCurrent(myDc, myRc);       glClearColor(1,1,1, 0);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormResize(TObject *Sender)
{
   if(ClientWidth >= ClientHeight) 
        glViewport(0,0, ClientHeight,ClientHeight);
   else  glViewport(0,0, ClientWidth ,ClientWidth );       this->Repaint();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint(TObject *Sender)
{
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);       glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
   glOrtho(-1,1, -1,1, 0,2);                //z=0~-4; x=-1~1, y=-1~1
   gluLookAt(0,0,1, 0,0,0, 0,1,0);        //由 z往-z看       glMatrixMode( GL_MODELVIEW );
   glLoadIdentity();       myDraw();
}    void TForm1::myDraw()
{
   glFlush();
   SwapBuffers( myDc );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
   wglMakeCurrent(NULL, NULL);
   wglDeleteContext( myRc );
}
//---------------------------------------------------------------------------
yangkissktop
------
yangkissktop
yangkissktop
一般會員


發表:13
回覆:29
積分:8
註冊:2003-10-25

發送簡訊給我
#4 引用回覆 回覆 發表時間:2005-10-07 19:34:40 IP:192.192.xxx.xxx 未訂閱
嗚~~~~~~~~沒人理我 我貼一段老外(和我一樣的疑問)之對話 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Got a tough one here...well it is for me. This is for Borland C Builder. I need to init an OpenGL Rendering Context for a control, say like TImage. The problem is that OGL doesnt like the DC that the handle property for the canvas returns. However, TImage is derived from TComponent which has a GetDeviceContext method, but this is protected and thus cannot be used to get the Device Context and GetDC(control) doesnt work as it needs a HWND, which a control is not. And TImage->TCanvas->Handle, gets the boot from OGL. Any help would be Great. All i need to do is initialise a Rendering Context for a TImage control rather than just the form. Thanks. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ you can only create device contexts using controls derived from a TWinControl. Try using a TPanel instead of a TImage control. André "- To begin with, said the Cat, a dog's not mad. You grant that? - I suppose so, said Alice. - Well, then, - the Cat went on - you see, a dog growls when it's angry, and wags its tail when it's pleased. Now I growl when I'm pleased, and wag my tail when I'm angry. Therefore I'm mad." @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ yangkissktop
------
yangkissktop
yangkissktop
一般會員


發表:13
回覆:29
積分:8
註冊:2003-10-25

發送簡訊給我
#5 引用回覆 回覆 發表時間:2005-10-08 15:50:16 IP:59.104.xxx.xxx 未訂閱
我找到答案了,原來這麼簡單,簡單到讓人意外    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 頭檔:    
#include  
#include  
.....
private:
        bool __fastcall  MySetupPixelFormat(HDC hdc);
        HDC   myDC;
        HGLRC myRC;
.....
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 主要FORM檔:
bool __fastcall TForm1::MySetupPixelFormat(HDC hdc)
{
  PIXELFORMATDESCRIPTOR  pfd, *ppfd = &pfd;
  int                    pixelformat;      ppfd->nSize        = sizeof( PIXELFORMATDESCRIPTOR );
  ppfd->nVersion     = 1;
  ppfd->dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  ppfd->dwLayerMask  = PFD_MAIN_PLANE;
  ppfd->iPixelType   = PFD_TYPE_RGBA;
  ppfd->cColorBits   = 8;
  ppfd->cDepthBits   = 16;
  ppfd->cAccumBits   = 0;
  ppfd->cStencilBits = 0;      if((pixelformat=ChoosePixelFormat(hdc, ppfd)) == 0)
  {
    MessageBox(NULL, "選擇像素格式失敗", "錯誤", MB_OK);
    return false;
  }      if(SetPixelFormat(hdc, pixelformat, ppfd) == 0)
  {
    MessageBox(NULL, "設定像素格式失敗", "錯誤", MB_OK);
    return false;
  }      return true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
   ///// 定基礎 /////
   myDC = GetDC( Panel1->Handle );
   if( !MySetupPixelFormat(myDC) ) Close();       myRC = wglCreateContext( myDC );
   wglMakeCurrent(myDC, myRC);       ///// 初始化 /////
   glShadeModel( GL_SMOOTH );       glClearColor(0.0f, 0.0f, 0.0f, 0.5f);       glClearDepth( 1.0f );
   glEnable( GL_DEPTH_TEST );
   glDepthFunc( GL_LEQUAL );       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);       ///// 設大小 /////
   int  w = Panel1->ClientWidth,
        h = Panel1->ClientHeight;       if(h == 0) h = 1;
   glViewport(0,0, w,h);       glMatrixMode( GL_PROJECTION );
   glLoadIdentity();       gluPerspective(45.0f, (float)w/(float)h, 0.1f, 100.0f);       glMatrixMode( GL_MODELVIEW );
   glLoadIdentity();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();      glTranslatef(-1.5f,0.0f,-6.0f);
  glBegin( GL_TRIANGLES );
    glVertex3f( 0.0f, 1.0f, 0.0f);
    glVertex3f(-1.0f,-1.0f, 0.0f);
    glVertex3f( 1.0f,-1.0f, 0.0f);
  glEnd();      glTranslatef(3.0f,0.0f,0.0f);
  glBegin( GL_QUADS );
    glVertex3f(-1.0f, 1.0f, 0.0f);
    glVertex3f( 1.0f, 1.0f, 0.0f);
    glVertex3f( 1.0f,-1.0f, 0.0f);
    glVertex3f(-1.0f,-1.0f, 0.0f);
  glEnd();      SwapBuffers( myDC );
}
yangkissktop
------
yangkissktop
系統時間:2024-04-28 23:06:43
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!