Daily update 2 on 20240228 by nitload youmu

This commit is contained in:
Nitload
2025-03-01 04:58:46 +08:00
parent 90d5f76511
commit f22862dfc4
983 changed files with 180004 additions and 0 deletions
@@ -0,0 +1,188 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BlueprintSchedueler.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.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace StgSharp.Blueprint
{
/// <summary>
/// A sets of complex logic designed for running in multi threads environment. Warning: do not
/// run a <see cref="BlueprintSchedueler" /> instance in multi threads more than once.
/// </summary>
public partial class BlueprintSchedueler : IConvertableToBlueprintNode
{
private BeginningNode beginNode;
private Dictionary<string, BlueprintNode> allNode;
private EndingNode endNode;
private Func<bool> terminate;
private List<BlueprintNode> globalNodeList;
private List<BlueprintNode> nativeNodeList;
private SemaphoreSlim runningStat;
internal int currentGlobalNodeIndex;
internal int currentNativeNodeIndex;
public BlueprintSchedueler()
{
allNode = new Dictionary<string, BlueprintNode>();
globalNodeList = new List<BlueprintNode>();
nativeNodeList = new List<BlueprintNode>();
runningStat = new SemaphoreSlim( 1, 1 );
beginNode = new BeginningNode( this );
endNode = new EndingNode( this );
}
public BlueprintNode BeginLayer => beginNode;
public BlueprintNode EndLayer => endNode;
public bool IsRunning
{
get => runningStat.CurrentCount == 0;
}
public ReadOnlySpan<string> InputInterfacesName
{
get { return beginNode.OutputInterfaces
.Select( p => p.Key )
.ToArray(); }
}
public ReadOnlySpan<string> OutputInterfacesName
{
get { return beginNode.OutputInterfaces
.Select( p => p.Key )
.ToArray(); }
}
/**/
internal SemaphoreSlim RunningStat
{
get => runningStat;
}
/**/
public void AddNode( BlueprintNode node, bool isNative )
{
_ = node ?? throw new ArgumentNullException( nameof( node ) );
node.IsNative = isNative;
allNode.Add( node.Name, node );
}
public void ExecuteMain(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output )
{
BlueprintRunner.Run( this );
}
public BlueprintNodeOperation Operation
{
get => ExecuteMain;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public (string name, BlueprintPipelineArgs arg)[] GetOutput()
{
return endNode.OutputData;
}
public void Init()
{
foreach( KeyValuePair<string, BlueprintNode> item in allNode ) {
if( item.Value.IsNative ) {
nativeNodeList.Add( item.Value );
} else {
globalNodeList.Add( item.Value );
}
}
nativeNodeList.Sort();
globalNodeList.Sort();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetInput(
params (string name, BlueprintPipelineArgs arg)[] parameters )
{
beginNode.InputData = parameters;
}
public void Terminate()
{
Interlocked.Exchange( ref currentGlobalNodeIndex, int.MaxValue );
Interlocked.Exchange( ref currentNativeNodeIndex, int.MaxValue );
}
internal bool RequestNexGlobalNode( out BlueprintNode node )
{
if( currentGlobalNodeIndex < globalNodeList.Count ) {
node = globalNodeList[ currentGlobalNodeIndex ];
Interlocked.Increment( ref currentGlobalNodeIndex );
return true;
}
node = default!;
return false;
}
internal bool RequestNextNativeNode( out BlueprintNode node )
{
if( currentNativeNodeIndex < nativeNodeList.Count ) {
node = nativeNodeList[ currentNativeNodeIndex ];
Interlocked.Increment( ref currentNativeNodeIndex );
return true;
}
node = default!;
return false;
}
~BlueprintSchedueler()
{
runningStat.Dispose();
}
}
}
@@ -0,0 +1,303 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BlueprintNode.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.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Blueprint
{
/// <summary>
///
/// </summary>
/// <risk>
/// Reset pipeline has risk, this operation is a direct operation to port in current node, the
/// port on the other node cannot get the change.
/// </risk>
#pragma warning disable CA1036
public class BlueprintNode : IComparable<BlueprintNode>
#pragma warning restore CA1036
{
private static BlueprintNode _emptyNode = new BlueprintNode(
string.Empty, null!, false );
private static Dictionary<string, BlueprintPipeline> _emptyLayer = new();
private protected bool _levelAvailable, _nativeRequested;
private protected Dictionary<string, BlueprintPipeline> _inputInterfaces;
private protected Dictionary<string, BlueprintPipeline> _outputInterfaces;
private protected int _level;
private IConvertableToBlueprintNode _mainOperation;
private string _name;
internal BlueprintNode(
string name,
IConvertableToBlueprintNode node,
bool isNative )
{
_levelAvailable = false;
_name = name;
_nativeRequested = isNative;
_mainOperation = node;
_inputInterfaces = new Dictionary<string, BlueprintPipeline>();
_outputInterfaces = new Dictionary<string, BlueprintPipeline>();
foreach( string portName in node.InputInterfacesName ) {
_inputInterfaces.Add( portName, null! );
}
foreach( string portName in node.OutputInterfacesName ) {
_outputInterfaces.Add( portName, null! );
}
}
#pragma warning disable CS8618
internal BlueprintNode(
BlueprintNodeOperation operation,
string name,
bool isNative,
string[] inputPorts,
string[] outputPorts )
#pragma warning restore CS8618
{
if( ( inputPorts == null ) || ( inputPorts.Length == 0 ) ) {
throw new ArgumentNullException( nameof( inputPorts ) );
}
if( ( outputPorts == null ) || ( outputPorts.Length == 0 ) ) {
throw new ArgumentNullException( nameof( outputPorts ) );
}
_levelAvailable = false;
_name = name;
_nativeRequested = isNative;
operation = operation ?? DefaultOperation;
_mainOperation = new DefaultConvertableToBlueprintNode(
operation,
inputPorts,
outputPorts);
_inputInterfaces = new Dictionary<string, BlueprintPipeline>();
_outputInterfaces = new Dictionary<string, BlueprintPipeline>();
foreach( string portName in inputPorts ) {
_inputInterfaces.Add(
portName,
SealedBlueprintPiipeline.SealOutput( this, name ) );
}
foreach( string portName in outputPorts ) {
_outputInterfaces.Add( portName, null! );
}
}
protected static void DefaultOperation(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
{
BlueprintPipeline.SkipAll(output);
}
public static BlueprintNode Empty
{
get => _emptyNode;
}
public bool IsNative
{
get => _nativeRequested;
internal set => _nativeRequested = value;
}
public static Dictionary<string, BlueprintPipeline> EmptyPortLayer
{
get => _emptyLayer;
}
public int Level
{
get
{
if( _levelAvailable ) {
return _level;
}
_level = 0;
foreach( KeyValuePair<string, BlueprintPipeline> item in _inputInterfaces ) {
if( item.Value == null ) {
continue;
}
if( _level < item.Value.Level ) {
_level = item.Value.Level;
}
}
_level += 1;
_levelAvailable = true;
return _level;
}
}
public string Name => _name;
internal Dictionary<string, BlueprintPipeline> InputInterfaces => _inputInterfaces;
internal Dictionary<string, BlueprintPipeline> OutputInterfaces => _outputInterfaces;
internal IConvertableToBlueprintNode Value
{
get => _mainOperation;
}
public void Append(
[NotNull] BlueprintNode next,
string thisOutputPortName,
string afterInputPortName )
{
this._levelAvailable = false;
BlueprintPipeline pipeline = new BlueprintPipeline( this, next );
if( next is EndingNode enode ) {
enode.SetCertainInputPort( afterInputPortName, pipeline );
} else {
next.SetCertainInputPort( afterInputPortName, pipeline );
}
SetCertainOutputPort( thisOutputPortName, pipeline );
}
public int CompareTo( BlueprintNode other )
{
if( null == other ) {
throw new ArgumentNullException( nameof( other ) );
}
return this.Level.CompareTo( other.Level );
}
public void Prepend(
[NotNull] BlueprintNode former,
string formerOutputPortName,
string thisInputPortName )
{
this._levelAvailable = false;
BlueprintPipeline pipeline = new BlueprintPipeline( former, this );
if( former is BeginningNode bnode ) {
bnode.SetCertainOutputPort( formerOutputPortName, pipeline );
} else {
former.SetCertainOutputPort( formerOutputPortName, pipeline );
}
SetCertainInputPort( thisInputPortName, pipeline );
}
public virtual void Run()
{
try {
//Console.WriteLine(_name);
BlueprintPipeline.WaitAll( _inputInterfaces );
if( _mainOperation != null ) {
_mainOperation.Operation(
in _inputInterfaces, in _outputInterfaces );
}
}
catch( Exception ) {
throw;
}
}
#region port operation
public BlueprintPipeline GetInputPort( string name )
{
BlueprintPipeline ret;
if( !_inputInterfaces.TryGetValue( name, out ret ) ) {
throw new ArgumentOutOfRangeException(
$"Cannot find the interface named {name} in node {Name}." );
}
return ret;
}
public BlueprintPipeline GetOutputPort( string name )
{
BlueprintPipeline ret;
if( !_outputInterfaces.TryGetValue( name, out ret ) ) {
throw new ArgumentOutOfRangeException(
$"Cannot find the interface named {name} in node {Name}." );
}
return ret;
}
public void SetCertainInputPort(
string name,
BlueprintPipeline pipeline )
{
if( !_inputInterfaces.ContainsKey( name ) ) {
throw new ArgumentException(
$"Cannot find the interface named {name} in node {Name}." );
}
_inputInterfaces[ name ] = pipeline;
}
public void SetCertainOutputPort(
string name,
BlueprintPipeline pipeline )
{
if( !_outputInterfaces.ContainsKey( name ) ) {
throw new ArgumentOutOfRangeException(
$"Cannot find the interface named {name} in node {Name}." );
}
_outputInterfaces[ name ] = pipeline;
}
#endregion
}//--------------------------------- end of class -----------------------------------
public class BlueprintNodeRunException : Exception
{
protected BlueprintNodeRunException(
SerializationInfo info,
StreamingContext context )
: base( info, context ) { }
public BlueprintNodeRunException() { }
public BlueprintNodeRunException( Exception ex )
: base( string.Empty, ex ) { }
public BlueprintNodeRunException( string message ) : base( message ) { }
public BlueprintNodeRunException(
string message,
Exception innerException )
: base( message, innerException ) { }
}
}
@@ -0,0 +1,58 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BlueprintNodeCraeater.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Blueprint
{
public partial class BlueprintSchedueler
{
public BlueprintNode CreateBlueprintNode(
string name,
BlueprintNodeOperation operation,
string[] inputPort,
string[] outputPort,
bool isNative )
{
BlueprintNode node = new BlueprintNode(
operation, name, isNative, inputPort, outputPort );
if( isNative ) {
nativeNodeList.Add( node );
} else {
globalNodeList.Add( node );
}
return node;
}
}
}
@@ -0,0 +1,226 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BlueprintRunner.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.Threading;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Blueprint
{
public static class BlueprintRunner
{
private static NodeRunner[] allAvailableTask = CreateBlueprintRunnerArray();
private static CancellationTokenSource cts = new CancellationTokenSource();
private static ConcurrentStack<BlueprintSchedueler> blueprintInWaiting
= new ConcurrentStack<BlueprintSchedueler>();
private static int _callingThread;
private static SemaphoreSlim bpLock = new SemaphoreSlim( 0, 1 );
private static NodeRunner[] CreateBlueprintRunnerArray()
{
int count = Environment.ProcessorCount;
return new NodeRunner[ count < 2 ? count : count - 2];
}
/// <summary>
/// Only the fallowing occasions of calling are valid:
/// 1. no bp is running or the only bp is quitting.
/// 2. calling from the main thread and the current running bp.
/// </summary>
internal static bool IsValidCalling
{
get
{
if( ( NodeRunner.CurrentBlueprint == null ) || //no bp running at all
( ( blueprintInWaiting.IsEmpty ) && ( NodeRunner.CurrentBlueprint.IsRunning == false ) ) )
// a bp is quiting
{
//in case no bp is running
return true;
}
int? id = Task.CurrentId;
if( id is null ) {
// in case calling from main thread and current running bp
return _callingThread == Environment.CurrentManagedThreadId;
}
foreach( NodeRunner item in allAvailableTask ) {
if( item.Id == id ) {
//if calling from any bp running task
return true;
}
}
return false;
}
}
public static void Run(BlueprintSchedueler blueprint)
{
//Console.WriteLine();
if( blueprint == null ) {
return;
}
if( blueprint.IsRunning ) {
throw new InvalidOperationException(
"Attempt to run a blueprint instance twice." );
}
if( IsValidCalling ) {
//Console.WriteLine("valid and run");
if( InterruptAndRunNewBp( blueprint ) ) {
while (InterruptAndRunNewBp(
NodeRunner.CurrentBlueprint )){ };
}
} else {
bpLock.Wait();
if( InterruptAndRunNewBp( blueprint ) ) {
while (InterruptAndRunNewBp(
NodeRunner.CurrentBlueprint)) { }
}
bpLock.Release();
}
Interlocked.Exchange( ref _callingThread, -1 );
}
public static void SetMaxTaskCount( int size )
{
if( size < 1 ) {
size = 1;
}
if( allAvailableTask.Length >= size ) {
for( int i = size; i < allAvailableTask.Length; i++ ) {
if( allAvailableTask[ i ] != null ) {
allAvailableTask[ i ].Cancel();
}
}
}
Array.Resize( ref allAvailableTask, size );
}
public static void Terminate()
{
cts.Cancel();
NodeRunner.CurrentBlueprint.Terminate();
foreach( NodeRunner task in allAvailableTask ) {
task.Cts.Cancel();
}
foreach( BlueprintSchedueler bp in blueprintInWaiting ) {
bp.Terminate();
}
blueprintInWaiting.Clear();
}
internal static bool InterruptAndRunNewBp( BlueprintSchedueler newBp )
{
Debug.Assert( newBp != null );
if( ( newBp != NodeRunner.CurrentBlueprint ) && ( NodeRunner.CurrentBlueprint != null ) ) {
//if a running bp exists
blueprintInWaiting.Push( NodeRunner.CurrentBlueprint );
}
//load new bp to current bp
Interlocked.Exchange( ref NodeRunner.CurrentBlueprint!, newBp );
Interlocked.Exchange(
ref _callingThread, Environment.CurrentManagedThreadId );
//run beginning node to init it first.
if( !NodeRunner.CurrentBlueprint.IsRunning ) {
( NodeRunner.CurrentBlueprint.BeginLayer as BeginningNode )!.Run();
}
//refresh all tasks
for( int i = 0; i < allAvailableTask.Length; i++ ) {
NodeRunner item = allAvailableTask[ i ];
if( ( item is null ) || item.IsCompleted ) {
allAvailableTask[ i ] = NodeRunner.Run();
}
}
BlueprintNode node;
while( !cts.Token.IsCancellationRequested && NodeRunner.CurrentBlueprint
.RequestNextNativeNode( out node ) ) {
node.Run();
if( !NodeRunner.CurrentBlueprint.IsRunning ) {
break;
}
}
( NodeRunner.CurrentBlueprint.EndLayer as EndingNode )!.Run();
return blueprintInWaiting.TryPeek( out NodeRunner.CurrentBlueprint );
}
}
internal class NodeRunner : CancellableTask
{
private static BlueprintSchedueler _current;
internal NodeRunner()
: base()
{
_startup = InternalRun;
}
internal static ref BlueprintSchedueler CurrentBlueprint
{
get => ref _current;
}
internal static NodeRunner Run()
{
NodeRunner ret = new NodeRunner { _startup = InternalRun };
ret._internalTask = Task.Run( ret.InternalAction );
return ret;
}
private static void InternalRun( CancellationToken token )
{
//Console.WriteLine("Task Begin");
BlueprintNode item;
while( ( CurrentBlueprint != null ) && CurrentBlueprint.IsRunning && !token.IsCancellationRequested && CurrentBlueprint.RequestNexGlobalNode(
out item ) ) {
//Console.WriteLine($"Get node of {item.Name}, going to run.");
item.Run();
}
//Console.WriteLine("Task Completed");
}
}//------------------------------------- End of Class ------------------------------------------
}
@@ -0,0 +1,91 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="CrossFrameBlueprintNode.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Blueprint;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Blueprint
{
public class CrossFrameOperation : IConvertableToBlueprintNode
{
private int currentCount;
private readonly int cycleCount;
private Action _mainExecution;
public CrossFrameOperation( Action startup, int cycleCount )
{
MainExecution = startup;
this.cycleCount = ( cycleCount > 1 ) ?
cycleCount : throw new ArgumentException(
$"{$"The {typeof(CrossFrameOperation).Name} crosses only one cycle, "}{$"please use a {typeof(BlueprintNode).Name} instead."}" );
this.cycleCount = cycleCount;
currentCount = cycleCount;
}
public Action MainExecution
{
get => _mainExecution;
private protected set => _mainExecution = value;
}
private static string[] _inputName = ["TaskIn"];
private static string[] _outputName = ["TaskOut"];
public BlueprintNodeOperation Operation
{
get => ExecuteMain;
}
public void ExecuteMain(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output )
{
if( currentCount < cycleCount ) {
Interlocked.Increment( ref currentCount );
} else {
Interlocked.Exchange( ref currentCount, 0 );
Task.Run( MainExecution );
}
//Console.WriteLine(currentCount);
BlueprintPipeline.SkipAll( output );
}
public ReadOnlySpan<string> InputInterfacesName => _inputName;
public ReadOnlySpan<string> OutputInterfacesName => _outputName;
}
}
@@ -0,0 +1,82 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IConvertableToBlueprintNode.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace StgSharp.Blueprint
{
public delegate void BlueprintNodeOperation(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output );
public interface IConvertableToBlueprintNode
{
public ReadOnlySpan<string> InputInterfacesName
{
get;
}
public ReadOnlySpan<string> OutputInterfacesName
{
get;
}
BlueprintNodeOperation Operation { get; }
}
internal class DefaultConvertableToBlueprintNode : IConvertableToBlueprintNode
{
private string[] _input;
private string[] _output;
private BlueprintNodeOperation _execution;
public DefaultConvertableToBlueprintNode(
BlueprintNodeOperation execution,
string[] input,
string[] output )
{
_input = input;
_output = output;
_execution = execution;
}
public BlueprintNodeOperation Operation => _execution;
public ReadOnlySpan<string> InputInterfacesName => _input;
public ReadOnlySpan<string> OutputInterfacesName => _output;
}
}
+164
View File
@@ -0,0 +1,164 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="PipeLine.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Security.Authentication.ExtendedProtection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Blueprint
{
public class BlueprintPipeline
{
private protected BlueprintNode after;
private protected BlueprintNode former;
private protected BlueprintPipelineArgs args;
private protected SemaphoreSlim formerCompleteSemaphore;
public BlueprintPipeline( BlueprintNode former, BlueprintNode after )
{
this.former = former;
this.after = after;
formerCompleteSemaphore = new SemaphoreSlim(
initialCount: 0, maxCount: 1 );
}
public BlueprintNode After => after;
public BlueprintNode Former => former;
public BlueprintPipelineArgs Args
{
get => args;
set => args = value;
}
public int Level => former.Level;
public static void SkipAll(
Dictionary<string, BlueprintPipeline> ports )
{
if( ports == null ) {
return;
}
foreach( KeyValuePair<string, BlueprintPipeline> item in ports ) {
if( item.Value != null ) {
item.Value.CompleteAndSkip();
}
}
}
public static void WaitAll(
Dictionary<string, BlueprintPipeline> ports )
{
if( ports == null ) {
return;
}
foreach( KeyValuePair<string, BlueprintPipeline> item in ports ) {
if( item.Value != null ) {
item.Value.WaitForStart();
}
}
}
public virtual void WaitForStart()
{
//Console.WriteLine($"Waiting \t{former.ContextName}\t->\t{after.ContextName}");
formerCompleteSemaphore.Wait();
}
~BlueprintPipeline()
{
formerCompleteSemaphore.Dispose();
}
#region pipline op
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void CompleteAndSkip()
{
//Console.WriteLine($"Complete\t{former.Name}\t->\t{after.Name}");
formerCompleteSemaphore.Release();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void CompleteAndWriteData( BlueprintPipelineArgs args )
{
this.args = args;
CompleteAndSkip();
}
#endregion
}
public abstract class BlueprintPipelineArgs
{
public object? Value
{
get;
set;
}
public object? ValueDefault
{
get;
}
}
public sealed class SealedBlueprintPiipeline:BlueprintPipeline
{
internal SealedBlueprintPiipeline(BlueprintNode former, BlueprintNode after):
base(former, after)
{
}
public static SealedBlueprintPiipeline SealOutput(BlueprintNode node, string portName)
{
return new SealedBlueprintPiipeline(node, BlueprintNode.Empty);
}
public static SealedBlueprintPiipeline SealInput(BlueprintNode node, string portName)
{
return new SealedBlueprintPiipeline(BlueprintNode.Empty, node);
}
public sealed override void WaitForStart()
{
}
}
}
@@ -0,0 +1,111 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="RouteSwitch.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace StgSharp.Blueprint
{
public class RouteSwitch : BlueprintNode
{
private protected Dictionary<string, (BlueprintPipeline pipeline, Func<bool> openingRule)> outputDictionary;
public RouteSwitch( string name, bool isNative, string inputPorts )
: base(DefaultOperation, name, isNative, [inputPorts], [string.Empty] )
{
outputDictionary = new Dictionary<string, (BlueprintPipeline pipeline, Func<bool> openingRule)>(
);
}
public new int Level
{
get
{
if( _levelAvailable ) {
return _level;
}
_level = 0;
KeyValuePair<string, BlueprintPipeline> item = _inputInterfaces.First(
);
if( item.Value == null ) {
throw new InvalidOperationException();
}
if( _level <= item.Value.Level ) {
_level = item.Value.Level;
}
return _level;
}
}
public new void AddBefore(
BlueprintNode after,
string thisOutputPortName,
string afterInputPortName )
{
this.AppendNode( after, afterInputPortName, () => true );
}
public void AppendNode(
BlueprintNode node,
string portName,
Func<bool> openningRule )
{
if( node == null ) {
throw new ArgumentNullException( nameof( node ) );
}
string indexName = $"{node.Name}.{portName}";
BlueprintPipeline p = new BlueprintPipeline( this, node );
node.InputInterfaces[ portName ] = p;
outputDictionary.Add( indexName, (p, openningRule) );
}
public new void Run()
{
try {
BlueprintPipeline input = InputInterfaces.First().Value;
input.WaitForStart();
foreach( KeyValuePair<string, (BlueprintPipeline pipeline, Func<bool> openingRule)> item in outputDictionary ) {
if( item.Value.openingRule() ) {
item.Value.pipeline.CompleteAndWriteData( input.Args );
}
}
}
catch( Exception ) {
throw;
}
}
}
}
+121
View File
@@ -0,0 +1,121 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="SideNode.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Blueprint
{
internal sealed class BeginningNode : BlueprintNode
{
private BlueprintSchedueler _bp;
public BeginningNode( BlueprintSchedueler bp )
: base(DefaultOperation, name: "BeginningNode", true, ["default"], ["default"] )
{
_bp = bp;
}
internal (string name, BlueprintPipelineArgs arg)[] InputData
{
set
{
if( value == null ) {
return;
}
foreach( (string name, BlueprintPipelineArgs arg) parameter in value ) {
OutputInterfaces[ parameter.name ].Args = parameter.arg;
}
}
}
public override void Run()
{
_bp.RunningStat.Wait();
BlueprintPipeline.SkipAll( _outputInterfaces );
}
public new void SetCertainOutputPort(
string name,
BlueprintPipeline pipeline )
{
if( _outputInterfaces.ContainsKey( name ) ) {
_outputInterfaces[ name ] = pipeline;
}
_outputInterfaces.Add( name, pipeline );
}
}
internal sealed class EndingNode : BlueprintNode
{
private BlueprintSchedueler _bp;
public EndingNode( BlueprintSchedueler bp )
: base(DefaultOperation, name: "EndingNode", true, ["default"], ["default"] )
{
_bp = bp;
}
internal (string name, BlueprintPipelineArgs arg)[] OutputData
{
get { return InputInterfaces.Select(
key => (key.Key, key.Value.Args) )
.ToArray(); }
}
public override void Run()
{
BlueprintPipeline.WaitAll( _inputInterfaces );
Interlocked.Exchange( ref _bp.currentGlobalNodeIndex, 0 );
Interlocked.Exchange( ref _bp.currentNativeNodeIndex, 0 );
_bp.RunningStat.Release();
}
public new void SetCertainInputPort(
string name,
BlueprintPipeline pipeline )
{
if( _inputInterfaces.ContainsKey( name ) ) {
_inputInterfaces[ name ] = pipeline;
}
_inputInterfaces.Add( name, pipeline );
}
}
}
+131
View File
@@ -0,0 +1,131 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Counter.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;
namespace StgSharp
{
public class Counter<T>
where T: struct, IConvertible, IFormattable, IComparable
#if NET8_OR_GREATER
,INumber
#endif
{
internal dynamic _value;
internal readonly T _defualtIncreament;
internal readonly T _defualtDecreament;
internal readonly T _defaultValue;
public Counter( T defualtValue, T defualtIncreament, T defualtDecreament )
{
Type tType = typeof( T );
if (
tType != typeof(byte) &&
tType != typeof(short) &&
tType != typeof(int) &&
tType != typeof(long) &&
tType != typeof(sbyte) &&
tType != typeof(ushort) &&
tType != typeof(uint) &&
tType != typeof(ulong) &&
tType != typeof(float) &&
tType != typeof(double))
{
throw new ArgumentException(
"Input is not number value type");
}
_value = defualtValue;
_defaultValue = defualtValue;
_defualtIncreament = defualtIncreament;
_defualtDecreament = defualtDecreament;
}
public T DecreamentSoan => _defualtDecreament;
public T IncreamentSpan => _defualtIncreament;
public T CurrentSpan => _value - _defaultValue;
public T Value
{
get => _value;
set => _value = value;
}
public void Add( T value )
{
_value += value;
}
public void QuickAdd()
{
_value += _defualtIncreament;
}
public void QuickSub()
{
_value -= _defualtDecreament;
}
public void Reset()
{
_value = _defaultValue;
}
public void Sub( T value )
{
_value -= value;
}
public override string ToString()
{
return Value.ToString();
}
public static Counter<T> operator --( Counter<T> counter )
{
counter.QuickSub();
return counter;
}
public static Counter<T> operator ++( Counter<T> counter )
{
counter.QuickAdd();
return counter;
}
public static implicit operator T( Counter<T> counter )
{
return counter.Value;
}
}
}
@@ -0,0 +1,81 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="PlainGeometryCollisionSensor.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Geometries;
using System;
namespace StgSharp
{
public class CollisionEventArgs:EventArgs
{
public CollisionEventArgs(IGeometry target, IGeometry boarder)
{
Target = target;
Boarder = boarder;
}
public IGeometry Target { get; set; }
public IGeometry Boarder { get; set; }
}
public class PlainGeometryCollisionSensor<TBoarder,TTarget>
where TBoarder : IGeometry
where TTarget : IGeometry
{
internal PlainGeometry _boarder;
internal PlainGeometry _target;
internal EventHandler<CollisionEventArgs> _rule;
public event EventHandler<CollisionEventArgs> Rule
{
add { _rule += value; }
remove
{
if (value == null)
{
return;
}
#pragma warning disable CS8601
_rule -= value;
#pragma warning restore CS8601
}
}
public PlainGeometry boarder => _boarder;
public PlainGeometry target
{
get => _target;
set => _target = value;
}
}
}
+72
View File
@@ -0,0 +1,72 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="StateMachine.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
public interface IStateMachine<T> where T: Enum
{
public T LastStableState
{
get;
}
public bool TryEnterState();
public bool TryExitState();
public bool TrySwitchState();
}
public interface IStateMachineWithSwitchSpan<TState, TSpan> : IStateMachine<TState>
where TState: Enum
{
public bool IsInStabelState
{
get;
}
public TState NextStableState
{
get;
}
public bool TrySwitchState();
}
}
@@ -0,0 +1,164 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TimeFunction.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Timing
{
public class TimeFunction
{
private float _beginning, _ending;
private Func<float, float> _timeRelatedCalculation;
private TimeSpanProvider _timeProvider;
internal TimeFunction() { }
public TimeFunction(
TimeSpanProvider timeSpanProvider,
Func<float, float> timeRelatedCalculation,
float range )
{
_timeProvider = timeSpanProvider;
_timeRelatedCalculation = timeRelatedCalculation;
if( timeSpanProvider == null ) {
return;
}
_beginning = _timeProvider.CurrentSecond;
_ending = _timeProvider.CurrentSecond + range;
}
public virtual bool IsComplete
{
get => _timeProvider.CurrentSecond > _ending;
}
public Func<float, float> TimeRelatedCalculation
{
get { return _timeRelatedCalculation; }
set { _timeRelatedCalculation = value; }
}
public static TimeFunction One
{
get => new TimeFunctionOne();
}
public TimeSpanProvider TimeSpanProvider
{
get { return _timeProvider; }
set { _timeProvider = value; }
}
public virtual float Calculate()
{
if( _timeProvider.CurrentSecond < _ending ) {
return 0;
}
return _timeRelatedCalculation(
_timeProvider.CurrentSecond - _beginning );
}
public static TimeFunction Proportional(
TimeSpanProvider time,
float begin,
float range )
{
return new TimeFunction( time, ( float t ) => t + begin, range );
}
public virtual TimeFunction Renew(
(Func<float, float> func, float range) funcPair )
{
return new TimeFunction(
_timeProvider, funcPair.func, funcPair.range );
}
public virtual TimeFunction Renew(
Func<float, float> func,
float range )
{
return new TimeFunction( _timeProvider, func, range );
}
public void Reset()
{
float range = _ending - _beginning;
_beginning = _timeProvider.CurrentSecond;
_ending = _beginning + range;
}
public virtual TimeFunction Reverse()
{
float range = _ending - _beginning;
return new TimeFunction(
_timeProvider, p => _timeRelatedCalculation( range - p ),
range );
}
}
public sealed class TimeFunctionOne : TimeFunction
{
internal TimeFunctionOne() : base() { }
public override bool IsComplete
{
get => true;
}
public override float Calculate()
{
return 1;
}
public override TimeFunction Renew(
(Func<float, float> func, float range) funcPair )
{
throw new NotSupportedException();
}
public override TimeFunction Renew(
Func<float, float> func,
float range )
{
throw new NotSupportedException();
}
#pragma warning disable CA1822
public new void Reset()
#pragma warning restore CA1822
{ }
}
}
@@ -0,0 +1,152 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TimeProvider.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.Timing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
namespace StgSharp
{
public static partial class StgSharp
{
internal static StgSharpTime mainTimeProvider = new StgSharpTime();
internal static TimeSourceProviderBase MainTimeProvider => mainTimeProvider;
}
public sealed class StgSharpTime : TimeSourceProviderBase
{
private static List<TimeSpanProvider> subscriberList = new List<TimeSpanProvider>(
);
private static long accuracy;
private static Stopwatch mainProvider = new Stopwatch();
private static Thread timeProvideThread;
internal StgSharpTime() { }
public static TimeSourceProviderBase OnlyInstance => StgSharp.MainTimeProvider;
public override sealed void StartProvidingTime()
{
if( mainProvider.IsRunning ) {
return;
}
mainProvider.Start();
//speed test
long totalMS, internalFrequncy = Stopwatch.Frequency;
for( int i = 0; i < 100; i++ ) {
totalMS = mainProvider.ElapsedTicks / ( internalFrequncy / ( 1000L * 1000L ) );
for( int t = 0; t < 10; t++ ) {
if( totalMS < 1000 ) {
subscriberList.Add(
new TimeSpanProvider(
100L, TimeSpanProvider.DefaultProvider ) );
}
}
}
mainProvider.Stop();
subscriberList.Clear();
totalMS = mainProvider.ElapsedTicks / ( internalFrequncy / ( 1000L * 1000L ) ) / 100L;
accuracy = ( totalMS * 2 ) / 3;
mainProvider.Reset();
timeProvideThread = new Thread( new ThreadStart( ProvideTime ) );
timeProvideThread.Start();
}
public override void StopProvidingTime()
{
lock( mainProvider ) {
mainProvider.Stop();
}
}
public void Terminate()
{
lock( mainProvider ) {
mainProvider.Stop();
}
}
protected override sealed void AddSubscriberUnsynced(
TimeSpanProvider subscriber )
{
subscriberList.Add( subscriber );
}
protected override sealed void RemoveSubscriberUnsynced(
TimeSpanProvider subscriber )
{
subscriberList.Remove( subscriber );
}
private void ProvideTime()
{
long totalMS, internalFrequncy = Stopwatch.Frequency;
lock( mainProvider ) {
mainProvider.Restart();
}
while( mainProvider.IsRunning ) {
totalMS = mainProvider.ElapsedTicks / ( internalFrequncy / ( 1000L * 1000L ) );
if( subscriberList.Count == 0 ) {
continue;
}
CheckSubscriberSemaphore.Wait();
List<TimeSpanProvider> toRemoveList = new List<TimeSpanProvider>(
);
foreach( TimeSpanProvider subscriber in subscriberList ) {
if( !subscriber.CheckTime( totalMS ) ) {
toRemoveList.Add( subscriber );
InternalIO.InternalWriteLog(
$"Time subscriber {subscriber} is to be removed.",
LogType.Info );
}
;
}
if( toRemoveList.Count != 0 ) {
foreach( TimeSpanProvider subscriber in toRemoveList ) {
subscriberList.Remove( subscriber );
}
}
CheckSubscriberSemaphore.Release();
}
}
}
}
@@ -0,0 +1,89 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TimeSourceProvider.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.Linq;
using System.Threading;
namespace StgSharp.Timing
{
public abstract class TimeSourceProviderBase
{
private SemaphoreSlim _addSubscriberSemaphore = new SemaphoreSlim(
1, 1 );
protected SemaphoreSlim CheckSubscriberSemaphore
{
get => _addSubscriberSemaphore;
}
public void AddSubscriber( TimeSpanProvider subscriber )
{
try {
_addSubscriberSemaphore.Wait();
AddSubscriberUnsynced( subscriber );
}
catch( Exception ) {
throw;
}
finally {
_addSubscriberSemaphore.Release();
}
}
public void RemoveSubscriber( TimeSpanProvider subscriber )
{
_addSubscriberSemaphore.Wait();
try {
RemoveSubscriberUnsynced( subscriber );
}
catch( Exception ) {
throw;
}
finally {
_addSubscriberSemaphore.Release();
}
}
public abstract void StartProvidingTime();
public abstract void StopProvidingTime();
protected abstract void AddSubscriberUnsynced(
TimeSpanProvider subscriber );
protected abstract void RemoveSubscriberUnsynced(
TimeSpanProvider subscriber );
}
}
@@ -0,0 +1,165 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TimeSpanAwaitingToken.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.Diagnostics.Contracts;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Timing
{
#nullable enable
public sealed class TimeSpanAwaitingToken : IDisposable
{
private static readonly ConcurrentStack<int> s_unusedID = new ConcurrentStack<int>(
[0] );
private static int s_maxID;
private static readonly object s_lock = new object();
private EventHandler? _refreshHandler,_missHandler;
private int _size, _id;
private object _participantObject = new object();
private SemaphoreSlim _awaitingSemaphore;
private TimeSpanProvider _provider;
internal TimeSpanAwaitingToken( TimeSpanProvider provider )
{
if( s_unusedID.Count == 1 ) {
lock( s_lock ) {
s_unusedID.TryPop( out int id );
TokenID = id;
s_unusedID.Push( s_maxID++ );
}
} else {
s_unusedID.TryPop( out int id );
TokenID = id;
}
_provider = provider;
_size = 1;
_awaitingSemaphore = new SemaphoreSlim( 0, 1 );
}
internal TimeSpanAwaitingToken( TimeSpanProvider provider, int count )
{
if( s_unusedID.Count == 1 ) {
lock( s_lock ) {
s_unusedID.TryPop( out int id );
TokenID = id;
s_unusedID.Push( s_maxID++ );
}
} else {
s_unusedID.TryPop( out int id );
TokenID = id;
}
_provider = provider;
_size = count;
_awaitingSemaphore = new SemaphoreSlim( 0, _size );
}
public event EventHandler MissTimeSpanRefreshed
{
add { _missHandler += value; }
remove { _missHandler -= value; }
}
public event EventHandler TimeSpanRefreshed
{
add { _refreshHandler += value; }
remove { _refreshHandler -= value; }
}
public int TokenID
{
get => _id;
private set => _id = value;
}
internal SemaphoreSlim AwaitingSemaphoreSlim
{
get => _awaitingSemaphore;
}
public void Dispose()
{
_provider.QuitSpanAwaiting( this );
s_unusedID.Push( TokenID );
_awaitingSemaphore.Dispose();
GC.SuppressFinalize( this );
}
public override int GetHashCode()
{
return _id;
}
public void Participant()
{
lock( _participantObject ) {
_size++;
SemaphoreSlim newSemaphore = new SemaphoreSlim(
_awaitingSemaphore.CurrentCount, _size );
Interlocked.Exchange( ref _awaitingSemaphore, newSemaphore )
.Dispose();
}
}
public void WaitNextSpan()
{
_awaitingSemaphore.Wait();
}
internal void MissRefresh()
{
_missHandler?.Invoke( this, EventArgs.Empty );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
internal void Refresh()
{
_refreshHandler?.Invoke( this, EventArgs.Empty );
}
~TimeSpanAwaitingToken()
{
Dispose();
}
}
#nullable restore
}
@@ -0,0 +1,233 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TimeSpanProvider.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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
namespace StgSharp.Timing
{
/// <summary>
/// A microsecond-accuracy timer. It will refresh every a certain time span.
/// </summary>
public class TimeSpanProvider
{
private bool _subscribed;
private ConcurrentQueue<TimeSpanAwaitingToken> _tokenToAdd = new ConcurrentQueue<TimeSpanAwaitingToken>(
);
private ConcurrentQueue<TimeSpanAwaitingToken> _tokenToQuit;
private Counter<int> timeSpanCount = new Counter<int>( -1, 1, 1 );
private HashSet<TimeSpanAwaitingToken> _awaitingTokens;
private long _maxSpanCount;
private long _spanBegin;
private readonly long _spanLength;
private readonly TimeSourceProviderBase _timeSource;
/// <summary>
/// Create a new <see cref="TimeSpanProvider" /> and define the length of time span. Length
/// of a single time span is defined in microseconds.
/// </summary>
/// <param _name="spanMicroSeconds"></param>
/// <param _name="provider"></param>
public TimeSpanProvider(
long spanMicroSeconds,
TimeSourceProviderBase provider )
{
if( provider == null ) {
throw new ArgumentNullException( nameof( provider ) );
}
_timeSource = provider;
_spanLength = spanMicroSeconds;
_maxSpanCount = int.MaxValue;
provider.AddSubscriber( this );
_subscribed = true;
_awaitingTokens = new HashSet<TimeSpanAwaitingToken>();
_tokenToQuit = new ConcurrentQueue<TimeSpanAwaitingToken>();
}
/// <summary>
/// Create a new <see cref="TimeSpanProvider" /> and define the length of time span. Length
/// of a single time span is defined in seconds.
/// </summary>
/// <param _name="spanSeconds"></param>
/// <param _name="provider"></param>
public TimeSpanProvider(
double spanSeconds,
TimeSourceProviderBase provider )
{
if( provider == null ) {
throw new ArgumentNullException( nameof( provider ) );
}
_timeSource = provider;
_spanLength = ( long )( spanSeconds * 1000L * 1000L );
_spanBegin = -_spanLength;
_maxSpanCount = long.MaxValue;
provider.AddSubscriber( this );
_subscribed = true;
_awaitingTokens = new HashSet<TimeSpanAwaitingToken>();
_tokenToQuit = new ConcurrentQueue<TimeSpanAwaitingToken>();
}
/// <summary>
/// Create a new <see cref="TimeSpanProvider" /> and define the length of time span. Length
/// of a single time span is defined in microseconds.
/// </summary>
/// <param _name="spanLength"></param>
/// <param _name="maxSpan"></param>
/// <param _name="provider"></param>
public TimeSpanProvider(
long spanLength,
long maxSpan,
TimeSourceProviderBase provider )
{
if( provider == null ) {
throw new ArgumentNullException( nameof( provider ) );
}
if( maxSpan <= 0 ) {
throw new ArgumentException(
"Sapn count cannot be smaller than zero" );
}
_timeSource = provider;
_spanLength = spanLength;
_spanBegin = -_spanLength;
provider.AddSubscriber( this );
_subscribed = true;
_awaitingTokens = new HashSet<TimeSpanAwaitingToken>();
_tokenToQuit = new ConcurrentQueue<TimeSpanAwaitingToken>();
}
public double SpanLength
{
get => ( _spanLength * 1.0 ) / ( 1000L * 1000L );
}
public float CurrentSecond
{
get => timeSpanCount.Value * SpanLengthLowPrecession;
}
public float SpanLengthLowPrecession
{
get => ( _spanLength * 1.0f ) / ( 1000 * 1000 );
}
public int CurrentSpan
{
get => timeSpanCount.Value;
}
/// <summary>
/// Time source provider provided in <see cref="StgSharp" /> internal framework.
/// </summary>
public static TimeSourceProviderBase DefaultProvider => StgSharpTime.OnlyInstance;
public TimeSpanAwaitingToken ParticipantSpanAwaiting( int count )
{
TimeSpanAwaitingToken token = new TimeSpanAwaitingToken(
this, count );
_tokenToAdd.Enqueue( token );
return token;
}
public void QuitSpanAwaiting( TimeSpanAwaitingToken token )
{
_tokenToQuit.Enqueue( token );
}
public void StopSpanProviding()
{
Interlocked.Exchange( ref _maxSpanCount, 0 );
}
public void SubscribeToTimeSource(
TimeSourceProviderBase serviceHandler )
{
if( serviceHandler == null ) {
throw new ArgumentNullException( nameof( serviceHandler ) );
}
if( _subscribed ) {
return;
}
_subscribed = true;
serviceHandler.AddSubscriber( this );
}
public int ToInt32()
{
return timeSpanCount.Value;
}
internal bool CheckTime( long microseconds )
{
if( microseconds - _spanBegin < _spanLength ) {
return true;
}
while( !_tokenToAdd.IsEmpty ) {
_tokenToAdd.TryDequeue( out TimeSpanAwaitingToken tokenAdd );
_awaitingTokens.Add( tokenAdd );
}
while( !_tokenToQuit.IsEmpty ) {
_tokenToQuit.TryDequeue( out TimeSpanAwaitingToken tokenQuit );
_awaitingTokens.Remove( tokenQuit );
InternalIO.InternalWriteLog(
$"Awaiting token {tokenQuit!.TokenID} has been removed.",
LogType.Info );
}
_spanBegin = microseconds;
timeSpanCount++;
foreach( TimeSpanAwaitingToken item in _awaitingTokens ) {
if( item.AwaitingSemaphoreSlim.CurrentCount == 0 ) {
item.AwaitingSemaphoreSlim.Release();
item.Refresh();
} else {
item.MissRefresh();
}
}
return timeSpanCount < _maxSpanCount;
}
public static explicit operator int(
[NotNull]TimeSpanProvider provider )
{
return provider.ToInt32();
}
}
}