Merge pull request #14784 from calixteman/intersect

Improve performance of shared/utils.js::intersect (bug 1135277)
This commit is contained in:
calixteman 2022-04-15 22:38:19 +02:00 committed by GitHub
commit 681a9b8927
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -827,46 +827,33 @@ class Util {
} }
// Returns a rectangle [x1, y1, x2, y2] corresponding to the // Returns a rectangle [x1, y1, x2, y2] corresponding to the
// intersection of rect1 and rect2. If no intersection, returns 'false' // intersection of rect1 and rect2. If no intersection, returns 'null'
// The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
static intersect(rect1, rect2) { static intersect(rect1, rect2) {
function compare(a, b) { const xLow = Math.max(
return a - b; Math.min(rect1[0], rect1[2]),
Math.min(rect2[0], rect2[2])
);
const xHigh = Math.min(
Math.max(rect1[0], rect1[2]),
Math.max(rect2[0], rect2[2])
);
if (xLow > xHigh) {
return null;
} }
const yLow = Math.max(
// Order points along the axes Math.min(rect1[1], rect1[3]),
const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare); Math.min(rect2[1], rect2[3])
const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare); );
const result = []; const yHigh = Math.min(
Math.max(rect1[1], rect1[3]),
rect1 = Util.normalizeRect(rect1); Math.max(rect2[1], rect2[3])
rect2 = Util.normalizeRect(rect2); );
if (yLow > yHigh) {
// X: first and second points belong to different rectangles?
if (
(orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
(orderedX[0] === rect2[0] && orderedX[1] === rect1[0])
) {
// Intersection must be between second and third points
result[0] = orderedX[1];
result[2] = orderedX[2];
} else {
return null; return null;
} }
// Y: first and second points belong to different rectangles? return [xLow, yLow, xHigh, yHigh];
if (
(orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
(orderedY[0] === rect2[1] && orderedY[1] === rect1[1])
) {
// Intersection must be between second and third points
result[1] = orderedY[1];
result[3] = orderedY[2];
} else {
return null;
}
return result;
} }
// From https://github.com/adobe-webplatform/Snap.svg/blob/b365287722a72526000ac4bfcf0ce4cac2faa015/src/path.js#L852 // From https://github.com/adobe-webplatform/Snap.svg/blob/b365287722a72526000ac4bfcf0ce4cac2faa015/src/path.js#L852