< Summary

Line coverage
100%
Covered lines: 262
Uncovered lines: 0
Coverable lines: 262
Total lines: 465
Line coverage: 100%
Branch coverage
100%
Covered branches: 134
Total branches: 134
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/CollisionHandling/Pairs/Mixed/CollisionPairMixed.cs

#LineLine coverage
 1//=======================================================================
 2// CollisionPairMixed.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System;
 9using System.Runtime.CompilerServices;
 10using FixedMathSharp;
 11using Gravitas.Colliders;
 12using SwiftCollections;
 13
 14namespace Gravitas.CollisionHandling;
 15
 16/// <summary>
 17/// Owns one stable mixed 3D/2D collision pair identity and contact lifecycle.
 18/// </summary>
 19/// <content>Owns retained mixed manifold rows, per-step impulses, notifications and replay state.</content>
 20internal sealed partial class CollisionPairMixed
 21{
 22    private bool _isColliding;
 23    private bool _isTriggerPair;
 24    private bool _notificationInProgress;
 25    private bool _separationPending;
 26    private bool _collider3DNotified;
 27    private bool _collider2DNotified;
 28    private long _lifetimeVersion;
 29    private uint _lastCollider3DContactDependencyVersion;
 30    private uint _lastCollider2DContactDependencyVersion;
 31    private bool _hasManifoldCache;
 32    private uint _manifold3DBroadPhaseVersion, _manifold2DBroadPhaseVersion;
 33    private uint _manifold3DContactDependencyVersion, _manifold2DContactDependencyVersion;
 34    private Vector2d _manifold2DCenter;
 35    private Fixed64 _manifold2DRotation;
 36    private bool _watchSpatialLayerRow, _watchPlanarLayerColumn;
 37    private ulong _manifoldCollisionLayers;
 38
 81039    public CollisionPairMixed(LSCollider collider3D, LSCollider2D collider2D)
 40    {
 81041        Collider3D = collider3D;
 81042        Collider2D = collider2D;
 81043        Initialize(collider3D, collider2D);
 81044    }
 45
 46    public LSCollider Collider3D { get; private set; }
 47
 48    public LSCollider2D Collider2D { get; private set; }
 49
 50    public int Collider3DId { get; private set; }
 51
 52    public int Collider2DId { get; private set; }
 53
 54    public ulong Key { get; private set; }
 55
 8013756    public GravitasWorldContext Context => Collider3D.Context;
 57
 58    public long LastFrame { get; private set; } = -1;
 59
 60    // Collision-pass freshness is independent of hosts advancing the public frame clock.
 61    internal long LastVisitToken { get; private set; } = -1;
 62
 63    public MixedContact Contact { get; private set; }
 64
 65    public ContactManifold Manifold { get; } = new();
 66
 67    // Accumulation belongs to one solve pass; mixed pairs do not warm-start across frames.
 68    internal ContactWarmStartCache SolveImpulses;
 69
 70    internal ExactContactImpulseState?[]? ExactSolveImpulses;
 71
 72    internal ContactResponseSnapshot ResponseSnapshot { get; set; }
 73
 6464274    internal long LifetimeVersion => _lifetimeVersion;
 75
 18376    internal bool IsNotificationInProgress => _notificationInProgress;
 77
 78    public void Initialize(LSCollider collider3D, LSCollider2D collider2D)
 79    {
 82180        ChronicleGuard.ThrowIfNull(collider3D, nameof(collider3D));
 82181        ChronicleGuard.ThrowIfNull(collider2D, nameof(collider2D));
 82
 82183        _lifetimeVersion++;
 82184        Collider3D = collider3D;
 82185        Collider2D = collider2D;
 82186        Collider3DId = collider3D.Id;
 82187        Collider2DId = collider2D.Id;
 82188        Key = MixedColliderKey.CreateKey(Collider3DId, Collider2DId);
 82189        LastFrame = -1;
 82190        LastVisitToken = -1;
 82191        _isColliding = false;
 82192        _hasManifoldCache = false;
 82193        _watchSpatialLayerRow = _watchPlanarLayerColumn = false;
 82194        _manifoldCollisionLayers = 0;
 82195        _lastCollider3DContactDependencyVersion = 0;
 82196        _lastCollider2DContactDependencyVersion = 0;
 82197        _isTriggerPair = collider3D.IsTrigger || collider2D.IsTrigger;
 82198        _notificationInProgress = false;
 82199        _separationPending = false;
 821100        _collider3DNotified = false;
 821101        _collider2DNotified = false;
 821102        Contact = default;
 821103        Manifold.Reset();
 821104        ClearSolveState();
 821105    }
 106
 107    public void MarkColliding(long frame, MixedContact contact)
 108    {
 12109        PublishContact(frame, contact);
 12110        NotifyCollision(frame);
 10111    }
 112
 113    public void MarkColliding(long frame, ContactManifold manifold)
 114    {
 16090115        PublishManifold(frame, manifold);
 16090116        NotifyCollision(frame);
 16090117    }
 118
 119    private void NotifyCollision(long frame)
 120    {
 16102121        bool changed = !_isColliding;
 16102122        _isColliding = true;
 16102123        _isTriggerPair = Collider3D.IsTrigger || Collider2D.IsTrigger;
 16102124        LastFrame = frame;
 16102125        LastVisitToken = Context.LateSimulateToken;
 126
 16102127        Context.Diagnostics.EmitMixedContact(this, Contact);
 128
 16102129        var registration3D = new ColliderLifetimeToken(Collider3D);
 16102130        var registration2D = new ColliderLifetimeToken2D(Collider2D);
 16102131        bool shouldRaiseTrigger = ColliderTriggerEventPolicy.ShouldRaise(Collider3D, Collider2D);
 16102132        _notificationInProgress = true;
 16102133        SwiftList<Exception>? notificationExceptions = null;
 134        try
 135        {
 16102136            bool notifyEnter3D = changed || !_collider3DNotified;
 16102137            _collider3DNotified = true;
 16102138            Collider3D.NotifyMixedContact(
 16102139                Collider2D,
 16102140                true,
 16102141                notifyEnter3D,
 16102142                _isTriggerPair,
 16102143                allowInactive: false,
 16102144                registration3D,
 16102145                registration2D,
 16102146                shouldRaiseTrigger);
 16101147            if (_isColliding && registration3D.IsActive && registration2D.IsActive && !_separationPending)
 148            {
 16090149                bool notifyEnter2D = changed || !_collider2DNotified;
 16090150                _collider2DNotified = true;
 16090151                Collider2D.NotifyMixedContact(
 16090152                    Collider3D,
 16090153                    true,
 16090154                    notifyEnter2D,
 16090155                    _isTriggerPair,
 16090156                    allowInactive: false,
 16090157                    registration2D,
 16090158                    registration3D,
 16090159                    shouldRaiseTrigger);
 160            }
 16101161        }
 1162        catch (Exception exception)
 163        {
 1164            CollisionNotificationExceptions.Capture(ref notificationExceptions, exception);
 1165        }
 166
 167        try
 168        {
 16102169            EndNotification(
 16102170                registration3D,
 16102171                registration2D,
 16102172                shouldRaiseTrigger);
 16101173        }
 1174        catch (Exception exception)
 175        {
 1176            CollisionNotificationExceptions.Capture(ref notificationExceptions, exception);
 1177        }
 178
 16102179        CollisionNotificationExceptions.ThrowIfAny(notificationExceptions);
 16100180    }
 181
 182    public void MarkResting(long frame)
 183    {
 2184        _hasManifoldCache = false;
 2185        RefreshContactDependencies();
 2186        LastFrame = frame;
 2187        LastVisitToken = Context.LateSimulateToken;
 2188        ClearSolveState();
 2189    }
 190
 191    public void MarkResting(long frame, ContactManifold manifold)
 192    {
 154193        PublishManifold(frame, manifold);
 153194        LastFrame = frame;
 153195        LastVisitToken = Context.LateSimulateToken;
 153196    }
 197
 198    private void PublishContact(long frame, MixedContact contact)
 199    {
 12200        _hasManifoldCache = false;
 12201        RefreshContactDependencies(incomingPlanar: contact.HasContact && contact.Normal3DTo2D.ToVector2d() != Vector2d.Z
 12202        Manifold.BeginUpdate(frame);
 12203        if (contact.HasContact)
 10204            Manifold.AddContact(default, contact.ToManifoldContact());
 12205        Contact = contact;
 12206        ClearSolveState();
 12207    }
 208
 209    private void PublishManifold(long frame, ContactManifold source)
 210    {
 16244211        ChronicleGuard.ThrowIfNull(source, nameof(source));
 16243212        bool solid = !Collider3D.IsTrigger && !Collider2D.IsTrigger;
 16243213        bool watchRow = solid && Collider2D.StaticSurface != null;
 16243214        bool watchColumn = solid && Collider3D is LSMeshCollider { StaticSurface: not null };
 16243215        ulong layers = watchRow || watchColumn
 16243216            ? Context.Settings.GetCollisionLayerMask(Collider3D.Layer, Collider2D.Layer, watchRow, watchColumn) : 0;
 217        // An edited but locally unused matrix bit must not wake an unchanged
 218        // sleeper. Compare the rebuilt physical rows before publishing them.
 16243219        if (_isColliding && _hasManifoldCache && layers != _manifoldCollisionLayers && !Manifold.HasSameContacts(source)
 2220            WakeBodiesForContactChange(source);
 16243221        _hasManifoldCache = false;
 16243222        RefreshContactDependencies(source);
 16243223        Manifold.CopyFrom(source, frame);
 16243224        Contact = Manifold.HasContact ? MixedContact.FromManifoldContact(Manifold.PrimaryContact) : default;
 16243225        _manifold3DBroadPhaseVersion = Collider3D.BroadPhaseVersion;
 16243226        _manifold2DBroadPhaseVersion = Collider2D.BroadPhaseVersion;
 16243227        _manifold3DContactDependencyVersion = Collider3D.ContactDependencyVersion;
 16243228        _manifold2DContactDependencyVersion = Collider2D.ContactDependencyVersion;
 16243229        _manifold2DCenter = Collider2D.Center;
 16243230        _manifold2DRotation = Collider2D.Rotation;
 32486231        _watchSpatialLayerRow = watchRow; _watchPlanarLayerColumn = watchColumn;
 16243232        _manifoldCollisionLayers = layers;
 16243233        _hasManifoldCache = true;
 16243234        ClearSolveState();
 16243235    }
 236
 237    // Dynamic 2D pose can change without a partition or contact-dependency revision.
 31782238    internal bool HasCurrentManifoldCache => _isColliding && _hasManifoldCache
 31782239        && _manifold3DBroadPhaseVersion == Collider3D.BroadPhaseVersion
 31782240        && _manifold2DBroadPhaseVersion == Collider2D.BroadPhaseVersion
 31782241        && _manifold3DContactDependencyVersion == Collider3D.ContactDependencyVersion
 31782242        && _manifold2DContactDependencyVersion == Collider2D.ContactDependencyVersion
 31782243        && _manifold2DCenter == Collider2D.Center
 31782244        && _manifold2DRotation == Collider2D.Rotation
 31782245        && (!_watchSpatialLayerRow && !_watchPlanarLayerColumn || _manifoldCollisionLayers ==
 31782246            Context.Settings.GetCollisionLayerMask(Collider3D.Layer, Collider2D.Layer,
 31782247                _watchSpatialLayerRow, _watchPlanarLayerColumn));
 248
 249    internal bool TryCopyCachedManifold(long frame, ContactManifold target)
 250    {
 30474251        if (!HasCurrentManifoldCache) return false;
 748252        target.CopyFrom(Manifold, frame);
 748253        return true;
 254    }
 255
 256    internal void InvalidateSurfaceContact(bool wake)
 257    {
 462258        _hasManifoldCache = false;
 462259        ClearSolveState();
 692260        if (wake && _isColliding && !_isTriggerPair) WakeBodiesForContactChange();
 462261    }
 262
 263    private void ClearSolveState()
 264    {
 17728265        SolveImpulses.Clear();
 17728266        if (ExactSolveImpulses != null)
 45267            foreach (ExactContactImpulseState? state in ExactSolveImpulses) state?.Clear();
 17728268        ResponseSnapshot = default;
 17728269    }
 270    public void MarkSeparated()
 271    {
 188272        _hasManifoldCache = false;
 188273        if (_isColliding && !_isTriggerPair)
 168274            WakeBodiesForContactChange();
 188275        Manifold.Reset();
 188276        ClearSolveState();
 188277        Contact = default;
 278        // The 2D side is admitted only after the 3D side, so it cannot be the sole notified side.
 188279        if (!_isColliding && !_collider3DNotified)
 2280            return;
 281
 186282        _isColliding = false;
 186283        if (_notificationInProgress)
 284        {
 16285            _separationPending = true;
 16286            return;
 287        }
 288
 170289        var registration3D = new ColliderLifetimeToken(Collider3D);
 170290        var registration2D = new ColliderLifetimeToken2D(Collider2D);
 170291        _notificationInProgress = true;
 292        try
 293        {
 170294            NotifySeparation(
 170295                registration3D,
 170296                registration2D,
 170297                ColliderTriggerEventPolicy.ShouldRaise(Collider3D, Collider2D));
 169298        }
 299        finally
 300        {
 170301            _separationPending = false;
 170302            _notificationInProgress = false;
 170303        }
 169304    }
 305
 306    private void EndNotification(
 307        in ColliderLifetimeToken registration3D,
 308        in ColliderLifetimeToken2D registration2D,
 309        bool shouldRaiseTrigger)
 310    {
 311        try
 312        {
 16102313            if (!_separationPending)
 16086314                return;
 315
 16316            _separationPending = false;
 16317            NotifySeparation(registration3D, registration2D, shouldRaiseTrigger);
 15318        }
 319        finally
 320        {
 16102321            _separationPending = false;
 16102322            _notificationInProgress = false;
 16102323        }
 16101324    }
 325
 326    private void NotifySeparation(
 327        in ColliderLifetimeToken registration3D,
 328        in ColliderLifetimeToken2D registration2D,
 329        bool shouldRaiseTrigger)
 330    {
 186331        bool notify2D = _collider2DNotified;
 186332        _collider3DNotified = false;
 186333        _collider2DNotified = false;
 186334        SwiftList<Exception>? notificationExceptions = null;
 335        try
 336        {
 186337            Collider3D.NotifyMixedContact(
 186338                Collider2D,
 186339                false,
 186340                true,
 186341                _isTriggerPair,
 186342                allowInactive: true,
 186343                registration3D,
 186344                registration2D,
 186345                shouldRaiseTrigger);
 184346        }
 2347        catch (Exception exception)
 348        {
 2349            CollisionNotificationExceptions.Capture(ref notificationExceptions, exception);
 2350        }
 351
 186352        if (notify2D && registration2D.IsCurrentLifetime)
 353        {
 354            try
 355            {
 173356                Collider2D.NotifyMixedContact(
 173357                    Collider3D,
 173358                    false,
 173359                    true,
 173360                    _isTriggerPair,
 173361                    allowInactive: true,
 173362                    registration2D,
 173363                    registration3D,
 173364                    shouldRaiseTrigger);
 172365            }
 1366            catch (Exception exception)
 367            {
 1368                CollisionNotificationExceptions.Capture(ref notificationExceptions, exception);
 1369            }
 370        }
 371
 186372        CollisionNotificationExceptions.ThrowIfAny(notificationExceptions);
 184373    }
 374
 375    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 376    private void RefreshContactDependencies(ContactManifold? incoming = null, bool incomingPlanar = false)
 377    {
 16257378        uint version3D = Collider3D.ContactDependencyVersion;
 16257379        uint version2D = Collider2D.ContactDependencyVersion;
 16257380        bool triggerPair = Collider3D.IsTrigger || Collider2D.IsTrigger;
 381        // Replacing a planar constraint with a vertical one still invalidates
 382        // its former 2D dependency. Purely vertical rows never couple 2D wake.
 16257383        if (_isColliding)
 384        {
 15550385            if (triggerPair != _isTriggerPair) WakeBodiesForContactChange(incoming, incomingPlanar);
 15542386            else if (!triggerPair)
 387            {
 16015388                if (version2D != _lastCollider2DContactDependencyVersion) Collider3D.Body?.WakeForContactChange();
 15468389                if (version3D != _lastCollider3DContactDependencyVersion)
 1292390                    Wake2DBodyForContactChange(incoming, incomingPlanar);
 391            }
 392        }
 393
 16257394        _lastCollider3DContactDependencyVersion = version3D;
 16257395        _lastCollider2DContactDependencyVersion = version2D;
 16257396        _isTriggerPair = triggerPair;
 16257397    }
 398
 399    private void WakeBodiesForContactChange(ContactManifold? incoming = null, bool incomingPlanar = false)
 400    {
 404401        Collider3D.Body?.WakeForContactChange();
 404402        Wake2DBodyForContactChange(incoming, incomingPlanar);
 404403    }
 404
 405    private void Wake2DBodyForContactChange(ContactManifold? incoming, bool incomingPlanar)
 406    {
 1696407        SolidBody2D? body = Collider2D.Body;
 1696408        if (body?.IsSleeping != true)
 1675409            return;
 410
 21411        if (incomingPlanar || CollisionResponseMixed.HasPlanarResponseCoupling(Manifold)
 21412            || (incoming != null && CollisionResponseMixed.HasPlanarResponseCoupling(incoming)))
 12413            body.WakeForContactChange();
 21414    }
 415
 416    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 417    internal void WakeSleepingBodiesForCollision()
 418    {
 10397419        SolidBody? body3D = Collider3D.Body;
 10397420        SolidBody2D? body2D = Collider2D.Body;
 10397421        if (body3D == null || body2D == null)
 10265422            return;
 423
 132424        bool body3DAwake = body3D.IsAwakeForCollision;
 132425        bool body2DAwake = body2D.IsAwakeForCollision;
 132426        if (body3D.IsSleeping && body2DAwake)
 1427            body3D.Wake();
 132428        if (body2D.IsSleeping && body3DAwake)
 3429            body2D.Wake();
 132430    }
 431}

/home/runner/work/Gravitas/Gravitas/src/Gravitas/CollisionHandling/Pairs/Mixed/CollisionPairMixed.ReplayHash.cs

#LineLine coverage
 1//=======================================================================
 2// CollisionPairMixed.ReplayHash.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 Chronicler.Hashing;
 9
 10namespace Gravitas.CollisionHandling;
 11
 12/// <content>Hashes mixed pair identity, contact freshness, and retained manifolds.</content>
 13internal sealed partial class CollisionPairMixed
 14{
 15    internal void ContributeReplayHash(
 16        ref ChronicleHashWriter writer,
 17        GravitasReplayHashMode mode)
 18    {
 25719        writer.WriteSection("pair.mixed", 9);
 25720        writer.WriteInt32(Collider3D.ReplayOrdinal);
 25721        writer.WriteInt32(Collider2D.ReplayOrdinal);
 25722        writer.WriteUInt64(MixedColliderKey.CreateKey(Collider3D.ReplayOrdinal, Collider2D.ReplayOrdinal));
 25723        writer.WriteInt64(LastFrame);
 25724        writer.WriteBool(_isColliding);
 25725        writer.WriteBool(_isTriggerPair);
 26        // Only an existing contact depends on these stamps; loading may republish noncontact geometry.
 25727        writer.WriteBool(!_isColliding || _lastCollider3DContactDependencyVersion == Collider3D.ContactDependencyVersion
 25728        writer.WriteBool(!_isColliding || _lastCollider2DContactDependencyVersion == Collider2D.ContactDependencyVersion
 25729        writer.WriteBool(!_isColliding || !_hasManifoldCache || HasCurrentManifoldCache);
 25730        CollisionPair.ContributeManifoldReplayHash(ref writer, Context, Manifold, "manifold.mixed");
 31        // Per-step impulses are rebuilt before the next solve and cannot
 32        // affect future authoritative state, unlike cross-frame 3D warm starts.
 25733    }
 34}