Click here to Skip to main content
Click here to Skip to main content

SharpGL: A C# OpenGL Class Library

By , 22 Feb 2012
 
SharpGL-Logo.jpg

SharpGL is a project that lets you use OpenGL in your Windows Forms or WPF applications with ease! With all OpenGL functions up to the latest 4.2 release, all major extensions, a powerful scene graph and project templates for Visual Studio, you have all the tools you need to create compelling 3D applications - or to port existing code to a new platform.

A picture paints a thousand words, so let's see some screenshots first!

Radial Blur - The Radial Blur Sample shows how you can create advanced lighting effects using standard OpenGL functions.

RadialBlurSample.jpg

Utah Teapot WPF Sample - Direct OpenGL Rendering in a WPF application - with no airspace or Windows Forms Host objects. The SharpGL OpenGLControl provides an OpenGL rendering surface directly in your application.

WpfTeapotSample.jpg

Texturing Sample - Speed up OpenGL development by utilising classes like the Texture class, used to load and transform image data into OpenGL textures.

TexturesSample.jpg

Hit Testing Sample - By deriving scene elements from IBoundable, you can let your own custom classes participate in hit testing.

HitTestSample.jpg

What is SharpGL?

SharpGL is a collection of class libraries that let you use OpenGL functionality in your code. Class libraries are:

SharpGL - Contains the main OpenGL object - this object wraps all OpenGL functions, enumerations and extensions.

SharpGL.SceneGraph - Contains all wrappers for OpenGL objects and Scene Elements - Lights, Materials, Textures, NURBs, Shaders and more.

SharpGL.WinForms - Contains Windows Forms Controls for your applications.

SharpGL.WPF - Contains WPF Controls for your applications.

SharpGL.Serialization - Contains classes used to load geometry and data from 3D Studio Max files, Discreet obj files and trueSpace files.

Between these libraries, SharpGL gives to a wrapper to all current OpenGL functions, all major extensions and a rich set of objects for advanced functionality. You can use SharpGL to perform 'traditional' OpenGL drawing or you can use the SceneGraph to implement more application specific tasks.

How do I use SharpGL?

It's simple! If you have a chunk of code like the below:

//  Set the line width and point size.
glLineWidth(3.0f);
glPointSize(2.0f);

Then it would be written as:

//  Get a reference to the OpenGL object.
OpenGL gl = openGLCtrl1.OpenGL;

//  Set the line width and point size.
gl.LineWidth(3.0f);
gl.PointSize(2.0f);

This is the first fundamental - any OpenGL function that begins with 'gl' or 'glu' is a member function of the SharpGL.OpenGL object, with the 'gl' or 'glu' removed.

This takes care of the most basic functions - however, there is an exception to this rule. The code below:

//  Set the color.
glColor3f(0.5f, 0.5f, 0.5f);

//  Output some vertices.
glVertex3f(2.0f, 3.0f 4.0f);
glVertex4f(2.0f, 1.0f, 10.0f, 1.0f);

Would be written as:

//  Set the color.
gl.Color3(0.5f, 0.5f, 0.5f);

//  Output some vertices.
gl.Vertex3(2.0f, 3.0f 4.0f);
gl.Vertex4(2.0f, 1.0f, 10.0f, 1.0f);

Note the absense of the 'f' at the end of the function. This is the second fundamental - SharpGL wrapper functions never have a type postfix. OpenGL functions often end in 'f' (for float), 'fv' (for float vector), 'i' (for integer) and so on. We do not need to have unique names in C# so we do not apply these postfixes to the function name. We do keep the number however - as in the case where arrays are passed in, the wrapper needs to know how many elements are to be used.

This takes care of functions that take fundamental types as parameters. For other types of functions, we have one more thing to remember. The code below:

//  Set the polygon mode.
glPolygonMode(GL_FRONT, GL_FILL);

is written as:

//  Set the polygon mode.
gl.PolygonMode(OpenGL.GL_FRONT, OpenGL.GL_FILL);

or:

//  Set the polygon mode.
gl.PolygonMode(PolygonFace.Front, PolygonMode.Fill);

This describes the final fundamental. OpenGL constants are all defined as constant members of the SharpGL.OpenGL class, and have exactly the same names.

This takes care of how 'standard' C OpenGL code would be written using SharpGL. As an aid to the programmer, many of the standard OpenGL functions have overloads that take strong types. In the snippet above (PolygonMode) we can use OpenGL constants or the PolygonFace and PolygonMode enumerations - both are perfectly valid. The first is more in line with typical C code, the second gives the developer more in the way of intellisense to aid them.

Coding with SharpGL

Coding with SharpGL is very straightforward. Some of the benefits you will notice are:

Code Hints and Intellisense

Screenshot_CodeHints.png

All core OpenGL functions are fully documented, meaning you get the information you need as you type - less looking through The Red Book and more productivity.

Enumerations for Core Functions

Screenshot_Enumerations.png

Improve readability and reduce errors by using type-safe enumerations for core functions.

Extensions and Core Support to 4.2

Screenshot_Extensions.png

All major extension functions available, deprecated functions are marked as deprecated, extensions that have made it into the standard are present both in extension form and core form.

Your first SharpGL Application

You can have a SharpGL application running in five minutes - here's how.

1. Install the SharpGL Visual Studio Extension

Download the SharpGL Visual Studio Extension and extract it. Double click on the *.vsix file - the install confirmation will be shown. Choose 'Install'.

ConfirmInstallation.png

2. Run Visual Studio and create a New Project

Run Visual Studio and choose 'New Project'. You'll see that under C# there are two new templates - SharpGL Windows Forms Application and SharpGL WPF Application. Choose your preferred platform.

NewWpfApplication.png

3. Run the Application

Hit Ctrl-F5 or press 'Run'. Your new SharpGL application runs up, showing a rotating pyramid. You have three functions by default:

OpenGLDraw - Used to do OpenGL rendering.
OpenGLInitialized - Used to perform any OpenGL initialization.
Resize - Used to create a projection transformation.

The code that comes with the template does the basic for you - and there are many sample applications provided with the source code as baselines for your own project.

WpfApp.png

Related Articles

SharpGL is big. OpenGL is big and very mature now. Rather than squeeze too much detail into this article, I will write separate articles on specific topics. If you have any suggestions or questions then please comment below.

Using SharpGL in a WPF Application - http://www.codeproject.com/KB/WPF/openglinwpf.aspx

SharpGL Documentation - http://sharpgl.codeplex.com/documentation

Keep Up To Date

Up to date information on SharpGL development is available from the CodePlex site. SharpGL is hosted on CodePlex, at http://sharpgl.codeplex.com.

I write about various interesting areas I come across when developing SharpGL on my blog at http://www.dwmkerr.com.

Feature Requests

I am looking for feature requests for SharpGL 2.1 and the roadmap! Add feature requests from the CodePlex page's 'Issues' section or via the comments below.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Dave Kerr
Software Developer
United Kingdom United Kingdom
Member
Follow my blog at www.dwmkerr.com and find out about my charity at www.childrenshomesnepal.org.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralQuite CoolprofessionalBrisingr Aerowing15 May '13 - 15:05 
Like this, I do. Good job you have done. The good work, keep it up.
 
(Star Wars on the brain, I have. See that, you likely can.)
Gryphons Are Awesome! ‮Gryphons Are Awesome!‬

GeneralRe: Quite CoolmvpDave Kerr16 May '13 - 2:27 
Thanks!

GeneralMy vote of 5memberMax Holder18 Apr '13 - 2:25 
Very nice indroduction!
GeneralRe: My vote of 5mvpDave Kerr18 Apr '13 - 2:32 
Thanks Smile | :)

BugWhat if (frameRate is 0) but (timerDrawing.Enabled is false) @OpenGLControl.SetupDrawingTimer() ?memberbitzhuwei16 Apr '13 - 16:05 
First of all, really great work!
I saw this
        private void SetupDrawingTimer()
        {
            //  First, if the framerate is less than zero, set it to zero.
            if (frameRate < 0)
                frameRate = 0;
 
            //  Now, if the framerate is zero, we're going to disable the timer.
            if (frameRate == 0 && timerDrawing.Enabled)
            {
                //  Disable the timer - at this stage we're done.
                timerDrawing.Enabled = false;
                return;
            }
 
            //  Now set the interval.
            timerDrawing.Interval = (int)(1000.0 / FrameRate);
 
            //  Finally, if the timer is not enabled, enable it now.
            if(timerDrawing.Enabled == false)
                timerDrawing.Enabled = true;
        }
So, the timerDrawing.Interval will not work properly when frameRate is 0 and timerDrawing.Enabled is false.
I think maybe we can write it like this:
            //...
            //  Now, if the framerate is zero, we're going to disable the timer.
            if (frameRate == 0)
            {
                //  Disable the timer - at this stage we're done.
                if (timerDrawing.Enabled)
                    timerDrawing.Enabled = false;
                return;
            }
            //...
Hope this help.
GeneralRe: What if (frameRate is 0) but (timerDrawing.Enabled is false) @OpenGLControl.SetupDrawingTimer() ?mvpDave Kerr16 Apr '13 - 21:25 
Hi,
 
Thanks for letting me know, I've raised a bug (https://sharpgl.codeplex.com/workitem/1083[^]) and will look into it for the next release Smile | :)

GeneralFantastic stuff thank you.membermakaveli_000020 Feb '13 - 7:33 
Thanks for the great alternative to OpenTK. I applaud the work you have put into this. I plan on using it to do a port of World Wind to C#.
 
Your templates are also a very good way to get one started. Thanks again.
GeneralRe: Fantastic stuff thank you.mvpDave Kerr20 Feb '13 - 21:37 
I'm very pleased you like the project Smile | :)

GeneralRe: Fantastic stuff thank you.memberJuan Manuel Romero Martin7 Apr '13 - 12:12 
Hi Makeveli_0000,
 
Are you porting WorldWindJava to c#? I have been working with WorldWindJava from its version 0.3. How are you going it ?
 
I have read that NASA is cleaning the WorldWind source code to put make the available.
 
Please, I would like to know if you have a website or a blog in which I can follow your work.
 
Thanks in advance.
GeneralRe: Fantastic stuff thank you.membermakaveli_00007 Apr '13 - 13:23 
Yes, I am working on a port of the World Wind SDK to C# with the goal of opening up the architecture to other graphic libraries. The project is still in its infancy which means there is nothing running yet as I am still trying to figure out the proper abstractions using SharpGL and OpenTK. Having said this, there is quite some code already written although neither currently compiling nor untested at least for the next couple of weeks. The plan is to get things running once I go through the entire drawing cycle which should hopefully be soon.
 
You can follow the progress here : https://bitbucket.org/knji/worldwindsdk[^]
Questiontext in 3d spacemembertcpmv1 Jan '13 - 10:15 
I see .DrawText and DrawText3D but I can't place text in 3D space, i.e. x=10, y=20, z=40 @ 45 degree. How can I do this?
Thanks,
AnswerRe: text in 3d spacemvpDave Kerr2 Jan '13 - 21:32 
First, you'll absolutely need to use DrawText3D - DrawText will just render normal 2D text on the framebuffer. What you should do is download the sample applications and take a look at the Text sample - it'll show you how to draw 3D text. To rotate it and position it, you'll need to transform the modelview - just as you would with any standard geometry. Let me know if that helps Smile | :)

Generaltext in 3d spacemembertcpmv3 Jan '13 - 4:58 
I did not see that project. I will go get it. Thanks.
GeneralRe: text in 3d spacemvpDave Kerr3 Jan '13 - 7:10 
You're welcome - from memory I think it is in the WPF samples folder, however, the approach works the same for WinForms.

QuestionWhen I initialize the OpenGL, why I must Translate the modelview.memberzy3327197942 Dec '12 - 15:23 
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.LoadIdentity();
gl.Translate(0f, 0f, -2f);
If I dosen't use the Translate methord, I can see nothing. And I user other source such as Tao Framework, it no need to "translate". Why?
AnswerRe: When I initialize the OpenGL, why I must Translate the modelview.mvpDave Kerr4 Dec '12 - 3:12 
I would guess that in this case the camera is at the origin, (0,0,0) so is clipping geometry you are drawing - that translation pushes into the cameras field of view.

QuestionCan't get startedmemberMWBate29 Nov '12 - 8:01 
I followed your instructions to create your first SharpGL project exactly (for a Winforms app) and pressing Ctrl-F5 appeared to do nothing. Clicking on Debug caused the following error message: "Extension function glGenFramebuffersEXT not supported".
 
I get the same error message if I try to open the SharpGL in the VS designer.
 
I am running VS2010 Professional, on Windows 7 Pro, 64-bit. Your instructions say nothing about installing the libraries, but I unpacked everything into a directory D:\SharpGL (subdirectories include Binaries, SourceCode, Samples). I created my new project at D:\SharpGL\MyApps\Sample2 and SharpGL appears to have created at least some of the libraries in their expected locations beneath the Sample2 subdirectory. Each of the three created libaries (SharpGL.DLL, SharpGLSceneGraph.dll and SharGLWinforms.dll) are slightly smaller than either the debug or release libraries extracted from your ZIP file. My new project lists no other dependencies.
 
Am I doing something stupid?
AnswerRe: Can't get started - solvedmemberMWBate3 Dec '12 - 16:48 
I found the answer to this on a forum on CodePlex - The line in GLForm.Designer.cs needs to be changed from:
 
this.openGLControl.RenderContextType = SharpGL.RenderContextType.FBO;
 
to:
 
this.openGLControl.RenderContextType = SharpGL.RenderContextType.DIBSection;
 
because the default value assumes that hardware acceleration is available.
GeneralRe: Can't get started - solvedmvpDave Kerr4 Dec '12 - 3:12 
Sorry for the late reply, glad you got the problem sorted!

QuestionProblem with Intel HD 3000 on laptopmemberandrea tosetto24 Nov '12 - 4:32 
Hello,
I've got a problem with an implementation of sharpgl on my laptop, my graphic card is the one in subject, the problem seems to be related to deep buffer. I know that there are problems with opengl and the graphic card, but the strange thing is that the previous implementation of sharpgl works correctly.
What I can do to setup sharpGL 2.0 to behave like the previous version? Or if you have any suggestion it will be appreciated.
 
Thanks!
 
Regards,
Andrea
Question2d ImagesmemberMember 778994826 Oct '12 - 8:21 
Hello,
Firstly, SharpGL looks awesome Smile | :)
 
Secondly, I have never worked with anything like this before (OpenGL, DirectX, etc) so I am by no means an expert but I am a quick learner and good listener.
 
I want to implement a small map using SharpGL but I am not sure where to start. All the tutorials and sample code I can find deal with much more complicated 3d objects and rotations.
 
I assume that my map will most likely just be a large 2d square with a loaded texture on it. If so, what would be the best way to go about zooming in and panning?
Questionwhyt the run result is always balckgroundmemberlxp211022 Oct '12 - 4:57 
I have done my sharp windows form application as you have said step by step ...
1. Install the SharpGL Visual Studio Extension
2. Run Visual Studio and create a New Project
3. Run the Application
however the result is always black background,it seems doesn't work...
i have almost spent whole nignt todeal with it,but i dont konw the reason ...please help me
Bugbug in framerate setter [modified]memberchristophe.thalet13 Oct '12 - 8:00 
Hello Dave,
 
I discovered another bug: setting the framerate doesn't work at all Frown | :-(
 
Here's why: your code reads:
        [Description("The rate at which the control should be re-drawn, in Hertz."), Category("SharpGL")]
        public int FrameRate
        {
            get { return frameRate; }
            set
            {
                frameRate = value;
                timerDrawing.Interval = 1000 / 20;
            }
        }
 
Note the hardcoded 20 at the end. It should be "frameRate" instead.
 
Additionally, IMHO the code should be extended to stop the timer if frameRate is <=0.
When changing it up again to something >0, then the timer should be re-started.
Here's the implementation I suggest:
 
        private int frameRate = 20;
        private bool constructorFinished = false; // this bool is needed to prevent the timer from starting when the Constructor code isn't finished yet

        [Description("The rate at which the control should be re-drawn, in Hertz."), Category("SharpGL"), DefaultValue(20)]
        public int FrameRate
        {
            get { return frameRate; }
            set
            {
               if(value <= 0)
               {
                  frameRate = 0;
               }
               else
               {
                  frameRate = value;
                  timerDrawing.Interval = 1000 / frameRate;
               }
               if(constructorFinished)
               {
                  timerDrawing.Enabled = frameRate>0;
               }
            }
        }
and
        public OpenGLControl()
        {
            InitializeComponent();
 
            //  Set the user draw styles.
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
 
            int f = FrameRate;
            FrameRate = 0;
            constructorFinished = true;
            FrameRate = f; // will start the timer
        }
 
Note that I've changed the constructor to no longer fiddle with the timer
implementation details. Instead, only the setter for FrameRate now does.
 
Regards,
Christophe

modified 13 Oct '12 - 14:38.

GeneralRe: bug in framerate settermvpDave Kerr13 Oct '12 - 23:27 
Hi Cristophe,
 
Thanks for this update - I've created a task in the CodePlex project:
http://sharpgl.codeplex.com/workitem/905[^]
 
This will be fixed in the next version - thanks!

Generala problemmemberxitangzi16 Jul '12 - 22:57 
when i use it in wpf,i put a openglcontrol on a usercontrol,then i put the usercontrol on a window,but it dosen't work,just a black background?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 22 Feb 2012
Article Copyright 2002 by Dave Kerr
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid