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
@@ -53,10 +53,5 @@ namespace StgSharp.MVVM
throw new NotImplementedException();
}
protected override void Main()
{
throw new NotImplementedException();
}
}
}
+47 -39
View File
@@ -29,13 +29,14 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Timing;
using StgSharp.Math;
using StgSharp.MVVM.ViewModel;
using StgSharp.Timing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Numerics;
using System.Reflection;
@@ -44,15 +45,16 @@ using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
namespace StgSharp.MVVM.View
{
/// <summary>
/// ViewBase 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"/>.
/// ViewBase 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 ViewBase
@@ -70,46 +72,43 @@ namespace StgSharp.MVVM.View
private ViewPort context;
private delegate bool GetDataBindingEntryDelegate(string name, out DataBindingEntry entry);
private delegate bool GetDataBindingEntryDelegate(
string name,
out DataBindingEntry entry );
public DataBindingEntry this[string name]
public DataBindingEntry this[ string name ]
{
get
{
if (TryGetObjectReference(name, out DataBindingEntry entry))
{
if( getDataBindingEntry( name, out DataBindingEntry entry ) ) {
return entry;
}
if (getDataBindingEntry(name, out entry))
{
if( TryGetObjectReference( name, out entry ) ) {
return entry;
}
throw new KeyNotFoundException();
}
}
internal bool IsWaitingWindowEvent
{
get => context.IsWaitingEvent;
}
public (int x, int y, int z) UnitCubeSize
{
get => unitCubeSize;
}
public bool Activated { get; internal set; }
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;
@@ -124,7 +123,11 @@ namespace StgSharp.MVVM.View
public string ContextName => context.Name;
public string SelfName { get; set; }
public string SelfName
{
get;
set;
}
public ViewPort Port
{
@@ -136,7 +139,7 @@ namespace StgSharp.MVVM.View
get => time;
}
protected IViewRender<ViewBase> Render
protected internal IViewRender<ViewBase> Render
{
get => _render;
set => _render = value;
@@ -148,20 +151,24 @@ namespace StgSharp.MVVM.View
set => _responder = value;
}
public abstract void CustomizedInitialize([NotNull]ViewModelBase viewModelBinding);
public abstract void CustomizedInitialize(
[NotNull]ViewModelBase viewModelBinding );
/// <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)
/// <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);
return InternalIO.glfwGetKey( context.ViewPortID, ( int )key );
}
public void InternalInitialize(string name, (int, int, int) cubeSize, [NotNull]ViewModelBase viewModelBinding)
public void InternalInitialize(
string name,
(int, int, int) cubeSize,
[NotNull]ViewModelBase viewModelBinding )
{
SelfName = name;
unitCubeSize = cubeSize;
@@ -169,32 +176,33 @@ namespace StgSharp.MVVM.View
context = viewModelBinding.ViewPortBinding;
time = viewModelBinding.frameTimeProvider;
CustomizedInitialize(viewModelBinding);
CustomizedInitialize( viewModelBinding );
}
public abstract bool TryGetObjectReference(string name, out DataBindingEntry entry);
public abstract bool TryGetObjectReference(
string name,
out DataBindingEntry entry );
public void Use()
{
if (usedFrame == 0)
{
if (!ValidateInitialization())
{
throw new InvalidOperationException("This view is not correctly initialized before rendering.");
if( usedFrame == 0 ) {
if( !ValidateInitialization() ) {
throw new InvalidOperationException(
"This view is not correctly initialized before rendering." );
}
}
Show();
usedFrame++;
}
public bool ValidateInitialization()
{
return (_design != null) && (_render != null) && (getDataBindingEntry != null) && (_responder != null)
&& _design.ValidateInitializing() && _responder.ValidateInitializing() && _render.ValidateInitializing()
;
return ( _design != null ) && ( _render != null ) && ( getDataBindingEntry != null ) && ( _responder != null ) && _design.ValidateInitializing(
) && _responder.ValidateInitializing() && _render.ValidateInitializing(
);
}
protected internal abstract void Show();
}
}
+34 -31
View File
@@ -44,10 +44,12 @@ namespace StgSharp.MVVM.View
{
public abstract partial class ViewBase
{
public interface IViewDesigner<out TView> where TView : ViewBase
public interface IViewDesigner<out TView> where TView: ViewBase
{
abstract void CustomizedInitialize();
abstract void Initialize();
abstract bool ValidateInitializing();
@@ -55,11 +57,12 @@ namespace StgSharp.MVVM.View
}
/// <summary>
/// ViewDesigner provides descriptions of various controls in the view,
/// binds the controls to specific user actions and behaviors,
/// and describes the layout and interactions of each control.
/// ViewDesigner provides descriptions of various controls in the view, binds the controls
/// to specific user actions and behaviors, and describes the layout and interactions of
/// each control.
/// </summary>
public abstract class ViewDesigner<TView> : IViewDesigner<TView> where TView : ViewBase
public abstract class ViewDesigner<TView> : IViewDesigner<TView>
where TView: ViewBase
{
private KeyboardButtonGroup currentButtonGroup;
@@ -67,7 +70,7 @@ namespace StgSharp.MVVM.View
private List<ControllingItem> _controlList;
protected TView _binding;
public ViewDesigner(TView binding)
public ViewDesigner( TView binding )
{
_binding = binding;
_controlList = new List<ControllingItem>();
@@ -79,52 +82,52 @@ namespace StgSharp.MVVM.View
}
public CharacterLineIndexImage CreateCharacterLine(
int length, char blankFilling, PlainGeometryMesh tittle, IEnumerable<(char, PlainGeometryMesh)> charList
)
int length,
char blankFilling,
PlainGeometryMesh tittle,
IEnumerable<(char, PlainGeometryMesh)> charList )
{
CharacterLineIndexImage ret = new CharacterLineIndexImage(length, blankFilling, tittle, charList);
_controlList.Add(ret);
CharacterLineIndexImage ret = new CharacterLineIndexImage(
length, blankFilling, tittle, charList );
_controlList.Add( ret );
return ret;
}
public TriggerButton CreateKeyboardButton(
Rectangle bonding, TextureProvider defaultAnimation, bool isEnable
)
Rectangle bonding,
TextureProvider defaultAnimation,
bool isEnable )
{
TriggerButton ret = new TriggerButton();
ret.BoundingBox = bonding;
ret.Texture = defaultAnimation;
if (isEnable)
{
if( isEnable ) {
ret.IsDisabled = false;
ret.Enable();
}
else
{
} else {
ret.IsDisabled = true;
ret.Disable();
}
currentButtonGroup.AddButton(ret);
currentButtonGroup.AddButton( ret );
return ret;
}
public TButtonGroup CreateKeyboardButtonGroup<TButtonGroup>(
ITrigger leftBidning,
ITrigger rightBinding,
ITrigger upBinding,
ITrigger downBinding,
ITrigger confirmBinding
)
where TButtonGroup : KeyboardButtonGroup, new()
IClickTrigger leftBidning,
IClickTrigger rightBinding,
IClickTrigger upBinding,
IClickTrigger downBinding,
IClickTrigger confirmBinding )
where TButtonGroup: KeyboardButtonGroup, new()
{
TButtonGroup ret = new TButtonGroup();
_controlList.Add(ret);
_controlList.Add( ret );
currentButtonGroup = ret;
_binding.Responder[leftBidning] = ret.MoveLeft;
_binding.Responder[rightBinding] = ret.MoveRight;
_binding.Responder[upBinding] = ret.MoveUp;
_binding.Responder[downBinding] = ret.MoveDown;
_binding.Responder[confirmBinding] = ret.Confirm;
_binding.Responder[ leftBidning ] = ret.MoveLeft;
_binding.Responder[ rightBinding ] = ret.MoveRight;
_binding.Responder[ upBinding ] = ret.MoveUp;
_binding.Responder[ downBinding ] = ret.MoveDown;
_binding.Responder[ confirmBinding ] = ret.Confirm;
return ret;
}
+43 -26
View File
@@ -28,9 +28,9 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Graphics;
using StgSharp.Math;
using StgSharp.MVVM.ViewModel;
@@ -48,13 +48,20 @@ namespace StgSharp.MVVM.View
{
public abstract partial class ViewBase
{
protected interface IViewRender<out TView> where TView : ViewBase
protected internal interface IViewRender<out TView>
where TView: ViewBase
{
RenderStream this[string renderName] { get; }
RenderStream this[ DataLabel renderName ]
{
get;
}
void CustomizedInitialize();
IEnumerator<ViewPort> GetEnumerator();
void Initialize();
bool ValidateInitializing();
@@ -62,27 +69,26 @@ namespace StgSharp.MVVM.View
}
protected abstract class ViewRender<TView> : IViewRender<TView>
where TView : ViewBase
where TView: ViewBase
{
protected ViewRender(TView binding)
protected ViewRender( TView binding )
{
_binding = binding;
_render = new Dictionary<DataLabel, RenderStream>();
}
public RenderStream this[string renderName]
public RenderStream this[ DataLabel renderName ]
{
get => _render.TryGetValue(renderName, out RenderStream stream) ? stream : (null!);
get => _render.TryGetValue(
renderName, out RenderStream stream ) ?
stream : ( null! );
protected set
{
if (_render.ContainsKey(renderName))
{
_render[renderName] = value;
}
else
{
_render.Add(renderName, value);
if( _render.ContainsKey( renderName ) ) {
_render[ renderName ] = value;
} else {
_render.Add( renderName, value );
}
}
}
@@ -91,31 +97,43 @@ namespace StgSharp.MVVM.View
protected ViewPort ContextBinding => _binding.context;
protected ViewDesigner<TView> Design => (_binding.Designer as ViewDesigner<TView>)!;
protected ViewDesigner<TView> Design => ( _binding.Designer as ViewDesigner<TView> )!;
protected Dictionary<string, RenderStream> Render
protected Dictionary<DataLabel, RenderStream> Render
{
get => _render;
}
protected ViewResponder<TView> Responder => (_binding.Responder as ViewResponder<TView>)!;
protected ViewResponder<TView> Responder => ( _binding.Responder as ViewResponder<TView> )!;
public T CreateRenderStream<T>((int x, int y, int z) unitCubeSize) where T : RenderStream, new()
public T CreateRenderStream<T>( (int x, int y, int z) unitCubeSize )
where T: RenderStream, new()
{
T ret = new T();
ret.Initialize(_binding.context, unitCubeSize, Binding.TimeProvider);
ret.Initialize(
_binding.context, unitCubeSize, Binding.TimeProvider );
return ret;
}
public T CreateRenderStream<T>(ViewPort vp, (int x, int y, int z) unitCubeSize) where T : RenderStream, new()
public T CreateRenderStream<T>(
ViewPort vp,
(int x, int y, int z) unitCubeSize )
where T: RenderStream, new()
{
T ret = new T();
ret.Initialize(vp, unitCubeSize, Binding.TimeProvider);
ret.Initialize( vp, unitCubeSize, Binding.TimeProvider );
return ret;
}
public abstract void CustomizedInitialize();
public IEnumerator<ViewPort> GetEnumerator()
{
foreach( RenderStream item in Render.Values ) {
yield return item.BindedViewPortContext;
}
}
public void Initialize()
{
CustomizedInitialize();
@@ -123,12 +141,11 @@ namespace StgSharp.MVVM.View
public abstract bool ValidateInitializing();
#pragma warning disable CS8618
private Dictionary<string, RenderStream> _render;
#pragma warning disable CS8618
private Dictionary<DataLabel, RenderStream> _render;
private TView _binding;
#pragma warning restore CS8618
}
}
}
+48 -33
View File
@@ -29,6 +29,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Controlling.UsrActivity;
using StgSharp.MVVM.ViewModel;
using System;
using System.Collections.Generic;
@@ -40,14 +41,20 @@ namespace StgSharp.MVVM.View
{
public partial class ViewBase
{
protected interface IViewResponder<out TVIew> where TVIew : ViewBase
protected interface IViewResponder<out TVIew> where TVIew: ViewBase
{
Action? this[ITrigger trigger] { get; set; }
Action? this[ IClickTrigger trigger ]
{
get;
set;
}
void CustomizedInitialize(Func<ITrigger, string, Action> keyRegister);
void CustomizedInitialize(
Func<IClickTrigger, string, Action> keyRegister );
void Initialize(Func<string, Action> keyGetter);
void Initialize( MethodLookUpDelegate methodGetter );
void ProcessUserInput();
@@ -55,67 +62,75 @@ namespace StgSharp.MVVM.View
}
protected abstract class ViewResponder<TView> : IViewResponder<TView> where TView : ViewBase
protected abstract class ViewResponder<TView> : IViewResponder<TView>
where TView: ViewBase
{
private bool _isInitialized;
private Dictionary<ITrigger, Action> keyCallbackIndex;
private Dictionary<IClickTrigger, Action> keyCallbackIndex;
private Dictionary<string, Action> nameToCallbackMap;
private TView _binding;
protected ViewResponder(TView binding)
protected ViewResponder( TView binding )
{
keyCallbackIndex = new Dictionary<ITrigger, Action>();
keyCallbackIndex = new Dictionary<IClickTrigger, Action>();
nameToCallbackMap = new Dictionary<string, Action>();
_binding = binding;
}
public Action? this[ITrigger trigger]
#pragma warning disable CA1043
public Action? this[ IClickTrigger trigger ]
#pragma warning restore CA1043
{
get => keyCallbackIndex.TryGetValue(trigger, out Action callback) ? callback : null;
get => keyCallbackIndex.TryGetValue(
trigger, out Action callback ) ?
callback : null;
set
{
if (keyCallbackIndex.TryGetValue(trigger, out Action callback))
{
if( keyCallbackIndex.TryGetValue(
trigger, out Action callback ) ) {
callback += value;
}
else
{
keyCallbackIndex.Add(trigger, value ?? throw new ArgumentNullException(nameof(value)));
} else {
keyCallbackIndex.Add(
trigger,
value ??
throw new ArgumentNullException(
nameof( value ) ) );
}
}
}
protected TView Binding => _binding;
public abstract void CustomizedInitialize(Func<ITrigger, string, Action> keyRegister);
public abstract void CustomizedInitialize(
Func<IClickTrigger, string, Action> keyRegister );
public void Initialize(Func<string, Action> keyGetter)
public void Initialize( MethodLookUpDelegate methodGetter )
{
if (_isInitialized)
{
if( _isInitialized ) {
return;
}
CustomizedInitialize(
(trigger, name) =>
{
if (!nameToCallbackMap.TryGetValue(name, out Action ret))
{
ret = keyGetter.Invoke(name) ??
throw new InvalidOperationException($"Cannot find method named {name} in binded view model");
( trigger, name ) => {
if( !nameToCallbackMap.TryGetValue(
name, out Action ret ) ) {
if( methodGetter( name, out Action lookup ) ) {
this[ trigger ] = lookup;
} else {
throw new InvalidOperationException(
$"Cannot find method named {name} in binded view model" );
}
}
this[trigger] = ret;
return ret;
}
);
} );
}
public void ProcessUserInput()
{
foreach (KeyValuePair<ITrigger, Action> pair in keyCallbackIndex)
{
if (InternalIO.glfwGetKey(_binding.ViewHandle, pair.Key.TargetKeyOrButtonID) == pair.Key.TriggeredStatus)
{
foreach( KeyValuePair<IClickTrigger, Action> pair in keyCallbackIndex ) {
if( InternalIO.glfwGetKey(
_binding.ViewHandle,
pair.Key.TargetKeyOrButtonID ) == pair.Key.TriggeredStatus ) {
pair.Value();
}
}
@@ -28,8 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Data.Intrinsic;
using System;
using System.Collections.Generic;
using System.Data.Common;
@@ -45,50 +44,59 @@ namespace StgSharp.MVVM.ViewModel
{
#nullable enable
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate ref object BindingDataGetter();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void BindingDataSetter(ref object value);
[UnmanagedFunctionPointer( CallingConvention.Cdecl )]
public delegate ref object BindingDataGetter();
[UnmanagedFunctionPointer( CallingConvention.Cdecl )]
public delegate void BindingDataSetter( ref object value );
[UnmanagedFunctionPointer( CallingConvention.Cdecl )]
public delegate bool MethodLookUpDelegate(
string name,
out Action callback );
public abstract partial class ViewModelBase
{
public bool MethodLookup(string methodName, out Action callback)
public bool MethodLookup( string methodName, out Action callback )
{
MethodInfo method = GetType().GetMethod(methodName);
try
{
callback = (Action)Delegate.CreateDelegate(typeof(Action), this, methodName);
MethodInfo method = GetType().GetMethod( methodName )!;
if( method == null ) {
callback = null!;
return false;
}
try {
callback = ( Action )Delegate.CreateDelegate(
typeof( Action ), this, methodName );
return true;
}
catch (MissingMethodException)
{
catch( MissingMethodException ) {
callback = null!;
return false;
}
catch (MethodAccessException)
{
catch( MethodAccessException ) {
callback = null!;
return false;
}
catch (Exception)
{
catch( Exception ) {
throw;
}
}
}
[StructLayout(LayoutKind.Explicit)]
[StructLayout( LayoutKind.Explicit )]
public unsafe struct DataBindingEntry
{
[FieldOffset(0)] private M128 _mask;
[FieldOffset(0)] private IntPtr getterPtr;
[FieldOffset(8)] private IntPtr setterPtr;
[FieldOffset( 0 )] private IntPtr getterPtr;
[FieldOffset( 8 )] private IntPtr setterPtr;
[FieldOffset( 0 )] private M128 _mask;
public DataBindingEntry(
[NotNull] BindingDataGetter gettingCallback,
[NotNull] BindingDataSetter settingCallback)
[NotNull] BindingDataSetter settingCallback )
{
getterPtr = Marshal.GetFunctionPointerForDelegate(gettingCallback);
setterPtr = Marshal.GetFunctionPointerForDelegate(settingCallback);
getterPtr = Marshal.GetFunctionPointerForDelegate( gettingCallback );
setterPtr = Marshal.GetFunctionPointerForDelegate( settingCallback );
}
public static DataBindingEntry NullBinding
@@ -96,49 +104,54 @@ namespace StgSharp.MVVM.ViewModel
get => new DataBindingEntry();
}
public bool ExactEqual(DataBindingEntry other)
public bool Equals( DataBindingEntry other )
{
return (getterPtr == other.getterPtr) && (setterPtr == other.setterPtr);
return ( _mask == other._mask );
}
public ref object GetValue()
public override bool Equals( object obj )
{
return ref ((delegate* unmanaged[Cdecl]<ref object>)getterPtr)();
}
public void SetValue(ref object value)
{
((delegate* unmanaged[Cdecl]<ref object, void>)setterPtr)(ref value);
}
public static bool operator ==(DataBindingEntry left, DataBindingEntry right)
{
return left._mask == right._mask;
}
public static bool operator !=(DataBindingEntry left, DataBindingEntry right)
{
return left._mask != right._mask;
}
public bool Equals(DataBindingEntry other)
{
return (_mask == other._mask);
}
public override bool Equals(object obj)
{
if (obj is not DataBindingEntry other)
{
if( obj is not DataBindingEntry other ) {
return false;
}
return Equals(other);
return Equals( other );
}
public bool ExactEqual( DataBindingEntry other )
{
return ( getterPtr == other.getterPtr ) && ( setterPtr == other.setterPtr );
}
public override int GetHashCode()
{
return _mask.GetHashCode();
}
public ref object GetValue()
{
return ref ( ( delegate* unmanaged[Cdecl]<ref object> )getterPtr )();
}
public void SetValue( ref object value )
{
( ( delegate* unmanaged[Cdecl]<ref object, void> )setterPtr )(
ref value );
}
public static bool operator !=(
DataBindingEntry left,
DataBindingEntry right )
{
return left._mask != right._mask;
}
public static bool operator ==(
DataBindingEntry left,
DataBindingEntry right )
{
return left._mask == right._mask;
}
}
#nullable restore
@@ -28,8 +28,11 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Controls;
using StgSharp.Graphics;
using StgSharp.MVVM.View;
using StgSharp.Threading;
using StgSharp.Timing;
using System;
using System.Collections.Generic;
@@ -40,6 +43,8 @@ namespace StgSharp.MVVM.ViewModel
{
public abstract partial class ViewModelBase
{
private volatile bool _closed = true;
private ViewBase _nextView, _currentView;
protected ViewBase CurrentView
@@ -51,46 +56,91 @@ namespace StgSharp.MVVM.ViewModel
/// <summary>
/// CustomizeInit this form and render it on screen, and respond with operation
/// </summary>
public unsafe void UseViewModel(string viewEntryName)
public unsafe void UseViewModel( string viewEntryName )
{
CustomizeInitialize();
//BuildGlobalKeyControl();
UseViewInNextFrame(viewEntryName);
while (0 == InternalIO.glfwWindowShouldClose(this.viewPortDisplay.ViewPortID))
{
ShowFrameOnce();
UseViewInNextFrame( viewEntryName );
TimeSpanAwaitingToken fpsCountingToken = fpsCountProvider.ParticipantSpanAwaiting(
1 );
fpsCountingToken.TimeSpanRefreshed += CountFps;
fpsCountingToken.MissTimeSpanRefreshed += CountFps;
if( _nextView != _currentView ) {
Interlocked.Exchange( ref _currentView, _nextView );
}
Thread renderThread = new Thread(
( token ) => {
try {
ProcessFrameWithoutEvent();
}
catch( Exception ex ) {
InternalIO.InternalWriteLog(
$"Critical error when rendering:\n" + $"{ex}",
LogType.Error );
ShouldClose = true;
}
} );
renderThread.Start();
/**/
using( TimeSpanAwaitingToken eventAwaitingToken = frameTimeProvider.ParticipantSpanAwaiting(
1 ) ) {
while( _closed ) {
if( _nextView != _currentView ) {
Interlocked.Exchange( ref _currentView, _nextView );
}
InternalIO.glfwPollEvents();
eventAwaitingToken.WaitNextSpan();
_closed = !ShouldClose;
}
}
/**/
renderThread.Join();
fpsCountingToken.Dispose();
fpsCountProvider.StopSpanProviding();
frameTimeProvider.StopSpanProviding();
}
protected void UseViewInNextFrame(string name)
protected void UseViewInNextFrame( string name )
{
if (!allView.TryGetValue(name, out ViewBase v))
{
throw new KeyNotFoundException($"{$"Cannot find View named {name} "}{$"in current View Model of {GetType().FullName}"}");
if( !allView.TryGetValue( name, out ViewBase v ) ) {
throw new KeyNotFoundException(
$"{$"Cannot find View named {name} "}{$"in current View Model of {GetType().FullName}"}" );
}
CurrentView = v;
}
private void CountFps( object sender, EventArgs e )
{
Interlocked.Exchange( ref _frameSpeed, _frameCount );
Interlocked.Exchange( ref _frameCount, 0 );
/**/
Console.Clear();
Console.WriteLine( FrameSpeed );
/**/
}
private unsafe void PrivateShow()
{
if (0 == InternalIO.glfwWindowShouldClose(this.viewPortDisplay.ViewPortID))
{
if( 0 == InternalIO.glfwWindowShouldClose(
this.viewPortDisplay.ViewPortID ) ) {
CurrentView.Use();
RenderStream.PollEvents();
}
}
private void ShowFrameOnce()
private void ProcessFrameWithoutEvent()
{
viewPortDisplay.FlushSize();
if (_nextView != _currentView)
{
Interlocked.Exchange(ref _currentView, _nextView);
using( TimeSpanAwaitingToken renderAwaitingToken = frameTimeProvider.ParticipantSpanAwaiting(
1 ) ) {
renderAwaitingToken.TimeSpanRefreshed += ( _, _ ) => { };
while( _closed ) {
foreach( ViewPort context in CurrentView.Render ) {
context.FlushSize();
}
CurrentView.Use();
renderAwaitingToken.WaitNextSpan();
Interlocked.Add( ref _frameCount, 1 );
}
}
CurrentView.Use();
RenderStream.PollEvents();
frameTimeProvider.WaitNextSpan();
Interlocked.Add(ref _frameCount, 1);
}
}
@@ -44,13 +44,15 @@ namespace StgSharp.MVVM.ViewModel
private Dictionary<string, ViewBase> allView;
public T CreateAndBindView<T>(string name, (int x, int y, int z) unitCubeSize)
where T : ViewBase, new()
public T CreateAndBindView<T>(
string name,
(int x, int y, int z) unitCubeSize )
where T: ViewBase, new()
{
T ret = new T();
ret.SelfName = name;
ret.InternalInitialize(name, unitCubeSize, this);
allView.Add(name, ret);
ret.InternalInitialize( name, unitCubeSize, this );
allView.Add( name, ret );
return ret;
}
+81 -163
View File
@@ -34,6 +34,7 @@ using StgSharp.Graphics.OpenGL;
using StgSharp.Math;
using StgSharp.MVVM.View;
using StgSharp.MVVM.ViewModel;
using StgSharp.Threading;
using StgSharp.Timing;
using System;
@@ -51,6 +52,7 @@ namespace StgSharp.MVVM.ViewModel
public abstract partial class ViewModelBase
{
private FrameBufferSizeHandler _resizeCallback;
private int _frameCount;
private int _frameSpeed;
private ViewPort viewPortDisplay;
@@ -61,135 +63,72 @@ namespace StgSharp.MVVM.ViewModel
internal TimeSpanProvider frameTimeProvider;
internal Vector4 backgroundColor;
protected ViewModelBase(int frameSpeed)
protected ViewModelBase( int frameSpeed )
{
viewPortDisplay = new ViewPort();
allView = new();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
fpsCountProvider = new TimeSpanProvider(
1.0, TimeSpanProvider.DefaultProvider );
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback = CountFps;
long frameLength = (FrameSpeed > 0) ? ((1000L * 1000L) / FrameSpeed) : 0;
long frameLength = ( FrameSpeed > 0 ) ?
( ( 1000L * 1000L ) / FrameSpeed ) : 0;
frameTimeProvider = new TimeSpanProvider(
frameLength, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
viewPortDisplay.FrameSizeCallback = (handle, width, height)
=>
{
InternalIO.glfwMakeContextCurrent(viewPortDisplay.ViewPortID);
OpenGLFunction.CurrentGL.Viewport(0, 0, width, height);
PrivateShow();
};
viewPortDisplay.FramePostionCallback = (handle, xpos, ypos)
=>
{
PrivateShow();
};
frameLength, TimeSpanProvider.DefaultProvider );
FrameSizeCallback = DefaultFrameRewsizeCallback;
}
protected ViewModelBase(float frameLength)
protected ViewModelBase( float frameLength )
{
viewPortDisplay = new ViewPort();
allView = new();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
fpsCountProvider = new TimeSpanProvider(
1.0, TimeSpanProvider.DefaultProvider );
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback = CountFps;
long _frameLength = (FrameSpeed > 0) ? ((long)(1000 * frameLength)) : 0;
long _frameLength = ( FrameSpeed > 0 ) ?
( ( long )( 1000 * frameLength ) ) : 0;
frameTimeProvider = new TimeSpanProvider(
_frameLength, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
viewPortDisplay.FrameSizeCallback = (handle, width, height)
=>
{
InternalIO.glfwMakeContextCurrent(viewPortDisplay.ViewPortID);
OpenGLFunction.CurrentGL.Viewport(0, 0, width, height);
PrivateShow();
};
viewPortDisplay.FramePostionCallback = (handle, xpos, ypos)
=>
{
PrivateShow();
};
_frameLength, TimeSpanProvider.DefaultProvider );
FrameSizeCallback = DefaultFrameRewsizeCallback;
}
public ViewModelBase(ViewPort vBinding, int frameSpeed)
public ViewModelBase( ViewPort vBinding, int frameSpeed )
{
viewPortDisplay = vBinding;
allView = new();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
fpsCountProvider = new TimeSpanProvider(
1.0, TimeSpanProvider.DefaultProvider );
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback = CountFps;
long frameLength = (frameSpeed > 0) ? ((1000L * 1000L) / frameSpeed) : 0;
long frameLength = ( frameSpeed > 0 ) ?
( ( 1000L * 1000L ) / frameSpeed ) : 0;
frameTimeProvider = new TimeSpanProvider(
frameLength, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
viewPortDisplay.FrameSizeCallback = (handle, width, height)
=>
{
InternalIO.glfwMakeContextCurrent(viewPortDisplay.ViewPortID);
OpenGLFunction.CurrentGL.Viewport(0, 0, width, height);
PrivateShow();
};
viewPortDisplay.FramePostionCallback = (handle, xpos, ypos)
=>
{
PrivateShow();
};
frameLength, TimeSpanProvider.DefaultProvider );
FrameSizeCallback = DefaultFrameRewsizeCallback;
}
public ViewModelBase(ViewPort vBinding, float frameLength)
public ViewModelBase( ViewPort vBinding, float frameLength )
{
viewPortDisplay = vBinding;
allView = new();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
fpsCountProvider = new TimeSpanProvider(
1.0, TimeSpanProvider.DefaultProvider );
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback = CountFps;
long _frameLength = (frameLength > 0) ? ((long)(1000 * frameLength)) : 0;
long _frameLength = ( frameLength > 0 ) ?
( ( long )( 1000 * frameLength ) ) : 0;
frameTimeProvider = new TimeSpanProvider(
_frameLength, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
viewPortDisplay.FrameSizeCallback = (handle, width, height)
=>
{
InternalIO.glfwMakeContextCurrent(viewPortDisplay.ViewPortID);
OpenGLFunction.CurrentGL.Viewport(0, 0, width, height);
PrivateShow();
};
viewPortDisplay.FramePostionCallback = (handle, xpos, ypos)
=>
{
PrivateShow();
};
_frameLength, TimeSpanProvider.DefaultProvider );
FrameSizeCallback = DefaultFrameRewsizeCallback;
}
public DataBindingEntry this[string name]
public DataBindingEntry this[ string name ]
{
get
{
if (this.TryGetObjectReference(name, out DataBindingEntry entry))
{
if( this.TryGetObjectReference(
name, out DataBindingEntry entry ) ) {
return entry;
}
throw new KeyNotFoundException();
@@ -198,8 +137,10 @@ namespace StgSharp.MVVM.ViewModel
public bool ShouldClose
{
get => InternalIO.glfwWindowShouldClose(viewPortDisplay.ViewPortID) != 0;
set => InternalIO.glfwSetWindowShouldClose(viewPortDisplay.ViewPortID, value ? 1 : 0);
get => InternalIO.glfwWindowShouldClose(
viewPortDisplay.ViewPortID ) != 0;
set => InternalIO.glfwSetWindowShouldClose(
viewPortDisplay.ViewPortID, value ? 1 : 0 );
}
public int CurrentFrameCount => frameTimeProvider.CurrentSpan;
@@ -207,28 +148,19 @@ namespace StgSharp.MVVM.ViewModel
public int FrameSpeed => _frameSpeed;
/// <summary>
/// Height of this form, represent in <see cref="int"/>
/// Height of this form, represent in <see cref="int" />
/// </summary>
public int Height
{
get => viewPortDisplay.Height;
set { viewPortDisplay.Height = value; }
}
/// <summary>
/// Width of this form, represent in <see cref="int"/>
/// Width of this form, represent in <see cref="int" />
/// </summary>
public int Width
{
get => viewPortDisplay.Width;
set
{
viewPortDisplay.Width = value;
if (WindowID != IntPtr.Zero)
{
InternalIO.glfwSetWindowSize(viewPortDisplay.ViewPortID, Width, Height);
}
}
}
public unsafe IntPtr WindowID
@@ -242,20 +174,11 @@ namespace StgSharp.MVVM.ViewModel
}
/// <summary>
/// Width of this form, represent in <see cref="int"/>
/// Width of this form, represent in <see cref="int" />
/// </summary>
public vec2d Size
public Vec2 Size
{
get => new vec2d(Width, Height);
set
{
Width = (int)value.X;
Height = (int)value.Y;
if (WindowID != IntPtr.Zero)
{
InternalIO.glfwSetWindowSize(viewPortDisplay.ViewPortID, Width, Height);
}
}
get => new Vec2( Width, Height );
}
public ViewPort ViewPortBinding
@@ -263,79 +186,74 @@ namespace StgSharp.MVVM.ViewModel
get => viewPortDisplay;
}
#pragma warning disable CA1044
#pragma warning disable CA1044
protected FrameBufferSizeHandler FrameSizeCallback
{
set
{
IntPtr handlerPtr = Marshal.GetFunctionPointerForDelegate(value);
InternalIO.glfwSetFramebufferSizeCallback(viewPortDisplay.ViewPortID, handlerPtr);
_resizeCallback = value;
IntPtr handlerPtr = Marshal.GetFunctionPointerForDelegate(
value );
InternalIO.glfwSetFramebufferSizeCallback(
viewPortDisplay.ViewPortID, handlerPtr );
}
}
#pragma warning restore CA1044
#pragma warning restore CA1044
public abstract void CustomizeInitialize();
/// <summary>
/// Resize the current form
/// </summary>
/// <param name="size">
/// A <see cref="vec2d"/> (width,height) representing the new size of current form
/// </param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSize(vec2d size)
{
this.Size = size;
InternalIO.glfwSetWindowSize(this.viewPortDisplay.ViewPortID, (int)size.X, (int)size.Y);
}
/// <summary>
/// Set the size limit of current form
/// </summary>
/// <param name="minSize">
/// Minimum size of current form. In form of a <see cref="vec2d"/> of (width,height)
/// Minimum size of current form. In form of a <see cref="Vec2" /> of (width,height)
/// </param>
/// <param name="maxSize">
/// Maximum size of current form. In form of a <see cref="vec2d"/> of (width,height)
/// Maximum size of current form. In form of a <see cref="Vec2" /> of (width,height)
/// </param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSizeLimit(vec2d minSize, vec2d maxSize)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetSizeLimit( Vec2 minSize, Vec2 maxSize )
{
ThreadHelper.MainThreadAssert();
InternalIO.glfwSetWindowSizeLimits(
this.viewPortDisplay.ViewPortID,
(int)minSize.X,
(int)minSize.Y,
(int)maxSize.X,
(int)maxSize.Y);
this.viewPortDisplay.ViewPortID, ( int )minSize.X,
( int )minSize.Y, ( int )maxSize.X, ( int )maxSize.Y );
}
/// <summary>
/// Set the size limit of current form
/// </summary>
/// <param name="minWidth">Minimum width of current form</param>
/// <param name="minHeight">Minimum height of current form</param>
/// <param name="maxWidth">Maximum width of current form</param>
/// <param name="maxHeight">Maximum height of current form</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSizeLimit(int minWidth, int minHeight, int maxWidth, int maxHeight)
/// <param name="minWidth"> Minimum width of current form </param>
/// <param name="minHeight"> Minimum height of current form </param>
/// <param name="maxWidth"> Maximum width of current form </param>
/// <param name="maxHeight"> Maximum height of current form </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetSizeLimit(
int minWidth,
int minHeight,
int maxWidth,
int maxHeight )
{
//TODO 重做form的尺寸极限控制
InternalIO.glfwSetWindowSizeLimits(this.viewPortDisplay.ViewPortID, minWidth, minHeight, maxWidth, maxHeight);
ThreadHelper.MainThreadAssert();
InternalIO.glfwSetWindowSizeLimits(
this.viewPortDisplay.ViewPortID, minWidth, minHeight, maxWidth,
maxHeight );
}
public abstract bool TryGetObjectReference(string name, out DataBindingEntry entry);
public abstract bool TryGetObjectReference(
string name,
out DataBindingEntry entry );
private void CountFps()
private void DefaultFrameRewsizeCallback(
IntPtr windowHandle,
int width,
int height )
{
/**/
Console.Clear();
Console.WriteLine(FrameSpeed);
/**/
Interlocked.Exchange(ref _frameSpeed, _frameCount);
Interlocked.Exchange(ref _frameCount, 0);
ViewPort.GetExistedViewPort( windowHandle, out ViewPort vp );
vp.RequestFlushSizeInNextFrame( width, height );
//Console.WriteLine($"{width} {height}");
}
}
}
+66 -68
View File
@@ -30,11 +30,14 @@
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Math;
using StgSharp.Threading;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
@@ -43,106 +46,101 @@ namespace StgSharp.MVVM
{
public class ViewPort
{
private FrameBufferSizeHandler _sizeHandler;
private FramePositionHandler _positionHandler;
private int _width, _height;
private static ConcurrentDictionary<IntPtr, ViewPort> _handleToViewPortIndex = new ConcurrentDictionary<IntPtr, ViewPort>(
);
private int _shouldCloseMask, _closeRequestedMask;
private int _width, _height, _newWidth, _newHeight;
internal ViewPort()
{
_height = 600;
_width = 800;
Name = new StackFrame(1, false).
_newHeight = 600;
_newWidth = 800;
FlushSize();
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.");
ViewPortID = InternalIO.glfwCreateWindow(
_newWidth, _newHeight, Encoding.UTF8.GetBytes( Name ), Monitor,
IntPtr.Zero );
if( ViewPortID == IntPtr.Zero ) {
throw new InvalidOperationException(
"Unable to create viewport handle." );
}
_handleToViewPortIndex.TryAdd( ViewPortID, this );
}
public ViewPort(vec2d size, string name, IntPtr monitor)
internal ViewPort( Vec2 size, string name, IntPtr monitor )
{
_width = (int)size.X;
_height = (int)size.Y;
_newWidth = ( int )size.X;
_newHeight = ( int )size.Y;
FlushSize();
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 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);
ViewPortID = InternalIO.glfwCreateWindow(
_newWidth, _newHeight, Encoding.UTF8.GetBytes( Name ), Monitor,
IntPtr.Zero );
if( ViewPortID == IntPtr.Zero ) {
throw new InvalidOperationException(
"Unable to create viewport handle." );
}
_handleToViewPortIndex.TryAdd( ViewPortID, this );
}
public unsafe int Height
{
get { return _height; }
set { InternalIO.glfwSetWindowSize(ViewPortID, _width, value); }
internal set { Interlocked.Exchange( ref _height, value ); }
}
public unsafe int Width
{
get { return _width; }
set { InternalIO.glfwSetWindowSize(ViewPortID, value, _height); }
internal set { Interlocked .Exchange( ref _width, value ); }
}
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()
public IntPtr GraphicHandle
{
InternalIO.glfwSetWindowShouldClose(ViewPortID, 1);
get;
internal set;
}
public IntPtr Monitor
{
get;
internal set;
}
public IntPtr ViewPortID
{
get;
private set;
}
public string Name
{
get;
set;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool GetExistedViewPort(
IntPtr handle,
out ViewPort port )
{
return _handleToViewPortIndex.TryGetValue( handle, out port );
}
internal unsafe void FlushSize()
{
fixed (int* wptr = &_width, hptr = &_height)
{
InternalIO.glfwGetWindowSize(ViewPortID, wptr, hptr);
}
Interlocked.Exchange( ref _height, _newHeight );
Interlocked.Exchange( ref _width, _newWidth );
}
private int _eventWaitingMask;
internal bool IsWaitingEvent
internal void RequestFlushSizeInNextFrame( int width, int height )
{
get => _eventWaitingMask == 1;
}
internal unsafe void InternalShowViewModelMain()
{
Interlocked.Exchange(ref _eventWaitingMask, 1);
InternalIO.glfwWaitEvents();
Interlocked.Exchange(ref _eventWaitingMask, 0);
Interlocked.Exchange( ref _newHeight, height );
Interlocked .Exchange( ref _newWidth, width );
}
}