move random gen to Math, working on VL4

This commit is contained in:
Nitload
2026-03-02 23:56:21 +08:00
parent 7e3ed8b0fd
commit ae1a49d6fb
63 changed files with 6463 additions and 6970 deletions
+7 -22
View File
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HlsfAllocatorBench" // file="HlsfAllocatorBench"
// 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,7 +26,7 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes;
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.Benchmark namespace StgSharp.Benchmark
@@ -40,15 +40,7 @@ namespace StgSharp.Benchmark
private const int AllocationCount = 2048; private const int AllocationCount = 2048;
private static readonly int[] AllocSizes = [ private static readonly int[] AllocSizes = [64, 96, 150, 200, 400, 1024, 4096];
64,
96,
150,
200,
400,
1024,
4096
];
private HybridLayerSegregatedFitAllocator _hlsfAllocator = null!; private HybridLayerSegregatedFitAllocator _hlsfAllocator = null!;
private readonly List<HybridLayerSegregatedFitAllocationHandle> _hlsfLocalList = new(); private readonly List<HybridLayerSegregatedFitAllocationHandle> _hlsfLocalList = new();
private readonly List<nint> _libcLocalList = new(); private readonly List<nint> _libcLocalList = new();
@@ -104,9 +96,7 @@ namespace StgSharp.Benchmark
_hlsfAllocator = new HybridLayerSegregatedFitAllocator(GetArenaBytes(), align:(int)Alignment); _hlsfAllocator = new HybridLayerSegregatedFitAllocator(GetArenaBytes(), align:(int)Alignment);
} }
private static uint AlignSize( private static uint AlignSize(uint size)
uint size
)
{ {
uint mask = Alignment - 1; uint mask = Alignment - 1;
return (size + mask) & ~mask; return (size + mask) & ~mask;
@@ -119,9 +109,7 @@ namespace StgSharp.Benchmark
int mb = defaultMb; int mb = defaultMb;
string? env = Environment.GetEnvironmentVariable("HLSF_BENCH_ARENA_MB"); string? env = Environment.GetEnvironmentVariable("HLSF_BENCH_ARENA_MB");
if (!string.IsNullOrWhiteSpace(env) && if (!string.IsNullOrWhiteSpace(env) && int.TryParse(env, out int parsed) && parsed >= minMb) {
int.TryParse(env, out int parsed) &&
parsed >= minMb) {
mb = parsed; mb = parsed;
} }
@@ -130,10 +118,7 @@ namespace StgSharp.Benchmark
private uint GetNextRandomSize() => (uint)AllocSizes[_random.Next(AllocSizes.Length)]; private uint GetNextRandomSize() => (uint)AllocSizes[_random.Next(AllocSizes.Length)];
private void RunHlsf( private void RunHlsf(HybridLayerSegregatedFitAllocator allocator, FreePolicy policy)
HybridLayerSegregatedFitAllocator allocator,
FreePolicy policy
)
{ {
_hlsfLocalList.Clear(); _hlsfLocalList.Clear();
-91
View File
@@ -1,91 +0,0 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="ValueBox"
// Project: StgSharp
// AuthorGroup: Nitload
// Copyright (c) Nitload. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Data
{
public interface IValueBox
{
ref object ValueReference { get; }
static virtual IValueBox<T> AsGeneric<T>(IValueBox box) where T: unmanaged
{
if (box is not IValueBox<T> genericBox) {
return null;
}
return genericBox;
}
static virtual bool IsGeneric<T>(IValueBox box) where T: unmanaged
{
return box is IValueBox<T>;
}
}
public interface IValueBox<T> where T: unmanaged
{
T Value { get; set; }
}
/// <summary>
/// A class attempt to reduce cost of boxing, though still a bit slower than direct access to
/// _origin value type instance.
/// </summary>
/// <typeparam name="T">
/// Type of instance to be boxed.
/// </typeparam>
public class ValueBox<T> : IValueBox, IValueBox<T> where T: unmanaged
{
private T _value;
public ValueBox(T value)
{
_value = value;
}
public ref object ValueReference => ref Unsafe.As<T, object>(ref _value);
public T Value
{
get => _value;
set => _value = value;
}
}
}
-68
View File
@@ -1,68 +0,0 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="Lable"
// Project: StgSharp
// AuthorGroup: Nitload
// Copyright (c) Nitload. 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.Runtime.CompilerServices;
namespace StgSharp.HighPerformance
{
public class DataLabel
{
public DataLabel(string labelName)
{
Name = labelName;
}
public string Name
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
init;
}
public override unsafe int GetHashCode()
{
ReadOnlySpan<char> nameSpan = Name.AsSpan();
fixed (char* cptr = nameSpan) {
return NativeIntrinsic.Context.city_hash_simplify(cptr, Name.Length);
}
}
}
public static class DataLabelBuilder
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DataLabel AsLabel(this string name)
{
return new DataLabel(name);
}
}
}
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="BufferStack" // file="BufferStack"
// 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
@@ -29,10 +29,10 @@ using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
[CollectionBuilder(typeof(BufferStackBuilder), nameof(BufferStackBuilder.Create))] [CollectionBuilder(typeof(BufferStackBuilder), nameof(BufferStackBuilder.Create))]
public unsafe class BufferStack<T> : IDisposable where T : unmanaged public unsafe class BufferStack<T> : IDisposable where T: unmanaged
{ {
private byte* _buffer; private byte* _buffer;
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="ConcurrentBufferStack" // file="ConcurrentBufferStack"
// 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
@@ -33,7 +33,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public static class BufferStackBuilder public static class BufferStackBuilder
{ {
@@ -279,9 +279,8 @@ namespace StgSharp.HighPerformance.Memory
T* dataStart = (T*)(_buffer + sizeof(Header)); T* dataStart = (T*)(_buffer + sizeof(Header));
fixed (T* sourcePtr = span) { fixed (T* sourcePtr = span) {
Buffer.MemoryCopy(sourcePtr, dataStart, Buffer.MemoryCopy(sourcePtr, dataStart, (nuint)header->Capacity * (nuint)sizeof(T),
(nuint)header->Capacity * (nuint)sizeof(T), (nuint)span.Length * (nuint)sizeof(T));
(nuint)span.Length * (nuint)sizeof(T));
} }
header->Top = span.Length; header->Top = span.Length;
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocationHandle" // file="HLSFAllocationHandle"
// Project: StgSharp // Project: StgSharp
@@ -32,9 +32,9 @@ using System.Drawing;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Allocator = StgSharp.HighPerformance.Memory.HybridLayerSegregatedFitAllocator; using Allocator = StgSharp.Mathematics.Memory.HybridLayerSegregatedFitAllocator;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public readonly unsafe struct HybridLayerSegregatedFitAllocationHandle public readonly unsafe struct HybridLayerSegregatedFitAllocationHandle
{ {
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.Alloc" // file="HLSFAllocator.Alloc"
// Project: StgSharp // Project: StgSharp
@@ -27,9 +27,9 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using System; using System;
using System.Numerics; using System.Numerics;
using hlsfHandle = StgSharp.HighPerformance.Memory.HybridLayerSegregatedFitAllocationHandle; using hlsfHandle = StgSharp.Mathematics.Memory.HybridLayerSegregatedFitAllocationHandle;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public unsafe partial class HybridLayerSegregatedFitAllocator public unsafe partial class HybridLayerSegregatedFitAllocator
{ {
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.BucketNode" // file="HLSFAllocator.BucketNode"
// 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
@@ -30,7 +30,7 @@ using System.Reflection.Metadata;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public unsafe partial class HybridLayerSegregatedFitAllocator public unsafe partial class HybridLayerSegregatedFitAllocator
{ {
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.Debug" // file="HLSFAllocator.Debug"
// 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,13 +31,12 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public sealed class HLSFPositionChainBreakException : Exception public sealed class HLSFPositionChainBreakException : Exception
{ {
public HLSFPositionChainBreakException() public HLSFPositionChainBreakException() : base("Position chain of an HLSF allocator is broken") { }
: base("Position chain of an HLSF allocator is broken") { }
} }
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.Free" // file="HLSFAllocator.Free"
// 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
@@ -35,9 +35,9 @@ using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using hlsfHandle = StgSharp.HighPerformance.Memory.HybridLayerSegregatedFitAllocationHandle; using hlsfHandle = StgSharp.Mathematics.Memory.HybridLayerSegregatedFitAllocationHandle;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public enum FreePolicy public enum FreePolicy
{ {
@@ -90,10 +90,7 @@ namespace StgSharp.HighPerformance.Memory
/// Handle to the allocated memory block /// Handle to the allocated memory block
/// <param name="collectPolicy"> /// <param name="collectPolicy">
/// </param> /// </param>
public void Free( public void Free(hlsfHandle handle, FreePolicy collectPolicy = FreePolicy.NoCollect)
hlsfHandle handle,
FreePolicy collectPolicy = FreePolicy.NoCollect
)
{ {
Entry* e = handle.EntryHandle; Entry* e = handle.EntryHandle;
if (e == null) { if (e == null) {
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.Level" // file="HLSFAllocator.Level"
// Project: StgSharp // Project: StgSharp
@@ -33,14 +33,14 @@ using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public unsafe partial class HybridLayerSegregatedFitAllocator public unsafe partial class HybridLayerSegregatedFitAllocator
{ {
private const int MaxLevel = 9; private const int MaxLevel = 9;
private int[] _levelSizeArray = [ 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216 ]; private int[] _levelSizeArray = [64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216];
public int AlignOfLevel(int bucketLevel) public int AlignOfLevel(int bucketLevel)
{ {
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.SegmentEntry" // file="HLSFAllocator.SegmentEntry"
// 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
@@ -29,7 +29,7 @@ using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public unsafe partial class HybridLayerSegregatedFitAllocator public unsafe partial class HybridLayerSegregatedFitAllocator
{ {
@@ -38,10 +38,7 @@ namespace StgSharp.HighPerformance.Memory
/// Check if two Entries are adjacent in memory /// Check if two Entries are adjacent in memory
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool AssertAdjacentTo( private static bool AssertAdjacentTo(Entry* current, Entry* other)
Entry* current,
Entry* other
)
{ {
// Only a predicate; never throw here. Callers rely on false to skip merging. // Only a predicate; never throw here. Callers rely on false to skip merging.
return other->Position + (nuint)other->Size == current->Position || return other->Position + (nuint)other->Size == current->Position ||
@@ -51,11 +48,7 @@ namespace StgSharp.HighPerformance.Memory
/// <summary> /// <summary>
/// check out if a bucket is within the same higher-level boundary as currentOffset /// check out if a bucket is within the same higher-level boundary as currentOffset
/// </summary> /// </summary>
private bool AssertBoundary( private bool AssertBoundary(Entry* previous, Entry* current, int level)
Entry* previous,
Entry* current,
int level
)
{ {
level = int.Min(level, MaxLevel); level = int.Min(level, MaxLevel);
int nextLevelSize = _levelSizeArray[level] * 4; int nextLevelSize = _levelSizeArray[level] * 4;
@@ -68,21 +61,14 @@ namespace StgSharp.HighPerformance.Memory
/// Determine segment index based on size and originLevel /// Determine segment index based on size and originLevel
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int DetermineSegmentIndex( private static int DetermineSegmentIndex(int[] levelSizeArray, long size, int level)
int[] levelSizeArray,
long size,
int level
)
{ {
level = int.Min(level, MaxLevel); level = int.Min(level, MaxLevel);
return (int)((size - 1) / levelSizeArray[level]); return (int)((size - 1) / levelSizeArray[level]);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void InsertEntryAfter( private static void InsertEntryAfter(Entry* entry, Entry* position)
Entry* entry,
Entry* position
)
{ {
Entry* next = position->NextNear; Entry* next = position->NextNear;
entry->NextNear = next; entry->NextNear = next;
@@ -92,10 +78,7 @@ namespace StgSharp.HighPerformance.Memory
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void InsertEntryBefore( private static void InsertEntryBefore(Entry* entry, Entry* position)
Entry* entry,
Entry* position
)
{ {
Entry* prev = position->PreviousNear; Entry* prev = position->PreviousNear;
entry->NextNear = position; entry->NextNear = position;
@@ -109,9 +92,7 @@ namespace StgSharp.HighPerformance.Memory
/// Current Entry will serve as the final merged block. The Merge will be in lazy /// Current Entry will serve as the final merged block. The Merge will be in lazy
/// strategy. /// strategy.
/// </summary> /// </summary>
private void MergeAndRemoveFromBuckets( private void MergeAndRemoveFromBuckets(Entry* entry)
Entry* entry
)
{ {
if (entry == null) { if (entry == null) {
return; return;
@@ -171,9 +152,7 @@ namespace StgSharp.HighPerformance.Memory
/// Remove node from position linked list, this method does not recycle a BucketNode from /// Remove node from position linked list, this method does not recycle a BucketNode from
/// size bucket /// size bucket
/// </summary> /// </summary>
private void RemoveFromPositionChain( private void RemoveFromPositionChain(Entry* entry)
Entry* entry
)
{ {
Entry* prev = entry->PreviousNear; Entry* prev = entry->PreviousNear;
Entry* next = entry->NextNear; Entry* next = entry->NextNear;
@@ -190,11 +169,7 @@ namespace StgSharp.HighPerformance.Memory
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void SetEntryLevel( private static void SetEntryLevel(Entry* entry, nuint position, long size)
Entry* entry,
nuint position,
long size
)
{ {
entry ->Position = position; entry ->Position = position;
entry->Size = size; entry->Size = size;
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator" // file="HLSFAllocator"
// Project: StgSharp // Project: StgSharp
@@ -31,7 +31,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public unsafe partial class HybridLayerSegregatedFitAllocator : IDisposable public unsafe partial class HybridLayerSegregatedFitAllocator : IDisposable
{ {
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="SlabAllocationHandle" // file="SlabAllocationHandle"
// 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,7 +28,7 @@
using System; using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public unsafe struct SlabAllocationHandle<T> : IDisposable where T: unmanaged public unsafe struct SlabAllocationHandle<T> : IDisposable where T: unmanaged
{ {
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="SlabAllocator.Chunked" // file="SlabAllocator.Chunked"
// 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
@@ -33,9 +33,9 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
internal sealed unsafe class ChunkedSlabAllocator<T> : SlabAllocator<T> where T : unmanaged internal sealed unsafe class ChunkedSlabAllocator<T> : SlabAllocator<T> where T: unmanaged
{ {
private bool _disposed; private bool _disposed;
@@ -96,6 +96,7 @@ namespace StgSharp.HighPerformance.Memory
return; return;
} }
_disposed = true; _disposed = true;
// NativeMemory.Free((void*)_currentBuffer); // NativeMemory.Free((void*)_currentBuffer);
while (_buffers.TryPop(out nuint buffer)) while (_buffers.TryPop(out nuint buffer))
{ {
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="SlabAllocator.ChunkedConcurrent" // file="SlabAllocator.ChunkedConcurrent"
// 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
@@ -36,9 +36,9 @@ using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
internal sealed unsafe class ConcurrentChunkedSlabAllocator<T> : SlabAllocator<T> where T : unmanaged internal sealed unsafe class ConcurrentChunkedSlabAllocator<T> : SlabAllocator<T> where T: unmanaged
{ {
private bool _disposed; private bool _disposed;
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="SlabAllocator.SequencialConcurrent" // file="SlabAllocator.SequencialConcurrent"
// 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
@@ -32,15 +32,15 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public sealed unsafe class ConcurrentSequentialSlabAllocator<T> : SlabAllocator<T> where T: unmanaged public sealed unsafe class ConcurrentSequentialSlabAllocator<T> : SlabAllocator<T> where T: unmanaged
{ {
private bool _disposed;
private T* _buffer; private T* _buffer;
private bool _disposed;
private readonly BufferExpansionLock _lock = new(); private readonly BufferExpansionLock _lock = new();
private readonly ConcurrentBufferStack<nuint> _stack; private readonly ConcurrentBufferStack<nuint> _stack;
private readonly int _elementSize; private readonly int _elementSize;
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="SlabAllocator" // file="SlabAllocator"
// 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
@@ -27,9 +27,9 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using System; using System;
namespace StgSharp.HighPerformance.Memory namespace StgSharp.Mathematics.Memory
{ {
public abstract class SlabAllocator<T> : IDisposable where T : unmanaged public abstract class SlabAllocator<T> : IDisposable where T: unmanaged
{ {
public abstract nuint Allocate(); public abstract nuint Allocate();
@@ -56,32 +56,29 @@ namespace StgSharp.HighPerformance.Memory
/// Thrown when requesting unsupported configurations. /// Thrown when requesting unsupported configurations.
/// </exception> /// </exception>
/// <remarks> /// <remarks>
/// <para><strong> Important Threading Considerations: </strong></para> <para> While SLAB /// <para><strong> Important Threading Considerations: </strong></para> <para>While SLAB
/// /// allocators themselves may be designed for single-threaded use, allocated objects /// /// allocators themselves may be designed for single-threaded use, allocated objects
/// are /// frequently shared across multiple threads in real-world applications. Due to /// are /// frequently shared across multiple threads in real-world applications. Due to
/// the /// special implementation of expandable concurrent sequential SLAB allocators, /// the /// special implementation of expandable concurrent sequential SLAB allocators,
/// they rely /// on internal expansion locks to ensure that memory buffer expansions /// they rely /// on internal expansion locks to ensure that memory buffer expansions
/// (which involve /// copying the entire buffer to a new location) do not occur while /// (which involve /// copying the entire buffer to a new location) do not occur while
/// other threads are /// reading from allocated regions.</para> <para><strong> /// other threads are /// reading from allocated regions. </para> <para><strong>
/// Sequential Layout Limitations: /// </strong><br /> Sequential layout SLAB allocators /// Sequential Layout Limitations: ///</strong><br /> Sequential layout SLAB allocators
/// cannot provide a single-threaded /// version because:<list /// cannot provide a single-threaded /// version because:<list
/// type="bullet"><item><description> They use contiguous memory /// layout that /// type="bullet"><item><description>They use contiguous memory /// layout that requires
/// requires buffer expansion when capacity is exceeded /// /// buffer expansion when capacity is exceeded
/// </description></item><item><description> Buffer expansion involves copying all /// /// ///</description></item><item><description>Buffer expansion involves copying all ///
/// existing data to a new memory location </description></item><item><description>/// /// existing data to a new memory location</description></item><item><description> ///
/// Without proper synchronization, concurrent access to allocated objects during /// /// Without proper synchronization, concurrent access to allocated objects during ///
/// expansion would cause memory corruption </description></item><item><description> The /// expansion would cause memory corruption</description></item><item><description>The
/// /// expansion lock mechanism is essential even if allocation itself is single- /// /// /// expansion lock mechanism is essential even if allocation itself is single- ///
/// threaded</description></item></list></para> <para><strong> Chunked Layout: /// /// threaded </description></item></list></para> <para><strong>Chunked Layout:
/// </strong><br /> Chunked layout allocators can optionally provide single-threaded /// /// ///</strong><br /> Chunked layout allocators can optionally provide single-threaded
/// versions since they don't require buffer expansion and copying. Each chunk is /// /// /// versions since they don't require buffer expansion and copying. Each chunk is
/// allocated independently, avoiding the memory relocation issues present in sequential /// /// allocated independently, avoiding the memory relocation issues present in
/// /// layouts.</para> /// sequential /// layouts. </para>
/// </remarks> /// </remarks>
public static SlabAllocator<T> Create( public static SlabAllocator<T> Create(nuint count, SlabBufferLayout layout, bool concurrentSupport = true)
nuint count,
SlabBufferLayout layout,
bool concurrentSupport = true)
{ {
if (concurrentSupport) { if (concurrentSupport) {
return layout switch return layout switch
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="IRegisterType" // file="IRegisterType"
// 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
@@ -32,7 +32,7 @@ using System.Numerics;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.HighPerformance namespace StgSharp.Mathematics
{ {
/// <summary> /// <summary>
/// Abstraction for a wide SIMD register or equivalent packed numeric storage. Provides raw /// Abstraction for a wide SIMD register or equivalent packed numeric storage. Provides raw
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="M128" // file="M128"
// Project: StgSharp // Project: StgSharp
@@ -36,7 +36,7 @@ using System.Runtime.Intrinsics.X86;
using System.Text; using System.Text;
namespace StgSharp.HighPerformance namespace StgSharp.Mathematics
{ {
[StructLayout(LayoutKind.Explicit, Pack = 16)] [StructLayout(LayoutKind.Explicit, Pack = 16)]
public unsafe struct M128 : IRegisterPresentation public unsafe struct M128 : IRegisterPresentation
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="M256" // file="M256"
// Project: StgSharp // Project: StgSharp
@@ -35,7 +35,7 @@ using System.Runtime.Intrinsics;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.HighPerformance namespace StgSharp.Mathematics
{ {
[StructLayout(LayoutKind.Explicit, Pack = 16)] [StructLayout(LayoutKind.Explicit, Pack = 16)]
public unsafe struct M256 : IRegisterPresentation public unsafe struct M256 : IRegisterPresentation
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="M512" // file="M512"
// 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
@@ -35,7 +35,7 @@ using System.Runtime.Intrinsics;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.HighPerformance namespace StgSharp.Mathematics
{ {
[StructLayout(LayoutKind.Explicit, Size = 64, Pack = 64)] [StructLayout(LayoutKind.Explicit, Size = 64, Pack = 64)]
public unsafe struct M512 : IRegisterPresentation public unsafe struct M512 : IRegisterPresentation
@@ -44,17 +44,17 @@ namespace StgSharp.HighPerformance
[FieldOffset(0)] private fixed byte _buffer[64]; [FieldOffset(0)] private fixed byte _buffer[64];
[FieldOffset(0)] private Vector512<float> Vec; [FieldOffset(0)] private Vector512<float> Vec;
public ref T AsRef<T>() where T : unmanaged, INumber<T> public ref T AsRef<T>() where T: unmanaged, INumber<T>
{ {
return ref Unsafe.As<byte, T>(ref _buffer[0]); return ref Unsafe.As<byte, T>(ref _buffer[0]);
} }
public void BroadCastFrom<T>(T value) where T : unmanaged, INumber<T> public void BroadCastFrom<T>(T value) where T: unmanaged, INumber<T>
{ {
Vec = Vector512.Create(value).AsSingle(); Vec = Vector512.Create(value).AsSingle();
} }
public ref T Member<T>(int index) where T : unmanaged, INumber<T> public ref T Member<T>(int index) where T: unmanaged, INumber<T>
{ {
return ref Unsafe.As<byte, T>(ref _buffer[0]); return ref Unsafe.As<byte, T>(ref _buffer[0]);
} }
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="M64" // file="M64"
// 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
@@ -30,7 +30,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Intrinsics; using System.Runtime.Intrinsics;
namespace StgSharp.HighPerformance namespace StgSharp.Mathematics
{ {
[StructLayout(LayoutKind.Explicit, Pack = 8)] [StructLayout(LayoutKind.Explicit, Pack = 8)]
public unsafe struct M64 : IRegisterPresentation public unsafe struct M64 : IRegisterPresentation
@@ -47,12 +47,12 @@ namespace StgSharp.HighPerformance
Unsafe.SkipInit(out value); Unsafe.SkipInit(out value);
} }
public ref T AsRef<T>() where T : unmanaged,INumber<T> public ref T AsRef<T>() where T: unmanaged,INumber<T>
{ {
return ref Unsafe.As<byte, T>(ref buffer[0]); return ref Unsafe.As<byte, T>(ref buffer[0]);
} }
public void BroadCastFrom<T>(T value) where T : unmanaged, INumber<T> public void BroadCastFrom<T>(T value) where T: unmanaged, INumber<T>
{ {
vec = Vector64.Create(value).AsSingle(); vec = Vector64.Create(value).AsSingle();
} }
@@ -68,7 +68,7 @@ namespace StgSharp.HighPerformance
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T Member<T>(int index) where T : unmanaged, INumber<T> public ref T Member<T>(int index) where T: unmanaged, INumber<T>
{ {
return ref Unsafe.As<byte, T>(ref buffer[index * sizeof(T)]); return ref Unsafe.As<byte, T>(ref buffer[index * sizeof(T)]);
} }
@@ -1,54 +0,0 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="UnsafeCompute"
// Project: StgSharp
// AuthorGroup: Nitload
// Copyright (c) Nitload. 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.Runtime.CompilerServices;
namespace StgSharp.HighPerformance
{
public static class UnsafeCompute
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int CityHashSimplify(char* span, int length)
{
return NativeIntrinsic.Context.city_hash_simplify(span, length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int CityHashSimplify(char* span, int begin, int length)
{
return NativeIntrinsic.Context.city_hash_simplify(span + begin, length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int IndexOfCharPair(char* source, int pairValue, int length)
{
return NativeIntrinsic.Context.index_pair(source, pairValue, length);
}
}
}
+4
View File
@@ -23,4 +23,8 @@
<None Remove="Graphics\**" /> <None Remove="Graphics\**" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="HighPerformance\RegisterAbstraction\" />
</ItemGroup>
</Project> </Project>
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="TimeSpanProvider.Awaiting" // file="TimeSpanProvider.Awaiting"
// 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,7 +25,7 @@
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
@@ -154,9 +154,7 @@ namespace StgSharp.Timing
/// OperationCanceledException when token is cancelled. If the provider is disposed during /// OperationCanceledException when token is cancelled. If the provider is disposed during
/// wait an OperationCanceledException is thrown to indicate end. /// wait an OperationCanceledException is thrown to indicate end.
/// </summary> /// </summary>
public Task WaitNextSpanAsync( public Task WaitNextSpanAsync(CancellationToken ct)
CancellationToken ct
)
{ {
// Block the current thread until the event is signaled or cancellation requested. // Block the current thread until the event is signaled or cancellation requested.
_event.Wait(ct); _event.Wait(ct);
@@ -195,9 +193,7 @@ namespace StgSharp.Timing
/// True if the span provider is working. False if time is over (the sequence ended). /// True if the span provider is working. False if time is over (the sequence ended).
/// </returns> /// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool OnSpanTick( internal bool OnSpanTick(long currentTick)
long currentTick
)
{ {
if (_sequence.EndsAt(currentTick)) if (_sequence.EndsAt(currentTick))
{ {
+220 -255
View File
@@ -1,311 +1,276 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="TextureGL" // file="TextureGL"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Graphics; using StgSharp.Graphics;
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StgSharp.Graphics.OpenGL
{
public sealed unsafe class TextureGL
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StgSharp.Graphics.OpenGL
{
public sealed unsafe class TextureGL
{
private int currentEditingTextureIndex; private int currentEditingTextureIndex;
private OpenGLFunction _gl; private OpenGLFunction _gl;
internal GlHandle[] _textureHandle; internal GlHandle[] _textureHandle;
internal TextureGL( internal TextureGL(int count, glRender binding)
int count, {
glRender binding // sourceList = new Image[count];
) this._gl = binding.GL;
{ _textureHandle = _gl.GenTextures(count);
// sourceList = new Image[count]; }
this._gl = binding.GL;
_textureHandle = _gl.GenTextures(count); public GlHandle this[int index]
} {
get => _textureHandle[index];
public GlHandle this[ }
int index
] public int Count
{ {
get => _textureHandle[index]; get => _textureHandle.Length;
}
public int Count
{
get => _textureHandle.Length;
} }
// internal Image[] sourceList; // internal Image[] sourceList;
public int IndexOfCurrentTexture public int IndexOfCurrentTexture
{ {
get => currentEditingTextureIndex; get => currentEditingTextureIndex;
}
internal OpenGLFunction GL => _gl;
public void ActivateAs(TextureUnit unit)
{
_gl.ActiveTextureUnit((uint)unit);
}
public void Bind2D(int index)
{
currentEditingTextureIndex = index;
_gl.BindTexture(glConst.TEXTURE_2D, _textureHandle[index]);
} }
internal OpenGLFunction GL => _gl; /// <summary>
/// Load an <see cref="Image" /> to certain texture.
public void ActivateAs(
TextureUnit unit
)
{
_gl.ActiveTextureUnit((uint)unit);
}
public void Bind2D(
int index
)
{
currentEditingTextureIndex = index;
_gl.BindTexture(glConst.TEXTURE_2D, _textureHandle[index]);
}
/// <summary>
/// Load an <see cref="Image" /> to certain texture.
/// </summary> /// </summary>
/// <param _label="index"> /// <param _label="index">
/// ///
/// </param> /// </param>
/// <param _label="i"> /// <param _label="i">
/// ///
/// </param> /// </param>
public unsafe void LoadTexture( public unsafe void LoadTexture(int index, Image i)
int index, {
Image i byte[] handle = i.PixelBuffer;
) _gl.TextureImage2d(Texture2DTarget.Texture2D, 0, i.Channel, i.Width, i.Height, i.Channel, i.PixelLayout,
{ pixels:handle);
byte[] handle = i.PixelBuffer; _gl.GenerateMipmap(Texture2DTarget.Texture2D);
_gl.TextureImage2d(Texture2DTarget.Texture2D, 0, i.Channel, i.Width, i.Height,
i.Channel, i.PixelLayout, pixels:handle);
_gl.GenerateMipmap(Texture2DTarget.Texture2D);
} }
#region texture setting #region texture setting
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set2dFilterProperty( public void Set2dFilterProperty(int index, TextureFilter onMinify, TextureFilter onMagnify)
int index,
TextureFilter onMinify,
TextureFilter onMagnify
)
{ {
#if DEBUG #if DEBUG
if (index != currentEditingTextureIndex) if (index != currentEditingTextureIndex)
{ {
throw new InvalidOperationException( throw new InvalidOperationException(
"Texture to be editted is not the one being activated."); "Texture to be editted is not the one being activated.");
} }
#endif #endif
_gl.TextureParameter(glConst.TEXTURE_2D, glConst.TEXTURE_MIN_FILTER, (int)onMinify); _gl.TextureParameter(glConst.TEXTURE_2D, glConst.TEXTURE_MIN_FILTER, (int)onMinify);
_gl.TextureParameter(glConst.TEXTURE_2D, glConst.TEXTURE_MAG_FILTER, _gl.TextureParameter(glConst.TEXTURE_2D, glConst.TEXTURE_MAG_FILTER,
(int)onMagnify); (int)onMagnify);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set2dWrapProperty( public void Set2dWrapProperty(int index, TextureWrap onHorizontial, TextureWrap onVertical)
int index,
TextureWrap onHorizontial,
TextureWrap onVertical
)
{ {
#if DEBUG #if DEBUG
if (index != currentEditingTextureIndex) if (index != currentEditingTextureIndex)
{ {
throw new InvalidOperationException( throw new InvalidOperationException(
"Texture to be editted is not the one being activated."); "Texture to be editted is not the one being activated.");
} }
#endif #endif
_gl.TextureParameter(glConst.TEXTURE_2D, glConst.TEXTURE_WRAP_S, _gl.TextureParameter(glConst.TEXTURE_2D, glConst.TEXTURE_WRAP_S,
(int)onHorizontial); (int)onHorizontial);
_gl.TextureParameter(glConst.TEXTURE_2D, glConst.TEXTURE_WRAP_T, (int)onVertical); _gl.TextureParameter(glConst.TEXTURE_2D, glConst.TEXTURE_WRAP_T, (int)onVertical);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set2dProperty( public void Set2dProperty(int index, TextureProperty property)
int index, {
TextureProperty property Set2dFilterProperty(index, property.FilterOnMinify, property.FilterOnMagnify);
) Set2dWrapProperty(index, property.WrapOnHorizontial, property.WrapOnVertical);
{
Set2dFilterProperty(index, property.FilterOnMinify, property.FilterOnMagnify);
Set2dWrapProperty(index, property.WrapOnHorizontial, property.WrapOnVertical);
} }
#endregion texture setting #endregion texture setting
} }
[StructLayout(LayoutKind.Explicit)] [StructLayout(LayoutKind.Explicit)]
public struct TextureProperty public struct TextureProperty
{ {
[FieldOffset(0)] private M128 mask; [FieldOffset(0)] private M128 mask;
[FieldOffset(0)] private TextureFilter mag; [FieldOffset(0)] private TextureFilter mag;
[FieldOffset(4)] private TextureFilter min; [FieldOffset(4)] private TextureFilter min;
[FieldOffset(8)] private TextureWrap hori; [FieldOffset(8)] private TextureWrap hori;
[FieldOffset(12)] private TextureWrap vert; [FieldOffset(12)] private TextureWrap vert;
public TextureProperty( public TextureProperty(
TextureFilter onMagnify, TextureFilter onMagnify,
TextureFilter onMinify, TextureFilter onMinify,
TextureWrap onHorizontial, TextureWrap onHorizontial,
TextureWrap onVertical TextureWrap onVertical)
) {
{ FilterOnMagnify = onMagnify;
FilterOnMagnify = onMagnify; FilterOnMinify = onMinify;
FilterOnMinify = onMinify; WrapOnHorizontial = onHorizontial;
WrapOnHorizontial = onHorizontial; WrapOnVertical = onVertical;
WrapOnVertical = onVertical; }
public TextureFilter FilterOnMagnify
{
get => mag;
set => mag = value;
}
public TextureFilter FilterOnMinify
{
get => min;
set => min = value;
}
public TextureWrap WrapOnHorizontial
{
get => hori;
set => hori = value;
}
public TextureWrap WrapOnVertical
{
get => vert;
set => vert = value;
}
public override bool Equals([NotNullWhen(true)] object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return HashCode.Combine(FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial, WrapOnVertical);
}
public override string ToString()
{
return $"FilterOnMagnify:{FilterOnMagnify}, " + $"FilterOnMagnify:{FilterOnMagnify}, " + $"WrapOnHorizontial:{WrapOnHorizontial}, " + $"WrapOnVertical:{WrapOnVertical}";
}
public static bool operator !=(TextureProperty left, TextureProperty right)
{
return left.mask != right.mask;
} }
public TextureFilter FilterOnMagnify public static bool operator ==(TextureProperty left, TextureProperty right)
{ {
get => mag; return left.mask == right.mask;
set => mag = value;
} }
public TextureFilter FilterOnMinify public static implicit operator TextureProperty(
{
get => min;
set => min = value;
}
public TextureWrap WrapOnHorizontial
{
get => hori;
set => hori = value;
}
public TextureWrap WrapOnVertical
{
get => vert;
set => vert = value;
}
public override bool Equals(
[NotNullWhen(true)] object obj
)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return HashCode.Combine(FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial,
WrapOnVertical);
}
public override string ToString()
{
return $"FilterOnMagnify:{FilterOnMagnify}, " + $"FilterOnMagnify:{FilterOnMagnify}, " + $"WrapOnHorizontial:{WrapOnHorizontial}, " + $"WrapOnVertical:{WrapOnVertical}";
}
public static bool operator !=(
TextureProperty left,
TextureProperty right
)
{
return left.mask != right.mask;
}
public static bool operator ==(
TextureProperty left,
TextureProperty right
)
{
return left.mask == right.mask;
}
public static implicit operator TextureProperty(
( (
TextureFilter onMagnify, TextureFilter onMinify, TextureFilter onMagnify, TextureFilter onMinify,
TextureWrap onHorizontial, TextureWrap onVertical TextureWrap onHorizontial, TextureWrap onVertical
) propertyValueTuple ) propertyValueTuple)
) {
{ return new TextureProperty(propertyValueTuple.onMagnify, propertyValueTuple.onMinify,
return new TextureProperty(propertyValueTuple.onMagnify, propertyValueTuple.onMinify, propertyValueTuple.onHorizontial, propertyValueTuple.onVertical);
propertyValueTuple.onHorizontial, }
propertyValueTuple.onVertical);
}
} }
#pragma warning disable CA1008 #pragma warning disable CA1008
public enum TextureFilter public enum TextureFilter
#pragma warning restore CA1008 #pragma warning restore CA1008
{ {
Nearest = glConst.NEAREST, Nearest = glConst.NEAREST,
Linear = glConst.LINEAR, Linear = glConst.LINEAR,
NearestLinearMipmap = glConst.NEAREST_MIPMAP_LINEAR, NearestLinearMipmap = glConst.NEAREST_MIPMAP_LINEAR,
LinearLinearMipmap = glConst.LINEAR_MIPMAP_LINEAR, LinearLinearMipmap = glConst.LINEAR_MIPMAP_LINEAR,
NearestNearestMipmap = glConst.NEAREST_MIPMAP_NEAREST, NearestNearestMipmap = glConst.NEAREST_MIPMAP_NEAREST,
LinearNearestMipmap = glConst.LINEAR_MIPMAP_NEAREST, LinearNearestMipmap = glConst.LINEAR_MIPMAP_NEAREST,
} }
#pragma warning disable CA1008 #pragma warning disable CA1008
public enum TextureUnit public enum TextureUnit
#pragma warning restore CA1008 #pragma warning restore CA1008
{ {
Unit0 = glConst.TEXTURE0, Unit0 = glConst.TEXTURE0,
Unit1 = glConst.TEXTURE1, Unit1 = glConst.TEXTURE1,
Unit2 = glConst.TEXTURE2, Unit2 = glConst.TEXTURE2,
Unit3 = glConst.TEXTURE3, Unit3 = glConst.TEXTURE3,
Unit4 = glConst.TEXTURE4, Unit4 = glConst.TEXTURE4,
Unit5 = glConst.TEXTURE5, Unit5 = glConst.TEXTURE5,
Unit6 = glConst.TEXTURE6, Unit6 = glConst.TEXTURE6,
Unit7 = glConst.TEXTURE7, Unit7 = glConst.TEXTURE7,
Unit8 = glConst.TEXTURE8, Unit8 = glConst.TEXTURE8,
Unit9 = glConst.TEXTURE9, Unit9 = glConst.TEXTURE9,
Unit10 = glConst.TEXTURE10, Unit10 = glConst.TEXTURE10,
Unit11 = glConst.TEXTURE11, Unit11 = glConst.TEXTURE11,
Unit12 = glConst.TEXTURE12, Unit12 = glConst.TEXTURE12,
Unit13 = glConst.TEXTURE13, Unit13 = glConst.TEXTURE13,
Unit14 = glConst.TEXTURE14, Unit14 = glConst.TEXTURE14,
Unit15 = glConst.TEXTURE15, Unit15 = glConst.TEXTURE15,
} }
#pragma warning disable CA1008 #pragma warning disable CA1008
public enum TextureWrap public enum TextureWrap
#pragma warning restore CA1008 #pragma warning restore CA1008
{ {
Repeat = glConst.REPEAT, Repeat = glConst.REPEAT,
MirroredRepeat = glConst.MIRRORED_REPEAT, MirroredRepeat = glConst.MIRRORED_REPEAT,
ClampToEdge = glConst.CLAMP_TO_EDGE, ClampToEdge = glConst.CLAMP_TO_EDGE,
ClampToBorder = glConst.CLAMP_TO_BORDER, ClampToBorder = glConst.CLAMP_TO_BORDER,
} }
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="TriangulatedSurface" // file="TriangulatedSurface"
// 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,7 +25,7 @@
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.Mathematics; using StgSharp.Mathematics;
using StgSharp.Mathematics.Graphics; using StgSharp.Mathematics.Graphics;
+82 -94
View File
@@ -1,99 +1,87 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="ColumnSet2" // file="ColumnSet2.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 //
// copies or substantial portions of the Software. // The above copyright notice and
// // this permission notice shall be included in all copies
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // THE SOFTWARE IS PROVIDED “AS IS”,
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// SOFTWARE. // 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.Numerics; using System;
using System.Runtime.CompilerServices; using System.Numerics;
using System.Runtime.InteropServices; using System.Runtime.CompilerServices;
using System.Text; using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Mathematics.Internal
{ namespace StgSharp.Mathematics.Internal
[StructLayout(LayoutKind.Explicit, Size = 12 * sizeof(float), Pack = 16)] {
internal struct ColumnSet2 : IEquatable<ColumnSet2> [StructLayout(LayoutKind.Explicit, Size = 12 * sizeof(float), Pack = 16)]
{ internal struct ColumnSet2 : IEquatable<ColumnSet2>
{
[FieldOffset(0 * sizeof(float))] internal float m00;
[FieldOffset(4 * sizeof(float))] internal float m01; [FieldOffset(0 * sizeof(float))] internal float m00;
[FieldOffset(1 * sizeof(float))] internal float m10; [FieldOffset(4 * sizeof(float))] internal float m01;
[FieldOffset(5 * sizeof(float))] internal float m11; [FieldOffset(1 * sizeof(float))] internal float m10;
[FieldOffset(2 * sizeof(float))] internal float m20; [FieldOffset(5 * sizeof(float))] internal float m11;
[FieldOffset(6 * sizeof(float))] internal float m21; [FieldOffset(2 * sizeof(float))] internal float m20;
[FieldOffset(3 * sizeof(float))] internal float m30; [FieldOffset(6 * sizeof(float))] internal float m21;
[FieldOffset(3 * sizeof(float))] internal float m30;
[FieldOffset(7 * sizeof(float))] internal float m31; [FieldOffset(7 * sizeof(float))] internal float m31;
[FieldOffset(0)] internal Vector4 colum0; [FieldOffset(0)] internal Vector4 colum0;
[FieldOffset(4 * sizeof(float))] internal Vector4 colum1; [FieldOffset(4 * sizeof(float))] internal Vector4 colum1;
internal ColumnSet2( internal ColumnSet2(Vector4 c0, Vector4 c1)
Vector4 c0, {
Vector4 c1 Unsafe.SkipInit(out this);
) colum0 = c0;
{ colum1 = c1;
Unsafe.SkipInit(out this); }
colum0 = c0;
colum1 = c1; [MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object? obj)
{
return (obj is ColumnSet2 mat) && Equals(mat);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(ColumnSet2 other)
{
return colum0.Equals(other.colum0) && colum1.Equals(other.colum1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(ColumnSet2 left, ColumnSet2 right)
{
return !(left == right);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals( public static bool operator ==(ColumnSet2 left, ColumnSet2 right)
object? obj {
) return left.Equals(right);
{ }
return (obj is ColumnSet2 mat) && Equals(mat);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(
ColumnSet2 other
)
{
return colum0.Equals(other.colum0) && colum1.Equals(other.colum1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(
ColumnSet2 left,
ColumnSet2 right
)
{
return !(left == right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(
ColumnSet2 left,
ColumnSet2 right
)
{
return left.Equals(right);
}
}
} }
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixKernel" // file="MatrixKernel"
// 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
@@ -30,7 +30,7 @@ using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.HighPerformance namespace StgSharp.Mathematics
{ {
public unsafe struct MatrixKernel public unsafe struct MatrixKernel
{ {
@@ -41,7 +41,7 @@ namespace StgSharp.HighPerformance
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
[InlineArray(16)] [InlineArray(16)]
public unsafe struct MatrixKernel<T> where T : unmanaged, INumber<T> public unsafe struct MatrixKernel<T> where T: unmanaged, INumber<T>
{ {
public static readonly int Size = 16 * sizeof(T); public static readonly int Size = 16 * sizeof(T);
@@ -53,19 +53,14 @@ namespace StgSharp.HighPerformance
Unsafe.SkipInit(out this); Unsafe.SkipInit(out this);
} }
public MatrixKernel( public MatrixKernel(bool clear)
bool clear
)
{ {
if (!clear) { if (!clear) {
Unsafe.SkipInit(out this); Unsafe.SkipInit(out this);
} }
} }
public ref T this[ public ref T this[int x, int y]
int x,
int y
]
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref Unsafe.Add(ref c0r0, (x * 4) + y); get => ref Unsafe.Add(ref c0r0, (x * 4) + y);
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixPanel" // file="MatrixPanel"
// Project: StgSharp // Project: StgSharp
@@ -31,7 +31,7 @@ using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.HighPerformance namespace StgSharp.Mathematics
{ {
public unsafe struct MatrixPanel public unsafe struct MatrixPanel
{ {
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="ScalarPacket" // file="ScalarPacket"
// 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
@@ -33,7 +33,7 @@ using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.HighPerformance namespace StgSharp.Mathematics
{ {
public unsafe struct ScalarPacket public unsafe struct ScalarPacket
{ {
@@ -0,0 +1,57 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="UnsafeCompute.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.Runtime.CompilerServices;
namespace StgSharp.Mathematics.Internal
{
public static class UnsafeCompute
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int CityHashSimplify(char* span, int length)
{
return NativeIntrinsic.Context.city_hash_simplify(span, length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int CityHashSimplify(char* span, int begin, int length)
{
return NativeIntrinsic.Context.city_hash_simplify(span + begin, length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int IndexOfCharPair(char* source, int pairValue, int length)
{
return NativeIntrinsic.Context.index_pair(source, pairValue, length);
}
}
}
@@ -1,50 +1,50 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="intrinsicContextProvider" // file="intrinsicContextProvider"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Mathematics.Internal; using StgSharp.Mathematics.Internal;
using System; using System;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.Mathematics.Internal namespace StgSharp.Mathematics.Internal
{ {
internal static unsafe partial class NativeIntrinsic internal static unsafe partial class NativeIntrinsic
{ {
private static readonly IntrinsicContext _intrinsicContext = new(); private static readonly IntrinsicContext _intrinsicContext = new();
public static SIMDID IntrinsicMask { get; set; } public static SIMDID IntrinsicMask { get; set; }
internal static IntrinsicContext Context internal static IntrinsicContext Context
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _intrinsicContext; get => _intrinsicContext;
} }
/* /*
@@ -74,6 +74,6 @@ namespace StgSharp.Mathematics.Internal
[LibraryImport(Native.LibName, EntryPoint = "load_intrinsic_function")] [LibraryImport(Native.LibName, EntryPoint = "load_intrinsic_function")]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
private static partial void LoadIntrinsicFunction(IntrinsicContext* context, ulong id); private static partial void LoadIntrinsicFunction(IntrinsicContext* context, ulong id);
/**/ /**/
} }
} }
+204 -239
View File
@@ -1,263 +1,228 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Matrix44" // file="Matrix44"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.Mathematics.Internal; using StgSharp.Mathematics.Intrinsic;
using StgSharp.Mathematics.Numeric; using StgSharp.Mathematics.Numeric;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.Mathematics.Graphics namespace StgSharp.Mathematics.Graphics
{ {
[StructLayout(LayoutKind.Explicit, Size = (16 * sizeof(float)), Pack = 16)] [StructLayout(LayoutKind.Explicit, Size = (16 * sizeof(float)), Pack = 16)]
public unsafe struct Matrix44 : IEquatable<Matrix44> public unsafe struct Matrix44 : IEquatable<Matrix44>
{ {
[FieldOffset(0 * sizeof(float))] internal Column column; [FieldOffset(0 * sizeof(float))] internal Column column;
[FieldOffset(0)] internal ColumnSet4 mat; [FieldOffset(0)] internal ColumnSet4 mat;
[FieldOffset(0)] internal MatrixKernel<float> kernel; [FieldOffset(0)] internal MatrixKernel<float> kernel;
internal Matrix44( internal Matrix44(ColumnSet4 mat)
ColumnSet4 mat {
) Unsafe.SkipInit(out this);
{ this.mat = mat;
Unsafe.SkipInit(out this); }
this.mat = mat;
} internal Matrix44(Vector4 vec0, Vector4 vec1, Vector4 vec2, Vector4 vec3)
{
internal Matrix44( Unsafe.SkipInit(out this);
Vector4 vec0, mat.colum0 = vec0;
Vector4 vec1, mat.colum1 = vec1;
Vector4 vec2, mat.colum2 = vec2;
Vector4 vec3 mat.colum3 = vec3;
) }
{
Unsafe.SkipInit(out this); public Matrix44()
mat.colum0 = vec0; {
mat.colum1 = vec1; Unsafe.SkipInit(out this);
mat.colum2 = vec2; }
mat.colum3 = vec3;
} public unsafe Matrix44(
float a00,
public Matrix44() float a01,
{ float a02,
Unsafe.SkipInit(out this); float a03,
} float a10,
float a11,
public unsafe Matrix44( float a12,
float a00, float a13,
float a01, float a20,
float a02, float a21,
float a03, float a22,
float a10, float a23,
float a11, float a30,
float a12, float a31,
float a13, float a32,
float a20, float a33)
float a21, {
float a22, Unsafe.SkipInit(out this);
float a23, mat.colum0 = new Vector4(a00, a10, a20, a30);
float a30, mat.colum1 = new Vector4(a01, a11, a21, a31);
float a31, mat.colum2 = new Vector4(a02, a12, a22, a32);
float a32, mat.colum3 = new Vector4(a03, a13, a23, a33);
float a33 }
)
{ public unsafe float this[int rowNum, int columNum]
Unsafe.SkipInit(out this); {
mat.colum0 = new Vector4(a00, a10, a20, a30); get
mat.colum1 = new Vector4(a01, a11, a21, a31);
mat.colum2 = new Vector4(a02, a12, a22, a32);
mat.colum3 = new Vector4(a03, a13, a23, a33);
}
public unsafe float this[
int rowNum,
int columNum
]
{
get
{ {
#if DEBUG #if DEBUG
if (rowNum is > 3 or < 0) if (rowNum is > 3 or < 0)
{ {
throw new ArgumentOutOfRangeException(nameof(columNum)); throw new ArgumentOutOfRangeException(nameof(columNum));
} }
if (columNum is > 3 or < 0) { if (columNum is > 3 or < 0) {
throw new ArgumentOutOfRangeException(nameof(columNum)); throw new ArgumentOutOfRangeException(nameof(columNum));
} }
#endif #endif
return kernel[rowNum + 4 * columNum]; return kernel[rowNum + 4 * columNum];
} }
set set
{ {
#if DEBUG #if DEBUG
if (rowNum is > 3 or < 0) if (rowNum is > 3 or < 0)
{ {
throw new ArgumentOutOfRangeException(nameof(columNum)); throw new ArgumentOutOfRangeException(nameof(columNum));
} }
if (columNum is > 3 or < 0) { if (columNum is > 3 or < 0) {
throw new ArgumentOutOfRangeException(nameof(columNum)); throw new ArgumentOutOfRangeException(nameof(columNum));
} }
#endif #endif
kernel[rowNum + 4 * columNum] = value; kernel[rowNum + 4 * columNum] = value;
} }
}
public Matrix44 Transpose
{
get
{
Matrix44 transpose = new();
InternalTranspose(ref transpose);
return transpose;
}
}
public static Matrix44 Unit => new Matrix44(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
public static Matrix44 WNegativeUnit => new Matrix44(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1);
public static Matrix44 XNegativeUnit => new Matrix44(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
public static Matrix44 YNegativeUnit => new Matrix44(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
public static Matrix44 ZNegativeUnit => new Matrix44(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1);
public ReadOnlySpan<float> AsSpan()
{
return MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As<ColumnSet4, float>(ref mat), 16);
}
public override bool Equals(object? obj)
{
return obj is Matrix44 x && Equals(x);
}
public bool Equals(Matrix44 other)
{
return mat.Equals(other.mat);
}
public override int GetHashCode()
{
return HashCode.Combine(mat.colum0.GetHashCode(), mat.colum1.GetHashCode(), mat.colum2.GetHashCode(),
mat.colum3.GetHashCode());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void InternalTranspose(ref Matrix44 transpose)
{
const int f32 = 0;
fixed (MatrixKernel<float>* source = &this.kernel, target = &transpose.kernel) {
NativeIntrinsic.Context.mat[f32].buffer_transpose(source, target);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe Matrix44 operator -(Matrix44 left, Matrix44 right)
{
Matrix44 ret = new();
const int f32 = 0;
NativeIntrinsic.Context.mat[f32].buffer_sub(&left, &right, &ret, 1);
return ret;
} }
public Matrix44 Transpose public static bool operator !=(Matrix44 left, Matrix44 right)
{ {
get return !(left == right);
{
Matrix44 transpose = new();
InternalTranspose(ref transpose);
return transpose;
}
} }
public static Matrix44 Unit => new Matrix44(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe Matrix44 operator *(Matrix44 mat, float value)
public static Matrix44 WNegativeUnit => new Matrix44(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1); {
return new Matrix44(mat.mat.colum0 * value, mat.mat.colum1 * value, mat.mat.colum2 * value,
public static Matrix44 XNegativeUnit => new Matrix44(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); mat.mat.colum3 * value);
public static Matrix44 YNegativeUnit => new Matrix44(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
public static Matrix44 ZNegativeUnit => new Matrix44(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1);
public ReadOnlySpan<float> AsSpan()
{
return MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As<ColumnSet4, float>(ref mat), 16);
} }
public override bool Equals( [MethodImpl(MethodImplOptions.AggressiveInlining)]
object? obj public static Matrix44 operator *(Matrix44 left, Matrix44 right)
) {
{ Matrix44 ret = new();
return obj is Matrix44 x && Equals(x); int f32 = (int)MatrixElementType.F32;
NativeIntrinsic.Context.mat[f32].kernel_fma(&left, &right, &ret);
return ret;
} }
public bool Equals( [MethodImpl(MethodImplOptions.AggressiveInlining)]
Matrix44 other public static unsafe Matrix44 operator +(Matrix44 left, Matrix44 right)
) {
{ Matrix44 ret = new();
return mat.Equals(other.mat); const int f32 = 0;
NativeIntrinsic.Context.mat[f32].buffer_add(&left, &right, &ret, 1);
return ret;
} }
public override int GetHashCode() public static bool operator ==(Matrix44 left, Matrix44 right)
{ {
return HashCode.Combine(mat.colum0.GetHashCode(), mat.colum1.GetHashCode(), return left.Equals(right);
mat.colum2.GetHashCode(), mat.colum3.GetHashCode());
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [InlineArray(4)]
internal unsafe void InternalTranspose( internal struct Column
ref Matrix44 transpose {
)
{ private Vec4 value;
const int f32 = 0;
fixed (MatrixKernel<float>* source = &this.kernel, target = &transpose.kernel) { }
NativeIntrinsic.Context.mat[f32].buffer_transpose(source, target);
} }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe Matrix44 operator -(
Matrix44 left,
Matrix44 right
)
{
Matrix44 ret = new();
const int f32 = 0;
NativeIntrinsic.Context.mat[f32].buffer_sub(&left, &right, &ret, 1);
return ret;
}
public static bool operator !=(
Matrix44 left,
Matrix44 right
)
{
return !(left == right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe Matrix44 operator *(
Matrix44 mat,
float value
)
{
return new Matrix44(mat.mat.colum0 * value, mat.mat.colum1 * value,
mat.mat.colum2 * value, mat.mat.colum3 * value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Matrix44 operator *(
Matrix44 left,
Matrix44 right
)
{
Matrix44 ret = new();
int f32 = (int)MatrixElementType.F32;
NativeIntrinsic.Context.mat[f32].kernel_fma(&left, &right, &ret);
return ret;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe Matrix44 operator +(
Matrix44 left,
Matrix44 right
)
{
Matrix44 ret = new();
const int f32 = 0;
NativeIntrinsic.Context.mat[f32].buffer_add(&left, &right, &ret, 1);
return ret;
}
public static bool operator ==(
Matrix44 left,
Matrix44 right
)
{
return left.Equals(right);
}
[InlineArray(4)]
internal struct Column
{
private Vec4 value;
}
}
} }
+141 -141
View File
@@ -1,162 +1,162 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Vec2" // file="Vec2"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.Mathematics.Numeric; using StgSharp.Mathematics.Numeric;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.Mathematics.Graphics namespace StgSharp.Mathematics.Graphics
{ {
/// <summary> /// <summary>
/// A two dimension vector defined by two elements. Vec2 in World are default used as colum /// A two dimension vector defined by two elements. Vec2 in World are default used as colum
/// vector. /// vector.
/// </summary> /// </summary>
[StructLayout(LayoutKind.Explicit, Size = 16, Pack = 16)] [StructLayout(LayoutKind.Explicit, Size = 16, Pack = 16)]
public struct Vec2 : IUnmanagedVector<Vec2> public struct Vec2 : IUnmanagedVector<Vec2>
{ {
[FieldOffset(0)] internal unsafe fixed float num[2]; [FieldOffset(0)] internal unsafe fixed float num[2];
[FieldOffset(0)] [FieldOffset(0)]
internal M128 reg; internal M128 reg;
[FieldOffset(0)] [FieldOffset(0)]
internal Vector2 v; internal Vector2 v;
[FieldOffset(0)] [FieldOffset(0)]
public float X; public float X;
[FieldOffset(4)] [FieldOffset(4)]
public float Y; public float Y;
internal Vec2(Vector2 vec) internal Vec2(Vector2 vec)
{ {
Unsafe.SkipInit(out reg); Unsafe.SkipInit(out reg);
Unsafe.SkipInit(out X); Unsafe.SkipInit(out X);
Unsafe.SkipInit(out Y); Unsafe.SkipInit(out Y);
v = vec; v = vec;
}
internal Vec2(M128 vec)
{
Unsafe.SkipInit(out reg);
Unsafe.SkipInit(out X);
Unsafe.SkipInit(out Y);
reg = vec;
reg.Member<ulong>(1) = 0;
}
public Vec2(float x, float y)
{
v = new Vector2(x, y);
}
public static Vec2 Unit => new Vec2(1, 1);
public static Vec2 Zero => new Vec2(0, 0);
public static Vec2 One
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new Vec2(1, 1);
}
public Vec2 XY
{
readonly get => this;
set => this = value;
}
public Vec3 XYZ
{
readonly get => new(reg);
set
{
reg = value.reg;
reg.Member<ulong>(1) = 0;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Cross(Vec2 right)
{
return X * right.Y - Y * right.X;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Dot(Vec2 vec)
{
return Vector2.Dot(v, vec.v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec2 operator -(Vec2 left, Vec2 right)
{
return new Vec2(left.v - right.v);
} }
internal Vec2(M128 vec) public static bool operator !=(Vec2 left, Vec2 right)
{ {
Unsafe.SkipInit(out reg); return !(left == right);
Unsafe.SkipInit(out X);
Unsafe.SkipInit(out Y);
reg = vec;
reg.Member<ulong>(1) = 0;
} }
public Vec2(float x, float y) public static Vec2 operator *(Vec2 vec, float value)
{ {
v = new Vector2(x, y); return new Vec2(vec.v * value);
}
public static Vec2 operator *(float value, Vec2 vec)
{
return new Vec2(vec.v * value);
} }
public static Vec2 Unit => new Vec2(1, 1); public static Vec2 operator /(Vec2 vec, float value)
{
public static Vec2 Zero => new Vec2(0, 0); return new Vec2(vec.v / value);
public static Vec2 One
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new Vec2(1, 1);
} }
public Vec2 XY [MethodImpl(MethodImplOptions.AggressiveInlining)]
{ public static Vec2 operator +(Vec2 left, Vec2 right)
readonly get => this; {
set => this = value; return new Vec2(left.v + right.v);
} }
public Vec3 XYZ [MethodImpl(MethodImplOptions.AggressiveInlining)]
{ public static bool operator ==(Vec2 left, Vec2 right)
readonly get => new(reg); {
set return left.v == right.v;
{
reg = value.reg;
reg.Member<ulong>(1) = 0;
}
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Cross(Vec2 right) public static implicit operator Vec2((float, float) tuple)
{ {
return X * right.Y - Y * right.X; return new Vec2(tuple.Item1, tuple.Item2);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] }
public float Dot(Vec2 vec)
{
return Vector2.Dot(v, vec.v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec2 operator -(Vec2 left, Vec2 right)
{
return new Vec2(left.v - right.v);
}
public static bool operator !=(Vec2 left, Vec2 right)
{
return !(left == right);
}
public static Vec2 operator *(Vec2 vec, float value)
{
return new Vec2(vec.v * value);
}
public static Vec2 operator *(float value, Vec2 vec)
{
return new Vec2(vec.v * value);
}
public static Vec2 operator /(Vec2 vec, float value)
{
return new Vec2(vec.v / value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec2 operator +(Vec2 left, Vec2 right)
{
return new Vec2(left.v + right.v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vec2 left, Vec2 right)
{
return left.v == right.v;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Vec2((float, float) tuple)
{
return new Vec2(tuple.Item1, tuple.Item2);
}
}
} }
+215 -267
View File
@@ -1,288 +1,236 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Vec3" // file="Vec3"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.Mathematics.Numeric; using StgSharp.Mathematics.Numeric;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.Mathematics.Graphics namespace StgSharp.Mathematics.Graphics
{ {
[CollectionBuilder(typeof(Vec3), nameof(FromSpan))] [CollectionBuilder(typeof(Vec3), nameof(FromSpan))]
[StructLayout(LayoutKind.Explicit, Size = 16, Pack = 16)] [StructLayout(LayoutKind.Explicit, Size = 16, Pack = 16)]
public struct Vec3 : IEquatable<Vec3>, IUnmanagedVector<Vec3>, IEnumerable<float> public struct Vec3 : IEquatable<Vec3>, IUnmanagedVector<Vec3>, IEnumerable<float>
{ {
[FieldOffset(0)] internal unsafe fixed float num[3]; [FieldOffset(0)] internal unsafe fixed float num[3];
[FieldOffset(0)] internal M128 reg; [FieldOffset(0)] internal M128 reg;
[FieldOffset(0)] internal Vector3 v; [FieldOffset(0)] internal Vector3 v;
[FieldOffset(0)] public float X; [FieldOffset(0)] public float X;
[FieldOffset(4)] public float Y; [FieldOffset(4)] public float Y;
[FieldOffset(8)] public float Z; [FieldOffset(8)] public float Z;
internal Vec3( internal Vec3(M128 vector)
M128 vector {
) Unsafe.SkipInit(out this);
{ reg = vector;
Unsafe.SkipInit(out this); reg.Member<uint>(3) = 0;
reg = vector; }
reg.Member<uint>(3) = 0;
internal Vec3(Vector3 vector)
{
v = vector;
}
public Vec3()
{
Unsafe.SkipInit(out this);
}
public Vec3(Vec2 xy, float z)
{
Unsafe.SkipInit(out this);
reg = xy.reg;
Z = z;
}
public Vec3(float x, float y, float z)
{
Unsafe.SkipInit(out this);
v = new Vector3(x, y, z);
}
public unsafe Vec2 XY
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => new(reg);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<Vector3, Vector2>(ref v) = value.v;
}
public Vec3 XYZ
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => new(v);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => this = value;
}
public static Vec3 Zero => new(0, 0, 0);
public static Vec3 One => new(1, 1, 1);
public static Vec3 UnitX => new(1, 0, 0);
public static Vec3 UnitY => new(0, 1, 0);
public static Vec3 UnitZ => new(0, 0, 1);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 Cross(Vec3 left, Vec3 right)
{
return Linear.Cross(left, right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float Dot(Vec3 right)
{
return Vector3.Dot(v, right.v);
}
public readonly bool Equals(Vec3 other)
{
return reg == other.reg;
}
public override readonly bool Equals(object obj)
{
return obj is not null && obj is Vec3 vec && this == vec;
}
public static Vec3 FromSpan(ReadOnlySpan<float> span)
{
Vec3 v = new();
span.CopyTo(MemoryMarshal.CreateSpan(ref v.X, 3));
return v;
}
public unsafe IEnumerator<float> GetEnumerator()
{
for (int i = 0; i < 3; i++) {
yield return reg.Member<float>(i);
}
}
public override unsafe int GetHashCode()
{
fixed (float* add = &X) {
return HashCode.Combine(X, Y, Z, (ulong)add);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float GetMaxValue()
{
float ret = X;
ret = ret > Y ? ret : Y;
ret = ret > Z ? ret : Z;
return ret;
}
public static bool IsParallel(Vec3 left, Vec3 right)
{
return Cross(left, right) == Zero;
}
public override readonly string ToString()
{
return $"[{X},{Y},{Z}]";
}
public readonly string ToString(string sample)
{
return $"[{X.ToString(sample)},{Y.ToString(sample)},{Z.ToString(sample)}]";
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 operator -(Vec3 vec)
{
return new Vec3(-vec.v);
} }
internal Vec3( [MethodImpl(MethodImplOptions.AggressiveInlining)]
Vector3 vector public static Vec3 operator -(Vec3 left, Vec3 right)
) {
{ return new Vec3(left.v - right.v);
v = vector;
} }
public Vec3() [MethodImpl(MethodImplOptions.AggressiveInlining)]
{ public static bool operator !=(Vec3 left, Vec3 right)
Unsafe.SkipInit(out this); {
return left.v != right.v;
} }
public Vec3( [MethodImpl(MethodImplOptions.AggressiveInlining)]
Vec2 xy, public static Vec3 operator *(Vec3 vec, float value)
float z {
) return new Vec3(vec.v * value);
{
Unsafe.SkipInit(out this);
reg = xy.reg;
Z = z;
} }
public Vec3( [MethodImpl(MethodImplOptions.AggressiveInlining)]
float x, public static float operator *(Vec3 left, Vec3 right)
float y, {
float z return Vector3.Dot(left.v, right.v);
)
{
Unsafe.SkipInit(out this);
v = new Vector3(x, y, z);
} }
public unsafe Vec2 XY [MethodImpl(MethodImplOptions.AggressiveInlining)]
{ public static Vec3 operator /(Vec3 vec, float value)
[MethodImpl(MethodImplOptions.AggressiveInlining)] {
readonly get => new(reg); return new Vec3(vec.v / value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<Vector3, Vector2>(ref v) = value.v;
} }
public Vec3 XYZ [MethodImpl(MethodImplOptions.AggressiveInlining)]
{ public static Vec3 operator +(Vec3 left, Vec3 right)
[MethodImpl(MethodImplOptions.AggressiveInlining)] {
readonly get => new(v); return new Vec3(left.v + right.v);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => this = value;
} }
public static Vec3 Zero => new(0, 0, 0); [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vec3 left, Vec3 right)
public static Vec3 One => new(1, 1, 1); {
return left.v == right.v;
public static Vec3 UnitX => new(1, 0, 0);
public static Vec3 UnitY => new(0, 1, 0);
public static Vec3 UnitZ => new(0, 0, 1);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 Cross(
Vec3 left,
Vec3 right
)
{
return Linear.Cross(left, right);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float Dot( public static unsafe implicit operator Vec3((float, float, float) tuple)
Vec3 right {
) return Unsafe.As<(float,float,float), Vec3>(ref tuple);
{ }
return Vector3.Dot(v, right.v);
} IEnumerator IEnumerable.GetEnumerator()
{
public readonly bool Equals( return GetEnumerator();
Vec3 other }
)
{ }
return reg == other.reg;
}
public override readonly bool Equals(
object obj
)
{
return obj is not null && obj is Vec3 vec && this == vec;
}
public static Vec3 FromSpan(
ReadOnlySpan<float> span
)
{
Vec3 v = new();
span.CopyTo(MemoryMarshal.CreateSpan(ref v.X, 3));
return v;
}
public unsafe IEnumerator<float> GetEnumerator()
{
for (int i = 0; i < 3; i++) {
yield return reg.Member<float>(i);
}
}
public override unsafe int GetHashCode()
{
fixed (float* add = &X) {
return HashCode.Combine(X, Y, Z, (ulong)add);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float GetMaxValue()
{
float ret = X;
ret = ret > Y ? ret : Y;
ret = ret > Z ? ret : Z;
return ret;
}
public static bool IsParallel(
Vec3 left,
Vec3 right
)
{
return Cross(left, right) == Zero;
}
public override readonly string ToString()
{
return $"[{X},{Y},{Z}]";
}
public readonly string ToString(
string sample
)
{
return $"[{X.ToString(sample)},{Y.ToString(sample)},{Z.ToString(sample)}]";
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 operator -(
Vec3 vec
)
{
return new Vec3(-vec.v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 operator -(
Vec3 left,
Vec3 right
)
{
return new Vec3(left.v - right.v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(
Vec3 left,
Vec3 right
)
{
return left.v != right.v;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 operator *(
Vec3 vec,
float value
)
{
return new Vec3(vec.v * value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float operator *(
Vec3 left,
Vec3 right
)
{
return Vector3.Dot(left.v, right.v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 operator /(
Vec3 vec,
float value
)
{
return new Vec3(vec.v / value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 operator +(
Vec3 left,
Vec3 right
)
{
return new Vec3(left.v + right.v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(
Vec3 left,
Vec3 right
)
{
return left.v == right.v;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe implicit operator Vec3(
(float, float, float) tuple
)
{
return Unsafe.As<(float,float,float), Vec3>(ref tuple);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} }
+188 -229
View File
@@ -1,251 +1,210 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Vec4" // file="Vec4"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.Mathematics.Internal; using StgSharp.Mathematics.Intrinsic;
using StgSharp.Mathematics.Numeric; using StgSharp.Mathematics.Numeric;
using System; using System;
using System.Data.Common; using System.Data.Common;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StgSharp.Mathematics.Graphics namespace StgSharp.Mathematics.Graphics
{ {
[CollectionBuilder(builderType:typeof(Vec4), methodName: nameof(Vec4.FromSpan))] [CollectionBuilder(builderType:typeof(Vec4), methodName: nameof(Vec4.FromSpan))]
[StructLayout(LayoutKind.Explicit, Size = 16, Pack = 16)] [StructLayout(LayoutKind.Explicit, Size = 16, Pack = 16)]
public unsafe struct Vec4 : IEquatable<Vec4>, IUnmanagedVector<Vec4> public unsafe struct Vec4 : IEquatable<Vec4>, IUnmanagedVector<Vec4>
{ {
[FieldOffset(0)] internal unsafe fixed float num[4]; [FieldOffset(0)] internal unsafe fixed float num[4];
[FieldOffset(0)] internal M128 reg; [FieldOffset(0)] internal M128 reg;
[FieldOffset(0)] internal Vector4 vec; [FieldOffset(0)] internal Vector4 vec;
[FieldOffset(12)] public float W; [FieldOffset(12)] public float W;
[FieldOffset(0)] public float X; [FieldOffset(0)] public float X;
[FieldOffset(4)] public float Y; [FieldOffset(4)] public float Y;
[FieldOffset(8)] public float Z; [FieldOffset(8)] public float Z;
internal Vec4( internal Vec4(Vector4 v)
Vector4 v {
) Unsafe.SkipInit(out X);
{ Unsafe.SkipInit(out Y);
Unsafe.SkipInit(out X); Unsafe.SkipInit(out Z);
Unsafe.SkipInit(out Y); Unsafe.SkipInit(out W);
Unsafe.SkipInit(out Z);
Unsafe.SkipInit(out W);
Unsafe.SkipInit(out reg); Unsafe.SkipInit(out reg);
vec = v; vec = v;
} }
internal Vec4( internal Vec4(M128 v)
M128 v {
) Unsafe.SkipInit(out X);
{ Unsafe.SkipInit(out Y);
Unsafe.SkipInit(out X); Unsafe.SkipInit(out Z);
Unsafe.SkipInit(out Y); Unsafe.SkipInit(out W);
Unsafe.SkipInit(out Z);
Unsafe.SkipInit(out W);
Unsafe.SkipInit(out vec); Unsafe.SkipInit(out vec);
reg = v; reg = v;
} }
public Vec4( public Vec4(Vec3 v3, float w)
Vec3 v3, {
float w Unsafe.SkipInit(out X);
) Unsafe.SkipInit(out Y);
{ Unsafe.SkipInit(out Z);
Unsafe.SkipInit(out X); Unsafe.SkipInit(out W);
Unsafe.SkipInit(out Y); reg = v3.reg;
Unsafe.SkipInit(out Z); W = w;
Unsafe.SkipInit(out W); }
reg = v3.reg;
W = w; public Vec4(float x, float y, float z, float w)
} {
vec = new Vector4(x, y, z, w);
public Vec4( }
float x,
float y, public unsafe Vec2 XY
float z, {
float w get => new Vec2(reg);
) set
{ {
vec = new Vector4(x, y, z, w); X = value.X;
} Y = value.Y;
}
public unsafe Vec2 XY }
{
get => new Vec2(reg); public unsafe Vec3 XYZ
set {
{ get => new Vec3(reg);
X = value.X; set
Y = value.Y; {
} float w = W;
} reg = value.reg;
W = w;
public unsafe Vec3 XYZ }
{ }
get => new Vec3(reg);
set public static Vec4 One
{ {
float w = W; [MethodImpl(MethodImplOptions.AggressiveInlining)]
reg = value.reg; get => new Vec4(1, 1, 1, 1);
W = w; }
}
} public static Vec4 Zero
{
public static Vec4 One [MethodImpl(MethodImplOptions.AggressiveInlining)]
{ get => new Vec4(0, 0, 0, 0);
[MethodImpl(MethodImplOptions.AggressiveInlining)] }
get => new Vec4(1, 1, 1, 1);
} [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec4 Add(Vec4 left, Vec4 right)
public static Vec4 Zero {
{ return left + right;
[MethodImpl(MethodImplOptions.AggressiveInlining)] }
get => new Vec4(0, 0, 0, 0);
} public ReadOnlySpan<float> AsSpan()
{
[MethodImpl(MethodImplOptions.AggressiveInlining)] return MemoryMarshal.CreateReadOnlySpan(ref reg.Member<float>(0), 4);
public static Vec4 Add( }
Vec4 left,
Vec4 right public override bool Equals(object obj)
) {
{ return obj is Vec4 v && v == this;
return left + right; }
}
public static Vec4 FromSpan(ReadOnlySpan<float> span)
public ReadOnlySpan<float> AsSpan() {
{ if (span.Length < 4) {
return MemoryMarshal.CreateReadOnlySpan(ref reg.Member<float>(0), 4); throw new ArgumentException("Span length must be at least 4.", nameof(span));
}
public override bool Equals(
object obj
)
{
return obj is Vec4 v && v == this;
}
public static Vec4 FromSpan(
ReadOnlySpan<float> span
)
{
if (span.Length < 4) {
throw new ArgumentException("Span length must be at least 4.", nameof(span));
} }
// Read 4 floats as a Vector4 in one operation without per-element copy. // Read 4 floats as a Vector4 in one operation without per-element copy.
Vector4 v = MemoryMarshal.Read<Vector4>(MemoryMarshal.AsBytes(span)); Vector4 v = MemoryMarshal.Read<Vector4>(MemoryMarshal.AsBytes(span));
return new Vec4(v); return new Vec4(v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<float>.Enumerator GetEnumerator()
{
return AsSpan().GetEnumerator();
}
public override int GetHashCode()
{
return vec.GetHashCode();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec4 Subtract(Vec4 left, Vec4 right)
{
return left - right;
}
public override string ToString()
{
return vec.ToString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec4 operator -(Vec4 left, Vec4 right)
{
return new Vec4(left.vec - right.vec);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vec4 left, Vec4 right)
public ReadOnlySpan<float>.Enumerator GetEnumerator() {
{ return !(left == right);
return AsSpan().GetEnumerator();
} }
public override int GetHashCode() [MethodImpl(MethodImplOptions.AggressiveInlining)]
{ public static Vec4 operator *(Matrix44 mat, Vec4 vec)
return vec.GetHashCode(); {
Matrix44 transpose = mat.Transpose;
return new Vec4(Vector4.Dot(transpose.mat.colum0, vec.vec), Vector4.Dot(transpose.mat.colum1, vec.vec),
Vector4.Dot(transpose.mat.colum2, vec.vec), Vector4.Dot(transpose.mat.colum3, vec.vec));
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec4 Subtract( public static Vec4 operator +(Vec4 left, Vec4 right)
Vec4 left, {
Vec4 right return new Vec4(left.vec + right.vec);
)
{
return left - right;
} }
public override string ToString() public static bool operator ==(Vec4 left, Vec4 right)
{ {
return vec.ToString(); return left.vec == right.vec;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] bool IEquatable<Vec4>.Equals(Vec4 other)
public static Vec4 operator -( {
Vec4 left, return vec == other.vec;
Vec4 right }
)
{ }
return new Vec4(left.vec - right.vec);
}
public static bool operator !=(
Vec4 left,
Vec4 right
)
{
return !(left == right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec4 operator *(
Matrix44 mat,
Vec4 vec
)
{
Matrix44 transpose = mat.Transpose;
return new Vec4(Vector4.Dot(transpose.mat.colum0, vec.vec),
Vector4.Dot(transpose.mat.colum1, vec.vec),
Vector4.Dot(transpose.mat.colum2, vec.vec),
Vector4.Dot(transpose.mat.colum3, vec.vec));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec4 operator +(
Vec4 left,
Vec4 right
)
{
return new Vec4(left.vec + right.vec);
}
public static bool operator ==(
Vec4 left,
Vec4 right
)
{
return left.vec == right.vec;
}
bool IEquatable<Vec4>.Equals(
Vec4 other
)
{
return vec == other.vec;
}
}
} }
@@ -1,101 +1,101 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Matrix.Create" // file="Matrix.Create"
// 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 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
public unsafe partial class Matrix<T> public unsafe partial class Matrix<T>
{ {
private const int KernelSideLength = 4; private const int KernelSideLength = 4;
public static Matrix<T> Create( public static Matrix<T> Create(
int columnLength, int columnLength,
int rowLength, int rowLength,
MatrixLayout layout, MatrixLayout layout,
HybridLayerSegregatedFitAllocator allocator) HybridLayerSegregatedFitAllocator allocator)
{ {
ArgumentNullException.ThrowIfNull(allocator); ArgumentNullException.ThrowIfNull(allocator);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(columnLength); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(columnLength);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(rowLength); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(rowLength);
int kernelColumns = DivideRoundUp(columnLength, KernelSideLength); int kernelColumns = DivideRoundUp(columnLength, KernelSideLength);
int kernelRows = DivideRoundUp(rowLength, KernelSideLength); int kernelRows = DivideRoundUp(rowLength, KernelSideLength);
if (layout is MatrixLayout.UpperTriangle or MatrixLayout.LowerTriangle) if (layout is MatrixLayout.UpperTriangle or MatrixLayout.LowerTriangle)
{ {
if (kernelColumns != kernelRows) { if (kernelColumns != kernelRows) {
throw new ArgumentException("Triangular layouts require square matrices."); throw new ArgumentException("Triangular layouts require square matrices.");
} }
} }
long kernelCount = layout switch long kernelCount = layout switch
{ {
MatrixLayout.DenseRectangle => (long)kernelColumns * kernelRows, MatrixLayout.DenseRectangle => (long)kernelColumns * kernelRows,
MatrixLayout.UpperTriangle => TriangularKernelCount(kernelColumns), MatrixLayout.UpperTriangle => TriangularKernelCount(kernelColumns),
MatrixLayout.LowerTriangle => TriangularKernelCount(kernelRows), MatrixLayout.LowerTriangle => TriangularKernelCount(kernelRows),
_ => throw new ArgumentOutOfRangeException(nameof(layout)) _ => throw new ArgumentOutOfRangeException(nameof(layout))
}; };
long requiredBytes = kernelCount * MatrixKernel<T>.Size; long requiredBytes = kernelCount * MatrixKernel<T>.Size;
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(requiredBytes, nameof(requiredBytes)); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(requiredBytes, nameof(requiredBytes));
HybridLayerSegregatedFitAllocationHandle handle = allocator.Alloc((uint)requiredBytes); HybridLayerSegregatedFitAllocationHandle handle = allocator.Alloc((uint)requiredBytes);
MatrixStorageHLSF<T> storage = new MatrixStorageHLSF<T>(allocator, handle); MatrixStorageHLSF<T> storage = new MatrixStorageHLSF<T>(allocator, handle);
Matrix<T> matrix = new Matrix<T>(MatrixKernelBoarder.Create(layout), new MatrixSize(columnLength, rowLength, Matrix<T> matrix = new Matrix<T>(MatrixKernelBoarder.Create(layout), new MatrixSize(columnLength, rowLength,
kernelColumns, kernelColumns,
kernelRows), storage); kernelRows), storage);
return matrix; return matrix;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int DivideRoundUp(int value, int divisor) private static int DivideRoundUp(int value, int divisor)
{ {
return (value + (divisor - 1)) / divisor; return (value + (divisor - 1)) / divisor;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static long TriangularKernelCount(int order) private static long TriangularKernelCount(int order)
{ {
long n = order; long n = order;
return (n * (n + 1L)) / 2L; return (n * (n + 1L)) / 2L;
} }
} }
} }
+153 -174
View File
@@ -1,204 +1,183 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Matrix" // file="Matrix"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.Mathematics.Numeric; using StgSharp.Mathematics.Numeric;
using System; using System;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
// using hlsfHandle = global::StgSharp.HighPerformance.Memory.HybridLayerSegregatedFitAllocationHandle; // using hlsfHandle = global::StgSharp.HighPerformance.Memory.HybridLayerSegregatedFitAllocationHandle;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
public unsafe partial class Matrix<T> where T : unmanaged, INumber<T> public unsafe partial class Matrix<T> where T: unmanaged, INumber<T>
{ {
private protected static readonly int t_count = 16 / sizeof(T); private protected static readonly int t_count = 16 / sizeof(T);
private protected static readonly int t_size = sizeof(T); private protected static readonly int t_size = sizeof(T);
private readonly MatrixKernelBoarder _boarder; private readonly MatrixKernelBoarder _boarder;
private readonly MatrixSize _size; private readonly MatrixSize _size;
private readonly MatrixStorage<T> _buffer; private readonly MatrixStorage<T> _buffer;
private protected Matrix( private protected Matrix(
MatrixKernelBoarder boarder, MatrixKernelBoarder boarder,
MatrixSize size, MatrixSize size,
MatrixStorage<T> buffer MatrixStorage<T> buffer
) )
{ {
_boarder = boarder; _boarder = boarder;
_size = size; _size = size;
_buffer = buffer; _buffer = buffer;
}
public T this[int x, int y]
{
get
{
if (y < 0 || y > _size.ElementColumnLength || x < 0 || x > _size.ElementRowLength) {
throw new ArgumentOutOfRangeException($"Index [{x},{y}] is out of matrix index range.");
}
long offset = GetElementOffset(x, y);
if (offset < 0) {
return T.Zero;
}
return ((T*)Buffer)[offset];
}
set
{
if (y < 0 || y > _size.ElementColumnLength || x < 0 || x > _size.ElementRowLength) {
throw new ArgumentOutOfRangeException($"Index [{x},{y}] is out of matrix index range.");
}
long offset = GetElementOffset(x, y);
if (offset < 0) {
return;
}
((T*)Buffer)[offset] = value;
}
} }
public T this[ /// <summary>
int x, /// Matlab style indexer to generate a new matrix
int y
]
{
get
{
if (y < 0 || y > _size.ElementColumnLength || x < 0 || x > _size.ElementRowLength) {
throw new ArgumentOutOfRangeException($"Index [{x},{y}] is out of matrix index range.");
}
long offset = GetElementOffset(x, y);
if (offset < 0) {
return T.Zero;
}
return ((T*)Buffer)[offset];
}
set
{
if (y < 0 || y > _size.ElementColumnLength || x < 0 || x > _size.ElementRowLength) {
throw new ArgumentOutOfRangeException($"Index [{x},{y}] is out of matrix index range.");
}
long offset = GetElementOffset(x, y);
if (offset < 0) {
return;
}
((T*)Buffer)[offset] = value;
}
}
/// <summary>
/// Matlab style indexer to generate a new matrix
/// </summary> /// </summary>
/// <param name="column"> /// <param name="column">
/// ///
/// </param> /// </param>
/// <param name="row"> /// <param name="row">
/// ///
/// </param> /// </param>
/// <returns> /// <returns>
/// ///
/// </returns> /// </returns>
/// <exception cref="NotImplementedException"> /// <exception cref="NotImplementedException">
/// ///
/// </exception> /// </exception>
public unsafe Matrix<T> this[ public unsafe Matrix<T> this[ReadOnlySpan<MatrixIndex> column, ReadOnlySpan<MatrixIndex> row]
ReadOnlySpan<MatrixIndex> column, {
ReadOnlySpan<MatrixIndex> row get { throw new NotImplementedException(); }
] set { throw new NotImplementedException(); }
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
} }
/// <summary> /// <summary>
/// Length of the matrix in columns. /// Length of the matrix in columns.
/// </summary> /// </summary>
public int ColumnLength => _size.ElementColumnLength; public int ColumnLength => _size.ElementColumnLength;
/// <summary> /// <summary>
/// Length of the matrix in rows. /// Length of the matrix in rows.
/// </summary> /// </summary>
public int RowLength => _size.ElementRowLength; public int RowLength => _size.ElementRowLength;
public MatrixLayout Layout { get; init; } public MatrixLayout Layout { get; init; }
internal MatrixKernel<T>* Buffer internal MatrixKernel<T>* Buffer
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (MatrixKernel<T>*)_buffer.BufferPointer; get => (MatrixKernel<T>*)_buffer.BufferPointer;
} }
protected internal int KernelColumnLength => _size.KernelColumnLength; protected internal int KernelColumnLength => _size.KernelColumnLength;
protected internal int KernelRowLength => _size.KernelRowLength; protected internal int KernelRowLength => _size.KernelRowLength;
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe ref MatrixKernel<T> GetMatrixKernel( public unsafe ref MatrixKernel<T> GetMatrixKernel(int x, int y)
int x, {
int y return ref _boarder.IsInBuffer(x, y, in _size) ?
) ref _buffer[_boarder.GetIndexOffset(x, y, in _size)] :
{ ref Unsafe.NullRef<MatrixKernel<T>>();
return ref _boarder.IsInBuffer(x, y, in _size) ? }
ref _buffer[_boarder.GetIndexOffset(x, y, in _size)] :
ref Unsafe.NullRef<MatrixKernel<T>>(); internal long GetElementOffset(int x, int y)
} {
internal long GetElementOffset(
int x,
int y
)
{
int int
k_c = y / 4, k_c = y / 4,
c = y % 4, c = y % 4,
k_r = x / 4, k_r = x / 4,
r = x % 4; r = x % 4;
if (!_boarder.IsInBuffer(k_r, k_c, in _size)) { if (!_boarder.IsInBuffer(k_r, k_c, in _size)) {
return -1; return -1;
} }
long kernelOffset = _boarder.GetIndexOffset(k_r, k_c, in _size); long kernelOffset = _boarder.GetIndexOffset(k_r, k_c, in _size);
return kernelOffset * 16 + 4 * r + c; return kernelOffset * 16 + 4 * r + c;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe ref T GetElementUnsafe( internal unsafe ref T GetElementUnsafe(int x, int y)
int x, {
int y // Caller guarantees: indices in range, layout is dense square.
) int k_c = y / 4;
{ int k_r = x / 4;
// Caller guarantees: indices in range, layout is dense square. int c = y % 4;
int k_c = y / 4;
int k_r = x / 4;
int c = y % 4;
int r = x % 4; int r = x % 4;
ref MatrixKernel<T> kernel = ref _buffer[_boarder.GetIndexOffset(k_r, k_c, in _size)]; ref MatrixKernel<T> kernel = ref _buffer[_boarder.GetIndexOffset(k_r, k_c, in _size)];
return ref kernel[c, r]; return ref kernel[c, r];
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe MatrixKernel<T>* GetKernelAddressUnsafe( internal unsafe MatrixKernel<T>* GetKernelAddressUnsafe(int x, int y)
int x, {
int y return Buffer + _boarder.GetIndexOffset(x, y, in _size);
) }
{
return Buffer + _boarder.GetIndexOffset(x, y, in _size); [MethodImpl(MethodImplOptions.AggressiveInlining)]
} internal unsafe ref MatrixKernel<T> GetKernelUnsafe(int x, int y)
{
[MethodImpl(MethodImplOptions.AggressiveInlining)] // Caller guarantees: indices in range, layout is dense square.
internal unsafe ref MatrixKernel<T> GetKernelUnsafe( int k_c = y / 4;
int x, int k_r = x / 4;
int y int c = y % 4;
) int r = x % 4;
{ return ref _buffer[_boarder.GetIndexOffset(k_c, k_r, in _size)];
// Caller guarantees: indices in range, layout is dense square. }
int k_c = y / 4;
int k_r = x / 4; }
int c = y % 4;
int r = x % 4;
return ref _buffer[_boarder.GetIndexOffset(k_c, k_r, in _size)];
}
}
} }
@@ -1,72 +1,72 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixStorage" // file="MatrixStorage"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using HLSFAllocator = global::StgSharp.HighPerformance.Memory.HybridLayerSegregatedFitAllocator; using HLSFAllocator = global::StgSharp.Mathematics.Memory.HybridLayerSegregatedFitAllocator;
using HLSFHandle = global::StgSharp.HighPerformance.Memory.HybridLayerSegregatedFitAllocationHandle; using HLSFHandle = global::StgSharp.Mathematics.Memory.HybridLayerSegregatedFitAllocationHandle;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
public abstract class MatrixStorage<T> : IDisposable where T : unmanaged, INumber<T> public abstract class MatrixStorage<T> : IDisposable where T: unmanaged, INumber<T>
{ {
internal unsafe ref MatrixKernel<T> this[long index] internal unsafe ref MatrixKernel<T> this[long index]
{ {
get { return ref Unsafe.AsRef<MatrixKernel<T>>(BufferPointer + MatrixKernel<T>.Size * index); } get { return ref Unsafe.AsRef<MatrixKernel<T>>(BufferPointer + MatrixKernel<T>.Size * index); }
} }
protected internal abstract unsafe T* BufferPointer { get; } protected internal abstract unsafe T* BufferPointer { get; }
public abstract void Dispose(); public abstract void Dispose();
} }
internal class MatrixStorageHLSF<T>(HLSFAllocator allocator, HLSFHandle handle) : MatrixStorage<T> internal class MatrixStorageHLSF<T>(HLSFAllocator allocator, HLSFHandle handle) : MatrixStorage<T>
where T : unmanaged, INumber<T> where T: unmanaged, INumber<T>
{ {
internal HLSFAllocator _allocator = allocator; internal HLSFAllocator _allocator = allocator;
internal HLSFHandle _handle = handle; internal HLSFHandle _handle = handle;
protected internal override unsafe T* BufferPointer => (T*)_handle.Pointer; protected internal override unsafe T* BufferPointer => (T*)_handle.Pointer;
public override void Dispose() public override void Dispose()
{ {
allocator.Free(_handle); allocator.Free(_handle);
} }
} }
} }
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixCompute.Float" // file="MatrixCompute.Float"
// 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,8 +26,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Collections; using StgSharp.Collections;
using StgSharp.HighPerformance;
using StgSharp.Internal; using StgSharp.Internal;
using StgSharp.Mathematics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
@@ -42,11 +42,7 @@ namespace StgSharp.Mathematics.Numeric
public static partial class MatrixCompute public static partial class MatrixCompute
{ {
public static unsafe void Add( public static unsafe void Add(Matrix<float> left, Matrix<float> right, Matrix<float> ans)
Matrix<float> left,
Matrix<float> right,
Matrix<float> ans
)
{ {
int f32 = (int)MatrixElementType.F32; int f32 = (int)MatrixElementType.F32;
if (left.ColumnLength != right.ColumnLength || if (left.ColumnLength != right.ColumnLength ||
@@ -92,10 +88,7 @@ namespace StgSharp.Mathematics.Numeric
return; return;
} }
public static unsafe void Fill( public static unsafe void Fill(Matrix<float> ans, float value)
Matrix<float> ans,
float value
)
{ {
int f32 = (int)MatrixElementType.F32; int f32 = (int)MatrixElementType.F32;
long count = (long)ans.KernelColumnLength * ans.KernelRowLength; long count = (long)ans.KernelColumnLength * ans.KernelRowLength;
@@ -126,11 +119,7 @@ namespace StgSharp.Mathematics.Numeric
taskGroup.Dispose(); taskGroup.Dispose();
} }
public static unsafe void Mul( public static unsafe void Mul(Matrix<float> left, Matrix<float> right, Matrix<float> ans)
Matrix<float> left,
Matrix<float> right,
Matrix<float> ans
)
{ {
int f32 = (int)MatrixElementType.F32; int f32 = (int)MatrixElementType.F32;
@@ -168,8 +157,7 @@ namespace StgSharp.Mathematics.Numeric
NativeIntrinsic.Context NativeIntrinsic.Context
.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, (MatrixKernel*)ans.Buffer, enumeration);
enumeration);
} }
} }
@@ -196,18 +184,13 @@ namespace StgSharp.Mathematics.Numeric
return; return;
} }
public static unsafe void Mul( public static unsafe void Mul(Matrix<float> left, float right, Matrix<float> ans)
Matrix<float> left,
float right,
Matrix<float> ans
)
{ {
int f32 = (int)MatrixElementType.F32; int f32 = (int)MatrixElementType.F32;
if (left.ColumnLength != ans.ColumnLength || left.RowLength != ans.RowLength) { if (left.ColumnLength != ans.ColumnLength || left.RowLength != ans.RowLength) {
throw new IndexOutOfRangeException("Matrix dimensions must agree."); throw new IndexOutOfRangeException("Matrix dimensions must agree.");
} }
if (left.Layout != MatrixLayout.DenseRectangle || if (left.Layout != MatrixLayout.DenseRectangle || ans.Layout != MatrixLayout.DenseRectangle) {
ans.Layout != MatrixLayout.DenseRectangle) {
throw new NotSupportedException("Only dense rectangle matrices are supported."); throw new NotSupportedException("Only dense rectangle matrices are supported.");
} }
long count = (long)left.KernelColumnLength * left.KernelRowLength; long count = (long)left.KernelColumnLength * left.KernelRowLength;
@@ -248,11 +231,7 @@ namespace StgSharp.Mathematics.Numeric
return; return;
} }
public static unsafe void Sub( public static unsafe void Sub(Matrix<float> left, Matrix<float> right, Matrix<float> ans)
Matrix<float> left,
Matrix<float> right,
Matrix<float> ans
)
{ {
int f32 = (int)MatrixElementType.F32; int f32 = (int)MatrixElementType.F32;
if (left.ColumnLength != right.ColumnLength || if (left.ColumnLength != right.ColumnLength ||
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixCompute" // file="MatrixCompute"
// 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,8 @@
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance;
using StgSharp.Internal; using StgSharp.Internal;
using StgSharp.Mathematics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -45,8 +45,8 @@ namespace StgSharp.Mathematics.Numeric
MatrixKernel<T>* buffer, MatrixKernel<T>* buffer,
int colLength, int colLength,
int x, int x,
int y int y)
) where T : unmanaged, INumber<T> where T: unmanaged, INumber<T>
{ {
return (MatrixKernel*)(buffer + (colLength * x + y)); return (MatrixKernel*)(buffer + (colLength * x + y));
} }
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixCompute.double" // file="MatrixCompute.double"
// 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,8 @@
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance;
using StgSharp.Internal; using StgSharp.Internal;
using StgSharp.Mathematics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -38,11 +38,7 @@ namespace StgSharp.Mathematics.Numeric
public partial class MatrixCompute public partial class MatrixCompute
{ {
public static unsafe void Add( public static unsafe void Add(Matrix<double> left, Matrix<double> right, Matrix<double> ans)
Matrix<double> left,
Matrix<double> right,
Matrix<double> ans
)
{ {
int f64 = (int)MatrixElementType.F64; int f64 = (int)MatrixElementType.F64;
if (left.ColumnLength != right.ColumnLength || if (left.ColumnLength != right.ColumnLength ||
@@ -88,10 +84,7 @@ namespace StgSharp.Mathematics.Numeric
return; return;
} }
public static unsafe void Fill( public static unsafe void Fill(Matrix<double> ans, double value)
Matrix<double> ans,
double value
)
{ {
int f64 = (int)MatrixElementType.F64; int f64 = (int)MatrixElementType.F64;
long count = (long)ans.KernelColumnLength * ans.KernelRowLength; long count = (long)ans.KernelColumnLength * ans.KernelRowLength;
@@ -122,11 +115,7 @@ namespace StgSharp.Mathematics.Numeric
taskGroup.Dispose(); taskGroup.Dispose();
} }
public static unsafe void Mul( public static unsafe void Mul(Matrix<double> left, Matrix<double> right, Matrix<double> ans)
Matrix<double> left,
Matrix<double> right,
Matrix<double> ans
)
{ {
int f64 = (int)MatrixElementType.F64; int f64 = (int)MatrixElementType.F64;
@@ -158,8 +147,7 @@ namespace StgSharp.Mathematics.Numeric
NativeIntrinsic.Context NativeIntrinsic.Context
.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, (MatrixKernel*)ans.Buffer, enumeration);
enumeration);
} }
} }
if (count > 256) { if (count > 256) {
@@ -185,18 +173,13 @@ namespace StgSharp.Mathematics.Numeric
return; return;
} }
public static unsafe void Mul( public static unsafe void Mul(Matrix<double> left, double right, Matrix<double> ans)
Matrix<double> left,
double right,
Matrix<double> ans
)
{ {
int f64 = (int)MatrixElementType.F64; int f64 = (int)MatrixElementType.F64;
if (left.ColumnLength != ans.ColumnLength || left.RowLength != ans.RowLength) { if (left.ColumnLength != ans.ColumnLength || left.RowLength != ans.RowLength) {
throw new IndexOutOfRangeException("Matrix dimensions must agree."); throw new IndexOutOfRangeException("Matrix dimensions must agree.");
} }
if (left.Layout != MatrixLayout.DenseRectangle || if (left.Layout != MatrixLayout.DenseRectangle || ans.Layout != MatrixLayout.DenseRectangle) {
ans.Layout != MatrixLayout.DenseRectangle) {
throw new NotSupportedException("Only dense rectangle matrices are supported."); throw new NotSupportedException("Only dense rectangle matrices are supported.");
} }
long count = (long)left.KernelColumnLength * left.KernelRowLength; long count = (long)left.KernelColumnLength * left.KernelRowLength;
@@ -237,11 +220,7 @@ namespace StgSharp.Mathematics.Numeric
return; return;
} }
public static unsafe void Sub( public static unsafe void Sub(Matrix<double> left, Matrix<double> right, Matrix<double> ans)
Matrix<double> left,
Matrix<double> right,
Matrix<double> ans
)
{ {
int f64 = (int)MatrixElementType.F64; int f64 = (int)MatrixElementType.F64;
if (left.ColumnLength != right.ColumnLength || if (left.ColumnLength != right.ColumnLength ||
@@ -1,80 +1,76 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixParallel.Publish" // file="MatrixParallel.Publish"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Collections; using StgSharp.Collections;
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
public static partial class MatrixParallel public static partial class MatrixParallel
{ {
private const int MIN_TASK_PER_THREAD = 256; private const int MIN_TASK_PER_THREAD = 256;
private const int REC_TASK_PER_THREAD = 1024; private const int REC_TASK_PER_THREAD = 1024;
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe MatrixParallelWrap ScheduleTask( internal static unsafe MatrixParallelWrap ScheduleTask(MatrixParallelTask* package)
MatrixParallelTask* package {
) switch (package->ComputeMode.OperationStyle)
{ {
switch (package->ComputeMode.OperationStyle) case MatrixIndexStyle.BUFFER_INDEX:
{ return ScheduleBufferTask(package);
case MatrixIndexStyle.BUFFER_INDEX: default:
return ScheduleBufferTask(package); throw new InvalidOperationException($"Unknown mode {package->ComputeMode.OperationStyle}.");
default: }
throw new InvalidOperationException($"Unknown mode {package->ComputeMode.OperationStyle}."); }
}
} private static unsafe MatrixParallelWrap ScheduleBufferTask(MatrixParallelTask* package)
{
private static unsafe MatrixParallelWrap ScheduleBufferTask( int primCount = package->PrimCount;
MatrixParallelTask* package int secCount = package->SecCount;
)
{
int primCount = package->PrimCount;
int secCount = package->SecCount;
long count = (long)primCount * secCount; long count = (long)primCount * secCount;
// Console.WriteLine($"amount of kernels is {count}"); // Console.WriteLine($"amount of kernels is {count}");
long recommendCount = count / 1024; long recommendCount = count / 1024;
MatrixParallelThread[] pool = LeadParallel((int)recommendCount); MatrixParallelThread[] pool = LeadParallel((int)recommendCount);
MatrixParallelWrap wrap = new MatrixParallelWrap(pool); MatrixParallelWrap wrap = new MatrixParallelWrap(pool);
wrap.TaskQueue = MatrixParallelQueue.Rent(package); wrap.TaskQueue = MatrixParallelQueue.Rent(package);
return wrap; return wrap;
} }
} }
} }
@@ -1,132 +1,124 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixParallel" // file="MatrixParallel"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Collections; using StgSharp.Collections;
using StgSharp.HighPerformance.Memory; using StgSharp.Internal;
using StgSharp.Internal; using StgSharp.Mathematics.Intrinsic;
using StgSharp.Mathematics.Internal; using StgSharp.Mathematics.Memory;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
public static partial class MatrixParallel public static partial class MatrixParallel
{ {
private static bool _meaningful; private static bool _meaningful;
private static CapacityFixedStack<MatrixParallelThread> _threads; private static CapacityFixedStack<MatrixParallelThread> _threads;
private static ConcurrentDictionary<SIMDID, nint> contextMap; private static ConcurrentDictionary<SIMDID, nint> contextMap;
private static SlabAllocator<IntrinsicContext> contextAllocator; private static SlabAllocator<IntrinsicContext> contextAllocator;
public static bool IsParallelSupported { get; } = Environment.ProcessorCount > 6; public static bool IsParallelSupported { get; } = Environment.ProcessorCount > 6;
public static bool IsParallelMeaningful => Environment.ProcessorCount > 6 && IsInitialized; public static bool IsParallelMeaningful => Environment.ProcessorCount > 6 && IsInitialized;
private static bool IsInitialized { get; set; } = false; private static bool IsInitialized { get; set; } = false;
internal static unsafe IntrinsicContext* GetContext( internal static unsafe IntrinsicContext* GetContext(SIMDID simd)
SIMDID simd {
) if (!IsParallelSupported) {
{ return null;
if (!IsParallelSupported) { }
return null; if (contextMap.TryGetValue(simd, out nint handle))
} {
if (contextMap.TryGetValue(simd, out nint handle)) return (IntrinsicContext*)handle;
{ } else
return (IntrinsicContext*)handle; {
} else
{
IntrinsicContext* context = (IntrinsicContext*)contextAllocator.Allocate(); IntrinsicContext* context = (IntrinsicContext*)contextAllocator.Allocate();
return context; return context;
} }
} }
internal static void Init() internal static void Init()
{ {
if (IsInitialized) { if (IsInitialized) {
return; return;
} }
if (!IsParallelSupported) if (!IsParallelSupported)
{ {
IsInitialized = true; IsInitialized = true;
return; return;
} }
MatrixParallelFactory.Init(); MatrixParallelFactory.Init();
contextAllocator = SlabAllocator<IntrinsicContext>.Create(4, SlabBufferLayout.Chunked, false); contextAllocator = SlabAllocator<IntrinsicContext>.Create(4, SlabBufferLayout.Chunked, false);
contextMap = []; contextMap = [];
int count = Environment.ProcessorCount; int count = Environment.ProcessorCount;
_threads = new(count); _threads = new(count);
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
{ {
MatrixParallelThread thread = new MatrixParallelThread(i); MatrixParallelThread thread = new MatrixParallelThread(i);
_threads.Push(thread); _threads.Push(thread);
SpinWait.SpinUntil(() => thread.State == MatrixThreadState.Ready); SpinWait.SpinUntil(() => thread.State == MatrixThreadState.Ready);
} }
// TODO 构建全局的保底上下文 // TODO 构建全局的保底上下文
foreach (MatrixParallelThread thread in _threads) { } foreach (MatrixParallelThread thread in _threads) { }
if (contextMap.Keys.Count == 1) if (contextMap.Keys.Count == 1)
{ {
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
{ {
MatrixParallelThread thread = _threads.Pop(); MatrixParallelThread thread = _threads.Pop();
thread.Dispose(); thread.Dispose();
} }
} else } else
{ {
// TODO 排序并丢弃四个能力最弱线程 // TODO 排序并丢弃四个能力最弱线程
} }
_awaitingLeaderHandle = new AwaitingQueue(); _awaitingLeaderHandle = new AwaitingQueue();
IsInitialized = true; IsInitialized = true;
} }
[LibraryImport(Native.LibName, EntryPoint = "sn_compare_simd")] [LibraryImport(Native.LibName, EntryPoint = "sn_compare_simd")]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
private static unsafe partial ulong CompareSIMDID( private static unsafe partial ulong CompareSIMDID(IntrinsicContext* context, ulong id);
IntrinsicContext* context,
ulong id [LibraryImport(Native.LibName, EntryPoint = "load_intrinsic_function")]
); [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]
private static unsafe partial void LoadIntrinsicFunction(IntrinsicContext* context, ulong id);
[LibraryImport(Native.LibName, EntryPoint = "load_intrinsic_function")]
[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] }
private static unsafe partial void LoadIntrinsicFunction(
IntrinsicContext* context,
ulong id
);
}
} }
@@ -1,64 +1,60 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixParallelTask" // file="MatrixParallelTask"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.Mathematics.Internal; using StgSharp.Mathematics.Intrinsic;
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.InteropServices;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
[StructLayout(LayoutKind.Explicit)] [StructLayout(LayoutKind.Explicit)]
internal unsafe struct MatrixParallelTask internal unsafe struct MatrixParallelTask
{ {
[FieldOffset(0)]public MatrixKernel* Mat1; // 8 [FieldOffset(0)]public MatrixKernel* Mat1; // 8
[FieldOffset(8)] public MatrixKernel* Mat2; // 8 [FieldOffset(8)] public MatrixKernel* Mat2; // 8
[FieldOffset(16)] public MatrixKernel* Mat3; // 16 [FieldOffset(16)] public MatrixKernel* Mat3; // 16
[FieldOffset(32)] public int Common_i; [FieldOffset(32)] public int Common_i;
[FieldOffset(36)] public int Common_j; [FieldOffset(36)] public int Common_j;
[FieldOffset(40)] public int Common_k; [FieldOffset(40)] public int Common_k;
[FieldOffset(44)] public int i; [FieldOffset(44)] public int i;
[FieldOffset(48)] public int j; [FieldOffset(48)] public int j;
[FieldOffset(52)] public int k; [FieldOffset(52)] public int k;
[FieldOffset(56)] public MatrixElementType ElementType; // 56 [FieldOffset(56)] public MatrixElementType ElementType; // 56
[FieldOffset(24)] public nint Span; // 24 [FieldOffset(24)] public nint Span; // 24
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Copy( public static void Copy(MatrixParallelTask* source, MatrixParallelTask* target)
MatrixParallelTask* source, {
MatrixParallelTask* target Buffer.MemoryCopy(source, target, sizeof(MatrixParallelTask), sizeof(MatrixParallelTask));
) }
{
Buffer.MemoryCopy(source, target, sizeof(MatrixParallelTask), }
sizeof(MatrixParallelTask));
}
}
} }
@@ -1,105 +1,99 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixParallelThread.Fma" // file="MatrixParallelThread.Fma"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Internal;
using StgSharp.Internal; using StgSharp.Mathematics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
public partial class MatrixParallelThread public partial class MatrixParallelThread
{ {
internal static unsafe void ComputeFmaPanelF32( internal static unsafe void ComputeFmaPanelF32(MatrixParallelTask* p)
MatrixParallelTask* p {
) int f32 = MatrixElementType.F32.IntrinsicNode;
{ MatrixKernel* leftBuffer = (MatrixKernel*)p->Left;
int f32 = MatrixElementType.F32.IntrinsicNode; MatrixKernel* rightBuffer = (MatrixKernel*)p->Right;
MatrixKernel* leftBuffer = (MatrixKernel*)p->Left; MatrixKernel* ansBuffer = (MatrixKernel*)p->Answer;
MatrixKernel* rightBuffer = (MatrixKernel*)p->Right; ref long offsetRef = ref Unsafe.As<int, long>(ref p->PrimTileOffset);
MatrixKernel* ansBuffer = (MatrixKernel*)p->Answer; ref long lengthRef = ref Unsafe.As<int, long>(ref p->PrimCount);
ref long offsetRef = ref Unsafe.As<int, long>(ref p->PrimTileOffset); int ansWidth = p->AnsPrimOffset;
ref long lengthRef = ref Unsafe.As<int, long>(ref p->PrimCount); int ansHeight = p->AnsSecOffset;
int ansWidth = p->AnsPrimOffset;
int ansHeight = p->AnsSecOffset;
int commonK = p->LeftPrimOffset; int commonK = p->LeftPrimOffset;
M128* enumeration = stackalloc M128[1]; M128* enumeration = stackalloc M128[1];
enumeration->Member<int>(2) = commonK; enumeration->Member<int>(2) = commonK;
enumeration->Member<int>(3) = ansHeight; enumeration->Member<int>(3) = ansHeight;
// in this occasion size must be 1 // in this occasion size must be 1
for (long c = offsetRef; c < offsetRef + lengthRef; c++) for (long c = offsetRef; c < offsetRef + lengthRef; c++)
{ {
int i = (int)(c / ansHeight); int i = (int)(c / ansHeight);
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, NativeIntrinsic.Context.mat[f32].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer, enumeration);
enumeration); }
} }
}
internal static unsafe void ComputeFmaPanelF64(MatrixParallelTask* p)
internal static unsafe void ComputeFmaPanelF64( {
MatrixParallelTask* p
)
{
int f64 = MatrixElementType.F64.IntrinsicNode; int f64 = MatrixElementType.F64.IntrinsicNode;
// int size = 1; // int size = 1;
MatrixKernel* leftBuffer = (MatrixKernel*)p->Left; MatrixKernel* leftBuffer = (MatrixKernel*)p->Left;
MatrixKernel* rightBuffer = (MatrixKernel*)p->Right; MatrixKernel* rightBuffer = (MatrixKernel*)p->Right;
MatrixKernel* ansBuffer = (MatrixKernel*)p->Answer; MatrixKernel* ansBuffer = (MatrixKernel*)p->Answer;
ref long offsetRef = ref Unsafe.As<int, long>(ref p->PrimTileOffset); ref long offsetRef = ref Unsafe.As<int, long>(ref p->PrimTileOffset);
ref long lengthRef = ref Unsafe.As<int, long>(ref p->PrimCount); ref long lengthRef = ref Unsafe.As<int, long>(ref p->PrimCount);
int ansWidth = p->AnsPrimOffset; int ansWidth = p->AnsPrimOffset;
int ansHeight = p->AnsSecOffset; int ansHeight = p->AnsSecOffset;
int commonK = p->LeftPrimOffset; int commonK = p->LeftPrimOffset;
M128* enumeration = stackalloc M128[1]; M128* enumeration = stackalloc M128[1];
enumeration->Member<int>(2) = commonK; enumeration->Member<int>(2) = commonK;
enumeration->Member<int>(3) = ansHeight; enumeration->Member<int>(3) = ansHeight;
// in this occasion size must be 1 // in this occasion size must be 1
for (long c = offsetRef; c < offsetRef + lengthRef; c++) for (long c = offsetRef; c < offsetRef + lengthRef; c++)
{ {
int i = (int)(c / ansHeight); int i = (int)(c / ansHeight);
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, NativeIntrinsic.Context.mat[f64].kernel_tile_fma(leftBuffer, rightBuffer, ansBuffer, enumeration);
enumeration); }
} }
}
}
}
} }
@@ -1,75 +1,70 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixParallelThread.Model" // file="MatrixParallelThread.Model"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using System; using System;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
public partial class MatrixParallelThread public partial class MatrixParallelThread
{ {
private const int KernelStealCount = 64; private const int KernelStealCount = 64;
internal unsafe void BufferCompute( internal unsafe void BufferCompute(MatrixParallelTask* p)
MatrixParallelTask* p {
) // while () { }
{ int size = p->ElementSize * 16;
// while () { } long count = Unsafe.As<int, long>(ref p->PrimCount);
int size = p->ElementSize * 16; long offset = Unsafe.As<int, long>(ref p->PrimTileOffset) * size;
long count = Unsafe.As<int, long>(ref p->PrimCount); ScalarPacket* scalar = p->Scalar;
long offset = Unsafe.As<int, long>(ref p->PrimTileOffset) * size;
ScalarPacket* scalar = p->Scalar;
IntPtr computeHandle = _context[p->ComputeHandle]; IntPtr computeHandle = _context[p->ComputeHandle];
((delegate* unmanaged[Cdecl]<void*, void*, void*, void*, long, void>)computeHandle)((void*)(p->Left + offset), ((delegate* unmanaged[Cdecl]<void*, void*, void*, void*, long, void>)computeHandle)((void*)(p->Left + offset),
(void*)(p->Right + offset), (void*)(p->Right + offset),
(void*)(p->Answer + offset), (void*)(p->Answer + offset),
scalar, scalar, count);
count); }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void SpecialBufferCompute(MatrixParallelTask* p)
internal unsafe void SpecialBufferCompute( {
MatrixParallelTask* p switch ((MatrixElementType)p->ElementSize)
) {
{ case MatrixElementType.F64:
switch ((MatrixElementType)p->ElementSize) ComputeFmaPanelF64(p);
{ return;
case MatrixElementType.F64: case MatrixElementType.F32:
ComputeFmaPanelF64(p); ComputeFmaPanelF32(p);
return; break;
case MatrixElementType.F32: default:
ComputeFmaPanelF32(p); break;
break; }
default: }
break;
} }
}
}
} }
@@ -26,7 +26,7 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Internal; using StgSharp.Internal;
using StgSharp.Mathematics.Internal; using StgSharp.Mathematics.Intrinsic;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@@ -1,48 +1,48 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixTaskFactory" // file="MatrixTaskFactory"
// 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
// in the Software without restriction, including without limitation the rights // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is // copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: // 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 this permission notice shall be included in all
// copies or substantial portions of the Software. // 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", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // IMPLIED, 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. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 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 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE. // SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics;
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using hlsfAllocator = StgSharp.HighPerformance.Memory.HybridLayerSegregatedFitAllocator; using hlsfAllocator = StgSharp.Mathematics.Memory.HybridLayerSegregatedFitAllocator;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
internal static unsafe class MatrixParallelFactory internal static unsafe class MatrixParallelFactory
{ {
private static hlsfAllocator _intermediateResult; private static hlsfAllocator _intermediateResult;
private static private static
@@ -57,63 +57,57 @@ namespace StgSharp.Mathematics.Numeric
private static SlabAllocator<MatrixParallelTask> _wrapAllocator; private static SlabAllocator<MatrixParallelTask> _wrapAllocator;
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static MatrixParallelTask* CreateBaseTask() public static MatrixParallelTask* CreateBaseTask()
{ {
MatrixParallelTask* p = (MatrixParallelTask*)_wrapAllocator.Allocate(); MatrixParallelTask* p = (MatrixParallelTask*)_wrapAllocator.Allocate();
Span<byte> s = new Span<byte>((byte*)p, sizeof(MatrixParallelTask)); Span<byte> s = new Span<byte>((byte*)p, sizeof(MatrixParallelTask));
s.Fill(0); s.Fill(0);
return p; return p;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ScalarPacket* CreateScalarPacket() public static ScalarPacket* CreateScalarPacket()
{ {
ScalarPacket* p = (ScalarPacket*)_scalarAllocator.Allocate(); ScalarPacket* p = (ScalarPacket*)_scalarAllocator.Allocate();
return p; return p;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe MatrixParallelTask* FromExistPackage( public static unsafe MatrixParallelTask* FromExistPackage(MatrixParallelTask* exist)
MatrixParallelTask* exist {
) MatrixParallelTask* ptr = (MatrixParallelTask*)_wrapAllocator.Allocate();
{ MatrixParallelTask.Copy(exist, ptr);
MatrixParallelTask* ptr = (MatrixParallelTask*)_wrapAllocator.Allocate(); return ptr;
MatrixParallelTask.Copy(exist, ptr); }
return ptr;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Release( public static void Release(ScalarPacket* source)
ScalarPacket* source {
) _scalarAllocator.Free((nuint)source);
{ }
_scalarAllocator.Free((nuint)source);
} [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Release(MatrixParallelTask* source)
[MethodImpl(MethodImplOptions.AggressiveInlining)] {
public static void Release( if (source->Scalar != null) {
MatrixParallelTask* source _scalarAllocator.Free((nuint)source->Scalar);
) }
{ _wrapAllocator.Free((nuint)source);
if (source->Scalar != null) { }
_scalarAllocator.Free((nuint)source->Scalar);
} [MethodImpl(MethodImplOptions.AggressiveInlining)]
_wrapAllocator.Free((nuint)source); internal static void Init()
} {
if (_intermediateResult is null)
[MethodImpl(MethodImplOptions.AggressiveInlining)] {
internal static void Init() _intermediateResult = new hlsfAllocator(64 * 16 * 16);
{ _scalarAllocator = SlabAllocator<ScalarPacket>.Create(64 * 1024, SlabBufferLayout.Chunked);
if (_intermediateResult is null)
{
_intermediateResult = new hlsfAllocator(64 * 16 * 16);
_scalarAllocator = SlabAllocator<ScalarPacket>.Create(64 * 1024, SlabBufferLayout.Chunked);
_wrapAllocator = SlabAllocator<MatrixParallelTask>. _wrapAllocator = SlabAllocator<MatrixParallelTask>.
Create(128 * 1024, SlabBufferLayout.Chunked); Create(128 * 1024, SlabBufferLayout.Chunked);
} }
} }
} }
} }
@@ -1,31 +1,34 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="RandomGenerator" // file="RandomGenerator.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 //
// copies or substantial portions of the Software. // The above copyright notice and
// // this permission notice shall be included in all copies
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // THE SOFTWARE IS PROVIDED “AS IS”,
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// SOFTWARE. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance; using StgSharp.Mathematics.Internal;
using System; using System;
using System.IO; using System.IO;
@@ -33,7 +36,7 @@ using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using System.Xml.Serialization; using System.Xml.Serialization;
namespace StgSharp.Data namespace StgSharp.Mathematics.Numeric.Scalar
{ {
public unsafe class RandomGenerator public unsafe class RandomGenerator
{ {
@@ -53,12 +56,7 @@ namespace StgSharp.Data
string data = sw.ToString(); string data = sw.ToString();
originKey = Encoding.Unicode.GetBytes(data); originKey = Encoding.Unicode.GetBytes(data);
} }
currentKey = [ currentKey = [ 0, 0, 0, 0 ];
0,
0,
0,
0
];
fixed (byte* o = originKey, c = currentKey) { fixed (byte* o = originKey, c = currentKey) {
*(int*)c = UnsafeCompute.CityHashSimplify((char*)o, 0, originKey.Length / 2); *(int*)c = UnsafeCompute.CityHashSimplify((char*)o, 0, originKey.Length / 2);
} }
-1
View File
@@ -2,7 +2,6 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\StgSharp.Common\StgSharp.Common.csproj" /> <ProjectReference Include="..\StgSharp.Common\StgSharp.Common.csproj" />
<ProjectReference Include="..\StgSharp.Script\StgSharp.Script.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+36 -16
View File
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HlsfStressTest" // file="HlsfStressTest"
// 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,7 +25,7 @@
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
@@ -45,8 +45,36 @@ namespace StgSharp
3UL * 1024UL * 1024UL * 1024UL; // lower default to 512MB 3UL * 1024UL * 1024UL * 1024UL; // lower default to 512MB
private static readonly uint[] SizeSweep = { private static readonly uint[] SizeSweep = {
64, 128, 192, 256, 512, 768, 1024, 2048, 3072, 4096, 8192, 12288, 16384, 32768, 49152, 65536, 131072, 196608, 262144, 524288, 786432, 1_048_576, 2_097_152, 3_145_728, 4_194_304, 8_388_608, 12_582_912, 16_777_216, 25_165_824, 33_554_432 64,
}; 128,
192,
256,
512,
768,
1024,
2048,
3072,
4096,
8192,
12288,
16384,
32768,
49152,
65536,
131072,
196608,
262144,
524288,
786432,
1_048_576,
2_097_152,
3_145_728,
4_194_304,
8_388_608,
12_582_912,
16_777_216,
25_165_824,
33_554_432 };
public static unsafe void Run() public static unsafe void Run()
{ {
@@ -116,10 +144,7 @@ namespace StgSharp
Console.WriteLine("=== Benchmark Complete ==="); Console.WriteLine("=== Benchmark Complete ===");
} }
private static void BenchAllocFreePairs( private static void BenchAllocFreePairs(HybridLayerSegregatedFitAllocator allocator, int pairs, uint blockSize)
HybridLayerSegregatedFitAllocator allocator,
int pairs,
uint blockSize)
{ {
Stopwatch sw = Stopwatch.StartNew(); Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < pairs; i++) for (int i = 0; i < pairs; i++)
@@ -176,9 +201,7 @@ namespace StgSharp
Console.WriteLine($" size={Fmt(blockSize),-12} ops={ops,-12} alloc/s={allocOpsPerSec,-16:0.0} touch={touch,-5}"); Console.WriteLine($" size={Fmt(blockSize),-12} ops={ops,-12} alloc/s={allocOpsPerSec,-16:0.0} touch={touch,-5}");
} }
private static void BenchFragmentationCycle( private static void BenchFragmentationCycle(HybridLayerSegregatedFitAllocator allocator, int targetMiB)
HybridLayerSegregatedFitAllocator allocator,
int targetMiB)
{ {
int targetBytes = targetMiB * 1024 * 1024; int targetBytes = targetMiB * 1024 * 1024;
Random rng = new Random(123); Random rng = new Random(123);
@@ -229,10 +252,7 @@ namespace StgSharp
Console.WriteLine($" cleanup freed {live.Count} in {swD.Elapsed.TotalSeconds:0.00}s"); Console.WriteLine($" cleanup freed {live.Count} in {swD.Elapsed.TotalSeconds:0.00}s");
} }
private static void BenchFreeThroughput( private static void BenchFreeThroughput(HybridLayerSegregatedFitAllocator allocator, int count, uint blockSize)
HybridLayerSegregatedFitAllocator allocator,
int count,
uint blockSize)
{ {
List<HybridLayerSegregatedFitAllocationHandle> list = new List<HybridLayerSegregatedFitAllocationHandle>(count); List<HybridLayerSegregatedFitAllocationHandle> list = new List<HybridLayerSegregatedFitAllocationHandle>(count);
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
+2 -2
View File
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="MatrixTest" // file="MatrixTest"
// Project: StgSharp // Project: StgSharp
@@ -26,7 +26,7 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Syntax;
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using StgSharp.Mathematics.Numeric; using StgSharp.Mathematics.Numeric;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
+3 -3
View File
@@ -1,4 +1,4 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Program" // file="Program"
// Project: StgSharp // Project: StgSharp
@@ -26,9 +26,9 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.Common.Timing; using StgSharp.Common.Timing;
using StgSharp.HighPerformance;
using StgSharp.HighPerformance.Memory;
using StgSharp.Internal; using StgSharp.Internal;
using StgSharp.Mathematics;
using StgSharp.Mathematics.Memory;
using StgSharp.Mathematics.Numeric; using StgSharp.Mathematics.Numeric;
using StgSharp.Timing; using StgSharp.Timing;
+3 -3
View File
@@ -2,8 +2,8 @@
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="SlabStressTest" // file="SlabStressTest"
// 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,7 +25,7 @@
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using System; using System;
using System.Diagnostics; using System.Diagnostics;
-1
View File
@@ -14,7 +14,6 @@
<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" />
<ProjectReference Include="..\StgSharp.Script\StgSharp.Script.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
+28 -31
View File
@@ -1,38 +1,35 @@
//-----------------------------------------------------------------------
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// file="NewRender.cs" // -----------------------------------------------------------------------
// Project: StgSharp // file="NewRender"
// AuthorGroup: Nitload Space // Project: StgSharp
// Copyright (c) Nitload Space. All rights reserved. // AuthorGroup: Nitload Space
// 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 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.
// //
// The above copyright notice and // -----------------------------------------------------------------------
// this permission notice shall be included in all copies // -----------------------------------------------------------------------
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics; using StgSharp.Graphics;
using StgSharp.HighPerformance;
using StgSharp.Internal; using StgSharp.Internal;
using StgSharp.Mathematics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -49,12 +46,12 @@ namespace StgSharp
private class NewRender : ViewRender<ViewMain> private class NewRender : ViewRender<ViewMain>
{ {
public NewRender( ViewMain view ) : base( view ) { } public NewRender(ViewMain view) : base(view) { }
public override void CustomizedInitialize() public override void CustomizedInitialize()
{ {
Binding.Stream = CreateRenderStream<ParticleRenderStream>(); Binding.Stream = CreateRenderStream<ParticleRenderStream>();
Render[ "only".AsLabel() ] = Binding.Stream; Render["only".AsLabel()] = Binding.Stream;
} }
public override bool ValidateInitializing() public override bool ValidateInitializing()
+9 -6
View File
@@ -1,9 +1,9 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="hlsf-test" // file="hlsf-test"
// 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,7 +25,7 @@
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
using StgSharp.HighPerformance.Memory; using StgSharp.Mathematics.Memory;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
@@ -50,8 +50,11 @@ namespace StgSharp
int maxRounds = 10000; // 可调整 int maxRounds = 10000; // 可调整
uint[] sizes = { uint[] sizes = {
64u, 128u, 256u, 512u, 1024u 64u,
}; 128u,
256u,
512u,
1024u };
Random rnd = new Random(42); Random rnd = new Random(42);
for (int round = 1; round <= maxRounds; round++) for (int round = 1; round <= maxRounds; round++)
{ {
+5 -18
View File
@@ -1,6 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 Microsoft Visual Studio Solution File, Format Version 12.00
VisualStudioVersion = 17.3.32825.248 # Visual Studio Version 18
VisualStudioVersion = 18.3.11520.95 d18.3
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.Common", "StgSharp.Common\StgSharp.Common.csproj", "{3EAF2EE6-FA9E-4F57-951F-7E6F8125DFBF}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.Common", "StgSharp.Common\StgSharp.Common.csproj", "{3EAF2EE6-FA9E-4F57-951F-7E6F8125DFBF}"
ProjectSection(ProjectDependencies) = postProject ProjectSection(ProjectDependencies) = postProject
@@ -25,8 +26,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.TerminalDialogue", "StgSharp.TerminalDialogue\StgSharp.TerminalDialogue.csproj", "{10B5819F-2A62-41B6-980A-EB9E76A0E95C}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.TerminalDialogue", "StgSharp.TerminalDialogue\StgSharp.TerminalDialogue.csproj", "{10B5819F-2A62-41B6-980A-EB9E76A0E95C}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.Script", "StgSharp.Script\StgSharp.Script.csproj", "{5B51F5EA-138C-46B5-B36F-1D389968B6CF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.Model", "StgSharp.Model\StgSharp.Model.csproj", "{D9538DE0-EE4C-4183-86D6-7DFC08A7BDFB}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.Model", "StgSharp.Model\StgSharp.Model.csproj", "{D9538DE0-EE4C-4183-86D6-7DFC08A7BDFB}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.Mathematics", "StgSharp.Mathematics\StgSharp.Mathematics.csproj", "{9946599F-4D34-440F-840D-F9443D5AEFAA}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StgSharp.Mathematics", "StgSharp.Mathematics\StgSharp.Mathematics.csproj", "{9946599F-4D34-440F-840D-F9443D5AEFAA}"
@@ -105,18 +104,6 @@ Global
{10B5819F-2A62-41B6-980A-EB9E76A0E95C}.Release|ARM64.Build.0 = Release|ARM64 {10B5819F-2A62-41B6-980A-EB9E76A0E95C}.Release|ARM64.Build.0 = Release|ARM64
{10B5819F-2A62-41B6-980A-EB9E76A0E95C}.Release|x64.ActiveCfg = Release|x64 {10B5819F-2A62-41B6-980A-EB9E76A0E95C}.Release|x64.ActiveCfg = Release|x64
{10B5819F-2A62-41B6-980A-EB9E76A0E95C}.Release|x64.Build.0 = Release|x64 {10B5819F-2A62-41B6-980A-EB9E76A0E95C}.Release|x64.Build.0 = Release|x64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.Debug|ARM64.ActiveCfg = Debug|ARM64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.Debug|ARM64.Build.0 = Debug|ARM64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.Debug|x64.ActiveCfg = Debug|x64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.Debug|x64.Build.0 = Debug|x64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.PerformanceDebug|ARM64.ActiveCfg = PerformanceDebug|ARM64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.PerformanceDebug|ARM64.Build.0 = PerformanceDebug|ARM64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.PerformanceDebug|x64.ActiveCfg = PerformanceDebug|x64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.PerformanceDebug|x64.Build.0 = PerformanceDebug|x64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.Release|ARM64.ActiveCfg = Release|ARM64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.Release|ARM64.Build.0 = Release|ARM64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.Release|x64.ActiveCfg = Release|x64
{5B51F5EA-138C-46B5-B36F-1D389968B6CF}.Release|x64.Build.0 = Release|x64
{D9538DE0-EE4C-4183-86D6-7DFC08A7BDFB}.Debug|ARM64.ActiveCfg = Debug|ARM64 {D9538DE0-EE4C-4183-86D6-7DFC08A7BDFB}.Debug|ARM64.ActiveCfg = Debug|ARM64
{D9538DE0-EE4C-4183-86D6-7DFC08A7BDFB}.Debug|ARM64.Build.0 = Debug|ARM64 {D9538DE0-EE4C-4183-86D6-7DFC08A7BDFB}.Debug|ARM64.Build.0 = Debug|ARM64
{D9538DE0-EE4C-4183-86D6-7DFC08A7BDFB}.Debug|x64.ActiveCfg = Debug|x64 {D9538DE0-EE4C-4183-86D6-7DFC08A7BDFB}.Debug|x64.ActiveCfg = Debug|x64
@@ -172,4 +159,4 @@ Global
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E13615C2-4C8D-4072-95A1-124440983818} SolutionGuid = {E13615C2-4C8D-4072-95A1-124440983818}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal