Click here to Skip to main content
Click here to Skip to main content
Articles » Multimedia » OpenGL » General » Revisions
 

SharpGL: a C# OpenGL class library

By , 12 Oct 2011
 
This is an old version of the currently published article.

Screenshot.jpg

Headline: SharpGL 2.0 Beta 1 is available to be tried out from the SharpGL CodePlex site - the latest download is here: http://sharpgl.codeplex.com/releases/view/74704 

Introduction 

Use OpenGL in your C# applications with SharpGL, it's a breeze! Just drag an OpenGLControl onto your Windows Form and handle the 'OpenGLDraw' function - now just call ordinary OpenGL functions! 

Keeping Track of SharpGL 

Before I go much further here are some useful bits of information: 

SharpGL is now hosted on CodePlex at: http://sharpgl.codeplex.com   

SharpGL is currently at version 2.0 Beta 1 - this version adds support for WPF, OpenGL 4.2 extensions and more. 

I am also writing about the various challenges of creating the new version on my blog at: 

http://www.dwmkerr.com   

Using SharpGL in WinForms Applications 

SharpGL provides you with two controls for designing forms. The OpenGLControl, which lets you do standard OpenGL drawing in a C# application, and the SceneControl, which does the same with added support for polygons/persistence/picking and more. The screenshot above shows the SceneControl in action, with the supplied 'SceneBuilder' application. The screenshot below shows some 'old fasioned' OpenGL drawing, with calls to 'glBegin' and 'glEnd' etc.

Screenshot-Small.jpg

If you want to get OpenGL in your application quickly, there's no easier way. There are eight example applications in the download that show you how to use some common features. 

Getting Started

Create a Windows Forms application, use the SharpGL DLL as a reference, and drop an OpenGLControl onto the form. Then handle the 'OpenGLDraw' event and you're ready to go!

Calls that in C++ would look like:

glBegin(GL_LINES);
    glVertex3f(1.0f, 1.0f, 1.0f); ...etc...

Will have to look like:

OpenGL gl = someForm.someOpenGLControl.OpenGL;

gl.Begin(OpenGL.LINES); 
		gl.Vertex(1, 1, 1); ...etc...

Porting over existing OpenGL code is therefore trivial. Every OpenGL and GLU library function has been imported and fully commented - no need to look through reference books for function parameters, the Code Hints will show you everything you need to see!

screenshot_codehints.jpg

The Scene Graph

The Scene Graph contains classes like 'Texture' and 'Camera' to make working with certain types of object much easier. You don't have to use them, you can use certain components or you can use the whole lot. Or you can mix and match. There is an example application that shows how to do texturing with the Scene Graph. 

Using SharpGL in WPF Applications 

The screenshot below shows SharpGL being used in a WPF application: 

MainWindow-Final.png 

There is a full article describing how to use SharpGL in a WPF application on the CodeProject, at: http://www.codeproject.com/KB/WPF/openglinwpf.aspx

Updates 

New to SharpGL 2.0 Beta 1
Note: Beta 1 is available on the CodePlex site only and won't be uploaded to this page until the Beta testing is complete. 

  • Hardware acceleration
  • OpenGL Extensions Support  
  • Core OpenGL Functionality up to OpenGL 4.2 
  • A dedicated WPF library 

New to SharpGL 1.83  

  • Five example applications in the download.
  • Numerous bug fixes, updates and optimisations. 

New to SharpGL 1.8 

  • Three new example applications.
  • Significant improvements to texturing code.
  • Rollup Controls in SceneBuilder keep the interface clutter free.
  • A new materials editor in the Modify tab allows quick material editing.
  • All SceneObjects in SharpGL now automatically optimise themselves to use display lists. This has made the Scene drawing extremely fast.
  • An overhaul of the GDI code by Lee Davies and myself has removed the large memory leak and hugely increased the overall performace of the library and application.
  • Many more minor updates and bug fixes are documented in the updates document in the project.

You can now automatically load simple 3D objects from Caligari trueSpace files. This makes creating applications a bit more simple, as you can test the polygon classes with real objects. A Polygon in the SharpGL scene graph is very powerful, they can cast real time shadows. A set of 'Builders' have been added to the SceneBuilder application, allowing you to build polygons from scratch, play around with materials etc.

SceneBuilder (the Test Application) is a simple application showing some of what SharpGL can do, and all the sourcecode is bundled with it, you can use it to build many aspects of a scene.

Points of Interest

The library is great to use, the Scene Graph 'Scene' object lets you do picking, you can control objects via the mouse, even parts of objects, such as the control points of NURBS and evaluators can be moved around. The polygons can be edited by Face, Vertex or as whole objects, and cast shadows over other objects.

Many of the 'kludgy' aspects of OpenGL such as the limits on the number of lights have been smoothed over. Using lights as an example, when the scene is created, the maximum number of lights is ascertained, and you cannot go over that limit. The extent of Mouse control is amazing, and very easy to implement in your own classes. The Persistence code is some of the best code I've ever written, you can call a function in the persistence engine, passing a type of object, and immediately a File Open / Save dialog will be shown with all the available file formats there for the user to select from, then the object will be created from the file or saved to the file. This means in the SceneBuilder app, it takes about two lines to be able to load a polygon from file, with all the possible formats automatically shown.

Keep Up To Date 

Up to date information on SharpGL development is available from the CodePlex site. 

SharpGL is now 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


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
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 12 Oct 2011
Article Copyright 2002 by Dave Kerr
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid