< Summary

Information
Class: Gravitas.Colliders.LSMeshCollider
Assembly: Gravitas
File(s): /home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/LSMeshCollider.cs
Line coverage
100%
Covered lines: 331
Uncovered lines: 0
Coverable lines: 331
Total lines: 660
Line coverage: 100%
Branch coverage
100%
Covered branches: 130
Total branches: 130
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_Shape()100%11100%
get_Priority()100%11100%
get_Area()100%11100%
get_Mesh()100%11100%
get_Mode()100%11100%
get_IsClosedSurface()100%11100%
.ctor(...)100%11100%
.ctor(...)100%11100%
.ctor(...)100%11100%
get_ScaledRadius()100%11100%
PrepareShape(...)100%44100%
PublishShape()100%22100%
CalculateMassPropertyWeight()100%44100%
CalculatePreparedMassPropertyWeight()100%44100%
get_SupportsMassProperties()100%22100%
CalculateLocalMassPoint()100%44100%
CalculatePreparedLocalMassPoint()100%44100%
CalculateInertiaTensor(...)100%2424100%
CalculateCenterOfMassInertiaTensor(...)100%11100%
EnsureDetachedMassGeometry()100%88100%
GetFrontalArea(...)100%11100%
GetNearbyTriangles(...)100%11100%
GetTrianglesInBounds(...)100%11100%
ClosestPointOnSurface(...)100%22100%
GetClosestSurfaceAnchor(...)100%11100%
FindClosestPointAnchor(...)100%11100%
FindClosestPointAnchor(...)100%1010100%
FindClosestPointWithoutLocalQuery(...)100%3434100%
GetClosestPointAnchorOnTriangle(...)100%22100%
GetMeshQueryHalfExtent()100%11100%
CreateQueryBounds(...)100%11100%
ValidateInertiaPolicy(...)100%22100%
GetVertices(...)100%11100%
GetTriangles(...)100%11100%
GetInertiaPolicy(...)100%11100%
TryCreateClosestPointSearchBounds(...)100%66100%
FindClosestPointAcrossAllTriangles(...)100%22100%
KeepClosestPointOnTriangle(...)100%88100%
GetNormalAtPoint(...)100%11100%
TryGetPlanarSurfaceNormal(...)100%11100%
ColliderOverlapsRay(...)100%11100%
OrientNormalTowardPoint(...)100%44100%
OrientNormalTowardPoint(...)100%44100%

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/LSMeshCollider.cs

#LineLine coverage
 1//=======================================================================
 2// LSMeshCollider.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System;
 9using System.Runtime.CompilerServices;
 10using FixedMathSharp;
 11using FixedMathSharp.Geometry;
 12using Gravitas.Queries;
 13using SwiftCollections;
 14using SwiftCollections.Query;
 15
 16namespace Gravitas.Colliders;
 17
 18/// <summary>Represents a runtime 3D collider backed by deterministic triangle-mesh geometry.</summary>
 19public sealed class LSMeshCollider : LSCollider
 20{
 21    internal StaticSurface? StaticSurface { get; set; }
 399022    private readonly SwiftList<int> _triangleQueryBuffer = new();
 23    private bool _inertiaOriginValid, _inertiaOriginExact;
 24    private Vector3d _inertiaOriginOffset, _inertiaOriginScale, _inertiaOrigin;
 25
 26    /// <inheritdoc/>
 249305327    public override ColliderType Shape => ColliderType.Mesh;
 28
 29    /// <inheritdoc/>
 2503130    public override int Priority => ColliderSettings.GetPriority(Shape);
 31
 32    /// <inheritdoc/>
 283333    public override Fixed64 Area => Mesh.TotalArea;
 34
 35    /// <summary>Gets the deterministic runtime mesh geometry.</summary>
 36    /// <remarks>
 37    /// Detached access prepares geometry at the current authored part scale.
 38    /// Runtime transforms are owned by the collider, body and host transform;
 39    /// the returned mesh cannot be transformed independently.
 40    /// </remarks>
 41    public PhysicsMesh Mesh
 42    {
 43        get
 44        {
 188519545            EnsureDetachedMassGeometry();
 188519546            return GeometryMesh;
 47        }
 48    }
 49
 50    internal PhysicsMesh GeometryMesh { get; }
 51
 52    /// <summary>Gets the mesh collision mode.</summary>
 6028953    public MeshColliderMode Mode => GeometryMesh.Mode;
 54
 55    /// <summary>
 56    /// Gets whether the mesh's exact-position-welded triangle topology is one
 57    /// connected, consistently wound, closed two-manifold surface.
 58    /// </summary>
 17759    public bool IsClosedSurface => GeometryMesh.IsClosedSurface;
 60
 61    /// <summary>
 62    /// Determines how inertia is derived when this mesh collider is attached to a body with angular dynamics.
 63    /// </summary>
 64    public MeshInertiaPolicy InertiaPolicy { get; }
 65
 66    /// <summary>Creates a convex mesh collider from authored vertices and triangle indices.</summary>
 67    public LSMeshCollider(Vector3d[] vertices, int[] triangles)
 1968        : this(vertices, triangles, MeshColliderMode.Convex, MeshInertiaPolicy.RequireClosedVolume)
 69    {
 1970    }
 71
 72    /// <summary>Creates a mesh collider with an explicit collision mode.</summary>
 73    public LSMeshCollider(Vector3d[] vertices, int[] triangles, MeshColliderMode mode)
 9574        : this(vertices, triangles, mode, MeshInertiaPolicy.RequireClosedVolume)
 75    {
 9576    }
 77
 78    /// <summary>Creates a mesh collider with explicit collision and inertia policies.</summary>
 399079    public LSMeshCollider(
 399080        Vector3d[] vertices,
 399081        int[] triangles,
 399082        MeshColliderMode mode,
 399083        MeshInertiaPolicy inertiaPolicy)
 84    {
 399085        ValidateInertiaPolicy(inertiaPolicy);
 399086        InertiaPolicy = inertiaPolicy;
 399087        GeometryMesh = new PhysicsMesh(vertices, triangles, mode, colliderOwned: true);
 399088        _offset = GeometryMesh.LocalBounds.Center;
 89        // The inherited authoring summary may saturate; runtime vertices retain exact source differences.
 399090        _size = GeometryMesh.LocalBounds.Max - GeometryMesh.LocalBounds.Min;
 399091        _radius = _size.Magnitude * Fixed64.Half;
 399092    }
 93
 94    /// <summary>Creates a runtime convex mesh from an authored shape definition.</summary>
 95    public LSMeshCollider(ColliderShapeDefinition definition)
 21496        : this(
 21497            GetVertices(definition),
 21498            GetTriangles(definition),
 21499            MeshColliderMode.Convex,
 214100            GetInertiaPolicy(definition))
 101    {
 214102        Material = definition.Material;
 214103    }
 104
 105    /// <inheritdoc/>
 106    public override Fixed64 ScaledRadius
 107    {
 108        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 109        get
 110        {
 94111            EnsureDetachedMassGeometry();
 94112            return GeometryMesh.ScaledLocalRadius;
 113        }
 114    }
 115
 116    private protected override void PrepareShape(in ColliderShapeSnapshot snapshot)
 117    {
 19703118        GeometryMesh.PrepareTransformation(
 19703119            snapshot.Center,
 19703120            snapshot.Rotation,
 19703121            snapshot.OwnerScale,
 19703122            snapshot.PartScale,
 19703123            InertiaPolicy,
 19703124            new ScaledRigidFrame3d(snapshot.PoseOrigin, snapshot.PlacementRotation,
 19703125                snapshot.LocalOffset, snapshot.OwnerScale, snapshot.Rotation,
 19703126                GeometryMesh.LocalBounds.Center, snapshot.PartScale));
 19695127        if (CompoundOwner == null
 19695128            && !CalculatePreparedLocalMassPoint().TryGetPoint(out _))
 129        {
 1130            throw new InvalidOperationException(
 1131                "Prepared collider mass-property point is outside the Fixed64 coordinate domain.");
 132        }
 19694133        SetPreparedGeometryReach(GeometryMesh.PreparedScaledLocalRadius);
 19694134        SetPreparedBounds(GeometryMesh.PreparedBounds);
 19694135    }
 136
 137    private protected override void PublishShape()
 138    {
 19685139        GeometryMesh.PublishPreparedTransformation();
 19685140        StaticSurface?.Invalidate(geometryChanged: true, changed: this);
 7141    }
 142
 143    internal override ExactMassWeight CalculateMassPropertyWeight()
 144    {
 81145        EnsureDetachedMassGeometry();
 81146        if (InertiaPolicy == MeshInertiaPolicy.SurfaceApproximation)
 147        {
 33148            _ = GeometryMesh.SurfaceMassProperties;
 33149            return GeometryMesh.SurfaceMassWeight;
 150        }
 151
 48152        if (GeometryMesh.TryGetClosedVolumeMassProperties(out MeshMassProperties properties, out _))
 39153            return GeometryMesh.GetCompoundMassIntegrals(usePrepared: false, InertiaPolicy).Weight;
 154
 9155        return ExactMassWeight.Zero;
 156    }
 157
 158    internal override ExactMassWeight CalculatePreparedMassPropertyWeight()
 159    {
 5650160        if (InertiaPolicy == MeshInertiaPolicy.SurfaceApproximation)
 268161            return GeometryMesh.PreparedSurfaceMassWeight;
 162
 5382163        if (GeometryMesh.TryGetPreparedClosedVolumeMassProperties(
 5382164            out MeshMassProperties properties,
 5382165            out _))
 166        {
 5352167            return GeometryMesh.GetCompoundMassIntegrals(usePrepared: true, InertiaPolicy).Weight;
 168        }
 169
 30170        return ExactMassWeight.Zero;
 171    }
 172
 173    internal override bool SupportsMassProperties
 174    {
 175        get
 176        {
 40177            EnsureDetachedMassGeometry();
 37178            return InertiaPolicy == MeshInertiaPolicy.SurfaceApproximation
 37179                || GeometryMesh.TryGetClosedVolumeMassProperties(out _, out _);
 180        }
 181    }
 182
 183    internal override ExactMassPoint3D CalculateLocalMassPoint()
 184    {
 7738185        EnsureDetachedMassGeometry();
 186        Vector3d meshCenterOfMass;
 7738187        if (InertiaPolicy == MeshInertiaPolicy.SurfaceApproximation)
 188        {
 2664189            meshCenterOfMass =
 2664190                GeometryMesh.SurfaceMassProperties.CenterOfMass;
 191        }
 5074192        else if (GeometryMesh.TryGetClosedVolumeMassProperties(
 5074193            out MeshMassProperties properties,
 5074194            out _))
 195        {
 5041196            meshCenterOfMass = properties.CenterOfMass;
 197        }
 198        else
 199        {
 33200            meshCenterOfMass = Vector3d.Zero;
 201        }
 202
 7738203        return TransformRelativeMassPropertyPointExact(
 7738204            meshCenterOfMass);
 205    }
 206
 207    internal override ExactMassPoint3D CalculatePreparedLocalMassPoint()
 208    {
 209        Vector3d meshCenterOfMass;
 19695210        if (InertiaPolicy == MeshInertiaPolicy.SurfaceApproximation)
 211        {
 7500212            meshCenterOfMass =
 7500213                GeometryMesh.PreparedSurfaceMassProperties.CenterOfMass;
 214        }
 12195215        else if (GeometryMesh.TryGetPreparedClosedVolumeMassProperties(
 12195216            out MeshMassProperties properties,
 12195217            out _))
 218        {
 12100219            meshCenterOfMass = properties.CenterOfMass;
 220        }
 221        else
 222        {
 95223            meshCenterOfMass = Vector3d.Zero;
 224        }
 225
 19695226        return TransformPreparedRelativeMassPropertyPointExact(
 19695227            meshCenterOfMass);
 228    }
 229
 230    /// <inheritdoc/>
 231    public override Fixed3x3 CalculateInertiaTensor(Fixed64 mass, Vector3d localCenterOfMassOffset)
 232    {
 1731233        if (mass <= Fixed64.Zero) return Fixed3x3.Zero;
 1729234        EnsureDetachedMassGeometry();
 1729235        if (CompoundOwner == null)
 236        {
 1725237            GetCurrentShapeScales(out Vector3d ownerScale, out _);
 1725238            if (!_inertiaOriginValid || _inertiaOriginOffset != LocalOffset || _inertiaOriginScale != ownerScale)
 239            {
 567240                ExactMassPoint3D origin = TransformRelativeMassPropertyPointExact(Vector3d.Zero);
 567241                _inertiaOriginExact = origin.TryGetPoint(out _inertiaOrigin);
 567242                if (_inertiaOriginExact)
 243                {
 566244                    ExactMassPoint3D projected = ExactMassPoint3D.FromPoint(_inertiaOrigin);
 566245                    _inertiaOriginExact = WideArithmetic.SubtractSigned320(origin.XNumerator, projected.XNumerator).IsZe
 566246                        && WideArithmetic.SubtractSigned320(origin.YNumerator, projected.YNumerator).IsZero
 566247                        && WideArithmetic.SubtractSigned320(origin.ZNumerator, projected.ZNumerator).IsZero;
 248                }
 567249                _inertiaOriginOffset = LocalOffset;
 567250                _inertiaOriginScale = ownerScale;
 567251                _inertiaOriginValid = true;
 252            }
 1725253            if (_inertiaOriginExact && Vector3d.TrySubtract(localCenterOfMassOffset, _inertiaOrigin, out Vector3d refere
 1704254                return GeometryMesh.CalculateInertiaTensor(mass, InertiaPolicy, reference);
 255        }
 256        // Keep semantic offsets and first moments until the final mass-applied
 257        // conversion when a body-local reference cannot be mapped to a scalar.
 25258        if (InertiaPolicy == MeshInertiaPolicy.SurfaceApproximation)
 19259            _ = GeometryMesh.SurfaceMassProperties;
 6260        else if (!GeometryMesh.TryGetClosedVolumeMassProperties(out _, out MeshVolumeValidationResult result))
 1261            throw new InvalidOperationException($"Mesh inertia requires a validated closed volume. Validation result: {r
 24262        MeshMassIntegrals integrals = GeometryMesh.GetCompoundMassIntegrals(false, InertiaPolicy);
 24263        CompoundInertiaTensor exact = default;
 24264        CompoundInertiaMath3D.AddMesh(ref exact, integrals, CompoundLocalRotation,
 24265            TransformRelativeMassPropertyPointExact(integrals.Reference), localCenterOfMassOffset);
 24266        return exact.MaterializeSaturated(mass, integrals.Weight);
 267    }
 268
 269    internal override Fixed3x3 CalculateCenterOfMassInertiaTensor(Fixed64 mass) =>
 1270        CalculateInertiaTensor(mass, CalculateLocalCenterOfMassOffset());
 271
 272    private void EnsureDetachedMassGeometry()
 273    {
 3788398274        if (HasCommittedShape) return;
 1358275        GetCurrentShapeScales(out Vector3d ownerScale, out Vector3d partScale);
 2305276        if (GeometryMesh.HasRuntimeGeometry && GeometryMesh.OwnerScale == ownerScale && GeometryMesh.PartScale == partSc
 277        // Authored part scale may be compensated by a later host scale; prepare
 278        // only when current properties are requested, never during construction.
 411279        GeometryMesh.PrepareTransformation(_offset, FixedQuaternion.Identity, ownerScale, partScale, null);
 408280        GeometryMesh.PublishPreparedTransformation();
 408281        _bounds = GeometryMesh.Bounds;
 408282    }
 283
 284    /// <inheritdoc/>
 285    public override Fixed64 GetFrontalArea(Vector3d direction) =>
 5286        Mesh.GetFrontalArea(direction);
 287
 288    /// <summary>Writes triangle indices near a world-space point into a caller-owned buffer.</summary>
 289    public void GetNearbyTriangles(Vector3d queryPoint, SwiftList<int> result)
 290    {
 1291        EnsureDetachedMassGeometry();
 1292        FixedBoundVolume queryBounds = CreateQueryBounds(queryPoint, GetMeshQueryHalfExtent());
 1293        GetTrianglesInBounds(queryBounds, result);
 1294    }
 295
 296    /// <summary>Writes triangle indices overlapping world-space bounds into a caller-owned buffer.</summary>
 297    public void GetTrianglesInBounds(FixedBoundVolume queryBounds, SwiftList<int> result)
 298    {
 151929299        Mesh.GetTrianglesInWorldBounds(queryBounds, result);
 151929300    }
 301
 302    /// <inheritdoc/>
 303    public override Vector3d ClosestPointOnSurface(Vector3d queryPoint)
 304    {
 44305        FixedPointAnchor closest =
 44306            GetClosestSurfaceAnchor(queryPoint, out _);
 44307        if (closest.TryGetPoint(out Vector3d point))
 42308            return point;
 309
 2310        throw new InvalidOperationException(
 2311            "The closest mesh point is outside the representable coordinate range.");
 312    }
 313
 314    internal override FixedPointAnchor GetClosestSurfaceAnchor(
 315        Vector3d queryPoint,
 316        out Vector3d normal)
 317    {
 1258318        FindClosestPointAnchor(
 1258319            queryPoint,
 1258320            _triangleQueryBuffer,
 1258321            out FixedPointAnchor closest,
 1258322            out normal);
 1258323        return closest;
 324    }
 325
 326    internal void FindClosestPointAnchor(
 327        Vector3d queryPoint,
 328        out FixedPointAnchor closest,
 329        out Vector3d normal) =>
 1665330        FindClosestPointAnchor(
 1665331            queryPoint,
 1665332            _triangleQueryBuffer,
 1665333            out closest,
 1665334            out normal);
 335
 336    internal void FindClosestPointAnchor(
 337        Vector3d queryPoint,
 338        SwiftList<int> triangleBuffer,
 339        out FixedPointAnchor closest,
 340        out Vector3d normal)
 341    {
 5134342        if (!Mesh.GeometryFrame.IsRigid || !Mesh.TryConvertWorldToRigidGeometry(
 5134343                queryPoint,
 5134344                out Vector3d localQueryPoint))
 345        {
 119346            FindClosestPointWithoutLocalQuery(
 119347                queryPoint,
 119348                triangleBuffer,
 119349                out closest,
 119350                out normal);
 119351            return;
 352        }
 353
 5015354        Vector3d localClosest = localQueryPoint;
 5015355        normal = Vector3d.Zero;
 5015356        int closestTriangleIndex = -1;
 5015357        _ = KeepClosestPointOnTriangle(
 5015358            0,
 5015359            localQueryPoint,
 5015360            ref closestTriangleIndex,
 5015361            ref localClosest,
 5015362            ref normal);
 5015363        if (localClosest == localQueryPoint)
 364        {
 2439365            closest = Mesh.CreatePointAnchor(localClosest);
 2439366            normal = Mesh.Rotation.Rotate(normal).Normalized;
 2439367            return;
 368        }
 369
 2576370        if (!TryCreateClosestPointSearchBounds(
 2576371                localQueryPoint,
 2576372                localClosest,
 2576373                out FixedBoundVolume queryBounds))
 374        {
 2375            FindClosestPointAcrossAllTriangles(
 2376                localQueryPoint,
 2377                1,
 2378                ref closestTriangleIndex,
 2379                ref localClosest,
 2380                ref normal);
 381        }
 382        else
 383        {
 2574384            Mesh.GetTrianglesInGeometryBounds(queryBounds, triangleBuffer);
 24416385            for (int i = 0; i < triangleBuffer.Count; i++)
 386            {
 9634387                _ = KeepClosestPointOnTriangle(
 9634388                    triangleBuffer[i],
 9634389                    localQueryPoint,
 9634390                    ref closestTriangleIndex,
 9634391                    ref localClosest,
 9634392                    ref normal);
 393            }
 394        }
 395
 2576396        closest = Mesh.CreatePointAnchor(localClosest);
 2576397        normal = Mesh.Rotation.Rotate(normal).Normalized;
 2576398    }
 399
 400    private void FindClosestPointWithoutLocalQuery(
 401        Vector3d queryPoint,
 402        SwiftList<int> triangleBuffer,
 403        out FixedPointAnchor closest,
 404        out Vector3d normal)
 405    {
 119406        var queryAnchor = new FixedPointAnchor(
 119407            queryPoint,
 119408            FixedQuaternion.Identity,
 119409            Vector3d.Zero);
 119410        bool exactRanking = !Mesh.GeometryFrame.IsRigid;
 411        const int words = 36;
 119412        Span<ulong> values = stackalloc ulong[exactRanking ? 8 * words : 0];
 119413        Span<int> signs = stackalloc int[exactRanking ? 8 : 0];
 119414        ContactQuadratic bestNumerator = exactRanking ? ContactQuadratic.At(values, signs, 0, words) : default;
 119415        ContactQuadratic bestDenominator = exactRanking ? ContactQuadratic.At(values, signs, 1, words) : default;
 119416        ContactQuadratic candidateNumerator = exactRanking ? ContactQuadratic.At(values, signs, 2, words) : default;
 119417        ContactQuadratic candidateDenominator = exactRanking ? ContactQuadratic.At(values, signs, 3, words) : default;
 119418        closest = GetClosestPointAnchorOnTriangle(
 119419            0,
 119420            queryAnchor,
 119421            bestNumerator,
 119422            bestDenominator,
 119423            out normal);
 424        // The first finite witness bounds every possible winner in physical
 425        // space. Inverse-map that outward box into the existing authored BVH.
 119426        FixedBoundVolume bounds = default;
 119427        bool bounded = closest.TryGetPoint(out Vector3d firstPoint)
 119428            && TryCreateClosestPointSearchBounds(queryPoint, firstPoint, out bounds);
 232429        if (bounded) Mesh.GetTrianglesInWorldBounds(bounds, triangleBuffer);
 119430        int bestTriangle = 0;
 119431        int count = bounded ? triangleBuffer.Count : Mesh.TriangleCount;
 2790432        for (int index = 0; index < count; index++)
 433        {
 1276434            int triangleIndex = bounded ? triangleBuffer[index] : index;
 1276435            if (triangleIndex == 0) continue;
 1157436            FixedPointAnchor candidate = GetClosestPointAnchorOnTriangle(
 1157437                triangleIndex, queryAnchor, candidateNumerator, candidateDenominator, out Vector3d candidateNormal);
 1157438            int comparison = exactRanking
 1157439                ? ContactQuadratic.CompareRatios(candidateNumerator, candidateDenominator, ReadOnlySpan<ulong>.Empty,
 1157440                    bestNumerator, bestDenominator, ReadOnlySpan<ulong>.Empty)
 1157441                : queryAnchor.CompareSquaredDistance(candidate, closest);
 1157442            if (comparison > 0 || comparison == 0 && triangleIndex >= bestTriangle) continue;
 107443            if (exactRanking)
 444            {
 106445                candidateNumerator.CopyTo(bestNumerator);
 106446                candidateDenominator.CopyTo(bestDenominator);
 447            }
 107448            closest = candidate;
 107449            normal = candidateNormal;
 107450            bestTriangle = triangleIndex;
 451        }
 452
 119453    }
 454
 455    private FixedPointAnchor GetClosestPointAnchorOnTriangle(
 456        int triangleIndex,
 457        in FixedPointAnchor query,
 458        scoped ContactQuadratic squaredDistanceNumerator,
 459        scoped ContactQuadratic squaredDistanceDenominator,
 460        out Vector3d normal)
 461    {
 1276462        Mesh.GetGeometryTriangleVertices(
 1276463            triangleIndex,
 1276464            out Vector3d first,
 1276465            out Vector3d second,
 1276466            out Vector3d third);
 1276467        var triangle = new FixedTriangle(first, second, third);
 468        FixedPointAnchor closest;
 1276469        if (Mesh.GeometryFrame.IsRigid)
 8470            closest = triangle.GetClosestPointAnchor(Mesh.Origin, Mesh.Rotation, query);
 471        else
 472        {
 473            // This caller creates a scalar query with zero local displacement.
 474            // Its finite closest witness stays within admitted mesh reach.
 1268475            bool represented = WideTriangleRelations.TryGetClosestPointAnchor(triangle, Mesh.GeometryFrame,
 1268476                RationalPoint3d.FromScalarPoint(query.Origin), Mesh.Origin,
 1268477                squaredDistanceNumerator, squaredDistanceDenominator, out closest);
 478            System.Diagnostics.Debug.Assert(represented);
 479        }
 1276480        normal = OrientNormalTowardPoint(
 1276481            Mesh.GetFaceNormalWorld(triangleIndex),
 1276482            query,
 1276483            closest);
 1276484        return closest;
 485    }
 486
 487    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 488    private Fixed64 GetMeshQueryHalfExtent()
 489    {
 1490        Vector3d extents =
 1491            ColliderCanonicalBounds.GetMaximumAbsoluteExtents(
 1492                this,
 1493                Mesh.Origin);
 1494        return FixedMath.Max(
 1495            FixedMath.Max(extents.X, extents.Y),
 1496            extents.Z);
 497    }
 498
 499    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 500    private static FixedBoundVolume CreateQueryBounds(Vector3d center, Fixed64 halfExtent)
 501    {
 1502        Vector3d extents = Vector3d.One * halfExtent;
 1503        return new FixedBoundVolume(center - extents, center + extents);
 504    }
 505
 506    private static void ValidateInertiaPolicy(MeshInertiaPolicy inertiaPolicy)
 507    {
 3990508        ChronicleGuard.ThrowIfArgument(
 3990509            inertiaPolicy != MeshInertiaPolicy.RequireClosedVolume &&
 3990510            inertiaPolicy != MeshInertiaPolicy.SurfaceApproximation,
 3990511            nameof(inertiaPolicy),
 3990512            "Unsupported mesh inertia policy.");
 3990513    }
 514
 515    private static Vector3d[] GetVertices(ColliderShapeDefinition definition)
 516    {
 214517        definition.EnsureKind(ColliderShapeDefinitionKind.ConvexMesh);
 214518        return definition.GetMeshVerticesForRuntime();
 519    }
 520
 521    private static int[] GetTriangles(ColliderShapeDefinition definition)
 522    {
 214523        definition.EnsureKind(ColliderShapeDefinitionKind.ConvexMesh);
 214524        return definition.GetMeshTrianglesForRuntime();
 525    }
 526
 527    private static MeshInertiaPolicy GetInertiaPolicy(ColliderShapeDefinition definition)
 528    {
 214529        definition.EnsureKind(ColliderShapeDefinitionKind.ConvexMesh);
 214530        return definition.MeshInertiaPolicy;
 531    }
 532
 533    private static bool TryCreateClosestPointSearchBounds(
 534        Vector3d point,
 535        Vector3d closest,
 536        out FixedBoundVolume bounds)
 537    {
 2694538        if (!Vector3d.TrySubtract(point, closest, out Vector3d delta)
 2694539            || !delta.TryGetMagnitudeCeiling(out Fixed64 halfExtent)
 2694540            || !Fixed64.TryAdd(
 2694541                halfExtent,
 2694542                Fixed64.Epsilon,
 2694543                out halfExtent))
 544        {
 7545            bounds = default;
 7546            return false;
 547        }
 548
 2687549        Vector3d extents = Vector3d.One * halfExtent;
 2687550        Vector3d min = point - extents;
 2687551        Vector3d max = point + extents;
 2687552        bounds = new FixedBoundVolume(min, max);
 2687553        return true;
 554    }
 555
 556    private void FindClosestPointAcrossAllTriangles(
 557        Vector3d point,
 558        int startTriangleIndex,
 559        ref int closestTriangleIndex,
 560        ref Vector3d closest,
 561        ref Vector3d normal)
 562    {
 6563        for (int i = startTriangleIndex; i < Mesh.TriangleCount; i++)
 564        {
 1565            _ = KeepClosestPointOnTriangle(
 1566                i,
 1567                point,
 1568                ref closestTriangleIndex,
 1569                ref closest,
 1570                ref normal);
 571        }
 2572    }
 573
 574    private bool KeepClosestPointOnTriangle(
 575        int triangleIndex,
 576        Vector3d point,
 577        ref int closestTriangleIndex,
 578        ref Vector3d closest,
 579        ref Vector3d normal)
 580    {
 14650581        Mesh.GetGeometryTriangleVertices(
 14650582            triangleIndex,
 14650583            out Vector3d first,
 14650584            out Vector3d second,
 14650585            out Vector3d third);
 14650586        var triangle = new FixedTriangle(first, second, third);
 14650587        Vector3d faceNormal = triangle.Normal;
 14650588        Vector3d pointOnTriangle = triangle.ClosestPoint(point);
 14650589        if (closestTriangleIndex >= 0)
 590        {
 9635591            int distanceComparison = Vector3d.CompareDistanceSquared(
 9635592                point,
 9635593                pointOnTriangle,
 9635594                point,
 9635595                closest);
 9635596            if (distanceComparison > 0
 9635597                || (distanceComparison == 0 && triangleIndex >= closestTriangleIndex))
 598            {
 8110599                return false;
 600            }
 601        }
 602
 6540603        closestTriangleIndex = triangleIndex;
 6540604        closest = pointOnTriangle;
 6540605        normal = OrientNormalTowardPoint(faceNormal, point - pointOnTriangle);
 6540606        return true;
 607    }
 608
 609    /// <inheritdoc/>
 610    public override Vector3d GetNormalAtPoint(Vector3d point)
 611    {
 657612        _ = GetClosestSurfaceAnchor(
 657613            point,
 657614            out Vector3d normal);
 657615        return normal;
 616    }
 617
 618    internal override bool TryGetPlanarSurfaceNormal(Vector3d point, out Vector3d normal)
 619    {
 2211620        FindClosestPointAnchor(
 2211621            point,
 2211622            _triangleQueryBuffer,
 2211623            out _,
 2211624            out normal);
 2211625        return true;
 626    }
 627
 628    /// <inheritdoc/>
 629    public override bool ColliderOverlapsRay(RaycastSegmentWorker worker, ref SwiftList<Vector3d> outputIntersectionPoin
 630    {
 1346631        return worker.CheckMeshOverlaps(this, ref outputIntersectionPoints);
 632    }
 633
 634    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 635    private static Vector3d OrientNormalTowardPoint(Vector3d normal, Vector3d targetDirection)
 636    {
 6540637        if (targetDirection.MagnitudeSquared <= Fixed64.Epsilon)
 3088638            return normal;
 639
 3452640        return Vector3d.Dot(normal, targetDirection) < Fixed64.Zero ? -normal : normal;
 641    }
 642
 643    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 644    private static Vector3d OrientNormalTowardPoint(
 645        Vector3d normal,
 646        in FixedPointAnchor target,
 647        in FixedPointAnchor surfacePoint)
 648    {
 1276649        if (target.ProjectNonNegativeOffsetFrom(surfacePoint, normal)
 1276650            > Fixed64.Zero)
 651        {
 971652            return normal;
 653        }
 654
 305655        return surfacePoint.ProjectNonNegativeOffsetFrom(target, normal)
 305656            > Fixed64.Zero
 305657            ? -normal
 305658            : normal;
 659    }
 660}

Methods/Properties

.ctor(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.MeshColliderMode,Gravitas.Colliders.MeshInertiaPolicy)
get_Shape()
get_Priority()
get_Area()
get_Mesh()
get_Mode()
get_IsClosedSurface()
.ctor(FixedMathSharp.Vector3d[],System.Int32[])
.ctor(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.MeshColliderMode)
.ctor(Gravitas.Colliders.ColliderShapeDefinition)
get_ScaledRadius()
PrepareShape(System.Runtime.InteropServices.InAttribute))
PublishShape()
CalculateMassPropertyWeight()
CalculatePreparedMassPropertyWeight()
get_SupportsMassProperties()
CalculateLocalMassPoint()
CalculatePreparedLocalMassPoint()
CalculateInertiaTensor(FixedMathSharp.Fixed64,FixedMathSharp.Vector3d)
CalculateCenterOfMassInertiaTensor(FixedMathSharp.Fixed64)
EnsureDetachedMassGeometry()
GetFrontalArea(FixedMathSharp.Vector3d)
GetNearbyTriangles(FixedMathSharp.Vector3d,SwiftCollections.SwiftList`1<System.Int32>)
GetTrianglesInBounds(SwiftCollections.Query.FixedBoundVolume,SwiftCollections.SwiftList`1<System.Int32>)
ClosestPointOnSurface(FixedMathSharp.Vector3d)
GetClosestSurfaceAnchor(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&)
FindClosestPointAnchor(FixedMathSharp.Vector3d,FixedMathSharp.Geometry.FixedPointAnchor&,FixedMathSharp.Vector3d&)
FindClosestPointAnchor(FixedMathSharp.Vector3d,SwiftCollections.SwiftList`1<System.Int32>,FixedMathSharp.Geometry.FixedPointAnchor&,FixedMathSharp.Vector3d&)
FindClosestPointWithoutLocalQuery(FixedMathSharp.Vector3d,SwiftCollections.SwiftList`1<System.Int32>,FixedMathSharp.Geometry.FixedPointAnchor&,FixedMathSharp.Vector3d&)
GetClosestPointAnchorOnTriangle(System.Int32,FixedMathSharp.Geometry.FixedPointAnchor&,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Vector3d&)
GetMeshQueryHalfExtent()
CreateQueryBounds(FixedMathSharp.Vector3d,FixedMathSharp.Fixed64)
ValidateInertiaPolicy(Gravitas.Colliders.MeshInertiaPolicy)
GetVertices(Gravitas.Colliders.ColliderShapeDefinition)
GetTriangles(Gravitas.Colliders.ColliderShapeDefinition)
GetInertiaPolicy(Gravitas.Colliders.ColliderShapeDefinition)
TryCreateClosestPointSearchBounds(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,SwiftCollections.Query.FixedBoundVolume&)
FindClosestPointAcrossAllTriangles(FixedMathSharp.Vector3d,System.Int32,System.Int32&,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&)
KeepClosestPointOnTriangle(System.Int32,FixedMathSharp.Vector3d,System.Int32&,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&)
GetNormalAtPoint(FixedMathSharp.Vector3d)
TryGetPlanarSurfaceNormal(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&)
ColliderOverlapsRay(Gravitas.Queries.RaycastSegmentWorker,SwiftCollections.SwiftList`1<FixedMathSharp.Vector3d>&)
OrientNormalTowardPoint(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
OrientNormalTowardPoint(FixedMathSharp.Vector3d,FixedMathSharp.Geometry.FixedPointAnchor&,FixedMathSharp.Geometry.FixedPointAnchor&)