daily update on 20240828 by nitload youmu, autotexture added

This commit is contained in:
Nitload
2024-08-28 10:58:31 +08:00
parent d082071f2d
commit 1ee4e4a42f
586 changed files with 60910 additions and 123106 deletions
@@ -29,7 +29,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp;
using StgSharp.Logic;
using System;
using System.Collections.Generic;
@@ -43,35 +43,72 @@ using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace StgSharp.Logic
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.
///
/// </summary>
public partial class Blueprint : IConvertableToBlueprintNode
{
private BeginningNode beginNode;
private Dictionary<string, BlueprintNode> allNode;
private EndingNode endNode;
private Func<bool> terminate;
private int currentNodeIndex;
private List<Task> allThread;
private Func<bool> terminate;
private List<BlueprintNode> globalNodeList;
private List<BlueprintNode> nativeNodeList;
private List<BlueprintNode> nodeList;
private SemaphoreSlim runningStat;
internal int currentGlobalNodeIndex;
internal int currentNativeNodeIndex;
public Blueprint()
{
allNode = new Dictionary<string, BlueprintNode>();
allThread = new List<Task>();
nodeList = new List<BlueprintNode>();
globalNodeList = new List<BlueprintNode>();
nativeNodeList = new List<BlueprintNode>();
terminate = () => true;
beginNode = new BeginningNode();
endNode = new EndingNode();
runningStat = new SemaphoreSlim(1, 1);
beginNode = new BeginningNode(this);
endNode = new EndingNode(this);
}
public BlueprintNode BeginLayer => beginNode;
public BlueprintNode EndLayer => endNode;
public bool IsRunning => allThread.Any(t => t.Status == TaskStatus.Running);
public bool IsRunning
{
get => runningStat.CurrentCount == 0;
}
/**/
internal Func<bool> ShouldClose
{
get => terminate;
set => terminate = value;
}
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, () => true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public (string name, BlueprintPipelineArgs arg)[] GetOutput()
@@ -79,115 +116,21 @@ namespace StgSharp.Logic
return endNode.OutputData;
}
public void Init(int threadCount)
public void Init()
{
if (threadCount > nodeList.Count)
foreach (KeyValuePair<string, BlueprintNode> item in allNode)
{
InternalIO.InternalWriteLog(
"Thread setting error: amount of threads of this blueprint is larger than amount of nodes.", LogType.Warning);
threadCount = nodeList.Count;
}
if (threadCount!=0)
{
foreach (var item in allNode)
if (item.Value.IsNative)
{
if (item.Value.IsNative)
{
nativeNodeList.Add(item.Value);
}
else
{
nodeList.Add(item.Value);
}
nativeNodeList.Add(item.Value);
}
nativeNodeList.Sort();
PrepareTasks(threadCount);
}
else
{
foreach (var item in allNode)
else
{
nodeList.Add(item.Value);
globalNodeList.Add(item.Value);
}
}
nodeList.Sort();
}
public void PrepareTasks(int count)
{
for (int i = 0; i < count; i++)
{
allThread.Add(new Task(IndividualTask));
}
}
private void IndividualTask()
{
do
{
BlueprintNode node;
while (RequestNextNode(out node))
{
node.Run();
}
} while (!terminate());
}
/// <summary>
/// Run all nodes repeatedly until it is instructed to terminate.
/// </summary>
/// <param name="terminateInstructor">Instructor to terminate all tasks. Returns <see langword="true"/> if tasks should terminate</param>
public void RunRepeatedly(Func<bool> terminateInstructor)
{
if (allThread.Count != 0)
{
MultiThreadRun(terminateInstructor);
return;
}
SingleThreadRun(terminateInstructor);
}
private void MultiThreadRun(Func<bool> terminateInstructor)
{
if (terminate != terminateInstructor)
{
terminate = terminateInstructor;
if (allThread.Count != 0)
{
foreach (var t in allThread)
{
t.Start();
}
}
}
beginNode.Run();
foreach (var node in nativeNodeList)
{
node.Run();
}
EndLayer.Run();
}
private void SingleThreadRun(Func<bool> terminateInstructor)
{
beginNode.Run();
foreach (var item in nodeList)
{
item.Run();
}
EndLayer.Run();
}
public void AddNativeNode(BlueprintNode node)
{
node.IsNative = true;
allNode.Add(node.Name, node);
}
public void AddAsyncNode(BlueprintNode node)
{
node.IsNative = false;
allNode.Add(node.Name, node);
nativeNodeList.Sort();
globalNodeList.Sort();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -196,59 +139,47 @@ namespace StgSharp.Logic
beginNode.InputData = parameters;
}
private bool RequestNextNode(out BlueprintNode node)
public void Terminate()
{
if (currentNodeIndex < nodeList.Count)
Interlocked.Exchange(ref currentGlobalNodeIndex, int.MaxValue);
Interlocked.Exchange(ref currentNativeNodeIndex, int.MaxValue);
}
internal bool RequestNexGlobalNode(out BlueprintNode node)
{
if (currentGlobalNodeIndex < globalNodeList.Count)
{
BlueprintNode ret = nodeList[currentNodeIndex];
Interlocked.Increment(ref currentNodeIndex);
node = ret;
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;
}
Interlocked.Exchange(ref currentNodeIndex, 0);
node = default!;
return false;
}
string[] IConvertableToBlueprintNode.InputInterfacesName
{
get
{
return beginNode.OutputInterfaces.Select(
p => p.Key).ToArray();
}
}
BlueprintNodeAction IConvertableToBlueprintNode.MainExecution
{
get
{
return (in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
=>
{
beginNode.Run();
foreach (var node in nativeNodeList)
{
node.Run();
}
endNode.Run();
};
}
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(); }
}
}
internal class NodeClearException : Exception
{
}
}
@@ -0,0 +1,63 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BlueprintActionNode.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.BluePrint
{
public class BlueprintActionNode : IConvertableToBlueprintNode
{
private string[] inPorts;
private string[] outPorts;
private Action<Dictionary<string, BlueprintPipeline>, Dictionary<string, BlueprintPipeline>> mainAction;
internal BlueprintActionNode()
{
}
public string[] InputInterfacesName => inPorts;
public string[] OutputInterfacesName => outPorts;
public void ExecuteMain(in Dictionary<string, BlueprintPipeline> input, in Dictionary<string, BlueprintPipeline> output)
{
mainAction?.Invoke(input, output);
}
}
}
@@ -35,18 +35,15 @@ using StgSharp.Entities;
using System;
using System.Collections.Generic;
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.Logic
namespace StgSharp.BluePrint
{
public delegate void BlueprintNodeAction(
in Dictionary<string, BlueprintPipeline> inpput,
in Dictionary<string, BlueprintPipeline> output);
/// <summary>
///
@@ -59,83 +56,62 @@ namespace StgSharp.Logic
public class BlueprintNode : IComparable<BlueprintNode>
#pragma warning restore CA1036
{
private BlueprintNodeAction mainOperation;
private protected bool levelAvailable, nativeRequested;
private protected int _level;
private string name;
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,
BlueprintNodeAction operation, bool isNative,
string[] inputPorts,
string[] outputPorts)
IConvertableToBlueprintNode node, bool isNative)
{
this.levelAvailable = false;
this.name = name;
nativeRequested = isNative;
mainOperation = operation;
mainOperation = node;
_inputInterfaces = new Dictionary<string, BlueprintPipeline>();
_outputInterfaces = new Dictionary<string, BlueprintPipeline>();
if (inputPorts.Length == 0 )
foreach (string portName in node.InputInterfacesName)
{
throw new ArgumentNullException(nameof(inputPorts));
_inputInterfaces.Add(portName, null!);
}
if (outputPorts.Length == 0)
foreach (string portName in node.OutputInterfacesName)
{
throw new ArgumentNullException(nameof(outputPorts));
}
foreach (var portName in inputPorts)
{
_inputInterfaces.Add(portName, null);
}
foreach (var portName in outputPorts)
{
_outputInterfaces.Add(portName, null);
_outputInterfaces.Add(portName, null!);
}
}
public BlueprintNode(string name, IConvertableToBlueprintNode convertable)
{
this.levelAvailable = false;
this.name = name;
_inputInterfaces = new Dictionary<string, BlueprintPipeline>();
_outputInterfaces = new Dictionary<string, BlueprintPipeline>();
mainOperation = convertable.MainExecution;
foreach (var soket in convertable.InputInterfacesName)
{
_inputInterfaces.Add(soket, null);
}
foreach (var soket in convertable.OutputInterfacesName)
{
_outputInterfaces.Add(soket, null);
}
}
public BlueprintNode(string name,
#pragma warning disable CS8618
internal BlueprintNode(string name, bool isNative,
string[] inputPorts,
string[] outputPorts
)
#pragma warning restore CS8618
{
this.levelAvailable = false;
if ((inputPorts == null) || (inputPorts.Length == 0))
{
throw new ArgumentNullException(nameof(inputPorts));
}
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>();
if (inputPorts.Length * outputPorts.Length == 0)
foreach (string portName in inputPorts)
{
throw new Exception();
_inputInterfaces.Add(portName, null!);
}
foreach (var portName in inputPorts)
foreach (string portName in outputPorts)
{
_inputInterfaces.Add(portName, null);
}
foreach (var portName in outputPorts)
{
_outputInterfaces.Add(portName, null);
_outputInterfaces.Add(portName, null!);
}
}
@@ -154,7 +130,7 @@ namespace StgSharp.Logic
return _level;
}
_level = 0;
foreach (var item in _inputInterfaces)
foreach (KeyValuePair<string, BlueprintPipeline> item in _inputInterfaces)
{
if (item.Value == null)
{
@@ -175,6 +151,11 @@ namespace StgSharp.Logic
internal Dictionary<string, BlueprintPipeline> InputInterfaces => _inputInterfaces;
internal Dictionary<string, BlueprintPipeline> OutputInterfaces => _outputInterfaces;
internal IConvertableToBlueprintNode Value
{
get => mainOperation;
}
public void AddAfter(
BlueprintNode former,
@@ -213,21 +194,6 @@ namespace StgSharp.Logic
SetCertainOutputPort(thisOutputPortName, pipeline);
}
public void Run()
{
try
{
//Console.WriteLine(name);
BlueprintPipeline.WaitAll(_inputInterfaces);
mainOperation(in _inputInterfaces, in _outputInterfaces);
}
catch (Exception)
{
throw;
}
}
public int CompareTo(BlueprintNode other)
{
#pragma warning disable CA1062
@@ -235,12 +201,30 @@ namespace StgSharp.Logic
#pragma warning restore CA1062
}
public virtual void Run()
{
try
{
//Console.WriteLine(name);
BlueprintPipeline.WaitAll(_inputInterfaces);
if (mainOperation != null)
{
mainOperation.ExecuteMain(in _inputInterfaces, in _outputInterfaces);
}
}
catch (Exception)
{
throw;
}
}
#region port operation
public BlueprintPipeline GetCertainInputPort(string name)
{
BlueprintPipeline ret;
if (!_inputInterfaces.TryGetValue(name,out ret))
if (!_inputInterfaces.TryGetValue(name, out ret))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
}
@@ -281,17 +265,15 @@ namespace StgSharp.Logic
}//--------------------------------- end of class -----------------------------------
public interface IConvertableToBlueprintNode
{
public string[] InputInterfacesName { get; }
public BlueprintNodeAction MainExecution { get; }
public string[] OutputInterfacesName { get; }
}
public class BlueprintNodeRunException : Exception
{
protected BlueprintNodeRunException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public BlueprintNodeRunException()
{
}
@@ -308,9 +290,6 @@ namespace StgSharp.Logic
{
}
protected BlueprintNodeRunException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
@@ -0,0 +1,234 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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 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;
using StgSharp.Threading;
namespace StgSharp.BluePrint
{
public static class BlueprintRunner
{
private static NodeRunner[] allAvailableTask = new NodeRunner[1];
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);
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
{
//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
//Console.WriteLine($"\t{_callingThread}");
//Console.WriteLine($"\t{Thread.CurrentThread.ManagedThreadId}");
return _callingThread == Thread.CurrentThread.ManagedThreadId;
}
foreach (NodeRunner item in allAvailableTask)
{
if (item.Id == id)
{
//if calling from any bp running task
return true;
}
}
return false;
}
}
public static void Run(Blueprint blueprint, Func<bool> terminateInstructor)
{
//Console.WriteLine();
if (blueprint == null)
{
return;
}
if (terminateInstructor == null)
{
throw new ArgumentNullException(nameof(terminateInstructor));
}
if (blueprint.IsRunning)
{
throw new InvalidOperationException("Attempt to run a blueprint instance twice.");
}
blueprint.ShouldClose = terminateInstructor;
if (IsValidCalling)
{
//Console.WriteLine("valid and run");
if (InterruptAndRunNewBp(blueprint))
{
do { } while (InterruptAndRunNewBp(NodeRunner.CurrentBlueprint));
}
}
else
{
bpLock.Wait();
if (InterruptAndRunNewBp(blueprint))
{
do { } 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 (Blueprint bp in blueprintInWaiting)
{
bp.Terminate();
}
blueprintInWaiting.Clear();
}
internal static bool InterruptAndRunNewBp(Blueprint 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, Thread.CurrentThread.ManagedThreadId);
//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 Blueprint _current;
internal NodeRunner() : base()
{
_startup = InternalRun;
}
internal static ref Blueprint CurrentBlueprint
{
get => ref _current;
}
internal static NodeRunner Run()
{
NodeRunner ret = new NodeRunner { _startup = InternalRun };
ret.taskInternal = 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,72 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BpNodeActionAttribute.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
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class BpNodeActionAttribute : Attribute
{
private string[] _input;
private string[] _output;
private int _operationSpan;
public BpNodeActionAttribute(int operationSpan)
{
_input = Array.Empty<string>();
_output = Array.Empty<string>();
_operationSpan = operationSpan;
}
public BpNodeActionAttribute(string[] inputPort, string[] outputPort)
{
_input = inputPort;
_output = outputPort;
this._operationSpan = 1;
}
public BpNodeActionAttribute(string[] inputPort, string[] outputPort, int operationSpan)
{
_input = inputPort;
_output = outputPort;
this._operationSpan = operationSpan;
}
public string[] InputPort => _input;
public string[] OutputPort => _output;
public int OperationSpan => _operationSpan;
}
}
@@ -0,0 +1,71 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BpNodeBuilder.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 static class BpNodeConverter
{
public static IConvertableToBlueprintNode AsBlueprintNodeMainExecution(this BlueprintNodeOperation 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)}");
}
return new DefaultConvertableToBlueprintNode(startUp, attri.InputPort, attri.OutputPort);
}
public static IConvertableToBlueprintNode AsBlueprintNodeMainExecution(this Action 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)}");
}
return new CrossFrameOperation(startUp, attri.OperationSpan);
}
}
}
@@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Logic
{
/*
public class CrossCycleProcess:BlueprintNode
{
public CrossCycleProcess(string name, Action operation)
:base()
{
}
}
/**/
}
@@ -0,0 +1,83 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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;
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; 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)
{
if (currentCount < cycleCount)
{
Interlocked.Increment(ref currentCount);
}
else
{
Interlocked.Exchange(ref currentCount, 0);
Task.Run(MainExecution);
}
//Console.WriteLine(currentCount);
BlueprintPipeline.SkipAll(output);
}
string[] IConvertableToBlueprintNode.InputInterfacesName => [InputInterfacesName];
string[] IConvertableToBlueprintNode.OutputInterfacesName => [OutputInterfacesName];
}
}
@@ -0,0 +1,84 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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
{
#pragma warning disable CA1819
public string[] InputInterfacesName { get; }
#pragma warning restore CA1819
#pragma warning disable CA1819
public string[] OutputInterfacesName { get; }
#pragma warning restore CA1819
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ExecuteMain(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output);
}
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;
}
void IConvertableToBlueprintNode.ExecuteMain(in Dictionary<string, BlueprintPipeline> input, in Dictionary<string, BlueprintPipeline> output)
{
_execution(in input, in output);
}
string[] IConvertableToBlueprintNode.InputInterfacesName => _input;
string[] IConvertableToBlueprintNode.OutputInterfacesName => _output;
}
}
@@ -32,12 +32,13 @@ 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.Logic
namespace StgSharp.BluePrint
{
public class BlueprintPipeline
@@ -59,26 +60,13 @@ namespace StgSharp.Logic
public BlueprintNode Former => former;
public int Level => former.Level;
public BlueprintPipelineArgs Args
{
get => args;
set => args = value;
}
public void CompleteAndSkip()
{
//Console.WriteLine($"Complete\t{former.ContextName}\t->\t{after.ContextName}");
formerCompleteSemaphore.Release();
}
public void CompleteAndWriteData(BlueprintPipelineArgs args)
{
this.args = args;
//Console.WriteLine($"Complete\t{former.ContextName}\t->\t{after.ContextName}");
formerCompleteSemaphore.Release();
}
public int Level => former.Level;
public static void SkipAll(Dictionary<string, BlueprintPipeline> ports)
{
@@ -86,9 +74,9 @@ namespace StgSharp.Logic
{
throw new ArgumentNullException(nameof(ports));
}
foreach (var item in ports)
foreach (KeyValuePair<string, BlueprintPipeline> item in ports)
{
if (item.Value!=null)
if (item.Value != null)
{
item.Value.CompleteAndSkip();
}
@@ -101,9 +89,9 @@ namespace StgSharp.Logic
{
throw new ArgumentNullException(nameof(ports));
}
foreach (var item in ports)
foreach (KeyValuePair<string, BlueprintPipeline> item in ports)
{
if (item.Value!=null)
if (item.Value != null)
{
item.Value.WaitForStart();
}
@@ -116,10 +104,36 @@ namespace StgSharp.Logic
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; }
}
@@ -35,14 +35,15 @@ using System.Reflection.Emit;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace StgSharp.Logic
namespace StgSharp.BluePrint
{
public class RouteSwitch : BlueprintNode
{
private protected Dictionary<string, (BlueprintPipeline pipeline, Func<bool> openingRule)> outputDictionary;
public RouteSwitch(string name, string inputPorts) :
base(name, [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)>();
}
@@ -111,72 +112,4 @@ namespace StgSharp.Logic
}
public sealed class RouteHub : BlueprintNode
{
private Dictionary<string, (BlueprintPipeline pipeline, Func<bool> controllingFunc)> inputDictionary;
public RouteHub(string name, string[] inputPorts, string[] outputPorts) : base(name, inputPorts, outputPorts)
{
inputDictionary = new Dictionary<string, (BlueprintPipeline pipeline, Func<bool> controllingFunc)>();
}
public new 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;
}
}
return _level;
}
}
public void PrependNode(BlueprintNode node, string portName, Func<bool> usingRule)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
string indexName = $"{node.Name}.{portName}";
BlueprintPipeline p = new BlueprintPipeline(this, node);
node.InputInterfaces[portName] = p;
inputDictionary.Add(indexName, (p, usingRule));
}
public new void Run()
{
try
{
foreach (KeyValuePair<string, (BlueprintPipeline pipeline, Func<bool> controllingFunc)> item in inputDictionary)
{
item.Value.pipeline.WaitForStart();
if (item.Value.controllingFunc())
{
_outputInterfaces.First().Value.CompleteAndWriteData(item.Value.pipeline.Args);
}
}
}
catch (Exception)
{
throw;
}
}
}
}
@@ -1,20 +1,55 @@
using StgSharp.Logic;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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.Logic
namespace StgSharp.BluePrint
{
internal sealed class BeginningNode : BlueprintNode
{
public BeginningNode() : base(name: "BeginningNode", null,
true, ["default"], ["default"]
private Blueprint _bp;
public BeginningNode(Blueprint bp) : base(name: "BeginningNode", true, ["default"], ["default"]
)
{ }
{
_bp = bp;
}
internal (string name, BlueprintPipelineArgs arg)[] InputData
{
@@ -24,13 +59,19 @@ namespace StgSharp.Logic
{
return;
}
foreach (var parameter in value)
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))
@@ -40,33 +81,30 @@ namespace StgSharp.Logic
_outputInterfaces.Add(name, pipeline);
}
public new void Run()
{
BlueprintPipeline.SkipAll(_outputInterfaces);
}
}
internal sealed class EndingNode : BlueprintNode
{
public EndingNode() : base(name: "EndingNode",
operation: (
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output
) =>
{
},
true, ["default"], ["default"]
private Blueprint _bp;
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);
_bp.RunningStat.Release();
}
public new void SetCertainInputPort(string name, BlueprintPipeline pipeline)
@@ -78,9 +116,5 @@ namespace StgSharp.Logic
_inputInterfaces.Add(name, pipeline);
}
public new void Run()
{
BlueprintPipeline.WaitAll(_inputInterfaces);
}
}
}