< Summary

Line coverage
100%
Covered lines: 1868
Uncovered lines: 0
Coverable lines: 1868
Total lines: 3625
Line coverage: 100%
Branch coverage
100%
Covered branches: 802
Total branches: 802
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: .ctor(...)100%11100%
File 1: GetMassCache(...)100%66100%
File 1: GetRuntimeMassCache(...)100%88100%
File 1: BuildRuntimeMassCache(...)100%66100%
File 1: GetCompoundMassIntegrals(...)100%2424100%
File 2: .ctor(...)100%11100%
File 2: .cctor()100%11100%
File 2: CreateTopologyTriangles(...)100%1010100%
File 2: CompareVertexUses(...)100%66100%
File 2: CreateConvexSatEdgeVertexPairs(...)100%1818100%
File 2: RegisterBoundaryEdge(...)100%1010100%
File 2: CalculateSharedEdgeSide(...)100%44100%
File 2: ValidateOpenConvexBoundary(...)100%22100%
File 2: GetDominantNormalAxis(...)100%66100%
File 2: ProjectToBoundaryPlane(...)100%44100%
File 2: ValidateBoundaryMatchesConvexHull(...)100%11100%
File 2: TryGetStrictConvexBoundary(...)100%1212100%
File 2: ValidateProjectedTriangleFill(...)100%66100%
File 2: AppendConvexHullVertex(...)100%44100%
File 2: MatchesCyclicHull(...)100%66100%
File 2: CompareBoundaryVertices(...)100%22100%
File 2: HasSingleVertexLinks(...)100%1212100%
File 2: FindTriangleCornerIndex(...)100%44100%
File 2: CompareVertexCornerUses(...)100%22100%
File 2: CreateSatEdgeVertexPairs(...)100%44100%
File 2: CountConvexSatEdges(...)100%44100%
File 2: FindEdgeUseGroupEnd(...)100%44100%
File 2: ShouldIncludeConvexSatEdge(...)100%66100%
File 2: FindOppositeVertexIndex(...)100%88100%
File 2: .ctor(...)100%11100%
File 2: .ctor(...)100%11100%
File 2: .ctor(...)100%11100%
File 3: .ctor(...)100%11100%
File 3: .cctor()100%11100%
File 3: GetConvexCoplanarPatchCornerVertexIndices(...)100%22100%
File 3: get_HasSingleConvexCoplanarPatch()100%66100%
File 3: EnsureTopologyBuffer(...)100%22100%
File 3: ReleaseTopologyPreparation()100%11100%
File 3: PrepareCoplanarPatches(...)100%5050100%
File 3: PrepareConvexCoplanarPatchCorners(...)100%1818100%
File 3: ClassifyCoplanarSeam(...)100%44100%
File 3: CreateOrientedPatchBoundaryEdge(...)100%44100%
File 3: GetPatchProjectionAxis(...)100%22100%
File 3: RejectAmbiguousPatchBoundaryVertices(...)100%1212100%
File 3: ComparePatchBoundaryVertexUses(...)100%22100%
File 3: .ctor(...)100%11100%
File 4: get_LocalVertices()100%11100%
File 4: get_ScaledLocalVertices()100%11100%
File 4: get_VertexCount()100%11100%
File 4: get_Triangles()100%11100%
File 4: get_TriangleCount()100%11100%
File 4: get_ConvexSatEdgeVertexPairs()100%11100%
File 4: get_TotalArea()100%11100%
File 4: get_TriangleBVH()100%11100%
File 4: get_TriangleBvhBuildCount()100%11100%
File 4: .ctor(...)100%1010100%
File 4: get_Origin()100%22100%
File 4: get_Rotation()100%11100%
File 4: get_Bounds()100%11100%
File 4: get_LocalBounds()100%11100%
File 4: .ctor(...)100%11100%
File 4: .ctor(...)100%11100%
File 4: UpdatePosition(...)100%11100%
File 4: UpdateTransform(...)100%11100%
File 4: ValidateInput(...)100%1010100%
File 4: BuildTriangleBVH(...)100%22100%
File 4: CalculateBounds(...)100%22100%
File 4: CompareEdgeUses(...)100%88100%
File 4: GetFrontalArea(...)100%66100%
File 4: GetTriangleVertices(...)100%22100%
File 4: TryGetTriangleVertices(...)100%22100%
File 4: GetLocalTriangleVertices(...)100%11100%
File 4: GetScaledLocalFaceNormal(...)100%11100%
File 4: TryGetVertexWorld(...)100%11100%
File 4: GetVertexWorld(...)100%22100%
File 4: TryGetSupportVertexWorld(...)100%11100%
File 4: GetSupportVertexWorld(...)100%22100%
File 4: GetSupportVertexLocal(...)100%1414100%
File 4: .ctor(...)100%11100%
File 4: .ctor(...)100%11100%
File 4: Compare(...)100%22100%
File 4: BoundsPoint(...)100%88100%
File 4: Project(...)100%11100%
File 4: FindSupportVertexIndex(...)100%1212100%
File 4: SearchSupportLeaf(...)100%88100%
File 4: PushSupportNode(...)100%66100%
File 4: ComesBeforeSupportNode(...)100%22100%
File 4: BuildSupportTreeNode(...)100%22100%
File 4: RefitSupportTree(...)100%44100%
File 4: CalculateSupportRangeBounds(...)100%44100%
File 4: CreateSupportVertexIndices(...)100%22100%
File 4: GetDominantAxis(...)100%66100%
File 4: GetBoundsSupportPoint(...)100%66100%
File 4: GetFaceNormalWorld(...)100%22100%
File 4: GetTrianglesInWorldBounds(...)100%22100%
File 4: GetTrianglesInLocalBounds(...)100%22100%
File 4: TryConvertWorldToScaledLocal(...)100%11100%
File 4: ConvertWorldToScaledLocal(...)100%22100%
File 4: TryConvertScaledLocalToWorld(...)100%11100%
File 4: ConvertScaledLocalToWorld(...)100%22100%
File 4: CreatePointAnchor(...)100%22100%
File 4: TryConvertWorldDirectionToLocal(...)100%11100%
File 4: ConvertWorldDirectionToLocal(...)100%22100%
File 4: .ctor(...)100%11100%
File 4: get_StartVertexIndex()100%11100%
File 4: get_EndVertexIndex()100%11100%
File 4: Create(...)100%66100%
File 4: .ctor(...)100%11100%
File 4: Create(...)100%66100%
File 4: .ctor(...)100%11100%
File 4: get_IsLeaf()100%11100%
File 4: CreateLeaf(...)100%11100%
File 4: CreateBranch(...)100%11100%
File 4: .ctor()100%11100%
File 4: Reset(...)100%11100%
File 4: Compare(...)100%22100%
File 4: GetAxisValue(...)100%44100%
File 5: get_GeometryFrame()100%11100%
File 5: get_GeometryVertices()100%22100%
File 5: get_GeometryLocalBounds()100%22100%
File 5: GetGeometryTriangleVertices(...)100%11100%
File 5: TryConvertWorldToRigidGeometry(...)100%11100%
File 5: GetTrianglesInGeometryBounds(...)100%11100%
File 5: SelectPreparedGeometryFrame(...)100%44100%
File 6: .cctor()100%11100%
File 6: CalculateInertiaTensor(...)100%11100%
File 6: CalculateInertiaTensor(...)100%11100%
File 6: CalculateInertiaTensor(...)100%11100%
File 6: TryGetClosedVolumeMassProperties(...)100%11100%
File 6: TryGetPreparedClosedVolumeMassProperties(...)100%22100%
File 6: PrepareClosedVolumeMassProperties(...)100%88100%
File 6: TryCalculateCandidateClosedVolumeMassProperties(...)100%2222100%
File 6: PublishPreparedClosedVolumeMassProperties()100%22100%
File 6: EnsureScaledClosedVolumeMassProperties()100%22100%
File 6: EnsureClosedVolumeMassProperties()100%22100%
File 6: EvaluateClosedVolumeTopology(...)100%2424100%
File 6: TryCalculateClosedVolumeMassProperties(...)100%2020100%
File 6: IntegrateClosedVolume(...)100%44100%
File 6: TryGetIntegratedCenter(...)100%11100%
File 6: AddWeightedCoordinateSum(...)100%11100%
File 6: AddWeighted(...)100%11100%
File 6: GetTetrahedronDeterminant(...)100%11100%
File 6: ContainsDuplicateTriangle(...)100%44100%
File 6: CompareTriangleUses(...)100%1212100%
File 6: Find(...)100%22100%
File 6: Union(...)100%44100%
File 7: .ctor(...)100%11100%
File 7: get_OwnerScale()100%11100%
File 7: get_PartScale()100%11100%
File 7: get_ScaledLocalBounds()100%11100%
File 7: get_ScaledLocalRadius()100%11100%
File 7: get_PreparedScaledLocalRadius()100%11100%
File 7: get_HasRuntimeGeometry()100%11100%
File 7: get_SurfaceMassWeight()100%11100%
File 7: get_PreparedSurfaceMassWeight()100%11100%
File 7: GetScaledLocalRadius(...)100%1010100%
File 7: get_PreparedBounds()100%11100%
File 7: get_PreparedSurfaceMassProperties()100%11100%
File 7: get_SurfaceMassProperties()100%11100%
File 7: PrepareTransformation(...)100%11100%
File 7: PrepareTransformation(...)100%1616100%
File 7: PublishPreparedTransformation()100%88100%
File 7: ValidateSurfaceMassProperties(...)100%22100%
File 7: ValidateClosedVolumeScaleRepresentability(...)100%66100%
File 7: PrepareScaledGeometry(...)100%3434100%
File 7: CopyCommittedGeometryCandidate()100%11100%
File 8: .ctor(...)100%11100%
File 8: GetCanonicalSurfaceOrdinal(...)100%11100%
File 8: GetCanonicalSurfaceBoundaryVertexPairs(...)100%11100%
File 8: GetCoplanarTriangleNeighbors(...)100%11100%
File 8: GetWeldedTriangleVertexIndices(...)100%11100%
File 8: GetWeldedVertexTriangleIndices(...)100%11100%
File 8: PrepareWeldedSurfaceIncidence(...)100%66100%
File 8: PrepareSurfaceTopology(...)100%3232100%
File 8: PrepareCoplanarNeighbors(...)100%1212100%
File 8: AddCanonicalPatchBoundary(...)100%66100%
File 8: PrepareReducedSurfaceCycles(...)100%1212100%
File 8: AddSurfaceBoundaryEdge(...)100%22100%
File 8: CompareSurfaceBoundaryEdges(...)100%22100%
File 8: CompareSurfaceEdgeGeometry(...)100%22100%
File 8: CompareSurfaceDomains(...)100%44100%
File 8: CompareSurfacePositions(...)100%44100%
File 8: .ctor(...)100%11100%
File 9: .ctor(...)100%11100%
File 9: GetManifoldSurfaceOwner(...)100%22100%
File 9: GetManifoldSurfaceBoundaryVertexPairs(...)100%22100%
File 9: PrepareManifoldPatchTrust(...)100%1212100%
File 9: IsEmbeddedSurfaceBoundary(...)100%4444100%
File 9: SurfaceCycleOrientation(...)100%1212100%
File 9: SurfaceCycleContains(...)100%1414100%
File 9: SurfaceBoundarySegmentsIntersect(...)100%66100%

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/PhysicsMesh.CompoundMassProperties.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.CompoundMassProperties.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;
 11
 12namespace Gravitas.Colliders;
 13
 14/// <content>Caches and evaluates mesh mass integrals for compound collider parts.</content>
 15public partial class PhysicsMesh
 16{
 17    // Allocate retained moments only when inertia is requested. Each physical
 18    // policy keeps its geometry across alternating requests and pose changes.
 19    private CompoundMassCache? _compoundMassCache;
 20
 21    private sealed class CompoundMassCache
 22    {
 23        internal readonly MeshInertiaPolicy Policy;
 24        internal MeshMassIntegrals Current, Prepared;
 25        internal bool CurrentValid, PreparedValid;
 26        internal CompoundMassCache? Alternate;
 27        internal MeshRuntimeInertia? Runtime;
 28
 130229        internal CompoundMassCache(MeshInertiaPolicy policy) => Policy = policy;
 30    }
 31
 32    private CompoundMassCache GetMassCache(MeshInertiaPolicy policy)
 33    {
 896634        if (_compoundMassCache == null)
 64735            _compoundMassCache = new CompoundMassCache(policy);
 896636        return _compoundMassCache.Policy == policy ? _compoundMassCache
 896637            : _compoundMassCache.Alternate ??= new CompoundMassCache(policy);
 38    }
 39
 40    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 41    private CompoundMassCache GetRuntimeMassCache(MeshInertiaPolicy policy)
 42    {
 292443        if (policy != MeshInertiaPolicy.RequireClosedVolume && policy != MeshInertiaPolicy.SurfaceApproximation)
 244            throw new ArgumentOutOfRangeException(nameof(policy), policy, "Unsupported mesh inertia policy.");
 292245        CompoundMassCache cache = GetMassCache(policy);
 352346        if (cache.Runtime?.Ready != true) BuildRuntimeMassCache(cache);
 291847        return cache;
 48    }
 49
 50    [MethodImpl(MethodImplOptions.NoInlining)]
 51    private void BuildRuntimeMassCache(CompoundMassCache cache)
 52    {
 53        Vector3d center;
 60154        if (cache.Policy == MeshInertiaPolicy.RequireClosedVolume)
 55        {
 27856            if (!TryGetClosedVolumeMassProperties(out MeshMassProperties properties, out MeshVolumeValidationResult resu
 457                throw new InvalidOperationException($"Mesh inertia requires a validated closed volume. Validation result
 27458            center = properties.CenterOfMass;
 59        }
 32360        else center = SurfaceMassProperties.CenterOfMass;
 59761        MeshMassIntegrals integrals = GetCompoundMassIntegrals(usePrepared: false, cache.Policy);
 59762        (cache.Runtime ??= new MeshRuntimeInertia()).Build(integrals, center);
 59763    }
 64
 65    internal MeshMassIntegrals GetCompoundMassIntegrals(bool usePrepared, MeshInertiaPolicy policy)
 66    {
 604467        CompoundMassCache cache = GetMassCache(policy);
 604468        ref MeshMassIntegrals integrals = ref (usePrepared ? ref cache.Prepared : ref cache.Current);
 604469        ref bool valid = ref (usePrepared ? ref cache.PreparedValid : ref cache.CurrentValid);
 604470        if (!valid)
 71        {
 66072            Vector3d[] vertices = usePrepared ? _preparedScaledLocalVertices : _scaledLocalVertices;
 66073            bool exactScale = !(usePrepared ? _preparedScaleIsExact : _scaleIsExact);
 66074            ref readonly var frame = ref (usePrepared ? ref _preparedSourceFrame : ref _sourceFrame);
 75            // Public unit tensors are projections, not an input to mass-applied
 76            // moments. Evaluate once per effective geometry, never per mass/pose.
 66077            if (policy == MeshInertiaPolicy.SurfaceApproximation)
 78            {
 79                // Surface projection was already validated during preparation;
 80                // the same immutable geometry supplies its unrounded integrals.
 33481                _ = TriangleShellMassProperties.TryCreateUniformShell(
 33482                    exactScale ? _localVertices : vertices,
 33483                    _triangles, out _, out _, out _, out integrals,
 33484                    frame, exactScale);
 85            }
 86            else
 87            {
 32688                Vector3d reference = exactScale ? Vector3d.Zero : (usePrepared ? _preparedScaledLocalBounds : _scaledLoc
 32689                IntegrateClosedVolume(exactScale ? _localVertices : vertices, reference,
 32690                    out Signed576 volume,
 32691                    out Signed576 firstX, out Signed576 firstY, out Signed576 firstZ,
 32692                    out Signed576 x2, out Signed576 y2, out Signed576 z2,
 32693                    out Signed576 xy, out Signed576 xz, out Signed576 yz,
 32694                    frame, exactScale);
 32695                integrals = MeshMassIntegrals.FromSolid(reference, volume,
 32696                    firstX, firstY, firstZ, x2, y2, z2, xy, xz, yz, exactScale ? 64 : 0);
 97            }
 66098            valid = true;
 99        }
 6044100        return integrals;
 101    }
 102}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/PhysicsMesh.ConvexTopology.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.ConvexTopology.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.Collections.Generic;
 10using FixedMathSharp;
 11using FixedMathSharp.Geometry;
 12using SwiftCollections;
 13
 14namespace Gravitas.Colliders;
 15
 16/// <content>Welds topology vertices and validates convex boundaries for mesh collision features.</content>
 17public partial class PhysicsMesh
 18{
 435219    private readonly SwiftList<VertexUse> _topologyVertexUses = new();
 435220    private int[] _topologyRepresentativeIndices = Array.Empty<int>();
 435221    private int[] _topologyWeldedTriangles = Array.Empty<int>();
 435222    private readonly SwiftList<BoundaryVertex> _topologySortedBoundary = new();
 435223    private BoundaryVertex[] _topologyBoundaryHull = Array.Empty<BoundaryVertex>();
 435224    private BoundaryVertex[] _topologyStrictBoundary = Array.Empty<BoundaryVertex>();
 225    private static readonly IComparer<BoundaryVertex> BoundaryVertexComparer =
 226        Comparer<BoundaryVertex>.Create(CompareBoundaryVertices);
 227    private static readonly IComparer<VertexUse> TopologyVertexUseComparer = Comparer<VertexUse>.Create(CompareVertexUse
 28
 29    private int[] CreateTopologyTriangles(Vector3d[] vertices, int[] triangles)
 30    {
 434131        _topologyVertexUses.FastClear();
 434132        _topologyVertexUses.EnsureCapacity(vertices.Length);
 434133        EnsureTopologyBuffer(ref _topologyRepresentativeIndices, vertices.Length);
 434134        int[] representativeIndices = _topologyRepresentativeIndices;
 8942235        for (int i = 0; i < vertices.Length; i++)
 4037036            _topologyVertexUses.Add(new VertexUse(vertices[i], i));
 37
 434138        _topologyVertexUses.SortInPlace(TopologyVertexUseComparer);
 434139        ReadOnlySpan<VertexUse> vertexUses = _topologyVertexUses.AsReadOnlySpan();
 434140        int representativeIndex = vertexUses[0].VertexIndex;
 434141        representativeIndices[representativeIndex] = representativeIndex;
 434142        bool hasExactPositionSeams = false;
 8074043        for (int i = 1; i < vertices.Length; i++)
 44        {
 3602945            VertexUse current = vertexUses[i];
 3602946            if (current.Position != vertexUses[i - 1].Position)
 3512047                representativeIndex = current.VertexIndex;
 48            else
 90949                hasExactPositionSeams = true;
 50
 3602951            representativeIndices[current.VertexIndex] = representativeIndex;
 52        }
 53
 434154        if (!hasExactPositionSeams)
 427855            return triangles;
 56
 6357        EnsureTopologyBuffer(ref _topologyWeldedTriangles, triangles.Length);
 6358        int[] topologyTriangles = _topologyWeldedTriangles;
 487259        for (int i = 0; i < triangles.Length; i++)
 237360            topologyTriangles[i] = representativeIndices[triangles[i]];
 61
 6362        return topologyTriangles;
 63    }
 64
 65    private static int CompareVertexUses(VertexUse first, VertexUse second)
 66    {
 24301467        int comparison = first.Position.X.CompareTo(second.Position.X);
 24301468        if (comparison != 0)
 10705069            return comparison;
 70
 13596471        comparison = first.Position.Y.CompareTo(second.Position.Y);
 13596472        if (comparison != 0)
 7222173            return comparison;
 74
 6374375        comparison = first.Position.Z.CompareTo(second.Position.Z);
 6374376        if (comparison != 0)
 6216677            return comparison;
 78
 157779        return first.VertexIndex.CompareTo(second.VertexIndex);
 80    }
 81
 82    private int[] CreateConvexSatEdgeVertexPairs(
 83        Vector3d[] vertices,
 84        int[] triangles,
 85        int triangleCount)
 86    {
 136587        var triangleUses = new TriangleUse[triangleCount];
 136588        var edgeUses = new EdgeUse[triangleCount * 3];
 136589        int edgeIndex = 0;
 8117090        for (int i = 0; i < triangleCount; i++)
 91        {
 3922092            int triangleIndex = i * 3;
 3922093            int index0 = triangles[triangleIndex];
 3922094            int index1 = triangles[triangleIndex + 1];
 3922095            int index2 = triangles[triangleIndex + 2];
 96
 3922097            triangleUses[i] = TriangleUse.Create(index0, index1, index2);
 3922098            edgeUses[edgeIndex++] = EdgeUse.Create(index0, index1, i);
 3922099            edgeUses[edgeIndex++] = EdgeUse.Create(index1, index2, i);
 39220100            edgeUses[edgeIndex++] = EdgeUse.Create(index2, index0, i);
 101        }
 102
 1365103        ChronicleGuard.ThrowIfArgument(
 1365104            ContainsDuplicateTriangle(triangleUses),
 1365105            nameof(triangles),
 1365106            "Convex mesh triangles must not contain duplicate faces.");
 107
 1365108        Array.Sort(edgeUses, CompareEdgeUses);
 1365109        var parents = new int[triangleCount];
 81170110        for (int i = 0; i < parents.Length; i++)
 39220111            parents[i] = i;
 112
 1365113        var boundaryNext = new int[vertices.Length];
 1365114        var boundaryPrevious = new int[vertices.Length];
 1365115        Array.Fill(boundaryNext, -1);
 1365116        Array.Fill(boundaryPrevious, -1);
 117
 1365118        int boundaryEdgeCount = 0;
 1365119        int boundaryStart = -1;
 1365120        int dihedralSign = 0;
 62742121        for (int start = 0; start < edgeUses.Length;)
 122        {
 60015123            int end = FindEdgeUseGroupEnd(edgeUses, start);
 60015124            int useCount = end - start;
 60015125            ChronicleGuard.ThrowIfArgument(
 60015126                useCount > 2,
 60015127                nameof(triangles),
 60015128                "Convex mesh edges must be manifold and used by at most two triangles.");
 129
 60015130            EdgeUse first = edgeUses[start];
 60015131            if (useCount == 1)
 132            {
 2385133                RegisterBoundaryEdge(
 2385134                    first,
 2385135                    boundaryNext,
 2385136                    boundaryPrevious,
 2385137                    ref boundaryEdgeCount,
 2385138                    ref boundaryStart,
 2385139                    triangles);
 2384140                start = end;
 2384141                continue;
 142            }
 143
 57630144            EdgeUse second = edgeUses[start + 1];
 57630145            ChronicleGuard.ThrowIfArgument(
 57630146                first.Direction + second.Direction != 0,
 57630147                nameof(triangles),
 57630148                "Adjacent convex mesh triangles must use opposite shared-edge winding.");
 149
 57629150            Union(parents, first.TriangleIndex, second.TriangleIndex);
 57629151            int currentSign = CalculateSharedEdgeSide(vertices, triangles, first, second);
 57629152            if (currentSign != 0)
 153            {
 11369154                ChronicleGuard.ThrowIfArgument(
 11369155                    dihedralSign != 0 && currentSign != dihedralSign,
 11369156                    nameof(triangles),
 11369157                    "Closed convex mesh triangles must not contain reflex edges.");
 11368158                dihedralSign = currentSign;
 159            }
 160
 57628161            start = end;
 162        }
 163
 1362164        int root = Find(parents, 0);
 78406165        for (int i = 1; i < parents.Length; i++)
 166        {
 37842167            ChronicleGuard.ThrowIfArgument(
 37842168                Find(parents, i) != root,
 37842169                nameof(triangles),
 37842170                "Convex mesh triangles must form one edge-connected surface.");
 171        }
 172
 1361173        IsClosedSurface = boundaryEdgeCount == 0;
 1361174        _surfaceClosureValidationResult = IsClosedSurface
 1361175            ? MeshVolumeValidationResult.Valid
 1361176            : MeshVolumeValidationResult.BoundaryEdge;
 1361177        if (IsClosedSurface)
 178        {
 879179            ChronicleGuard.ThrowIfArgument(
 879180                dihedralSign == 0,
 879181                nameof(triangles),
 879182                "Closed convex mesh triangles must enclose nonzero volume.");
 879183            ChronicleGuard.ThrowIfArgument(
 879184                !HasSingleVertexLinks(triangles, edgeUses),
 879185                nameof(triangles),
 879186                "Closed convex mesh triangles must be manifold around every vertex.");
 187        }
 188        else
 189        {
 482190            ChronicleGuard.ThrowIfArgument(
 482191                dihedralSign != 0,
 482192                nameof(triangles),
 482193                "Open convex mesh triangles must form one coplanar surface.");
 480194            ValidateOpenConvexBoundary(
 480195                vertices,
 480196                triangles,
 480197                triangleCount,
 480198                boundaryNext,
 480199                boundaryEdgeCount,
 480200                boundaryStart);
 201        }
 202
 1356203        return CreateSatEdgeVertexPairs(edgeUses, vertices, triangles);
 204    }
 205
 206    private static void RegisterBoundaryEdge(
 207        EdgeUse edgeUse,
 208        int[] boundaryNext,
 209        int[] boundaryPrevious,
 210        ref int boundaryEdgeCount,
 211        ref int boundaryStart,
 212        int[] triangles)
 213    {
 2385214        int start = edgeUse.Direction > 0
 2385215            ? edgeUse.StartVertexIndex
 2385216            : edgeUse.EndVertexIndex;
 2385217        int end = edgeUse.Direction > 0
 2385218            ? edgeUse.EndVertexIndex
 2385219            : edgeUse.StartVertexIndex;
 220
 2385221        ChronicleGuard.ThrowIfArgument(
 2385222            boundaryNext[start] >= 0 || boundaryPrevious[end] >= 0,
 2385223            nameof(triangles),
 2385224            "Open convex mesh triangles must form one consistently wound boundary loop.");
 225
 2384226        boundaryNext[start] = end;
 2384227        boundaryPrevious[end] = start;
 2384228        boundaryEdgeCount++;
 2384229        if (boundaryStart < 0 || start < boundaryStart)
 842230            boundaryStart = start;
 2384231    }
 232
 233    private static int CalculateSharedEdgeSide(
 234        Vector3d[] vertices,
 235        int[] triangles,
 236        EdgeUse firstUse,
 237        EdgeUse secondUse)
 238    {
 57629239        int startIndex = firstUse.Direction > 0
 57629240            ? firstUse.StartVertexIndex
 57629241            : firstUse.EndVertexIndex;
 57629242        int endIndex = firstUse.Direction > 0
 57629243            ? firstUse.EndVertexIndex
 57629244            : firstUse.StartVertexIndex;
 57629245        Vector3d start = vertices[startIndex];
 57629246        Vector3d end = vertices[endIndex];
 57629247        Vector3d firstOpposite = vertices[FindOppositeVertexIndex(
 57629248            triangles,
 57629249            firstUse.TriangleIndex,
 57629250            startIndex,
 57629251            endIndex)];
 57629252        Vector3d secondOpposite = vertices[FindOppositeVertexIndex(
 57629253            triangles,
 57629254            secondUse.TriangleIndex,
 57629255            startIndex,
 57629256            endIndex)];
 257
 57629258        return Vector3d.ScalarTripleProductSign(
 57629259            end - start,
 57629260            firstOpposite - start,
 57629261            secondOpposite - start);
 262    }
 263
 264    private void ValidateOpenConvexBoundary(
 265        Vector3d[] vertices,
 266        int[] triangles,
 267        int triangleCount,
 268        int[] boundaryNext,
 269        int boundaryEdgeCount,
 270        int boundaryStart)
 271    {
 480272        ChronicleGuard.ThrowIfArgument(
 480273            boundaryStart < 0,
 480274            nameof(triangles),
 480275            "Open convex mesh triangles must form one boundary loop.");
 276
 480277        int droppedAxis = GetDominantNormalAxis(vertices, triangles);
 480278        var boundaryVertices = new BoundaryVertex[boundaryEdgeCount];
 480279        int current = boundaryStart;
 480280        int visitedEdges = 0;
 281        do
 282        {
 2366283            int next = boundaryNext[current];
 284
 2366285            boundaryVertices[visitedEdges] = new BoundaryVertex(
 2366286                ProjectToBoundaryPlane(vertices[current], droppedAxis),
 2366287                current);
 2366288            current = next;
 2366289            visitedEdges++;
 2366290            ChronicleGuard.ThrowIfArgument(
 2366291                visitedEdges > boundaryEdgeCount,
 2366292                nameof(triangles),
 2366293                "Open convex mesh triangles must form one boundary loop.");
 294        }
 2366295        while (current != boundaryStart);
 296
 480297        ChronicleGuard.ThrowIfArgument(
 480298            visitedEdges != boundaryEdgeCount,
 480299            nameof(triangles),
 480300            "Open convex mesh triangles must form one boundary loop.");
 301
 480302        ValidateBoundaryMatchesConvexHull(boundaryVertices, triangles);
 478303        ValidateProjectedTriangleFill(
 478304            vertices,
 478305            triangles,
 478306            triangleCount,
 478307            boundaryVertices,
 478308            droppedAxis);
 477309    }
 310
 311    private static int GetDominantNormalAxis(Vector3d[] vertices, int[] triangles)
 312    {
 480313        Vector3d first = vertices[triangles[0]];
 480314        Vector3d second = vertices[triangles[1]];
 480315        Vector3d third = vertices[triangles[2]];
 480316        Vector3d absoluteNormal = Vector3d.Abs(Vector3d.Cross(second - first, third - first));
 480317        if (absoluteNormal.X >= absoluteNormal.Y && absoluteNormal.X >= absoluteNormal.Z)
 27318            return 0;
 319
 453320        return absoluteNormal.Y >= absoluteNormal.Z ? 1 : 2;
 321    }
 322
 323    private static Vector2d ProjectToBoundaryPlane(Vector3d vertex, int droppedAxis) =>
 641975324        droppedAxis switch
 641975325        {
 161132326            0 => new Vector2d(vertex.Y, vertex.Z),
 321173327            1 => new Vector2d(vertex.X, vertex.Z),
 159670328            _ => new Vector2d(vertex.X, vertex.Y),
 641975329        };
 330
 331    private void ValidateBoundaryMatchesConvexHull(
 332        BoundaryVertex[] authoredBoundary,
 333        int[] triangles)
 334    {
 480335        ChronicleGuard.ThrowIfArgument(
 480336            !TryGetStrictConvexBoundary(authoredBoundary, authoredBoundary.Length, out _, out _),
 480337            nameof(triangles),
 480338            "Open convex mesh triangles must have a nondegenerate convex boundary.");
 478339    }
 340
 341    // Shared exact trust owner: local turn signs alone admit a star polygon.
 342    // Match the entire cyclic order against its monotone convex hull instead.
 343    private bool TryGetStrictConvexBoundary(BoundaryVertex[] authoredBoundary, int boundaryCount,
 344        out BoundaryVertex[] strictAuthoredBoundary, out int strictAuthoredCount)
 345    {
 8875346        strictAuthoredBoundary = Array.Empty<BoundaryVertex>();
 8875347        strictAuthoredCount = 0;
 8875348        EnsureTopologyBuffer(ref _topologyBoundaryHull, boundaryCount * 2);
 8875349        EnsureTopologyBuffer(ref _topologyStrictBoundary, boundaryCount);
 8875350        _topologySortedBoundary.FastClear();
 8875351        _topologySortedBoundary.AddRange(authoredBoundary.AsSpan(0, boundaryCount));
 8875352        _topologySortedBoundary.SortInPlace(BoundaryVertexComparer);
 8875353        ReadOnlySpan<BoundaryVertex> sorted = _topologySortedBoundary.AsReadOnlySpan();
 354
 355        // Both callers walk distinct exactly welded vertices in one coplanar
 356        // surface. Their projection drops a nonzero plane-normal component,
 357        // so it is injective on that plane and cannot duplicate positions.
 8875358        BoundaryVertex[] hull = _topologyBoundaryHull;
 8875359        int hullCount = 0;
 99166360        for (int i = 0; i < boundaryCount; i++)
 40708361            AppendConvexHullVertex(hull, ref hullCount, 2, sorted[i]);
 362
 8875363        int upperStart = hullCount + 1;
 81416364        for (int i = boundaryCount - 2; i >= 0; i--)
 31833365            AppendConvexHullVertex(hull, ref hullCount, upperStart, sorted[i]);
 366
 367        // The upper pass repeats the lexicographically first lower-hull point.
 8875368        hullCount--;
 369
 8875370        strictAuthoredBoundary = _topologyStrictBoundary;
 99166371        for (int i = 0; i < boundaryCount; i++)
 372        {
 40708373            BoundaryVertex previous = authoredBoundary[(i + boundaryCount - 1) % boundaryCount];
 40708374            BoundaryVertex current = authoredBoundary[i];
 40708375            BoundaryVertex next = authoredBoundary[(i + 1) % boundaryCount];
 40708376            if (Vector2d.OrientationSign(previous.Position, current.Position, next.Position) == 0)
 377                continue;
 378
 36202379            strictAuthoredBoundary[strictAuthoredCount++] = current;
 380        }
 381
 8875382        return hullCount >= 3 && strictAuthoredCount == hullCount
 8875383            && MatchesCyclicHull(strictAuthoredBoundary, strictAuthoredCount, hull);
 384    }
 385
 386    private static void ValidateProjectedTriangleFill(
 387        Vector3d[] vertices,
 388        int[] triangles,
 389        int triangleCount,
 390        BoundaryVertex[] boundary,
 391        int droppedAxis)
 392    {
 478393        Fixed64 triangleArea = Fixed64.Zero;
 478394        int surfaceOrientation = 0;
 3796395        for (int i = 0; i < triangleCount; i++)
 396        {
 1421397            int index = i * 3;
 1421398            Vector2d first = ProjectToBoundaryPlane(vertices[triangles[index]], droppedAxis);
 1421399            Vector2d second = ProjectToBoundaryPlane(vertices[triangles[index + 1]], droppedAxis);
 1421400            Vector2d third = ProjectToBoundaryPlane(vertices[triangles[index + 2]], droppedAxis);
 1421401            int orientation = Vector2d.OrientationSign(first, second, third);
 1421402            if (surfaceOrientation == 0)
 478403                surfaceOrientation = orientation;
 404
 1421405            ChronicleGuard.ThrowIfArgument(
 1421406                orientation != surfaceOrientation,
 1421407                nameof(triangles),
 1421408                "Open convex mesh triangles must fill their convex boundary without holes, overlap, or folds.");
 1420409            ChronicleGuard.ThrowIfArgument(
 1420410                !Fixed64.TryAdd(triangleArea, new FixedTriangle2d(first, second, third).Area, out triangleArea),
 1420411                nameof(triangles),
 1420412                "Open convex mesh projected area must be representable.");
 413        }
 414
 477415        Fixed64 boundaryArea = Fixed64.Zero;
 477416        Vector2d anchor = boundary[0].Position;
 3748417        for (int i = 1; i < boundary.Length - 1; i++)
 418        {
 1397419            Fixed64 area = new FixedTriangle2d(
 1397420                anchor,
 1397421                boundary[i].Position,
 1397422                boundary[i + 1].Position).Area;
 1397423            ChronicleGuard.ThrowIfArgument(
 1397424                !Fixed64.TryAdd(boundaryArea, area, out boundaryArea),
 1397425                nameof(triangles),
 1397426                "Open convex mesh projected boundary area must be representable.");
 427        }
 428
 477429        Fixed64 areaTolerance = Fixed64.Epsilon * (Fixed64)(triangleCount + boundary.Length);
 477430        ChronicleGuard.ThrowIfArgument(
 477431            FixedMath.Abs(triangleArea - boundaryArea) > areaTolerance,
 477432            nameof(triangles),
 477433            "Open convex mesh triangles must fill their convex boundary without holes, overlap, or folds.");
 477434    }
 435
 436    private static void AppendConvexHullVertex(
 437        BoundaryVertex[] hull,
 438        ref int hullCount,
 439        int minimumCount,
 440        BoundaryVertex candidate)
 441    {
 100341442        while (hullCount >= minimumCount
 100341443            && Vector2d.OrientationSign(
 100341444                hull[hullCount - 2].Position,
 100341445                hull[hullCount - 1].Position,
 100341446                candidate.Position) <= 0)
 447        {
 27800448            hullCount--;
 449        }
 450
 72541451        hull[hullCount++] = candidate;
 72541452    }
 453
 454    private static bool MatchesCyclicHull(
 455        BoundaryVertex[] authoredBoundary,
 456        int authoredCount,
 457        BoundaryVertex[] hull)
 458    {
 8774459        int authoredStart = 0;
 70858460        for (int i = 1; i < authoredCount; i++)
 461        {
 26655462            if (CompareBoundaryVertices(authoredBoundary[i], authoredBoundary[authoredStart]) < 0)
 421463                authoredStart = i;
 464        }
 465
 8774466        bool forward = true;
 8774467        bool reverse = true;
 88406468        for (int i = 0; i < authoredCount; i++)
 469        {
 35429470            forward &= authoredBoundary[(authoredStart + i) % authoredCount].VertexIndex
 35429471                == hull[i].VertexIndex;
 35429472            reverse &= authoredBoundary[(authoredStart - i + authoredCount) % authoredCount].VertexIndex
 35429473                == hull[i].VertexIndex;
 474        }
 475
 8774476        return forward || reverse;
 477    }
 478
 479    private static int CompareBoundaryVertices(BoundaryVertex first, BoundaryVertex second)
 480    {
 105968481        int comparison = first.Position.X.CompareTo(second.Position.X);
 105968482        if (comparison != 0)
 72113483            return comparison;
 484
 33855485        return first.Position.Y.CompareTo(second.Position.Y);
 486    }
 487
 488    private static bool HasSingleVertexLinks(
 489        int[] triangles,
 490        EdgeUse[] sortedEdgeUses)
 491    {
 492        // Edge validation has already proven that every edge has exactly two
 493        // oppositely wound uses. Link connectivity is the remaining local
 494        // manifold condition at each welded vertex.
 930495        var linkParents = new int[triangles.Length];
 930496        var cornerUses = new VertexCornerUse[triangles.Length];
 232152497        for (int i = 0; i < triangles.Length; i++)
 498        {
 115146499            linkParents[i] = i;
 115146500            cornerUses[i] = new VertexCornerUse(triangles[i], i);
 501        }
 502
 59433503        for (int start = 0; start < sortedEdgeUses.Length;)
 504        {
 57573505            int end = FindEdgeUseGroupEnd(sortedEdgeUses, start);
 57573506            EdgeUse first = sortedEdgeUses[start];
 57573507            EdgeUse second = sortedEdgeUses[start + 1];
 57573508            Union(
 57573509                linkParents,
 57573510                FindTriangleCornerIndex(triangles, first.TriangleIndex, first.StartVertexIndex),
 57573511                FindTriangleCornerIndex(triangles, second.TriangleIndex, first.StartVertexIndex));
 57573512            Union(
 57573513                linkParents,
 57573514                FindTriangleCornerIndex(triangles, first.TriangleIndex, first.EndVertexIndex),
 57573515                FindTriangleCornerIndex(triangles, second.TriangleIndex, first.EndVertexIndex));
 57573516            start = end;
 517        }
 518
 930519        Array.Sort(cornerUses, CompareVertexCornerUses);
 22905520        for (int start = 0; start < cornerUses.Length;)
 521        {
 21046522            int root = Find(linkParents, cornerUses[start].CornerIndex);
 21046523            int vertexIndex = cornerUses[start].VertexIndex;
 21046524            int end = start + 1;
 115111525            while (end < cornerUses.Length && cornerUses[end].VertexIndex == vertexIndex)
 526            {
 94066527                if (Find(linkParents, cornerUses[end].CornerIndex) != root)
 1528                    return false;
 94065529                end++;
 530            }
 531
 21045532            start = end;
 533        }
 534
 929535        return true;
 536    }
 537
 538    private static int FindTriangleCornerIndex(
 539        int[] triangles,
 540        int triangleIndex,
 541        int vertexIndex)
 542    {
 230292543        int cornerIndex = triangleIndex * 3;
 230292544        if (triangles[cornerIndex] == vertexIndex)
 76764545            return cornerIndex;
 153528546        if (triangles[cornerIndex + 1] == vertexIndex)
 76764547            return cornerIndex + 1;
 76764548        return cornerIndex + 2;
 549    }
 550
 551    private static int CompareVertexCornerUses(VertexCornerUse first, VertexCornerUse second)
 552    {
 1627246553        int comparison = first.VertexIndex.CompareTo(second.VertexIndex);
 1627246554        return comparison != 0
 1627246555            ? comparison
 1627246556            : first.CornerIndex.CompareTo(second.CornerIndex);
 557    }
 558
 559    private static int[] CreateSatEdgeVertexPairs(
 560        EdgeUse[] edgeUses,
 561        Vector3d[] vertices,
 562        int[] triangles)
 563    {
 1356564        int satEdgeCount = CountConvexSatEdges(edgeUses, vertices, triangles);
 1356565        var edgeVertexPairs = new int[satEdgeCount * 2];
 1356566        int pairIndex = 0;
 62665567        for (int start = 0; start < edgeUses.Length;)
 568        {
 59953569            int end = FindEdgeUseGroupEnd(edgeUses, start);
 59953570            if (ShouldIncludeConvexSatEdge(edgeUses, start, end, vertices, triangles))
 571            {
 13708572                edgeVertexPairs[pairIndex++] = edgeUses[start].StartVertexIndex;
 13708573                edgeVertexPairs[pairIndex++] = edgeUses[start].EndVertexIndex;
 574            }
 575
 59953576            start = end;
 577        }
 578
 1356579        return edgeVertexPairs;
 580    }
 581
 582    private static int CountConvexSatEdges(
 583        EdgeUse[] edgeUses,
 584        Vector3d[] vertices,
 585        int[] triangles)
 586    {
 1356587        int count = 0;
 62665588        for (int start = 0; start < edgeUses.Length;)
 589        {
 59953590            int end = FindEdgeUseGroupEnd(edgeUses, start);
 59953591            if (ShouldIncludeConvexSatEdge(edgeUses, start, end, vertices, triangles))
 13708592                count++;
 593
 59953594            start = end;
 595        }
 596
 1356597        return count;
 598    }
 599
 600    private static int FindEdgeUseGroupEnd(ReadOnlySpan<EdgeUse> edgeUses, int start)
 601    {
 407286602        long key = edgeUses[start].Key;
 407286603        int end = start + 1;
 1373235604        while (end < edgeUses.Length && edgeUses[end].Key == key)
 965949605            end++;
 606
 407286607        return end;
 608    }
 609
 610    private static bool ShouldIncludeConvexSatEdge(
 611        EdgeUse[] edgeUses,
 612        int start,
 613        int end,
 614        Vector3d[] vertices,
 615        int[] triangles)
 616    {
 119906617        if (end - start <= 1)
 4702618            return true;
 619
 115204620        int edgeStart = edgeUses[start].StartVertexIndex;
 115204621        int edgeEnd = edgeUses[start].EndVertexIndex;
 115204622        Vector3d first = vertices[edgeStart];
 115204623        Vector3d edge = vertices[edgeEnd] - first;
 115204624        Vector3d firstOpposite = vertices[FindOppositeVertexIndex(
 115204625            triangles,
 115204626            edgeUses[start].TriangleIndex,
 115204627            edgeStart,
 115204628            edgeEnd)];
 415388629        for (int i = start + 1; i < end; i++)
 630        {
 115204631            Vector3d nextOpposite = vertices[FindOppositeVertexIndex(
 115204632                triangles,
 115204633                edgeUses[i].TriangleIndex,
 115204634                edgeStart,
 115204635                edgeEnd)];
 115204636            if (Vector3d.ScalarTripleProductSign(
 115204637                edge,
 115204638                firstOpposite - first,
 115204639                nextOpposite - first) != 0)
 640            {
 22714641                return true;
 642            }
 643        }
 644
 92490645        return false;
 646    }
 647
 648    private static int FindOppositeVertexIndex(
 649        int[] triangles,
 650        int triangleIndex,
 651        int edgeStart,
 652        int edgeEnd)
 653    {
 480880654        int index = triangleIndex * 3;
 480880655        int first = triangles[index];
 480880656        if (first != edgeStart && first != edgeEnd)
 159616657            return first;
 658
 321264659        int second = triangles[index + 1];
 321264660        return second != edgeStart && second != edgeEnd
 321264661            ? second
 321264662            : triangles[index + 2];
 663    }
 664
 665    private readonly struct VertexUse
 666    {
 667        public VertexUse(Vector3d position, int vertexIndex)
 668        {
 40370669            Position = position;
 40370670            VertexIndex = vertexIndex;
 40370671        }
 672
 673        public Vector3d Position { get; }
 674
 675        public int VertexIndex { get; }
 676    }
 677
 678    private readonly struct BoundaryVertex
 679    {
 680        public BoundaryVertex(Vector2d position, int vertexIndex)
 681        {
 41164682            Position = position;
 41164683            VertexIndex = vertexIndex;
 41164684        }
 685
 686        public Vector2d Position { get; }
 687
 688        public int VertexIndex { get; }
 689    }
 690
 691    private readonly struct VertexCornerUse
 692    {
 693        public VertexCornerUse(int vertexIndex, int cornerIndex)
 694        {
 115146695            VertexIndex = vertexIndex;
 115146696            CornerIndex = cornerIndex;
 115146697        }
 698
 699        public int VertexIndex { get; }
 700
 701        public int CornerIndex { get; }
 702    }
 703}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/PhysicsMesh.CoplanarPatches.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.CoplanarPatches.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.Collections.Generic;
 10using FixedMathSharp;
 11using FixedMathSharp.Geometry;
 12using SwiftCollections;
 13
 14namespace Gravitas.Colliders;
 15
 16/// <content>Retains immutable authored seam ownership through positive affine mesh transforms.</content>
 17public partial class PhysicsMesh
 18{
 435219    private int[] _coplanarPatchBoundaryOffsets = Array.Empty<int>();
 435220    private int[] _coplanarPatchBoundaryVertexPairs = Array.Empty<int>();
 435221    private int[] _convexCoplanarPatchCornerOffsets = Array.Empty<int>();
 435222    private int[] _convexCoplanarPatchCornerVertexIndices = Array.Empty<int>();
 435223    private int[] _patchIds = Array.Empty<int>();
 24    // Construction scratch is separate from the immutable topology views.
 435225    private readonly SwiftList<EdgeUse> _patchEdgeUses = new();
 435226    private int[] _patchParents = Array.Empty<int>();
 435227    private bool[] _patchRejected = Array.Empty<bool>();
 435228    private int[] _patchCounts = Array.Empty<int>();
 435229    private readonly SwiftList<PatchBoundaryVertexUse> _patchBoundaryVertexUses = new();
 435230    private BoundaryVertex[] _patchWalkedBoundary = Array.Empty<BoundaryVertex>();
 231    private static readonly IComparer<EdgeUse> PatchEdgeUseComparer = Comparer<EdgeUse>.Create(CompareEdgeUses);
 232    private static readonly IComparer<PatchBoundaryVertexUse> PatchBoundaryVertexUseComparer =
 233        Comparer<PatchBoundaryVertexUse>.Create(ComparePatchBoundaryVertexUses);
 34
 35    // An oriented strict-corner ring, starting at its minimum welded index.
 36    // Empty means that convex fill is untrusted, not that the patch is empty.
 37    // The borrower obtains neighboring corner triplets by cyclic indexing.
 38    internal ReadOnlySpan<int> GetConvexCoplanarPatchCornerVertexIndices(int triangleIndex)
 39    {
 11348940        ChronicleGuard.ThrowIfArrayIndexInvalid(triangleIndex, _triangleCount, nameof(triangleIndex));
 11348941        int patch = _manifoldPatchIds[triangleIndex];
 11348942        return patch < 0 ? ReadOnlySpan<int>.Empty
 11348943            : _convexCoplanarPatchCornerVertexIndices.AsSpan(_convexCoplanarPatchCornerOffsets[patch],
 11348944                _convexCoplanarPatchCornerOffsets[patch + 1] - _convexCoplanarPatchCornerOffsets[patch]);
 45    }
 46
 47    internal bool HasSingleConvexCoplanarPatch
 48    {
 49        get
 50        {
 154551            if (GetConvexCoplanarPatchCornerVertexIndices(0).IsEmpty)
 5952                return false;
 148653            int owner = _manifoldPatchIds[0];
 1163254            for (int triangle = 1; triangle < _triangleCount; triangle++)
 435055                if (_manifoldPatchIds[triangle] != owner)
 2056                    return false;
 146657            return true;
 58        }
 59    }
 60
 61    private static void EnsureTopologyBuffer<T>(ref T[] buffer, int count)
 62    {
 14765263        if (buffer.Length < count)
 11293064            Array.Resize(ref buffer, count);
 14765265    }
 66
 67    private void ReleaseTopologyPreparation()
 68    {
 69        // Positive affine transforms preserve the copied topology; construction
 70        // scratch must not retain mesh-sized capacity for the runtime lifetime.
 433271        _patchIds = _patchParents = _patchCounts = Array.Empty<int>();
 433272        _patchRejected = Array.Empty<bool>();
 433273        _patchWalkedBoundary = Array.Empty<BoundaryVertex>();
 433274        _topologyRepresentativeIndices = _topologyWeldedTriangles = Array.Empty<int>();
 433275        _topologyBoundaryHull = _topologyStrictBoundary = Array.Empty<BoundaryVertex>();
 433276        _surfaceWriteOffsets = _surfaceKeyOffsets = _surfacePreviousByVertex = Array.Empty<int>();
 433277        _surfaceCycleVertices = _surfaceCycleOffsets = Array.Empty<int>();
 433278        _surfacePreparationVertices = Array.Empty<Vector3d>();
 433279        _surfaceBoundaryEdgeComparer = null;
 433280        _surfaceOrderComparer = null;
 866481        _patchEdgeUses.FastClear(); _patchEdgeUses.TrimExcessCapacity();
 866482        _patchBoundaryVertexUses.FastClear(); _patchBoundaryVertexUses.TrimExcessCapacity();
 866483        _topologyVertexUses.FastClear(); _topologyVertexUses.TrimExcessCapacity();
 866484        _topologySortedBoundary.FastClear(); _topologySortedBoundary.TrimExcessCapacity();
 866485        _surfaceNeighborPairs.FastClear(); _surfaceNeighborPairs.TrimExcessCapacity();
 866486        _surfaceBoundaryEdges.FastClear(); _surfaceBoundaryEdges.TrimExcessCapacity();
 866487        _surfaceOrder.FastClear(); _surfaceOrder.TrimExcessCapacity();
 433288    }
 89
 90    private void PrepareCoplanarPatches(Vector3d[] vertices)
 91    {
 92        // Positive affine transforms preserve source incidence and coplanarity;
 93        // classify once, independently of rounded inspection coordinates.
 434194        int[] triangles = CreateTopologyTriangles(vertices, _triangles);
 434195        PrepareWeldedSurfaceIncidence(triangles);
 434196        _surfaceNeighborPairs.FastClear();
 434197        _surfaceNeighborPairs.EnsureCapacity(triangles.Length / 2);
 434198        _patchEdgeUses.FastClear();
 434199        _patchEdgeUses.EnsureCapacity(triangles.Length);
 4341100        EnsureTopologyBuffer(ref _patchParents, _triangleCount);
 4341101        EnsureTopologyBuffer(ref _patchRejected, _triangleCount);
 4341102        EnsureTopologyBuffer(ref _patchCounts, _triangleCount);
 4341103        int[] parents = _patchParents;
 4341104        bool[] rejected = _patchRejected;
 4341105        Array.Clear(rejected, 0, _triangleCount);
 310460106        for (int i = 0; i < _triangleCount; i++)
 107        {
 150889108            parents[i] = i;
 150889109            int index = i * 3;
 150889110            _patchEdgeUses.Add(EdgeUse.Create(triangles[index], triangles[index + 1], i));
 150889111            _patchEdgeUses.Add(EdgeUse.Create(triangles[index + 1], triangles[index + 2], i));
 150889112            _patchEdgeUses.Add(EdgeUse.Create(triangles[index + 2], triangles[index], i));
 113        }
 4341114        _patchEdgeUses.SortInPlace(PatchEdgeUseComparer);
 4341115        Span<EdgeUse> edgeUses = _patchEdgeUses.AsSpan();
 93578116        for (int start = 0; start < edgeUses.Length;)
 117        {
 84896118            int end = FindEdgeUseGroupEnd(edgeUses, start);
 84896119            if (end - start > 2)
 120            {
 600428121                for (int i = start; i < end; i++)
 300189122                    rejected[edgeUses[i].TriangleIndex] = true;
 123            }
 84871124            else if (end - start == 2)
 125            {
 135214126                EdgeUse first = edgeUses[start], second = edgeUses[start + 1];
 67607127                int seam = ClassifyCoplanarSeam(vertices, triangles, first, second);
 67607128                if (seam > 0)
 129                {
 55410130                    Union(parents, first.TriangleIndex, second.TriangleIndex);
 55410131                    _surfaceNeighborPairs.Add((first.TriangleIndex, second.TriangleIndex));
 132                }
 12197133                else if (seam < 0)
 39134                    rejected[first.TriangleIndex] = rejected[second.TriangleIndex] = true;
 135            }
 84896136            start = end;
 137        }
 138
 4341139        int[] counts = _patchCounts;
 4341140        Array.Clear(counts, 0, _triangleCount);
 310460141        for (int i = 0; i < parents.Length; i++)
 142        {
 150889143            parents[i] = Find(parents, i);
 150889144            counts[parents[i]]++;
 150889145            if (rejected[i])
 100112146                rejected[parents[i]] = true;
 147        }
 148
 149        // Opposite geometric interiors establish a two-sided seam regardless
 150        // of authored winding. Orient its surviving boundary to the root face
 151        // so the existing directed-chain coverage proof remains valid.
 4341152        int boundaryCount = 0;
 93578153        for (int start = 0; start < edgeUses.Length;)
 154        {
 84896155            int end = FindEdgeUseGroupEnd(edgeUses, start);
 84896156            if (end - start != 2
 84896157                || parents[edgeUses[start].TriangleIndex] != parents[edgeUses[start + 1].TriangleIndex])
 158            {
 742666159                for (int i = start; i < end; i++)
 160                {
 341847161                    EdgeUse edge = edgeUses[i];
 341847162                    int patch = parents[edge.TriangleIndex];
 341847163                    if (counts[patch] > 1 && !rejected[patch])
 39170164                        edgeUses[boundaryCount++] = CreateOrientedPatchBoundaryEdge(vertices, triangles, edge, patch);
 165                }
 166            }
 84896167            start = end;
 168        }
 169
 4341170        RejectAmbiguousPatchBoundaryVertices(edgeUses, boundaryCount, rejected);
 4341171        EnsureTopologyBuffer(ref _patchIds, _triangleCount);
 4341172        EnsureTopologyBuffer(ref _coplanarPatchBoundaryOffsets, _triangleCount + 1);
 4341173        int[] ids = _patchIds;
 4341174        int[] offsets = _coplanarPatchBoundaryOffsets;
 4341175        Array.Clear(offsets, 0, _triangleCount + 1);
 310460176        for (int i = 0; i < ids.Length; i++)
 150889177            ids[i] = counts[parents[i]] > 1 && !rejected[parents[i]] ? parents[i] : -1;
 87022178        for (int i = 0; i < boundaryCount; i++)
 179        {
 39170180            int patch = edgeUses[i].TriangleIndex;
 39170181            if (!rejected[patch])
 39162182                offsets[patch + 1] += 2;
 183        }
 310460184        for (int i = 1; i < offsets.Length; i++)
 150889185            offsets[i] += offsets[i - 1];
 4341186        EnsureTopologyBuffer(ref _coplanarPatchBoundaryVertexPairs, offsets[_triangleCount]);
 4341187        int[] boundaries = _coplanarPatchBoundaryVertexPairs;
 4341188        Array.Copy(offsets, counts, counts.Length);
 87022189        for (int i = 0; i < boundaryCount; i++)
 190        {
 39170191            EdgeUse edge = edgeUses[i];
 39170192            if (rejected[edge.TriangleIndex])
 193                continue;
 39162194            int index = counts[edge.TriangleIndex];
 39162195            boundaries[index] = edge.Direction > 0 ? edge.StartVertexIndex : edge.EndVertexIndex;
 39162196            boundaries[index + 1] = edge.Direction > 0 ? edge.EndVertexIndex : edge.StartVertexIndex;
 39162197            counts[edge.TriangleIndex] += 2;
 198        }
 4341199        PrepareConvexCoplanarPatchCorners(vertices, triangles, ids, offsets, boundaries);
 4341200        PrepareSurfaceTopology(vertices, triangles, ids, offsets, boundaries);
 4341201    }
 202
 203    private void PrepareConvexCoplanarPatchCorners(Vector3d[] vertices, int[] triangles,
 204        int[] ids, int[] boundaryOffsets, int[] boundaries)
 205    {
 4341206        EnsureTopologyBuffer(ref _convexCoplanarPatchCornerOffsets, _triangleCount + 1);
 4341207        EnsureTopologyBuffer(ref _convexCoplanarPatchCornerVertexIndices, boundaryOffsets[_triangleCount] / 2);
 4341208        int[] offsets = _convexCoplanarPatchCornerOffsets;
 4341209        int[] corners = _convexCoplanarPatchCornerVertexIndices;
 210        // Welding has finished consuming the representative map. Reuse its
 211        // vertex-sized storage for each patch's outgoing successor links.
 4341212        int[] nextByVertex = _topologyRepresentativeIndices;
 4341213        int cornerCount = 0;
 310460214        for (int patch = 0; patch < _triangleCount; patch++)
 215        {
 150889216            offsets[patch] = cornerCount;
 150889217            if (ids[patch] != patch)
 218                continue;
 16924219            int begin = boundaryOffsets[patch], end = boundaryOffsets[patch + 1];
 8462220            int boundaryStart = int.MaxValue;
 95248221            for (int i = begin; i < end; i += 2)
 222            {
 39162223                int vertex = boundaries[i];
 39162224                nextByVertex[vertex] = boundaries[i + 1];
 39162225                boundaryStart = Math.Min(boundaryStart, vertex);
 226            }
 227
 228            // The existing degree-two check and opposite-wound cancellation
 229            // give one incoming/outgoing edge per boundary vertex. Populate
 230            // only this patch's successors: no per-patch whole-vertex clearing.
 8462231            int triangle = patch * 3;
 8462232            int axis = GetPatchProjectionAxis(vertices[triangles[triangle]],
 8462233                vertices[triangles[triangle + 1]], vertices[triangles[triangle + 2]]);
 25386234            int edgeCount = (end - begin) / 2, visited = 0, current = boundaryStart;
 8462235            EnsureTopologyBuffer(ref _patchWalkedBoundary, edgeCount);
 8462236            BoundaryVertex[] boundary = _patchWalkedBoundary;
 237            do
 238            {
 38798239                boundary[visited++] = new BoundaryVertex(ProjectToBoundaryPlane(vertices[current], axis), current);
 38798240                current = nextByVertex[current];
 241            }
 38798242            while (current != boundaryStart);
 8462243            if (visited != edgeCount
 8462244                || !TryGetStrictConvexBoundary(boundary, edgeCount, out BoundaryVertex[] strict, out int count))
 245                continue;
 246
 247            // The root-oriented coplanar triangle chain is consistent, and each
 248            // canceled seam has exactly two opposite-side interiors. A single
 249            // boundary matching its convex hull has winding multiplicity one
 250            // inside and zero outside. It therefore proves exact filled
 251            // coverage; rounded projected-area tolerances are not a certificate.
 8292252            int start = 0;
 66762253            for (int i = 1; i < count; i++)
 25089254                if (strict[i].VertexIndex < strict[start].VertexIndex)
 4255                    start = i;
 83346256            for (int i = 0; i < count; i++)
 33381257                corners[cornerCount++] = strict[(start + i) % count].VertexIndex;
 258        }
 4341259        offsets[^1] = cornerCount;
 4341260    }
 261
 262    private static int ClassifyCoplanarSeam(Vector3d[] vertices, int[] triangles, EdgeUse first, EdgeUse second)
 263    {
 135214264        Vector3d start = vertices[first.StartVertexIndex], end = vertices[first.EndVertexIndex];
 67607265        Vector3d firstOpposite = vertices[FindOppositeVertexIndex(triangles, first.TriangleIndex,
 67607266            first.StartVertexIndex, first.EndVertexIndex)];
 67607267        Vector3d secondOpposite = vertices[FindOppositeVertexIndex(triangles, second.TriangleIndex,
 67607268            first.StartVertexIndex, first.EndVertexIndex)];
 269        // Source points may span the scalar domain even when scale admits a small mesh.
 67607270        new FixedTriangle(start, end, firstOpposite).GetExactNormal(out Signed192 nx, out Signed192 ny, out Signed192 nz
 67607271        Signed320 planeSide = WideArithmetic.AddSigned320(WideArithmetic.AddSigned320(
 67607272            WideArithmetic.MultiplySigned192(nx, WideArithmetic.Difference(secondOpposite.X, start.X)),
 67607273            WideArithmetic.MultiplySigned192(ny, WideArithmetic.Difference(secondOpposite.Y, start.Y))),
 67607274            WideArithmetic.MultiplySigned192(nz, WideArithmetic.Difference(secondOpposite.Z, start.Z)));
 67607275        if (!planeSide.IsZero)
 12158276            return 0;
 277
 55449278        int droppedAxis = GetPatchProjectionAxis(start, end, firstOpposite);
 55449279        Vector2d projectedStart = ProjectToBoundaryPlane(start, droppedAxis);
 55449280        Vector2d projectedEnd = ProjectToBoundaryPlane(end, droppedAxis);
 55449281        int firstSide = Vector2d.OrientationSign(projectedStart, projectedEnd,
 55449282            ProjectToBoundaryPlane(firstOpposite, droppedAxis));
 55449283        int secondSide = Vector2d.OrientationSign(projectedStart, projectedEnd,
 55449284            ProjectToBoundaryPlane(secondOpposite, droppedAxis));
 55449285        return firstSide == -secondSide ? 1 : -1;
 286    }
 287
 288    private static EdgeUse CreateOrientedPatchBoundaryEdge(Vector3d[] vertices, int[] triangles, EdgeUse edge, int patch
 289    {
 78340290        int root = patch * 3, face = edge.TriangleIndex * 3;
 117510291        Vector3d a = vertices[triangles[root]], b = vertices[triangles[root + 1]], c = vertices[triangles[root + 2]];
 39170292        int axis = GetPatchProjectionAxis(a, b, c);
 39170293        int rootOrientation = Vector2d.OrientationSign(ProjectToBoundaryPlane(a, axis),
 39170294            ProjectToBoundaryPlane(b, axis), ProjectToBoundaryPlane(c, axis));
 39170295        int faceOrientation = Vector2d.OrientationSign(ProjectToBoundaryPlane(vertices[triangles[face]], axis),
 39170296            ProjectToBoundaryPlane(vertices[triangles[face + 1]], axis), ProjectToBoundaryPlane(vertices[triangles[face 
 39170297        int direction = edge.Direction * rootOrientation * faceOrientation;
 39170298        return EdgeUse.Create(direction > 0 ? edge.StartVertexIndex : edge.EndVertexIndex,
 39170299            direction > 0 ? edge.EndVertexIndex : edge.StartVertexIndex, patch);
 300    }
 301
 302    private static int GetPatchProjectionAxis(Vector3d first, Vector3d second, Vector3d third)
 303    {
 111706304        if (Vector2d.OrientationSign(new Vector2d(first.X, first.Y),
 111706305                new Vector2d(second.X, second.Y), new Vector2d(third.X, third.Y)) != 0)
 29472306            return 2;
 82234307        return Vector2d.OrientationSign(new Vector2d(first.X, first.Z),
 82234308            new Vector2d(second.X, second.Z), new Vector2d(third.X, third.Z)) != 0 ? 1 : 0;
 309    }
 310
 311    private void RejectAmbiguousPatchBoundaryVertices(ReadOnlySpan<EdgeUse> edges, int count, bool[] rejected)
 312    {
 4341313        int vertexCount = count * 2;
 4341314        _patchBoundaryVertexUses.FastClear();
 4341315        _patchBoundaryVertexUses.EnsureCapacity(vertexCount);
 87022316        for (int i = 0; i < count; i++)
 317        {
 39170318            EdgeUse edge = edges[i];
 39170319            _patchBoundaryVertexUses.Add(new PatchBoundaryVertexUse(edge.TriangleIndex, edge.StartVertexIndex));
 39170320            _patchBoundaryVertexUses.Add(new PatchBoundaryVertexUse(edge.TriangleIndex, edge.EndVertexIndex));
 321        }
 4341322        _patchBoundaryVertexUses.SortInPlace(PatchBoundaryVertexUseComparer);
 4341323        ReadOnlySpan<PatchBoundaryVertexUse> vertices = _patchBoundaryVertexUses.AsReadOnlySpan();
 47851324        for (int start = 0; start < vertexCount;)
 325        {
 39169326            PatchBoundaryVertexUse first = vertices[start];
 39169327            int end = start + 1;
 78340328            while (end < vertexCount && vertices[end].Patch == first.Patch && vertices[end].Vertex == first.Vertex)
 39171329                end++;
 330            // Canceling opposite-wound seams preserves balanced incoming and
 331            // outgoing uses. Degree two therefore establishes disjoint oriented
 332            // cycles, including holes. Pinched vertices decline the patch.
 39169333            if (end - start != 2)
 1334                rejected[first.Patch] = true;
 39169335            start = end;
 336        }
 4341337    }
 338
 339    private static int ComparePatchBoundaryVertexUses(PatchBoundaryVertexUse first, PatchBoundaryVertexUse second)
 340    {
 355392341        int comparison = first.Patch.CompareTo(second.Patch);
 355392342        return comparison != 0 ? comparison : first.Vertex.CompareTo(second.Vertex);
 343    }
 344
 345    private readonly struct PatchBoundaryVertexUse
 346    {
 347        internal readonly int Patch, Vertex;
 348        internal PatchBoundaryVertexUse(int patch, int vertex)
 349        {
 156680350            Patch = patch; Vertex = vertex;
 78340351        }
 352    }
 353}

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

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.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.Collections.Generic;
 10using FixedMathSharp;
 11using FixedMathSharp.Geometry;
 12using SwiftCollections;
 13using SwiftCollections.Query;
 14
 15namespace Gravitas.Colliders
 16{
 17    /// <summary>
 18    /// Owns immutable authored triangle topology and committed deterministic runtime mesh geometry.
 19    /// </summary>
 20    /// <content>Construction, geometry inspection, and shared state for mesh transformation, topology and queries.</con
 21    public partial class PhysicsMesh
 22    {
 23        private const int SupportTreeVertexThreshold = 32;
 24        private const int SupportTreeLeafVertexCount = 8;
 25        private const int SupportTreeStackCapacity = 64;
 26
 27        /// <summary>
 28        /// Maximum accepted vertex count for deterministic runtime mesh construction.
 29        /// </summary>
 30        public const int MaxVertexCount = 65535;
 31
 32        /// <summary>
 33        /// Maximum accepted triangle count for deterministic runtime mesh construction.
 34        /// </summary>
 35        public const int MaxTriangleCount = 131072;
 36
 37
 38        private readonly Vector3d[] _localVertices;
 39
 40        private Vector3d[] _scaledLocalVertices;
 41        private Vector3d[] _preparedScaledLocalVertices;
 42        private int[]? _supportVertexIndices;
 43        private SupportTreeNode[]? _supportTreeNodes;
 44        private SupportTreeNode[]? _preparedSupportTreeNodes;
 45        private int _supportTreeNodeCount;
 46
 47        /// <summary>
 48        /// Holds the source vertices in local mesh space.
 49        /// </summary>
 5505150        internal ReadOnlySpan<Vector3d> LocalVertices => _localVertices;
 51
 52        /// <summary>
 53        /// Holds the committed scaled vertices as center-relative local
 54        /// offsets. Collision relations apply <see cref="Rotation"/> without
 55        /// materializing absolute world points.
 56        /// </summary>
 47057        internal ReadOnlySpan<Vector3d> ScaledLocalVertices => _scaledLocalVertices;
 58
 59        /// <summary>
 60        /// Number of vertices in the immutable local mesh topology.
 61        /// </summary>
 19903962        public int VertexCount => _localVertices.Length;
 63
 64        private readonly int[] _triangles;
 65        /// <summary>
 66        /// Holds all the triangles that make up the mesh in the form of indices to the vertices array.
 67        /// example: Triangles[0-3] = 4,2,3 means that the first triangle of the mesh is made up of the vertices _vertic
 68        /// </summary>
 13471069        public ReadOnlySpan<int> Triangles => _triangles;
 70
 71        private readonly int _triangleCount;
 72        /// <summary>Gets the number of authored triangles.</summary>
 5623173        public int TriangleCount => _triangleCount;
 74
 75        private readonly int[] _convexSatEdgeVertexPairs;
 2353476        internal ReadOnlySpan<int> ConvexSatEdgeVertexPairs => _convexSatEdgeVertexPairs;
 77
 78        /// <summary>Gets the mesh collision mode.</summary>
 79        public MeshColliderMode Mode { get; }
 80
 81        /// <summary>
 82        /// Gets whether the complete exact-position-welded triangle topology is one
 83        /// connected, consistently wound, closed two-manifold surface.
 84        /// </summary>
 85        public bool IsClosedSurface { get; private set; }
 86
 87        /// <summary>
 88        /// Gets the current triangle surface area after local scale.
 89        /// </summary>
 285190        public Fixed64 TotalArea => _scaledTotalArea;
 91
 92        private int _triangleBvhBuildCount;
 93        private SwiftFixedBVH<int> _triangleBVH;
 94        private SwiftFixedBVH<int> _preparedTriangleBVH;
 95
 96        /// <summary>
 97        /// Triangle acceleration structure in local mesh space.
 98        /// </summary>
 18269599        internal SwiftFixedBVH<int> TriangleBVH => _triangleBVH;
 100
 101        /// <summary>Gets the number of committed triangle BVH builds.</summary>
 35102        public int TriangleBvhBuildCount => _triangleBvhBuildCount;
 103
 4352104        private FixedQuaternion _rotation = FixedQuaternion.Identity;
 105
 106        /// <summary>
 107        /// Gets the committed world-space origin of the mesh's rigid frame.
 108        /// </summary>
 237589109        internal Vector3d Origin => _geometryFrame.IsRigid ? _geometryFrame.RigidOrigin : _position;
 110
 111        /// <summary>
 112        /// Gets the committed local-to-world mesh orientation.
 113        /// </summary>
 300375114        internal FixedQuaternion Rotation => _rotation;
 115
 116        private FixedBoundBox _bounds;
 117        /// <summary>Gets the committed world-space axis-aligned bounds.</summary>
 100803118        public FixedBoundBox Bounds => _bounds;
 119
 120        private readonly FixedBoundBox _localBounds;
 121
 122        /// <summary>
 123        /// Axis-aligned bounds of the source vertices in local mesh space.
 124        /// </summary>
 31718125        public FixedBoundBox LocalBounds => _localBounds;
 126
 127        /// <summary>Creates a convex runtime mesh at a world-space pose.</summary>
 128        public PhysicsMesh(Vector3d[] vertices, int[] triangles, Vector3d position, FixedQuaternion rotation)
 117129            : this(vertices, triangles, position, rotation, MeshColliderMode.Convex) { }
 130
 131        /// <summary>Creates a runtime mesh with an explicit collision mode and world-space pose.</summary>
 132        public PhysicsMesh(
 133            Vector3d[] vertices,
 134            int[] triangles,
 135            Vector3d position,
 136            FixedQuaternion rotation,
 137            MeshColliderMode mode)
 362138            : this(vertices, triangles, mode, colliderOwned: false)
 139        {
 342140            PrepareTransformation(position, rotation, Vector3d.One, Vector3d.One, null);
 327141            PublishPreparedTransformation();
 327142        }
 143
 144        private readonly bool _colliderOwned;
 145
 146        // Collider authoring cannot commit geometry until its owner and part scales are known.
 4352147        internal PhysicsMesh(Vector3d[] vertices, int[] triangles, MeshColliderMode mode, bool colliderOwned)
 148        {
 4352149            _colliderOwned = colliderOwned;
 4352150            ChronicleGuard.ThrowIfArgument(
 4352151                mode != MeshColliderMode.Convex && mode != MeshColliderMode.Concave,
 4352152                nameof(mode),
 4352153                "Unsupported mesh collider mode.");
 154
 4352155            ValidateInput(vertices, triangles);
 156
 4341157            Mode = mode;
 4341158            _localVertices = new Vector3d[vertices.Length];
 4341159            Array.Copy(vertices, _localVertices, vertices.Length);
 4341160            _scaledLocalVertices = new Vector3d[vertices.Length];
 4341161            _preparedScaledLocalVertices = new Vector3d[vertices.Length];
 4341162            _triangles = new int[triangles.Length];
 4341163            Array.Copy(triangles, _triangles, triangles.Length);
 4341164            _triangleCount = triangles.Length / 3; // 3 vertices per triangle
 4341165            _triangleBVH = new SwiftFixedBVH<int>(2 * TriangleCount - 1);
 4341166            _preparedTriangleBVH = new SwiftFixedBVH<int>(2 * TriangleCount - 1);
 4341167            _scaledFaceAreas = new Fixed64[TriangleCount];
 4341168            _preparedScaledFaceAreas = new Fixed64[TriangleCount];
 4341169            _scaledFaceNormals = new Vector3d[TriangleCount];
 4341170            _preparedScaledFaceNormals = new Vector3d[TriangleCount];
 171
 4341172            _localBounds = CalculateBounds(_localVertices);
 173
 174            // Positive admitted scales preserve authored incidence and planar fill.
 4341175            PrepareCoplanarPatches(_localVertices);
 4341176            int[] topologyTriangles = _weldedTriangleVertices;
 4341177            _convexSatEdgeVertexPairs = Mode == MeshColliderMode.Convex
 4341178                ? CreateConvexSatEdgeVertexPairs(_localVertices, topologyTriangles, _triangleCount)
 4341179                : Array.Empty<int>();
 4332180            if (Mode == MeshColliderMode.Concave)
 181            {
 2976182                IsClosedSurface = EvaluateClosedVolumeTopology(topologyTriangles, out _surfaceClosureValidationResult);
 183            }
 184
 4332185            ReleaseTopologyPreparation();
 186
 4332187            if (Mode == MeshColliderMode.Convex && _localVertices.Length > SupportTreeVertexThreshold)
 188            {
 16189                _supportVertexIndices = CreateSupportVertexIndices(_localVertices.Length);
 16190                _supportTreeNodes = new SupportTreeNode[(2 * _localVertices.Length) - 1];
 16191                _preparedSupportTreeNodes = new SupportTreeNode[(2 * _localVertices.Length) - 1];
 192            }
 193
 4332194        }
 195
 196        /// <summary>Updates the mesh world-space position and rigid rotation.</summary>
 197        /// <exception cref="InvalidOperationException">The mesh is owned by a collider.</exception>
 198        public void UpdatePosition(Vector3d position, FixedQuaternion rotation)
 199        {
 33200            ChronicleGuard.ThrowIfTrue(_colliderOwned, nameof(PhysicsMesh),
 33201                "Collider-owned mesh transformations must be changed through the collider or its host transform.");
 32202            PrepareTransformation(position, rotation, _ownerScale, _partScale, null);
 32203            PublishPreparedTransformation();
 32204        }
 205
 206        /// <summary>
 207        /// Updates the mesh center, normalized rigid rotation, and strictly positive authored scale.
 208        /// </summary>
 209        /// <exception cref="InvalidOperationException">The mesh is owned by a collider.</exception>
 210        public void UpdateTransform(Vector3d position, FixedQuaternion rotation, Vector3d scale)
 211        {
 98212            ChronicleGuard.ThrowIfTrue(_colliderOwned, nameof(PhysicsMesh),
 98213                "Collider-owned mesh transformations must be changed through the collider or its host transform.");
 97214            PrepareTransformation(position, rotation, scale, Vector3d.One, null);
 83215            PublishPreparedTransformation();
 83216        }
 217
 218        private static void ValidateInput(Vector3d[] vertices, int[] triangles)
 219        {
 4352220            ChronicleGuard.ThrowIfNull(vertices, nameof(vertices));
 4351221            ChronicleGuard.ThrowIfNull(triangles, nameof(triangles));
 4350222            ChronicleGuard.ThrowIfArgument(vertices.Length < 3, nameof(vertices), "Mesh must contain at least three vert
 4350223            ChronicleGuard.ThrowIfArgument(triangles.Length == 0 || triangles.Length % 3 != 0, nameof(triangles), "Trian
 4348224            ChronicleGuard.ThrowIfArgumentOutOfRange(vertices.Length > MaxVertexCount, vertices.Length, nameof(vertices)
 225
 4347226            int triangleCount = triangles.Length / 3;
 4347227            ChronicleGuard.ThrowIfArgumentOutOfRange(triangleCount > MaxTriangleCount, triangleCount, nameof(triangles),
 228
 4347229            var referencedVertices = new bool[vertices.Length];
 310476230            for (int i = 0; i < triangleCount; i++)
 231            {
 150895232                int index0 = triangles[i * 3];
 150895233                int index1 = triangles[i * 3 + 1];
 150895234                int index2 = triangles[i * 3 + 2];
 235
 150895236                ChronicleGuard.ThrowIfArgumentOutOfRange((uint)index0 >= (uint)vertices.Length, vertices.Length, nameof(
 150895237                ChronicleGuard.ThrowIfArgumentOutOfRange((uint)index1 >= (uint)vertices.Length, vertices.Length, nameof(
 150895238                ChronicleGuard.ThrowIfArgumentOutOfRange((uint)index2 >= (uint)vertices.Length, vertices.Length, nameof(
 239
 150894240                ChronicleGuard.ThrowIfArgument(
 150894241                    index0 == index1 || index1 == index2 || index2 == index0,
 150894242                    nameof(triangles),
 150894243                    "Triangle indices must be unique within each triangle.");
 244
 150893245                Fixed64 area = new FixedTriangle(
 150893246                    vertices[index0],
 150893247                    vertices[index1],
 150893248                    vertices[index2]).Area;
 150893249                ChronicleGuard.ThrowIfArgument(area <= Fixed64.Epsilon, nameof(triangles), "Degenerate triangles are not
 250
 150891251                referencedVertices[index0] = true;
 150891252                referencedVertices[index1] = true;
 150891253                referencedVertices[index2] = true;
 254            }
 255
 89438256            for (int i = 0; i < referencedVertices.Length; i++)
 40378257                ChronicleGuard.ThrowIfArgument(!referencedVertices[i], nameof(vertices), "Every mesh vertex must be refe
 4341258        }
 259
 260        private void BuildTriangleBVH(
 261            SwiftFixedBVH<int> bvh,
 262            ReadOnlySpan<Vector3d> vertices)
 263        {
 4440264            bvh.Clear();
 302224265            for (int i = 0; i < _triangleCount; i++)
 266            {
 146672267                int index0 = _triangles[i * 3];
 146672268                int index1 = _triangles[i * 3 + 1];
 146672269                int index2 = _triangles[i * 3 + 2];
 146672270                Vector3d min = Vector3d.Min(Vector3d.Min(vertices[index0], vertices[index1]), vertices[index2]);
 146672271                Vector3d max = Vector3d.Max(Vector3d.Max(vertices[index0], vertices[index1]), vertices[index2]);
 146672272                bvh.Insert(i, new FixedBoundVolume(min, max));
 273            }
 4440274        }
 275
 276        private static FixedBoundBox CalculateBounds(Vector3d[] vertices)
 277        {
 8785278            Vector3d min = vertices[0];
 8785279            Vector3d max = vertices[0];
 159312280            for (int i = 1; i < vertices.Length; i++)
 281            {
 70871282                min = Vector3d.Min(min, vertices[i]);
 70871283                max = Vector3d.Max(max, vertices[i]);
 284            }
 285
 8785286            return FixedBoundBox.FromMinMax(min, max);
 287        }
 288
 289        /// <summary>Compares deterministic edge uses for topology validation.</summary>
 290        private static int CompareEdgeUses(EdgeUse first, EdgeUse second)
 291        {
 9259310292            if (first.Key != second.Key)
 3685715293                return first.Key < second.Key ? -1 : 1;
 294
 5573595295            if (first.TriangleIndex == second.TriangleIndex)
 1246296                return 0;
 297
 5572349298            return first.TriangleIndex < second.TriangleIndex ? -1 : 1;
 299        }
 300
 301        /// <summary>Gets the projected mesh area facing a world-space direction.</summary>
 302        public Fixed64 GetFrontalArea(Vector3d direction)
 303        {
 11304            Fixed64 directionMagnitude = direction.Magnitude;
 11305            if (directionMagnitude <= Fixed64.Epsilon)
 1306                return Fixed64.Zero;
 307
 10308            Vector3d normalizedDirection = direction / directionMagnitude;
 10309            Fixed64 totalArea = Fixed64.Zero;
 56310            for (int i = 0; i < _triangleCount; i++)
 311            {
 18312                Fixed64 projection = Vector3d.Dot(GetFaceNormalWorld(i), normalizedDirection);
 18313                if (projection > Fixed64.Zero)
 11314                    totalArea += _scaledFaceAreas[i] * FixedMath.Min(projection, Fixed64.One);
 315            }
 316
 10317            return totalArea;
 318        }
 319
 320        /// <summary>Gets one triangle's vertices in world space.</summary>
 321        public void GetTriangleVertices(int index, out Vector3d first, out Vector3d second, out Vector3d third)
 322        {
 5323            if (TryGetTriangleVertices(index, out first, out second, out third))
 4324                return;
 325
 1326            throw new InvalidOperationException(
 1327                "At least one triangle vertex lies outside the Fixed64 world-coordinate domain.");
 328        }
 329
 330        /// <summary>
 331        /// Attempts to materialize one triangle's absolute world vertices.
 332        /// Canonical collision and query paths should consume scaled-local
 333        /// geometry instead.
 334        /// </summary>
 335        public bool TryGetTriangleVertices(
 336            int index,
 337            out Vector3d first,
 338            out Vector3d second,
 339            out Vector3d third)
 340        {
 310341            GetGeometryTriangleVertices(
 310342                index,
 310343                out Vector3d localFirst,
 310344                out Vector3d localSecond,
 310345                out Vector3d localThird);
 310346            bool representable =
 310347                _geometryFrame.TryGetPoint(localFirst, out first)
 310348                & _geometryFrame.TryGetPoint(localSecond, out second)
 310349                & _geometryFrame.TryGetPoint(localThird, out third);
 310350            if (representable)
 304351                return true;
 352
 6353            first = default;
 6354            second = default;
 6355            third = default;
 6356            return false;
 357        }
 358
 359        /// <summary>
 360        /// Gets one triangle's committed scaled vertices in local mesh space.
 361        /// </summary>
 362        public void GetLocalTriangleVertices(int index, out Vector3d first, out Vector3d second, out Vector3d third)
 363        {
 71364            ChronicleGuard.ThrowIfArrayIndexInvalid(index, _triangleCount, nameof(index));
 365
 71366            int triangleIndex = index * 3;
 71367            first = _scaledLocalVertices[_triangles[triangleIndex]];
 71368            second = _scaledLocalVertices[_triangles[triangleIndex + 1]];
 71369            third = _scaledLocalVertices[_triangles[triangleIndex + 2]];
 71370        }
 371
 372        /// <summary>
 373        /// Gets one triangle's committed scaled normal in local mesh space.
 374        /// </summary>
 375        internal Vector3d GetScaledLocalFaceNormal(int index)
 376        {
 7357377            ChronicleGuard.ThrowIfArrayIndexInvalid(index, _triangleCount, nameof(index));
 7357378            return _scaledFaceNormals[index];
 379        }
 380
 381        /// <summary>
 382        /// Attempts to materialize one scaled vertex in world space.
 383        /// </summary>
 384        public bool TryGetVertexWorld(int index, out Vector3d vertex)
 385        {
 1940386            ChronicleGuard.ThrowIfArrayIndexInvalid(index, _localVertices.Length, nameof(index));
 1940387            return _sourceFrame.TryGetPoint(_localVertices[index], out vertex);
 388        }
 389
 390        /// <summary>
 391        /// Materializes one scaled vertex in world space.
 392        /// </summary>
 393        /// <exception cref="InvalidOperationException">
 394        /// The conceptual vertex lies outside the representable world-coordinate
 395        /// domain.
 396        /// </exception>
 397        public Vector3d GetVertexWorld(int index)
 398        {
 1918399            if (TryGetVertexWorld(index, out Vector3d vertex))
 1917400                return vertex;
 401
 1402            throw new InvalidOperationException(
 1403                "The selected vertex lies outside the Fixed64 world-coordinate domain.");
 404        }
 405
 406        /// <summary>
 407        /// Attempts to materialize the world-space vertex with the greatest
 408        /// projection onto <paramref name="direction"/>, preserving source
 409        /// vertex order for ties.
 410        /// </summary>
 411        public bool TryGetSupportVertexWorld(
 412            Vector3d direction,
 413            out Vector3d vertex)
 414        {
 56415            Vector3d localPoint = GetSupportVertexLocal(direction);
 56416            return _geometryFrame.TryGetPoint(localPoint, out vertex);
 417        }
 418
 419        /// <summary>
 420        /// Materializes the world-space vertex with the greatest projection
 421        /// onto <paramref name="direction"/>, preserving source vertex order
 422        /// for ties.
 423        /// </summary>
 424        /// <exception cref="InvalidOperationException">
 425        /// The conceptual support vertex lies outside the representable
 426        /// world-coordinate domain.
 427        /// </exception>
 428        public Vector3d GetSupportVertexWorld(Vector3d direction)
 429        {
 55430            if (TryGetSupportVertexWorld(direction, out Vector3d vertex))
 54431                return vertex;
 432
 1433            throw new InvalidOperationException(
 1434                "The selected support vertex lies outside the Fixed64 world-coordinate domain.");
 435        }
 436
 437        internal Vector3d GetSupportVertexLocal(Vector3d direction)
 438        {
 439            SupportDirection localDirection;
 8776440            if (!_geometryFrame.IsRigid)
 441            {
 296442                WideAxis3 covector = _geometryFrame.GetSourceDirectionNumerators(direction);
 298443                if (covector.IsZero) covector = new WideAxis3(Signed320.ExtendValue(Signed192.Signed(1)), default, defau
 296444                localDirection = new SupportDirection(covector);
 445            }
 446            else
 447            {
 8480448                Vector3d compact = ConvertWorldDirectionToLocal(direction);
 8480449                localDirection = new SupportDirection(compact != Vector3d.Zero ? compact.Normalized : Vector3d.Right);
 450            }
 8776451            if (_supportTreeNodes != null && _supportVertexIndices != null)
 41452                return GeometryVertices[FindSupportVertexIndex(localDirection)];
 453
 8735454            int bestIndex = 0;
 128932455            for (int index = 1; index < VertexCount; index++)
 62562456                if (localDirection.Compare(GeometryVertices[index], GeometryVertices[bestIndex]) > 0) bestIndex = index;
 8735457            return GeometryVertices[bestIndex];
 458        }
 459
 460        // Exact affine support changes the covector, not the source-space index.
 461        // Compact calls retain their existing projection and tie behavior.
 462        private readonly struct SupportDirection
 463        {
 464            private readonly Vector3d _compact;
 465            private readonly WideAxis3 _exact;
 466            private readonly bool _wide;
 33920467            internal SupportDirection(Vector3d compact) { _compact = compact; _exact = default; _wide = false; }
 1184468            internal SupportDirection(WideAxis3 exact) { _compact = default; _exact = exact; _wide = true; }
 56955469            internal int Compare(Vector3d first, Vector3d second) => _wide
 56955470                ? WideArithmetic.SubtractSigned576(Project(first), Project(second)).Sign
 56955471                : Vector3d.CompareProjection(first, second, _compact);
 1070472            internal Vector3d BoundsPoint(Vector3d min, Vector3d max) => _wide
 1070473                ? new Vector3d(_exact.X.Sign >= 0 ? max.X : min.X, _exact.Y.Sign >= 0 ? max.Y : min.Y, _exact.Z.Sign >= 
 1070474                : GetBoundsSupportPoint(min, max, _compact);
 4482475            private Signed576 Project(Vector3d point) => WideArithmetic.AddSigned576(WideArithmetic.AddSigned576(
 4482476                WideArithmetic.MultiplySigned320(_exact.X, Signed192.Raw(point.X)),
 4482477                WideArithmetic.MultiplySigned320(_exact.Y, Signed192.Raw(point.Y))),
 4482478                WideArithmetic.MultiplySigned320(_exact.Z, Signed192.Raw(point.Z)));
 479        }
 480
 481        private int FindSupportVertexIndex(in SupportDirection localDirection)
 482        {
 41483            int bestIndex = 0;
 41484            Span<int> stack = stackalloc int[SupportTreeStackCapacity];
 41485            int stackCount = 0;
 41486            stack[stackCount++] = 0;
 487
 387488            while (stackCount > 0)
 489            {
 346490                int nodeIndex = stack[--stackCount];
 346491                SupportTreeNode node = _supportTreeNodes![nodeIndex];
 346492                Vector3d upperPoint = localDirection.BoundsPoint(node.Min, node.Max);
 346493                int upperComparison = localDirection.Compare(upperPoint, GeometryVertices[bestIndex]);
 346494                if (upperComparison < 0 || (upperComparison == 0 && node.MinVertexIndex >= bestIndex))
 495                    continue;
 496
 241497                if (node.IsLeaf)
 498                {
 60499                    SearchSupportLeaf(node, localDirection, ref bestIndex);
 60500                    continue;
 501                }
 502
 181503                SupportTreeNode left = _supportTreeNodes[node.Left];
 181504                SupportTreeNode right = _supportTreeNodes[node.Right];
 505
 181506                if (ComesBeforeSupportNode(left, right, localDirection))
 507                {
 70508                    PushSupportNode(right, bestIndex, localDirection, stack, ref stackCount);
 70509                    PushSupportNode(left, bestIndex, localDirection, stack, ref stackCount);
 70510                    continue;
 511                }
 512
 111513                PushSupportNode(left, bestIndex, localDirection, stack, ref stackCount);
 111514                PushSupportNode(right, bestIndex, localDirection, stack, ref stackCount);
 515            }
 516
 41517            return bestIndex;
 518        }
 519
 520        private void SearchSupportLeaf(
 521            SupportTreeNode node,
 522            in SupportDirection localDirection,
 523            ref int bestIndex)
 524        {
 790525            for (int i = 0; i < node.Count; i++)
 526            {
 335527                int vertexIndex = _supportVertexIndices![node.Start + i];
 335528                Vector3d vertex = GeometryVertices[vertexIndex];
 335529                int projectionComparison = localDirection.Compare(vertex, GeometryVertices[bestIndex]);
 335530                if (projectionComparison < 0 || (projectionComparison == 0 && vertexIndex >= bestIndex))
 531                    continue;
 532
 89533                bestIndex = vertexIndex;
 534            }
 60535        }
 536
 537        private void PushSupportNode(
 538            SupportTreeNode node,
 539            int bestIndex,
 540            in SupportDirection localDirection,
 541            Span<int> stack,
 542            ref int stackCount)
 543        {
 362544            Vector3d upperPoint = localDirection.BoundsPoint(node.Min, node.Max);
 362545            int upperComparison = localDirection.Compare(upperPoint, GeometryVertices[bestIndex]);
 362546            if (upperComparison < 0 || (upperComparison == 0 && node.MinVertexIndex >= bestIndex))
 57547                return;
 548
 305549            stack[stackCount++] = node.Index;
 305550        }
 551
 552        private static bool ComesBeforeSupportNode(
 553            SupportTreeNode left,
 554            SupportTreeNode right,
 555            in SupportDirection localDirection)
 556        {
 181557            Vector3d leftPoint = localDirection.BoundsPoint(left.Min, left.Max);
 181558            Vector3d rightPoint = localDirection.BoundsPoint(right.Min, right.Max);
 181559            int projectionComparison = localDirection.Compare(leftPoint, rightPoint);
 181560            if (projectionComparison != 0)
 117561                return projectionComparison > 0;
 562
 64563            return left.MinVertexIndex < right.MinVertexIndex;
 564        }
 565
 566        private int BuildSupportTreeNode(
 567            Vector3d[] vertices,
 568            int[] vertexIndices,
 569            SupportTreeNode[] nodes,
 570            SupportVertexIndexComparer comparer,
 571            ref int nodeCount,
 572            int start,
 573            int count)
 574        {
 2757575            int nodeIndex = nodeCount++;
 576
 2757577            CalculateSupportRangeBounds(
 2757578                vertices,
 2757579                vertexIndices,
 2757580                start,
 2757581                count,
 2757582                out Vector3d min,
 2757583                out Vector3d max,
 2757584                out int minVertexIndex);
 2757585            if (count <= SupportTreeLeafVertexCount)
 586            {
 1386587                nodes[nodeIndex] = SupportTreeNode.CreateLeaf(
 1386588                    nodeIndex,
 1386589                    min,
 1386590                    max,
 1386591                    start,
 1386592                    count,
 1386593                    minVertexIndex);
 1386594                return nodeIndex;
 595            }
 596
 1371597            int axis = GetDominantAxis(max - min);
 1371598            comparer.Reset(vertices, axis);
 1371599            Array.Sort(
 1371600                vertexIndices,
 1371601                start,
 1371602                count,
 1371603                comparer);
 604
 1371605            int leftCount = count / 2;
 1371606            int rightCount = count - leftCount;
 1371607            int leftIndex = BuildSupportTreeNode(
 1371608                vertices,
 1371609                vertexIndices,
 1371610                nodes,
 1371611                comparer,
 1371612                ref nodeCount,
 1371613                start,
 1371614                leftCount);
 1371615            int rightIndex = BuildSupportTreeNode(
 1371616                vertices,
 1371617                vertexIndices,
 1371618                nodes,
 1371619                comparer,
 1371620                ref nodeCount,
 1371621                start + leftCount,
 1371622                rightCount);
 1371623            nodes[nodeIndex] = SupportTreeNode.CreateBranch(
 1371624                nodeIndex,
 1371625                min,
 1371626                max,
 1371627                leftIndex,
 1371628                rightIndex,
 1371629                minVertexIndex);
 1371630            return nodeIndex;
 631        }
 632
 633        private void RefitSupportTree(
 634            Vector3d[] vertices,
 635            SupportTreeNode[] sourceNodes,
 636            SupportTreeNode[] targetNodes)
 637        {
 638            // Children follow their parent in the immutable preorder topology,
 639            // so reverse traversal makes both child bounds available first.
 2112640            for (int i = _supportTreeNodeCount - 1; i >= 0; i--)
 641            {
 1046642                SupportTreeNode source = sourceNodes[i];
 1046643                if (source.IsLeaf)
 644                {
 528645                    CalculateSupportRangeBounds(
 528646                        vertices,
 528647                        _supportVertexIndices!,
 528648                        source.Start,
 528649                        source.Count,
 528650                        out Vector3d min,
 528651                        out Vector3d max,
 528652                        out int minVertexIndex);
 528653                    targetNodes[i] = SupportTreeNode.CreateLeaf(
 528654                        source.Index,
 528655                        min,
 528656                        max,
 528657                        source.Start,
 528658                        source.Count,
 528659                        minVertexIndex);
 528660                    continue;
 661                }
 662
 518663                SupportTreeNode left = targetNodes[source.Left];
 518664                SupportTreeNode right = targetNodes[source.Right];
 518665                targetNodes[i] = SupportTreeNode.CreateBranch(
 518666                    source.Index,
 518667                    Vector3d.Min(left.Min, right.Min),
 518668                    Vector3d.Max(left.Max, right.Max),
 518669                    source.Left,
 518670                    source.Right,
 518671                    source.MinVertexIndex);
 672            }
 10673        }
 674
 675        private static void CalculateSupportRangeBounds(
 676            Vector3d[] vertices,
 677            int[] vertexIndices,
 678            int start,
 679            int count,
 680            out Vector3d min,
 681            out Vector3d max,
 682            out int minVertexIndex)
 683        {
 3285684            int firstIndex = vertexIndices[start];
 3285685            minVertexIndex = firstIndex;
 3285686            min = vertices[firstIndex];
 3285687            max = min;
 169212688            for (int i = 1; i < count; i++)
 689            {
 81321690                int vertexIndex = vertexIndices[start + i];
 81321691                Vector3d vertex = vertices[vertexIndex];
 81321692                min = Vector3d.Min(min, vertex);
 81321693                max = Vector3d.Max(max, vertex);
 81321694                if (vertexIndex < minVertexIndex)
 1566695                    minVertexIndex = vertexIndex;
 696            }
 3285697        }
 698
 699        private static int[] CreateSupportVertexIndices(int vertexCount)
 700        {
 16701            var indices = new int[vertexCount];
 28948702            for (int i = 0; i < indices.Length; i++)
 14458703                indices[i] = i;
 704
 16705            return indices;
 706        }
 707
 708        private static int GetDominantAxis(Vector3d extents)
 709        {
 1371710            if (extents.X >= extents.Y && extents.X >= extents.Z)
 431711                return 0;
 712
 940713            return extents.Y >= extents.Z ? 1 : 2;
 714        }
 715
 716        private static Vector3d GetBoundsSupportPoint(Vector3d min, Vector3d max, Vector3d direction) =>
 721717            new(
 721718                direction.X >= Fixed64.Zero ? max.X : min.X,
 721719                direction.Y >= Fixed64.Zero ? max.Y : min.Y,
 721720                direction.Z >= Fixed64.Zero ? max.Z : min.Z);
 721
 722        /// <summary>Gets a triangle face normal in world space.</summary>
 723        public Vector3d GetFaceNormalWorld(int index)
 724        {
 5441725            ChronicleGuard.ThrowIfArrayIndexInvalid(index, _triangleCount, nameof(index));
 5441726            if (!_scaleIsExact)
 727            {
 213728                GetGeometryTriangleVertices(index, out Vector3d a, out Vector3d b, out Vector3d c);
 213729                return WideTriangleRelations.GetScaledTriangleLocalNormal(new FixedTriangle(a, b, c), _sourceFrame)
 213730                    .Transform(_sourceFrame.GeometryBasis).GetNormal(false);
 731            }
 5228732            _ = _rotation.TryRotate(_scaledFaceNormals[index], out Vector3d worldNormal);
 5228733            return worldNormal.Normalized;
 734        }
 735
 736        /// <summary>Writes triangle indices overlapping world-space bounds into a caller-owned buffer.</summary>
 737        public void GetTrianglesInWorldBounds(FixedBoundVolume worldBounds, SwiftList<int> result)
 738        {
 169474739            result.FastClear();
 169474740            if (!_geometryFrame.IsRigid)
 741            {
 742                // Collider admission requires positive scale; inverse bounds
 743                // clip to the source domain and cannot be singular here.
 1790744                bool inverted = _sourceFrame.TryGetSourceBounds(worldBounds.Min, worldBounds.Max, out FixedBoundBox sour
 745                System.Diagnostics.Debug.Assert(inverted);
 1790746                TriangleBVH.Query(new FixedBoundVolume(sourceBounds.Min, sourceBounds.Max), result);
 1790747                return;
 748            }
 167684749            FixedBoundBox localBounds =
 167684750                FixedBoundBox.FromRelativeRotatedBoundsClippedToDomain(
 167684751                    Vector3d.Zero,
 167684752                    FixedQuaternion.Identity,
 167684753                    worldBounds.Min,
 167684754                    worldBounds.Max,
 167684755                    _geometryFrame.RigidOrigin,
 167684756                    _rotation);
 167684757            TriangleBVH.Query(
 167684758                new FixedBoundVolume(localBounds.Min, localBounds.Max),
 167684759                result);
 167684760        }
 761
 762        /// <summary>Writes triangle indices overlapping scaled-local bounds into a caller-owned buffer.</summary>
 763        public void GetTrianglesInLocalBounds(FixedBoundVolume localBounds, SwiftList<int> result)
 764        {
 9765            result.FastClear();
 9766            if (_geometryUsesSource)
 767            {
 3768                bool inverted = _sourceFrame.TryGetSourceBoundsFromScaledLocal(localBounds.Min, localBounds.Max, out Fix
 769                System.Diagnostics.Debug.Assert(inverted);
 3770                TriangleBVH.Query(new FixedBoundVolume(source.Min, source.Max), result);
 771            }
 6772            else TriangleBVH.Query(localBounds, result);
 6773        }
 774
 775        /// <summary>
 776        /// Attempts to express a world point in the committed scaled-local
 777        /// mesh frame without saturating the relative displacement.
 778        /// </summary>
 779        public bool TryConvertWorldToScaledLocal(
 780            Vector3d worldPoint,
 781            out Vector3d localPoint) =>
 3782            _sourceFrame.TryGetScaledLocalPointIn(worldPoint, out localPoint);
 783
 784        /// <summary>
 785        /// Expresses a world point in the committed scaled-local mesh frame.
 786        /// </summary>
 787        /// <exception cref="InvalidOperationException">
 788        /// The exact relative displacement lies outside the representable
 789        /// coordinate domain.
 790        /// </exception>
 791        public Vector3d ConvertWorldToScaledLocal(Vector3d worldPoint)
 792        {
 2793            if (TryConvertWorldToScaledLocal(worldPoint, out Vector3d localPoint))
 1794                return localPoint;
 795
 1796            throw new InvalidOperationException(
 1797                "The world point cannot be represented in the mesh's scaled-local frame.");
 798        }
 799
 800        /// <summary>
 801        /// Attempts to materialize a scaled-local mesh point in world space.
 802        /// </summary>
 803        public bool TryConvertScaledLocalToWorld(
 804            Vector3d scaledLocalPoint,
 805            out Vector3d worldPoint) =>
 4806            _sourceFrame.GetScaledLocalPoint(scaledLocalPoint).TryGetPoint(out worldPoint);
 807
 808        /// <summary>
 809        /// Materializes a scaled-local mesh point in world space.
 810        /// </summary>
 811        /// <exception cref="InvalidOperationException">
 812        /// The conceptual world point lies outside the representable
 813        /// coordinate domain.
 814        /// </exception>
 815        public Vector3d ConvertScaledLocalToWorld(Vector3d scaledLocalPoint)
 816        {
 3817            if (TryConvertScaledLocalToWorld(
 3818                    scaledLocalPoint,
 3819                    out Vector3d worldPoint))
 820            {
 2821                return worldPoint;
 822            }
 823
 1824            throw new InvalidOperationException(
 1825                "The scaled-local point lies outside the Fixed64 world-coordinate domain.");
 826        }
 827
 828        internal FixedPointAnchor CreatePointAnchor(
 829            Vector3d geometryPoint)
 830        {
 35157831            if (_geometryFrame.IsRigid)
 34594832                return FixedPointAnchor.FromValidatedFrame(_geometryFrame.RigidOrigin, _rotation, geometryPoint);
 833
 834            // Production callers supply an admitted vertex or finite convex
 835            // witness: its offset from the mesh center is bounded by reach.
 563836            bool represented = _geometryFrame.GetPoint(geometryPoint).TryGetLocalPointIn(_position,
 563837                FixedQuaternion.Identity, out Vector3d offset);
 838            System.Diagnostics.Debug.Assert(represented);
 563839            return FixedPointAnchor.FromValidatedFrame(_position, FixedQuaternion.Identity, offset);
 840        }
 841
 842        /// <summary>
 843        /// Attempts to express a world-space direction in the committed
 844        /// scaled-local mesh frame.
 845        /// </summary>
 846        public bool TryConvertWorldDirectionToLocal(
 847            Vector3d worldDirection,
 848            out Vector3d localDirection) =>
 8482849            _rotation.Inverse().TryRotate(
 8482850                worldDirection,
 8482851                out localDirection);
 852
 853        /// <summary>
 854        /// Expresses a world-space direction in the committed scaled-local
 855        /// mesh frame.
 856        /// </summary>
 857        public Vector3d ConvertWorldDirectionToLocal(
 858            Vector3d worldDirection)
 859        {
 8481860            if (TryConvertWorldDirectionToLocal(
 8481861                    worldDirection,
 8481862                    out Vector3d localDirection))
 863            {
 8480864                return localDirection;
 865            }
 866
 1867            throw new InvalidOperationException(
 1868                "The world direction cannot be represented in the mesh's scaled-local frame.");
 869        }
 870
 871        private readonly struct EdgeUse
 872        {
 873            private EdgeUse(long key, int direction, int triangleIndex)
 874            {
 944504875                Key = key;
 944504876                Direction = direction;
 944504877                TriangleIndex = triangleIndex;
 944504878            }
 879
 880            public long Key { get; }
 881
 624395882            public int StartVertexIndex => (int)(Key >> 32);
 883
 884            // Mask explicitly: ARM64 Tier0 can retain upper key bits in a narrowed getter return.
 624395885            public int EndVertexIndex => (int)(Key & uint.MaxValue);
 886
 887            public int Direction { get; }
 888
 889            public int TriangleIndex { get; }
 890
 891            public static EdgeUse Create(int start, int end, int triangleIndex)
 892            {
 944504893                int min = start < end ? start : end;
 944504894                int max = start < end ? end : start;
 944504895                long key = ((long)min << 32) | (uint)max;
 944504896                int direction = start == min ? 1 : -1;
 944504897                return new EdgeUse(key, direction, triangleIndex);
 898            }
 899        }
 900
 901        private readonly struct TriangleUse
 902        {
 903            private TriangleUse(int a, int b, int c)
 904            {
 150889905                A = a;
 150889906                B = b;
 150889907                C = c;
 150889908            }
 909
 910            public int A { get; }
 911
 912            public int B { get; }
 913
 914            public int C { get; }
 915
 916            public static TriangleUse Create(int first, int second, int third)
 917            {
 150889918                int a = first;
 150889919                int b = second;
 150889920                int c = third;
 921
 150889922                if (a > b)
 10137923                    (a, b) = (b, a);
 150889924                if (b > c)
 23276925                    (b, c) = (c, b);
 150889926                if (a > b)
 7576927                    (a, b) = (b, a);
 928
 150889929                return new TriangleUse(a, b, c);
 930            }
 931        }
 932
 933        private readonly struct SupportTreeNode
 934        {
 935            private SupportTreeNode(
 936                int index,
 937                Vector3d min,
 938                Vector3d max,
 939                int left,
 940                int right,
 941                int start,
 942                int count,
 943                int minVertexIndex)
 944            {
 3803945                Index = index;
 3803946                Min = min;
 3803947                Max = max;
 3803948                Left = left;
 3803949                Right = right;
 3803950                Start = start;
 3803951                Count = count;
 3803952                MinVertexIndex = minVertexIndex;
 3803953            }
 954
 955            public int Index { get; }
 956
 957            public Vector3d Min { get; }
 958
 959            public Vector3d Max { get; }
 960
 961            public int Left { get; }
 962
 963            public int Right { get; }
 964
 965            public int Start { get; }
 966
 967            public int Count { get; }
 968
 969            public int MinVertexIndex { get; }
 970
 1287971            public bool IsLeaf => Count > 0;
 972
 973            public static SupportTreeNode CreateLeaf(
 974                int index,
 975                Vector3d min,
 976                Vector3d max,
 977                int start,
 978                int count,
 979                int minVertexIndex) =>
 1914980                new(index, min, max, -1, -1, start, count, minVertexIndex);
 981
 982            public static SupportTreeNode CreateBranch(
 983                int index,
 984                Vector3d min,
 985                Vector3d max,
 986                int left,
 987                int right,
 988                int minVertexIndex) =>
 1889989                new(index, min, max, left, right, 0, 0, minVertexIndex);
 990        }
 991
 992        private sealed class SupportVertexIndexComparer : IComparer<int>
 993        {
 15994            private Vector3d[] _vertices = Array.Empty<Vector3d>();
 995            private int _axis;
 996
 997            public void Reset(Vector3d[] vertices, int axis)
 998            {
 1371999                _vertices = vertices;
 13711000                _axis = axis;
 13711001            }
 1002
 1003            public int Compare(int first, int second)
 1004            {
 5690831005                Fixed64 firstValue = GetAxisValue(_vertices[first], _axis);
 5690831006                Fixed64 secondValue = GetAxisValue(_vertices[second], _axis);
 5690831007                int valueComparison = firstValue.CompareTo(secondValue);
 5690831008                if (valueComparison != 0)
 2864641009                    return valueComparison;
 1010
 2826191011                return first.CompareTo(second);
 1012            }
 1013
 1014            private static Fixed64 GetAxisValue(Vector3d vertex, int axis)
 1015            {
 11381661016                return axis switch
 11381661017                {
 4314561018                    0 => vertex.X,
 3886981019                    1 => vertex.Y,
 3180121020                    _ => vertex.Z
 11381661021                };
 1022            }
 1023        }
 1024    }
 1025}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/PhysicsMesh.GeometryFrame.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.GeometryFrame.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 FixedMathSharp;
 10using FixedMathSharp.Geometry;
 11using SwiftCollections;
 12using SwiftCollections.Query;
 13
 14namespace Gravitas.Colliders;
 15
 16/// <content>Retains authored geometry independently of rounded collider center and inspection vertices.</content>
 17public partial class PhysicsMesh
 18{
 19    private ScaledRigidFrame3d _sourceFrame, _preparedSourceFrame;
 20    private ScaledRigidFrame3d _geometryFrame, _preparedGeometryFrame;
 21    private bool _geometryUsesSource, _preparedGeometryUsesSource;
 22    private bool _scaleIsExact, _preparedScaleIsExact;
 23
 38414724    internal ref readonly ScaledRigidFrame3d GeometryFrame => ref _geometryFrame;
 25
 26    internal ReadOnlySpan<Vector3d> GeometryVertices =>
 113147827        _geometryUsesSource ? _localVertices : _scaledLocalVertices;
 28
 29    internal FixedBoundBox GeometryLocalBounds =>
 585430        _geometryUsesSource ? _localBounds : _scaledLocalBounds;
 31
 32    internal void GetGeometryTriangleVertices(int index,
 33        out Vector3d first, out Vector3d second, out Vector3d third)
 34    {
 54239235        ChronicleGuard.ThrowIfArrayIndexInvalid(index, _triangleCount, nameof(index));
 54239236        ReadOnlySpan<Vector3d> vertices = GeometryVertices;
 54239237        int offset = index * 3;
 54239238        first = vertices[_triangles[offset]];
 54239239        second = vertices[_triangles[offset + 1]];
 54239240        third = vertices[_triangles[offset + 2]];
 54239241    }
 42
 43    internal bool TryConvertWorldToRigidGeometry(Vector3d worldPoint, out Vector3d point) =>
 720744        new FixedPointAnchor(worldPoint, FixedQuaternion.Identity, Vector3d.Zero)
 720745            .TryGetLocalPointIn(_geometryFrame.RigidOrigin, _geometryFrame.Rotation, out point);
 46
 47    internal void GetTrianglesInGeometryBounds(FixedBoundVolume bounds, SwiftList<int> result)
 48    {
 1320949        result.FastClear();
 1320950        TriangleBVH.Query(bounds, result);
 1320951    }
 52
 53    private void SelectPreparedGeometryFrame(Vector3d center, FixedQuaternion rotation)
 54    {
 55        // With zero placement, the supplied scalar center is the exact pose
 56        // origin. Exact centered scale products then retain the compact map.
 2057057        _preparedGeometryUsesSource = _preparedSourceFrame.HasLocalPlacement || !_preparedScaleIsExact;
 2057058        _preparedGeometryFrame = _preparedGeometryUsesSource
 2057059            ? _preparedSourceFrame
 2057060            : ScaledRigidFrame3d.Rigid(center, rotation);
 2057061    }
 62}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/PhysicsMesh.MassProperties.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.MassProperties.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 FixedMathSharp;
 10using FixedMathSharp.Geometry;
 11
 12namespace Gravitas.Colliders;
 13
 14/// <content>Evaluates and caches closed-volume mesh mass properties and their scaled forms.</content>
 15public partial class PhysicsMesh
 16{
 217    private static readonly Signed576 ClosedVolumeRawDenominator =
 218        WideArithmetic.MultiplySigned576(Signed576.ExtendValue(Signed320.ExtendValue(Signed192.One)), Signed192.One, Sig
 19
 20    private bool _closedVolumeMassPropertiesEvaluated;
 21    private MeshMassProperties _closedVolumeMassProperties;
 22    private MeshVolumeValidationResult _closedVolumeValidationResult;
 23    private bool _scaledClosedVolumeMassPropertiesEvaluated;
 24    private MeshMassProperties _scaledClosedVolumeMassProperties;
 25    private MeshVolumeValidationResult _scaledClosedVolumeValidationResult;
 26    private bool _preparedClosedVolumeMassPropertiesEvaluated;
 27    private MeshMassProperties _preparedClosedVolumeMassProperties;
 28    private MeshVolumeValidationResult _preparedClosedVolumeValidationResult;
 29    private bool _preparedClosedVolumeEvaluationIncrement;
 30    private MeshVolumeValidationResult _surfaceClosureValidationResult;
 31
 32    internal int ClosedVolumeScaleEvaluationCount { get; private set; }
 33
 34    /// <summary>Calculates closed-volume mesh inertia for the supplied mass.</summary>
 35    public Fixed3x3 CalculateInertiaTensor(Fixed64 mass) =>
 2736        CalculateInertiaTensor(mass, MeshInertiaPolicy.RequireClosedVolume);
 37
 38    /// <summary>
 39    /// Calculates mesh inertia for the supplied mass using the requested policy.
 40    /// Applies signed mass algebraically and saturates only final entries.
 41    /// This is a geometry/topology API; callers apply body mobility gates before requesting inertia.
 42    /// </summary>
 43    public Fixed3x3 CalculateInertiaTensor(Fixed64 mass, MeshInertiaPolicy policy)
 44    {
 4345        CompoundMassCache cache = GetRuntimeMassCache(policy);
 3946        return cache.Runtime!.Calculate(mass, cache.Runtime.Center, cache.Current);
 47    }
 48
 49    /// <summary>
 50    /// Calculates mesh inertia for the supplied mass about a specific local reference point.
 51    /// Applies signed mass algebraically and saturates only final entries.
 52    /// This is a geometry/topology API; callers apply body mobility gates before requesting inertia.
 53    /// </summary>
 54    public Fixed3x3 CalculateInertiaTensor(Fixed64 mass, MeshInertiaPolicy policy, Vector3d localReferencePoint)
 55    {
 288156        CompoundMassCache cache = GetRuntimeMassCache(policy);
 287957        return cache.Runtime!.Calculate(mass, localReferencePoint, cache.Current);
 58    }
 59
 60    /// <summary>
 61    /// Gets cached closed-volume mass properties when this mesh is a valid closed triangle shell.
 62    /// </summary>
 63    public bool TryGetClosedVolumeMassProperties(
 64        out MeshMassProperties properties,
 65        out MeshVolumeValidationResult result)
 66    {
 548267        EnsureScaledClosedVolumeMassProperties();
 548268        properties = _scaledClosedVolumeMassProperties;
 548269        result = _scaledClosedVolumeValidationResult;
 548270        return result == MeshVolumeValidationResult.Valid;
 71    }
 72
 73    internal bool TryGetPreparedClosedVolumeMassProperties(
 74        out MeshMassProperties properties,
 75        out MeshVolumeValidationResult result)
 76    {
 1757977        properties = _preparedClosedVolumeMassProperties;
 1757978        result = _preparedClosedVolumeValidationResult;
 1757979        return _preparedClosedVolumeMassPropertiesEvaluated
 1757980            && result == MeshVolumeValidationResult.Valid;
 81    }
 82
 83    private void PrepareClosedVolumeMassProperties(
 84        MeshInertiaPolicy? inertiaPolicy,
 85        bool geometryChanged,
 86        Vector3d ownerScale,
 87        Vector3d partScale)
 88    {
 2057089        _preparedClosedVolumeEvaluationIncrement = false;
 2057090        if (!geometryChanged)
 91        {
 1613092            _preparedClosedVolumeMassPropertiesEvaluated =
 1613093                _scaledClosedVolumeMassPropertiesEvaluated;
 1613094            _preparedClosedVolumeMassProperties =
 1613095                _scaledClosedVolumeMassProperties;
 1613096            _preparedClosedVolumeValidationResult =
 1613097                _scaledClosedVolumeValidationResult;
 1613098            return;
 99        }
 100
 4440101        _preparedClosedVolumeMassPropertiesEvaluated = false;
 4440102        if (!IsClosedSurface)
 103        {
 3483104            _preparedClosedVolumeMassPropertiesEvaluated = true;
 3483105            _preparedClosedVolumeValidationResult = _surfaceClosureValidationResult;
 3483106            _preparedClosedVolumeMassProperties = default;
 3483107            return;
 108        }
 109
 957110        if (inertiaPolicy != MeshInertiaPolicy.RequireClosedVolume)
 438111            return;
 112
 519113        _preparedClosedVolumeMassPropertiesEvaluated = true;
 519114        _preparedClosedVolumeEvaluationIncrement = true;
 519115        if (!TryCalculateCandidateClosedVolumeMassProperties(
 519116                ownerScale,
 519117                partScale,
 519118                usePreparedVertices: true,
 519119                out _preparedClosedVolumeMassProperties,
 519120                out _preparedClosedVolumeValidationResult))
 121        {
 4122            throw new ArgumentException(
 4123                $"Mesh scale must preserve a representable closed volume. Validation result: {_preparedClosedVolumeValid
 4124                nameof(inertiaPolicy));
 125        }
 515126    }
 127
 128    private bool TryCalculateCandidateClosedVolumeMassProperties(
 129        Vector3d ownerScale,
 130        Vector3d partScale,
 131        bool usePreparedVertices,
 132        out MeshMassProperties properties,
 133        out MeshVolumeValidationResult result)
 134    {
 569135        bool exactScale = !(usePreparedVertices ? _preparedScaleIsExact : _scaleIsExact);
 569136        if (exactScale)
 18137            return TryCalculateClosedVolumeMassProperties(_localVertices, _localBounds, out properties, out result,
 18138                sourceFrame: usePreparedVertices ? _preparedSourceFrame : _sourceFrame, exactScale: true);
 139
 551140        Fixed64 x = default;
 551141        Fixed64 y = default;
 551142        Fixed64 z = default;
 551143        if (Fixed64.TryMultiplyDivide(
 551144                ownerScale.X,
 551145                partScale.X,
 551146                Fixed64.One,
 551147                out x)
 551148            && Fixed64.TryMultiplyDivide(
 551149                ownerScale.Y,
 551150                partScale.Y,
 551151                Fixed64.One,
 551152                out y)
 551153            && Fixed64.TryMultiplyDivide(
 551154                ownerScale.Z,
 551155                partScale.Z,
 551156                Fixed64.One,
 551157                out z))
 158        {
 550159            EnsureClosedVolumeMassProperties();
 550160            properties = _closedVolumeMassProperties;
 550161            Vector3d scale = new(x, y, z);
 162            // Identity preserves the integrated rounded tensor; recovering its
 163            // covariance would round halves again without changing geometry.
 550164            if (_closedVolumeValidationResult == MeshVolumeValidationResult.Valid
 550165                && (scale == Vector3d.One
 550166                    || _closedVolumeMassProperties.TryScale(scale, out properties) == MeshMassScaleResult.Valid))
 167            {
 540168                result = properties.Volume > Fixed64.Epsilon
 540169                    ? MeshVolumeValidationResult.Valid
 540170                    : MeshVolumeValidationResult.ZeroVolume;
 540171                return result == MeshVolumeValidationResult.Valid;
 172            }
 173
 174            // A source/cache ratio can fail although the already prepared final
 175            // geometry is representable (compensated scales or a tiny source).
 176            // Retain the fast cache path; evaluate final vertices only on failure.
 177        }
 178
 11179        if (usePreparedVertices)
 180        {
 5181            return TryCalculateClosedVolumeMassProperties(
 5182                _preparedScaledLocalVertices,
 5183                _preparedScaledLocalBounds,
 5184                out properties,
 5185                out result);
 186        }
 187
 6188        return TryCalculateClosedVolumeMassProperties(
 6189            _scaledLocalVertices,
 6190            _scaledLocalBounds,
 6191            out properties,
 6192            out result);
 193    }
 194
 195    private void PublishPreparedClosedVolumeMassProperties()
 196    {
 4430197        _scaledClosedVolumeMassPropertiesEvaluated =
 4430198            _preparedClosedVolumeMassPropertiesEvaluated;
 4430199        _scaledClosedVolumeMassProperties =
 4430200            _preparedClosedVolumeMassProperties;
 4430201        _scaledClosedVolumeValidationResult =
 4430202            _preparedClosedVolumeValidationResult;
 4430203        if (_preparedClosedVolumeEvaluationIncrement)
 511204            ClosedVolumeScaleEvaluationCount++;
 4430205    }
 206
 207    private void EnsureScaledClosedVolumeMassProperties()
 208    {
 5482209        if (_scaledClosedVolumeMassPropertiesEvaluated)
 5432210            return;
 211
 50212        _scaledClosedVolumeMassPropertiesEvaluated = true;
 50213        ClosedVolumeScaleEvaluationCount++;
 50214        TryCalculateCandidateClosedVolumeMassProperties(
 50215            _ownerScale,
 50216            _partScale,
 50217            usePreparedVertices: false,
 50218            out _scaledClosedVolumeMassProperties,
 50219            out _scaledClosedVolumeValidationResult);
 50220    }
 221
 222    private void EnsureClosedVolumeMassProperties()
 223    {
 550224        if (_closedVolumeMassPropertiesEvaluated)
 19225            return;
 226
 531227        _closedVolumeMassPropertiesEvaluated = true;
 531228        TryCalculateClosedVolumeMassProperties(
 531229            _localVertices,
 531230            _localBounds,
 531231            out _closedVolumeMassProperties,
 531232            out _closedVolumeValidationResult,
 531233            recenter: true);
 531234    }
 235
 236    private bool EvaluateClosedVolumeTopology(int[] triangles, out MeshVolumeValidationResult result)
 237    {
 2976238        var triangleUses = new TriangleUse[_triangleCount];
 2976239        var edgeUses = new EdgeUse[_triangleCount * 3];
 2976240        int edgeIndex = 0;
 229290241        for (int i = 0; i < _triangleCount; i++)
 242        {
 111669243            int triangleIndex = i * 3;
 111669244            int index0 = triangles[triangleIndex];
 111669245            int index1 = triangles[triangleIndex + 1];
 111669246            int index2 = triangles[triangleIndex + 2];
 247
 111669248            triangleUses[i] = TriangleUse.Create(index0, index1, index2);
 111669249            edgeUses[edgeIndex++] = EdgeUse.Create(index0, index1, i);
 111669250            edgeUses[edgeIndex++] = EdgeUse.Create(index1, index2, i);
 111669251            edgeUses[edgeIndex++] = EdgeUse.Create(index2, index0, i);
 252        }
 253
 2976254        if (ContainsDuplicateTriangle(triangleUses))
 255        {
 15256            result = MeshVolumeValidationResult.DuplicateTriangle;
 15257            return false;
 258        }
 259
 2961260        Array.Sort(edgeUses, CompareEdgeUses);
 261
 2961262        int[] parents = new int[_triangleCount];
 29078263        for (int i = 0; i < parents.Length; i++)
 11578264            parents[i] = i;
 265
 7244266        for (int i = 0; i < edgeUses.Length;)
 267        {
 4232268            int groupStart = i;
 4232269            EdgeUse first = edgeUses[i++];
 5568270            while (i < edgeUses.Length && edgeUses[i].Key == first.Key)
 1336271                i++;
 272
 4232273            int count = i - groupStart;
 4232274            if (count == 1)
 275            {
 2899276                result = MeshVolumeValidationResult.BoundaryEdge;
 2899277                return false;
 278            }
 279
 1333280            if (count > 2)
 281            {
 3282                result = MeshVolumeValidationResult.NonManifoldEdge;
 3283                return false;
 284            }
 285
 1330286            EdgeUse second = edgeUses[groupStart + 1];
 1330287            if (first.Direction + second.Direction != 0)
 288            {
 8289                result = MeshVolumeValidationResult.InconsistentWinding;
 8290                return false;
 291            }
 292
 1322293            Union(parents, first.TriangleIndex, second.TriangleIndex);
 294        }
 295
 51296        if (!HasSingleVertexLinks(triangles, edgeUses))
 297        {
 1298            result = MeshVolumeValidationResult.NonManifoldVertex;
 1299            return false;
 300        }
 301
 50302        int root = Find(parents, 0);
 1184303        for (int i = 1; i < parents.Length; i++)
 304        {
 543305            if (Find(parents, i) == root)
 306                continue;
 307
 1308            result = MeshVolumeValidationResult.DisconnectedShell;
 1309            return false;
 310        }
 311
 49312        result = MeshVolumeValidationResult.Valid;
 49313        return true;
 314    }
 315
 316    private bool TryCalculateClosedVolumeMassProperties(
 317        ReadOnlySpan<Vector3d> vertices,
 318        FixedBoundBox bounds,
 319        out MeshMassProperties properties,
 320        out MeshVolumeValidationResult result,
 321        bool recenter = false,
 322        in ScaledRigidFrame3d sourceFrame = default,
 323        bool exactScale = false)
 324    {
 560325        Vector3d reference = exactScale ? Vector3d.Zero : bounds.Center;
 560326        IntegrateClosedVolume(vertices, reference, out Signed576 signedVolume,
 560327            out Signed576 firstX, out Signed576 firstY, out Signed576 firstZ,
 560328            out Signed576 integralX2, out Signed576 integralY2, out Signed576 integralZ2,
 560329            out Signed576 integralXY, out Signed576 integralXZ, out Signed576 integralYZ,
 560330            sourceFrame, exactScale);
 331
 560332        Signed576 absoluteWeight = signedVolume.Sign < 0
 560333            ? WideArithmetic.SubtractSigned576(default, signedVolume) : signedVolume;
 560334        properties = default;
 560335        Signed576 volumeDenominator = ClosedVolumeRawDenominator;
 560336        if (exactScale)
 360337            for (int index = 0; index < 6; index++) volumeDenominator = WideArithmetic.MultiplySigned576(volumeDenominat
 560338        if (!Fixed64.TryGetSignedRawRatio(absoluteWeight, volumeDenominator, out Fixed64 absoluteVolume))
 339        {
 6340            result = MeshVolumeValidationResult.NonRepresentableVolume;
 6341            return false;
 342        }
 554343        if (absoluteVolume <= Fixed64.Epsilon)
 344        {
 3345            result = MeshVolumeValidationResult.ZeroVolume;
 3346            return false;
 347        }
 348
 349        // Source properties are cached in the same centered frame as final
 350        // vertices. Rounding an authored centroid then subtracting its origin
 351        // loses half-even parity and makes equivalent authoring frames disagree.
 551352        Vector3d outputReference = recenter ? Vector3d.Zero : reference;
 551353        Signed192 coordinateDivisor = exactScale ? new Signed192(0, 1, 0) : Signed192.Signed(1);
 551354        Signed192 squaredRawDivisor = exactScale ? new Signed192(1UL << 32, 0, 0) : Signed192.One;
 551355        Signed576 centerDenominator = WideArithmetic.MultiplySigned576(signedVolume, Signed192.Signed(4), coordinateDivi
 551356        Signed576 diagonalDenominator = WideArithmetic.MultiplySigned576(signedVolume, Signed192.Signed(10), squaredRawD
 551357        Signed576 productDenominator = WideArithmetic.MultiplySigned576(signedVolume, Signed192.Signed(20), squaredRawDi
 358        // Signed ratios cancel winding. Add the reference before rounding so
 359        // half-even centroid ties depend on the final coordinate's raw parity.
 551360        bool representable = TryGetIntegratedCenter(firstX, centerDenominator, outputReference.X, out Fixed64 centerX)
 551361            & TryGetIntegratedCenter(firstY, centerDenominator, outputReference.Y, out Fixed64 centerY)
 551362            & TryGetIntegratedCenter(firstZ, centerDenominator, outputReference.Z, out Fixed64 centerZ)
 551363            & Fixed64.TryGetSignedRawRatio(WideArithmetic.AddSigned576(integralY2, integralZ2), diagonalDenominator, out
 551364            & Fixed64.TryGetSignedRawRatio(WideArithmetic.AddSigned576(integralX2, integralZ2), diagonalDenominator, out
 551365            & Fixed64.TryGetSignedRawRatio(WideArithmetic.AddSigned576(integralX2, integralY2), diagonalDenominator, out
 551366            & Fixed64.TryGetSignedRawRatio(WideArithmetic.SubtractSigned576(default, integralXY), productDenominator, ou
 551367            & Fixed64.TryGetSignedRawRatio(WideArithmetic.SubtractSigned576(default, integralXZ), productDenominator, ou
 551368            & Fixed64.TryGetSignedRawRatio(WideArithmetic.SubtractSigned576(default, integralYZ), productDenominator, ou
 551369        if (!representable)
 370        {
 1371            result = MeshVolumeValidationResult.NonRepresentableMassProperties;
 1372            return false;
 373        }
 374
 550375        properties = new MeshMassProperties(
 550376            absoluteVolume,
 550377            new Vector3d(centerX, centerY, centerZ),
 550378            outputReference,
 550379            new Fixed3x3(
 550380                ixx, ixy, ixz,
 550381                ixy, iyy, iyz,
 550382                ixz, iyz, izz));
 550383        result = MeshVolumeValidationResult.Valid;
 550384        return true;
 385    }
 386
 387    private void IntegrateClosedVolume(ReadOnlySpan<Vector3d> vertices, Vector3d reference,
 388        out Signed576 signedVolume,
 389        out Signed576 firstX, out Signed576 firstY, out Signed576 firstZ,
 390        out Signed576 integralX2, out Signed576 integralY2, out Signed576 integralZ2,
 391        out Signed576 integralXY, out Signed576 integralXZ, out Signed576 integralYZ,
 392        in ScaledRigidFrame3d sourceFrame = default, bool exactScale = false)
 393    {
 886394        signedVolume = default;
 886395        firstX = firstY = firstZ = default;
 886396        integralX2 = integralY2 = integralZ2 = default;
 886397        integralXY = integralXZ = integralYZ = default;
 398
 399        // Raw determinant weights retain all tetrahedra until normalization.
 400        // Degree-five products plus int-bounded triangle accumulation fit 576 bits.
 55500401        for (int i = 0; i < _triangleCount; i++)
 402        {
 26864403            int triangleIndex = i * 3;
 26864404            var triangle = exactScale
 26864405                ? new FixedTriangle(vertices[_triangles[triangleIndex]], vertices[_triangles[triangleIndex + 1]], vertic
 26864406                : new FixedTriangle(vertices[_triangles[triangleIndex]] - reference,
 26864407                    vertices[_triangles[triangleIndex + 1]] - reference, vertices[_triangles[triangleIndex + 2]] - refer
 26864408            var coordinates = new TriangleCoordinates(triangle, sourceFrame, exactScale);
 26864409            Signed576 weight = GetTetrahedronDeterminant(coordinates);
 26864410            signedVolume = WideArithmetic.AddSigned576(signedVolume, weight);
 26864411            firstX = AddWeightedCoordinateSum(firstX, coordinates.AX, coordinates.BX, coordinates.CX, weight);
 26864412            firstY = AddWeightedCoordinateSum(firstY, coordinates.AY, coordinates.BY, coordinates.CY, weight);
 26864413            firstZ = AddWeightedCoordinateSum(firstZ, coordinates.AZ, coordinates.BZ, coordinates.CZ, weight);
 26864414            TriangleShellMassProperties.GetProductSums(coordinates,
 26864415                out Signed320 x2, out Signed320 y2, out Signed320 z2,
 26864416                out Signed320 xy, out Signed320 xz, out Signed320 yz);
 26864417            integralX2 = AddWeighted(integralX2, weight, x2);
 26864418            integralY2 = AddWeighted(integralY2, weight, y2);
 26864419            integralZ2 = AddWeighted(integralZ2, weight, z2);
 26864420            integralXY = AddWeighted(integralXY, weight, xy);
 26864421            integralXZ = AddWeighted(integralXZ, weight, xz);
 26864422            integralYZ = AddWeighted(integralYZ, weight, yz);
 423        }
 424
 886425    }
 426
 427    private static bool TryGetIntegratedCenter(Signed576 firstMoment, Signed576 denominator, Fixed64 reference, out Fixe
 1653428        Fixed64.TryGetSignedRawRatio(WideArithmetic.AddSigned576(firstMoment,
 1653429            WideArithmetic.MultiplySigned576(denominator, Signed192.Raw(reference))), denominator, out center);
 430
 431    private static Signed576 AddWeightedCoordinateSum(Signed576 total, Signed192 a, Signed192 b, Signed192 c, Signed576 
 80592432        AddWeighted(total, weight, WideArithmetic.AddSigned320(WideArithmetic.AddSigned320(
 80592433            Signed320.ExtendValue(a), Signed320.ExtendValue(b)), Signed320.ExtendValue(c)));
 434
 435    private static Signed576 AddWeighted(Signed576 total, Signed576 weight, Signed320 value) =>
 241776436        WideArithmetic.AddSigned576(total, Signed576.NarrowValue(WideArithmetic.MultiplySigned576ToSigned832(weight, val
 437
 438    private static Signed576 GetTetrahedronDeterminant(in TriangleCoordinates t)
 439    {
 26864440        Signed320 x = WideArithmetic.SubtractSigned320(WideArithmetic.MultiplySigned192(t.BY, t.CZ), WideArithmetic.Mult
 26864441        Signed320 y = WideArithmetic.SubtractSigned320(WideArithmetic.MultiplySigned192(t.BZ, t.CX), WideArithmetic.Mult
 26864442        Signed320 z = WideArithmetic.SubtractSigned320(WideArithmetic.MultiplySigned192(t.BX, t.CY), WideArithmetic.Mult
 443        // Admitted numerator coordinates are <2^109. Degree-five moments plus
 444        // at most 2^17 triangle contributions stay below the 576-bit accumulator.
 26864445        return WideArithmetic.AddSigned576(WideArithmetic.AddSigned576(
 26864446            WideArithmetic.MultiplySigned320(x, t.AX), WideArithmetic.MultiplySigned320(y, t.AY)),
 26864447            WideArithmetic.MultiplySigned320(z, t.AZ));
 448    }
 449
 450    private static bool ContainsDuplicateTriangle(TriangleUse[] triangleUses)
 451    {
 4341452        Array.Sort(triangleUses, CompareTriangleUses);
 101632453        for (int i = 1; i < triangleUses.Length; i++)
 454        {
 46490455            if (CompareTriangleUses(triangleUses[i], triangleUses[i - 1]) == 0)
 15456                return true;
 457        }
 458
 4326459        return false;
 460    }
 461
 462    private static int CompareTriangleUses(TriangleUse first, TriangleUse second)
 463    {
 1896752464        if (first.A != second.A)
 458454465            return first.A < second.A ? -1 : 1;
 466
 1438298467        if (first.B != second.B)
 48281468            return first.B < second.B ? -1 : 1;
 469
 1390017470        if (first.C != second.C)
 2482471            return first.C < second.C ? -1 : 1;
 472
 1387535473        return 0;
 474    }
 475
 476    private static int Find(int[] parents, int index)
 477    {
 1164710478        while (parents[index] != index)
 479        {
 399898480            parents[index] = parents[parents[index]];
 399898481            index = parents[index];
 482        }
 483
 764812484        return index;
 485    }
 486
 487    private static void Union(int[] parents, int first, int second)
 488    {
 229507489        int firstRoot = Find(parents, first);
 229507490        int secondRoot = Find(parents, second);
 229507491        if (firstRoot == secondRoot)
 55101492            return;
 493
 174406494        if (firstRoot < secondRoot)
 172927495            parents[secondRoot] = firstRoot;
 496        else
 1479497            parents[firstRoot] = secondRoot;
 1479498    }
 499}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/PhysicsMesh.Scale.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.Scale.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 FixedMathSharp;
 10using FixedMathSharp.Geometry;
 11
 12namespace Gravitas.Colliders;
 13
 14/// <content>Prepares and atomically publishes scaled geometry and its derived caches.</content>
 15public partial class PhysicsMesh
 16{
 17    private Vector3d _position;
 435218    private Vector3d _ownerScale = Vector3d.One;
 435219    private Vector3d _partScale = Vector3d.One;
 20    private bool _scaleInitialized;
 21    private Fixed64[] _scaledFaceAreas;
 22    private Fixed64[] _preparedScaledFaceAreas;
 23    private Vector3d[] _scaledFaceNormals;
 24    private Vector3d[] _preparedScaledFaceNormals;
 25    private Fixed64 _scaledTotalArea;
 26    private ExactMassWeight _scaledTotalAreaWeight;
 27    private Fixed64 _scaledLocalRadius;
 28    private FixedBoundBox _scaledLocalBounds;
 29    private MeshSurfaceMassProperties _surfaceMassProperties;
 30
 31    private Vector3d _preparedPosition;
 32    private Vector3d _preparedOwnerScale;
 33    private Vector3d _preparedPartScale;
 34    private FixedQuaternion _preparedRotation;
 35    private FixedBoundBox _preparedBounds;
 36    private FixedBoundBox _preparedScaledLocalBounds;
 37    private Fixed64 _preparedScaledTotalArea;
 38    private ExactMassWeight _preparedScaledTotalAreaWeight;
 39    private Fixed64 _preparedScaledLocalRadius;
 40    private MeshSurfaceMassProperties _preparedSurfaceMassProperties;
 41    private bool _preparedGeometryChanged;
 42
 43    /// <summary>
 44    /// Gets the committed host or standalone scale factor.
 45    /// </summary>
 98046    public Vector3d OwnerScale => _ownerScale;
 47
 48    /// <summary>
 49    /// Gets the committed authored compound-part scale factor.
 50    /// Standalone meshes use <see cref="Vector3d.One"/>.
 51    /// </summary>
 95852    public Vector3d PartScale => _partScale;
 53
 54    /// <summary>
 55    /// Gets the current centered, scaled bounds in mesh-local coordinates.
 56    /// </summary>
 957    public FixedBoundBox ScaledLocalBounds => _scaledLocalBounds;
 58
 10259    internal Fixed64 ScaledLocalRadius => _scaledLocalRadius;
 60
 1969461    internal Fixed64 PreparedScaledLocalRadius => _preparedScaledLocalRadius;
 62
 135863    internal bool HasRuntimeGeometry => _scaleInitialized;
 64
 65    internal ExactMassWeight SurfaceMassWeight =>
 3766        _scaledTotalAreaWeight;
 67
 68    internal ExactMassWeight PreparedSurfaceMassWeight =>
 26869        _preparedScaledTotalAreaWeight;
 70
 71    internal Fixed64 GetScaledLocalRadius(
 72        Vector3d ownerScale,
 73        Vector3d partScale)
 74    {
 1175        if (_scaleInitialized
 1176            && ownerScale == _ownerScale
 1177            && partScale == _partScale)
 78        {
 679            return _scaledLocalRadius;
 80        }
 81
 582        var frame = new ScaledRigidFrame3d(Vector3d.Zero, FixedQuaternion.Identity, Vector3d.Zero,
 583            ownerScale, FixedQuaternion.Identity, _localBounds.Center, partScale);
 584        Fixed64 radius = Fixed64.Zero;
 2285        foreach (Vector3d vertex in _localVertices)
 86        {
 887            frame.GetScaledLocalPointNumerators(vertex, out Signed192 x, out Signed192 y, out Signed192 z);
 888            if (!WideGeometry.TryGetMagnitudeCeiling(x, y, z, new Signed192(0, 1, 0), out Fixed64 vertexRadius))
 489                return Fixed64.MaxValue;
 490            radius = FixedMath.Max(radius, vertexRadius);
 91        }
 92
 193        return radius;
 94    }
 95
 1969496    internal FixedBoundBox PreparedBounds => _preparedBounds;
 97
 98    internal MeshSurfaceMassProperties PreparedSurfaceMassProperties =>
 750099        _preparedSurfaceMassProperties;
 100
 101    /// <summary>
 102    /// Gets cached uniform thin-shell mass properties for the committed geometry.
 103    /// </summary>
 3057104    public MeshSurfaceMassProperties SurfaceMassProperties => _surfaceMassProperties;
 105
 106    internal void PrepareTransformation(
 107        Vector3d position,
 108        FixedQuaternion rotation,
 109        Vector3d ownerScale,
 110        Vector3d partScale,
 111        MeshInertiaPolicy? inertiaPolicy)
 112    {
 910113        var frame = new ScaledRigidFrame3d(position, FixedQuaternion.Identity,
 910114            Vector3d.Zero, ownerScale, rotation, _localBounds.Center, partScale);
 908115        PrepareTransformation(position, rotation, ownerScale, partScale, inertiaPolicy, frame);
 871116    }
 117
 118    internal void PrepareTransformation(
 119        Vector3d position,
 120        FixedQuaternion rotation,
 121        Vector3d ownerScale,
 122        Vector3d partScale,
 123        MeshInertiaPolicy? inertiaPolicy,
 124        in ScaledRigidFrame3d sourceFrame)
 125    {
 20611126        ColliderScalePolicy.Validate(ownerScale);
 20603127        ColliderScalePolicy.Validate(partScale);
 20603128        _preparedSourceFrame = sourceFrame;
 20603129        _preparedPosition = position;
 20603130        _preparedRotation = rotation;
 131
 20603132        bool geometryChanged = !_scaleInitialized
 20603133            || ownerScale != _ownerScale
 20603134            || partScale != _partScale
 20603135            || (_scaleIsExact && _geometryUsesSource != sourceFrame.HasLocalPlacement);
 20603136        _preparedGeometryChanged = geometryChanged;
 60806137        for (CompoundMassCache? cache = _compoundMassCache; cache != null; cache = cache.Alternate)
 138        {
 9800139            cache.PreparedValid = !geometryChanged && cache.CurrentValid;
 9800140            cache.Prepared = cache.Current;
 141        }
 20603142        if (geometryChanged)
 4473143            PrepareScaledGeometry(ownerScale, partScale);
 144        else
 145        {
 16130146            CopyCommittedGeometryCandidate();
 16130147            SelectPreparedGeometryFrame(position, rotation);
 148        }
 149
 20570150        PrepareClosedVolumeMassProperties(
 20570151            inertiaPolicy,
 20570152            geometryChanged,
 20570153            ownerScale,
 20570154            partScale);
 155
 20566156        _preparedPosition = position;
 20566157        _preparedRotation = rotation;
 20566158        _preparedOwnerScale = ownerScale;
 20566159        _preparedPartScale = partScale;
 20566160        _preparedBounds = _preparedGeometryUsesSource
 20566161            ? sourceFrame.GetWorldBounds(_localBounds.Min, _localBounds.Max)
 20566162            : FixedBoundBox.FromRelativeRotatedBoundsClippedToDomain(
 20566163                position, rotation, _preparedScaledLocalBounds.Min, _preparedScaledLocalBounds.Max,
 20566164                Vector3d.Zero, FixedQuaternion.Identity);
 20566165    }
 166
 167    internal void PublishPreparedTransformation()
 168    {
 20550169        if (_preparedGeometryChanged)
 170        {
 4430171            (_scaledLocalVertices, _preparedScaledLocalVertices) =
 4430172                (_preparedScaledLocalVertices, _scaledLocalVertices);
 4430173            (_scaledFaceAreas, _preparedScaledFaceAreas) =
 4430174                (_preparedScaledFaceAreas, _scaledFaceAreas);
 4430175            (_scaledFaceNormals, _preparedScaledFaceNormals) =
 4430176                (_preparedScaledFaceNormals, _scaledFaceNormals);
 4430177            (_triangleBVH, _preparedTriangleBVH) =
 4430178                (_preparedTriangleBVH, _triangleBVH);
 4430179            if (_supportVertexIndices != null)
 180            {
 23181                (_supportTreeNodes, _preparedSupportTreeNodes) =
 23182                    (_preparedSupportTreeNodes, _supportTreeNodes);
 183            }
 184
 4430185            _scaledLocalBounds = _preparedScaledLocalBounds;
 4430186            _scaledTotalArea = _preparedScaledTotalArea;
 4430187            _scaledTotalAreaWeight =
 4430188                _preparedScaledTotalAreaWeight;
 4430189            _scaledLocalRadius = _preparedScaledLocalRadius;
 4430190            _surfaceMassProperties = _preparedSurfaceMassProperties;
 8994191            for (CompoundMassCache? cache = _compoundMassCache; cache != null; cache = cache.Alternate)
 192            {
 67193                cache.Current = cache.Prepared;
 67194                cache.CurrentValid = cache.PreparedValid;
 83195                if (cache.Runtime != null) cache.Runtime.Ready = false;
 196            }
 4430197            _triangleBvhBuildCount++;
 4430198            PublishPreparedClosedVolumeMassProperties();
 199        }
 200
 20550201        _position = _preparedPosition;
 20550202        _rotation = _preparedRotation;
 20550203        _ownerScale = _preparedOwnerScale;
 20550204        _partScale = _preparedPartScale;
 20550205        _sourceFrame = _preparedSourceFrame;
 20550206        _geometryFrame = _preparedGeometryFrame;
 20550207        _geometryUsesSource = _preparedGeometryUsesSource;
 20550208        _scaleIsExact = _preparedScaleIsExact;
 20550209        _scaleInitialized = true;
 20550210        _bounds = _preparedBounds;
 20550211    }
 212
 213    internal void ValidateSurfaceMassProperties(Vector3d scale)
 214    {
 3215        ChronicleGuard.ThrowIfArgument(
 3216            scale != _ownerScale || _partScale != Vector3d.One,
 3217            nameof(scale),
 3218            "Scale must match the committed standalone mesh scale.");
 1219        _ = SurfaceMassProperties;
 1220    }
 221
 222    internal void ValidateClosedVolumeScaleRepresentability(Vector3d scale)
 223    {
 4224        ChronicleGuard.ThrowIfArgument(
 4225            scale != _ownerScale || _partScale != Vector3d.One,
 4226            nameof(scale),
 4227            "Scale must match the committed standalone mesh scale.");
 2228        if (!TryGetClosedVolumeMassProperties(out _, out MeshVolumeValidationResult result)
 2229            && IsClosedSurface)
 230        {
 1231            throw new ArgumentException(
 1232                $"Mesh scale must preserve a representable closed volume. Validation result: {result}.",
 1233                nameof(scale));
 234        }
 1235    }
 236
 237    private void PrepareScaledGeometry(Vector3d ownerScale, Vector3d partScale)
 238    {
 4473239        Vector3d sourceCenter = _localBounds.Center;
 4473240        _preparedScaledLocalRadius = Fixed64.Zero;
 4473241        _preparedScaleIsExact = true;
 112338242        for (int i = 0; i < _localVertices.Length; i++)
 243        {
 51699244            Vector3d vertex = _localVertices[i];
 51699245            if (!Fixed64.TryMultiplyDifference(
 51699246                    vertex.X,
 51699247                    sourceCenter.X,
 51699248                    ownerScale.X,
 51699249                    partScale.X,
 51699250                    out Fixed64 x)
 51699251                || !Fixed64.TryMultiplyDifference(
 51699252                    vertex.Y,
 51699253                    sourceCenter.Y,
 51699254                    ownerScale.Y,
 51699255                    partScale.Y,
 51699256                    out Fixed64 y)
 51699257                || !Fixed64.TryMultiplyDifference(
 51699258                    vertex.Z,
 51699259                    sourceCenter.Z,
 51699260                    ownerScale.Z,
 51699261                    partScale.Z,
 51699262                    out Fixed64 z))
 263            {
 3264                throw new ArgumentException(
 3265                    "Mesh scale must keep every centered authored vertex representable.",
 3266                    nameof(ownerScale));
 267            }
 268
 51696269            Vector3d scaledVertex = new(x, y, z);
 51696270            _preparedScaledLocalVertices[i] = scaledVertex;
 51696271            bool vertexIsExact = _preparedSourceFrame.IsScaledLocalPointExact(vertex, scaledVertex);
 51696272            _preparedScaleIsExact &= vertexIsExact;
 273            Fixed64 vertexRadius;
 274            bool radiusRepresented;
 51696275            if (vertexIsExact)
 276            {
 277                // Exact scalar vertices have the same norm as their retained
 278                // affine numerators, so keep the compact integer square root.
 51255279                radiusRepresented = scaledVertex.TryGetMagnitudeCeiling(out vertexRadius);
 280            }
 281            else
 282            {
 441283                _preparedSourceFrame.GetScaledLocalPointNumerators(vertex,
 441284                    out Signed192 exactX, out Signed192 exactY, out Signed192 exactZ);
 441285                radiusRepresented = WideGeometry.TryGetMagnitudeCeiling(exactX, exactY, exactZ,
 441286                    new Signed192(0, 1, 0), out vertexRadius);
 287            }
 51696288            if (!radiusRepresented)
 289            {
 15290                _preparedScaledLocalRadius = Fixed64.MaxValue;
 291            }
 51681292            else if (vertexRadius > _preparedScaledLocalRadius)
 293            {
 4668294                _preparedScaledLocalRadius = vertexRadius;
 295            }
 296        }
 297
 4470298        ColliderGeometryPolicy.ValidateReach(_preparedScaledLocalRadius, nameof(ownerScale));
 4444299        _preparedScaledLocalBounds = CalculateBounds(_preparedScaledLocalVertices);
 4444300        _preparedScaledTotalArea = Fixed64.Zero;
 4444301        _preparedScaledTotalAreaWeight = ExactMassWeight.Zero;
 302232302        for (int i = 0; i < _triangleCount; i++)
 303        {
 146676304            int triangleIndex = i * 3;
 146676305            Vector3d first = _preparedScaledLocalVertices[_triangles[triangleIndex]];
 146676306            Vector3d second = _preparedScaledLocalVertices[_triangles[triangleIndex + 1]];
 146676307            Vector3d third = _preparedScaledLocalVertices[_triangles[triangleIndex + 2]];
 146676308            var triangle = new FixedTriangle(first, second, third);
 309            Vector3d normal;
 310            Fixed64 area;
 146676311            if (_preparedScaleIsExact)
 292266312            { normal = triangle.Normal; area = triangle.Area; }
 313            else
 314            {
 543315                var sourceTriangle = new FixedTriangle(_localVertices[_triangles[triangleIndex]],
 543316                    _localVertices[_triangles[triangleIndex + 1]], _localVertices[_triangles[triangleIndex + 2]]);
 543317                WideTriangleRelations.GetScaledAreaAndNormal(sourceTriangle, _preparedSourceFrame, out area, out normal)
 318            }
 146676319            if (area <= Fixed64.Epsilon)
 320            {
 4321                throw new ArgumentException(
 4322                    "Mesh scale must keep every source triangle representably nondegenerate.",
 4323                    nameof(ownerScale));
 324            }
 146672325            if (normal == Vector3d.Zero)
 326            {
 327                // FixedTriangle's public degeneracy threshold intentionally uses
 328                // squared area. Mesh admission has always used surface area, so
 329                // preserve an admitted micro-triangle's representable direction.
 101330                normal = triangle.UnnormalizedNormal.Normalized;
 331            }
 332
 146672333            _preparedScaledTotalArea += area;
 146672334            _preparedScaledFaceAreas[i] = area;
 146672335            _preparedScaledFaceNormals[i] = normal;
 336        }
 337
 4440338        _preparedSurfaceMassProperties = MeshSurfaceMassProperties.Create(
 4440339            _preparedScaleIsExact ? _preparedScaledLocalVertices : _localVertices,
 4440340            _triangles,
 4440341            _preparedScaledTotalArea,
 4440342            out _preparedScaledTotalAreaWeight,
 4440343            out MeshMassIntegrals shellIntegrals, _preparedSourceFrame, exactScale: !_preparedScaleIsExact);
 8936344        for (CompoundMassCache? cache = _compoundMassCache; cache != null; cache = cache.Alternate)
 345        {
 28346            if (cache.Policy != MeshInertiaPolicy.SurfaceApproximation) continue;
 13347            cache.Prepared = shellIntegrals;
 13348            cache.PreparedValid = true;
 349        }
 350
 4440351        SelectPreparedGeometryFrame(_preparedPosition, _preparedRotation);
 4440352        Vector3d[] geometryVertices = _preparedGeometryUsesSource
 4440353            ? _localVertices : _preparedScaledLocalVertices;
 4440354        BuildTriangleBVH(_preparedTriangleBVH, geometryVertices);
 4440355        if (_supportVertexIndices != null)
 356        {
 25357            if (!_scaleInitialized)
 358            {
 15359                _supportTreeNodeCount = 0;
 15360                BuildSupportTreeNode(
 15361                    geometryVertices,
 15362                    _supportVertexIndices,
 15363                    _preparedSupportTreeNodes!,
 15364                    new SupportVertexIndexComparer(),
 15365                    ref _supportTreeNodeCount,
 15366                    0,
 15367                    _supportVertexIndices.Length);
 368            }
 369            else
 370            {
 10371                RefitSupportTree(
 10372                    geometryVertices,
 10373                    _supportTreeNodes!,
 10374                    _preparedSupportTreeNodes!);
 375            }
 376        }
 4425377    }
 378
 379    private void CopyCommittedGeometryCandidate()
 380    {
 16130381        _preparedScaleIsExact = _scaleIsExact;
 16130382        _preparedScaledLocalBounds = _scaledLocalBounds;
 16130383        _preparedScaledTotalArea = _scaledTotalArea;
 16130384        _preparedScaledTotalAreaWeight =
 16130385            _scaledTotalAreaWeight;
 16130386        _preparedScaledLocalRadius = _scaledLocalRadius;
 16130387        _preparedSurfaceMassProperties = _surfaceMassProperties;
 16130388    }
 389
 390}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/PhysicsMesh.SurfaceTopology.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.SurfaceTopology.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.Collections.Generic;
 10using FixedMathSharp;
 11using SwiftCollections;
 12
 13namespace Gravitas.Colliders;
 14
 15/// <content>Retains canonical surface provenance and welded incidence for committed mesh geometry.</content>
 16public partial class PhysicsMesh
 17{
 435218    private int[] _canonicalSurfaceOrdinals = Array.Empty<int>();
 435219    private int[] _coplanarNeighborOffsets = Array.Empty<int>();
 435220    private int[] _coplanarNeighbors = Array.Empty<int>();
 435221    private int[] _weldedTriangleVertices = Array.Empty<int>();
 435222    private int[] _weldedVertexRepresentatives = Array.Empty<int>();
 435223    private int[] _weldedVertexTriangleOffsets = Array.Empty<int>();
 435224    private int[] _weldedVertexTriangles = Array.Empty<int>();
 435225    private int[] _canonicalBoundaryOffsets = Array.Empty<int>();
 435226    private int[] _canonicalBoundaryVertices = Array.Empty<int>();
 27
 435228    private readonly SwiftList<(int First, int Second)> _surfaceNeighborPairs = new();
 435229    private readonly SwiftList<SurfaceBoundaryEdge> _surfaceBoundaryEdges = new();
 435230    private int[] _surfaceWriteOffsets = Array.Empty<int>();
 435231    private int[] _surfaceKeyOffsets = Array.Empty<int>();
 435232    private readonly SwiftList<int> _surfaceOrder = new();
 435233    private int[] _surfacePreviousByVertex = Array.Empty<int>();
 435234    private int[] _surfaceCycleVertices = Array.Empty<int>();
 435235    private int[] _surfaceCycleOffsets = Array.Empty<int>();
 435236    private Vector3d[] _surfacePreparationVertices = Array.Empty<Vector3d>();
 37    private IComparer<SurfaceBoundaryEdge>? _surfaceBoundaryEdgeComparer;
 38    private IComparer<int>? _surfaceOrderComparer;
 39
 40    /// <summary>
 41    /// Gets the collision-free geometric ordering of the committed surface.
 42    /// Trusted patches use their exact boundary domain; declined patches retain
 43    /// individual triangle geometry. This is not an admitted contact-region ID.
 44    /// </summary>
 45    internal int GetCanonicalSurfaceOrdinal(int triangleIndex)
 46    {
 7362947        ChronicleGuard.ThrowIfArrayIndexInvalid(triangleIndex, _triangleCount, nameof(triangleIndex));
 7362948        return _canonicalSurfaceOrdinals[triangleIndex];
 49    }
 50
 51    /// <summary>Gets sorted true boundary segments with monotone collinear subdivisions removed.</summary>
 52    internal ReadOnlySpan<int> GetCanonicalSurfaceBoundaryVertexPairs(int triangleIndex)
 53    {
 4825654        int owner = GetManifoldSurfaceOwner(triangleIndex);
 4825655        return _canonicalBoundaryVertices.AsSpan(_canonicalBoundaryOffsets[owner],
 4825656            _canonicalBoundaryOffsets[owner + 1] - _canonicalBoundaryOffsets[owner]);
 57    }
 58
 59    /// <summary>Gets trusted coplanar shared-edge neighbors in authored triangle order.</summary>
 60    internal ReadOnlySpan<int> GetCoplanarTriangleNeighbors(int triangleIndex)
 61    {
 4509562        ChronicleGuard.ThrowIfArrayIndexInvalid(triangleIndex, _triangleCount, nameof(triangleIndex));
 4509563        return _coplanarNeighbors.AsSpan(_coplanarNeighborOffsets[triangleIndex],
 4509564            _coplanarNeighborOffsets[triangleIndex + 1] - _coplanarNeighborOffsets[triangleIndex]);
 65    }
 66
 67    /// <summary>Gets the committed exactly welded representatives of a triangle's three vertices.</summary>
 68    internal ReadOnlySpan<int> GetWeldedTriangleVertexIndices(int triangleIndex)
 69    {
 10692970        ChronicleGuard.ThrowIfArrayIndexInvalid(triangleIndex, _triangleCount, nameof(triangleIndex));
 10692971        return _weldedTriangleVertices.AsSpan(triangleIndex * 3, 3);
 72    }
 73
 74    /// <summary>
 75    /// Gets all triangles incident to an authored vertex's committed welded position.
 76    /// Incidence alone does not establish admitted connectivity or trusted seam ownership.
 77    /// </summary>
 78    internal ReadOnlySpan<int> GetWeldedVertexTriangleIndices(int vertexIndex)
 79    {
 4343880        ChronicleGuard.ThrowIfArrayIndexInvalid(vertexIndex, VertexCount, nameof(vertexIndex));
 4343881        int representative = _weldedVertexRepresentatives[vertexIndex];
 4343882        return _weldedVertexTriangles.AsSpan(_weldedVertexTriangleOffsets[representative],
 4343883            _weldedVertexTriangleOffsets[representative + 1] - _weldedVertexTriangleOffsets[representative]);
 84    }
 85
 86    private void PrepareWeldedSurfaceIncidence(int[] triangles)
 87    {
 88        // Snapshot before convex/canonical boundary preparation borrows the
 89        // welding representative map as outgoing boundary-link scratch.
 434190        EnsureTopologyBuffer(ref _weldedTriangleVertices, triangles.Length);
 434191        EnsureTopologyBuffer(ref _weldedVertexRepresentatives, VertexCount);
 434192        EnsureTopologyBuffer(ref _weldedVertexTriangleOffsets, VertexCount + 1);
 434193        EnsureTopologyBuffer(ref _weldedVertexTriangles, triangles.Length);
 434194        EnsureTopologyBuffer(ref _surfaceWriteOffsets, Math.Max(VertexCount, _triangleCount) + 1);
 434195        Array.Copy(triangles, _weldedTriangleVertices, triangles.Length);
 434196        Array.Copy(_topologyRepresentativeIndices, _weldedVertexRepresentatives, VertexCount);
 434197        int[] offsets = _weldedVertexTriangleOffsets;
 434198        Array.Clear(offsets, 0, VertexCount + 1);
 91401699        for (int i = 0; i < triangles.Length; i++)
 452667100            offsets[triangles[i] + 1]++;
 89422101        for (int i = 1; i <= VertexCount; i++)
 40370102            offsets[i] += offsets[i - 1];
 4341103        Array.Copy(offsets, _surfaceWriteOffsets, VertexCount);
 914016104        for (int i = 0; i < triangles.Length; i++)
 452667105            _weldedVertexTriangles[_surfaceWriteOffsets[triangles[i]]++] = i / 3;
 4341106    }
 107
 108    private void PrepareSurfaceTopology(Vector3d[] vertices, int[] triangles,
 109        int[] patchIds, int[] boundaryOffsets, int[] boundaries)
 110    {
 4341111        PrepareManifoldPatchTrust(vertices, triangles, patchIds, boundaryOffsets, boundaries);
 4341112        patchIds = _manifoldPatchIds;
 4341113        PrepareCoplanarNeighbors(patchIds);
 4341114        _surfacePreparationVertices = vertices;
 4341115        _surfaceBoundaryEdgeComparer = Comparer<SurfaceBoundaryEdge>.Create(CompareSurfaceBoundaryEdges);
 4341116        _surfaceOrderComparer = Comparer<int>.Create(CompareSurfaceDomains);
 4341117        _surfaceBoundaryEdges.FastClear();
 4341118        int edgeCapacity = 0;
 310460119        for (int i = 0; i < _triangleCount; i++)
 150889120            if (patchIds[i] < 0)
 100940121                edgeCapacity += 3;
 49949122            else if (patchIds[i] == i)
 8455123                edgeCapacity += (boundaryOffsets[i + 1] - boundaryOffsets[i]) / 2;
 4341124        _surfaceBoundaryEdges.EnsureCapacity(edgeCapacity);
 4341125        EnsureTopologyBuffer(ref _canonicalSurfaceOrdinals, _triangleCount);
 4341126        EnsureTopologyBuffer(ref _surfaceKeyOffsets, _triangleCount + 1);
 4341127        _surfaceOrder.FastClear();
 4341128        _surfaceOrder.EnsureCapacity(_triangleCount);
 4341129        EnsureTopologyBuffer(ref _surfacePreviousByVertex, VertexCount);
 310460130        for (int surface = 0; surface < _triangleCount; surface++)
 131        {
 150889132            if (patchIds[surface] >= 0 && patchIds[surface] != surface)
 133                continue;
 109395134            _surfaceOrder.Add(surface);
 109395135            if (patchIds[surface] < 0)
 136            {
 100940137                int index = surface * 3;
 100940138                AddSurfaceBoundaryEdge(surface, triangles[index], triangles[index + 1]);
 100940139                AddSurfaceBoundaryEdge(surface, triangles[index + 1], triangles[index + 2]);
 100940140                AddSurfaceBoundaryEdge(surface, triangles[index + 2], triangles[index]);
 141            }
 142            else
 8455143                AddCanonicalPatchBoundary(surface, triangles, boundaryOffsets, boundaries);
 144        }
 4341145        _surfaceBoundaryEdges.SortInPlace(_surfaceBoundaryEdgeComparer);
 4341146        Array.Clear(_surfaceKeyOffsets, 0, _triangleCount + 1);
 4341147        ReadOnlySpan<SurfaceBoundaryEdge> edges = _surfaceBoundaryEdges.AsReadOnlySpan();
 683650148        for (int i = 0; i < edges.Length; i++)
 337484149            _surfaceKeyOffsets[edges[i].Surface + 1]++;
 310460150        for (int i = 1; i <= _triangleCount; i++)
 150889151            _surfaceKeyOffsets[i] += _surfaceKeyOffsets[i - 1];
 152        // The ordering key already contains exactly the reduced exposed
 153        // segments needed for sampling. Snapshot it in the existing atomic
 154        // preparation/publication transaction; scratch is not committed data.
 4341155        EnsureTopologyBuffer(ref _canonicalBoundaryOffsets, _triangleCount + 1);
 4341156        EnsureTopologyBuffer(ref _canonicalBoundaryVertices, edges.Length * 2);
 319142157        for (int i = 0; i <= _triangleCount; i++)
 155230158            _canonicalBoundaryOffsets[i] = _surfaceKeyOffsets[i] * 2;
 683650159        for (int i = 0; i < edges.Length; i++)
 160        {
 337484161            _canonicalBoundaryVertices[i * 2] = edges[i].Start;
 337484162            _canonicalBoundaryVertices[i * 2 + 1] = edges[i].End;
 163        }
 4341164        _surfaceOrder.SortInPlace(_surfaceOrderComparer);
 4341165        int ordinal = 0;
 227472166        for (int i = 0; i < _surfaceOrder.Count; i++)
 167        {
 109395168            if (i > 0 && CompareSurfaceDomains(_surfaceOrder[i - 1], _surfaceOrder[i]) != 0)
 4995169                ordinal++;
 109395170            _canonicalSurfaceOrdinals[_surfaceOrder[i]] = ordinal;
 171        }
 310460172        for (int i = 0; i < _triangleCount; i++)
 150889173            if (patchIds[i] >= 0)
 49949174                _canonicalSurfaceOrdinals[i] = _canonicalSurfaceOrdinals[patchIds[i]];
 4341175    }
 176
 177    private void PrepareCoplanarNeighbors(int[] patchIds)
 178    {
 4341179        EnsureTopologyBuffer(ref _coplanarNeighborOffsets, _triangleCount + 1);
 4341180        int[] offsets = _coplanarNeighborOffsets;
 4341181        Array.Clear(offsets, 0, _triangleCount + 1);
 4341182        ReadOnlySpan<(int First, int Second)> pairs = _surfaceNeighborPairs.AsReadOnlySpan();
 119502183        for (int i = 0; i < pairs.Length; i++)
 184        {
 55410185            (int first, int second) = pairs[i];
 55410186            if (patchIds[first] < 0)
 187                continue;
 55360188            offsets[first + 1]++;
 55360189            offsets[second + 1]++;
 190        }
 310460191        for (int i = 1; i <= _triangleCount; i++)
 150889192            offsets[i] += offsets[i - 1];
 4341193        EnsureTopologyBuffer(ref _coplanarNeighbors, offsets[_triangleCount]);
 4341194        Array.Copy(offsets, _surfaceWriteOffsets, _triangleCount);
 119502195        for (int i = 0; i < pairs.Length; i++)
 196        {
 55410197            (int first, int second) = pairs[i];
 55410198            if (patchIds[first] < 0)
 199                continue;
 55360200            _coplanarNeighbors[_surfaceWriteOffsets[first]++] = second;
 55360201            _coplanarNeighbors[_surfaceWriteOffsets[second]++] = first;
 202        }
 310460203        for (int i = 0; i < _triangleCount; i++)
 150889204            Array.Sort(_coplanarNeighbors, offsets[i], offsets[i + 1] - offsets[i]);
 4341205    }
 206
 207    private void AddCanonicalPatchBoundary(int surface, int[] triangles, int[] offsets, int[] boundaries)
 208    {
 8455209        int index = surface * 3;
 8455210        int axis = GetPatchProjectionAxis(_surfacePreparationVertices[triangles[index]],
 8455211            _surfacePreparationVertices[triangles[index + 1]], _surfacePreparationVertices[triangles[index + 2]]);
 8455212        int cycles = PrepareReducedSurfaceCycles(_surfacePreparationVertices, surface, offsets, boundaries, axis);
 213        // Keep directed cycles until trust has been established. Only the
 214        // canonical provenance key discards orientation and sorts segments.
 33954215        for (int cycle = 0; cycle < cycles; cycle++)
 216        {
 17044217            int begin = _surfaceCycleOffsets[cycle], end = _surfaceCycleOffsets[cycle + 1];
 86372218            for (int corner = begin; corner < end; corner++)
 34664219                AddSurfaceBoundaryEdge(surface, _surfaceCycleVertices[corner],
 34664220                    _surfaceCycleVertices[corner + 1 == end ? begin : corner + 1]);
 221        }
 8455222    }
 223
 224    private int PrepareReducedSurfaceCycles(Vector3d[] vertices, int surface,
 225        int[] offsets, int[] boundaries, int axis)
 226    {
 17250227        int begin = offsets[surface], end = offsets[surface + 1];
 8625228        int[] next = _topologyRepresentativeIndices;
 8625229        EnsureTopologyBuffer(ref _surfacePreviousByVertex, VertexCount);
 99236230        for (int i = begin; i < end; i += 2)
 231        {
 40993232            next[boundaries[i]] = boundaries[i + 1];
 40993233            _surfacePreviousByVertex[boundaries[i + 1]] = boundaries[i];
 234        }
 8625235        EnsureTopologyBuffer(ref _surfaceCycleVertices, (end - begin) / 2);
 8625236        EnsureTopologyBuffer(ref _surfaceCycleOffsets, (end - begin) / 2 + 1);
 17250237        int count = 0, cycles = 0;
 238        // Degree two supplies closed directed walks, not geometric simplicity.
 239        // Remove only monotone collinear vertices: retain every backtrack so
 240        // the embedding certificate can reject it rather than erase overlap.
 99236241        for (int i = begin; i < end; i += 2)
 242        {
 40993243            int start = boundaries[i];
 40993244            if (next[start] < 0)
 245                continue;
 8759246            _surfaceCycleOffsets[cycles++] = count;
 8759247            int current = start;
 248            do
 249            {
 40993250                int successor = next[current];
 40993251                int previous = _surfacePreviousByVertex[current];
 40993252                Vector3d a = vertices[previous];
 40993253                Vector3d b = vertices[current];
 40993254                Vector3d c = vertices[successor];
 40993255                if (Vector2d.OrientationSign(ProjectToBoundaryPlane(a, axis),
 40993256                        ProjectToBoundaryPlane(b, axis), ProjectToBoundaryPlane(c, axis)) != 0
 40993257                    || Math.Sign(CompareSurfacePositions(a, b)) == Math.Sign(CompareSurfacePositions(c, b)))
 35982258                    _surfaceCycleVertices[count++] = current;
 40993259                next[current] = -1;
 40993260                current = successor;
 261            }
 40993262            while (current != start);
 263        }
 8625264        _surfaceCycleOffsets[cycles] = count;
 8625265        return cycles;
 266    }
 267
 268    private void AddSurfaceBoundaryEdge(int surface, int start, int end)
 269    {
 337484270        if (CompareSurfacePositions(_surfacePreparationVertices[start], _surfacePreparationVertices[end]) > 0)
 218896271            (start, end) = (end, start);
 337484272        _surfaceBoundaryEdges.Add(new SurfaceBoundaryEdge(surface, start, end));
 337484273    }
 274
 275    private int CompareSurfaceBoundaryEdges(SurfaceBoundaryEdge first, SurfaceBoundaryEdge second)
 276    {
 5718092277        int comparison = first.Surface.CompareTo(second.Surface);
 5718092278        return comparison != 0 ? comparison : CompareSurfaceEdgeGeometry(first, second);
 279    }
 280
 281    private int CompareSurfaceEdgeGeometry(SurfaceBoundaryEdge first, SurfaceBoundaryEdge second)
 282    {
 4849402283        int comparison = CompareSurfacePositions(_surfacePreparationVertices[first.Start],
 4849402284            _surfacePreparationVertices[second.Start]);
 4849402285        return comparison != 0 ? comparison : CompareSurfacePositions(_surfacePreparationVertices[first.End],
 4849402286            _surfacePreparationVertices[second.End]);
 287    }
 288
 289    private int CompareSurfaceDomains(int first, int second)
 290    {
 3005148291        int firstStart = _surfaceKeyOffsets[first], secondStart = _surfaceKeyOffsets[second];
 1502574292        int firstCount = _surfaceKeyOffsets[first + 1] - firstStart;
 1502574293        int secondCount = _surfaceKeyOffsets[second + 1] - secondStart;
 1502574294        ReadOnlySpan<SurfaceBoundaryEdge> edges = _surfaceBoundaryEdges.AsReadOnlySpan();
 11934374295        for (int i = 0; i < Math.Min(firstCount, secondCount); i++)
 296        {
 4479635297            int comparison = CompareSurfaceEdgeGeometry(edges[firstStart + i], edges[secondStart + i]);
 4479635298            if (comparison != 0)
 15022299                return comparison;
 300        }
 1487552301        return firstCount.CompareTo(secondCount);
 302    }
 303
 304    private static int CompareSurfacePositions(Vector3d first, Vector3d second)
 305    {
 9792584306        int comparison = first.X.CompareTo(second.X);
 9792584307        if (comparison != 0)
 364745308            return comparison;
 9427839309        comparison = first.Y.CompareTo(second.Y);
 9427839310        return comparison != 0 ? comparison : first.Z.CompareTo(second.Z);
 311    }
 312
 313    private readonly struct SurfaceBoundaryEdge
 314    {
 315        internal readonly int Surface, Start, End;
 316        internal SurfaceBoundaryEdge(int surface, int start, int end)
 317        {
 1012452318            Surface = surface; Start = start; End = end;
 337484319        }
 320    }
 321}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Colliders/Mesh/PhysicsMesh.SurfaceTrust.cs

#LineLine coverage
 1//=======================================================================
 2// PhysicsMesh.SurfaceTrust.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 FixedMathSharp;
 10
 11namespace Gravitas.Colliders;
 12
 13/// <content>Certifies embedded planar owners before manifold seam suppression and connectivity.</content>
 14public partial class PhysicsMesh
 15{
 435216    private int[] _manifoldPatchIds = Array.Empty<int>();
 17
 18
 19    /// <summary>Gets an embedded planar patch owner, or the individual declined triangle.</summary>
 20    internal int GetManifoldSurfaceOwner(int triangleIndex)
 21    {
 82080722        ChronicleGuard.ThrowIfArrayIndexInvalid(triangleIndex, _triangleCount, nameof(triangleIndex));
 82080723        int patch = _manifoldPatchIds[triangleIndex];
 82080724        return patch < 0 ? triangleIndex : patch;
 25    }
 26
 27    /// <summary>Gets the true perimeter of a certified manifold owner; empty means use the triangle's three edges.</sum
 28    internal ReadOnlySpan<int> GetManifoldSurfaceBoundaryVertexPairs(int triangleIndex)
 29    {
 5153330        ChronicleGuard.ThrowIfArrayIndexInvalid(triangleIndex, _triangleCount, nameof(triangleIndex));
 5153331        int patch = _manifoldPatchIds[triangleIndex];
 5153332        return patch < 0 ? ReadOnlySpan<int>.Empty
 5153333            : _coplanarPatchBoundaryVertexPairs.AsSpan(_coplanarPatchBoundaryOffsets[patch],
 5153334                _coplanarPatchBoundaryOffsets[patch + 1] - _coplanarPatchBoundaryOffsets[patch]);
 35    }
 36
 37    private void PrepareManifoldPatchTrust(Vector3d[] vertices, int[] triangles, int[] legacyIds,
 38        int[] boundaryOffsets, int[] boundaries)
 39    {
 434140        EnsureTopologyBuffer(ref _manifoldPatchIds, _triangleCount);
 31046041        for (int patch = 0; patch < _triangleCount; patch++)
 42        {
 15088943            if (legacyIds[patch] != patch) continue;
 44            // A strict convex ring already proves unit winding. Other patches
 45            // use the same exact chain proof after reducing their full boundary.
 846246            bool trusted = _convexCoplanarPatchCornerOffsets[patch + 1]
 846247                > _convexCoplanarPatchCornerOffsets[patch];
 846248            if (!trusted)
 49            {
 17050                int first = patch * 3;
 17051                int axis = GetPatchProjectionAxis(vertices[triangles[first]], vertices[triangles[first + 1]], vertices[t
 17052                int orientation = Vector2d.OrientationSign(ProjectToBoundaryPlane(vertices[triangles[first]], axis),
 17053                    ProjectToBoundaryPlane(vertices[triangles[first + 1]], axis), ProjectToBoundaryPlane(vertices[triang
 17054                int cycles = PrepareReducedSurfaceCycles(vertices, patch, boundaryOffsets, boundaries, axis);
 17055                trusted = IsEmbeddedSurfaceBoundary(vertices,
 17056                    _surfaceCycleVertices.AsSpan(0, _surfaceCycleOffsets[cycles]),
 17057                    _surfaceCycleOffsets.AsSpan(0, cycles + 1), axis, orientation);
 58            }
 846259            _surfaceWriteOffsets[patch] = trusted ? patch : -1;
 60        }
 31046061        for (int triangle = 0; triangle < _triangleCount; triangle++)
 15088962            _manifoldPatchIds[triangle] = legacyIds[triangle] < 0 ? -1 : _surfaceWriteOffsets[legacyIds[triangle]];
 434163    }
 64
 65    /// <summary>Certifies reduced directed planar cycles as the boundary of a domain with multiplicity zero or one.</su
 66    /// <remarks>
 67    /// Offsets delimit complete cycles of vertex indices, with monotone collinear
 68    /// subdivisions removed. Projection is injective on the common plane and
 69    /// orientation is the nonzero projected triangle orientation. Indices and
 70    /// offsets are prepared storage; geometric simplicity is not a precondition.
 71    /// </remarks>
 72    internal static bool IsEmbeddedSurfaceBoundary(ReadOnlySpan<Vector3d> vertices, ReadOnlySpan<int> corners,
 73        ReadOnlySpan<int> offsets, int axis, int orientation)
 74    {
 75        // Preparation orients the two-sided triangle chain to its root face;
 76        // full opposite-side welded seams then cancel regardless of authored winding.
 77        // Every remaining open cell's positive triangle multiplicity equals
 78        // boundary winding. Simple disjoint cycles with winding 0/1 therefore
 79        // exclude interior overlaps. An unshared touch on a canceled seam would
 80        // overlap its two incident half-neighborhoods; an uncanceled touch is
 81        // rejected below. Exact welding handles genuine shared vertices.
 82        // ponytail: O(B^2) in reduced boundary corners; use a deterministic
 83        // sweep only if detailed perimeters, rather than subdivision, dominate.
 18484        int cycles = offsets.Length - 1;
 18585        if (cycles == 0) return false;
 86686        for (int cycle = 0; cycle < cycles; cycle++)
 87        {
 52488            int begin = offsets[cycle], end = offsets[cycle + 1];
 26389            if (end - begin < 3) return false;
 324090            for (int edge = begin; edge < end; edge++)
 91            {
 137092                Vector2d a = ProjectToBoundaryPlane(vertices[corners[edge]], axis);
 137093                Vector2d b = ProjectToBoundaryPlane(vertices[corners[edge + 1 == end ? begin : edge + 1]], axis);
 137094                Vector2d previous = ProjectToBoundaryPlane(vertices[corners[edge == begin ? end - 1 : edge - 1]], axis);
 95                // Monotone straight corners are already gone. A remaining
 96                // zero turn is a reversal or collapsed edge, never a simple rim.
 137197                if (Vector2d.OrientationSign(previous, a, b) == 0) return false;
 612098                for (int otherCycle = cycle; otherCycle < cycles; otherCycle++)
 99                {
 3402100                    int otherBegin = offsets[otherCycle], otherEnd = offsets[otherCycle + 1];
 14424101                    for (int other = otherCycle == cycle ? edge + 1 : otherBegin; other < otherEnd; other++)
 102                    {
 5521103                        if (otherCycle == cycle && (other == edge + 1 || edge == begin && other == end - 1)) continue;
 4150104                        Vector2d c = ProjectToBoundaryPlane(vertices[corners[other]], axis);
 4150105                        Vector2d d = ProjectToBoundaryPlane(vertices[corners[other + 1 == otherEnd ? otherBegin : other 
 4160106                        if (SurfaceBoundarySegmentsIntersect(a, b, c, d)) return false;
 107                    }
 108                }
 109            }
 110        }
 832111        for (int cycle = 0; cycle < cycles; cycle++)
 112        {
 248113            Vector2d point = ProjectToBoundaryPlane(vertices[corners[offsets[cycle]]], axis);
 248114            int winding = SurfaceCycleOrientation(vertices, corners, offsets[cycle], offsets[cycle + 1], axis) * orienta
 1316115            for (int other = 0; other < cycles; other++)
 410116                if (other != cycle && SurfaceCycleContains(vertices, corners, offsets[other], offsets[other + 1], axis, 
 75117                    winding += SurfaceCycleOrientation(vertices, corners, offsets[other], offsets[other + 1], axis) * or
 118            // Each cycle bounds one new nested cell. Its first vertex lies
 119            // strictly inside every ancestor and outside all its descendants.
 251120            if (winding < 0 || winding > 1) return false;
 121        }
 168122        return true;
 123    }
 124
 125    private static int SurfaceCycleOrientation(ReadOnlySpan<Vector3d> vertices, ReadOnlySpan<int> corners,
 126        int begin, int end, int axis)
 127    {
 323128        int minimum = begin;
 323129        Vector2d point = ProjectToBoundaryPlane(vertices[corners[minimum]], axis);
 3302130        for (int i = begin + 1; i < end; i++)
 131        {
 1328132            Vector2d candidate = ProjectToBoundaryPlane(vertices[corners[i]], axis);
 1328133            if (candidate.X < point.X || candidate.X == point.X && candidate.Y < point.Y)
 134            {
 101135                minimum = i;
 101136                point = candidate;
 137            }
 138        }
 323139        return Vector2d.OrientationSign(
 323140            ProjectToBoundaryPlane(vertices[corners[minimum == begin ? end - 1 : minimum - 1]], axis), point,
 323141            ProjectToBoundaryPlane(vertices[corners[minimum + 1 == end ? begin : minimum + 1]], axis));
 142    }
 143
 144    private static bool SurfaceCycleContains(ReadOnlySpan<Vector3d> vertices, ReadOnlySpan<int> corners,
 145        int begin, int end, int axis, Vector2d point)
 146    {
 162147        int winding = 0;
 1612148        for (int i = begin; i < end; i++)
 149        {
 644150            Vector2d a = ProjectToBoundaryPlane(vertices[corners[i]], axis);
 644151            Vector2d b = ProjectToBoundaryPlane(vertices[corners[i + 1 == end ? begin : i + 1]], axis);
 152            // Half-open crossings count vertices once, without a division or
 153            // rounded ray intersection. Disjointness excludes boundary points.
 644154            if (a.Y <= point.Y)
 155            {
 242156                if (b.Y > point.Y && Vector2d.OrientationSign(a, b, point) > 0) winding++;
 157            }
 481158            else if (b.Y <= point.Y && Vector2d.OrientationSign(a, b, point) < 0) winding--;
 159        }
 162160        return winding != 0;
 161    }
 162
 163    private static bool SurfaceBoundarySegmentsIntersect(Vector2d a, Vector2d b, Vector2d c, Vector2d d)
 164    {
 4150165        if (FixedMath.Max(FixedMath.Min(a.X, b.X), FixedMath.Min(c.X, d.X)) > FixedMath.Min(FixedMath.Max(a.X, b.X), Fix
 8269166            || FixedMath.Max(FixedMath.Min(a.Y, b.Y), FixedMath.Min(c.Y, d.Y)) > FixedMath.Min(FixedMath.Max(a.Y, b.Y), 
 31167        return Vector2d.OrientationSign(a, b, c) * Vector2d.OrientationSign(a, b, d) <= 0
 31168            && Vector2d.OrientationSign(c, d, a) * Vector2d.OrientationSign(c, d, b) <= 0;
 169    }
 170}

Methods/Properties

.ctor(Gravitas.Colliders.MeshInertiaPolicy)
GetMassCache(Gravitas.Colliders.MeshInertiaPolicy)
GetRuntimeMassCache(Gravitas.Colliders.MeshInertiaPolicy)
BuildRuntimeMassCache(Gravitas.Colliders.PhysicsMesh/CompoundMassCache)
GetCompoundMassIntegrals(System.Boolean,Gravitas.Colliders.MeshInertiaPolicy)
.ctor(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.MeshColliderMode,System.Boolean)
.cctor()
CreateTopologyTriangles(FixedMathSharp.Vector3d[],System.Int32[])
CompareVertexUses(Gravitas.Colliders.PhysicsMesh/VertexUse,Gravitas.Colliders.PhysicsMesh/VertexUse)
CreateConvexSatEdgeVertexPairs(FixedMathSharp.Vector3d[],System.Int32[],System.Int32)
RegisterBoundaryEdge(Gravitas.Colliders.PhysicsMesh/EdgeUse,System.Int32[],System.Int32[],System.Int32&,System.Int32&,System.Int32[])
CalculateSharedEdgeSide(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.PhysicsMesh/EdgeUse,Gravitas.Colliders.PhysicsMesh/EdgeUse)
ValidateOpenConvexBoundary(FixedMathSharp.Vector3d[],System.Int32[],System.Int32,System.Int32[],System.Int32,System.Int32)
GetDominantNormalAxis(FixedMathSharp.Vector3d[],System.Int32[])
ProjectToBoundaryPlane(FixedMathSharp.Vector3d,System.Int32)
ValidateBoundaryMatchesConvexHull(Gravitas.Colliders.PhysicsMesh/BoundaryVertex[],System.Int32[])
TryGetStrictConvexBoundary(Gravitas.Colliders.PhysicsMesh/BoundaryVertex[],System.Int32,Gravitas.Colliders.PhysicsMesh/BoundaryVertex[]&,System.Int32&)
ValidateProjectedTriangleFill(FixedMathSharp.Vector3d[],System.Int32[],System.Int32,Gravitas.Colliders.PhysicsMesh/BoundaryVertex[],System.Int32)
AppendConvexHullVertex(Gravitas.Colliders.PhysicsMesh/BoundaryVertex[],System.Int32&,System.Int32,Gravitas.Colliders.PhysicsMesh/BoundaryVertex)
MatchesCyclicHull(Gravitas.Colliders.PhysicsMesh/BoundaryVertex[],System.Int32,Gravitas.Colliders.PhysicsMesh/BoundaryVertex[])
CompareBoundaryVertices(Gravitas.Colliders.PhysicsMesh/BoundaryVertex,Gravitas.Colliders.PhysicsMesh/BoundaryVertex)
HasSingleVertexLinks(System.Int32[],Gravitas.Colliders.PhysicsMesh/EdgeUse[])
FindTriangleCornerIndex(System.Int32[],System.Int32,System.Int32)
CompareVertexCornerUses(Gravitas.Colliders.PhysicsMesh/VertexCornerUse,Gravitas.Colliders.PhysicsMesh/VertexCornerUse)
CreateSatEdgeVertexPairs(Gravitas.Colliders.PhysicsMesh/EdgeUse[],FixedMathSharp.Vector3d[],System.Int32[])
CountConvexSatEdges(Gravitas.Colliders.PhysicsMesh/EdgeUse[],FixedMathSharp.Vector3d[],System.Int32[])
FindEdgeUseGroupEnd(System.ReadOnlySpan`1<Gravitas.Colliders.PhysicsMesh/EdgeUse>,System.Int32)
ShouldIncludeConvexSatEdge(Gravitas.Colliders.PhysicsMesh/EdgeUse[],System.Int32,System.Int32,FixedMathSharp.Vector3d[],System.Int32[])
FindOppositeVertexIndex(System.Int32[],System.Int32,System.Int32,System.Int32)
.ctor(FixedMathSharp.Vector3d,System.Int32)
.ctor(FixedMathSharp.Vector2d,System.Int32)
.ctor(System.Int32,System.Int32)
.ctor(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.MeshColliderMode,System.Boolean)
.cctor()
GetConvexCoplanarPatchCornerVertexIndices(System.Int32)
get_HasSingleConvexCoplanarPatch()
EnsureTopologyBuffer(T[]&,System.Int32)
ReleaseTopologyPreparation()
PrepareCoplanarPatches(FixedMathSharp.Vector3d[])
PrepareConvexCoplanarPatchCorners(FixedMathSharp.Vector3d[],System.Int32[],System.Int32[],System.Int32[],System.Int32[])
ClassifyCoplanarSeam(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.PhysicsMesh/EdgeUse,Gravitas.Colliders.PhysicsMesh/EdgeUse)
CreateOrientedPatchBoundaryEdge(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.PhysicsMesh/EdgeUse,System.Int32)
GetPatchProjectionAxis(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
RejectAmbiguousPatchBoundaryVertices(System.ReadOnlySpan`1<Gravitas.Colliders.PhysicsMesh/EdgeUse>,System.Int32,System.Boolean[])
ComparePatchBoundaryVertexUses(Gravitas.Colliders.PhysicsMesh/PatchBoundaryVertexUse,Gravitas.Colliders.PhysicsMesh/PatchBoundaryVertexUse)
.ctor(System.Int32,System.Int32)
get_LocalVertices()
get_ScaledLocalVertices()
get_VertexCount()
get_Triangles()
get_TriangleCount()
get_ConvexSatEdgeVertexPairs()
get_TotalArea()
get_TriangleBVH()
get_TriangleBvhBuildCount()
.ctor(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.MeshColliderMode,System.Boolean)
get_Origin()
get_Rotation()
get_Bounds()
get_LocalBounds()
.ctor(FixedMathSharp.Vector3d[],System.Int32[],FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
.ctor(FixedMathSharp.Vector3d[],System.Int32[],FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,Gravitas.Colliders.MeshColliderMode)
UpdatePosition(FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
UpdateTransform(FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,FixedMathSharp.Vector3d)
ValidateInput(FixedMathSharp.Vector3d[],System.Int32[])
BuildTriangleBVH(SwiftCollections.Query.SwiftFixedBVH`1<System.Int32>,System.ReadOnlySpan`1<FixedMathSharp.Vector3d>)
CalculateBounds(FixedMathSharp.Vector3d[])
CompareEdgeUses(Gravitas.Colliders.PhysicsMesh/EdgeUse,Gravitas.Colliders.PhysicsMesh/EdgeUse)
GetFrontalArea(FixedMathSharp.Vector3d)
GetTriangleVertices(System.Int32,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&)
TryGetTriangleVertices(System.Int32,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&)
GetLocalTriangleVertices(System.Int32,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&)
GetScaledLocalFaceNormal(System.Int32)
TryGetVertexWorld(System.Int32,FixedMathSharp.Vector3d&)
GetVertexWorld(System.Int32)
TryGetSupportVertexWorld(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&)
GetSupportVertexWorld(FixedMathSharp.Vector3d)
GetSupportVertexLocal(FixedMathSharp.Vector3d)
.ctor(FixedMathSharp.Vector3d)
.ctor(FixedMathSharp.Geometry.WideAxis3)
Compare(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
BoundsPoint(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
Project(FixedMathSharp.Vector3d)
FindSupportVertexIndex(Gravitas.Colliders.PhysicsMesh/SupportDirection&)
SearchSupportLeaf(Gravitas.Colliders.PhysicsMesh/SupportTreeNode,Gravitas.Colliders.PhysicsMesh/SupportDirection&,System.Int32&)
PushSupportNode(Gravitas.Colliders.PhysicsMesh/SupportTreeNode,System.Int32,Gravitas.Colliders.PhysicsMesh/SupportDirection&,System.Span`1<System.Int32>,System.Int32&)
ComesBeforeSupportNode(Gravitas.Colliders.PhysicsMesh/SupportTreeNode,Gravitas.Colliders.PhysicsMesh/SupportTreeNode,Gravitas.Colliders.PhysicsMesh/SupportDirection&)
BuildSupportTreeNode(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.PhysicsMesh/SupportTreeNode[],Gravitas.Colliders.PhysicsMesh/SupportVertexIndexComparer,System.Int32&,System.Int32,System.Int32)
RefitSupportTree(FixedMathSharp.Vector3d[],Gravitas.Colliders.PhysicsMesh/SupportTreeNode[],Gravitas.Colliders.PhysicsMesh/SupportTreeNode[])
CalculateSupportRangeBounds(FixedMathSharp.Vector3d[],System.Int32[],System.Int32,System.Int32,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&,System.Int32&)
CreateSupportVertexIndices(System.Int32)
GetDominantAxis(FixedMathSharp.Vector3d)
GetBoundsSupportPoint(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
GetFaceNormalWorld(System.Int32)
GetTrianglesInWorldBounds(SwiftCollections.Query.FixedBoundVolume,SwiftCollections.SwiftList`1<System.Int32>)
GetTrianglesInLocalBounds(SwiftCollections.Query.FixedBoundVolume,SwiftCollections.SwiftList`1<System.Int32>)
TryConvertWorldToScaledLocal(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&)
ConvertWorldToScaledLocal(FixedMathSharp.Vector3d)
TryConvertScaledLocalToWorld(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&)
ConvertScaledLocalToWorld(FixedMathSharp.Vector3d)
CreatePointAnchor(FixedMathSharp.Vector3d)
TryConvertWorldDirectionToLocal(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&)
ConvertWorldDirectionToLocal(FixedMathSharp.Vector3d)
.ctor(System.Int64,System.Int32,System.Int32)
get_StartVertexIndex()
get_EndVertexIndex()
Create(System.Int32,System.Int32,System.Int32)
.ctor(System.Int32,System.Int32,System.Int32)
Create(System.Int32,System.Int32,System.Int32)
.ctor(System.Int32,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)
get_IsLeaf()
CreateLeaf(System.Int32,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32,System.Int32,System.Int32)
CreateBranch(System.Int32,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32,System.Int32,System.Int32)
.ctor()
Reset(FixedMathSharp.Vector3d[],System.Int32)
Compare(System.Int32,System.Int32)
GetAxisValue(FixedMathSharp.Vector3d,System.Int32)
get_GeometryFrame()
get_GeometryVertices()
get_GeometryLocalBounds()
GetGeometryTriangleVertices(System.Int32,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&,FixedMathSharp.Vector3d&)
TryConvertWorldToRigidGeometry(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d&)
GetTrianglesInGeometryBounds(SwiftCollections.Query.FixedBoundVolume,SwiftCollections.SwiftList`1<System.Int32>)
SelectPreparedGeometryFrame(FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion)
.cctor()
CalculateInertiaTensor(FixedMathSharp.Fixed64)
CalculateInertiaTensor(FixedMathSharp.Fixed64,Gravitas.Colliders.MeshInertiaPolicy)
CalculateInertiaTensor(FixedMathSharp.Fixed64,Gravitas.Colliders.MeshInertiaPolicy,FixedMathSharp.Vector3d)
TryGetClosedVolumeMassProperties(Gravitas.Colliders.MeshMassProperties&,Gravitas.Colliders.MeshVolumeValidationResult&)
TryGetPreparedClosedVolumeMassProperties(Gravitas.Colliders.MeshMassProperties&,Gravitas.Colliders.MeshVolumeValidationResult&)
PrepareClosedVolumeMassProperties(System.Nullable`1<Gravitas.Colliders.MeshInertiaPolicy>,System.Boolean,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
TryCalculateCandidateClosedVolumeMassProperties(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Boolean,Gravitas.Colliders.MeshMassProperties&,Gravitas.Colliders.MeshVolumeValidationResult&)
PublishPreparedClosedVolumeMassProperties()
EnsureScaledClosedVolumeMassProperties()
EnsureClosedVolumeMassProperties()
EvaluateClosedVolumeTopology(System.Int32[],Gravitas.Colliders.MeshVolumeValidationResult&)
TryCalculateClosedVolumeMassProperties(System.ReadOnlySpan`1<FixedMathSharp.Vector3d>,FixedMathSharp.Geometry.FixedBoundBox,Gravitas.Colliders.MeshMassProperties&,Gravitas.Colliders.MeshVolumeValidationResult&,System.Boolean,FixedMathSharp.Geometry.ScaledRigidFrame3d&,System.Boolean)
IntegrateClosedVolume(System.ReadOnlySpan`1<FixedMathSharp.Vector3d>,FixedMathSharp.Vector3d,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Signed576&,FixedMathSharp.Geometry.ScaledRigidFrame3d&,System.Boolean)
TryGetIntegratedCenter(FixedMathSharp.Signed576,FixedMathSharp.Signed576,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64&)
AddWeightedCoordinateSum(FixedMathSharp.Signed576,FixedMathSharp.Signed192,FixedMathSharp.Signed192,FixedMathSharp.Signed192,FixedMathSharp.Signed576)
AddWeighted(FixedMathSharp.Signed576,FixedMathSharp.Signed576,FixedMathSharp.Signed320)
GetTetrahedronDeterminant(Gravitas.Colliders.TriangleCoordinates&)
ContainsDuplicateTriangle(Gravitas.Colliders.PhysicsMesh/TriangleUse[])
CompareTriangleUses(Gravitas.Colliders.PhysicsMesh/TriangleUse,Gravitas.Colliders.PhysicsMesh/TriangleUse)
Find(System.Int32[],System.Int32)
Union(System.Int32[],System.Int32,System.Int32)
.ctor(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.MeshColliderMode,System.Boolean)
get_OwnerScale()
get_PartScale()
get_ScaledLocalBounds()
get_ScaledLocalRadius()
get_PreparedScaledLocalRadius()
get_HasRuntimeGeometry()
get_SurfaceMassWeight()
get_PreparedSurfaceMassWeight()
GetScaledLocalRadius(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
get_PreparedBounds()
get_PreparedSurfaceMassProperties()
get_SurfaceMassProperties()
PrepareTransformation(FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Nullable`1<Gravitas.Colliders.MeshInertiaPolicy>)
PrepareTransformation(FixedMathSharp.Vector3d,FixedMathSharp.FixedQuaternion,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Nullable`1<Gravitas.Colliders.MeshInertiaPolicy>,FixedMathSharp.Geometry.ScaledRigidFrame3d&)
PublishPreparedTransformation()
ValidateSurfaceMassProperties(FixedMathSharp.Vector3d)
ValidateClosedVolumeScaleRepresentability(FixedMathSharp.Vector3d)
PrepareScaledGeometry(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
CopyCommittedGeometryCandidate()
.ctor(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.MeshColliderMode,System.Boolean)
GetCanonicalSurfaceOrdinal(System.Int32)
GetCanonicalSurfaceBoundaryVertexPairs(System.Int32)
GetCoplanarTriangleNeighbors(System.Int32)
GetWeldedTriangleVertexIndices(System.Int32)
GetWeldedVertexTriangleIndices(System.Int32)
PrepareWeldedSurfaceIncidence(System.Int32[])
PrepareSurfaceTopology(FixedMathSharp.Vector3d[],System.Int32[],System.Int32[],System.Int32[],System.Int32[])
PrepareCoplanarNeighbors(System.Int32[])
AddCanonicalPatchBoundary(System.Int32,System.Int32[],System.Int32[],System.Int32[])
PrepareReducedSurfaceCycles(FixedMathSharp.Vector3d[],System.Int32,System.Int32[],System.Int32[],System.Int32)
AddSurfaceBoundaryEdge(System.Int32,System.Int32,System.Int32)
CompareSurfaceBoundaryEdges(Gravitas.Colliders.PhysicsMesh/SurfaceBoundaryEdge,Gravitas.Colliders.PhysicsMesh/SurfaceBoundaryEdge)
CompareSurfaceEdgeGeometry(Gravitas.Colliders.PhysicsMesh/SurfaceBoundaryEdge,Gravitas.Colliders.PhysicsMesh/SurfaceBoundaryEdge)
CompareSurfaceDomains(System.Int32,System.Int32)
CompareSurfacePositions(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
.ctor(System.Int32,System.Int32,System.Int32)
.ctor(FixedMathSharp.Vector3d[],System.Int32[],Gravitas.Colliders.MeshColliderMode,System.Boolean)
GetManifoldSurfaceOwner(System.Int32)
GetManifoldSurfaceBoundaryVertexPairs(System.Int32)
PrepareManifoldPatchTrust(FixedMathSharp.Vector3d[],System.Int32[],System.Int32[],System.Int32[],System.Int32[])
IsEmbeddedSurfaceBoundary(System.ReadOnlySpan`1<FixedMathSharp.Vector3d>,System.ReadOnlySpan`1<System.Int32>,System.ReadOnlySpan`1<System.Int32>,System.Int32,System.Int32)
SurfaceCycleOrientation(System.ReadOnlySpan`1<FixedMathSharp.Vector3d>,System.ReadOnlySpan`1<System.Int32>,System.Int32,System.Int32,System.Int32)
SurfaceCycleContains(System.ReadOnlySpan`1<FixedMathSharp.Vector3d>,System.ReadOnlySpan`1<System.Int32>,System.Int32,System.Int32,System.Int32,FixedMathSharp.Vector2d)
SurfaceBoundarySegmentsIntersect(FixedMathSharp.Vector2d,FixedMathSharp.Vector2d,FixedMathSharp.Vector2d,FixedMathSharp.Vector2d)