< Summary

Information
Class: Gravitas.StaticSurface2D
Assembly: Gravitas
File(s): File 1: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.Contacts.cs
File 2: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.ContinuousCollision.cs
File 3: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.cs
File 4: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.Mixed.cs
File 5: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedBoundaryLines.cs
File 6: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedCapsule.cs
File 7: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedCurved.cs
File 8: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedCurved.Domain.cs
File 9: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedCurved.Regions.cs
File 10: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedMesh.cs
File 11: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedRegions.cs
File 12: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedSphere.cs
File 13: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.Recovery.cs
File 14: /home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.Serialization.cs
Line coverage
100%
Covered lines: 2004
Uncovered lines: 0
Coverable lines: 2004
Total lines: 3686
Line coverage: 100%
Branch coverage
100%
Covered branches: 2012
Total branches: 2012
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: .cctor()100%11100%
File 1: .ctor(...)100%11100%
File 1: InvalidateGeometry()100%11100%
File 1: Reduce(...)100%3232100%
File 1: Gather(...)100%1010100%
File 1: Prepare()100%1818100%
File 1: Build(...)100%4242100%
File 1: PlaneAdmitted(...)100%1010100%
File 1: SpansMeet(...)100%66100%
File 1: FaceContacts(...)100%88100%
File 1: BuildFan(...)100%1212100%
File 1: Add(...)100%11100%
File 1: Offsets(...)100%44100%
File 1: BoundsOverlap(...)100%66100%
File 2: .ctor(...)100%11100%
File 2: get_ContinuousOrder()100%11100%
File 2: GetMixedContinuousSupport(...)100%66100%
File 2: IntersectsMixedContinuous(...)100%1414100%
File 2: AppendMixedContinuousContacts(...)100%2020100%
File 2: GatherMixedContinuous(...)100%66100%
File 2: AdmitContinuousWitness(...)100%2424100%
File 2: AdmitMixedContinuousWitness(...)100%3434100%
File 3: .ctor(...)100%11100%
File 3: get_ReplayMembership()100%22100%
File 3: ReplaceMembers(...)100%4646100%
File 3: Invalidate(...)100%1616100%
File 3: Touches(...)100%22100%
File 3: Remove(...)100%22100%
File 3: Dispose()100%22100%
File 3: Release()100%22100%
File 4: .ctor(...)100%11100%
File 4: .cctor()100%11100%
File 4: get_MixedMovingPoints()100%44100%
File 4: get_MixedMovingTriangles()100%44100%
File 4: get_MixedMovingEdges()100%44100%
File 4: AppendMixed(...)100%8484100%
File 4: RequestMixedReach(...)100%22100%
File 4: GatherMixed(...)100%1010100%
File 4: GatherMixedMembers(...)100%1010100%
File 4: PrepareMixed()100%1616100%
File 4: PrepareMixedBands(...)100%1818100%
File 4: BuildMixed()100%66100%
File 4: BuildMixedPart()100%2828100%
File 4: FindMixedPenetration(...)100%66100%
File 4: AdmitMixedRigidAxis(...)100%11100%
File 4: AdmitMixedAxis(...)100%66100%
File 4: HasMixedReach(...)100%44100%
File 4: VisitMixed(...)100%44100%
File 4: IsMixedFaceAxis(...)100%44100%
File 4: VisitMixedEdges(...)100%2424100%
File 4: VisitMixedEdgeInterval(...)100%66100%
File 4: VisitMixedEdgeInterior(...)100%2626100%
File 4: VisitMixedFaces(...)100%2424100%
File 4: MixedSupportPoint(...)100%22100%
File 4: MaySupplyMixedFace(...)100%1212100%
File 4: VisitMixedFaces(...)100%5252100%
File 4: VisitMixedSide(...)100%1212100%
File 4: VisitMixedRigidFace(...)100%11100%
File 4: FindMixedGroup(...)100%1616100%
File 4: FixedMathSharp.Geometry.IScaledConvexHullContactDomain.GetEdgeIntervals(...)100%22100%
File 4: GetMixedEdgeIntervals(...)100%1010100%
File 4: FixedMathSharp.Geometry.IScaledConvexHullContactDomain.ContainsPoint(...)100%11100%
File 4: FixedMathSharp.Geometry.IScaledConvexHullContactDomain.ContainsPoint(...)100%22100%
File 4: ContainsMixedPoint(...)100%3434100%
File 4: SupportsMixedFan(...)100%44100%
File 4: TryGetMixedHeights(...)100%44100%
File 4: MixedHeightContains(...)100%1010100%
File 4: AddMixedSample(...)100%11100%
File 4: .ctor(...)100%11100%
File 4: get_Axis()100%22100%
File 4: .ctor(...)100%11100%
File 4: .ctor()100%11100%
File 4: Matches(...)100%66100%
File 4: Prepare(...)100%1010100%
File 4: .ctor()100%11100%
File 5: .ctor(...)100%11100%
File 5: PrepareMixedBoundaryLines()100%4242100%
File 5: KeepMixedBoundaryLine(...)100%2626100%
File 5: AppendMixedCapsuleBoundaryPeaks(...)100%5656100%
File 5: MixedBoundaryLineNormal(...)100%22100%
File 5: GetMixedBoundaryBounds(...)100%88100%
File 5: SameMixedBoundaryInterval(...)100%22100%
File 5: .ctor(...)100%11100%
File 6: .ctor(...)100%11100%
File 6: FixedMathSharp.Geometry.IPrismCapsuleContactDomain.get_IncludeRecovery()100%11100%
File 6: BuildMixedCapsule()100%3030100%
File 6: PrepareMixedCapsuleChoice(...)100%3636100%
File 6: RemoveMixedCapsuleParentWindows(...)100%2020100%
File 6: FixedMathSharp.Geometry.IPrismCapsuleContactDomain.GetSupportIntervals(...)100%3232100%
File 6: SameMixedCapsuleIntervalWide(...)100%1818100%
File 6: FixedMathSharp.Geometry.IPrismCapsuleContactDomain.AddSupportContact(...)100%1616100%
File 6: AddMixedCapsuleSample(...)100%11100%
File 6: SameMixedCapsulePlane(...)100%66100%
File 6: FixedMathSharp.Geometry.IPrismCapsuleContactDomain.GetEdgeIntervals(...)100%66100%
File 6: FixedMathSharp.Geometry.IPrismCapsuleContactDomain.AdmitEdgePoint(...)100%22100%
File 6: FixedMathSharp.Geometry.IPrismCapsuleContactDomain.AddEdgeContact(...)100%22100%
File 6: GetMixedCapsuleEdge(...)100%22100%
File 6: AppendMixedCapsule(...)100%2828100%
File 7: .ctor(...)100%11100%
File 7: BuildMixedCurved()100%2828100%
File 7: VisitMixedCurvedMember(...)100%4242100%
File 7: ContainsMixedCurvedBoundaryWindow(...)100%1818100%
File 7: AreMixedCurvedCutRowsCompatible(...)100%3636100%
File 7: KeepMixedCurvedBoundary(...)100%11100%
File 7: .ctor(...)100%11100%
File 7: AddMixedCurvedSample(...)100%22100%
File 7: AppendMixedCurved(...)100%11100%
File 7: .ctor(...)100%11100%
File 8: .ctor(...)100%11100%
File 8: .cctor()100%11100%
File 8: PrepareMixedCurvedDomain(...)100%2222100%
File 8: PrepareMixedCurvedDomains()100%2020100%
File 8: PrepareMixedCurvedEdges(...)100%22100%
File 8: PrepareMixedCurvedEdge(...)100%2222100%
File 8: KeepMixedCurvedWindow(...)100%88100%
File 8: PrepareMixedCurvedCertificates(...)100%1818100%
File 8: GetMixedCurvedPlane(...)100%66100%
File 8: SameMixedCurvedPlane(...)100%44100%
File 8: .ctor(...)100%11100%
File 8: .ctor(...)100%11100%
File 8: .ctor()100%11100%
File 9: AddMixedCurvedCertificatePlane(...)100%88100%
File 9: GetMixedCurvedPlaneForRow(...)100%22100%
File 9: CompleteMixedCurvedRegions(...)100%2020100%
File 9: MixedCurvedCapsTouch(...)100%2424100%
File 9: MixedCurvedSidesTouch(...)100%2020100%
File 9: IntersectMixedCurvedEdges(...)100%11100%
File 9: IsBestMixedCurvedFarRegion(...)100%1414100%
File 9: RequestMixedCurvedFarReach()100%88100%
File 9: AppendMixedCurvedRegions(...)100%1616100%
File 10: .ctor(...)100%11100%
File 10: BuildMixedMesh(...)100%1010100%
File 10: SetMixedMovingFeature(...)100%22100%
File 11: .ctor(...)100%11100%
File 11: AddMixedRegion(...)100%44100%
File 11: HasMixedFaceRegion(...)100%66100%
File 11: CompleteMixedRegions()100%3636100%
File 11: AppendMixedRegionSamples(...)100%2626100%
File 11: FindMixedRegion(...)100%22100%
File 11: MixedEdgeRegionsTouch(...)100%2222100%
File 11: MixedVerticalEdgeRegionsTouch(...)100%1010100%
File 11: TryIntersectMixedIntervals(...)100%1616100%
File 11: MixedFaceEdgeRegionsTouch(...)100%1010100%
File 11: MixedEdgeRegionEndpoint(...)100%1010100%
File 11: IntersectsMixedRegionEdge(...)100%44100%
File 11: MixedRegionBoundary(...)100%44100%
File 11: MixedRegionsTouch(...)100%3030100%
File 11: MixedCapSupportVertex(...)100%1414100%
File 11: MixedRegionRectangle(...)100%11100%
File 11: MixedSideRegionsTouch(...)100%2424100%
File 11: IntersectsMixedRegionSegment(...)100%22100%
File 11: VisitMixedRegionSegment(...)100%22100%
File 11: .ctor(...)100%11100%
File 11: .ctor()100%11100%
File 11: GetEdgeIntervals(...)100%22100%
File 11: ContainsPoint(...)100%11100%
File 11: ContainsPoint(...)100%44100%
File 11: ContainsParameter(...)100%88100%
File 12: .ctor(...)100%11100%
File 12: BuildMixedSphere()100%6464100%
File 12: SelectMixedSphereSources(...)100%5050100%
File 12: PrepareMixedSphereConcavity()100%4848100%
File 12: AppendMixedSphere(...)100%1616100%
File 12: .ctor(...)100%11100%
File 12: .ctor(...)100%44100%
File 12: AppendMixedSphereFacePeaks(...)100%1818100%
File 12: AdmitMixedSphereBoundaryPoint(...)100%11100%
File 12: AdmitMixedSpherePoint(...)100%44100%
File 12: AdmitMixedPrismSupportPoint(...)100%1010100%
File 12: AdmitMixedSphereFan(...)100%2222100%
File 13: TryGetRecovery(...)100%2020100%
File 13: IsRecoveryClear(...)100%1414100%
File 13: TryRecoveryDirection(...)100%1010100%
File 14: RecordData(...)100%1818100%

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.Contacts.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.Contacts.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 Gravitas.Colliders;
 13using Gravitas.CollisionHandling;
 14using Gravitas.Support;
 15using SwiftCollections;
 16
 17namespace Gravitas;
 18
 19/// <content>Local filled-boundary contacts; member overlap remains independent of response ownership.</content>
 20public sealed partial class StaticSurface2D
 21{
 122    private static readonly IComparer<LSCollider2D> SurfaceMemberOrder = Comparer<LSCollider2D>.Create(static (a, b) =>
 123        ((IPhysicsColliderRegistryItem)a).ReplayOrder.CompareTo(((IPhysicsColliderRegistryItem)b).ReplayOrder));
 180024    private readonly SwiftList<LSCollider2D> _candidates = new(), _local = new(), _prepared = new();
 60025    private readonly SwiftList<MeshSurfaceBoundaryDomain2D> _domains = new();
 60026    private readonly SwiftList<(int Member, int Span)> _admitted = new();
 60027    private readonly SwiftList<int> _fanMembers = new();
 60028    private readonly SwiftList<int> _components = new();
 60029    private readonly SwiftList<FixedPointAnchor2d> _fan = new();
 60030    private readonly ContactManifold2D _contacts = new();
 31    private LSCollider2D? _moving, _carrier;
 32    private Vector2d _movingCenter;
 33    private Fixed64 _movingRotation;
 34    private uint _movingShape, _movingDependency;
 35    private bool _current;
 36
 37    partial void InvalidateGeometry()
 38    {
 213039        _current = false;
 213040        _mixedCurrent = false;
 213041        _mixedMoving = null;
 213042        _mixedLocal.Clear(clearRetainedReferences: true);
 213043        _moving = _carrier = null;
 44        // FastClear leaves reference tails beyond Count; ended member lifetimes
 45        // must be released even when this declaration becomes empty or is retained after disposal.
 213046        _candidates.Clear(clearRetainedReferences: true);
 213047        _local.Clear(clearRetainedReferences: true);
 213048        _prepared.Clear(clearRetainedReferences: true);
 213049    }
 50
 51    internal void Reduce(LSCollider2D mover, LSCollider2D overlapMember, ContactManifold2D destination, bool reverse)
 52    {
 303453        Gather(mover);
 303454        bool same = _local.Count == _prepared.Count;
 1967355        for (int i = 0; same && i < _local.Count; i++) same = _local[i] == _prepared[i];
 320656        if (!same) Prepare();
 303457        if (!_current || _moving != mover || _movingCenter != mover.Center || _movingRotation != mover.Rotation
 303458            || _movingShape != mover.RuntimeShapeVersion || _movingDependency != (mover.CompoundOwner ?? mover).ContactD
 59        {
 200360            Build(mover, overlapMember);
 600961            _moving = mover; _movingCenter = mover.Center; _movingRotation = mover.Rotation;
 400662            _movingShape = mover.RuntimeShapeVersion; _movingDependency = (mover.CompoundOwner ?? mover).ContactDependen
 200363            _current = true;
 64        }
 314365        if (_carrier != overlapMember) return;
 299166        if (!_contacts.HasContact) { destination.NeedsSurfaceRecovery = true; return; }
 344067        if (!reverse) { destination.CopyFrom(_contacts, destination.LastUpdatedFrame); return; }
 1075868        for (int g = 0; g < _contacts.GroupCount; g++)
 69        {
 276170            ref ContactGroup2D group = ref _contacts.GetGroup(g);
 1106271            for (int p = 0; p < group.Count; p++)
 72            {
 277073                ManifoldContact2D row = group[p];
 277074                destination.AddContact(row.AnchorB, row.AnchorA, row.Depth, -row.Normal,
 277075                    row.MaterialB, row.MaterialA, row.DepthIsClamped, group: group.Key.Remap(0, 0, true));
 76            }
 77        }
 261878    }
 79
 80    private void Gather(LSCollider2D mover)
 81    {
 305082        Fixed64 reach = mover.CanonicalCenteredProxyRadius * Fixed64.Two;
 305083        FixedBoundArea bounds = FixedBoundArea.FromCenterAndScopeClippedToDomain(mover.Center, Vector2d.One * reach);
 305084        _context.Collisions2D.CollectBoundsCandidates(bounds.Min, bounds.Max, PhysicsLayerMask.All,
 305085            _context.Query2D.NextOverlapQueryVersion(), false, _candidates, staticStyleOnly: true);
 305086        _local.FastClear();
 1575087        foreach (LSCollider2D candidate in _candidates.AsReadOnlySpan())
 482588            if (candidate.StaticSurface == this && !candidate.IsTrigger
 963189                && _context.Physics2D.RequireCollisionPair(mover.CompoundOwner ?? mover, candidate)) _local.Add(candidat
 305090        _local.SortInPlace(SurfaceMemberOrder);
 305091    }
 92
 93    private void Prepare()
 94    {
 17595        _current = false;
 17596        _prepared.FastClear();
 108897        foreach (LSCollider2D member in _local.AsReadOnlySpan()) _prepared.Add(member);
 54998        while (_domains.Count < _local.Count) _domains.Add(new MeshSurfaceBoundaryDomain2D());
 108899        for (int i = 0; i < _local.Count; i++) _domains[i].Build(_local.AsReadOnlySpan(), i);
 175100        _components.FastClear();
 1088101        for (int i = 0; i < _local.Count; i++) _components.Add(i);
 842102        for (int i = 0; i < _local.Count; i++)
 2486103            foreach (var span in _domains[i].Spans)
 997104                if (span.Kind == SpanKind.Joined)
 105                {
 284106                    int from = _components[span.OtherMember], to = _components[i];
 1378107                    for (int j = 0; j < _components.Count; j++) if (_components[j] == from) _components[j] = to;
 108                }
 175109    }
 110
 111    private void Build(LSCollider2D mover, LSCollider2D knownOverlap)
 112    {
 6009113        _contacts.Reset(); _carrier = null; _admitted.FastClear();
 2003114        Span<FixedContactAnchors2d> rows = stackalloc FixedContactAnchors2d[2];
 2003115        Span<Vector2d> box = stackalloc Vector2d[4];
 10556116        for (int member = 0; member < _local.Count; member++)
 117        {
 3275118            LSCollider2D supplier = _local[member];
 5278119            if (_carrier == null && (supplier == knownOverlap || CollisionDetection2D.HasSurfaceOverlap(mover, supplier)
 3275120            ReadOnlySpan<BoundarySpan2D> spans = _domains[member].Spans;
 32780121            for (int s = 0; s < spans.Length; s++)
 122            {
 13115123                if (spans[s].Kind == SpanKind.Joined) continue;
 10571124                int count = FaceContacts(mover, member, s, rows);
 10571125                if (count == 0) continue;
 2105126                _admitted.Add((member, s));
 10921127                for (int p = 0; p < count; p++) Add(mover, member, s, rows[p]);
 128            }
 129        }
 130        int previous;
 131        do
 132        {
 3161133            previous = _admitted.Count;
 17506134            for (int member = 0; member < _local.Count; member++)
 55950135                for (int s = 0; s < _domains[member].Spans.Length; s++)
 136                {
 22383137                    var face = _domains[member].Spans[s];
 22383138                    if (face.Kind == SpanKind.Joined || _admitted.Contains((member, s)) || !PlaneAdmitted(member, s)) co
 1162139                    _admitted.Add((member, s));
 1162140                    int count = FaceContacts(mover, member, s, rows, planeAdmitted: true);
 2339141                    for (int p = 0; p < count; p++) Add(mover, member, s, rows[p]);
 142                }
 3161143        } while (_admitted.Count != previous);
 10556144        for (int member = 0; member < _local.Count; member++)
 145        {
 3275146            LSCollider2D supplier = _local[member];
 32750147            for (int v = 0; v < supplier.VertexCount; v++)
 148            {
 13100149                if (!BoundsOverlap(mover, _domains[member].VertexBounds[v])) continue;
 1175150                var vertex = new FixedPointAnchor2d(supplier.Center, supplier.ConvexRotation, supplier.GetScaledLocalVer
 1175151                BuildFan(member, vertex);
 1175152                bool hit = mover is LSCircleCollider2D circle
 1175153                    ? WideCenteredCapsule2dRelations.TryGetBoundaryVertexContact(mover.Center, mover.Rotation, Fixed64.Z
 1175154                        circle.ScaledRadius, vertex, _fan.AsReadOnlySpan(), out rows[0])
 1175155                    : mover is LSCapsuleCollider2D capsule
 1175156                        ? WideCenteredCapsule2dRelations.TryGetBoundaryVertexContact(mover.Center, mover.Rotation, capsu
 1175157                            capsule.ScaledRadius, vertex, _fan.AsReadOnlySpan(), out rows[0])
 1175158                        : WideConvex2dRelations.TryGetBoundaryVertexContact(mover.Center, mover.ConvexRotation,
 1175159                            Offsets(mover, box), vertex, _fan.AsReadOnlySpan(), out rows[0]);
 1355160                if (hit) Add(mover, member, v, rows[0], vertex: true);
 161            }
 162        }
 2003163    }
 164
 165    private bool PlaneAdmitted(int member, int span)
 166    {
 13093167        LSCollider2D supplier = _local[member];
 13093168        var face = _domains[member].Spans[span];
 64794169        foreach (var admitted in _admitted.AsReadOnlySpan())
 170        {
 19885171            if (_components[member] != _components[admitted.Member]) continue;
 19885172            LSCollider2D other = _local[admitted.Member];
 19885173            var otherFace = _domains[admitted.Member].Spans[admitted.Span];
 174            // Meeting retained spans must also meet in their outward-rounded
 175            // whole-edge bounds; distant coplanar faces need no exact comparison.
 19885176            if (!face.Bounds.Intersects(otherFace.Bounds)) continue;
 6892177            if (WideConvex2dRelations.SameBoundaryPlane(supplier.Center, supplier.ConvexRotation,
 6892178                new FixedSegment2d(face.Start, face.End), supplier.GetScaledLocalVertexUnchecked((face.Second + 1) % sup
 6892179                other.Center, other.ConvexRotation, new FixedSegment2d(otherFace.Start, otherFace.End),
 6892180                other.GetScaledLocalVertexUnchecked((otherFace.Second + 1) % other.VertexCount))
 8054181                && SpansMeet(supplier, face, other, otherFace)) return true;
 182        }
 11931183        return false;
 184    }
 185
 186    private static bool SpansMeet(LSCollider2D first, in BoundarySpan2D a,
 187        LSCollider2D second, in BoundarySpan2D b)
 188    {
 189        // Solid connectivity off this plane must not bridge a genuine boundary gap.
 1165190        Span<FixedPointAnchor2d> endpoints = stackalloc FixedPointAnchor2d[4]
 1165191        {
 1165192            new(first.Center, first.ConvexRotation, a.Start), new(first.Center, first.ConvexRotation, a.End),
 1165193            new(second.Center, second.ConvexRotation, b.Start), new(second.Center, second.ConvexRotation, b.End)
 1165194        };
 4666195        foreach (var point in endpoints)
 1749196            if (WideConvex2dRelations.LocateBoundaryPoint(point, first.Center, first.ConvexRotation,
 1749197                    new FixedSegment2d(a.Start, a.End), a.Interval) >= 0
 1749198                && WideConvex2dRelations.LocateBoundaryPoint(point, second.Center, second.ConvexRotation,
 2911199                    new FixedSegment2d(b.Start, b.End), b.Interval) >= 0) return true;
 3200        return false;
 201    }
 202
 203    private int FaceContacts(LSCollider2D mover, int member, int span, Span<FixedContactAnchors2d> rows, bool planeAdmit
 204    {
 11733205        LSCollider2D supplier = _local[member];
 11733206        var face = _domains[member].Spans[span];
 19722207        if (!planeAdmitted && !BoundsOverlap(mover, face.Bounds)) return 0;
 3744208        Vector2d inward = supplier.GetScaledLocalVertexUnchecked((face.Second + 1) % supplier.VertexCount);
 3744209        var edge = new FixedSegment2d(face.Start, face.End);
 3744210        Span<Vector2d> box = stackalloc Vector2d[4];
 3744211        return mover is LSCircleCollider2D circle
 3744212            ? WideConvex2dRelations.GetCapsuleBoundaryFaceContacts(mover.Center, mover.Rotation, Fixed64.Zero, circle.Sc
 3744213                supplier.Center, supplier.ConvexRotation, edge, inward, face.Interval, rows, planeAdmitted)
 3744214            : mover is LSCapsuleCollider2D capsule
 3744215                ? WideConvex2dRelations.GetCapsuleBoundaryFaceContacts(mover.Center, mover.Rotation, capsule.AxisLength,
 3744216                    supplier.Center, supplier.ConvexRotation, edge, inward, face.Interval, rows, planeAdmitted)
 3744217                : WideConvex2dRelations.GetBoundaryFaceContacts(mover.Center, mover.ConvexRotation, Offsets(mover, box),
 3744218                    supplier.Center, supplier.ConvexRotation, edge, inward, face.Interval, rows, planeAdmitted);
 219    }
 220
 221    private void BuildFan(int source, in FixedPointAnchor2d vertex)
 222    {
 3555223        _fan.FastClear(); _fanMembers.FastClear(); _fanMembers.Add(source);
 7060224        for (int cursor = 0; cursor < _fanMembers.Count; cursor++)
 225        {
 2345226            int member = _fanMembers[cursor];
 2345227            LSCollider2D supplier = _local[member];
 23450228            for (int v = 0; v < supplier.VertexCount; v++)
 9380229                _fan.Add(new FixedPointAnchor2d(supplier.Center, supplier.ConvexRotation, supplier.GetScaledLocalVertexU
 23496230            foreach (var span in _domains[member].Spans)
 9403231                if (span.Kind == SpanKind.Joined && !_fanMembers.Contains(span.OtherMember)
 9403232                    && WideConvex2dRelations.LocateBoundaryPoint(vertex, supplier.Center, supplier.ConvexRotation,
 10563233                        new FixedSegment2d(span.Start, span.End), span.Interval) >= 0) _fanMembers.Add(span.OtherMember)
 234        }
 1185235    }
 236
 237    private void Add(LSCollider2D mover, int member, int feature, in FixedContactAnchors2d row, bool vertex = false)
 238    {
 2422239        LSCollider2D supplier = _local[member];
 2422240        _contacts.AddContact(new ContactAnchor2D(row.FirstAnchor), new ContactAnchor2D(row.SecondAnchor), row.Depth, row
 2422241            mover.Material, supplier.Material, row.DepthIsClamped,
 2422242            group: new ContactGroupKey(0, 0, surfaceB: feature, region: vertex ? 1 : 0, sourceIdB: supplier.Id + 1,
 2422243                sourceOrderB: ((IPhysicsColliderRegistryItem)supplier).ReplayOrder + 1));
 2422244    }
 245
 246    private static ReadOnlySpan<Vector2d> Offsets(LSCollider2D collider, Span<Vector2d> box)
 247    {
 937248        if (collider is LSPolygonCollider2D polygon) return polygon.ScaledLocalVertices;
 3822249        for (int i = 0; i < 4; i++) box[i] = collider.GetScaledLocalVertexUnchecked(i);
 273250        return box;
 251    }
 252
 253    // Outward-rounded native bounds reject only impossible finite crossings;
 254    // borrowed plane support deliberately bypasses this individual-face gate.
 255    private static bool BoundsOverlap(LSCollider2D mover, FixedBoundArea bounds) =>
 23671256        mover.MinX <= bounds.Max.X && mover.MaxX >= bounds.Min.X
 23671257        && mover.MinY <= bounds.Max.Y && mover.MaxY >= bounds.Min.Y;
 258}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.ContinuousCollision.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.ContinuousCollision.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 FixedMathSharp;
 9using FixedMathSharp.Geometry;
 10using Gravitas.Colliders;
 11using Gravitas.CollisionHandling;
 12using SwiftCollections;
 13
 14namespace Gravitas;
 15
 16/// <content>Shares exact boundary and declared-surface ownership with continuous collision.</content>
 17public sealed partial class StaticSurface2D
 18{
 60019    private readonly SwiftList<LSCollider2D> _continuousMixedMembers = new();
 20    private ContactManifold? _continuousMixedContacts;
 8921    internal int ContinuousOrder => ((IPhysicsColliderRegistryItem)_members[0]).ReplayOrder;
 22
 23    private static RationalPoint3d GetMixedContinuousSupport(LSCollider2D member, Vector3d outward)
 24    {
 25        // Handoff needs the exact global extremum in the native yaw chart;
 26        // a rounded inverse direction can select a lower support vertex.
 26727        var frame = new NativePrismYawFrame3d(MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation);
 26728        Fixed64 cap = outward.Y < Fixed64.Zero ? -member.MixedHalfThickness : member.MixedHalfThickness;
 26729        Vector2d vertex = member.GetScaledLocalVertexUnchecked(0);
 26730        RationalPoint3d support = frame.GetPoint(new(vertex.X, cap, vertex.Y));
 213631        for (int index = 1; index < member.VertexCount; index++)
 32        {
 80133            vertex = member.GetScaledLocalVertexUnchecked(index);
 80134            RationalPoint3d candidate = frame.GetPoint(new(vertex.X, cap, vertex.Y));
 100535            if (RationalPoint3d.CompareProjection(candidate, support, outward) > 0) support = candidate;
 36        }
 26737        return support;
 38    }
 39
 40    internal bool IntersectsMixedContinuous(LSCollider mover, Fixed64 padding = default,
 41        Vector3d? separationOutward = null, RationalPoint3d separationPlane = default)
 42    {
 43        try
 44        {
 43545            if (!GatherMixedContinuous(mover, padding)) return true;
 166346            foreach (LSCollider2D member in _continuousMixedMembers.AsReadOnlySpan())
 47            {
 48                // Only a nonnegative full-member gap qualifies. A previously
 49                // handled penetration cannot license skipping another edge.
 57550                if (separationOutward is { } axis && RationalPoint3d.CompareProjection(
 57551                        GetMixedContinuousSupport(member, axis), separationPlane, axis) <= 0) continue;
 39852                if (padding > Fixed64.Zero && ContinuousCollisionBounds.AreSeparated(mover, member, padding)) continue;
 74753                if (CollisionDetectionMixed.IntersectsForContinuousCollision(mover, member, padding)) return true;
 54            }
 8255            return false;
 56        }
 86657        finally { _continuousMixedMembers.Clear(); }
 43358    }
 59
 60    internal void AppendMixedContinuousContacts(LSCollider mover, ContactManifold destination,
 61        Vector3d? separationOutward = null, RationalPoint3d separationPlane = default)
 62    {
 63        try
 64        {
 11165            GatherMixedContinuous(mover, Fixed64.Zero);
 11166            ContactManifold emitted = destination;
 11167            if (separationOutward.HasValue)
 68            {
 669                emitted = _continuousMixedContacts ??= new();
 670                emitted.BeginUpdate(_context.FrameCount);
 71            }
 72            // Native emission regathers projected suppliers; keep the physical
 73            // carrier inventory separate while those existing owners run.
 63874            foreach (LSCollider2D member in _continuousMixedMembers.AsReadOnlySpan())
 20875                CollisionDetectionMixed.AppendManifold(mover, member, emitted, 0, 0, surfaceResponse: true);
 11176            if (separationOutward is { } axis)
 77            {
 2678                for (int groupIndex = 0; groupIndex < emitted.GroupCount; groupIndex++)
 79                {
 780                    ref ContactGroup group = ref emitted.GetGroup(groupIndex);
 81                    // A carrier may borrow an unsolved supplier's wall row.
 82                    // Filter by actual provenance only after native emission.
 783                    if (_context.Physics2D.TryGetColliderById(group.Key.SourceIdB - 1, out var supplier)
 784                        && supplier!.StaticSurface == this && RationalPoint3d.CompareProjection(
 785                            GetMixedContinuousSupport(supplier, axis), separationPlane, axis) <= 0) continue;
 4286                    for (int row = 0; row < group.Count; row++) destination.AddContact(group.Key, group[row]);
 87                }
 88            }
 11189        }
 33390        finally { _continuousMixedMembers.Clear(); _continuousMixedContacts?.Reset(); }
 11191    }
 92
 93    private bool GatherMixedContinuous(LSCollider mover, Fixed64 padding)
 94    {
 54495        _continuousMixedMembers.Clear();
 54496        FixedBoundBox bounds = mover.Bounds;
 54497        if (padding > Fixed64.Zero)
 98        {
 5199            Vector3d expansion = Vector3d.One * padding;
 51100            if (!Vector3d.TrySubtract(bounds.Min, expansion, out Vector3d minimum)
 53101                || !Vector3d.TryAdd(bounds.Max, expansion, out Vector3d maximum)) return false;
 49102            bounds = FixedBoundBox.FromMinMax(minimum, maximum);
 103        }
 542104        GatherMixedMembers(mover, bounds, _continuousMixedMembers);
 542105        return true;
 106    }
 107
 108    internal bool AdmitContinuousWitness(LSCollider2D mover, LSCollider2D target,
 109        in ContactAnchor2D witness)
 110    {
 16111        Gather(mover);
 16112        bool same = _local.Count == _prepared.Count;
 110113        for (int i = 0; same && i < _local.Count; i++) same = _local[i] == _prepared[i];
 19114        if (!same) Prepare();
 76115        for (int member = 0; member < _local.Count; member++)
 116        {
 32117            if (_local[member] != target) continue;
 100118            foreach (var span in _domains[member].Spans)
 42119                if (WideConvex2dRelations.LocateBoundaryPoint(witness.GeometryPoint, target.Center,
 42120                    target.ConvexRotation, new FixedSegment2d(span.Start, span.End), span.Interval) >= 0)
 121                {
 10122                    BuildFan(member, witness.GeometryPoint);
 13123                    if (mover is not (LSCircleCollider2D or LSCapsuleCollider2D)) return true;
 7124                    WideDirection3d axis = WideCenteredCapsule2dRelations.GetPointToCoreDirection(mover.Center, mover.Ro
 7125                        mover is LSCapsuleCollider2D capsule ? capsule.AxisLength : Fixed64.Zero, witness.GeometryPoint)
 126                    // A rounded witness must still support its own finite polygon
 127                    // before its radial direction can exclude an incident neighbor.
 7128                    if (!WideConvex2dRelations.SupportsBoundaryFan(axis, witness.GeometryPoint,
 9129                            _fan.AsReadOnlySpan()[..target.VertexCount])) return true;
 5130                    return WideConvex2dRelations.SupportsBoundaryFan(axis, witness.GeometryPoint, _fan.AsReadOnlySpan())
 131                }
 132        }
 6133        return true;
 134    }
 135
 136    internal bool AdmitMixedContinuousWitness(LSCollider mover, Vector3d proxyCenter, LSCollider2D target,
 137        in ContactAnchor witness)
 138    {
 139        // The caller proves an exact sphere projection of a sphere/capsule;
 140        // these native rounded sources always use the scalar-yaw prism chart.
 141        System.Diagnostics.Debug.Assert(mover is LSSphereCollider or LSCapsuleCollider);
 33142        GatherMixed(mover, mover.CanonicalCenteredProxyRadius * Fixed64.Two);
 33143        RationalPoint3d point = RationalPoint3d.FromAnchor(witness.GeometryPoint);
 33144        WideDirection3d axis = WideTriangleRelations.GetScaledPointDifference(RationalPoint3d.FromScalarPoint(proxyCente
 33145            point, WideArithmetic.TruncateSigned320By64(point.Denominator));
 33146        RationalPoint3d footprint = new(point.X, default, point.Z, point.Denominator);
 33147        int source = -1;
 198148        for (int member = 0; member < _mixedLocal.Count; member++)
 95149            if (_mixedLocal[member] == target) source = member;
 37150        if (source < 0) return true;
 29151        if (RationalPoint3d.CompareProjection(point, RationalPoint3d.FromScalarPoint(target.MixedBounds3D.Min), Vector3d
 34152            || RationalPoint3d.CompareProjection(point, RationalPoint3d.FromScalarPoint(target.MixedBounds3D.Max), Vecto
 24153        bool onBoundary = false;
 240154        foreach (var span in _mixedPrisms[source].Bands[0].Boundary.Spans)
 96155            onBoundary |= Locate(source, span) >= 0;
 28156        if (!onBoundary) return true;
 40157        _mixedFan.FastClear(); _mixedFan.Add(source);
 68158        for (int cursor = 0; cursor < _mixedFan.Count; cursor++)
 159        {
 50160            int member = _mixedFan[cursor]; MixedPrism prism = _mixedPrisms[member];
 161            // Own-prism failure leaves the rounded witness unproved; only a
 162            // neighbor can exclude a certified radial support at the join.
 353163            foreach (Vector3d vertex in prism.Points)
 164            {
 157165                RationalPoint3d incident = prism.NativeFrame.GetPoint(vertex);
 157166                if (WideDirection3d.Dot(axis, WideTriangleRelations.GetScaledPointDifference(incident, point,
 168167                    WideArithmetic.TruncateSigned320By64(point.Denominator))).Sign > 0) return cursor == 0;
 168            }
 72169            for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 170            {
 22171                MixedBand band = prism.Bands[bandIndex];
 44172                Vector3d lower = new(Fixed64.Zero, band.Lower, Fixed64.Zero), upper = new(Fixed64.Zero, band.Upper, Fixe
 44173                RationalPoint3d a = prism.NativeFrame.GetPoint(lower), b = prism.NativeFrame.GetPoint(upper);
 22174                if (RationalPoint3d.CompareProjection(point, a, Vector3d.Up) < 0
 22175                    || RationalPoint3d.CompareProjection(point, b, Vector3d.Up) > 0) continue;
 140176                foreach (var span in band.Boundary.Spans)
 56177                    if (span.Kind == SpanKind.Joined && !_mixedFan.Contains(span.OtherMember)
 61178                        && Locate(member, span) >= 0) _mixedFan.Add(span.OtherMember);
 179            }
 180        }
 9181        return true;
 182
 183        int Locate(int member, BoundarySpan2D span)
 184        {
 185            MixedPrism prism = _mixedPrisms[member];
 186            FixedSegment edge = new(new(span.Start.X, Fixed64.Zero, span.Start.Y), new(span.End.X, Fixed64.Zero, span.En
 187            return WideTriangleRelations.LocatePointOnFrameEdge(footprint, edge, prism.NativeFootFrame, span.Interval);
 188        }
 189    }
 190}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.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.Geometry;
 10using Gravitas.Colliders;
 11using SwiftCollections;
 12
 13namespace Gravitas;
 14
 15/// <summary>Declares continuity between registered static AABB or convex polygon colliders in one context.</summary>
 16/// <remarks>
 17/// Exact shared boundary spans participate in one filled planar surface while members
 18/// retain their collider identities, materials, queries and overlap events.
 19/// Mixed contacts also preserve each member's finite embedded height and thickness.
 20/// Create declarations through <see cref="GravitasPhysics2DService.CreateStaticSurface"/>.
 21/// Context reset or disposal ends the declaration's lifetime.
 22/// </remarks>
 23/// <content>Owns typed member lifetime, transactional replacement and contact invalidation.</content>
 24public sealed partial class StaticSurface2D : IDisposable, Chronicler.IRecordable
 25{
 26    private readonly GravitasWorldContext _context;
 60027    private LSCollider2D[] _members = Array.Empty<LSCollider2D>();
 60028    private FixedBoundBox[] _memberBounds = Array.Empty<FixedBoundBox>();
 60029    private readonly SwiftHashSet<int> _changedSuppliers = new();
 30    private bool _disposed;
 239831    internal int ReplayMembership => _members.Length == 0 ? 0 : _members[0].ReplayOrdinal + 1;
 32
 60033    internal StaticSurface2D(GravitasWorldContext context, ReadOnlySpan<LSCollider2D> members)
 34    {
 60035        _context = context;
 60036        _mixedAdmit = AdmitMixedAxis;
 60037        _mixedSphereAdmit = AdmitMixedSpherePoint;
 60038        _mixedCapsuleAdmit = AdmitMixedPrismSupportPoint;
 60039        _mixedSphereBoundaryAdmit = AdmitMixedSphereBoundaryPoint;
 60040        _mixedAdmitRigid = AdmitMixedRigidAxis;
 60041        ReplaceMembers(members);
 59742    }
 43
 44    /// <summary>Atomically replaces the registered members of this declaration.</summary>
 45    /// <param name="members">Distinct active AABB or convex polygon colliders with bodyless or explicit-static ownershi
 46    /// <remarks>
 47    /// Call between complete fixed steps. Compound roots and leaves are ineligible.
 48    /// Rejection preserves the previous membership; disconnected pieces retain their boundaries.
 49    /// Deactivated members must be explicitly added again after reinitialization.
 50    /// </remarks>
 51    /// <exception cref="ArgumentException">A member is ineligible or belongs to another declaration.</exception>
 52    /// <exception cref="ObjectDisposedException">This declaration or its context has ended.</exception>
 53    /// <exception cref="InvalidOperationException">A fixed step is in progress.</exception>
 54    public void ReplaceMembers(ReadOnlySpan<LSCollider2D> members)
 55    {
 65356        _context.ThrowIfDisposed();
 65257        _context.ThrowIfFixedStepMutationNotAllowed();
 65558        if (_disposed) throw new ObjectDisposedException(nameof(StaticSurface2D));
 64759        LSCollider2D[] next = members.ToArray();
 64760        var unique = new SwiftHashSet<LSCollider2D>();
 412861        foreach (LSCollider2D member in next)
 62        {
 63            // Registry identity excludes stale lifetimes even when an ID has been reused.
 142664            if (member is not (LSAABBoxCollider2D or LSPolygonCollider2D)
 142665                || !unique.Add(member) || member.CompoundOwner != null
 142666                || !_context.Physics2D.TryGetColliderById(member.Id, out var registered) || registered != member
 142667                || !member.IsStatic || !member.IsActive || member.IsDeactivationInProgress
 142668                || member.StaticSurface != null && member.StaticSurface != this)
 1869                throw new ArgumentException("Members must be distinct registered static AABB or convex polygon colliders
 70        }
 62971        bool unchanged = next.Length == _members.Length;
 140872        foreach (LSCollider2D member in _members) unchanged &= unique.Contains(member);
 64273        if (unchanged) return;
 61674        Array.Sort(next, static (first, second) => ((IPhysicsColliderRegistryItem)first).ReplayOrder
 61675            .CompareTo(((IPhysicsColliderRegistryItem)second).ReplayOrder));
 76        // Publish associations only after every candidate has passed admission.
 61677        var bounds = new FixedBoundBox[next.Length];
 541178        for (int index = 0; index < next.Length; index++) bounds[index] = next[index].MixedBounds3D;
 61679        LSCollider2D[] previousMembers = _members;
 132680        foreach (LSCollider2D previous in previousMembers)
 7481            if (!unique.Contains(previous)) Invalidate(previous);
 137382        foreach (LSCollider2D previous in previousMembers) previous.StaticSurface = null;
 123283        _members = next; _memberBounds = bounds;
 541184        foreach (LSCollider2D member in _members) member.StaticSurface = this;
 401885        foreach (LSCollider2D member in _members)
 276686            if (Array.IndexOf(previousMembers, member) < 0) Invalidate(member);
 61687    }
 88
 89    internal void Invalidate(LSCollider2D? changed = null, bool includeNeighbors = true)
 90    {
 213091        InvalidateGeometry();
 213092        _changedSuppliers.Clear();
 426093        FixedBoundBox before = default, after = default;
 213094        if (changed != null)
 95        {
 153396            int index = Array.IndexOf(_members, changed);
 306697            before = _memberBounds[index]; after = changed.MixedBounds3D;
 153398            _memberBounds[index] = after;
 99        }
 15224100        for (int index = 0; index < _members.Length; index++)
 5482101            if (changed == null || _members[index] == changed || includeNeighbors
 5482102                && (Touches(_memberBounds[index], before) || Touches(_memberBounds[index], after)))
 103            {
 4793104                _changedSuppliers.Add(_members[index].Id + 1);
 4793105                _members[index].MarkContactDependencyChanged(notifySurface: false);
 106            }
 15224107        foreach (LSCollider2D member in _members)
 5482108            _context.Physics2D.ClearWarmStartCachesForCollider(member, _changedSuppliers);
 2130109        _context.MixedCollisions.InvalidateSurfaceContacts(null, this, _changedSuppliers);
 2130110        _changedSuppliers.Clear();
 2130111    }
 112
 113    private bool Touches(in FixedBoundBox first, in FixedBoundBox second) =>
 3204114        _context.Settings.RuntimeMode == PhysicsRuntimeMode.Mixed ? first.Intersects(second)
 3204115        : FixedBoundArea.FromMinMax(new(first.Min.X, first.Min.Z), new(first.Max.X, first.Max.Z)).Intersects(
 3204116            FixedBoundArea.FromMinMax(new(second.Min.X, second.Min.Z), new(second.Max.X, second.Max.Z)));
 117
 118    partial void InvalidateGeometry();
 119
 120    internal void Remove(LSCollider2D member)
 121    {
 26122        int index = Array.IndexOf(_members, member);
 27123        if (index < 0) return;
 25124        Invalidate(member);
 25125        member.StaticSurface = null;
 25126        Array.Copy(_members, index + 1, _members, index, _members.Length - index - 1);
 25127        Array.Copy(_memberBounds, index + 1, _memberBounds, index, _memberBounds.Length - index - 1);
 25128        Array.Resize(ref _members, _members.Length - 1);
 25129        Array.Resize(ref _memberBounds, _members.Length);
 25130    }
 131
 132    /// <summary>Ends this declaration and restores independent member response.</summary>
 133    /// <remarks>Call between complete fixed steps. Members remain registered. Repeated disposal is harmless.</remarks>
 134    /// <exception cref="InvalidOperationException">A fixed step is in progress.</exception>
 135    public void Dispose()
 136    {
 605137        if (_disposed) return;
 585138        _context.ThrowIfFixedStepMutationNotAllowed();
 584139        Release();
 584140        _context.Physics2D.RemoveStaticSurface(this);
 584141    }
 142
 143    internal void Release()
 144    {
 597145        Invalidate();
 5157146        foreach (LSCollider2D member in _members) member.StaticSurface = null;
 597147        _members = Array.Empty<LSCollider2D>();
 597148        _memberBounds = Array.Empty<FixedBoundBox>();
 597149        _disposed = true;
 597150    }
 151}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.Mixed.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.Mixed.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 Gravitas.Colliders;
 13using Gravitas.CollisionHandling;
 14using Gravitas.Support;
 15using SwiftCollections;
 16
 17namespace Gravitas;
 18
 19/// <content>Admits finite exposed prism supports before native mixed response selection.</content>
 20public sealed partial class StaticSurface2D : IScaledConvexHullContactDomain
 21{
 60022    private readonly SwiftList<LSCollider2D> _mixedLocal = new();
 60023    private readonly SwiftList<MixedPrism> _mixedPrisms = new();
 120024    private readonly SwiftList<MixedSample> _mixedSamples = new(), _mixedPool = new();
 60025    private readonly SwiftList<MixedGroup> _mixedGroups = new();
 60026    private readonly SwiftHashSet<int> _mixedOverlaps = new();
 60027    private readonly SwiftList<RationalSegmentInterval> _mixedIntervals = new();
 60028    private readonly SwiftList<int> _mixedFan = new();
 60029    private readonly SwiftList<Fixed64> _mixedHeights = new();
 30    private int _mixedEdgeStart, _mixedEdgeEnd;
 60031    private readonly RationalSegmentInterval[] _mixedEdgeClip = new RationalSegmentInterval[1];
 132    private static readonly RationalSegmentInterval[] MixedFullInterval = { default };
 60033    private readonly Vector3d[] _mixedBox = new Vector3d[8];
 60034    private Vector3d[] _mixedFace = new Vector3d[4];
 180035    private int[] _mixedFaceTriangles = new int[6], _mixedFaceEdges = new int[8], _mixedComponents = Array.Empty<int>();
 36    private readonly ScaledHullPenetrationAdmission _mixedAdmit;
 37    private readonly PointSpanPenetrationAdmission _mixedAdmitRigid;
 38    private WidePointSpanPenetration _mixedRigidPenetration;
 39    private bool _mixedUsingRigid;
 40    private LSCollider? _mixedMoving;
 41    private ScaledRigidFrame3d _mixedMovingFrame;
 42    private uint _mixedMovingBroad, _mixedMovingDependency;
 43    private Vector3d _mixedMovingCenter;
 44    private FixedQuaternion _mixedMovingRotation;
 45    private bool _mixedCurrent, _mixedQuaternion;
 46    private Fixed64 _mixedReach, _mixedRequestedReach;
 60047    private int _mixedMember, _mixedGroup, _mixedSupplier, _mixedPreparedCount = -1;
 148    private static readonly IComparer<MixedSample> MixedPointOrder = Comparer<MixedSample>.Create(static (a, b) =>
 149    {
 150        int order = a.Contact.SecondAnchor.CompareLocalFeature(b.Contact.SecondAnchor);
 151        return order != 0 ? order : a.Supplier.CompareTo(b.Supplier);
 152    });
 53
 991854    private ReadOnlySpan<Vector3d> MixedMovingPoints => _mixedMoving is LSMeshCollider mesh
 991855        ? _mixedMovingFeature >= 0 ? _mixedPatchPoints.AsReadOnlySpan() : mesh.Mesh.GeometryVertices : _mixedBox;
 898056    private ReadOnlySpan<int> MixedMovingTriangles => _mixedMoving is LSMeshCollider mesh
 898057        ? _mixedMovingFeature >= 0 ? _mixedPatchTriangles.AsReadOnlySpan() : mesh.Mesh.Triangles : WideOrientedBox.BoxHu
 932258    private ReadOnlySpan<int> MixedMovingEdges => _mixedMoving is LSMeshCollider mesh
 932259        ? _mixedMovingFeature >= 0 ? _mixedPatchEdges.AsReadOnlySpan() : mesh.Mesh.ConvexSatEdgeVertexPairs : WideOrient
 60
 61    internal bool AppendMixed(LSCollider mover, LSCollider2D overlap, ContactManifold destination,
 62        int namespace3D, int namespace2D)
 63    {
 742464        if (_members.Length == 1)
 1465            return CollisionDetectionMixed.AppendManifold(mover, overlap, destination, namespace3D, namespace2D, false);
 741066        bool current = _mixedCurrent && _mixedMoving == mover && _mixedMovingBroad == mover.BroadPhaseVersion
 741067            && _mixedMovingDependency == (mover.CompoundOwner ?? mover).ContactDependencyVersion
 741068            && _mixedMovingCenter == mover.Center && _mixedMovingRotation == mover.Rotation;
 1239269        if (!current) _mixedReach = mover.CanonicalCenteredProxyRadius * Fixed64.Two;
 70        while (true)
 71        {
 797072            GatherMixed(mover, _mixedReach);
 797073            if (current && _mixedCurrent) break;
 554374            _mixedMoving = mover;
 554375            _mixedMovingFrame = mover is LSMeshCollider mesh ? mesh.Mesh.GeometryFrame
 554376                : ScaledRigidFrame3d.Rigid(mover.Center, mover.Rotation);
 644977            if (mover is LSCuboidCollider box) WideOrientedBox.GetBoxHullVertices(box.OrientedBox.HalfExtents, _mixedBox
 554378            _mixedRequestedReach = _mixedReach;
 554379            _mixedMovingFeature = -1;
 665480            if (mover is LSCapsuleCollider capsule && capsule.AxisLength > Fixed64.Zero) BuildMixedCapsule();
 614781            else if (mover is LSSphereCollider or LSCapsuleCollider) BuildMixedSphere();
 334982            else if (mover is LSCylinderCollider or LSConeCollider) BuildMixedCurved();
 208583            else BuildMixed();
 554384            if (_mixedRequestedReach > _mixedReach)
 85            {
 86                // A deep placement can project beyond the body's initial query.
 87                // Grow only to a considered native SAT exit, never a guessed iteration budget.
 168088                _mixedReach = _mixedRequestedReach; current = false; continue;
 89            }
 996690            _mixedMovingBroad = mover.BroadPhaseVersion; _mixedMovingDependency = (mover.CompoundOwner ?? mover).Contact
 1494991            _mixedMovingCenter = mover.Center; _mixedMovingRotation = mover.Rotation; _mixedCurrent = true;
 92            break;
 93        }
 4423894        for (int member = 0; member < _mixedLocal.Count; member++)
 95            // Keep a mesh's native patch inventory when it leaves the seam's
 96            // neighborhood; switching back to individual triangles changes response.
 1603097            if (_mixedLocal[member] == overlap && !_mixedPrisms[member].Joined && _mixedMovingFeature < 0)
 132198                return CollisionDetectionMixed.AppendManifold(mover, overlap, destination, namespace3D, namespace2D, fal
 608999        if (mover is LSCapsuleCollider supportedCapsule && supportedCapsule.AxisLength > Fixed64.Zero)
 1777100            return AppendMixedCapsule(overlap, destination, namespace3D, namespace2D);
 4312101        if (mover is LSSphereCollider or LSCapsuleCollider)
 1195102            return AppendMixedSphere(overlap, destination, namespace3D, namespace2D);
 3117103        if (mover is LSCylinderCollider or LSConeCollider)
 1166104            return AppendMixedCurved(overlap, destination, namespace3D, namespace2D);
 1951105        Span<int> chosen = stackalloc int[ContactManifold.MaxContactsPerGroup];
 8196106        for (int group = 0; group < _mixedGroups.Count; group++)
 107        {
 2147108            MixedGroup response = _mixedGroups[group];
 2147109            if (response.Carrier != overlap.Id) continue;
 1425110            _mixedPool.FastClear();
 26506111            foreach (MixedSample sample in _mixedSamples.AsReadOnlySpan()) if (sample.Group == group) _mixedPool.Add(sam
 1425112            _mixedPool.SortInPlace(MixedPointOrder);
 1425113            int count = Math.Min(chosen.Length, _mixedPool.Count);
 12518114            for (int slot = 0; slot < count; slot++)
 4834115                chosen[slot] = slot == 0 ? 0 : MeshPlaneSampleReduction.ChooseNext(_mixedPool.AsReadOnlySpan(),
 4834116                    chosen[..slot], response.Axis, MixedPointOrder);
 12518117            for (int slot = 0; slot < count; slot++)
 118            {
 9668119                MixedSample sample = _mixedPool[chosen[slot]]; LSCollider2D supplier = _mixedLocal[sample.Supplier];
 4834120                FixedContactAnchors contact = sample.Contact;
 4834121                destination.AddContact(new ContactAnchor(contact.FirstAnchor), new ContactAnchor(contact.SecondAnchor),
 4834122                    contact.Depth, contact.Normal, mover.Material, supplier.Material, contact.DepthIsClamped,
 4834123                    featureNamespaceA: namespace3D, featureNamespaceB: namespace2D,
 4834124                    group: new ContactGroupKey(namespace3D, namespace2D,
 4834125                        surfaceA: response.Feature < 0 ? 0 : ((LSMeshCollider)mover).Mesh.GetCanonicalSurfaceOrdinal(res
 4834126                        region: group, sourceIdB: supplier.Id + 1,
 4834127                        sourceOrderB: ((IPhysicsColliderRegistryItem)supplier).ReplayOrder + 1));
 128            }
 129        }
 1951130        return _mixedOverlaps.Contains(overlap.Id);
 131    }
 132
 133    private void RequestMixedReach(Fixed64 depth)
 134    {
 3898135        Fixed64 reach = _mixedMoving!.CanonicalCenteredProxyRadius + depth + Fixed64.MinIncrement + Fixed64.MinIncrement
 3923136        if (reach > _mixedRequestedReach) _mixedRequestedReach = reach;
 3898137    }
 138
 139    private void GatherMixed(LSCollider mover, Fixed64 reach)
 140    {
 8003141        FixedBoundBox bounds = FixedBoundBox.FromCenterAndScopeClippedToDomain(mover.Center,
 8003142            Vector3d.One * reach);
 8003143        int previous = _mixedLocal.Count;
 8003144        GatherMixedMembers(mover, bounds, _mixedLocal);
 8569145        if (previous != _mixedLocal.Count) _mixedCurrent = false;
 8003146        bool quaternion = mover is LSMeshCollider;
 8003147        bool prepared = _mixedQuaternion == quaternion && _mixedPreparedCount == _mixedLocal.Count;
 10003148        while (_mixedPrisms.Count < _mixedLocal.Count) _mixedPrisms.Add(new MixedPrism());
 50794149        for (int member = 0; member < _mixedLocal.Count; member++)
 17394150            prepared &= _mixedPrisms[member].Matches(_mixedLocal[member]);
 9716151        if (!prepared) { _mixedQuaternion = quaternion; PrepareMixed(); _mixedCurrent = false; }
 152
 8003153    }
 154
 155    private void GatherMixedMembers(LSCollider mover, FixedBoundBox bounds, SwiftList<LSCollider2D> destination)
 156    {
 8545157        _context.MixedCollisions.Collect2DCandidatesInMixedBounds(bounds.Min, bounds.Max, PhysicsLayerMask.All,
 8545158            _candidates, staticStyleOnly: true, cachePartitionRefresh: true);
 8545159        destination.FastClear();
 54116160        foreach (LSCollider2D candidate in _candidates.AsReadOnlySpan())
 18513161            if (candidate.StaticSurface == this && !candidate.IsTrigger
 36926162                && _context.MixedCollisions.RequireCollisionPair(mover.CompoundOwner ?? mover, candidate)) destination.A
 8545163        destination.SortInPlace(SurfaceMemberOrder);
 8545164    }
 165
 166    private void PrepareMixed()
 167    {
 571168        _mixedSphereConcavityCurrent = false;
 571169        _mixedBoundaryLinesCurrent = false;
 571170        _mixedCurvedDomainsCurrent = false;
 571171        _mixedPreparedCount = _mixedLocal.Count;
 1015172        if (_mixedComponents.Length < _mixedLocal.Count) Array.Resize(ref _mixedComponents, _mixedLocal.Count);
 3814173        for (int member = 0; member < _mixedLocal.Count; member++)
 174        {
 1336175            _mixedPrisms[member].Prepare(_mixedLocal[member], _mixedQuaternion);
 1336176            _mixedPrisms[member].Joined = false;
 1336177            PrepareMixedBands(member);
 1336178            _mixedComponents[member] = member;
 179        }
 3814180        for (int member = 0; member < _mixedLocal.Count; member++)
 7032181            for (int band = 0; band < _mixedPrisms[member].BandCount; band++)
 22834182                foreach (var span in _mixedPrisms[member].Bands[band].Boundary.Spans)
 9237183                    if (span.Kind == SpanKind.Joined)
 184                    {
 2238185                        _mixedPrisms[member].Joined = true;
 4476186                        int from = _mixedComponents[span.OtherMember], to = _mixedComponents[member];
 22532187                        for (int index = 0; index < _mixedLocal.Count; index++)
 15313188                            if (_mixedComponents[index] == from) _mixedComponents[index] = to;
 189                    }
 571190    }
 191
 192    private void PrepareMixedBands(int member)
 193    {
 1336194        MixedPrism prism = _mixedPrisms[member];
 1336195        Fixed64 half = _mixedLocal[member].MixedHalfThickness;
 4008196        _mixedHeights.FastClear(); _mixedHeights.Add(-half); _mixedHeights.Add(half);
 10588197        for (int other = 0; other < _mixedLocal.Count; other++)
 3958198            if (TryGetMixedHeights(member, other, out Fixed64 lower, out Fixed64 upper))
 199            {
 4427200                if (lower > -half && lower < half) _mixedHeights.Add(lower);
 4445201                if (upper > -half && upper < half) _mixedHeights.Add(upper);
 202            }
 1336203        _mixedHeights.SortInPlace();
 1336204        int count = 0;
 7384205        for (int height = 1; height < _mixedHeights.Count; height++)
 206        {
 4712207            Fixed64 lower = _mixedHeights[height - 1], upper = _mixedHeights[height];
 2356208            if (lower == upper) continue;
 3584209            if (prism.Bands.Count == count) prism.Bands.Add(new MixedBand());
 2180210            MixedBand band = prism.Bands[count++];
 4360211            band.Lower = lower; band.Upper = upper;
 2180212            band.Boundary.Build(_mixedLocal.AsReadOnlySpan(), member, mixed: _mixedQuaternion,
 2180213                lowerHeight: lower, upperHeight: upper);
 214        }
 1336215        prism.BandCount = count;
 1336216    }
 217
 218    private void BuildMixed()
 219    {
 6255220        _mixedSamples.FastClear(); _mixedGroups.FastClear(); _mixedOverlaps.Clear();
 4170221        _mixedRegions.FastClear(); _mixedRegionParents.FastClear();
 2085222        if (_mixedMoving is LSMeshCollider mesh && (mesh.Mode != MeshColliderMode.Convex || !mesh.Mesh.IsClosedSurface))
 322223            BuildMixedMesh(mesh.Mesh);
 1763224        else BuildMixedPart();
 2085225        CompleteMixedRegions();
 2085226    }
 227
 228    private void BuildMixedPart()
 229    {
 11416230        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 231        {
 3595232            MixedPrism prism = _mixedPrisms[_mixedMember];
 3595233            if (!_mixedMoving!.Bounds.Intersects(_mixedLocal[_mixedMember].MixedBounds3D)) continue;
 2846234            bool hit = _mixedQuaternion ? FindMixedPenetration(prism.Frame, prism, out var penetration)
 2846235                : FindMixedPenetration(prism.NativeFrame, prism, out penetration);
 2846236            if (!hit) continue;
 2619237            _mixedOverlaps.Add(_mixedLocal[_mixedMember].Id);
 3975238            if (!prism.Joined && _mixedMovingFeature < 0) { HasMixedReach(penetration); continue; }
 1941239            if (!AdmitMixedAxis(penetration))
 240            {
 223241                if (_mixedRequestedReach > _mixedReach) return;
 329242                if (_mixedQuaternion) FindMixedPenetration(prism.Frame, prism, out penetration, _mixedAdmit);
 105243                else FindMixedPenetration(prism.NativeFrame, prism, out penetration, _mixedAdmit);
 244            }
 1989245            if (_mixedRequestedReach > _mixedReach) return;
 1887246            if (!penetration.HasValue) continue;
 1885247            _mixedGroup = FindMixedGroup(penetration);
 1885248            if (IsMixedFaceAxis(penetration) && HasMixedFaceRegion(_mixedGroup)) continue;
 1443249            if (_mixedGroup == _mixedGroups.Count)
 1414250                _mixedGroups.Add(new(_mixedComponents[_mixedMember], _mixedLocal[_mixedMember].Id, penetration, _mixedMo
 1443251            VisitMixed(penetration, false);
 252        }
 2113253    }
 254
 255    private bool FindMixedPenetration<TFrame>(in TFrame frame, MixedPrism prism, out WideScaledHullPenetration penetrati
 256        ScaledHullPenetrationAdmission? admission = null) where TFrame : struct, IForwardHullFrame3d
 257    {
 3063258        _mixedUsingRigid = _mixedMovingFrame.IsRigid && prism.Rigid;
 3063259        if (_mixedUsingRigid)
 260        {
 2929261            bool hit = WideOrientedBox.TryGetConvexHullPenetration(_mixedMovingFrame.RigidOrigin, _mixedMovingFrame.Rota
 2929262                MixedMovingPoints, MixedMovingTriangles, MixedMovingEdges, prism.Frame.RigidOrigin, prism.Frame.Rotation
 2929263                prism.Points, prism.Triangles, prism.Edges, out WidePointSpanPenetration selected,
 2929264                skipParallelDirections: true, admission: admission == null ? null : _mixedAdmitRigid);
 265            // Admission borrows the current candidate for rigid visitation;
 266            // it must not alias the SAT accumulator through this field.
 2929267            _mixedRigidPenetration = selected;
 2929268            penetration = new(_mixedRigidPenetration);
 2929269            return hit;
 270        }
 134271        return WideOrientedBox.TryGetConvexHullPenetration(_mixedMovingFrame, MixedMovingPoints, MixedMovingTriangles,
 134272            MixedMovingEdges, frame, prism.Points, prism.Triangles, prism.Edges, out penetration,
 134273            skipParallelDirections: true, admission: admission);
 274    }
 275
 276    private bool AdmitMixedRigidAxis(in WidePointSpanPenetration penetration)
 277    {
 1623278        _mixedRigidPenetration = penetration;
 1623279        return AdmitMixedAxis(new WideScaledHullPenetration(penetration));
 280    }
 281
 282    private bool AdmitMixedAxis(in WideScaledHullPenetration penetration) =>
 3783283        HasMixedReach(penetration) && (IsMixedFaceAxis(penetration) && HasMixedFaceRegion(FindMixedGroup(penetration))
 3783284        || VisitMixed(penetration, true) > 0);
 285
 286    private bool HasMixedReach(in WideScaledHullPenetration penetration)
 287    {
 288        // Every source support point is within its radius; projecting it to
 289        // this plane adds at most the exact depth. One raw unit raises the
 290        // nearest depth outward; another covers final anchor rounding.
 4461291        Fixed64 reach = _mixedMoving!.CanonicalCenteredProxyRadius
 4461292            + penetration.GetRoundedDepth(out _) + Fixed64.MinIncrement + Fixed64.MinIncrement;
 8566293        if (reach <= _mixedReach) return true;
 457294        if (reach > _mixedRequestedReach) _mixedRequestedReach = reach;
 356295        return false;
 296    }
 297
 298    private int VisitMixed(in WideScaledHullPenetration penetration, bool admissionOnly)
 299    {
 300        // Select the original prism's actual feature. A remote coplanar face
 301        // must not suppress a disconnected vertex/edge supplier on this plane.
 7919302        if (IsMixedFaceAxis(penetration)) return VisitMixedFaces(penetration, admissionOnly);
 909303        MixedPrism prism = _mixedPrisms[_mixedMember];
 909304        _mixedSupplier = _mixedMember;
 909305        return _mixedQuaternion ? VisitMixedEdges(prism.Frame, prism, penetration, admissionOnly)
 909306            : VisitMixedEdges(prism.NativeFrame, prism, penetration, admissionOnly);
 307    }
 308
 309    private bool IsMixedFaceAxis(in WideScaledHullPenetration penetration)
 310    {
 9728311        MixedPrism prism = _mixedPrisms[_mixedMember];
 9728312        WideDirection3d axis = penetration.Negate ? -penetration.Axis : penetration.Axis;
 9728313        return _mixedQuaternion ? SupportsFace(prism.Frame) : SupportsFace(prism.NativeFrame);
 314        bool SupportsFace<TFrame>(TFrame frame) where TFrame : struct, IForwardHullFrame3d
 315        {
 316            Signed832 support = WideOrientedBox.GetScaledHullSupport(frame, prism.Points, axis, false);
 317            for (int triangle = 0; triangle < prism.Triangles.Length; triangle += 3)
 318                if (WideOrientedBox.IsScaledHullSupport(frame.GetPoint(prism.Points[prism.Triangles[triangle]]), axis, s
 319                    && WideOrientedBox.IsScaledHullSupport(frame.GetPoint(prism.Points[prism.Triangles[triangle + 1]]), 
 320                    && WideOrientedBox.IsScaledHullSupport(frame.GetPoint(prism.Points[prism.Triangles[triangle + 2]]), 
 321            return false;
 322        }
 323    }
 324
 325
 326    private int VisitMixedEdges<TFrame>(in TFrame frame, MixedPrism prism, in WideScaledHullPenetration penetration,
 327        bool admissionOnly) where TFrame : struct, IForwardHullFrame3d
 328    {
 909329        WideDirection3d axis = penetration.Negate ? -penetration.Axis : penetration.Axis;
 909330        Signed832 support = WideOrientedBox.GetScaledHullSupport(frame, prism.Points, axis, false);
 1818331        int count = 0; bool hasEdge = false;
 22170332        for (int edge = 0; edge < prism.Edges.Length; edge += 2)
 333        {
 20542334            int start = prism.Edges[edge], end = prism.Edges[edge + 1];
 10271335            if (!WideOrientedBox.IsScaledHullSupport(frame.GetPoint(prism.Points[start]), axis, support)
 10271336                || !WideOrientedBox.IsScaledHullSupport(frame.GetPoint(prism.Points[end]), axis, support)) continue;
 598337            hasEdge = true;
 2869338            foreach (var clip in GetMixedEdgeIntervals(start, end))
 339            {
 884340                int firstSample = _mixedSamples.Count;
 884341                count += VisitMixedEdgeInterval(frame, prism, start, end, clip, penetration, admissionOnly);
 1024342                if (!admissionOnly) AddMixedRegion(_mixedMember, -1, default, default, default, firstSample,
 140343                    edgeStart: start, edgeEnd: end, edgeInterval: clip);
 979344                if (admissionOnly && count > 0) return count;
 345            }
 346        }
 1317347        if (hasEdge) return count;
 2874348        for (int vertex = 0; vertex < prism.Points.Length; vertex++)
 349        {
 1437350            if (!WideOrientedBox.IsScaledHullSupport(frame.GetPoint(prism.Points[vertex]), axis, support)) continue;
 311351            int firstSample = _mixedSamples.Count;
 311352            count += VisitMixedEdgeInterval(frame, prism, vertex, vertex, default, penetration, admissionOnly);
 312353            if (!admissionOnly) AddMixedRegion(_mixedMember, -1, default, default, default, firstSample,
 1354                edgeStart: vertex, edgeEnd: vertex);
 1355            break;
 356        }
 311357        return count;
 358    }
 359
 360    private int VisitMixedEdgeInterval<TFrame>(in TFrame frame, MixedPrism prism, int start, int end,
 361        in RationalSegmentInterval clip, in WideScaledHullPenetration penetration, bool admissionOnly)
 362        where TFrame : struct, IForwardHullFrame3d
 363    {
 3699364        _mixedEdgeStart = start; _mixedEdgeEnd = end; _mixedEdgeClip[0] = clip;
 1233365        Span<Vector3d> points = stackalloc Vector3d[2] { prism.Points[start], prism.Points[end] };
 1233366        ReadOnlySpan<int> edges = stackalloc int[2] { 0, 1 };
 1233367        int count = WideOrientedBox.VisitConvexHullContacts(_mixedMovingFrame, _mixedMoving!.Center, MixedMovingPoints,
 1233368            MixedMovingTriangles, MixedMovingEdges, frame, MixedEmbedded2DGeometry.GetCenter3D(_mixedLocal[_mixedMember]
 1233369            points, ReadOnlySpan<int>.Empty, edges, penetration, this,
 1233370            static (owner, contact) => owner.AddMixedSample(contact), this, admissionOnly);
 1233371        if (count == 0 && start != end)
 715372            count = VisitMixedEdgeInterior(frame, points, clip, penetration, admissionOnly);
 1233373        return count;
 374    }
 375
 376    private int VisitMixedEdgeInterior<TFrame>(in TFrame frame, ReadOnlySpan<Vector3d> points,
 377        in RationalSegmentInterval clip, in WideScaledHullPenetration penetration, bool admissionOnly)
 378        where TFrame : struct, IForwardHullFrame3d
 379    {
 715380        Signed832 one = Signed832.ExtendValue(Signed192.Signed(1));
 1430381        Signed832 ln = clip.IsClipped ? clip.WideLowerNumerator : default, ld = clip.IsClipped ? clip.WideLowerDenominat
 1430382        Signed832 un = clip.IsClipped ? clip.WideUpperNumerator : one, ud = clip.IsClipped ? clip.WideUpperDenominator :
 721383        if (RationalSegmentInterval.CompareParameters(ln, ld, un, ud) >= 0) return 0;
 1418384        Span<ulong> values = stackalloc ulong[6 * 14]; Span<int> signs = stackalloc int[6];
 1418385        var n = ContactQuadratic.At(values, signs, 0, 14); var d = ContactQuadratic.At(values, signs, 1, 14);
 709386        var term = ContactQuadratic.At(values, signs, 2, 14);
 387        // The exact mediant is strictly inside a nonempty retained band. Its
 388        // <833-bit values fit the existing triangle witness's 2048-bit banks.
 4254389        n.Set(ln); term.Set(un); n.Add(term); d.Set(ld); term.Set(ud); d.Add(term);
 709390        WideDirection3d axis = penetration.Negate ? -penetration.Axis : penetration.Axis;
 1360391        if (!ContainsMixedPoint(0, 1, n, d, axis)) return 0;
 58392        Signed832 support = WideOrientedBox.GetScaledHullSupport(_mixedMovingFrame, MixedMovingPoints, axis, true);
 116393        RationalPoint3d a = frame.GetPoint(points[0]), b = frame.GetPoint(points[1]);
 116394        ReadOnlySpan<Vector3d> moving = MixedMovingPoints; ReadOnlySpan<int> triangles = MixedMovingTriangles;
 852395        for (int triangle = 0; triangle < triangles.Length; triangle += 3)
 396        {
 1158397            Vector3d x = moving[triangles[triangle]], y = moving[triangles[triangle + 1]], z = moving[triangles[triangle
 386398            if (!WideOrientedBox.IsScaledHullSupport(_mixedMovingFrame.GetPoint(x), axis, support)
 386399                || !WideOrientedBox.IsScaledHullSupport(_mixedMovingFrame.GetPoint(y), axis, support)
 386400                || !WideOrientedBox.IsScaledHullSupport(_mixedMovingFrame.GetPoint(z), axis, support)) continue;
 42401            if (!WideTriangleRelations.TryGetProjectedFrameSegmentFaceAnchors(new(x, y, z), _mixedMovingFrame, a, b,
 42402                default, default, MixedEmbedded2DGeometry.GetCenter3D(_mixedLocal[_mixedMember]), _mixedMoving!.Center,
 42403                0, out FixedPointAnchor target, out FixedPointAnchor source, requirePhysicalTargetBoundary: false,
 42404                materialize: !admissionOnly, wideN: n, wideD: d)) continue;
 26405            if (!admissionOnly) AddMixedSample(new(source, target, axis.GetNormal(false),
 8406                penetration.GetRoundedDepth(out bool clamped), clamped));
 18407            return 1;
 408        }
 40409        return 0;
 410    }
 411
 412    private int VisitMixedFaces(in WideScaledHullPenetration penetration, bool admissionOnly)
 413    {
 7010414        int source = _mixedMember, count = 0;
 3505415        bool rigid = _mixedUsingRigid;
 3505416        MixedPrism original = _mixedPrisms[source];
 3505417        WideDirection3d axis = penetration.Negate ? -penetration.Axis : penetration.Axis;
 3505418        RationalPoint3d reference = _mixedQuaternion ? MixedSupportPoint(original.Frame, original, axis)
 3505419            : MixedSupportPoint(original.NativeFrame, original, axis);
 17956420        for (int member = 0; member < _mixedLocal.Count; member++)
 421        {
 6937422            if (_mixedComponents[member] != _mixedComponents[source] || !MaySupplyMixedFace(member, axis)) continue;
 5846423            MixedPrism prism = _mixedPrisms[member];
 5846424            RationalPoint3d support = _mixedQuaternion ? MixedSupportPoint(prism.Frame, prism, axis)
 5846425                : MixedSupportPoint(prism.NativeFrame, prism, axis);
 5846426            Signed192 denominator = _mixedQuaternion ? original.Frame.RotationDenominator : original.NativeFrame.Rotatio
 5846427            if (!WideTriangleRelations.DotScaledDirections(axis,
 5846428                WideTriangleRelations.GetScaledPointDifference(support, reference, denominator)).IsZero) continue;
 4395429            _mixedMember = member;
 4395430            _mixedUsingRigid = _mixedMovingFrame.IsRigid && prism.Rigid;
 4395431            count += _mixedQuaternion ? VisitMixedFaces(prism.Frame, prism, penetration, admissionOnly)
 4395432                : VisitMixedFaces(prism.NativeFrame, prism, penetration, admissionOnly);
 4395433            if (admissionOnly && count > 0) break;
 434        }
 7010435        _mixedMember = source; _mixedUsingRigid = rigid;
 3505436        return count;
 437    }
 438
 439    private static RationalPoint3d MixedSupportPoint<TFrame>(in TFrame frame, MixedPrism prism,
 440        in WideDirection3d axis) where TFrame : struct, IForwardHullFrame3d
 441    {
 13552442        Signed832 support = WideOrientedBox.GetScaledHullSupport(frame, prism.Points, axis, maximize: false);
 13552443        int vertex = 0;
 444        // Admitted nonempty geometry has a vertex attaining its exact support.
 95190445        while (!WideOrientedBox.IsScaledHullSupport(frame.GetPoint(prism.Points[vertex]), axis, support)) vertex++;
 13552446        return frame.GetPoint(prism.Points[vertex]);
 447    }
 448
 449    private bool MaySupplyMixedFace(int member, in WideDirection3d normal)
 450    {
 6936451        FixedBoundBox bounds = _mixedLocal[member].MixedBounds3D;
 48968452        for (int axis = 0; axis < 3; axis++)
 18638453            if ((axis == 0 ? normal.X : axis == 1 ? normal.Y : normal.Z).IsZero
 18638454                && (bounds.Max[axis] < _mixedMoving!.Bounds.Min[axis]
 19728455                    || bounds.Min[axis] > _mixedMoving.Bounds.Max[axis])) return false;
 5846456        return true;
 457    }
 458
 459    private int VisitMixedFaces<TFrame>(in TFrame frame, MixedPrism prism, in WideScaledHullPenetration penetration,
 460        bool admissionOnly) where TFrame : struct, IForwardHullFrame3d
 461    {
 4395462        WideDirection3d axis = penetration.Negate ? -penetration.Axis : penetration.Axis;
 4395463        Signed832 support = WideOrientedBox.GetScaledHullSupport(frame, prism.Points, axis, maximize: false);
 4395464        int emitted = 0;
 4395465        _mixedSupplier = _mixedMember;
 55018466        for (int face = 0; face < prism.Offsets.Length + 2; face++)
 467        {
 24578468            int count = face < 2 ? prism.Offsets.Length : 4;
 24580469            if (_mixedFace.Length < count) Array.Resize(ref _mixedFace, count);
 24580470            if (_mixedFaceTriangles.Length < 3 * (count - 2)) Array.Resize(ref _mixedFaceTriangles, 3 * (count - 2));
 24580471            if (_mixedFaceEdges.Length < 2 * count) Array.Resize(ref _mixedFaceEdges, 2 * count);
 245688472            for (int vertex = 0; vertex < count; vertex++)
 473            {
 196532474                int edge = face - 2, next = (edge + 1) % prism.Offsets.Length;
 98266475                int index = face < 2 ? 2 * vertex + face
 98266476                    : vertex == 0 ? 2 * edge : vertex == 1 ? 2 * next : vertex == 2 ? 2 * next + 1 : 2 * edge + 1;
 98266477                _mixedFace[vertex] = prism.Points[index];
 196532478                _mixedFaceEdges[2 * vertex] = vertex; _mixedFaceEdges[2 * vertex + 1] = (vertex + 1) % count;
 98266479                if (vertex < 2) continue;
 49110480                int triangle = 3 * (vertex - 2);
 147330481                _mixedFaceTriangles[triangle] = 0; _mixedFaceTriangles[triangle + 1] = vertex - 1; _mixedFaceTriangles[t
 482            }
 24578483            bool supporting = true;
 245688484            for (int vertex = 0; vertex < count; vertex++)
 98266485                supporting &= WideArithmetic.SubtractSigned832(WideOrientedBox.ProjectScaledHullPoint(
 98266486                    frame.GetPoint(_mixedFace[vertex]), axis, Signed192.One), support).IsZero;
 24578487            if (!supporting) continue;
 4365488            if (face >= 2)
 489            {
 16476490                for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 491                {
 5512492                    MixedBand band = prism.Bands[bandIndex];
 51130493                    foreach (var span in band.Boundary.Spans)
 494                    {
 20740495                        if (span.First != face - 2) continue;
 5524496                        if (span.Kind != SpanKind.Joined)
 4305497                            emitted += VisitMixedSide(frame, span, band.Lower, band.Upper, penetration, admissionOnly, b
 6898498                        if (admissionOnly && emitted > 0) return emitted;
 499                    }
 500                }
 2726501                continue;
 502            }
 265503            int firstSample = _mixedSamples.Count;
 265504            emitted += _mixedUsingRigid
 265505                ? VisitMixedRigidFace(prism, count, admissionOnly)
 265506                : WideOrientedBox.VisitConvexHullContacts(_mixedMovingFrame, _mixedMoving!.Center,
 265507                MixedMovingPoints, MixedMovingTriangles, MixedMovingEdges, frame,
 265508                MixedEmbedded2DGeometry.GetCenter3D(_mixedLocal[_mixedMember]), _mixedFace.AsSpan(0, count),
 265509                _mixedFaceTriangles.AsSpan(0, 3 * (count - 2)), _mixedFaceEdges.AsSpan(0, 2 * count), penetration,
 265510                this, static (owner, contact) => owner.AddMixedSample(contact), admissionOnly: admissionOnly);
 408511            if (!admissionOnly) AddMixedRegion(_mixedMember, face, default, _mixedFace[0].Y, _mixedFace[0].Y, firstSampl
 355512            if (admissionOnly && emitted > 0) return emitted;
 513        }
 2931514        return emitted;
 515    }
 516
 517    private int VisitMixedSide<TFrame>(in TFrame frame, in BoundarySpan2D span,
 518        Fixed64 lower, Fixed64 upper, in WideScaledHullPenetration penetration, bool admissionOnly, int band)
 519        where TFrame : struct, IForwardHullFrame3d
 520    {
 4305521        MixedPrism prism = _mixedPrisms[_mixedMember];
 4305522        int firstSample = _mixedSamples.Count;
 523        int emitted;
 4305524        if (_mixedUsingRigid && !span.Interval.IsClipped
 4305525            && lower == -_mixedLocal[_mixedMember].MixedHalfThickness && upper == _mixedLocal[_mixedMember].MixedHalfThi
 2387526            emitted = VisitMixedRigidFace(prism, 4, admissionOnly);
 527        else
 528        {
 1918529            FixedTriangle rectangle = new(new Vector3d(span.Start.X, lower, span.Start.Y),
 1918530                new(span.End.X, lower, span.End.Y), new(span.Start.X, upper, span.Start.Y));
 1918531            emitted = WideOrientedBox.VisitProjectedHullRectangleContacts(_mixedMovingFrame, _mixedMoving!.Center,
 1918532                MixedMovingPoints, MixedMovingTriangles, MixedMovingEdges, frame,
 1918533                MixedEmbedded2DGeometry.GetCenter3D(_mixedLocal[_mixedMember]), rectangle, span.Interval,
 1918534                penetration, this, static (owner, contact) => owner.AddMixedSample(contact), admissionOnly);
 535        }
 6695536        if (!admissionOnly) AddMixedRegion(_mixedMember, span.First + 2, span, lower, upper, firstSample, band);
 4305537        return emitted;
 538    }
 539
 540    private int VisitMixedRigidFace(MixedPrism prism, int count, bool admissionOnly) =>
 2630541        WideOrientedBox.VisitConvexHullContacts(_mixedMovingFrame.RigidOrigin, _mixedMovingFrame.Rotation,
 2630542            MixedMovingPoints, MixedMovingTriangles, MixedMovingEdges, prism.Frame.RigidOrigin, prism.Frame.Rotation,
 2630543            _mixedFace.AsSpan(0, count), _mixedFaceTriangles.AsSpan(0, 3 * (count - 2)), _mixedFaceEdges.AsSpan(0, 2 * c
 2630544            _mixedRigidPenetration, this, static (owner, contact) => owner.AddMixedSample(contact), admissionOnly: admis
 545
 546    private int FindMixedGroup(in WideScaledHullPenetration penetration)
 547    {
 4478548        WideDirection3d axis = penetration.Negate ? -penetration.Axis : penetration.Axis;
 10034549        for (int group = 0; group < _mixedGroups.Count; group++)
 550        {
 1470551            MixedGroup existing = _mixedGroups[group];
 1470552            if (existing.Component == _mixedComponents[_mixedMember] && existing.Feature == _mixedMovingFeature
 1470553                && WideDirection3d.AreParallel(axis, existing.Axis)
 1470554                && WideDirection3d.Dot(axis, existing.Axis).Sign > 0
 1470555                && !existing.Penetration.ShouldReplace(penetration.Overlap, penetration.SquaredAxisLength, penetration.C
 1470556                && !penetration.ShouldReplace(existing.Penetration.Overlap, existing.Penetration.SquaredAxisLength,
 2401557                    existing.Penetration.CommonDenominator)) return group;
 558        }
 3547559        return _mixedGroups.Count;
 560    }
 561
 562    ReadOnlySpan<RationalSegmentInterval> IScaledConvexHullContactDomain.GetEdgeIntervals(bool first, int start, int end
 563        in WideDirection3d normal)
 4235564        => first ? MixedFullInterval : _mixedEdgeClip;
 565
 566    private ReadOnlySpan<RationalSegmentInterval> GetMixedEdgeIntervals(int start, int end)
 567    {
 3581568        _mixedIntervals.FastClear();
 3581569        MixedPrism prism = _mixedPrisms[_mixedMember];
 7162570        Vector3d a = prism.Points[start], b = prism.Points[end];
 3581571        if (a.Y == b.Y)
 572        {
 6632573            for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 17848574                foreach (var span in prism.Bands[bandIndex].Boundary.Spans)
 7156575                    if (span.Interval.TryMapToSegment(new FixedSegment(new(span.Start.X, a.Y, span.Start.Y),
 8948576                        new(span.End.X, a.Y, span.End.Y)), new FixedSegment(a, b), out var mapped)) _mixedIntervals.Add(
 577        }
 578        else
 579        {
 580            // Neighbor caps split an original vertical edge into exact bands.
 9420581            for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 582            {
 2677583                MixedBand band = prism.Bands[bandIndex];
 5354584                Fixed64 lower = band.Lower - a.Y, upper = band.Upper - a.Y;
 585                // Original vertical prism edges are always bottom to top.
 2677586                Signed320 denominator = Signed320.ExtendValue(Signed192.Raw(b.Y - a.Y));
 2677587                _mixedIntervals.Add(new(Signed320.ExtendValue(Signed192.Raw(lower)), denominator,
 2677588                    Signed320.ExtendValue(Signed192.Raw(upper)), denominator));
 589            }
 590        }
 3581591        return _mixedIntervals.AsReadOnlySpan();
 592    }
 593
 594    bool IScaledConvexHullContactDomain.ContainsPoint(bool first, int start, int end, in Signed832 numerator,
 595        in Signed832 denominator, in WideDirection3d normal)
 596    {
 597        System.Diagnostics.Debug.Assert(!first);
 1716598        Span<ulong> values = stackalloc ulong[52]; Span<int> signs = stackalloc int[4];
 1716599        var n = ContactQuadratic.At(values, signs, 0, 13); var d = ContactQuadratic.At(values, signs, 1, 13);
 1716600        n.Set(numerator); d.Set(denominator);
 858601        return ContainsMixedPoint(start, end, n, d, normal);
 602    }
 603
 604    bool IScaledConvexHullContactDomain.ContainsPoint(bool first, int start, int end, scoped ContactQuadratic numerator,
 605        scoped ContactQuadratic denominator, in WideDirection3d normal) =>
 776606        first || ContainsMixedPoint(start, end, numerator, denominator, normal);
 607
 608    private bool ContainsMixedPoint(int start, int end, scoped ContactQuadratic n, scoped ContactQuadratic d,
 609        in WideDirection3d normal)
 610    {
 611        // This domain belongs to the current original edge, represented by the
 612        // two-point visitor as indices 0/1. Preserve its exact parameter.
 1955613        if (start == end)
 614        {
 662615            Span<ulong> storage = stackalloc ulong[52]; Span<int> signs = stackalloc int[4];
 662616            var endpoint = ContactQuadratic.At(storage, signs, 0, 13); var one = ContactQuadratic.At(storage, signs, 1, 
 662617            endpoint.Set(Signed576.ExtendValue(Signed192.Signed(start))); one.Set(Signed576.ExtendValue(Signed192.Signed
 419618            if (_mixedEdgeClip[0].IsClipped && !_mixedEdgeClip[0].Contains(endpoint, one, ReadOnlySpan<ulong>.Empty)) re
 243619            start = end = start == 0 ? _mixedEdgeStart : _mixedEdgeEnd;
 620        }
 621        else
 622        {
 1738623            if (_mixedEdgeClip[0].IsClipped && !_mixedEdgeClip[0].Contains(n, d, ReadOnlySpan<ulong>.Empty)) return fals
 3020624            start = _mixedEdgeStart; end = _mixedEdgeEnd;
 625        }
 1753626        MixedPrism source = _mixedPrisms[_mixedMember];
 3506627        Vector3d a = source.Points[start], b = source.Points[end];
 1753628        FixedSegment footprint = new(new(a.X, Fixed64.Zero, a.Z), new(b.X, Fixed64.Zero, b.Z));
 3506629        _mixedFan.FastClear(); _mixedFan.Add(_mixedMember);
 7452630        for (int cursor = 0; cursor < _mixedFan.Count; cursor++)
 631        {
 6616632            int member = _mixedFan[cursor]; MixedPrism prism = _mixedPrisms[member];
 3308633            if (member != _mixedMember)
 634            {
 635                // Every queried target edge lies on the selected support plane;
 636                // its original endpoint is an exact projection reference too.
 1555637                bool supports = _mixedQuaternion ? SupportsMixedFan(prism.Frame, source.Frame, a, prism.Points, normal)
 1555638                    : SupportsMixedFan(prism.NativeFrame, source.NativeFrame, a, prism.Points, normal);
 2890639                if (!supports) return false;
 640            }
 11516641            for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 642            {
 3785643                MixedBand band = prism.Bands[bandIndex];
 644                // A reached fan member already contains the queried height. Each
 645                // prepared band is covered completely by every Joined neighbor.
 3785646                Fixed64 delta = _mixedLocal[member].MixedSlabCenterY - _mixedLocal[_mixedMember].MixedSlabCenterY;
 3785647                if (!MixedHeightContains(a.Y, b.Y, n, d, delta + band.Lower, delta + band.Upper)) continue;
 20748648                foreach (var span in band.Boundary.Spans)
 649                {
 8191650                    if (span.Kind != SpanKind.Joined || _mixedFan.Contains(span.OtherMember)) continue;
 2856651                    FixedSegment edge = new(new(span.Start.X, Fixed64.Zero, span.Start.Y), new(span.End.X, Fixed64.Zero,
 2856652                    int location = _mixedQuaternion
 2856653                        ? WideTriangleRelations.LocateFrameEdgePoint(footprint, source.FootFrame, n, d, edge, prism.Foot
 2856654                        : WideTriangleRelations.LocateFrameEdgePoint(footprint, source.NativeFootFrame, n, d, edge, pris
 4649655                    if (location >= 0) _mixedFan.Add(span.OtherMember);
 656                }
 657            }
 658        }
 418659        return true;
 660    }
 661
 662    private static bool SupportsMixedFan<TFrame>(in TFrame frame, in TFrame source, Vector3d reference,
 663        ReadOnlySpan<Vector3d> points, in WideDirection3d normal) where TFrame : struct, IForwardHullFrame3d
 664    {
 24849665        RationalPoint3d origin = source.GetPoint(reference);
 275121666        foreach (Vector3d vertex in points)
 118356667            if (WideTriangleRelations.DotScaledDirections(normal, WideTriangleRelations.GetScaledPointDifference(
 129645668                frame.GetPoint(vertex), origin, source.RotationDenominator)).Sign < 0) return false;
 13560669        return true;
 670    }
 671
 672    private bool TryGetMixedHeights(int source, int other, out Fixed64 lower, out Fixed64 upper)
 673    {
 8832674        LSCollider2D a = _mixedLocal[source], b = _mixedLocal[other];
 4416675        lower = upper = default;
 4454676        if (a.MixedBounds3D.Max.Y < b.MixedBounds3D.Min.Y || a.MixedBounds3D.Min.Y > b.MixedBounds3D.Max.Y) return false
 677        // Intersecting bounded extrusions have a bounded center difference.
 678        // Absolute cap coordinates may exceed Fixed64 and must not be clamped.
 4378679        Fixed64 delta = b.MixedSlabCenterY - a.MixedSlabCenterY;
 8756680        lower = delta - b.MixedHalfThickness; upper = delta + b.MixedHalfThickness;
 4378681        return true;
 682    }
 683
 684    private static bool MixedHeightContains(Fixed64 first, Fixed64 second, scoped ContactQuadratic n,
 685        scoped ContactQuadratic d, Fixed64 minimum, Fixed64 maximum)
 686    {
 4375687        if (second < minimum || first > maximum) return false;
 3972688        if (first == second) return true;
 4836689        Fixed64 lower = minimum > first ? minimum : first, upper = maximum < second ? maximum : second;
 2418690        Signed320 denominator = Signed320.ExtendValue(Signed192.Raw(second - first));
 2418691        var interval = new RationalSegmentInterval(Signed320.ExtendValue(Signed192.Raw(lower - first)), denominator,
 2418692            Signed320.ExtendValue(Signed192.Raw(upper - first)), denominator);
 2418693        return interval.Contains(n, d, ReadOnlySpan<ulong>.Empty);
 694    }
 695
 696    private void AddMixedSample(FixedContactAnchors contact)
 697    {
 7930698        bool represented = contact.SecondAnchor.TryGetPointInFrame(_mixedMoving!.Center, out Vector3d point);
 699        System.Diagnostics.Debug.Assert(represented);
 7930700        _mixedSamples.Add(new(_mixedGroup, _mixedSupplier, point, contact));
 7930701    }
 702
 703    private readonly struct MixedSample : IPlaneContactSample
 704    {
 705        internal readonly int Group, Supplier;
 706        internal readonly FixedContactAnchors Contact;
 707        public Vector3d Point { get; }
 708        internal MixedSample(int group, int supplier, Vector3d point, FixedContactAnchors contact)
 139190709        { Group = group; Supplier = supplier; Point = point; Contact = contact; }
 710    }
 711
 712    private readonly struct MixedGroup
 713    {
 714        internal readonly int Component, Carrier, Feature;
 715        internal readonly WideScaledHullPenetration Penetration;
 6316716        internal WideDirection3d Axis => Penetration.Negate ? -Penetration.Axis : Penetration.Axis;
 717        internal MixedGroup(int component, int carrier, WideScaledHullPenetration penetration, int feature)
 7070718        { Component = component; Carrier = carrier; Penetration = penetration; Feature = feature; }
 719    }
 720
 721    private sealed class MixedPrism
 722    {
 1000723        internal readonly SwiftList<MixedBand> Bands = new();
 724        internal int BandCount;
 1000725        internal Vector2d[] Offsets = Array.Empty<Vector2d>();
 1000726        internal Vector3d[] Points = Array.Empty<Vector3d>();
 2000727        internal int[] Triangles = Array.Empty<int>(), Edges = Array.Empty<int>();
 728        internal ScaledRigidFrame3d Frame;
 729        internal ScaledRigidFrame3d FootFrame;
 730        internal NativePrismYawFrame3d NativeFrame, NativeFootFrame;
 731        internal bool Rigid, Joined, SphereHasConcaveFace;
 732        private int _id;
 733        private long _lifetime;
 734        private uint _broad, _dependency;
 17394735        internal bool Matches(LSCollider2D member) => _id == member.Id && _lifetime == member.LifetimeVersion
 17394736            && _broad == member.BroadPhaseVersion && _dependency == member.ContactDependencyVersion;
 737        internal void Prepare(LSCollider2D member, bool quaternion)
 738        {
 1336739            int count = member.VertexCount;
 1336740            if (Offsets.Length != count)
 741            {
 2000742                Offsets = new Vector2d[count]; Points = new Vector3d[2 * count];
 2000743                Triangles = new int[12 * count - 12]; Edges = new int[6 * count];
 744            }
 18608745            for (int vertex = 0; vertex < count; vertex++) Offsets[vertex] = member.GetScaledLocalVertexUnchecked(vertex
 1336746            CollisionDetectionMixed.FillPrismGeometry(Offsets, member.MixedHalfThickness, Points, Triangles, Edges);
 1336747            Vector3d center = MixedEmbedded2DGeometry.GetCenter3D(member);
 1336748            Rigid = quaternion || member.ConvexRotation == Fixed64.Zero;
 2656749            if (Rigid) Frame = ScaledRigidFrame3d.Rigid(center, FixedQuaternion.FromAxisAngle(Vector3d.Up, -member.Conve
 1336750            Vector3d footprint = new(center.X, Fixed64.Zero, center.Z);
 1555751            if (quaternion) FootFrame = ScaledRigidFrame3d.Rigid(footprint, Frame.Rotation);
 2234752            else { NativeFrame = new(center, member.ConvexRotation); NativeFootFrame = new(footprint, member.ConvexRotat
 4008753            _id = member.Id; _lifetime = member.LifetimeVersion; _broad = member.BroadPhaseVersion;
 1336754            _dependency = member.ContactDependencyVersion;
 1336755        }
 756    }
 757
 758    private sealed class MixedBand
 759    {
 1404760        internal readonly MeshSurfaceBoundaryDomain2D Boundary = new();
 761        internal Fixed64 Lower, Upper;
 762    }
 763}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedBoundaryLines.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.MixedBoundaryLines.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 FixedMathSharp;
 9using FixedMathSharp.Geometry;
 10using Gravitas.Colliders;
 11using Gravitas.CollisionHandling;
 12using SwiftCollections;
 13
 14namespace Gravitas;
 15
 16/// <content>Prepares exact concave boundary lines shared by native rounded-solid contacts.</content>
 17public sealed partial class StaticSurface2D
 18{
 60019    private readonly SwiftList<MixedBoundaryLine> _mixedBoundaryLines = new();
 60020    private readonly SwiftList<int> _mixedCapsuleLineGroups = new();
 21    private CapsulePrismBoundaryContacts? _mixedCapsuleBoundary;
 22    private bool _mixedBoundaryLinesCurrent;
 23
 24    private void PrepareMixedBoundaryLines()
 25    {
 19426        _mixedBoundaryLines.FastClear();
 38627        if (!_mixedSphereConcavityCurrent) PrepareMixedSphereConcavity();
 133228        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 29        {
 47230            MixedPrism prism = _mixedPrisms[_mixedMember];
 47231            if (!prism.SphereHasConcaveFace) continue;
 120032            for (int index = 0; index < prism.BandCount; index++)
 33            {
 38634                MixedBand band = prism.Bands[index];
 412235                foreach (var span in band.Boundary.Spans)
 36                {
 167537                    if (span.Kind == SpanKind.Joined) continue;
 124238                    GetMixedBoundaryBounds(span.Interval, out var ln, out var ld, out var un, out var ud);
 124239                    Probe(new(_mixedMember, span.First, 0, new(ln, ld, ln, ld), band.Lower, band.Upper));
 124240                    Probe(new(_mixedMember, span.First, 0, new(un, ud, un, ud), band.Lower, band.Upper));
 41                    // A height step may cut only part of this exposed span.
 42                    // Intersect with the incident band's actual joined windows before probing.
 745243                    for (int end = 0; end < 2; end++)
 44                    {
 248445                        Fixed64 y = end == 0 ? band.Lower : band.Upper;
 248446                        int adjacent = end == 0 ? index - 1 : index + 1;
 248447                        if (adjacent >= 0 && adjacent < prism.BandCount)
 1178048                            foreach (var joined in prism.Bands[adjacent].Boundary.Spans)
 479149                                if (joined.First == span.First && joined.Kind == SpanKind.Joined
 479150                                    && TryIntersectMixedIntervals(span.Interval, joined.Interval, out var clip))
 17451                                    Probe(new(_mixedMember, span.First, 0, clip, y, y));
 52                        // Incident fans can become blocked at a single endpoint only.
 248453                        Probe(new(_mixedMember, span.First, 0, new(ln, ld, ln, ld), y, y));
 248454                        Probe(new(_mixedMember, span.First, 0, new(un, ud, un, ud), y, y));
 55                    }
 56                }
 57            }
 128458            for (int cap = 0; cap < 2; cap++)
 59            {
 42860                Fixed64 y = cap == 0 ? -_mixedLocal[_mixedMember].MixedHalfThickness : _mixedLocal[_mixedMember].MixedHa
 458661                foreach (var span in prism.Bands[cap == 0 ? 0 : prism.BandCount - 1].Boundary.Spans)
 62                {
 186563                    int vertical = cap == 0 ? 1 : -1;
 186564                    if (span.Kind == SpanKind.Joined)
 48065                        Probe(new(_mixedMember, span.First, vertical, span.Interval, y, y));
 186566                    GetMixedBoundaryBounds(span.Interval, out var ln, out var ld, out var un, out var ud);
 186567                    Probe(new(_mixedMember, span.First, vertical, new(ln, ld, ln, ld), y, y));
 186568                    Probe(new(_mixedMember, span.First, vertical, new(un, ud, un, ud), y, y));
 69                }
 70            }
 71        }
 19472        _mixedBoundaryLinesCurrent = true;
 73
 74        void Probe(in MixedBoundaryLine line)
 75        {
 76            MixedPrism prism = _mixedPrisms[line.Member];
 77            Vector2d a = prism.Offsets[line.Edge], b = prism.Offsets[(line.Edge + 1) % prism.Offsets.Length];
 78            WideDirection3d normal = MixedBoundaryLineNormal(line);
 79            GetMixedBoundaryBounds(line.Clip, out var ln, out var ld, out var un, out var ud);
 80            const int words = 32;
 81            System.Span<ulong> values = stackalloc ulong[8 * words]; System.Span<int> signs = stackalloc int[8];
 82            var n = ContactQuadratic.At(values, signs, 0, words); var d = ContactQuadratic.At(values, signs, 1, words);
 83            var y = ContactQuadratic.At(values, signs, 2, words); var yd = ContactQuadratic.At(values, signs, 3, words);
 84            n.Set(WideArithmetic.AddSigned576(WideArithmetic.MultiplySigned320(ln, ud), WideArithmetic.MultiplySigned320
 85            Signed576 divisor = WideArithmetic.MultiplySigned320(ld, ud);
 86            d.Set(WideArithmetic.AddSigned576(divisor, divisor));
 87            y.Set(Signed576.ExtendValue(WideArithmetic.AddSigned192(Signed192.Raw(line.Lower), Signed192.Raw(line.Upper)
 88            yd.Set(Signed576.ExtendValue(Signed192.Signed(2)));
 89            if (AdmitMixedSphereFan(new(new(a.X, Fixed64.Zero, a.Y), new(b.X, Fixed64.Zero, b.Y)), n, d, y, yd, normal))
 90            KeepMixedBoundaryLine(line);
 91        }
 19492    }
 93
 94    private void KeepMixedBoundaryLine(MixedBoundaryLine line)
 95    {
 96        // Remove artificial height-band cuts before selecting a peak, so a
 97        // remote neighbor cannot change the sampling of one continuous line.
 4190098        for (int index = _mixedBoundaryLines.Count - 1; index >= 0; index--)
 99        {
 18949100            MixedBoundaryLine old = _mixedBoundaryLines[index];
 18949101            if (line.Member != old.Member || line.Edge != old.Edge || line.Vertical != old.Vertical) continue;
 1767102            bool sameTangent = SameMixedBoundaryInterval(line.Clip, old.Clip);
 1767103            if (sameTangent && line.Lower <= old.Upper && old.Lower <= line.Upper)
 104            {
 598105                line = new(line.Member, line.Edge, line.Vertical, line.Clip,
 598106                    FixedMath.Min(line.Lower, old.Lower), FixedMath.Max(line.Upper, old.Upper));
 1196107                _mixedBoundaryLines.RemoveAt(index); continue;
 108            }
 1169109            if (line.Lower != line.Upper || old.Lower != old.Upper || line.Lower != old.Lower
 1169110                || !TryIntersectMixedIntervals(line.Clip, old.Clip, out _)) continue;
 625111            GetMixedBoundaryBounds(line.Clip, out var ln, out var ld, out var un, out var ud);
 625112            GetMixedBoundaryBounds(old.Clip, out var oln, out var oldd, out var oun, out var oud);
 1285113            if (RationalSegmentInterval.CompareParameters(ln, ld, oln, oldd) > 0) { ln = oln; ld = oldd; }
 1231114            if (RationalSegmentInterval.CompareParameters(un, ud, oun, oud) < 0) { un = oun; ud = oud; }
 625115            line = new(line.Member, line.Edge, line.Vertical, new(ln, ld, un, ud), line.Lower, line.Upper);
 625116            _mixedBoundaryLines.RemoveAt(index);
 117        }
 2001118        _mixedBoundaryLines.Add(line);
 2001119    }
 120
 121    private void AppendMixedCapsuleBoundaryPeaks(LSCapsuleCollider capsule)
 122    {
 1101123        _mixedCapsuleLineGroups.FastClear();
 1101124        int supportCount = _mixedSphereGroups.Count;
 1101125        int sampleIndex = 0;
 3706126        for (int ordinal = 0; ordinal < _mixedBoundaryLines.Count; ordinal++)
 127        {
 752128            MixedBoundaryLine line = _mixedBoundaryLines[ordinal];
 752129            _mixedCapsuleLineGroups.Add(-1);
 752130            if (sampleIndex == _mixedCurvedBoundarySamples.Count || _mixedCurvedBoundarySamples[sampleIndex].Ordinal != 
 161131            var sample = _mixedCurvedBoundarySamples[sampleIndex++];
 161132            FixedContactAnchors contact = sample.Contact;
 161133            _mixedMember = line.Member;
 322134            LSCollider2D member = _mixedLocal[line.Member]; MixedPrism prism = _mixedPrisms[line.Member];
 161135            bool prepared = _mixedCapsuleBoundary!.PrepareSource(capsule.Center, capsule.Rotation, capsule.AxisLength, c
 161136                MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation, prism.Offsets[line.Edge],
 161137                prism.Offsets[(line.Edge + 1) % prism.Offsets.Length], prism.Offsets[(line.Edge + 2) % prism.Offsets.Len
 161138                line.Clip, line.Lower, line.Upper, line.Vertical, out _);
 139            System.Diagnostics.Debug.Assert(prepared);
 161140            WideDirection3d normal = MixedBoundaryLineNormal(line);
 161141            int component = _mixedComponents[line.Member];
 161142            int group = AddMixedCapsuleSample(new(component, member.Id, line.Member, normal,
 161143                MixedSupportPoint(prism.NativeFrame, prism, normal), default, contact), default,
 161144                _mixedCapsuleUseCuts[line.Member] && !sample.GeometryOnly);
 161145            _mixedCapsuleLineGroups[_mixedCapsuleLineGroups.Count - 1] = group;
 165146            while (sampleIndex < _mixedCurvedBoundarySamples.Count && _mixedCurvedBoundarySamples[sampleIndex].Ordinal =
 147            {
 4148                var cut = _mixedCurvedBoundarySamples[sampleIndex++];
 4149                int fragment = AddMixedCapsuleSample(new(component, member.Id, line.Member, normal,
 4150                    MixedSupportPoint(prism.NativeFrame, prism, normal), default, cut.Contact), default,
 4151                    _mixedCapsuleUseCuts[line.Member]);
 4152                _mixedRegionParents[fragment] = FindMixedRegion(group);
 153            }
 2418154            for (int support = 0; support < supportCount; support++)
 1048155                if (_mixedSphereGroups[support].Supplier == line.Member
 1048156                    && SameMixedCapsulePlane(group, support)
 1048157                    && _mixedCapsuleBoundary.ConnectsSupport(_mixedCapsuleCore[support]))
 30158                    _mixedRegionParents[FindMixedRegion(group)] = FindMixedRegion(support);
 2314159            for (int previous = 0; previous < _mixedCapsuleLineGroups.Count - 1; previous++)
 160            {
 996161                int other = _mixedCapsuleLineGroups[previous];
 996162                if (other < 0 || FindMixedRegion(group) == FindMixedRegion(other) || !SameMixedCapsulePlane(group, other
 92163                MixedBoundaryLine old = _mixedBoundaryLines[previous];
 164                // Same-source strata meet at a rational native point. Test the
 165                // actual finite capsule there; a rounded peak is not connectivity evidence.
 92166                if (line.Member == old.Member && line.Edge == old.Edge
 92167                    && FixedMath.Max(line.Lower, old.Lower) <= FixedMath.Min(line.Upper, old.Upper)
 92168                    && TryIntersectMixedIntervals(line.Clip, old.Clip, out var clip))
 169                {
 16170                    GetMixedBoundaryBounds(clip, out var n, out var d, out _, out _);
 16171                    if (_mixedCapsuleBoundary.ContainsPoint(n, d, FixedMath.Max(line.Lower, old.Lower)))
 15172                        _mixedRegionParents[FindMixedRegion(group)] = FindMixedRegion(other);
 173                }
 76174                else if (line.Member == old.Member && line.Vertical != 0)
 175                {
 35176                    int count = prism.Offsets.Length;
 35177                    bool atStart = (old.Edge + 1) % count == line.Edge
 35178                        && ContainsEndpoint(old.Clip, true) && ContainsEndpoint(line.Clip, false);
 35179                    bool atEnd = (line.Edge + 1) % count == old.Edge
 35180                        && ContainsEndpoint(line.Clip, true) && ContainsEndpoint(old.Clip, false);
 35181                    if ((atStart || atEnd) && _mixedCapsuleBoundary.ContainsPoint(atStart ? default : Signed320.One,
 35182                        Signed320.One, line.Lower))
 31183                        _mixedRegionParents[FindMixedRegion(group)] = FindMixedRegion(other);
 184                }
 185            }
 186        }
 187
 188        static bool ContainsEndpoint(in RationalSegmentInterval clip, bool upper)
 189        {
 190            GetMixedBoundaryBounds(clip, out var ln, out var ld, out var un, out var ud);
 191            Signed320 n = upper ? Signed320.One : default;
 192            return RationalSegmentInterval.CompareParameters(ln, ld, n, Signed320.One) <= 0
 193                && RationalSegmentInterval.CompareParameters(un, ud, n, Signed320.One) >= 0;
 194        }
 1101195    }
 196
 197    private WideDirection3d MixedBoundaryLineNormal(in MixedBoundaryLine line)
 198    {
 16272199        if (line.Vertical != 0) return new(default, Signed576.ExtendValue(Signed192.Signed(line.Vertical)), default);
 7722200        MixedPrism prism = _mixedPrisms[line.Member];
 15444201        Vector2d a = prism.Offsets[line.Edge], b = prism.Offsets[(line.Edge + 1) % prism.Offsets.Length],
 7722202            inside = prism.Offsets[(line.Edge + 2) % prism.Offsets.Length];
 7722203        var triangle = new FixedTriangle(new(a.X, Fixed64.Zero, a.Y), new(b.X, Fixed64.Zero, b.Y), new(inside.X, Fixed64
 7722204        return prism.NativeFrame.GetInwardAxis(triangle, triangle.A, triangle.B);
 205    }
 206
 207    private static void GetMixedBoundaryBounds(in RationalSegmentInterval clip,
 208        out Signed320 ln, out Signed320 ld, out Signed320 un, out Signed320 ud)
 209    {
 21845210        Signed320 one = Signed320.One;
 43690211        ln = clip.IsClipped ? clip.LowerNumerator : default; ld = clip.IsClipped ? clip.LowerDenominator : one;
 43690212        un = clip.IsClipped ? clip.UpperNumerator : one; ud = clip.IsClipped ? clip.UpperDenominator : one;
 21845213    }
 214
 215    private static bool SameMixedBoundaryInterval(in RationalSegmentInterval a, in RationalSegmentInterval b)
 216    {
 2583217        GetMixedBoundaryBounds(a, out var ln, out var ld, out var un, out var ud);
 2583218        GetMixedBoundaryBounds(b, out var bln, out var bld, out var bun, out var bud);
 2583219        return RationalSegmentInterval.CompareParameters(ln, ld, bln, bld) == 0
 2583220            && RationalSegmentInterval.CompareParameters(un, ud, bun, bud) == 0;
 221    }
 222
 223    private readonly struct MixedBoundaryLine
 224    {
 225        internal readonly int Member, Edge, Vertical;
 226        internal readonly RationalSegmentInterval Clip;
 227        internal readonly Fixed64 Lower, Upper;
 228        internal MixedBoundaryLine(int member, int edge, int vertical, RationalSegmentInterval clip, Fixed64 lower, Fixe
 91413229        { Member = member; Edge = edge; Vertical = vertical; Clip = clip; Lower = lower; Upper = upper; }
 230    }
 231}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedCapsule.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.MixedCapsule.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 Gravitas.Colliders;
 12using Gravitas.CollisionHandling;
 13using SwiftCollections;
 14
 15namespace Gravitas;
 16
 17/// <content>Retains finite capsule support intervals on original native prism faces.</content>
 18public sealed partial class StaticSurface2D : IPrismCapsuleContactDomain
 19{
 20    private readonly PrismPointAdmission _mixedCapsuleAdmit;
 60021    private readonly SwiftList<RationalSegmentInterval> _mixedCapsuleCore = new();
 120022    private readonly SwiftList<bool> _mixedCapsuleSelected = new(), _mixedCapsuleUseCuts = new();
 60023    private readonly SwiftList<MixedCurvedFaceWindow> _mixedCapsuleParents = new();
 24    private bool _mixedCapsuleChoiceMade;
 25    private bool _mixedCapsuleRecovery;
 1424626    bool IPrismCapsuleContactDomain.IncludeRecovery => _mixedCapsuleRecovery;
 27
 28    private void BuildMixedCapsule()
 29    {
 333330        _mixedSphereGroups.FastClear(); _mixedSamples.FastClear(); _mixedRegionParents.FastClear();
 333331        _mixedCapsuleCore.FastClear(); _mixedCapsuleSelected.FastClear(); _mixedCapsuleUseCuts.FastClear();
 333332        _mixedCurvedBoundarySamples.FastClear(); _mixedOverlaps.Clear(); _mixedSpherePhysicalComponents.Clear();
 909533        for (int member = 0; member < _mixedLocal.Count; member++) _mixedCapsuleUseCuts.Add(false);
 111134        var capsule = (LSCapsuleCollider)_mixedMoving!;
 35        // Prepare topology before FMS borrows support intervals during callbacks.
 118836        if (!_mixedBoundaryLinesCurrent) PrepareMixedBoundaryLines();
 111137        _mixedCapsuleRecovery = false;
 676038        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 39        {
 227940            LSCollider2D member = _mixedLocal[_mixedMember];
 227941            if (!capsule.Bounds.Intersects(member.MixedBounds3D)) continue;
 162842            MixedPrism prism = _mixedPrisms[_mixedMember];
 162843            if (!prism.Joined)
 44            {
 1245                if (FixedConvexPrismRelations.TryGetCenteredCapsuleContact(capsule.Center, capsule.Rotation, Vector3d.Up
 1246                    capsule.AxisLength, capsule.ScaledRadius, MixedEmbedded2DGeometry.GetCenter3D(member),
 1247                    member.ConvexRotation, prism.Offsets, member.MixedHalfThickness, out var separate))
 1148                    RequestMixedReach(separate.Depth);
 1349                if (_mixedRequestedReach > _mixedReach) return;
 50                continue;
 51            }
 161652            VisitMember(member, prism);
 162553            if (_mixedRequestedReach > _mixedReach) return;
 54        }
 110155        AppendMixedCapsuleBoundaryPeaks(capsule);
 56        // Admitted geometry still connects finite patches, but only the chosen
 57        // source alternative contributes solver samples or blocks far recovery.
 823858        for (int sample = _mixedSamples.Count - 1; sample >= 0; sample--)
 316459            if (!_mixedCapsuleSelected[_mixedSamples[sample].Group]) _mixedSamples.RemoveAt(sample);
 287260            else _mixedSpherePhysicalComponents.Add(_mixedSphereGroups[_mixedSamples[sample].Group].Component);
 61        // Genuine local boundary constraints take precedence over a far exit
 62        // through the solid. Only wholly embedded components need that recovery search.
 110163        _mixedCapsuleRecovery = true;
 672464        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 65        {
 452866            LSCollider2D member = _mixedLocal[_mixedMember]; MixedPrism prism = _mixedPrisms[_mixedMember];
 226467            if (!prism.Joined || !_mixedOverlaps.Contains(member.Id)
 226468                || _mixedSpherePhysicalComponents.Contains(_mixedComponents[_mixedMember])) continue;
 969            VisitMember(member, prism);
 1270            if (_mixedRequestedReach > _mixedReach) return;
 71        }
 72
 73        void VisitMember(LSCollider2D member, MixedPrism prism)
 74        {
 75            _mixedCapsuleChoiceMade = _mixedCapsuleRecovery || _mixedBoundaryLines.Count == 0;
 76            WideConvexPrismRelations.VisitCapsuleContacts(capsule.Center, capsule.Rotation, capsule.AxisLength, capsule.
 77                MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation, prism.Offsets, member.MixedHalfThick
 78                _mixedCapsuleAdmit, this, out bool overlaps);
 79            if (overlaps) _mixedOverlaps.Add(member.Id);
 80            if (overlaps && !_mixedCapsuleChoiceMade)
 81                PrepareMixedCapsuleChoice(default, hasNative: false, hasParent: false);
 82        }
 109883    }
 84
 85    private void PrepareMixedCapsuleChoice(scoped in CapsulePrismContactDepth native, bool hasNative, bool hasParent)
 86    {
 20087        _mixedCapsuleChoiceMade = true;
 20088        var capsule = (LSCapsuleCollider)_mixedMoving!;
 40089        var member = _mixedLocal[_mixedMember]; var prism = _mixedPrisms[_mixedMember];
 20090        int start = _mixedCurvedBoundarySamples.Count;
 465291        for (int ordinal = 0; ordinal < _mixedBoundaryLines.Count; ordinal++)
 92        {
 212693            MixedBoundaryLine line = _mixedBoundaryLines[ordinal];
 212694            if (line.Member != _mixedMember) continue;
 72695            int face = line.Vertical == 0 ? line.Edge : line.Vertical > 0 ? -1 : -2;
 72696            var numeric = new PrismCurvedBoundaryLine(face, line.Clip, line.Lower, line.Upper);
 145297            _mixedCurvedActiveLines.FastClear(); _mixedCurvedActiveLines.Add(numeric);
 138998            if (hasParent) RemoveMixedCapsuleParentWindows(face);
 72699            bool unchanged = _mixedCurvedActiveLines.Count == 1
 726100                && _mixedCurvedActiveLines[0].Lower == line.Lower && _mixedCurvedActiveLines[0].Upper == line.Upper
 726101                && SameMixedBoundaryInterval(_mixedCurvedActiveLines[0].Clip, line.Clip);
 726102            _mixedCapsuleBoundary ??= new();
 726103            if (!_mixedCapsuleBoundary.TryGetContact(capsule.Center, capsule.Rotation, capsule.AxisLength, capsule.Scale
 726104                MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation, prism.Offsets[line.Edge],
 726105                prism.Offsets[(line.Edge + 1) % prism.Offsets.Length], prism.Offsets[(line.Edge + 2) % prism.Offsets.Len
 726106                line.Clip, line.Lower, line.Upper, line.Vertical, out var contact)) continue;
 181107            int comparison = hasNative && unchanged ? _mixedCapsuleBoundary.CompareDepth(native) : -1;
 181108            _mixedCurvedBoundarySamples.Add(new(ordinal, contact, comparison, !unchanged));
 181109            if (unchanged) continue;
 110            // The complete line still connects regions. Rank only its pieces
 111            // outside admitted parent faces, not a maximum attained inside one.
 168112            foreach (var cut in _mixedCurvedActiveLines.AsReadOnlySpan())
 5113                if (_mixedCapsuleBoundary.TryGetContact(capsule.Center, capsule.Rotation, capsule.AxisLength, capsule.Sc
 5114                    MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation, prism.Offsets[line.Edge],
 5115                    prism.Offsets[(line.Edge + 1) % prism.Offsets.Length], prism.Offsets[(line.Edge + 2) % prism.Offsets
 5116                    cut.Clip, cut.Lower, cut.Upper, line.Vertical, out contact))
 4117                    _mixedCurvedBoundarySamples.Add(new(ordinal, contact, _mixedCapsuleBoundary.CompareDepth(native)));
 118        }
 200119        var cuts = _mixedCurvedBoundarySamples.AsReadOnlySpan()[start..];
 200120        bool useCuts = false;
 121        // A finite cut family needs every independent row. Its exact maximum
 122        // competes with the native exit; ties preserve that native alternative.
 662123        foreach (var cut in cuts)
 124        {
 145125            if (cut.GeometryOnly) continue;
 134126            if (cut.CompareToNative >= 0) { useCuts = false; break; }
 50127            useCuts = true;
 128        }
 200129        _mixedCapsuleUseCuts[_mixedMember] = useCuts && AreMixedCurvedCutRowsCompatible(cuts);
 200130    }
 131
 132    private void RemoveMixedCapsuleParentWindows(int face)
 133    {
 2728134        foreach (var parent in _mixedCapsuleParents.AsReadOnlySpan())
 135        {
 701136            if (parent.Face != face) continue;
 1412137            for (int index = _mixedCurvedActiveLines.Count - 1; index >= 0; index--)
 138            {
 350139                var line = _mixedCurvedActiveLines[index];
 700140                Fixed64 lower = FixedMath.Max(line.Lower, parent.Lower), upper = FixedMath.Min(line.Upper, parent.Upper)
 350141                if (lower > upper || !TryIntersectMixedIntervals(line.Clip, parent.Interval, out var overlap)) continue;
 336142                _mixedCurvedActiveLines.RemoveAt(index);
 336143                if (line.Lower != line.Upper)
 144                {
 206145                    if (line.Lower < lower) _mixedCurvedActiveLines.Add(new(face, line.Clip, line.Lower, lower));
 135146                    if (upper < line.Upper) _mixedCurvedActiveLines.Add(new(face, line.Clip, upper, line.Upper));
 147                }
 148                else
 149                {
 203150                    GetMixedBoundaryBounds(line.Clip, out var ln, out var ld, out var un, out var ud);
 203151                    GetMixedBoundaryBounds(overlap, out var oln, out var old, out var oun, out var oud);
 203152                    if (RationalSegmentInterval.CompareParameters(ln, ld, oln, old) < 0)
 17153                        _mixedCurvedActiveLines.Add(new(face, new(ln, ld, oln, old), line.Lower, line.Upper));
 203154                    if (RationalSegmentInterval.CompareParameters(oun, oud, un, ud) < 0)
 16155                        _mixedCurvedActiveLines.Add(new(face, new(oun, oud, un, ud), line.Lower, line.Upper));
 156                }
 157            }
 158        }
 663159    }
 160
 161    ReadOnlySpan<RationalSegmentInterval> IPrismCapsuleContactDomain.GetSupportIntervals(in WideDirection3d normal,
 162        ReadOnlySpan<Signed832> projected, Signed832 denominator, in RationalSegmentInterval solidClip)
 163    {
 3089164        _mixedIntervals.FastClear();
 3089165        _mixedCapsuleParents.FastClear();
 3089166        WideDirection3d supportNormal = normal;
 3089167        MixedPrism prism = _mixedPrisms[_mixedMember];
 3089168        LSCollider2D member = _mixedLocal[_mixedMember];
 12780169        for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 170        {
 3301171            MixedBand band = prism.Bands[bandIndex];
 33904172            foreach (var span in band.Boundary.Spans)
 13651173                if (span.Kind != SpanKind.Joined
 13651174                    && WideConvexPrismRelations.TryClipProjectedPrismFace(projected, denominator, member.ConvexRotation,
 13651175                        span.Start, span.End, span.Interval, band.Lower, band.Upper, solidClip, out var retained))
 5482176                { Keep(retained); KeepParent(span.First, span.Interval, band.Lower, band.Upper); }
 177        }
 18534178        for (int cap = 0; cap < 2; cap++)
 179        {
 6178180            Fixed64 height = cap == 0 ? -member.MixedHalfThickness : member.MixedHalfThickness;
 6178181            if (WideConvexPrismRelations.TryClipProjectedPrismFace(projected, denominator, member.ConvexRotation,
 6178182                default, default, default, height, height, solidClip, out var retained, cap: true))
 183            {
 574184                bool onEdge = false;
 3646185                for (int edge = 0; edge < prism.Offsets.Length; edge++)
 186                {
 3372187                    Vector2d a = prism.Offsets[edge], b = prism.Offsets[(edge + 1) % prism.Offsets.Length];
 1686188                    if (!WideConvexPrismRelations.TryClipProjectedPrismFace(projected, denominator, member.ConvexRotatio
 1686189                        a, b, default, height, height, retained, out var edgeClip)
 1686190                        || !SameMixedCapsuleIntervalWide(edgeClip, retained)) continue;
 191                    // A cap support along its footprint rim may cross a taller
 192                    // neighbor. Retain its exact fan windows, not one midpoint.
 4830193                    foreach (var span in prism.Bands[cap == 0 ? 0 : prism.BandCount - 1].Boundary.Spans)
 1978194                        if (span.First == edge && WideConvexPrismRelations.TryClipProjectedPrismFace(projected, denomina
 2415195                            member.ConvexRotation, a, b, span.Interval, height, height, retained, out var window)) Keep(
 874196                    onEdge = true; break;
 197                }
 711198                if (!onEdge) Keep(retained);
 574199                KeepParent(cap == 0 ? -1 : -2, default, height, height);
 200            }
 201        }
 3089202        return _mixedIntervals.AsReadOnlySpan();
 203
 204        void Keep(in RationalSegmentInterval interval)
 205        {
 206            foreach (var previous in _mixedIntervals)
 207                if (SameMixedCapsuleIntervalWide(previous, interval)) return;
 208            _mixedIntervals.Add(interval);
 209        }
 210        void KeepParent(int face, in RationalSegmentInterval interval, Fixed64 lower, Fixed64 upper)
 211        {
 212            GetMixedCurvedPlane(_mixedMember, face, out var axis, out _);
 213            if (WideDirection3d.AreParallel(supportNormal, axis) && WideDirection3d.Dot(supportNormal, axis).Sign > 0)
 214                _mixedCapsuleParents.Add(new(face, interval, lower, upper));
 215        }
 216    }
 217
 218    private static bool SameMixedCapsuleIntervalWide(in RationalSegmentInterval a, in RationalSegmentInterval b)
 219    {
 1032220        Signed832 one = Signed832.ExtendValue(Signed192.Signed(1));
 1032221        return RationalSegmentInterval.CompareParameters(a.IsClipped ? a.WideLowerNumerator : default,
 1032222            a.IsClipped ? a.WideLowerDenominator : one, b.IsClipped ? b.WideLowerNumerator : default,
 1032223            b.IsClipped ? b.WideLowerDenominator : one) == 0
 1032224            && RationalSegmentInterval.CompareParameters(a.IsClipped ? a.WideUpperNumerator : one,
 1032225                a.IsClipped ? a.WideUpperDenominator : one, b.IsClipped ? b.WideUpperNumerator : one,
 1032226                b.IsClipped ? b.WideUpperDenominator : one) == 0;
 227    }
 228
 229    void IPrismCapsuleContactDomain.AddSupportContact(in FixedContactAnchors contact, scoped in CapsulePrismContactDepth
 230        in WideConvexPrismRelations.ProjectionDepth depth, bool physical, int interval)
 231    {
 3054232        if (!_mixedCapsuleChoiceMade) PrepareMixedCapsuleChoice(native, hasNative: true, hasParent: true);
 2873233        int component = _mixedComponents[_mixedMember];
 2873234        RationalPoint3d reference = MixedSupportPoint(_mixedPrisms[_mixedMember].NativeFrame, _mixedPrisms[_mixedMember]
 2873235        int group = AddMixedCapsuleSample(new(component, _mixedLocal[_mixedMember].Id, _mixedMember,
 2873236            normal, reference, depth, contact, !physical), _mixedIntervals[interval],
 2873237            _mixedCapsuleRecovery || !_mixedCapsuleUseCuts[_mixedMember]);
 2873238        if (physical)
 239            // A common component/plane alone does not declare a local join:
 240            // an ambiguous cap can connect to the same component elsewhere.
 13806241            for (int previous = 0; previous < group; previous++)
 4039242                if (SameMixedCapsulePlane(group, previous)
 4039243                    && (_mixedSphereGroups[previous].Supplier == _mixedMember || _mixedFan.Contains(_mixedSphereGroups[p
 4039244                    && TryIntersectMixedIntervals(_mixedCapsuleCore[group], _mixedCapsuleCore[previous], out _))
 2775245                    _mixedRegionParents[FindMixedRegion(group)] = FindMixedRegion(previous);
 2873246        RequestMixedReach(contact.Depth);
 2873247    }
 248
 249    private int AddMixedCapsuleSample(in SphereGroup row, in RationalSegmentInterval core, bool selected = true)
 250    {
 3042251        int group = _mixedSphereGroups.Count;
 9126252        _mixedSphereGroups.Add(row); _mixedCapsuleCore.Add(core); _mixedRegionParents.Add(group);
 3042253        _mixedCapsuleSelected.Add(selected);
 3042254        bool represented = row.Contact.SecondAnchor.TryGetPointInFrame(_mixedMoving!.Center, out Vector3d point);
 255        System.Diagnostics.Debug.Assert(represented);
 3042256        _mixedSamples.Add(new(group, row.Supplier, point, row.Contact));
 3042257        return group;
 258    }
 259
 260    private bool SameMixedCapsulePlane(int a, int b)
 261    {
 9930262        SphereGroup first = _mixedSphereGroups[a], second = _mixedSphereGroups[b];
 4965263        return first.Component == second.Component && WideDirection3d.AreParallel(first.Axis, second.Axis)
 4965264            && WideDirection3d.Dot(first.Axis, second.Axis).Sign > 0
 4965265            && WideTriangleRelations.DotScaledDirections(first.Axis, WideTriangleRelations.GetScaledPointDifference(
 4965266                first.Reference, second.Reference, Signed192.Signed(1))).IsZero;
 267    }
 268
 269    ReadOnlySpan<RationalSegmentInterval> IPrismCapsuleContactDomain.GetEdgeIntervals(int vertex, int kind)
 270    {
 1956271        GetMixedCapsuleEdge(vertex, kind, out int start, out int end);
 1956272        GetMixedEdgeIntervals(start, end);
 273        // Several height bands can map the same original cap edge window.
 8096274        for (int index = _mixedIntervals.Count - 1; index >= 0; index--)
 4364275            for (int previous = 0; previous < index; previous++)
 174276                if (SameMixedCapsuleIntervalWide(_mixedIntervals[index], _mixedIntervals[previous]))
 168277                { _mixedIntervals.RemoveAt(index); break; }
 1956278        return _mixedIntervals.AsReadOnlySpan();
 279    }
 280
 281    bool IPrismCapsuleContactDomain.AdmitEdgePoint(int vertex, int kind, in Signed832 edgeN,
 282        in Signed832 edgeD, in WideDirection3d normal)
 283    {
 200284        GetMixedCapsuleEdge(vertex, kind, out int start, out int end);
 200285        MixedPrism prism = _mixedPrisms[_mixedMember];
 400286        Vector3d a = prism.Points[start], b = prism.Points[end];
 287        const int words = 32;
 400288        Span<ulong> values = stackalloc ulong[12 * words]; Span<int> signs = stackalloc int[12];
 400289        var n = ContactQuadratic.At(values, signs, 0, words); var d = ContactQuadratic.At(values, signs, 1, words);
 400290        var y = ContactQuadratic.At(values, signs, 2, words); var yd = ContactQuadratic.At(values, signs, 3, words);
 200291        var term = ContactQuadratic.At(values, signs, 4, words);
 400292        n.Set(edgeN); d.Set(edgeD);
 200293        ContactQuadratic.Scale(d, Signed576.ExtendValue(Signed192.Raw(a.Y)), y);
 400294        ContactQuadratic.Scale(n, Signed576.ExtendValue(Signed192.Raw(b.Y - a.Y)), term); y.Add(term);
 200295        d.CopyTo(yd);
 576296        if (kind == 2) { n.Clear(); d.Set(Signed576.ExtendValue(Signed192.Signed(1))); }
 200297        return AdmitMixedSphereFan(new(new(a.X, Fixed64.Zero, a.Z), new(b.X, Fixed64.Zero, b.Z)), n, d, y, yd, normal);
 298    }
 299
 300    void IPrismCapsuleContactDomain.AddEdgeContact(in FixedContactAnchors contact, scoped in CapsulePrismContactDepth na
 301        int vertex, int kind, int interval)
 302    {
 303        // Every admitted edge pair supports the entire convex prism and core,
 304        // so distinct callbacks have the same certified closest-pair depth.
 6305        if (!_mixedCapsuleChoiceMade) PrepareMixedCapsuleChoice(native, hasNative: true, hasParent: false);
 8306        MixedPrism prism = _mixedPrisms[_mixedMember]; int component = _mixedComponents[_mixedMember];
 4307        AddMixedCapsuleSample(new(component, _mixedLocal[_mixedMember].Id, _mixedMember, normal,
 4308            MixedSupportPoint(prism.NativeFrame, prism, normal), default, contact), default,
 4309            !_mixedCapsuleUseCuts[_mixedMember]);
 4310        RequestMixedReach(contact.Depth);
 4311    }
 312
 313    private void GetMixedCapsuleEdge(int vertex, int kind, out int start, out int end)
 314    {
 5237315        int count = _mixedPrisms[_mixedMember].Offsets.Length;
 5237316        start = vertex * 2 + (kind == 1 ? 1 : 0);
 5237317        end = kind == 2 ? start + 1 : ((vertex + 1) % count) * 2 + (kind == 1 ? 1 : 0);
 5237318    }
 319
 320    private bool AppendMixedCapsule(LSCollider2D overlap, ContactManifold destination, int namespace3D, int namespace2D)
 321    {
 1777322        Span<int> chosen = stackalloc int[ContactManifold.MaxContactsPerGroup];
 1777323        SolidBody? body = _mixedMoving!.Body ?? _mixedMoving.CompoundOwner?.Body;
 1777324        var center = body == null ? new FixedPointAnchor(_mixedMoving.Center, _mixedMoving.Rotation, Vector3d.Zero)
 1777325            : new FixedPointAnchor(body.Position3d, body.Rotation, body.LocalCenterOfMassOffset);
 14288326        for (int group = 0; group < _mixedSphereGroups.Count; group++)
 327        {
 5367328            if (FindMixedRegion(group) != group) continue;
 2225329            SphereGroup row = _mixedSphereGroups[group];
 2225330            if (row.Carrier != overlap.Id) continue;
 1364331            if (row.Recovery)
 332            {
 6333                bool better = false;
 26334                for (int other = 0; other < _mixedSphereGroups.Count; other++)
 9335                    if (_mixedCapsuleSelected[other] && _mixedSphereGroups[other].Component == row.Component)
 336                    {
 337                        System.Diagnostics.Debug.Assert(_mixedSphereGroups[other].Recovery);
 9338                        int order = WideConvexPrismRelations.CompareProjectionDepths(_mixedSphereGroups[other].Depth, ro
 13339                        if (order < 0 || order == 0 && other < group) { better = true; break; }
 340                    }
 6341                if (better) continue;
 342            }
 1362343            AppendMixedRegionSamples(group, row.Axis, destination, namespace3D, namespace2D, chosen, center);
 344        }
 1777345        return _mixedOverlaps.Contains(overlap.Id);
 346    }
 347}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedCurved.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.MixedCurved.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 Gravitas.Colliders;
 12using Gravitas.CollisionHandling;
 13using SwiftCollections;
 14
 15namespace Gravitas;
 16
 17/// <content>Retains native cylinder/cone supports on exposed prism face windows.</content>
 18public sealed partial class StaticSurface2D
 19{
 20    private ConePrismBoundaryContacts? _mixedConeBoundary;
 60021    private readonly SwiftList<CurvedGroup> _mixedCurvedGroups = new();
 60022    private readonly SwiftList<int> _mixedCurvedCarriers = new();
 60023    private readonly SwiftList<PrismCurvedBoundaryLine> _mixedCurvedActiveLines = new();
 60024    private readonly SwiftList<CurvedBoundarySample> _mixedCurvedBoundarySamples = new();
 25    private PrismCurvedBoundaryContactVisitor? _mixedCurvedBoundaryVisitor;
 26
 27    private void BuildMixedCurved()
 28    {
 252829        _mixedSamples.FastClear(); _mixedCurvedGroups.FastClear(); _mixedRegionParents.FastClear(); _mixedOverlaps.Clear
 126430        _mixedSpherePhysicalComponents.Clear(); _mixedCurvedCarriers.FastClear();
 607931        for (int member = 0; member < _mixedLocal.Count; member++) _mixedCurvedCarriers.Add(-1);
 63232        LSCollider mover = _mixedMoving!;
 63233        bool cone = mover is LSConeCollider;
 63234        Fixed64 height = cone ? ((LSConeCollider)mover).Height : ((LSCylinderCollider)mover).Height;
 63235        Span<WideDirection3d> vertices = stackalloc WideDirection3d[32];
 36        // Geometric overlap belongs to each member; a finite support supplier
 37        // can lie elsewhere in that same declared component.
 447438        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 39        {
 321040            LSCollider2D member = _mixedLocal[_mixedMember]; MixedPrism prism = _mixedPrisms[_mixedMember];
 160541            if (!mover.Bounds.Intersects(member.MixedBounds3D)
 160542                || !WideConvexPrismRelations.IntersectsCurvedPrism(cone, mover.Center, mover.Rotation, Vector3d.Up,
 160543                    height, mover.ScaledRadius, MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation,
 160544                    prism.Offsets, member.MixedHalfThickness)) continue;
 112445            _mixedOverlaps.Add(member.Id);
 224846            int component = _mixedComponents[_mixedMember], carrier = _mixedCurvedCarriers[component];
 176447            if (carrier < 0) _mixedCurvedCarriers[component] = member.Id;
 48        }
 74949        if (!_mixedBoundaryLinesCurrent) PrepareMixedBoundaryLines();
 63250        PrepareMixedCurvedCertificates(cone, height, vertices);
 444851        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 52        {
 159953            if (!_mixedOverlaps.Contains(_mixedLocal[_mixedMember].Id)) continue;
 111854            VisitMixedCurvedMember(cone, height, vertices, farBoundary: false);
 112555            if (_mixedRequestedReach > _mixedReach) return;
 56        }
 57        // Far certificates are needed only when no genuine physical boundary
 58        // exists in a component; ordinary exterior contacts skip that work.
 62559        PrepareMixedCurvedCertificates(cone, height, vertices, farBoundary: true);
 443260        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 61        {
 159162            if (!_mixedPrisms[_mixedMember].Joined || _mixedCurvedCarriers[_mixedComponents[_mixedMember]] < 0
 159163                || _mixedSpherePhysicalComponents.Contains(_mixedComponents[_mixedMember])) continue;
 2664            VisitMixedCurvedMember(cone, height, vertices, farBoundary: true);
 65        }
 62566        CompleteMixedCurvedRegions(cone, height, vertices);
 62567        RequestMixedCurvedFarReach();
 62568    }
 69
 70    private void VisitMixedCurvedMember(bool cone, Fixed64 height, Span<WideDirection3d> vertices, bool farBoundary)
 71    {
 114472        LSCollider mover = _mixedMoving!;
 228873        LSCollider2D member = _mixedLocal[_mixedMember]; MixedPrism prism = _mixedPrisms[_mixedMember];
 114474        Vector3d origin = MixedEmbedded2DGeometry.GetCenter3D(member);
 114475        if (!prism.Joined)
 76        {
 1277            bool ordinaryContactFound = CurvedPrismContact.TryGetContact(mover.Center, mover.Rotation, Vector3d.Up, heig
 1278                origin, member.ConvexRotation, prism.Offsets, member.MixedHalfThickness, cone, out var separate);
 79            System.Diagnostics.Debug.Assert(ordinaryContactFound);
 1280            RequestMixedReach(separate.Depth);
 1281            return;
 82        }
 113283        var geometry = new CurvedPrismContactGeometry(mover.Center, mover.Rotation, Vector3d.Up,
 113284            height, mover.ScaledRadius, origin, member.ConvexRotation, prism.Offsets, member.MixedHalfThickness, cone, v
 113285        var prepared = PrepareMixedCurvedDomain(geometry, farBoundary);
 113286        _mixedCurvedActiveLines.FastClear();
 113287        if (!farBoundary)
 748688            foreach (var line in _mixedCurvedDomains[_mixedMember].Lines.AsReadOnlySpan())
 89            {
 263790                bool parent = false;
 4303691                foreach (var proof in _mixedCurvedCertificates.AsReadOnlySpan())
 1935592                    if (proof.Physical && proof.Member == _mixedMember && proof.Window.Face == line.Face
 2125193                        && ContainsMixedCurvedBoundaryWindow(proof.Window, line)) { parent = true; break; }
 94                // An own admitted parent MAX dominates its subset line. A
 95                // borrowed coplanar proof may live in a disconnected window;
 96                // it remains a native bound, not this line's parent admission.
 432697                if (!parent) _mixedCurvedActiveLines.Add(line);
 98            }
 113299        ReadOnlySpan<PrismCurvedBoundaryLine> lines = _mixedCurvedActiveLines.AsReadOnlySpan();
 2264100        _mixedCurvedBoundarySamples.FastClear(); _mixedCurvedBoundaryVisitor ??= KeepMixedCurvedBoundary;
 1142101        if (cone && !lines.IsEmpty) _mixedConeBoundary ??= new();
 1132102        var domain = new PrismCurvedContactDomain(prepared.Edges, prepared.FanCovectors, includeFarBoundary: farBoundary
 1132103        bool found = CurvedPrismContact.TryGetContact(geometry, domain, mover.Center, mover.Rotation, origin,
 1132104            out var contact, out int face, out bool physical, out int certificate,
 1132105            lines, _mixedCurvedBoundaryVisitor, _mixedConeBoundary);
 106        // One source has two response alternatives: its whole-prism native exit
 107        // or its complete independent finite cut set. The latter needs every
 108        // constraint, so compare the native depth to the set's exact maximum.
 109        // FMS streams comparisons while its native algebraic selection is alive;
 110        // these buffers retain only ordinary contact payloads and line ordinals.
 1132111        bool useCuts = _mixedCurvedBoundarySamples.Count > 0;
 2789112        foreach (var sample in _mixedCurvedBoundarySamples.AsReadOnlySpan())
 630113            if (sample.CompareToNative >= 0) { useCuts = false; break; }
 1143114        if (useCuts && !AreMixedCurvedCutRowsCompatible(_mixedCurvedBoundarySamples.AsReadOnlySpan())) useCuts = false;
 1132115        if (useCuts)
 116        {
 482117            foreach (var sample in _mixedCurvedBoundarySamples.AsReadOnlySpan())
 118            {
 159119                var line = lines[sample.Ordinal];
 159120                AddMixedCurvedSample(sample.Contact, line.Face, true, line.Clip, line.Lower, line.Upper, line.BoundaryEd
 121            }
 122        }
 1050123        else if (found)
 124        {
 125            // Decide the source obligation before pooling actual supplier
 126            // windows. Borrowed suppliers keep their identities even when their
 127            // own source subsequently selects a different response family.
 2051128            if (certificate >= 0) AddMixedCurvedCertificatePlane(_mixedCurvedCertificateSources[certificate], physical);
 5129            else AddMixedCurvedSample(contact, face, physical);
 130        }
 27131    }
 132
 133    private static bool ContainsMixedCurvedBoundaryWindow(in MixedCurvedFaceWindow window, in PrismCurvedBoundaryLine li
 134    {
 1286135        if (window.Lower > line.Lower || window.Upper < line.Upper) return false;
 136        // A complete original cap contains every original footprint edge.
 1858137        if (window.Face < 0 || !window.Interval.IsClipped) return true;
 46138        var interval = line.Clip;
 46139        Signed832 one = Signed832.ExtendValue(Signed192.Signed(1));
 46140        Signed832 ln = interval.IsClipped ? interval.WideLowerNumerator : default,
 46141            ld = interval.IsClipped ? interval.WideLowerDenominator : one,
 46142            un = interval.IsClipped ? interval.WideUpperNumerator : one,
 46143            ud = interval.IsClipped ? interval.WideUpperDenominator : one;
 46144        return RationalSegmentInterval.CompareParameters(ln, ld, window.Interval.WideLowerNumerator, window.Interval.Wid
 46145            && RationalSegmentInterval.CompareParameters(un, ud, window.Interval.WideUpperNumerator, window.Interval.Wid
 146    }
 147    // This checks the published solver rows, not exact geometric admission or
 148    // depth ranking. Prism faces are horizontal normals or +/-Y, so translation
 149    // compatibility separates into one planar semicircle and two vertical signs.
 150    private static bool AreMixedCurvedCutRowsCompatible(ReadOnlySpan<CurvedBoundarySample> samples)
 151    {
 2885152        bool up = false, down = false, positiveUp = false, positiveDown = false, positiveHorizontal = false;
 2672153        foreach (var sample in samples)
 154        {
 759155            if (sample.GeometryOnly) continue;
 1500156            Vector3d normal = sample.Contact.Normal; bool positive = sample.Contact.Depth > Fixed64.Zero;
 794157            if (normal.Y > Fixed64.Zero) { up = true; positiveUp |= positive; }
 818158            else if (normal.Y < Fixed64.Zero) { down = true; positiveDown |= positive; }
 683159            else positiveHorizontal |= positive;
 160        }
 581161        if (up && down && (positiveUp || positiveDown)) return false;
 600162        if (!positiveHorizontal) return true;
 546163        bool semicircle = false;
 2421164        foreach (var first in samples)
 165        {
 672166            if (first.GeometryOnly) continue;
 663167            Vector3d normal = first.Contact.Normal;
 663168            if (normal.Y != Fixed64.Zero) continue;
 658169            var axis = new WideDirection3d(Signed576.ExtendValue(Signed192.Raw(normal.X)), default,
 658170                Signed576.ExtendValue(Signed192.Raw(normal.Z)));
 658171            bool contains = true;
 3243172            foreach (var second in samples)
 173            {
 971174                if (second.GeometryOnly) continue;
 952175                Vector3d other = second.Contact.Normal;
 952176                if (other.Y != Fixed64.Zero) continue;
 945177                var candidate = new WideDirection3d(Signed576.ExtendValue(Signed192.Raw(other.X)), default,
 945178                    Signed576.ExtendValue(Signed192.Raw(other.Z)));
 945179                int cross = WideDirection3d.Cross(axis, candidate).Y.Sign;
 960180                if (cross < 0) contains = false;
 930181                else if (cross == 0 && WideDirection3d.Dot(axis, candidate).Sign < 0
 945182                    && (first.Contact.Depth > Fixed64.Zero || second.Contact.Depth > Fixed64.Zero)) return false;
 183            }
 184            // Inspect all pivots even after finding a semicircle: a positive
 185            // duplicate of either zero-depth extreme can forbid that motion.
 643186            semicircle |= contains;
 187        }
 531188        return semicircle;
 189    }
 190    private void KeepMixedCurvedBoundary(int ordinal, in FixedContactAnchors contact, int compareToNative) =>
 961191        _mixedCurvedBoundarySamples.Add(new(ordinal, contact, compareToNative));
 192
 193    private readonly struct CurvedBoundarySample
 194    {
 195        internal readonly int Ordinal, CompareToNative;
 196        internal readonly bool GeometryOnly;
 197        internal readonly FixedContactAnchors Contact;
 198        internal CurvedBoundarySample(int ordinal, FixedContactAnchors contact, int compareToNative, bool geometryOnly =
 8395199        { Ordinal = ordinal; Contact = contact; CompareToNative = compareToNative; GeometryOnly = geometryOnly; }
 200    }
 201    private void AddMixedCurvedSample(in FixedContactAnchors contact, int face, bool physical,
 202        RationalSegmentInterval clip = default, Fixed64 lower = default, Fixed64 upper = default, int boundaryEdge = -1)
 203    {
 1006204        bool represented = contact.SecondAnchor.TryGetPointInFrame(_mixedMoving!.Center, out Vector3d point);
 205        System.Diagnostics.Debug.Assert(represented);
 1006206        _mixedSamples.Add(new(_mixedCurvedGroups.Count, _mixedMember, point, contact));
 1006207        GetMixedCurvedPlaneForRow(_mixedMember, face, contact, out var axis, out var reference);
 1006208        _mixedCurvedGroups.Add(new(_mixedMember, face, clip, lower, upper, boundaryEdge, !physical, axis, reference));
 1006209        _mixedRegionParents.Add(_mixedRegionParents.Count);
 2978210        if (physical) { _mixedSpherePhysicalComponents.Add(_mixedComponents[_mixedMember]); RequestMixedReach(contact.De
 1006211    }
 212
 213    private bool AppendMixedCurved(LSCollider2D overlap, ContactManifold destination, int namespace3D, int namespace2D)
 214    {
 215#if DEBUG
 216        // This checks completeness of the admitted candidate inventory; it is
 217        // not another geometry restriction. Keep the extra scan out of Release.
 218        int component = -1;
 219        for (int member = 0; member < _mixedLocal.Count; member++)
 220            if (_mixedLocal[member] == overlap && _mixedOverlaps.Contains(overlap.Id))
 221            { component = _mixedComponents[member]; break; }
 222        if (component >= 0 && (_mixedMoving!.Body ?? _mixedMoving.CompoundOwner?.Body) is { HasSolverMobility: true })
 223        {
 224            bool boundary = false;
 225            foreach (MixedSample sample in _mixedSamples.AsReadOnlySpan())
 226                boundary |= _mixedComponents[sample.Supplier] == component;
 227            System.Diagnostics.Debug.Assert(boundary,
 228                "A response-required closed-solid overlap must retain an admitted boundary constraint.");
 229        }
 230#endif
 1166231        AppendMixedCurvedRegions(overlap, destination, namespace3D, namespace2D);
 1166232        return _mixedOverlaps.Contains(overlap.Id);
 233    }
 234
 235    private readonly struct CurvedGroup
 236    {
 237        internal readonly int Member, Face, BoundaryEdge;
 238        internal readonly RationalSegmentInterval Clip;
 239        internal readonly Fixed64 Lower, Upper;
 240        internal readonly bool FarBoundary;
 241        internal readonly WideDirection3d Axis;
 242        internal readonly RationalPoint3d Reference;
 243        internal CurvedGroup(int member, int face, RationalSegmentInterval clip, Fixed64 lower, Fixed64 upper,
 244            int boundaryEdge, bool farBoundary, WideDirection3d axis, RationalPoint3d reference)
 245        {
 5030246            Member = member; Face = face; Clip = clip; Lower = lower; Upper = upper;
 4024247            BoundaryEdge = boundaryEdge; FarBoundary = farBoundary; Axis = axis; Reference = reference;
 1006248        }
 249    }
 250}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedCurved.Domain.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.MixedCurved.Domain.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 Gravitas.CollisionHandling;
 13using SwiftCollections;
 14
 15namespace Gravitas;
 16
 17/// <content>Reuses prepared native boundary strata and their exact incident support fans.</content>
 18public sealed partial class StaticSurface2D
 19{
 60020    private readonly SwiftList<MixedCurvedDomain> _mixedCurvedDomains = new();
 60021    private readonly SwiftList<RationalSegmentInterval> _mixedCurvedCuts = new();
 60022    private readonly SwiftList<MixedCurvedCertificate> _mixedCurvedCertificates = new();
 60023    private readonly SwiftList<PrismCurvedFaceCertificate> _mixedCurvedFaceCertificates = new();
 120024    private readonly SwiftList<int> _mixedCurvedCertificateSources = new(), _mixedCurvedCertificateGroups = new();
 25    private bool _mixedCurvedDomainsCurrent;
 126    private static readonly IComparer<RationalSegmentInterval> MixedCurvedCutOrder =
 127        Comparer<RationalSegmentInterval>.Create(static (a, b) => RationalSegmentInterval.CompareParameters(
 128            a.WideLowerNumerator, a.WideLowerDenominator, b.WideLowerNumerator, b.WideLowerDenominator));
 29
 30    private PrismCurvedContactDomain PrepareMixedCurvedDomain(in CurvedPrismContactGeometry geometry, bool farBoundary)
 31    {
 113232        MixedCurvedDomain domain = _mixedCurvedDomains[_mixedMember];
 138933        if (!domain.EdgesCurrent) PrepareMixedCurvedEdges(domain);
 113234        domain.ActiveEdges.FastClear();
 113235        if (!farBoundary)
 10122636            foreach (var edge in domain.Edges.AsReadOnlySpan())
 5822037                if (CurvedPrismContact.IntersectsRealEdge(geometry, edge.Edge, edge.Interval)) domain.ActiveEdges.Add(ed
 113238        ReadOnlySpan<PrismCurvedEdgeWindow> edges = farBoundary ? domain.Edges.AsReadOnlySpan() : domain.ActiveEdges.AsR
 113239        domain.LocalFans.FastClear();
 34751240        foreach (WideDirection3d world in edges.IsEmpty ? ReadOnlySpan<WideDirection3d>.Empty : domain.WorldFans.AsReadO
 41        {
 42            // Native points share Q^2. Their full-domain differences need fewer
 43            // than 131 bits, and B^T adds at most 65: no coordinate is rounded.
 17262444            var delta = new WideAxis3(Signed320.NarrowValue(world.X),
 17262445                Signed320.NarrowValue(world.Y), Signed320.NarrowValue(world.Z));
 17262446            WideRigidProjection.GetLocalAxisProjections(delta, geometry.WorldBasis, out var x, out var y, out var z);
 17262447            domain.LocalFans.Add(new(x, y, z));
 48        }
 226449        _mixedCurvedFaceCertificates.FastClear(); _mixedCurvedCertificateSources.FastClear();
 1584650        for (int face = -2; face < _mixedPrisms[_mixedMember].Offsets.Length; face++)
 51        {
 679152            GetMixedCurvedPlane(_mixedMember, face, out var axis, out var reference);
 7553453            for (int certificate = 0; certificate < _mixedCurvedCertificates.Count; certificate++)
 54            {
 3097655                MixedCurvedCertificate source = _mixedCurvedCertificates[certificate];
 3097656                if (_mixedComponents[source.Member] != _mixedComponents[_mixedMember]
 3097657                    || !SameMixedCurvedPlane(axis, reference, source.Axis, source.Reference)) continue;
 265958                _mixedCurvedFaceCertificates.Add(new(face, source.Contact, source.Physical));
 265959                _mixedCurvedCertificateSources.Add(certificate);
 60            }
 61        }
 113262        return new(edges, domain.LocalFans.AsReadOnlySpan(),
 113263            certificates: _mixedCurvedFaceCertificates.AsReadOnlySpan());
 64    }
 65
 66    private void PrepareMixedCurvedDomains()
 67    {
 11768        int original = _mixedMember;
 61369        while (_mixedCurvedDomains.Count < _mixedLocal.Count) _mixedCurvedDomains.Add(new());
 82270        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 71        {
 29472            MixedPrism prism = _mixedPrisms[_mixedMember];
 29473            MixedCurvedDomain domain = _mixedCurvedDomains[_mixedMember];
 29474            domain.Faces.FastClear();
 58875            domain.Lines.FastClear(); domain.EdgesCurrent = false;
 401676            foreach (var line in _mixedBoundaryLines.AsReadOnlySpan())
 171477                if (line.Member == _mixedMember)
 41878                    domain.Lines.Add(new(line.Vertical == 0 ? line.Edge : line.Vertical > 0 ? -1 : -2,
 41879                        line.Clip, line.Lower, line.Upper, line.Vertical == 0 ? -1 : line.Edge));
 139480            for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 81            {
 40382                MixedBand band = prism.Bands[bandIndex];
 418683                foreach (var span in band.Boundary.Spans)
 169084                    if (span.Kind != SpanKind.Joined)
 121885                        KeepMixedCurvedWindow(domain, new(span.First, span.Interval, band.Lower, band.Upper));
 86            }
 29487            Fixed64 half = _mixedLocal[_mixedMember].MixedHalfThickness;
 58888            domain.Faces.Add(new(-1, default, -half, -half)); domain.Faces.Add(new(-2, default, half, half));
 29489            _mixedCurvedActiveLines.EnsureCapacity(domain.Lines.Count);
 29490            _mixedCurvedBoundarySamples.EnsureCapacity(domain.Lines.Count);
 91        }
 23492        _mixedMember = original; _mixedCurvedDomainsCurrent = true;
 11793    }
 94
 95    private void PrepareMixedCurvedEdges(MixedCurvedDomain domain)
 96    {
 51497        domain.Edges.FastClear(); domain.WorldFans.FastClear();
 98        // Nearby members may only supply a face witness. Build their larger
 99        // edge/fan inventory only when they become a visited response source;
 100        // both physical and far visits share the same exact topology lifetime.
 6676101        for (int edge = 0; edge < 3 * _mixedPrisms[_mixedMember].Offsets.Length; edge++)
 3081102            PrepareMixedCurvedEdge(domain, edge);
 257103        domain.ActiveEdges.EnsureCapacity(domain.Edges.Count);
 257104        domain.EdgesCurrent = true;
 257105    }
 106
 107    private void PrepareMixedCurvedEdge(MixedCurvedDomain domain, int edge)
 108    {
 3081109        GetMixedCapsuleEdge(edge / 3, edge % 3, out int first, out int last);
 4108110        if (edge % 3 == 2) GetMixedEdgeIntervals(first, last);
 111        else
 112        {
 2054113            _mixedIntervals.FastClear();
 2054114            MixedPrism prism = _mixedPrisms[_mixedMember];
 2054115            int band = edge % 3 == 0 ? 0 : prism.BandCount - 1;
 21224116            foreach (var span in prism.Bands[band].Boundary.Spans)
 10702117                if (span.First == edge / 3) _mixedIntervals.Add(span.Interval);
 118        }
 3081119        _mixedCurvedCuts.FastClear();
 13328120        foreach (RationalSegmentInterval interval in _mixedIntervals.AsReadOnlySpan())
 121        {
 3583122            Signed832 one = Signed832.ExtendValue(Signed192.Signed(1));
 3583123            AddCut(interval.IsClipped ? interval.WideLowerNumerator : default,
 3583124                interval.IsClipped ? interval.WideLowerDenominator : one);
 3583125            AddCut(interval.IsClipped ? interval.WideUpperNumerator : one,
 3583126                interval.IsClipped ? interval.WideUpperDenominator : one);
 127        }
 3081128        _mixedCurvedCuts.SortInPlace(MixedCurvedCutOrder);
 19490129        for (int cut = 0; cut < _mixedCurvedCuts.Count; cut++)
 130        {
 6664131            RationalSegmentInterval point = _mixedCurvedCuts[cut];
 6664132            Keep(point, true);
 6664133            if (cut + 1 < _mixedCurvedCuts.Count)
 134            {
 3583135                RationalSegmentInterval next = _mixedCurvedCuts[cut + 1];
 3583136                Keep(new(point.WideLowerNumerator, point.WideLowerDenominator,
 3583137                    next.WideLowerNumerator, next.WideLowerDenominator), false);
 138            }
 139        }
 140
 141        void AddCut(Signed832 numerator, Signed832 denominator)
 142        {
 143            foreach (RationalSegmentInterval point in _mixedCurvedCuts.AsReadOnlySpan())
 144                if (RationalSegmentInterval.CompareParameters(numerator, denominator,
 145                        point.WideLowerNumerator, point.WideLowerDenominator) == 0) return;
 146            _mixedCurvedCuts.Add(new(numerator, denominator, numerator, denominator));
 147        }
 148
 149        void Keep(in RationalSegmentInterval interval, bool point)
 150        {
 151            const int words = 32;
 152            Span<ulong> values = stackalloc ulong[16 * words]; Span<int> signs = stackalloc int[16];
 153            var n = ContactQuadratic.At(values, signs, 0, words); var d = ContactQuadratic.At(values, signs, 1, words);
 154            var y = ContactQuadratic.At(values, signs, 2, words); var yd = ContactQuadratic.At(values, signs, 3, words);
 155            var ln = ContactQuadratic.At(values, signs, 4, words); var ld = ContactQuadratic.At(values, signs, 5, words)
 156            var un = ContactQuadratic.At(values, signs, 6, words); var ud = ContactQuadratic.At(values, signs, 7, words)
 157            // The complete [0,1] interval canonicalizes to default, whose
 158            // stored fields are all zero. Reconstruct its unit denominators;
 159            // a homogeneous 0/0 point would otherwise reach every fan neighbor.
 160            Signed832 one = Signed832.ExtendValue(Signed192.Signed(1));
 161            ln.Set(interval.IsClipped ? interval.WideLowerNumerator : default);
 162            ld.Set(interval.IsClipped ? interval.WideLowerDenominator : one);
 163            un.Set(interval.IsClipped ? interval.WideUpperNumerator : one);
 164            ud.Set(interval.IsClipped ? interval.WideUpperDenominator : one);
 165            ContactQuadratic.Multiply(ln, ud, ReadOnlySpan<ulong>.Empty, n);
 166            ContactQuadratic.Multiply(un, ld, ReadOnlySpan<ulong>.Empty, y); n.Add(y);
 167            ContactQuadratic.Multiply(ld, ud, ReadOnlySpan<ulong>.Empty, d); d.Add(d);
 168            bool covered = false;
 169            foreach (RationalSegmentInterval retained in _mixedIntervals.AsReadOnlySpan())
 170                covered |= !retained.IsClipped || retained.Contains(n, d, ReadOnlySpan<ulong>.Empty);
 171            if (!covered) return;
 172            MixedPrism prism = _mixedPrisms[_mixedMember];
 173            Vector3d a = prism.Points[first], b = prism.Points[last];
 174            ContactQuadratic.Scale(d, Signed576.ExtendValue(Signed192.Raw(a.Y)), y);
 175            ContactQuadratic.Scale(n, Signed576.ExtendValue(WideArithmetic.Difference(b.Y, a.Y)), yd); y.Add(yd); d.Copy
 176            if (edge % 3 == 2) { n.Clear(); d.Set(Signed576.ExtendValue(Signed192.Signed(1))); }
 177            // A zero normal requests only the existing exact incident-network
 178            // traversal. Open intervals and endpoints gather independently;
 179            // crossing a join at one endpoint must not hide its stricter fan.
 180            AdmitMixedSphereFan(new(new(a.X, Fixed64.Zero, a.Z), new(b.X, Fixed64.Zero, b.Z)), n, d, y, yd, default);
 181            int reference = point && RationalSegmentInterval.CompareParameters(interval.WideLowerNumerator,
 182                interval.WideLowerDenominator, Signed832.ExtendValue(Signed192.Signed(1)),
 183                Signed832.ExtendValue(Signed192.Signed(1))) == 0 ? last : first;
 184            RationalPoint3d origin = prism.NativeFrame.GetPoint(prism.Points[reference]);
 185            int fanStart = domain.WorldFans.Count;
 186            foreach (int member in _mixedFan.AsReadOnlySpan())
 187            {
 188                if (member == _mixedMember) continue;
 189                MixedPrism neighbor = _mixedPrisms[member];
 190                foreach (Vector3d vertex in neighbor.Points)
 191                    domain.WorldFans.Add(WideTriangleRelations.GetScaledPointDifference(
 192                        neighbor.NativeFrame.GetPoint(vertex), origin, prism.NativeFrame.RotationDenominator));
 193            }
 194            domain.Edges.Add(new(edge, interval, point, reference, fanStart, domain.WorldFans.Count - fanStart));
 195        }
 3081196    }
 197
 198    private static void KeepMixedCurvedWindow(MixedCurvedDomain domain, in MixedCurvedFaceWindow window)
 199    {
 5652200        for (int index = 0; index < domain.Faces.Count; index++)
 201        {
 1881202            MixedCurvedFaceWindow previous = domain.Faces[index];
 1881203            if (previous.Face == window.Face && SameMixedBoundaryInterval(previous.Interval, window.Interval)
 1881204                && previous.Upper == window.Lower)
 205            {
 546206                domain.Faces[index] = new(window.Face, window.Interval, previous.Lower, window.Upper); return;
 207            }
 208        }
 945209        domain.Faces.Add(window);
 945210    }
 211
 212    private void PrepareMixedCurvedCertificates(bool cone, Fixed64 height, Span<WideDirection3d> vertices, bool farBound
 213    {
 1374214        if (!_mixedCurvedDomainsCurrent) PrepareMixedCurvedDomains();
 2521215        if (!farBoundary) { _mixedCurvedCertificates.FastClear(); _mixedCurvedCertificateGroups.FastClear(); }
 1257216        int original = _mixedMember;
 8906217        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 218        {
 3196219            MixedPrism prism = _mixedPrisms[_mixedMember];
 3196220            if (!prism.Joined || _mixedCurvedCarriers[_mixedComponents[_mixedMember]] < 0
 3196221                || farBoundary && _mixedSpherePhysicalComponents.Contains(_mixedComponents[_mixedMember])) continue;
 3230222            var member = _mixedLocal[_mixedMember]; var mover = _mixedMoving!;
 1615223            Vector3d origin = MixedEmbedded2DGeometry.GetCenter3D(member);
 1615224            var geometry = new CurvedPrismContactGeometry(mover.Center, mover.Rotation, Vector3d.Up,
 1615225                height, mover.ScaledRadius, origin, member.ConvexRotation, prism.Offsets, member.MixedHalfThickness, con
 20042226            foreach (var window in _mixedCurvedDomains[_mixedMember].Faces.AsReadOnlySpan())
 227            {
 8406228                if (!CurvedPrismContact.TryGetFaceSupportContact(geometry, window.Face, window.Interval, window.Lower, w
 8406229                    mover.Center, mover.Rotation, origin, farBoundary, out var contact, out bool physical)) continue;
 1614230                GetMixedCurvedPlane(_mixedMember, window.Face, out var axis, out var reference);
 1614231                _mixedCurvedCertificates.Add(new(_mixedMember, window, axis, reference, contact, physical));
 1614232                _mixedCurvedCertificateGroups.Add(-1);
 233            }
 234        }
 1257235        _mixedMember = original;
 1257236    }
 237
 238    private void GetMixedCurvedPlane(int member, int face, out WideDirection3d axis, out RationalPoint3d reference)
 239    {
 13161240        MixedPrism prism = _mixedPrisms[member];
 16570241        if (face < 0) axis = new(default, Signed576.ExtendValue(Signed192.Signed(face == -1 ? 1 : -1)), default);
 242        else
 243        {
 19504244            Vector2d a = prism.Offsets[face], b = prism.Offsets[(face + 1) % prism.Offsets.Length],
 9752245                inside = prism.Offsets[(face + 2) % prism.Offsets.Length];
 9752246            var triangle = new FixedTriangle(new(a.X, Fixed64.Zero, a.Y), new(b.X, Fixed64.Zero, b.Y), new(inside.X, Fix
 9752247            axis = prism.NativeFrame.GetInwardAxis(triangle, triangle.A, triangle.B);
 248        }
 13161249        reference = prism.NativeFrame.GetPoint(prism.Points[face < 0 ? face == -1 ? 0 : 1 : 2 * face]);
 13161250    }
 251
 252    private static bool SameMixedCurvedPlane(in WideDirection3d a, in RationalPoint3d first,
 35456253        in WideDirection3d b, in RationalPoint3d second) => WideDirection3d.AreParallel(a, b)
 35456254        && WideDirection3d.Dot(a, b).Sign > 0 && WideTriangleRelations.DotScaledDirections(a,
 35456255            WideTriangleRelations.GetScaledPointDifference(first, second, Signed192.Signed(1))).IsZero;
 256
 257    private readonly struct MixedCurvedCertificate
 258    {
 259        internal readonly int Member;
 260        internal readonly MixedCurvedFaceWindow Window;
 261        internal readonly WideDirection3d Axis;
 262        internal readonly RationalPoint3d Reference;
 263        internal readonly FixedContactAnchors Contact;
 264        internal readonly bool Physical;
 265        internal MixedCurvedCertificate(int member, MixedCurvedFaceWindow window, WideDirection3d axis,
 266            RationalPoint3d reference, FixedContactAnchors contact, bool physical)
 11298267        { Member = member; Window = window; Axis = axis; Reference = reference; Contact = contact; Physical = physical; 
 268    }
 269
 270    private readonly struct MixedCurvedFaceWindow
 271    {
 272        internal readonly int Face;
 273        internal readonly RationalSegmentInterval Interval;
 274        internal readonly Fixed64 Lower, Upper;
 275        internal MixedCurvedFaceWindow(int face, RationalSegmentInterval interval, Fixed64 lower, Fixed64 upper)
 23420276        { Face = face; Interval = interval; Lower = lower; Upper = upper; }
 277    }
 278
 279    private sealed class MixedCurvedDomain
 280    {
 281        internal bool EdgesCurrent;
 248282        internal readonly SwiftList<MixedCurvedFaceWindow> Faces = new();
 248283        internal readonly SwiftList<PrismCurvedBoundaryLine> Lines = new();
 496284        internal readonly SwiftList<PrismCurvedEdgeWindow> Edges = new(), ActiveEdges = new();
 496285        internal readonly SwiftList<WideDirection3d> WorldFans = new(), LocalFans = new();
 286    }
 287}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedCurved.Regions.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.MixedCurved.Regions.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 Gravitas.Colliders;
 12using Gravitas.CollisionHandling;
 13
 14namespace Gravitas;
 15
 16/// <content>Connects exact finite source strata before reducing curved response samples.</content>
 17public sealed partial class StaticSurface2D
 18{
 19    private void AddMixedCurvedCertificatePlane(int selected, bool physical)
 20    {
 102321        MixedCurvedCertificate seed = _mixedCurvedCertificates[selected];
 102322        int original = _mixedMember;
 1087623        for (int index = 0; index < _mixedCurvedCertificates.Count; index++)
 24        {
 441525            MixedCurvedCertificate source = _mixedCurvedCertificates[index];
 441526            if (_mixedCurvedCertificateGroups[index] >= 0
 441527                || _mixedComponents[source.Member] != _mixedComponents[seed.Member]
 441528                || !SameMixedCurvedPlane(seed.Axis, seed.Reference, source.Axis, source.Reference)) continue;
 29            // An own physical proof forces a physical source response; far
 30            // certificates are prepared only for components without one.
 31            System.Diagnostics.Debug.Assert(source.Physical == physical);
 168432            _mixedMember = source.Member; var window = source.Window;
 84233            _mixedCurvedCertificateGroups[index] = _mixedCurvedGroups.Count;
 84234            AddMixedCurvedSample(source.Contact, window.Face, physical, window.Interval, window.Lower, window.Upper);
 35        }
 102336        _mixedMember = original;
 102337    }
 38
 39    private void GetMixedCurvedPlaneForRow(int member, int face, in FixedContactAnchors contact,
 40        out WideDirection3d axis, out RationalPoint3d reference)
 41    {
 200742        if (face >= -2) GetMixedCurvedPlane(member, face, out axis, out reference);
 43        else
 44        {
 45            // Nonface minima have one isolated sample; this rounded direction
 46            // is used only by final sample reduction, never geometry admission.
 547            axis = new(Signed576.ExtendValue(Signed192.Raw(contact.Normal.X)),
 548                Signed576.ExtendValue(Signed192.Raw(contact.Normal.Y)), Signed576.ExtendValue(Signed192.Raw(contact.Norm
 549            reference = default;
 50        }
 551    }
 52
 53    private void CompleteMixedCurvedRegions(bool cone, Fixed64 height, Span<WideDirection3d> vertices)
 54    {
 323655        for (int second = 0; second < _mixedCurvedGroups.Count; second++)
 56        {
 99357            CurvedGroup b = _mixedCurvedGroups[second];
 99358            if (b.Face < -2 || b.FarBoundary) continue;
 338059            for (int first = 0; first < second; first++)
 60            {
 72261                CurvedGroup a = _mixedCurvedGroups[first];
 72262                if (a.Face < -2 || FindMixedRegion(first) == FindMixedRegion(second)
 72263                    || _mixedComponents[a.Member] != _mixedComponents[b.Member]
 72264                    || !SameMixedCurvedPlane(a.Axis, a.Reference, b.Axis, b.Reference)) continue;
 80165                var member = _mixedLocal[a.Member]; var prism = _mixedPrisms[a.Member]; var mover = _mixedMoving!;
 26766                var geometry = new CurvedPrismContactGeometry(mover.Center, mover.Rotation, Vector3d.Up,
 26767                    height, mover.ScaledRadius, MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation,
 26768                    prism.Offsets, member.MixedHalfThickness, cone, vertices);
 26769                bool connected = a.Face < 0 ? MixedCurvedCapsTouch(a, b, geometry) : MixedCurvedSidesTouch(a, b, geometr
 35470                if (connected) _mixedRegionParents[FindMixedRegion(second)] = FindMixedRegion(first);
 71            }
 72        }
 62573    }
 74
 75    private bool MixedCurvedCapsTouch(in CurvedGroup a, in CurvedGroup b, in CurvedPrismContactGeometry geometry)
 76    {
 77        // Both physical rows lie in this one exposed convex cap. Its
 78        // intersection with a convex cone/cylinder is connected even when
 79        // boundary-line producers meet it on opposite sides of the section.
 10880        if (a.Member == b.Member) return true;
 9681        MixedPrism prism = _mixedPrisms[a.Member];
 30882        for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 83        {
 11284            MixedBand band = prism.Bands[bandIndex];
 11285            if (a.Lower < band.Lower || a.Lower > band.Upper) continue;
 75886            foreach (var span in band.Boundary.Spans)
 87            {
 31088                if (span.Kind != SpanKind.Joined || span.OtherMember != b.Member) continue;
 6689                RationalSegmentInterval clip = span.Interval;
 6690                if (a.BoundaryEdge >= 0 && !IntersectMixedCurvedEdges(a.Member, span.First, clip,
 6691                    a.Member, a.BoundaryEdge, a.Clip, out clip)) continue;
 6492                if (b.BoundaryEdge >= 0 && !IntersectMixedCurvedEdges(a.Member, span.First, clip,
 6493                    b.Member, b.BoundaryEdge, b.Clip, out clip)) continue;
 11494                if (CurvedPrismContact.IntersectsBoundaryLine(geometry, span.First, clip, a.Lower, a.Lower)) return true
 95            }
 96        }
 4297        return false;
 98    }
 99
 100    // Cooriented side windows have disjoint interiors; shared strata are lines.
 101    private bool MixedCurvedSidesTouch(in CurvedGroup a, in CurvedGroup b, in CurvedPrismContactGeometry geometry)
 102    {
 165103        Fixed64 delta = _mixedLocal[b.Member].MixedSlabCenterY - _mixedLocal[a.Member].MixedSlabCenterY;
 330104        Fixed64 lower = FixedMath.Max(a.Lower, b.Lower + delta), upper = FixedMath.Min(a.Upper, b.Upper + delta);
 301105        if (lower > upper || !IntersectMixedCurvedEdges(a.Member, a.Face, a.Clip, b.Member, b.Face, b.Clip, out var clip
 30106        if (a.Member == b.Member) return CurvedPrismContact.IntersectsBoundaryLine(geometry, a.Face, clip, lower, upper)
 28107        MixedPrism prism = _mixedPrisms[a.Member];
 126108        for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 109        {
 62110            MixedBand band = prism.Bands[bandIndex];
 124111            Fixed64 bottom = FixedMath.Max(lower, band.Lower), top = FixedMath.Min(upper, band.Upper);
 62112            if (bottom > top) continue;
 315113            foreach (var span in band.Boundary.Spans)
 126114                if (span.Kind == SpanKind.Joined && span.OtherMember == b.Member
 126115                    && IntersectMixedCurvedEdges(a.Member, a.Face, clip, a.Member, span.First, span.Interval, out var sh
 153116                    && CurvedPrismContact.IntersectsBoundaryLine(geometry, a.Face, shared, bottom, top)) return true;
 117        }
 1118        return false;
 119    }
 120
 121    private bool IntersectMixedCurvedEdges(int member, int edge, in RationalSegmentInterval clip,
 122        int otherMember, int otherEdge, in RationalSegmentInterval otherClip, out RationalSegmentInterval intersection)
 123    {
 282124        MixedPrism a = _mixedPrisms[member], b = _mixedPrisms[otherMember];
 282125        var first = _mixedLocal[member]; var second = _mixedLocal[otherMember];
 141126        return WideConvex2dRelations.TryIntersectBoundarySegments(first.Center, first.ConvexRotation,
 141127            new(a.Offsets[edge], a.Offsets[(edge + 1) % a.Offsets.Length]), clip, second.Center, second.ConvexRotation,
 141128            new(b.Offsets[otherEdge], b.Offsets[(otherEdge + 1) % b.Offsets.Length]), otherClip, out intersection);
 129    }
 130
 131    private bool IsBestMixedCurvedFarRegion(int group)
 132    {
 62133        CurvedGroup source = _mixedCurvedGroups[group]; int component = _mixedComponents[source.Member];
 134        // Far groups are never coalesced and retain one sample at their group index.
 31135        Fixed64 depth = _mixedSamples[group].Contact.Depth;
 142136        for (int other = 0; other < _mixedCurvedGroups.Count; other++)
 52137            if (other != group && FindMixedRegion(other) == other && _mixedComponents[_mixedCurvedGroups[other].Member] 
 138            {
 24139                Fixed64 candidate = _mixedSamples[other].Contact.Depth;
 36140                if (candidate < depth || candidate == depth && other < group) return false;
 141            }
 19142        return true;
 143    }
 144
 145    private void RequestMixedCurvedFarReach()
 146    {
 3236147        for (int group = 0; group < _mixedCurvedGroups.Count; group++)
 993148            if (FindMixedRegion(group) == group && _mixedCurvedGroups[group].FarBoundary && IsBestMixedCurvedFarRegion(g
 12149                RequestMixedReach(_mixedSamples[group].Contact.Depth);
 625150    }
 151
 152    private void AppendMixedCurvedRegions(LSCollider2D overlap, ContactManifold destination, int namespace3D, int namesp
 153    {
 1166154        Span<int> chosen = stackalloc int[ContactManifold.MaxContactsPerGroup];
 1166155        var body = _mixedMoving!.Body ?? _mixedMoving.CompoundOwner?.Body;
 1166156        var center = body == null ? new FixedPointAnchor(_mixedMoving.Center, _mixedMoving.Rotation, Vector3d.Zero)
 1166157            : new FixedPointAnchor(body.Position3d, body.Rotation, body.LocalCenterOfMassOffset);
 7840158        for (int group = 0; group < _mixedCurvedGroups.Count; group++)
 159        {
 2754160            CurvedGroup row = _mixedCurvedGroups[group];
 2754161            if (FindMixedRegion(group) != group || _mixedCurvedCarriers[_mixedComponents[row.Member]] != overlap.Id
 2754162                || row.FarBoundary && !IsBestMixedCurvedFarRegion(group)) continue;
 904163            AppendMixedRegionSamples(group, row.Axis, destination, namespace3D, namespace2D, chosen, center);
 164        }
 1166165    }
 166}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedMesh.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.MixedMesh.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 Gravitas.Colliders;
 11using Gravitas.CollisionHandling;
 12using SwiftCollections;
 13
 14namespace Gravitas;
 15
 16/// <content>Visits native moving mesh patches without filling concavities or holes.</content>
 17public sealed partial class StaticSurface2D
 18{
 60019    private readonly SwiftList<Vector3d> _mixedPatchPoints = new();
 120020    private readonly SwiftList<int> _mixedPatchTriangles = new(), _mixedPatchEdges = new();
 60021    private readonly SwiftHashSet<int> _mixedPatchOwners = new();
 60022    private int _mixedMovingFeature = -1;
 23
 24    private void BuildMixedMesh(PhysicsMesh mesh)
 25    {
 32226        _mixedPatchOwners.Clear();
 204427        for (int triangle = 0; triangle < mesh.TriangleCount; triangle++)
 28        {
 71029            int owner = mesh.GetManifoldSurfaceOwner(triangle);
 71030            bool convex = !mesh.GetConvexCoplanarPatchCornerVertexIndices(triangle).IsEmpty;
 71031            if (convex && !_mixedPatchOwners.Add(owner)) continue;
 40432            SetMixedMovingFeature(convex ? owner : triangle);
 40433            BuildMixedPart();
 41434            if (_mixedRequestedReach > _mixedReach) return;
 35        }
 31236    }
 37
 38    private void SetMixedMovingFeature(int feature)
 39    {
 41440        _mixedMovingFeature = feature;
 41441        PhysicsMesh mesh = ((LSMeshCollider)_mixedMoving!).Mesh;
 41442        ReadOnlySpan<int> corners = mesh.GetConvexCoplanarPatchCornerVertexIndices(feature);
 41443        if (!corners.IsEmpty)
 32044            MeshHullSurfaceContacts.FillPatch(mesh, corners, _mixedPatchPoints, _mixedPatchTriangles, _mixedPatchEdges);
 45        else
 46        {
 9447            mesh.GetGeometryTriangleVertices(feature, out var a, out var b, out var c);
 37648            _mixedPatchPoints.FastClear(); _mixedPatchPoints.Add(a); _mixedPatchPoints.Add(b); _mixedPatchPoints.Add(c);
 37649            _mixedPatchTriangles.FastClear(); _mixedPatchTriangles.Add(0); _mixedPatchTriangles.Add(1); _mixedPatchTrian
 9450            _mixedPatchEdges.FastClear();
 28251            _mixedPatchEdges.Add(0); _mixedPatchEdges.Add(1); _mixedPatchEdges.Add(1);
 28252            _mixedPatchEdges.Add(2); _mixedPatchEdges.Add(2); _mixedPatchEdges.Add(0);
 53        }
 9454    }
 55
 56}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedRegions.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.MixedRegions.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 Gravitas.Colliders;
 12using Gravitas.CollisionHandling;
 13using SwiftCollections;
 14
 15namespace Gravitas;
 16
 17/// <content>Separates projected finite supports before reducing their response samples.</content>
 18public sealed partial class StaticSurface2D
 19{
 60020    private readonly SwiftList<MixedRegion> _mixedRegions = new();
 120021    private readonly SwiftList<int> _mixedRegionParents = new(), _mixedRegionOrdinals = new();
 60022    private readonly SwiftList<MixedGroup> _mixedRegionResponses = new();
 60023    private readonly MixedRegionSupport _mixedRegionSupport = new();
 24
 25    private void AddMixedRegion(int member, int face, in BoundarySpan2D span,
 26        Fixed64 lower, Fixed64 upper, int firstSample, int band = -1, int edgeStart = -1, int edgeEnd = -1,
 27        RationalSegmentInterval edgeInterval = default)
 28    {
 343529        if (firstSample == _mixedSamples.Count) return;
 191330        int region = _mixedRegions.Count;
 191331        _mixedRegions.Add(new(_mixedGroup, member, face, band, span, lower, upper, edgeStart, edgeEnd, edgeInterval));
 191332        _mixedRegionParents.Add(region);
 1968633        for (int index = firstSample; index < _mixedSamples.Count; index++)
 34        {
 793035            MixedSample sample = _mixedSamples[index];
 793036            _mixedSamples[index] = new(region, sample.Supplier, sample.Point, sample.Contact);
 37        }
 191338    }
 39
 40    private bool HasMixedFaceRegion(int group)
 41    {
 1172642        foreach (MixedRegion region in _mixedRegions.AsReadOnlySpan())
 280843            if (region.Group == group && region.Face >= 0) return true;
 350544        return false;
 45    }
 46
 47    private void CompleteMixedRegions()
 48    {
 799649        for (int second = 0; second < _mixedRegions.Count; second++)
 525850            for (int first = 0; first < second; first++)
 51            {
 143252                MixedRegion a = _mixedRegions[first], b = _mixedRegions[second];
 71653                if (a.Group != b.Group || FindMixedRegion(first) == FindMixedRegion(second)) continue;
 52754                if (_mixedMovingFeature != _mixedGroups[a.Group].Feature) SetMixedMovingFeature(_mixedGroups[a.Group].Fe
 55                // One exact plane cannot mix horizontal caps with side faces,
 56                // but it can meet another prism only along its vertical edge.
 51757                bool connected = a.Face < 0
 51758                    ? b.Face < 0 ? MixedEdgeRegionsTouch(a, b) : MixedFaceEdgeRegionsTouch(b, a)
 51759                    : b.Face < 0 ? MixedFaceEdgeRegionsTouch(a, b) : MixedRegionsTouch(a, b);
 51760                if (!connected) continue;
 46961                _mixedRegionParents[FindMixedRegion(second)] = FindMixedRegion(first);
 62            }
 208563        _mixedRegionResponses.FastClear();
 841264        foreach (MixedGroup response in _mixedGroups.AsReadOnlySpan()) _mixedRegionResponses.Add(response);
 417065        _mixedGroups.FastClear(); _mixedRegionOrdinals.FastClear();
 990966        for (int index = 0; index < _mixedRegions.Count; index++) _mixedRegionOrdinals.Add(-1);
 799667        for (int index = 0; index < _mixedRegions.Count; index++)
 68        {
 191369            int root = FindMixedRegion(index);
 191370            if (_mixedRegionOrdinals[root] >= 0) continue;
 144471            _mixedRegionOrdinals[root] = _mixedGroups.Count;
 144472            _mixedGroups.Add(_mixedRegionResponses[_mixedRegions[index].Group]);
 73        }
 2003074        for (int index = 0; index < _mixedSamples.Count; index++)
 75        {
 793076            MixedSample sample = _mixedSamples[index];
 793077            _mixedSamples[index] = new(_mixedRegionOrdinals[FindMixedRegion(sample.Group)],
 793078                sample.Supplier, sample.Point, sample.Contact);
 79        }
 80        // Adjacent patches may emit the same final witness. Deduplicate only
 81        // after exact region ownership is known, so disconnected rims survive.
 2003082        for (int index = _mixedSamples.Count - 1; index >= 0; index--)
 5851283            for (int previous = 0; previous < index; previous++)
 2373484                if (_mixedSamples[index].Group == _mixedSamples[previous].Group
 2373485                    && _mixedSamples[index].Point == _mixedSamples[previous].Point)
 481686                { _mixedSamples.RemoveAt(index); break; }
 208587    }
 88
 89    // Capsule and curved-solid response retain the same bounded final pool.
 90    // Geometry, connectivity, carrier and far-boundary policy stay with callers.
 91    private void AppendMixedRegionSamples(int group, in WideDirection3d axis, ContactManifold destination,
 92        int namespace3D, int namespace2D, scoped Span<int> chosen, in FixedPointAnchor center)
 93    {
 226694        _mixedPool.FastClear();
 1738095        foreach (MixedSample sample in _mixedSamples.AsReadOnlySpan())
 642496            if (FindMixedRegion(sample.Group) == group)
 97            {
 415998                bool duplicate = false;
 1842299                foreach (MixedSample kept in _mixedPool.AsReadOnlySpan()) duplicate |= kept.Point == sample.Point;
 8091100                if (!duplicate) _mixedPool.Add(sample);
 101            }
 102        // A capsule region can retain admitted connectivity geometry while
 103        // every solver sample in that region belongs to the other alternative.
 2329104        if (_mixedPool.Count == 0) return;
 2203105        _mixedPool.SortInPlace(MixedPointOrder);
 106        // Keep the deepest, lowest-lever physical point before reducing
 107        // coverage; the manifold assigns its own canonical solver order.
 2203108        int seed = 0;
 7864109        for (int index = 1; index < _mixedPool.Count; index++)
 110        {
 3458111            FixedContactAnchors candidate = _mixedPool[index].Contact, current = _mixedPool[seed].Contact;
 1729112            int depth = candidate.Depth.CompareTo(current.Depth);
 1729113            if (depth > 0 || depth == 0 && center.CompareSquaredDistance(candidate.FirstAnchor, current.FirstAnchor) < 0
 789114                seed = index;
 115        }
 2991116        if (seed != 0) (_mixedPool[0], _mixedPool[seed]) = (_mixedPool[seed], _mixedPool[0]);
 2203117        int count = Math.Min(chosen.Length, _mixedPool.Count);
 12262118        for (int slot = 0; slot < count; slot++)
 3928119            chosen[slot] = slot == 0 ? 0 : MeshPlaneSampleReduction.ChooseNext(_mixedPool.AsReadOnlySpan(), chosen[..slo
 12262120        for (int slot = 0; slot < count; slot++)
 121        {
 3928122            MixedSample sample = _mixedPool[chosen[slot]];
 7856123            FixedContactAnchors contact = sample.Contact; LSCollider2D supplier = _mixedLocal[sample.Supplier];
 3928124            destination.AddContact(new ContactAnchor(contact.FirstAnchor), new ContactAnchor(contact.SecondAnchor),
 3928125                contact.Depth, contact.Normal, _mixedMoving!.Material, supplier.Material, contact.DepthIsClamped,
 3928126                featureNamespaceA: namespace3D, featureNamespaceB: namespace2D,
 3928127                group: new ContactGroupKey(namespace3D, namespace2D, region: group, sourceIdB: supplier.Id + 1,
 3928128                    sourceOrderB: ((IPhysicsColliderRegistryItem)supplier).ReplayOrder + 1));
 129        }
 2203130    }
 131
 132    private int FindMixedRegion(int index)
 133    {
 61096134        while (_mixedRegionParents[index] != index) index = _mixedRegionParents[index];
 35866135        return index;
 136    }
 137
 138    private bool MixedEdgeRegionsTouch(in MixedRegion a, in MixedRegion b)
 139    {
 49140        if (a.Member == b.Member && a.EdgeStart == b.EdgeStart && a.EdgeEnd == b.EdgeEnd)
 141        {
 24142            return TryIntersectMixedIntervals(a.EdgeInterval, b.EdgeInterval, out var clip)
 24143                && IntersectsMixedRegionEdge(a, clip, -1);
 144        }
 50145        Vector3d a0 = _mixedPrisms[a.Member].Points[a.EdgeStart], a1 = _mixedPrisms[a.Member].Points[a.EdgeEnd],
 50146            b0 = _mixedPrisms[b.Member].Points[b.EdgeStart], b1 = _mixedPrisms[b.Member].Points[b.EdgeEnd];
 41147        if (a0.Y != a1.Y && b0.Y != b1.Y) return MixedVerticalEdgeRegionsTouch(a, b, a0, a1, b0, b1);
 38148        for (int endpoint = 0; endpoint < 2; endpoint++)
 149        {
 14150            bool hit = _mixedQuaternion
 14151                ? MixedEdgeRegionEndpoint(a, b, _mixedPrisms[a.Member].Frame, _mixedPrisms[b.Member].Frame, endpoint)
 14152                    || MixedEdgeRegionEndpoint(b, a, _mixedPrisms[b.Member].Frame, _mixedPrisms[a.Member].Frame, endpoin
 14153                : MixedEdgeRegionEndpoint(a, b, _mixedPrisms[a.Member].NativeFrame, _mixedPrisms[b.Member].NativeFrame, 
 14154                    || MixedEdgeRegionEndpoint(b, a, _mixedPrisms[b.Member].NativeFrame, _mixedPrisms[a.Member].NativeFr
 18155            if (hit) return true;
 156        }
 5157        return false;
 158    }
 159
 160    private bool MixedVerticalEdgeRegionsTouch(in MixedRegion a, in MixedRegion b,
 161        Vector3d a0, Vector3d a1, Vector3d b0, Vector3d b1)
 162    {
 16163        var pointA = new FixedSegment(new(a0.X, Fixed64.Zero, a0.Z), new(a0.X, Fixed64.Zero, a0.Z));
 16164        var pointB = new FixedSegment(new(b0.X, Fixed64.Zero, b0.Z), new(b0.X, Fixed64.Zero, b0.Z));
 32165        Span<ulong> values = stackalloc ulong[52]; Span<int> signs = stackalloc int[4];
 32166        var n = ContactQuadratic.At(values, signs, 0, 13); var d = ContactQuadratic.At(values, signs, 1, 13);
 32167        n.Clear(); d.Set(Signed576.ExtendValue(Signed192.Signed(1)));
 16168        int location = _mixedQuaternion
 16169            ? WideTriangleRelations.LocateFrameEdgePoint(pointA, _mixedPrisms[a.Member].FootFrame, n, d,
 16170                pointB, _mixedPrisms[b.Member].FootFrame)
 16171            : WideTriangleRelations.LocateFrameEdgePoint(pointA, _mixedPrisms[a.Member].NativeFootFrame, n, d,
 16172                pointB, _mixedPrisms[b.Member].NativeFootFrame);
 20173        if (location < 0 || !TryGetMixedHeights(a.Member, b.Member, out _, out _)) return false;
 174        // Coincident physical footprints put both original vertical segments
 175        // in A's bounded chart; reuse exact interval mapping before fan admission.
 12176        Fixed64 delta = _mixedLocal[b.Member].MixedSlabCenterY - _mixedLocal[a.Member].MixedSlabCenterY;
 12177        var source = new FixedSegment(new(a0.X, b0.Y + delta, a0.Z), new(a0.X, b1.Y + delta, a0.Z));
 12178        return b.EdgeInterval.TryMapToSegment(source, new(a0, a1), out var mapped)
 12179            && TryIntersectMixedIntervals(a.EdgeInterval, mapped, out var clip)
 12180            && IntersectsMixedRegionEdge(a, clip, b.Member);
 181    }
 182
 183    private static bool TryIntersectMixedIntervals(in RationalSegmentInterval a, in RationalSegmentInterval b,
 184        out RationalSegmentInterval intersection)
 185    {
 4058186        Signed832 one = Signed832.ExtendValue(Signed192.Signed(1));
 8116187        Signed832 ln = a.IsClipped ? a.WideLowerNumerator : default, ld = a.IsClipped ? a.WideLowerDenominator : one,
 8116188            un = a.IsClipped ? a.WideUpperNumerator : one, ud = a.IsClipped ? a.WideUpperDenominator : one;
 4058189        if (b.IsClipped)
 190        {
 1472191            if (RationalSegmentInterval.CompareParameters(ln, ld, b.WideLowerNumerator, b.WideLowerDenominator) < 0)
 536192            { ln = b.WideLowerNumerator; ld = b.WideLowerDenominator; }
 1472193            if (RationalSegmentInterval.CompareParameters(un, ud, b.WideUpperNumerator, b.WideUpperDenominator) > 0)
 514194            { un = b.WideUpperNumerator; ud = b.WideUpperDenominator; }
 195        }
 4058196        intersection = default;
 4160197        if (RationalSegmentInterval.CompareParameters(ln, ld, un, ud) > 0) return false;
 7912198        intersection = new(ln, ld, un, ud); return true;
 199    }
 200
 201    private bool MixedFaceEdgeRegionsTouch(in MixedRegion face, in MixedRegion edge)
 202    {
 36203        Vector3d a = _mixedPrisms[edge.Member].Points[edge.EdgeStart], b = _mixedPrisms[edge.Member].Points[edge.EdgeEnd
 18204        var point = new FixedSegment(new(a.X, Fixed64.Zero, a.Z), new(a.X, Fixed64.Zero, a.Z));
 18205        var side = new FixedSegment(new(face.Span.Start.X, Fixed64.Zero, face.Span.Start.Y), new(face.Span.End.X, Fixed6
 36206        Span<ulong> values = stackalloc ulong[52]; Span<int> signs = stackalloc int[4];
 36207        var n = ContactQuadratic.At(values, signs, 0, 13); var d = ContactQuadratic.At(values, signs, 1, 13);
 36208        n.Clear(); d.Set(Signed576.ExtendValue(Signed192.Signed(1)));
 18209        int location = _mixedQuaternion
 18210            ? WideTriangleRelations.LocateFrameEdgePoint(point, _mixedPrisms[edge.Member].FootFrame, n, d,
 18211                side, _mixedPrisms[face.Member].FootFrame, face.Span.Interval)
 18212            : WideTriangleRelations.LocateFrameEdgePoint(point, _mixedPrisms[edge.Member].NativeFootFrame, n, d,
 18213                side, _mixedPrisms[face.Member].NativeFootFrame, face.Span.Interval);
 24214        if (location < 0 || !TryGetMixedHeights(edge.Member, face.Member, out _, out _)) return false;
 215        // Same horizontal-normal group guarantees an increasing vertical edge.
 216        // Intersect in its bounded local chart, retaining the original parameter.
 12217        Fixed64 delta = _mixedLocal[face.Member].MixedSlabCenterY - _mixedLocal[edge.Member].MixedSlabCenterY;
 24218        Fixed64 lower = FixedMath.Max(a.Y, face.Lower + delta), upper = FixedMath.Min(b.Y, face.Upper + delta);
 14219        if (lower > upper) return false;
 10220        Signed320 denominator = Signed320.ExtendValue(Signed192.Raw(b.Y - a.Y));
 10221        var heights = new RationalSegmentInterval(Signed320.ExtendValue(Signed192.Raw(lower - a.Y)), denominator,
 10222            Signed320.ExtendValue(Signed192.Raw(upper - a.Y)), denominator);
 10223        return TryIntersectMixedIntervals(edge.EdgeInterval, heights, out var clip)
 10224            && IntersectsMixedRegionEdge(edge, clip, face.Member);
 225    }
 226
 227    private bool MixedEdgeRegionEndpoint<TFrame>(in MixedRegion a, in MixedRegion b,
 228        in TFrame firstFrame, in TFrame secondFrame, int endpoint) where TFrame : struct, IForwardHullFrame3d
 229    {
 48230        Signed832 one = Signed832.ExtendValue(Signed192.Signed(1)), value = endpoint == 0 ? default : one;
 48231        Span<ulong> values = stackalloc ulong[52]; Span<int> signs = stackalloc int[4];
 48232        var n = ContactQuadratic.At(values, signs, 0, 13); var d = ContactQuadratic.At(values, signs, 1, 13);
 48233        n.Set(value); d.Set(one);
 28234        if (a.EdgeInterval.IsClipped && !a.EdgeInterval.Contains(n, d, ReadOnlySpan<ulong>.Empty)) return false;
 20235        Vector3d point = _mixedPrisms[a.Member].Points[endpoint == 0 ? a.EdgeStart : a.EdgeEnd];
 20236        var source = new FixedSegment(point, point);
 20237        var target = new FixedSegment(_mixedPrisms[b.Member].Points[b.EdgeStart], _mixedPrisms[b.Member].Points[b.EdgeEn
 32238        if (WideTriangleRelations.LocateFrameEdgePoint(source, firstFrame, n, d, target, secondFrame, b.EdgeInterval) < 
 8239        return IntersectsMixedRegionEdge(a, new(value, one, value, one), b.Member);
 240    }
 241
 242    private bool IntersectsMixedRegionEdge(in MixedRegion region, in RationalSegmentInterval clip, int other)
 243    {
 76244        int saved = _mixedMember; _mixedMember = region.Member;
 38245        MixedPrism prism = _mixedPrisms[region.Member];
 38246        bool intersects = (_mixedQuaternion
 38247            ? VisitMixedEdgeInterval(prism.Frame, prism, region.EdgeStart, region.EdgeEnd, clip, _mixedGroups[region.Gro
 38248            : VisitMixedEdgeInterval(prism.NativeFrame, prism, region.EdgeStart, region.EdgeEnd, clip, _mixedGroups[regi
 249        // Fan traversal proves the shared endpoint belongs to the declared
 250        // continuity; coincident but undeclared/ambiguous rims stay independent.
 38251        intersects &= other < 0 || _mixedFan.Contains(other);
 38252        _mixedMember = saved;
 38253        return intersects;
 254    }
 255
 256    private MeshSurfaceBoundaryDomain2D MixedRegionBoundary(in MixedRegion region)
 257    {
 465258        MixedPrism prism = _mixedPrisms[region.Member];
 465259        int band = region.Band >= 0 ? region.Band : region.Face == 0 ? 0 : prism.BandCount - 1;
 465260        return prism.Bands[band].Boundary;
 261    }
 262
 263    private bool MixedRegionsTouch(in MixedRegion a, in MixedRegion b)
 264    {
 900265        Fixed64 lower = a.Lower, upper = a.Upper;
 450266        if (a.Member != b.Member)
 267        {
 432268            if (!TryGetMixedHeights(a.Member, b.Member, out _, out _)) return false;
 428269            Fixed64 delta = _mixedLocal[b.Member].MixedSlabCenterY - _mixedLocal[a.Member].MixedSlabCenterY;
 856270            lower = FixedMath.Max(lower, b.Lower + delta); upper = FixedMath.Min(upper, b.Upper + delta);
 430271            if (lower > upper) return false;
 426272            bool joined = false;
 4284273            foreach (var span in MixedRegionBoundary(a).Spans)
 1716274                joined |= span.Kind == SpanKind.Joined && span.OtherMember == b.Member;
 429275            if (!joined) return false;
 276        }
 40277        else { lower = FixedMath.Max(lower, b.Lower); upper = FixedMath.Min(upper, b.Upper); }
 447278        if (lower > upper) return false;
 439279        if (a.Face < 2)
 280        {
 223281            foreach (var span in MixedRegionBoundary(a).Spans)
 91282                if (span.Kind == SpanKind.Joined && span.OtherMember == b.Member)
 283                {
 40284                    var segment = new FixedSegment(new(span.Start.X, lower, span.Start.Y), new(span.End.X, lower, span.E
 40285                    MixedPrism prism = _mixedPrisms[a.Member];
 286                    // Strict convex admission makes the next original vertex
 287                    // noncollinear with this original consecutive boundary edge.
 40288                    Vector2d third = prism.Offsets[(span.Second + 1) % prism.Offsets.Length];
 40289                    var triangle = new FixedTriangle(segment.Start, segment.End, new(third.X, lower, third.Y));
 40290                    bool vertex = _mixedQuaternion ? MixedCapSupportVertex(prism.Frame, triangle, span.Interval, a.Group
 40291                        : MixedCapSupportVertex(prism.NativeFrame, triangle, span.Interval, a.Group);
 77292                    if (vertex || IntersectsMixedRegionSegment(a.Member, segment, span.Interval, a.Group)) return true;
 293                }
 2294            return false;
 295        }
 400296        return _mixedQuaternion
 400297            ? MixedSideRegionsTouch(a, b, _mixedPrisms[a.Member].Frame, _mixedPrisms[b.Member].Frame, lower)
 400298            : MixedSideRegionsTouch(a, b, _mixedPrisms[a.Member].NativeFrame, _mixedPrisms[b.Member].NativeFrame, lower)
 299    }
 300
 301    private bool MixedCapSupportVertex<TFrame>(in TFrame frame, in FixedTriangle triangle,
 302        in RationalSegmentInterval clip, int group) where TFrame : struct, IForwardHullFrame3d
 303    {
 40304        Span<Signed832> halfPlanes = stackalloc Signed832[3];
 40305        WideDirection3d axis = _mixedGroups[group].Axis;
 40306        Signed832 support = WideOrientedBox.GetScaledHullSupport(_mixedMovingFrame, MixedMovingPoints, axis, true);
 80307        Span<ulong> values = stackalloc ulong[4 * 14]; Span<int> signs = stackalloc int[4];
 80308        var n = ContactQuadratic.At(values, signs, 0, 14); var d = ContactQuadratic.At(values, signs, 1, 14);
 510309        foreach (Vector3d vertex in MixedMovingPoints)
 310        {
 216311            RationalPoint3d point = _mixedMovingFrame.GetPoint(vertex);
 216312            if (!WideOrientedBox.IsScaledHullSupport(point, axis, support)) continue;
 148313            frame.TryGetTriangleHalfPlanes(triangle, point, halfPlanes);
 148314            if (!halfPlanes[0].IsZero || halfPlanes[1].Sign < 0 || halfPlanes[2].Sign < 0) continue;
 315            // On AB, H0=0; u=H2/(H1+H2). A 14-word borrowed bank
 316            // retains the carry when adding full 832-bit finite weights.
 18317            n.Set(halfPlanes[2]); d.Set(halfPlanes[1]); d.Add(n);
 8318            if (!clip.IsClipped || clip.Contains(n, d, ReadOnlySpan<ulong>.Empty)) return true;
 319        }
 38320        return false;
 321    }
 322
 800323    private static FixedTriangle MixedRegionRectangle(in MixedRegion region) => new(
 800324        new Vector3d(region.Span.Start.X, region.Lower, region.Span.Start.Y),
 800325        new(region.Span.End.X, region.Lower, region.Span.End.Y),
 800326        new(region.Span.Start.X, region.Upper, region.Span.Start.Y));
 327
 328    private bool MixedSideRegionsTouch<TFrame>(in MixedRegion a, in MixedRegion b,
 329        in TFrame firstFrame, in TFrame secondFrame, Fixed64 lower)
 330        where TFrame : struct, IForwardHullFrame3d
 331    {
 800332        FixedTriangle firstRectangle = MixedRegionRectangle(a), secondRectangle = MixedRegionRectangle(b);
 800333        MixedGroup response = _mixedGroups[a.Group]; WideDirection3d axis = response.Axis;
 400334        Signed832 support = WideOrientedBox.GetScaledHullSupport(_mixedMovingFrame, MixedMovingPoints, axis, true);
 335        const int words = 32;
 800336        Span<ulong> values = stackalloc ulong[16 * words]; Span<int> signs = stackalloc int[16];
 800337        var an = ContactQuadratic.At(values, signs, 0, words); var ad = ContactQuadratic.At(values, signs, 1, words);
 800338        var ax = ContactQuadratic.At(values, signs, 2, words); var ay = ContactQuadratic.At(values, signs, 3, words);
 800339        var bn = ContactQuadratic.At(values, signs, 4, words); var bd = ContactQuadratic.At(values, signs, 5, words);
 800340        var bx = ContactQuadratic.At(values, signs, 6, words); var by = ContactQuadratic.At(values, signs, 7, words);
 341        // Clip original support edges independently, then intersect their exact
 342        // parameter windows. Retained cuts can exceed the compact 832-bit type.
 800343        ReadOnlySpan<Vector3d> points = MixedMovingPoints; ReadOnlySpan<int> edges = MixedMovingEdges;
 6109344        foreach (Vector3d vertex in points)
 345        {
 2677346            RationalPoint3d point = _mixedMovingFrame.GetPoint(vertex);
 2677347            if (WideOrientedBox.IsScaledHullSupport(point, axis, support)
 2677348                && WideTriangleRelations.TryGetProjectedRectangleInterval(firstRectangle, firstFrame, point, point, a.Sp
 2722349                && WideTriangleRelations.TryGetProjectedRectangleInterval(secondRectangle, secondFrame, point, point, b.
 350        }
 1478351        for (int edge = 0; edge < edges.Length; edge += 2)
 352        {
 1446353            RationalPoint3d start = _mixedMovingFrame.GetPoint(points[edges[edge]]), end = _mixedMovingFrame.GetPoint(po
 723354            if (!WideOrientedBox.IsScaledHullSupport(start, axis, support) || !WideOrientedBox.IsScaledHullSupport(end, 
 723355                || !WideTriangleRelations.TryGetProjectedRectangleInterval(firstRectangle, firstFrame, start, end, a.Spa
 723356                || !WideTriangleRelations.TryGetProjectedRectangleInterval(secondRectangle, secondFrame, start, end, b.S
 339357            if (ContactQuadratic.CompareRatios(an, ad, ReadOnlySpan<ulong>.Empty, bx, by, ReadOnlySpan<ulong>.Empty) <= 
 678358                && ContactQuadratic.CompareRatios(bn, bd, ReadOnlySpan<ulong>.Empty, ax, ay, ReadOnlySpan<ulong>.Empty) 
 359        }
 360        // With no support vertex/boundary crossing, a nonempty common
 361        // rectangle lies wholly inside the convex support. Its lower edge is
 362        // sufficient; both charts preserve endpoints of nested retained cuts.
 16363        var segment = new FixedSegment(new(a.Span.Start.X, lower, a.Span.Start.Y), new(a.Span.End.X, lower, a.Span.End.Y
 30364        if (IntersectsMixedRegionSegment(a.Member, segment, a.Span.Interval, a.Group, b.Member, b.Span)) return true;
 2365        Fixed64 delta = _mixedLocal[a.Member].MixedSlabCenterY - _mixedLocal[b.Member].MixedSlabCenterY;
 2366        lower += delta;
 2367        segment = new(new(b.Span.Start.X, lower, b.Span.Start.Y), new(b.Span.End.X, lower, b.Span.End.Y));
 2368        return IntersectsMixedRegionSegment(b.Member, segment, b.Span.Interval, a.Group, a.Member, a.Span);
 369    }
 370
 371    private bool IntersectsMixedRegionSegment(int member, in FixedSegment segment,
 372        in RationalSegmentInterval clip, int group, int other = -1,
 373        BoundarySpan2D otherSpan = default)
 374    {
 168375        _mixedRegionSupport.Owner = this; _mixedRegionSupport.Member = member; _mixedRegionSupport.Other = other;
 168376        _mixedRegionSupport.Segment = segment; _mixedRegionSupport.OtherSpan = otherSpan; _mixedRegionSupport.Intervals[
 56377        Span<Vector3d> points = stackalloc Vector3d[2] { segment.Start, segment.End };
 56378        ReadOnlySpan<int> edges = stackalloc int[2] { 0, 1 };
 56379        MixedPrism prism = _mixedPrisms[member];
 56380        return _mixedQuaternion ? VisitMixedRegionSegment(prism.Frame, member, points, edges, group)
 56381            : VisitMixedRegionSegment(prism.NativeFrame, member, points, edges, group);
 382    }
 383
 384    private bool VisitMixedRegionSegment<TFrame>(in TFrame frame, int member, ReadOnlySpan<Vector3d> points,
 385        ReadOnlySpan<int> edges, int group) where TFrame : struct, IForwardHullFrame3d =>
 56386        WideOrientedBox.VisitConvexHullContacts(_mixedMovingFrame, _mixedMoving!.Center, MixedMovingPoints,
 56387            MixedMovingTriangles, MixedMovingEdges, frame, MixedEmbedded2DGeometry.GetCenter3D(_mixedLocal[member]),
 56388            points, ReadOnlySpan<int>.Empty, edges, _mixedGroups[group].Penetration,
 56389            this, static (_, _) => { }, _mixedRegionSupport, admissionOnly: true) > 0;
 390
 391    private readonly struct MixedRegion
 392    {
 393        internal readonly int Group, Member, Face, Band, EdgeStart, EdgeEnd;
 394        internal readonly RationalSegmentInterval EdgeInterval;
 395        internal readonly BoundarySpan2D Span;
 396        internal readonly Fixed64 Lower, Upper;
 397        internal MixedRegion(int group, int member, int face, int band, in BoundarySpan2D span,
 398            Fixed64 lower, Fixed64 upper, int edgeStart, int edgeEnd, in RationalSegmentInterval edgeInterval)
 399        {
 13391400            Group = group; Member = member; Face = face; Band = band; Span = span; Lower = lower; Upper = upper;
 5739401            EdgeStart = edgeStart; EdgeEnd = edgeEnd; EdgeInterval = edgeInterval;
 1913402        }
 403    }
 404
 405    private sealed class MixedRegionSupport : IScaledConvexHullContactDomain
 406    {
 407        internal StaticSurface2D? Owner;
 408        internal int Member, Other;
 409        internal FixedSegment Segment;
 410        internal BoundarySpan2D OtherSpan;
 600411        internal readonly RationalSegmentInterval[] Intervals = new RationalSegmentInterval[1];
 412        public ReadOnlySpan<RationalSegmentInterval> GetEdgeIntervals(bool first, int start, int end, in WideDirection3d
 254413            => first ? MixedFullInterval : Intervals;
 414        public bool ContainsPoint(bool first, int start, int end, in Signed832 n, in Signed832 d, in WideDirection3d nor
 415        {
 416            System.Diagnostics.Debug.Assert(!first);
 154417            Span<ulong> values = stackalloc ulong[52]; Span<int> signs = stackalloc int[4];
 154418            var numerator = ContactQuadratic.At(values, signs, 0, 13); var denominator = ContactQuadratic.At(values, sig
 154419            numerator.Set(n); denominator.Set(d);
 77420            return ContainsPoint(false, start, end, numerator, denominator, normal);
 421        }
 422        public bool ContainsPoint(bool first, int start, int end, scoped ContactQuadratic n,
 423            scoped ContactQuadratic d, in WideDirection3d normal)
 424        {
 119425            if (first) return true;
 91426            if (start == end)
 427            {
 44428                Span<ulong> values = stackalloc ulong[52]; Span<int> signs = stackalloc int[4];
 44429                var endpoint = ContactQuadratic.At(values, signs, 0, 13); var one = ContactQuadratic.At(values, signs, 1
 44430                endpoint.Set(Signed576.ExtendValue(Signed192.Signed(start))); one.Set(Signed576.ExtendValue(Signed192.Si
 22431                return ContainsParameter(endpoint, one);
 432            }
 69433            return ContainsParameter(n, d);
 434        }
 435        private bool ContainsParameter(scoped ContactQuadratic n, scoped ContactQuadratic d)
 436        {
 101437            if (Intervals[0].IsClipped && !Intervals[0].Contains(n, d, ReadOnlySpan<ulong>.Empty)) return false;
 130438            if (Other < 0) return true;
 32439            StaticSurface2D owner = Owner!;
 32440            FixedSegment source = new(new(Segment.Start.X, Fixed64.Zero, Segment.Start.Z), new(Segment.End.X, Fixed64.Ze
 32441            FixedSegment target = new(new(OtherSpan.Start.X, Fixed64.Zero, OtherSpan.Start.Y), new(OtherSpan.End.X, Fixe
 32442            return owner._mixedQuaternion
 32443                ? WideTriangleRelations.LocateFrameEdgePoint(source, owner._mixedPrisms[Member].FootFrame, n, d,
 32444                    target, owner._mixedPrisms[Other].FootFrame, OtherSpan.Interval) >= 0
 32445                : WideTriangleRelations.LocateFrameEdgePoint(source, owner._mixedPrisms[Member].NativeFootFrame, n, d,
 32446                    target, owner._mixedPrisms[Other].NativeFootFrame, OtherSpan.Interval) >= 0;
 447        }
 448    }
 449}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.MixedSphere.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.MixedSphere.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 Gravitas.Colliders;
 12using Gravitas.CollisionHandling;
 13using SwiftCollections;
 14
 15namespace Gravitas;
 16
 17/// <content>Admits rounded point supports against the existing exposed prism domain.</content>
 18public sealed partial class StaticSurface2D
 19{
 20    private readonly PrismPointAdmission _mixedSphereAdmit;
 21    private readonly PrismSphereBoundaryAdmission _mixedSphereBoundaryAdmit;
 22    private FixedSegment _mixedSphereFaceFootprint;
 23
 60024    private readonly SwiftList<SphereGroup> _mixedSphereGroups = new();
 60025    private readonly SwiftList<SpherePeak> _mixedSpherePeaks = new();
 60026    private readonly SwiftList<int> _mixedSphereSourceGroups = new();
 60027    private readonly SwiftList<bool> _mixedSphereSelectedGroups = new();
 60028    private readonly SwiftHashSet<int> _mixedSphereInsideComponents = new();
 60029    private readonly SwiftHashSet<int> _mixedSpherePhysicalComponents = new();
 30    private bool _mixedSphereInside, _mixedSphereConcavityCurrent, _mixedSphereChooseSources;
 31
 32    private void BuildMixedSphere()
 33    {
 188334        if (!_mixedSphereConcavityCurrent) PrepareMixedSphereConcavity();
 857535        _mixedSphereGroups.FastClear(); _mixedSpherePeaks.FastClear(); _mixedOverlaps.Clear(); _mixedSphereInsideCompone
 514536        _mixedSphereSourceGroups.FastClear(); _mixedSphereSelectedGroups.FastClear(); _mixedSphereChooseSources = false;
 171537        Fixed64 radius = _mixedMoving is LSSphereCollider sphere ? sphere.ScaledRadius : ((LSCapsuleCollider)_mixedMovin
 956438        for (int member = 0; member < _mixedLocal.Count; member++)
 39        {
 306740            LSCollider2D source = _mixedLocal[member];
 306741            _mixedSphereChooseSources |= _mixedPrisms[member].SphereHasConcaveFace;
 306742            if (source.ContainsPoint(new(_mixedMoving!.Center.X, _mixedMoving.Center.Z))
 306743                && MixedEmbedded2DGeometry.ContainsPointInSlab(source, _mixedMoving.Center.Y))
 74844                _mixedSphereInsideComponents.Add(_mixedComponents[member]);
 45        }
 171546        if (_mixedSphereChooseSources)
 633447            for (int member = 0; member < _mixedLocal.Count; member++) _mixedSphereSourceGroups.Add(-1);
 792448        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 49        {
 272650            LSCollider2D member = _mixedLocal[_mixedMember];
 272651            if (!_mixedMoving!.Bounds.Intersects(member.MixedBounds3D)) continue;
 244652            MixedPrism prism = _mixedPrisms[_mixedMember];
 244653            if (!prism.Joined)
 54            {
 55                // Preserve the ordinary per-member path, but discover any
 56                // remote neighbor reached by a deep exit before concluding it is unjoined.
 61157                if (FixedConvexPrismRelations.TryGetSphereContact(_mixedMoving.Center, radius,
 61158                    MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation, prism.Offsets,
 61159                    member.MixedHalfThickness, out var separate))
 60                {
 60961                    Fixed64 separateReach = radius + separate.Depth + Fixed64.MinIncrement + Fixed64.MinIncrement;
 62162                    if (separateReach > _mixedRequestedReach) { _mixedRequestedReach = separateReach; return; }
 63                }
 64                continue;
 65            }
 183566            int component = _mixedComponents[_mixedMember];
 183567            _mixedSphereInside = _mixedSphereInsideComponents.Contains(component);
 183568            bool found = WideConvexPrismRelations.TryGetSphereContact(_mixedMoving.Center, radius,
 183569                MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation, prism.Offsets,
 183570                member.MixedHalfThickness, _mixedSphereAdmit, out var contact, out var axis, out var depth, out bool ove
 350771            if (overlaps) _mixedOverlaps.Add(member.Id);
 183572            bool physical = found && WideConvexPrismRelations.IsSphereProjectionWithinRadius(depth);
 235173            if (physical) _mixedSpherePhysicalComponents.Add(component);
 183574            if (!found) continue;
 163275            Fixed64 reach = radius + contact.Depth + Fixed64.MinIncrement + Fixed64.MinIncrement;
 257876            if (reach > _mixedRequestedReach) { _mixedRequestedReach = reach; return; }
 115977            RationalPoint3d reference = MixedSupportPoint(prism.NativeFrame, prism, axis);
 115978            int group = 0;
 129179            for (; group < _mixedSphereGroups.Count; group++)
 80            {
 31581                SphereGroup previous = _mixedSphereGroups[group];
 31582                if (previous.Component != component) continue;
 30383                if (!physical && previous.Recovery || physical && !previous.Recovery && WideDirection3d.AreParallel(axis
 30384                    && WideDirection3d.Dot(axis, previous.Axis).Sign > 0
 30385                    && WideTriangleRelations.DotScaledDirections(axis, WideTriangleRelations.GetScaledPointDifference(
 30386                        reference, previous.Reference, Signed192.Signed(1))).IsZero) break;
 87            }
 115988            var row = new SphereGroup(component, member.Id, _mixedMember, axis, reference, depth, contact, !physical);
 115989            if (group == _mixedSphereGroups.Count)
 90            {
 91091                _mixedSphereGroups.Add(row);
 144292                if (_mixedSphereChooseSources) _mixedSphereSelectedGroups.Add(false);
 93            }
 24994            else if (!physical && WideConvexPrismRelations.CompareProjectionDepths(depth, _mixedSphereGroups[group].Dept
 1095                _mixedSphereGroups[group] = row;
 190196            if (_mixedSphereChooseSources) _mixedSphereSourceGroups[_mixedMember] = group;
 97        }
 150098        if (_mixedSphereChooseSources) SelectMixedSphereSources(radius);
 123699    }
 100
 101    private void SelectMixedSphereSources(Fixed64 radius)
 102    {
 264103        _mixedSpherePhysicalComponents.Clear();
 1824104        for (_mixedMember = 0; _mixedMember < _mixedLocal.Count; _mixedMember++)
 105        {
 648106            int own = _mixedSphereSourceGroups[_mixedMember];
 648107            MixedPrism prism = _mixedPrisms[_mixedMember];
 648108            if (!prism.SphereHasConcaveFace || !_mixedOverlaps.Contains(_mixedLocal[_mixedMember].Id))
 109            {
 124110                if (own >= 0) _mixedSphereSelectedGroups[own] = true;
 6111                continue;
 112            }
 530113            int native = own >= 0 && !_mixedSphereGroups[own].Recovery ? own : -1;
 114            // A physical witness on another member can certify this convex
 115            // source's complete exit only on one of its original support planes.
 2324116            for (int candidate = 0; candidate < _mixedSphereGroups.Count; candidate++)
 117            {
 632118                SphereGroup proof = _mixedSphereGroups[candidate];
 632119                if (candidate == native || proof.Recovery || proof.Component != _mixedComponents[_mixedMember]) continue
 990120                for (int face = -2; face < prism.Offsets.Length; face++)
 121                {
 440122                    GetMixedCurvedPlane(_mixedMember, face, out var axis, out var reference);
 440123                    if (!SameMixedCurvedPlane(axis, reference, proof.Axis, proof.Reference)) continue;
 28124                    if (native < 0 || WideConvexPrismRelations.CompareProjectionDepths(proof.Depth, _mixedSphereGroups[n
 26125                        native = candidate;
 26126                    break;
 127                }
 128            }
 530129            int peakStart = _mixedSpherePeaks.Count;
 530130            _mixedCurvedBoundarySamples.FastClear();
 530131            AppendMixedSphereFacePeaks(radius, native);
 530132            var cuts = _mixedCurvedBoundarySamples.AsReadOnlySpan();
 530133            bool useCuts = !cuts.IsEmpty;
 2106134            foreach (var cut in cuts)
 563135                if (cut.CompareToNative >= 0) { useCuts = false; break; }
 536136            if (useCuts && !AreMixedCurvedCutRowsCompatible(cuts)) useCuts = false;
 980137            if (useCuts) _mixedSpherePhysicalComponents.Add(_mixedComponents[_mixedMember]);
 138            else
 139            {
 310140                for (int peak = _mixedSpherePeaks.Count - 1; peak >= peakStart; peak--) _mixedSpherePeaks.RemoveAt(peak)
 80141                int selected = native >= 0 ? native : own;
 158142                if (selected >= 0) _mixedSphereSelectedGroups[selected] = true;
 143            }
 144        }
 1152145        for (int group = 0; group < _mixedSphereGroups.Count; group++)
 312146            if (_mixedSphereSelectedGroups[group] && !_mixedSphereGroups[group].Recovery)
 66147                _mixedSpherePhysicalComponents.Add(_mixedSphereGroups[group].Component);
 264148    }
 149
 150    private void PrepareMixedSphereConcavity()
 151    {
 152        // A component wholly inside every exposed face half-plane cannot have
 153        // a concave face peak. Cache this sufficient certificate with its geometry;
 154        // uncertain/nonconvex pieces still use exact pointwise incident fans.
 360155        Span<Vector3d> corner = stackalloc Vector3d[1];
 360156        var world = new NativePrismYawFrame3d(Vector3d.Zero, Fixed64.Zero);
 2508157        for (int member = 0; member < _mixedLocal.Count; member++)
 158        {
 1788159            MixedPrism prism = _mixedPrisms[member]; prism.SphereHasConcaveFace = false;
 894160            if (!prism.Joined) continue;
 1614161            Vector3d minimum = _mixedLocal[member].MixedBounds3D.Min, maximum = _mixedLocal[member].MixedBounds3D.Max;
 6656162            for (int other = 0; other < _mixedLocal.Count; other++)
 2521163                if (_mixedComponents[other] == _mixedComponents[member])
 164                {
 2185165                    minimum = Vector3d.Min(minimum, _mixedLocal[other].MixedBounds3D.Min);
 2185166                    maximum = Vector3d.Max(maximum, _mixedLocal[other].MixedBounds3D.Max);
 167                }
 807168            bool bounded = true;
 6456169            for (int axis = 0; axis < 3; axis++)
 2421170                bounded &= minimum[axis] > Fixed64.MinValue && maximum[axis] < Fixed64.MaxValue;
 7866171            for (int face = -2; face < prism.Offsets.Length; face++)
 172            {
 173                Vector3d reference; WideDirection3d normal;
 3550174                if (face < 0)
 175                {
 1454176                    reference = prism.Points[face == -2 ? 0 : 1];
 1454177                    normal = new(default, Signed576.ExtendValue(Signed192.Signed(face == -2 ? 1 : -1)), default);
 178                }
 179                else
 180                {
 2096181                    bool exposed = false;
 10172182                    for (int band = 0; band < prism.BandCount; band++)
 32072183                        foreach (var span in prism.Bands[band].Boundary.Spans)
 15522184                            if (span.First == face && span.Kind != SpanKind.Joined) exposed = true;
 2096185                    if (!exposed) continue;
 3304186                    Vector2d a = prism.Offsets[face], b = prism.Offsets[(face + 1) % prism.Offsets.Length];
 1652187                    Vector2d inside = prism.Offsets[(face + 2) % prism.Offsets.Length];
 1652188                    var footprint = new FixedTriangle(new(a.X, Fixed64.Zero, a.Y), new(b.X, Fixed64.Zero, b.Y), new(insi
 1652189                    reference = footprint.A;
 1652190                    normal = prism.NativeFrame.GetInwardAxis(footprint, footprint.A, footprint.B);
 191                }
 192                // One conservative box corner can certify the entire component.
 193                // Clipped domain bounds are uncertain; retain the exact vertex proof there.
 3106194                corner[0] = new(normal.X.Sign < 0 ? maximum.X : minimum.X,
 3106195                    normal.Y.Sign < 0 ? maximum.Y : minimum.Y, normal.Z.Sign < 0 ? maximum.Z : minimum.Z);
 3106196                if (bounded && SupportsMixedFan(world, prism.NativeFrame, reference, corner, normal)) continue;
 1786197                for (int other = 0; other < _mixedLocal.Count; other++)
 837198                    if (other != member && _mixedComponents[other] == _mixedComponents[member]
 837199                        && !SupportsMixedFan(_mixedPrisms[other].NativeFrame, prism.NativeFrame, reference,
 837200                            _mixedPrisms[other].Points, normal))
 848201                    { prism.SphereHasConcaveFace = true; break; }
 480202                if (prism.SphereHasConcaveFace) break;
 203            }
 204        }
 360205        _mixedSphereConcavityCurrent = true;
 360206    }
 207
 208    private bool AppendMixedSphere(LSCollider2D overlap, ContactManifold destination, int namespace3D, int namespace2D)
 209    {
 5004210        for (int group = 0; group < _mixedSphereGroups.Count; group++)
 211        {
 1307212            SphereGroup row = _mixedSphereGroups[group];
 1307213            if (_mixedSphereChooseSources && !_mixedSphereSelectedGroups[group]) continue;
 801214            if (row.Carrier != overlap.Id || row.Recovery && _mixedSpherePhysicalComponents.Contains(row.Component)) con
 491215            Append(row.Contact, row.Supplier, group);
 216        }
 4482217        for (int peak = 0; peak < _mixedSpherePeaks.Count; peak++)
 218        {
 1046219            SpherePeak row = _mixedSpherePeaks[peak];
 1531220            if (_mixedLocal[row.Member].Id == overlap.Id) Append(row.Contact, row.Member, _mixedSphereGroups.Count + pea
 221        }
 222        void Append(in FixedContactAnchors contact, int member, int group)
 223        {
 224            LSCollider2D supplier = _mixedLocal[member];
 225            destination.AddContact(new ContactAnchor(contact.FirstAnchor), new ContactAnchor(contact.SecondAnchor),
 226                contact.Depth, contact.Normal, _mixedMoving!.Material, supplier.Material, contact.DepthIsClamped,
 227                featureNamespaceA: namespace3D, featureNamespaceB: namespace2D,
 228                group: new ContactGroupKey(namespace3D, namespace2D, region: group, sourceIdB: supplier.Id + 1,
 229                    sourceOrderB: ((IPhysicsColliderRegistryItem)supplier).ReplayOrder + 1));
 230        }
 1195231        return _mixedOverlaps.Contains(overlap.Id);
 232    }
 233
 234    private readonly struct SphereGroup
 235    {
 236        internal readonly int Component, Carrier, Supplier;
 237        internal readonly WideDirection3d Axis;
 238        internal readonly RationalPoint3d Reference;
 239        internal readonly WideConvexPrismRelations.ProjectionDepth Depth;
 240        internal readonly FixedContactAnchors Contact;
 241        internal readonly bool Recovery;
 242        internal SphereGroup(int component, int carrier, int supplier, WideDirection3d axis, RationalPoint3d reference,
 243            WideConvexPrismRelations.ProjectionDepth depth, FixedContactAnchors contact, bool recovery = false)
 37809244        { Component = component; Carrier = carrier; Supplier = supplier; Axis = axis; Reference = reference; Depth = dep
 245    }
 246
 247    private readonly struct SpherePeak
 248    {
 249        internal readonly int Member, Edge, Vertical;
 250        internal readonly Fixed64 Height;
 251        internal readonly Signed320 Numerator, Denominator;
 252        internal readonly FixedContactAnchors Contact;
 253        internal SpherePeak(int member, int edge, int next, int vertical, Fixed64 height,
 254            in RationalSegmentInterval parameter, in FixedContactAnchors contact)
 255        {
 2156256            Member = member; Edge = edge; Vertical = vertical; Height = height;
 257            // Native boundary cuts use Signed320, and a fresh closest-point
 258            // Gram ratio needs <162 bits. The wider math helper is not narrowed generically.
 1617259            Numerator = parameter.LowerNumerator; Denominator = parameter.LowerDenominator; Contact = contact;
 260            // Two footprint edges can sample one cap vertex; sides retain their
 261            // own normals, while cap endpoints share a canonical vertex key.
 539262            if (vertical != 0 && RationalSegmentInterval.CompareParameters(Numerator, Denominator, Signed320.One, Signed
 42263            { Edge = next; Numerator = default; Denominator = Signed320.One; }
 539264        }
 265    }
 266
 267    private void AppendMixedSphereFacePeaks(Fixed64 radius, int native)
 268    {
 530269        MixedPrism prism = _mixedPrisms[_mixedMember];
 530270        LSCollider2D member = _mixedLocal[_mixedMember];
 530271        Span<ulong> storage = stackalloc ulong[CapsulePlaneRaySelection.StorageWords];
 530272        Span<int> signs = stackalloc int[CapsulePlaneRaySelection.SignCount];
 530273        Span<sbyte> valueSigns = stackalloc sbyte[CapsulePlaneRaySelection.ValueSignCount];
 530274        var selection = new CapsulePlaneRaySelection(storage, signs, valueSigns);
 2836275        for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 276        {
 888277            MixedBand band = prism.Bands[bandIndex];
 9904278            foreach (var span in band.Boundary.Spans)
 279            {
 4064280                if (span.Kind == SpanKind.Joined) continue;
 3140281                Keep(span, band.Lower, band.Upper, 0, ref selection);
 282            }
 283        }
 3180284        for (int cap = 0; cap < 2; cap++)
 285        {
 1060286            Fixed64 y = cap == 0 ? -member.MixedHalfThickness : member.MixedHalfThickness;
 1060287            MixedBand band = prism.Bands[cap == 0 ? 0 : prism.BandCount - 1];
 11492288            foreach (var span in band.Boundary.Spans)
 4686289                if (span.Kind == SpanKind.Joined)
 996290                    Keep(span, y, y, cap == 0 ? 1 : -1, ref selection);
 291        }
 292
 293        void Keep(in BoundarySpan2D span, Fixed64 lower, Fixed64 upper, int vertical,
 294            ref CapsulePlaneRaySelection retained)
 295        {
 296            _mixedSphereFaceFootprint = new(new(span.Start.X, Fixed64.Zero, span.Start.Y), new(span.End.X, Fixed64.Zero,
 297            bool found = WideConvexPrismRelations.TryGetSphereBoundaryFaceContact(_mixedMoving!.Center, radius,
 298                MixedEmbedded2DGeometry.GetCenter3D(member), member.ConvexRotation, span.Start, span.End,
 299                prism.Offsets[(span.Second + 1) % prism.Offsets.Length], span.Interval, lower, upper,
 300                ref retained, out var ray, out var contact, out var parameter, out Fixed64 localY, vertical, _mixedSpher
 301            if (!found) return;
 302            // Height bands may share the same finite peak. Only an identical
 303            // point on the same original face is redundant; coplanar regions are not.
 304            var candidate = new SpherePeak(_mixedMember, span.First, span.Second, vertical, localY, parameter, contact);
 305            foreach (SpherePeak peak in _mixedSpherePeaks)
 306                if (peak.Member == candidate.Member && peak.Edge == candidate.Edge && peak.Vertical == candidate.Vertica
 307                    && peak.Height == candidate.Height && RationalSegmentInterval.CompareParameters(
 308                        peak.Numerator, peak.Denominator, candidate.Numerator, candidate.Denominator) == 0) return;
 309            _mixedSpherePeaks.Add(candidate);
 310            int comparison = native < 0 ? -1
 311                : new CapsulePrismContactDepth(_mixedSphereGroups[native].Depth).Compare(retained, ray);
 312            _mixedCurvedBoundarySamples.Add(new(_mixedSpherePeaks.Count - 1, contact, comparison));
 313        }
 530314    }
 315
 316    private bool AdmitMixedSphereBoundaryPoint(in RationalSegmentInterval parameter, Fixed64 localY,
 317        in WideDirection3d normal)
 318    {
 319        const int words = 32;
 8272320        Span<ulong> values = stackalloc ulong[8 * words]; Span<int> signs = stackalloc int[8];
 8272321        var n = ContactQuadratic.At(values, signs, 0, words); var d = ContactQuadratic.At(values, signs, 1, words);
 8272322        var height = ContactQuadratic.At(values, signs, 2, words); var heightD = ContactQuadratic.At(values, signs, 3, w
 8272323        n.Set(parameter.WideLowerNumerator); d.Set(parameter.WideLowerDenominator);
 8272324        height.Set(Signed576.ExtendValue(Signed192.Raw(localY))); heightD.Set(Signed576.ExtendValue(Signed192.Signed(1))
 325        // A blocked incident normal identifies a genuine concave cut. Flat
 326        // joins and convex rims stay with the original finite support owner.
 4136327        return !AdmitMixedSphereFan(_mixedSphereFaceFootprint, n, d, height, heightD, normal);
 328    }
 329
 330    private bool AdmitMixedSpherePoint(in WideDirection3d normal, in WideConvexPrismRelations.ProjectionDepth depth, sco
 331        scoped ContactQuadratic y, scoped ContactQuadratic z, scoped ContactQuadratic d)
 332    {
 333        // Exterior contacts require an actual finite boundary inside the sphere.
 334        // A far side through the solid is recovery, not another exterior row.
 8581335        if (!_mixedSphereInside && depth.Rational.Sign > 0) return false;
 7387336        return AdmitMixedPrismSupportPoint(normal, depth, x, y, z, d);
 337    }
 338
 339    private bool AdmitMixedPrismSupportPoint(in WideDirection3d normal, in WideConvexPrismRelations.ProjectionDepth dept
 340        scoped ContactQuadratic x, scoped ContactQuadratic y, scoped ContactQuadratic z, scoped ContactQuadratic d)
 341    {
 12589342        MixedPrism prism = _mixedPrisms[_mixedMember];
 343        const int words = 32;
 25178344        Span<ulong> values = stackalloc ulong[12 * words]; Span<int> signs = stackalloc int[12];
 12589345        var nx = ContactQuadratic.At(values, signs, 0, words);
 12589346        var nz = ContactQuadratic.At(values, signs, 1, words);
 12589347        var term = ContactQuadratic.At(values, signs, 2, words);
 12589348        var side = ContactQuadratic.At(values, signs, 3, words);
 12589349        var parameter = ContactQuadratic.At(values, signs, 4, words);
 12589350        var divisor = ContactQuadratic.At(values, signs, 5, words);
 71114351        for (int edge = 0; edge < prism.Offsets.Length; edge++)
 352        {
 69406353            Vector2d a = prism.Offsets[edge], b = prism.Offsets[(edge + 1) % prism.Offsets.Length];
 104109354            x.CopyTo(nx); ContactQuadratic.Scale(d, Signed576.ExtendValue(Signed192.Raw(a.X)), term); nx.Add(term, -1);
 104109355            z.CopyTo(nz); ContactQuadratic.Scale(d, Signed576.ExtendValue(Signed192.Raw(a.Y)), term); nz.Add(term, -1);
 34703356            ContactQuadratic.Scale(nx, Signed576.ExtendValue(Signed192.Raw(b.Y - a.Y)), side);
 69406357            ContactQuadratic.Scale(nz, Signed576.ExtendValue(Signed192.Raw(b.X - a.X)), term); side.Add(term, -1);
 34703358            if (side.Signs[0] != 0) continue;
 11735359            Fixed64 delta = b.X != a.X ? b.X - a.X : b.Y - a.Y;
 11735360            (b.X != a.X ? nx : nz).CopyTo(parameter);
 11735361            ContactQuadratic.Scale(d, Signed576.ExtendValue(Signed192.Raw(delta)), divisor);
 25137362            if (delta < Fixed64.Zero) { parameter.MultiplySign(-1); divisor.MultiplySign(-1); }
 11735363            return AdmitMixedSphereFan(new(new(a.X, Fixed64.Zero, a.Y), new(b.X, Fixed64.Zero, b.Y)),
 11735364                parameter, divisor, y, d, normal);
 365        }
 1708366        _mixedFan.FastClear(); _mixedFan.Add(_mixedMember);
 854367        return true;
 368    }
 369
 370    private bool AdmitMixedSphereFan(in FixedSegment footprint, scoped ContactQuadratic n,
 371        scoped ContactQuadratic d, scoped ContactQuadratic height, scoped ContactQuadratic heightD,
 372        in WideDirection3d normal)
 373    {
 38154374        MixedPrism source = _mixedPrisms[_mixedMember];
 38154375        Signed832 support = WideOrientedBox.GetScaledHullSupport(source.NativeFrame, source.Points, normal, false);
 38154376        int vertex = 0;
 134252377        while (!WideOrientedBox.IsScaledHullSupport(source.NativeFrame.GetPoint(source.Points[vertex]), normal, support)
 378        const int words = 32;
 76308379        Span<ulong> values = stackalloc ulong[4 * words]; Span<int> signs = stackalloc int[4];
 38154380        var wall = ContactQuadratic.At(values, signs, 0, words);
 38154381        var term = ContactQuadratic.At(values, signs, 1, words);
 76308382        _mixedFan.FastClear(); _mixedFan.Add(_mixedMember);
 173694383        for (int cursor = 0; cursor < _mixedFan.Count; cursor++)
 384        {
 115526385            int member = _mixedFan[cursor]; MixedPrism prism = _mixedPrisms[member];
 57763386            if (member != _mixedMember && !SupportsMixedFan(prism.NativeFrame, source.NativeFrame,
 66833387                source.Points[vertex], prism.Points, normal)) return false;
 48693388            Fixed64 delta = _mixedLocal[member].MixedSlabCenterY - _mixedLocal[_mixedMember].MixedSlabCenterY;
 274256389            for (int bandIndex = 0; bandIndex < prism.BandCount; bandIndex++)
 390            {
 88435391                MixedBand band = prism.Bands[bandIndex];
 265305392                height.CopyTo(wall); ContactQuadratic.Scale(heightD, Signed576.ExtendValue(Signed192.Raw(delta + band.Lo
 88435393                if (wall.Signs[0] < 0) continue;
 215799394                height.CopyTo(wall); ContactQuadratic.Scale(heightD, Signed576.ExtendValue(Signed192.Raw(delta + band.Up
 71933395                if (wall.Signs[0] > 0) continue;
 583524396                foreach (var span in band.Boundary.Spans)
 397                {
 237619398                    if (span.Kind != SpanKind.Joined || _mixedFan.Contains(span.OtherMember)) continue;
 50961399                    var edge = new FixedSegment(new(span.Start.X, Fixed64.Zero, span.Start.Y), new(span.End.X, Fixed64.Z
 50961400                    if (WideTriangleRelations.LocateFrameEdgePoint(footprint, source.NativeFootFrame, n, d,
 70852401                        edge, prism.NativeFootFrame, span.Interval) >= 0) _mixedFan.Add(span.OtherMember);
 402                }
 403            }
 404        }
 29084405        return true;
 406    }
 407}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.Recovery.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.Recovery.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 Gravitas.Colliders;
 12using Gravitas.CollisionHandling;
 13using Gravitas.Support;
 14
 15namespace Gravitas;
 16
 17/// <content>Conservative deep-placement proposals certified against the complete final spatial neighborhood.</content>
 18public sealed partial class StaticSurface2D
 19{
 20    internal bool TryGetRecovery(LSCollider2D mover, out Vector2d center)
 21    {
 4222        center = mover.Center;
 4223        SolidBody2D body = mover.Body!;
 4324        if (!body.CanTranslate) return false;
 4725        if (IsRecoveryClear(mover, center)) return true;
 11126        foreach (LSCollider2D member in _local.AsReadOnlySpan())
 27        {
 3528            if (!CollisionDetection2D.DoesPostureCandidatePenetrate(mover, center, member)
 3529                || !TryRecoveryDirection(mover, center, member, out Vector2d normal, out Fixed64 depth)) continue;
 30            // Existing penetration slop only expands a proposal beyond its
 31            // rounded member exit; exact final clearance is still mandatory.
 3532            if (!Fixed64.TryAdd(depth, CollisionResponse2D.PenetrationSlop, out Fixed64 distance)
 3533                || !Fixed64.TryMultiplyDivide(-normal.X, distance, Fixed64.One, out Fixed64 x)
 3534                || !Fixed64.TryMultiplyDivide(-normal.Y, distance, Fixed64.One, out Fixed64 y)
 3535                || !Vector2d.TryAdd(center, body.ProjectLinearMotion(new(x, y)), out Vector2d next)) continue;
 3536            center = next;
 6437            if (IsRecoveryClear(mover, center)) return true;
 38        }
 639        center = mover.Center;
 640        return false;
 41    }
 42
 43    internal bool IsRecoveryClear(LSCollider2D mover, Vector2d center)
 44    {
 10445        if (!Vector2d.TrySubtract(center, mover.Center, out Vector2d displacement)) return false;
 10246        SolidBody2D body = mover.Body!;
 10247        if (!Vector2d.TryAdd(body.Position, displacement, out Vector2d position)
 10648            || !mover.TryPrepareRecoveryPose(position, body.Rotation, out Vector2d preparedCenter)) return false;
 49        // A translated offset can change a midpoint tie by one raw unit;
 50        // certify the center the body will actually publish.
 9851        center = preparedCenter;
 9852        FixedBoundArea bounds = FixedBoundArea.FromCenterAndScopeClippedToDomain(center,
 9853            Vector2d.One * mover.CanonicalCenteredProxyRadius);
 9854        _context.Collisions2D.CollectBoundsCandidates(bounds.Min, bounds.Max, PhysicsLayerMask.All,
 9855            _context.Query2D.NextOverlapQueryVersion(), false, _candidates);
 34056        foreach (LSCollider2D candidate in _candidates.AsReadOnlySpan())
 57        {
 9758            if (candidate.IsTrigger || !_context.Physics2D.RequireCollisionPair(mover, candidate)) continue;
 13159            if (CollisionDetection2D.DoesPostureCandidatePenetrate(mover, center, candidate)) return false;
 60        }
 4861        return true;
 62    }
 63
 64    private static bool TryRecoveryDirection(LSCollider2D mover, Vector2d center, LSCollider2D member,
 65        out Vector2d normal, out Fixed64 depth)
 66    {
 7067        Span<Vector2d> targetBox = stackalloc Vector2d[4], movingBox = stackalloc Vector2d[4];
 3568        ReadOnlySpan<Vector2d> target = Offsets(member, targetBox);
 69        bool hit, clamped;
 3570        if (mover is LSCircleCollider2D or LSCapsuleCollider2D)
 71        {
 5472            Span<FixedPointAnchor2d> first = stackalloc FixedPointAnchor2d[2], second = stackalloc FixedPointAnchor2d[2]
 2773            hit = WideCenteredCapsule2dRelations.TryGetContacts(center, mover.Rotation, Vector2d.Forward,
 2774                mover is LSCapsuleCollider2D capsule ? capsule.AxisLength : Fixed64.Zero,
 2775                mover is LSCircleCollider2D circle ? circle.ScaledRadius : ((LSCapsuleCollider2D)mover).ScaledRadius,
 2776                member.Center, member.ConvexRotation, target, first, second, out _, out normal, out depth, out clamped);
 77        }
 78        else
 79        {
 1680            Span<Vector2d> first = stackalloc Vector2d[2], second = stackalloc Vector2d[2];
 881            hit = WideConvex2dRelations.TryGetContactOffsets(center, mover.ConvexRotation, Offsets(mover, movingBox),
 882                member.Center, member.ConvexRotation, target, first, second, out _, out normal, out depth, out clamped);
 83        }
 84        // Admitted colliders have reach <= 4,096; an intersecting local
 85        // pair's penetration cannot approach the scalar depth limit.
 86        System.Diagnostics.Debug.Assert(!hit || !clamped);
 3587        return hit;
 88    }
 89}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Core/2D/StaticSurfaces/StaticSurface2D.Serialization.cs

#LineLine coverage
 1//=======================================================================
 2// StaticSurface2D.Serialization.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.Globalization;
 10using Chronicler;
 11using Gravitas.Colliders;
 12
 13namespace Gravitas;
 14
 15/// <content>Records planar membership independently of derived joins and contact caches.</content>
 16public sealed partial class StaticSurface2D
 17{
 18    /// <inheritdoc/>
 19    public void RecordData(IChronicler chronicler)
 20    {
 2621        ChronicleGuard.ThrowIfNull(chronicler, nameof(chronicler));
 2522        _context.ThrowIfDisposed();
 2723        if (_disposed) throw new ObjectDisposedException(nameof(StaticSurface2D));
 2324        bool loading = chronicler.Mode == SerializationMode.Loading;
 3925        if (loading) _context.ThrowIfFixedStepMutationNotAllowed();
 2226        int schema = 1;
 2227        RecordValues.Look(chronicler, ref schema, "SurfaceSchemaVersion", 0);
 2428        if (schema != 1) throw new InvalidOperationException("Unsupported static-surface membership schema.");
 2029        int count = _members.Length;
 2030        RecordValues.Look(chronicler, ref count, "MemberCount", -1);
 2031        if (count < 0 || count > _context.Physics2D.ColliderCount)
 332            throw new ArgumentOutOfRangeException(nameof(count), "Membership must fit the registered collider graph.");
 1733        LSCollider2D[] members = loading ? new LSCollider2D[count] : _members;
 8034        for (int index = 0; index < count; index++)
 35        {
 2536            LSCollider2D member = members[index];
 2537            RecordLinks.Look(chronicler, ref member, "Member" + index.ToString(CultureInfo.InvariantCulture));
 3838            if (loading) members[index] = member;
 39        }
 2440        if (loading) ReplaceMembers(members);
 1141    }
 42}

Methods/Properties

.cctor()
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
InvalidateGeometry()
Reduce(Gravitas.Colliders.LSCollider2D,Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.ContactManifold2D,System.Boolean)
Gather(Gravitas.Colliders.LSCollider2D)
Prepare()
Build(Gravitas.Colliders.LSCollider2D,Gravitas.Colliders.LSCollider2D)
PlaneAdmitted(System.Int32,System.Int32)
SpansMeet(Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.BoundarySpan2D&,Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.BoundarySpan2D&)
FaceContacts(Gravitas.Colliders.LSCollider2D,System.Int32,System.Int32,System.Span`1<FixedMathSharp.Geometry.FixedContactAnchors2d>,System.Boolean)
BuildFan(System.Int32,FixedMathSharp.Geometry.FixedPointAnchor2d&)
Add(Gravitas.Colliders.LSCollider2D,System.Int32,System.Int32,FixedMathSharp.Geometry.FixedContactAnchors2d&,System.Boolean)
Offsets(Gravitas.Colliders.LSCollider2D,System.Span`1<FixedMathSharp.Vector2d>)
BoundsOverlap(Gravitas.Colliders.LSCollider2D,FixedMathSharp.Geometry.FixedBoundArea)
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
get_ContinuousOrder()
GetMixedContinuousSupport(Gravitas.Colliders.LSCollider2D,FixedMathSharp.Vector3d)
IntersectsMixedContinuous(Gravitas.Colliders.LSCollider,FixedMathSharp.Fixed64,System.Nullable`1<FixedMathSharp.Vector3d>,FixedMathSharp.Geometry.RationalPoint3d)
AppendMixedContinuousContacts(Gravitas.Colliders.LSCollider,Gravitas.CollisionHandling.ContactManifold,System.Nullable`1<FixedMathSharp.Vector3d>,FixedMathSharp.Geometry.RationalPoint3d)
GatherMixedContinuous(Gravitas.Colliders.LSCollider,FixedMathSharp.Fixed64)
AdmitContinuousWitness(Gravitas.Colliders.LSCollider2D,Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.ContactAnchor2D&)
AdmitMixedContinuousWitness(Gravitas.Colliders.LSCollider,FixedMathSharp.Vector3d,Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.ContactAnchor&)
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
get_ReplayMembership()
ReplaceMembers(System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
Invalidate(Gravitas.Colliders.LSCollider2D,System.Boolean)
Touches(FixedMathSharp.Geometry.FixedBoundBox&,FixedMathSharp.Geometry.FixedBoundBox&)
Remove(Gravitas.Colliders.LSCollider2D)
Dispose()
Release()
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
.cctor()
get_MixedMovingPoints()
get_MixedMovingTriangles()
get_MixedMovingEdges()
AppendMixed(Gravitas.Colliders.LSCollider,Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.ContactManifold,System.Int32,System.Int32)
RequestMixedReach(FixedMathSharp.Fixed64)
GatherMixed(Gravitas.Colliders.LSCollider,FixedMathSharp.Fixed64)
GatherMixedMembers(Gravitas.Colliders.LSCollider,FixedMathSharp.Geometry.FixedBoundBox,SwiftCollections.SwiftList`1<Gravitas.Colliders.LSCollider2D>)
PrepareMixed()
PrepareMixedBands(System.Int32)
BuildMixed()
BuildMixedPart()
FindMixedPenetration(TFrame&,Gravitas.StaticSurface2D/MixedPrism,FixedMathSharp.Geometry.WideScaledHullPenetration&,FixedMathSharp.Geometry.ScaledHullPenetrationAdmission)
AdmitMixedRigidAxis(FixedMathSharp.Geometry.WidePointSpanPenetration&)
AdmitMixedAxis(FixedMathSharp.Geometry.WideScaledHullPenetration&)
HasMixedReach(FixedMathSharp.Geometry.WideScaledHullPenetration&)
VisitMixed(FixedMathSharp.Geometry.WideScaledHullPenetration&,System.Boolean)
IsMixedFaceAxis(FixedMathSharp.Geometry.WideScaledHullPenetration&)
VisitMixedEdges(TFrame&,Gravitas.StaticSurface2D/MixedPrism,FixedMathSharp.Geometry.WideScaledHullPenetration&,System.Boolean)
VisitMixedEdgeInterval(TFrame&,Gravitas.StaticSurface2D/MixedPrism,System.Int32,System.Int32,FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Geometry.WideScaledHullPenetration&,System.Boolean)
VisitMixedEdgeInterior(TFrame&,System.ReadOnlySpan`1<FixedMathSharp.Vector3d>,FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Geometry.WideScaledHullPenetration&,System.Boolean)
VisitMixedFaces(FixedMathSharp.Geometry.WideScaledHullPenetration&,System.Boolean)
MixedSupportPoint(TFrame&,Gravitas.StaticSurface2D/MixedPrism,FixedMathSharp.Geometry.WideDirection3d&)
MaySupplyMixedFace(System.Int32,FixedMathSharp.Geometry.WideDirection3d&)
VisitMixedFaces(TFrame&,Gravitas.StaticSurface2D/MixedPrism,FixedMathSharp.Geometry.WideScaledHullPenetration&,System.Boolean)
VisitMixedSide(TFrame&,Gravitas.CollisionHandling.BoundarySpan2D&,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Geometry.WideScaledHullPenetration&,System.Boolean,System.Int32)
VisitMixedRigidFace(Gravitas.StaticSurface2D/MixedPrism,System.Int32,System.Boolean)
FindMixedGroup(FixedMathSharp.Geometry.WideScaledHullPenetration&)
FixedMathSharp.Geometry.IScaledConvexHullContactDomain.GetEdgeIntervals(System.Runtime.InteropServices.InAttribute))
GetMixedEdgeIntervals(System.Int32,System.Int32)
FixedMathSharp.Geometry.IScaledConvexHullContactDomain.ContainsPoint(System.Runtime.InteropServices.InAttribute))
FixedMathSharp.Geometry.IScaledConvexHullContactDomain.ContainsPoint(System.Runtime.InteropServices.InAttribute))
ContainsMixedPoint(System.Int32,System.Int32,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.WideDirection3d&)
SupportsMixedFan(TFrame&,TFrame&,FixedMathSharp.Vector3d,System.ReadOnlySpan`1<FixedMathSharp.Vector3d>,FixedMathSharp.Geometry.WideDirection3d&)
TryGetMixedHeights(System.Int32,System.Int32,FixedMathSharp.Fixed64&,FixedMathSharp.Fixed64&)
MixedHeightContains(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
AddMixedSample(FixedMathSharp.Geometry.FixedContactAnchors)
.ctor(System.Int32,System.Int32,FixedMathSharp.Vector3d,FixedMathSharp.Geometry.FixedContactAnchors)
get_Axis()
.ctor(System.Int32,System.Int32,FixedMathSharp.Geometry.WideScaledHullPenetration,System.Int32)
.ctor()
Matches(Gravitas.Colliders.LSCollider2D)
Prepare(Gravitas.Colliders.LSCollider2D,System.Boolean)
.ctor()
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
PrepareMixedBoundaryLines()
KeepMixedBoundaryLine(Gravitas.StaticSurface2D/MixedBoundaryLine)
AppendMixedCapsuleBoundaryPeaks(Gravitas.Colliders.LSCapsuleCollider)
MixedBoundaryLineNormal(Gravitas.StaticSurface2D/MixedBoundaryLine&)
GetMixedBoundaryBounds(FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Signed320&,FixedMathSharp.Signed320&,FixedMathSharp.Signed320&,FixedMathSharp.Signed320&)
SameMixedBoundaryInterval(FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Geometry.RationalSegmentInterval&)
.ctor(System.Int32,System.Int32,System.Int32,FixedMathSharp.Geometry.RationalSegmentInterval,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
FixedMathSharp.Geometry.IPrismCapsuleContactDomain.get_IncludeRecovery()
BuildMixedCapsule()
PrepareMixedCapsuleChoice(FixedMathSharp.Geometry.CapsulePrismContactDepth&,System.Boolean,System.Boolean)
RemoveMixedCapsuleParentWindows(System.Int32)
FixedMathSharp.Geometry.IPrismCapsuleContactDomain.GetSupportIntervals(System.Runtime.InteropServices.InAttribute))
SameMixedCapsuleIntervalWide(FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Geometry.RationalSegmentInterval&)
FixedMathSharp.Geometry.IPrismCapsuleContactDomain.AddSupportContact(System.Runtime.InteropServices.InAttribute),System.Boolean,System.Int32)
AddMixedCapsuleSample(Gravitas.StaticSurface2D/SphereGroup&,FixedMathSharp.Geometry.RationalSegmentInterval&,System.Boolean)
SameMixedCapsulePlane(System.Int32,System.Int32)
FixedMathSharp.Geometry.IPrismCapsuleContactDomain.GetEdgeIntervals(System.Int32,System.Int32)
FixedMathSharp.Geometry.IPrismCapsuleContactDomain.AdmitEdgePoint(System.Runtime.InteropServices.InAttribute))
FixedMathSharp.Geometry.IPrismCapsuleContactDomain.AddEdgeContact(System.Runtime.InteropServices.InAttribute),System.Int32,System.Int32,System.Int32)
GetMixedCapsuleEdge(System.Int32,System.Int32,System.Int32&,System.Int32&)
AppendMixedCapsule(Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.ContactManifold,System.Int32,System.Int32)
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
BuildMixedCurved()
VisitMixedCurvedMember(System.Boolean,FixedMathSharp.Fixed64,System.Span`1<FixedMathSharp.Geometry.WideDirection3d>,System.Boolean)
ContainsMixedCurvedBoundaryWindow(Gravitas.StaticSurface2D/MixedCurvedFaceWindow&,FixedMathSharp.Geometry.PrismCurvedBoundaryLine&)
AreMixedCurvedCutRowsCompatible(System.ReadOnlySpan`1<Gravitas.StaticSurface2D/CurvedBoundarySample>)
KeepMixedCurvedBoundary(System.Int32,FixedMathSharp.Geometry.FixedContactAnchors&,System.Int32)
.ctor(System.Int32,FixedMathSharp.Geometry.FixedContactAnchors,System.Int32,System.Boolean)
AddMixedCurvedSample(FixedMathSharp.Geometry.FixedContactAnchors&,System.Int32,System.Boolean,FixedMathSharp.Geometry.RationalSegmentInterval,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,System.Int32)
AppendMixedCurved(Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.ContactManifold,System.Int32,System.Int32)
.ctor(System.Int32,System.Int32,FixedMathSharp.Geometry.RationalSegmentInterval,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,System.Int32,System.Boolean,FixedMathSharp.Geometry.WideDirection3d,FixedMathSharp.Geometry.RationalPoint3d)
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
.cctor()
PrepareMixedCurvedDomain(FixedMathSharp.Geometry.CurvedPrismContactGeometry&,System.Boolean)
PrepareMixedCurvedDomains()
PrepareMixedCurvedEdges(Gravitas.StaticSurface2D/MixedCurvedDomain)
PrepareMixedCurvedEdge(Gravitas.StaticSurface2D/MixedCurvedDomain,System.Int32)
KeepMixedCurvedWindow(Gravitas.StaticSurface2D/MixedCurvedDomain,Gravitas.StaticSurface2D/MixedCurvedFaceWindow&)
PrepareMixedCurvedCertificates(System.Boolean,FixedMathSharp.Fixed64,System.Span`1<FixedMathSharp.Geometry.WideDirection3d>,System.Boolean)
GetMixedCurvedPlane(System.Int32,System.Int32,FixedMathSharp.Geometry.WideDirection3d&,FixedMathSharp.Geometry.RationalPoint3d&)
SameMixedCurvedPlane(FixedMathSharp.Geometry.WideDirection3d&,FixedMathSharp.Geometry.RationalPoint3d&,FixedMathSharp.Geometry.WideDirection3d&,FixedMathSharp.Geometry.RationalPoint3d&)
.ctor(System.Int32,Gravitas.StaticSurface2D/MixedCurvedFaceWindow,FixedMathSharp.Geometry.WideDirection3d,FixedMathSharp.Geometry.RationalPoint3d,FixedMathSharp.Geometry.FixedContactAnchors,System.Boolean)
.ctor(System.Int32,FixedMathSharp.Geometry.RationalSegmentInterval,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
.ctor()
AddMixedCurvedCertificatePlane(System.Int32,System.Boolean)
GetMixedCurvedPlaneForRow(System.Int32,System.Int32,FixedMathSharp.Geometry.FixedContactAnchors&,FixedMathSharp.Geometry.WideDirection3d&,FixedMathSharp.Geometry.RationalPoint3d&)
CompleteMixedCurvedRegions(System.Boolean,FixedMathSharp.Fixed64,System.Span`1<FixedMathSharp.Geometry.WideDirection3d>)
MixedCurvedCapsTouch(Gravitas.StaticSurface2D/CurvedGroup&,Gravitas.StaticSurface2D/CurvedGroup&,FixedMathSharp.Geometry.CurvedPrismContactGeometry&)
MixedCurvedSidesTouch(Gravitas.StaticSurface2D/CurvedGroup&,Gravitas.StaticSurface2D/CurvedGroup&,FixedMathSharp.Geometry.CurvedPrismContactGeometry&)
IntersectMixedCurvedEdges(System.Int32,System.Int32,FixedMathSharp.Geometry.RationalSegmentInterval&,System.Int32,System.Int32,FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Geometry.RationalSegmentInterval&)
IsBestMixedCurvedFarRegion(System.Int32)
RequestMixedCurvedFarReach()
AppendMixedCurvedRegions(Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.ContactManifold,System.Int32,System.Int32)
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
BuildMixedMesh(Gravitas.Colliders.PhysicsMesh)
SetMixedMovingFeature(System.Int32)
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
AddMixedRegion(System.Int32,System.Int32,Gravitas.CollisionHandling.BoundarySpan2D&,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,System.Int32,System.Int32,System.Int32,System.Int32,FixedMathSharp.Geometry.RationalSegmentInterval)
HasMixedFaceRegion(System.Int32)
CompleteMixedRegions()
AppendMixedRegionSamples(System.Int32,FixedMathSharp.Geometry.WideDirection3d&,Gravitas.CollisionHandling.ContactManifold,System.Int32,System.Int32,System.Span`1<System.Int32>,FixedMathSharp.Geometry.FixedPointAnchor&)
FindMixedRegion(System.Int32)
MixedEdgeRegionsTouch(Gravitas.StaticSurface2D/MixedRegion&,Gravitas.StaticSurface2D/MixedRegion&)
MixedVerticalEdgeRegionsTouch(Gravitas.StaticSurface2D/MixedRegion&,Gravitas.StaticSurface2D/MixedRegion&,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
TryIntersectMixedIntervals(FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Geometry.RationalSegmentInterval&)
MixedFaceEdgeRegionsTouch(Gravitas.StaticSurface2D/MixedRegion&,Gravitas.StaticSurface2D/MixedRegion&)
MixedEdgeRegionEndpoint(Gravitas.StaticSurface2D/MixedRegion&,Gravitas.StaticSurface2D/MixedRegion&,TFrame&,TFrame&,System.Int32)
IntersectsMixedRegionEdge(Gravitas.StaticSurface2D/MixedRegion&,FixedMathSharp.Geometry.RationalSegmentInterval&,System.Int32)
MixedRegionBoundary(Gravitas.StaticSurface2D/MixedRegion&)
MixedRegionsTouch(Gravitas.StaticSurface2D/MixedRegion&,Gravitas.StaticSurface2D/MixedRegion&)
MixedCapSupportVertex(TFrame&,FixedMathSharp.Geometry.FixedTriangle&,FixedMathSharp.Geometry.RationalSegmentInterval&,System.Int32)
MixedRegionRectangle(Gravitas.StaticSurface2D/MixedRegion&)
MixedSideRegionsTouch(Gravitas.StaticSurface2D/MixedRegion&,Gravitas.StaticSurface2D/MixedRegion&,TFrame&,TFrame&,FixedMathSharp.Fixed64)
IntersectsMixedRegionSegment(System.Int32,FixedMathSharp.Geometry.FixedSegment&,FixedMathSharp.Geometry.RationalSegmentInterval&,System.Int32,System.Int32,Gravitas.CollisionHandling.BoundarySpan2D)
VisitMixedRegionSegment(TFrame&,System.Int32,System.ReadOnlySpan`1<FixedMathSharp.Vector3d>,System.ReadOnlySpan`1<System.Int32>,System.Int32)
.ctor(System.Int32,System.Int32,System.Int32,System.Int32,Gravitas.CollisionHandling.BoundarySpan2D&,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,System.Int32,System.Int32,FixedMathSharp.Geometry.RationalSegmentInterval&)
.ctor()
GetEdgeIntervals(System.Boolean,System.Int32,System.Int32,FixedMathSharp.Geometry.WideDirection3d&)
ContainsPoint(System.Boolean,System.Int32,System.Int32,FixedMathSharp.Signed832&,FixedMathSharp.Signed832&,FixedMathSharp.Geometry.WideDirection3d&)
ContainsPoint(System.Boolean,System.Int32,System.Int32,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.WideDirection3d&)
ContainsParameter(FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic)
.ctor(Gravitas.GravitasWorldContext,System.ReadOnlySpan`1<Gravitas.Colliders.LSCollider2D>)
BuildMixedSphere()
SelectMixedSphereSources(FixedMathSharp.Fixed64)
PrepareMixedSphereConcavity()
AppendMixedSphere(Gravitas.Colliders.LSCollider2D,Gravitas.CollisionHandling.ContactManifold,System.Int32,System.Int32)
.ctor(System.Int32,System.Int32,System.Int32,FixedMathSharp.Geometry.WideDirection3d,FixedMathSharp.Geometry.RationalPoint3d,FixedMathSharp.Geometry.WideConvexPrismRelations/ProjectionDepth,FixedMathSharp.Geometry.FixedContactAnchors,System.Boolean)
.ctor(System.Int32,System.Int32,System.Int32,System.Int32,FixedMathSharp.Fixed64,FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Geometry.FixedContactAnchors&)
AppendMixedSphereFacePeaks(FixedMathSharp.Fixed64,System.Int32)
AdmitMixedSphereBoundaryPoint(FixedMathSharp.Geometry.RationalSegmentInterval&,FixedMathSharp.Fixed64,FixedMathSharp.Geometry.WideDirection3d&)
AdmitMixedSpherePoint(FixedMathSharp.Geometry.WideDirection3d&,FixedMathSharp.Geometry.WideConvexPrismRelations/ProjectionDepth&,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic)
AdmitMixedPrismSupportPoint(FixedMathSharp.Geometry.WideDirection3d&,FixedMathSharp.Geometry.WideConvexPrismRelations/ProjectionDepth&,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic)
AdmitMixedSphereFan(FixedMathSharp.Geometry.FixedSegment&,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.ContactQuadratic,FixedMathSharp.Geometry.WideDirection3d&)
TryGetRecovery(Gravitas.Colliders.LSCollider2D,FixedMathSharp.Vector2d&)
IsRecoveryClear(Gravitas.Colliders.LSCollider2D,FixedMathSharp.Vector2d)
TryRecoveryDirection(Gravitas.Colliders.LSCollider2D,FixedMathSharp.Vector2d,Gravitas.Colliders.LSCollider2D,FixedMathSharp.Vector2d&,FixedMathSharp.Fixed64&)
RecordData(Chronicler.IChronicler)