daily update on 20241002 by nitload youmu, intrinsic function rebuild, syntax style arrange

This commit is contained in:
Nitload
2024-10-03 04:03:06 +08:00
parent 0979123ac0
commit 6e2f93b053
265 changed files with 26732 additions and 19058 deletions
@@ -29,60 +29,60 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Collections;
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;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
/// <summary>
/// A collection of a sets of OpenGL textures. The collection can automatically select one of the
/// texture with minimum costs to upgrade pixels to buffer. Usually <see cref="AutoTextureGL"/> is used for
/// <see cref="IImageProvider"/> loading, but not for target of
/// <see cref="OpenGLFunction.FrameBufferTexture2d(FrameBufferTarget, uint, Texture2DTarget, GlHandle, int)"/>.
/// A collection of a sets of OpenGL textures. The collection can automatically select one of
/// the texture with minimum costs to upgrade pixels to buffer. Usually <see
/// cref="AutoTextureGL" /> is used for <see cref="IImageProvider" /> loading, but not for
/// target of <see cref="OpenGLFunction.FrameBufferTexture2d(FrameBufferTarget, uint,
/// Texture2DTarget, GlHandle, int)" />.
/// </summary>
public sealed class AutoTextureGL
{
private BidirectionalDictionary<Image, int> imageIndexMap = new BidirectionalDictionary<Image, int>();
private Dictionary<Image, int> imageUpdateIndex = new Dictionary<Image, int>();
private TextureProperty[] propertyCache;
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)
private AutoTextureGL( TextureGL texture )
{
texturePackage = texture;
_size = texture.Count;
imageIndexMap = new BidirectionalDictionary<Image, int>();
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
Enumerable.Range( 0, _size ) );
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
public AutoTextureGL(int textureObjectSize, [NotNull]glRender binding)
public AutoTextureGL( int textureObjectSize, [NotNull]glRender binding )
{
this._size = textureObjectSize;
imageIndexMap = new BidirectionalDictionary<Image, int>();
texturePackage = new TextureGL(textureObjectSize, binding);
texturePackage = new TextureGL( textureObjectSize, binding );
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
Enumerable.Range( 0, _size ) );
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
@@ -93,75 +93,70 @@ namespace StgSharp.Graphics.OpenGL
set => _textureProperty = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SelectTextureAndBind(Image i)
private OpenGLFunction GL
{
get => texturePackage.GL;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SelectTextureAndBind( Image i )
{
TextureProperty property = _textureProperty;
SelectTextureAndBind(i, property);
SelectTextureAndBind( i, property );
}
public void SelectTextureAndBind([NotNull]Image i, TextureProperty property)
public void SelectTextureAndBind(
[NotNull]Image i,
TextureProperty property )
{
//usable texture with image match
if (imageIndexMap.TryGetValue(i, out int index))
{
if( imageIndexMap.TryGetValue( i, out int index ) ) {
//prop setting match
if (propertyCache[index] == property)
{
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);
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
{
_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))
{
} 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
{
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;
usedTextureIndex.AddLast( reusedIndex );
imageIndexMap[ i ] = reusedIndex;
propertyCache[ newIndex ] = property;
imageUpdateIndex[ i ] = i.PixelUpdateCount;
}
}
}
public static AutoTextureGL ToAuto([NotNull]TextureGL texture)
public static AutoTextureGL ToAuto( [NotNull]TextureGL texture )
{
if (texture.IndexOfCurrentTexture != -1)
{
throw new InvalidOperationException("Texture to be converted has been editted.");
if( texture.IndexOfCurrentTexture != -1 ) {
throw new InvalidOperationException(
"Texture to be converted has been editted." );
}
return new AutoTextureGL(texture);
return new AutoTextureGL( texture );
}
}
}
@@ -41,42 +41,50 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
/// <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.
/// 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 sealed unsafe class ElementBuffer : GlBufferObjectBase
{
internal ElementBuffer(int n, glRender binding) : base(binding)
internal ElementBuffer( int n, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenBuffers(n);
_bufferHandle = GL.GenBuffers( n );
}
public override sealed void Bind(int index)
public override sealed void Bind( int index )
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
}
public void SetValue<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct, IConvertible
public void SetValue<T>( int index, T[] bufferArray, BufferUsage usage )
where T: struct, IConvertible
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ElementArrayBuffer, bufferArray, usage);
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData(
BufferType.ElementArrayBuffer, bufferArray, usage );
}
public void SetValue<T>(int index, ReadOnlySpan<T> bufferSpan, BufferUsage usage)
where T : struct, IConvertible
public void SetValue<T>(
int index,
ReadOnlySpan<T> bufferSpan,
BufferUsage usage )
where T: struct, IConvertible
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ElementArrayBuffer, bufferSpan, usage);
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData( BufferType.ElementArrayBuffer, bufferSpan,
usage );
}
protected override sealed void Dispose(bool disposing)
protected override sealed void Dispose( bool disposing )
{
if (disposing)
{
GL.DeleteBuffers(_bufferHandle);
if( disposing ) {
GL.DeleteBuffers( _bufferHandle );
}
}
@@ -40,55 +40,59 @@ using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
#pragma warning disable CA1008
#pragma warning disable CA1028
#pragma warning disable CA1008
#pragma warning disable CA1028
public enum FrameBufferTarget : uint
#pragma warning restore CA1028
#pragma warning restore CA1008
#pragma warning restore CA1028
#pragma warning restore CA1008
{
Read = GLconst.READ_FRAMEBUFFER,
All = GLconst.FRAMEBUFFER,
Draw = GLconst.DRAW_FRAMEBUFFER,
}
public sealed class FrameBuffer : GlBufferObjectBase
{
internal unsafe FrameBuffer(int count, glRender binding) : base(binding)
internal unsafe FrameBuffer( int count, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenFrameBuffers(count);
_bufferHandle = GL.GenFrameBuffers( count );
}
/// <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.
/// 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>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override unsafe void Bind(int index)
/// <param name="index"> Index of object to be binded in handle set </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public override unsafe void Bind( int index )
{
GL.BindFrameBuffer(FrameBufferTarget.All, _bufferHandle[index]);
GL.BindFrameBuffer( FrameBufferTarget.All, _bufferHandle[ index ] );
}
/// <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.
/// 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>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Bind(FrameBufferTarget target, int index)
/// <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>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Bind( FrameBufferTarget target, int index )
{
GL.BindFrameBuffer(target, _bufferHandle[index]);
GL.BindFrameBuffer( target, _bufferHandle[ index ] );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void BindNull()
{
OpenGLFunction.CurrentGL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero);
OpenGLFunction.CurrentGL
.BindFrameBuffer( FrameBufferTarget.All, GlHandle.Zero );
}
protected override void Dispose(bool disposing)
protected override void Dispose( bool disposing )
{
throw new NotImplementedException();
}
@@ -41,7 +41,7 @@ namespace StgSharp.Graphics.OpenGL
private readonly glRender _contextBinding;
protected GlBufferObjectBase(glRender contextBinding)
protected GlBufferObjectBase( glRender contextBinding )
{
binding = contextBinding;
_contextBinding = contextBinding;
@@ -35,36 +35,38 @@ using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public sealed class RenderBuffer : GlBufferObjectBase
{
public RenderBuffer(int count, glRender binding) : base(binding)
public RenderBuffer( int count, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenRenderBuffer(count);
_bufferHandle = GL.GenRenderBuffer( count );
}
public override void Bind(int index)
public override void Bind( int index )
{
GL.BindRenderBuffer(this[index]);
GL.BindRenderBuffer( this[ index ] );
}
public void Store(RenderBufferInternalFormat format, (int width, int height) size)
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");
if( ( size.width > binding.Width ) || ( size.height > binding.Height ) ) {
StgSharp.LogWarning(
"FrameBuffer is larger than current canvas binding" );
}
}
protected override void Dispose(bool disposing)
protected override void Dispose( bool disposing )
{
throw new NotImplementedException();
foreach( GlHandle item in _bufferHandle ) {
Console.WriteLine( "removing a render buffer" );
GL.DeleteRenderBuffer( item );
}
}
}
@@ -28,7 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Data.Intrinsic;
using StgSharp.Math;
using System;
@@ -58,8 +58,6 @@ namespace StgSharp.Graphics.OpenGL
_textureHandle = _gl.GenTextures( count );
}
internal OpenGLFunction GL => _gl;
public GlHandle this[ int index ]
{
get => _textureHandle[ index ];
@@ -77,12 +75,17 @@ namespace StgSharp.Graphics.OpenGL
get => currentEditingTextureIndex;
}
public void ActivateAs( TextureUnit unit ) { _gl.ActiveTextureUnit( ( uint )unit ); }
internal OpenGLFunction GL => _gl;
public void ActivateAs( TextureUnit unit )
{
_gl.ActiveTextureUnit( ( uint )unit );
}
public void Bind2D( int index )
{
currentEditingTextureIndex = index;
_gl.BindTexture( GLconst.TEXTURE_2D, _textureHandle[ index ] );
_gl.BindTexture( GLconst.TEXTURE_2D, _textureHandle[ index ] );
}
/// <summary>
@@ -94,8 +97,8 @@ namespace StgSharp.Graphics.OpenGL
{
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 );
Texture2DTarget.Texture2D, 0, i.Channel, ( uint )i.Width,
( uint )i.Height, i.Channel, i.PixelLayout, pixels: handle );
_gl.GenerateMipmap( Texture2DTarget.Texture2D );
}
@@ -108,14 +111,17 @@ namespace StgSharp.Graphics.OpenGL
TextureFilter onMagnify )
{
#if DEBUG
if( index != currentEditingTextureIndex )
{
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 );
_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 )]
@@ -125,21 +131,25 @@ namespace StgSharp.Graphics.OpenGL
TextureWrap onVertical )
{
#if DEBUG
if( index != currentEditingTextureIndex )
{
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 );
_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 );
Set2dFilterProperty(
index, property.FilterOnMinify, property.FilterOnMagnify );
Set2dWrapProperty(
index, property.WrapOnHorizontial, property.WrapOnVertical );
}
#endregion texture setting
@@ -192,23 +202,35 @@ namespace StgSharp.Graphics.OpenGL
set => vert = value;
}
public override bool Equals( [NotNullWhen( true )] object obj )
{
return base.Equals( obj );
}
public override int GetHashCode()
{
return HashCode.Combine(
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial, WrapOnVertical );
}
public override bool Equals([NotNullWhen(true)] object obj)
{
return base.Equals(obj);
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial,
WrapOnVertical );
}
public override string ToString()
{
return $"FilterOnMagnify:{FilterOnMagnify}, " +
$"FilterOnMagnify:{FilterOnMagnify}, " +
$"WrapOnHorizontial:{WrapOnHorizontial}, " +
$"WrapOnVertical:{WrapOnVertical}";
return $"FilterOnMagnify:{FilterOnMagnify}, " + $"FilterOnMagnify:{FilterOnMagnify}, " + $"WrapOnHorizontial:{WrapOnHorizontial}, " + $"WrapOnVertical:{WrapOnVertical}";
}
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;
}
public static implicit operator TextureProperty(
@@ -219,18 +241,10 @@ namespace StgSharp.Graphics.OpenGL
{
return new TextureProperty(
propertyValueTuple.onMagnify, propertyValueTuple.onMinify,
propertyValueTuple.onHorizontial, propertyValueTuple.onVertical );
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
@@ -29,7 +29,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
@@ -40,37 +39,41 @@ namespace StgSharp.Graphics.OpenGL
public sealed unsafe class VertexArray : GlBufferObjectBase
{
internal VertexArray(int n, glRender binding) : base(binding)
internal VertexArray( int n, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenVertexArrays(n);
_bufferHandle = GL.GenVertexArrays( n );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override sealed void Bind(int index)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public override sealed void Bind( int index )
{
GL.BindVertexArray(_bufferHandle[index]);
GL.BindVertexArray( _bufferHandle[ index ] );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void BindNull()
{
OpenGLFunction.CurrentGL.BindVertexArray(GlHandle.Zero);
OpenGLFunction.CurrentGL.BindVertexArray( GlHandle.Zero );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetVertexAttribute(uint index, int vertexLength, TypeCode dataType, bool isNomalized, uint stride, int pointer)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetVertexAttribute(
uint index,
int vertexLength,
TypeCode dataType,
bool isNomalized,
uint stride,
int pointer )
{
GL.SetVertexAttribute(
index, vertexLength, dataType,
isNomalized,
stride, pointer);
index, vertexLength, dataType, isNomalized, stride, pointer );
}
protected override sealed void Dispose(bool disposing)
protected override sealed void Dispose( bool disposing )
{
if (disposing)
{
GL.DeleteVertexArrays(_bufferHandle);
if( disposing ) {
GL.DeleteVertexArrays( _bufferHandle );
}
}
@@ -43,108 +43,126 @@ namespace StgSharp.Graphics.OpenGL
public sealed unsafe class VertexBuffer : GlBufferObjectBase
{
internal VertexBuffer(int n, glRender binding) : base(binding)
internal VertexBuffer( int n, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenBuffers(n);
_bufferHandle = GL.GenBuffers( n );
}
public override sealed void Bind(int index)
public override sealed void Bind( int index )
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
}
/// <summary>
///
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Unbind()
{
GL.BindBuffer(BufferType.ArrayBuffer, GlHandle.Zero);
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)
where T : struct, IMat
/// <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
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ArrayBuffer, bufferData, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.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,
/// <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
#endif
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ArrayBuffer, bufferArray, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.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,
/// <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
#endif
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ArrayBuffer, scalerSpan, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.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
/// <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
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferVectorData(BufferType.ArrayBuffer, vectorSpan, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.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
/// <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
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferVectorData(BufferType.ArrayBuffer, vectorArray, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferVectorData( BufferType.ArrayBuffer, vectorArray,
usage );
}
protected override sealed void Dispose(bool disposing)
protected override sealed void Dispose( bool disposing )
{
if (disposing)
{
GL.DeleteBuffers(_bufferHandle);
if( disposing ) {
GL.DeleteBuffers( _bufferHandle );
}
}
@@ -42,22 +42,25 @@ namespace StgSharp.Graphics.ShaderEdit
{
/// <summary>
///
///
/// </summary>
public void DisplayGLtypeDefinition();
/// <summary>
///
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
public void GainAllUniforms(
ShaderProgram source,
params string[] uniformName );
/// <summary>
///
///
/// </summary>
/// <returns></returns>
public ShaderStruct GetConvertedGLtype();
/// <summary>
///
///
/// </summary>
public void SetAllUniforms();
@@ -45,19 +45,21 @@ namespace StgSharp.Graphics.OpenGL
{
/// <summary>
/// Create an instance of <see cref="Shader"/> program
/// Create an instance of <see cref="Shader" /> program
/// </summary>
/// <returns>New instance of <see cref="Shader"/> instance. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
/// <returns> New instance of <see cref="Shader" /> instance. </returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected override sealed ShaderProgram CreateShaderProgram()
{
return new ShaderProgram(this);
return new ShaderProgram( this );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override sealed Shader CreateShaderSegment(ShaderType type, int count)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected override sealed Shader CreateShaderSegment(
ShaderType type,
int count )
{
return new Shader(GL.CreateShaderSet(count, type), type, this);
return new Shader( GL.CreateShaderSet( count, type ), type, this );
}
}
@@ -69,7 +71,10 @@ namespace StgSharp.Graphics.OpenGL
internal readonly GlHandle[] handle;
public readonly ShaderType type;
internal unsafe Shader(GlHandle[] handle, ShaderType usage, glRender stream)
internal unsafe Shader(
GlHandle[] handle,
ShaderType usage,
glRender stream )
{
this.handle = handle;
GL = stream.GL;
@@ -81,60 +86,58 @@ namespace StgSharp.Graphics.OpenGL
/// <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)
/// <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 )
{
GL.AttachShader(target.handle, handle[index]);
GL.AttachShader( target.handle, handle[ index ] );
}
public void CheckStatus(int index, ShaderStatus status)
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}");
string log = GL.GetShaderStatus( this, index, ( int )status );
if( !string.IsNullOrEmpty( log ) ) {
throw new Exception( $"{$"Shader Error \t{status}\n"}{log}" );
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, byte[] codeStream)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Compile( int index, byte[] codeStream )
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
if( codeStream == null ) {
throw new ArgumentNullException( nameof( codeStream ) );
}
GL.LoadShaderSource(handle[index], codeStream);
GL.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
GL.LoadShaderSource( handle[ index ], codeStream );
GL.CompileShader( handle[ index ] );
CheckStatus( index, ShaderStatus.CompileStatus );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, string codeStream)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Compile( int index, string codeStream )
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
if( codeStream == null ) {
throw new ArgumentNullException( nameof( codeStream ) );
}
GL.LoadShaderSource(handle[index], Encoding.ASCII.GetBytes(codeStream));
GL.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
GL.LoadShaderSource(
handle[ index ], Encoding.ASCII.GetBytes( codeStream ) );
GL.CompileShader( handle[ index ] );
CheckStatus( index, ShaderStatus.CompileStatus );
}
public void FromBytes(byte[] stream)
public void FromBytes( byte[] stream )
{
throw new NotImplementedException();
}
public static byte[] FromCodeFile(string fileRoute)
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}");
string str = File.ReadAllText( fileRoute );
if( string.IsNullOrEmpty( str ) ) {
throw new InvalidOperationException(
$"Cannot load and GLSL code from {fileRoute}" );
}
return Encoding.UTF8.GetBytes(str);
return Encoding.UTF8.GetBytes( str );
}
public byte[] GetBytes()
@@ -142,7 +145,7 @@ namespace StgSharp.Graphics.OpenGL
return Array.Empty<byte>();
}
public byte[] GetBytes(out int length)
public byte[] GetBytes( out int length )
{
throw new NotImplementedException();
}
@@ -156,7 +159,9 @@ namespace StgSharp.Graphics.OpenGL
public enum ShaderStatus : int
{
CompileStatus = GLconst.COMPILE_STATUS,
}
public class ShaderProgram
@@ -168,64 +173,63 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// CustomizeInit a program with no shader attached.
/// </summary>
internal unsafe ShaderProgram(glRender binding)
internal unsafe ShaderProgram( glRender binding )
{
GL = binding.GL;
handle = GL.CreateProgram();
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// 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>
/// <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
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe Uniform<T> GetUniform<T>( string name ) where T: struct
{
return new Uniform<T>(GL.GetUniformLocation(this.handle, name));
return new Uniform<T>( GL.GetUniformLocation( this.handle, name ) );
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// 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>
/// <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
public unsafe Uniform<T, U> GetUniform<T, U>( string name )
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>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// 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>
/// <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
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>(GL.GetUniformLocation(this.handle, name));
return new Uniform<T, U, V>(
GL.GetUniformLocation( this.handle, name ) );
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// 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>
/// <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
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>(GL.GetUniformLocation(this.handle, name));
return new Uniform<T, U, V, W>(
GL.GetUniformLocation( this.handle, name ) );
}
/// <summary>
@@ -233,20 +237,18 @@ namespace StgSharp.Graphics.OpenGL
/// </summary>
public unsafe void Link()
{
if (InternalIO.InternalLinkShaderProgram((OpenglContext*)this.GL.ContextHandle, handle.Value) == 0)
{
if( InternalIO.InternalLinkShaderProgram(
( OpenglContext* )this.GL.ContextHandle, handle.Value ) == 0 ) {
IntPtr logPtr = InternalIO.InternalReadSSCLog();
try
{
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);
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);
catch( Exception ex ) {
InternalIO.InternalWriteLog( ex.Message, LogType.Error );
}
}
}
@@ -254,10 +256,10 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Let the current viewPortDisplay use this shader.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Use()
{
GL.UseProgram(handle);
GL.UseProgram( handle );
}
~ShaderProgram()
@@ -52,93 +52,73 @@ namespace StgSharp.Graphics.OpenGL
}
public sealed class Uniform<T> : Uniform
where T : struct
public sealed class Uniform<T> : Uniform where T: struct
{
internal Uniform()
{
internal Uniform() { }
}
internal unsafe Uniform(GlHandle id)
internal unsafe Uniform( GlHandle id )
{
this.id = id;
}
internal static Uniform<T> FromHandle(GlHandle handle)
internal static Uniform<T> FromHandle( GlHandle handle )
{
return new Uniform<T> { id = handle };
}
}
public sealed class Uniform<T, U> : Uniform
where T : struct
where U : struct
public sealed class Uniform<T, U> : Uniform where T: struct where U: struct
{
internal Uniform() { }
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
internal unsafe Uniform( GlHandle id )
{
this.id = id;
}
internal static Uniform<T, U> FromHandle(GlHandle handle)
internal static Uniform<T, U> FromHandle( GlHandle 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
public sealed class Uniform<T, U, V> : Uniform where T: struct
where U: struct
where V: struct
{
internal Uniform()
{
internal Uniform() { }
}
internal unsafe Uniform(GlHandle id)
internal unsafe Uniform( GlHandle id )
{
this.id = id;
}
internal static Uniform<T, U, V> FromHandle(GlHandle handle)
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
where T : struct
where U : struct
where V : struct
where W : struct
public sealed class Uniform<T, U, V, W> : Uniform where T: struct
where U: struct
where V: struct
where W: struct
{
internal Uniform()
{
internal Uniform() { }
}
internal unsafe Uniform(GlHandle id)
internal unsafe Uniform( GlHandle id )
{
this.id = id;
}
internal static Uniform<T, U, V, W> FromHandle(GlHandle handle)
internal static Uniform<T, U, V, W> FromHandle( GlHandle handle )
{
return new Uniform<T, U, V, W> { id = handle };
}
@@ -148,59 +128,71 @@ namespace StgSharp.Graphics.OpenGL
public unsafe partial class OpenGLFunction
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue
(Uniform<Matrix44> uniform, Matrix44 mat)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue( Uniform<Matrix44> uniform, Matrix44 mat )
{
Matrix44 temp = mat;
Context.glUniformMatrix4fv(uniform.id.SignedValue, 1, false, (float*)&temp);
Context.glUniformMatrix4fv(
uniform.id.SignedValue, 1, false, ( float* )&temp );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float, float, float> uniform, vec4d vec)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue(
Uniform<float, float, float, float> uniform,
Vec4 vec )
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
Vec4 temp = vec;
Context.glUniform1fv( uniform.id.SignedValue, 4, &temp );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<vec4d> uniform, vec4d vec)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue( Uniform<Vec4> uniform, Vec4 vec )
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
Vec4 temp = vec;
Context.glUniform1fv( uniform.id.SignedValue, 4, &temp );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float> uniform, float v0)
[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)
[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)
[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)
[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)
[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 );
}
}
}
@@ -34,14 +34,11 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
[AttributeUsage(AttributeTargets.Method)]
[AttributeUsage( AttributeTargets.Method )]
public sealed class OpenGLAPICallingAttribute : Attribute
{
public OpenGLAPICallingAttribute()
{
}
public OpenGLAPICallingAttribute() { }
}
}
File diff suppressed because it is too large Load Diff
@@ -36,6 +36,7 @@ namespace StgSharp.Graphics.OpenGL
{
public static partial class glManager
{
#region coreVersion
private static bool core10 = false;
@@ -682,8 +683,6 @@ namespace StgSharp.Graphics.OpenGL
private static bool WIN_phong_shading;
private static bool WIN_specular_fog;
#endregion
}
}
@@ -0,0 +1,92 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glFucntionSourceManager.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;
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,107 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glRenderSourceGenrator.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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
public partial class glRender
{
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected AutoTextureGL CreateAutoTexture( int count )
{
return new AutoTextureGL( count, this );
}
/// <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 FrameBuffer CreateFrameBuffer( int count )
{
return new FrameBuffer( count, this );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected RenderBuffer CreateRenderBuffer( int count )
{
return new RenderBuffer( 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,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glRender.cs"
// file="glRenderStream.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -28,24 +28,28 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using StgSharp.Threading;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
public abstract partial class glRender : RenderStream
{
private protected static readonly ConcurrentDictionary<glRender, Thread> renderToThread
= new ConcurrentDictionary<glRender, Thread>();
private OpenGLFunction _context;
protected internal OpenGLFunction GL
@@ -54,93 +58,134 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Initialize 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.
/// Initialize an opengl context and load all opengl functions.
/// </summary>
public unsafe void InitializeContext()
{
if( ContextHandle == default ) {
ContextHandle = Marshal.AllocHGlobal(
Marshal.SizeOf( typeof( OpenglContext ) ) );
OpenglContext* contextID = ( OpenglContext* )ContextHandle;
contextID->glGetString = ( delegate*<uint, IntPtr> )IntPtr.Zero;
}
if( GL == null ) {
_context = OpenGLFunction.BuildGlFunctionPackage(
ContextHandle );
}
}
/// <summary>
/// Initialize 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(OpenglContext)));
OpenglContext* contextID = (OpenglContext*)ContextHandle;
contextID->glGetString = (delegate*<uint, IntPtr>)IntPtr.Zero;
}
if (GL == null)
{
_context = OpenGLFunction.BuildGlFunctionPackage(ContextHandle);
}
if (OpenGLFunction.CurrentGL != GL)
{
OpenGLFunction.CurrentGL = GL;
InternalIO.glfwMakeContextCurrent(CanvasHandle);
}
InternalIO.glfwMakeContextCurrent( CanvasHandle );
OpenGLFunction.CurrentGL = this.GL;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void SetSizeLimit(int minWidth, int minHeight, int maxWidth, int maxHeight)
/// <inheritdoc />
public override void RenderEnd()
{
InternalIO.glfwSetWindowSizeLimits(this.CanvasHandle, minWidth, minHeight, maxWidth, maxHeight);
if( !renderToThread.TryGetValue( this,
out Thread t ) || t != Thread.CurrentThread ) {
throw new InvalidOperationException(
$"Current render has had been binded to thread {t!.ManagedThreadId}" );
}
SwapBuffers();
renderToThread[ this ] = ThreadHelper.EmptyThread;
InternalIO.glfwMakeContextCurrent( IntPtr.Zero );
OpenGLFunction.CurrentGL = null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal override sealed void Draw()
/// <inheritdoc />
public override void RenderStart()
{
MakeAsCurrentContext();
Main();
Thread current = Thread.CurrentThread;
if( !renderToThread.TryGetValue( this,
out Thread t ) || t == ThreadHelper.EmptyThread ) {
renderToThread[ this ] = current;
MakeAsCurrentContext();
return;
}
if( t != current ) {
throw new InvalidOperationException(
$"Current render has had been binded to thread {t!.ManagedThreadId}" );
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public override void SetSizeLimit(
int minWidth,
int minHeight,
int maxWidth,
int maxHeight )
{
InternalIO.glfwSetWindowSizeLimits(
this.CanvasHandle, minWidth, minHeight, maxWidth, maxHeight );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
internal override sealed void PlatformSpecifiedInitialize()
{
InitializeContext();
MakeAsCurrentContext();
glManager.LoadOpenGLApiTo(Port.GraphicHandle);
glManager.LoadOpenGLApiTo( BindedViewPortContext.GraphicHandle );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
internal override sealed void Terminate()
{
CustomizeDeinit();
}
protected override sealed Uniform<Matrix44> NativeCameraUniform(ShaderProgram source, string name)
protected override sealed Uniform<Matrix44> NativeCameraUniform(
ShaderProgram source,
string name )
{
NativeCamera.GainAllUniforms(source, 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)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected override sealed void NativeCameraViewRange(
Radius fieldOfRange,
Vec2 offset,
(float frontDepth, float backDepth) viewDepth )
{
NativeCamera.SetViewRange(fieldOfRange, this.Size, offset, viewDepth);
NativeCamera.SetViewRange(
fieldOfRange, this.Size, offset, viewDepth );
}
protected override sealed void NativeCameraViewTarget(vec3d position, vec3d direction, vec3d up)
protected override sealed void NativeCameraViewTarget(
Vec3 position,
Vec3 direction,
Vec3 up )
{
NativeCamera.SetViewDirection(position, direction, up);
NativeCamera.SetViewDirection( position, direction, up );
}
#region Key Control
protected KeyStatus CheckKey(KeyboardKey key)
protected KeyStatus CheckKey( KeyboardKey key )
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
return InternalIO.glfwGetKey( this.CanvasHandle, ( int )key );
}
protected KeyStatus CheckKey(Mouse key)
protected KeyStatus CheckKey( Mouse key )
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
return InternalIO.glfwGetKey( this.CanvasHandle, ( int )key );
}
protected KeyStatus CheckKey(Joystick key)
protected KeyStatus CheckKey( Joystick key )
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
return InternalIO.glfwGetKey( this.CanvasHandle, ( int )key );
}
#endregion
}
}
@@ -0,0 +1,49 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glRenderThreadSecurity.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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
public partial class glRender
{
private static ConcurrentDictionary<Thread, glRender> threadLocalIndex
= new ConcurrentDictionary<Thread, glRender>();
private readonly SynchronizationContext mainThreadContext = SynchronizationContext.Current;
}
}