Coder Social home page Coder Social logo

dwmkerr / sharpgl Goto Github PK

View Code? Open in Web Editor NEW
746.0 83.0 299.0 7.76 MB

Use OpenGL in .NET applications. SharpGL wraps all modern OpenGL features and offers a powerful scene graph to aid development.

License: MIT License

C# 98.61% PowerShell 0.95% GLSL 0.44%

sharpgl's Introduction

SharpGL

main codecov GuardRails badge

Unlock the power of OpenGL in any .NET application. SharpGL wraps all modern OpenGL features, provides helpful wrappers for advanced objects like Vertex Buffer Arrays and shaders, as well as offering a powerful Scene Graph and utility library to help you build your projects.

Example of SharpGL

Check out the Samples, they're a great place to start learning how to use SharpGL.

Getting Started

SharpGL is made up of a number of packages, you can install whichever package or packages you need!

Package Link Overview
SharpGL SharpGL Core All OpenGL functions wrapped and ready to execute, as well as all OpenGL extensions.
SharpGL.SceneGraph SharpGL SceneGraph The SceneGraph library contains a full class library which models key 3D entities.
SharpGL.Serialization SharpGL Serialization The Serialization library contains utilities to load data from Discreet, Wavefront and Caligari file formats.
SharpGL.WPF SharpGL WPF SharpGL for WPF includes the Core as well as OpenGL controls to drop into your WPF app.
SharpGL.WinForms SharpGL WinForms SharpGL for WinForms includes the Core as well as OpenGL controls to drop into your WinForms app.

Install SharpGL packages with NuGet, either by using the Package Explorer or the Package Manager tool, e.g:

PM> Install-Package SharpGL

Compatibility

SharpGL has built in support for OpenGL support, newer functions can be loaded on demand as needed. The table below shows the compatibility across frameworks and platforms.

OpenGL

Currently SharpGL has built in bindings for OpenGL 4.0 - functions from later versions can be loaded at runtime as needed.

Framework Compatibility

All components support the .NET Framework 4.0 onwards, .NET Core 3.0 onwards and .NET Standard 2.1 onwards. Some components also support earlier versions.

Component .NET Framework .NET Core .NET Standard
SharpGL 4.0+ 2.0+ 2.0+
SharpGL.SceneGraph 4.0+ 2.0+ 2.0+
SharpGL.Serialization 4.0+ 2.0+ 2.0+
SharpGL.WinForms 4.0+ 3.0+ 2.1+
SharpGL.WPF 4.0+ 3.0+ 2.1+

Platform Compatibility

Compatibility across platforms is supported via framework specific components.

Platform Support
WinForms on Microsoft Windows ✅ via SharpGL.WinForms
WPF on Microsoft Windows ✅ via SharpGL.WPF
UWP on Microsoft Windows ❌ Work in Progress
Xamarin on Microsoft Windows ❌ Work in Progress
Xamarin on MacOS ❌ Work in Progress
Xamarin on Linux ❌ Work in Progress

Legacy Versions

The Visual Studio 2017 version of the codebase, which supports the .NET Framework only, is available on the release/2.x branch. However, this branch will not be maintained going forwards. The current mainline still supports the .NET Framework.

Developer Guide

To build the code, clone the repo and open the SharpGL, Samples or Tools solution. The Extensions solution is used for the Visual Studio Project Templates and requires additional components - you can find out more on the Wiki on the 'Developing SharpGL' page.

You can also use the following scripts to run the processes:

Script Notes
config.ps1 Ensure your machine can run builds by installing necessary components such as nunit. Should only need to be run once.
build.ps1 Build all solutions. Ensures that we build both 32/64 bit versions of native components.
test.ps1 Run all tests, including those in samples.
coverage.ps1 Create a coverage report. Reports are written to ./artifacts/coverage
pack.ps1 Create all of the SharpGL NuGet packages, which are copied to ./artifacts/packages.

These scripts will generate various artifacts which may be useful to review:

artifacts\
  \tests                  # NUnit Test Reports
  \coverage               # Coverage Reports
  \packages               # NuGet Packages

Build Pipelines

Test the main build pipeline with act:

# Install act. See: https://github.com/nektos/act
brew install act

# Run the main pipeline to test release please
act -j main -s GITHUB_TOKEN=<token>

Releasing

To make and publish a release:

  1. Update the *.csproj files with the new version number
  2. Create the version tag (e.g. git tag v3.2.1)
  3. Push the code and tags (e.g. git push --follow-tags)

AppVeyor will automatically push the release to NuGet and GitHub.

Sample Applications

There are a large number of sample applications that show how to use SharpGL. Check out the 'Samples' solution to see the samples that are available.

WinForms - Ducky Sample

This sample shows how to load an object file with materials, using the Serialization library. It also has great support for internationalization (thanks odalet)!

Ducky Sample

This sample demonstrates:

  • Loading *.obj files and associated materials
  • Building polygons from *.obj files
  • Arcball rotation

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

WinForms - Extensions Sample

This sample shows how to use OpenGL extensions. It demonstrates this by using the 'bump map' extensions.

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Extensions Sample

WinForms - Hit Test Sample

This sample shows how to use to perform hit testing with SharpGL. It uses the Scene Graph to support this.

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Extensions Sample

WinForms - Modern OpenGL Sample

This sample shows how to use modern OpenGL capabilities which are Shader based, by showing a vertex and fragment shader.

Extensions Sample

WinForms - Native Textures Sample

This sample shows how to load textures into OpenGL using pure OpenGL functions. However, the Texture object from the SceneGraph will be much easier to use!

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Native Textures Sample

WinForms - Particle Systems Sample

This sample shows how to build a simple particle system with OpenGL.

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Native Textures Sample

WinForms - Polygon Loading

This sample shows how to load polygon data with the Scene Graph and Serialization libraries.

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Native Textures Sample

WinForms - Radial Blue

This sample shows how to use a Radial Blur effect in OpenGL.

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Native Textures Sample

WinForms - Render Contexts Sample

This sample demonstrates the different types of render contexts which are available, and how they affect performance and the extensions available.

Native Textures Sample

WinForms - Render Trigger Sample

This sample shows different ways to render; either on a timer or on demand.

Native Textures Sample

WinForms - Scene Sample

This sample demonstrates the Scene Graph which can be used to manage and render geometry.

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Native Textures Sample

WinForms - SharpGL Textures Sample

This sample demonstrates how textures can be loaded using the SharpGL Textures object, which greatly simplifies texture management.

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Native Textures Sample

WinForms - Simple Drawing Sample

This sample demonstrates the most basic form of simple drawing in OpenGL.

Note that this sample uses immediate mode OpenGL, which is officially deprecated.

Native Textures Sample

WPF - Cel Shading Sample

This sample demonstrates how to use shaders to create a cel-shaing effect.

Native Textures Sample

WPF - Drawing Mechanisms Sample

This sample demonstrates how to use shaders to create a cel-shaing effect.

WPF - FastGL

This sample demonstrates how to use NV_DX_interop(2) to accelerate drawing using DirectX.

WPF - Object Loading Sample

This sample demonstrates how to load objects in a WPF OpenGL project.

WPF - Simple Shader Sample

This sample shows how to use a simple shader.

Simple Shader Sample

WPF - Tea Pot Sample

This sample shows how to quickly and easily render geometry.

Simple Shader Sample

WPF - Text Rendering Sample

This sample shows how to render 3D and 2D text.

Text Rendering Sample

WPF - Two Dimensional Rendering Sample

This sample shows how to do simple 2D render, with a visual like an old Windows Screen-Saver.

Text Rendering Sample

Documentation

All documentation is available on the Wiki.

SharpGL Visual Studio Extensions

There are project templates available for SharpGL WinForms and WPF projects - just search for SharpGL on the Visual Studio Extensions gallery, or get the extensions directly:

Please be aware that these extensions have not been maintained over time and I am looking for support in maintaining them.

Credits, Sponsorship & Thanks

SharpGL is written and maintained by me. Special thanks go to the following contributors:

  • robinsedlaczek - Code and documentation updates, tireless patience while I get through a backlog of work!
  • odalet - amazing work on internationalization and making the serialization code work in all locales

NDepend

NDepend

SharpGL is proudly sponsored by NDepend! Find out more at www.NDepend.com.

Red Gate

Red Gate

Many thanks to Red Gate who have kindly provided SharpGL with a copy of their superb .NET Developer Bundle

JetBrains

JetBrains

Thanks for JetBrains for sponsoring SharpGL with Resharper!

Built with SharpGL

If you've got a project that uses SharpGL and you'd like to show it off, just add the details here in a PR!

Open Vogel

Checkout https://sites.google.com/site/gahvogel/ to see a free, open source project which supports aerodynamics!

AgOpenGPS

This is the very first open source Precision Agricultural App! Built by Brian Tischler, you can see the discussions and excitement on this project with farmers across the world!

sharpgl's People

Contributors

arahaan avatar babooncodes avatar davidhnilica avatar dwmkerr avatar ersoga avatar frozen-eye avatar ftlphysicsguy avatar github-actions[bot] avatar guardrails[bot] avatar hellgate94 avatar joshuanapoli avatar littlefox94 avatar mohsenheydari avatar odalet avatar pyrdacor avatar robinsedlaczek avatar timmitry avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharpgl's Issues

Callback before GL context destroyed?

Is there any way I could get a callback right before the GL context is torn down? I need to clean up a lot of GL objects and obviously this cannot be done if the context no longer exists.

It seems WPF offers no way of binding an event to be executed before the control is destroyed and the WPF OpenGLControl has Initialized and Draw but not Destroyed. Would this be possible?

Make OpenGL Static

The core OpenGL class should be a static class named 'gl'. This means that the OpenGL class no longer has state - context state is controlled via an OpenGLContext instead.

Object Loader Sample

Needs:

  • Wavefront support
  • Scaling, rotation, ideally auto scaling too
  • immediate/retained
  • points, lines polys
  • textures
  • tesselation of quads

Improve WPF Garbage Collection Performance

If you're using SharpGL in a WPF application, and you're using RenderContextType.FBO, then when the OpenGLControl responds to its DispatchTimer's Tick event (see the timer_Tick method in OpenGLControl.xaml.cs under the OpenGL.WPF folder) it will call the static HBitmapToBitmapSource(IntPtr) method (see BitmapConversion.cs). To prevent possible memory problems when too much is going and and garbage collection isn't fast enough, the HBitmapToBitmapSource method includes a call to GC.Collect() in a finally block that occurs with every call.

I have found this to cause too much of a slow-down with fast changing scenes, and to speed things up, I've made the following changes: I added a "static int gcCount = 0;" and a "static readonly int MaxCyclesBeforeGC = 50;" to the BitmapConversion class. Then, in the HBitmapToBitmapSource method's finally block have the following instead of the GC.Collect() call:

 gcCount++;
 if (gcCount > MaxCyclesBeforeGC)
 {
     gcCount = 0;
     GC.Collect();
 }

You can play around with the value for MaxCyclesBeforeGC, but NOT calling GC.Collect() with every cycle makes for a much smoother result and performing the garbage collection every so often seems to keep any memory problems in check.

Just a friendly suggestion.

Potential bug with attributes

Hello!

I found a line in the code sharpGL on GitHub.
Perhaps here the error...

        AttributeMask attributeFlags = AttributeMask.None;
        attributeFlags &= accumBufferAttributes.AreAnyAttributesSet() ? accumBufferAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= colorBufferAttributes.AreAnyAttributesSet() ? colorBufferAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= currentAttributes.AreAnyAttributesSet() ? currentAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= depthBufferAttributes.AreAnyAttributesSet() ? depthBufferAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= enableAttributes.AreAnyAttributesSet() ? enableAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= fogAttributes.AreAnyAttributesSet() ? fogAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= lightingAttributes.AreAnyAttributesSet() ? lightingAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= lineAttributes.AreAnyAttributesSet() ? lineAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= pointAttributes.AreAnyAttributesSet() ? pointAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= polygonAttributes.AreAnyAttributesSet() ? polygonAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= evalAttributes.AreAnyAttributesSet() ? evalAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= hintAttributes.AreAnyAttributesSet() ? hintAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= listAttributes.AreAnyAttributesSet() ? listAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= pixelModeAttributes.AreAnyAttributesSet() ? pixelModeAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= polygonStippleAttributes.AreAnyAttributesSet() ? polygonStippleAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= scissorAttributes.AreAnyAttributesSet() ? scissorAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= stencilBufferAttributes.AreAnyAttributesSet() ? stencilBufferAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= textureAttributes.AreAnyAttributesSet() ? textureAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= transformAttributes.AreAnyAttributesSet() ? transformAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags &= viewportAttributes.AreAnyAttributesSet() ? viewportAttributes.AttributeFlags : AttributeMask.None;

&= Change to |=

        AttributeMask attributeFlags = AttributeMask.None;
        attributeFlags |= accumBufferAttributes.AreAnyAttributesSet() ? accumBufferAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= colorBufferAttributes.AreAnyAttributesSet() ? colorBufferAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= currentAttributes.AreAnyAttributesSet() ? currentAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= depthBufferAttributes.AreAnyAttributesSet() ? depthBufferAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= enableAttributes.AreAnyAttributesSet() ? enableAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= fogAttributes.AreAnyAttributesSet() ? fogAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= lightingAttributes.AreAnyAttributesSet() ? lightingAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= lineAttributes.AreAnyAttributesSet() ? lineAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= pointAttributes.AreAnyAttributesSet() ? pointAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= polygonAttributes.AreAnyAttributesSet() ? polygonAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= evalAttributes.AreAnyAttributesSet() ? evalAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= hintAttributes.AreAnyAttributesSet() ? hintAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= listAttributes.AreAnyAttributesSet() ? listAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= pixelModeAttributes.AreAnyAttributesSet() ? pixelModeAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= polygonStippleAttributes.AreAnyAttributesSet() ? polygonStippleAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= scissorAttributes.AreAnyAttributesSet() ? scissorAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= stencilBufferAttributes.AreAnyAttributesSet() ? stencilBufferAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= textureAttributes.AreAnyAttributesSet() ? textureAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= transformAttributes.AreAnyAttributesSet() ? transformAttributes.AttributeFlags : AttributeMask.None;
        attributeFlags |= viewportAttributes.AreAnyAttributesSet() ? viewportAttributes.AttributeFlags : AttributeMask.None;

best regards Chistik D.U.

Retire the Serialization Library

The serialization library is based on the scenegraph, so doesn't offer the client enough power to deal with input files. This library should be removed, and a sample should be built that shows how to use the more powerful:

file-format-wavefront
file-format-discrete

libraries instead.

SharpGL.WinForms is using deprecated functions

When I tried profiling my application, I noticed that glError() always returns GL_INVALID_OPERATION before the beginning of the rendering function.

The problem appears to be that the WinForms-Control creates and pushes a perspective matrix even when the Context is set to a higher version of OpenGL (e.g. 4.3.0) and therefore all fixed pipeline funtions are deprecated and cause errors.

I hope I did not miss any option which allows to change this behavior.

OpenFileDialog.ShowDialog() => OK affects my buffers.

Dear SharpGL developers

I've been enhancing SharpGL a little and I'm creating some more modern OGL samples as practice. At the moment I'm creating a buffer based OBJ-file loader. I've created the import algorithm from scratch, so it might not be perfect.

The OBJ import works quite fine when I'm loading a file from a URL. However, when I use the OpenFileDialog.ShowDialog(), choose a file and press OK it seems to do something with my Buffers. After this all my objects disappear and I can't add any others anymore either.

After some debugging it seems that the ShowDialog => OK is causing the issue (it doesn't do it when I press Cancel instead).

When the ShowDialog closes it always continues to HiddenWindowRenderContextProvider.WndProc(...).

Do you have any idea what the problem might be? Note that I've been messing around with the OpenGLControl.xaml.cs, but I don't think that I did anything that influences this.

The full source code can be found here:
https://github.com/jochemgeussens/sharpgl/tree/master/source/SharpGL/Samples/WPF/JOG/SharpGLObjFileImport

For the project to work, you'll have to use my version of SharpGL/SharpGL.WPF and SharpGL.SceneGraph.

Thanks in advance.

Kind regards,
Jochem

Missing methods and constants?

Dear Sir

I'd like to let you know that I've found a couple of missing GL constants and methods while using SharpGL. I think there might be a need to do a big update regarding the implementation of the newer constants and method calls. Most of the ones I've found so far are neglectable for me, but VAO sounds quite promising, so it should be available in SharpGL. I'll continue updating this list as I find more of them.

Constants:
https://www.opengl.org/sdk/docs/man3/xhtml/glBindBuffer.xml

  • GL_COPY_READ_BUFFER = 36662
  • GL_COPY_WRITE_BUFFER = 36663
  • GL_UNIFORM_BUFFER = 35345
  • GL_HALF_FLOAT = 5131
  • Int_2_10_10_10_Rev = 36255
  • GL_COLOR_ATTACHMENT0 = 36065

Methods:

Kind regards,
Jochem

Correct FPS

Original issues:
https://sharpgl.codeplex.com/workitem/1083
https://sharpgl.codeplex.com/workitem/903

Details:
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.

Next issue:

The FPS measurement routine is a bit off. It measures the frame drawing time. The true FPS(which depends on the total code) is different. One must measure the total time, including non-rendering code as that effects the frame rate. e.g., it doesn't matter if you can draw a frame in 0s if your non-rendering code takes 10 seconds(==> 1/10 fps).

I've attached a modified OpenGLControl that not only adds these proper FPS measurements(both single frame executing/drawing time + true FPS) + it minimizes the effect by not doing the calculation every frame.

The DTPF is the time it takes to draw a frame(user drawing code + gl rendering code), the AFPS is the average frames per second(the fps as seen by the user), DFPS is the desired frames per second as set by the timer = FrameRate, NDT is the "non-drawing time" which is the time left over for other code outside the gl loop.

(the code could be cleaned up a bit as I just downloaded the code)

Source code at: https://sharpgl.codeplex.com/workitem/903

Create Automated Release Build

We need a script that can build an entire release - all of the core libraries, tools, samples, extensions and Nuget packages. Without this, small and fast releases cannot be made due to the overhead of pulling together the different components to build. The structure must be:

  1. A folder at the root called 'release'.
  2. A PowerShell script called 'BuildRelease.ps1'.
  3. When the script runs, it should build everything, and drop it into a version numbered folder in the 'release' folder.

Documentation for SceneGraph

In order to know how the SceneGraph can be used in applications, there should be a kind of documentation of the API. Further, we need some walkthroughs and/or HowTos for the SceneGraph.

Sensible Package Names

Upload the packages as:

SharpGL
SharpGL.WinForms
SharpGL.WPF

which is a more sensible naming convention.

Include SetLastError = true into all winapi functions

If every imported function (that potentially can fail) in SharpGL.Win32 namespace will be changed from:

        [DllImport(OpenGL32)]
        public static extern IntPtr wglCreateContext(IntPtr hdc);

to:

        [DllImport(OpenGL32, SetLastError = true)]
        public static extern IntPtr wglCreateContext(IntPtr hdc);

, user can actually get what was wrong with the his call, if it fails, just by calling System.Runtime.InteropServices.Marshal.GetLastWin32Error() or better - by creating and\or throwing System.ComponentModel.Win32Exception().

Without SetLastError, trying to call GetLastWin32Error() after obviously failed winapi call (it returned zero) returns error code 0 ("The operation completed successfully"), as if no error occured.

See remarks section on: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getlastwin32error%28v=vs.100%29.aspx

Write up Cel Shading Sample

Hi @prideout if you see this message can you let me know whether I can write about implementing your cel shading code in .NET with this SharpGL library on the CodeProject (obviously referencing your article and you as the original author) - I'd like to get explicit permission before I distribute anything!

Thanks,

Dave

Dramatic Performance Increase -- Stop Using DynamicInvoke!

In the OpenGLExtensions.cs file under the SharpGL folder, all the extension methods generally rely on InvokeExtensionFunction(params object[] args). Apart from one minor performance issue in that method (it uses Dictionary.ContainsKey vice Dictionary.TryGetValue, thus accessing the dictionary twice instead of only once) there is one MAJOR performance issue with the way it does business. It creates a generalized Delegate object and then calls DynamicInvoke. DynamicInvoke has a huge amount of overhead. You need to replace this pattern with the following:

Repalce the InvokeExtensionFunction(params object[] args) method with the following:

private T GetDelegateFor<T>() where T : class
{
    //  Get the type of the extension function.
    Type delegateType = typeof(T);

    //  Get the name of the extension function.
    string name = delegateType.Name;

    // ftlPhysicsGuy - Better way
    Delegate del = null;
    if (extensionFunctions.TryGetValue(name, out del) == false)
    {
        IntPtr proc = Win32.wglGetProcAddress(name);
        if (proc == IntPtr.Zero)
            throw new Exception("Extension function " + name + " not supported");

        //  Get the delegate for the function pointer.
        del = Marshal.GetDelegateForFunctionPointer(proc, delegateType);
        if (del == null)
            throw new Exception("Extension function " + name + " marshalled incorrectly");

        //  Add to the dictionary.
        extensionFunctions.Add(name, del);
    }
    return del as T;
}

Then everywhere you call InvokeExtensionFunction(…), replace it like so:

// NOTE: JUST ONE EXAMPLE. MANY METHODS IN OpenGLExtensions.cs USE THIS PATTERN
public void BlendColor(float red, float green, float blue, float alpha)
{   
    //InvokeExtensionFunction<glBlendColor>(red, green, blue, alpha);
    GetDelegateFor<glBlendColor>()(red, green, blue, alpha);
}

That calls the delegate directly (without DynamicInvoke) and can make the process two to three times faster!

Now if you really want to boost the speed, stop accessing that dictionary (in GetDelegateFor, or previously in InvokeExtensionFunction) every time you call an extension. Instead, create a dedicated delegate for every method call:

// NOTE: JUST ONE EXAMPLE. MANY METHODS IN OpenGLExtensions.cs USE THIS PATTERN
glBlendColor m_glBlendColor = null;
public void BlendColor(float red, float green, float blue, float alpha)
{
    //InvokeExtensionFunction<glBlendColor>(red, green, blue, alpha);
    if (m_glBlendColor == null)
        m_glBlendColor = GetDelegateFor<glBlendColor>();
    m_glBlendColor(red, green, blue, alpha);
}

I’d suggest changing every method in OpenGLExtensions.cs to match this pattern. I’ve already started changing the methods I call the most, and the performance increase for my project is dramatic.

Hope that's helpful.

Transformation for Polygon and Quadrics should be more generic

When using polygon objects and quadric objects in an application I like to handle transformation more generic. Currently, there is a Transformation-property in both base classes: Quadric and Polygon. If I want to transform those objects, I have to differentiate between those in code. The Transformation-property should be in the common base class SceneElement, so it does not matter if I handle a polygon or quadric in my code.

Is there any reason why the Quadric-class does not have a setter for the Transformation-property?

Tutorial 1 - Installation and Setup

Write a new series on the codeproject for SharpGL. The first will have to be:

  1. Setting up a project with the Templates
  2. Setting up a project with Nuget
  3. Your first project.

This can for now demonstrate immediate mode rendering, although the default should be immediate.

Crash when sharpgl container width has binding to relative source

Hello,

Can you help me with following issue?
I have a control template for a tab control:

<ControlTemplate TargetType="TabControl">
                    <Grid Name="MainGrid"
                          HorizontalAlignment="Stretch">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <TabPanel x:Name="HeaderPanel"
                                  Style="{DynamicResource TabPanelStyle}"
                                  Grid.Row="0"
                                  Margin="0,10,0,5"
                                  HorizontalAlignment="Center"
                                  IsItemsHost="True"
                                  Background="Transparent"/>
                        <ContentPresenter x:Name="PART_SelectedContentHost" 
                                          HorizontalAlignment="Stretch"
                                          ContentSource="SelectedContent"
                                          Grid.Column="0"
                                          Grid.Row="1"
                                          Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Grid}, Path=ActualWidth}" />
                    </Grid>
                </ControlTemplate>

In only one of the tabs there is a sharpGL control. At run, before any frame is drawn, the app is crashing only when following xaml line exists (otherwise everything is working fine):

Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Grid}, Path=ActualWidth}"

Message and partial stack trace:

Message: "Value cannot be null."
Parameter name: "bitmap"
   at System.Windows.Interop.Imaging.CriticalCreateBitmapSourceFromHBitmap(IntPtr bitmap, IntPtr palette, Int32Rect sourceRect, BitmapSizeOptions sizeOptions, WICBitmapAlphaChannelOption alphaOptions)
   at System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(IntPtr bitmap, IntPtr palette, Int32Rect sourceRect, BitmapSizeOptions sizeOptions)
   at SharpGL.WPF.BitmapConversion.HBitmapToBitmapSource(IntPtr hBitmap) in c:\Repositories\GitHub\sharpgl\source\SharpGL\Core\SharpGL.WPF\BitmapConversion.cs:line 28
   at SharpGL.WPF.OpenGLControl.timer_Tick(Object sender, EventArgs e) in c:\Repositories\GitHub\sharpgl\source\SharpGL\Core\SharpGL.WPF\OpenGLControl.xaml.cs:line 158
   at System.Windows.Threading.DispatcherTimer.FireTick(Object unused) ...

Is there any fix for this (xaml, drawing code, sharpGL libraries...)?
Thanks!

Email Peter when 2.3 is released

Email Peter when the 2.3 release is done, also include link to the OpenGL in .NET - Getting started article on the codeproject

Support OpenGL 3.0+ Render Contexts

OpenGL 3.0 onwards uses a more complicated mechanism to create a render context. This involves first creating a standard render context, then using an extension to create a new 3.0 upwards render context. We should be supporting this properly - if we don't, then we cannot expect the advanced functionality of OpenGL 3.0 upwards to work properly.

See:

http://www.opengl.org/wiki/Creating_an_OpenGL_Context_(WGL)#Proper_Context_Creation

http://www.swiftless.com/tutorials/opengl4/1-opengl-window.html

Add uint overload for BufferData to OpenGLExtensions

Dear Sir

I'm really grateful for the ushort[] and float[] overload to BufferData, as I previously had no experience with IntPtr's. So this was a good example to get started with it. But for larger data (>65k) ushort is not an option as index buffer. So could you consider adding a uint overload as well. I created an extension method for it at the moment.

I think you can just copy paste this into OpenGLExtensions:

    public void BufferData(uint target, uint[] data, uint usage)
    {
        var dataSize = data.Length * sizeof(uint);
        IntPtr p = Marshal.AllocHGlobal(dataSize);
        var intData = new int[data.Length];
        Buffer.BlockCopy(data, 0, intData, 0, dataSize);
        Marshal.Copy(intData, 0, p, data.Length);
        InvokeExtensionFunction<glBufferData>(target, dataSize, p, usage);
        Marshal.FreeHGlobal(p);
    }

Kind regards,
Jochem.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.