daily update on 20240828 by nitload youmu, autotexture added

This commit is contained in:
Nitload
2024-08-28 10:58:31 +08:00
parent d082071f2d
commit 1ee4e4a42f
586 changed files with 60910 additions and 123106 deletions
@@ -1,88 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="AnimationBuilder.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Geometries;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace StgSharp.Graphics
{
public delegate Image BuildAnimationDelegate(float time, out Polygon4 texutreFrame);
public sealed class AnimationBuilder: IImageProvider
{
private Image cache;
private Polygon4 textureFrame;
private TimeFunction time;
public AnimationBuilder(
BuildAnimationDelegate builderFunc,
TimeFunction timeline
)
{
textureFrame = new Polygon4();
time = timeline;
BuilderFunc = builderFunc;
cache = BuilderFunc(time.Calculate(), out textureFrame);
}
public Polygon4 TextureFrame { get => textureFrame; }
public BuildAnimationDelegate BuilderFunc { get; set; }
public bool IsComplete
{
get => time.IsComplete;
}
public Image GetAnimationFrame()
{
if (!time.IsComplete)
{
cache = BuilderFunc(time.Calculate(),out textureFrame);
}
return cache;
}
public void reset()
{
time.Reset();
}
Image IImageProvider.ProvideImage()
{
return GetAnimationFrame();
}
}
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IImageProvider.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
@@ -7,6 +37,5 @@ namespace StgSharp.Graphics
public interface IImageProvider
{
Image ProvideImage();
}
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ImageHelper.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
@@ -12,10 +42,10 @@ namespace StgSharp.Graphics
{
throw new ArgumentNullException(nameof(i));
}
Array.Resize(ref i.data, width * height * i.PixelSize);
Array.Resize(ref i.Data, width * height * i.PixelSize);
i.Height = height;
i.Width = width;
switch (move)
switch (move)
{
case ImageMovement.Discard:
break;
@@ -24,8 +54,8 @@ namespace StgSharp.Graphics
default:
throw new NotImplementedException();
}
i.PixelUpdateCount++;
}
}
[Flags]
@@ -1,46 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics
{
public static class ImageProcessor
{
public static void Resize(Image i, int width, int height, ImageMovement move)
{
if (i == null)
{
throw new ArgumentNullException(nameof(i));
}
Array.Resize(ref i.data, width * height * i.ChannelCount);
i.Height = height;
i.Width = width;
switch (move)
{
case ImageMovement.Discard:
break;
case ImageMovement.Top:
break;
default:
throw new NotSupportedException("Invalid or not supported data remanence");
}
}
}
[Flags]
public enum ImageMovement
{
#pragma warning disable CA1008
Discard = 0,
#pragma warning restore CA1008
Top = 1,
Bottom = 2,
Left = 4,
Right = 8,
TopLeft = Top | Left,
BottomLeft = Bottom | Left,
TopRight = Top | Right,
BottomRight = Bottom | Right,
}
}
@@ -43,8 +43,9 @@ namespace StgSharp.Graphics
/// </summary>
public abstract class BufferObjectBase : IDisposable
{
protected RenderStream binding;
protected GlHandle[] _bufferHandle;
protected RenderStream binding;
/// <summary>
/// Get the only handle to one of the Object instance
+155 -140
View File
@@ -49,22 +49,9 @@ namespace StgSharp.Graphics
public unsafe struct GLFWcontext
{
private int client;
private IntPtr destroy;
private delegate*<byte*> extensionSupported;
private GLFWbool forward, debug, noerror;
//PFNGLGETINTEGERVPROC GetIntegerv;
private IntPtr GetIntegerv;
private delegate*<delegate*<void>, void> getProcAddress;
//PFNGLGETSTRINGPROC GetString;
private IntPtr GetString;
//PFNGLGETSTRINGIPROC GetStringi;
private IntPtr GetStringi;
private int major, minor, revision;
/*
void (* makeCurrent) (glfwWindow*);
void (* swapBuffers) (glfwWindow*);
@@ -75,12 +62,26 @@ namespace StgSharp.Graphics
*/
private delegate*<glfwWindow*> makeCurrent;
private delegate*<glfwWindow*> swapBuffer;
private delegate*<int> swapInterval;
private GLFWbool forward, debug, noerror;
private int client;
private int major, minor, revision;
private int profile;
private int release;
private int robustness;
private int source;
private delegate*<glfwWindow*> swapBuffer;
private delegate*<int> swapInterval;
private IntPtr destroy;
//PFNGLGETINTEGERVPROC GetIntegerv;
private IntPtr GetIntegerv;
//PFNGLGETSTRINGPROC GetString;
private IntPtr GetString;
//PFNGLGETSTRINGIPROC GetStringi;
private IntPtr GetStringi;
internal struct egl
{
@@ -165,15 +166,16 @@ namespace StgSharp.Graphics
public unsafe struct GLFWimage
{
/*! The pixel _data of this image, arranged left-to-right, top-to-bottom.
*/
private byte* pixels;
/*! The height, in pixels, of this image.
*/
private int height;
/*! The width, in pixels, of this image.
*/
private int width;
/*! The pixel data of this image, arranged left-to-right, top-to-bottom.
*/
private byte* pixels;
}
@@ -182,22 +184,24 @@ namespace StgSharp.Graphics
public unsafe struct GLFWgamepadstate
{
/*! The states of each [gamepad axis](@ref gamepad_axes), in the range -1.0
* to 1.0 inclusive.
*/
public fixed float axes[6];
/*! The states of each [gamepad button](@ref gamepad_buttons), `GLFW_PRESS`
* or `GLFW_RELEASE`.
*/
public fixed byte buttons[15];
/*! The states of each [gamepad axis](@ref gamepad_axes), in the range -1.0
* to 1.0 inclusive.
*/
public fixed float axes[6];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct GLFWallocator
{
private void* user;
//GLFWallocatefun allocate;
private IntPtr allocate;
@@ -207,34 +211,32 @@ namespace StgSharp.Graphics
//GLFWreallocatefun reallocate;
private IntPtr reallocate;
private void* user;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct glfwMonitor
{
private fixed byte name[128];
private IntPtr userPointer;
private int width, height;
private glfwVideomode* modes;
private glfwWindow* window;
private glfwVideomode* modes;
private int modeCount;
private glfwVideomode currentMode;
private fixed byte name[128];
private glfwGammaramp currentRamp;
private glfwGammaramp originalRamp;
private glfwGammaramp currentRamp;
private glfwVideomode currentMode;
private int modeCount;
private int width, height;
private IntPtr userPointer;
public glfwMonitor()
{ }
public unsafe string Name
{
get
get
{
fixed (byte* cptr = name)
{
@@ -242,69 +244,73 @@ namespace StgSharp.Graphics
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct glfwWindow
{
glfwWindow* next;
// Window settings and state
int resizable;
int decorated;
int autoIconify;
int floating;
int focusOnShow;
int mousePassthrough;
int shouldClose;
void* userPointer;
int doublebuffer;
// glfwVideomode videoMode; // 根据GLFWvidmode的定义转换
IntPtr monitor; // _GLFWmonitor* monitor;
IntPtr cursor; // _GLFWcursor* cursor;
int minwidth, minheight;
int maxwidth, maxheight;
int numer, denom;
int stickyKeys;
int stickyMouseButtons;
int lockKeyMods;
int cursorMode;
public fixed byte mouseButtons[GLconst.GLFW_MOUSE_BUTTON_LAST + 1];
public fixed byte keys[GLconst.GLFW_KEY_LAST + 1];
bool rawMouseMotion;
Callbacks callbacks;
// Virtual cursor position when cursor is disabled
double virtualCursorPosX, virtualCursorPosY;
bool rawMouseMotion;
int autoIconify;
int cursorMode;
int decorated;
int doublebuffer;
int floating;
int focusOnShow;
int lockKeyMods;
int maxwidth, maxheight;
int minwidth, minheight;
int mousePassthrough;
int numer, denom;
// Window settings and state
int resizable;
int shouldClose;
int stickyKeys;
int stickyMouseButtons;
IntPtr cursor; // _GLFWcursor* cursor;
// glfwVideomode videoMode; // 根据GLFWvidmode的定义转换
IntPtr monitor; // _GLFWmonitor* monitor;
public fixed byte keys[GLconst.GLFW_KEY_LAST + 1];
public fixed byte mouseButtons[GLconst.GLFW_MOUSE_BUTTON_LAST + 1];
// _GLFWcontext viewPortDisplay; // 根据_GLFWcontext的定义转换
// Callbacks are represented as IntPtr since we don't need the actual function pointers in C#
internal struct Callbacks
{
internal IntPtr pos;
internal IntPtr size;
internal IntPtr close;
internal IntPtr refresh;
internal IntPtr focus;
internal IntPtr iconify;
internal IntPtr maximize;
internal IntPtr fbsize;
internal IntPtr scale;
internal IntPtr mouseButton;
internal IntPtr cursorPos;
internal IntPtr cursorEnter;
internal IntPtr scroll;
internal IntPtr key;
internal IntPtr character;
internal IntPtr charmods;
internal IntPtr close;
internal IntPtr cursorEnter;
internal IntPtr cursorPos;
internal IntPtr drop;
}
Callbacks callbacks;
internal IntPtr fbsize;
internal IntPtr focus;
internal IntPtr iconify;
internal IntPtr key;
internal IntPtr maximize;
internal IntPtr mouseButton;
internal IntPtr pos;
internal IntPtr refresh;
internal IntPtr scale;
internal IntPtr scroll;
internal IntPtr size;
// GLFW_PLATFORM_WINDOW_STATE platformWindowState;
}
}
// GLFW_PLATFORM_WINDOW_STATE platformWindowState;
}
[StructLayout(LayoutKind.Sequential)]
@@ -345,9 +351,9 @@ namespace StgSharp.Graphics
public unsafe struct GLFWinitconfig
{
private int angleType;
private GLFWbool hatButtons;
private int angleType;
private int platformID;
//PFN_vkGetInstanceProcAddr vulkanLoader;
@@ -359,19 +365,20 @@ namespace StgSharp.Graphics
public unsafe struct GLFWwndconfig
{
private byte* title;
private GLFWbool autoIconify;
private GLFWbool centerCursor;
private GLFWbool decorated;
private GLFWbool floating;
private GLFWbool focused;
private GLFWbool focusOnShow;
private int height;
private GLFWbool maximized;
private GLFWbool mousePassthrough;
private GLFWbool resizable;
private GLFWbool scaleToMonitor;
private byte* title;
private GLFWbool visible;
private int height;
private int width;
private int xpos;
@@ -437,19 +444,20 @@ namespace StgSharp.Graphics
public unsafe struct GLFWctxconfig
{
private int client;
private GLFWbool debug;
private GLFWbool forward;
private GLFWbool noerror;
private int client;
private int major;
private int minor;
private GLFWbool noerror;
private int profile;
private int release;
private int robustness;
private int source;
//glfwWindow* share;
private IntPtr share;
private int source;
internal Nsgl nsgl = new Nsgl();
@@ -470,6 +478,11 @@ namespace StgSharp.Graphics
public unsafe struct GLFWfbconfig
{
private GLFWbool doublebuffer;
private GLFWbool sRGB;
private GLFWbool stereo;
private GLFWbool transparent;
private int accumAlphaBits;
private int accumBlueBits;
private int accumGreenBits;
@@ -478,16 +491,12 @@ namespace StgSharp.Graphics
private int auxBuffers;
private int blueBits;
private int depthBits;
private GLFWbool doublebuffer;
private int greenBits;
private uintptr_t handle;
private int redBits;
private int samples;
private GLFWbool sRGB;
private int stencilBits;
private GLFWbool stereo;
private GLFWbool transparent;
private uintptr_t handle;
}
@@ -495,37 +504,37 @@ namespace StgSharp.Graphics
internal unsafe struct GLFWlibrary
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GLconst.GLFW_JOYSTICK_LAST + 1)]
private GLFWjoystick[] joysticks = new GLFWjoystick[GLconst.GLFW_JOYSTICK_LAST + 1];
private GLFWallocator allocator;
private GLFWbool initialized;
private GLFWbool joysticksInitialized;
private GLFWls contextSlot;
private GLFWls errorSlot;
private GLFWmutex errorLock;
private GLFWplatform platform;
private int mappingCount;
private int monitorCount;
//GLFWcursor* cursorListHead;
private IntPtr cursorListHead;
//GLFWerror* errorListHead;
private IntPtr errorListHead;
private GLFWmutex errorLock;
private GLFWls errorSlot;
private GLFWbool initialized;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GLconst.GLFW_JOYSTICK_LAST + 1)]
private GLFWjoystick[] joysticks = new GLFWjoystick[GLconst.GLFW_JOYSTICK_LAST + 1];
private GLFWbool joysticksInitialized;
private int mappingCount;
//GLFWmapping* mappings;
private IntPtr mappings;
private int monitorCount;
//GLFWmonitor** monitors;
private IntPtr monitors;
private GLFWplatform platform;
//glfwWindow* windowListHead;
private IntPtr windowListHead;
@@ -548,8 +557,8 @@ namespace StgSharp.Graphics
private GLFWfbconfig framebuffer;
private GLFWinitconfig init;
private int refreshRate;
private GLFWwndconfig window;
private int refreshRate;
}
@@ -566,23 +575,36 @@ namespace StgSharp.Graphics
internal unsafe struct Egl
{
internal void* display;
internal void* handle;
internal bool ANGLE_platform_angle;
internal bool ANGLE_platform_angle_d3d;
internal bool ANGLE_platform_angle_metal;
internal bool ANGLE_platform_angle_opengl;
internal bool ANGLE_platform_angle_vulkan;
internal bool EXT_client_extensions;
internal bool EXT_platform_base;
internal bool EXT_platform_wayland;
internal bool EXT_platform_x11;
internal bool EXT_present_opaque;
internal bool KHR_colorSpace;
internal bool KHR_context_flush_control;
internal bool KHR_create_context;
internal bool KHR_create_context_no_error;
internal bool KHR_get_all_proc_addresses;
internal bool prefix;
internal int major, minor;
internal int platform;
internal IntPtr BindAPI;
internal IntPtr CreateContext;
internal IntPtr CreatePlatformWindowSurfaceEXT;
internal IntPtr CreateWindowSurface;
internal IntPtr DestroyContext;
internal IntPtr DestroySurface;
internal void* display;
internal bool EXT_client_extensions;
internal bool EXT_platform_base;
internal bool EXT_platform_wayland;
internal bool EXT_platform_x11;
internal bool EXT_present_opaque;
internal IntPtr GetConfigAttrib;
internal IntPtr GetConfigs;
@@ -591,20 +613,8 @@ namespace StgSharp.Graphics
internal IntPtr GetPlatformDisplayEXT;
internal IntPtr GetProcAddress;
internal void* handle;
internal IntPtr Initialize;
internal bool KHR_colorSpace;
internal bool KHR_context_flush_control;
internal bool KHR_create_context;
internal bool KHR_create_context_no_error;
internal bool KHR_get_all_proc_addresses;
internal int major, minor;
internal IntPtr MakeCurrent;
internal int platform;
internal bool prefix;
internal IntPtr QueryString;
internal IntPtr SwapBuffers;
internal IntPtr SwapInterval;
@@ -615,6 +625,8 @@ namespace StgSharp.Graphics
internal unsafe struct Osmesa
{
private void* handle;
private IntPtr CreateContextAttribs;
private IntPtr CreateContextExt;
@@ -622,8 +634,6 @@ namespace StgSharp.Graphics
private IntPtr GetColorBuffer;
private IntPtr GetDepthBuffer;
private IntPtr GetProcAddress;
private void* handle;
private IntPtr MakeCurrent;
}
@@ -631,17 +641,18 @@ namespace StgSharp.Graphics
internal unsafe struct vk
{
private void* handle;
private GLFWbool available;
private GLFWbool EXT_metal_surface;
private fixed ulong extensions[2];
private IntPtr GetInstanceProcAddr;
private void* handle;
private GLFWbool KHR_surface;
private GLFWbool KHR_wayland_surface;
private GLFWbool KHR_win32_surface;
private GLFWbool KHR_xcb_surface;
private GLFWbool KHR_xlib_surface;
private GLFWbool MVK_macos_surface;
private IntPtr GetInstanceProcAddr;
private fixed ulong extensions[2];
public vk()
{
@@ -664,12 +675,13 @@ namespace StgSharp.Graphics
public unsafe struct GLFWmapelement
{
private sbyte axisOffset;
private sbyte axisScale;
private byte index;
private byte type;
private sbyte axisOffset;
private sbyte axisScale;
}
[StructLayout(LayoutKind.Sequential)]
@@ -694,20 +706,21 @@ namespace StgSharp.Graphics
public unsafe struct GLFWjoystick
{
private GLFWbool allocated;
private float* axes;
private byte* buttons;
private byte* hats;
private void* userPointer;
private fixed byte guid[33];
private fixed byte name[128];
private GLFWbool allocated;
private GLFWbool connected;
private int axisCount;
private int buttonCount;
private byte* buttons;
private GLFWbool connected;
private fixed byte guid[33];
private int hatCount;
private byte* hats;
//GLFWmapping* mapping;
private IntPtr mapping;
private fixed byte name[128];
private void* userPointer;
// This is defined in platform.h
// not completed in transforming
@@ -730,12 +743,12 @@ namespace StgSharp.Graphics
public unsafe struct GLFWplatform
{
private int platformID;
// init
//GLFWbool(*init)(void);
private IntPtr init;
private int platformID;
//void (* terminate) (void);
private IntPtr terminate;
internal IntPtr createCursor;
@@ -953,7 +966,9 @@ namespace StgSharp.Graphics
[StructLayout(LayoutKind.Sequential)]
internal struct GLsync
{
public IntPtr Handle;
}
#endregion glad struct
@@ -28,14 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
/*
* This file is created to link functions in OpenGL to version in C#
* The name of delegates and organization to init all these delegates
* are refferd from GLAD1 in agreement of MIT license generated from
* https://glad.dav1d.de/
*/
using StgSharp.Math;
using System;
@@ -44,6 +36,13 @@ using System.Runtime.InteropServices;
namespace StgSharp.Graphics
{
/// <summary>
/// Function handler to load an opengl function by searching its name.
/// </summary>
/// <param name="name">the name of the Opengl function</param>
/// <returns>An Intptr value representing the pointer to the function</returns>
public delegate IntPtr glLoader(string name);
#region StgSharpDele
public unsafe delegate void FrameBufferSizeHandler(IntPtr window, uint width, uint height);
@@ -52,12 +51,6 @@ namespace StgSharp.Graphics
#endregion
/// <summary>
/// Function handler to load an opengl function by searching its name.
/// </summary>
/// <param name="name">the name of the Opengl function</param>
/// <returns>An Intptr value representing the pointer to the function</returns>
public delegate IntPtr glLoader(string name);
#region glDEBUG
@@ -4849,13 +4849,18 @@ namespace StgSharp.Graphics.OpenGL
public static class glAttachment
{
public const uint Depth = GLconst.DEPTH_ATTACHMENT;
public const uint DepthAndStencil = GLconst.DEPTH_STENCIL_ATTACHMENT;
public const uint Stencil = GLconst.STENCIL_ATTACHMENT;
private static int colorRange =
GlFunction.CurrentGL.GetMaskInteger((uint)GLconst.MAX_COLOR_ATTACHMENTS);
OpenGLFunction.CurrentGL.GetMaskInteger((uint)GLconst.MAX_COLOR_ATTACHMENTS);
public static uint Color(int i)
{
#if DEBUG
if (i>colorRange||i<0)
if ((i > colorRange) || (i < 0))
{
throw new ArgumentOutOfRangeException();
}
@@ -4863,8 +4868,5 @@ namespace StgSharp.Graphics.OpenGL
return (uint)(GLconst.COLOR_ATTACHMENT0 + i);
}
public const uint Depth = GLconst.DEPTH_ATTACHMENT;
public const uint Stencil = GLconst.STENCIL_ATTACHMENT;
public const uint DepthAndStencil = GLconst.DEPTH_STENCIL_ATTACHMENT;
}
}
@@ -1,80 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BufferObjectBase.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
{
/// <summary>
/// Interface of all kinds OpenGL buffer objects
/// </summary>
public abstract class BufferObjectBase : IDisposable
{
protected RenderStream binding;
protected glHandleSet _bufferHandle;
/// <summary>
/// Get the only handle to one of the Object instance
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public glHandle this[int index] => _bufferHandle[index];
/// <summary>
/// Bind a buffer instance to OpenGL
/// </summary>
/// <param name="index">Index of handle of the object in this instance to be bind</param>
public abstract void Bind(int index);
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
/// <inheritdoc/>
public override string ToString()
{
return $"This is a {GetType().FullName}, containing {_bufferHandle.length} buffer handles: {_bufferHandle.ToString()}.";
}
protected abstract void Dispose(bool disposing);
~BufferObjectBase()
{
Dispose(disposing: false);
}
}
}
@@ -1,84 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="EBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.GL
{
/// <summary>
/// A collection of handle to Element Buffer Object in OpenglFunc.
/// Each <see langword="uint"/> value indexed from instance of this class this
/// is the only handle to one Element Buffer Object.
/// </summary>
public unsafe class ElementBuffer : BufferObjectBase
{
internal ElementBuffer(int n, glRenderStream binding)
{
this.binding = binding;
_bufferHandle = glFunc.GenBuffers(n);
}
public override sealed void Bind(int index)
{
glFunc.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
}
public void SetValue<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct, IConvertible
{
glFunc.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferData(BufferType.ElementArrayBuffer, bufferArray, usage);
}
public void SetValue<T>(int index, ReadOnlySpan<T> bufferSpan, BufferUsage usage)
where T : struct, IConvertible
{
glFunc.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferData(BufferType.ElementArrayBuffer, bufferSpan, usage);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
glFunc.DeleteBuffers(_bufferHandle);
_bufferHandle.Release();
}
}
}
}
@@ -1,60 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
{
#pragma warning disable CA1008
#pragma warning disable CA1028
public enum FrameBufferTarget:uint
#pragma warning restore CA1028
#pragma warning restore CA1008
{
Read = GLconst.READ_FRAMEBUFFER,
All = GLconst.FRAMEBUFFER,
Draw = GLconst.DRAW_FRAMEBUFFER,
}
public class FrameBuffer : BufferObjectBase
{
internal unsafe FrameBuffer(int count, glRenderStream contextBinding)
{
binding = contextBinding;
_bufferHandle = new glHandleSet(count);
((GLcontext*)binding.ContextHandle)->glGenFramebuffers((uint)count,_bufferHandle.handle);
}
/// <summary>
/// Bind the frame buffer object with name frame buffer to the frame buffer target specified by target.
/// <see langword="FrameBufferTarget.All"/> will be set as default target.
/// </summary>
/// <param name="index">Index of object to be binded in handle set</param>
public unsafe override void Bind(int index)
{
glFunc.BindFrameBuffer(FrameBufferTarget.All,_bufferHandle[index]);
}
public static void BindNull()
{
glFunc.BindFrameBuffer(FrameBufferTarget.All,glHandle.Zero);
}
/// <summary>
/// Bind the frame buffer object with name frame buffer to the frame buffer target specified by target.
/// Target of this frame buffer should be set manually.
/// </summary>
/// <param name="target">The frame buffer target of the binding operation.</param>
/// <param name="index">Index of object to be binded in handle set</param>
public unsafe void Bind(FrameBufferTarget target, int index)
{
((GLcontext*)binding.ContextHandle)->glBindFramebuffer((uint)target, _bufferHandle[index].Value);
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
}
}
@@ -1,38 +0,0 @@
using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
namespace StgSharp.Graphics.GL
{
public class RenderBuffer : BufferObjectBase
{
public RenderBuffer(int count, glRenderStream binding)
{
this.binding = binding;
_bufferHandle = glFunc.GenRenderBuffer(count);
}
public override void Bind(int index)
{
glFunc.BindRenderBuffer(this[index]);
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
public void Store(RenderBufferInternalFormat format, (int width,int height) size)
{
if (size.width > binding.Width || size.height>binding.Height)
{
StgSharp.LogWarning("FrameBuffer is larger than current canvas binding");
}
}
}
}
@@ -1,156 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="texture.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
{
public unsafe class TextureGL
{
internal static bool[] unitActivated = new bool[16];
private IntPtr binding;
internal glHandleSet _textureHandle;
internal Image[] sourceList;
public glHandle this[int index]
{
get => _textureHandle[index];
}
internal TextureGL(int n, glRenderStream binding)
{
sourceList = new Image[n];
this.binding = binding.ContextHandle;
_textureHandle = glFunc.GenTextures(n);
}
public static void Activate(TextureUnit unit)
{
glFunc.ActiveTexture((uint)unit);
}
public void Bind2D(int index)
{
glFunc.BindTexture(GLconst.TEXTURE_2D, _textureHandle[index]);
}
/// <summary>
/// Load an <see cref="Image"/> to certain texture.
/// </summary>
/// <param name="index"> </param>
/// <param name="i"> </param>
public unsafe void LoadTexture(int index, Image i)
{
sourceList[index] = i;
glArrayHandle handle = sourceList[index].GetArrayHandle();
glFunc.TextureImage2d(
Texture2DTarget.Texture2D, 0, (uint)i.Channel,
(uint)sourceList[index].Width, (uint)sourceList[index].Height,
(uint)i.Channel, ImageChannelLayout.Byte,
pixelArrayHandle: handle
);
handle.Release();
}
#region texture setting
public void Set2dFilterProperty(
Filter onMinify, Filter onMagnify)
{
glFunc.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, (int)onMinify);
glFunc.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, (int)onMagnify);
}
public void Set2dWrapProperty(
Wrap onHorizontial, Wrap onVertical)
{
glFunc.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, (int)onHorizontial);
glFunc.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, (int)onVertical);
}
#endregion texture setting
}
#pragma warning disable CA1008
public enum Filter
#pragma warning restore CA1008
{
Nearest = GLconst.NEAREST,
Linear = GLconst.LINEAR,
NearestLinearMipmap = GLconst.NEAREST_MIPMAP_LINEAR,
LinearLinearMipmap = GLconst.LINEAR_MIPMAP_LINEAR,
NearestNearestMipmap = GLconst.NEAREST_MIPMAP_NEAREST,
LinearNearestMipmap = GLconst.LINEAR_MIPMAP_NEAREST,
}
#pragma warning disable CA1008
public enum TextureUnit
#pragma warning restore CA1008
{
Unit0 = GLconst.TEXTURE0,
Unit1 = GLconst.TEXTURE1,
Unit2 = GLconst.TEXTURE2,
Unit3 = GLconst.TEXTURE3,
Unit4 = GLconst.TEXTURE4,
Unit5 = GLconst.TEXTURE5,
Unit6 = GLconst.TEXTURE6,
Unit7 = GLconst.TEXTURE7,
Unit8 = GLconst.TEXTURE8,
Unit9 = GLconst.TEXTURE9,
Unit10 = GLconst.TEXTURE10,
Unit11 = GLconst.TEXTURE11,
Unit12 = GLconst.TEXTURE12,
Unit13 = GLconst.TEXTURE13,
Unit14 = GLconst.TEXTURE14,
Unit15 = GLconst.TEXTURE15,
}
#pragma warning disable CA1008
public enum Wrap
#pragma warning restore CA1008
{
Repeat = GLconst.REPEAT,
MirroredRepeat = GLconst.MIRRORED_REPEAT,
ClampToEdge = GLconst.CLAMP_TO_EDGE,
ClampToBorder = GLconst.CLAMP_TO_BORDER,
}
}
@@ -1,155 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="VBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.GL;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.GL
{
public unsafe class VertexBuffer : BufferObjectBase
{
internal VertexBuffer(int n, glRenderStream binding)
{
this.binding = binding;
_bufferHandle = glFunc.GenBuffers(n);
}
public override sealed void Bind(int index)
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
}
/// <summary>
/// Set data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="bufferData">Data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteMatrixData<T>(int index, T bufferData, BufferUsage usage)
where T : struct, IMat
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferData(BufferType.ArrayBuffer, bufferData, usage);
}
/// <summary>
/// Set data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="bufferArray">Data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteScalerData<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferData(BufferType.ArrayBuffer, bufferArray, usage);
}
/// <summary>
/// Set data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="scalerSpan">A <see cref="Span{T}"/> of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteScalerData<T>(int index, ReadOnlySpan<T> scalerSpan, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferData(BufferType.ArrayBuffer, scalerSpan, usage);
}
/// <summary>
/// Set data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="vectorSpan">A <see cref="Span{T}"/> of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteVectorData<T>(int index, ReadOnlySpan<T> vectorSpan, BufferUsage usage) where T : struct, IVector
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferVectorData(BufferType.ArrayBuffer, vectorSpan, usage);
}
/// <summary>
/// Set data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="vectorArray">A array of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteVectorData<T>(int index, T[] vectorArray, BufferUsage usage) where T : struct, IVector
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferVectorData(BufferType.ArrayBuffer, vectorArray, usage);
}
/// <summary>
///
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unbind()
{
glFunc.BindBuffer(BufferType.ArrayBuffer, glHandle.Zero);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
glFunc.DeleteBuffers(_bufferHandle);
_bufferHandle.Release();
}
}
}
}
-362
View File
@@ -1,362 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLhandle.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics
{
/// <summary>
/// A handle to an OpenGL object,
/// must be indexed from a <see cref="glHandleSet"/>.
/// Direct call will cause <see langword="InvalidOperationException"/>
/// </summary>
public unsafe class glHandle: IDisposable
{
private static uint* zeroHandle = (uint*)Marshal.AllocHGlobal(Marshal.SizeOf<uint>());
internal uint* source;
internal uint* valuePtr;
private glHandle(IntPtr handle)
{
this.valuePtr = (uint*)handle;
source = (uint*)0;
}
private glHandle(uint value)
{
source = (uint*)0;
valuePtr = (uint*)Marshal.AllocHGlobal(sizeof(uint));
*valuePtr = value;
}
internal glHandle(uint* val, glHandleSet set)
{
source = set!=null ? set!.handle:(uint*)0;
valuePtr = val;
}
[Obsolete("Cannot init instance of this type", true)]
public glHandle()
{
}
public IntPtr Handle
{
get=> (IntPtr)valuePtr;
}
public bool IsIsolated
{
get => source == (uint*)0;
}
public uint Value
{
get => *valuePtr;
set => *valuePtr = value;
}
public static glHandle ZeroHandle => FromPtr(IntPtr.Zero);
public static glHandle Zero => Alloc(0);
public static glHandle Alloc(uint value)
{
return new glHandle(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glHandle FromPtr(IntPtr p)
{
return new glHandle(p);
}
~glHandle()
{
if (valuePtr != zeroHandle && IsIsolated)
{
Marshal.FreeHGlobal((IntPtr)valuePtr);
}
}
protected virtual void Dispose(bool disposing)
{
if (IsIsolated)
{
GCHandle.FromIntPtr((IntPtr)valuePtr).Free();
if (disposing)
{
}
}
}
//
// ~glHandle()
// {
// Dispose(disposing: false);
// }
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
public unsafe class glSHandle
{
private static int* zeroHandle = (int*)Marshal.AllocHGlobal(Marshal.SizeOf<int>());
internal int* source;
internal int* valuePtr;
private glSHandle(IntPtr handle)
{
this.valuePtr = (int*)handle;
source = (int*)0;
}
private glSHandle(int value)
{
source = (int*)0;
valuePtr = (int*)Marshal.AllocHGlobal(sizeof(int));
*valuePtr = value;
}
internal glSHandle(int* val, glHandleSet set)
{
source = set != null ? (int*)set!.handle : (int*)0;
valuePtr = val;
}
[Obsolete("Cannot init instance of this type", true)]
public glSHandle()
{
}
public IntPtr Handle
{
get => (IntPtr)valuePtr;
}
public bool IsIsolated
{
get => source == (uint*)0;
}
public int Value
{
get => *valuePtr;
set => *valuePtr = value;
}
public static glSHandle Zero => Alloc(0);
public static glSHandle Alloc(int value)
{
return new glSHandle(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glSHandle FromPtr(IntPtr p)
{
return new glSHandle(p);
}
~glSHandle()
{
if (valuePtr != zeroHandle && IsIsolated)
{
Marshal.FreeHGlobal((IntPtr)valuePtr);
}
}
}
public unsafe class glArrayHandle
{
internal readonly Array a;
internal GCHandle handle;
private bool disposedValue;
internal glArrayHandle(Array array)
{
this.a = array;
handle = GCHandle.Alloc(array, GCHandleType.Pinned);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IntPtr AddressOfArray()
{
if (handle != default)
{
return handle.AddrOfPinnedObject();
}
else
{
throw new InvalidOperationException();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glArrayHandle Alloc<T>(T[] array) where T : struct
{
return new glArrayHandle(array);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glArrayHandle CopyAlloc<T>(T[] array) where T : struct
{
Array copy = new T[array.Length];
array.CopyTo(copy, 0);
return new glArrayHandle(copy);
}
public void Release()
{
handle.Free();
handle = default;
}
}
/// <summary>
/// A handle to an OpenGL object.
/// </summary>
public unsafe class glHandleSet
{
private readonly uint[] _value;
internal uint* handle;
internal int length;
public glHandleSet(int count)
{
_value = new uint[count];
length = count;
handle = (uint*)GCHandle.Alloc(_value, GCHandleType.Pinned).AddrOfPinnedObject();
}
public IntPtr Handle
{
get => (IntPtr)handle;
}
public glHandle this[int index]
{
get
{
if (index > length)
{
throw new IndexOutOfRangeException();
}
return new glHandle(handle + index, this);
}
}
public glSHandle this[uint index]
{
get
{
if (index > length)
{
throw new IndexOutOfRangeException();
}
return new glSHandle(((int*)handle) + index, this);
}
}
public static void Copy(in glHandleSet source, glHandleSet target)
{
if ((source == null) || (target == null))
{
throw new NullReferenceException();
}
if (source.length != target.length)
{
throw new Exception($"Lengths of {nameof(source)} and {nameof(target)} are not equal.");
}
for (int i = 0; i < source.length; i++)
{
target._value[i] = source._value[i];
}
}
public void Pin()
{
if (_value == null)
{
return;
}
handle = (uint*)GCHandle.Alloc(_value, GCHandleType.Pinned).AddrOfPinnedObject();
}
/// <summary>
/// Release all resource in this handle.
/// This will release all resource in this <see cref="glHandle"/>.
/// This <see langword="glHandle"/> will be not usable.
/// </summary>
public void Release()
{
if (_value == null)
{
return;
}
else
{
GCHandle.FromIntPtr((IntPtr)handle).Free();
handle = (uint*)IntPtr.Zero;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetValue(int index, uint value)
{
_value[index] = value;
}
~glHandleSet()
{
}
}
}
-621
View File
@@ -1,621 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLpack.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp
{
internal static unsafe partial class InternalIO
{
[DllImport(SSC_libName, EntryPoint = "glCheckShaderStat",
CallingConvention = CallingConvention.Cdecl)]
#pragma warning disable CA5392
internal static extern int glCheckShaderStatus(ref GLcontext context, uint shaderHandle, int key, ref IntPtr logPtr);
#pragma warning restore CA5392
}
}
namespace StgSharp.Graphics.GL
{
internal static unsafe partial class glFunc
{
private static GLcontext* context;
public static IntPtr CurrentContextHandle
{
get { return (IntPtr)context; }
set { context = (GLcontext*)value; }
}
private static ref GLcontext Context
{
get
{
#if DEBUG
if ((IntPtr)context==IntPtr.Zero)
{
throw new NullReferenceException();
}
#endif
return ref (*context);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ActiveTexture(uint type)
{
Context.glActiveTexture(type);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AttachShader(glHandle program, glHandle shader)
{
Context.glAttachShader(program.Value, shader.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindBuffer(BufferType bufferType, glHandle handle)
{
Context.glBindBuffer((uint)bufferType, handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void GetTextureImage<T>(Texture2DTarget target, int level, ImageChannel channel, ImageChannelLayout channelLayout, ref T[] dataStream)where T: struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
#pragma warning disable CS8500
fixed (T* tptr = dataStream)
{
Context.glGetTexImage((uint)target, level, (uint)channel, (uint)channelLayout, tptr);
}
#pragma warning restore CS8500
}
/// <summary>
/// Bind a frame buffer to a frame buffer target
/// Same function as <see href="https://docs.gl/gl3/glBindFramebuffer">glBindFramebuffer</see>.
/// </summary>
/// <param name="target"> The frame buffer target of the binding operation.</param>
/// <param name="handle"> The handle of the frame buffer object to bind.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindFrameBuffer(FrameBufferTarget target, glHandle handle)
{
Context.glBindFramebuffer((uint)target, handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindRenderBuffer(glHandle handle)
{
Context.glBindRenderbuffer(GLconst.RENDERBUFFER, handle.Value);
}
public static void WaitAccomplishment()
{
Context.glFinish();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindTexture(uint type, glHandle texture)
{
Context.glBindTexture(type, texture.Value);
}
public static unsafe int GetMaskInteger(uint statusCode)
{
int ret = 0;
Context.glGetIntegerv(statusCode,&ret);
return ret;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindVertexArray(glHandle handle)
{
Context.glBindVertexArray(handle.Value);
}
public static void RereadImage(
this Image i, (int X, int Y) beginPosition, FrameBufferChannel format, ImageChannelLayout dataType)
{
glArrayHandle handle = i.GetArrayHandle();
Context.glReadPixels(
beginPosition.X, beginPosition.Y, i.Width, i.Height, (uint)format, (uint)dataType, (byte*)handle.AddressOfArray()
);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FrameBufferTexture2d(FrameBufferTarget target, uint attachment, Texture2DTarget texTarget,glHandle textureHandle ,int level)
{
Context.glFramebufferTexture2D(
(uint)target, attachment, (uint)texTarget,textureHandle.Value, level
);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ReadPixels(
(int X, int Y) beginPosition, (int width, int height) size, FrameBufferChannel format, ImageChannelLayout dataType, ref byte[] stream
)
{
fixed (byte* bptr = stream)
{
Context.glReadPixels(
beginPosition.X, beginPosition.Y,
size.width, size.height, (uint)format, (uint)dataType, bptr);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Clear(MaskBufferBit mask)
{
Context.glClear((uint)mask);
}
public static void CombineFrameBufferRenderBuffer(glHandle fboHandle, glHandle rboHandle)
{
Context.glFramebufferRenderbuffer(GLconst.FRAMEBUFFER,fboHandle.Value,GLconst.RENDERBUFFER, rboHandle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void ClearColor(float R, float G, float B, float A)
{
Context.glClearColor(R, G, B, A);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void ClearGraphicError()
{
while (Context.glGetError() != 0) { }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CompileShader(glHandle shaderhandle)
{
Context.glCompileShader(shaderhandle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandle CreateGraphicProgram()
{
return glHandle.Alloc(Context.glCreateProgram());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glHandle CreateProgram()
{
return glHandle.Alloc(Context.glCreateProgram());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandleSet CreateProgram(int count)
{
glHandleSet h = new glHandleSet(count);
for (int i = 0; i < count; i++)
{
h.SetValue(i, Context.glCreateProgram());
}
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glHandleSet CreateShaderSet(int count, ShaderType type)
{
glHandleSet ret = new glHandleSet(count);
uint t = (uint)type;
for (int i = 0; i < count; i++)
{
uint id = Context.glCreateShader(t);
if (id == 0)
{
uint error = Context.glGetError();
InternalIO.InternalWriteLog($"Failed in creating shader: {error}", LogType.Error);
throw new Exception();
}
ret.SetValue(i, id);
}
return ret;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DeleteBuffer(glHandle handle)
{
Context.glDeleteBuffers(1, (uint*)handle.Handle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DeleteBuffers(glHandleSet handle)
{
Context.glDeleteBuffers(handle.length, (uint*)handle.Handle);
handle.Release();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DeleteVertexArrays(glHandleSet arrays)
{
Context.glDeleteVertexArrays(arrays.length, (uint*)arrays.Handle);
arrays.Release();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DrawElements(GeometryType mode, uint count, TypeCode type, IntPtr ptr)
{
uint a;
switch (type)
{
case TypeCode.UInt32:
a = GLconst.UNSIGNED_INT;
break;
case TypeCode.UInt16:
a = GLconst.UNSIGNED_SHORT;
break;
case TypeCode.Byte:
a = GLconst.UNSIGNED_BYTE;
break;
default:
InternalIO.InternalWriteLog(
$"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}",
LogType.Error);
return;
}
Context.glDrawElements((uint)mode, count, a, (void*)ptr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DrawElementsInstanced(
GeometryType mode, uint count, TypeCode type, IntPtr ptr, uint amount
)
{
uint a;
switch (type)
{
case TypeCode.UInt32:
a = GLconst.UNSIGNED_INT;
break;
case TypeCode.UInt16:
a = GLconst.UNSIGNED_SHORT;
break;
case TypeCode.Byte:
a = GLconst.UNSIGNED_BYTE;
break;
default:
InternalIO.InternalWriteLog(
$"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}",
LogType.Error);
return;
}
Context.glDrawElementsInstanced((uint)mode, count, a, (void*)ptr, amount);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Enable(GLOperation operation)
{
Context.glEnable((uint)operation);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandleSet GenBuffers(int count)
{
glHandleSet h = new glHandleSet(count);
Context.glGenBuffers(count, (uint*)h.Handle);
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandleSet GenRenderBuffer(int count)
{
glHandleSet h = new glHandleSet(count);
Context.glGenRenderbuffers(count, (uint*)h.Handle);
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandleSet GenTextures(int count)
{
glHandleSet h = new glHandleSet(count);
Context.glGenTextures(count, (uint*)h.Handle);
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetRenderBufferStorage(RenderBufferInternalFormat internalFormat ,(int width, int height) size)
{
Context.glRenderbufferStorage(
GLconst.RENDERBUFFER, (uint)internalFormat,size.width,size.height
);
}
public static unsafe glHandleSet GenVertexArrays(int count)
{
glHandleSet h = new glHandleSet(count);
Context.glGenVertexArrays(count, (uint*)h.Handle);
return h;
}
public static string GetShaderStatus(Shader s, int index, int key)
{
IntPtr sptr = IntPtr.Zero;
if (InternalIO.glCheckShaderStatus(ref Context, s.handle[index].Value, key, ref sptr) == 0)
{
return Marshal.PtrToStringAnsi(sptr);
}
return string.Empty;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glSHandle GetUniformLocation(glHandle program, string name)
{
byte[] code = Encoding.UTF8.GetBytes(name);
fixed (byte* ptr = code)
{
int ret = Context.glGetUniformLocation(program.Value, ptr);
#if DEBUG
if (ret == (int)(GLconst.INVALID_OPERATION) ||
ret == (int)(GLconst.INVALID_VALUE))
{
throw new InvalidOperationException();
}
if (ret == -1 )
{
throw new UniformEmptyReferenceException(nameof(program), name);
}
#endif
return glSHandle.Alloc(ret);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void LoadShaderSource(glHandle shaderHandle, byte[] codeStream)
{
fixed (byte* streamPtr = codeStream)
{
Context.glShaderSource(shaderHandle.Value, 1, &streamPtr, (void*)0);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, T bufferData, BufferUsage usage)
where T : struct
{
int size = Marshal.SizeOf<T>();
#pragma warning disable CS8500
T* p = &bufferData;
#pragma warning restore CS8500
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)p,
(uint)usage);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = bufferArray)
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, ReadOnlySpan<T> bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = bufferArray)
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, Span<T> bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = &bufferArray.GetPinnableReference())
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferVectorData<T>(BufferType bufferType, ReadOnlySpan<T> bufferArray, BufferUsage usage)
where T : struct, IVector
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = &bufferArray.GetPinnableReference())
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferVectorData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
where T : struct, IVector
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = bufferArray)
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetVertexAttribute(uint index, int size, TypeCode t, bool normalized, uint stride, int pointer)
{
uint type = InternalIO.GLtype[t];
Context.glVertexAttribPointer(index, size, type, normalized ? 1 : 0, stride, (void*)pointer);
Context.glEnableVertexAttribArray(index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void TextureImage2d(Texture2DTarget target, int level, uint internalformat, uint width, uint height,
uint format, ImageChannelLayout type, glHandle pixels)
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, pixels.valuePtr
);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void TextureImage2d(Texture2DTarget target, int level, uint internalformat, uint width, uint height,
uint format, ImageChannelLayout type, glArrayHandle pixelArrayHandle)
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, (void*)pixelArrayHandle.handle.AddrOfPinnedObject()
);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void TextureParameter(int target, uint pname, int param)
{
Context.glTexParameteri((uint)target, pname, param);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void UseProgram(glHandle program)
{
Context.glUseProgram(program.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void VertexAttributeDivisor(uint layoutIndex, uint divisor)
{
Context.glVertexAttribDivisor(layoutIndex, divisor);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Viewport(int x, int y, uint width, uint height)
{
Context.glViewport(x, y, width, height);
}
}
}
@@ -1,102 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLresourceGenrator.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
{
public partial class glRenderStream
{
/// <summary>
/// Create a set of <see cref="ElementBuffer"/>.
/// </summary>
/// <param name="count">Amount of EBO to be created.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected ElementBuffer CreateElementBuffer(int count)
{
return new ElementBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected RenderBuffer CreateRenderBuffer(int count)
{
return new RenderBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected FrameBuffer CreateFrameBuffer(int count)
{
return new FrameBuffer(count, this);
}
/// <summary>
/// Create a sets of <see cref="TextureGL"/>
/// </summary>
/// <param name="count">Amount of textures to be created.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected TextureGL CreateTexture(int count)
{
return new TextureGL(count, this);
}
/// <summary>
/// Create a set of <see cref="VertexArray"/>.
/// </summary>
/// <param name="count">Amount of VAO to be created.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected VertexArray CreateVertexArray(int count)
{
return new VertexArray(count, this);
}
/// <summary>
/// Create a set of <see cref="VertexBuffer"/>.
/// </summary>
/// <param name="count">Amount of Object to be created.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected VertexBuffer CreateVertexBuffer(int count)
{
return new VertexBuffer(count, this);
}
}
}
@@ -1,35 +0,0 @@
using StgSharp.Graphics.GL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.ShaderEdit
{
public interface IglConvertable
{
/// <summary>
///
/// </summary>
public void SetAllUniforms();
/// <summary>
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
/// <summary>
///
/// </summary>
public void DisplayGLtypeDefinition();
/// <summary>
///
/// </summary>
/// <returns></returns>
public ShaderStruct GetConvertedGLtype();
}
}
@@ -1,264 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Shader.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp;
using StgSharp.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml.Linq;
namespace StgSharp.Graphics.GL
{
public abstract partial class glRenderStream : RenderStream
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override Shader CreateShaderSegment(ShaderType type, int count)
{
return new Shader( glFunc.CreateShaderSet(count, type), type);
}
/// <summary>
/// Create an instance of <see cref="Shader"/> program
/// </summary>
/// <returns>New instance of <see cref="Shader"/> instance. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override ShaderProgram CreateShaderProgram()
{
return new ShaderProgram(this);
}
}
public class Shader : ISSDSerializable
{
private readonly IntPtr context;
internal readonly glHandleSet handle;
public readonly ShaderType type;
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.Shader;
internal unsafe Shader(glHandleSet handle, ShaderType usage)
{
this.handle = handle;
context = glFunc.CurrentContextHandle;
type = usage;
}
/// <summary>
/// Attach one shader code to a shader program.
/// </summary>
/// <param name="target">Shader program to attach</param>
/// <param name="index">Index of shader code in current shader code set.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AttachTo(int index, ShaderProgram target)
{
glFunc.AttachShader(target.handle, handle[index]);
}
public static byte[] FromCodeFile(string fileRoute)
{
string str = File.ReadAllText(fileRoute);
if (string.IsNullOrEmpty(str))
{
throw new InvalidOperationException($"Cannot load and GLSL code from {fileRoute}");
}
return Encoding.UTF8.GetBytes(str);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, byte[] codeStream)
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
}
glFunc.LoadShaderSource(handle[index], codeStream);
glFunc.CompileShader(handle[index]);
CheckStatus(index,ShaderStatus.CompileStatus);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, string codeStream)
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
}
glFunc.LoadShaderSource(handle[index],Encoding.ASCII.GetBytes( codeStream));
glFunc.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
}
public override string ToString()
{
return $"This is a {type} shader, its shader handles are {handle.ToString()}.";
}
public byte[] GetBytes()
{
return Array.Empty<byte>();
}
public void CheckStatus(int index, ShaderStatus status)
{
string log = glFunc.GetShaderStatus(this,index, (int)status);
if (!string.IsNullOrEmpty(log))
{
throw new Exception($"Shader Error \t{status}\n" + log);
}
}
public byte[] GetBytes(out int length)
{
throw new NotImplementedException();
}
public void FromBytes(byte[] stream)
{
throw new NotImplementedException();
}
}
public enum ShaderStatus : int
{
CompileStatus = GLconst.COMPILE_STATUS,
}
public class ShaderProgram
{
private readonly IntPtr binding;
internal readonly glHandle handle;
/// <summary>
/// Init a program with no shader attached.
/// </summary>
internal unsafe ShaderProgram(glRenderStream binding)
{
this.binding = binding.ContextHandle;
handle = glFunc.CreateProgram();
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Uniform<T> GetUniform<T>(string name) where T : struct
{
return new Uniform<T>(this, name, binding);
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <returns></returns>
public unsafe Uniform<T, U> GetUniform<T, U>(string name)
where T : struct
where U : struct
{
return new Uniform<T, U>(this, name, binding);
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <returns></returns>
public unsafe Uniform<T, U, V> GetUniform<T, U, V>(string name)
where T : struct
where U : struct
where V : struct
{
return new Uniform<T, U, V>(this, name);
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <returns></returns>
public unsafe Uniform<T, U, V, W> GetUniform<T, U, V, W>(string name)
where T : struct
where U : struct
where V : struct
where W : struct
{
return new Uniform<T, U, V, W>(this, name);
}
/// <summary>
/// Link the shader to current viewPortDisplay.
/// </summary>
public unsafe void Link()
{
if (InternalIO.InternalLinkShaderProgram((GLcontext*)this.binding, handle.Value) == 0)
{
IntPtr logPtr = InternalIO.InternalReadSSCLog();
try
{
byte[] logByte = new byte[512];
Marshal.Copy(logPtr, logByte, 0, 512);
string log = Encoding.UTF8.GetString(logByte);
log = log.Replace("\0", string.Empty);
InternalIO.InternalWriteLog(log, LogType.Error);
}
catch (Exception ex)
{
InternalIO.InternalWriteLog(ex.Message, LogType.Error);
}
}
}
/// <summary>
/// Let the current viewPortDisplay use this shader.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Use()
{
glFunc.UseProgram(handle);
}
~ShaderProgram()
{
//handle.Dispose();
}
}
}
@@ -1,257 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Uniform.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.GL
{
public class Uniform
{
protected IntPtr binding;
internal glSHandle id;
public glSHandle Handle
{
get => id;
}
}
public sealed class Uniform<T> : Uniform
where T : struct
{
internal unsafe Uniform(glSHandle id)
{
this.id = id;
}
internal unsafe Uniform(
ShaderProgram program, string name, glRenderStream binding)
{
this.binding = binding.ContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name, IntPtr binding)
{
this.binding = binding;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal Uniform()
{
}
internal static Uniform<T> FromHandle(glSHandle handle)
{
return new Uniform<T>() { id = handle };
}
}
public sealed class Uniform<T, U>: Uniform
where T : struct
where U : struct
{
internal unsafe Uniform(glSHandle id)
{
this.id = id;
}
internal unsafe Uniform(
ShaderProgram program, string name, glRenderStream binding)
{
this.binding = binding.ContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name, IntPtr binding)
{
this.binding = binding;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal Uniform()
{
}
internal static Uniform<T,U> FromHandle(glSHandle handle)
{
return new Uniform<T, U>() { id = handle };
}
}
public sealed class Uniform<T, U, V>:Uniform
where T : struct
where U : struct
where V : struct
{
internal unsafe Uniform(glSHandle id)
{
this.id = id;
}
internal unsafe Uniform(
ShaderProgram program, string name)
{
this.binding = glFunc.CurrentContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
public unsafe Uniform(ShaderProgram program, string name, glRenderStream binding)
{
this.binding = binding.ContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal Uniform()
{
}
internal static Uniform<T,U,V> FromHandle(glSHandle handle)
{
return new Uniform<T, U, V>() { id = handle };
}
}
public sealed class Uniform<T, U, V, W>:Uniform
where T : struct
where U : struct
where V : struct
where W : struct
{
internal unsafe Uniform(glSHandle id)
{
this.id = id;
}
internal unsafe Uniform(ShaderProgram program, string name, glRenderStream binding)
{
this.binding = binding.ContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name)
{
this.binding = glFunc.CurrentContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal Uniform()
{
}
internal static Uniform<T, U, V, W> FromHandle(glSHandle handle)
{
return new Uniform<T, U, V, W>() { id = handle };
}
}
internal partial class glFunc
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static void SetUniformValue
(Uniform<Matrix44> uniform, Matrix44 mat)
{
Matrix44 temp = mat;
Context.glUniformMatrix4fv(uniform.id.Value, 1, false, (float*)&temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static void SetUniformValue(Uniform<float, float, float, float> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.Value , 4, &temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static void SetUniformValue(Uniform<vec4d> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.Value , 4, &temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<float> uniform, float v0)
{
Context.glUniform1f(uniform.id.Value , v0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<int> uniform, int i0)
{
Context.glUniform1i(uniform.id.Value , i0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<float, float> uniform, float v0, float v1)
{
Context.glUniform2f(uniform.id.Value , v0, v1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<float, float, float> uniform, float v0, float v1, float v2)
{
Context.glUniform3f(uniform.id.Value , v0, v1, v2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<float, float, float, float> uniform, float v0, float v1, float v2, float v3)
{
Context.glUniform4f(uniform.id.Value , v0, v1, v2, v3);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,689 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glApiManagerConst.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics.GL
{
public static partial class glManager
{
#region coreVersion
private static bool core10 = false;
private static bool core11 = false;
private static bool core12 = false;
private static bool core13 = false;
private static bool core14 = false;
private static bool core15 = false;
private static bool core20 = false;
private static bool core21 = false;
private static bool core30 = false;
private static bool core31 = false;
private static bool core32 = false;
private static bool core33 = false;
private static bool core40 = false;
private static bool core41 = false;
private static bool core42 = false;
private static bool core43 = false;
private static bool core44 = false;
private static bool core45 = false;
private static bool core46 = false;
#endregion
#region extension
private static bool _3DFX_tbuffer;
private static bool _3DFX_texture_compression_FXT1;
private static bool _4DFX_multisample;
private static bool AMD_blend_minmax_factor;
private static bool AMD_conservative_depth;
private static bool AMD_debug_output;
private static bool AMD_depth_clamp_separate;
private static bool AMD_draw_buffers_blend;
private static bool AMD_framebuffer_multisample_advanced;
private static bool AMD_framebuffer_sample_positions;
private static bool AMD_gcn_shader;
private static bool AMD_gpu_shader_half_float;
private static bool AMD_gpu_shader_int16;
private static bool AMD_gpu_shader_int64;
private static bool AMD_interleaved_elements;
private static bool AMD_multi_draw_indirect;
private static bool AMD_name_gen_delete;
private static bool AMD_occlusion_query_event;
private static bool AMD_performance_monitor;
private static bool AMD_pinned_memory;
private static bool AMD_query_buffer_object;
private static bool AMD_sample_positions;
private static bool AMD_seamless_cubemap_per_texture;
private static bool AMD_shader_atomic_counter_ops;
private static bool AMD_shader_ballot;
private static bool AMD_shader_explicit_vertex_parameter;
private static bool AMD_shader_gpu_shader_half_float_fetch;
private static bool AMD_shader_image_load_store_lod;
private static bool AMD_shader_stencil_export;
private static bool AMD_shader_trinary_minmax;
private static bool AMD_sparse_texture;
private static bool AMD_stencil_operation_extended;
private static bool AMD_texture_gather_bias_lod;
private static bool AMD_texture_texture4;
private static bool AMD_transform_feedback3_lines_triangles;
private static bool AMD_transform_feedback4;
private static bool AMD_vertex_shader_layer;
private static bool AMD_vertex_shader_tessellator;
private static bool AMD_vertex_shader_viewport_index;
private static bool APPLE_aux_depth_stencil;
private static bool APPLE_client_storage;
private static bool APPLE_element_array;
private static bool APPLE_fence;
private static bool APPLE_float_pixels;
private static bool APPLE_flush_buffer_range;
private static bool APPLE_object_purgeable;
private static bool APPLE_rgb_422;
private static bool APPLE_row_bytes;
private static bool APPLE_specular_vector;
private static bool APPLE_texture_range;
private static bool APPLE_transform_hint;
private static bool APPLE_vertex_array_object;
private static bool APPLE_vertex_array_range;
private static bool APPLE_vertex_program_evaluators;
private static bool APPLE_ycbcr_422;
private static bool ARB_arrays_of_arrays;
private static bool ARB_base_instance;
private static bool ARB_bindless_texture;
private static bool ARB_blend_func_extended;
private static bool ARB_buffer_storage;
private static bool ARB_cl_event;
private static bool ARB_clear_buffer_object;
private static bool ARB_clear_texture;
private static bool ARB_clip_control;
private static bool ARB_color_buffer_float;
private static bool ARB_compatibility;
private static bool ARB_compressed_texture_pixel_storage;
private static bool ARB_compute_shader;
private static bool ARB_compute_variable_group_size;
private static bool ARB_conditional_render_inverted;
private static bool ARB_conservative_depth;
private static bool ARB_copy_buffer;
private static bool ARB_copy_image;
private static bool ARB_cull_distance;
private static bool ARB_debug_output;
private static bool ARB_depth_buffer_float;
private static bool ARB_depth_clamp;
private static bool ARB_depth_texture;
private static bool ARB_derivative_control;
private static bool ARB_direct_state_access;
private static bool ARB_draw_buffers;
private static bool ARB_draw_buffers_blend;
private static bool ARB_draw_elements_base_vertex;
private static bool ARB_draw_indirect;
private static bool ARB_draw_instanced;
private static bool ARB_enhanced_layouts;
private static bool ARB_ES2_compatibility;
private static bool ARB_ES3_1_compatibility;
private static bool ARB_ES3_2_compatibility;
private static bool ARB_ES3_compatibility;
private static bool ARB_explicit_attrib_location;
private static bool ARB_explicit_uniform_location;
private static bool ARB_fragment_coord_conventions;
private static bool ARB_fragment_layer_viewport;
private static bool ARB_fragment_program;
private static bool ARB_fragment_program_shadow;
private static bool ARB_fragment_shader;
private static bool ARB_fragment_shader_interlock;
private static bool ARB_framebuffer_no_attachments;
private static bool ARB_framebuffer_object;
private static bool ARB_framebuffer_sRGB;
private static bool ARB_geometry_shader4;
private static bool ARB_get_program_binary;
private static bool ARB_get_texture_sub_image;
private static bool ARB_gl_spirv;
private static bool ARB_gpu_shader_fp64;
private static bool ARB_gpu_shader_int64;
private static bool ARB_gpu_shader5;
private static bool ARB_half_float_pixel;
private static bool ARB_half_float_vertex;
private static bool ARB_imaging;
private static bool ARB_indirect_parameters;
private static bool ARB_instanced_arrays;
private static bool ARB_internalformat_query;
private static bool ARB_internalformat_query2;
private static bool ARB_invalidate_subdata;
private static bool ARB_map_buffer_alignment;
private static bool ARB_map_buffer_range;
private static bool ARB_matrix_palette;
private static bool ARB_multi_bind;
private static bool ARB_multi_draw_indirect;
private static bool ARB_multisample;
private static bool ARB_multitexture;
private static bool ARB_occlusion_query;
private static bool ARB_occlusion_query2;
private static bool ARB_parallel_shader_compile;
private static bool ARB_pipeline_statistics_query;
private static bool ARB_pixel_buffer_object;
private static bool ARB_point_parameters;
private static bool ARB_point_sprite;
private static bool ARB_polygon_offset_clamp;
private static bool ARB_post_depth_coverage;
private static bool ARB_program_interface_query;
private static bool ARB_provoking_vertex;
private static bool ARB_query_buffer_object;
private static bool ARB_robust_buffer_access_behavior;
private static bool ARB_robustness;
private static bool ARB_robustness_isolation;
private static bool ARB_sample_locations;
private static bool ARB_sample_shading;
private static bool ARB_sampler_objects;
private static bool ARB_seamless_cube_map;
private static bool ARB_seamless_cubemap_per_texture;
private static bool ARB_separate_shader_objects;
private static bool ARB_shader_atomic_counter_ops;
private static bool ARB_shader_atomic_counters;
private static bool ARB_shader_ballot;
private static bool ARB_shader_bit_encoding;
private static bool ARB_shader_clock;
private static bool ARB_shader_draw_parameters;
private static bool ARB_shader_group_vote;
private static bool ARB_shader_image_load_store;
private static bool ARB_shader_image_size;
private static bool ARB_shader_objects;
private static bool ARB_shader_precision;
private static bool ARB_shader_stencil_export;
private static bool ARB_shader_storage_buffer_object;
private static bool ARB_shader_subroutine;
private static bool ARB_shader_texture_image_samples;
private static bool ARB_shader_texture_lod;
private static bool ARB_shader_viewport_layer_array;
private static bool ARB_shading_language_100;
private static bool ARB_shading_language_420pack;
private static bool ARB_shading_language_include;
private static bool ARB_shading_language_packing;
private static bool ARB_shadow;
private static bool ARB_shadow_ambient;
private static bool ARB_sparse_buffer;
private static bool ARB_sparse_texture;
private static bool ARB_sparse_texture_clamp;
private static bool ARB_sparse_texture2;
private static bool ARB_spirv_extensions;
private static bool ARB_stencil_texturing;
private static bool ARB_sync;
private static bool ARB_tessellation_shader;
private static bool ARB_texture_barrier;
private static bool ARB_texture_border_clamp;
private static bool ARB_texture_buffer_object;
private static bool ARB_texture_buffer_object_rgb32;
private static bool ARB_texture_buffer_range;
private static bool ARB_texture_compression;
private static bool ARB_texture_compression_bptc;
private static bool ARB_texture_compression_rgtc;
private static bool ARB_texture_cube_map;
private static bool ARB_texture_cube_map_array;
private static bool ARB_texture_env_add;
private static bool ARB_texture_env_combine;
private static bool ARB_texture_env_crossbar;
private static bool ARB_texture_env_dot3;
private static bool ARB_texture_filter_anisotropic;
private static bool ARB_texture_filter_minmax;
private static bool ARB_texture_float;
private static bool ARB_texture_gather;
private static bool ARB_texture_mirror_clamp_to_edge;
private static bool ARB_texture_mirrored_repeat;
private static bool ARB_texture_multisample;
private static bool ARB_texture_non_power_of_two;
private static bool ARB_texture_query_levels;
private static bool ARB_texture_query_lod;
private static bool ARB_texture_rectangle;
private static bool ARB_texture_rg;
private static bool ARB_texture_rgb10_a2ui;
private static bool ARB_texture_stencil8;
private static bool ARB_texture_storage;
private static bool ARB_texture_storage_multisample;
private static bool ARB_texture_swizzle;
private static bool ARB_texture_view;
private static bool ARB_timer_query;
private static bool ARB_transform_feedback_instanced;
private static bool ARB_transform_feedback_overflow_query;
private static bool ARB_transform_feedback2;
private static bool ARB_transform_feedback3;
private static bool ARB_transpose_matrix;
private static bool ARB_uniform_buffer_object;
private static bool ARB_vertex_array_bgra;
private static bool ARB_vertex_array_object;
private static bool ARB_vertex_attrib_64bit;
private static bool ARB_vertex_attrib_binding;
private static bool ARB_vertex_blend;
private static bool ARB_vertex_buffer_object;
private static bool ARB_vertex_program;
private static bool ARB_vertex_shader;
private static bool ARB_vertex_type_10f_11f_11f_rev;
private static bool ARB_vertex_type_2_10_10_10_rev;
private static bool ARB_viewport_array;
private static bool ARB_window_pos;
private static bool ATI_draw_buffers;
private static bool ATI_element_array;
private static bool ATI_envmap_bumpmap;
private static bool ATI_fragment_shader;
private static bool ATI_map_object_buffer;
private static bool ATI_meminfo;
private static bool ATI_pixel_format_float;
private static bool ATI_pn_triangles;
private static bool ATI_separate_stencil;
private static bool ATI_text_fragment_shader;
private static bool ATI_texture_env_combine3;
private static bool ATI_texture_float;
private static bool ATI_texture_mirror_once;
private static bool ATI_vertex_array_object;
private static bool ATI_vertex_attrib_array_object;
private static bool ATI_vertex_streams;
private static bool EXT_422_pixels;
private static bool EXT_abgr;
private static bool EXT_bgra;
private static bool EXT_bindable_uniform;
private static bool EXT_blend_color;
private static bool EXT_blend_equation_separate;
private static bool EXT_blend_func_separate;
private static bool EXT_blend_logic_op;
private static bool EXT_blend_minmax;
private static bool EXT_blend_subtract;
private static bool EXT_clip_volume_hint;
private static bool EXT_cmyka;
private static bool EXT_color_subtable;
private static bool EXT_compiled_vertex_array;
private static bool EXT_convolution;
private static bool EXT_coordinate_frame;
private static bool EXT_copy_texture;
private static bool EXT_cull_vertex;
private static bool EXT_debug_label;
private static bool EXT_debug_marker;
private static bool EXT_depth_bounds_test;
private static bool EXT_direct_state_access;
private static bool EXT_draw_buffers2;
private static bool EXT_draw_instanced;
private static bool EXT_draw_range_elements;
private static bool EXT_EGL_image_storage;
private static bool EXT_EGL_sync;
private static bool EXT_external_buffer;
private static bool EXT_fog_coord;
private static bool EXT_framebuffer_blit;
private static bool EXT_framebuffer_blit_layers;
private static bool EXT_framebuffer_multisample;
private static bool EXT_framebuffer_multisample_blit_scaled;
private static bool EXT_framebuffer_object;
private static bool EXT_framebuffer_sRGB;
private static bool EXT_geometry_shader4;
private static bool EXT_gpu_program_parameters;
private static bool EXT_gpu_shader4;
private static bool EXT_histogram;
private static bool EXT_index_array_formats;
private static bool EXT_index_func;
private static bool EXT_index_material;
private static bool EXT_index_texture;
private static bool EXT_light_texture;
private static bool EXT_memory_object;
private static bool EXT_memory_object_fd;
private static bool EXT_memory_object_win32;
private static bool EXT_misc_attribute;
private static bool EXT_multi_draw_arrays;
private static bool EXT_multisample;
private static bool EXT_multiview_tessellation_geometry_shader;
private static bool EXT_multiview_texture_multisample;
private static bool EXT_multiview_timer_query;
private static bool EXT_packed_depth_stencil;
private static bool EXT_packed_float;
private static bool EXT_packed_pixels;
private static bool EXT_paletted_texture;
private static bool EXT_pixel_buffer_object;
private static bool EXT_pixel_transform;
private static bool EXT_pixel_transform_color_table;
private static bool EXT_point_parameters;
private static bool EXT_polygon_offset;
private static bool EXT_polygon_offset_clamp;
private static bool EXT_post_depth_coverage;
private static bool EXT_provoking_vertex;
private static bool EXT_raster_multisample;
private static bool EXT_rescale_normal;
private static bool EXT_secondary_color;
private static bool EXT_semaphore;
private static bool EXT_semaphore_fd;
private static bool EXT_semaphore_win32;
private static bool EXT_separate_shader_objects;
private static bool EXT_separate_specular_color;
private static bool EXT_shader_framebuffer_fetch;
private static bool EXT_shader_framebuffer_fetch_non_coherent;
private static bool EXT_shader_image_load_formatted;
private static bool EXT_shader_image_load_store;
private static bool EXT_shader_integer_mix;
private static bool EXT_shader_samples_identical;
private static bool EXT_shadow_funcs;
private static bool EXT_shared_texture_palette;
private static bool EXT_sparse_texture2;
private static bool EXT_stencil_clear_tag;
private static bool EXT_stencil_two_side;
private static bool EXT_stencil_wrap;
private static bool EXT_subtexture;
private static bool EXT_texture;
private static bool EXT_texture_array;
private static bool EXT_texture_buffer_object;
private static bool EXT_texture_compression_latc;
private static bool EXT_texture_compression_rgtc;
private static bool EXT_texture_compression_s3tc;
private static bool EXT_texture_cube_map;
private static bool EXT_texture_env_add;
private static bool EXT_texture_env_combine;
private static bool EXT_texture_env_dot3;
private static bool EXT_texture_filter_anisotropic;
private static bool EXT_texture_filter_minmax;
private static bool EXT_texture_integer;
private static bool EXT_texture_lod_bias;
private static bool EXT_texture_mirror_clamp;
private static bool EXT_texture_object;
private static bool EXT_texture_perturb_normal;
private static bool EXT_texture_shadow_lod;
private static bool EXT_texture_shared_exponent;
private static bool EXT_texture_snorm;
private static bool EXT_texture_sRGB;
private static bool EXT_texture_sRGB_decode;
private static bool EXT_texture_sRGB_R8;
private static bool EXT_texture_sRGB_RG8;
private static bool EXT_texture_storage;
private static bool EXT_texture_swizzle;
private static bool EXT_texture3D;
private static bool EXT_timer_query;
private static bool EXT_transform_feedback;
private static bool EXT_vertex_array;
private static bool EXT_vertex_array_bgra;
private static bool EXT_vertex_attrib_64bit;
private static bool EXT_vertex_shader;
private static bool EXT_vertex_weighting;
private static bool EXT_win32_keyed_mutex;
private static bool EXT_window_rectangles;
private static bool EXT_x11_sync_object;
private static bool GREMEDY_frame_terminator;
private static bool GREMEDY_string_marker;
private static bool HP_convolution_border_modes;
private static bool HP_image_transform;
private static bool HP_occlusion_test;
private static bool HP_texture_lighting;
private static bool IBM_cull_vertex;
private static bool IBM_multimode_draw_arrays;
private static bool IBM_rasterpos_clip;
private static bool IBM_static_data;
private static bool IBM_texture_mirrored_repeat;
private static bool IBM_vertex_array_lists;
private static bool INGR_blend_func_separate;
private static bool INGR_color_clamp;
private static bool INGR_interlace_read;
private static bool INTEL_blackhole_render;
private static bool INTEL_conservative_rasterization;
private static bool INTEL_fragment_shader_ordering;
private static bool INTEL_framebuffer_CMAA;
private static bool INTEL_map_texture;
private static bool INTEL_parallel_arrays;
private static bool INTEL_performance_query;
private static bool KHR_blend_equation_advanced;
private static bool KHR_blend_equation_advanced_coherent;
private static bool KHR_context_flush_control;
private static bool KHR_debug;
private static bool KHR_no_error;
private static bool KHR_parallel_shader_compile;
private static bool KHR_robust_buffer_access_behavior;
private static bool KHR_robustness;
private static bool KHR_shader_subgroup;
private static bool KHR_texture_compression_astc_hdr;
private static bool KHR_texture_compression_astc_ldr;
private static bool KHR_texture_compression_astc_sliced_3d;
private static bool MESA_framebuffer_flip_x;
private static bool MESA_framebuffer_flip_y;
private static bool MESA_framebuffer_swap_xy;
private static bool MESA_pack_invert;
private static bool MESA_program_binary_formats;
private static bool MESA_resize_buffers;
private static bool MESA_shader_integer_functions;
private static bool MESA_tile_raster_order;
private static bool MESA_window_pos;
private static bool MESA_ycbcr_texture;
private static bool MESAX_texture_stack;
private static bool NV_alpha_to_coverage_dither_control;
private static bool NV_bindless_multi_draw_indirect;
private static bool NV_bindless_multi_draw_indirect_count;
private static bool NV_bindless_texture;
private static bool NV_blend_equation_advanced;
private static bool NV_blend_equation_advanced_coherent;
private static bool NV_blend_minmax_factor;
private static bool NV_blend_square;
private static bool NV_clip_space_w_scaling;
private static bool NV_command_list;
private static bool NV_compute_program5;
private static bool NV_compute_shader_derivatives;
private static bool NV_conditional_render;
private static bool NV_conservative_raster;
private static bool NV_conservative_raster_dilate;
private static bool NV_conservative_raster_pre_snap;
private static bool NV_conservative_raster_pre_snap_triangles;
private static bool NV_conservative_raster_underestimation;
private static bool NV_copy_depth_to_color;
private static bool NV_copy_image;
private static bool NV_deep_texture3D;
private static bool NV_depth_buffer_float;
private static bool NV_depth_clamp;
private static bool NV_draw_texture;
private static bool NV_draw_vulkan_image;
private static bool NV_evaluators;
private static bool NV_explicit_multisample;
private static bool NV_fence;
private static bool NV_fill_rectangle;
private static bool NV_float_buffer;
private static bool NV_fog_distance;
private static bool NV_fragment_coverage_to_color;
private static bool NV_fragment_program;
private static bool NV_fragment_program_option;
private static bool NV_fragment_program2;
private static bool NV_fragment_program4;
private static bool NV_fragment_shader_barycentric;
private static bool NV_fragment_shader_interlock;
private static bool NV_framebuffer_mixed_samples;
private static bool NV_framebuffer_multisample_coverage;
private static bool NV_geometry_program4;
private static bool NV_geometry_shader_passthrough;
private static bool NV_geometry_shader4;
private static bool NV_gpu_multicast;
private static bool NV_gpu_program4;
private static bool NV_gpu_program5;
private static bool NV_gpu_program5_mem_extended;
private static bool NV_gpu_shader5;
private static bool NV_half_float;
private static bool NV_internalformat_sample_query;
private static bool NV_light_max_exponent;
private static bool NV_memory_attachment;
private static bool NV_memory_object_sparse;
private static bool NV_mesh_shader;
private static bool NV_multisample_coverage;
private static bool NV_multisample_filter_hint;
private static bool NV_occlusion_query;
private static bool NV_packed_depth_stencil;
private static bool NV_parameter_buffer_object;
private static bool NV_parameter_buffer_object2;
private static bool NV_path_rendering;
private static bool NV_path_rendering_shared_edge;
private static bool NV_pixel_data_range;
private static bool NV_point_sprite;
private static bool NV_present_video;
private static bool NV_primitive_restart;
private static bool NV_primitive_shading_rate;
private static bool NV_query_resource;
private static bool NV_query_resource_tag;
private static bool NV_register_combiners;
private static bool NV_register_combiners2;
private static bool NV_representative_fragment_test;
private static bool NV_robustness_video_memory_purge;
private static bool NV_sample_locations;
private static bool NV_sample_mask_override_coverage;
private static bool NV_scissor_exclusive;
private static bool NV_shader_atomic_counters;
private static bool NV_shader_atomic_float;
private static bool NV_shader_atomic_float64;
private static bool NV_shader_atomic_fp16_vector;
private static bool NV_shader_atomic_int64;
private static bool NV_shader_buffer_load;
private static bool NV_shader_buffer_store;
private static bool NV_shader_storage_buffer_object;
private static bool NV_shader_subgroup_partitioned;
private static bool NV_shader_texture_footprint;
private static bool NV_shader_thread_group;
private static bool NV_shader_thread_shuffle;
private static bool NV_shading_rate_image;
private static bool NV_stereo_view_rendering;
private static bool NV_tessellation_program5;
private static bool NV_texgen_emboss;
private static bool NV_texgen_reflection;
private static bool NV_texture_barrier;
private static bool NV_texture_compression_vtc;
private static bool NV_texture_env_combine4;
private static bool NV_texture_expand_normal;
private static bool NV_texture_multisample;
private static bool NV_texture_rectangle;
private static bool NV_texture_rectangle_compressed;
private static bool NV_texture_shader;
private static bool NV_texture_shader2;
private static bool NV_texture_shader3;
private static bool NV_timeline_semaphore;
private static bool NV_transform_feedback;
private static bool NV_transform_feedback2;
private static bool NV_uniform_buffer_std430_layout;
private static bool NV_uniform_buffer_unified_memory;
private static bool NV_vdpau_interop;
private static bool NV_vdpau_interop2;
private static bool NV_vertex_array_range;
private static bool NV_vertex_array_range2;
private static bool NV_vertex_attrib_integer_64bit;
private static bool NV_vertex_buffer_unified_memory;
private static bool NV_vertex_program;
private static bool NV_vertex_program1_1;
private static bool NV_vertex_program2;
private static bool NV_vertex_program2_option;
private static bool NV_vertex_program3;
private static bool NV_vertex_program4;
private static bool NV_video_capture;
private static bool NV_viewport_array2;
private static bool NV_viewport_swizzle;
private static bool NVX_blend_equation_advanced_multi_draw_buffers;
private static bool NVX_conditional_render;
private static bool NVX_gpu_memory_info;
private static bool NVX_gpu_multicast2;
private static bool NVX_linked_gpu_multicast;
private static bool NVX_progress_fence;
private static bool OES_byte_coordinates;
private static bool OES_compressed_paletted_texture;
private static bool OES_fixed_point;
private static bool OES_query_matrix;
private static bool OES_read_format;
private static bool OES_single_precision;
private static bool OML_interlace;
private static bool OML_resample;
private static bool OML_subsample;
private static bool OVR_multiview;
private static bool OVR_multiview2;
private static bool PGI_misc_hints;
private static bool PGI_vertex_hints;
private static bool REND_screen_coordinates;
private static bool S3_s3tc;
private static bool SGI_color_matrix;
private static bool SGI_color_table;
private static bool SGI_texture_color_table;
private static bool SGIS_detail_texture;
private static bool SGIS_fog_function;
private static bool SGIS_generate_mipmap;
private static bool SGIS_multisample;
private static bool SGIS_pixel_texture;
private static bool SGIS_point_line_texgen;
private static bool SGIS_point_parameters;
private static bool SGIS_sharpen_texture;
private static bool SGIS_texture_border_clamp;
private static bool SGIS_texture_color_mask;
private static bool SGIS_texture_edge_clamp;
private static bool SGIS_texture_filter4;
private static bool SGIS_texture_lod;
private static bool SGIS_texture_select;
private static bool SGIS_texture4D;
private static bool SGIX_async;
private static bool SGIX_async_histogram;
private static bool SGIX_async_pixel;
private static bool SGIX_blend_alpha_minmax;
private static bool SGIX_calligraphic_fragment;
private static bool SGIX_clipmap;
private static bool SGIX_convolution_accuracy;
private static bool SGIX_depth_pass_instrument;
private static bool SGIX_depth_texture;
private static bool SGIX_flush_raster;
private static bool SGIX_fog_offset;
private static bool SGIX_fragment_lighting;
private static bool SGIX_framezoom;
private static bool SGIX_igloo_interface;
private static bool SGIX_instruments;
private static bool SGIX_interlace;
private static bool SGIX_ir_instrument1;
private static bool SGIX_list_priority;
private static bool SGIX_pixel_texture;
private static bool SGIX_pixel_tiles;
private static bool SGIX_polynomial_ffd;
private static bool SGIX_reference_plane;
private static bool SGIX_resample;
private static bool SGIX_scalebias_hint;
private static bool SGIX_shadow;
private static bool SGIX_shadow_ambient;
private static bool SGIX_sprite;
private static bool SGIX_subsample;
private static bool SGIX_tag_sample_buffer;
private static bool SGIX_texture_add_env;
private static bool SGIX_texture_coordinate_clamp;
private static bool SGIX_texture_lod_bias;
private static bool SGIX_texture_multi_buffer;
private static bool SGIX_texture_scale_bias;
private static bool SGIX_vertex_preclip;
private static bool SGIX_ycrcb;
private static bool SGIX_ycrcb_subsample;
private static bool SGIX_ycrcba;
private static bool SUN_convolution_border_modes;
private static bool SUN_global_alpha;
private static bool SUN_mesh_array;
private static bool SUN_slice_accum;
private static bool SUN_triangle_list;
private static bool SUN_vertex;
private static bool SUNX_constant_data;
private static bool WIN_phong_shading;
private static bool WIN_specular_fog;
#endregion
}
}
@@ -1,144 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glRenderStream.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Logic;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
{
public abstract partial class glRenderStream : RenderStream
{
protected glRenderStream(ViewPort v, (int,int,int) cube) : base(v,cube)
{
}
protected IntPtr glContextHandle
{
get { return ContextHandle; }
}
/// <summary>
/// Init an OpenGl viewPortDisplay if current form has not been binded to any viewPortDisplay. and set the viewPortDisplay binded to
/// current form as current OpenGL viewPortDisplay.
/// </summary>
/// <exception cref="Exception">
/// Something goes wrong and StgSharp fails in creating a new OpenGL viewPortDisplay.
/// </exception>
public unsafe void MakeAsCurrentContext()
{
if (ContextHandle == default)
{
ContextHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GLcontext)));
GLcontext* contextID = (GLcontext*)ContextHandle;
contextID->glGetString = (delegate*<uint, IntPtr>)IntPtr.Zero;
}
if (glFunc.CurrentContextHandle != ContextHandle)
{
glFunc.CurrentContextHandle = ContextHandle;
InternalIO.glfwMakeContextCurrent(CanvasHandle);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void SetSizeLimit(int minWidth, int minHeight, int maxWidth, int maxHeight)
{
InternalIO.glfwSetWindowSizeLimits(this.CanvasHandle, minWidth, minHeight, maxWidth, maxHeight);
}
internal override sealed void InternalDraw(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
{
MakeAsCurrentContext();
Main(in input, in output);
}
internal override sealed void InternalInit()
{
MakeAsCurrentContext();
this.Port.LoadGLapi();
Init();
}
internal override sealed void InternalTerminate()
{
Deinit();
}
protected override sealed Uniform<Matrix44> NativeCameraUniform(ShaderProgram source, string name)
{
NativeCamera.GainAllUniforms(source, name);
return NativeCamera.convertedUniform;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override sealed void NativeCameraViewRange(Radius fieldOfRange, vec2d offset, (float frontDepth, float backDepth) viewDepth)
{
NativeCamera.SetViewRange(fieldOfRange, this.Size, offset, viewDepth);
}
protected override sealed void NativeCameraViewTarget(vec3d position, vec3d direction, vec3d up)
{
NativeCamera.SetViewDirection(position, direction, up);
}
#region Key Control
protected KeyStatus CheckKey(KeyboardKey key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
protected KeyStatus CheckKey(Mouse key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
protected KeyStatus CheckKey(Joystick key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
#endregion
}
}
+33 -1
View File
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IGraphicAPIs.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
@@ -6,7 +36,9 @@ namespace StgSharp.Graphics
{
public interface IGraphicAPIs
{
public IntPtr GraphicApiPackageHandle { get; }
}
}
+72 -50
View File
@@ -46,15 +46,9 @@ namespace StgSharp.Graphics
{
public class Image : ISSDSerializable, IImageProvider
{
internal byte[] data;
internal ImageInfo info;
public PixelChannelLayout PixelLayout
{
get => info.pixelLayout;
private set => info.pixelLayout = value;
}
private byte[] _data;
private ImageInfo info;
private int _pixelUpdateCount = 0;
internal unsafe Image()
{
@@ -64,15 +58,42 @@ namespace StgSharp.Graphics
internal Image(ImageInfo information)
{
info = information;
data = Array.Empty<byte>();
_data = Array.Empty<byte>();
//int length = info.width * info.height * info.channel;
}
internal ref byte[] Data
{
get => ref _data;
}
public (int width, int height) Size
{
get => (info.Width, info.Height);
}
/// <summary>
/// Hash code of time pixels updated last time.
/// </summary>
public int PixelUpdateCount
{
get => _pixelUpdateCount;
internal set => _pixelUpdateCount = value;
}
public byte[] PixelBuffer
{
get
{
if ((_data.Length == 0) || (_data == null))
{
GetBytes();
return _data!;
}
return _data;
}
}
public ImageChannel Channel => info.Channel;
public int ChannelCount => info.ChannelCount;
public int Height
@@ -89,6 +110,12 @@ namespace StgSharp.Graphics
public int PixelSize => GlHelper.GetPixelSize(info.pixelLayout, info.Channel);
public PixelChannelLayout PixelLayout
{
get => info.pixelLayout;
private set => info.pixelLayout = value;
}
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.PixelImage;
public void FromBytes(byte[] stream)
@@ -106,21 +133,6 @@ namespace StgSharp.Graphics
return ret;
}
public static Image FromMemory((int width, int height) size, ImageChannel channel, PixelChannelLayout layout, byte[] stream)
{
ImageInfo _info = new ImageInfo
{
Height = size.height,
Width = size.width,
Channel = channel,
StreamPtr = IntPtr.Zero
};
Image ret = new Image(_info);
ret.PixelLayout = layout;
ret.data = stream;
return ret;
}
public static Image FromMemory((int width, int height) size, ImageChannel channel, byte[] stream)
{
ImageInfo _info = new ImageInfo
@@ -132,35 +144,38 @@ namespace StgSharp.Graphics
};
Image ret = new Image(_info);
ret.PixelLayout = PixelChannelLayout.Byte;
ret.data = stream;
ret._data = stream;
return ret;
}
public static Image FromMemory((int width, int height) size, ImageChannel channel, PixelChannelLayout layout, byte[] stream)
{
ImageInfo _info = new ImageInfo
{
Height = size.height,
Width = size.width,
Channel = channel,
StreamPtr = IntPtr.Zero
};
Image ret = new Image(_info);
ret.PixelLayout = layout;
ret._data = stream;
return ret;
}
public unsafe byte[] GetBytes()
{
if (data.Length == 0)
if (_data.Length == 0)
{
int size = Width * Height * GlHelper.GetPixelSize(PixelLayout, Channel);
_data = new Span<byte>((byte*)info.StreamPtr, size).ToArray();
fixed (ImageInfo* pptr = &info)
{
int size = Width * Height * GlHelper.GetPixelSize(PixelLayout, Channel);
data = new Span<byte>((byte*)info.StreamPtr, size).ToArray();
fixed (ImageInfo* pptr = &info)
{
InternalIO.InternalUnloadImage(pptr);
}
info.StreamPtr = IntPtr.Zero;
InternalIO.InternalUnloadImage(pptr);
}
return data;
}
public byte[] PixelBuffer
{
get{
if ((data.Length == 0) || (data == null))
{
GetBytes();
return data!;
}
return data;
info.StreamPtr = IntPtr.Zero;
}
return _data;
}
public Image ProvideImage() => this;
@@ -168,6 +183,7 @@ namespace StgSharp.Graphics
{
throw new NotImplementedException();
}
}
[StructLayout(LayoutKind.Sequential)]
@@ -183,10 +199,7 @@ namespace StgSharp.Graphics
public ImageChannel Channel
{
get => channel;
set
{
channel = value;
}
set { channel = value; }
}
public int ChannelCount
@@ -222,6 +235,14 @@ namespace StgSharp.Graphics
return $"{channel}\t{width}\t{height}\t{(ulong)StreamPtr}";
}
public override int GetHashCode()
{
int hash = 17;
hash = hash * 17 + width;
hash = hash * 17 + height;
hash = hash * 17 + (int)channel;
return hash;
}
}
public enum ImageChannel : uint
@@ -276,5 +297,6 @@ namespace StgSharp.Graphics.OpenGL
_ => throw new ArgumentException("Unknown layout type"),
};
}
}
}
@@ -0,0 +1,161 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="AutoTexture.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using StgSharp.Collections;
namespace StgSharp.Graphics.OpenGL
{
public sealed class AutoTextureGL
{
private BidirectionalDictionary<Image, int> imageIndexMap = new BidirectionalDictionary<Image, int>();
private Dictionary<Image, int> imageUpdateIndex = new Dictionary<Image, int>();
private int _size, _currentIndex;
private LinkedList<int> usedTextureIndex;
private Queue<int> unusedTextureUnitIndex;
private TextureProperty[] propertyCache;
private TextureGL texturePackage;
private TextureProperty _textureProperty;
private OpenGLFunction GL
{
get => texturePackage.GL;
}
private AutoTextureGL(TextureGL texture)
{
texturePackage = texture;
_size = texture.Count;
imageIndexMap = new BidirectionalDictionary<Image, int>();
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
public AutoTextureGL(int textureObjectSize, [NotNull]glRenderStream binding)
{
this._size = textureObjectSize;
imageIndexMap = new BidirectionalDictionary<Image, int>();
texturePackage = new TextureGL(textureObjectSize, binding);
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
public TextureProperty DefaultTextureProperty
{
get => _textureProperty;
set => _textureProperty = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SelectTextureAndBind(Image i)
{
TextureProperty property = _textureProperty;
SelectTextureAndBind(i, property);
}
public void SelectTextureAndBind([NotNull]Image i, TextureProperty property)
{
//usable texture with image match
if (imageIndexMap.TryGetValue(i, out int index))
{
//prop setting match
if (propertyCache[index] == property)
{
_currentIndex = index; //GL.Assert(true);
texturePackage.Bind2D(index); //GL.Assert(true);
if (i.PixelUpdateCount != imageUpdateIndex[i])
{
texturePackage.LoadTexture(index, i); //GL.Assert(true);
}
}
else
{
_currentIndex = index; //GL.Assert(true);
texturePackage.Bind2D(index); //GL.Assert(true);
texturePackage.Set2dProperty(index, property); //GL.Assert(true);
if (i.PixelUpdateCount != imageUpdateIndex[i])
{
texturePackage.LoadTexture(index, i); //GL.Assert(true);
}
}
}
else
{
if (unusedTextureUnitIndex.TryDequeue(out int newIndex))
{
//has extra unused texture object
imageIndexMap.Add(i, index);
texturePackage.Bind2D(index);
texturePackage.Set2dProperty(index, property);
texturePackage.LoadTexture(index, i);
usedTextureIndex.AddLast(newIndex);
propertyCache[newIndex] = property;
imageUpdateIndex[i] = i.PixelUpdateCount;
}
else
{
//recycle from current
int reusedIndex = usedTextureIndex.First!.Value;
usedTextureIndex.RemoveFirst();
usedTextureIndex.AddLast(reusedIndex);
imageIndexMap[i] = reusedIndex;
propertyCache[newIndex] = property;
imageUpdateIndex[i] = i.PixelUpdateCount;
}
}
}
public static AutoTextureGL ToAuto([NotNull]TextureGL texture)
{
if (texture.IndexOfCurrentTexture != -1)
{
throw new InvalidOperationException("Texture to be converted has been editted.");
}
return new AutoTextureGL(texture);
}
}
}
@@ -45,10 +45,10 @@ namespace StgSharp.Graphics.OpenGL
/// Each <see langword="uint"/> value indexed from instance of this class this
/// is the only handle to one Element Buffer Object.
/// </summary>
public unsafe class ElementBuffer : GlBufferObjectBase
public sealed unsafe class ElementBuffer : GlBufferObjectBase
{
internal ElementBuffer(int n, glRenderStream binding):base(binding)
internal ElementBuffer(int n, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenBuffers(n);
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="FBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -12,7 +42,7 @@ namespace StgSharp.Graphics.OpenGL
{
#pragma warning disable CA1008
#pragma warning disable CA1028
public enum FrameBufferTarget:uint
public enum FrameBufferTarget : uint
#pragma warning restore CA1028
#pragma warning restore CA1008
{
@@ -21,9 +51,10 @@ namespace StgSharp.Graphics.OpenGL
Draw = GLconst.DRAW_FRAMEBUFFER,
}
public class FrameBuffer : GlBufferObjectBase
public sealed class FrameBuffer : GlBufferObjectBase
{
internal unsafe FrameBuffer(int count, glRenderStream binding):base(binding)
internal unsafe FrameBuffer(int count, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenFrameBuffers(count);
}
@@ -34,15 +65,9 @@ namespace StgSharp.Graphics.OpenGL
/// </summary>
/// <param name="index">Index of object to be binded in handle set</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe override void Bind(int index)
public override unsafe void Bind(int index)
{
GL.BindFrameBuffer(FrameBufferTarget.All,_bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
GlFunction.CurrentGL.BindFrameBuffer(FrameBufferTarget.All,GlHandle.Zero);
GL.BindFrameBuffer(FrameBufferTarget.All, _bufferHandle[index]);
}
/// <summary>
@@ -57,9 +82,16 @@ namespace StgSharp.Graphics.OpenGL
GL.BindFrameBuffer(target, _bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
OpenGLFunction.CurrentGL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero);
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLBufferObjectBase.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -8,6 +38,7 @@ namespace StgSharp.Graphics.OpenGL
{
public abstract class GlBufferObjectBase : BufferObjectBase
{
private readonly glRenderStream _contextBinding;
protected GlBufferObjectBase(glRenderStream contextBinding)
@@ -16,7 +47,7 @@ namespace StgSharp.Graphics.OpenGL
_contextBinding = contextBinding;
}
protected GlFunction GL => _contextBinding.GL;
protected OpenGLFunction GL => _contextBinding.GL;
}
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="RBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -11,9 +41,10 @@ namespace StgSharp.Graphics.OpenGL
public class RenderBuffer : GlBufferObjectBase
public sealed class RenderBuffer : GlBufferObjectBase
{
public RenderBuffer(int count, glRenderStream binding):base(binding)
public RenderBuffer(int count, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenRenderBuffer(count);
}
@@ -23,17 +54,18 @@ namespace StgSharp.Graphics.OpenGL
GL.BindRenderBuffer(this[index]);
}
public void Store(RenderBufferInternalFormat format, (int width, int height) size)
{
if ((size.width > binding.Width) || (size.height > binding.Height))
{
StgSharp.LogWarning("FrameBuffer is larger than current canvas binding");
}
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
public void Store(RenderBufferInternalFormat format, (int width,int height) size)
{
if (size.width > binding.Width || size.height>binding.Height)
{
StgSharp.LogWarning("FrameBuffer is larger than current canvas binding");
}
}
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="texture.cs"
// file="TextureGL.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -28,104 +28,230 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
public unsafe class TextureGL
public sealed unsafe class TextureGL
{
private GlFunction GL;
internal static bool[] unitActivated = new bool[16];
private int currentEditingTextureIndex;
private OpenGLFunction _gl;
internal GlHandle[] _textureHandle;
internal Image[] sourceList;
public GlHandle this[int index]
internal TextureGL( int count, glRenderStream binding )
{
get => _textureHandle[index];
//sourceList = new Image[count];
this._gl = binding.GL;
_textureHandle = _gl.GenTextures( count );
}
internal TextureGL(int n, glRenderStream binding)
internal OpenGLFunction GL => _gl;
public GlHandle this[ int index ]
{
sourceList = new Image[n];
this.GL = binding.GL;
_textureHandle = GL.GenTextures(n);
get => _textureHandle[ index ];
}
public void ActivateAs(TextureUnit unit)
public int Count
{
GL.ActiveTexture((uint)unit);
get => _textureHandle.Length;
}
public void Bind2D(int index)
//internal Image[] sourceList;
public int IndexOfCurrentTexture
{
GL.BindTexture(GLconst.TEXTURE_2D, _textureHandle[index]);
get => currentEditingTextureIndex;
}
public void ActivateAs( TextureUnit unit ) { _gl.ActiveTextureUnit( ( uint )unit ); }
public void Bind2D( int index )
{
currentEditingTextureIndex = index;
_gl.BindTexture( GLconst.TEXTURE_2D, _textureHandle[ index ] );
}
/// <summary>
/// Load an <see cref="Image"/> to certain texture.
/// Load an <see cref="Image" /> to certain texture.
/// </summary>
/// <param name="index"> </param>
/// <param name="i"> </param>
public unsafe void LoadTexture(int index, Image i)
public unsafe void LoadTexture( int index, Image i )
{
sourceList[index] = i;
var handle = sourceList[index].PixelBuffer;
GL.TextureImage2d(
Texture2DTarget.Texture2D, 0, (uint)i.Channel,
(uint)sourceList[index].Width, (uint)sourceList[index].Height,
(uint)i.Channel, i.PixelLayout,
pixels: handle
);
GL.GenerateMipmap(Texture2DTarget.Texture2D);
byte[] handle = i.PixelBuffer;
_gl.TextureImage2d(
Texture2DTarget.Texture2D, 0, ( uint )i.Channel, ( uint )i.Width, ( uint )i.Height,
( uint )i.Channel, i.PixelLayout, pixels: handle );
_gl.GenerateMipmap( Texture2DTarget.Texture2D );
}
#region texture setting
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dFilterProperty(
Filter onMinify, Filter onMagnify)
int index,
TextureFilter onMinify,
TextureFilter onMagnify )
{
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, (int)onMinify);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, (int)onMagnify);
#if DEBUG
if( index != currentEditingTextureIndex )
{
throw new InvalidOperationException(
"Texture to be editted is not the one being activated." );
}
#endif
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, ( int )onMinify );
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, ( int )onMagnify );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dWrapProperty(
Wrap onHorizontial, Wrap onVertical)
int index,
TextureWrap onHorizontial,
TextureWrap onVertical )
{
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, (int)onHorizontial);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, (int)onVertical);
#if DEBUG
if( index != currentEditingTextureIndex )
{
throw new InvalidOperationException(
"Texture to be editted is not the one being activated." );
}
#endif
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, ( int )onHorizontial );
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, ( int )onVertical );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dProperty( int index, TextureProperty property )
{
Set2dFilterProperty( index, property.FilterOnMinify, property.FilterOnMagnify );
Set2dWrapProperty( index, property.WrapOnHorizontial, property.WrapOnVertical );
}
#endregion texture setting
}
#pragma warning disable CA1008
public enum Filter
#pragma warning restore CA1008
[StructLayout( LayoutKind.Explicit )]
public struct TextureProperty
{
[FieldOffset( 0 )] private M128 mask;
[FieldOffset( 0 )] private TextureFilter mag;
[FieldOffset( 4 )] private TextureFilter min;
[FieldOffset( 8 )] private TextureWrap hori;
[FieldOffset( 12 )] private TextureWrap vert;
public TextureProperty(
TextureFilter onMagnify,
TextureFilter onMinify,
TextureWrap onHorizontial,
TextureWrap onVertical )
{
FilterOnMagnify = onMagnify;
FilterOnMinify = onMinify;
WrapOnHorizontial = onHorizontial;
WrapOnVertical = onVertical;
}
public TextureFilter FilterOnMagnify
{
get => mag;
set => mag = value;
}
public TextureFilter FilterOnMinify
{
get => min;
set => min = value;
}
public TextureWrap WrapOnHorizontial
{
get => hori;
set => hori = value;
}
public TextureWrap WrapOnVertical
{
get => vert;
set => vert = value;
}
public override int GetHashCode()
{
return HashCode.Combine(
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial, WrapOnVertical );
}
public override bool Equals([NotNullWhen(true)] object obj)
{
return base.Equals(obj);
}
public override string ToString()
{
return $"FilterOnMagnify:{FilterOnMagnify}, " +
$"FilterOnMagnify:{FilterOnMagnify}, " +
$"WrapOnHorizontial:{WrapOnHorizontial}, " +
$"WrapOnVertical:{WrapOnVertical}";
}
public static implicit operator TextureProperty(
(
TextureFilter onMagnify, TextureFilter onMinify,
TextureWrap onHorizontial, TextureWrap onVertical
) propertyValueTuple )
{
return new TextureProperty(
propertyValueTuple.onMagnify, propertyValueTuple.onMinify,
propertyValueTuple.onHorizontial, propertyValueTuple.onVertical );
}
public static bool operator ==(TextureProperty left, TextureProperty right)
{
return left.mask == right.mask;
}
public static bool operator !=(TextureProperty left, TextureProperty right)
{
return left.mask != right.mask;
}
}
#pragma warning disable CA1008
public enum TextureFilter
#pragma warning restore CA1008
{
Nearest = GLconst.NEAREST,
Linear = GLconst.LINEAR,
NearestLinearMipmap = GLconst.NEAREST_MIPMAP_LINEAR,
LinearLinearMipmap = GLconst.LINEAR_MIPMAP_LINEAR,
NearestNearestMipmap = GLconst.NEAREST_MIPMAP_NEAREST,
LinearNearestMipmap = GLconst.LINEAR_MIPMAP_NEAREST,
}
#pragma warning disable CA1008
#pragma warning disable CA1008
public enum TextureUnit
#pragma warning restore CA1008
#pragma warning restore CA1008
{
Unit0 = GLconst.TEXTURE0,
Unit1 = GLconst.TEXTURE1,
Unit2 = GLconst.TEXTURE2,
@@ -142,15 +268,18 @@ namespace StgSharp.Graphics.OpenGL
Unit13 = GLconst.TEXTURE13,
Unit14 = GLconst.TEXTURE14,
Unit15 = GLconst.TEXTURE15,
}
#pragma warning disable CA1008
public enum Wrap
#pragma warning restore CA1008
#pragma warning disable CA1008
public enum TextureWrap
#pragma warning restore CA1008
{
Repeat = GLconst.REPEAT,
MirroredRepeat = GLconst.MIRRORED_REPEAT,
ClampToEdge = GLconst.CLAMP_TO_EDGE,
ClampToBorder = GLconst.CLAMP_TO_BORDER,
}
}
@@ -37,10 +37,10 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexArray : GlBufferObjectBase
public sealed unsafe class VertexArray : GlBufferObjectBase
{
internal VertexArray(int n, glRenderStream binding):base(binding)
internal VertexArray(int n, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenVertexArrays(n);
}
@@ -54,7 +54,7 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
GlFunction.CurrentGL.BindVertexArray(GlHandle.Zero);
OpenGLFunction.CurrentGL.BindVertexArray(GlHandle.Zero);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -40,10 +40,10 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexBuffer : GlBufferObjectBase
public sealed unsafe class VertexBuffer : GlBufferObjectBase
{
internal VertexBuffer(int n, glRenderStream binding):base(binding)
internal VertexBuffer(int n, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenBuffers(n);
}
@@ -54,13 +54,22 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
///
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unbind()
{
GL.BindBuffer(BufferType.ArrayBuffer, GlHandle.Zero);
}
/// <summary>
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="bufferData">Data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteMatrixData<T>(int index, T bufferData, BufferUsage usage)
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteMatrixData<T>(int index, T bufferData, BufferUsage usage)
where T : struct, IMat
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
@@ -68,12 +77,12 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="bufferArray">Data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteScalerData<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
@@ -87,12 +96,12 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="scalerSpan">A <see cref="Span{T}"/> of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
/// <param name="scalerSpan">A <see cref="Span{T}"/> of _data to write in</param>
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteScalerData<T>(int index, ReadOnlySpan<T> scalerSpan, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
@@ -106,12 +115,12 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="vectorSpan">A <see cref="Span{T}"/> of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
/// <param name="vectorSpan">A <see cref="Span{T}"/> of _data to write in</param>
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteVectorData<T>(int index, ReadOnlySpan<T> vectorSpan, BufferUsage usage) where T : struct, IVector
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
@@ -119,27 +128,18 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="vectorArray">A array of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
/// <param name="vectorArray">A array of _data to write in</param>
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteVectorData<T>(int index, T[] vectorArray, BufferUsage usage) where T : struct, IVector
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferVectorData(BufferType.ArrayBuffer, vectorArray, usage);
}
/// <summary>
///
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unbind()
{
GL.BindBuffer(BufferType.ArrayBuffer, GlHandle.Zero);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLresourceGenrator.cs"
// file="glResourceGenrator.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -51,6 +51,12 @@ namespace StgSharp.Graphics.OpenGL
return new ElementBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected FrameBuffer CreateFrameBuffer(int count)
{
return new FrameBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected RenderBuffer CreateRenderBuffer(int count)
@@ -58,12 +64,6 @@ namespace StgSharp.Graphics.OpenGL
return new RenderBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected FrameBuffer CreateFrameBuffer(int count)
{
return new FrameBuffer(count, this);
}
/// <summary>
/// Create a sets of <see cref="TextureGL"/>
/// </summary>
@@ -75,6 +75,13 @@ namespace StgSharp.Graphics.OpenGL
return new TextureGL(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected AutoTextureGL CreateAutoTexture(int count)
{
return new AutoTextureGL(count, this);
}
/// <summary>
/// Create a set of <see cref="VertexArray"/>.
/// </summary>
@@ -97,6 +104,6 @@ namespace StgSharp.Graphics.OpenGL
return new VertexBuffer(count, this);
}
}
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glException.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
@@ -9,6 +39,7 @@ namespace StgSharp.Graphics.OpenGL
{
public sealed class GlExecutionException : Exception
{
public GlExecutionException()
{
}
@@ -21,10 +52,6 @@ namespace StgSharp.Graphics.OpenGL
public sealed class GlArrayFormatException : Exception
{
public GlArrayFormatException(PixelChannelLayout layout, string arrayname):
base($"{arrayname} cannot be used as layout of {layout}")
{
}
internal GlArrayFormatException(string message) : base(message)
{
@@ -37,22 +64,28 @@ namespace StgSharp.Graphics.OpenGL
internal GlArrayFormatException(string message, Exception innerException) : base(message, innerException)
{
}
public GlArrayFormatException(PixelChannelLayout layout, string arrayname) :
base($"{arrayname} cannot be used as layout of {layout}")
{
}
}
public static partial class GlHelper
{
public static bool CheckArrayFormat(this Array array, PixelChannelLayout layout)
{
return layout switch
{
PixelChannelLayout.Byte or PixelChannelLayout.UByte332 or PixelChannelLayout.UByte233Rev
=> array is byte[] || array is sbyte[],
=> (array is byte[]) || (array is sbyte[]),
PixelChannelLayout.Short => array is short[],
PixelChannelLayout.UShort => array is ushort[],
PixelChannelLayout.Int => array is int[],
PixelChannelLayout.Float => array is float[],
PixelChannelLayout.UShort4444 => array is ushort[] || array is byte[],
PixelChannelLayout.UByte => array is byte[] || array is sbyte[],
PixelChannelLayout.UShort4444 => (array is ushort[]) || (array is byte[]),
PixelChannelLayout.UByte => (array is byte[]) || (array is sbyte[]),
PixelChannelLayout.UInt => array is uint[],
PixelChannelLayout.UShort565 or
PixelChannelLayout.UShort565Rev or
+10 -9
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLhandle.cs"
// file="GlHandle.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -49,24 +49,25 @@ namespace StgSharp.Graphics.OpenGL
[StructLayout(LayoutKind.Explicit, Size = 4)]
public struct GlHandle
{
[FieldOffset(0)] public uint Value;
[FieldOffset(0)] public int SignedValue;
[FieldOffset(0)] public uint Value;
public static GlHandle Zero
{
get => new GlHandle { Value = 0 };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GlHandle Alloc(uint value)
{
return new GlHandle() { Value = value };
return new GlHandle { Value = value };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GlHandle SignedAlloc(int value)
{
return new GlHandle() { SignedValue = value };
}
public static GlHandle Zero
{
get => new GlHandle() { Value = 0 };
return new GlHandle { SignedValue = value };
}
}
@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class OpenGLAPICallingAttribute:Attribute
{
public OpenGLAPICallingAttribute()
{
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IglConvertable.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -10,26 +40,26 @@ namespace StgSharp.Graphics.ShaderEdit
{
public interface IglConvertable
{
/// <summary>
///
/// </summary>
public void SetAllUniforms();
/// <summary>
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
/// <summary>
///
/// </summary>
public void DisplayGLtypeDefinition();
/// <summary>
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
/// <summary>
///
/// </summary>
/// <returns></returns>
public ShaderStruct GetConvertedGLtype();
/// <summary>
///
/// </summary>
public void SetAllUniforms();
}
}
@@ -44,30 +44,31 @@ namespace StgSharp.Graphics.OpenGL
public abstract partial class glRenderStream : RenderStream
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override Shader CreateShaderSegment(ShaderType type, int count)
{
return new Shader( GL.CreateShaderSet(count, type), type, this);
}
/// <summary>
/// Create an instance of <see cref="Shader"/> program
/// </summary>
/// <returns>New instance of <see cref="Shader"/> instance. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override ShaderProgram CreateShaderProgram()
protected override sealed ShaderProgram CreateShaderProgram()
{
return new ShaderProgram(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override sealed Shader CreateShaderSegment(ShaderType type, int count)
{
return new Shader(GL.CreateShaderSet(count, type), type, this);
}
}
public class Shader : ISSDSerializable
{
private readonly GlFunction GL;
private readonly OpenGLFunction GL;
internal readonly GlHandle[] handle;
public readonly ShaderType type;
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.Shader;
internal unsafe Shader(GlHandle[] handle, ShaderType usage, glRenderStream stream)
{
this.handle = handle;
@@ -75,6 +76,8 @@ namespace StgSharp.Graphics.OpenGL
type = usage;
}
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.Shader;
/// <summary>
/// Attach one shader code to a shader program.
/// </summary>
@@ -86,14 +89,13 @@ namespace StgSharp.Graphics.OpenGL
GL.AttachShader(target.handle, handle[index]);
}
public static byte[] FromCodeFile(string fileRoute)
public void CheckStatus(int index, ShaderStatus status)
{
string str = File.ReadAllText(fileRoute);
if (string.IsNullOrEmpty(str))
string log = GL.GetShaderStatus(this, index, (int)status);
if (!string.IsNullOrEmpty(log))
{
throw new InvalidOperationException($"Cannot load and GLSL code from {fileRoute}");
throw new Exception($"{$"Shader Error \t{status}\n"}{log}");
}
return Encoding.UTF8.GetBytes(str);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -105,7 +107,7 @@ namespace StgSharp.Graphics.OpenGL
}
GL.LoadShaderSource(handle[index], codeStream);
GL.CompileShader(handle[index]);
CheckStatus(index,ShaderStatus.CompileStatus);
CheckStatus(index, ShaderStatus.CompileStatus);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -115,14 +117,24 @@ namespace StgSharp.Graphics.OpenGL
{
throw new ArgumentNullException(nameof(codeStream));
}
GL.LoadShaderSource(handle[index],Encoding.ASCII.GetBytes( codeStream));
GL.LoadShaderSource(handle[index], Encoding.ASCII.GetBytes(codeStream));
GL.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
}
public override string ToString()
public void FromBytes(byte[] stream)
{
return $"This is a {type} shader, its shader handles are {handle.ToString()}.";
throw new NotImplementedException();
}
public static byte[] FromCodeFile(string fileRoute)
{
string str = File.ReadAllText(fileRoute);
if (string.IsNullOrEmpty(str))
{
throw new InvalidOperationException($"Cannot load and GLSL code from {fileRoute}");
}
return Encoding.UTF8.GetBytes(str);
}
public byte[] GetBytes()
@@ -130,24 +142,16 @@ namespace StgSharp.Graphics.OpenGL
return Array.Empty<byte>();
}
public void CheckStatus(int index, ShaderStatus status)
{
string log = GL.GetShaderStatus(this,index, (int)status);
if (!string.IsNullOrEmpty(log))
{
throw new Exception($"Shader Error \t{status}\n" + log);
}
}
public byte[] GetBytes(out int length)
{
throw new NotImplementedException();
}
public void FromBytes(byte[] stream)
public override string ToString()
{
throw new NotImplementedException();
return $"This is a {type} shader, its shader handles are {handle.ToString()}.";
}
}
public enum ShaderStatus : int
@@ -157,7 +161,8 @@ namespace StgSharp.Graphics.OpenGL
public class ShaderProgram
{
private readonly GlFunction GL;
private readonly OpenGLFunction GL;
internal readonly GlHandle handle;
/// <summary>
@@ -191,7 +196,7 @@ namespace StgSharp.Graphics.OpenGL
where T : struct
where U : struct
{
return new Uniform<T, U>(GL.GetUniformLocation(this.handle,name));
return new Uniform<T, U>(GL.GetUniformLocation(this.handle, name));
}
/// <summary>
@@ -42,109 +42,112 @@ namespace StgSharp.Graphics.OpenGL
{
public class Uniform
{
internal GlHandle id;
public GlHandle Handle
{
get => id;
}
}
public sealed class Uniform<T> : Uniform
where T : struct
{
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal static Uniform<T> FromHandle(GlHandle handle)
{
return new Uniform<T>() { id = handle };
return new Uniform<T> { id = handle };
}
}
public sealed class Uniform<T, U>: Uniform
public sealed class Uniform<T, U> : Uniform
where T : struct
where U : struct
{
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal static Uniform<T,U> FromHandle(GlHandle handle)
internal unsafe Uniform(GlHandle id)
{
return new Uniform<T, U>() { id = handle };
this.id = id;
}
internal static Uniform<T, U> FromHandle(GlHandle handle)
{
return new Uniform<T, U> { id = handle };
}
}
public sealed class Uniform<T, U, V>:Uniform
public sealed class Uniform<T, U, V> : Uniform
where T : struct
where U : struct
where V : struct
{
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal static Uniform<T,U,V> FromHandle(GlHandle handle)
internal unsafe Uniform(GlHandle id)
{
return new Uniform<T, U, V>() { id = handle };
this.id = id;
}
internal static Uniform<T, U, V> FromHandle(GlHandle handle)
{
return new Uniform<T, U, V> { id = handle };
}
}
public sealed class Uniform<T, U, V, W>:Uniform
public sealed class Uniform<T, U, V, W> : Uniform
where T : struct
where U : struct
where V : struct
where W : struct
{
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal static Uniform<T, U, V, W> FromHandle(GlHandle handle)
{
return new Uniform<T, U, V, W>() { id = handle };
return new Uniform<T, U, V, W> { id = handle };
}
}
public unsafe partial class GlFunction
public unsafe partial class OpenGLFunction
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue
(Uniform<Matrix44> uniform, Matrix44 mat)
@@ -157,7 +160,7 @@ namespace StgSharp.Graphics.OpenGL
public void SetUniformValue(Uniform<float, float, float, float> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue , 4, &temp);
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
}
@@ -165,37 +168,37 @@ namespace StgSharp.Graphics.OpenGL
public void SetUniformValue(Uniform<vec4d> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue , 4, &temp);
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float> uniform, float v0)
{
Context.glUniform1f(uniform.id.SignedValue , v0);
Context.glUniform1f(uniform.id.SignedValue, v0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<int> uniform, int i0)
{
Context.glUniform1i(uniform.id.SignedValue , i0);
Context.glUniform1i(uniform.id.SignedValue, i0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float> uniform, float v0, float v1)
{
Context.glUniform2f(uniform.id.SignedValue , v0, v1);
Context.glUniform2f(uniform.id.SignedValue, v0, v1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float, float> uniform, float v0, float v1, float v2)
{
Context.glUniform3f(uniform.id.SignedValue , v0, v1, v2);
Context.glUniform3f(uniform.id.SignedValue, v0, v1, v2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float, float, float> uniform, float v0, float v1, float v2, float v3)
{
Context.glUniform4f(uniform.id.SignedValue , v0, v1, v2, v3);
Context.glUniform4f(uniform.id.SignedValue, v0, v1, v2, v3);
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="VAO.cs"
// file="glAPICalling.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -28,53 +28,20 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexArray : BufferObjectBase
[AttributeUsage(AttributeTargets.Method)]
public sealed class OpenGLAPICallingAttribute : Attribute
{
internal VertexArray(int n, glRenderStream binding)
public OpenGLAPICallingAttribute()
{
this.binding = binding;
_bufferHandle = glFunc.GenVertexArrays(n);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override sealed void Bind(int index)
{
glFunc.BindVertexArray(_bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
glFunc.BindVertexArray(glHandle.Zero);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetVertexAttribute(uint index, int vertexLength, TypeCode dataType, bool isNomalized, uint stride, int pointer)
{
glFunc.SetVertexAttribute(
index, vertexLength, dataType,
isNomalized,
stride, pointer);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
glFunc.DeleteVertexArrays(_bufferHandle);
_bufferHandle.Release();
}
}
}
}
}
@@ -57,6 +57,25 @@ namespace StgSharp.Graphics.OpenGL
private static string glExtensionList;
//--------------------------------------------------------------------------------
/// <summary>
/// Get the function pointer of given OpenGL api name
/// </summary>
/// <param name="name">ContextName of the OpenGL api</param>
/// <returns>The funtion pointer of the api in stream of <see cref="IntPtr"/></returns>
public static IntPtr LoadGLfunc(string name)
{
IntPtr ret = InternalIO.glfwGetProcAddress(name);
if (ret == default)
{
InternalIO.InternalAppendLog(
$"Cannot load OpenGL api called {name}, this api may not exist or supported.");
return ret;
}
return ret;
}
/// <summary>
/// Load all supported OpenGL APIs and bind them to given <see cref="ViewPort"/>.
/// </summary>
@@ -64,7 +83,7 @@ namespace StgSharp.Graphics.OpenGL
public static unsafe void LoadOpenGLApiTo(IntPtr contextHandle)
{
OpenglContext* context = (OpenglContext*)contextHandle;
delegate*<string,IntPtr> loader = &InternalIO.glfwGetProcAddress;
delegate*<string, IntPtr> loader = &InternalIO.glfwGetProcAddress;
if ((IntPtr)context->glGetString != IntPtr.Zero)
{
return;
@@ -84,7 +103,7 @@ namespace StgSharp.Graphics.OpenGL
{
InternalIO.InternalWriteLog("Failed to call glGetString", LogType.Error);
}
coreVersion = Marshal.PtrToStringAnsi(context->glGetString(glVersion))??string.Empty;
coreVersion = Marshal.PtrToStringAnsi(context->glGetString(glVersion)) ?? string.Empty;
foreach (string branch in glBranch)
{
@@ -140,7 +159,7 @@ namespace StgSharp.Graphics.OpenGL
}
int extensionCount;
context->glGetIntegerv(GLconst.NUM_EXTENSIONS,&extensionCount);
context->glGetIntegerv(GLconst.NUM_EXTENSIONS, &extensionCount);
if (extensionCount == 0)
{
InternalIO.InternalWriteLog("No supported OpenGL extensions are found.", LogType.Info);
@@ -151,12 +170,11 @@ namespace StgSharp.Graphics.OpenGL
for (uint i = 0; i < extensionCount; i++)
{
byte* strPtr = context->glGetStringi(GLconst.EXTENSIONS,i);
byte* strPtr = context->glGetStringi(GLconst.EXTENSIONS, i);
extensions.Add(Marshal.PtrToStringAnsi((IntPtr)strPtr));
}
InternalIO.InternalWriteLog($"Find OpenGL extensions:" + Environment.NewLine +
$"{string.Join(';', extensions)}",
InternalIO.InternalWriteLog($"{$"Find OpenGL extensions:"}{Environment.NewLine}{($"{string.Join(';', extensions)}")}",
LogType.Info);
#region checkGLextensions
@@ -786,25 +804,6 @@ namespace StgSharp.Graphics.OpenGL
}
//--------------------------------------------------------------------------------
/// <summary>
/// Get the function pointer of given OpenGL api name
/// </summary>
/// <param name="name">ContextName of the OpenGL api</param>
/// <returns>The funtion pointer of the api in stream of <see cref="IntPtr"/></returns>
public static IntPtr LoadGLfunc(string name)
{
IntPtr ret = InternalIO.glfwGetProcAddress(name);
if (ret == default)
{
InternalIO.InternalAppendLog(
$"Cannot load OpenGL api called {name}, this api may not exist or supported.");
return ret;
}
return ret;
}
internal static void CheckCoreVersion(int majorVersion, int minorVersion)
{
if (majorVersion < 3)
@@ -1017,7 +1016,7 @@ namespace StgSharp.Graphics.OpenGL
}
}
internal static unsafe void LoadGLcore10(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore10(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core10)
{
@@ -1081,7 +1080,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.0 APIs");
}
internal static unsafe void LoadGLcore11(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore11(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core11)
{
@@ -1111,7 +1110,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.1 APIs");
}
internal static unsafe void LoadGLcore12(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore12(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core12)
{
@@ -1131,7 +1130,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.2 APIs");
}
internal static unsafe void LoadGLcore13(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore13(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core13)
{
@@ -1156,7 +1155,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.3 APIs");
}
internal static unsafe void LoadGLcore14(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore14(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core14)
{
@@ -1181,7 +1180,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.4 APIs");
}
internal static unsafe void LoadGLcore15(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore15(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core15)
{
@@ -1216,7 +1215,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.5 APIs");
}
internal static unsafe void LoadGLcore20(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore20(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core20)
{
@@ -1325,7 +1324,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 2.0 APIs");
}
internal static unsafe void LoadGLcore21(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore21(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core21)
{
@@ -1347,7 +1346,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 2.1 APIs");
}
internal static unsafe void LoadGLcore30(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore30(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core30)
{
@@ -1447,7 +1446,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.0 APIs");
}
internal static unsafe void LoadGLcore31(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore31(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core31)
{
@@ -1478,7 +1477,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.1 APIs");
}
internal static unsafe void LoadGLcore32(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore32(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core32)
{
@@ -1513,7 +1512,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.2 APIs");
}
internal static unsafe void LoadGLcore33(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore33(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core33)
{
@@ -1557,7 +1556,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.3 APIs");
}
internal static unsafe void LoadGLcore40(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore40(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core40)
{
@@ -1619,7 +1618,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.0 APIs");
}
internal static unsafe void LoadGLcore41(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore41(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core41)
{
@@ -1723,7 +1722,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.1 APIs");
}
internal static unsafe void LoadGLcore42(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore42(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core42)
{
@@ -1751,7 +1750,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.2 APIs");
}
internal static unsafe void LoadGLcore43(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore43(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core43)
{
@@ -1811,7 +1810,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.3 APIs");
}
internal static unsafe void LoadGLcore44(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore44(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core44)
{
@@ -1836,7 +1835,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.4 APIs");
}
internal static unsafe void LoadGLcore45(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore45(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core45)
{
@@ -1962,7 +1961,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.5 APIs");
}
internal static unsafe void LoadGLcore46(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore46(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core46)
{
@@ -29,7 +29,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using System;
@@ -58,22 +58,24 @@ namespace StgSharp
namespace StgSharp.Graphics.OpenGL
{
public unsafe partial class GlFunction
public unsafe partial class OpenGLFunction
{
private static Dictionary<IntPtr, GlFunction> contextToGLMap = new Dictionary<IntPtr, GlFunction>();
private static Dictionary<IntPtr, OpenGLFunction> contextToGLMap = new Dictionary<IntPtr, OpenGLFunction>();
private OpenglContext* _context;
private GlFunction()
private OpenGLFunction()
{
textureUnitCountGetter = new Lazy<int>(() => GetMaskInteger(GLconst.MAX_TEXTURE_IMAGE_UNITS));
unusedTextureImageUintInitilizing = new Lazy<ConcurrentQueue<TextureUnit>>(InitializeUnusedTextureImageUint);
}
internal static GlFunction CurrentGL { get; set; }
internal IntPtr ContextHandle => (IntPtr)_context;
internal static OpenGLFunction CurrentGL { get; set; }
protected ref OpenglContext Context
{
get
@@ -89,11 +91,32 @@ namespace StgSharp.Graphics.OpenGL
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ActiveTexture(uint type)
public void ActiveTextureUnit(uint type)
{
Context.glActiveTexture(type);
}
[Conditional("DEBUG")]
public void Assert(bool shouldReportWhenNormal)
{
try
{
uint code = Context.glGetError();
if (code != GLconst.NO_ERROR)
{
throw new GlExecutionException(code);
}
if (shouldReportWhenNormal)
{
Console.WriteLine("OpenGL runs normally");
}
}
catch (GlExecutionException ex)
{
throw ex;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AttachShader(GlHandle program, GlHandle shader)
{
@@ -108,7 +131,7 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Bind a frame buffer to a frame buffer target
/// Same function as <see href="https://docs.GL/gl3/glBindFramebuffer">glBindFramebuffer</see>.
/// Same function as <see href="https://docs._gl/gl3/glBindFramebuffer">glBindFramebuffer</see>.
/// </summary>
/// <param name="target"> The frame buffer target of the binding operation.</param>
/// <param name="handle"> The handle of the frame buffer object to bind.</param>
@@ -160,33 +183,6 @@ namespace StgSharp.Graphics.OpenGL
while (Context.glGetError() != 0) { }
}
[Conditional("DEBUG")]
public void Assert(bool shouldReportWhenNormal)
{
try
{
uint code = Context.glGetError();
if (code != GLconst.NO_ERROR)
{
throw new GlExecutionException(code);
}
if (shouldReportWhenNormal)
{
Console.WriteLine("OpenGL runs normally");
}
}
catch (GlExecutionException ex)
{
throw ex;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GenerateMipmap(Texture2DTarget target)
{
Context.glGenerateMipmap((uint)target);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void ClearGraphicError()
{
@@ -292,7 +288,7 @@ namespace StgSharp.Graphics.OpenGL
TypeCode.UInt16 => GLconst.UNSIGNED_SHORT,
TypeCode.Byte => GLconst.UNSIGNED_BYTE,
_ => throw new ArgumentException(
$"{($"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}")}{($"{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}")}")
$"{$"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}"}{$"{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}"}")
};
Context.glDrawElements((uint)mode, count, a, (void*)ptr);
}
@@ -354,6 +350,12 @@ namespace StgSharp.Graphics.OpenGL
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GenerateMipmap(Texture2DTarget target)
{
Context.glGenerateMipmap((uint)target);
}
public unsafe GlHandle[] GenFrameBuffers(int count)
{
GlHandle[] h = new GlHandle[count];
@@ -498,6 +500,7 @@ namespace StgSharp.Graphics.OpenGL
Context.glReadPixels(
beginPosition.X, beginPosition.Y, i.Width, i.Height, (uint)format, (uint)dataType, bptr);
}
i.PixelUpdateCount++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -665,7 +668,7 @@ namespace StgSharp.Graphics.OpenGL
#endif
{
#pragma warning disable CS8500
fixed (T* tptr = ((pixels == null) || (pixels.Length == 0)) ? pixels : null)
fixed (T* tptr = ((pixels == null) || (pixels.Length == 0)) ? null : pixels)
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, tptr);
@@ -697,7 +700,7 @@ namespace StgSharp.Graphics.OpenGL
Context.glTexParameteri((uint)target, pname, param);
}
public static bool TryGetFunctionPackage(IntPtr handle, out GlFunction functionPackage)
public static bool TryGetFunctionPackage(IntPtr handle, out OpenGLFunction functionPackage)
{
return contextToGLMap.TryGetValue(handle, out functionPackage);
}
@@ -726,19 +729,19 @@ namespace StgSharp.Graphics.OpenGL
Context.glFinish();
}
internal static GlFunction BuildGlFunctionPackage(IntPtr handle)
internal static OpenGLFunction BuildGlFunctionPackage(IntPtr handle)
{
GlFunction pack;
OpenGLFunction pack;
if (contextToGLMap.TryGetValue(handle, out pack))
{
return pack;
}
pack = new GlFunction { _context = (OpenglContext*)handle };
pack = new OpenGLFunction { _context = (OpenglContext*)handle };
contextToGLMap.Add(handle, pack);
return pack;
}
~GlFunction()
~OpenGLFunction()
{
contextToGLMap.Remove(ContextHandle);
}
@@ -28,7 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Logic;
using StgSharp.Math;
using System;
@@ -45,9 +45,10 @@ namespace StgSharp.Graphics.OpenGL
public abstract partial class glRenderStream : RenderStream
{
private GlFunction _context;
internal protected GlFunction GL
private OpenGLFunction _context;
protected internal OpenGLFunction GL
{
get { return _context; }
}
@@ -69,11 +70,11 @@ namespace StgSharp.Graphics.OpenGL
}
if (GL == null)
{
_context = GlFunction.BuildGlFunctionPackage(ContextHandle);
_context = OpenGLFunction.BuildGlFunctionPackage(ContextHandle);
}
if (GlFunction.CurrentGL != GL)
if (OpenGLFunction.CurrentGL != GL)
{
GlFunction.CurrentGL = GL;
OpenGLFunction.CurrentGL = GL;
InternalIO.glfwMakeContextCurrent(CanvasHandle);
}
}
@@ -0,0 +1,99 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glResourceManager.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the ¡°Software¡±), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ¡°AS IS¡±,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace StgSharp.Graphics.OpenGL
{
public partial class OpenGLFunction
{
private Lazy<int> textureUnitCountGetter;
private Lazy<ConcurrentQueue<TextureUnit>> unusedTextureImageUintInitilizing;
public int TextureUnitCount
{
get => textureUnitCountGetter.Value;
}
private ConcurrentQueue<TextureUnit> UnusedTextureImageUint
{
get => unusedTextureImageUintInitilizing.Value;
}
internal void ReturnAvailableUnit(IEnumerable<TextureUnit> source)
{
int v = GLconst.TEXTURE0 + TextureUnitCount;
foreach (TextureUnit unit in source)
{
if ((int)unit > v)
{
throw new InvalidOperationException("Source contains texture unit beyond context support.");
}
}
}
internal int TryGetAvailableTextureUnit(int count, out IEnumerable<TextureUnit> result)
{
result = new Queue<TextureUnit>();
for (int i = 0; i < count; i++)
{
if (UnusedTextureImageUint.TryDequeue(out TextureUnit unit))
{
(result as Queue<TextureUnit>)!.Enqueue(unit);
}
else
{
return i;
}
}
return count;
}
private ConcurrentQueue<TextureUnit> InitializeUnusedTextureImageUint()
{
ConcurrentQueue<TextureUnit> result = new ConcurrentQueue<TextureUnit>();
for (int index = 0; index < TextureUnitCount; index++)
{
result.Enqueue((TextureUnit)(GLconst.TEXTURE0 + index));
}
return result;
}
}
}
+38 -5
View File
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Pixels.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
@@ -7,22 +37,25 @@ namespace StgSharp.Graphics
{
public interface IPixel
{
internal int Size { get; }
public float Red { get; set; }
public float Green { get; set; }
public float Blue { get; set; }
public float Alpha { get; set; }
internal int Size { get; }
}
[StructLayout(LayoutKind.Explicit,Size = 32)]
[StructLayout(LayoutKind.Explicit, Size = 32)]
public unsafe struct Pixel32
{
[FieldOffset(0)]private unsafe fixed byte data[4];
[FieldOffset(0)] private unsafe fixed byte data[4];
internal int Size => 4;
}
@@ -1,4 +1,34 @@
using StgSharp.Geometries;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="PlainGeometryMesh.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Geometries;
using StgSharp.Math;
using System;
@@ -12,15 +42,26 @@ namespace StgSharp.Graphics
{
public class PlainGeometryMesh
{
private PlainGeometry _shape;
private TextureProvider _texture;
public PlainGeometryMesh([NotNull] PlainGeometry shape, [NotNull] TextureProvider texture)
{
if (shape.VertexCount > texture.TextureCoordinate.Length)
{
throw new ArgumentException(paramName: nameof(texture), message: "Amount of texture coordination is too less");
}
_texture = texture;
_shape = shape;
}
//private Image _texture;
public PlainGeometryMesh(
PlainGeometry shape, Image texture, vec2d[] texCoord
)
{
if (shape==null)
if (shape == null)
{
throw new ArgumentNullException(nameof(shape));
}
@@ -33,34 +74,25 @@ namespace StgSharp.Graphics
{
throw new ArgumentException(paramName: nameof(texCoord), message: "Amount of texture coordination is too less");
}
_texture = new TextureProvider(texture,texCoord);
_texture = new TextureProvider(texture, texCoord);
}
public PlainGeometryMesh([NotNull]PlainGeometry shape, [NotNull]TextureProvider texture)
public vec4d[] VertexArray => _shape.VertexStream;
public Image TextureImage
{
if (shape.VertexCount > texture.TextureCoordinate.Length)
{
throw new ArgumentException(paramName: nameof(texture), message: "Amount of texture coordination is too less");
}
_texture = texture;
_shape = shape;
get => _texture.ProvideImage();
internal set => _texture.ReadImage(value);
}
public ReadOnlySpan<int> MeshIndices => _shape.VertexIndices;
public ReadOnlySpan<vec4d> TextureCoord => MemoryMarshal.Cast<vec2d, vec4d>(_texture.TextureCoordinate);
public PlainGeometryMesh Resize(PlainGeometry newShape)
{
return new PlainGeometryMesh(newShape, _texture);
}
public ReadOnlySpan<int> MeshIndices => _shape.VertexIndices;
public vec4d[] VertexArray => _shape.VertexStream;
public Image TextureImage
{
get => _texture.ProvideImage();
internal set => _texture.ReadImage( value);
}
public ReadOnlySpan<vec4d> TextureCoord => MemoryMarshal.Cast<vec2d,vec4d>( _texture.TextureCoordinate);
}
}
+21 -17
View File
@@ -29,7 +29,8 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using StgSharp.Logic;
using StgSharp.Timing;
using StgSharp.Math;
using StgSharp.MVVM;
using StgSharp.MVVM.View;
@@ -45,13 +46,14 @@ using System.Threading.Tasks;
namespace StgSharp.Graphics
{
public abstract class RenderStream
public abstract class RenderStream
{
private protected (int x, int y, int z) _coordStretch;
private Camera nativeCamera;
private protected ViewPort primeArgs;
private Camera nativeCamera;
internal TimeSpanProvider _timeProvider;
public (int width, int height) Size
{
get => (Width, Height);
@@ -63,6 +65,11 @@ namespace StgSharp.Graphics
}
}
public abstract bool IsContextSharable
{
get;
}
public int Height
{
get => primeArgs.Height;
@@ -81,11 +88,6 @@ namespace StgSharp.Graphics
internal set => primeArgs.Monitor = value;
}
public abstract bool IsContextSharable
{
get;
}
public string Name
{
get => primeArgs.Name;
@@ -98,6 +100,7 @@ namespace StgSharp.Graphics
get => primeArgs;
internal set => primeArgs = value;
}
internal IntPtr CanvasHandle { get => primeArgs.ViewPortID; }
@@ -113,6 +116,11 @@ namespace StgSharp.Graphics
internal set => nativeCamera = value;
}
protected float FramePassed
{
get => _timeProvider.CurrentSpan;
}
protected int PassedFrames
{
get => _timeProvider.CurrentSpan;
@@ -123,11 +131,6 @@ namespace StgSharp.Graphics
get => _timeProvider.CurrentSecond;
}
protected float FramePassed
{
get => _timeProvider.CurrentSpan;
}
protected TimeSpanProvider TimeProvider
{
get => _timeProvider;
@@ -148,16 +151,16 @@ namespace StgSharp.Graphics
where TTarget : RenderStream, new()
{
TTarget target = new TTarget();
target.Initialize(source.Port,source._coordStretch,source._timeProvider);
target.Initialize(source.Port, source._coordStretch, source._timeProvider);
return target;
}
internal protected static void PollEvents()
protected internal static void PollEvents()
{
InternalIO.glfwPollEvents();
}
internal protected void SwapBuffers()
protected internal void SwapBuffers()
{
InternalIO.glfwSwapBuffers(CanvasHandle);
}
@@ -217,6 +220,7 @@ namespace StgSharp.Graphics
#endregion
}
}
@@ -43,14 +43,15 @@ namespace StgSharp.Graphics.ShaderEdit
{
public class ShaderGenerator
{
private Dictionary<int,ShaderParameter> uniformDefine;
private Dictionary<int, ShaderParameter> uniformDefine;
private List<string> codeList;
private List<ShaderFunction> usedShaderFunctions;
public Uniform<T> DefineUniform<T>(string name, int index) where T : struct
{
ShaderParameter p = new ShaderParameter(name,ShaderParameter.TypeMarshal<T>());
uniformDefine.Add(index,p);
ShaderParameter p = new ShaderParameter(name, ShaderParameter.TypeMarshal<T>());
uniformDefine.Add(index, p);
//return new Uniform<TView>();
throw new NotImplementedException();
}
@@ -59,10 +60,11 @@ namespace StgSharp.Graphics.ShaderEdit
public class ShaderFunction
{
private List<string> codeList;
private List<ShaderParameter> inputList;
private string name;
private ShaderParameter outPut;
private string name;
public int ParameterCount => inputList.Count;
@@ -104,10 +106,11 @@ namespace StgSharp.Graphics.ShaderEdit
public class ShaderParameter
{
public static readonly ShaderParameter Void = new ShaderParameter(string.Empty, InternalShaderType.Void);
internal readonly bool isReadOnly;
internal readonly string name;
internal readonly InternalShaderType type;
internal readonly string name;
public ShaderParameter(string name, InternalShaderType type)
{
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ShaderStruct.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -10,14 +40,19 @@ namespace StgSharp.Graphics.ShaderEdit
{
public class ShaderStructMember
{
internal InternalShaderType type;
internal object value;
}
public class ShaderStruct
{
internal Dictionary<GlHandle, ShaderStructMember> uniformPair;
internal ShaderStruct() { }
public ShaderStruct(params (GlHandle, ShaderStructMember)[] uniformPairs)
{
uniformPair = new Dictionary<GlHandle, ShaderStructMember>();
@@ -26,28 +61,28 @@ namespace StgSharp.Graphics.ShaderEdit
return;
}
foreach (var item in uniformPairs)
foreach ((GlHandle, ShaderStructMember) item in uniformPairs)
{
uniformPair.Add(item.Item1,item.Item2);
uniformPair.Add(item.Item1, item.Item2);
}
}
internal ShaderStruct() { }
public unsafe void SetAllUniforms()
{
OpenglContext* gl = (OpenglContext*)OpenGL.GlFunction.CurrentGL.ContextHandle;
foreach (var uniform in uniformPair)
OpenglContext* gl = (OpenglContext*)OpenGL.OpenGLFunction.CurrentGL.ContextHandle;
foreach (KeyValuePair<GlHandle, ShaderStructMember> uniform in uniformPair)
{
int id = uniform.Key.SignedValue;
ShaderStructMember s = uniform.Value;
switch (s.type)
{
case InternalShaderType.Struct: throw new ArgumentException(
case InternalShaderType.Struct:
throw new ArgumentException(
"Incorrect type \"Struct\" defined in this self define type");
case InternalShaderType.Void:throw new ArgumentException(
case InternalShaderType.Void:
throw new ArgumentException(
"Incorrect type \"Void\" defined in this self define type");
case InternalShaderType.Float:
gl->glUniform1f(id, (float)s.value);
@@ -62,5 +97,6 @@ namespace StgSharp.Graphics.ShaderEdit
}
}
}//------------------------------------ End of Class ---------------------------------------
}
}
@@ -1,32 +0,0 @@
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace StgSharp.Graphics
{
public class TextureImage : IImageProvider
{
private Image _tex;
private vec2d[] _texCoord;
Image IImageProvider.ProvideImage()
{
return _tex;
}
public TextureImage(Image image, vec2d[] coord)
{
_tex = image;
_texCoord = coord;
}
public ref vec2d this[int index]
{
get => ref _texCoord[index];
}
}
}
+38 -4
View File
@@ -1,4 +1,36 @@
using StgSharp.Logic;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TexturePipeline.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.BluePrint;
using System;
using System.Collections.Generic;
@@ -8,19 +40,21 @@ using System.Threading.Tasks;
namespace StgSharp.Graphics
{
public class TexturePipeline:BlueprintPipelineArgs
public class TexturePipeline : BlueprintPipelineArgs
{
private Image _value;
public TexturePipeline(Image i)
{
_value = i;
}
private Image _value;
public new Image Value
{
get => _value;
set => _value = value ?? throw new ArgumentNullException(nameof(value));
}
}
}
+46 -15
View File
@@ -1,4 +1,34 @@
using StgSharp.Math;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TextureProvider.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
using System.Collections.Generic;
@@ -9,8 +39,20 @@ namespace StgSharp.Graphics
{
public class TextureProvider : IImageProvider
{
private Image _tex;
private vec2d[] _texCoord;
private Image _tex;
public TextureProvider(Image image, vec2d[] coord)
{
_tex = image;
_texCoord = coord;
}
public ref vec2d this[int index]
{
get => ref _texCoord[index];
}
public Span<vec2d> TextureCoordinate
{
@@ -22,15 +64,9 @@ namespace StgSharp.Graphics
return _tex;
}
public TextureProvider(Image image, vec2d[] coord)
public void ReadImage(IImageProvider provider)
{
_tex = image;
_texCoord = coord;
}
public ref vec2d this[int index]
{
get => ref _texCoord[index];
_tex = provider.ProvideImage();
}
public void UpdateFromImage(Image i)
@@ -50,10 +86,5 @@ namespace StgSharp.Graphics
}
public void ReadImage(IImageProvider provider)
{
_tex = provider.ProvideImage();
}
}
}
@@ -1,74 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="FormThreading.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using StgSharp.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Graphics
{
public partial class View
{
internal Blueprint localLogic;
/*
private void GatherSingleFrameAsyncThread(MethodInfo[] methods)
{
if (methods.Length == 0)
{
return;
}
foreach (MethodInfo m in methods) //find all methods decorated by RenderActivityAttribute
{
RenderActivityAttribute attr = m.GetCustomAttribute<RenderActivityAttribute>(false);
if (attr == null)
{
continue;
}
if (!m.IsStatic && (m.GetParameters().Length != 0) && (m.ReturnType != typeof(void)))
{
throw new NotSupportedException("A render activity cannot have parameters, returning value or be static.");
}
ThreadStart s = (ThreadStart)Delegate.CreateDelegate(typeof(ThreadStart), this, m);
FrameAsyncThread thread = new(s, attr._priority);
//singleFrameAsyncThreadList.Add(thread);
}
}
/**/
}
}
-202
View File
@@ -1,202 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="View.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Logic;
using StgSharp.Math;
using StgSharpDebug.Logic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace StgSharp.Graphics
{
/// <summary>
/// View is the base type for all view types, providing context binding and control element binding.
/// A complete view should contain one complete <see cref="ViewDesigner{T}"/>, <see cref="ViewRender{TView}"/>, and <see cref="ViewResponder"/>,
/// which provide layout descriptions of control elements, user responses, and rendering implementations in the view.
/// Data between instances of <see cref="ViewDesigner{T}"/>, <see cref="ViewRender{TView}"/>, and <see cref="ViewResponder{T}"/> is shared through <see cref="ViewBase"/>.
/// </summary>
public abstract unsafe partial class View
{
private delegate bool GetDataBindingEntryDelegate(string name, out DataBindingEntry entry);
private (int x, int y, int z) unitCubeSize;
private TimeSpanProvider time;
private GetDataBindingEntryDelegate getDataBindingEntry;
private ViewPort context;
private ViewDesigner<View> _design;
private ViewRender<View> _render;
private ViewResponder<View> _responder;
public View()
{
}
public View(ViewPort vp)
{
context = vp;
unitCubeSize = (1, 1, 1);
SelfName = string.Empty;
}
public View(ViewPort vp, (int, int, int) cubeSize)
{
context = vp;
unitCubeSize = cubeSize;
SelfName = string.Empty;
}
public DataBindingEntry this[string name]
{
get
{
if (TryGetObjectReference(name, out DataBindingEntry entry))
{
return entry;
}
if (getDataBindingEntry(name, out entry))
{
return entry;
}
throw new KeyNotFoundException();
}
}
public (int x, int y, int z) UnitCubeSize
{
get => unitCubeSize;
}
public bool Activated { get; internal set; }
public int Height
{
get => context.Height;
private set { context.Height = value; }
}
public int Width
{
get => context.Width;
private set { context.Width = value; }
}
public IntPtr Monitor => context.Monitor;
public IntPtr ViewHandle => context.ViewPortID;
public string ContextName => context.Name;
public string SelfName { get; set; }
public ViewDesigner<View> Designer
{
get => _design;
protected set => _design = value;
}
public ViewPort Port
{
get => context;
}
public ViewRender<View> Render
{
get => _render;
protected set => _render = value;
}
public ViewResponder<View> Responder
{
get => _responder;
protected set => _responder = value;
}
/// <summary>
/// Get the status of a certain key on the keyboard.
/// </summary>
/// <param name="key"></param>
/// <returns><see cref="KeyStatus"/> representing if a key is pressed or released.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public KeyStatus GetKeyStatus(KeyboardKey key)
{
return InternalIO.glfwGetKey(context.ViewPortID, (int)key);
}
public abstract bool TryGetObjectReference(string name, out DataBindingEntry entry);
private int usedFrame = 0;
public void Use()
{
if (usedFrame == 0)
{
ValidateInitialization();
}
}
internal TimeSpanProvider TimeProvider
{
get => time;
}
public bool ValidateInitialization()
{
return _design != null && _render != null && getDataBindingEntry != null && _responder != null;
}
internal protected abstract void Show();
public void InternalInitialize(ViewModelBase viewModelBinding)
{
getDataBindingEntry = viewModelBinding.TryGetObjectReference;
context = viewModelBinding.ViewPortBinding;
time = viewModelBinding.frameTimeProvider;
}
public abstract void CustomizedInitialize(ViewModelBase viewModelBinding);
}
}
@@ -1,145 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewPort.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace StgSharp.Graphics
{
public class ViewPort
{
private int _width, _height;
private FrameBufferSizeHandler _sizeHandler;
private FramePositionHandler _positionHandler;
internal ViewPort()
{
_height = 800;
_width = 600;
Name = new StackFrame(1, false).
GetMethod()!.DeclaringType!.Name;
Monitor = IntPtr.Zero;
ViewPortID = InternalIO.glfwCreateWindow(_width, _height,
Encoding.UTF8.GetBytes(Name), Monitor, IntPtr.Zero
);
if (ViewPortID == IntPtr.Zero)
{
throw new InvalidOperationException("Unable to create viewport handle.");
}
}
public ViewPort(vec2d size, string name, IntPtr monitor)
{
_width = (int)size.X;
_height = (int)size.Y;
Name = name;
Monitor = monitor;
ViewPortID = InternalIO.glfwCreateWindow(_width, _height,
Encoding.UTF8.GetBytes(Name), Monitor, IntPtr.Zero
);
if (ViewPortID == IntPtr.Zero)
{
throw new InvalidOperationException("Unable to create viewport handle.");
}
}
public unsafe int Height
{
get
{
return _height;
}
set
{
InternalIO.glfwSetWindowSize(this.ViewPortID, _width, value);
}
}
public unsafe int Width
{
get
{
return _width;
}
set
{
InternalIO.glfwSetWindowSize(this.ViewPortID, value, _height);
}
}
public IntPtr GraphicHandle { get; internal set; }
public IntPtr Monitor { get; internal set; }
public IntPtr ViewPortID { get; private set; }
public string Name { get; set; }
public void Close()
{
InternalIO.glfwSetWindowShouldClose(this.ViewPortID,1);
}
internal unsafe void FlushSize()
{
fixed (int* wptr = &_width, hptr = &_height)
{
InternalIO.glfwGetWindowSize(ViewPortID, wptr, hptr);
}
}
public FrameBufferSizeHandler FrameSizeCallback
{
set
{
_sizeHandler = value;
IntPtr handlerPtr = Marshal.GetFunctionPointerForDelegate(_sizeHandler);
InternalIO.glfwSetFramebufferSizeCallback(ViewPortID, handlerPtr);
}
}
public FramePositionHandler FramePostionCallback
{
set
{
_positionHandler = value;
IntPtr handlerPtr = Marshal.GetFunctionPointerForDelegate(_positionHandler);
InternalIO.glfwSetWindowPosCallback(ViewPortID,handlerPtr);
}
}
}
}
@@ -1,95 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="FormThreading.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using StgSharp.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace StgSharp.Graphics
{
public abstract class ViewRender<TView>
where TView:View
{
private TView _binding;
protected ViewModelBase ModelBinding { get; set; }
private Dictionary<string, RenderStream> _render;
public TView Binding => _binding;
protected ViewDesigner<TView> Design => _binding.Designer as ViewDesigner<TView>;
protected ViewResponder<TView> Responder => _binding.Responder as ViewResponder<TView>;
protected Dictionary<string, RenderStream> Render
{
get => _render;
}
protected ViewPort ContextBinding;
public T BuildNewRenderStream<T>(ViewPort arg, (int x, int y, int z) unitCubeSize) where T : RenderStream,new()
{
T ret = new T();
ret.Init(arg, unitCubeSize);
ret.timeProvider = this.Binding.TimeProvider;
return ret;
}
public RenderStream this[string renderName]
{
get => _render.TryGetValue(renderName, out RenderStream stream) ? stream : null;
internal set
{
if (_render.ContainsKey(renderName))
{
_render[renderName] = value;
}
else
{
_render.Add(renderName, value);
}
}
}
public abstract void CustomizedInitialize();
public abstract bool ValidateInitializing();
}
}