mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-25 12:38:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
5557 changed files with 768360 additions and 0 deletions
68
brutal.box2d/Brutal.Box2D/B2Joint.cs
Normal file
68
brutal.box2d/Brutal.Box2D/B2Joint.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.InteropServices.Marshalling;
|
||||
|
||||
namespace Brutal.Box2DApi;
|
||||
|
||||
[NativeMarshalling(typeof(B2JointMarshaller<B2Joint>))]
|
||||
public partial class B2Joint : IBox2DObject<B2Joint>
|
||||
{
|
||||
[FieldOffset(0)]
|
||||
internal ulong InteropValue;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsNull()
|
||||
{
|
||||
return InteropValue == 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(B2Joint? x, B2Joint? y)
|
||||
{
|
||||
if (x is null && y is null)
|
||||
return true;
|
||||
|
||||
if (x is null || y is null)
|
||||
return false;
|
||||
|
||||
return x.InteropValue == y.InteropValue;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int GetHashCode(B2Joint obj)
|
||||
{
|
||||
if (obj.IsNull())
|
||||
return 0;
|
||||
|
||||
return obj.InteropValue.GetHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
[CustomMarshaller(typeof(B2Joint), MarshalMode.Default, typeof(B2JointMarshaller<B2Joint>))]
|
||||
[CustomMarshaller(typeof(B2DistanceJoint), MarshalMode.Default, typeof(B2JointMarshaller<B2DistanceJoint>))]
|
||||
[CustomMarshaller(typeof(B2FilterJoint), MarshalMode.Default, typeof(B2JointMarshaller<B2FilterJoint>))]
|
||||
[CustomMarshaller(typeof(B2MotorJoint), MarshalMode.Default, typeof(B2JointMarshaller<B2MotorJoint>))]
|
||||
[CustomMarshaller(typeof(B2MouseJoint), MarshalMode.Default, typeof(B2JointMarshaller<B2MouseJoint>))]
|
||||
[CustomMarshaller(typeof(B2PrismaticJoint), MarshalMode.Default, typeof(B2JointMarshaller<B2PrismaticJoint>))]
|
||||
[CustomMarshaller(typeof(B2RevoluteJoint), MarshalMode.Default, typeof(B2JointMarshaller<B2RevoluteJoint>))]
|
||||
[CustomMarshaller(typeof(B2WeldJoint), MarshalMode.Default, typeof(B2JointMarshaller<B2WeldJoint>))]
|
||||
[CustomMarshaller(typeof(B2WheelJoint), MarshalMode.Default, typeof(B2JointMarshaller<B2WheelJoint>))]
|
||||
internal static class B2JointMarshaller<T>
|
||||
where T : B2Joint, new()
|
||||
{
|
||||
internal static ulong ConvertToUnmanaged(T? managed)
|
||||
{
|
||||
if (managed is null)
|
||||
return 0;
|
||||
|
||||
return managed.InteropValue;
|
||||
}
|
||||
|
||||
internal static T? ConvertToManaged(ulong unmanaged)
|
||||
{
|
||||
if (unmanaged == 0)
|
||||
return null;
|
||||
|
||||
return new T { InteropValue = unmanaged };
|
||||
}
|
||||
}
|
||||
32
brutal.box2d/Brutal.Box2D/Box2D.cs
Normal file
32
brutal.box2d/Brutal.Box2D/Box2D.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Brutal.Box2DApi;
|
||||
|
||||
/// <summary>
|
||||
/// A 2D physics engine.
|
||||
/// </summary>
|
||||
public static partial class Box2D
|
||||
{
|
||||
private const string Dll =
|
||||
#if DEBUG
|
||||
"box2dd";
|
||||
#else
|
||||
"box2d";
|
||||
#endif
|
||||
|
||||
static Box2D()
|
||||
{
|
||||
// Load the GLFW native library
|
||||
var glfwNative = NativeLibrary.Load(Dll, typeof(Box2D).Assembly, DllImportSearchPath.AssemblyDirectory);
|
||||
|
||||
// Assign the native library to the assembly resolver
|
||||
NativeLibrary.SetDllImportResolver(
|
||||
typeof(Box2D).Assembly,
|
||||
(libraryName, _, _) =>
|
||||
{
|
||||
return glfwNative;
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
2459
brutal.box2d/Brutal.Box2D/Box2D.gen.cs
Normal file
2459
brutal.box2d/Brutal.Box2D/Box2D.gen.cs
Normal file
File diff suppressed because it is too large
Load diff
539
brutal.box2d/Brutal.Box2D/Enumerations.gen.cs
Normal file
539
brutal.box2d/Brutal.Box2D/Enumerations.gen.cs
Normal file
|
|
@ -0,0 +1,539 @@
|
|||
/*
|
||||
* @brief Contains the Box2D enumerations ported to C#.
|
||||
*
|
||||
* @warning This file is auto-generated by Brutal.Box2D.Generate.
|
||||
* Do not edit this file directly.
|
||||
* If you want to change the generated code, modify the generation rules.
|
||||
*/
|
||||
namespace Brutal.Box2DApi
|
||||
{
|
||||
/// Describes the TOI output
|
||||
public enum B2ToiState : uint
|
||||
{
|
||||
///
|
||||
Unknown = 0U,
|
||||
|
||||
///
|
||||
Failed = 1U,
|
||||
|
||||
///
|
||||
Overlapped = 2U,
|
||||
|
||||
///
|
||||
Hit = 3U,
|
||||
|
||||
///
|
||||
Separated = 4U,
|
||||
}
|
||||
|
||||
/// The body simulation type.
|
||||
/// Each body is one of these three types. The type determines how the body behaves in the simulation.
|
||||
public enum B2BodyType : uint
|
||||
{
|
||||
/// zero mass, zero velocity, may be manually moved
|
||||
Static = 0,
|
||||
|
||||
/// zero mass, velocity set by user, moved by solver
|
||||
Kinematic = 1,
|
||||
|
||||
/// positive mass, velocity determined by forces, moved by solver
|
||||
Dynamic = 2,
|
||||
|
||||
/// number of body types
|
||||
TypeCount = 3U,
|
||||
}
|
||||
|
||||
/// Shape type
|
||||
public enum B2ShapeType : uint
|
||||
{
|
||||
/// A circle with an offset
|
||||
Circle = 0U,
|
||||
|
||||
/// A capsule is an extruded circle
|
||||
Capsule = 1U,
|
||||
|
||||
/// A line segment
|
||||
Segment = 2U,
|
||||
|
||||
/// A convex polygon
|
||||
Polygon = 3U,
|
||||
|
||||
/// A line segment owned by a chain shape
|
||||
ChainSegment = 4U,
|
||||
|
||||
/// The number of shape types
|
||||
TypeCount = 5U,
|
||||
}
|
||||
|
||||
/// Joint type enumeration
|
||||
/// This is useful because all joint types use b2JointId and sometimes you
|
||||
/// want to get the type of a joint.
|
||||
public enum B2JointType : uint
|
||||
{
|
||||
///
|
||||
Distance = 0U,
|
||||
|
||||
///
|
||||
Filter = 1U,
|
||||
|
||||
///
|
||||
Motor = 2U,
|
||||
|
||||
///
|
||||
Mouse = 3U,
|
||||
|
||||
///
|
||||
Prismatic = 4U,
|
||||
|
||||
///
|
||||
Revolute = 5U,
|
||||
|
||||
///
|
||||
Weld = 6U,
|
||||
|
||||
///
|
||||
Wheel = 7U,
|
||||
}
|
||||
|
||||
/// These colors are used for debug draw and mostly match the named SVG colors.
|
||||
/// See https://www.rapidtables.com/web/color/index.html
|
||||
/// https://johndecember.com/html/spec/colorsvg.html
|
||||
/// https://upload.wikimedia.org/wikipedia/commons/2/2b/SVG_Recognized_color_keyword_names.svg
|
||||
public enum B2HexColor : uint
|
||||
{
|
||||
///
|
||||
AliceBlue = 0xF0F8FF,
|
||||
|
||||
///
|
||||
AntiqueWhite = 0xFAEBD7,
|
||||
|
||||
///
|
||||
Aqua = 0x00FFFF,
|
||||
|
||||
///
|
||||
Aquamarine = 0x7FFFD4,
|
||||
|
||||
///
|
||||
Azure = 0xF0FFFF,
|
||||
|
||||
///
|
||||
Beige = 0xF5F5DC,
|
||||
|
||||
///
|
||||
Bisque = 0xFFE4C4,
|
||||
|
||||
///
|
||||
Black = 0x000000,
|
||||
|
||||
///
|
||||
BlanchedAlmond = 0xFFEBCD,
|
||||
|
||||
///
|
||||
Blue = 0x0000FF,
|
||||
|
||||
///
|
||||
BlueViolet = 0x8A2BE2,
|
||||
|
||||
///
|
||||
Brown = 0xA52A2A,
|
||||
|
||||
///
|
||||
Burlywood = 0xDEB887,
|
||||
|
||||
///
|
||||
CadetBlue = 0x5F9EA0,
|
||||
|
||||
///
|
||||
Chartreuse = 0x7FFF00,
|
||||
|
||||
///
|
||||
Chocolate = 0xD2691E,
|
||||
|
||||
///
|
||||
Coral = 0xFF7F50,
|
||||
|
||||
///
|
||||
CornflowerBlue = 0x6495ED,
|
||||
|
||||
///
|
||||
Cornsilk = 0xFFF8DC,
|
||||
|
||||
///
|
||||
Crimson = 0xDC143C,
|
||||
|
||||
///
|
||||
Cyan = 0x00FFFF,
|
||||
|
||||
///
|
||||
DarkBlue = 0x00008B,
|
||||
|
||||
///
|
||||
DarkCyan = 0x008B8B,
|
||||
|
||||
///
|
||||
DarkGoldenRod = 0xB8860B,
|
||||
|
||||
///
|
||||
DarkGray = 0xA9A9A9,
|
||||
|
||||
///
|
||||
DarkGreen = 0x006400,
|
||||
|
||||
///
|
||||
DarkKhaki = 0xBDB76B,
|
||||
|
||||
///
|
||||
DarkMagenta = 0x8B008B,
|
||||
|
||||
///
|
||||
DarkOliveGreen = 0x556B2F,
|
||||
|
||||
///
|
||||
DarkOrange = 0xFF8C00,
|
||||
|
||||
///
|
||||
DarkOrchid = 0x9932CC,
|
||||
|
||||
///
|
||||
DarkRed = 0x8B0000,
|
||||
|
||||
///
|
||||
DarkSalmon = 0xE9967A,
|
||||
|
||||
///
|
||||
DarkSeaGreen = 0x8FBC8F,
|
||||
|
||||
///
|
||||
DarkSlateBlue = 0x483D8B,
|
||||
|
||||
///
|
||||
DarkSlateGray = 0x2F4F4F,
|
||||
|
||||
///
|
||||
DarkTurquoise = 0x00CED1,
|
||||
|
||||
///
|
||||
DarkViolet = 0x9400D3,
|
||||
|
||||
///
|
||||
DeepPink = 0xFF1493,
|
||||
|
||||
///
|
||||
DeepSkyBlue = 0x00BFFF,
|
||||
|
||||
///
|
||||
DimGray = 0x696969,
|
||||
|
||||
///
|
||||
DodgerBlue = 0x1E90FF,
|
||||
|
||||
///
|
||||
FireBrick = 0xB22222,
|
||||
|
||||
///
|
||||
FloralWhite = 0xFFFAF0,
|
||||
|
||||
///
|
||||
ForestGreen = 0x228B22,
|
||||
|
||||
///
|
||||
Fuchsia = 0xFF00FF,
|
||||
|
||||
///
|
||||
Gainsboro = 0xDCDCDC,
|
||||
|
||||
///
|
||||
GhostWhite = 0xF8F8FF,
|
||||
|
||||
///
|
||||
Gold = 0xFFD700,
|
||||
|
||||
///
|
||||
GoldenRod = 0xDAA520,
|
||||
|
||||
///
|
||||
Gray = 0x808080,
|
||||
|
||||
///
|
||||
Green = 0x008000,
|
||||
|
||||
///
|
||||
GreenYellow = 0xADFF2F,
|
||||
|
||||
///
|
||||
HoneyDew = 0xF0FFF0,
|
||||
|
||||
///
|
||||
HotPink = 0xFF69B4,
|
||||
|
||||
///
|
||||
IndianRed = 0xCD5C5C,
|
||||
|
||||
///
|
||||
Indigo = 0x4B0082,
|
||||
|
||||
///
|
||||
Ivory = 0xFFFFF0,
|
||||
|
||||
///
|
||||
Khaki = 0xF0E68C,
|
||||
|
||||
///
|
||||
Lavender = 0xE6E6FA,
|
||||
|
||||
///
|
||||
LavenderBlush = 0xFFF0F5,
|
||||
|
||||
///
|
||||
LawnGreen = 0x7CFC00,
|
||||
|
||||
///
|
||||
LemonChiffon = 0xFFFACD,
|
||||
|
||||
///
|
||||
LightBlue = 0xADD8E6,
|
||||
|
||||
///
|
||||
LightCoral = 0xF08080,
|
||||
|
||||
///
|
||||
LightCyan = 0xE0FFFF,
|
||||
|
||||
///
|
||||
LightGoldenRodYellow = 0xFAFAD2,
|
||||
|
||||
///
|
||||
LightGray = 0xD3D3D3,
|
||||
|
||||
///
|
||||
LightGreen = 0x90EE90,
|
||||
|
||||
///
|
||||
LightPink = 0xFFB6C1,
|
||||
|
||||
///
|
||||
LightSalmon = 0xFFA07A,
|
||||
|
||||
///
|
||||
LightSeaGreen = 0x20B2AA,
|
||||
|
||||
///
|
||||
LightSkyBlue = 0x87CEFA,
|
||||
|
||||
///
|
||||
LightSlateGray = 0x778899,
|
||||
|
||||
///
|
||||
LightSteelBlue = 0xB0C4DE,
|
||||
|
||||
///
|
||||
LightYellow = 0xFFFFE0,
|
||||
|
||||
///
|
||||
Lime = 0x00FF00,
|
||||
|
||||
///
|
||||
LimeGreen = 0x32CD32,
|
||||
|
||||
///
|
||||
Linen = 0xFAF0E6,
|
||||
|
||||
///
|
||||
Magenta = 0xFF00FF,
|
||||
|
||||
///
|
||||
Maroon = 0x800000,
|
||||
|
||||
///
|
||||
MediumAquaMarine = 0x66CDAA,
|
||||
|
||||
///
|
||||
MediumBlue = 0x0000CD,
|
||||
|
||||
///
|
||||
MediumOrchid = 0xBA55D3,
|
||||
|
||||
///
|
||||
MediumPurple = 0x9370DB,
|
||||
|
||||
///
|
||||
MediumSeaGreen = 0x3CB371,
|
||||
|
||||
///
|
||||
MediumSlateBlue = 0x7B68EE,
|
||||
|
||||
///
|
||||
MediumSpringGreen = 0x00FA9A,
|
||||
|
||||
///
|
||||
MediumTurquoise = 0x48D1CC,
|
||||
|
||||
///
|
||||
MediumVioletRed = 0xC71585,
|
||||
|
||||
///
|
||||
MidnightBlue = 0x191970,
|
||||
|
||||
///
|
||||
MintCream = 0xF5FFFA,
|
||||
|
||||
///
|
||||
MistyRose = 0xFFE4E1,
|
||||
|
||||
///
|
||||
Moccasin = 0xFFE4B5,
|
||||
|
||||
///
|
||||
NavajoWhite = 0xFFDEAD,
|
||||
|
||||
///
|
||||
Navy = 0x000080,
|
||||
|
||||
///
|
||||
OldLace = 0xFDF5E6,
|
||||
|
||||
///
|
||||
Olive = 0x808000,
|
||||
|
||||
///
|
||||
OliveDrab = 0x6B8E23,
|
||||
|
||||
///
|
||||
Orange = 0xFFA500,
|
||||
|
||||
///
|
||||
OrangeRed = 0xFF4500,
|
||||
|
||||
///
|
||||
Orchid = 0xDA70D6,
|
||||
|
||||
///
|
||||
PaleGoldenRod = 0xEEE8AA,
|
||||
|
||||
///
|
||||
PaleGreen = 0x98FB98,
|
||||
|
||||
///
|
||||
PaleTurquoise = 0xAFEEEE,
|
||||
|
||||
///
|
||||
PaleVioletRed = 0xDB7093,
|
||||
|
||||
///
|
||||
PapayaWhip = 0xFFEFD5,
|
||||
|
||||
///
|
||||
PeachPuff = 0xFFDAB9,
|
||||
|
||||
///
|
||||
Peru = 0xCD853F,
|
||||
|
||||
///
|
||||
Pink = 0xFFC0CB,
|
||||
|
||||
///
|
||||
Plum = 0xDDA0DD,
|
||||
|
||||
///
|
||||
PowderBlue = 0xB0E0E6,
|
||||
|
||||
///
|
||||
Purple = 0x800080,
|
||||
|
||||
///
|
||||
RebeccaPurple = 0x663399,
|
||||
|
||||
///
|
||||
Red = 0xFF0000,
|
||||
|
||||
///
|
||||
RosyBrown = 0xBC8F8F,
|
||||
|
||||
///
|
||||
RoyalBlue = 0x4169E1,
|
||||
|
||||
///
|
||||
SaddleBrown = 0x8B4513,
|
||||
|
||||
///
|
||||
Salmon = 0xFA8072,
|
||||
|
||||
///
|
||||
SandyBrown = 0xF4A460,
|
||||
|
||||
///
|
||||
SeaGreen = 0x2E8B57,
|
||||
|
||||
///
|
||||
SeaShell = 0xFFF5EE,
|
||||
|
||||
///
|
||||
Sienna = 0xA0522D,
|
||||
|
||||
///
|
||||
Silver = 0xC0C0C0,
|
||||
|
||||
///
|
||||
SkyBlue = 0x87CEEB,
|
||||
|
||||
///
|
||||
SlateBlue = 0x6A5ACD,
|
||||
|
||||
///
|
||||
SlateGray = 0x708090,
|
||||
|
||||
///
|
||||
Snow = 0xFFFAFA,
|
||||
|
||||
///
|
||||
SpringGreen = 0x00FF7F,
|
||||
|
||||
///
|
||||
SteelBlue = 0x4682B4,
|
||||
|
||||
///
|
||||
Tan = 0xD2B48C,
|
||||
|
||||
///
|
||||
Teal = 0x008080,
|
||||
|
||||
///
|
||||
Thistle = 0xD8BFD8,
|
||||
|
||||
///
|
||||
Tomato = 0xFF6347,
|
||||
|
||||
///
|
||||
Turquoise = 0x40E0D0,
|
||||
|
||||
///
|
||||
Violet = 0xEE82EE,
|
||||
|
||||
///
|
||||
Wheat = 0xF5DEB3,
|
||||
|
||||
///
|
||||
White = 0xFFFFFF,
|
||||
|
||||
///
|
||||
WhiteSmoke = 0xF5F5F5,
|
||||
|
||||
///
|
||||
Yellow = 0xFFFF00,
|
||||
|
||||
///
|
||||
YellowGreen = 0x9ACD32,
|
||||
|
||||
///
|
||||
Box2DRed = 0xDC3132,
|
||||
|
||||
///
|
||||
Box2DBlue = 0x30AEBF,
|
||||
|
||||
///
|
||||
Box2DGreen = 0x8CC924,
|
||||
|
||||
///
|
||||
Box2DYellow = 0xFFEE8C,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
Brutal.Box2D redistributes the third-party components listed below. Each is
|
||||
reproduced with the license that governs it.
|
||||
|
||||
============================================================
|
||||
Box2D 3.1.1 -- MIT -- https://github.com/erincatto/box2d
|
||||
Shipped as: box2d.dll / libbox2d.so / libbox2d.dylib
|
||||
============================================================
|
||||
|
||||
Built from Box2D's own sources only. The upstream project also carries glad and
|
||||
jsmn; both belong to its samples application, which this build does not produce,
|
||||
so neither reaches the libraries shipped here.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Erin Catto
|
||||
|
||||
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.
|
||||
239
brutal.box2d/Brutal.Box2D/Structs.cs
Normal file
239
brutal.box2d/Brutal.Box2D/Structs.cs
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
// ReSharper disable MemberCanBePrivate.Global
|
||||
|
||||
using Brutal.Numerics;
|
||||
|
||||
namespace Brutal.Box2DApi;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for Box2D objects.
|
||||
/// </summary>
|
||||
public interface IBox2DObject<T> : INullable, IEqualityComparer<T> { }
|
||||
|
||||
public partial record struct B2World : IBox2DObject<B2World>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public bool IsNull()
|
||||
{
|
||||
return Index1 == 0 && Generation == 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(B2World x, B2World y)
|
||||
{
|
||||
return x.Index1 == y.Index1 && x.Generation == y.Generation;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int GetHashCode(B2World obj)
|
||||
{
|
||||
return HashCode.Combine(obj.Index1, obj.Generation);
|
||||
}
|
||||
}
|
||||
|
||||
public partial record struct B2Body : IBox2DObject<B2Body>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public bool IsNull()
|
||||
{
|
||||
return Index1 == 0 && Generation == 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(B2Body x, B2Body y)
|
||||
{
|
||||
return x.Index1 == y.Index1 && x.Generation == y.Generation;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int GetHashCode(B2Body obj)
|
||||
{
|
||||
return HashCode.Combine(obj.Index1, obj.Generation);
|
||||
}
|
||||
}
|
||||
|
||||
public partial record struct B2Chain : IBox2DObject<B2Chain>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public bool IsNull()
|
||||
{
|
||||
return Index1 == 0 && Generation == 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(B2Chain x, B2Chain y)
|
||||
{
|
||||
return x.Index1 == y.Index1 && x.Generation == y.Generation;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int GetHashCode(B2Chain obj)
|
||||
{
|
||||
return HashCode.Combine(obj.Index1, obj.Generation);
|
||||
}
|
||||
}
|
||||
|
||||
public partial record struct B2Shape : IBox2DObject<B2Shape>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public bool IsNull()
|
||||
{
|
||||
return Index1 == 0 && Generation == 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Equals(B2Shape x, B2Shape y)
|
||||
{
|
||||
return x.Index1 == y.Index1 && x.Generation == y.Generation;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public int GetHashCode(B2Shape obj)
|
||||
{
|
||||
return HashCode.Combine(obj.Index1, obj.Generation);
|
||||
}
|
||||
}
|
||||
|
||||
public partial struct B2BodyDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultBodyDef"/>
|
||||
public static readonly B2BodyDef Default = Box2D.DefaultBodyDef();
|
||||
}
|
||||
|
||||
public partial struct B2ChainDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultChainDef"/>
|
||||
public static readonly B2ChainDef Default = Box2D.DefaultChainDef();
|
||||
}
|
||||
|
||||
public partial struct B2DebugDraw
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultDebugDraw"/>
|
||||
public static readonly B2DebugDraw Default = Box2D.DefaultDebugDraw();
|
||||
}
|
||||
|
||||
public partial struct B2DistanceJointDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultDistanceJointDef"/>
|
||||
public static readonly B2DistanceJointDef Default = Box2D.DefaultDistanceJointDef();
|
||||
}
|
||||
|
||||
public partial struct B2ExplosionDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultExplosionDef"/>
|
||||
public static readonly B2ExplosionDef Default = Box2D.DefaultExplosionDef();
|
||||
}
|
||||
|
||||
public partial struct B2Filter
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultFilter"/>
|
||||
public static readonly B2Filter Default = Box2D.DefaultFilter();
|
||||
}
|
||||
|
||||
public partial struct B2FilterJointDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultFilterJointDef"/>
|
||||
public static readonly B2FilterJointDef Default = Box2D.DefaultFilterJointDef();
|
||||
}
|
||||
|
||||
public partial struct B2MotorJointDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultMotorJointDef"/>
|
||||
public static readonly B2MotorJointDef Default = Box2D.DefaultMotorJointDef();
|
||||
}
|
||||
|
||||
public partial struct B2MouseJointDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultMouseJointDef"/>
|
||||
public static readonly B2MouseJointDef Default = Box2D.DefaultMouseJointDef();
|
||||
}
|
||||
|
||||
public partial struct B2PrismaticJointDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultPrismaticJointDef"/>
|
||||
public static readonly B2PrismaticJointDef Default = Box2D.DefaultPrismaticJointDef();
|
||||
}
|
||||
|
||||
public partial struct B2QueryFilter
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultQueryFilter"/>
|
||||
public static readonly B2QueryFilter Default = Box2D.DefaultQueryFilter();
|
||||
}
|
||||
|
||||
public partial struct B2RevoluteJointDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultRevoluteJointDef"/>
|
||||
public static readonly B2RevoluteJointDef Default = Box2D.DefaultRevoluteJointDef();
|
||||
}
|
||||
|
||||
public partial struct B2WheelJointDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultWheelJointDef"/>
|
||||
public static readonly B2WheelJointDef Default = Box2D.DefaultWheelJointDef();
|
||||
}
|
||||
|
||||
public partial struct B2WeldJointDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultWeldJointDef"/>
|
||||
public static readonly B2WeldJointDef Default = Box2D.DefaultWeldJointDef();
|
||||
}
|
||||
|
||||
public partial struct B2SurfaceMaterial
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultSurfaceMaterial"/>
|
||||
public static readonly B2SurfaceMaterial Default = Box2D.DefaultSurfaceMaterial();
|
||||
}
|
||||
|
||||
public partial struct B2ShapeDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultShapeDef"/>
|
||||
public static readonly B2ShapeDef Default = Box2D.DefaultShapeDef();
|
||||
}
|
||||
|
||||
public partial struct B2WorldDef
|
||||
{
|
||||
/// <inheritdoc cref="Box2D.DefaultWorldDef"/>
|
||||
public static readonly B2WorldDef Default = Box2D.DefaultWorldDef();
|
||||
}
|
||||
|
||||
public partial struct B2Rot
|
||||
{
|
||||
/// <summary>
|
||||
/// An identity rotation.
|
||||
/// </summary>
|
||||
public static readonly B2Rot Identity = new(0);
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a rotation by sine and cosine values.
|
||||
/// </summary>
|
||||
public B2Rot(float sine, float cosine)
|
||||
{
|
||||
S = sine;
|
||||
C = cosine;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a rotation by an angle in radians.
|
||||
/// </summary>
|
||||
public B2Rot(float angle)
|
||||
{
|
||||
S = MathF.Sin(angle);
|
||||
C = MathF.Cos(angle);
|
||||
}
|
||||
}
|
||||
|
||||
public partial struct B2Transform
|
||||
{
|
||||
/// <summary>
|
||||
/// An identity transformation.
|
||||
/// </summary>
|
||||
public static readonly B2Transform Identity = new(float2.Zero, B2Rot.Identity);
|
||||
|
||||
/// <summary>
|
||||
/// Specifies a transformation with a position and a rotation.
|
||||
/// </summary>
|
||||
public B2Transform(float2 p, B2Rot q)
|
||||
{
|
||||
P = p;
|
||||
Q = q;
|
||||
}
|
||||
}
|
||||
4679
brutal.box2d/Brutal.Box2D/Structs.gen.cs
Normal file
4679
brutal.box2d/Brutal.Box2D/Structs.gen.cs
Normal file
File diff suppressed because it is too large
Load diff
177
brutal.box2d/Brutal.Box2D/Typedefs.gen.cs
Normal file
177
brutal.box2d/Brutal.Box2D/Typedefs.gen.cs
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
/*
|
||||
* @brief Contains the Box2D typedefs ported to C#.
|
||||
*
|
||||
* @warning This file is auto-generated by Brutal.Box2D.Generate.
|
||||
* Do not edit this file directly.
|
||||
* If you want to change the generated code, modify the generation rules.
|
||||
*/
|
||||
using System.Runtime.InteropServices;
|
||||
using Brutal.Numerics;
|
||||
|
||||
namespace Brutal.Box2DApi
|
||||
{
|
||||
/// Prototype for user allocation function
|
||||
/// <param name="size">the allocation size in bytes </param>
|
||||
/// <param name="alignment">the required alignment, guaranteed to be a power of 2 </param>
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate void* B2AllocFcn(uint size, int alignment);
|
||||
|
||||
/// Prototype for user free function
|
||||
/// <param name="mem">the memory previously allocated through `b2AllocFcn` </param>
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate void B2FreeFcn(nint mem);
|
||||
|
||||
/// Prototype for the user assert callback. Return 0 to skip the debugger break.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate int B2AssertFcn(byte* condition, byte* fileName, int lineNumber);
|
||||
|
||||
/// This function receives proxies found in the AABB query.
|
||||
/// RETURN: true if the query should continue
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate Bool8 B2TreeQueryCallbackFcn(int proxyId, ulong userData, nint context);
|
||||
|
||||
/// This function receives clipped ray cast input for a proxy. The function
|
||||
/// returns the new ray fraction.
|
||||
/// - return a value of 0 to terminate the ray cast
|
||||
/// - return a value less than input->maxFraction to clip the ray
|
||||
/// - return a value of input->maxFraction to continue the ray cast without clipping
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate float B2TreeRayCastCallbackFcn(
|
||||
B2RayCastInput* input,
|
||||
int proxyId,
|
||||
ulong userData,
|
||||
nint context
|
||||
);
|
||||
|
||||
/// This function receives clipped ray cast input for a proxy. The function
|
||||
/// returns the new ray fraction.
|
||||
/// - return a value of 0 to terminate the ray cast
|
||||
/// - return a value less than input->maxFraction to clip the ray
|
||||
/// - return a value of input->maxFraction to continue the ray cast without clipping
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate float B2TreeShapeCastCallbackFcn(
|
||||
B2ShapeCastInput* input,
|
||||
int proxyId,
|
||||
ulong userData,
|
||||
nint context
|
||||
);
|
||||
|
||||
/// Task interface
|
||||
/// This is prototype for a Box2D task. Your task system is expected to invoke the Box2D task with these arguments.
|
||||
/// The task spans a range of the parallel-for: [startIndex, endIndex)
|
||||
/// The worker index must correctly identify each worker in the user thread pool, expected in [0, workerCount).
|
||||
/// A worker must only exist on only one thread at a time and is analogous to the thread index.
|
||||
/// The task context is the context pointer sent from Box2D when it is enqueued.
|
||||
/// The startIndex and endIndex are expected in the range [0, itemCount) where itemCount is the argument to b2EnqueueTaskCallback
|
||||
/// below. Box2D expects startIndex
|
||||
/// <
|
||||
/// endIndex and will execute a loop like this:
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate void B2TaskCallback(int startIndex, int endIndex, uint workerIndex, nint taskContext);
|
||||
|
||||
/// These functions can be provided to Box2D to invoke a task system. These are designed to work well with enkiTS.
|
||||
/// Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box2D that the work was executed
|
||||
/// serially within the callback and there is no need to call b2FinishTaskCallback.
|
||||
/// The itemCount is the number of Box2D work items that are to be partitioned among workers by the user's task system.
|
||||
/// This is essentially a parallel-for. The minRange parameter is a suggestion of the minimum number of items to assign
|
||||
/// per worker to reduce overhead. For example, suppose the task is small and that itemCount is 16. A minRange of 8 suggests
|
||||
/// that your task system should split the work items among just two workers, even if you have more available.
|
||||
/// In general the range [startIndex, endIndex) send to b2TaskCallback should obey:
|
||||
/// endIndex - startIndex >= minRange
|
||||
/// The exception of course is when itemCount
|
||||
/// <
|
||||
/// minRange.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate void* B2EnqueueTaskCallback(
|
||||
nint task,
|
||||
int itemCount,
|
||||
int minRange,
|
||||
nint taskContext,
|
||||
nint userContext
|
||||
);
|
||||
|
||||
/// Finishes a user task object that wraps a Box2D task.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate void B2FinishTaskCallback(nint userTask, nint userContext);
|
||||
|
||||
/// Optional friction mixing callback. This intentionally provides no context objects because this is called
|
||||
/// from a worker thread.
|
||||
/// WARNING: This function should not attempt to modify Box2D state or user application state.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate float B2FrictionCallback(
|
||||
float frictionA,
|
||||
int userMaterialIdA,
|
||||
float frictionB,
|
||||
int userMaterialIdB
|
||||
);
|
||||
|
||||
/// Optional restitution mixing callback. This intentionally provides no context objects because this is called
|
||||
/// from a worker thread.
|
||||
/// WARNING: This function should not attempt to modify Box2D state or user application state.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate float B2RestitutionCallback(
|
||||
float restitutionA,
|
||||
int userMaterialIdA,
|
||||
float restitutionB,
|
||||
int userMaterialIdB
|
||||
);
|
||||
|
||||
/// Prototype for a contact filter callback.
|
||||
/// This is called when a contact pair is considered for collision. This allows you to
|
||||
/// perform custom logic to prevent collision between shapes. This is only called if
|
||||
/// one of the two shapes has custom filtering enabled.
|
||||
/// Notes:
|
||||
/// - this function must be thread-safe
|
||||
/// - this is only called if one of the two shapes has enabled custom filtering
|
||||
/// - this is called only for awake dynamic bodies
|
||||
/// Return false if you want to disable the collision
|
||||
/// SEE: b2ShapeDef
|
||||
/// WARNING: Do not attempt to modify the world inside this callback
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate Bool8 B2CustomFilterFcn(B2Shape shapeIdA, B2Shape shapeIdB, nint context);
|
||||
|
||||
/// Prototype for a pre-solve callback.
|
||||
/// This is called after a contact is updated. This allows you to inspect a
|
||||
/// contact before it goes to the solver. If you are careful, you can modify the
|
||||
/// contact manifold (e.g. modify the normal).
|
||||
/// Notes:
|
||||
/// - this function must be thread-safe
|
||||
/// - this is only called if the shape has enabled pre-solve events
|
||||
/// - this is called only for awake dynamic bodies
|
||||
/// - this is not called for sensors
|
||||
/// - the supplied manifold has impulse values from the previous step
|
||||
/// Return false if you want to disable the contact this step
|
||||
/// WARNING: Do not attempt to modify the world inside this callback
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate Bool8 B2PreSolveFcn(B2Shape shapeIdA, B2Shape shapeIdB, B2Manifold* manifold, nint context);
|
||||
|
||||
/// Prototype callback for overlap queries.
|
||||
/// Called for each shape found in the query.
|
||||
/// SEE: b2World_OverlapABB
|
||||
/// RETURN: false to terminate the query.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate Bool8 B2OverlapResultFcn(B2Shape shapeId, nint context);
|
||||
|
||||
/// Prototype callback for ray and shape casts.
|
||||
/// Called for each shape found in the query. You control how the ray cast
|
||||
/// proceeds by returning a float:
|
||||
/// return -1: ignore this shape and continue
|
||||
/// return 0: terminate the ray cast
|
||||
/// return fraction: clip the ray to this point
|
||||
/// return 1: don't clip the ray and continue
|
||||
/// A cast with initial overlap will return a zero fraction and a zero normal.
|
||||
/// <param name="shapeId">the shape hit by the ray </param>
|
||||
/// <param name="point">the point of initial intersection </param>
|
||||
/// <param name="normal">the normal vector at the point of intersection, zero for a shape cast with initial overlap </param>
|
||||
/// <param name="fraction">the fraction along the ray at the point of intersection, zero for a shape cast with initial overlap </param>
|
||||
/// <param name="context">the user context </param>
|
||||
/// RETURN: -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue
|
||||
/// SEE: b2World_CastRay
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate float B2CastResultFcn(B2Shape shapeId, float2 point, float2 normal, float fraction, nint context);
|
||||
|
||||
/// Used to collect collision planes for character movers.
|
||||
/// Return true to continue gathering planes.
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate Bool8 B2PlaneResultFcn(B2Shape shapeId, B2PlaneResult* plane, nint context);
|
||||
}
|
||||
145
brutal.collections/Brutal.Collections/FreeList.cs
Normal file
145
brutal.collections/Brutal.Collections/FreeList.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for a free list index pool, a lightweight allocator that tracks free elements
|
||||
/// See: https://en.wikipedia.org/wiki/Free_list
|
||||
/// </summary>
|
||||
public interface IFreeListIndexPool
|
||||
{
|
||||
/// <summary>
|
||||
/// Total backing capacity
|
||||
/// </summary>
|
||||
public int Capacity { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Add element to list, returns index/key to element
|
||||
/// </summary>
|
||||
/// <returns>Index to element</returns>
|
||||
public int Add();
|
||||
|
||||
/// <summary>
|
||||
/// Check if element at index is empty
|
||||
/// </summary>
|
||||
public bool IsEmpty(int index);
|
||||
|
||||
/// <summary>
|
||||
/// Remove element at index
|
||||
/// </summary>
|
||||
public void Remove(int index);
|
||||
|
||||
/// <summary>
|
||||
/// Reset list as empty
|
||||
/// </summary>
|
||||
public void Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pool/allocator of indices that tracks free elements to avoid reallocation.
|
||||
/// Can be used as the allocator for a FreeList. See: https://en.wikipedia.org/wiki/Free_list
|
||||
/// </summary>
|
||||
public class FreeListIndexPool : IFreeListIndexPool
|
||||
{
|
||||
/// <summary>
|
||||
/// Empty element index not part of linked list of free elements
|
||||
/// </summary>
|
||||
const int OCCUPIED = -1;
|
||||
|
||||
/// <summary>
|
||||
/// Construct a new free list, that is empty and can grow
|
||||
/// </summary>
|
||||
public FreeListIndexPool()
|
||||
{
|
||||
_list = new();
|
||||
AllowResize = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construct a new free list with a given capacity
|
||||
/// </summary>
|
||||
/// <param name="capacity">Initial capacity</param>
|
||||
/// <param name="allowResize">If false, will throw instead of growing capacity when backing list is full</param>
|
||||
public FreeListIndexPool(int capacity, bool allowResize)
|
||||
{
|
||||
_list = new(capacity);
|
||||
AllowResize = allowResize;
|
||||
}
|
||||
|
||||
private readonly List<int> _list;
|
||||
private int _firstFree = OCCUPIED;
|
||||
|
||||
/// <summary>
|
||||
/// If true, the list will grow when full, if false, it will throw an exception
|
||||
/// </summary>
|
||||
public readonly bool AllowResize;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int Capacity
|
||||
{
|
||||
get => _list.Capacity;
|
||||
set => _list.Capacity = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Access element by index
|
||||
/// </summary>
|
||||
public int this[int index]
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get => _list[index];
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
set => _list[index] = value;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool IsEmpty(int index)
|
||||
{
|
||||
return _list[index] == OCCUPIED;
|
||||
}
|
||||
|
||||
public bool TryAdd(out int index)
|
||||
{
|
||||
if (_firstFree != OCCUPIED)
|
||||
{
|
||||
index = _firstFree;
|
||||
_firstFree = _list[index];
|
||||
_list[index] = OCCUPIED;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!AllowResize && _list.Count == _list.Capacity)
|
||||
{
|
||||
index = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
_list.Add(OCCUPIED);
|
||||
index = _list.Count - 1;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int Add()
|
||||
{
|
||||
if (!TryAdd(out var index))
|
||||
throw new Exception("FreeListIndexPool is full, and is not allowed to grow");
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Remove(int index)
|
||||
{
|
||||
_list[index] = _firstFree;
|
||||
_firstFree = index;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Clear()
|
||||
{
|
||||
_list.Clear();
|
||||
_firstFree = OCCUPIED;
|
||||
}
|
||||
}
|
||||
102
brutal.collections/Brutal.Collections/Name/Name.cs
Normal file
102
brutal.collections/Brutal.Collections/Name/Name.cs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// A pool-based (see: <see cref="Namespace{T}"/>) unique identifier for various entities in a system.
|
||||
/// </summary>
|
||||
public readonly struct Name<T> : IEquatable<Name<T>>
|
||||
{
|
||||
/// <summary>
|
||||
/// The underlying string value of the Name.
|
||||
/// </summary>
|
||||
public readonly string Value;
|
||||
|
||||
/// <summary>
|
||||
/// Construct a Name from a string, using the shared pool for the type T.
|
||||
/// </summary>
|
||||
public Name(string id)
|
||||
: this(id, Namespace<T>.Shared) { }
|
||||
|
||||
/// <summary>
|
||||
/// Construct a Name from a string, using the given pool.
|
||||
/// </summary>
|
||||
public Name(string id, Namespace<T> pool)
|
||||
{
|
||||
Value = pool.GetOrAdd(id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the underlying string value of the Name.
|
||||
/// </summary> public new string ToString() => Value;
|
||||
/// <summary>
|
||||
/// Checks equality with another Name, based on reference equality of the underlying string.
|
||||
/// </summary>
|
||||
public bool Equals(Name<T> other)
|
||||
{
|
||||
return ReferenceEquals(Value, other.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks equality with another object.
|
||||
/// </summary>
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
return obj is Name<T> other && Equals(other);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the hash code for the Name (based on the reference of the Value).
|
||||
/// </summary>
|
||||
public override int GetHashCode()
|
||||
{
|
||||
// Hash the reference of the Value for performance
|
||||
return RuntimeHelpers.GetHashCode(Value);
|
||||
}
|
||||
|
||||
/// <summary>Equality operator for Name.</summary>
|
||||
public static bool operator ==(Name<T> left, Name<T> right)
|
||||
{
|
||||
return left.Equals(right);
|
||||
}
|
||||
|
||||
/// <summary>Inequality operator for Name.</summary>
|
||||
public static bool operator !=(Name<T> left, Name<T> right)
|
||||
{
|
||||
return !left.Equals(right);
|
||||
}
|
||||
|
||||
/// <summary>Equality operator for Name and string.</summary>
|
||||
public static bool operator ==(Name<T> left, string right)
|
||||
{
|
||||
return left.Value == right;
|
||||
}
|
||||
|
||||
/// <summary>Inequality operator for Name and string.</summary>
|
||||
public static bool operator !=(Name<T> left, string right)
|
||||
{
|
||||
return left.Value != right;
|
||||
}
|
||||
|
||||
/// <summary>Equality operator for string and Name.</summary>
|
||||
public static bool operator ==(string left, Name<T> right)
|
||||
{
|
||||
return left == right.Value;
|
||||
}
|
||||
|
||||
/// <summary>Inequality operator for string and Name.</summary>
|
||||
public static bool operator !=(string left, Name<T> right)
|
||||
{
|
||||
return left != right.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Implicitly construct a Name from a string.
|
||||
/// </summary>
|
||||
public static implicit operator Name<T>(string id) => new(id);
|
||||
|
||||
/// <summary>
|
||||
/// Get the underlying string value of the Name.
|
||||
/// </summary>
|
||||
public override string ToString() => Value;
|
||||
}
|
||||
56
brutal.collections/Brutal.Collections/Name/Namespace.cs
Normal file
56
brutal.collections/Brutal.Collections/Name/Namespace.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using CommunityToolkit.HighPerformance.Buffers;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// A pool of unique identifiers
|
||||
/// </summary>
|
||||
public class Namespace<T>
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
|
||||
/// <summary>
|
||||
/// A global shared pool
|
||||
/// </summary>
|
||||
public static Namespace<T> Shared { get; } = new();
|
||||
|
||||
private readonly StringPool _pool = new();
|
||||
|
||||
internal string GetOrAdd(ReadOnlySpan<char> id)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _pool.GetOrAdd(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Try to get an existing ID from the pool
|
||||
/// </summary>
|
||||
public bool TryGet(ReadOnlySpan<char> id, [NotNullWhen(true)] out Name<T>? existing)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_pool.TryGet(id, out var key))
|
||||
{
|
||||
existing = new Name<T>(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
existing = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if the pool contains the given ID
|
||||
/// </summary>
|
||||
public bool Contains(ReadOnlySpan<char> id)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _pool.TryGet(id, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
using Brutal.Memory;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for native-memory backed lists
|
||||
/// </summary>
|
||||
public interface INativeList : ISpanLike, IDisposable
|
||||
{
|
||||
public ElementCount Count { get; set; }
|
||||
public ElementCount Capacity { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Matching C# List's Clear(), zeroes count but preserves capacity
|
||||
/// </summary>
|
||||
public void Clear();
|
||||
|
||||
/// <summary>
|
||||
/// Set the capacity to the actual number of elements in the list, if the current
|
||||
/// </summary>
|
||||
public void TrimExcess();
|
||||
|
||||
/// <summary>
|
||||
/// Increase the capacity of the vector (the total number of elements that the vector can hold without requiring
|
||||
/// reallocation) to a value that's greater or equal to newCapacity. If new_cap is greater than the current
|
||||
/// Capacity, new storage is then allocated; otherwise the function does nothing.
|
||||
/// </summary>
|
||||
/// <param name="capacity">The new max size</param>
|
||||
public void EnsureCapacity(ElementCount capacity);
|
||||
|
||||
/// <summary>
|
||||
/// Reset the array and free memory
|
||||
/// </summary>
|
||||
public void Free();
|
||||
}
|
||||
|
||||
public interface INativeList<T> : INativeList, ISpanLike<T>, IEnumerable<T>
|
||||
where T : unmanaged
|
||||
{
|
||||
/// <summary>
|
||||
/// Get or set an element at an index
|
||||
/// </summary>
|
||||
public ref T this[Index index] { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Add an element to the end of the list
|
||||
/// </summary>
|
||||
/// <param name="item">The item to add</param>
|
||||
public void Add(T item);
|
||||
|
||||
/// <summary>
|
||||
/// Add a range of elements to the end of the list
|
||||
/// </summary>
|
||||
/// <param name="items">The items to add</param>
|
||||
public void AddRange(ReadOnlySpan<T> items);
|
||||
|
||||
/// <summary>
|
||||
/// Insert an element at an index, shifting all later elements up by one
|
||||
/// </summary>
|
||||
/// <param name="index">The index to insert at</param>
|
||||
/// <param name="item">The item to insert</param>
|
||||
public void Insert(ElementCount index, T item);
|
||||
|
||||
/// <summary>
|
||||
/// Remove an element at an index, shifting all later elements down by one
|
||||
/// </summary>
|
||||
/// <param name="index">The index to remove at</param>
|
||||
public void RemoveAt(ElementCount index);
|
||||
}
|
||||
380
brutal.collections/Brutal.Collections/NativeList/NativeList.cs
Normal file
380
brutal.collections/Brutal.Collections/NativeList/NativeList.cs
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
using System.Diagnostics;
|
||||
using Brutal.Attributes;
|
||||
using Brutal.Memory;
|
||||
using Brutal.Pointers;
|
||||
using Brutal.Pointers.Extensions;
|
||||
using CommunityToolkit.HighPerformance;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// A native-memory backed list with no fixed type or stride
|
||||
/// </summary>
|
||||
public sealed class NativeList : INativeList
|
||||
{
|
||||
/// <summary>
|
||||
/// The default capacity of the array (in elements) when first growing from 0
|
||||
/// </summary>
|
||||
private const int DEFAULT_CAPACITY = 4;
|
||||
|
||||
/// <summary>
|
||||
/// The capacity of the array (in elements) we can hold without reallocating
|
||||
/// </summary>
|
||||
private ByteSize _byteCapacity;
|
||||
|
||||
/// <summary>
|
||||
/// The actual number of elements in the array
|
||||
/// </summary>
|
||||
private ByteSize _byteSize;
|
||||
|
||||
/// <summary>
|
||||
/// Free memory
|
||||
/// </summary>
|
||||
~NativeList()
|
||||
{
|
||||
Free();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsNull()
|
||||
{
|
||||
return Ptr.IsNull();
|
||||
}
|
||||
|
||||
private void _Reallocate(ByteSize byteSize)
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
if (byteSize == 0)
|
||||
{
|
||||
Free();
|
||||
_byteCapacity = ByteSize.Zero;
|
||||
_byteSize = ByteSize.Zero;
|
||||
return;
|
||||
}
|
||||
|
||||
void* oldMem = Ptr;
|
||||
Ptr = Mem.Alloc(byteSize);
|
||||
|
||||
if (oldMem != null)
|
||||
{
|
||||
Mem.Copy(oldMem, Ptr, _byteSize);
|
||||
Mem.Free(oldMem);
|
||||
}
|
||||
|
||||
_byteCapacity = byteSize;
|
||||
}
|
||||
}
|
||||
|
||||
internal void GrowInternal(ByteSize bytes)
|
||||
{
|
||||
Debug.Assert(_byteCapacity < bytes);
|
||||
|
||||
var newCapacity = _byteCapacity == 0 ? ByteSize.Of(DEFAULT_CAPACITY) : 2 * _byteCapacity;
|
||||
|
||||
// Allow the list to grow to the maximum possible capacity (~2G elements) before encountering overflow.
|
||||
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
|
||||
if ((uint)newCapacity > Array.MaxLength)
|
||||
newCapacity = ByteSize.Of(Array.MaxLength);
|
||||
|
||||
// If the computed capacity is still less than specified, set to the original argument.
|
||||
// Capacities exceeding Array.MaxLength will be surfaced as OutOfMemoryException by Array.Resize.
|
||||
if (newCapacity < bytes)
|
||||
newCapacity = bytes;
|
||||
|
||||
Capacity = newCapacity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reallocate the array to match the number of elements
|
||||
/// </summary>
|
||||
public void TrimExcess()
|
||||
{
|
||||
if (_byteSize != _byteCapacity)
|
||||
_Reallocate(_byteSize);
|
||||
}
|
||||
|
||||
void INativeList.EnsureCapacity(ElementCount capacity)
|
||||
{
|
||||
EnsureCapacity(ByteSize.Of(capacity));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frees any unmanaged resources.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This function MUST not cause problems if called more than once on the same instance.
|
||||
/// This class does not implement the Dispose pattern which is fine, but only because
|
||||
/// Free is able to handle being called from Dispose() and then called from the finaliser.
|
||||
/// </remarks>
|
||||
public void Free()
|
||||
{
|
||||
Mem.Free(Ptr);
|
||||
Ptr = null;
|
||||
_byteCapacity = ByteSize.Zero;
|
||||
_byteSize = ByteSize.Zero;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose of the resources. This function can be called multiple times safely.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Free();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Ptr Ptr { get; private set; }
|
||||
|
||||
ElementCount ISpanLike.Length => ElementCount.Of(Size);
|
||||
|
||||
ElementCount INativeList.Count
|
||||
{
|
||||
get => ElementCount.Of(_byteSize.Bytes);
|
||||
set => Size = ByteSize.Of(value);
|
||||
}
|
||||
|
||||
ElementCount INativeList.Capacity
|
||||
{
|
||||
get => ElementCount.Of(_byteSize.Bytes);
|
||||
set => Size = ByteSize.Of(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The number of elements in the list
|
||||
/// </summary>
|
||||
public ByteSize Size
|
||||
{
|
||||
get => new(_byteSize.Bytes);
|
||||
set
|
||||
{
|
||||
if (value == Size)
|
||||
return;
|
||||
|
||||
if (value > Capacity)
|
||||
GrowInternal(value);
|
||||
|
||||
if (value > Size)
|
||||
{
|
||||
Mem.Fill(Ptr.Offset(Size), value - Size, 0);
|
||||
}
|
||||
|
||||
_byteSize = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The capacity of the array
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentOutOfRangeException">If the new capacity is less than Count</exception>
|
||||
public ByteSize Capacity
|
||||
{
|
||||
get => _byteCapacity;
|
||||
set
|
||||
{
|
||||
if (_byteCapacity == value)
|
||||
return;
|
||||
|
||||
if (value < Size)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(value),
|
||||
"Capacity must be greater than or equal to Count."
|
||||
);
|
||||
}
|
||||
|
||||
_byteCapacity = value;
|
||||
_Reallocate(_byteCapacity);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create an untyped native list with a given stride and initial capacity
|
||||
/// </summary>
|
||||
public NativeList(ByteSize initialCapacity = default)
|
||||
{
|
||||
Capacity = initialCapacity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs a new NativeList and copies the contents of the given span
|
||||
/// </summary>
|
||||
public unsafe NativeList(ReadOnlySpan<byte> initialData)
|
||||
{
|
||||
if (initialData.Length > 0)
|
||||
{
|
||||
_byteCapacity = ByteSize.Of(initialData.Length);
|
||||
_byteSize = ByteSize.Of(initialData.Length);
|
||||
Ptr = Mem.AllocAndCopy(initialData).AsPointer();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds any unmanaged type to the list
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Does not check for stride, use it with caution
|
||||
/// </remarks>
|
||||
/// <param name="data">Unmanaged struct to copy over</param>
|
||||
/// <typeparam name="T">Data type, size should match the list's size</typeparam>
|
||||
public void Add<T>(T data)
|
||||
where T : unmanaged
|
||||
{
|
||||
var offset = Size;
|
||||
var stride = ByteSize.Of<T>();
|
||||
if (Capacity - Size < stride)
|
||||
{
|
||||
GrowInternal(Size == 0 ? ByteSize.Of<T>(DEFAULT_CAPACITY) : Size * 2);
|
||||
}
|
||||
_byteSize = _byteSize + stride;
|
||||
Ptr.Offset(offset).Cast<T>().Value = data;
|
||||
}
|
||||
|
||||
ByteSize ISpanLike.Stride => ByteSize.Zero;
|
||||
public bool IsEmpty => Size == 0;
|
||||
|
||||
[return: Fixed]
|
||||
public Span<T> AsSpan<T>()
|
||||
where T : unmanaged
|
||||
{
|
||||
return Ptr.AsSpan<byte>(ElementCount.Of(Size)).Cast<byte, T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get an element at index as a specific unmanaged type
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Does not check for stride, use it with caution
|
||||
/// </remarks>
|
||||
/// <exception cref="IndexOutOfRangeException">If the index is out of range</exception>
|
||||
public byte this[int index]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (index < 0 || index >= (int)Size.Bytes)
|
||||
throw new IndexOutOfRangeException();
|
||||
return Ptr.Offset(ByteSize.Of(index)).Cast<byte>().Value;
|
||||
}
|
||||
set => throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void AddRange<T>(ReadOnlySpan<T> items)
|
||||
where T : unmanaged
|
||||
{
|
||||
var byteSize = ByteSize.Of(items);
|
||||
var newCount = Size + byteSize;
|
||||
if (Capacity < newCount)
|
||||
GrowInternal(newCount);
|
||||
Mem.Copy(items, Ptr.Offset(Size).AsSpan<T>(items.Length));
|
||||
_byteSize += byteSize;
|
||||
}
|
||||
|
||||
public void AddRange<T>(T items)
|
||||
where T : ISpanLike, allows ref struct
|
||||
{
|
||||
var byteSize = ByteSize.Of(items);
|
||||
var newCount = Size + byteSize;
|
||||
if (Capacity < newCount)
|
||||
GrowInternal(newCount);
|
||||
Mem.Copy(items.AsSpan<byte>(), Ptr.Offset(Size).AsSpan<byte>(ElementCount.Of(byteSize)));
|
||||
_byteSize += byteSize;
|
||||
}
|
||||
|
||||
public void Add(byte item)
|
||||
{
|
||||
Add<byte>(item);
|
||||
}
|
||||
|
||||
public void Insert(ByteSize index, byte item)
|
||||
{
|
||||
if (index.Bytes < 0 || index.Bytes > Size)
|
||||
throw new IndexOutOfRangeException();
|
||||
|
||||
if (Size + 1 <= Capacity)
|
||||
{
|
||||
Mem.Copy(Ptr.Offset(index), Ptr.Offset(index + 1), Size - index);
|
||||
Ptr.Offset(index).Cast<byte>().Value = item;
|
||||
}
|
||||
else
|
||||
{
|
||||
var newPtr = Mem.Alloc(Size + 1);
|
||||
Mem.Copy(Ptr, newPtr, index);
|
||||
newPtr.Offset(index).Cast<byte>().Value = item;
|
||||
Mem.Copy(Ptr.Offset(index), newPtr.Offset(index + 1), Size - index);
|
||||
Mem.Free(Ptr);
|
||||
Ptr = newPtr;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Insert an item at the given index, shifting all later elements up
|
||||
/// </summary>
|
||||
public void Insert<T>(ByteSize index, T item)
|
||||
where T : unmanaged
|
||||
{
|
||||
if (index > Size)
|
||||
throw new IndexOutOfRangeException();
|
||||
|
||||
var stride = ByteSize.Of<T>();
|
||||
|
||||
if (Size + stride <= Capacity)
|
||||
{
|
||||
Mem.Copy(Ptr.Offset(index), Ptr.Offset(index + stride), Size - index);
|
||||
Ptr.Offset(index).Cast<T>().Value = item;
|
||||
}
|
||||
else
|
||||
{
|
||||
var newPtr = Mem.Alloc(Size + stride);
|
||||
Mem.Copy(Ptr, newPtr, index);
|
||||
newPtr.Offset(index).Cast<T>().Value = item;
|
||||
Mem.Copy(Ptr.Offset(index), newPtr.Offset(index + stride), Size - index);
|
||||
Mem.Free(Ptr);
|
||||
Ptr = newPtr;
|
||||
}
|
||||
|
||||
_byteSize += stride;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove a byte at an index, shifting all later elements down
|
||||
/// </summary>
|
||||
public void RemoveAt(ByteSize index)
|
||||
{
|
||||
RemoveAt(index, ByteSize.One);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove a number of bytes at an index, shifting all later elements down
|
||||
/// </summary>
|
||||
public void RemoveAt(ByteSize index, ByteSize numBytes)
|
||||
{
|
||||
if (index >= Size)
|
||||
throw new IndexOutOfRangeException();
|
||||
|
||||
if (index < Size - numBytes)
|
||||
{
|
||||
Mem.Copy(Ptr.Offset(index + numBytes), Ptr.Offset(index), Size - index - numBytes);
|
||||
}
|
||||
|
||||
_byteSize -= numBytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clear NativeList and optionally change the element stride.
|
||||
/// </summary>
|
||||
/// <exception cref="DivideByZeroException">If newStride is less than or equal to zero</exception>
|
||||
public void Clear()
|
||||
{
|
||||
_byteSize = ByteSize.Zero;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensure the list has enough capacity to hold the given number of elements
|
||||
/// </summary>
|
||||
public void EnsureCapacity(ByteSize capacity)
|
||||
{
|
||||
if (_byteCapacity < capacity)
|
||||
GrowInternal(capacity);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
using System.Collections;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// Enumerator class for generic NativeList
|
||||
/// </summary>
|
||||
public struct NativeListEnumerator<T> : IEnumerator<T>
|
||||
where T : unmanaged
|
||||
{
|
||||
private readonly NativeList<T> _list;
|
||||
private int _index;
|
||||
|
||||
/// <summary>
|
||||
/// Construct enumerator from the list
|
||||
/// </summary>
|
||||
/// <param name="list">Source list</param>
|
||||
public NativeListEnumerator(NativeList<T> list)
|
||||
{
|
||||
_list = list;
|
||||
_index = -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Iterate next element
|
||||
/// </summary>
|
||||
/// <returns>True if enumerator still running</returns>
|
||||
public bool MoveNext()
|
||||
{
|
||||
_index++;
|
||||
return _index < _list.Count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reset enumerator
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
_index = -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Index enumerator
|
||||
/// </summary>
|
||||
public T Current => _list[_index];
|
||||
|
||||
object IEnumerator.Current => Current;
|
||||
|
||||
/// <summary>
|
||||
/// Dispose of enumerator
|
||||
/// </summary>
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
using System.Collections;
|
||||
using Brutal.Attributes;
|
||||
using Brutal.Memory;
|
||||
using Brutal.Pointers;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// A native-memory backed list with a fixed type
|
||||
/// </summary>
|
||||
/// <typeparam name="TValueType">Element type</typeparam>
|
||||
public class NativeList<TValueType> : INativeList<TValueType>
|
||||
where TValueType : unmanaged
|
||||
{
|
||||
~NativeList()
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
|
||||
private readonly NativeStrideList _nativeList;
|
||||
|
||||
public NativeList(ElementCount capacity = default)
|
||||
{
|
||||
_nativeList = new NativeStrideList(Stride, capacity);
|
||||
}
|
||||
|
||||
public NativeList(ReadOnlySpan<TValueType> nativeList)
|
||||
{
|
||||
_nativeList = NativeStrideList.FromSpan(Stride, nativeList);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_nativeList.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public bool IsNull()
|
||||
{
|
||||
return _nativeList.IsNull();
|
||||
}
|
||||
|
||||
public ByteSize Stride => ByteSize.Of<TValueType>();
|
||||
public bool IsEmpty => Count == 0;
|
||||
|
||||
public ref TValueType this[Index index]
|
||||
{
|
||||
get
|
||||
{
|
||||
var actualIndex = index.GetOffset(Count);
|
||||
return ref _nativeList.AsSpan<TValueType>()[actualIndex];
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(TValueType item)
|
||||
{
|
||||
_nativeList.Add(item);
|
||||
}
|
||||
|
||||
public void AddRange(Span<TValueType> items)
|
||||
{
|
||||
_nativeList.AddRange(items);
|
||||
}
|
||||
|
||||
public void AddRange(ReadOnlySpan<TValueType> items)
|
||||
{
|
||||
_nativeList.AddRange(items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a range of bytes to the end of the list. The length of items must be a multiple of stride
|
||||
/// </summary>
|
||||
public void AddRange<T>(T items)
|
||||
where T : ISpanLike<TValueType>
|
||||
{
|
||||
_nativeList.AddRange(items.AsSpan());
|
||||
}
|
||||
|
||||
public void Insert(ElementCount index, TValueType item)
|
||||
{
|
||||
_nativeList.Insert(index, item);
|
||||
}
|
||||
|
||||
public void RemoveAt(ElementCount index)
|
||||
{
|
||||
_nativeList.RemoveAt<TValueType>(index);
|
||||
}
|
||||
|
||||
public Ptr<TValueType> Ptr => _nativeList.Ptr.Cast<TValueType>();
|
||||
|
||||
Ptr ISpanLike.Ptr => Ptr;
|
||||
ElementCount ISpanLike.Length => Count;
|
||||
|
||||
public ElementCount Count
|
||||
{
|
||||
get => _nativeList.Count;
|
||||
set => _nativeList.Count = value;
|
||||
}
|
||||
|
||||
public ElementCount Capacity
|
||||
{
|
||||
get => _nativeList.Capacity;
|
||||
set => _nativeList.Capacity = value;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_nativeList.Clear();
|
||||
}
|
||||
|
||||
public void TrimExcess()
|
||||
{
|
||||
_nativeList.TrimExcess();
|
||||
}
|
||||
|
||||
public void EnsureCapacity(ElementCount capacity)
|
||||
{
|
||||
_nativeList.EnsureCapacity(capacity);
|
||||
}
|
||||
|
||||
public void Free()
|
||||
{
|
||||
_nativeList.Free();
|
||||
}
|
||||
|
||||
public IEnumerator<TValueType> GetEnumerator()
|
||||
{
|
||||
for (var i = 0; i < Count; ++i)
|
||||
yield return this[i];
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return GetEnumerator();
|
||||
}
|
||||
|
||||
public Span<TValueType> Slice(ElementCount start, ElementCount length)
|
||||
{
|
||||
return AsSpan().Slice(start, length);
|
||||
}
|
||||
|
||||
public Span<TValueType> Slice(ElementCount start)
|
||||
{
|
||||
return AsSpan()[(int)start..];
|
||||
}
|
||||
|
||||
[Fixed]
|
||||
public Span<TValueType> this[Range range] => AsSpan()[range];
|
||||
|
||||
[return: Fixed]
|
||||
public Span<TValueType> AsSpan()
|
||||
{
|
||||
return _nativeList.AsSpan<TValueType>();
|
||||
}
|
||||
|
||||
Span<TCastType> ISpanLike.AsSpan<TCastType>()
|
||||
{
|
||||
return _nativeList.AsSpan<TCastType>();
|
||||
}
|
||||
|
||||
public NativeStrideSpan AsNativeSpan()
|
||||
{
|
||||
return new NativeStrideSpan(Ptr, Count, Stride);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool isDisposing)
|
||||
{
|
||||
if (!isDisposing)
|
||||
return;
|
||||
|
||||
_nativeList.Dispose();
|
||||
}
|
||||
|
||||
public ref TValueType GetPinnableReference()
|
||||
{
|
||||
return ref this[0];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,253 @@
|
|||
using Brutal.Attributes;
|
||||
using Brutal.Memory;
|
||||
using Brutal.Pointers;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// A native-memory backed list with a fixed stride
|
||||
/// </summary>
|
||||
public class NativeStrideList : INativeList
|
||||
{
|
||||
~NativeStrideList()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
private readonly NativeList _nativeList;
|
||||
|
||||
/// <summary>
|
||||
/// The size of each element in bytes
|
||||
/// </summary>
|
||||
public ByteSize Stride { get; }
|
||||
|
||||
public bool IsEmpty => Count == 0;
|
||||
|
||||
/// <summary>
|
||||
/// A raw pointer to the underlying memory
|
||||
/// </summary>
|
||||
public Ptr Ptr => _nativeList.Ptr;
|
||||
|
||||
ElementCount ISpanLike.Length => Count;
|
||||
|
||||
/// <summary>
|
||||
/// The number of elements in the list
|
||||
/// </summary>
|
||||
public ElementCount Count
|
||||
{
|
||||
get => _nativeList.Size.ToElementCount(Stride);
|
||||
set => _nativeList.Size = value * Stride;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The number of elements that can be stored in the list without resizing
|
||||
/// </summary>
|
||||
public ElementCount Capacity
|
||||
{
|
||||
get => _nativeList.Capacity.ToElementCount(Stride);
|
||||
set => _nativeList.Capacity = value * Stride;
|
||||
}
|
||||
|
||||
// ReSharper disable once UnusedMember.Local
|
||||
private NativeStrideList() => throw new InvalidOperationException("NativeStrideList cannot be default constructed");
|
||||
|
||||
/// <summary>
|
||||
/// Constructs a new NativeStrideList with the given stride and initial capacity
|
||||
/// </summary>
|
||||
public NativeStrideList(ByteSize stride, ElementCount capacity = default)
|
||||
{
|
||||
Stride = stride;
|
||||
_nativeList = new NativeList();
|
||||
|
||||
if (stride < 1)
|
||||
throw new ArgumentOutOfRangeException(nameof(stride), stride, "stride must be greater than 0");
|
||||
|
||||
_nativeList.EnsureCapacity(Stride * capacity);
|
||||
}
|
||||
|
||||
public static NativeStrideList FromSpan<TSpanLike>(ByteSize stride, TSpanLike span)
|
||||
where TSpanLike : ISpanLike, allows ref struct
|
||||
{
|
||||
var outList = new NativeStrideList(stride);
|
||||
outList.AddRange(span.AsSpan<byte>());
|
||||
return outList;
|
||||
}
|
||||
|
||||
public static NativeStrideList FromSpan<TSpanLike>(TSpanLike span)
|
||||
where TSpanLike : ISpanLike, allows ref struct
|
||||
{
|
||||
return FromSpan(span.Stride, span);
|
||||
}
|
||||
|
||||
public static NativeStrideList FromSpan<TValueType>(ByteSize stride, ReadOnlySpan<TValueType> span)
|
||||
where TValueType : unmanaged
|
||||
{
|
||||
var outList = new NativeStrideList(stride);
|
||||
outList.AddRange(span);
|
||||
return outList;
|
||||
}
|
||||
|
||||
public static NativeStrideList FromSpan<TValueType>(ReadOnlySpan<TValueType> span)
|
||||
where TValueType : unmanaged
|
||||
{
|
||||
return FromSpan(ByteSize.Of<TValueType>(), span);
|
||||
}
|
||||
|
||||
// This class does not track if it's been disposed of before, because
|
||||
// _nativeList.Dispose() is idempotent. Should that or out implementation
|
||||
// change, then you may need to implement the Dispose pattern in this class.
|
||||
/// <summary>
|
||||
/// Disposes the native memory.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the native list is null
|
||||
/// </summary>
|
||||
public bool IsNull()
|
||||
{
|
||||
return _nativeList.IsNull();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the list, setting count to 0 but preserving capacity
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
_nativeList.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Trim the capacity to the actual number of elements in the list
|
||||
/// </summary>
|
||||
public void TrimExcess()
|
||||
{
|
||||
_nativeList.TrimExcess();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensure the list can hold at least capacity elements without resizing
|
||||
/// </summary>
|
||||
public void EnsureCapacity(ElementCount capacity)
|
||||
{
|
||||
_nativeList.EnsureCapacity(capacity * Stride);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frees the native memory and resets the list
|
||||
/// </summary>
|
||||
public void Free()
|
||||
{
|
||||
_nativeList.Free();
|
||||
}
|
||||
|
||||
public NativeStrideSpan AsNativeSpan()
|
||||
{
|
||||
return new NativeStrideSpan(Ptr, Count, Stride);
|
||||
}
|
||||
|
||||
public void AddRange(Span<byte> items)
|
||||
{
|
||||
AddRange((ReadOnlySpan<byte>)items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a range of bytes to the end of the list. The length of items must be a multiple of stride
|
||||
/// </summary>
|
||||
public void AddRange(ReadOnlySpan<byte> items)
|
||||
{
|
||||
if (ByteSize.Of(items) % Stride != 0)
|
||||
throw new ArgumentException("Items length must be a multiple of stride", nameof(items));
|
||||
|
||||
_nativeList.AddRange(items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a range of bytes to the end of the list. The length of items must be a multiple of stride
|
||||
/// </summary>
|
||||
public void AddRange<T>(T items)
|
||||
where T : ISpanLike, allows ref struct
|
||||
{
|
||||
if (ByteSize.Of(items) % Stride != 0)
|
||||
throw new ArgumentException("Items length must be a multiple of stride", nameof(items));
|
||||
|
||||
_nativeList.AddRange(items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds an item to the end of the list
|
||||
/// </summary>
|
||||
public void Add<T>(T item)
|
||||
where T : unmanaged
|
||||
{
|
||||
CheckStride<T>();
|
||||
_nativeList.Add(item);
|
||||
}
|
||||
|
||||
public void AddRange<T>(Span<T> items)
|
||||
where T : unmanaged
|
||||
{
|
||||
AddRange((ReadOnlySpan<T>)items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a range of items to the end of the list
|
||||
/// </summary>
|
||||
public void AddRange<T>(ReadOnlySpan<T> items)
|
||||
where T : unmanaged
|
||||
{
|
||||
CheckStride<T>();
|
||||
_nativeList.AddRange(items);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts an item at the given index, shifting all later items up by one
|
||||
/// </summary>
|
||||
public void Insert<T>(ElementCount index, T item)
|
||||
where T : unmanaged
|
||||
{
|
||||
CheckStride<T>();
|
||||
_nativeList.Insert(Stride * index, item);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the item at the given index, shifting all later items down by one
|
||||
/// </summary>
|
||||
public void RemoveAt<T>(ElementCount index)
|
||||
where T : unmanaged
|
||||
{
|
||||
CheckStride<T>();
|
||||
_nativeList.RemoveAt(Stride * index, Stride);
|
||||
}
|
||||
|
||||
private void CheckStride<T>()
|
||||
where T : unmanaged
|
||||
{
|
||||
CheckStride(ByteSize.Of<T>());
|
||||
}
|
||||
|
||||
private void CheckStride(ByteSize stride)
|
||||
{
|
||||
if (Stride != stride)
|
||||
throw new ArgumentException($"NativeStrideList expected stride: {Stride}, but got: {stride}");
|
||||
}
|
||||
|
||||
[return: Fixed]
|
||||
public Span<T> AsSpan<T>()
|
||||
where T : unmanaged
|
||||
{
|
||||
return _nativeList.AsSpan<T>();
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool isDisposing)
|
||||
{
|
||||
if (!isDisposing)
|
||||
return;
|
||||
|
||||
_nativeList.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
using Brutal.Attributes;
|
||||
using Brutal.Memory;
|
||||
using Brutal.Pointers;
|
||||
using Brutal.Pointers.Extensions;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// An untyped span to unsafe memory, however with a stride.
|
||||
/// </summary>
|
||||
public readonly ref struct NativeStrideSpan(Ptr inData, ElementCount inLength, ByteSize inStride) : ISpanLike
|
||||
{
|
||||
/// <summary>
|
||||
/// The pointer to the first element of the span.
|
||||
/// </summary>
|
||||
public Ptr Ptr => inData;
|
||||
|
||||
/// <summary>
|
||||
/// The length of the span.
|
||||
/// </summary>
|
||||
public ElementCount Length => inLength;
|
||||
|
||||
/// <summary>
|
||||
/// The stride of each element.
|
||||
/// </summary>
|
||||
public ByteSize Stride => inStride;
|
||||
|
||||
public bool IsEmpty => Length == 0;
|
||||
|
||||
/// <summary>
|
||||
/// The total size of the span in bytes.
|
||||
/// </summary>
|
||||
public ByteSize ByteSize => Length * Stride;
|
||||
|
||||
/// <summary>
|
||||
/// Slice the span into a new raw span.
|
||||
/// </summary>
|
||||
public NativeStrideSpan Slice(int start, int length)
|
||||
{
|
||||
return new NativeStrideSpan(Ptr.Offset(start * Stride), length, Stride);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new raw span with a different stride.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentOutOfRangeException"></exception>
|
||||
public NativeStrideSpan WithStride(ByteSize stride)
|
||||
{
|
||||
if (stride <= 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(stride));
|
||||
var prevSize = ByteSize;
|
||||
return new NativeStrideSpan(Ptr, prevSize.ToElementCount(stride), stride);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsNull() => Ptr.IsNull();
|
||||
|
||||
/// <summary>
|
||||
/// Create a new raw span from a managed span.
|
||||
/// </summary>
|
||||
public static unsafe NativeStrideSpan FromSpan<T>([Fixed] ReadOnlySpan<T> span)
|
||||
where T : unmanaged
|
||||
{
|
||||
return new NativeStrideSpan(span.AsPointer(), span.Length, ByteSize.Of<T>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new raw span from a managed span.
|
||||
/// </summary>
|
||||
public static unsafe NativeStrideSpan FromSpan<T>([Fixed] Span<T> span)
|
||||
where T : unmanaged
|
||||
{
|
||||
return new NativeStrideSpan(span.AsPointer(), span.Length, ByteSize.Of<T>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Slice the span into a new raw span.
|
||||
/// </summary>
|
||||
public NativeStrideSpan this[int start, int end] => Slice(start, end - start);
|
||||
|
||||
[return: Fixed]
|
||||
public unsafe Span<T> AsSpan<T>()
|
||||
where T : unmanaged
|
||||
{
|
||||
if (typeof(T) == typeof(byte))
|
||||
return new Span<T>(Ptr.Cast<T>(), ElementCount.Of(Length * Stride));
|
||||
|
||||
var size = ByteSize.Of<T>();
|
||||
if (size != Stride)
|
||||
throw new InvalidOperationException("Stride must be equal to the size of the type, or type must be byte.");
|
||||
|
||||
return new Span<T>(Ptr.Cast<T>(), Length);
|
||||
}
|
||||
|
||||
public NativeStrideSpan this[Range start] => Slice(start.Start.Value, start.End.Value - start.Start.Value);
|
||||
}
|
||||
53
brutal.collections/Brutal.Collections/Span/ScratchSpan.cs
Normal file
53
brutal.collections/Brutal.Collections/Span/ScratchSpan.cs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Brutal.Collections.Experimental;
|
||||
|
||||
/// <summary>
|
||||
/// Stackalloc-or-rent scratch buffer.
|
||||
/// <see cref="Span"/> is backed by the stack buffer if it's big enough,
|
||||
/// else by an array rented from <see cref="ArrayPool{T}"/>.
|
||||
/// <see cref="Dispose"/> returns any rented array to the pool.
|
||||
/// </summary>
|
||||
/// <remarks>Usage:<code>
|
||||
/// using (var scratch = new ScratchSpan<T>(requiredLength, stackalloc T[256]))
|
||||
/// {
|
||||
/// var buf = scratch.Span; // length == required, backed by stack or pool
|
||||
/// // ...
|
||||
/// }
|
||||
/// </code></remarks>
|
||||
public readonly ref struct ScratchSpan<T>
|
||||
{
|
||||
private readonly T[]? _rented;
|
||||
|
||||
/// <summary>The scratch span of exactly <c>requiredLength</c> elements.</summary>
|
||||
public Span<T> Span { get; }
|
||||
|
||||
public static implicit operator Span<T>(ScratchSpan<T> scratch) => scratch.Span;
|
||||
|
||||
/// <summary>Construct a ScratchSpan, get the result in <see cref="Span"/>.</summary>
|
||||
/// <param name="requiredLength">Number of elements the caller needs.</param>
|
||||
/// <param name="stackBuffer">Stack-allocated tentative buffer to use if large enough, otherwise an array is rented.</param>
|
||||
public ScratchSpan(int requiredLength, Span<T> stackBuffer)
|
||||
{
|
||||
Span = requiredLength <= stackBuffer.Length ? stackBuffer : _rented = ArrayPool<T>.Shared.Rent(requiredLength);
|
||||
Span = Span[..requiredLength];
|
||||
}
|
||||
|
||||
/// <summary>Alternative form where <see cref="Span"/> is output directly to <paramref name="span"/>.</summary>
|
||||
/// <param name="requiredLength">Number of elements the caller needs.</param>
|
||||
/// <param name="stackBuffer">Stack-allocated tentative buffer to use if large enough, otherwise an array is rented.</param>
|
||||
/// <param name="span">Output span of exactly <paramref name="requiredLength"/> elements, backed by either <paramref name="stackBuffer"/> or a rented array.</param>
|
||||
public ScratchSpan(int requiredLength, Span<T> stackBuffer, out Span<T> span)
|
||||
: this(requiredLength, stackBuffer)
|
||||
{
|
||||
span = Span;
|
||||
}
|
||||
|
||||
/// Returns any rented array to the pool. No-op if the stack buffer was used.
|
||||
public void Dispose()
|
||||
{
|
||||
if (_rented != null)
|
||||
ArrayPool<T>.Shared.Return(_rented, clearArray: RuntimeHelpers.IsReferenceOrContainsReferences<T>());
|
||||
}
|
||||
}
|
||||
9
brutal.concurrency/Brutal.Concurrency/Jobs/IJob.cs
Normal file
9
brutal.concurrency/Brutal.Concurrency/Jobs/IJob.cs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
namespace Brutal.Concurrency.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a job that can be executed by the JobScheduler.
|
||||
/// </summary>
|
||||
public interface IJob
|
||||
{
|
||||
void Run();
|
||||
}
|
||||
371
brutal.concurrency/Brutal.Concurrency/Jobs/JobRunner.cs
Normal file
371
brutal.concurrency/Brutal.Concurrency/Jobs/JobRunner.cs
Normal file
|
|
@ -0,0 +1,371 @@
|
|||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Brutal.Concurrency.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Provides functionality for queuing, running a collection of IJob instances on a single resource.
|
||||
/// At present, this resource is a single thread from the System.Threadpool.
|
||||
/// </summary>
|
||||
public class JobRunner
|
||||
{
|
||||
public const int DEFAULT_CAPACITY = 1024;
|
||||
public const ThreadPriority DEFAULT_THREAD_PRIORITY = ThreadPriority.AboveNormal;
|
||||
|
||||
/// <summary>
|
||||
/// A delegate that is called when a <see cref="JobRunner"/> completes execution.
|
||||
/// </summary>
|
||||
/// <param name="runner">This JobRunner</param>
|
||||
/// <param name="result">Result of job execution</param>
|
||||
/// <param name="lastTickTimeMillis">The total time in milliseconds it took to run the jobs</param>
|
||||
public delegate void JobCompletedDelegate(
|
||||
JobRunner runner,
|
||||
ExecutionResult result,
|
||||
double lastTickTimeMillis
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Construct a JobRunner with an optional name, thread priority, capacity and shared Lock instance.
|
||||
/// </summary>
|
||||
/// <remarks>The shared lock is useful if you want to have your own synchronisation that you wish the JobRunner to take part in. If this parameter is null
|
||||
/// then the JobRunner will fallback to using its own locking mechanism. </remarks>
|
||||
/// <param name="name">Name of the runner. Defaults to an empty string.</param>
|
||||
/// <param name="threadPriority">The priority to run the worker thread under. Defaults to <see cref="DEFAULT_THREAD_PRIORITY"/>.</param>
|
||||
/// <param name="capacity">Number of entries in the job queue to allocate space for. Defaults to <see cref="DEFAULT_CAPACITY"/>.</param>
|
||||
/// <param name="lock">An optional lock object for the JobRunner to use.</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown if capacity < 1</exception>
|
||||
public JobRunner(
|
||||
string name = "",
|
||||
ThreadPriority threadPriority = DEFAULT_THREAD_PRIORITY,
|
||||
int capacity = DEFAULT_CAPACITY,
|
||||
Lock? @lock = null
|
||||
)
|
||||
{
|
||||
if (capacity < 1)
|
||||
throw new ArgumentOutOfRangeException(nameof(capacity), @"capacity");
|
||||
|
||||
// In DotNet 9 System.Threading.Lock was added to give a bit of performance over Monitor which was used when you went
|
||||
// lock(some_object). Now you use lock(someLockInstance).
|
||||
_lock = @lock ?? new Lock();
|
||||
_timer = new JobRunnerTimer();
|
||||
_state = (int)JobState.Idle;
|
||||
_jobs = new List<IJob>(capacity);
|
||||
_nextJobIndexToExecute = -1;
|
||||
_workExecutor = new WorkExecutor(this);
|
||||
Name = name;
|
||||
ThreadPriority = threadPriority;
|
||||
|
||||
_metrics = new()
|
||||
{
|
||||
AverageTickTimeMillis = 0,
|
||||
MaxTickTimeMillis = 0,
|
||||
LastTickTimeMillis = 0,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the threadpriority that this runner runs on. Takes effect the next time this runner runs jobs.
|
||||
/// </summary>
|
||||
public ThreadPriority ThreadPriority { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The user-defined name of the job runner specified in the constructor.
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the current state of the JobRunner.
|
||||
/// </summary>
|
||||
public JobState State => ReadStateSynchronised();
|
||||
|
||||
/// <summary>
|
||||
/// Queue a job to the JobRunner if it is currently idle.
|
||||
/// </summary>
|
||||
/// <param name="job">The job to queue</param>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the job runner is not idle.</exception>
|
||||
public void Queue(IJob job)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (ReadStateSynchronised() != JobState.Idle)
|
||||
throw new InvalidOperationException("JobRunner is not idle");
|
||||
_jobs.Add(job);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a <see cref="ReadOnlySpan{IJob}"/> of the currently queued jobs for a JobRunner.
|
||||
/// </summary>
|
||||
/// <remarks>The returned <see cref="ReadOnlySpan{IJob}"/> is a view of the <see cref="JobRunner" />'s queued jobs at the time of the call. If more jobs are added after the call or
|
||||
/// the <see cref="JobRunner" />'s jobs are executed (which clears the queue) then the ReadOnlySpan is invalidated.
|
||||
/// </remarks>
|
||||
/// <returns>The ReadOnlySpan of the queued IJob instances.</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the <see cref="JobRunner" /> is not idle.</exception>
|
||||
public ReadOnlySpan<IJob> GetQueuedJobs()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (ReadStateSynchronised() != JobState.Idle)
|
||||
throw new InvalidOperationException("JobRunner is not idle");
|
||||
return CollectionsMarshal.AsSpan(_jobs);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts execution of all queued jobs.
|
||||
/// After a call to ExecuteJobs() no more jobs can be queued until the runner is idle.
|
||||
/// </summary>
|
||||
/// <param name="onCompleteHandler" cref="JobCompletedDelegate" >An optional callback that is invoked when the JobRunner jobs have finished or been aborted.</param>
|
||||
/// <remarks>If there are no jobs to run, metrics are not updated, but the callback is still called with the last tick time being set to 0</remarks>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the runner is not currently idle</exception>
|
||||
public void ExecuteJobs(JobCompletedDelegate? onCompleteHandler = null)
|
||||
{
|
||||
// Locked (not just the state CAS in CheckedTransitionState) so that a concurrent
|
||||
// Queue() call is fully ordered relative to this transition: either its Add()
|
||||
// completes and is visible in the _jobs.Count read below, or it observes the
|
||||
// Scheduled state and throws before ever touching _jobs. See issue #22.
|
||||
lock (_lock)
|
||||
{
|
||||
CheckedTransitionState(JobState.Idle, JobState.Scheduled);
|
||||
}
|
||||
|
||||
if (_jobs.Count == 0)
|
||||
{
|
||||
Interlocked.Exchange(ref _state, (int)JobState.Idle);
|
||||
onCompleteHandler?.Invoke(this, ExecutionResult.NoJobs, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// With SafeStartTimer being here, we include the time to get the job thread actually up and running so we
|
||||
// get a view of the start to finish time.
|
||||
SafeStartTimer();
|
||||
_workExecutor.OnCompleteHandler = onCompleteHandler;
|
||||
ThreadPool.UnsafeQueueUserWorkItem(_workExecutor, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request aborting of jobs that have not already started executing. If the JobRunner is currently Idle or in the process of aborting, this function does nothing.
|
||||
///
|
||||
/// <remarks><br /><br />
|
||||
/// Jobs that are already running will not be aborted.<br />
|
||||
/// Metrics will not be updated.<br />
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
public void RequestAbort()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var currentState = ReadStateSynchronised();
|
||||
if (currentState is JobState.Idle or JobState.Abort)
|
||||
return;
|
||||
Debug.Assert(currentState is JobState.Scheduled or JobState.Running);
|
||||
|
||||
if (
|
||||
Interlocked.CompareExchange(ref _state, (int)JobState.Abort, (int)currentState)
|
||||
== (int)currentState
|
||||
)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the latest metrics of the JobRunner's last execution, which include AverageMillis, MaxMillis and LastMillis, in milliseconds.
|
||||
/// </summary>
|
||||
/// <remarks><p>Threadsafe and atomic. Can be called at any time from any thread to get a consistent view of the current metrics.<br />
|
||||
/// This function performs lightweight spin waiting around a sequence token. This does introduce a small overhead. Higher overhead comes
|
||||
/// with heavier contention such as calling GetMetrics while ResetMetrics is being called from another thread, or the JobRunner is updating its metrics at the end of
|
||||
/// successfully executing all of its jobs.</p><p>Call GetMetricsUnsafe() if shorn JobRunnerMetrics data (Each field itself is still atomic) is acceptable.</p></remarks>
|
||||
/// <returns cref="JobRunnerMetrics">The metrics of the JobRunner</returns>
|
||||
public JobRunnerMetrics GetMetrics()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _metrics;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the latest metrics of the JobRunner's last execution in a non-threadsafe manner. Includes AverageMillis, MaxMillis and LastMillis, in milliseconds.<br />
|
||||
/// </summary>
|
||||
/// <remarks>NOT atomic. If you call this while ResetMetrics is running or the JobRunner threads are updating their metrics you will likely get
|
||||
/// shorn results. That is, results of previous metrics mixed with results of the latest. However, each individual value will be consistent and not shorn due to
|
||||
/// our requirement of 64bit systems, alignment of the metrics fields and doubles being atomic on those systems if aligned.</remarks>
|
||||
/// <returns cref="JobRunnerMetrics">The metrics of the JobRunner</returns>
|
||||
public JobRunnerMetrics GetMetricsUnsafe()
|
||||
{
|
||||
// AKB: Do not just return _metrics, that is not an individual copy of each field and therefore you could get shorn data within each field.
|
||||
// Even though this function may return inconsistent results, using per-field copies at least gives us atomic sets of each member.
|
||||
var returned = new JobRunnerMetrics
|
||||
{
|
||||
AverageTickTimeMillis = _metrics.AverageTickTimeMillis,
|
||||
MaxTickTimeMillis = _metrics.MaxTickTimeMillis,
|
||||
LastTickTimeMillis = _metrics.LastTickTimeMillis,
|
||||
};
|
||||
return returned;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Busy waits the current thread until the jobs have finished executing or been aborted.
|
||||
/// </summary>
|
||||
/// <remarks>This method busy blocks and may starve a thread or core if waiting too long</remarks>
|
||||
public void Wait()
|
||||
{
|
||||
while (ReadStateSynchronised() != JobState.Idle)
|
||||
{
|
||||
// This code intentionally left blank
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all metrics of the JobRunner in an atomic fashion. You will not get shorn fields from the
|
||||
/// case where a job wants to update the metrics at the same time as ResetMetrics is clearing them.
|
||||
/// <br />
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The thread safety adds about 10 nanoseconds of overhead on a 3GHz machine.<br />
|
||||
/// </remarks>
|
||||
public void ResetMetrics()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
ResetMetricsUnsafe();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets all collected timing and performance metrics to their initial state without thread safety guarantees.
|
||||
/// </summary>
|
||||
/// <remarks>This method is not thread-safe. CAlling ResetMetrics while others are accessing the (e.g. the JobRunner itself)
|
||||
/// could result in inconsistent values.</remarks>
|
||||
public void ResetMetricsUnsafe()
|
||||
{
|
||||
_timer.ResetTimings();
|
||||
_metrics.AverageTickTimeMillis = 0;
|
||||
_metrics.MaxTickTimeMillis = 0;
|
||||
_metrics.LastTickTimeMillis = 0;
|
||||
}
|
||||
|
||||
#region Private
|
||||
|
||||
private void SafeStartTimer()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_timer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private JobState ReadStateSynchronised()
|
||||
{
|
||||
return (JobState)Volatile.Read(ref _state);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteStateSynchronised(JobState newState)
|
||||
{
|
||||
Volatile.Write(ref _state, (int)newState);
|
||||
}
|
||||
|
||||
private void CheckedTransitionState(JobState fromState, JobState toState)
|
||||
{
|
||||
var actual = (JobState)
|
||||
Interlocked.CompareExchange(ref _state, (int)toState, (int)fromState);
|
||||
if (actual != fromState)
|
||||
throw new InvalidOperationException(
|
||||
$"Unexpected state. Expected:{fromState} Actual:{actual}"
|
||||
);
|
||||
}
|
||||
|
||||
private void DoWork(JobCompletedDelegate? onCompleteHandler)
|
||||
{
|
||||
var executionResult = ExecutionResult.Success;
|
||||
try
|
||||
{
|
||||
Debug.Assert((JobState)_state is JobState.Scheduled or JobState.Abort);
|
||||
Debug.Assert(_jobs.Count > 0);
|
||||
|
||||
Thread.CurrentThread.Priority = ThreadPriority;
|
||||
|
||||
// From the time we set our state to Scheduled in ExecuteJobs
|
||||
// it's possible a RequestAbort came in and our state is now Abort.
|
||||
// We just let the code flow as normal and the abort check below will detect this,
|
||||
// however we must let this CompareExchange continue even if it doesn't return Scheduled.
|
||||
// There is an assumption made that the state will never be Idle here.
|
||||
Interlocked.CompareExchange(ref _state, (int)JobState.Running, (int)JobState.Scheduled);
|
||||
|
||||
_nextJobIndexToExecute = 0;
|
||||
while (_nextJobIndexToExecute < _jobs.Count)
|
||||
{
|
||||
if (ReadStateSynchronised() == JobState.Abort)
|
||||
{
|
||||
executionResult = ExecutionResult.Aborted;
|
||||
break;
|
||||
}
|
||||
|
||||
var job = _jobs[_nextJobIndexToExecute++];
|
||||
job.Run();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
var lastTickTime = StopTimerAndUpdateMetrics(executionResult);
|
||||
|
||||
_jobs.Clear();
|
||||
_nextJobIndexToExecute = -1;
|
||||
onCompleteHandler?.Invoke(this, executionResult, lastTickTime);
|
||||
|
||||
// Inserts memory fences to ensure operations before the call are not ordered after the write.
|
||||
// Release semantics will ensure other threads seeing the change, will see previous changes as well.
|
||||
WriteStateSynchronised(JobState.Idle);
|
||||
}
|
||||
}
|
||||
|
||||
private double StopTimerAndUpdateMetrics(ExecutionResult executionResult)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_timer.Stop();
|
||||
if (executionResult != ExecutionResult.Success)
|
||||
return _timer.LastMillis;
|
||||
|
||||
_metrics.AverageTickTimeMillis = _timer.AverageMillis;
|
||||
_metrics.MaxTickTimeMillis = _timer.MaxMillis;
|
||||
_metrics.LastTickTimeMillis = _timer.LastMillis;
|
||||
return _timer.LastMillis;
|
||||
}
|
||||
}
|
||||
|
||||
// Using an IThreadPoolWorkItem allows us to avoid the overhead of a closure and delegate allocation for each job execution.
|
||||
private class WorkExecutor : IThreadPoolWorkItem
|
||||
{
|
||||
public WorkExecutor(JobRunner runner)
|
||||
{
|
||||
_runner = runner;
|
||||
}
|
||||
|
||||
public JobCompletedDelegate? OnCompleteHandler { private get; set; }
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
Debug.Assert(_runner != null);
|
||||
_runner.DoWork(OnCompleteHandler);
|
||||
}
|
||||
|
||||
private readonly JobRunner _runner;
|
||||
}
|
||||
|
||||
private int _state;
|
||||
private int _nextJobIndexToExecute;
|
||||
private readonly List<IJob> _jobs;
|
||||
private readonly JobRunnerTimer _timer;
|
||||
private JobRunnerMetrics _metrics;
|
||||
private readonly WorkExecutor _workExecutor;
|
||||
|
||||
// This can be passed in as a parameter to the constructor if you wish to share a lock
|
||||
// amongst your JobRunners.
|
||||
private readonly Lock _lock;
|
||||
|
||||
#endregion
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue