Skip to content

Fix VesselDistanceComparer throwing ArgumentException when vessel position is NaN#388

Open
kilfoil wants to merge 1 commit into
FirstPersonKSP:masterfrom
kilfoil:fix/vessel-distance-comparer-nan
Open

Fix VesselDistanceComparer throwing ArgumentException when vessel position is NaN#388
kilfoil wants to merge 1 commit into
FirstPersonKSP:masterfrom
kilfoil:fix/vessel-distance-comparer-nan

Conversation

@kilfoil

@kilfoil kilfoil commented Jul 4, 2026

Copy link
Copy Markdown

Problem

MASFlightComputerProxy.VesselDistanceComparer.Compare() uses:

return (int)(distA - distB);

Array.Sort() requires a consistent IComparer. If any vessel's GetTransform().position contains NaN (which can occur with certain save states), then distA or distB is NaN, and (int)(NaN - NaN) evaluates to 0 regardless of operand order. This violates the sort contract (transitivity) and causes Array.Sort() to throw:

ArgumentException: Unable to sort because the IComparer.Compare() method
returns inconsistent results. IComparer:
'AvionicsSystems.MASFlightComputerProxy+VesselDistanceComparer'

This fires on every FixedUpdate (50×/sec) while in IVA with nearby vessels, generating thousands of log entries and breaking any MFD page that displays neighbouring vessel information.

The same (int) cast also overflows silently for very large squared distances (> int.MaxValue ≈ 46,340 km), producing incorrect sort order at interplanetary distances.

Fix

Replace the cast with float.CompareTo(), which handles NaN and large values correctly:

return distA.CompareTo(distB);

One character change; no behaviour change for normal finite distances.

…ition is NaN

Array.Sort() requires a consistent IComparer. The original implementation
casts float subtraction to int: (int)(distA - distB). This produces
inconsistent results when any vessel's transform position contains NaN
(NaN - NaN = NaN; (int)NaN = 0 regardless of operand order), which
violates the sort contract and causes an ArgumentException from Array.Sort()
on every FixedUpdate.

Also fixes a secondary issue where very large squared distances (> int.MaxValue)
could overflow and produce incorrect ordering.

Fix: replace (int)(distA - distB) with distA.CompareTo(distB), which handles
NaN and large values correctly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant