Popular Post LarsJ Posted May 19, 2013 Popular Post Share Posted May 19, 2013 (edited) You can find a lot of libraries (DLLs) to create OpenGL windows and contexts, to load images and data into textures, to load 3D models, and to call functions that are not in opengl32.dll. Are all these external libraries necessary?The zip files below contains UDFs to create contexts, load images and models, and call functions without any external libraries. They also contains a number of examples.Well, it's not quite true that I do not use any DLLs at all. In some examples I'm using The Embedded Flat Assembler (FASM) UDF by Ward (includes fasm.dll) to optimize loops.This is the ExLauncher, that can be used to run the examples:Press Play to run the first example, and Next to run the following examples. In the Samples menu you can select OpenGL 1.1, 2.1, and 3.3 examples. With Samples | Models you can open the 3D model Viewers, and run 3D model examples. With Samples | Templates you can see a number of templates, as you can use as a start for your own examples.The documentation is divided into five chapters:Chapter 1 is mostly about OpenGL 1.x. Topics like calling functions, creating a rendering context, and loading images into textures are also covered.Chapter 2 deals with OpenGL 2.x and the new concepts that appeared in these versions. Most important is the concept of shaders.Chapter 3 is mostly about OpenGL 3.x. There is also a section on OpenGL/GLSL versions and a section on error handling.Chapter 4 is about implementing a model loader for Wavefront (OBJ) 3D models.Chapter 5 is a summary.In bottom of the post you can download zip files.Use ExLauncher.au3 in top folder to run examples.To view Wavefront (OBJ) 3D models see section 4.0.Chapter 1 is mostly about OpenGL 1.x. Topics like calling functions, creating a rendering context, and loading images into textures are also covered.1.1 Calling functionsFunctions defined in OpenGL 1.2 and higher and functions defined in extensions are part of the software that belongs to the video card. To access these functions you normally use a function loading library e.g. GLEW. You can also access the functions manually:You can get the address of a function with wglGetProcAddress and you can call the function with DllCallAddress. wglGetProcAddress is a Windows extension to OpenGL. DllCallAddress is an AutoIt function.This is an example with glActiveTexture in OpenGL 1.3:Func glActiveTexture( $texture ) Local Static $ptr = 0 If $ptr = 0 Then $ptr = wglGetProcAddress( "glActiveTexture" ) If @error Then Return SetError( 2, @error, 0 ) EndIf DllCallAddress( "none", $ptr, "uint", $texture ) If @error Then Return SetError( 3, 0, 0 ) EndFuncA point to note about wglGetProcAddress is that it can only be used within a rendering context. Another point is that it can't be used for OpenGL 1.1 functions. If you need the address of an OpenGL 1.1 function you can use the usual GetProcAddress.ReferencesOpenGL 1.1, OpenGL 2.1, OpenGL 3.3, OpenGL 4.x1.2 Rendering contexts (Update 2013-09-21)With OpenGL 3.0 and higher there are more ways to create a rendering context. In the OpenGL wiki the terms simple and proper are used to describe two different types of contexts. Update: New MSAA context.(First part of the section is unchanged since 2013-05-18)In a simple context the pixel format is specified with the usual PFD-structure (PIXELFORMATDESCRIPTOR) and chosen with ChoosePixelFormat. The context is created with wglCreateContext.In a proper context the pixel format is specified with a pixel format attribute list and chosen with wglChoosePixelFormatARB. The context is created with wglCreateContextAttribsARB or wglCreateContext if the former can't be used.wglChoosePixelFormatARB belongs to the WGL_ARB_pixel_format extension. wglCreateContextAttribsARB belongs to the WGL_ARB_create_context extension.If you specify a major and minor version number in a context attribute list, wglCreateContextAttribsARB is able to create a context with a specific version as long as your video card supports this version.If your video card supports OpenGL 3.3 you are able to create a simple 3.3 context, a proper 2.1, 3.0, 3.1, 3.2, 3.3 context and a generic 1.1 (not hardware accelerated) context.On my XP with a NVIDIA card that supports OpenGL 3.3 I can create all these contexts. If I inspect the version with glGetString( $GL_VERSION ) it certainly shows these version numbers.oglIncludesoglContext.au3 contains two functions to create contexts: EnableOpenGL to create a simple context and EnableOpenGLEx to create a proper context:EnableOpenGL( $hWnd, ByRef $hDeviceContext, ByRef $hOpenGLRenderingContext ) EnableOpenGLEx( $hWnd, ByRef $hDeviceContext, ByRef $hOpenGLRenderingContext, $iMajor = -1, $iMinor = -1 )It also contains wrapper functions which prints out error messages in a MsgBox and Scite console:; A wrapper around EnableOpenGLEx which falls back to EnableOpenGL in case of an error CreateOpenGLContext( $hWnd, ByRef $hDeviceContext, ByRef $hOpenGLRenderingContext, $iMajor = -1, $iMinor = -1 )In the Context menu in ExLauncher.au3 (see 1.5 Run examples) you can select a context that your video card supports, save it in an inifile, and run the examples under this specific context.If your video card does not support OpenGL 3.0 or higher you are not able to select contexts. In that case you'll get the (simple) context that your video card supports.MSAA context (Update 2013-09-21)The purpose of a MSAA (multisample antialiasing, Multisampling, wgl_arb_multisample.txt) context is among other things to reduce flicker along edges. See picture in post 16.To create a context which supports MSAA is a matter of adding a few attributes to the pixel format attribute list. See wgl_pixel_format.txt for a list of attributes (not a complete list, more attributes have been added through extensions).This is the pixel format attribute list for a default proper context:$WGL_DRAW_TO_WINDOW_ARB, $GL_TRUE $WGL_SUPPORT_OPENGL_ARB, $GL_TRUE $WGL_DOUBLE_BUFFER_ARB, $GL_TRUE $WGL_PIXEL_TYPE_ARB, $WGL_TYPE_RGBA_ARB $WGL_COLOR_BITS_ARB, 32 $WGL_DEPTH_BITS_ARB, 24 $WGL_STENCIL_BITS_ARB, 8This is the pixel format attribute list for a MSAA context:$WGL_DRAW_TO_WINDOW_ARB, $GL_TRUE $WGL_ACCELERATION_ARB, $WGL_FULL_ACCELERATION_ARB $WGL_COLOR_BITS_ARB, 24 $WGL_ALPHA_BITS_ARB, 8 $WGL_DEPTH_BITS_ARB, 24 $WGL_STENCIL_BITS_ARB, 8 $WGL_DOUBLE_BUFFER_ARB, $GL_TRUE $WGL_SAMPLE_BUFFERS_ARB, 1 $WGL_SAMPLES_ARB, 4To be able to select different contexts an optional parameter $sContext = "Default" is added to the parameter specifikation of EnableOpenGLEx in oglIncludesoglContext.au3. This parameter can be used to specify a named context. So far you can use the names MSAA and MSAAbest. MSAA will create the context above. MSAAbest will test higher values of $WGL_SAMPLES_ARB starting with 16:Func GetPixelFormatAttribListMSAAbest( $hDeviceContext ) Local $aPixelFormatAttribListMSAAbest[19] = [ _ $WGL_DRAW_TO_WINDOW_ARB, $GL_TRUE, _ $WGL_ACCELERATION_ARB, $WGL_FULL_ACCELERATION_ARB, _ $WGL_COLOR_BITS_ARB, 24, _ $WGL_ALPHA_BITS_ARB, 8, _ $WGL_DEPTH_BITS_ARB, 24, _ $WGL_STENCIL_BITS_ARB, 8, _ $WGL_DOUBLE_BUFFER_ARB, $GL_TRUE, _ $WGL_SAMPLE_BUFFERS_ARB, 1, _ $WGL_SAMPLES_ARB, 0, _ 0 ] ; End of attributes list Local $n = UBound( $aPixelFormatAttribListMSAAbest ) Local $tPixelFormatAttribList = DllStructCreate( "int[" & $n & "]" ) For $i = 0 To $n - 1 DllStructSetData( $tPixelFormatAttribList, 1, $aPixelFormatAttribListMSAAbest[$i], $i+1 ) Next ; Choose best MSAA pixel format Local $iPixelFormat, $iNumFormats, $iSamples = 16 While $iSamples >= 1 $aPixelFormatAttribListMSAAbest[17] = $iSamples DllStructSetData( $tPixelFormatAttribList, 1, $aPixelFormatAttribListMSAAbest[17], 18 ) wglChoosePixelFormatARB( $hDeviceContext, DllStructGetPtr( $tPixelFormatAttribList ), 0, 1, $iPixelFormat, $iNumFormats ) If Not @error And $iNumFormats Then ExitLoop $iSamples /= 2 WEnd If $iSamples >= 1 Then ;MsgBox( 0, "MSAA context: $iSamples", $iSamples ) Return $aPixelFormatAttribListMSAAbest Else Return 0 EndIf EndFuncThe value of $WGL_SAMPLES_ARB is important. The tower to the right in the picture in post 16 is rendered with a value of 16 on my XP with a NVIDIA card. On my laptop with an Intel card the value of $WGL_SAMPLES_ARB is only 4. On my laptop the tower is only slightly better than the tower to the left in the picture.In function GetOpenGLContext in IncludesUtilities.au3 the MSAAbest context is set as a new default context by replacing these two lines:If $sContextType = "Simple" Then Return OpenGLSimpleContext( $hWnd, $hDC, $hRC ) ...with these linesIf $sContextType = "Simple" Then If EnableOpenGLEx( $hWnd, $hDC, $hRC, -1, -1, "MSAAbest" ) = 0 Then ;MsgBox( 48, "GetOpenGLContext", "MSAA context is not supported" ) Return OpenGLSimpleContext( $hWnd, $hDC, $hRC ) Else Return 1 EndIf ...A disadvantage of the MSAA context is that it can be more CPU/GPU intensive than the simple context or the default proper context. Especially in full screen windows.An easy way to switch between the MSAAbest context and the default proper context is to use ExLauncher.au3. In the Context | Select menu and the "Supported context" group you can select a Simple and Proper context.Simple will try to create a MSAAbest context and fall back to the Simple context in case of an error.Proper will create a default proper context (which does not support MSAA).LinksCreating an OpenGL Contextwgl_create_context.txtwgl_pixel_format.txtwgl_arb_multisample.txtMultisampling1.3 Textures and images (Update 2013-09-21)A texture is an OpenGL object that contains an image. Without an image loading library or at least an image loading function it can be tricky to load an image into a texture. These functions loads BMP, GIF, ICO, JPG, PNG, RGB, RGBA, TGA, TGA(RLE), TIF and WMF files. Update: Anisotropic filter (bottom of spoiler).(First part of the section is unchanged since 2013-05-18) ; OpenGL image loading functions ; ; LoadTextureImage( ByRef $texture, $imgFile, ByRef $width, ByRef $height, $fTexGlu = 0 ) ; Loads an image into a texture and creates mipmaps ; Wrapper around the OpenGL image loading functions ; Calls the proper function depending on image type (suffix) ; Image types: BMP, GIF, ICO, JPG, PNG, RGB, RGBA, TGA, TIF and WMF ; The image can be specified as a file name or as an internet URL ( "http://..." ) ; ( Internet URL is available for BMP, GIF, ICO, JPG and WMF images ) ; ; LoadImage( ByRef $texture, $imgFile, ByRef $width, ByRef $height, $fTexGlu = 0 ) ; Reads a BMP, GIF, ICO, JPG and WMF image into a byte structure ; The image can be specified as a file name or as an internet URL ( "http://..." ) ; Calls CreateTexture() ; ; LoadGDIimage( ByRef $texture, $imgFile, ByRef $width, ByRef $height, $fTexGlu = 0 ) ; Reads a BMP, JPG, PNG and TIF image into a byte structure ; PNG and TIF images when called through LoadTextureImage() ; BMP, JPG, PNG and TIF images when called directly ; Calls CreateTexture() ; ; LoadTGAimage( ByRef $texture, $imgFile, ByRef $width, ByRef $height, $fTexGlu = 0 ) ; Reads a TGA ( uncompressed or RLE-encoded ) image into a byte structure ; Calls CreateTexture() ; ; LoadRGBimage( ByRef $texture, $imgFile, $width, $height, $fTexGlu = 0 ) ; Reads a RGB and RGBA image into a byte structure ; Calls CreateTexture() ; ; CreateTexture( ByRef $texture, $width, $height, $format, $pImage, $fTexGlu = 0 ) ; Loads a byte structure into a texture and creates mipmapsCode in oglIncludesoglLoadImages.au3.LoadImage is implemented with the IPicture interface and OleLoadPicturePath. Because these functions supports creation of a picture object from the contents of a stream, you can specify the image as an URL. IPicture interface handles BMP, GIF, ICO, JPG and WMF images. LoadImage returns the width and height of the image.LoadGDIimage is based on the GDIPlus UDF and loads BMP, JPG, PNG and TIF images. LoadGDIimage returns the width and height of the image.LoadTGAimage handles uncompressed and RLE-encoded (runlength encoded, a lossless compression format) TGA images. LoadTGAimage returns the width and height of the image.LoadRGBimage handles the native OpenGL image formats RGB and RGBA. You must specify width and height of the image. The easiest way to convert an image to RGB/RGBA format is to use GIMP (GNU Image Manipulation Program). Alternatively you can use GraphicsMagick:gm convert -flop -rotate 180 Font.tga rgba:Font.rgbaThe options "-flop -rotate 180" means flip the picture vertical (around a horizontal line in the middle of the picture) and rotate 180 degrees. This is necessary to show the picture properly in an OpenGL window.CreateTextureIf the video card supports OpenGL 2.1 or higher glTexImage2D and glGenerateMipmap will be used to load images into textures and create mipmaps.If the supported version is 2.0 or lower gluBuild2DMipmaps will be used to load images into textures and create mipmaps.Because gluBuild2DMipmaps is a very widely used function, you can specify $fTexGlu = 1 to force usage of the GLU function.CreateTexture returns the texture name or id (integer > 0).CreateTexture is called in the bottom of the image loading functions above. In the WikiBooksGraphs examples (OpenGL 2.1 examples) CreateTexture is used to create textures from arrays of graph data.TransparencySeveral image formats support transparency. In these examples PNG, RGBA, TGA and TGA (RLE) are used for textures with transparent areas. Enable transparency with blending as follows:glEnable( $GL_BLEND ) glBlendFunc( $GL_SRC_ALPHA, $GL_ONE_MINUS_SRC_ALPHA )Anisotropic filter (Update 2013-09-21)To reduce flicker in textures along edges you can use an anisotropic filter. Such a filter can be applied through the GL_EXT_texture_filter_anisotropic extension. In this update the filter is implemented in CreateTexture in oglLoadImages.au3:Local Static $fMaxAnisotrophy = 0.0 If $fMaxAnisotrophy = 0.0 Then If CheckOpenGLextension( "GL_EXT_texture_filter_anisotropic" ) Then glGetFloatv( $GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, $fMaxAnisotrophy ) If $fMaxAnisotrophy > 1.0 Then ;MsgBox( 0, "CreateTexture: $fMaxAnisotrophy", $fMaxAnisotrophy ) glTexParameterf( $GL_TEXTURE_2D, $GL_TEXTURE_MAX_ANISOTROPY_EXT, $fMaxAnisotrophy ) Else $fMaxAnisotrophy = 1.0 EndIf Else $fMaxAnisotrophy = 1.0 EndIf EndIfLinksTextureImage FormatAnisotropic filter1.4 OpenGL 1.1 examples (Update 2013-08-03)SamplesOpenGL 1.1 contains the OpenGL 1.1 examples. Here is a list:Added a new group of examples in glCommands folder (2013-08-03):expandcollapse popupglCommands\glCallLists.au3 glCommands\glColorPointer.au3 glCommands\glDrawArrays (GL_QUADS).au3 glCommands\glReadPixels.au3 glCommands\glTexCoordPointer.au3 glCommands\glVertexPointer.au3 Miscellaneous\Sparklers\Sparklers by trancexx.au3 Miscellaneous\Sparklers\Sparklers with stars.au3 Miscellaneous\Threads\Moving stars 1.au3 Miscellaneous\Threads\Moving stars 2.au3 Miscellaneous\Threads\Point follows mouse.au3 Miscellaneous\Threads\Threads following mouse 1.au3 Miscellaneous\Threads\Threads following mouse 2.au3 Text and fonts\2D bitmap fonts with wglUseFontBitmaps.au3 Text and fonts\3D outline fonts with wglUseFontOutlines.au3 Text and fonts\Texture font from image file.au3 ; oglIncludes\oglUtilities.au3 contains two functions CreateOpenGLBitmapFont and CreateOpenGLOutlineFont ; to create bitmap and outline fonts. Textures\Basic\Homer Simpson.au3 Textures\Basic\Modern OpenGL images.au3 Textures\Basic\Test image formats.au3 Textures\Cubes\Colored cube, no texture.au3 Textures\Cubes\Cube Homer Simpson.au3 Textures\Cubes\Cube with 6 textures.au3 Textures\Cubes\Rubik's Cube.au3 Textures\Foggy city\Build foggy city.au3 Textures\Foggy city\Foggy city by minx.au3 Textures\Foggy city\Foggy city with 2 textures.au3 Textures\Foggy city\Foggy city with 5 textures.au3 Textures\Spheres\Textured sphere by minx.au3 Textures\Spheres\Textured sphere with GLU-functions.au3 Textures\Tunnels\Transparent texture.au3 Textures\Tunnels\Tunnel effect 1.au3 Textures\Tunnels\Tunnel effect 2.au3A script where the name ends with a 2-number is an optimized version of the example. See section 1.6.Code in examples is structured in this way:Opt( "GUIOnEventMode", 1 ) MainFunc() While 1 If $bResize Then glViewport( 0, 0, $iWidth, $iHeight ) $bResize = False EndIf DisplayFunction() Sleep(10) WEnd Func MainFunc() If Not InitGUIwindow() Then GUI_EVENT_CLOSE() If Not InitOpenGLwindow() Then GUI_EVENT_CLOSE() If Not CreateResources() Then GUI_EVENT_CLOSE() EndFunc Func InitGUIwindow() EndFunc Func InitOpenGLwindow() EndFunc Func CreateResources() EndFunc Func DisplayFunction() EndFunc1.5 Run examples (Update 2013-08-03)You can run examples in the Samples folder by double clicking, or you can run them from Scite. The easiest is to use ExLauncher.au3 in the top folder:ExLauncher.au3 starts up ready to run the OpenGL 1.1 examples.Menu system (Update 2013-08-03)In the Samples menu you can select other examples. Use the Models item to open the Wavefront (OBJ) 3D model viewers (see chapter 4) or one of the OpenGL 1.1 examples which shows how to use the 3D models (chapter 4). Note the Templates item in the bottom of the list. You can use these scripts as a base for your own examples.In the Context menu you can get info about the rendering context that your video card supports and the current context. You can select a context and save it in an inifile (Version.ini) in the top folder. Then this context will be the current context, and the examples will be run under this specific context. (Note that this will not change the version of the OpenGL Shading Language. The GLSL version is always the highest version supported by your video card. See section 2.2 for info about GLSL.)The Tools menu contains a few tools to get information about your OpenGL version and context. It also contains a menu item to launch the Model viewer (see chapter 4).The Links menu contains links to information including the links in this page.List of functions (Update 2013-06-16)If you select the first item in the Tools menu the last 21 lines of the list will look like this:[137]|------------------------------ Extensions ------------------------------ [138]|------------------------------ OpenGL 2.1 ------------------------------ [139]|---------------------- GL_ARB_framebuffer_object ----------------------- [140]|glGenerateMipmap( $target ) [141]|---------------------- GL_ARB_vertex_array_object ---------------------- [142]|glBindVertexArray( $array ) [143]|glDeleteVertexArrays( $n, ByRef $arrays ) [144]|glGenVertexArrays( $n, ByRef $arrays ) [145]|------------------------------ OpenGL 3.0 ------------------------------ [146]|------------------------------ OpenGL 3.1 ------------------------------ [147]|------------------- GL_ARB_draw_elements_base_vertex ------------------- [148]|glDrawElementsBaseVertex( $mode, $count, $type, $indices, $basevertex ) [149]|--------------------- GL_ARB_uniform_buffer_object --------------------- [150]|glBindBufferRange( $target, $index, $buffer, $offset, $size ) [151]|glGetUniformBlockIndex( $program, $uniformBlockName ) [152]|glUniformBlockBinding( $program, $uniformBlockIndex, $uniformBlockBinding ) [153]|------------------------------ OpenGL 3.2 ------------------------------ [154]|------------------------------ OpenGL 3.3 ------------------------------ [155]|------------------------------ OpenGL 4.0 ------------------------------ [156]|------------------------------ OpenGL 4.1 ------------------------------ [157]|------------------------------ OpenGL 4.2 ------------------------------This part of the list deals with the OpenGL extensions.The information in the list must be interpreted in this way: If you need to use the glGetUniformBlockIndex function (line #151), your video card must support OpenGL version 3.1 (#146) or version 2.1/3.0 and the GL_ARB_uniform_buffer_object extension (#149).glGetUniformBlockIndex is part of the OpenGL 3.1 core functions. If you have 3.1, you have this function.glGetUniformBlockIndex is also part of the GL_ARB_uniform_buffer_object extension. If you have this extension, you have this function. Also if your video card only supports OpenGL 2.1/3.0.If your video card supports OpenGL 2.1/3.0 and you have upgraded your system with the latest drivers and software, there is a good chance that you have this extension.1.6 Threads exampleImagine that when you move the mouse across the screen, it'll create a track on the screen that follows your mouse. Then imagine that there isn't just one track, but many tracks that are slightly offset relative to each other. This is threads:You find the example in the folder "SamplesOpenGL 1.1MiscellaneousThreads". Moving stars.au3 shows how to create some stars. Point follows mouse.au3 shows how to make a point follow the mouse. Threads following mouse.au3 is the threads example.To make examples like these look good, you need some fast loops. An efficient way to make fast loops is to use The Embedded Flat Assembler (FASM) UDF by Ward. In scripts where the name ends with a 2-number loops are optimized with FASM assembler code.In Threads following mouse 2.au3 three loops are optimized with FASM assembler code:For $i = 0 To $iThreadCount $aThreads[$i][0][0] = $xMouse $aThreads[$i][0][1] = $yMouse $aThreads[$i][0][2] = -2 For $j = $iThreadLength To 1 Step -1 $aThreads[$i][$j][0] = ( 2 * $aThreads[$i][$j-1][0] + $aThreads[$i][$j][0] ) / 2.9 + $aThreadOffsets[$i][0] $aThreads[$i][$j][1] = ( 2 * $aThreads[$i][$j-1][1] + $aThreads[$i][$j][1] ) / 2.9 + $aThreadOffsets[$i][1] $aThreads[$i][$j][2] = ( 2 * $aThreads[$i][$j-1][2] + $aThreads[$i][$j][2] ) / 2.9 + $aThreadOffsets[$i][2] Next NextFor $i = 0 To $iThreadCount glBegin( $GL_LINE_STRIP ) For $j = 0 To $iThreadLength $m = 1 - $j / $iThreadLength $r = 0.3 * ( 0.3 + Sin( $fElapsedTime / 1300 - $i / 50 ) ) * $m $g = 0.3 * ( 0.3 + Sin( $fElapsedTime / 700 - $i / 45 ) ) * $m $b = 0.3 * ( 0.3 + Sin( $fElapsedTime / 1000 - $i / 60 ) ) * $m glColor3f( $r, $g, $b ) glVertex3f( $x, $y, $z ) Next glEnd() NextFor $i = 0 To $iStars glBegin( $GL_LINE_STRIP ) ; Start point glColor3f( 0, 0, 0 ) glVertex3f( $aStars[$i][0], $aStars[$i][1], $aStars[$i][2] ) ; p0: x,y,z ; End point $rgbColor = $aStars[$i][3] / 5 glColor3f( $rgbColor, $rgbColor, $rgbColor ) glVertex3f( $aStars[$i][0], $aStars[$i][1], $aStars[$i][3] ) ; p1: x,y,z ; Start point = end point $aStars[$i][2] = $aStars[$i][3] ; p0.z = p1.z ; Increase z-coordinate of end point $aStars[$i][3] += $aStars[$i][4] ; p1.z += dz If $aStars[$i][2] >= 10 Then $aStars[$i][2] = 0 ; p0.z $aStars[$i][3] = 0 ; p1.z EndIf glEnd() NextThis is the assembler source (32 bit version) to implement the first loop:expandcollapse popup; FASM assembler code ; $aFasmData = DllStructCreate( "ushort;ushort;uint;float;ptr" ) ; Element 1, offset 0 : Ushort $iThreadCount ; Element 2, offset 2 : Ushort $iThreadLength ; Element 3, offset 4 : Uint ( $iThreadLength + 1 ) * 3 * 4 ; Element 4, offset 8 : Constant float 2.9 ; Element 5, offset 12 : Pointer in $aThreadOffsets ; $aThreads = DllStructCreate( "float[" & ( $iThreadCount + 1 ) * ( $iThreadLength + 1 ) * 3 & "]" ) ; $aThreadOffsets = DllStructCreate( "float[" & ( $iThreadCount + 1 ) * 3 & "]" ) ; For $i = 0 To $iThreadCount ; $aThreads[$i][0][0] = $xMouse ; $aThreads[$i][0][1] = $yMouse ; $aThreads[$i][0][2] = $zMouse ; ; For $j = $iThreadLength To 1 Step -1 ; $aThreads[$i][$j][0] = ( 2 * $aThreads[$i][$j-1][0] + $aThreads[$i][$j][0] ) / 2.9 + $aThreadOffsets[$i][0] ; $aThreads[$i][$j][1] = ( 2 * $aThreads[$i][$j-1][1] + $aThreads[$i][$j][1] ) / 2.9 + $aThreadOffsets[$i][1] ; $aThreads[$i][$j][2] = ( 2 * $aThreads[$i][$j-1][2] + $aThreads[$i][$j][2] ) / 2.9 + $aThreadOffsets[$i][2] ; Next ; Next ; Parameters: ; [ebp + 08] : $iThreadCount ; [ebp + 12] : $iThreadLength ; [ebp + 16] : $pThreads ; [ebp + 20] : $pThreadOffsets ; [ebp + 24] : $xMouse ; [ebp + 28] : $yMouse ; [ebp + 32] : $zMouse ; [ebp + 36] : $pFasmData use32 push ebp mov ebp, esp ; --- Initializations --- ; Handle parameters and fill in the $aFasmData table ; ebx is pointer in $aFasmData table mov ebx, [ebp + 36] ; $aFasmData start ; Initialize $i in the iLoop mov [ebx], word 0 ; This is $i in "For $i = 0 To $iThreadCount" ; Calculate the number of bytes per thread ; Bytes per thread = ( $iThreadLength + 1 ) * 3 * 4 mov [ebx + 04], word 12 ; $aFasmData element 3 mov ax, [ebp + 12] ; $iThreadLength inc ax ; $iThreadLength + 1 mul word [ebx + 04] ; * ( 3 * 4 ) mov [ebx + 04], ax ; Store least significant bytes (little-endian) mov [ebx + 06], dx ; Store most significant bytes ; $iThreadLength = 100 => 1212 bytes per thread ; $iThreadCount = 50 => 61812 bytes in $aThreads ; eax is pointer in $aThreads table mov eax, [ebp + 16] ; $aThreads start sub eax, [ebx + 04] ; Subtract ( $iThreadLength + 1 ) * 3 * 4 bytes from pointer ; Pointer in $aThreadOffsets table mov ecx, [ebp + 20] ; $pThreadOffsets is pointer in $aThreadOffsets add ecx, 12 ; Add 12 bytes to the pointer, now it's positioned at the ... mov [ebx + 12], ecx ; Store pointer in $aFasmData element 5 ; --- Calculations --- iLoop: ; For $i = 0 To $iThreadCount ; Calculate pointer (eax) for the next thread in $aThreads add eax, [ebx + 04] ; Add ( $iThreadLength + 1 ) * 3 * 4 bytes to pointer finit ; Init FPU ; $aThreads[$i][0][0] = $xMouse fld dword [ebp + 24] ; $xMouse fst dword [eax + 00] ; $xMouse -> $aThreads[$i][0][0] ; $aThreads[$i][0][1] = $yMouse fld dword [ebp + 28] ; $yMouse fst dword [eax + 04] ; $yMouse -> $aThreads[$i][0][1] ; $aThreads[$i][0][2] = $zMouse fld dword [ebp + 32] ; $zMouse fst dword [eax + 08] ; $zMouse -> $aThreads[$i][0][2] ; Initialize $j in the jLoop, start with $j = $iThreadLength and count backwards to 1 ; Including the first point above this gives a total of $iThreadLength + 1 points in a thread mov cx, [ebp + 12] ; $iThreadLength mov [ebx + 02], cx ; This is $j in "For $j = $iThreadLength To 1 Step -1" ; The jLoop is moving backwards down the thread, set the pointer to the end of the thread add eax, [ebx + 04] ; Add the number of bytes in a thread ... ; In the jLoop ecx is a pointer in $aThreadOffsets mov ecx, [ebx + 12] ; $aFasmData element 5 contains a pointer in ... jLoop: ; For $j = $iThreadLength To 1 Step -1 (going backwards) mov dl, 3 ; dl = 3 is used as counter in the zyxLoop, 3 coordinates zyxLoop:; Do the calculations for each of the coordinates z,y,x in that order (going backwards) sub eax, 4 ; Subtract 4 bytes from the pointer in $aThreads, the ... sub ecx, 4 ; Subtract 4 bytes from the pointer in $aThreadOffsets ... finit ; Init FPU ; z ~ $aThreads[$i][$j][2], y ~ $aThreads[$i][$j][1], x ~ $aThreads[$i][$j][0] ; $aThreads[$i][$j][2] = ( 2 * $aThreads[$i][$j-1][2] + $aThreads[$i][$j][2] ) / 2.9 ... ; It's exactly the same formula for each of the coordinates fld dword [eax - 12] ; $aThreads[$i][$j-1][2] fadd st0, st0 ; * 2 fadd dword [eax] ; + $aThreads[$i][$j][2] fdiv dword [ebx + 08] ; / 2.9 ( 2.9 is stored in $aFasmData element 4 ) fadd dword [ecx] ; + $aThreadOffsets[$i][2] fst dword [eax] ; Result -> $aThreads[$i][$j][2] dec dl ; Decrement coordinate counter jnz zyxLoop ; If > 0 jump to zyxLoop jNext: ; For $j = $iThreadLength To 1 Step -1 add ecx, 12 ; Add 12 bytes to the $aThreadOffsets pointer dec word [ebx + 02] ; This is $j in "For $j = $iThreadLength To 1 Step -1" ... jnz jLoop ; If > 0 jump to previous (going backwards) point in the ... iNext: ; For $i = 0 To $iThreadCount sub eax, 12 ; The jLoop terminates at second point, subtract 12 bytes ... add [ebx + 12], dword 12 ; Add 12 bytes to the $aThreadOffsets pointer to make it ... inc word [ebx] ; This is $i in "For $i = 0 To $iThreadCount", $i += 1 mov cx, [ebp + 08] ; $iThreadCount inc cx ; $iThreadCount += 1 cmp cx, word [ebx] ; Compare $i with $iThreadCount jne iLoop ; Jump to next thread if not equal pop ebp ret 32You find the assembler sources in Threadsutilitiesfasm in files Fasm1.asm and Fasm1-x64.asm. Source code for the stars is in Miscellaneousutilities.In SamplesOpenGL 1.1TexturesTunnelsTunnel effect 2.au3 two loops are optimized with FASM assembler code too.Chapter 2 deals with OpenGL 2.x and the new concepts that appeared in these versions. Most important is the concept of shaders.2.1 New conceptsIn the last versions of OpenGL 1.x and especially in version 2.0 and 2.1 a new set of concepts showed up. It was concepts such as shaders, attributes, uniforms and vertex buffer objects (VBOs):A shader is a program running on the GPU (see next section). Attributes and uniforms are used to pass information to shaders. Vertex buffer objects are used to pass data to the GPU memory.Shaders is an important concept in newer versions of OpenGL. Shaders were introduced in version 2.0. In websites about OpenGL one can often see the development from OpenGL 1.1 to 2.0 described as the change of a fixed pipeline to a programmable pipeline. It's the shaders that makes the pipeline programmable.The new concepts and commands are used in the OpenGL 2.1 and 3.3 examples. These examples are translations of examples you can find in the websites WikiBooks OpenGL Programming, Modern OpenGL (2.1 examples) and OpenGLBook.com (3.3 examples). The easiest way to get an explanation of the concepts is to read the text in these websites. OpenGLBook.com contains some good explanations.OpenGL 1.1 was released in 1997. 2.0 in 2004 and 2.1 in 2006. OpenGL 3.3 was released in 2010.2.2 ShadersShaders were introduced in OpenGL 2.0. A shader is a program running on the GPU. You write a shader in the OpenGL Shading Language (GLSL). It's a C-like language:Vertex shader:attribute vec2 coord2d; uniform mat4 transform; void main(void) { gl_Position = transform * vec4(coord2d.xy, 0, 1); }The vertex shader calculates a point on screen from a vertex in the OpenGL coordinate system.Fragment shader:uniform vec4 color; void main(void) { gl_FragColor = color; }The fragment shader calculates colors of the pixels.You make your shaders available with a set of commands as follows:$iVertexShaderId = glCreateShader( $GL_VERTEX_SHADER ) glShaderSource( $iVertexShaderId, 1, $sVertexShader, StringLen( $sVertexShader ) ) glCompileShader( $iVertexShaderId ) $iProgramId = glCreateProgram() glAttachShader( $iProgramId, $iVertexShaderId ) glLinkProgram( $iProgramId ) glUseProgram( $iProgramId )It appears to be common to save shaders in text files with extensions v.glsl and f.glsl. LoadGLSLshader is a function to load a shader in a text file. You find it in oglIncludesoglLoadShaders.au3:expandcollapse popupFunc LoadGLSLshader( ByRef $shaderId, $shaderFile, $shaderType ) ; File exists? If Not FileExists( $shaderFile ) Then PrintError( "Function LoadGLSLshader()" & @CRLF & _ "ERROR: File """ & $shaderFile & """ does not exists." ) Return SetError(1,0,0) EndIf ; Read file Local $glslFile = FileOpen( $shaderFile, 0 ) Local $glslSource = FileRead( $glslFile ) FileClose( $glslFile ) Local $iOpenGLerror = glGetError(), $bShader ; Create shader $shaderId = glCreateShader( $shaderType ) glShaderSource( $shaderId, 1, $glslSource, StringLen( $glslSource ) ) $iOpenGLerror = glGetError() If $iOpenGLerror <> $GL_NO_ERROR Then PrintOpenGLerror( "LoadGLSLshader()", "glCreateShader...", $iOpenGLerror ) Return SetError(2,0,0) EndIf ; Compile shader glCompileShader( $shaderId ) glGetShaderiv( $shaderId, $GL_COMPILE_STATUS, $bShader ) If $bShader = 0 Then PrintError( "Function LoadGLSLshader()" & @CRLF & _ "ERROR: Failed to compile shader """ & $shaderFile & """." ) glDeleteShader( $shaderId ) Return SetError(3,0,0) EndIf Return 1 EndFuncLinksGLSL (OpenGL), GLSL (Wikipedia), Reference2.3 Math functionsWhen you use shaders in OpenGL 2.0 and higher you don't use old functions like glMultMatrix, glRotate, glTranslate, gluLookAt or gluPerspective. You have to use a new set of functions that works with the functionality of the shaders:OpenGL Mathematics library (GLM) is a header only C++ library that provides these functions.Note that OpenGL and GLM accesses matrices in column major order. In AutoIt and C/C++ matrices or arrays are normally accessed in row major order. If you compare the results of GLM matrix calculations with most other matrix calculations, you'll see that rows and columns are interchanged.oglIncludesglmMaths.au3 contains a subset of these funtions. Most important are:glmInverse() - returns the inverse of a 4x4 matrix glmLookAt() - builds a look at view matrix glmMultiply() - multiplies two 4x4 matrices glmPerspective() - creates a matrix for a symmetric perspective-view frustum glmRotate() - builds a rotation 4x4 matrix created from an axis vector and an angle glmScale() - builds a scale 4x4 matrix created from a 3-component vector glmTranslate() - builds a translation 4x4 matrix created from a vectorglmMaths.au3 contains also a section with 3x3 matrix calculations, a section with functions for quaternion vectors, and sections with functions for 2-, 3- and 4-component vectors.2.4 OpenGL 2.1 examples (Update 2013-06-16)SamplesOpenGL 2.1 contains the OpenGL 2.1 examples. All these examples are based on shaders and the new concepts in OpenGL 2.1. Here is a list:expandcollapse popup1 WikiBooks\Basics\Tutorial 01.au3 1 WikiBooks\Basics\Tutorial 02.au3 1 WikiBooks\Basics\Tutorial 03-1.au3 1 WikiBooks\Basics\Tutorial 03-2.au3 1 WikiBooks\Basics\Tutorial 03-3.au3 1 WikiBooks\Basics\Tutorial 04.au3 1 WikiBooks\Basics\Tutorial 05.au3 1 WikiBooks\Basics\Tutorial 06.au3 ; The first examples are the basic examples. Tutorial 01 is the usual triangle. Here it's implemented with vertex ; and fragment shaders. The other examples shows how to use some of the new concepts: VBOs, attributes and uniforms. ; There is also an introduction to the GLM library, the OpenGL Mathematics library. When you are using shaders and ; the GLSL shading language, you are typically also using a mathematics library. GLM is very widely used. The last ; example, Tutorial 06, is a rotating textured cube. 1 WikiBooks\Graphs\Graph01.au3 1 WikiBooks\Graphs\Graph02.au3 1 WikiBooks\Graphs\Graph03.au3 1 WikiBooks\Graphs\Graph04.au3 1 WikiBooks\Graphs\Graph05.au3 ; Textures are normally used to represent images. Graph02, 04 and 05 shows how textures can be used to ; represent graph data. Graph04 and 05 shows the graph of the "Mexican hat" function. Zoom out with Page ; Down to see the effects of the textures (and the mipmaps). ; For the examples in the three sections below only the first file in each section contains code. The rest ; of the files calls the first one with parameters to load the proper shaders for the specific example. ; Some of these shaders are quite advanced. Especially those dealing with lights and lightsources. 1 WikiBooks\Lights\Lights-01.au3 1 WikiBooks\Lights\Lights-02.au3 1 WikiBooks\Lights\Lights-03.au3 1 WikiBooks\Lights\Lights-04.au3 1 WikiBooks\Lights\Lights-05.au3 1 WikiBooks\Lights\Lights-06.au3 1 WikiBooks\Textures\0-Earth.au3 1 WikiBooks\Textures\1 Tiling and offsets\1-Earth.au3 1 WikiBooks\Textures\2 Light sources\2-Earth.au3 1 WikiBooks\Textures\3 Glossy surfaces\3-Earth.au3 1 WikiBooks\Textures\3 Glossy surfaces\4-Earth.au3 1 WikiBooks\Textures\4 Transparency\5-Earth.au3 1 WikiBooks\Textures\4 Transparency\6-Earth.au3 1 WikiBooks\Textures\4 Transparency\7-Earth.au3 1 WikiBooks\Textures\5 Layers of textures\8-Earth.au3 ; The Modern OpenGL examples are based on two images (sunrise and sunset) slowly fading forth and back in a loop. 2 Modern OpenGL\hello-1.au3 2 Modern OpenGL\hello-2.au3 2 Modern OpenGL\hello-3.au3 2 Modern OpenGL\hello-4.au3 2 Modern OpenGL\hello-5.au3 2 Modern OpenGL\hello-6.au3 2 Modern OpenGL\hello-7.au3 2 Modern OpenGL\hello-8.au3To get an explanation of the code in the examples read the text in the websites WikiBooks OpenGL Programming and Modern OpenGL.Chapter 3 is mostly about OpenGL 3.x. There is also a section on OpenGL/GLSL versions and a section on error handling.3.1 OpenGL versionsOpenGL versions and corresponding GLSL version:OpenGL: 2.0 2.1 3.0 3.1 3.2 3.3 4.0 4.1 4.2 4.3 GLSL: 1.10 1.20 1.30 1.40 1.50 3.30 4.00 4.10 4.20 4.30Starting with OpenGL 3.3 the GLSL version matches.If the GLSL code in your shaders uses commands belonging to version 3.30, you need OpenGL 3.3 or higher to be able to run the code. Only OpenGL 3.3 or higher supports GLSL 3.30. Also if your OpenGL commands only requires OpenGL 2.1.If your video card supports OpenGL 3.1, and you have upgraded to the latest drivers and software, which can include GLSL 3.30 or part of it, there is a good chance to be able to run the shaders anyway. At least if the code in the shaders isn't too advanced.3.2 Error handlingOpenGL error handling is done with glGetError and glGet-functions. Initialize error handling before a group of commands and check errors after the last command. Here error handling is illustrated with LoadGLSLshader in oglIncludesoglLoadShaders.au3:expandcollapse popupFunc LoadGLSLshader( ByRef $shaderId, $shaderFile, $shaderType ) ; File exists? If Not FileExists( $shaderFile ) Then PrintError( "Function LoadGLSLshader()" & @CRLF & _ "ERROR: File """ & $shaderFile & """ does not exists." ) Return SetError(1,0,0) EndIf ; Read file Local $glslFile = FileOpen( $shaderFile, 0 ) Local $glslSource = FileRead( $glslFile ) FileClose( $glslFile ) Local $iOpenGLerror = glGetError(), $bShader ; <<<<<<<<<< Initialize error handling <<<<<<<<<< ; Create shader $shaderId = glCreateShader( $shaderType ) glShaderSource( $shaderId, 1, $glslSource, StringLen( $glslSource ) ) $iOpenGLerror = glGetError() ; <<<<<<<<<<<<<<<< Check errors <<<<<<<<<<<<<<<<< If $iOpenGLerror <> $GL_NO_ERROR Then PrintOpenGLerror( "LoadGLSLshader()", "glCreateShader...", $iOpenGLerror ) Return SetError(2,0,0) EndIf ; Compile shader glCompileShader( $shaderId ) glGetShaderiv( $shaderId, $GL_COMPILE_STATUS, $bShader ) ; <<<<<<<<< glGet-function <<<<<<<<<< If $bShader = 0 Then PrintError( "Function LoadGLSLshader()" & @CRLF & _ "ERROR: Failed to compile shader """ & $shaderFile & """." ) glDeleteShader( $shaderId ) Return SetError(3,0,0) EndIf Return 1 EndFunc3.3 OpenGL 3.3 examples (Update 2013-06-16)SamplesOpenGL 3.3 contains the OpenGL 3.3 examples. Most of these examples are added in an update on 2013-06-16.Update 2013-06-16The new examples are translated from Learning Modern 3D Graphics Programming. These are good examples, the shaders are not too advanced, and there are good explanations on the website. The examples are based on the Unofficial OpenGL Software Development Kit. You can probably run the examples if your video card supports OpenGL 3.1.Here is a list of the examples:expandcollapse popupModern 3D Graphics\I. The Basics\1. Hello, Triangle!\1.1 Tutorial 1.au3 Modern 3D Graphics\I. The Basics\2. Playing with Colors\2.1 FragPosition.au3 Modern 3D Graphics\I. The Basics\2. Playing with Colors\2.2 VertexColors.au3 ; The examples below shows a rotating triangle. In the first example two AutoIt functions are used to rotate the ; triangle. In example 3.2 and 3.3 first one and then both functions are move to the vertex shader. That means ; the functions are running on the GPU. In 3.4 color information is added to the fragnment shader. Modern 3D Graphics\II. Positioning\3. OpenGL's Moving Triangle\3.1 cpuPositionOffset.au3 Modern 3D Graphics\II. Positioning\3. OpenGL's Moving Triangle\3.2 vertPositionOffset.au3 Modern 3D Graphics\II. Positioning\3. OpenGL's Moving Triangle\3.3 vertCalcOffset.au3 Modern 3D Graphics\II. Positioning\3. OpenGL's Moving Triangle\3.4 fragChangeColor.au3 ; How to create an OpenGL window with a proper aspect ratio using vertex shaders? Modern 3D Graphics\II. Positioning\4. Objects at Rest\4.1 OrthoCube.au3 Modern 3D Graphics\II. Positioning\4. Objects at Rest\4.2 ShaderPerspective.au3 Modern 3D Graphics\II. Positioning\4. Objects at Rest\4.3 MatrixPerspective.au3 Modern 3D Graphics\II. Positioning\4. Objects at Rest\4.4 AspectRatio.au3 ; When you have two overlapping objects, how do you define which object to be in front and which to be in back? Modern 3D Graphics\II. Positioning\5. Objects in Depth\5.1 OverlapNoDepth.au3 Modern 3D Graphics\II. Positioning\5. Objects in Depth\5.2 BaseVertexOverlap.au3 Modern 3D Graphics\II. Positioning\5. Objects in Depth\5.3 DepthBuffer.au3 Modern 3D Graphics\II. Positioning\5. Objects in Depth\5.4 VertexClipping.au3 Modern 3D Graphics\II. Positioning\5. Objects in Depth\5.5 DepthClamping.au3 ; The examples in section 6 deals with moving objects. The Hierarchy example is a robotic arm. It consists of 5 ; moving parts which can be moved in 7 different ways. A hierarchy of matrices are used to control the movements. ; The last example shows how to handle three robotic arms. Modern 3D Graphics\II. Positioning\6. Objects in Motion\6.1 Translation.au3 Modern 3D Graphics\II. Positioning\6. Objects in Motion\6.2 Scaling.au3 Modern 3D Graphics\II. Positioning\6. Objects in Motion\6.3 Rotation.au3 Modern 3D Graphics\II. Positioning\6. Objects in Motion\6.4 Hierarchy.au3 Modern 3D Graphics\II. Positioning\6. Objects in Motion\Three robotic arms.au3 ; Section 7 shows how to build a world of objects with a dynamic, moving camera. A building that should look like ; Parthenon (a temple on the Athenian Acropolis) is created in an area with some trees. The building consists of ; 30 columns, each composed of 3 different parts. This provides 90 OpenGL objects. They are created in a loop. ; There are 98 trees which consists of 2 parts. This provides 196 objects created in a new loop. These two loops ; are executed for every single OpenGL drawing cycle. In order to ensure sufficiently good performance, it is ; necessary to optimize these loops. This can be done with The Embedded Flat Assembler (FASM) UDF by Ward. The ; scripts where the name ends with a 2-number are the optimized versions. ; ; (The "1-a"-scripts (not shown below) were used to create the optimized versions. They are slightly modified ; copies of the "1"-scripts.) Modern 3D Graphics\II. Positioning\7. World in Motion\7.1 World Scene-1.au3 Modern 3D Graphics\II. Positioning\7. World in Motion\7.1 World Scene-2.au3 Modern 3D Graphics\II. Positioning\7. World in Motion\7.2 World With UBO-1.au3 Modern 3D Graphics\II. Positioning\7. World in Motion\7.2 World With UBO-2.au3 ; The last examples shows how to maneuver a spaceship or an airplane. In 8.1 the maneuvers are made with gimbals. ; This means that the maneuvers are composed of rotations about the x-, y- and z-axes. A better way is to use yaw, ; pitch and roll transformations and do the calculations with quaternion vectors. This is shown in example 2 - 4. Modern 3D Graphics\II. Positioning\8. Getting Oriented\8.1 GimbalLock.au3 Modern 3D Graphics\II. Positioning\8. Getting Oriented\8.2 QuaternionYPR.au3 Modern 3D Graphics\II. Positioning\8. Getting Oriented\8.3 CameraRelative.au3 Modern 3D Graphics\II. Positioning\8. Getting Oriented\8.4 Interpolation.au3 ; Use W- and S-rotations to see the difference between Right and Left multiplication in 8.2. ; Use Q- and E-positions to see the difference between Lerp and Slerp interpolation in 8.4.So far only the examples in chapter I. and II. are translated.First 2013-05-19OpenGLBook\Chapter 1\Chapter 1.1.au3 OpenGLBook\Chapter 2\Chapter 2.1.au3 OpenGLBook\Chapter 2\Chapter 2.2.au3 OpenGLBook\Chapter 2\Chapter 2.3.au3 OpenGLBook\Chapter 2\Chapter 2.4.au3 OpenGLBook\Chapter 3\Chapter 3.1.au3 OpenGLBook\Chapter 3\Chapter 3.2.au3To get an explanation of the code in the examples read the text in the website OpenGLBook.com.Note that these examples only requires OpenGL 3.3 because of the GLSL code in the shaders, which uses commands belonging to GLSL version 3.30. The OpenGL code only requires OpenGL 2.1. If your video card supports OpenGL 3.1 or 3.2, and you have upgraded to the latest drivers and software, which can include GLSL 3.30, there is a good chance to be able to run the examples. I can run the examples on my laptop supporting OpenGL 3.1.Chapter 4 is about implementing a model loader for Wavefront (OBJ) 3D models4.0 View 3D models (New 2014-05-04)Added a few pictures that shows how the model Viewers works.You can use ExLauncher or run the scripts in SamplesModelsModel Viewer to start the Viewers:Click the Models menu to choose a group of examples:If you click the Small item you'll get a list of small model examples:When you start the Viewers, the window is bigger, and most of the models will fit in the window below the list.Click Next or Prev to view the next or previous model. Click Close to close the list. To use the shortcut keys to rotate, move, zoom or reset a model, the list must be closed.4.1 3D models (New 2013-08-03)When you need a 3D model in your OpenGL project you probably just want to find the model on the internet and load it into your project with some kind of model loading function.There are many different types of 3D models and an equal number of file formats: 3D Studio (3ds), Collada (dae), Stanford (ply) and Wavefront (obj) to name a few. And there are a lot of software packages to edit these 3D models such as Blender.The OpenGL 2.1 light examples (SamplesOpenGL 2.11 WikiBooksLights) are based on two small Wavefront (OBJ) 3D models: monkey.obj (or suzanne.obj) and two-sided.obj. Lights-01.au3 contains a very minimalistic OBJ-loader.It should be possible to create a loader for Wavefront (OBJ) 3D models with a little more functionality.4.2 Wavefront (OBJ) loader (Update 2013-09-21)A Wavefront 3D model (Wavefront .obj file) consists usually of two files: An OBJ-file (Object files) which contains vertices, texture coordinates, normal vectors and face triangles to describe the geometry of the model. And a MTL-file (Material files) with material definitions to describe the look of the model. Material definitions are parameters for the OpenGL glMaterial command to describe the light reflectivities of the surface of the model, and definitions of texture maps to put on the surface of the model.(First part of the section is unchanged since 2013-08-03)This is an example of a very simple smiley model:smiley.obj smiley.mtl ---------- ---------- mtllib smiley.mtl newmtl smiley Ka 0.000000 0.000000 0.000000 v -75 75 -50 Kd 1.000000 1.000000 1.000000 v 75 75 -50 Ks 0.000000 0.000000 0.000000 v -75 -75 -50 Ns 10.000000 v 75 -75 -50 Ni 1.000000 d 1.000000 vt 0 0 illum 2 vt 0 1 map_Kd smiley.png vt 1 1 vt 1 0 usemtl smiley f 4/3 3/2 1/1 f 2/4 4/3 1/1You can find the example in ModelsSamples.smiley.objEach line in the file starts with a token.mtllib defines the name of the MTL-filev means vertex coordinates: x, y, zvt is texture coordinates: u, vusemtl is a material definition, the usemtl name (smiley) should match a newmtl section name in the MTL-filef is a face triangle definition, triangle because each line contains 3 sets of vertex/texture indicesThe vertex/texture indices in the face triangle definitions are simply the numbers of the lines with vertex coordinates and texture coordinates. f 4/3 means the fourth line with vertex coordinates (v 75 -75 -50) and the third line with texture coordinates (vt 1 1).The whole line f 4/3 3/2 1/1 defines a triangle:vertex coordinates: 75 -75 -50, -75 -75 -50, -75 75 -50 texture coordinates: 1 1, 0 1, 0 0smiley.mtlnewmtl defines a section in the MTL-fileKa, Kd and Ks defines the reflectivity of ambient, diffuse and specular lightNs is the shininess (the brightness of the specular light)Ni is optical density or index of refraction (not implemented in this version)d defines the transparency of the material (not implemented in this version)illum is a specific number of a predefined set of illumination models (not implemented in this version)map_Ka, map_Kd, map_Ks are the ambient, diffuse and specular texture mapsKa, Kd, Ks and Ns are parameters for the OpenGL glMaterial command.The connections between the OBJ- and the MTL-file are the usemtl <name> and newmtl <name> lines. usemtl <name> determines which material definitions to be used for the following group of face triangles. These definitions are valid until the next usemtl <name> line.Model loading functions (Update 2013-09-21)The model loading functions are located in oglLoadModels.au3, oglLoadModels2.au3 and oglLoadModels3.au3 in oglIncludes.The main functions are:; Four model loading functions. They all use the same parameters: ; LoadObjModel, LoadObjModelBins, LoadObjQuads, LoadObjQuadsBins ; LoadObjModel( ByRef $aModel, $bOpenGL21 = True, $bNormals = 0, $bReload = False ) ; $bOpenGL21 is used to handle the OpenGL version ; Set $bOpenGL21 = True to use the model for OpenGL version 2.1 or higher ; Set $bOpenGL21 = False to use the model for version 2.0 or lower ; $bNormals is used to handle normal vectors. Values: 0, 1, -1 ; $bNormals = 0/1 is for models which does not contain any normal vectors ; Set $bNormals = 0 to calculate normal vectors (no average) ; Set $bNormals = 1 to calculate average normal vectors ; $bNormals = -1 is for models which does contain normal vectors ; Set $bNormals = -1 to exclude normal vectors when they are not needed ; $bReload is used when a model is reloaded in the viewers because of a change in settings ; $bReload is set to True to prevent an update of the progress info section in the inifile ; We don't want to update the progress info section just because of a reload in the viewers ; $bReload should always be set to False; it should only be set to True in main loop in viewers ; (If settings are saved the inifile is updated when LoadObjModel is called from CreateResources) ; ReadMaterials( $sObjPath, $sMaterialFile, ByRef $aMaterialInfo ) ; LoadMaterials( ByRef $aModel, ByRef $aMaterialData ) ; LoadTextures( ByRef $aModel, ByRef $aMaterialData ) ; Other functions: ; CheckModelFile( $sObjModel, ByRef $aModel ) ; GetModelSettings( ByRef $aModel, $bOpenGL21 = True ) ; SetModelSettings( $sObjModel, $bOpenGL21 = True )LoadObjModelLoadObjModel should be called with three parameters: $aModel is an array with informations to manage the model (see top of oglLoadModels.au3 for details), $bOpenGL21 is a flag to decide whether to generate data for OpenGL 1.1 (2.0 or lower) or OpenGL 2.1 (2.1 or higher). $bNormals is used to handle normal vectors.The fourth parameter, $bReload, should only be set to True in the viewers. In all other cases the default value False should be used. This means that there is no need to specify this parameter.LoadObjModel parses the OBJ-file, reads the MTL-file into an array, extracts vertices (v), texture coordinates (vt), normal vectors (vn) and face polygons (f).Vertices, texture coordinates and normal vectors are stored in three temporary arrays. When face lines are processed data are copied to permanent arrays.To handle triangles, quads and higher order polygons and to handle positive and negative references is a matter of how this copying is done.usemtl lines in the OBJ-file splits a model into smaller groups or objects with specific material definitions. Because the same usemtl lines can occur more times in a model, you can get more objects with the same material. To avoid too many different objects which slows down the OpenGL drawing cycle, the objects are sorted by material and objects with the same material are put together into one large object.If the OBJ-file consists only of vertex coordinates but no texture coordinates and no normal vectors, the normal vectors will be calculated by LoadObjModel (without a texture you need normal vectors to make it a 3D model).LoadObjModel also normalizes the model. That means places the center of the model in the origin of the coordinate system and scales coordinates to [-1,+1].For OpenGL 2.0 or lower data are stored in conventional RAM. For OpenGL 2.1 or higher data are uploaded directly to video RAM with VBO objects.LoadObjModelBinsLoadObjModelBins loads the model from binary files. The binary files are created with the viewers. See next section.The function reads information in the inifile to calculate which files to be loaded. It checks if the files exists, it reads the MTL-file, and then the vertices, texture coordinates, normal vectors and face polygons are loaded.This is the code to load the vertices:; Vertices ConsoleWrite( "Loading vertex coordinates from file: " & $sObjFile & $sVFile & @CRLF ) $hFile = FileOpen( $sObjModel & $sVFile, 16 ) ; 16 = binary mode $sBinData = FileRead( $hFile ) $iBytes = @extended FileClose( $hFile ) $tFloats = DllStructCreate( "float[" & $iBytes/4 & "]" ) $pFloats = DllStructGetPtr( $tFloats ) $tStruct = DllStructCreate( "byte[" & $iBytes & "]", $pFloats ) DllStructSetData( $tStruct, 1, $sBinData ) If $bOpenGL21 Then ConsoleWrite( "Uploading vertex coordinates to video RAM for OpenGL 2.1 (2.1 or higher)" & @CRLF ) glGenBuffers( 1, $iVbo ) glBindBuffer( $GL_ARRAY_BUFFER, $iVbo ) glBufferData( $GL_ARRAY_BUFFER, $GL_FLOAT, $iBytes, $pFloats, $GL_STATIC_DRAW ) $aModel[0] = $iVbo Else ConsoleWrite( "Storing vertex coordinates in conventional RAM for OpenGL 1.1 (2.0 or lower)" & @CRLF ) $aBuf[0] = $tFloats $aBuf[1] = $pFloats glEnableClientState( $GL_VERTEX_ARRAY ) glVertexPointer( 3, $GL_FLOAT, 0, $aBuf[1] ) $aModel[0] = $aBuf EndIfThis is very fast code. Even for files with a size of several megabytes. This means that if a model is loaded from binary files, it loads instantly.LoadObjQuads and LoadObjQuadsBinsLoadObjModel and LoadObjModelBins generates triangles and the draw mode in the commands glDrawArrays or glDrawElements must be set to $GL_TRIANGLES.If the model is a pure quad mesh it can be rendered with quads instead of triangles. In this case the functions LoadObjQuads and LoadObjQuadsBins should be used instead of LoadObjModel and LoadObjModelBins. And the draw mode must be set to $GL_QUADS.Other loading functionsReadMaterials reads a material file (MTL-file) for a model. The function is used to read materials when models are loaded as binary files. The function can also be used to change material files dynamically. $sObjPath is the path to the folder where the model and the material files are located. $sMaterialFile is the name of the MTL-file (without the path). $aMaterialInfo is an array to store the material information.LoadMaterials loads material information for a model. This corresponds to the information that can be set with the glMaterial command. $aMaterialData is an array to store information about materials and textures.LoadTextures creates textures and loads texture maps (smiley.png in the example above). This is done by calling LoadTextureImage (section 1.3).Other functionsCheckModelFile checks the format (OBJ) and the existance of a model file. It stores the full path to the OBJ-file without the .obj suffix in $aModel[11].GetModelSettings reads model settings in an inifile. The inifile must have the same name as the model and must be located in the same folder.SetModelSettings stores model settings in the inifile.4.3 Wavefront (OBJ) viewer (Update 2013-09-21)SamplesModelsModel Viewer contains two viewers for Wavefront (OBJ) 3D models. Model Viewer (OBJ) 1.1.au3 is an OpenGL 1.1 version (2.0 or lower) and Model Viewer (OBJ) 2.1.au3 is a 2.1 version (2.1 or higher). Model Viewer (OBJ).au3 calls the proper script depending on your OpenGL version. The latter can be opened through the Tools menu in ExLauncher.au3.Menu system (Update 2013-09-21)In the File menu you can Open a model and Reload the current model. Binaries contains two submenus to Save and Del binary files for the current model.The Save menu is used to save a model as binary files. Four binaries are generated for vertices, texture coordinates, normal vectors and face polygons. This is the code to generate the binary file to store vertices:If $bOpenGL21 Then $iVbo = $aModel[0] glBindBuffer( $GL_ARRAY_BUFFER, $iVbo ) glGetBufferParameteriv( $GL_ARRAY_BUFFER, $GL_BUFFER_SIZE, $iSize ) glGetBufferSubData( $GL_ARRAY_BUFFER, $GL_FLOAT, 0, $iSize, $tFloats ) $pStruct = DllStructGetPtr( $tFloats ) $tStruct = DllStructCreate( "byte[" & $iSize & "]", $pStruct ) Else $aBuffer = $aModel[0] $tStruct = DllStructCreate( "byte[" & DllStructGetSize( $aBuffer[0] ) & "]", $aBuffer[1] ) EndIf $sBinData = BinaryToString( DllStructGetData( $tStruct, 1 ) ) $hFile = FileOpen( $sObjModel & $sFile, 18 ) ; 18 = write + binary mode FileWrite( $hFile, $sBinData ) FileClose( $hFile )The binary files are saved in the same folder as the model. The name of a binary file is the name of the model plus a few extra characters and a BIN-extension.Besides the geometry data some additional data have to be saved. When a model is loaded from the OBJ-file a lot of data is extracted. E.g. material informations and informations about the objects as the model is build of. These additional data are stored in the inifile in a section named LoadBinFiles.When a quad mesh is saved a 4-number is added to the file names and the section name.(Rest of the section is unchanged since 2013-08-24)The Models menu creates lists of example models.The Materials item is new. With this menu you can read and load a material file (MTL-file) dynamically without the need to reload the entire model.By default the Materials menu is disabled (dimmed). It can be enabled in two ways:1) If a text file exists in the model folder with the name <model>-MtlFiles.txt and contains the names of the material files. An example is tree2.obj in SamplesBlender. In this folder exists a file with the name tree2-MtlFiles.txt. It contains a list of MTL-files which can be applied to the model. The names of the MTL-files will be added to the Materials menu as submenus. If a folder contains two or more models then <model>-MtlFiles.txt must be used to specify different material files for one or more of the models.2) If a folder only contains one model and two or more MTL-files, it's assumed that all MTL-files in the folder can be applied to this model. Then the list of MTL-files is generated with _RecFileListToArray (by Melba23).Only a few models are supplied with more than one material file. In the list of example models in section 4.4 a comment is added to the models with two or more material files.The View menu is new. It contains 2/3 items:Wireframe to show a wireframe drawing of the modelNormal vectors to draw normal vectors (only the OpenGL 1.1 version)Transformations to print the transformations of a modelNormal vectors can only be drawn for sample models (ModelsSamples). If a model contains more than 3000 normal vectors you must enable a menu item (View | Max vectors | No limit) to specify that you want to draw all these vectors. A large number of vectors has an impact on the performance.With the Transformations menu you can apply transformations to the model in the viewer and then print the transformations with _ArrayDisplay. The transformations for the models in the examples (section 4.6) are calculated in this way.In the Options menu you can set and save settings for a model.Settings are saved in an inifile in the same folder and with the same name as the model (the OBJ-file). Most of the examples are provided with an inifile with settings to form a good opening image of the model when it's loaded in the viewer.The menu is expanded with a Normal vectors item to add settings for normal vectors.If a model only contains vertices, but no texture coordinates and no normal vectors, the normal vectors are calculated automatically by the loader. The normal vectors can be calculated in two ways:Calculate: One normal vector per triangle (default)Average: One average normal vector per vertexThe first point means that if a vertex is common to more triangles, this vertex will be assigned several (different) normal vectors.In the second point only one normal vector will be calculated per vertex. This is a normal vector which is an average of the normal vectors of the adjacent triangles (in a mathematical sense this vector is not a normal vector, because it's not normal to the surface).For some models, which are provided with textures, the normal vectors may not be necessary (when you do not need lights). For these models you can set an option (Options | Normal vectors | None) to prevent loading normal vectors.If you can avoid normal vectors the loading function can be 20 - 30% faster. More important is that you will not waste memory and processor time to handle normal vectors when they are not used. If you watch the loading process in Scite console with and without normal vectors you'll see the difference.With Save transforms you can save the rotations, translations and scalings that are applied to the model (the transformations you can do with the keyboard shortcuts).(Rest of the section is unchanged since 2013-08-03)1.1 and 2.1 versionsA significant difference between the versions is how data are stored in memory. In version 1.1 vertex coordinates, texture coordinates, normal vectors and face triangles are stored in conventional RAM. In version 2.1 data are uploaded directly to video RAM (with VBO objects). Especially for larger models this gives a much better performance in version 2.1.Another major difference is the way light and surface reflectivities are handled. In version 1.1 these features are handled with the commands glEnable/glDisable light and glMaterial. In version 2.1 light is also handled through shaders. That's the reason why some models looks different under 1.1 and 2.1. There are two shaders to handle light: The Blinn-Phong shaders (default shaders) and the Perpixel-Light shaders. The Perpixel-Light shaders are used for models that only contains vertex coordinates (no texture coordinates and no normal vectors, in this case normal vectors are calculated by the loader).Disable light in version 1.1: Uncheck the Light item.Disable light in version 2.1: Set the shaders to Texture-Coords.CodeCode in the viewers is structured in this way:expandcollapse popupOpt( "GUIOnEventMode", 1 ) Global $sObjModel = "Small\Art\Greek vase\greek_vase.obj" MainFunc() While 1 If $sObjModel <> $sNewModel Then CreateResources( $sNewModel, $aNewModel ) EndIf If $bMenuCmd Then ; Menu command EndIf If $bResize Then ; Resize window EndIf ; OpenGL drawing cycle DisplayFunction() Sleep(10) WEnd Func MainFunc() If Not InitGUIwindow() Then CloseProgram() If Not InitOpenGLwindow() Then CloseProgram() If Not CheckOpenGLversion( 2, 1 ) Then CloseProgram() If Not CreateResources( $sObjModel, $aModel ) Then CloseProgram() EndFunc Func InitGUIwindow() EndFunc Func InitOpenGLwindow() EndFunc Func CreateResources( $sObjModel, ByRef $aModel ) ; Get model settings from inifile GetModelSettings( $sObjModel, $aModel, $bOpenGL21 ) ; Load model If Not LoadObjModel( $sObjModel, $aModel, $bOpenGL21 ) Then Return 0 ; Load materials LoadMaterials( $aModel, $aMaterialData ) ; Load texture maps LoadTextures( $sObjModel, $aModel, $aMaterialData ) EndFunc Func DrawModel( ByRef $aModel ) EndFunc Func DisplayFunction() DrawModel( $aModel ) EndFuncNote that the model is drawn with the DrawModel function.4.4 Example models (Update 2013-09-21)The Models folder at the top level contains the example models. The SamplesModels folder at the top level contains the viewers and the au3-scripts to run the examples. Example models are split into two groups: Samples and models. Models are further divided into three groups: Small, medium and large models:SamplesBlenderThe SamplesBlender folder contains models created in Blender. Among other some predefined models (Blender menu: Add | Mesh). See section 4.7 for more information about Blender.Samples\Blender\cone.obj Samples\Blender\cube.obj Samples\Blender\cylinder.obj ; One normal vector per triangle, an angular cylinder Samples\Blender\cylinder2.obj ; One average normal vector per vertex, a smooth cylinder Samples\Blender\monkey.obj ; = suzanne.obj Samples\Blender\sphereIco.obj Samples\Blender\sphereUV.obj Samples\Blender\torus.obj Samples\Blender\tree.obj ; An angular tree Samples\Blender\tree2.obj ; A smooth tree, 5 MTL-filesSamplesSamples\box1 (quads).obj ; Quad mesh Samples\box2.obj ; Colored cube with colors defined in MTL-file Samples\capsule.obj ; A larger example: http://paulbourke.net/dataformats/obj/minobj.html Samples\cube.obj ; http://www.opengl-tutorial.org/beginners-tutorials/tutorial-7-model-loading/ Samples\cylinder.obj Samples\PiggyBank (quads).obj ; Quad mesh, a larger example Samples\PiggyBank.obj ; A larger example Samples\rocket.obj Samples\room.obj ; Used in a Blender video tutorial, see section 4.7 Samples\smiley.obj ; This is the example mentioned in section 4.2 Samples\spaceship.obj ; Normal vectors calculated by the loader Samples\spaceship2.obj ; Normal vectors created in Blender Samples\suzanne.obj ; = monkey.obj Samples\triangle.obj Samples\two-sided.objSome of the models below are copied and downloaded from https://lua-files.googlecode.com/files/lua-files-media-latest.zip and free 3D models. If necessary, the models are converted to OBJ triangle meshes with Blender or AssimpView (section 4.7). In SamplesModelsModel Viewer you find text files with Scite console output lists.Small modelsSmall\Aircrafts\F-16 Fighting Falcon\f-16.obj Small\Aircrafts\Mitsubishi A6M Zero\A6M_ZERO (no propeller).obj ; 4 MTL-files and 4 texture images Small\Aircrafts\Mitsubishi A6M Zero\A6M_ZERO.obj ; 4 MTL-files and 4 texture images Small\Art\Greek vase\greek_vase.obj Small\Cars\Lancer\Lancer.obj Small\Cars\Porsche\porsche.obj Small\Clemson\al.obj ; The Clemson models are copied from a computer graphics course at Clemson Small\Clemson\castle.obj ; University, South Carolina: http://andrewd.ces.clemson.edu/courses/mobj/data/ Small\Clemson\couch.obj Small\Clemson\cow.obj Small\Clemson\dolphins.obj Small\Clemson\dragon.obj Small\Clemson\eagle.obj Small\Clemson\galleon.obj Small\Clemson\head_chord.obj Small\Clemson\ncc1701b.obj Small\Clemson\pawn.obj Small\Clemson\pig.obj Small\Clemson\rose+vase.obj Small\Clemson\shark.obj Small\Clemson\soccerball.obj Small\Clemson\teapot.obj Small\Clemson\venus.obj Small\Clemson\womanhead.obj Small\Clemson\world_curved.obj Small\Figures\Sonic\Sonic.obj Small\Plants\Fruits\Apple\apple.obj Small\Plants\Fruits\Banana\banana.obj Small\Spaceships\Juno\Juno.obj ; http://www.nasa.gov/multimedia/3d_resources/assets/eoss-juno.html Small\Weapons\Raygun\raygun_mark2.obj ; 2 MTL-filesMedium modelsMedium\Aircrafts\Airbus A380\A380.obj Medium\Animals\Elephant\elephant.obj Medium\Art\Dragon\dragon1.obj ; 4 MTL-files Medium\Plants\Bushes\Bush 01\Bush1.obj Medium\Plants\Trees\Tree 01\tree.obj ; 5 MTL-files and 5 texture images Medium\Weapons\AK103\ak103.objLarge modelsLarge\Buildings\Leaning Tower of Pisa\pisa (original, negative references).obj Large\Buildings\Leaning Tower of Pisa\pisa (quads and triangles).obj Large\Buildings\Leaning Tower of Pisa\pisa (triangles).obj Large\Spaceships\Apollo Lunar Module\lunarlandernofoil_carbajal.obj ; http://www.nasa.gov/multimedia/3d_resources/assets/lunarlandernofoil_c.html4.5 Large models (Update 2013-09-21)The optimizations provided in this update and the 2013-08-24 update has largely eliminated the problems of large models.There are two large models among the examples: Leaning Tower of Pisa and Apollo Lunar Module.2013-09-21: The ability to load models as binary files has eliminated the problems of long loading times. Sorting objects by material has minimized the problems of poor OpenGL performance.2013-08-24: The ability to exclude unnecessary data (texture coordinates if there is no texture image, normal vectors if they are not needed) has decreased loading times and increased OpenGL performance.4.6 Using the models (Update 2013-09-21)SamplesModelsOpenGL 1.1 and SamplesModelsOpenGL 2.1 contains some small examples which shows how to use the models.The easiest way to use the models is to copy the code in the viewers and delete the unnecessary code. If there are no lights and no glMaterial commands, delete that part of the code. If there are no textures, delete the code for textures.This is a list of the examples:Aircrafts1.au3 ; Only textures Aircrafts2.au3 ; With a picture of the sky and clouds as background Aircrafts3.au3 ; 3 instances with 3 material files and 3 textures Dragons.au3 ; 3 instances with 3 material files, no textures Small forest 1.au3 ; Only color parameters for the glMaterial command, no textures Small forest 2.au3 ; 3 instances with 3 material files Some trees.au3 ; 40 instances of a tree Tree demo 1.au3 Tree demo 2.au3 ; Material file and texture can be changed dynamically by clicking radio buttonsBinary files (Update 2013-09-21)Models in examples are loaded from binary files.(Rest of the section is unchanged since 2013-08-24)Multiple instances (Update 2013-08-24)The issue of using multiple instances of a model does not have much to do with the model loading functions. It's a matter of finding a way to handle multiple instances. It should at least be possible to rotate, move and scale an instance independently of the other instances. It should also be possible to use a specific material file for an instance.The transformations of a model is stored in $aTransforms in the 1.1 version of the viewer and in $mModelMatrix in the 2.1 version. $aTransforms and $mModelMatrix are arrays. The material data is stored in $aMaterialData. Also an array. The matter of using multiple instances seems to be a matter of using multiple instances of these arrays.This is easily done by expanding $aModel with three rows:$aModel[14] = $iInstances ; Number of instances $aModel[15] = $aMaterialData[] ; An a array of material data arrays, one material data array per instance $aModel[16] = $aModelMatrices[] ; OpenGL 2.1 or higher: An array of model matrices, one $mModelMatrix per instance $aModel[16] = $aTransforms[] ; OpenGL 2.0 or lower: An array of transformation arrays, one array per instanceWe also need a function to read the different material files, the MTL-files. But this function, ReadMaterials, was already implemented in the first version of the loader.(Rest of the section is unchanged since 2013-08-03)Code structureCode in the examples is structured in the usual way:expandcollapse popupMainFunc() While 1 If $bResize Then glViewport( 0, 0, $iWidth, $iHeight ) InitializeView() $bResize = False EndIf If $bClose Then CloseProgram() EndIf DisplayFunction() Sleep(10) WEnd Func MainFunc() If Not InitGUIwindow() Then CloseProgram() If Not InitOpenGLwindow() Then CloseProgram() ;If Not CheckOpenGLversion( 2, 1 ) Then CloseProgram() If Not CreateResources() Then CloseProgram() EndFunc Func InitGUIwindow() EndFunc Func InitOpenGLwindow() EndFunc Func CreateResources() EndFunc Func DrawModel() EndFunc Func DisplayFunction() DrawModel() EndFuncNote that the model is drawn with the DrawModel function.Aircrafts1.au3This is an example with the Mitsubishi A6M Zero aircraft model. Aircraft.txt contains the Scite console output from LoadObjModel. In this example only the textures are used. No light and no glMaterial commands. Aircraft.txt shows that there are two objects in the model and two textures. This reduces CreateResources, DrawModel and DisplayFunction to the following (the other functions are not interesting in this context): expandcollapse popupFunc CreateResources() If Not LoadObjModel( $sObjModel, $aModel, False ) Then Return 0 Local $iObjects = $aModel[11] Redim $aMaterialData[$iObjects][9] LoadTextures( $sObjModel, $aModel, $aMaterialData ) Return 1 EndFunc Func DrawModel( ByRef $aModel ) Local $aVertCnts = $aModel[4] ; Draw aircraft glBindTexture( $GL_TEXTURE_2D, $aMaterialData[0][7] ) glDrawArrays( $GL_TRIANGLES, 0, $aVertCnts[0] ) ; Draw propeller glBindTexture( $GL_TEXTURE_2D, $aMaterialData[1][7] ) glDrawArrays( $GL_TRIANGLES, $aVertCnts[0], $aVertCnts[1] ) EndFunc Func DisplayFunction() glClear( $GL_COLOR_BUFFER_BIT + $GL_DEPTH_BUFFER_BIT ) glPushMatrix() glRotatef( 30, 1.0, 0.0, 0.0 ) glRotatef( 45, 0.0, 1.0, 0.0 ) glScalef( 0.75, 0.75, 0.75 ) ; First aircraft glTranslatef( -0.75, 0, 0 ) DrawModel( $aModel ) ; Second aircraft glTranslatef( +1.25, 0, 0 ) DrawModel( $aModel ) ; Third aircraft glTranslatef( +1.25, 0, 0 ) DrawModel( $aModel ) glPopMatrix() SwapBuffers( $hDC ) EndFunc4.7 Software (Update 2013-08-24)Blender is a program to edit 3D models. AssimpView is a model viewer. Both of these programs are able to export a model as a Wavefront (OBJ) triangle mesh.Blender (2013-08-03)If you have tried to make even a simple figure or model in OpenGL that are not directly supported by the built-in commands you know how difficult it can be. It can be tricky to generate the correct coordinates. For example it should be relatively easy to make a model of a tree composed of a brown cylinder as the tree trunk and a green cone as the treetop. But it's not that easy.It appears to be much easier to create the model with a model editing program that is designed for the purpose. And then export the model as a file that can be imported in OpenGL. Blender is such a program.Blender is a free program, but a professional program. It may seem difficult to get started. The easiest and fastest way to get started is to watch some video tutorials.Blender can export a model as an OBJ-file. The OBJ-file can be imported into OpenGL with this OBJ-loader. The example models located in ModelsSamplesBlender are all created with Blender and exported as OBJ-files. Here you also find the simple model of a tree.To export a model in Blender you should apply these settings besides the default settings:Include NormalsTriangulate FacesVideo tutorial (Update 2013-08-24)In this collection of tutorials for OpenGL 3.3 you can find a video tutorial for Blender in tutorial 15: Lightmaps. This example explains how to build a simple scene in Blender. The model in ModelsSamplesroom.obj is a model of this scene.(Tutorial 7 implements an OBJ-loader. The tutorial contains an example with a cube. You can find this cube in ModelsSamplescube.obj.)AssimpView (2013-08-03)AssimpView can open several 3D formats (many more formats than Blender) and it can export a model in the OBJ-format. When a model is exported as an OBJ-model it's always exported as a triangle mesh. And this is exactly the format that is supported by this OBJ-loader. The medium model PlantsTreesTree 01tree.obj is downloaded from http://tf3dm.com/ as a 3DS-model, opened with AssimpView and exported as an OBJ-model. Although AssimpView is a good program, a few models can be exported with a bad result. If the original model can be imported into Blender, Blender will often give a better result.4.8 Next version (Update 2013-09-21)Some issues should be handled in the next version:This version of the loader only handles triangles, quads and higher order polygons. The next version of the loader should be able to handle points and lines.In this version of the loader the face lines must have the same format in the entire OBJ-file. A group of face lines that includes vertices and normal vectors (f v1//vn1 v2//vn2 v3//vn3 ...) can not be combined with a group of face lines that includes vertices, texture coordinates and normal vectors (f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3 ...). The next version of the loader should be able to handle models with different sets of face attributes.It's usually more efficient to draw a model with glDrawElements than glDrawArrays. In a model consisting of vertices (x,y,z), texture coordinates (u,v) and normal vectors (x,y,z) each set of data contains 8 coordinates. That's 32 bytes if the coordinates are stored as floats. If the same set of data (vertex, texture, normal) occurs more times, you have to store these data more times when you are using glDrawArrays. If you are using glDrawElements you use indices to draw the model. Then you only have to store the index more times. Because an index can be stored as a short or integer (2/4 bytes) one can save a lot of data for a large model. But to use glDrawElements you have to sort the data sets to calculate the indices and to remove redundant data. When the data sets contains 8 coordinates, this sorting can be very time consuming. And in addition, the sorting must be performed for each material in the model. Nevertheless, the possibility to use glDrawElements should be investigated.Resolved issues2013-09-21: Quad meshes and higher order polygon meshes are supported. This includes a mixture of different polygons. Pure quad meshes can be rendered with quads (instead of triangles).2013-09-21: Negative references in face definitions are supported.2013-09-21: The objects which a model is built of, are sorted by material. This can provide a huge performance improvement for models where the same material is used several times.2013-09-21: 3D models can be saved as binary files. This means that the models loads instantly.2013-08-24: Multiple instances of a model are handled. The MTL-file can be changed dynamically for different instances without the need to reload the entire model. In this way you can create for example an entire forest from the model of a single tree. If you rotates the individual trees a little bit relative to each other, they look like different trees. Using various MTL-files, you can create trees with different colored tree trunks and leaves.4.9 Summary (Update 2013-09-21)This is a summary of the main features and limitations for the Wavefront (OBJ) 3D model loader:First version of the loader was added in the update of 2013-08-03. It has been updated on 2013-08-24 and 2013-09-21.Files and foldersoglLoadModels.au3, oglLoadModels2.au3 and oglLoadModels3.au3 in oglIncludes. Main functions (section 4.2):CheckModelFile, checks a modelLoadObjModel, loads a modelLoadObjModelBins, loads a model from binary files (2013-09-21)LoadObjQuads, loads a model as a quad mesh (2013-09-21)LoadObjQuadsBins, loads a quad mesh from binary files (2013-09-21)ReadMaterials, reads a material file (MTL-file)LoadMaterials, loads parameters for the glMaterial commandLoadTextures, loads texture mapsGetModelSettings, reads model settingsSetModelSettings, writes model settingsSamplesModelsModel Viewer contains two model viewers (4.3)Models is a folder with example models (4.4)SamplesModelsOpenGL 1.1 contains scripts which shows how to use the models (4.6)SamplesModelsOpenGL 2.1 contains the same scripts with code adapted to OpenGL 2.1Main features of the model lader (4.2)Loads a Wavefront OBJ-model and possibly an associated MTL-file.Loading the OBJ-model:Handles vertex coordinates, texture coordinates, normal vectors and face polygonsHandles triangles, quads and higher order polygon meshes and a mixture of these (2013-09-21)A pure quad mesh can be stored and rendered as quads (instead of triangles) (2013-09-21)Negative indices/references in face definitions are supported (2013-09-21)If no valid texture images exists, texture coordinates are not loaded. This means that memory and processor time will not be wasted on data which are not used. (2013-08-24)If normal vectors are not needed, they can be excluded. This means that memory and processor time will not be wasted on data which are not used. (2013-08-24)The objects which a model is built of, are sorted by material. This can provide a huge performance improvement for models where the same material is used several times. (2013-09-21)If the model only contains vertices, then normal vectors are calculated automaticallyNormal vectors can be calculated in two ways (2013-08-24):One normal vector per triangle (default, this means more than one normal vector per vertex)One average normal vector per vertex (an average of the vectors of the adjacent triangles)The model is automatically normalized (center in (0,0,0), coordinates in range [-1,+1])A model can be loaded from binary files. This means that the model loads instantly. (2013-09-21)For OpenGL 1.1 (2.0 or lower) data is uploaded to conventional RAM with the commandsglVertexPointer, glTexCoordPointer and glNormalPointerFor OpenGL 2.1 (2.1 or higher) data is uploaded to video RAM with VBO-objectsModel loading can be cancelled through a Cancel button in the progress window (2013-08-24)The model can be drawn with the commands glDrawArrays or glDrawElementsLoading the MTL-file:Parameters for the glMaterial command: Ka, Kd, Ks, NsTexture maps: map_Ka, map_Kd, map_KsUsing the models (4.6, 2013-08-24):Multiple instances of a model can be handled without the need to load the model more than onceEach instance can be supplied with a transformation matrix/arrayEach instance can be supplied with a specific material fileMain features of the viewers (4.3)There are two versions of the viewers:Model Viewer (OBJ) 1.1.au3, for OpenGL 2.0 or lowerModel Viewer (OBJ) 2.1.au3, for OpenGL 2.1 or higherMain features:Menus to Open and Reload a modelA model can be saved as binary files (2013-09-21)Listbox with example models for quick accessMaterial files can be loaded dynamically (2013-08-24)A model can be drawn as a wireframe model (2013-08-24)Model transformations can be printed with _ArrayDisplay (2013-08-24)Enable/disable texture mapsCalculate normal vectors with and without average (2013-08-24)Exclude normal vectors if they are not needed (2013-08-24)A pure quad mesh can be rendered as quads (instead of triangles) (2013-09-21)Save options in an inifileSave transformationsFeatures for the 1.1 version only:Normal vectors can be drawn for sample models (2013-08-24)Light can be turned on/offFeatures for the 2.1 version only:Two set of shaders with light enabled:Blinn-Phong shadersPerpixel-Light shadersOne set of shaders with light disabled:Texture-Coords shadersLimitations of the model loaderRestrictions on the OBJ-filePoint and line definitions are not supportedOnly one set of face attributes in the entire model (all the f-lines must be in the same format)The following tokens in the MTL-file are not implementedd (transparency)illum (illumination model)Ni (optical density or index of refraction)Chapter 5 is a summary5.1 Sources for the UDFs (New 2013-06-16)The zipfile contains a number of OpenGL UDFs in the oglIncludes folder. This is a description of the sources for these UDFs:Constants and functions in oglConstants.au3 and oglFunctions.au3 belonging to OpenGL version 1.1 are created from gl.h and glu.h in Microsoft Windows SDK v7.1.Constants and functions in oglConstants.au3, wglConstants.au3 and oglFunctions.au3 belonging to OpenGL version 1.2 or higher are created from glew.h (GLEW) version 1.7.Constants and functions in extConstants.au3 and extFunctions.au3 (belonging to OpenGL extensions) are created from glew.h version 1.7.Functions in wglFunctions.au3 are created directly from the documentation of the functions.Functions in glmMaths.au3 are created from OpenGL Mathematics library (GLM, a header only C++ library) version 0.9.2.7.(The reason for using C/C++ header files to create functions is that you to some extent can automate the procedure. Function names and parameters and parameters for DllCalls can be generated automatically.)So far all functions without exceptions are testet. Only functions that are used in the examples are added to the UDFs.5.2 Updates (New 2014-05-04)The example was released 2013-05-19. This is a summary of the updates.2013-06-16Added more OpenGL 3.3 examples. Two pictures in post 7 and 8.2013-08-03Introduction of Wavefront (OBJ) 3D models. Pictures in post 13.Added a new chapter 4 to the documentation.2013-08-24This update is all about 3D models.Optimizations:Texture coordinates will not be loaded, if no valid texture image existsAdded an option to prevent loading normal vectors, if they are not neededFeatures:Multiple instances of a model can be handledMaterial files can be loaded and applied dynamicallyNew Viewer menu items:Models | Materials to load and apply material filesView | Wireframe to show a wireframe drawing of the modelView | Normal vectors to draw normal vectors. Only for sample models. Only the OpenGL 1.1 version.View | Transformations to print the transformations of a model with _ArrayDisplaySee post 14 and 15.2013-09-21A new MSAA context is set up as the default context to reduce flicker along edges. Post 16.An anisotropic texture filter is implemented to reduce texture flicker along edges. Post 16.An annoying sound alarm is removed in examples including the model viewers. Post 16.Quad meshes and higher order polygon meshes are supported. Post 17.Negative references in face definitions are supported. Post 17.Quad meshes can be rendered with quads (instead of triangles). Post 17.The objects which a model is built of, are sorted by material. This can provide a huge performance improvement for models where the same material is used several times. Post 18.3D models are saved as binary files. This means that the models loads instantly. Post 18.A lot of new models are included in the zipfile. Section 4.4.2014-05-04Code updated to AutoIt 3.3.10. The UDFs APIConstants.au3 and WinAPIEx.au3 by Yashied and RecFileListToArray.au3 by Melba23 are not used any more. These functions are included in 3.3.10. FASM assembler code to fix x64 issues is deleted. No x64 issues in 3.3.10.Zip files and downloadsIncluded UDFsFASM.au3 and MemoryDll.au3 by Ward to optimize loops. The UDFs are included in the code zip.Contents of the code zipThe zipfiles contains a number of files and folders:ExLauncher.au3 - to start the examples, run this fileImages - images used in the examples (not since 2014-05-04)Models - Wavefront (OBJ) 3D example modelsIncludes - utility functions and UDFsoglIncludes - OpenGL related constants and functionsSamples - a collection of examples and templatesTools - a few OpenGL toolszLinks - links to dokuUpdate 2014-05-04 for AutoIt 3.3.10 (code): OpenGL2-3.3.10.7zDownloads at DropboxThe images and 3D models can be downloaded from OpenGL Images and Models at Dropbox. The folder contains three 7z-files:Images.7z, 3.5 MB - the images from the first release 2013-05-19. You need these images, but if you have already installed the images, you do not need to download this package.ModelSamples.7z, 1.66 MB - sample 3D models. If you want to test the Wavefront (OBJ) 3D models and the model loading functions, you need this package.Models.7z, 39.15 MB (250 MB uncompressed) - larger models. The pictures in post 13, 14 and 16 are created from models in this package.If you don't want to test any 3D models there is no need to download and install the last two packages.Click the Download button in upper right corner to download all three packages in one big zip.Testet on XP 32 bit with a NVIDIA video card supporting OpenGL 3.3 and Win 7 64 bit with an Intel card supporting OpenGL 3.1.Use ExLauncher.au3 in top folder to run examples.To view Wavefront (OBJ) 3D models see section 4.0.AutoIt 3.3.8You can get the 2013-09-21 version for 3.3.8 here. You need the images and possibly the 3D models.Included UDFsFASM.au3 and MemoryDll.au3 by Ward to optimize loops.APIConstants.au3 and WinAPIEx.au3 by Yashied to use the Links menu in ExLauncher.au3.RecFileListToArray.au3 by Melba23 to create lists of examples in ExLauncher.au3 and model viewers.The UDFs are included in the code zip file.Update 2013-09-21 (code): OpenGL2.7zx64 issues (no x64 issues in 3.3.10)Because of an issue with double parameters in DllCall's in AutoIt 3.3.8 when scripts are run as 64 bit programs some OpenGL functions are not working. In these examples only a few functions uses double parameters. It's possible to make workarounds.A solution is to use The Embedded Flat Assembler (FASM) UDF by Ward to create assembler code to call the functions.The plan is to call the assembler functions from AutoIt with float parameters. In assembler code the floats are converted to doubles and the OpenGL functions are called with the proper parameters.This is an example with gluPerspective with 4 double parameters:; FASM assembler code ; gluPerspective( $fovy, $aspect, $zNear, $zFar ) ; Parameters: ; xmm0 : fovy ; xmm1 : aspect ; xmm2 : zNear ; xmm3 : zFar ; [rsp + 40] : Pointer to gluPerspective use64 mov rax, qword [rsp + 40] ; Pointer to gluPerspective ; Call gluPerspective sub rsp, 40 ; Stack space and alignment cvtss2sd xmm0, xmm0 ; fovy : float -> double cvtss2sd xmm1, xmm1 cvtss2sd xmm2, xmm2 cvtss2sd xmm3, xmm3 call rax ; Call gluPerspective add rsp, 40 ; Restore stack pointer retThe assembler function can be called from AutoIt in this way:Func gluPerspectiveX64( $fovy, $aspect, $zNear, $zFar ) Local Static $ptr = 0, $pCode, $tCode If $ptr = 0 Then $ptr = GetProcAddress( "glu32.dll", "gluPerspective" ) If @error Then Return SetError( 2, 0, 0 ) Local $sCode = "0x488B4424284883EC28F30F5AC0F30F5AC9F30F5AD2F30F5ADBFFD04883C428C3" $pCode = _MemVirtualAlloc( 0, 512, $MEM_COMMIT, $PAGE_EXECUTE_READWRITE ) $tCode = DllStructCreate( "byte[512]", $pCode ) DllStructSetData( $tCode, 1, $sCode ) EndIf DllCallAddress( "none", $pCode, _ "float", $fovy, "float", $aspect, "float", $zNear, "float", $zFar, "ptr", $ptr ) If @error Then Return SetError( 3, 0, 0 ) EndFuncThe binary code generated by the assembler source above is inserted in $sCode. This can be done because the code will hardly ever be changed. Alternatively the code could be read in one of the files gluPerspective-x64.bin or gluPerspective-x64.txt in folder oglIncludesFasm. But reading a file would take much longer time.The proper gluPerspective function can be called like this:If @AutoItX64 Then gluPerspectiveX64( $fovy, $aspect, $zNear, $zFar ) Else gluPerspective( $fovy, $aspect, $zNear, $zFar ) EndIfYou find the assembler source in oglIncludesFasmgluPerspective-x64.asm. Run gluPerspective-mk-x64-bin.au3 to create the binary code. gluPerspectiveX64 is in oglIncludesoglFunctions-x64.au3.Note that the FASM.au3 UDF cannot be run as a 64 bit program. But it certainly can generate 64 bit code. Edited May 7, 2014 by LarsJ Danyfirex, KaFu, Tomb and 6 others 9 Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
Andreik Posted May 19, 2013 Share Posted May 19, 2013 It is a lot of work here. Thanks for share with us! Sample files are pretty nice, especially tunnel effect. I'm still dizzy. Link to comment Share on other sites More sharing options...
LarsJ Posted May 21, 2013 Author Share Posted May 21, 2013 You are welcome. I've probably spent most time on the context stuff and the image loading functions. I already had made several versions of the examples. But they were made with freeglut and SOIL. Some of the examples are just copies. Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
GreenCan Posted May 21, 2013 Share Posted May 21, 2013 Very well done Nice examples, well written and well documented I like that Thanks for sharing GreenCan Contributions CheckUpdate - SelfUpdating script ------- Self updating script Dynamic input validation ------------------- Use a Input masks can make your life easier and Validation can be as simple MsgBox with CountDown ------------------- MsgBox with visual countdown Display Multiline text cells in ListView ---- Example of pop-up or ToolTip for multiline text items in ListView Presentation Manager ---------------------- Program to display and refresh different Border-less GUI's on a Display (large screen TV) USB Drive Tools ------------------------------ Tool to help you with your USB drive management Input Period udf ------------------------------ GUI for a period input Excel ColorPicker ---------------------------- Color pickup tool will allow you to select a color from the standard Excel color palette Excel Chart UDF ----------------------------- Collaboration project with water GetDateInString ------------------------------ Find date/time in a string using a date format notation like DD Mon YYYY hh:mm TaskListAllDetailed --------------------------- List All Scheduled Tasks Computer Info --------------------------------- A collection of information for helpdesk Shared memory Demo ----------------------- Demo: Two applications communicate with each other through means of a memory share (using Nomad function, 32bit only) Universal Date Format Conversion -------- Universal date converter from your PC local date format to any format Disable Windows DetailsPane -------------- Disable Windows Explorer Details Pane Oracle SQL Report Generator ------------- Oracle Report generator using SQL SQLite Report Generator ------------------- SQLite Report generator using SQL SQLite ListView and BLOB demo ---------- Demo: shows how binary (image) objects can be recognized natively in a database BLOB field DSN-Less Database connection demo --- Demo: ActiveX Data Objects DSN-Less Database access Animated animals ----------------------------- Fun: Moving animated objects Perforated image in GUI --------------------- Fun: Perforate your image with image objects UEZ's Perforator major update ------------- Fun: Pro version of Perforator by UEZ Visual Crop Tool (GUI) ----------------------- Easy to use Visual Image Crop tool Visual Image effect (GUI) -------------------- Visually apply effects on an image    Link to comment Share on other sites More sharing options...
Danyfirex Posted May 22, 2013 Share Posted May 22, 2013 thank you so much. Great job.  Danysys.com     AutoIt...  UDFs: VirusTotal API 2.0 UDF - libZPlay UDF - Apps: Guitar Tab Tester - VirusTotal Hash Checker Examples: Text-to-Speech ISpVoice Interface - Get installed applications - Enable/Disable Network connection  PrintHookProc - WINTRUST - Mute Microphone Level - Get Connected NetWorks - Create NetWork Connection ShortCut   Link to comment Share on other sites More sharing options...
LarsJ Posted May 23, 2013 Author Share Posted May 23, 2013 GreenCan, Thank you.Danyfirex, You are welcome. Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted June 16, 2013 Author Share Posted June 16, 2013 The first zipfile included only a few OpenGL 3.3 examples. Added a new zipfile, OpenGL33.7z, that contains some more. You can probably run the examples if your video card supports OpenGL 3.1. You can find the zip in the bottom of post #1. Section 3.3 in post #1 contains a list and a description of the examples.The text in section 1.5 and 2.4 is updated. Smaller updates to some of the other sections. Added a new section 4.0.ParthenonOne of the new examples shows how to build a world of objects with a dynamic, moving camera. A building that should look like Parthenon (a temple on the Athenian Acropolis) is created in an area with some trees.The building consists of 30 columns, each composed of 3 different parts. This provides 90 OpenGL objects. They are created in a loop. There are 98 trees which consists of 2 parts. This provides 196 objects created in a new loop. These two loops are executed for every single OpenGL drawing cycle. In order to ensure sufficiently good performance, it is necessary to optimize these loops. This is done with The Embedded Flat Assembler (FASM) UDF by Ward. Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted June 16, 2013 Author Share Posted June 16, 2013 Four of the new OpenGL 3.3 examples shows how to maneuver a spaceship or an airplane. In the first example the maneuvers are made with gimbals.This means that the maneuvers are composed of rotations about the x-, y- and z-axes. A better way is to use yaw, pitch and roll transformations. This is shown in the three other examples. Danyfirex 1 Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted July 14, 2013 Author Share Posted July 14, 2013 (edited) Tomb has pointed out an error in the implementation of glCallLists (see OpenGL GlReadPixels post #6) in oglFunctions.au3. I have reviewed all functions with array parameters and found the same error in glVertex3fv. The two functions are corrected in this version:Edit: The two functions are corrected in the update dated 2013-08-03. Edited August 4, 2013 by LarsJ Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
chesstiger Posted July 21, 2013 Share Posted July 21, 2013 LarsJ, I see you have done a lot of work. I'm here to ask you, if you want to participate in the AutoIt OpenGLCL Team. We (minx and Andy from Germany ;-) ) are currently adding OpenCL support to the most complete OpenGL UDF(s) for AutoIt ('?do=embed' frameborder='0' data-embedContent>>). OpenCL, in case you don't know, is a language similar to GLSL, but you're actually accsessing the cores of the GPU, making it possible to do an crazy amount of parallel calculations (peformance beats Inline-ASM by far). Yet we have a few examples running, but we are (or minx is) currently structuring the code. There are a few things missing in the SDK like GLSL or newer OpenGL extensions. Code, which you seem to work on. We would be glad if you join us (I'm currently using chesstigers account, because twitter login is disbaled...). Please contact me at squarecode@web.de if your interested. Link to comment Share on other sites More sharing options...
LarsJ Posted July 22, 2013 Author Share Posted July 22, 2013 Andy and minx, I'm not interested. Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
minxomat Posted July 22, 2013 Share Posted July 22, 2013 Oh ok then... I will answer every single PM, and you are free to ask anything anytime. Link to comment Share on other sites More sharing options...
LarsJ Posted August 4, 2013 Author Share Posted August 4, 2013 Added a new chapter 4 about implementing a model loader for Wavefront (OBJ) 3D models.This is a picture of one of the models. A Mitsubishi A6M Zero aircraft with and without a texture.This is a picture from a small example that shows how to use the models.And this is a picture of the provisional only large model (Apollo Lunar Module, 300.000 vertices, 35 secs to load).Added a new group of OpenGL 1.1 examples: SamplesOpenGL 1.1glCommands. See section 1.4. Tomb 1 Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted August 24, 2013 Author Share Posted August 24, 2013 Updates 2013-08-24.These updates relates to 3D models only.For a complete list of updates see section 4.9.Most sections in chapter 4 in first post are updated.Most important updates:OptimizationsTexture coordinates will not be loaded, if no valid texture image existsAdded an option to prevent loading normal vectors, if they are not neededThis means that the loading function runs faster. More important is that you will not waste memory and processor time on data which are not used.The Apollo Lunar Module large model (no valid texture images) now loads in 26.5 secs (old XP). 33.8 secs in the previous version. This is 20% faster. On a new laptop the model loads in 10 secs. See section 4.5 in first post.FeaturesMultiple instances of a model can be handledMaterial files can be loaded and applied dynamicallyViewersThe Models menu is expanded with a Materials item to load and apply material files.New View menu with 2/3 items:Wireframe to show a wireframe drawing of the modelNormal vectors to draw normal vectors. Only for sample models. Only the OpenGL 1.1 version.Transformations to print the transformations of a model with _ArrayDisplayIf you apply transformations to a model, you can print the transformations with the Transformations menu. The transformations for the models in the examples are calculated in this way.This is 3 instances of a dragon model with 3 different material files: Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted August 24, 2013 Author Share Posted August 24, 2013 Normal vectorsIf a model only contains vertices, but no texture coordinates and no normal vectors, the normal vectors are calculated automatically by the loader. The normal vectors can be calculated in two ways:One normal vector per triangle (default)One average normal vector per vertexThe first point means that if a vertex is common to more triangles, this vertex will be assigned several (different) normal vectors.In the second point only one normal vector will be calculated per vertex. This is a normal vector which is an average of the normal vectors of the adjacent triangles (in a mathematical sense this vector is not a normal vector, because it's not normal to the surface).Smooth surfacesThis is SamplesBlendercylinder.obj and cylinder2.obj drawn with normal vectors:The cylinders are created in Blender.The cylinder on the left is edgy because there is an abrupt change in the normal vectors exactly on the edge between two adjacent triangles. The normal vectors determines how the light is reflected. Because the normal vectors changes abruptly on the edges, the edges looks very sharp.Smoothing is added to the cylinder on the right. This means that Blender calculates average normal vectors on the edges, and the edges looks smooth.Dark surfacesFor the spaceship (Samplesspaceship.obj) on the left the normal vectors are calculated by the loader. They are calculated just as they are with one normal vector per triangle. This means that a vertex with more adjacent triangles has more normal vectors. The light looks good, but the edges are sharp.The normal vectors in the middle are also calculated by the loader. They are calculated as average normal vectors. The surface of the spaceship is smooth, but there is a problem with the light between the cockpit and cargo hold. It's too dark. The problem is that the normal vectors in this area are pointing in the wrong direction. They are pointing into the spaceship. For such a closed surface, all normal vectors should be pointing out of the surface.On the right the spaceship is imported into Blender and smoothing is added to the model. Then the spaceship is exported as spaceship2.obj. All normal vectors are pointing out of the spaceship and the light looks good.two-sided.objtwo-sided.obj is one of the small models which is used in the OpenGL 2.1 light examples (SamplesOpenGL 2.11 WikiBooksLights). Here you easily see why the model is named two-sided. If you only are concerned about the sides, all the normal vectors are pointing in the same direction. The side without any normal vectors is dark. Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted September 21, 2013 Author Share Posted September 21, 2013 (edited) General updates 2013-09-21.MSAA rendering contextThe model to the left (large model: Leaning Tower of Pisa) is rendered with a simple context while the model to the right is rendered with a proper context supporting MSAA (multisample antialiasing). The purpose of a MSAA context is among other things to reduce flicker along edges.Not only this model but all the 3D models and all the other examples benefits from this new MSAA context. If you take a closer look at the pictures in post 7, 8 and 13, you'll see that many of the edges looks as if they are composed of a lot of small triangles. With the new context these edges looks much smoother.The blue normal vectors in the post above also looks much better. With the simple context some of the vectors looks as if they are composed of 2 - 3 different line segments. With the new context the vectors looks much more like a single straight line.Because we already know how to create a proper context it's easy to create a MSAA context. It's a matter of extending the pixel format attribute list with a few more attributes. See section 1.2 in first post for details.As you can see in section 1.2, there are two new MSAA contexts in this update. A MSAA and a MSAAbest context. The MSAAbest context is set up as a new default context if your video card supports it.A disadvantage of the MSAA context is that it can be more CPU/GPU intensive than the simple context or the default proper context. Especially in full screen windows.An easy way to switch between the MSAAbest context and the default proper context is to use ExLauncher.au3. In the Context | Select menu and the "Supported context" group you can select a Simple and Proper context.Simple will try to create a MSAAbest context and fall back to the Simple context in case of an error.Proper will create a default proper context (which does not support MSAA).Anisotropic texture filterThe problem along edges in the model to the left also exists in textures along edges. But the problem does not seem to be so prevalent in textures. Nevertheless, a solution to the problem would be to use an anisotropic filter. Such a filter can be applied through the GL_EXT_texture_filter_anisotropic extension. In this update the filter is implemented in CreateTexture in oglLoadImages.au3. See section 1.3 in first post. Because CreateTexture is a common function all 3D models and examples benefits from this update."SamplesOpenGL 1.1TexturesCubesCube Homer Simpson.au3" (rotating cube with a Homer Simpson texture) is an example where you clearly gets a better result. There is much less flicker along the edges between the texture and the oblique corner sides of the cube.Sound alarmIf you create a GUI with a label as the only control you'll hear a sound alarm if you press a key e.g. a letter.In these examples a lot of GUIs have a label as the only control. The label is used as statusbar. Because _IsPressed is used to catch key presses to rotate and move OpenGL objects this sound alarm can be very annoying.An easy workaround is to add an input control to receive the key presses. In this update an input control is added to all the examples with this problem. Edited September 22, 2013 by LarsJ Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted September 21, 2013 Author Share Posted September 21, 2013 3D model updates 2013-09-21.FunctionalityQuad meshes and higher order polygon meshes are supportedNegative references in face definitions are supportedQuad meshes can be rendered with quads (instead of triangles)Polygon meshesThe picture shows how a pentagon can be constructed from 3 triangles.The design ensures that the order of the vertices are preserved in the triangles. This means that if we have to calculate the normal vectors ourselves (because they are not supplied in the model) the normal vectors of the triangles will be pointing in the same direction as the normal vector of the pentagon.The method can easily be extended to all types of polygons. The number of triangles equals the number of edges or vertices minus two. Programmatically the method is easy to implement.A disadvantage is that it introduces redundancy. V0 (and VT0 (texture coordinates) and VN0 (normal vector)) is used in every triangle. The other points except the first and the last are used twice. See section 4.8 in first post for a possible solution.Negative referencesA new large model is added: Leaning Tower of Pisa. You can see a picture in the post above. This model uses negative references in face polygons. The face polygons consists of triangles and quads. With negative references you counts backwards from the last added vertices, texture coordinates and normal vectors. -1 is the last vertex, texture and normal. -2 the second last and so on.Render with quadsSome models (albeit not many) are pure quad meshes. With this update it's possible to render these models with quads instead of triangles. By default, all models are rendered with triangles. For pure quad meshes the Load quads item in the Options menu is enabled and you can choose to load and render the model as a quad mesh.Two of the sample models are quad meshes: box1 (quads).obj and PiggyBank (quads).obj. Use View | Wireframe to see that the models are rendered with quads: Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted September 21, 2013 Author Share Posted September 21, 2013 3D model updates 2013-09-21.OptimizationsThe objects which a model is built of, are sorted by material3D models are saved as binary filesSortingThe Apollo Lunar Module large model is composed of 74 objects. In this context an object is a group of vertices, texture coordinates, normal vectors and face polygons which uses the same material and can be drawn with one single OpenGL drawing command (glDrawArrays or glDrawElements).These 74 objects are rendered in a loop which is processed for every single OpenGL drawing cycle. Because the material changes from object to object they must be rendered in a loop so that it's possible to change material with the glMaterial command.If the same material is used multiple times it's possible to achieve a performance improvement by sorting objects by material and put objects of the same material together into one large object.For the Apollo Lunar Module 74 objects are reduced to 12 by sorting the objects. This means that the number of loops in the OpenGL drawing cycle is also reduced from 74 to 12. This is a huge performance improvement.Under OpenGL 1.1 the CPU usage is 40% on my XP with 74 objects. With 12 objects the CPU usage is 5%. Even if you rotates the model (e.g. with the W-key) the CPU usage is still only about 5%. The model is running much smoother.Not only large models can be composed of high number of objects. Two of the new small models (AircraftsF-16 Fighting Falconf-16.obj and Clemsonal.obj) are composed of 117 and 173 objects. These numbers are reduced to 3 and 35 by sorting the objects.BinariesWhen an OBJ-file is parsed the result is a pile of data (vertex and texture coordinates, normal vectors and face polygons). Data is stored in 4 structures (OpenGL 1.1) or 4 VBO-objects (OpenGL 2.1). It's easy to save the contents of these data stores directly to binary files. This can be done with a few fast commands. glGetBufferSubData can be used to extract data from VBO-objects. See section 4.3 in first post.Restoring data from binary files can also be done with a few fast commands. Section 4.2.This update contains functions to save and read models as binary files. This means that the models loads instantly.Summary of 2013-09-21 updatesA new MSAA context is set up as the default context to reduce flicker along edges. Post 16.An anisotropic texture filter is implemented to reduce texture flicker along edges. Post 16.An annoying sound alarm is removed in examples including the model viewers. Post 16.Quad meshes and higher order polygon meshes are supported. Post 17.Negative references in face definitions are supported. Post 17.Quad meshes can be rendered with quads (instead of triangles). Post 17.The objects which a model is built of, are sorted by material. This can provide a huge performance improvement for models where the same material is used several times.3D models are saved as binary files. This means that the models loads instantly.A lot of new models are included in the zipfile. Section 4.4. Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
LarsJ Posted May 6, 2014 Author Share Posted May 6, 2014 The code was not running under 3.3.10. Updated. New zips in first post. There is still a zip for 3.3.8.The UDFs APIConstants.au3 and WinAPIEx.au3 by Yashied and RecFileListToArray.au3 by Melba23 are not used any more. These functions are included in 3.3.10. FASM assembler code to fix x64 issues is deleted. No x64 issues in 3.3.10. Controls,  File Explorer,  ROT objects,  UI Automation,  Windows Message MonitorCompiled code: Accessing AutoIt variables,  DotNet.au3 UDF,  Using C# and VB codeShell menus: The Context menu,  The Favorites menu. Shell related: Control Panel,  System Image ListsGraphics related: Rubik's Cube,  OpenGL without external libraries,  Navigating in an image,  Non-rectangular selectionsListView controls: Colors and fonts,  Multi-line header,  Multi-line items,  Checkboxes and icons,  Incremental searchListView controls: Virtual ListViews,  Editing cells,  Data display functions Link to comment Share on other sites More sharing options...
ThaiNhatMinh Posted May 15, 2014 Share Posted May 15, 2014 Sorry for my bed english Can you help me how to view more image to GUI. I try but i can not to do it Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now