vector and matrix optimization

This commit is contained in:
Youmu Liu
2025-10-14 18:13:18 +08:00
parent 47d2bfe558
commit c5eaf250ab
16 changed files with 482 additions and 381 deletions
@@ -15,26 +15,23 @@
// AuthorGroup: «?GetUserInfo(Company)» // AuthorGroup: «?GetUserInfo(Company)»
// Copyright (c) «?GetUserInfo(Company)». All rights reserved. // Copyright (c) «?GetUserInfo(Company)». 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
// The above copyright notice and //copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// -----------------------------------------------------------------------</Expansion> // -----------------------------------------------------------------------</Expansion>
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="ConcurrentBufferStack.cs" // file="ConcurrentBufferStack"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -103,7 +100,7 @@ namespace StgSharp.HighPerformance.Memory
public ulong Count public ulong Count
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Volatile.Read(ref _count); get => Volatile.Read(ref _count);
} }
@@ -125,7 +122,7 @@ namespace StgSharp.HighPerformance.Memory
public void Dispose() public void Dispose()
{ {
_lock.Dispose(); _lock.Dispose();
Marshal.FreeHGlobal((nint)_buffer); NativeMemory.Free(_buffer);
} }
public T Pop() public T Pop()
@@ -266,8 +263,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,
header->Capacity * (nuint)sizeof(T), header->Capacity * (nuint)sizeof(T),
(nuint)span.Length * (nuint)sizeof(T)); (nuint)span.Length * (nuint)sizeof(T));
} }
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.Alloc.cs" // file="HLSFAllocator.Alloc"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -125,18 +122,6 @@ namespace StgSharp.HighPerformance.Memory
Entry* old = current; Entry* old = current;
current = newEntry; current = newEntry;
// update lock and data
finalOffset += (ulong)s;
remainSize -= s;
newEntry->Level = i;
PushLevel(i, blockCount - 1, bucket);
// set new entry
current = newEntry;
// update data
finalOffset += (ulong)s; finalOffset += (ulong)s;
remainSize -= s; remainSize -= s;
} }
@@ -181,17 +166,6 @@ namespace StgSharp.HighPerformance.Memory
// update lock and data // update lock and data
finalOffset += (ulong)s; finalOffset += (ulong)s;
remainSize -= s; remainSize -= s;
newEntry->Level = i;
PushLevel(i, blockCount - 1, bucket);
// set new entry
current = newEntry;
// update data
finalOffset += (ulong)s;
remainSize -= s;
} }
} }
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.BucketNode.cs" // file="HLSFAllocator.BucketNode"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED ¡°AS IS¡±, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -39,14 +36,6 @@ namespace StgSharp.HighPerformance.Memory
public unsafe partial class HybridLayerSegregatedFitAllocator public unsafe partial class HybridLayerSegregatedFitAllocator
{ {
/// <summary>
/// Initialize bucket system (called in constructor)
/// </summary>
private void InitializeBucketSystem()
{
_bucketHeads = new ulong[levelSizeArray.Length * 3];
}
#region BucketNode Operations #region BucketNode Operations
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="HLSFAllocator.cs" // file="HLSFAllocator"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -59,7 +56,7 @@ namespace StgSharp.HighPerformance.Memory
m_Buffer = (byte*)NativeMemory.AlignedAlloc(byteSize, 16); m_Buffer = (byte*)NativeMemory.AlignedAlloc(byteSize, 16);
_align = 16; _align = 16;
InitializeBucketSystem(); _bucketHeads = new ulong[levelSizeArray.Length * 3];
_spareMemory = (Entry*)_entries.Allocate(); _spareMemory = (Entry*)_entries.Allocate();
_spareMemory->State = EntryState.Empty; _spareMemory->State = EntryState.Empty;
@@ -80,7 +77,7 @@ namespace StgSharp.HighPerformance.Memory
_align = align; _align = align;
_size = byteSize; _size = byteSize;
InitializeBucketSystem(); _bucketHeads = new ulong[levelSizeArray.Length * 3];
_spareMemory = (Entry*)_entries.Allocate(); _spareMemory = (Entry*)_entries.Allocate();
_spareMemory->State = EntryState.Empty; _spareMemory->State = EntryState.Empty;
+36 -39
View File
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Camera.cs" // file="Camera"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -82,7 +79,7 @@ namespace StgSharp.Mathematics.Graphic
return _lookAt; return _lookAt;
} }
Matrix44 move = Matrix44.Unit; Matrix44 move = Matrix44.Unit;
move.colum3.vec -= cameraAtt.colum3.vec; move.column3.vec -= cameraAtt.column3.vec;
_lookAt = rotationAtt.Transpose * move; _lookAt = rotationAtt.Transpose * move;
_isLookAtAvailable = true; _isLookAtAvailable = true;
return _lookAt; return _lookAt;
@@ -123,19 +120,19 @@ namespace StgSharp.Mathematics.Graphic
public void MoveNear(float distance) public void MoveNear(float distance)
{ {
cameraAtt.colum3.Z -= distance; cameraAtt.column3.Z -= distance;
_isLookAtAvailable = false; _isLookAtAvailable = false;
} }
public void MoveRight(float distance) public void MoveRight(float distance)
{ {
cameraAtt.colum3.X -= distance; cameraAtt.column3.X -= distance;
_isLookAtAvailable = false; _isLookAtAvailable = false;
} }
public void MoveUp(float distance) public void MoveUp(float distance)
{ {
cameraAtt.colum3.Y -= distance; cameraAtt.column3.Y -= distance;
_isLookAtAvailable = false; _isLookAtAvailable = false;
} }
@@ -148,7 +145,7 @@ namespace StgSharp.Mathematics.Graphic
public void SetViewDirection(Vec3 position, Vec3 target, Vec3 up) public void SetViewDirection(Vec3 position, Vec3 target, Vec3 up)
{ {
Vec3 direction = position - target; Vec3 direction = position - target;
if ((position.reg == cameraAtt.colum3.reg) && (this.up == up) && (cameraAtt.colum2.reg == direction.reg)) { if ((position.reg == cameraAtt.column3.reg) && (this.up == up) && (cameraAtt.column2.reg == direction.reg)) {
return; return;
} }
if (direction.GetLength() == 0) if (direction.GetLength() == 0)
@@ -168,10 +165,10 @@ namespace StgSharp.Mathematics.Graphic
Vec3 right = Linear.Orthogonalize(Linear.Cross(up, direction)); Vec3 right = Linear.Orthogonalize(Linear.Cross(up, direction));
cameraAtt.colum0.reg = right.reg; cameraAtt.column0.reg = right.reg;
cameraAtt.colum1.reg = up.reg; cameraAtt.column1.reg = up.reg;
cameraAtt.colum2.reg = direction.reg; cameraAtt.column2.reg = direction.reg;
cameraAtt.colum3.reg = position.reg; cameraAtt.column3.reg = position.reg;
InternalPitch(); InternalPitch();
InternalRow(); InternalRow();
@@ -189,13 +186,13 @@ namespace StgSharp.Mathematics.Graphic
width = Scaler.Abs(GeometryScaler.Tan(fovRadius / 2) * near * 2), width = Scaler.Abs(GeometryScaler.Tan(fovRadius / 2) * near * 2),
height = width * size.Y / size.X; height = width * size.Y / size.X;
_projection.colum0.X = 2 * near / width; _projection.column0.X = 2 * near / width;
_projection.colum1.Y = 2 * near / height; _projection.column1.Y = 2 * near / height;
_projection.colum2.X = 2 * offsetX / width; _projection.column2.X = 2 * offsetX / width;
_projection.colum2.Y = 2 * offsetY / height; _projection.column2.Y = 2 * offsetY / height;
_projection.colum2.Z = (far + near) / (near - far); _projection.column2.Z = (far + near) / (near - far);
_projection.colum2.W = -1; _projection.column2.W = -1;
_projection.colum3.Z = 2 * near * far / (near - far); _projection.column3.Z = 2 * near * far / (near - far);
} }
public void Test(params Vec4[] vec) public void Test(params Vec4[] vec)
+44 -37
View File
@@ -1,38 +1,32 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Matrix44.cs" // file="Matrix44"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.Internal.Intrinsic;
using StgSharp.Mathematics.Numeric; using StgSharp.Mathematics.Numeric;
using System; using System;
using System.ComponentModel;
using System.Drawing;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@@ -40,17 +34,17 @@ using System.Runtime.InteropServices;
namespace StgSharp.Mathematics.Graphic namespace StgSharp.Mathematics.Graphic
{ {
[StructLayout(LayoutKind.Explicit, Size = 2 * 16 * sizeof(float) + sizeof(bool), Pack = 16)] [StructLayout(LayoutKind.Explicit, Size = 2 * 16 * sizeof(float) + sizeof(bool), Pack = 16)]
public unsafe struct Matrix44 : IEquatable<Matrix44>, IMatrix<Matrix44> public unsafe struct Matrix44 : IEquatable<Matrix44>, IMatrix<float>
{ {
[FieldOffset(2 * 64 * sizeof(float))] internal bool isTransposed; [FieldOffset(2 * 64 * sizeof(float))] internal bool isTransposed;
[FieldOffset(0)] internal ColumnSet4 mat; [FieldOffset(0)] internal ColumnSet4 mat;
[FieldOffset(16 * sizeof(float))] internal ColumnSet4 transpose; [FieldOffset(16 * sizeof(float))] internal ColumnSet4 transpose;
[FieldOffset(0 * sizeof(float))] internal Vec4 colum0; [FieldOffset(0 * sizeof(float))] internal Vec4 column0;
[FieldOffset(4 * sizeof(float))] internal Vec4 colum1; [FieldOffset(4 * sizeof(float))] internal Vec4 column1;
[FieldOffset(8 * sizeof(float))] internal Vec4 colum2; [FieldOffset(8 * sizeof(float))] internal Vec4 column2;
[FieldOffset(12 * sizeof(float))] internal Vec4 colum3; [FieldOffset(12 * sizeof(float))] internal Vec4 column3;
internal Matrix44(ColumnSet4 mat) internal Matrix44(ColumnSet4 mat)
{ {
@@ -161,6 +155,11 @@ namespace StgSharp.Mathematics.Graphic
public static Matrix44 ZNegativeUnit => 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);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe float Det() public unsafe float Det()
{ {
@@ -208,9 +207,13 @@ namespace StgSharp.Mathematics.Graphic
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe Matrix44 operator -(Matrix44 left, Matrix44 right) public static unsafe Matrix44 operator -(Matrix44 left, Matrix44 right)
{ {
return new Matrix44( return new Matrix44
right.mat.colum0 - left.mat.colum0, right.mat.colum1 - left.mat.colum1, {
right.mat.colum2 - left.mat.colum2, right.mat.colum3 - left.mat.colum3); column0 = right.column0 - left.column0,
column1 = right.column1 - left.column1,
column2 = right.column2 - left.column2,
column3 = right.column3 - left.column3
};
} }
public static bool operator !=(Matrix44 left, Matrix44 right) public static bool operator !=(Matrix44 left, Matrix44 right)
@@ -255,9 +258,13 @@ namespace StgSharp.Mathematics.Graphic
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe Matrix44 operator +(Matrix44 left, Matrix44 right) public static unsafe Matrix44 operator +(Matrix44 left, Matrix44 right)
{ {
Matrix44 ret = new Matrix44(); Matrix44 ret = new()
{
// InternalIO.Intrinsic.add_mat_4(&left.mat, &right.mat, &ret.mat); column0 = left.column0 + right.column0,
column1 = left.column1 + right.column1,
column2 = left.column2 + right.column2,
column3 = left.column3 + right.column3
};
return ret; return ret;
} }
+21 -23
View File
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Vec2.cs" // file="Vec2"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -86,6 +83,7 @@ namespace StgSharp.Mathematics.Graphic
public static Vec2 One public static Vec2 One
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new Vec2(1, 1); get => new Vec2(1, 1);
} }
+44 -64
View File
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="Vec3.cs" // file="Vec3"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -55,10 +52,7 @@ namespace StgSharp.Mathematics.Graphic
internal Vec3(M128 vector) internal Vec3(M128 vector)
{ {
Unsafe.SkipInit(out X); Unsafe.SkipInit(out this);
Unsafe.SkipInit(out Y);
Unsafe.SkipInit(out Z);
Unsafe.SkipInit(out v);
reg = vector; reg = vector;
reg.Member<uint>(3) = 0; reg.Member<uint>(3) = 0;
} }
@@ -75,49 +69,42 @@ namespace StgSharp.Mathematics.Graphic
public Vec3(Vec2 xy, float z) public Vec3(Vec2 xy, float z)
{ {
Unsafe.SkipInit(out X); Unsafe.SkipInit(out this);
Unsafe.SkipInit(out Y);
Unsafe.SkipInit(out Z);
Unsafe.SkipInit(out v);
reg = xy.reg; reg = xy.reg;
Z = z; Z = z;
} }
public Vec3(float x, float y, float z) public Vec3(float x, float y, float z)
{ {
Unsafe.SkipInit(out reg); Unsafe.SkipInit(out this);
Unsafe.SkipInit(out X);
Unsafe.SkipInit(out Y);
Unsafe.SkipInit(out Z);
v = new Vector3(x, y, z); v = new Vector3(x, y, z);
} }
public unsafe Vec2 XY public unsafe Vec2 XY
{ {
get => new Vec2(reg); [MethodImpl(MethodImplOptions.AggressiveInlining)]
set readonly get => new(reg);
{ [MethodImpl(MethodImplOptions.AggressiveInlining)]
fixed (Vector3* vptr = &v) { set => Unsafe.As<Vector3, Vector2>(ref v) = value.v;
*(Vector2*)vptr = value.v;
}
}
} }
public Vec3 XYZ public Vec3 XYZ
{ {
get => new(v); [MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => new(v);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => this = value; set => this = value;
} }
public static Vec3 Zero => new Vec3(0, 0, 0); public static Vec3 Zero => new(0, 0, 0);
public static Vec3 One => new Vec3(1, 1, 1); public static Vec3 One => new(1, 1, 1);
public static Vec3 UnitX => new Vec3(1, 0, 0); public static Vec3 UnitX => new(1, 0, 0);
public static Vec3 UnitY => new Vec3(0, 1, 0); public static Vec3 UnitY => new(0, 1, 0);
public static Vec3 UnitZ => new Vec3(0, 0, 1); public static Vec3 UnitZ => new(0, 0, 1);
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vec3 Cross(Vec3 left, Vec3 right) public static Vec3 Cross(Vec3 left, Vec3 right)
@@ -126,30 +113,24 @@ namespace StgSharp.Mathematics.Graphic
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Dot(Vec3 right) public readonly float Dot(Vec3 right)
{ {
return Vector3.Dot(v, right.v); return Vector3.Dot(v, right.v);
} }
public bool Equals(Vec3 other) public readonly bool Equals(Vec3 other)
{ {
return reg == other.reg; return reg == other.reg;
} }
public override bool Equals(object obj) public override readonly bool Equals(object obj)
{ {
if (obj is Vec3) return obj is not null && obj is Vec3 vec && this == vec;
{
return this == (Vec3)obj;
} else
{
return false;
}
} }
public static Vec3 FromSpan(ReadOnlySpan<float> span) public static Vec3 FromSpan(ReadOnlySpan<float> span)
{ {
Vec3 v = new Vec3(); Vec3 v = new();
span.CopyTo(MemoryMarshal.CreateSpan(ref v.X, 3)); span.CopyTo(MemoryMarshal.CreateSpan(ref v.X, 3));
return v; return v;
} }
@@ -169,7 +150,7 @@ namespace StgSharp.Mathematics.Graphic
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public float GetMaxValue() public readonly float GetMaxValue()
{ {
float ret = X; float ret = X;
ret = ret > Y ? ret : Y; ret = ret > Y ? ret : Y;
@@ -182,12 +163,12 @@ namespace StgSharp.Mathematics.Graphic
return Cross(left, right) == Zero; return Cross(left, right) == Zero;
} }
public override string ToString() public override readonly string ToString()
{ {
return $"[{X},{Y},{Z}]"; return $"[{X},{Y},{Z}]";
} }
public string ToString(string sample) public readonly string ToString(string sample)
{ {
return $"[{X.ToString(sample)},{Y.ToString(sample)},{Z.ToString(sample)}]"; return $"[{X.ToString(sample)},{Y.ToString(sample)},{Z.ToString(sample)}]";
} }
@@ -243,8 +224,7 @@ namespace StgSharp.Mathematics.Graphic
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe implicit operator Vec3((float, float, float) tuple) public static unsafe implicit operator Vec3((float, float, float) tuple)
{ {
Vec3 vec = new Vec3(*(Vector3*)&tuple); return Unsafe.As<(float,float,float), Vec3>(ref tuple);
return vec;
} }
IEnumerator IEnumerable.GetEnumerator() IEnumerator IEnumerable.GetEnumerator()
+28 -24
View File
@@ -1,30 +1,27 @@
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// file="IMatrix.cs" // file="IMatrix"
// Project: StgSharp // Project: StgSharp
// AuthorGroup: Nitload Space // AuthorGroup: Nitload
// Copyright (c) Nitload Space. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -32,9 +29,16 @@ using StgSharp.Graphics;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics;
using System.Text; using System.Text;
namespace StgSharp.Mathematics.Numeric namespace StgSharp.Mathematics.Numeric
{ {
public interface IMatrix<TSelf> where TSelf: IMatrix<TSelf> { } public interface IMatrix<TElement> where TElement: unmanaged, INumber<TElement>
{
ReadOnlySpan<TElement> AsSpan();
}
} }
@@ -5,26 +5,23 @@
// AuthorGroup: Nitload // AuthorGroup: Nitload
// Copyright (c) Nitload. All rights reserved. // Copyright (c) Nitload. 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
// The above copyright notice and // copies or substantial portions of the Software.
// this permission notice shall be included in all copies //
// or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// THE SOFTWARE IS PROVIDED “AS IS”, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // SOFTWARE.
// 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.
// //
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@@ -39,7 +36,7 @@ using System.Threading;
/// </summary> /// </summary>
public struct SamplingAdaptiveBackoff public struct SamplingAdaptiveBackoff
{ {
/*
private const int CONFIDENCE_THRESHOLD = 3; // Requires N consecutive sampling confirmations to switch strategies private const int CONFIDENCE_THRESHOLD = 3; // Requires N consecutive sampling confirmations to switch strategies
// Configuration constants // Configuration constants
@@ -455,5 +452,6 @@ public struct SamplingAdaptiveBackoff
} }
} }
/**/
} }
@@ -0,0 +1,175 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="SingleConsumerBell"
// 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.Threading;
namespace StgSharp.Threading
{
/// <summary>
/// A single-consumer bell/signal primitive.
/// </summary>
/// <remarks>
/// <para>Producers can call <see cref="Set" /> multiple times to publish signals. The bell
/// keeps a pending count of not-yet-consumed signals. The consumer uses <see
/// cref="Wait(object, CancellationToken)" /> or <see cref="TryWait(object)" /> to consume
/// signals. </para> <para>When a producer increments the pending count from 0 to 1, the
/// internal event is set to wake the consumer. Consuming via <see cref="TryWait(object)" />
/// or <see cref="Wait(object, CancellationToken)" /> clears the entire pending count
/// (aggregate consumption). If new signals arrive while resetting, the event is set again to
/// avoid missed signals. </para> <para>Ownership: only the specified <c> owner </c> can call
/// the consumer APIs. </para>
/// </remarks>
public sealed class SingleConsumerBell : IDisposable
{
private volatile bool _disposed;
private int _pending; // not volatile: used with Interlocked/Volatile APIs to avoid CS0420
private readonly ManualResetEventSlim _evt;
private readonly object _owner;
/// <summary>
/// Initializes a new instance of <see cref="SingleConsumerBell" />.
/// </summary>
/// <param name="owner">
/// The unique consumer identity; subsequent calls to Wait/TryWait must pass the same
/// reference.
/// </param>
/// <param name="spinCount">
/// Spin count passed to the underlying <see cref="ManualResetEventSlim" />.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="owner" /> is null.
/// </exception>
public SingleConsumerBell(object owner, int spinCount = 100)
{
_owner = owner ?? throw new ArgumentNullException(nameof(owner));
_evt = new ManualResetEventSlim(false, spinCount);
}
/// <summary>
/// Disposes the bell, sets the event to wake any waiting consumer, and releases
/// resources.
/// </summary>
public void Dispose()
{
_disposed = true;
_evt.Set();
_evt.Dispose();
}
/// <summary>
/// Publishes a signal by incrementing the not-yet-consumed count and returns the current
/// pending count.
/// </summary>
/// <remarks>
/// If the pending count transitions from 0 to 1, the event is set to wake the consumer.
/// </remarks>
/// <returns>
/// The current pending count including this call.
/// </returns>
public int Set()
{
if (_disposed) {
return Volatile.Read(ref _pending);
}
// Increment pending; if we transitioned 0 -> 1, set the event to wake the consumer
int newCount = Interlocked.Increment(ref _pending);
if (newCount == 1) {
_evt.Set();
}
return newCount;
}
/// <summary>
/// Attempts to consume any pending signals without blocking.
/// </summary>
/// <param name="consumer">
/// The consumer object; must be the same reference provided at construction.
/// </param>
/// <returns>
/// <c> true </c> if a signal was available (pending or event set); otherwise
/// <c>false</c>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Thrown if <paramref name="consumer" /> is not the owner.
/// </exception>
public bool TryWait(object consumer)
{
if (!ReferenceEquals(_owner, consumer)) {
throw new InvalidOperationException("This bell is owned by another consumer.");
}
if (!_evt.IsSet && Volatile.Read(ref _pending) == 0) {
return false;
}
// Aggregate consumption: clear pending and reset event
_ = Interlocked.Exchange(ref _pending, 0);
_evt.Reset();
// If concurrent Set happened during reset, re-set the event to avoid lost signals
if (Volatile.Read(ref _pending) != 0)
{
_evt.Set();
}
return true;
}
/// <summary>
/// Blocks until a signal is available, then consumes all pending signals.
/// </summary>
/// <param name="consumer">
/// The consumer object; must be the same reference provided at construction.
/// </param>
/// <param name="cancellationToken">
/// A token to cancel the wait.
/// </param>
/// <exception cref="InvalidOperationException">
/// Thrown if <paramref name="consumer" /> is not the owner.
/// </exception>
public void Wait(object consumer, CancellationToken cancellationToken = default)
{
if (!ReferenceEquals(_owner, consumer)) {
throw new InvalidOperationException("This bell is owned by another consumer.");
}
_evt.Wait(cancellationToken);
// Consume this round of signals: clear pending and handle reset/concurrency
_ = Interlocked.Exchange(ref _pending, 0);
_evt.Reset();
if (Volatile.Read(ref _pending) != 0) {
_evt.Set();
}
}
}
}
+2 -6
View File
@@ -1,7 +1,3 @@
#ifdef _MSC_VER
#pragma once
#endif
#ifndef SSC_INTRIN #ifndef SSC_INTRIN
#define SSC_INTRIN #define SSC_INTRIN
@@ -128,7 +124,7 @@ typedef struct sn_intrinsic {
SCALARMATARITHMETIC f32_scalar_mul; SCALARMATARITHMETIC f32_scalar_mul;
MATARITHMETIC f32_sub; MATARITHMETIC f32_sub;
MATTRANSPOSEPROC f32_transpose; MATTRANSPOSEPROC f32_transpose;
VECTORNORMALIZEPROC normalize_3; VECTORNORMALIZEPROC f32_normalize_3;
} sn_intrinsic; } sn_intrinsic;
typedef enum most_advanced_instruction { typedef enum most_advanced_instruction {
@@ -145,4 +141,4 @@ typedef enum most_advanced_instruction {
#endif #endif
} most_advanced_instruction; } most_advanced_instruction;
#endif // !SSC_INTRIN #endif
+4 -11
View File
@@ -1,15 +1,15 @@
#ifndef SN_MATKERNEL #ifndef SN_MATKERNEL
#define SN_MATKERNEL #define SN_MATKERNEL
#include <immintrin.h>
#define ELEMENTSIZE(T) sizeof(T) #define ELEMENTSIZE(T) sizeof(T)
#define XMMCOUNT(T) sizeof(T) #define XMMCOUNT(T) sizeof(T)
#define YMMCOUNT(T) sizeof(T) / 2 #define YMMCOUNT(T) sizeof(T) / 2
#define ZMMCOUNT(T) sizeof(T) / 4 #define ZMMCOUNT(T) sizeof(T) / 4
#include <immintrin.h>
#define MAT_KERNEL(T) \ #define MAT_KERNEL(T) \
union mat_kernel_##T##{ \ union { \
__m128 xmm[XMMCOUNT(T)]; \ __m128 xmm[XMMCOUNT(T)]; \
__m256 ymm[YMMCOUNT(T)]; \ __m256 ymm[YMMCOUNT(T)]; \
__m512 zmm[ZMMCOUNT(T)]; \ __m512 zmm[ZMMCOUNT(T)]; \
@@ -17,18 +17,11 @@
} }
#define VEC(T) \ #define VEC(T) \
union vec_##T##{ \ union { \
__m128 xmm[XMMCOUNT(T) / 4]; \ __m128 xmm[XMMCOUNT(T) / 4]; \
__m256 ymm[YMMCOUNT(T) / 4]; \ __m256 ymm[YMMCOUNT(T) / 4]; \
__m512 zmm[ZMMCOUNT(T) / 4]; \ __m512 zmm[ZMMCOUNT(T) / 4]; \
T v[4]; \ T v[4]; \
} }
/*
#undef ELEMENTSIZE
#undef XMMCOUNT
#undef YMMCOUNT
#undef ZMMCOUNT
/**/
#endif #endif
+5 -6
View File
@@ -1,7 +1,6 @@
#include "StgSharpNative.h" #include "StgSharpNative.h"
#include "sn_intrinsic.h" #include "sn_intrinsic.h"
#if defined(_MSC_VER) && !defined(__clang__) #if defined(_MSC_VER) && !defined(__clang__)
#include <intrin.h> #include <intrin.h>
#include <isa_availability.h> #include <isa_availability.h>
@@ -71,7 +70,7 @@ void load_intrinsic_sse(sn_intrinsic *context)
context->f32_scalar_mul = f32_scalar_mul_sse; context->f32_scalar_mul = f32_scalar_mul_sse;
context->f32_sub = (MATARITHMETIC)f32_sub_sse; context->f32_sub = (MATARITHMETIC)f32_sub_sse;
context->f32_transpose = (MATTRANSPOSEPROC)f32_transpose_sse; context->f32_transpose = (MATTRANSPOSEPROC)f32_transpose_sse;
context->normalize_3 = normalize; context->f32_normalize_3 = f32_normalize;
} }
void load_intrinsic_avx(sn_intrinsic *context) void load_intrinsic_avx(sn_intrinsic *context)
@@ -80,11 +79,11 @@ void load_intrinsic_avx(sn_intrinsic *context)
context->factorial_simd = factorial_simd_sse; context->factorial_simd = factorial_simd_sse;
context->index_pair = index_pair_sse; context->index_pair = index_pair_sse;
context->f32_add = (MATARITHMETIC)f32_add_avx; context->f32_add = (MATARITHMETIC)f32_add_avx;
context->f32_fma = (void(*)(void*, void*, void*))f32_fma_sse; context->f32_fma = (void (*)(void *, void *, void *))f32_fma_sse;
context->f32_scalar_mul = f32_scalar_mul_avx; context->f32_scalar_mul = f32_scalar_mul_avx;
context->f32_sub = (MATARITHMETIC)f32_sub_avx; context->f32_sub = (MATARITHMETIC)f32_sub_avx;
context->f32_transpose = (MATTRANSPOSEPROC)f32_transpose_avx; context->f32_transpose = (MATTRANSPOSEPROC)f32_transpose_avx;
context->normalize_3 = normalize; context->f32_normalize_3 = f32_normalize;
} }
void load_intrinsic_512(sn_intrinsic *context) void load_intrinsic_512(sn_intrinsic *context)
@@ -93,9 +92,9 @@ void load_intrinsic_512(sn_intrinsic *context)
context->factorial_simd = factorial_simd_sse; context->factorial_simd = factorial_simd_sse;
context->index_pair = index_pair_sse; context->index_pair = index_pair_sse;
context->f32_add = (MATARITHMETIC)f32_add_512; context->f32_add = (MATARITHMETIC)f32_add_512;
context->f32_fma = (void(*)(void*, void*, void*))f32_fma_sse; context->f32_fma = (void (*)(void *, void *, void *))f32_fma_sse;
context->f32_scalar_mul = f32_scalar_mul_512; context->f32_scalar_mul = f32_scalar_mul_512;
context->f32_sub = (MATARITHMETIC)f32_sub_512; context->f32_sub = (MATARITHMETIC)f32_sub_512;
context->f32_transpose = (MATTRANSPOSEPROC)f32_transpose_512; context->f32_transpose = (MATTRANSPOSEPROC)f32_transpose_512;
context->normalize_3 = normalize; context->f32_normalize_3 = f32_normalize;
} }
+1 -1
View File
@@ -1,7 +1,7 @@
#include "sn_intrinsic.h" #include "sn_intrinsic.h"
#include "sn_internal.h" #include "sn_internal.h"
SN_API void SN_DECL normalize(VEC(float) *restrict source, VEC(float) *restrict target) INTERNAL void SN_DECL f32_normalize(VEC(float) *restrict source, VEC(float) *restrict target)
{ {
register __m128 s = _mm_load_ps(&source->xmm); register __m128 s = _mm_load_ps(&source->xmm);
register __m128 a_length_sq = _mm_mul_ps(s, s); register __m128 a_length_sq = _mm_mul_ps(s, s);