Skip to content

Commit

Permalink
refactor(data): switch to turf all-in-one package and fix some types
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelMakesGames committed Feb 23, 2024
1 parent 9ca7490 commit 929295d
Show file tree
Hide file tree
Showing 12 changed files with 1,767 additions and 260 deletions.
1,725 changes: 1,634 additions & 91 deletions package-lock.json

Large diffs are not rendered by default.

14 changes: 1 addition & 13 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,7 @@
"@tauri-apps/api": "^2.0.0-beta.0",
"@tauri-apps/plugin-dialog": "^2.0.0-beta.0",
"@tauri-apps/plugin-fs": "^2.0.0-beta.0",
"@turf/area": "^6.5.0",
"@turf/boolean-contains": "^6.5.0",
"@turf/boolean-point-in-polygon": "^6.5.0",
"@turf/buffer": "^6.5.0",
"@turf/center-of-mass": "^6.5.0",
"@turf/circle": "^6.5.0",
"@turf/convex": "^6.5.0",
"@turf/difference": "^6.5.0",
"@turf/explode": "^6.5.0",
"@turf/helpers": "^6.5.0",
"@turf/intersect": "^6.5.0",
"@turf/meta": "^6.5.0",
"@turf/union": "^6.5.0",
"@turf/turf": "^6.5.0",
"@zip.js/zip.js": "^2.7.32",
"d3-color": "^3.1.0",
"d3-delaunay": "^6.0.4",
Expand Down
8 changes: 0 additions & 8 deletions src/customTypings/@turf/helpers.d.ts

This file was deleted.

10 changes: 10 additions & 0 deletions src/customTypings/@turf/turf.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import '@turf/turf';

declare module '@turf/turf' {
export interface Position extends Array<number> {
0: number;
1: number;
}

export function coordAll(geojson: AllGeoJSON): Position[];
}
5 changes: 5 additions & 0 deletions src/customTypings/d3-path.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import 'd3-path';

declare module 'd3-path' {
export function pathRound(digits: number): Path;
}
60 changes: 24 additions & 36 deletions src/renderer/src/lib/map/data/processBorders.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import booleanPointInPolygon from '@turf/boolean-point-in-polygon';
import buffer from '@turf/buffer';
import difference from '@turf/difference';
import explode from '@turf/explode';
import * as helpers from '@turf/helpers';
import { coordAll } from '@turf/meta';
import union from '@turf/union';
import * as turf from '@turf/turf';
import type { GameState, Sector } from '../../GameState';
import type { MapSettings } from '../../mapSettings';
import { getOrDefault, isDefined, parseNumberEntry } from '../../utils';
Expand Down Expand Up @@ -50,7 +44,7 @@ export default function processBorders(
>['galaxyBorderCirclesGeoJSON'],
getSystemCoordinates: (id: number, options?: { invertX?: boolean }) => [number, number],
) {
const unassignedFragments: [number, helpers.Feature<helpers.Polygon>][] = [];
const unassignedFragments: [number, turf.Feature<turf.Polygon>][] = [];
const borders = Object.entries(unionLeaderToGeojson)
.map(parseNumberEntry)
.map(([countryId, outerBorderGeoJSON]) => {
Expand Down Expand Up @@ -86,21 +80,21 @@ export default function processBorders(
.filter(isDefined);

const unionMemberBorderLines: Set<string> = new Set();
getAllPositionArrays(helpers.featureCollection(unionMemberOuterPolygons)).forEach(
getAllPositionArrays(turf.featureCollection(unionMemberOuterPolygons)).forEach(
(positionArray) =>
positionArray.forEach((p, i) => {
const nextPosition = positionArray[(i + 1) % positionArray.length] as helpers.Position;
const nextPosition = positionArray[(i + 1) % positionArray.length] as turf.Position;
unionMemberBorderLines.add(
[positionToString(p), positionToString(nextPosition)].sort().join(','),
);
}),
);

const allBorderPoints: Set<string> = new Set(
explode(outerBorderGeoJSON).features.map((f) => positionToString(f.geometry.coordinates)),
turf.coordAll(outerBorderGeoJSON).map((coord) => positionToString(coord)),
);
const sectorOuterPoints: Set<string>[] = sectorOuterPolygons.map(
(p) => new Set(explode(p).features.map((f) => positionToString(f.geometry.coordinates))),
(p) => new Set(turf.coordAll(p).map((coord) => positionToString(coord))),
);
// include all border lines in this, so we don't draw sectors border where there is already an external border
const addedSectorLines: Set<string> = new Set(
Expand All @@ -110,15 +104,15 @@ export default function processBorders(
const isLastPos = i === positionArray.length - 1;
const nextPosition = positionArray[
(i + (isLastPos ? 2 : 1)) % positionArray.length
] as helpers.Position;
] as turf.Position;
return [positionToString(p), positionToString(nextPosition)].sort().join(',');
}),
)
.flat(),
);
const sectorSegments: helpers.Position[][] = [];
const sectorSegments: turf.Position[][] = [];
sectorOuterPolygons.flatMap(getAllPositionArrays).forEach((sectorRing, sectorIndex) => {
let currentSegment: helpers.Position[] = [];
let currentSegment: turf.Position[] = [];
const firstSegment = currentSegment;
sectorRing.forEach((pos, posIndex, posArray) => {
const posString = positionToString(pos);
Expand All @@ -132,7 +126,7 @@ export default function processBorders(
);

const nextPosIndex = (posIndex + (posIsLast ? 2 : 1)) % posArray.length;
const nextPos = posArray[nextPosIndex] as helpers.Position;
const nextPos = posArray[nextPosIndex] as turf.Position;
const nextPosString = positionToString(nextPos);

const nextLineString = [posString, nextPosString].sort().join(',');
Expand Down Expand Up @@ -189,7 +183,7 @@ export default function processBorders(
});
// make sure there are no 0 or 1 length segments
const nonEmptySectorSegments = sectorSegments.filter(
(segment): segment is [helpers.Position, helpers.Position, ...helpers.Position[]] =>
(segment): segment is [turf.Position, turf.Position, ...turf.Position[]] =>
segment.length > 1,
);
// check for union border segments
Expand All @@ -205,11 +199,9 @@ export default function processBorders(
if (allBorderPoints.has(positionToString(segment[0]))) {
segment[0] = getSmoothedPosition(segment[0], outerBorderGeoJSON);
}
if (
allBorderPoints.has(positionToString(segment[segment.length - 1] as helpers.Position))
) {
if (allBorderPoints.has(positionToString(segment[segment.length - 1] as turf.Position))) {
segment[segment.length - 1] = getSmoothedPosition(
segment[segment.length - 1] as helpers.Position,
segment[segment.length - 1] as turf.Position,
outerBorderGeoJSON,
);
}
Expand All @@ -222,13 +214,13 @@ export default function processBorders(
);

if (galaxyBorderCirclesGeoJSON) {
const fragments: helpers.Feature<helpers.Polygon>[] = [];
const fragments: turf.Feature<turf.Polygon>[] = [];
for (const polygon of getPolygons(boundedOuterBorderGeoJSON)) {
const systems = new Set(
Array.from(unionLeaderToSystemIds[countryId] ?? []).filter((systemId) => {
const coordinate = getSystemCoordinates(systemId);
const point = helpers.point(pointToGeoJSON(coordinate));
return booleanPointInPolygon(point, polygon);
const point = turf.point(pointToGeoJSON(coordinate));
return turf.booleanPointInPolygon(point, polygon);
}),
);
if (systems.size === 0) {
Expand All @@ -251,9 +243,9 @@ export default function processBorders(
const geojson = makeBorderCircleGeojson(gameState, getSystemCoordinates, cur);
if (acc == null) return geojson;
if (geojson == null) return acc;
return union(acc, geojson);
return turf.union(acc, geojson);
}, null);
const outOfBounds = bounds == null ? null : difference(polygon, bounds);
const outOfBounds = bounds == null ? null : turf.difference(polygon, bounds);
fragments.push(...getPolygons(outOfBounds));
unassignedFragments.push(
...getPolygons(outOfBounds).map<(typeof unassignedFragments)[number]>((geojson) => [
Expand All @@ -268,7 +260,7 @@ export default function processBorders(
boundedOuterBorderGeoJSON =
boundedOuterBorderGeoJSON == null
? null
: difference(boundedOuterBorderGeoJSON, fragment);
: turf.difference(boundedOuterBorderGeoJSON, fragment);
}
}

Expand Down Expand Up @@ -308,11 +300,7 @@ export default function processBorders(
const unionLeaderToPositionStrings: Record<number, Set<string>> = Object.fromEntries(
borders.map((border) => [
border.countryId,
new Set(
border.geojson == null
? []
: (coordAll(border.geojson) as [number, number][]).map(positionToString),
),
new Set(border.geojson == null ? [] : turf.coordAll(border.geojson).map(positionToString)),
]),
);

Expand All @@ -336,7 +324,7 @@ export default function processBorders(
unionLeaderId == null ? null : borders.find((b) => b.countryId === unionLeaderId);
const geojson = border == null ? null : border.geojson;
if (border && geojson) {
border.geojson = union(geojson, fragment);
border.geojson = turf.union(geojson, fragment);
}
}

Expand All @@ -349,9 +337,9 @@ export default function processBorders(
const smoothedInnerBorderGeoJSON =
smoothedOuterBorderGeoJSON == null
? null
: (buffer(smoothedOuterBorderGeoJSON, -settings.borderStroke.width / SCALE, {
: (turf.buffer(smoothedOuterBorderGeoJSON, -settings.borderStroke.width / SCALE, {
units: 'degrees',
}) as ReturnType<typeof buffer> | null);
}) as ReturnType<typeof turf.buffer> | null);
border.outerPath =
smoothedOuterBorderGeoJSON == null
? ''
Expand All @@ -363,7 +351,7 @@ export default function processBorders(
const borderOnlyGeoJSON =
smoothedInnerBorderGeoJSON == null || smoothedOuterBorderGeoJSON == null
? smoothedOuterBorderGeoJSON
: difference(smoothedOuterBorderGeoJSON, smoothedInnerBorderGeoJSON);
: turf.difference(smoothedOuterBorderGeoJSON, smoothedInnerBorderGeoJSON);
border.borderPath = borderOnlyGeoJSON
? multiPolygonToPath(borderOnlyGeoJSON, settings.borderStroke.smoothing)
: '';
Expand Down
28 changes: 11 additions & 17 deletions src/renderer/src/lib/map/data/processCircularGalaxyBorder.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import centerOfMass from '@turf/center-of-mass';
import convex from '@turf/convex';
import difference from '@turf/difference';
import * as helpers from '@turf/helpers';
import union from '@turf/union';
import * as turf from '@turf/turf';
import { interpolateBasis } from 'd3-interpolate';
import type { GameState } from '../../GameState';
import type { MapSettings } from '../../mapSettings';
Expand Down Expand Up @@ -41,7 +37,7 @@ export default function processCircularGalaxyBorders(
systems: Set<number>;
outliers: Set<number>;
bBox: { xMin: number; xMax: number; yMin: number; yMax: number };
points: helpers.FeatureCollection<helpers.Point>;
points: turf.FeatureCollection<turf.Point>;
}[] = [];

for (const go of Object.values(gameState.galactic_object)) {
Expand All @@ -55,9 +51,7 @@ export default function processCircularGalaxyBorders(
yMin: getSystemCoordinates(go.id)[1],
yMax: getSystemCoordinates(go.id)[1],
},
points: helpers.featureCollection([
helpers.point(pointToGeoJSON(getSystemCoordinates(go.id))),
]),
points: turf.featureCollection([turf.point(pointToGeoJSON(getSystemCoordinates(go.id)))]),
};
const edge = go.hyperlane.map((hyperlane) => hyperlane.to);
const edgeSet = new Set(edge);
Expand All @@ -68,7 +62,7 @@ export default function processCircularGalaxyBorders(
const next = gameState.galactic_object[nextId];
if (next != null && !cluster.systems.has(nextId)) {
cluster.systems.add(nextId);
cluster.points.features.push(helpers.point(pointToGeoJSON(getSystemCoordinates(nextId))));
cluster.points.features.push(turf.point(pointToGeoJSON(getSystemCoordinates(nextId))));
const nextHyperlanes = next.hyperlane;
const isOutlier = nextHyperlanes[0] != null && nextHyperlanes[0].length > OUTLIER_DISTANCE;
if (isOutlier) {
Expand Down Expand Up @@ -143,7 +137,7 @@ export default function processCircularGalaxyBorders(
// don't cut out inner shape if the core is too small (eg has gigastructures core)
if (innerRadii.every((r) => r > CIRCLE_INNER_PADDING)) {
const interpolateInnerRadii = interpolateBasis(innerRadii);
starburstGeoJSON = difference(
starburstGeoJSON = turf.difference(
starburstGeoJSON,
makeStarburstPolygon(innerStartAngle, interpolateInnerRadii, -CIRCLE_INNER_PADDING),
);
Expand All @@ -159,9 +153,9 @@ export default function processCircularGalaxyBorders(
cx = 0;
cy = 0;
} else {
const hull = convex(cluster.points);
const hull = turf.convex(cluster.points);
if (hull) {
const hullCenter = centerOfMass(hull);
const hullCenter = turf.centerOfMass(hull);
const point = pointFromGeoJSON(hullCenter.geometry.coordinates);
cx = point[0];
cy = point[1];
Expand Down Expand Up @@ -245,11 +239,11 @@ export default function processCircularGalaxyBorders(
if (galaxyBorderCirclesGeoJSON == null) {
galaxyBorderCirclesGeoJSON = polygon;
} else {
galaxyBorderCirclesGeoJSON = union(galaxyBorderCirclesGeoJSON, polygon);
galaxyBorderCirclesGeoJSON = turf.union(galaxyBorderCirclesGeoJSON, polygon);
}
} else if (circle.type === 'inner-padded') {
if (galaxyBorderCirclesGeoJSON != null) {
galaxyBorderCirclesGeoJSON = difference(galaxyBorderCirclesGeoJSON, polygon);
galaxyBorderCirclesGeoJSON = turf.difference(galaxyBorderCirclesGeoJSON, polygon);
}
}
}
Expand Down Expand Up @@ -334,7 +328,7 @@ function makeStarburstPolygon(
interpolateRadii: (n: number) => number,
padding: number,
): PolygonalFeature {
const positions: helpers.Position[] = [];
const positions: turf.Position[] = [];
for (let i = 0; i < STARBURST_NUM_SLICES; i++) {
const sliceIndex = i;
const fromAngle = startAngle + STARBURST_SLICE_ANGLE * sliceIndex;
Expand All @@ -352,5 +346,5 @@ function makeStarburstPolygon(
if (positions[0]) {
positions.push(positions[0]);
}
return helpers.polygon([positions]);
return turf.polygon([positions]);
}
Loading

0 comments on commit 929295d

Please sign in to comment.