Skip to content

Commit

Permalink
Cleanup (#27)
Browse files Browse the repository at this point in the history
* Add SmallConstraints to SpanData

* Make Shapes, Springs and Points public in SoftBody.cs

* Add AddRemoveTests.cs

* Add IsRegistered to Shape.cs

* Auto-clean

* Simplify Edges of SoftBodyCube.cs in the demo.
  • Loading branch information
notgiven688 authored Oct 10, 2023
1 parent 11e31cb commit 91716af
Show file tree
Hide file tree
Showing 37 changed files with 211 additions and 137 deletions.
2 changes: 1 addition & 1 deletion src/Jitter2/Collision/CollisionIsland.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public sealed class Island : IListIndex
public ReadOnlyHashSet<RigidBody> Bodies { get; private set; }

int IListIndex.ListIndex { get; set; } = -1;

/// <summary>
/// Initializes a new instance of the <see cref="Island"/> class.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Jitter2/Collision/DynamicTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ void SetTime(Timings type)
{
var sl = lists[ntask];
updatedProxies += sl.Count;

for (int i = 0; i < sl.Count; i++)
{
T proxy = sl[i];
Expand Down
2 changes: 1 addition & 1 deletion src/Jitter2/Collision/NarrowPhase/ConvexPolytope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public static bool Equals(in Edge a, in Edge b)
/// The return value may be invalidated by subsequent calls to <see cref="AddVertex"/> or <see cref="AddPoint"/>.
/// </summary>
public readonly bool OriginEnclosed => originEnclosed;

/// <summary>
/// Computes the barycentric coordinates of the origin projected onto a given triangle.
/// These coordinates are used to retrieve points in A- and B-space.
Expand Down
9 changes: 4 additions & 5 deletions src/Jitter2/Collision/NarrowPhase/NarrowPhase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ public static bool Raycast(ISupportMap support, in JMatrix orientation,

return result;
}

/// <summary>
/// Performs a raycast against a shape.
/// </summary>
Expand All @@ -525,12 +525,12 @@ public static bool Raycast(ISupportMap support, in JVector origin, in JVector di
{
solver.MKD.SupportA = support;
solver.MKD.SupportB = null!;

bool result = solver.Raycast(origin, direction, out fraction, out normal);

return result;
}

/// <summary>
/// Determines whether two convex shapes overlap, providing detailed information for both overlapping and separated
/// cases. Internally, the method employs the Expanding Polytope Algorithm (EPA) to gather collision information.
Expand Down Expand Up @@ -633,7 +633,7 @@ public static bool MPREPA(ISupportMap supportA, ISupportMap supportB,

return res;
}

/// <summary>
/// Detects whether two convex shapes overlap and provides detailed collision information.
/// It assumes that support shape A is at position zero and not rotated.
Expand Down Expand Up @@ -669,5 +669,4 @@ public static bool MPREPA(ISupportMap supportA, ISupportMap supportB,

return res;
}

}
15 changes: 11 additions & 4 deletions src/Jitter2/Collision/Shapes/Shape.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,25 @@ public abstract class Shape : ISupportMap, IListIndex, IDynamicTreeProxy
/// arranging shapes in a well-defined order.
/// </summary>
public readonly ulong ShapeId;

public Shape()
{
ShapeId = World.IdCounter++;
}

internal bool AttachRigidBody(RigidBody? body)
{
RigidBody ??= body;
return RigidBody == body;
if (RigidBody == null)
{
RigidBody = body;
return true;
}

return false;
}

public bool IsRegistered => (this as IListIndex).ListIndex != -1;

internal void DetachRigidBody()
{
RigidBody = null!;
Expand All @@ -63,7 +70,7 @@ internal void DetachRigidBody()
/// <summary>
/// The instance of <see cref="RigidBody"/> to which this shape is attached.
/// </summary>
public RigidBody? RigidBody { get; private set; } = null!;
public RigidBody? RigidBody { get; private set; }

/// <summary>
/// The bounding box of the shape in world space. It is automatically updated when the position or
Expand Down
2 changes: 1 addition & 1 deletion src/Jitter2/Collision/Shapes/SphereShape.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public override void SupportMap(in JVector direction, out JVector result)
result.Normalize();
JVector.Multiply(result, radius, out result);
}

public override void CalculateBoundingBox(in JMatrix orientation, in JVector position, out JBBox box)
{
box.Min.X = -radius;
Expand Down
2 changes: 1 addition & 1 deletion src/Jitter2/Collision/Shapes/TriangleShape.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public void GetWorldVertices(out JVector a, out JVector b, out JVector c)
c = Mesh.Vertices[triangle.IndexC];

if (RigidBody == null) return;

ref JMatrix orientation = ref RigidBody.Data.Orientation;
ref JVector position = ref RigidBody.Data.Position;

Expand Down
14 changes: 7 additions & 7 deletions src/Jitter2/Collision/TriangleMesh.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Jitter2.LinearMath;

namespace Jitter2.Collision;
Expand All @@ -45,7 +46,6 @@ public DegenerateTriangleException(string message, Exception inner) : base(messa
}
}


/// <summary>
/// Encapsulates the data of a triangle mesh. An instance of this can be supplied to the <see cref="Jitter2.Collision.Shapes.TriangleShape"/>.
/// The triangles within this class contain indices pointing to neighboring triangles.
Expand Down Expand Up @@ -85,7 +85,7 @@ public Triangle(int a, int b, int c)
#if NET6_0
System.Runtime.CompilerServices.Unsafe.SkipInit(out Normal);
#endif

IndexA = a;
IndexB = b;
IndexC = c;
Expand Down Expand Up @@ -116,7 +116,7 @@ public TriangleMesh(List<JTriangle> triangles)
{
Dictionary<JVector, int> tmpIndices = new();
List<JVector> tmpVertices = new();

// 1. step: build indices and vertices for triangles (JTriangle contains raw x, y, z coordinates).

Indices = new Triangle[triangles.Count];
Expand All @@ -125,7 +125,7 @@ int PushVector(JVector v)
{
if (!tmpIndices.TryGetValue(v, out int result))
{
result = (int)tmpVertices.Count;
result = tmpVertices.Count;
tmpIndices.Add(v, result);
tmpVertices.Add(v);
}
Expand All @@ -145,9 +145,9 @@ int PushVector(JVector v)
}

Vertices = tmpVertices.ToArray();

// 2. step: Identify the neighbors.

Dictionary<Edge, int> tmpEdges = new();

int GetEdge(Edge e)
Expand Down Expand Up @@ -179,7 +179,7 @@ int GetEdge(Edge e)
JVector A = Vertices[Indices[i].IndexA];
JVector B = Vertices[Indices[i].IndexB];
JVector C = Vertices[Indices[i].IndexC];

JVector normal = (C - A) % (B - A);

if (MathHelper.CloseToZero(normal, 1e-12f))
Expand Down
10 changes: 8 additions & 2 deletions src/Jitter2/DataStructures/ActiveList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ public ReadOnlyActiveList(ActiveList<T> list)

public T this[int i] => list[i];

public bool IsActive(T element) => list.IsActive(element);
public bool IsActive(T element)
{
return list.IsActive(element);
}

public IEnumerator<T> GetEnumerator()
{
Expand Down Expand Up @@ -151,7 +154,10 @@ private void Swap(int index0, int index1)
elements[index1].ListIndex = index1;
}

public bool IsActive(T element) => (element.ListIndex < Active);
public bool IsActive(T element)
{
return (element.ListIndex < Active);
}

public void MoveToActive(T element)
{
Expand Down
1 change: 0 additions & 1 deletion src/Jitter2/DataStructures/ReadOnlyHashset.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ namespace Jitter2.DataStructures;
/// <summary>
/// Implements a wrapper for <see cref="HashSet{T}"/>, eliminating garbage collection (GC) overhead during enumeration.
/// </summary>

public class ReadOnlyHashSet<T> : IReadOnlyCollection<T>
{
private readonly HashSet<T> hashset;
Expand Down
2 changes: 1 addition & 1 deletion src/Jitter2/Dynamics/Arbiter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class Arbiter

public RigidBody Body1 = null!;
public RigidBody Body2 = null!;

public JHandle<ContactData> Handle;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Jitter2/Dynamics/Constraints/AngularMotor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public float TargetVelocity
}

public JVector LocalAxis1 => handle.Data.LocalAxis1;

public JVector LocalAxis2 => handle.Data.LocalAxis2;

public float MaximumForce
Expand Down
3 changes: 1 addition & 2 deletions src/Jitter2/Dynamics/Constraints/Constraint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
*/

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Jitter2.UnmanagedMemory;

Expand Down Expand Up @@ -69,7 +68,7 @@ public abstract class Constraint : IDebugDrawable
/// </summary>
public JHandle<ConstraintData> Handle { internal set; get; }

public JHandle<SmallConstraintData> SmallHandle => JHandle<ConstraintData>.AsHandle<SmallConstraintData>(this.Handle);
public JHandle<SmallConstraintData> SmallHandle => JHandle<ConstraintData>.AsHandle<SmallConstraintData>(Handle);

/// <summary>
/// This method must be overridden. It initializes the function pointers for
Expand Down
5 changes: 1 addition & 4 deletions src/Jitter2/Dynamics/Constraints/DistanceLimit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,7 @@ public float TargetDistance
ref DistanceLimitData data = ref handle.Data;
data.Distance = value;
}
get
{
return handle.Data.Distance;
}
get => handle.Data.Distance;
}

public float Distance
Expand Down
4 changes: 2 additions & 2 deletions src/Jitter2/Dynamics/Constraints/LinearMotor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ protected override void Create()
prepareForIteration = &PrepareForIteration;
handle = JHandle<ConstraintData>.AsHandle<LinearMotorData>(Handle);
}

public JVector LocalAxis1 => handle.Data.LocalAxis1;

public JVector LocalAxis2 => handle.Data.LocalAxis2;

/// <summary>
Expand Down
13 changes: 9 additions & 4 deletions src/Jitter2/Dynamics/RigidBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public struct RigidBodyData
public sealed class RigidBody : IListIndex, IDebugDrawable
{
internal JHandle<RigidBodyData> handle;

public readonly ulong RigidBodyId;

/// <summary>
Expand Down Expand Up @@ -319,7 +319,7 @@ private void AttachToShape(Shape shape)
{
if (!shape.AttachRigidBody(this))
{
throw new InvalidOperationException("Shape has already been added to another body.");
throw new ArgumentException("Shape has already been added to another body.", nameof(shape));
}

if (shape.Mass == 0)
Expand Down Expand Up @@ -360,6 +360,11 @@ public void AddShape(IEnumerable<Shape> shapes, bool setMassInertia = true)
/// mass properties, assuming a unit density for the shape. If false, the inertia and mass remain unchanged.</param>
public void AddShape(Shape shape, bool setMassInertia = true)
{
if (shape.IsRegistered)
{
throw new ArgumentException("Shape can not be added. Is the shape already registered?");
}

AttachToShape(shape);
shapes.Add(shape);
if (setMassInertia) SetMassInertia();
Expand Down Expand Up @@ -413,15 +418,15 @@ public void RemoveShape(Shape shape, bool setMassInertia = true)
{
if (!shapes.Remove(shape))
{
throw new InvalidOperationException(
throw new ArgumentException(
"Shape is not part of this body.");
}

Stack<Arbiter> toRemoveArbiter = new();

foreach (var contact in Contacts)
{
if (contact.Handle.Data.Key.Key1 == shape.ShapeId || contact.Handle.Data.Key.Key2 == shape.ShapeId )
if (contact.Handle.Data.Key.Key1 == shape.ShapeId || contact.Handle.Data.Key.Key2 == shape.ShapeId)
{
toRemoveArbiter.Push(contact);
}
Expand Down
8 changes: 4 additions & 4 deletions src/Jitter2/Jitter2.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@

<PropertyGroup>
<Description>
Jitter Physics 2, the evolution of Jitter Physics, is an impulse-based dynamics engine with a semi-implicit Euler integrator.
It is a fast, simple, and dependency-free engine written in C# with a clear and user-friendly API.
Jitter Physics 2, the evolution of Jitter Physics, is an impulse-based dynamics engine with a semi-implicit Euler integrator.
It is a fast, simple, and dependency-free engine written in C# with a clear and user-friendly API.
</Description>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageReadmeFile>readme.md</PackageReadmeFile>
Expand All @@ -32,8 +32,8 @@
</PropertyGroup>

<ItemGroup>
<None Include="./../../publish/readme.md" Pack="true" PackagePath=""/>
<None Include="./../../publish/icon.png" Pack="true" PackagePath=""/>
<None Include="./../../publish/readme.md" Pack="true" PackagePath=""/>
<None Include="./../../publish/icon.png" Pack="true" PackagePath=""/>
</ItemGroup>

<PropertyGroup Condition="'$(Configuration)' == 'Release'">
Expand Down
12 changes: 6 additions & 6 deletions src/Jitter2/LinearMath/MathHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ public static bool LineLineIntersect(in JVector p1, in JVector p2, in JVector p3
}
*/

public static JMatrix InverseSquareRoot(JMatrix m, int sweeps = 2)
{
float phi, cp, sp;
Unsafe.SkipInit(out JMatrix r);

JMatrix rotation = JMatrix.Identity;

for (int i = 0; i < sweeps; i++)
{
// M32
Expand Down Expand Up @@ -111,10 +111,10 @@ public static JMatrix InverseSquareRoot(JMatrix m, int sweeps = 2)
}
}

JMatrix d = new JMatrix(1.0f / MathF.Sqrt(m.M11), 0, 0,
0, 1.0f / MathF.Sqrt(m.M22), 0,
JMatrix d = new JMatrix(1.0f / MathF.Sqrt(m.M11), 0, 0,
0, 1.0f / MathF.Sqrt(m.M22), 0,
0, 0, 1.0f / MathF.Sqrt(m.M33));

return rotation * d * JMatrix.Transpose(rotation);
}

Expand Down
5 changes: 1 addition & 4 deletions src/Jitter2/Parallelization/ThreadPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,7 @@ private ThreadPool()
ChangeThreadCount(ThreadCountSuggestion);
}

public static int ThreadCountSuggestion
{
get => Math.Max((int)(Environment.ProcessorCount * ThreadsPerProcessor), 1);
}
public static int ThreadCountSuggestion => Math.Max((int)(Environment.ProcessorCount * ThreadsPerProcessor), 1);

/// <summary>
/// Changes the number of worker threads.
Expand Down
Loading

0 comments on commit 91716af

Please sign in to comment.