Better module loading.

This commit is contained in:
Nitload
2026-03-04 00:51:29 +08:00
parent 7533e15fc7
commit 7e970352ab
21 changed files with 757 additions and 529 deletions
+19 -43
View File
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="SwissTable" // file="SwissTable"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload // AuthorGroup: Nitload Space
// Copyright (c) Nitload. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@@ -28,6 +28,7 @@
using System; using System;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.Arm;
using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics.X86;
@@ -36,7 +37,7 @@ namespace StgSharp.Collections
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
public unsafe partial class SwissTable public sealed unsafe partial class SwissTable
{ {
private const int BucketCount = 1 << EntryMaskWidth; private const int BucketCount = 1 << EntryMaskWidth;
@@ -46,9 +47,7 @@ namespace StgSharp.Collections
private readonly Entry* _entries; private readonly Entry* _entries;
private SwissTable( private SwissTable(Entry* buffer)
Entry* buffer
)
{ {
_entries = buffer; _entries = buffer;
for (int i = 0; i < BucketCount; i++) for (int i = 0; i < BucketCount; i++)
@@ -58,19 +57,13 @@ namespace StgSharp.Collections
} }
} }
public bool TryAddOrSet( public static SwissTable Create()
nint key,
nint value
)
{ {
throw new NotImplementedException(); Entry* buffer = (Entry*)NativeMemory.AlignedAlloc((nuint)Marshal.SizeOf<Entry>(), 16);
return new SwissTable(buffer);
} }
public bool TryAddOrSet( public bool TryAddOrSet(nint key, nint value, out bool isNewKey)
nint key,
ref nint value,
out bool isNewKey
)
{ {
uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key);
short entry = (short)(hash & ((1 << 11) - 1)); short entry = (short)(hash & ((1 << 11) - 1));
@@ -78,10 +71,7 @@ namespace StgSharp.Collections
return IBucketScanner.Current.TrySet(key, hash, bucket, value, out isNewKey); return IBucketScanner.Current.TrySet(key, hash, bucket, value, out isNewKey);
} }
public bool TryGet( public bool TryGet(nint key, out nint value)
nint key,
out nint value
)
{ {
uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key);
short entry = (short)(hash & ((1 << 11) - 1)); short entry = (short)(hash & ((1 << 11) - 1));
@@ -96,10 +86,7 @@ namespace StgSharp.Collections
*/ */
} }
public bool TryRemove( public bool TryRemove(nint key, out nint value)
nint key,
out nint value
)
{ {
uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key); uint hash = BitOperations.Crc32C(0xffff9961, (ulong)key);
short entry = (short)(hash & ((1 << 11) - 1)); short entry = (short)(hash & ((1 << 11) - 1));
@@ -107,6 +94,11 @@ namespace StgSharp.Collections
return IBucketScanner.Current.TryRemove(key, hash, bucket, out value); return IBucketScanner.Current.TryRemove(key, hash, bucket, out value);
} }
~SwissTable()
{
NativeMemory.AlignedFree(_entries);
}
[InlineArray(BucketCount)] [InlineArray(BucketCount)]
private struct Entry private struct Entry
{ {
@@ -129,27 +121,11 @@ namespace StgSharp.Collections
static IBucketScanner Current { get; } = Create(); static IBucketScanner Current { get; } = Create();
bool TryFind( bool TryFind(nint key, uint Hash, Bucket* bucket, out nint value);
nint key,
uint Hash,
Bucket* bucket,
out nint value
);
unsafe bool TryRemove( unsafe bool TryRemove(nint key, uint hash, Bucket* bucket, out nint value);
nint key,
uint hash,
Bucket* bucket,
out nint value
);
bool TrySet( bool TrySet(nint key, uint hash, Bucket* bucket, nint value, out bool isNewKey);
nint key,
uint hash,
Bucket* bucket,
nint value,
out bool isNewKey
);
private static IBucketScanner Create() private static IBucketScanner Create()
{ {
+23 -35
View File
@@ -1,27 +1,30 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="GlobalSetting" // file="GlobalSetting.cs"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload // AuthorGroup: Nitload Space
// Copyright (c) Nitload. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person
// of this software and associated documentation files (the "Software"), to deal // obtaining a copy of this software and associated documentation
// in the Software without restriction, including without limitation the rights // files (the “Software”), to deal in the Software without restriction,
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // including without limitation the rights to use, copy, modify, merge,
// copies of the Software, and to permit persons to whom the Software is // publish, distribute, sublicense, and/or sell copies of the Software,
// furnished to do so, subject to the following conditions: // 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 // The above copyright notice and
// copies or substantial portions of the Software. // 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 // THE SOFTWARE IS PROVIDED “AS IS”,
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// SOFTWARE. // ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -74,21 +77,6 @@ namespace StgSharp
private static int _mainThreadID { get; set; } = -1; private static int _mainThreadID { get; set; } = -1;
/// <summary>
/// CustomizeInit an instance of OpenGL program, This method should be called before any
/// other World api.
/// </summary>
public static void InitGL(int majorVersion, int minorVersion)
{
if (API == default) {
API = GraphicAPI.GL;
}
if (API != GraphicAPI.GL) {
return;
}
GraphicFramework.InternalInitGL(majorVersion, minorVersion);
}
public static class GlobalSetting public static class GlobalSetting
{ {
@@ -99,7 +87,7 @@ namespace StgSharp
get => vsyncActivated; get => vsyncActivated;
set set
{ {
GraphicFramework.glfwSwapInterval(value ? 1 : 0); // GraphicFramework.glfwSwapInterval(value ? 1 : 0);
vsyncActivated = value; vsyncActivated = value;
} }
} }
+214 -16
View File
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="IStaticModule" // file="IStaticModule"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload // AuthorGroup: Nitload Space
// Copyright (c) Nitload. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@@ -31,55 +31,253 @@ using System.Collections.Generic;
namespace StgSharp namespace StgSharp
{ {
/// <summary>
/// Represents a statically activated module that can be registered and initialized as part of
/// the application startup sequence, and gracefully torn down on shutdown.
/// </summary>
public interface IStaticModule public interface IStaticModule
{ {
/// <summary>
/// Gets the display name of this module, used for logging and diagnostics.
/// </summary>
string ModuleName { get; } string ModuleName { get; }
void InitializeModule(); /// <summary>
/// Performs all initialization work for this module using the provided profile.
/// </summary>
/// <param name="profile">
/// The configuration profile supplied at registration time. Use <see
/// cref="IModuleInitializeProfile.Empty" /> if no configuration is required.
/// </param>
void InitializeModule(IModuleInitializeProfile profile);
/// <summary>
/// Releases all resources acquired during <see cref="InitializeModule" />. Implementations should
/// be idempotent: calling this method more than once must not throw.
/// </summary>
void UninitializeModule();
} }
/// <summary>
/// Marker interface for module initialization configuration. Implementations are plain data
/// carriers; no static factory is required.
/// </summary>
public interface IModuleInitializeProfile
{
/// <summary>
/// A shared, allocation-free empty profile for modules that require no configuration.
/// </summary>
static readonly IModuleInitializeProfile Empty = EmptyModuleInitializeProfile.Instance;
private sealed class EmptyModuleInitializeProfile : IModuleInitializeProfile
{
public static readonly EmptyModuleInitializeProfile Instance = new();
private EmptyModuleInitializeProfile() { }
}
}
/// <summary>
/// Pairs an <see cref="IStaticModule" /> with its <see cref="IModuleInitializeProfile" />,
/// ensuring the two are never stored or iterated independently.
/// </summary>
/// <remarks>
/// Using a <see langword="readonly struct" /> avoids the boxing overhead that would occur if
/// the pair were stored as two parallel lists of reference types.
/// </remarks>
public readonly struct ModuleDescriptor
{
/// <summary>
/// Initializes a new <see cref="ModuleDescriptor" /> using <see
/// cref="IModuleInitializeProfile.Empty" /> as the profile.
/// </summary>
public ModuleDescriptor(IStaticModule module) : this(module, IModuleInitializeProfile.Empty) { }
/// <summary>
/// Initializes a new <see cref="ModuleDescriptor" /> with an explicit profile.
/// </summary>
public ModuleDescriptor(IStaticModule module, IModuleInitializeProfile profile)
{
Module = module;
Profile = profile;
}
/// <summary>
/// Gets the configuration profile associated with the module.
/// </summary>
public IModuleInitializeProfile Profile { get; }
/// <summary>
/// Gets the module to be initialized.
/// </summary>
public IStaticModule Module { get; }
/// <summary>
/// Calls <see cref="IStaticModule.InitializeModule" /> with the stored profile.
/// </summary>
public void Initialize()
{
Module.InitializeModule(Profile);
}
/// <summary>
/// Calls <see cref="IStaticModule.UninitializeModule" /> on the stored module.
/// </summary>
public void Uninitialize()
{
Module.UninitializeModule();
}
}
/// <summary>
/// An ordered collection of modules to be initialized during application startup and
/// uninitialized on shutdown. Supports three registration strategies so that the <c>new()</c>
/// generic constraint is never a hard requirement.
/// </summary>
public sealed class ModuleToInitializeCollection : IEnumerable<IStaticModule>, IStaticModule public sealed class ModuleToInitializeCollection : IEnumerable<IStaticModule>, IStaticModule
{ {
private readonly List<IStaticModule> _modules = []; private readonly List<ModuleDescriptor> _descriptors = [];
internal ModuleToInitializeCollection( internal ModuleToInitializeCollection(World.Initializer i)
World.Initializer i
)
{ {
_modules.Add(i); _descriptors.Add(new ModuleDescriptor(i));
} }
// ── IEnumerable<IStaticModule> ───────────────────────────────────────────
/// <inheritdoc />
public IEnumerator<IStaticModule> GetEnumerator() public IEnumerator<IStaticModule> GetEnumerator()
{ {
return ((IEnumerable<IStaticModule>)_modules).GetEnumerator(); foreach (ModuleDescriptor d in _descriptors) {
yield return d.Module;
}
} }
// ── Initialization / Uninitialization ────────────────────────────────────
/// <summary>
/// Initializes all registered modules in the order they were registered. Each module
/// receives the profile that was supplied at registration time.
/// </summary>
public void InitializeModule() public void InitializeModule()
{ {
foreach (IStaticModule module in _modules) { for (int i = 0; i < _descriptors.Count; i++) {
module.InitializeModule(); _descriptors[i].Initialize();
} }
} }
public ModuleToInitializeCollection UseModule<T>() where T : IStaticModule, new() /// <summary>
/// Uninitializes all registered modules in <b> reverse </b> registration order, mirroring
/// the typical LIFO teardown convention (e.g., GLFW must be unloaded after all subsystems
/// that depend on it).
/// </summary>
public void UninitializeModule()
{ {
_modules.Add(new T()); for (int i = _descriptors.Count - 1; i >= 0; i--) {
_descriptors[i].Uninitialize();
}
}
// ── Registration API ─────────────────────────────────────────────────────
/// <summary>
/// Registers a module of type <typeparamref name="T" /> using its default constructor.
/// This is the most concise overload for simple modules that expose a public
/// parameterless constructor.
/// </summary>
/// <typeparam name="T">
/// A concrete module type that implements <see cref="IStaticModule" /> and exposes a
/// public parameterless constructor.
/// </typeparam>
/// <param name="profile">
/// Optional initialization profile. Defaults to <see
/// cref="IModuleInitializeProfile.Empty" /> when <see langword="null" />.
/// </param>
public ModuleToInitializeCollection UseModule<T>(IModuleInitializeProfile? profile = null)
where T: IStaticModule, new()
{
return UseModule(static() => new T(), profile);
}
/// <summary>
/// Registers a module produced by a factory delegate. This overload imposes no generic
/// constraints and supports any construction strategy, including dependency injection and
/// parameterized constructors.
/// </summary>
/// <param name="factory">
/// A delegate that constructs and returns the module instance. The delegate is invoked
/// once, immediately at registration time. If <paramref name="factory" /> is <see
/// langword="null" /> or returns <see langword="null" />, the call is silently ignored
/// and the collection is returned unchanged.
/// </param>
/// <param name="profile">
/// Optional initialization profile. Defaults to <see
/// cref="IModuleInitializeProfile.Empty" /> when <see langword="null" />.
/// </param>
public ModuleToInitializeCollection UseModule(
Func<IStaticModule> factory,
IModuleInitializeProfile? profile = null)
{
if (factory is null) {
return this;
}
IStaticModule? mod = factory();
if (mod is null) {
return this;
}
_descriptors.Add(new ModuleDescriptor(
mod,
profile ?? IModuleInitializeProfile.Empty));
return this; return this;
} }
/// <summary>
/// Registers a pre-existing module instance. Use this overload when the module is
/// provided externally, such as from a DI container, an object pool, or a singleton.
/// </summary>
/// <param name="module">
/// The module instance to register.
/// </param>
/// <param name="profile">
/// Optional initialization profile. Defaults to <see
/// cref="IModuleInitializeProfile.Empty" /> when <see langword="null" />.
/// </param>
public ModuleToInitializeCollection UseModule(IStaticModule module, IModuleInitializeProfile? profile = null)
{
_descriptors.Add(new ModuleDescriptor(
module,
profile ?? IModuleInitializeProfile.Empty));
return this;
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() IEnumerator IEnumerable.GetEnumerator()
{ {
return ((IEnumerable)_modules).GetEnumerator(); return GetEnumerator();
} }
void IStaticModule.InitializeModule() // ── IStaticModule explicit implementation ────────────────────────────────
/// <summary>
/// Explicit <see cref="IStaticModule" /> implementation. Delegates to <see
/// cref="InitializeModule()" />, ignoring the supplied profile because each contained module uses
/// its own registered profile.
/// </summary>
void IStaticModule.InitializeModule(IModuleInitializeProfile profile)
{ {
throw new NotImplementedException(); InitializeModule();
} }
/// <inheritdoc />
string IStaticModule.ModuleName => "Module Initializer"; string IStaticModule.ModuleName => "Module Initializer";
} }
+2 -28
View File
@@ -58,29 +58,6 @@ namespace StgSharp
private static uint markCount = 0; private static uint markCount = 0;
internal static GraphicAPI API = default; internal static GraphicAPI API = default;
public static unsafe int DefaultSIMDAlignment
{
get
{
SIMDID id = NativeIntrinsic.IntrinsicMask;
switch (id.MaskByte[0] & 0b_00001111)
{
case 1:
return id.MaskByte[1] switch
{
1 => 16,
2 => 32,
3 => 64,
4 => 64,
5 => 64,
_ => 8,
};
default:
return 8;
}
}
}
public static ModuleToInitializeCollection Initialize() public static ModuleToInitializeCollection Initialize()
{ {
return new ModuleToInitializeCollection(new Initializer()); return new ModuleToInitializeCollection(new Initializer());
@@ -122,7 +99,8 @@ namespace StgSharp
public static void Terminate(int exitCode) public static void Terminate(int exitCode)
{ {
MainTimeProvider.StopProvidingTime(); MainTimeProvider.StopProvidingTime();
GraphicFramework.glfwTerminate();
// GraphicFramework.glfwTerminate();
Environment.Exit(exitCode); Environment.Exit(exitCode);
} }
@@ -204,10 +182,6 @@ namespace StgSharp
{ {
// Initialize time provider and start providing time // Initialize time provider and start providing time
MainTimeProvider.StartProvidingTime(); MainTimeProvider.StartProvidingTime();
GraphicFramework.LoadGlfw();
if (GraphicFramework.glfwInit() == 0) {
throw new Exception("Failed to init system graphic environment.");
}
DefaultLog.InternalAppendLog("\n\n\n"); DefaultLog.InternalAppendLog("\n\n\n");
DefaultLog.InternalWriteLog( DefaultLog.InternalWriteLog(
$"Program {Assembly.GetEntryAssembly()!.FullName} on {Environment.MachineName} Started.", LogType.Info); $"Program {Assembly.GetEntryAssembly()!.FullName} on {Environment.MachineName} Started.", LogType.Info);
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="PipelineScheduler" // file="PipelineScheduler"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload // AuthorGroup: Nitload Space
// Copyright (c) Nitload. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@@ -25,8 +25,6 @@
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Stg;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Monitors" // file="Monitor"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload // AuthorGroup: Nitload Space
// Copyright (c) Nitload. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@@ -26,32 +26,34 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp namespace StgSharp.Graphics
{ {
public static partial class World public static class GraphicsEnvironment
{ {
public static unsafe IntPtr[] MonitorsHandleArray private static IntPtr[] _monitorsHandleArray;
public static unsafe ReadOnlySpan<IntPtr> MonitorsHandleArray
{ {
get get
{ {
if (MonitorsArray == null) if (_monitorsHandleArray == null)
{ {
int count = 0; int count = 0;
IntPtr* arrayHandle = GraphicFramework.glfwGetMonitors(&count); IntPtr* arrayHandle = GraphicFramework.glfwGetMonitors(&count);
MonitorsArray = new IntPtr[count]; _monitorsHandleArray = new IntPtr[count];
Marshal.Copy((IntPtr)arrayHandle, MonitorsArray, 0, count); Marshal.Copy((IntPtr)arrayHandle, _monitorsHandleArray, 0, count);
Marshal.FreeHGlobal((IntPtr)arrayHandle); Marshal.FreeHGlobal((IntPtr)arrayHandle);
} }
return MonitorsArray; return _monitorsHandleArray;
} }
} }
public static nint[] MonitorsArray { get; set; } = [];
public static IntPtr DefaultMonitor => MonitorsHandleArray[0];
} }
} }
+58
View File
@@ -0,0 +1,58 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="GraphicInitializer"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
using StgSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics
{
public class GraphicModuel : IStaticModule
{
public string ModuleName => "Graphics";
public void InitializeModule(IModuleInitializeProfile profile)
{
GraphicFramework.LoadGlfw();
if (GraphicFramework.glfwInit() == 0) {
throw new Exception("Failed to init system graphic environment.");
}
}
public void UninitializeModule()
{
GraphicFramework.glfwTerminate();
}
}
}
+3 -2
View File
@@ -26,6 +26,7 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Internal; using StgSharp.Internal;
using StgSharp.Mathematics.Internal;
using System; using System;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
@@ -92,7 +93,7 @@ namespace StgSharp.Mathematics
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int KernelSideCount<T>() where T: unmanaged, INumber<T> internal static int KernelSideCount<T>() where T: unmanaged, INumber<T>
{ {
SIMDID id = NativeIntrinsic.IntrinsicMask; SIMDID id = MathematicsModule.IntrinsicMask;
switch (id.MaskByte[0] & 0b_00001111) switch (id.MaskByte[0] & 0b_00001111)
{ {
case 1: case 1:
@@ -147,7 +148,7 @@ namespace StgSharp.Mathematics
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int PanelSideLength<T>() where T: unmanaged, INumber<T> private static int PanelSideLength<T>() where T: unmanaged, INumber<T>
{ {
SIMDID id = NativeIntrinsic.IntrinsicMask; SIMDID id = MathematicsModule.IntrinsicMask;
switch (id.MaskByte[0] & 0b_00001111) switch (id.MaskByte[0] & 0b_00001111)
{ {
case 1: case 1:
+19 -22
View File
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="UnsafeCompute.cs" // file="UnsafeCompute"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
// //
// Permission is hereby granted, free of charge, to any person // Permission is hereby granted, free of charge, to any person obtaining a copy
// obtaining a copy of this software and associated documentation // of this software and associated documentation files (the "Software"), to deal
// files (the “Software”), to deal in the Software without restriction, // in the Software without restriction, including without limitation the rights
// including without limitation the rights to use, copy, modify, merge, // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// publish, distribute, sublicense, and/or sell copies of the Software, // copies of the Software, and to permit persons to whom the Software is
// and to permit persons to whom the Software is furnished to do so, // furnished to do so, subject to the following conditions:
// subject to the following conditions:
// //
// The above copyright notice and // The above copyright notice and this permission notice shall be included in all
// this permission notice shall be included in all copies // copies or substantial portions of the Software.
// or substantial portions of the Software.
// //
// THE SOFTWARE IS PROVIDED “AS IS”, // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// ARISING FROM, OUT OF OR IN CONNECTION WITH // SOFTWARE.
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -38,19 +35,19 @@ namespace StgSharp.Mathematics.Internal
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int CityHashSimplify(char* span, int length) public static unsafe int CityHashSimplify(char* span, int length)
{ {
return NativeIntrinsic.Context.city_hash_simplify(span, length); return MathematicsModule.GlobalContext.city_hash_simplify(span, length);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int CityHashSimplify(char* span, int begin, int length) public static unsafe int CityHashSimplify(char* span, int begin, int length)
{ {
return NativeIntrinsic.Context.city_hash_simplify(span + begin, length); return MathematicsModule.GlobalContext.city_hash_simplify(span + begin, length);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int IndexOfCharPair(char* source, int pairValue, int length) public static unsafe int IndexOfCharPair(char* source, int pairValue, int length)
{ {
return NativeIntrinsic.Context.index_pair(source, pairValue, length); return MathematicsModule.GlobalContext.index_pair(source, pairValue, length);
} }
} }
@@ -1,6 +1,6 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="intrinsicContextProvider" // file="Moduel"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
@@ -26,54 +26,55 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Mathematics.Internal; using StgSharp.Mathematics.Internal;
using System; using System;
using System.Reflection; using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Mathematics.Internal namespace StgSharp.Mathematics
{ {
internal static unsafe partial class NativeIntrinsic public class MathematicsModule : IStaticModule
{ {
private static readonly IntrinsicContext _intrinsicContext = new(); public static unsafe int DefaultSIMDAlignment
{
get
{
SIMDID id = GlobalIntrinsicMask;
switch (id.MaskByte[0] & 0b_00001111)
{
case 1:
return id.MaskByte[1] switch
{
1 => 16,
2 => 32,
3 => 64,
4 => 64,
5 => 64,
_ => 8,
};
default:
return 8;
}
}
}
public static SIMDID IntrinsicMask { get; set; } public string ModuleName => "Mathematics";
internal static IntrinsicContext Context internal static IntrinsicContext GlobalContext
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _intrinsicContext; get;
} = new();
internal static SIMDID GlobalIntrinsicMask { get; set; }
public void InitializeModule()
{
throw new NotImplementedException();
} }
/*
internal static void InitIntrinsicContext()
{
ulong statCode = 0;
fixed (IntrinsicContext* cPtr = &_intrinsicContext) {
statCode = LoadIntrinsicFunction(cPtr);
}
SIMDID id = new()
{
Mask = statCode
};
switch (id.MaskByte[1])
{
case 0:
Dialogue.PostError(new PlatformNotSupportedException("No SIMD instructions supported on current hardware platform"));
Environment.Exit(-1);
break;
default:
break;
}
IntrinsicMask = id;
}
[LibraryImport(Native.LibName, EntryPoint = "load_intrinsic_function")]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
private static partial void LoadIntrinsicFunction(IntrinsicContext* context, ulong id);
/**/
} }
} }
@@ -167,7 +167,7 @@ namespace StgSharp.Mathematics.Graphics
{ {
const int f32 = 0; const int f32 = 0;
fixed (MatrixKernel<float>* source = &this.kernel, target = &transpose.kernel) { fixed (MatrixKernel<float>* source = &this.kernel, target = &transpose.kernel) {
NativeIntrinsic.Context.mat[f32].buffer_transpose(source, target); MathematicsModule.GlobalContext.mat[f32].buffer_transpose(source, target);
} }
} }
@@ -176,7 +176,7 @@ namespace StgSharp.Mathematics.Graphics
{ {
Matrix44 ret = new(); Matrix44 ret = new();
const int f32 = 0; const int f32 = 0;
NativeIntrinsic.Context.mat[f32].buffer_sub(&left, &right, &ret, 1); MathematicsModule.GlobalContext.mat[f32].buffer_sub(&left, &right, &ret, 1);
return ret; return ret;
} }
@@ -197,7 +197,7 @@ namespace StgSharp.Mathematics.Graphics
{ {
Matrix44 ret = new(); Matrix44 ret = new();
int f32 = (int)MatrixElementType.F32; int f32 = (int)MatrixElementType.F32;
NativeIntrinsic.Context.mat[f32].kernel_fma(&left, &right, &ret); MathematicsModule.GlobalContext.mat[f32].kernel_fma(&left, &right, &ret);
return ret; return ret;
} }
@@ -206,7 +206,7 @@ namespace StgSharp.Mathematics.Graphics
{ {
Matrix44 ret = new(); Matrix44 ret = new();
const int f32 = 0; const int f32 = 0;
NativeIntrinsic.Context.mat[f32].buffer_add(&left, &right, &ret, 1); MathematicsModule.GlobalContext.mat[f32].buffer_add(&left, &right, &ret, 1);
return ret; return ret;
} }
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixCompute.Factorize" // file="MatrixCompute.Factorize"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload // AuthorGroup: Nitload Space
// Copyright (c) Nitload. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@@ -41,8 +41,7 @@ namespace StgSharp.Mathematics.Numeric
Matrix<float> matrix, Matrix<float> matrix,
Span<int> pivot, Span<int> pivot,
Matrix<float> lower, Matrix<float> lower,
Matrix<float> upper Matrix<float> upper)
)
{ {
if (matrix.ColumnLength != matrix.RowLength) { if (matrix.ColumnLength != matrix.RowLength) {
throw new InvalidOperationException("Matrix must be square."); throw new InvalidOperationException("Matrix must be square.");
@@ -54,14 +53,10 @@ namespace StgSharp.Mathematics.Numeric
if (pivot.Length < n) { if (pivot.Length < n) {
throw new ArgumentException("Pivot span length is insufficient.", nameof(pivot)); throw new ArgumentException("Pivot span length is insufficient.", nameof(pivot));
} }
if (lower.RowLength != n || if (lower.RowLength != n || lower.ColumnLength != n || lower.Layout != MatrixLayout.UpperTriangle) {
lower.ColumnLength != n ||
lower.Layout != MatrixLayout.UpperTriangle) {
throw new ArgumentException("Lower matrix must be lower-triangular with same dimensions as input.", nameof(lower)); throw new ArgumentException("Lower matrix must be lower-triangular with same dimensions as input.", nameof(lower));
} }
if (upper.RowLength != n || if (upper.RowLength != n || upper.ColumnLength != n || upper.Layout != MatrixLayout.UpperTriangle) {
upper.ColumnLength != n ||
upper.Layout != MatrixLayout.UpperTriangle) {
throw new ArgumentException("Upper matrix must be upper-triangular with same dimensions as input.", nameof(upper)); throw new ArgumentException("Upper matrix must be upper-triangular with same dimensions as input.", nameof(upper));
} }
@@ -77,9 +72,8 @@ namespace StgSharp.Mathematics.Numeric
ulong* pivots = stackalloc ulong[4]; ulong* pivots = stackalloc ulong[4];
for (int kBlock = 0; kBlock < n; kBlock += 4) for (int kBlock = 0; kBlock < n; kBlock += 4)
{ {
NativeIntrinsic.Context MathematicsModule.GlobalContext
.mat[(int)MatrixElementType.F32].pivot(matrix.Buffer, .mat[(int)MatrixElementType.F32].pivot(matrix.Buffer, (ulong)(kBlock >> 2),
(ulong)(kBlock >> 2),
(ulong)(matrix.KernelRowLength - (kBlock >> 2)), (ulong)(matrix.KernelRowLength - (kBlock >> 2)),
(ulong)pivots); (ulong)pivots);
int colsInBlock = Math.Min(4, n - kBlock); int colsInBlock = Math.Min(4, n - kBlock);
@@ -57,7 +57,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<float>* leftPtr = left.Buffer; MatrixKernel<float>* leftPtr = left.Buffer;
MatrixKernel<float>* rightPtr = right.Buffer; MatrixKernel<float>* rightPtr = right.Buffer;
MatrixKernel<float>* ansPtr = ans.Buffer; MatrixKernel<float>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f32].buffer_add(leftPtr, rightPtr, ansPtr, count); MathematicsModule.GlobalContext.mat[f32].buffer_add(leftPtr, rightPtr, ansPtr, count);
return; return;
} else if (count <= 1024) } else if (count <= 1024)
@@ -67,7 +67,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<float>* leftPtr = left.Buffer; MatrixKernel<float>* leftPtr = left.Buffer;
MatrixKernel<float>* rightPtr = right.Buffer; MatrixKernel<float>* rightPtr = right.Buffer;
MatrixKernel<float>* ansPtr = ans.Buffer; MatrixKernel<float>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f32].buffer_add(leftPtr, rightPtr, ansPtr, count); MathematicsModule.GlobalContext.mat[f32].buffer_add(leftPtr, rightPtr, ansPtr, count);
MatrixParallel.ReturnParallelResources(ref pool); MatrixParallel.ReturnParallelResources(ref pool);
return; return;
@@ -80,7 +80,7 @@ namespace StgSharp.Mathematics.Numeric
package->PrimCount = ans.KernelColumnLength; package->PrimCount = ans.KernelColumnLength;
package->SecCount = ans.KernelRowLength; package->SecCount = ans.KernelRowLength;
package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM); package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM);
package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f32].buffer_add; package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f32].buffer_add;
MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package);
taskGroup.LaunchParallel(SleepMode.DeepSleep); taskGroup.LaunchParallel(SleepMode.DeepSleep);
@@ -96,12 +96,12 @@ namespace StgSharp.Mathematics.Numeric
scalar->Data<float>(0) = value; scalar->Data<float>(0) = value;
if (count <= 256) if (count <= 256)
{ {
NativeIntrinsic.Context.mat[f32].buffer_fill(ans.Buffer, scalar, count); MathematicsModule.GlobalContext.mat[f32].buffer_fill(ans.Buffer, scalar, count);
return; return;
} else if (count <= 1024) } else if (count <= 1024)
{ {
MatrixParallelThread[] pool = MatrixParallel.LeadParallel(1); MatrixParallelThread[] pool = MatrixParallel.LeadParallel(1);
NativeIntrinsic.Context.mat[f32].buffer_fill(ans.Buffer, scalar, count); MathematicsModule.GlobalContext.mat[f32].buffer_fill(ans.Buffer, scalar, count);
MatrixParallel.ReturnParallelResources(ref pool); MatrixParallel.ReturnParallelResources(ref pool);
return; return;
} }
@@ -111,7 +111,7 @@ namespace StgSharp.Mathematics.Numeric
package->PrimCount = ans.KernelColumnLength; package->PrimCount = ans.KernelColumnLength;
package->SecCount = ans.KernelRowLength; package->SecCount = ans.KernelRowLength;
package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.ANS_SCALAR_PARAM); package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.ANS_SCALAR_PARAM);
package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f32].buffer_fill; package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f32].buffer_fill;
package->Scalar = scalar; package->Scalar = scalar;
MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package);
taskGroup.LaunchParallel(SleepMode.DeepSleep); taskGroup.LaunchParallel(SleepMode.DeepSleep);
@@ -154,7 +154,7 @@ namespace StgSharp.Mathematics.Numeric
enumeration->Member<int>(0) = i; enumeration->Member<int>(0) = i;
enumeration->Member<int>(1) = j; enumeration->Member<int>(1) = j;
NativeIntrinsic.Context MathematicsModule.GlobalContext
.mat[f32].kernel_tile_fma((MatrixKernel*)left.Buffer, .mat[f32].kernel_tile_fma((MatrixKernel*)left.Buffer,
(MatrixKernel*)right.Buffer, (MatrixKernel*)right.Buffer,
(MatrixKernel*)ans.Buffer, enumeration); (MatrixKernel*)ans.Buffer, enumeration);
@@ -200,7 +200,7 @@ namespace StgSharp.Mathematics.Numeric
{ {
MatrixKernel<float>* leftPtr = left.Buffer; MatrixKernel<float>* leftPtr = left.Buffer;
MatrixKernel<float>* ansPtr = ans.Buffer; MatrixKernel<float>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f32].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); MathematicsModule.GlobalContext.mat[f32].buffer_scalar_mul(leftPtr, ansPtr, scalar, count);
return; return;
} else if (count <= 1024) } else if (count <= 1024)
@@ -209,7 +209,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<float>* leftPtr = left.Buffer; MatrixKernel<float>* leftPtr = left.Buffer;
MatrixKernel<float>* ansPtr = ans.Buffer; MatrixKernel<float>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f32].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); MathematicsModule.GlobalContext.mat[f32].buffer_scalar_mul(leftPtr, ansPtr, scalar, count);
MatrixParallel.ReturnParallelResources(ref pool); MatrixParallel.ReturnParallelResources(ref pool);
return; return;
@@ -222,7 +222,7 @@ namespace StgSharp.Mathematics.Numeric
package->SecCount = left.KernelRowLength; package->SecCount = left.KernelRowLength;
package->Scalar = scalar; package->Scalar = scalar;
package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.RIGHT_ANS_SCALAR_PARAM); package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.RIGHT_ANS_SCALAR_PARAM);
package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f32].buffer_scalar_mul; package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f32].buffer_scalar_mul;
MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package);
taskGroup.LaunchParallel(SleepMode.DeepSleep); taskGroup.LaunchParallel(SleepMode.DeepSleep);
@@ -251,7 +251,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<float>* leftPtr = left.Buffer; MatrixKernel<float>* leftPtr = left.Buffer;
MatrixKernel<float>* rightPtr = right.Buffer; MatrixKernel<float>* rightPtr = right.Buffer;
MatrixKernel<float>* ansPtr = ans.Buffer; MatrixKernel<float>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f32].buffer_sub(leftPtr, rightPtr, ansPtr, count); MathematicsModule.GlobalContext.mat[f32].buffer_sub(leftPtr, rightPtr, ansPtr, count);
return; return;
} else if (count <= 1024) } else if (count <= 1024)
@@ -261,7 +261,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<float>* leftPtr = left.Buffer; MatrixKernel<float>* leftPtr = left.Buffer;
MatrixKernel<float>* rightPtr = right.Buffer; MatrixKernel<float>* rightPtr = right.Buffer;
MatrixKernel<float>* ansPtr = ans.Buffer; MatrixKernel<float>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f32].buffer_sub(leftPtr, rightPtr, ansPtr, count); MathematicsModule.GlobalContext.mat[f32].buffer_sub(leftPtr, rightPtr, ansPtr, count);
MatrixParallel.ReturnParallelResources(ref pool); MatrixParallel.ReturnParallelResources(ref pool);
return; return;
@@ -274,7 +274,7 @@ namespace StgSharp.Mathematics.Numeric
package->PrimCount = left.KernelColumnLength; package->PrimCount = left.KernelColumnLength;
package->SecCount = left.KernelRowLength; package->SecCount = left.KernelRowLength;
package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM); package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM);
package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f32].buffer_sub; package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f32].buffer_sub;
MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package);
taskGroup.LaunchParallel(SleepMode.DeepSleep); taskGroup.LaunchParallel(SleepMode.DeepSleep);
@@ -53,7 +53,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<double>* leftPtr = left.Buffer; MatrixKernel<double>* leftPtr = left.Buffer;
MatrixKernel<double>* rightPtr = right.Buffer; MatrixKernel<double>* rightPtr = right.Buffer;
MatrixKernel<double>* ansPtr = ans.Buffer; MatrixKernel<double>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f64].buffer_add(leftPtr, rightPtr, ansPtr, count); MathematicsModule.GlobalContext.mat[f64].buffer_add(leftPtr, rightPtr, ansPtr, count);
return; return;
} else if (count <= 1024) } else if (count <= 1024)
@@ -63,7 +63,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<double>* leftPtr = left.Buffer; MatrixKernel<double>* leftPtr = left.Buffer;
MatrixKernel<double>* rightPtr = right.Buffer; MatrixKernel<double>* rightPtr = right.Buffer;
MatrixKernel<double>* ansPtr = ans.Buffer; MatrixKernel<double>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f64].buffer_add(leftPtr, rightPtr, ansPtr, count); MathematicsModule.GlobalContext.mat[f64].buffer_add(leftPtr, rightPtr, ansPtr, count);
MatrixParallel.ReturnParallelResources(ref pool); MatrixParallel.ReturnParallelResources(ref pool);
return; return;
@@ -76,7 +76,7 @@ namespace StgSharp.Mathematics.Numeric
package->PrimCount = ans.KernelColumnLength; package->PrimCount = ans.KernelColumnLength;
package->SecCount = ans.KernelRowLength; package->SecCount = ans.KernelRowLength;
package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM); package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM);
package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f64].buffer_add; package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f64].buffer_add;
MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package);
taskGroup.LaunchParallel(SleepMode.DeepSleep); taskGroup.LaunchParallel(SleepMode.DeepSleep);
@@ -92,12 +92,12 @@ namespace StgSharp.Mathematics.Numeric
scalar->Data<double>(0) = value; scalar->Data<double>(0) = value;
if (count <= 256) if (count <= 256)
{ {
NativeIntrinsic.Context.mat[f64].buffer_fill(ans.Buffer, scalar, count); MathematicsModule.GlobalContext.mat[f64].buffer_fill(ans.Buffer, scalar, count);
return; return;
} else if (count <= 1024) } else if (count <= 1024)
{ {
MatrixParallelThread[] pool = MatrixParallel.LeadParallel(1); MatrixParallelThread[] pool = MatrixParallel.LeadParallel(1);
NativeIntrinsic.Context.mat[f64].buffer_fill(ans.Buffer, scalar, count); MathematicsModule.GlobalContext.mat[f64].buffer_fill(ans.Buffer, scalar, count);
MatrixParallel.ReturnParallelResources(ref pool); MatrixParallel.ReturnParallelResources(ref pool);
return; return;
} }
@@ -107,7 +107,7 @@ namespace StgSharp.Mathematics.Numeric
package->PrimCount = ans.KernelColumnLength; package->PrimCount = ans.KernelColumnLength;
package->SecCount = ans.KernelRowLength; package->SecCount = ans.KernelRowLength;
package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.ANS_SCALAR_PARAM); package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.ANS_SCALAR_PARAM);
package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f64].buffer_fill; package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f64].buffer_fill;
package->Scalar = scalar; package->Scalar = scalar;
MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package);
taskGroup.LaunchParallel(SleepMode.DeepSleep); taskGroup.LaunchParallel(SleepMode.DeepSleep);
@@ -144,7 +144,7 @@ namespace StgSharp.Mathematics.Numeric
enumeration->Member<int>(0) = i; enumeration->Member<int>(0) = i;
enumeration->Member<int>(1) = j; enumeration->Member<int>(1) = j;
NativeIntrinsic.Context MathematicsModule.GlobalContext
.mat[f64].kernel_tile_fma((MatrixKernel*)left.Buffer, .mat[f64].kernel_tile_fma((MatrixKernel*)left.Buffer,
(MatrixKernel*)right.Buffer, (MatrixKernel*)right.Buffer,
(MatrixKernel*)ans.Buffer, enumeration); (MatrixKernel*)ans.Buffer, enumeration);
@@ -189,7 +189,7 @@ namespace StgSharp.Mathematics.Numeric
{ {
MatrixKernel<double>* leftPtr = left.Buffer; MatrixKernel<double>* leftPtr = left.Buffer;
MatrixKernel<double>* ansPtr = ans.Buffer; MatrixKernel<double>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f64].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); MathematicsModule.GlobalContext.mat[f64].buffer_scalar_mul(leftPtr, ansPtr, scalar, count);
return; return;
} else if (count <= 1024) } else if (count <= 1024)
@@ -198,7 +198,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<double>* leftPtr = left.Buffer; MatrixKernel<double>* leftPtr = left.Buffer;
MatrixKernel<double>* ansPtr = ans.Buffer; MatrixKernel<double>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f64].buffer_scalar_mul(leftPtr, ansPtr, scalar, count); MathematicsModule.GlobalContext.mat[f64].buffer_scalar_mul(leftPtr, ansPtr, scalar, count);
MatrixParallel.ReturnParallelResources(ref pool); MatrixParallel.ReturnParallelResources(ref pool);
return; return;
@@ -211,7 +211,7 @@ namespace StgSharp.Mathematics.Numeric
package->SecCount = left.KernelRowLength; package->SecCount = left.KernelRowLength;
package->Scalar = scalar; package->Scalar = scalar;
package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.RIGHT_ANS_SCALAR_PARAM); package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.RIGHT_ANS_SCALAR_PARAM);
package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f64].buffer_scalar_mul; package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f64].buffer_scalar_mul;
MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package);
taskGroup.LaunchParallel(SleepMode.DeepSleep); taskGroup.LaunchParallel(SleepMode.DeepSleep);
@@ -240,7 +240,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<double>* leftPtr = left.Buffer; MatrixKernel<double>* leftPtr = left.Buffer;
MatrixKernel<double>* rightPtr = right.Buffer; MatrixKernel<double>* rightPtr = right.Buffer;
MatrixKernel<double>* ansPtr = ans.Buffer; MatrixKernel<double>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f64].buffer_sub(leftPtr, rightPtr, ansPtr, count); MathematicsModule.GlobalContext.mat[f64].buffer_sub(leftPtr, rightPtr, ansPtr, count);
return; return;
} else if (count <= 1024) } else if (count <= 1024)
@@ -250,7 +250,7 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<double>* leftPtr = left.Buffer; MatrixKernel<double>* leftPtr = left.Buffer;
MatrixKernel<double>* rightPtr = right.Buffer; MatrixKernel<double>* rightPtr = right.Buffer;
MatrixKernel<double>* ansPtr = ans.Buffer; MatrixKernel<double>* ansPtr = ans.Buffer;
NativeIntrinsic.Context.mat[f64].buffer_sub(leftPtr, rightPtr, ansPtr, count); MathematicsModule.GlobalContext.mat[f64].buffer_sub(leftPtr, rightPtr, ansPtr, count);
MatrixParallel.ReturnParallelResources(ref pool); MatrixParallel.ReturnParallelResources(ref pool);
return; return;
@@ -263,7 +263,7 @@ namespace StgSharp.Mathematics.Numeric
package->PrimCount = left.KernelColumnLength; package->PrimCount = left.KernelColumnLength;
package->SecCount = left.KernelRowLength; package->SecCount = left.KernelRowLength;
package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM); package->ComputeMode = new MatrixOpMode(MatrixIndexStyle.BUFFER_INDEX, MatrixOperationParam.LEFT_RIGHT_ANS_PARAM);
package->ComputeHandle = (IntPtr)NativeIntrinsic.Context.mat[f64].buffer_sub; package->ComputeHandle = (IntPtr)MathematicsModule.GlobalContext.mat[f64].buffer_sub;
MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package); MatrixParallelWrap taskGroup = MatrixParallel.ScheduleTask(package);
taskGroup.LaunchParallel(SleepMode.DeepSleep); taskGroup.LaunchParallel(SleepMode.DeepSleep);
@@ -62,7 +62,8 @@ namespace StgSharp.Mathematics.Numeric
int j = (int)(c % ansHeight); int j = (int)(c % ansHeight);
enumeration->Member<int>(0) = i; enumeration->Member<int>(0) = i;
enumeration->Member<int>(1) = j; enumeration->Member<int>(1) = j;
NativeIntrinsic.Context.mat[f32].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer, enumeration); MathematicsModule.GlobalContext.mat[f32].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer,
enumeration);
} }
} }
@@ -91,7 +92,8 @@ namespace StgSharp.Mathematics.Numeric
int j = (int)(c % ansHeight); int j = (int)(c % ansHeight);
enumeration->Member<int>(0) = i; enumeration->Member<int>(0) = i;
enumeration->Member<int>(1) = j; enumeration->Member<int>(1) = j;
NativeIntrinsic.Context.mat[f64].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer, enumeration); MathematicsModule.GlobalContext.mat[f64].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer,
enumeration);
} }
} }
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Factorial" // file="Factorial"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload // AuthorGroup: Nitload Space
// Copyright (c) Nitload. All rights reserved. // Copyright (c) Nitload Space. All rights reserved.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@@ -45,8 +45,7 @@ namespace StgSharp.Mathematics
362880, 362880,
3628800, 3628800,
39916800, 39916800,
479001600 479001600];
];
public static unsafe ulong Factorial(int n) public static unsafe ulong Factorial(int n)
{ {
@@ -55,7 +54,7 @@ namespace StgSharp.Mathematics
return factorialResult[n]; return factorialResult[n];
} }
if (n < 30) { if (n < 30) {
return NativeIntrinsic.Context.factorial_simd(n); return MathematicsModule.GlobalContext.factorial_simd(n);
} }
double double
dn = n, dn = n,
-25
View File
@@ -1,25 +0,0 @@
# 1. 版本 — 已确认 18.1.8
clang-format --version
# 2. 不可见字符扫描 — 用完整路径
$file = Join-Path $PWD "simdid.x86.c"
$bytes = [System.IO.File]::ReadAllBytes($file)
for ($i = 0; $i -lt $bytes.Length - 2; $i++) {
if ($bytes[$i] -eq 0xEF -and $bytes[$i+1] -eq 0xBB -and $bytes[$i+2] -eq 0xBF) {
Write-Host "BOM found at offset $i"
}
if ($bytes[$i] -eq 0xC2 -and $bytes[$i+1] -eq 0xA0) {
Write-Host "NBSP at offset $i"
}
if ($bytes[$i] -eq 0xE2 -and $bytes[$i+1] -eq 0x80 -and
($bytes[$i+2] -eq 0x8B -or $bytes[$i+2] -eq 0x8C -or $bytes[$i+2] -eq 0x8D)) {
Write-Host "Zero-width char at offset $i"
}
}
Write-Host "Scan complete. File size: $($bytes.Length) bytes"
# 3. 格式化对比 — 用 fc.exe 避免 PowerShell 的 Format-Custom 歧义
clang-format -assume-filename=test.c $file > formatted.c
fc.exe $file formatted.c
+3 -1
View File
@@ -26,6 +26,7 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Common.Timing; using StgSharp.Common.Timing;
using StgSharp.Graphics;
using StgSharp.Internal; using StgSharp.Internal;
using StgSharp.Mathematics; using StgSharp.Mathematics;
using StgSharp.Mathematics.Memory; using StgSharp.Mathematics.Memory;
@@ -48,8 +49,9 @@ namespace StgSharp
// TestRegexAnalyse.Run(); // TestRegexAnalyse.Run();
// HlsfStressTest.Run(); // HlsfStressTest.Run();
TestSwiss();
TestMatrix(); // TestMatrix();
/* /*
+1
View File
@@ -11,6 +11,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\StgSharp.Common\StgSharp.Common.csproj" /> <ProjectReference Include="..\StgSharp.Common\StgSharp.Common.csproj" />
<ProjectReference Include="..\StgSharp.Graphics\StgSharp.Graphics.csproj" />
<ProjectReference Include="..\StgSharp.Mathematics\StgSharp.Mathematics.csproj" /> <ProjectReference Include="..\StgSharp.Mathematics\StgSharp.Mathematics.csproj" />
<ProjectReference Include="..\StgSharp.Model\StgSharp.Model.csproj" /> <ProjectReference Include="..\StgSharp.Model\StgSharp.Model.csproj" />
<ProjectReference Include="..\StgSharp.RegularAnalysis\StgSharp.RegularAnalysis.csproj" /> <ProjectReference Include="..\StgSharp.RegularAnalysis\StgSharp.RegularAnalysis.csproj" />
+13 -15
View File
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="TestRender.cs" // file="TestRender.cs"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload Space
@@ -26,12 +26,10 @@
// ARISING FROM, OUT OF OR IN CONNECTION WITH // ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// //
//----------------------------------------------------------------------- // -----------------------------------------------------------------------
//----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Collections; using StgSharp.Collections;
using StgSharp.MVVM; using StgSharp.Graphics;
using StgSharp.MVVM.ViewModel;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -45,19 +43,19 @@ namespace StgSharp
public static void TestRender() public static void TestRender()
{ {
World.InitGL( 4, 6 ); // World.InitGL(4, 6);
World.GlobalSetting.VSyncActivated = false; World.GlobalSetting.VSyncActivated = false;
ViewPort vp = new ViewPort( 800, 600, "Hello StgSharp!", IntPtr.Zero ); ViewPort vp = new ViewPort(800, 600, "Hello StgSharp!", IntPtr.Zero);
//throw new NotImplementedException(); // throw new NotImplementedException();
/*
ViewModelBase mainModel = new ViewModelMain(vp);
mainModel.CreateAndBindView<ViewMain>("MainView", (1, 1, 1));
ViewModelBase mainModel = new ViewModelMain( vp ); mainModel.UseViewModel("MainView");
mainModel.CreateAndBindView<ViewMain>( "MainView", (1, 1, 1) ); /**/
World.Terminate(0);
mainModel.UseViewModel( "MainView" );
World.Terminate( 0 );
} }
} }
+64
View File
@@ -0,0 +1,64 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="TestSwiss"
// 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.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
internal static partial class Program
{
public static void TestSwiss()
{
SwissTable swiss = SwissTable.Create();
for (int i = 0; i < 10000; i++)
{
_ = swiss.TryAddOrSet(i, i * 2, out _);
Console.WriteLine($"Set a kvp of ({i},{i * 2})");
}
Random rand = new Random();
for (int i = 0; i < 10000; i++)
{
int key = rand.Next(0, 10000);
if (swiss.TryGet(key, out nint value))
{
Console.WriteLine($"Get a kvp of ({key},{value})");
} else
{
Console.WriteLine($"Failed to get a kvp of ({key},?)");
}
}
}
}
}