Skip to content

Commit

Permalink
Fix OpenTTD#7561: Fix power/running cost vehicle engine sorter
Browse files Browse the repository at this point in the history
  • Loading branch information
dorobouNeko committed May 6, 2019
1 parent 0bbce5b commit 1cf644b
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/build_vehicle_gui.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -273,21 +273,31 @@ static bool EnginePowerVsRunningCostSorter(const EngineID &a, const EngineID &b)
uint p_b = e_b->GetPower();
Money r_a = e_a->GetRunningCost();
Money r_b = e_b->GetRunningCost();
/* Check if running cost is zero in one or both engines */
/* Check if running cost is zero in one or both engines.
* If only one of them is zero then that one has higher value,
* else if both have zero cost then compare powers.
*/
if (r_a == 0) {
if (r_b == 0) {
if (p_a == p_b) return EngineNumberSorter(a,b);
return _engine_sort_direction ? p_a >= p_b : p_a < p_b;
/* If it is ambiguous which to return go with their ID */
if (p_a == p_b) return EngineNumberSorter(a, b);
return _engine_sort_direction != (p_a < p_b);
}
return !_engine_sort_direction;
}
if (r_b == 0 ) return _engine_sort_direction;

float va = p_a / r_a;
float vb = p_b / r_b;
/* Use EngineID to sort instead since we want consistent sorting */
if (va == vb) return EngineNumberSorter(a,b);
return _engine_sort_direction ? va > vb : va < vb;
if (r_b == 0) return _engine_sort_direction;
/* Using double for more precision when comparing close values.
* This shouldn't have any major effects in performance nor in keeping
* the game in sync between players since it's used in GUI only in client side
*/
double v_a = (double)p_a / (double)r_a;
double v_b = (double)p_b / (double)r_b;
/* Use EngineID to sort if both have same power/running cost,
* for example if both had zero power,
* since we want consistent sorting
*/
if (v_a == v_b) return EngineNumberSorter(a, b);
return _engine_sort_direction != (v_a < v_b);
}

/* Train sorting functions */
Expand Down

0 comments on commit 1cf644b

Please sign in to comment.