当前位置:首页 > 软件开发 > dev
firefox

用Delphi进行OpenGL编程学习心得

---- 在开发图形程序时,尤其是三维的图形程序,因为感觉opengl没有directx那么庞杂,所以选择了delphiopengl,凭感觉而言,delphi也没有c++那么繁杂而且更加人性化,于是选择delphi+opengl进行工作。在这过程中,碰到(肯定会)一些问题,在此提出希望和朋友们能够进行交流。

---- 首先是初始化。初始化时,有几项工作需要进行:①创建设备描述表(device context)。(注:关于dc,各种资料译文不尽相同如设备环境、设备描述表、设备上下文等,但好象都不太贴切。要是能有李善兰这样的翻译就好了。下文中的rc情形相同)②设置相应的象素格式(pixelformat descriptor)。③创建着色描述表(rendering context)。 delphi中有好几种获得或创建设备描述表的方法。最简单的就是直接获得画布对象(tcanvas)的句柄属性(handle),如:

dc:hdc;dc:=canvas.handle;也可以用api函数getdc获得设备描述表。如:dc:=getdc(handle,dc);

 

---- 也可以用函数createcompatibledc或者beginpaint..endpaint(需要注意它们之间的区别)等来获得设备描述表。但是设备描述表用完之后要记得释放或删除它,以解放资源的占用。拥有设备描述表的使用权后,就可以设置相应的象素格式。象素格式是个记录类型,其中有些字段或域是没什么用处的(至少现在是)。象素格式描述完成后,调用choosepixelformat和setpixelformat函数将之与设备描述表进行匹配和设置。如下面代码:

function setuppixelformat(var dc:hdc):boolean;var  ppfd:ppixelformatdescriptor;  npixelformat:integer;begin    new(ppfd);    ppfd^.nsize:=sizeof(pixelformatdescriptor);    ppfd^.nversion:=1;ppfd^.dwflags:=pfd_draw_to_window or pfd_support_opengl or                        pfd_doublebuffer;    ppfd^.dwlayermask:=pfd_main_plane;    ppfd^.ipixeltype:=pfd_type_colorindex;    ppfd^.ccolorbits:=8;    ppfd^.cdepthbits:=16;    ppfd^.caccumbits:=0;    ppfd^.cstencilbits:=0;    npixelformat:=choosepixelformat(dc, ppfd);    if (npixelformat=0) then      begin        messagebox(null, choosepixelformat failed,        error, mb_ok);        result:=false;        exit;      end;    if (setpixelformat(dc, npixelformat, ppfd)= false) then      begin        messagebox(null, setpixelformat failed,      error, mb_ok);        result:=false;        exit;      end;    result:=true;    dispose(ppfd);end;也可以向下面这样进行设置如:var pfd: pixelformatdescriptor;    npixelformat  : integer;begin  fillchar(pfd,sizeof(pfd),0);  with pfd do  begin    nsize:=sizeof(pfd);    nversion:=1;dwflags:=pfd_support_opengl  or pfd_draw_to_bitmap                     or pfd_doublebuffer;    ipixeltype:=pfd_type_rgba;    ccolorbits:=32;    cdepthbits:=32;    ilayertype:=byte(pfd_main_plane);  end;  npixelformat:=choosepixelformat(dc,@pfd);  setpixelformat(dc,npixelformat,@pfd); { // 使用describepixelformat检查象素格式是否设置正确  describepixelformat(dc,npixelformat,sizeof(pfd),@pfd); if (pfd.dwflags and pfd_need_palette)  < > 0 then setuppalette(dc,pfd);//setuppalette是自定义函数}end;

 

---- 上述工作完成以后,最好先运行一遍,并检查npixelformat的值。正常的话,该值应该是大于0的,否则就有问题。同样的代码,我在nt机器上能够得到正确的大于0的值而在pwin97或98的机器上得不到正确值,但是编译时不会有问题,而且nt上编译后在pwin97机器上也能够正确运行。现在可以创建着色描述表(rc)了。调用函数wglcreatecontext、wglmakecurrent,如下例示:

rc:hglrc;rc:=wglcreatecontext(dc);wglmakecurrent(dc,rc);在程序结束之前,要记得释放所占用的资源。 wglmakecurrent(0,0);  if rc< >null then    wgldeletecontext(rc);  if ghdc< >null then    releasedc(handle,dc);

 

---- 以下的代码是从c++builder 4中opengl的例子改写过来的。编译后的程序大小为300k左右,而在c++builder 4下编译后程序的大小为384k。

---- < a href="061403-05.zip ">程序代码 zip 3kb

---- 程序中的opengl函数及象素格式在delphi中的mshelp中有比较详细的解释,本文不敢多做解释。

 ↓相关文章:
© 2006-2008 All Rights Reserved