add from giga-device, new branch added

This commit is contained in:
Nitload Youmu
2025-08-21 16:51:25 +08:00
commit 43bbc06bbb
1296 changed files with 264186 additions and 0 deletions
@@ -0,0 +1,57 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="OpenGLControllingItemRender.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.MVVM
{
public class OpenGLControllingItemRender : glRender
{
public override bool IsContextSharable => true;
protected override void CustomizeDeinit()
{
throw new NotImplementedException();
}
protected override void CustomizeInit()
{
throw new NotImplementedException();
}
}
}
+205
View File
@@ -0,0 +1,205 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewBase.cs"
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Mathematics;
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;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace StgSharp.MVVM
{
/// <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" />.
/// </summary>
public abstract unsafe partial class ViewBase
{
private (int x, int y, int z) unitCubeSize;
private GetDataBindingEntryDelegate getDataBindingEntry;
private int usedFrame;
private IViewDesigner<ViewBase> _design;
private IViewRender<ViewBase> _render;
private IViewResponder<ViewBase> _responder;
private TimeSpanProvider time;
private ViewPort context;
private delegate bool GetDataBindingEntryDelegate( string name, out DataBindingEntry entry );
public DataBindingEntry this[ string name ]
{
get
{
if( getDataBindingEntry( name, out DataBindingEntry entry ) ) {
return entry;
}
if( TryGetObjectReference( name, out entry ) ) {
return entry;
}
throw new KeyNotFoundException();
}
}
public (int x, int y, int z) UnitCubeSize
{
get => unitCubeSize;
}
public bool Activated { get; internal set; }
public int Height
{
get => context.Height;
}
public int Width
{
get => context.Width;
}
public IntPtr Monitor => context.Monitor;
public IntPtr ViewHandle => context.ViewPortHandle;
public IViewDesigner<ViewBase> Designer
{
get => _design;
protected set => _design = value;
}
public string ContextName => context.Name;
public string SelfName { get; set; }
public ViewPort Port
{
get => context;
}
internal TimeSpanProvider TimeProvider
{
get => time;
}
protected internal IViewRender<ViewBase> Render
{
get => _render;
set => _render = value;
}
protected IViewResponder<ViewBase> Responder
{
get => _responder;
set => _responder = value;
}
public abstract void CustomizedInitialize( [NotNull]ViewModelBase viewModelBinding );
/// <summary>
/// Get the status of a certain key on the keyboard.
/// </summary>
/// <param _label="key">
///
/// </param>
/// <returns>
/// <see cref="KeyStatus" /> representing if a key is pressed or released.
/// </returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public KeyStatus GetKeyStatus( KeyboardKey key )
{
return InternalIO.glfwGetKey( context.ViewPortHandle, ( int )key );
}
public void InternalInitialize(
string name,
(int, int, int) cubeSize,
[NotNull]ViewModelBase viewModelBinding )
{
SelfName = name;
unitCubeSize = cubeSize;
getDataBindingEntry = viewModelBinding.TryGetObjectReference;
context = viewModelBinding.ViewPortBinding;
time = viewModelBinding.frameTimeProvider;
CustomizedInitialize( viewModelBinding );
}
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." );
}
}
Show();
usedFrame++;
}
public bool ValidateInitialization()
{
return ( _design != null ) &&
( _render != null ) &&
( getDataBindingEntry != null ) &&
( _responder != null ) &&
_design.ValidateInitializing() &&
_responder.ValidateInitializing() &&
_render.ValidateInitializing();
}
protected abstract void Show();
}
}
+147
View File
@@ -0,0 +1,147 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewDesigner.cs"
// Project: StepVisualizer
// 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.Controlling.UsrActivity;
using StgSharp.Controls;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Mathematics;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace StgSharp.MVVM
{
public abstract partial class ViewBase
{
public interface IViewDesigner<out TView> where TView: ViewBase
{
abstract void CustomizedInitialize();
abstract void Initialize();
abstract bool ValidateInitializing();
}
/// <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.
/// </summary>
public abstract class ViewDesigner<TView> : IViewDesigner<TView> where TView: ViewBase
{
private KeyboardButtonGroup currentButtonGroup;
private List<ControllingItem> _controlList;
protected TView _binding;
public ViewDesigner( TView binding )
{
_binding = binding;
_controlList = new List<ControllingItem>();
}
protected TView Binding
{
get => _binding;
}
public CharacterLineIndexImage CreateCharacterLine(
int length,
char blankFilling,
PlainGeometryMesh tittle,
IEnumerable<(char, PlainGeometryMesh)> charList )
{
CharacterLineIndexImage ret = new CharacterLineIndexImage(
length, blankFilling, tittle, charList );
_controlList.Add( ret );
return ret;
}
public TriggerButton CreateKeyboardButton(
Rectangle bonding,
TextureProvider defaultAnimation,
bool isEnable )
{
TriggerButton ret = new TriggerButton();
ret.BoundingBox = bonding;
ret.Texture = defaultAnimation;
if( isEnable )
{
ret.IsDisabled = false;
ret.Enable();
} else
{
ret.IsDisabled = true;
ret.Disable();
}
currentButtonGroup.AddButton( ret );
return ret;
}
public TButtonGroup CreateKeyboardButtonGroup<TButtonGroup>(
IClickTrigger leftBidning,
IClickTrigger rightBinding,
IClickTrigger upBinding,
IClickTrigger downBinding,
IClickTrigger confirmBinding )
where TButtonGroup: KeyboardButtonGroup, new()
{
TButtonGroup ret = new TButtonGroup();
_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;
return ret;
}
public abstract void CustomizedInitialize();
public void Initialize()
{
CustomizedInitialize();
}
public abstract bool ValidateInitializing();
}//---------------------------------- End of Class -----------------------------------------
}
}
+134
View File
@@ -0,0 +1,134 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewRender.cs"
// Project: StepVisualizer
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.HighPerformance;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StgSharp.MVVM
{
public abstract partial class ViewBase
{
protected internal interface IViewRender<out TView> where TView: ViewBase
{
RenderStream this[ DataLabel renderName ] { get; }
void CustomizedInitialize();
IEnumerator<ViewPort> GetEnumerator();
void Initialize();
bool ValidateInitializing();
}
protected abstract class ViewRender<TView> : IViewRender<TView> where TView: ViewBase
{
protected ViewRender( TView binding )
{
_binding = binding;
_render = new Dictionary<DataLabel, RenderStream>();
}
public RenderStream this[ DataLabel renderName ]
{
get => _render.TryGetValue( renderName, out RenderStream stream ) ?
stream : ( null! );
protected set
{
if( _render.ContainsKey( renderName ) )
{
_render[ renderName ] = value;
} else
{
_render.Add( renderName, value );
}
}
}
public TView Binding => _binding;
protected ViewPort ContextBinding => _binding.context;
protected ViewDesigner<TView> Design => ( _binding.Designer as ViewDesigner<TView> )!;
protected Dictionary<DataLabel, RenderStream> Render
{
get => _render;
}
protected ViewResponder<TView> Responder => ( _binding.Responder as ViewResponder<TView> )!;
public T CreateRenderStream<T>() where T: RenderStream, new()
{
T ret = new T();
ret.Initialize( _binding.context, Binding.TimeProvider );
return ret;
}
public T CreateRenderStream<T>( ViewPort vp ) where T: RenderStream, new()
{
T ret = new T();
ret.Initialize( vp, 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();
}
public abstract bool ValidateInitializing();
#pragma warning disable CS8618
private Dictionary<DataLabel, RenderStream> _render;
private TView _binding;
#pragma warning restore CS8618
}
}
}
+138
View File
@@ -0,0 +1,138 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewResponder.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.Controlling.UsrActivity;
using StgSharp.MVVM.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.MVVM
{
public partial class ViewBase
{
protected interface IViewResponder<out TVIew> where TVIew: ViewBase
{
Action? this[ IClickTrigger trigger ] { get; set; }
void CustomizedInitialize( Func<IClickTrigger, string, Action> keyRegister );
void Initialize( MethodLookUpDelegate methodGetter );
void ProcessUserInput();
bool ValidateInitializing();
}
protected abstract class ViewResponder<TView> : IViewResponder<TView> where TView: ViewBase
{
private bool _isInitialized;
private Dictionary<IClickTrigger, Action> keyCallbackIndex;
private Dictionary<string, Action> nameToCallbackMap;
private TView _binding;
protected ViewResponder( TView binding )
{
keyCallbackIndex = new Dictionary<IClickTrigger, Action>();
nameToCallbackMap = new Dictionary<string, Action>();
_binding = binding;
}
#pragma warning disable CA1043
public Action? this[ IClickTrigger trigger ]
#pragma warning restore CA1043
{
get => keyCallbackIndex.TryGetValue( trigger, out Action callback ) ?
callback : null;
set
{
if( keyCallbackIndex.TryGetValue( trigger, out Action callback ) )
{
callback += value;
} else
{
keyCallbackIndex.Add(
trigger, value ?? throw new ArgumentNullException( nameof( value ) ) );
}
}
}
protected TView Binding => _binding;
public abstract void CustomizedInitialize(
Func<IClickTrigger, string, Action> keyRegister );
public void Initialize( MethodLookUpDelegate methodGetter )
{
if( _isInitialized ) {
return;
}
CustomizedInitialize(
( 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" );
}
}
return ret;
} );
}
public void ProcessUserInput()
{
foreach( KeyValuePair<IClickTrigger, Action> pair in keyCallbackIndex )
{
if( InternalIO.glfwGetKey( _binding.ViewHandle,
pair.Key.TargetKeyOrButtonID ) ==
pair.Key.TriggeredStatus ) {
pair.Value();
}
}
}
public abstract bool ValidateInitializing();
}
}
}
@@ -0,0 +1,151 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="DataBinding.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.HighPerformance;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
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 bool MethodLookUpDelegate( string name, out Action callback );
public abstract partial class ViewModelBase
{
public bool MethodLookup( string methodName, out Action callback )
{
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 )
{
callback = null!;
return false;
}
catch( MethodAccessException )
{
callback = null!;
return false;
}
catch( Exception )
{
throw;
}
}
}
[StructLayout( LayoutKind.Explicit )]
public unsafe struct DataBindingEntry
{
[FieldOffset( 0 )] private IntPtr getterPtr;
[FieldOffset( 8 )] private IntPtr setterPtr;
[FieldOffset( 0 )] private M128 _mask;
public DataBindingEntry(
[NotNull] BindingDataGetter gettingCallback,
[NotNull] BindingDataSetter settingCallback )
{
getterPtr = Marshal.GetFunctionPointerForDelegate( gettingCallback );
setterPtr = Marshal.GetFunctionPointerForDelegate( settingCallback );
}
public static DataBindingEntry NullBinding
{
get => new DataBindingEntry();
}
public bool Equals( DataBindingEntry other )
{
return ( _mask == other._mask );
}
public override bool Equals( object obj )
{
if( obj is not DataBindingEntry other ) {
return false;
}
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
}
@@ -0,0 +1,148 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ShowViewPort.cs"
// Project: StepVisualizer
// 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.Controls;
using StgSharp.Graphics;
using StgSharp.MVVM;
using StgSharp.Threading;
using StgSharp.Timing;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace StgSharp.MVVM.ViewModel
{
public abstract partial class ViewModelBase
{
private volatile bool _closed = true;
private ViewBase _nextView, _currentView;
protected ViewBase CurrentView
{
get => _currentView;
set => _nextView = value;
}
/// <summary>
/// CustomizeInit this form and render it on screen, and respond with operation
/// </summary>
public unsafe void UseViewModel( string viewEntryName )
{
CustomizeInitialize();
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;
throw;
}
} );
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 )
{
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 );
}
private unsafe void PrivateShow()
{
if( 0 == InternalIO.glfwWindowShouldClose( this.viewPortDisplay.ViewPortHandle ) )
{
CurrentView.Use();
RenderStream.PollEvents();
}
}
private void ProcessFrameWithoutEvent()
{
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 );
}
}
}
}
}
@@ -0,0 +1,58 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewManage.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Graphics.OpenGL;
using StgSharp.MVVM;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Text;
namespace StgSharp.MVVM.ViewModel
{
public partial class ViewModelBase
{
private Dictionary<string, ViewBase> allView;
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 );
return ret;
}
}
}
+247
View File
@@ -0,0 +1,247 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="ViewModel.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.Controlling.UsrActivity;
using StgSharp.Graphics;
using StgSharp.Graphics.OpenGL;
using StgSharp.Mathematics;
using StgSharp.MVVM;
using StgSharp.MVVM.ViewModel;
using StgSharp.Threading;
using StgSharp.Timing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using static StgSharp.Internal.InternalIO;
namespace StgSharp.MVVM.ViewModel
{
public abstract partial class ViewModelBase
{
private FrameBufferSizeHandler _resizeCallback;
private int _frameCount;
private int _frameSpeed;
private ViewPort viewPortDisplay;
// internal IntPtr monitor;
internal TimeSpanProvider fpsCountProvider;
internal TimeSpanProvider frameTimeProvider;
internal Vector4 backgroundColor;
protected ViewModelBase(int frameSpeed)
{
viewPortDisplay = new ViewPort();
allView = [];
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
long frameLength = (FrameSpeed > 0) ? (1000L * 1000L / FrameSpeed) : 0;
frameTimeProvider = new TimeSpanProvider(frameLength, TimeSpanProvider.DefaultProvider);
SetFrameSizeCallback(DefaultFrameRewsizeCallback);
}
protected ViewModelBase(float frameLength)
{
viewPortDisplay = new ViewPort();
allView = [];
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
long _frameLength = (FrameSpeed > 0) ? ((long)(1000 * frameLength)) : 0;
frameTimeProvider = new TimeSpanProvider(_frameLength,
TimeSpanProvider.DefaultProvider);
SetFrameSizeCallback(DefaultFrameRewsizeCallback);
}
public ViewModelBase(ViewPort vBinding, int frameSpeed)
{
viewPortDisplay = vBinding;
allView = [];
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
long frameLength = (frameSpeed > 0) ? (1000L * 1000L / frameSpeed) : 0;
frameTimeProvider = new TimeSpanProvider(frameLength, TimeSpanProvider.DefaultProvider);
SetFrameSizeCallback(DefaultFrameRewsizeCallback);
}
public ViewModelBase(ViewPort vBinding, float frameLength)
{
viewPortDisplay = vBinding;
allView = [];
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
long _frameLength = (frameLength > 0) ? ((long)(1000 * frameLength)) : 0;
frameTimeProvider = new TimeSpanProvider(_frameLength,
TimeSpanProvider.DefaultProvider);
SetFrameSizeCallback(DefaultFrameRewsizeCallback);
}
public DataBindingEntry this[string name]
{
get
{
if (this.TryGetObjectReference(name, out DataBindingEntry entry)) {
return entry;
}
throw new KeyNotFoundException();
}
}
public bool ShouldClose
{
get => InternalIO.glfwWindowShouldClose(viewPortDisplay.ViewPortHandle) != 0;
set => InternalIO.glfwSetWindowShouldClose(
viewPortDisplay.ViewPortHandle, value ? 1 : 0);
}
public int CurrentFrameCount => frameTimeProvider.CurrentSpan;
public int FrameSpeed => _frameSpeed;
/// <summary>
/// Height of this form, represent in <see cref="int" />
/// </summary>
public int Height
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => viewPortDisplay.Height;
}
/// <summary>
/// Width of this form, represent in <see cref="int" />
/// </summary>
public int Width
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => viewPortDisplay.Width;
}
public unsafe IntPtr WindowID
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => viewPortDisplay.ViewPortHandle;
}
public string Name
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => viewPortDisplay.Name;
}
/// <summary>
/// Width of this form, represent in <see cref="int" />
/// </summary>
public Vec2 Size
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new Vec2(Width, Height);
}
public ViewPort ViewPortBinding
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => viewPortDisplay;
}
public abstract void CustomizeInitialize();
/// <summary>
/// Set the Size limit of current form
/// </summary>
/// <param _label="minSize">
/// Minimum Size of current form. In form of a <see cref="Vec2" /> of (width,height)
/// </param>
/// <param _label="maxSize">
/// Maximum Size of current form. In form of a <see cref="Vec2" /> of (width,height)
/// </param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSizeLimit(Vec2 minSize, Vec2 maxSize)
{
ThreadHelper.MainThreadAssert();
InternalIO.glfwSetWindowSizeLimits(
this.viewPortDisplay.ViewPortHandle, (int)minSize.X, (int)minSize.Y, (int)maxSize.X,
(int)maxSize.Y);
}
/// <summary>
/// Set the Size limit of current form
/// </summary>
/// <param _label="minWidth">
/// Minimum width of current form
/// </param>
/// <param _label="minHeight">
/// Minimum height of current form
/// </param>
/// <param _label="maxWidth">
/// Maximum width of current form
/// </param>
/// <param _label="maxHeight">
/// Maximum height of current form
/// </param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSizeLimit(int minWidth, int minHeight, int maxWidth, int maxHeight)
{
ThreadHelper.MainThreadAssert();
InternalIO.glfwSetWindowSizeLimits(
this.viewPortDisplay.ViewPortHandle, minWidth, minHeight, maxWidth, maxHeight);
}
public abstract bool TryGetObjectReference(string name, out DataBindingEntry entry);
protected unsafe void SetFrameSizeCallback(FrameBufferSizeHandler callback)
{
_resizeCallback = callback;
IntPtr handlerPtr = Marshal.GetFunctionPointerForDelegate(callback);
InternalIO.glfwSetFrameBufferSizeCallback(
viewPortDisplay.ViewPortHandle, (delegate* unmanaged[Cdecl]<IntPtr,int,int,void>)handlerPtr);
}
private void DefaultFrameRewsizeCallback(IntPtr windowHandle, int width, int height)
{
ViewPort.GetExistedViewPort(windowHandle, out ViewPort vp);
vp.RequestFlushSizeInNextFrame(width, height);
// Console.WriteLine($"{width} {height}");
}
}
}
+122
View File
@@ -0,0 +1,122 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="ViewPort.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
namespace StgSharp.MVVM
{
public class ViewPort
{
private static readonly ConcurrentDictionary<IntPtr, ViewPort> _handleToViewPortIndex = [];
private int _width, _height, _newWidth, _newHeight;
internal ViewPort()
{
_newHeight = 600;
_newWidth = 800;
FlushSize();
Name = new StackFrame(1, false).
GetMethod()!.DeclaringType!.Name;
Monitor = IntPtr.Zero;
ViewPortHandle = InternalIO.glfwCreateWindow(
_newWidth, _newHeight, Encoding.UTF8.GetBytes(Name), Monitor, IntPtr.Zero);
if (ViewPortHandle == IntPtr.Zero) {
throw new InvalidOperationException("Unable to create viewport handle.");
}
_ = _handleToViewPortIndex.TryAdd(ViewPortHandle, this);
}
public ViewPort(int width, int height, string name, IntPtr monitor)
{
_newWidth = width;
_newHeight = height;
FlushSize();
Name = name;
Monitor = monitor;
ViewPortHandle = InternalIO.glfwCreateWindow(
_newWidth, _newHeight, Encoding.UTF8.GetBytes(Name), Monitor, IntPtr.Zero);
if (ViewPortHandle == IntPtr.Zero) {
throw new InvalidOperationException("Unable to create viewport handle.");
}
_ = _handleToViewPortIndex.TryAdd(ViewPortHandle, this);
}
public unsafe int Height
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _height;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal set => Interlocked.Exchange(ref _height, value);
}
public unsafe int Width
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _width;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal set => Interlocked.Exchange(ref _width, value);
}
public IntPtr GraphicHandle { get; internal set; }
public IntPtr Monitor { get; internal set; }
public IntPtr ViewPortHandle { get; private set; }
public string Name { get; set; }
// [BlueprintNodeExecution]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool GetExistedViewPort(IntPtr handle, out ViewPort port)
{
return _handleToViewPortIndex.TryGetValue(handle, out port);
}
internal unsafe void FlushSize()
{
_ = Interlocked.Exchange(ref _height, _newHeight);
_ = Interlocked.Exchange(ref _width, _newWidth);
}
internal void RequestFlushSizeInNextFrame(int width, int height)
{
_ = Interlocked.Exchange(ref _newHeight, height);
_ = Interlocked .Exchange(ref _newWidth, width);
}
}
}