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

This commit is contained in:
Nitload
2024-10-03 04:03:06 +08:00
parent 0979123ac0
commit 6e2f93b053
265 changed files with 26732 additions and 19058 deletions
+38 -41
View File
@@ -30,7 +30,6 @@
//-----------------------------------------------------------------------
using StgSharp;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -46,9 +45,8 @@ 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="Blueprint"/> instance in multi threads more than once.
///
/// A sets of complex logic designed for running in multi threads environment. Warning: do not
/// run a <see cref="Blueprint" /> instance in multi threads more than once.
/// </summary>
public partial class Blueprint : IConvertableToBlueprintNode
{
@@ -71,12 +69,13 @@ namespace StgSharp.BluePrint
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);
runningStat = new SemaphoreSlim( 1, 1 );
beginNode = new BeginningNode( this );
endNode = new EndingNode( this );
}
public BlueprintNode BeginLayer => beginNode;
public BlueprintNode EndLayer => endNode;
public bool IsRunning
@@ -97,20 +96,21 @@ namespace StgSharp.BluePrint
}
/**/
public void AddNode(BlueprintNode node, bool isNative)
public void AddNode( BlueprintNode node, bool isNative )
{
_ = node ?? throw new ArgumentNullException(nameof(node));
_ = node ?? throw new ArgumentNullException( nameof( node ) );
node.IsNative = isNative;
allNode.Add(node.Name, node);
allNode.Add( node.Name, node );
}
public void ExecuteMain(in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
public void ExecuteMain(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output )
{
BlueprintRunner.Run(this, () => true);
BlueprintRunner.Run( this, () => true );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public (string name, BlueprintPipelineArgs arg)[] GetOutput()
{
return endNode.OutputData;
@@ -118,52 +118,46 @@ namespace StgSharp.BluePrint
public void Init()
{
foreach (KeyValuePair<string, BlueprintNode> item in allNode)
{
if (item.Value.IsNative)
{
nativeNodeList.Add(item.Value);
}
else
{
globalNodeList.Add(item.Value);
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)
[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);
Interlocked.Exchange( ref currentGlobalNodeIndex, int.MaxValue );
Interlocked.Exchange( ref currentNativeNodeIndex, int.MaxValue );
}
internal bool RequestNexGlobalNode(out BlueprintNode node)
internal bool RequestNexGlobalNode( out BlueprintNode node )
{
if (currentGlobalNodeIndex < globalNodeList.Count)
{
node = globalNodeList[currentGlobalNodeIndex];
Interlocked.Increment(ref currentGlobalNodeIndex);
if( currentGlobalNodeIndex < globalNodeList.Count ) {
node = globalNodeList[ currentGlobalNodeIndex ];
Interlocked.Increment( ref currentGlobalNodeIndex );
return true;
}
node = default!;
return false;
}
internal bool RequestNextNativeNode(out BlueprintNode node)
internal bool RequestNextNativeNode( out BlueprintNode node )
{
if (currentNativeNodeIndex < nativeNodeList.Count)
{
node = nativeNodeList[currentNativeNodeIndex];
Interlocked.Increment(ref currentNativeNodeIndex);
if( currentNativeNodeIndex < nativeNodeList.Count ) {
node = nativeNodeList[ currentNativeNodeIndex ];
Interlocked.Increment( ref currentNativeNodeIndex );
return true;
}
node = default!;
@@ -172,14 +166,17 @@ namespace StgSharp.BluePrint
string[] IConvertableToBlueprintNode.InputInterfacesName
{
get { return beginNode.OutputInterfaces.Select(p => p.Key).ToArray(); }
get { return beginNode.OutputInterfaces
.Select( p => p.Key )
.ToArray(); }
}
string[] IConvertableToBlueprintNode.OutputInterfacesName
{
get { return beginNode.OutputInterfaces.Select(p => p.Key).ToArray(); }
get { return beginNode.OutputInterfaces
.Select( p => p.Key )
.ToArray(); }
}
}
}
@@ -29,7 +29,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
@@ -45,18 +44,17 @@ namespace StgSharp.BluePrint
private string[] outPorts;
private Action<Dictionary<string, BlueprintPipeline>, Dictionary<string, BlueprintPipeline>> mainAction;
internal BlueprintActionNode()
{
}
internal BlueprintActionNode() { }
public string[] InputInterfacesName => inPorts;
public string[] OutputInterfacesName => outPorts;
public void ExecuteMain(in Dictionary<string, BlueprintPipeline> input, in Dictionary<string, BlueprintPipeline> output)
public void ExecuteMain(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output )
{
mainAction?.Invoke(input, output);
mainAction?.Invoke( input, output );
}
}
@@ -29,7 +29,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Entities;
using System;
@@ -44,17 +43,16 @@ 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.
/// 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
#pragma warning restore CA1036
{
private protected bool levelAvailable, nativeRequested;
@@ -64,8 +62,10 @@ namespace StgSharp.BluePrint
private IConvertableToBlueprintNode mainOperation;
private string name;
internal BlueprintNode(string name,
IConvertableToBlueprintNode node, bool isNative)
internal BlueprintNode(
string name,
IConvertableToBlueprintNode node,
bool isNative )
{
this.levelAvailable = false;
this.name = name;
@@ -73,45 +73,39 @@ namespace StgSharp.BluePrint
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.InputInterfacesName ) {
_inputInterfaces.Add( portName, null! );
}
foreach (string portName in node.OutputInterfacesName)
{
_outputInterfaces.Add(portName, null!);
foreach( string portName in node.OutputInterfacesName ) {
_outputInterfaces.Add( portName, null! );
}
}
#pragma warning disable CS8618
internal BlueprintNode(string name, bool isNative,
#pragma warning disable CS8618
internal BlueprintNode(
string name,
bool isNative,
string[] inputPorts,
string[] outputPorts
)
#pragma warning restore CS8618
string[] outputPorts )
#pragma warning restore CS8618
{
if ((inputPorts == null) || (inputPorts.Length == 0))
{
throw new ArgumentNullException(nameof(inputPorts));
if( ( inputPorts == null ) || ( inputPorts.Length == 0 ) ) {
throw new ArgumentNullException( nameof( inputPorts ) );
}
if ((outputPorts == null) || (outputPorts.Length == 0))
{
throw new ArgumentNullException(nameof(outputPorts));
if( ( outputPorts == null ) || ( outputPorts.Length == 0 ) ) {
throw new ArgumentNullException( nameof( outputPorts ) );
}
levelAvailable = false;
this.name = name;
IsNative = isNative;
_inputInterfaces = new Dictionary<string, BlueprintPipeline>();
_outputInterfaces = new Dictionary<string, BlueprintPipeline>();
foreach (string portName in inputPorts)
{
_inputInterfaces.Add(portName, null!);
foreach( string portName in inputPorts ) {
_inputInterfaces.Add( portName, null! );
}
foreach (string portName in outputPorts)
{
_outputInterfaces.Add(portName, null!);
foreach( string portName in outputPorts ) {
_outputInterfaces.Add( portName, null! );
}
}
@@ -125,19 +119,15 @@ namespace StgSharp.BluePrint
{
get
{
if (levelAvailable)
{
if( levelAvailable ) {
return _level;
}
_level = 0;
foreach (KeyValuePair<string, BlueprintPipeline> item in _inputInterfaces)
{
if (item.Value == null)
{
foreach( KeyValuePair<string, BlueprintPipeline> item in _inputInterfaces ) {
if( item.Value == null ) {
continue;
}
if (_level <= item.Value.Level)
{
if( _level <= item.Value.Level ) {
_level = item.Value.Level;
}
}
@@ -149,6 +139,7 @@ namespace StgSharp.BluePrint
public string Name => name;
internal Dictionary<string, BlueprintPipeline> InputInterfaces => _inputInterfaces;
internal Dictionary<string, BlueprintPipeline> OutputInterfaces => _outputInterfaces;
internal IConvertableToBlueprintNode Value
@@ -156,140 +147,124 @@ namespace StgSharp.BluePrint
get => mainOperation;
}
public void AddAfter(
BlueprintNode former,
string formerOutputPortName,
string thisInputPortName)
string thisInputPortName )
{
this.levelAvailable = false;
BlueprintPipeline pipeline = new BlueprintPipeline(former, this);
if (former is BeginningNode bnode)
{
bnode.SetCertainOutputPort(formerOutputPortName, pipeline);
BlueprintPipeline pipeline = new BlueprintPipeline( former, this );
if( former is BeginningNode bnode ) {
bnode.SetCertainOutputPort( formerOutputPortName, pipeline );
} else {
former.SetCertainOutputPort( formerOutputPortName, pipeline );
}
else
{
former.SetCertainOutputPort(formerOutputPortName, pipeline);
}
SetCertainInputPort(thisInputPortName, pipeline);
SetCertainInputPort( thisInputPortName, pipeline );
}
public void AddBefore(
BlueprintNode after,
string thisOutputPortName,
string afterInputPortName)
string afterInputPortName )
{
this.levelAvailable = false;
BlueprintPipeline pipeline = new BlueprintPipeline(this, after);
if (after is EndingNode enode)
{
enode.SetCertainInputPort(afterInputPortName, pipeline);
BlueprintPipeline pipeline = new BlueprintPipeline( this, after );
if( after is EndingNode enode ) {
enode.SetCertainInputPort( afterInputPortName, pipeline );
} else {
after.SetCertainInputPort( afterInputPortName, pipeline );
}
else
{
after.SetCertainInputPort(afterInputPortName, pipeline);
}
SetCertainOutputPort(thisOutputPortName, pipeline);
SetCertainOutputPort( thisOutputPortName, pipeline );
}
public int CompareTo(BlueprintNode other)
public int CompareTo( BlueprintNode other )
{
#pragma warning disable CA1062
return this.Level.CompareTo(other.Level);
#pragma warning restore CA1062
#pragma warning disable CA1062
return this.Level.CompareTo( other.Level );
#pragma warning restore CA1062
}
public virtual void Run()
{
try
{
try {
//Console.WriteLine(name);
BlueprintPipeline.WaitAll(_inputInterfaces);
if (mainOperation != null)
{
mainOperation.ExecuteMain(in _inputInterfaces, in _outputInterfaces);
BlueprintPipeline.WaitAll( _inputInterfaces );
if( mainOperation != null ) {
mainOperation.ExecuteMain(
in _inputInterfaces, in _outputInterfaces );
}
}
catch (Exception)
{
catch( Exception ) {
throw;
}
}
#region port operation
public BlueprintPipeline GetCertainInputPort(string name)
public BlueprintPipeline GetCertainInputPort( string name )
{
BlueprintPipeline ret;
if (!_inputInterfaces.TryGetValue(name, out ret))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
if( !_inputInterfaces.TryGetValue( name, out ret ) ) {
throw new Exception(
$"Cannot find the interface named {name} in node {Name}." );
}
return ret;
}
public BlueprintPipeline GetCertainOutputPort(string name)
public BlueprintPipeline GetCertainOutputPort( string name )
{
BlueprintPipeline ret;
if (!_outputInterfaces.TryGetValue(name, out ret))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
if( !_outputInterfaces.TryGetValue( name, out ret ) ) {
throw new Exception(
$"Cannot find the interface named {name} in node {Name}." );
}
return ret;
}
public void SetCertainInputPort(string name, BlueprintPipeline pipeline)
public void SetCertainInputPort(
string name,
BlueprintPipeline pipeline )
{
if (!_inputInterfaces.ContainsKey(name))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
if( !_inputInterfaces.ContainsKey( name ) ) {
throw new Exception(
$"Cannot find the interface named {name} in node {Name}." );
}
_inputInterfaces[name] = pipeline;
_inputInterfaces[ name ] = pipeline;
}
public void SetCertainOutputPort(string name, BlueprintPipeline pipeline)
public void SetCertainOutputPort(
string name,
BlueprintPipeline pipeline )
{
if (!_outputInterfaces.ContainsKey(name))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
if( !_outputInterfaces.ContainsKey( name ) ) {
throw new Exception(
$"Cannot find the interface named {name} in node {Name}." );
}
_outputInterfaces[name] = pipeline;
_outputInterfaces[ name ] = pipeline;
}
#endregion
}//--------------------------------- end of class -----------------------------------
public class BlueprintNodeRunException : Exception
{
protected BlueprintNodeRunException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
protected BlueprintNodeRunException(
SerializationInfo info,
StreamingContext context )
: base( info, context ) { }
public BlueprintNodeRunException()
{
}
public BlueprintNodeRunException() { }
public BlueprintNodeRunException(Exception ex) : base(string.Empty, ex)
{
}
public BlueprintNodeRunException( Exception ex )
: base( string.Empty, ex ) { }
public BlueprintNodeRunException(string message) : base(message)
{
}
public BlueprintNodeRunException( string message ) : base( message ) { }
public BlueprintNodeRunException(string message, Exception innerException) : base(message, innerException)
{
}
public BlueprintNodeRunException(
string message,
Exception innerException )
: base( message, innerException ) { }
}
}
@@ -28,6 +28,9 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Threading;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -36,9 +39,8 @@ using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using StgSharp.Threading;
using System.Threading.Tasks;
namespace StgSharp.BluePrint
{
@@ -46,33 +48,32 @@ namespace StgSharp.BluePrint
{
private static NodeRunner[] allAvailableTask = new NodeRunner[1];
private static CancellationTokenSource cts = new CancellationTokenSource();
private static ConcurrentStack<Blueprint> blueprintInWaiting = new ConcurrentStack<Blueprint>();
private static CancellationTokenSource cts = new CancellationTokenSource(
);
private static ConcurrentStack<Blueprint> blueprintInWaiting = new ConcurrentStack<Blueprint>(
);
private static int _callingThread;
private static SemaphoreSlim bpLock = new SemaphoreSlim(0, 1);
private static SemaphoreSlim bpLock = new SemaphoreSlim( 0, 1 );
internal static bool IsValidCalling
{
get
{
if ((NodeRunner.CurrentBlueprint == null) || //no bp running at all
((blueprintInWaiting.Count == 0) && (NodeRunner.CurrentBlueprint.IsRunning == false))) // a bp is quiting
if( ( NodeRunner.CurrentBlueprint == null ) || //no bp running at all
( ( blueprintInWaiting.Count == 0 ) && ( NodeRunner.CurrentBlueprint.IsRunning == false ) ) ) // a bp is quiting
{
//in case no bp is running
return true;
}
int? id = Task.CurrentId;
if (id is null)
{
if( id is null ) {
// in case calling from main thread and current running bp
//Console.WriteLine($"\t{_callingThread}");
//Console.WriteLine($"\t{Thread.CurrentThread.ManagedThreadId}");
return _callingThread == Thread.CurrentThread.ManagedThreadId;
}
foreach (NodeRunner item in allAvailableTask)
{
if (item.Id == id)
{
foreach( NodeRunner item in allAvailableTask ) {
if( item.Id == id ) {
//if calling from any bp running task
return true;
}
@@ -81,116 +82,105 @@ namespace StgSharp.BluePrint
}
}
public static void Run(Blueprint blueprint, Func<bool> terminateInstructor)
public static void Run(
Blueprint blueprint,
Func<bool> terminateInstructor )
{
//Console.WriteLine();
if (blueprint == null)
{
if( blueprint == null ) {
return;
}
if (terminateInstructor == null)
{
throw new ArgumentNullException(nameof(terminateInstructor));
if( terminateInstructor == null ) {
throw new ArgumentNullException( nameof( terminateInstructor ) );
}
if (blueprint.IsRunning)
{
throw new InvalidOperationException("Attempt to run a blueprint instance twice.");
if( blueprint.IsRunning ) {
throw new InvalidOperationException(
"Attempt to run a blueprint instance twice." );
}
blueprint.ShouldClose = terminateInstructor;
if (IsValidCalling)
{
if( IsValidCalling ) {
//Console.WriteLine("valid and run");
if (InterruptAndRunNewBp(blueprint))
{
do { } while (InterruptAndRunNewBp(NodeRunner.CurrentBlueprint));
if( InterruptAndRunNewBp( blueprint ) ) {
do { } while (InterruptAndRunNewBp(
NodeRunner.CurrentBlueprint ));
}
}
else
{
} else {
bpLock.Wait();
if (InterruptAndRunNewBp(blueprint))
{
do { } while (InterruptAndRunNewBp(NodeRunner.CurrentBlueprint));
if( InterruptAndRunNewBp( blueprint ) ) {
do { } while (InterruptAndRunNewBp(
NodeRunner.CurrentBlueprint ));
}
bpLock.Release();
}
Interlocked.Exchange(ref _callingThread, -1);
Interlocked.Exchange( ref _callingThread, -1 );
}
public static void SetMaxTaskCount(int size)
public static void SetMaxTaskCount( int size )
{
if (size < 1)
{
if( size < 1 ) {
size = 1;
}
if (allAvailableTask.Length >= size)
{
for (int i = size; i < allAvailableTask.Length; i++)
{
if (allAvailableTask[i] != null)
{
allAvailableTask[i].Cancel();
if( allAvailableTask.Length >= size ) {
for( int i = size; i < allAvailableTask.Length; i++ ) {
if( allAvailableTask[ i ] != null ) {
allAvailableTask[ i ].Cancel();
}
}
}
Array.Resize(ref allAvailableTask, size);
Array.Resize( ref allAvailableTask, size );
}
public static void Terminate()
{
cts.Cancel();
NodeRunner.CurrentBlueprint.Terminate();
foreach (NodeRunner task in allAvailableTask)
{
foreach( NodeRunner task in allAvailableTask ) {
task.Cts.Cancel();
}
foreach (Blueprint bp in blueprintInWaiting)
{
foreach( Blueprint bp in blueprintInWaiting ) {
bp.Terminate();
}
blueprintInWaiting.Clear();
}
internal static bool InterruptAndRunNewBp(Blueprint newBp)
internal static bool InterruptAndRunNewBp( Blueprint newBp )
{
Debug.Assert(newBp != null);
if ((newBp != NodeRunner.CurrentBlueprint) && (NodeRunner.CurrentBlueprint != null))
{
Debug.Assert( newBp != null );
if( ( newBp != NodeRunner.CurrentBlueprint ) && ( NodeRunner.CurrentBlueprint != null ) ) {
//if a running bp exists
blueprintInWaiting.Push(NodeRunner.CurrentBlueprint);
blueprintInWaiting.Push( NodeRunner.CurrentBlueprint );
}
//load new bp to current bp
Interlocked.Exchange(ref NodeRunner.CurrentBlueprint!, newBp);
Interlocked.Exchange(ref _callingThread, Thread.CurrentThread.ManagedThreadId);
Interlocked.Exchange( ref NodeRunner.CurrentBlueprint!, newBp );
Interlocked.Exchange(
ref _callingThread, Thread.CurrentThread.ManagedThreadId );
//run beginning node to init it first.
if (!NodeRunner.CurrentBlueprint.IsRunning)
{
(NodeRunner.CurrentBlueprint.BeginLayer as BeginningNode)!.Run();
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();
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))
{
while( !cts.Token.IsCancellationRequested && NodeRunner.CurrentBlueprint
.RequestNextNativeNode( out node ) ) {
node.Run();
if (!NodeRunner.CurrentBlueprint.IsRunning)
{
if( !NodeRunner.CurrentBlueprint.IsRunning ) {
break;
}
}
(NodeRunner.CurrentBlueprint.EndLayer as EndingNode)!.Run();
return blueprintInWaiting.TryPeek(out NodeRunner.CurrentBlueprint);
( NodeRunner.CurrentBlueprint.EndLayer as EndingNode )!.Run();
return blueprintInWaiting.TryPeek( out NodeRunner.CurrentBlueprint );
}
}
@@ -200,7 +190,8 @@ namespace StgSharp.BluePrint
private static Blueprint _current;
internal NodeRunner() : base()
internal NodeRunner()
: base()
{
_startup = InternalRun;
}
@@ -213,20 +204,20 @@ namespace StgSharp.BluePrint
internal static NodeRunner Run()
{
NodeRunner ret = new NodeRunner { _startup = InternalRun };
ret.taskInternal = Task.Run(ret.InternalAction);
ret._internalTask = Task.Run( ret.InternalAction );
return ret;
}
private static void InternalRun(CancellationToken token)
private static void InternalRun( CancellationToken token )
{
//Console.WriteLine("Task Begin");
BlueprintNode item;
while ((CurrentBlueprint != null) && CurrentBlueprint.IsRunning && !token.IsCancellationRequested
&& CurrentBlueprint.RequestNexGlobalNode(out 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");
}
@@ -34,8 +34,7 @@ using System.Text;
namespace StgSharp.BluePrint
{
[AttributeUsage(AttributeTargets.Method)]
[AttributeUsage( AttributeTargets.Method )]
public sealed class BpNodeActionAttribute : Attribute
{
@@ -43,21 +42,24 @@ namespace StgSharp.BluePrint
private string[] _output;
private int _operationSpan;
public BpNodeActionAttribute(int operationSpan)
public BpNodeActionAttribute( int operationSpan )
{
_input = Array.Empty<string>();
_output = Array.Empty<string>();
_operationSpan = operationSpan;
}
public BpNodeActionAttribute(string[] inputPort, string[] outputPort)
public BpNodeActionAttribute( string[] inputPort, string[] outputPort )
{
_input = inputPort;
_output = outputPort;
this._operationSpan = 1;
}
public BpNodeActionAttribute(string[] inputPort, string[] outputPort, int operationSpan)
public BpNodeActionAttribute(
string[] inputPort,
string[] outputPort,
int operationSpan )
{
_input = inputPort;
_output = outputPort;
@@ -65,7 +67,9 @@ namespace StgSharp.BluePrint
}
public string[] InputPort => _input;
public string[] OutputPort => _output;
public int OperationSpan => _operationSpan;
}
@@ -37,34 +37,39 @@ namespace StgSharp.BluePrint
public static class BpNodeConverter
{
public static IConvertableToBlueprintNode AsBlueprintNodeMainExecution(this BlueprintNodeOperation startUp)
public static IConvertableToBlueprintNode AsBlueprintNodeMainExecution(
this BlueprintNodeOperation startUp )
{
if (startUp == null)
{
throw new ArgumentNullException(nameof(startUp));
if( startUp == null ) {
throw new ArgumentNullException( nameof( startUp ) );
}
object[] attributeArray = startUp.Method.GetCustomAttributes(typeof(BpNodeActionAttribute), false);
BpNodeActionAttribute attri = (BpNodeActionAttribute)attributeArray[0];
if ((attributeArray.Length < 0) || (attri == null))
{
throw new InvalidCastException($"Delegate {nameof(startUp)} is not marked by {typeof(BpNodeActionAttribute)}");
object[] attributeArray = startUp.Method
.GetCustomAttributes( typeof( BpNodeActionAttribute ), false );
BpNodeActionAttribute attri = ( BpNodeActionAttribute )attributeArray[
0 ];
if( ( attributeArray.Length < 0 ) || ( attri == null ) ) {
throw new InvalidCastException(
$"Delegate {nameof(startUp)} is not marked by {typeof(BpNodeActionAttribute)}" );
}
return new DefaultConvertableToBlueprintNode(startUp, attri.InputPort, attri.OutputPort);
return new DefaultConvertableToBlueprintNode(
startUp, attri.InputPort, attri.OutputPort );
}
public static IConvertableToBlueprintNode AsBlueprintNodeMainExecution(this Action startUp)
public static IConvertableToBlueprintNode AsBlueprintNodeMainExecution(
this Action startUp )
{
if (startUp == null)
{
throw new ArgumentNullException(nameof(startUp));
if( startUp == null ) {
throw new ArgumentNullException( nameof( startUp ) );
}
object[] attributeArray = startUp.Method.GetCustomAttributes(typeof(BpNodeActionAttribute), false);
BpNodeActionAttribute attri = (BpNodeActionAttribute)attributeArray[0];
if ((attributeArray.Length < 0) || (attri == null))
{
throw new InvalidCastException($"Delegate {nameof(startUp)} is not marked by {typeof(BpNodeActionAttribute)}");
object[] attributeArray = startUp.Method
.GetCustomAttributes( typeof( BpNodeActionAttribute ), false );
BpNodeActionAttribute attri = ( BpNodeActionAttribute )attributeArray[
0 ];
if( ( attributeArray.Length < 0 ) || ( attri == null ) ) {
throw new InvalidCastException(
$"Delegate {nameof(startUp)} is not marked by {typeof(BpNodeActionAttribute)}" );
}
return new CrossFrameOperation(startUp, attri.OperationSpan);
return new CrossFrameOperation( startUp, attri.OperationSpan );
}
}
@@ -45,34 +45,39 @@ namespace StgSharp.BluePrint
private readonly int cycleCount;
public CrossFrameOperation(Action startup, int cycleCount)
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 > 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; private protected set; }
public Action MainExecution
{
get;
private protected set;
}
public static string InputInterfacesName => "TaskIn";
public static string OutputInterfacesName => "TaskOut";
public void ExecuteMain(in Dictionary<string, BlueprintPipeline> input, in Dictionary<string, BlueprintPipeline> output)
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);
if( currentCount < cycleCount ) {
Interlocked.Increment( ref currentCount );
} else {
Interlocked.Exchange( ref currentCount, 0 );
Task.Run( MainExecution );
}
//Console.WriteLine(currentCount);
BlueprintPipeline.SkipAll(output);
BlueprintPipeline.SkipAll( output );
}
string[] IConvertableToBlueprintNode.InputInterfacesName => [InputInterfacesName];
@@ -35,25 +35,30 @@ using System.Text;
namespace StgSharp.BluePrint
{
public delegate void BlueprintNodeOperation(in Dictionary<string, BlueprintPipeline> input, in Dictionary<string, BlueprintPipeline> output);
public delegate void BlueprintNodeOperation(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output );
public interface IConvertableToBlueprintNode
{
#pragma warning disable CA1819
public string[] InputInterfacesName { get; }
#pragma warning restore CA1819
public string[] InputInterfacesName
{
get;
}
#pragma warning restore CA1819
#pragma warning disable CA1819
public string[] OutputInterfacesName { get; }
#pragma warning restore CA1819
#pragma warning disable CA1819
public string[] OutputInterfacesName
{
get;
}
#pragma warning restore CA1819
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void ExecuteMain(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output);
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output );
}
@@ -64,16 +69,21 @@ namespace StgSharp.BluePrint
private string[] _output;
private BlueprintNodeOperation _execution;
public DefaultConvertableToBlueprintNode(BlueprintNodeOperation execution, string[] input, string[] output)
public DefaultConvertableToBlueprintNode(
BlueprintNodeOperation execution,
string[] input,
string[] output )
{
_input = input;
_output = output;
_execution = execution;
}
void IConvertableToBlueprintNode.ExecuteMain(in Dictionary<string, BlueprintPipeline> input, in Dictionary<string, BlueprintPipeline> output)
void IConvertableToBlueprintNode.ExecuteMain(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output )
{
_execution(in input, in output);
_execution( in input, in output );
}
string[] IConvertableToBlueprintNode.InputInterfacesName => _input;
+23 -26
View File
@@ -40,7 +40,6 @@ using System.Threading.Tasks;
namespace StgSharp.BluePrint
{
public class BlueprintPipeline
{
@@ -49,11 +48,12 @@ namespace StgSharp.BluePrint
private BlueprintPipelineArgs args;
private SemaphoreSlim formerCompleteSemaphore;
public BlueprintPipeline(BlueprintNode former, BlueprintNode after)
public BlueprintPipeline( BlueprintNode former, BlueprintNode after )
{
this.former = former;
this.after = after;
formerCompleteSemaphore = new SemaphoreSlim(initialCount: 0, maxCount: 1);
formerCompleteSemaphore = new SemaphoreSlim(
initialCount: 0, maxCount: 1 );
}
public BlueprintNode After => after;
@@ -68,31 +68,27 @@ namespace StgSharp.BluePrint
public int Level => former.Level;
public static void SkipAll(Dictionary<string, BlueprintPipeline> ports)
public static void SkipAll(
Dictionary<string, BlueprintPipeline> ports )
{
if (ports == null)
{
throw new ArgumentNullException(nameof(ports));
if( ports == null ) {
throw new ArgumentNullException( nameof( ports ) );
}
foreach (KeyValuePair<string, BlueprintPipeline> item in ports)
{
if (item.Value != null)
{
foreach( KeyValuePair<string, BlueprintPipeline> item in ports ) {
if( item.Value != null ) {
item.Value.CompleteAndSkip();
}
}
}
public static void WaitAll(Dictionary<string, BlueprintPipeline> ports)
public static void WaitAll(
Dictionary<string, BlueprintPipeline> ports )
{
if (ports == null)
{
throw new ArgumentNullException(nameof(ports));
if( ports == null ) {
throw new ArgumentNullException( nameof( ports ) );
}
foreach (KeyValuePair<string, BlueprintPipeline> item in ports)
{
if (item.Value != null)
{
foreach( KeyValuePair<string, BlueprintPipeline> item in ports ) {
if( item.Value != null ) {
item.Value.WaitForStart();
}
}
@@ -111,30 +107,31 @@ namespace StgSharp.BluePrint
#region pipline op
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[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)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void CompleteAndWriteData( BlueprintPipelineArgs args )
{
this.args = args;
CompleteAndSkip();
}
#endregion
}
public abstract class BlueprintPipelineArgs
{
public object? Value { get; set; }
public object? Value
{
get;
set;
}
}
}
@@ -42,28 +42,27 @@ namespace StgSharp.BluePrint
private protected Dictionary<string, (BlueprintPipeline pipeline, Func<bool> openingRule)> outputDictionary;
public RouteSwitch(string name, bool isNative, string inputPorts) :
base(name, isNative, [inputPorts], [string.Empty])
public RouteSwitch( string name, bool isNative, string inputPorts )
: base( name, isNative, [inputPorts], [string.Empty] )
{
outputDictionary = new Dictionary<string, (BlueprintPipeline pipeline, Func<bool> openingRule)>();
outputDictionary = new Dictionary<string, (BlueprintPipeline pipeline, Func<bool> openingRule)>(
);
}
public new int Level
{
get
{
if (levelAvailable)
{
if( levelAvailable ) {
return _level;
}
_level = 0;
KeyValuePair<string, BlueprintPipeline> item = _inputInterfaces.First();
if (item.Value == null)
{
KeyValuePair<string, BlueprintPipeline> item = _inputInterfaces.First(
);
if( item.Value == null ) {
throw new InvalidOperationException();
}
if (_level <= item.Value.Level)
{
if( _level <= item.Value.Level ) {
_level = item.Value.Level;
}
return _level;
@@ -73,43 +72,40 @@ namespace StgSharp.BluePrint
public new void AddBefore(
BlueprintNode after,
string thisOutputPortName,
string afterInputPortName)
string afterInputPortName )
{
this.AppendNode(after, afterInputPortName, () => true);
this.AppendNode( after, afterInputPortName, () => true );
}
public void AppendNode(BlueprintNode node, string portName, Func<bool> openningRule)
public void AppendNode(
BlueprintNode node,
string portName,
Func<bool> openningRule )
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
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));
BlueprintPipeline p = new BlueprintPipeline( this, node );
node.InputInterfaces[ portName ] = p;
outputDictionary.Add( indexName, (p, openningRule) );
}
public new void Run()
{
try
{
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);
foreach( KeyValuePair<string, (BlueprintPipeline pipeline, Func<bool> openingRule)> item in outputDictionary ) {
if( item.Value.openingRule() ) {
item.Value.pipeline.CompleteAndWriteData( input.Args );
}
}
}
catch (Exception)
{
catch( Exception ) {
throw;
}
}
}
}
+26 -25
View File
@@ -29,7 +29,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -45,8 +44,8 @@ namespace StgSharp.BluePrint
private Blueprint _bp;
public BeginningNode(Blueprint bp) : base(name: "BeginningNode", true, ["default"], ["default"]
)
public BeginningNode( Blueprint bp )
: base( name: "BeginningNode", true, ["default"], ["default"] )
{
_bp = bp;
}
@@ -55,13 +54,11 @@ namespace StgSharp.BluePrint
{
set
{
if (value == null)
{
if( value == null ) {
return;
}
foreach ((string name, BlueprintPipelineArgs arg) parameter in value)
{
OutputInterfaces[parameter.name].Args = parameter.arg;
foreach( (string name, BlueprintPipelineArgs arg) parameter in value ) {
OutputInterfaces[ parameter.name ].Args = parameter.arg;
}
}
}
@@ -69,16 +66,17 @@ namespace StgSharp.BluePrint
public override void Run()
{
_bp.RunningStat.Wait();
BlueprintPipeline.SkipAll(_outputInterfaces);
BlueprintPipeline.SkipAll( _outputInterfaces );
}
public new void SetCertainOutputPort(string name, BlueprintPipeline pipeline)
public new void SetCertainOutputPort(
string name,
BlueprintPipeline pipeline )
{
if (_outputInterfaces.ContainsKey(name))
{
_outputInterfaces[name] = pipeline;
if( _outputInterfaces.ContainsKey( name ) ) {
_outputInterfaces[ name ] = pipeline;
}
_outputInterfaces.Add(name, pipeline);
_outputInterfaces.Add( name, pipeline );
}
}
@@ -88,32 +86,35 @@ namespace StgSharp.BluePrint
private Blueprint _bp;
public EndingNode(Blueprint bp) : base(name: "EndingNode", true, ["default"], ["default"]
)
public EndingNode( Blueprint bp )
: base( name: "EndingNode", true, ["default"], ["default"] )
{
_bp = bp;
}
internal (string name, BlueprintPipelineArgs arg)[] OutputData
{
get { return InputInterfaces.Select(key => (key.Key, key.Value.Args)).ToArray(); }
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);
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)
public new void SetCertainInputPort(
string name,
BlueprintPipeline pipeline )
{
if (_inputInterfaces.ContainsKey(name))
{
_inputInterfaces[name] = pipeline;
if( _inputInterfaces.ContainsKey( name ) ) {
_inputInterfaces[ name ] = pipeline;
}
_inputInterfaces.Add(name, pipeline);
_inputInterfaces.Add( name, pipeline );
}
}
@@ -49,53 +49,47 @@ namespace StgSharp.Collections
_reverse = new Dictionary<TSecond, TFirst>();
}
public TFirst this[TSecond key]
public TFirst this[ TSecond key ]
{
get
{
if (_reverse.TryGetValue(key,out TFirst value))
{
if( _reverse.TryGetValue( key, out TFirst value ) ) {
return value;
}
throw new ArgumentException($"Cannot find key {key!.ToString()} in dictionary.");
throw new ArgumentException(
$"Cannot find key {key!.ToString()} in dictionary." );
}
set
{
if (_reverse.TryGetValue(key,out TFirst origin))
{
_reverse[key] = value;
_forward.Remove(origin);
if( _reverse.TryGetValue( key, out TFirst origin ) ) {
_reverse[ key ] = value;
_forward.Remove( origin );
} else {
_reverse.Add( key, value );
}
else
{
_reverse.Add(key, value);
}
_forward.Add(value, key);
_forward.Add( value, key );
}
}
public TSecond this[TFirst key]
public TSecond this[ TFirst key ]
{
get
{
if (_forward.TryGetValue(key, out TSecond value))
{
if( _forward.TryGetValue( key, out TSecond value ) ) {
return value;
}
throw new ArgumentException($"Cannot find key {key!.ToString()} in dictionary.");
throw new ArgumentException(
$"Cannot find key {key!.ToString()} in dictionary." );
}
set
{
if (_forward.TryGetValue(key, out TSecond origin))
{
_forward[key] = value;
_reverse.Remove(origin);
if( _forward.TryGetValue( key, out TSecond origin ) ) {
_forward[ key ] = value;
_reverse.Remove( origin );
} else {
_forward.Add( key, value );
}
else
{
_forward.Add(key, value);
}
_reverse.Add(value, key);
_reverse.Add( value, key );
}
}
@@ -107,28 +101,29 @@ namespace StgSharp.Collections
public int Count => _forward.Count;
public IReadOnlyDictionary<TFirst, TSecond> Forward => new ReadOnlyDictionary<TFirst,TSecond>(_forward);
public IReadOnlyDictionary<TFirst, TSecond> Forward => new ReadOnlyDictionary<TFirst, TSecond>(
_forward );
public IReadOnlyDictionary<TSecond, TFirst> Reverse => new ReadOnlyDictionary<TSecond,TFirst>(_reverse);
public IReadOnlyDictionary<TSecond, TFirst> Reverse => new ReadOnlyDictionary<TSecond, TFirst>(
_reverse );
public void Add( KeyValuePair<TFirst, TSecond> item )
{
if (_forward.ContainsKey(item.Key) || _reverse.ContainsKey(item.Value))
{
throw new ArgumentException("Duplicate key or value.");
if( _forward.ContainsKey( item.Key ) || _reverse.ContainsKey(
item.Value ) ) {
throw new ArgumentException( "Duplicate key or value." );
}
_forward.Add(item.Key,item.Value);
_reverse.Add(item.Value, item.Key);
_forward.Add( item.Key, item.Value );
_reverse.Add( item.Value, item.Key );
}
public void Add( TFirst key, TSecond value )
public void Add( TFirst key, TSecond value )
{
if (_forward.ContainsKey(key) || _reverse.ContainsKey(value))
{
throw new ArgumentException("Duplicate key or value.");
if( _forward.ContainsKey( key ) || _reverse.ContainsKey( value ) ) {
throw new ArgumentException( "Duplicate key or value." );
}
_forward.Add(key, value);
_reverse.Add(value, key);
_forward.Add( key, value );
_reverse.Add( value, key );
}
public void Clear()
@@ -139,75 +134,74 @@ namespace StgSharp.Collections
public bool Contains( KeyValuePair<TFirst, TSecond> item )
{
return _forward.Contains(item) && _reverse.TryGetValue(item.Value, out TFirst var) && var!.Equals(item.Key) ;
return _forward.Contains( item ) && _reverse.TryGetValue(
item.Value, out TFirst var ) && var!.Equals( item.Key );
}
public bool Contains(TSecond key)
public bool Contains( TSecond key )
{
return _reverse.ContainsKey(key);
return _reverse.ContainsKey( key );
}
public bool Contains(TFirst key)
public bool Contains( TFirst key )
{
return _forward.ContainsKey(key);
return _forward.ContainsKey( key );
}
public void CopyTo( KeyValuePair<TFirst, TSecond>[] array, int arrayIndex )
public void CopyTo(
KeyValuePair<TFirst, TSecond>[] array,
int arrayIndex )
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
if( array == null ) {
throw new ArgumentNullException( nameof( array ) );
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if( arrayIndex < 0 || arrayIndex > array.Length ) {
throw new ArgumentOutOfRangeException( nameof( arrayIndex ) );
}
if (array.Length - arrayIndex < _forward.Count)
{
throw new ArgumentException("The array is too small to copy the elements.");
if( array.Length - arrayIndex < _forward.Count ) {
throw new ArgumentException(
"The array is too small to copy the elements." );
}
foreach (var pair in _forward)
{
array[arrayIndex ++] = pair;
foreach( KeyValuePair<TFirst, TSecond> pair in _forward ) {
array[ arrayIndex++ ] = pair;
}
}
public IEnumerator<KeyValuePair<TFirst, TSecond>> GetEnumerator()
{
foreach (var pair in _forward)
{
foreach( KeyValuePair<TFirst, TSecond> pair in _forward ) {
yield return pair;
}
}
public bool Remove( TFirst key ) { throw new NotImplementedException(); }
public bool Remove( TFirst key )
{
throw new NotImplementedException();
}
public bool Remove( KeyValuePair<TFirst, TSecond> item )
{
if (_forward.Remove(item.Key))
{
return _reverse.Remove(item.Value);
if( _forward.Remove( item.Key ) ) {
return _reverse.Remove( item.Value );
}
return false;
}
public bool TryGetValue( TFirst key, out TSecond value )
{
return _forward.TryGetValue(key, out value);
return _forward.TryGetValue( key, out value );
}
public bool TryGetValue(TSecond key, out TFirst value)
public bool TryGetValue( TSecond key, out TFirst value )
{
return _reverse.TryGetValue(key, out value);
return _reverse.TryGetValue( key, out value );
}
IEnumerator IEnumerable.GetEnumerator()
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
@@ -1,3 +1,33 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IBidrirectionalDictionary.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;
using System.Collections.Generic;
@@ -5,46 +35,66 @@ using System.Threading.Tasks;
namespace StgSharp.Collections
{
public interface IBidirectionalDictionary<TFirst, TSecond> :
IDictionary<TFirst, TSecond>
public interface IBidirectionalDictionary<TFirst, TSecond> : IDictionary<TFirst, TSecond>
{
#pragma warning disable CA1033
public TFirst this[ TSecond key ]
{
get;
set;
}
public ICollection<TFirst> FirstIndex
{
get;
}
public ICollection<TSecond> SecondIndex
{
get;
}
public IReadOnlyDictionary<TFirst, TSecond> Forward
{
get;
}
public IReadOnlyDictionary<TSecond, TFirst> Reverse
{
get;
}
/// <summary>
/// Determines whether the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains
/// the specified key.
/// </summary>
/// <param name="key"> The value to locate in the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />. </param>
/// <returns>
/// true if the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains an element
/// with the specified key; otherwise, false.
/// </returns>
public bool Contains( TSecond key );
/// <summary>
/// Determines whether the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains
/// the specified key.
/// </summary>
/// <param name="key"> The value to locate in the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />. </param>
/// <returns>
/// true if the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains an element
/// with the specified key; otherwise, false.
/// </returns>
public bool Contains( TFirst key );
public bool TryGetValue( TSecond key, out TFirst value );
#pragma warning disable CA1033
ICollection<TFirst> IDictionary<TFirst, TSecond>.Keys => FirstIndex;
ICollection<TSecond> IDictionary<TFirst, TSecond>.Values => SecondIndex;
bool IDictionary<TFirst, TSecond>.ContainsKey(TFirst key) => Contains(key);
bool IDictionary<TFirst, TSecond>.ContainsKey( TFirst key ) => Contains(
key );
#pragma warning restore CA1033
public IReadOnlyDictionary<TFirst, TSecond> Forward { get; }
public IReadOnlyDictionary<TSecond, TFirst> Reverse { get; }
public ICollection<TFirst> FirstIndex { get;}
public ICollection<TSecond> SecondIndex { get; }
public TFirst this[TSecond key] { get;set; }
/// <summary>
/// Determines whether the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains the
/// specified key.
/// </summary>
/// <param name="key"> The value to locate in the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />. </param>
/// <returns>
/// true if the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains an element with the
/// specified key; otherwise, false.
/// </returns>
public bool Contains(TSecond key);
/// <summary>
/// Determines whether the <see cref="IBidirectionalDictionary{TFirst, TSecond}" /> contains the
/// specified key.
/// </summary>
/// <param name="key"> The value to locate in the <see cref="IBidirectionalDictionary{TFirst, TSecond}" />. </param>
/// <returns>
/// true if the <see cref="IBidirectionalDictionary{TFirst, TSecond}"/> contains an element with the
/// specified key; otherwise, false.
/// </returns>
public bool Contains(TFirst key);
public bool TryGetValue(TSecond key, out TFirst value);
}
}
@@ -42,23 +42,22 @@ namespace StgSharp.Collections
private T[] values;
private int capacity, _index;
public SizeFixedList(int size)
public SizeFixedList( int size )
{
values = new T[size];
}
public T this[int index]
public T this[ int index ]
{
get => (index < _index) ? values[index] : throw new ArgumentOutOfRangeException(nameof(index));
get => ( index < _index ) ?
values[ index ] : throw new ArgumentOutOfRangeException(
nameof( index ) );
set
{
if (index < _index)
{
values[index] = value;
}
else
{
throw new ArgumentOutOfRangeException(nameof(index));
if( index < _index ) {
values[ index ] = value;
} else {
throw new ArgumentOutOfRangeException( nameof( index ) );
}
}
}
@@ -67,12 +66,11 @@ namespace StgSharp.Collections
public int Count => _index + 1;
public void Add(T item)
public void Add( T item )
{
if (_index < capacity - 1)
{
if( _index < capacity - 1 ) {
_index++;
this[_index] = item;
this[ _index ] = item;
}
}
@@ -82,56 +80,43 @@ namespace StgSharp.Collections
_index = 0;
}
public bool Contains(T item)
public bool Contains( T item )
{
for (int i = 0; i <= _index; i++)
{
if (item.Equals(values[i]))
{
for( int i = 0; i <= _index; i++ ) {
if( item.Equals( values[ i ] ) ) {
return true;
}
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
public void CopyTo( T[] array, int arrayIndex )
{
throw new NotImplementedException();
}
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i <= _index; i++)
{
yield return values[i];
for( int i = 0; i <= _index; i++ ) {
yield return values[ i ];
}
}
public int IndexOf(T item)
public int IndexOf( T item )
{
for (int i = 0; i <= _index; i++)
{
if (values[i].Equals(item))
{
for( int i = 0; i <= _index; i++ ) {
if( values[ i ].Equals( item ) ) {
return i;
}
}
return -1;
}
void IList<T>.Insert(int index, T item)
public bool Remove( T item )
{
throw new NotSupportedException();
}
public bool Remove(T item)
{
for (int i = 0; i <= _index; i++)
{
if (values[i].Equals(item))
{
values[i] = values[_index];
for( int i = 0; i <= _index; i++ ) {
if( values[ i ].Equals( item ) ) {
values[ i ] = values[ _index ];
_index--;
return true;
}
@@ -139,30 +124,27 @@ namespace StgSharp.Collections
return false;
}
public void RemoveAll(Predicate<T> predicate)
public void RemoveAll( Predicate<T> predicate )
{
for (int i = _index; i > 0; i--)
{
if (predicate(values[i]))
{
values[i] = values[_index];
for( int i = _index; i > 0; i-- ) {
if( predicate( values[ i ] ) ) {
values[ i ] = values[ _index ];
_index--;
}
}
}
public void RemoveAt(int index)
public void RemoveAt( int index )
{
if (index <= _index)
{
values[index] = values[_index];
if( index <= _index ) {
values[ index ] = values[ _index ];
_index--;
}
}
public void Resize(int newSize)
public void Resize( int newSize )
{
Array.Resize(ref values, newSize);
Array.Resize( ref values, newSize );
}
IEnumerator IEnumerable.GetEnumerator()
@@ -170,5 +152,10 @@ namespace StgSharp.Collections
yield return GetEnumerator();
}
void IList<T>.Insert( int index, T item )
{
throw new NotSupportedException();
}
}//------------------------------------- End of Class ------------------------------------------
}
+14 -14
View File
@@ -33,11 +33,11 @@ using System.Xml.Serialization;
namespace StgSharp
{
public class Counter<T> where T : struct, IConvertible, IFormattable, IComparable
#if NET8_OR_GREATER
public class Counter<T>
where T: struct, IConvertible, IFormattable, IComparable
#if NET8_OR_GREATER
,INumber
#endif
#endif
{
@@ -47,11 +47,10 @@ namespace StgSharp
internal readonly T _defualtSubValue;
internal readonly T _defualtValue;
public Counter(T defualtValue, T defualtAddValue, T defualtSubValue)
public Counter( T defualtValue, T defualtAddValue, T defualtSubValue )
{
TypeCode type = Type.GetTypeCode(defualtValue.GetType());
switch (type)
{
TypeCode type = Type.GetTypeCode( defualtValue.GetType() );
switch( type ) {
case TypeCode.Byte:
break;
@@ -83,7 +82,8 @@ namespace StgSharp
break;
default:
throw new ArgumentException("Input is not number value type");
throw new ArgumentException(
"Input is not number value type" );
break;
}
_value = defualtValue;
@@ -104,7 +104,7 @@ namespace StgSharp
set => _value = value;
}
public void Add(T value)
public void Add( T value )
{
_value += value;
}
@@ -124,7 +124,7 @@ namespace StgSharp
_value = _defualtValue;
}
public void Sub(T value)
public void Sub( T value )
{
_value -= value;
}
@@ -134,19 +134,19 @@ namespace StgSharp
return Value.ToString();
}
public static Counter<T> operator --(Counter<T> counter)
public static Counter<T> operator --( Counter<T> counter )
{
counter.QuickSub();
return counter;
}
public static Counter<T> operator ++(Counter<T> counter)
public static Counter<T> operator ++( Counter<T> counter )
{
counter.QuickAdd();
return counter;
}
public static implicit operator T(Counter<T> counter)
public static implicit operator T( Counter<T> counter )
{
return counter.Value;
}
+9 -5
View File
@@ -32,8 +32,9 @@ using StgSharp.Geometries;
namespace StgSharp
{
public delegate bool SensorRuleHandler(PlainGeometry target, PlainGeometry boarder);
public delegate bool SensorRuleHandler(
PlainGeometry target,
PlainGeometry boarder );
public class Sensor<T>
{
@@ -42,7 +43,6 @@ namespace StgSharp
internal PlainGeometry _target;
internal SensorRuleHandler _rule;
public PlainGeometry boarder => _boarder;
public PlainGeometry target
@@ -57,13 +57,17 @@ namespace StgSharp
set => _rule = value;
}
public static Sensor<T> operator -(Sensor<T> sensor, SensorRuleHandler rule)
public static Sensor<T> operator -(
Sensor<T> sensor,
SensorRuleHandler rule )
{
sensor._rule -= rule;
return sensor;
}
public static Sensor<T> operator +(Sensor<T> sensor, SensorRuleHandler rule)
public static Sensor<T> operator +(
Sensor<T> sensor,
SensorRuleHandler rule )
{
sensor._rule += rule;
return sensor;
+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,122 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="CancellableTask.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Threading
{
internal class CancellableTask
{
private protected Action<CancellationToken> _startup;
private protected Task _internalTask;
private CancellationTokenSource cts;
private protected CancellableTask()
{
cts = new CancellationTokenSource();
}
private protected CancellableTask( Action<CancellationToken> action )
{
_internalTask = new Task( InternalAction );
cts = new CancellationTokenSource();
}
public bool IsCompleted
{
get => _internalTask.IsCompleted;
}
public CancellationTokenSource Cts
{
get => cts;
}
public int Id
{
get => _internalTask.Id;
}
public void Cancel()
{
Cts.Cancel();
}
public void CancelAndWait()
{
Cts.Cancel();
_internalTask.Wait();
}
public static CancellableTask Run( Action<CancellationToken> startup )
{
CancellableTask ret = new CancellableTask { _startup = startup };
ret._internalTask = Task.Run( ret.InternalAction );
return ret;
}
public void Wait()
{
_internalTask.Wait();
}
public static void WaitAll( IEnumerable<CancellableTask> tasks )
{
IEnumerable<Task> convertedTasks = tasks.Select<CancellableTask, Task>(
ct => ct._internalTask );
Task.WaitAll( convertedTasks.ToArray() );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
internal void InternalAction()
{
//Console.WriteLine($"Task {Task.CurrentId} is running.");
_startup( Cts.Token );
}
public static implicit operator Task( CancellableTask task )
{
return task._internalTask;
}
~CancellableTask()
{
Cts.Dispose();
}
}
}
@@ -0,0 +1,62 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="EmptyThread.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Threading
{
public static partial class ThreadHelper
{
private static readonly Thread _emptyThreadCache = new Thread(
() => { } );
static ThreadHelper()
{
_emptyThreadCache.Start();
}
/// <summary>
/// An individual thread doing nothing, and its <see cref="Thread.IsAlive" /> <see
/// langword="property" /> always returns false.
/// </summary>
public static Thread EmptyThread
{
get => _emptyThreadCache;
}
}
}
@@ -0,0 +1,58 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="MainThreadAssert.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Threading
{
public static partial class ThreadHelper
{
private static readonly int mainThreadId = Thread.CurrentThread.ManagedThreadId;
private static readonly ThreadLocal<bool> isNotMainThread = new ThreadLocal<bool>(
() => Thread.CurrentThread.ManagedThreadId != mainThreadId );
[Conditional( "DEBUG" )]
internal static void MainThreadAssert()
{
if( isNotMainThread.Value ) {
throw new InvalidOperationException(
$"Attempt to call sensitive operation which can be only called from main thread " + $"from thread {Thread.CurrentThread.ManagedThreadId}." );
}
}
}
}
@@ -0,0 +1,54 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="frameworkSyncContext.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Graphics
{
public class FrameworkSyncContext : SynchronizationContext
{
private ConcurrentQueue<SendOrPostCallback> _syncContexts = new ConcurrentQueue<SendOrPostCallback>(
);
private readonly Thread _mainThread = Thread.CurrentThread;
public override void Post( SendOrPostCallback d, object state )
{
base.Post( d, state );
}
}
}
+32 -28
View File
@@ -46,12 +46,11 @@ namespace StgSharp.Timing
public TimeFunction(
TimeSpanProvider timeSpanProvider,
Func<float, float> timeRelatedCalculation,
float range)
float range )
{
_timeProvider = timeSpanProvider;
_timeRelatedCalculation = timeRelatedCalculation;
if (timeSpanProvider == null)
{
if( timeSpanProvider == null ) {
return;
}
_beginning = _timeProvider.CurrentSecond;
@@ -82,28 +81,33 @@ namespace StgSharp.Timing
public virtual float Calculate()
{
if (_timeProvider.CurrentSecond < _ending)
{
if( _timeProvider.CurrentSecond < _ending ) {
return 0;
}
return _timeRelatedCalculation(_timeProvider.CurrentSecond - _beginning);
return _timeRelatedCalculation(
_timeProvider.CurrentSecond - _beginning );
}
public static TimeFunction Proportional(TimeSpanProvider time, float begin, float range)
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(
time, (float t) => t + begin, range
);
_timeProvider, funcPair.func, funcPair.range );
}
public virtual TimeFunction Renew((Func<float, float> func, float range) funcPair)
public virtual TimeFunction Renew(
Func<float, float> func,
float range )
{
return new TimeFunction(_timeProvider, funcPair.func, funcPair.range);
}
public virtual TimeFunction Renew(Func<float, float> func, float range)
{
return new TimeFunction(_timeProvider, func, range);
return new TimeFunction( _timeProvider, func, range );
}
public void Reset()
@@ -116,18 +120,17 @@ namespace StgSharp.Timing
public virtual TimeFunction Reverse()
{
float range = _ending - _beginning;
return new TimeFunction(_timeProvider, p => _timeRelatedCalculation(range - p), range);
return new TimeFunction(
_timeProvider, p => _timeRelatedCalculation( range - p ),
range );
}
}
public sealed class TimeFunctionOne : TimeFunction
{
internal TimeFunctionOne() : base()
{
}
internal TimeFunctionOne() : base() { }
public override bool IsComplete
{
@@ -139,22 +142,23 @@ namespace StgSharp.Timing
return 1;
}
public override TimeFunction Renew((Func<float, float> func, float range) funcPair)
public override TimeFunction Renew(
(Func<float, float> func, float range) funcPair )
{
throw new NotSupportedException();
}
public override TimeFunction Renew(Func<float, float> func, float range)
public override TimeFunction Renew(
Func<float, float> func,
float range )
{
throw new NotSupportedException();
}
#pragma warning disable CA1822
#pragma warning disable CA1822
public new void Reset()
#pragma warning restore CA1822
{
}
#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();
}
}
}
}
@@ -39,54 +39,51 @@ namespace StgSharp.Timing
public abstract class TimeSourceProviderBase
{
private SemaphoreSlim _addSubscriberSemaphore = new SemaphoreSlim(1, 1);
private SemaphoreSlim _addSubscriberSemaphore = new SemaphoreSlim(
1, 1 );
protected SemaphoreSlim CheckSubscriberSemaphore
{
get => _addSubscriberSemaphore;
}
public void AddSubscriber(TimeSpanProvider subscriber)
public void AddSubscriber( TimeSpanProvider subscriber )
{
_addSubscriberSemaphore.Wait();
try
{
AddSubscriberUnsynced(subscriber);
try {
_addSubscriberSemaphore.Wait();
AddSubscriberUnsynced( subscriber );
}
catch (Exception)
{
catch( Exception ) {
throw;
}
finally
{
finally {
_addSubscriberSemaphore.Release();
}
}
public void RemoveSubscriber(TimeSpanProvider subscriber)
public void RemoveSubscriber( TimeSpanProvider subscriber )
{
_addSubscriberSemaphore.Wait();
try
{
RemoveSubscriberUnsynced(subscriber);
try {
RemoveSubscriberUnsynced( subscriber );
}
catch (Exception)
{
catch( Exception ) {
throw;
}
finally
{
finally {
_addSubscriberSemaphore.Release();
}
}
public abstract void StartProvidingTime();
public abstract void StopProvidingTime();
protected abstract void AddSubscriberUnsynced(
TimeSpanProvider subscriber );
protected abstract void AddSubscriberUnsynced(TimeSpanProvider subscriber);
protected abstract void RemoveSubscriberUnsynced(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
}
@@ -29,104 +29,110 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
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 Action _frameUpdateMissCallback = () => { };
private Action _refreshCallback;
private bool _subscribed;
private Counter<int> timeSpanCount = new Counter<int>(-1, 1, 1);
private readonly int _maxSpanCount;
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 SemaphoreSlim _refreshSemaphore = new SemaphoreSlim(0, 1);
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.
/// 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)
public TimeSpanProvider(
long spanMicroSeconds,
TimeSourceProviderBase provider )
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
if( provider == null ) {
throw new ArgumentNullException( nameof( provider ) );
}
_timeSource = provider;
_spanLength = spanMicroSeconds;
_maxSpanCount = int.MaxValue;
provider.AddSubscriber(this);
provider.AddSubscriber( this );
_subscribed = true;
_refreshCallback = new Action(() => { });
_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.
/// 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)
public TimeSpanProvider(
double spanSeconds,
TimeSourceProviderBase provider )
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
if( provider == null ) {
throw new ArgumentNullException( nameof( provider ) );
}
_spanLength = (long)(spanSeconds * 1000L * 1000L);
_timeSource = provider;
_spanLength = ( long )( spanSeconds * 1000L * 1000L );
_spanBegin = -_spanLength;
_maxSpanCount = int.MaxValue;
provider.AddSubscriber(this);
_maxSpanCount = long.MaxValue;
provider.AddSubscriber( this );
_subscribed = true;
_refreshCallback = new Action(() => { });
_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.
/// 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, int maxSpan, TimeSourceProviderBase provider)
public TimeSpanProvider(
long spanLength,
long maxSpan,
TimeSourceProviderBase provider )
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
if( provider == null ) {
throw new ArgumentNullException( nameof( provider ) );
}
if (maxSpan <= 0)
{
maxSpan = int.MaxValue;
if( maxSpan <= 0 ) {
throw new ArgumentException(
"Sapn count cannot be smaller than zero" );
}
_spanLength = spanLength; _spanBegin = -_spanLength;
provider.AddSubscriber(this);
_timeSource = provider;
_spanLength = spanLength;
_spanBegin = -_spanLength;
provider.AddSubscriber( this );
_subscribed = true;
}
/// <summary>
/// The method this <see cref="TimeSpanProvider"/> will call every time a new time span started.
/// </summary>
public Action SpanRefreshCallback
{
get => _refreshCallback;
set => _refreshCallback = value;
_awaitingTokens = new HashSet<TimeSpanAwaitingToken>();
_tokenToQuit = new ConcurrentQueue<TimeSpanAwaitingToken>();
}
public double SpanLength
{
get => (_spanLength * 1.0) / (1000L * 1000L);
get => ( _spanLength * 1.0 ) / ( 1000L * 1000L );
}
public float CurrentSecond
@@ -136,7 +142,7 @@ namespace StgSharp.Timing
public float SpanLengthLowPrecession
{
get => (_spanLength * 1.0f) / (1000 * 1000);
get => ( _spanLength * 1.0f ) / ( 1000 * 1000 );
}
public int CurrentSpan
@@ -145,22 +151,39 @@ namespace StgSharp.Timing
}
/// <summary>
/// Time source provider provided in <see cref="StgSharp"/> internal framework.
/// Time source provider provided in <see cref="StgSharp" /> internal framework.
/// </summary>
public static TimeSourceProviderBase DefaultProvider => StgSharpTime.OnlyInstance;
public void SubscribeToTimeSource(TimeSourceProviderBase serviceHandler)
public TimeSpanAwaitingToken ParticipantSpanAwaiting( int count )
{
if (serviceHandler == null)
{
throw new ArgumentNullException(nameof(serviceHandler));
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)
{
if( _subscribed ) {
return;
}
_subscribed = true;
serviceHandler.AddSubscriber(this);
serviceHandler.AddSubscriber( this );
}
public int ToInt32()
@@ -168,49 +191,41 @@ namespace StgSharp.Timing
return timeSpanCount.Value;
}
public void WaitNextSpan()
internal bool CheckTime( long microseconds )
{
_refreshSemaphore.Wait();
}
internal bool CheckTime(long microseconds)
{
//Console.Write("1 ");
if (microseconds - _spanBegin < _spanLength)
{
if( microseconds - _spanBegin < _spanLength ) {
return true;
}
//Console.Write("2 ");
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++;
//Console.Write("3 ");
if (_refreshCallback != null)
{
_refreshCallback();
}
//Console.Write("4 ");
if (_refreshSemaphore.CurrentCount == 0)
{
_refreshSemaphore.Release();
}
else
{
if (_frameUpdateMissCallback != null)
{
_frameUpdateMissCallback();
foreach( TimeSpanAwaitingToken item in _awaitingTokens ) {
if( item.AwaitingSemaphoreSlim.CurrentCount == 0 ) {
item.AwaitingSemaphoreSlim.Release();
item.Refresh();
} else {
item.MissRefresh();
}
}
//Console.Write("5 ");
//Console.WriteLine( $"{timeSpanCount}\n" );
return timeSpanCount < _maxSpanCount;
}
public static implicit operator int(TimeSpanProvider provider)
public static explicit operator int(
[NotNull]TimeSpanProvider provider )
{
if (provider == null)
{
return 0;
}
return provider.ToInt32();
}