Fix computation of clusters and var->let

Compare matrix values against `undefined` instead of relying on `||`
because `||` does not work as intended when distance is `0`.

Differential Revision: https://code.wildfiregames.com/D2761
Fixes: #5761

This was SVN commit r23693.
This commit is contained in:
Angen
2020-05-23 12:53:11 +00:00
parent c8e6c05334
commit 21e3eedd2f
@@ -1559,20 +1559,20 @@ function GetFormationUnitAIs(ents, player, formationTemplate)
*/
function ClusterEntities(ents, separationDistance)
{
var clusters = [];
let clusters = [];
if (!ents.length)
return clusters;
var distSq = separationDistance * separationDistance;
var positions = [];
let distSq = separationDistance * separationDistance;
let positions = [];
// triangular matrix with the (squared) distances between the different clusters
// the other half is not initialised
var matrix = [];
let matrix = [];
for (let i = 0; i < ents.length; ++i)
{
matrix[i] = [];
clusters.push([ents[i]]);
var cmpPosition = Engine.QueryInterface(ents[i], IID_Position);
let cmpPosition = Engine.QueryInterface(ents[i], IID_Position);
positions.push(cmpPosition.GetPosition2D());
for (let j = 0; j < i; ++j)
matrix[i][j] = positions[i].distanceToSquared(positions[j]);
@@ -1580,10 +1580,10 @@ function ClusterEntities(ents, separationDistance)
while (clusters.length > 1)
{
// search two clusters that are closer than the required distance
var closeClusters = undefined;
let closeClusters = undefined;
for (var i = matrix.length - 1; i >= 0 && !closeClusters; --i)
for (var j = i - 1; j >= 0 && !closeClusters; --j)
for (let i = matrix.length - 1; i >= 0 && !closeClusters; --i)
for (let j = i - 1; j >= 0 && !closeClusters; --j)
if (matrix[i][j] < distSq)
closeClusters = [i,j];
@@ -1592,17 +1592,19 @@ function ClusterEntities(ents, separationDistance)
return clusters;
// make a new cluster with the entities from the two found clusters
var newCluster = clusters[closeClusters[0]].concat(clusters[closeClusters[1]]);
let newCluster = clusters[closeClusters[0]].concat(clusters[closeClusters[1]]);
// calculate the minimum distance between the new cluster and all other remaining
// clusters by taking the minimum of the two distances.
var distances = [];
let distances = [];
for (let i = 0; i < clusters.length; ++i)
{
if (i == closeClusters[1] || i == closeClusters[0])
let a = closeClusters[1];
let b = closeClusters[0];
if (i == a || i == b)
continue;
var dist1 = matrix[closeClusters[1]][i] || matrix[i][closeClusters[1]];
var dist2 = matrix[closeClusters[0]][i] || matrix[i][closeClusters[0]];
let dist1 = matrix[a][i] !== undefined ? matrix[a][i] : matrix[i][a];
let dist2 = matrix[b][i] !== undefined ? matrix[b][i] : matrix[i][b];
distances.push(Math.min(dist1, dist2));
}
// remove the rows and columns in the matrix for the merged clusters,