OpenGL graphics program design in Delphi

zhaozj2021-02-17  51

OpenGL graphics program design OpenGL is a three-dimensional graphics and model library, because it is outstanding performance in three-dimensional graphics, many advanced languages ​​offer interfaces with OpenGL, such as: VC, Delphi, C Builder, etc. Using OpenGL can greatly reduce user development graphics, the difficulty of images, the user makes high-level commercial advertisements, graphics CAD, 3D animation, graphics simulation and film collection.

First, OpenGL's function OpenGL is originally a graphics software library on the workstation. Because it is widely used in business, military, medical, aerospace, etc., currently in low-graphs can also develop graphics that meet the user requirements. OpenGL can not only draw basic images, but also provide a large number of functions and procedures for processing graphic images. 1. Graphical transformation is the basis of graphics display and production, and the animation design and animation display are inseparable from the transformation of the graphic. The graphical transformation is implemented by the multiplication of the rectangular multiplication, and the transformation generally includes translation, rotation, and zoom. According to the display properties of the graph: point of view transform, model transform, projection transformation, cutting transformation, and viewport transform, etc. 2. The color of the object that does not illuminate the light is formed by reflecting the external light of the object, which is a light. In the three-dimensional graphics, if the light use is improper, the three-dimensional pattern will lose the true three-dimensional sensation, and OpenGL divides the light into: radiant light, ambient light, scattering light, reflected light, and the like. 3, texture mapping can be added to the three-dimensional surface to add textures in the three-dimensional surface. Such as: A rectangle does not represent the object in the real world, if filling in the "nature" texture, it is realistic. 4, graphics special effects mixed function, refrigeration function, and fog function, can handle the transparent and translucent of the objects of the three-dimensional graphic listening, using line segments to increase mobody, and provide atomization. 5, the basic function of the image special effect processing bitmap: image drawing, image copy, storage, mapping, and transfer, zoom of images, etc. Bitmap operation functions can draw the original low-level description of the Chinese characters.

Second, create an OpenGL application 1, general principles A Some OpenGL support units are added to the USES: OpenGL; b Initialize OpenGL during the form's oncreate event, initialize OpenGL; D in the window onResize events during the window. Initializing OpenGL; EUNTER in the window, OpenGL; 2, simple instance a Create a project file-> new applicationb Add code in the oncreate event: Procedure TFRMMAIN.FORMCREATE (Sender: Tobject); var PFD: TpixelformATDescriptor ; // set description PixelFormat: Integer; begin ControlStyle: = ControlStyle [csOpaque]; FillChar (pfd, sizeof (pfd), 0); with pfd do begin nSize: = sizeof (TPixelFormatDescriptor); nVersion: = 1; dwFlags: = PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType: = PFD_TYPE_RGBA; cColorBits: = 24; cDepthBits: = 32; iLayerType: = PFD_MAIN_PLANE; end; PixelFormat: = ChoosePixelFormat (Canvas.Handle, @ pfd); SetPixelFormat (Canvas.Handle, PixelFormat, @pfd); hrc: = wglCreateContext (Canvas.Handle); w: = ClientWidth; h: = ClientHeight; end; C in OnDestroy event code procedure TfrmMain.FormDestroy (Sender: TObject); begin wglDeleteContext (hrc); end ; D of the code in the onpaint event Procedure TfrmMain.FormPaint (Sender: TObject); begin wglMakeCurrent (Canvas.Handle, hrc); glClearColor (1,1,1,1); glColor3f (1,0,0); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); MyDraw; glFlush; SwapBuffers (Canvas .Handle); end; E OnResize event in the code procedure TfrmMain.FormResize (Sender: TObject); begin glMatrixMode (GL_PROJECTION); glLoadIdentity; glFrustum (-1.0,1.0, -1.0,1.0,3.0,7.0); glViewPort ( 0,0, ClientWidth, ClientHeight); MyDraw; end; F MyDraw function code (user declared in the window class) procedure TfrmMain.MyDraw; begin glPushMatrix; Sphere: = gluNewQuadric; gluQuadricDrawStyle (Sphere, GLU_LINE); gluSphere ( Sphere, 0.5, 25, 25); GLPOPMAMATRIX;

SwapBuffers (canvas.handle); gludeletequadric (sphere); end; attached program original code: UNIT mainfrm;

Interface

Uses Windows, Messages, Sysutils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OpenGL;

type TfrmMain = class (TForm) procedure FormCreate (Sender: TObject); procedure FormDestroy (Sender: TObject); procedure FormPaint (Sender: TObject); procedure FormResize (Sender: TObject); private {Private declarations} hrc: HGLRC; w, H: glfloat; sphere: gluquadricobj; public {public declarations} procaic {public declaration;

Var frmmain: tfrmmain;

IMPLEMENTATION

{$ R * .dfm}

procedure TfrmMain.FormCreate (Sender: TObject); var pfd: TPixelFormatDescriptor; PixelFormat: Integer; begin ControlStyle: = ControlStyle [csOpaque]; FillChar (pfd, sizeof (pfd), 0); with pfd do begin nSize: = sizeof (TPixelFormatDescriptor ); nVersion: = 1; dwFlags: = PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType: = PFD_TYPE_RGBA; cColorBits: = 24; cDepthBits: = 32; iLayerType: = PFD_MAIN_PLANE; end; PixelFormat: = ChoosePixelFormat (Canvas.Handle, @ pfd) Setpixelformat (canvas.handle, Pixelformat, @ PFD); HRC: = WGLCReateContext (canvas.handle); W: = ClientWidth; H: = ClientHeight;

Procedure tfrmmain.formDestroy (sender: TOBJECT); Begin WgldeleteContext (HRC); END;

procedure TfrmMain.FormPaint (Sender: TObject); begin wglMakeCurrent (Canvas.Handle, hrc); glClearColor (1,1,1,1); glColor3f (1,0,0); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); MyDraw; glFlush SwapBuffers (canvas.handle);

procedure TfrmMain.MyDraw; begin glPushMatrix; Sphere: = gluNewQuadric; gluQuadricDrawStyle (Sphere, GLU_LINE); gluSphere (Sphere, 0.5,25,25); glPopMatrix; SwapBuffers (Canvas.handle); gluDeleteQuadric (Sphere); end; procedure TfrmMain. FormResize (Sender: TObject); begin glMatrixMode (GL_PROJECTION); glLoadIdentity; glFrustum (-1.0,1.0, -1.0,1.0,3.0,7.0); glViewPort (0,0, ClientWidth, ClientHeight); MyDraw; end;

End.

Third, OpenGL variables and functions of the OpenGL 1, OpenGL's library of three libraries: basic library, practical library, auxiliary library. In Delphi, the base library is implemented by the OpenGL unit. In the Windows environment, the auxiliary library is generally not used. 2, OpenGL constant agreed OpenGL constant using uppercase letters, starting with "GL", using underscores, such as: GL_LINES, means using a base library to draw straight lines. 3, the naming of the OpenGL function is the first portion starts with GL or WGL, such as GL in GLCOLOR3F. B The second part is the function function of the English, and the first letter of the word is written. C Part II is a number, indicating the parameters of the function. D Part II is lowercase letters, indicating the type of function. B 9-bit integer S 16-bit integer I 32-bit integer F 32-bit floating point number D 64-bit floating point number UB 9-bit unsigned integer case: Glvertex2f (37, 40); {Two 32-bit floating point numbers} GlvertEX3D ( 37, 40, 5); {Three 64-bit floating point numbers parameters} P [1..3]: array ofv (p); {3F represents three floating point numbers, v means calling an array as vertices Coordinate input}

Fourth, OpenGL initialization 1, PixelformATDescriptor structure mainly describes the nature of the pixel point, such as the color mode of pixels and red, green, and blue color constitution. tagPIXELFORMATDESCRIPTOR = packed record nSize: Word; nVersion: Word; dwFlags: DWORD; iPixelType: Byte; cColorBits: Byte; cRedBits: Byte; cRedShift: Byte; cGreenBits: Byte; cGreenShift: Byte; cBlueBits: Byte; cBlueShift: Byte; cAlphaBits: byte; cAlphaShift: byte; cAccumBits: byte; cAccumRedBits: byte; cAccumGreenBits: byte; cAccumBlueBits: byte; cAccumAlphaBits: byte; cDepthBits: byte; cStencilBits: byte; cAuxBuffers: byte; iLayerType: byte; bReserved: byte; dwLayerMask: DWORD; dwVisibleMask: DWORD; dwDamageMask: DWORD; end; TPixelFormatDescriptor = tagPIXELFORMATDESCRIPTOR; dwFlags attribute representative point format: PFD_DRAW_TO_WINDOW pattern painted on the screen or equipment surfaces PFD_DRAW_TO_BITMAP in memory bitmap drawing PFD_SUPPORT_GDI supported GDI graphics PFD_SUPPORT_OPENGL support OPENGL functions PFD_DOUBLEBUFFER double buffer PFD_STEREO perspective Cache PFD_NEED_PALLETTE uses RGBA palette PFD_GEneric_Format Select GDI supported format drawing PFD_NEED_SYSTEM_PALETTE Use OpenGL Support Hardware Pattern iPixelType Setting Pixel Color Mode: PFD_TYPE_RGBA or PFD_TYPE_INDEX .. CColorBits sets the color of the color, such as 9 indicates that 256 colors represent the color of the point. Credbits, CGreenBits, CBLuebits When using RGBA, the number of bits used in three primary colors. Credshitfs, CGreenshifts, CBLUESHIFTS When using RGBA, three primary colors can be adjusted. Calphabits, Calphashifts When using RGBA, the number of bits used by Alpha is used with adjustable bits. Caccumbits sets the total number of vertical cumulative cache. CaccumredBits, CaccumGreenBits, CaccumblueBits Sets the total number of three primary color planes in the cumulative cache. Caccumalphabits sets the total number of Alpha portions in the cumulative cache area. CDEPTHBITS sets the depth of the concentration cache. CstencilBits sets the depth of the Stencil cache. CAUXBuffers refers to the size of the auxiliary cache. The type of ILAYERTYPE specifies the layer. BRESERVED is not used, must be zero. DWLAYERMASK specifies the mask of the overlay. DwdamageMask is set to share the same pixel mode under the same framework cache. 2. Initialization of OpenGL Step A Use canvas.Handle to get the window handle. B Create a TPixelformATDescriptor variable defines the pixel format. C Use the choosepixelformat function to select a pixel format. D Use the setpixelformat function to use the pixel format to take effect.

E Establish a translation description table using the WGLCReateContext function. F Use the WGLmakeCurrent function to create the created translation description table as the current translation description table. 3. Resource Release A Use the WGLDeleteContext process to delete the pixel description table. B Use the ReleaseDC process to release the window memory. In the window of the ONDESTROY event: Begin IF HRC <> Null Then WGLDeletecurrent (HRC); if HDC <> Null Then ReleaseDC (Handle, HDC); END; 5, OpenGL Basic Graphics Draw 1, graphic color pay attention to the background color Setting, color settings are typically associated with pixel description variables, ie related to IpixelType members in the TPIXELFORMATDEScriptor definition. IpixelType: = PFD_TYPE_COLORINDEX; you can only use GlIndexd, Glindexf, Glindexi, Glindexs, Glindexv, Glindexfv, Glindexiv, and GlindexSV processes to set graphic colors. IpixelType: = PFD_TYPE_RGBA; you can only use GLCOLOR3B, GLCOLOR3F, GLCOLOR4B, GLCOLOR4F, GLCOLOR4FV to set graphic colors. A graphic base color: the color of the screen and the window, that is, the color of the color buffer. Changing the graphic base color First use the GLCLEARCOLOR process to set the background, and then use the GLCLEAR process to refresh the window and screen with this background. Procedure GlclearColor (Red: Glclampf, Green: Glclampf, Blue: Glclampf, Alpha: GlcLAMPF; Procedure Glclear (Mask: Glbitfield); Red, Green, Blue, Alpha is preparing the base color, their value is 0 to 1 . Mask is a way to refresh the background. Example: Set the pickup color map window to green glclearcolor (0, 1, 0, 1); GLCLEAR (GL_COLOR_BUFFER_BIT); MASK's value and meaning: GL_COLOR_BUFFER_BIT Sets the current color buffer GL_DEPTH_BUFFER_BIT Set the current depth buffer GL_ACCUM_BUFFER_BIT set the current accumulation buffer GL_STENCIL_BUFFER_bit Set the current STENCIL (Template) buffer drawing window set to gray glclearcolor (0.3, 0.3, 0.3, 1); Glclear (GL_COLOR_BUFFER_BIT); B graphics color uses Glclear3f with GLCLEAR 4F to set a graphic color. If three parameters are used, they are set to set red, blue, and green. If four parameters are used, the fourth represents the RGBA value. For example, the current drawing color is blue: GLCOLOR3F (0, 0, 1); Setting the drawing color is white: Glcolor3f (1, 1, 1); 2, simple graphics Draw a simple graphic between Glbegin and Glend For example, line, polygon, etc.

Glbegin (Mode: glenum); {Drawing Process} Glend; Mode value: GL_Points painted multiple points GL_LINES to draw multiple lines, draw a straight line GL_LINE_STRIP draw line GL_LINE_LOOP to draw the first closed polygonal GL_TRIANGLE_STRIP Draw a triple shape, draw a triangular GL_TRIANGLE_FAN every three points to draw a triangular GL_QUADS to draw quadrilateral GL_QUAD_STRIP to draw four sides, draw a four-sided strip GL_POLYGON drawing a polygonal example: Begin Glpushmatrix; Glbegin (GL_Point); Glvertex2f (0.1, 0.1); GlvertEX2F (0.5, 0.5); GlvertEX2F (0.1, 0.3); GLEND; swapBuffers (canvas.handle); END; If GL_POINT is changed to GL_LINES, a line will be drawn. The third point is invalid The Glcolor3f (0, 0, 1) is executed before GlvertEX2F, and the color of the line is changed to green. If GL_LINES is changed to GL_LINE_STRIP, you can draw two straight lines. Use the GLPointSize process to set the size of the point; use the GLLINEWIDTH process to set the line Width. Use the GLLINESTIPPL process to set up a line-upless template, use the glenable (GL_LINE_STIPPLLE) process, and the corresponding parameters allow the drawing to draw a dotted line .GLDISABLE process and the corresponding parameters shut down the dotline. Procedure GLLINESTIPPLE (Factor: Glint, Pattern: Glushort); Parameter Factor represents the number of repetitions of the point line pattern Pattern, and the value of the value is 1255, and patter is a binary sequence. GLLINESTIPPLE (1, 0, 0x11c); {0x11c is expressed as 10001110, 0 means no pain points, 1 Draw point} case: Begin Glcolor3f (1,0,0); GLLINEWIDTH (2); GLLINESTIPPLE (1, $ 11C); GLENABLE (GL_LINE_STIPLE); Glbegin (GL_LINES); GlvertEX2F (-0.9, 0.3); GlvertEX2F (0.9, 0.3); GLEND; GLDISABLE (GL_LINE_STIPPLE); GLCOLOR3F (1, 0, 1); GLLINESTIPPLE (2, $ 11C); GLENABLE (GL_LINE_STIPPLE); Glbegin (GL_LINES); Glvertex2f (-0.9, 0.1 ); Glvertex2f (0.9, 0.1); glend; gldisable (gl_line_stipple); swapbuffers (canvas.handle); END; polygon drawing and point line, change parameter GL_POLYGON, GL_QUADS, GL_TRANGLES. Precautions in drawing: a The edges of the polygon and edges are only in the vertex. B must be convex polygons. If the concave polygon is formed, the user only has a convex polygon, speeds up the plot speed. Example: glbegin (GL_POLYGON); GlvertEx2f (-0.9, 0.3); GlvertEx2f (0.9 0.3); GlvertEX2F (0.9, -0.6); GlvertEX2F (0.5, -0.6); GlvertEX2F (-0.9, -0.2); glend;

Polygon has a front and reverse, related to related process: GLPOLYGONMODE control multilateral positive, reverse drawing mode GLFRONTFACE Specify polygonal front GLCULLFACE display polygon is set to eliminate GLPOLYGONSTRIPPLE to form a polygon padded pattern 3, simple secondary curved cylinder, ring and ball .A belong quadric cylindrical gluCylinder (qobj: GLUquadricObj, baseRadius: GLdouble, topRadius: GLdouble, height: GLdouble, slices: GLint, stacks: GLint); qobj specify a quadric, baseRadius cylindrical bottom radius; topRadius For the top-top radius of the column drawn; Height is a cylinder high; SLICES is the number of split lines around the Z-axis; Stacks is the number of divided lines along the z-axis. If BaseRadius and Topradius are not equal, they can draw cone and cones. .procedure TfrmMain.MyDraw; var qObj: GLUQuadricObj; begin glPushMatrix; glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glColor3f (1,0,0); qObj: = gluNewQuadric; gluQuadricDrawStyle (qObj, GLU_LINE); gluCylinder (qObj, 0.5,0.1, 0.2,10,10); end; B ring gluDisk (qobj: GLUquadricObj, innerRadius: GLdouble, outerRadius: GLdouble, slices: GLint, loops: GLint); procedure TfrmMain.MyDraw; var qObj: GLUQuadricObj; begin glPushMatrix; glClear ( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glColor3f (1,0,0); qObj: = gluNewQuadric; gluQuadricDrawStyle (qObj, GLU_LINE); gluDisk (qObj, 0.2,0.5,10,5); SwapBuffers (Canvas.Handle); end; C half Ring gluPartialDisk (qobj: GLUquadricObj, innerRadius: GLdouble, outerRadius: GLdouble, slices: GLint, loops: GLint, startAngle: GLdouble, sweepAngle: GLdouble); startAngle, sweepAngle a semi-circle starting angle and end angle .procedure TfrmMain .MyDraw; var qObj: GLUQuadricObj; begin glPushMatrix; glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glColor3f (1,0,0); qObj: = gluNewQuadric; gluQuadricDrawStyle (qObj, GLU_LINE); gluPartialDisk (qObj, 0.2,0.5,10,5 , 90,190); SwapBuffers (Canvas.Handle); end; D sphere function gluSphere (qObj: GLUquadricObj, radius: GLdouble, slices: GLint, stacks: GLint); procedure TfrmMain.MyDraw; var qObj: GLUQuadricObj; begin glPushMatrix; glClear ( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); Glcolor3f (1,0,0); Qobj: = Glunewquadric;

GluquadricDrawStyle (Qobj, Glu_Line); {Silhouette [Silu (:) 5Et] n. Side Image, Contour} Glusphere (Qobj, 0.5, 20, 20); swapBuffers (canvas.handle); end; e About the second surface Create a new process gluNewQuadric quadric quadric objects gluDeleteQuadric delete a specified object is gluQuadricDrawStyle quadric type gluQuadricNormal provided quadric surface normal vector to be drawn gluQuadricOrientation quadric surface disposed within an outer rotation or rotational quadric disposed gluQuadricTexture general Procedure F whether texture mapping secondary surface defines a first GLUquadricObj objects; secondly create a surface object gluNewQuadric; quadric again set characteristics (gluQuadricDrawStyle, gluQuadricTexture) rendering quadric (gluCylinder, gluSphere, gluDisk, gluPartialDisk) six Transform transformation in OpenGL is the foundation of the animation design, including translation, rotation, scaling, etc. of graphics, and is implemented by matrix in mathematics. 1 The GLLoadIndentity process can turn the current matrix into unit matrix. 2 The GLLoadMatrix process can set the specified matrix as the current matrix.

Procedure GLLoadMatrixd (M: GLDOUBLE); Procedure GLLOADMAMATRIXF (M: GLFLOAT); M represents 4x4 matrix, the following code defines and makes the current matrix M: Array [1..4, 1..4] of GLFLOAT; GLLOADMAMATRIX @M); 3 GlmultMatrix process can multiply the current moment with the specified matrix, and take the result as the current moment. Procedure GlmultMatrixd (M: gldouble); Procedure GlmultMatrixf (M: GLFLOAT); 4 GLPushmatrix and GLPopMatrix GLPushmatrix can put the current moment Insert matrix stack, GLPopMatrix enables the currentumn matrix stack. GLPUSHMatrix can memorize the matrix current location, GLPopMatrix can return the previous location. Note: GLPushmatrix and GLPopMatrix must be placed outside Glbegin and Glend.5 Projection transformation A glortho can create a Positive projection matrix, take the current torque with the positive projection matrix, its result as the current matrix. Function glortho (Left: Gldouble, Right: GLDOUBLE, BOTTOM: GLDOUBLE, TOP: GLDOUBLE, NEAR: GLDOUBLE, FAR: GLDOUBLE); Procedure TfrmMain .Formresize (Sender: TOBJECT); VAR NRANGE: GLFLOAT; begin nrange: = 50.0; W: = ClientWidth; H: = ClientHeight; IF H = 0 THEN H: = 1; GLVIEWPORT (0, 0, W, h); IF W <= h Then Glortho (-NRANGE, NRANGE, -NRANGE * H / W, NRANGE * H / W, -NRANGE, NRANGE) Else Glortho (-NRANGE * H / W, NRANGE * H / W, -NRANGE, NRANGE, -NRANGE, NRANGE); repaint; end; b glortho2d only defines the front, back, left, right. Procedure glortho (Left: Gldouble, Right: GLDO Uble, Bottom: GLDOUBLE, TOP: GLDOUBLE; C GLmatrixMode process can set the type of type procedure glmatrixmode (Mode: glenum) of the current operation matrix; Mode: GL_MODELVIEW Specifies the matrix operation in the model matrix stack GL_PROJECTION NOTY The matrix operation after the projection matrix stack GL_TEXTURE is specified for the texture matrix stack D GLFRUSTUM process creates a perspective oblique projection matrix, multiplying the current matrix with the oblique projection matrix, and the result is the current matrix. Procedure GLFRUSTUM (Left: gldouble, Right: GLDOUBLE, BOTTOM: GLDOUBLE, TOP: GLDOUBLE, NEXT: GLDOUBLE, FAR: GLDOUBLE); These parameters define the left, right, upper, lower, front, and then cutting surfaces of the oblique projection. E GluPerspective process can define a Z-axis as The four-pricing view of the mid-line. Procedure Gluperspetive (fovy: gldouble: gldouble, zfar: gldouble); fovy defines the view of the Xoz plane, aspect defines the ratio in X and Y directions, Znear and ZfARs define the distance from the viewpoint to the cutting surface and the rear cut-cut surface. Procedure tfrmmain.formResize (sender: TOBJECT); var aspect: glfloat; begin w: = clientwidth; h: = clientHeight; if h =

0 then h: = 1; glViewPort (0,0, clientWidth, Clientheight); glMatrixMode (GL_PROJECTION); glLoadIdentity; aspect: = w / h; gluPerspective (30.0, aspect, 1.0,50.0); glMatrixMode (GL_MODELVIEW); glLoadIdentity; END; 6 Geometric transformation matrix three-dimensional object motion gesture conversion, refers to the pan, rotation, scaling .a GLTranslate procedure moves the coordinate original to (x, y, z), its declaration syntax: procedure gltranslated (x: GLDOUBLE, Y: GLDOUBLE, Z: GLDOUBLE); Procedure Gltranslatef (x: gldouble, y: gldouble, z: gldouble); B Glrotate can rotate a certain angle, its declaration syntax: Procedure Glrotated (Angle: Gldobule, x : GLDOUBLE, Y: GLDOUBLE, Z: GLDOUBLE; Procedure Glrotatef (Angle: Gldobule, x: GLDOUBLE, Y: GLDOUBLE, Z: GLDOUBLE); where angle is the rotation angle, the central axis of rotation is (0, 0, 0 Wireless connection between (x, y, z). C Glscale can scale the coordinate system, its declaration syntax is: Procedure Glscaled (x: Gldouble, Y: GLDOBLE, Z: GLDOUBLE); Procedure Glscalef (x : GLDOUBLE, Y: GLDOBLE, Z: GLDOUBLE); X, Y, Z value is greater than 1 indication amplification, less than 1 indicates shrinkage. Example of the original code: Unit mainfrm;

Interface

Uses Windows, Messages, Sysutils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OpenGL, ExtCtrls

type TfrmMain = class (TForm) Timer1: TTimer; procedure FormCreate (Sender: TObject); procedure FormDestroy (Sender: TObject); procedure FormPaint (Sender: TObject); procedure FormKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState ); procedure FormResize (Sender: TObject); procedure Timer1Timer (Sender: TObject); procedure FormClose (Sender: TObject; var Action: TCloseAction); private {Private declarations} hrc: HGLRC; w, h: Integer; latitude, longitude: GLFLOAT; RADIUS: GLDOUBLE; PUBLIC {Public Declarations} Procedure MyDraw; Procedure Initializegl (Var Width: Glsizei; Height: glsizei);

Var frmmain: tfrmmain;

IMPLEMENTATION

{$ R * .dfm}

procedure TfrmMain.FormCreate (Sender: TObject); var pfd: TPixelFormatDescriptor; PixelFormat: Integer; begin ControlStyle: = ControlStyle [csOpaque]; FillChar (pfd, sizeof (pfd), 0); with pfd do begin nSize: = sizeof (TPixelFormatDescriptor ); nVersion: = 1; dwFlags: = PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType: = PFD_TYPE_RGBA; cColorBits: = 24; cDepthBits: = 32; iLayerType: = PFD_MAIN_PLANE; end; PixelFormat: = ChoosePixelFormat (Canvas.Handle, @ pfd) ; SetPixelFormat (Canvas.Handle, PixelFormat, @ pfd); hrc: = wglCreateContext (Canvas.Handle); w: = ClientRect.Right; h: = ClientRect.Bottom; initializeGL (w, h); end; procedure TfrmMain.FormDestroy (Sender: TOBJECT); Begin WgldeleteContext (HRC); END;

procedure TfrmMain.FormPaint (Sender: TObject); begin wglMakeCurrent (Canvas.Handle, hrc); glClearColor (1,1,1,1); glColor3f (1,0,0); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); MyDraw; glFlush ;

procedure TfrmMain.MyDraw; var qObj: GLUQuadricObj; begin glPushMatrix; glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glColor3f (1,0,0); glRotated (0.5,0.0,1.0,0.0); glRotated (-latitude, 1.0,0.0,0.0 ); Glrotated (Longitude, 0.0, 0.0, 1.0); Qobj: = glunewquadric; gluquadricdrawstyle; glusphere (Qobj, 0.5, 20, 20); swapBuffers (canvas.handle);

{Procedure TFRMMAIN.FORMRESIZE (Sender: Tobject); var nrange: glfloat; begin nrange: = 50.0; w: = clientwidth; h: = clientHeight; if h = 0 THEN H: = 1; GLVIEWPORT (0, 0, W, h); GLMatrixMode; GLLoadidentity; if W <= h Then Glortho (-NRANGE, NRANGE, -NRANGE * H / W, NRANGE * H / W, -NRANGE, NRANGE) ELSE GLORTHO (-NRANGE * H / W , nRange * h / w, -nRange, nRange, -nRange, nRange); glMatrixMode (GL_MODELVIEW); glLoadidentity; repaint; end;} procedure TfrmMain.FormKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); begin IF key = vk_escape kilose; if key = vk_up then glrotatef (-5, 1.0, 0.0, 0.0); if key = vk_down the GLROTATEF (5, 1.0, 0.0, 0.0); if key = vk_left dam1 Glrotatef (-5, 0.0,1.0,0.0); if Key = VK_RIGHT then glRotatef (5.0,0.0,1.0,0.0); repaint; end; procedure TfrmMain.FormResize (Sender: TObject); begin glMatrixMode (GL_PROJECTION); glLoadIdentity; glFrustum (-1.0, 1.0, -1.0, 1.0, 3.0, 7.0); GLVIEWPORT (0, 0, ClientWidth, ClientHeight); repaint; invalidate;

procedure TfrmMain.InitializeGL (var width: GLsizei; height: GLsizei); var maxObjectSize, aspect: GLfloat; near_plane: GLdouble; begin glClearindex (0); glClearDepth (1.0); glEnable (GL_DEPTH_TEST); glMatrixMode (GL_PROJECTION); aspect: = 1.0; gluPerspective (45.0, aspect, 3.0,7.0); glmatrixMode (GL_MODELVIEW); near_plane: = 0.3; maxObjectSize: = 0.3; radius: = near_plane maxObjectSize / 2.0; latitude: = 0.3; longitude: = 0.6; end;

Procedure tfrmmain.timer1timer (sender: TOBJECT); Begin Timer1.enabled: = false; MyDraw; Yield; Timer1.enabled: = true;

Procedure tfrmmain.formclose (sero: tclosection); begin timer1.enabled: = false; if hrc <> null dam = wgldeletecontext (hrc); end; end.

7. OpenGL light and texture are means of enhancing three-dimensional stereotypes and color effects, and the light can increase the brightness of the graphic and three-dimensional effects, and the texture can be more approaching the reality. By using illumination, the appearance of the object can be manifested, and the texture can display a variety of existing objects. 1 Light and light source process and application A Glindex process enables a color in the color index table to become current colors. procedure glIndexd (c: GLdouble); procedure glIndexf (c: GLdouble); procedure glIndexi (c: GLdouble); procedure glIndexs (c: GLdouble); Parameter C index value, if glIndex procedure, TPiexlFormatDescriptor iPixelType member structure Set to PFD_TYPE_COLORINDEX. B Glshademodel Process Glshademodel Process Set Fill Mode, Value: GL_SMOOTH. Procedure Glshademodel (Mode: Glenum); Note: The above two processes can only be used outside Glbegin ..... Glend.

C glLight source process definition procedure glLightf (light: GLenum, pname: GLenum, param: GLfloat); procedure glLighti (light: GLenum, pname: GLenum, param: GLfloat); parameters defined light source, which is desirable value: GL_LIGHT0 ... ..GL_LIGHTN, N GL_MAX_LIGHT parameter value is less than specified by pname source parameters: ambient light component intensity GL_AMBIENT GL_DIFFUSE intensity of the scattered light component of the reflected light component intensity GL_SPECULAR direction GL_POSITION condensing light source position GL_SPOT_DIRECTION GL_SPOT_EXPONENT condensing light source index GL_SPOT_CUTOFF Convection GL_CONSTANT_ATTENUATION Overall Decayment Factor GL_LINEAR_ATTENUTION ON DETATION Factor Enables and Turn Off Light Source Use Glenable () and GLDISABLE () Procedure GLENABLE (GL_Lighting); // Enable Light Source GLDISABLE (GL_Light); // Turn off the light source glenable (GL_Light0); // Enable the 0th source GLDISABLE (GL_LIGHT0); // Close the 0th Light Source Setting the Light Source: Var SDirection: Array [1..4] of GLFLOAT: = {0.0, 1.0, 0.0, 0.0}; GLLightFv ( GL_LIGHT0, GL_SPOT_CUTOFF, 60); glLightfv (GL_LIGHT0, GL_SPOT_DIRECTION, sdirection); 2 materials and illumination model A glMaterial process of setting material parameters procedure glMaterialf (face: GLenum, pname: GLenum, param: GLfloat); procedure glMateriali (face: GLenum, PNAME: GLENUM, PARAM: GLFLOAT; Procedure Glmaterialfv (Face: Glenum, PName: Glenum, Param: GLFLOAT; Procedure Glmaterialiv (FAC E: Glenum, PNAME: Glenum, Param: GLFLOAT; Parameter Face Specifies the surface of the object, its value: GL_FRONT, GL_BACK, GL_FRONT_BACK. PNAME, PARAM This information is not introduced. B GLLightModel Process Procedure GLLightModelf (PName: Glenum, Param : GLfloat); pname parameter model parameters as a light source, can take the values ​​GL_LIGHT_MODEL_AMBIENT, GL_LIGHT_MODEL_LOCAL_VIEWER, GL_LIGHT_MODEL_TWO_SIDE Code example: procedure TfrmMain.SetLighting; var MaterialAmbient:. array [1..4] of GLfloat; MaterialDiffuse: Array [1..4] Of GLFLOAT; AMBIENTLIGHTPSITION: AMBIENTLIGHTPSITION: Array [1..4] of glflloat; lightambient: array [1..4] of glfloat; materialshininess: GLFLOAT; begin materialAlambient [1]: = 0.5; MaterialAlambient [2]: = 0.8; MaterialAlambient [1]: = 0.2; MaterialAlambient [1]: = 1.0;

MaterialDiffuse [1]: = 0.4; MaterialDiffuse [2]: = 0.8; MaterialDiffuse [3]: = 0.1; MaterialDiffuse [4]: ​​= 1.0; MaterialSpecular [1]: = 1.0; MaterialSpecular [2]: = 0.5; MaterialSpecular [ 3]: = 0.1; Materialspecular [4]: ​​= 1.0;

Materialshininess: = 50.0;

AmbientlightPosition [1]: = 0.5; AmbientlightPosition [2]: = 1.0; AmbientLightPosition [3]: = 1.0; AmbientlightPosition [4]: ​​= 0.0;

Lightambient [1]: = 0.5; Lightambient [2]: = 0.2; Lightambient [3]: = 0.8; Lightambient [4]: ​​= 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); GLShadeModel (GL_SMOOTH); end;. Application A glTexImage1D defined one-dimensional texture mapping 3 textures procedure glTexImage1D ( Target: Glenum, Level: Glint, Components: Glint, Width: Glsizei, Border: Glint, Format: Glenum, Type: Glenum, Pixels: GLVOID; Parameter Targer value is GL_TEXTURE_1D, defined as texture mapping, Level is multi-level resolution The grade of the texture image, Width is a texture width, a value of 2N, N value is 32, 64, 129, and the like, the border is the boundary of the texture, its value is 0 or 1, Pixel is the position of the texture in memory. Information specified RGBA Mixing and adjustment: 1 Select B ingredient 2 Select B, A ingredient 3 Select R, G, B ingredient 4 Select R, G, B, A ingredient B Glteximage2D Definition 2D texture map Procedure Glteximage2D (target: glenum, level: Glint, Components: Glint, Width: Glsizei, Border: Glint, Format: Glenum, Type: Glenum, Pixels: GLVOID; If the parameter Target is GL_TEXTURE_2D, the meaning is two-dimensional texture map, Height is the high texture, other parameters in the function Glteximage1D is the same.Component parameter value. Instance code: procedure tfrmmain.settextures; var bits: array [1..64, 1..64, 1..64] of glubyte; bmp: tbitmap; i, j: integer; Begin bmp: = tbitmap.create; bmp.loadfromfile ('d: /dsoft/1119/01/logon.bmp'); for i: = 1 to 64 do for j: = 1 To 64 Do Begin Bits [I, J, 1]: = Glbyte (Bmp.canvas.pixels [i, j])); BITS [I, J, 2]: = Glbyte (GtrVaS.pixels [ i, j])); BITS [I, J, 3]: = Glbyte (BMP.canvas.pixels [i, j])); BITS [I, J, 4]: = 255; End; {0 The representative is monochrome coloring level, GL_RGBA means that the mixed value 64x64 represents the high and wide texture of the texture, 0 indicates the boundary, GL_RGBA represents the texture type, the GL_UNUNSIGNED_TYPE represents the data type, @ 代 对 地址 地址} GLTexImage2D (GL_Texture_2D, 0, GL_RGBA, 64, 64 , 0, GL_RGBA, GL_UNSIGNED_BYTE, @ bits); glEnable (GL_TEXTURE_2D); end; C glTexParameter procedure set texture parameters procedure glTexParameterf (target: GLenum, pname: GLenum, param: GLfloat); procedure glTexParameteri (target: GLenum, pname: GLenum , PARAM: GLFLOAT;

Representative GL_TEXTURE_1D target parameter or GL_TEXTURE_2D, param texture environment parameter setting function glTexEnvf (target: GLenum, pname: GLenum, param: GLfloat) .D glTexEnv texture value for the function; function glTexEnvi (target: GLenum, pname: GLenum, param: GLfloat ); Parameter Target is GL_TEXTURE_ENV, parameter PNAME is the texture parameter value, with the value of GL_TEXTURE_ENV_MODE parameter param as ambient value, value GL_MODULATE, GL_DECAL and GL_BLEND. This program sample code: Unit Mainfrm; Interface

Uses Windows, Messages, Sysutils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OpenGL, ExtCtrls

type TfrmMain = class (TForm) Timer1: TTimer; procedure FormCreate (Sender: TObject); procedure FormDestroy (Sender: TObject); procedure FormPaint (Sender: TObject); procedure FormKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState ); procedure FormResize (Sender: TObject); procedure Timer1Timer (Sender: TObject); procedure FormClose (Sender: TObject; var Action: TCloseAction); private {Private declarations} hrc: HGLRC; w, h: Integer; latitude, longitude: GLfloat; radius: GLdouble; public {public declarations} procedure SetLighting; procedure SetTextures; procedure MyDraw; procedure initializeGL (var width: GLsizei; height: GLsizei); end;

Var frmmain: tfrmmain;

IMPLEMENTATION

{$ R * .dfm}

procedure TfrmMain.FormCreate (Sender: TObject); var pfd: TPixelFormatDescriptor; PixelFormat: Integer; begin ControlStyle: = ControlStyle [csOpaque]; FillChar (pfd, sizeof (pfd), 0); with pfd do begin nSize: = sizeof (TPixelFormatDescriptor ); nVersion: = 1; dwFlags: = PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType: = PFD_TYPE_RGBA; cColorBits: = 24; cDepthBits: = 32; iLayerType: = PFD_MAIN_PLANE; end; PixelFormat: = ChoosePixelFormat (Canvas.Handle, @ pfd) ; SetPixelFormat (Canvas.Handle, PixelFormat, @ pfd); hrc: = wglCreateContext (Canvas.Handle); w: = ClientRect.Right; h: = ClientRect.Bottom; initializeGL (w, h); end; procedure TfrmMain.FormDestroy (Sender: TOBJECT); Begin WgldeleteContext (HRC); END;

procedure TfrmMain.FormPaint (Sender: TObject); begin wglMakeCurrent (Canvas.Handle, hrc); glClearColor (1,1,1,1); glColor3f (1,0,0); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); SetTextures; MyDraw ;

procedure TfrmMain.MyDraw; var qObj: GLUQuadricObj; begin glPushMatrix; glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glColor3f (1,0,0); glRotated (0.5,0.0,1.0,0.0); glRotated (-latitude, 1.0,0.0,0.0 ); glrotated (longitude, 0.0,0.0,1.0); qObj: = gluNewQuadric; gluQuadricDrawStyle (qObj, GLU_LINE); gluSphere (qObj, 0.5,20,20); SwapBuffers (Canvas.Handle); SetLighting; SetTextures; end;

{Procedure TFRMMAIN.FORMRESIZE (Sender: Tobject); var nrange: glfloat; begin nrange: = 50.0; w: = clientwidth; h: = clientHeight; if h = 0 THEN H: = 1; GLVIEWPORT (0, 0, W, h); GLMatrixMode; GLLoadidentity; if W <= h Then Glortho (-NRANGE, NRANGE, -NRANGE * H / W, NRANGE * H / W, -NRANGE, NRANGE) ELSE GLORTHO (-NRANGE * H / W , nRange * h / w, -nRange, nRange, -nRange, nRange); glMatrixMode (GL_MODELVIEW); glLoadidentity; repaint; end;} procedure TfrmMain.FormKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); begin IF key = vk_escape kilose; if key = vk_up then glrotatef (-5, 1.0, 0.0, 0.0); if key = vk_down the GLROTATEF (5, 1.0, 0.0, 0.0); if key = vk_left dam1 Glrotatef (-5, 0.0,1.0,0.0); if Key = VK_RIGHT then glRotatef (5.0,0.0,1.0,0.0); repaint; end; procedure TfrmMain.FormResize (Sender: TObject); begin glMatrixMode (GL_PROJECTION); glLoadIdentity; glFrustum (-1.0, 1.0, -1.0, 1.0, 3.0, 7.0); GLVIEWPORT (0, 0, ClientWidth, ClientHeight); repaint; invalidate;

procedure TfrmMain.InitializeGL (var width: GLsizei; height: GLsizei); var maxObjectSize, aspect: GLfloat; near_plane: GLdouble; begin glClearindex (0); glClearDepth (1.0); glEnable (GL_DEPTH_TEST); glMatrixMode (GL_PROJECTION); aspect: = 1.0; gluPerspective (45.0, aspect, 3.0,7.0); glmatrixMode (GL_MODELVIEW); near_plane: = 0.3; maxObjectSize: = 0.3; radius: = near_plane maxObjectSize / 2.0; latitude: = 0.3; longitude: = 0.6; end;

Procedure tfrmmain.timer1timer (sender: TOBJECT); Begin Timer1.enabled: = false; MyDraw; Yield; Timer1.enabled: = true;

procedure TfrmMain.FormClose (Sender: TObject; var Action: TCloseAction); begin timer1.Enabled: = false; if hrc <> null then wglDeleteContext (hrc); end; procedure TfrmMain.SetLighting; var MaterialAmbient: array [1..4 ] OF GLFLOAT; MaterialDiffuse: Array [1..4] of GLFLOAT; Materialspecular: Array [1..4] of GLFLOAT; AmbientlightPosition: array [1..4] of glflloat; lightambient: array [1..4] of GLFLOAT; begininess; begin matialambient [1]: = 0.5; MaterialAlambient [2]: = 0.8; MaterialAlambient [1]: = 0.2; MaterialAlambient [1]: = 1.0;

Materialdiffuse [1]: = 0.4; MaterialDiffuse [2]: = 0.8; MaterialDiffuse [3]: = 0.1; MaterialDiffuse [4]: ​​= 1.0;

Materialspecular [1]: = 1.0; MaterialSpecular [2]: = 0.5; Materialspecular [3]: = 0.1; Materialspecular [4]: ​​= 1.0;

Materialshininess: = 50.0;

AmbientlightPosition [1]: = 0.5; AmbientlightPosition [2]: = 1.0; AmbientLightPosition [3]: = 1.0; AmbientlightPosition [4]: ​​= 0.0;

Lightambient [1]: = 0.5; Lightambient [2]: = 0.2; Lightambient [3]: = 0.8; Lightambient [4]: ​​= 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); GLShadeModel (GL_SMOOTH); end;

Procedure tfrmmain.settextures; var bits: array [1..64, 1..64, 1..64] of glubyte; bmp: tbitmap; i, j: integer; begin bmp: = tbitmap.create; bmp.LoadFromFile 'd: /dsoft/1119/02/logon.bmp'); for i: = 1 to 64 do for j: = 1 to 64 do begin bits [i, j, 1]: = Glbyte (GtrVaS .Pixels [i, j])); bits [i, j, 2]: = Glbyte (Bmp.canvas.pixels [i, j])); BITS [i, j, 3]: = Glbyte (GtrValue (bmp.Canvas.Pixels [i, j])); bits [i, j, 4]: = 255; end; glPixelStorei (GL_UNPACK_ALIGNMENT, 4); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); {0 level representative of a monochrome colored, showing a high mixing GL_RGBA 64X64 value representative of the texture and wide, 0 for no border, on behalf of the texture type GL_RGBA, GL_UNSIGNED_TYPE representing the data type, substituting @ object address} glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 64,64,0, GL_RGBA, GL_UNSIGNED_BYTE, @ bits); glEnable (GL_TEXTURE_2D); glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); end; end.

转载请注明原文地址:https://www.9cbs.com/read-30304.html

New Post(0)