From 58ac2965b078f10badf50081cc16409304d04899 Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Mon, 6 May 2024 21:29:52 +0200 Subject: [PATCH] refactor(geom): update centroid() for complexpoly - re-use migrated fn from thi.ng/geom-poly-utils --- packages/geom/src/centroid.ts | 38 ++++++++++------------------------- 1 file changed, 11 insertions(+), 27 deletions(-) diff --git a/packages/geom/src/centroid.ts b/packages/geom/src/centroid.ts index b7e780234b..f23e4b0edf 100644 --- a/packages/geom/src/centroid.ts +++ b/packages/geom/src/centroid.ts @@ -2,15 +2,16 @@ import type { Maybe } from "@thi.ng/api"; import type { MultiFn1O } from "@thi.ng/defmulti"; import { defmulti } from "@thi.ng/defmulti/defmulti"; import type { AABBLike, IShape, PCLike } from "@thi.ng/geom-api"; -import { centerOfWeight2 } from "@thi.ng/geom-poly-utils/center-of-weight"; +import { + centerOfWeight2, + complexCenterOfWeight2, +} from "@thi.ng/geom-poly-utils/center-of-weight"; import { centroid as _centroid } from "@thi.ng/geom-poly-utils/centroid"; import type { Vec } from "@thi.ng/vectors"; import { add } from "@thi.ng/vectors/add"; import { addmN } from "@thi.ng/vectors/addmn"; -import { divN2 } from "@thi.ng/vectors/divn"; -import { maddN, maddN2 } from "@thi.ng/vectors/maddn"; +import { maddN } from "@thi.ng/vectors/maddn"; import { mixN } from "@thi.ng/vectors/mixn"; -import { msubN2 } from "@thi.ng/vectors/msubn"; import { mulN } from "@thi.ng/vectors/muln"; import { set } from "@thi.ng/vectors/set"; import type { Circle } from "./api/circle.js"; @@ -20,7 +21,6 @@ import type { Line } from "./api/line.js"; import type { Plane } from "./api/plane.js"; import type { Polygon } from "./api/polygon.js"; import type { Triangle } from "./api/triangle.js"; -import { area } from "./area.js"; import { bounds } from "./bounds.js"; import { __dispatch } from "./internal/dispatch.js"; @@ -75,28 +75,12 @@ export const centroid: MultiFn1O> = defmulti< { circle: ($: Circle, out?) => set(out || [], $.pos), - // https://math.stackexchange.com/a/623849 - // ((Aout * Cout) - (Ain * Cin)) / (Aout - Ain) - complexpoly: ($: ComplexPolygon, out?) => { - const outerArea = Math.abs(area($.boundary)); - let innerArea = 0; - let innerCentroid = [0, 0]; - for (let child of $.children) { - const a = Math.abs(area(child)); - innerArea += a; - maddN2(innerCentroid, centroid(child)!, a, innerCentroid); - } - return divN2( - null, - msubN2( - out || [], - centroid($.boundary)!, - outerArea, - innerCentroid - ), - outerArea - innerArea - ); - }, + complexpoly: ($: ComplexPolygon, out?) => + complexCenterOfWeight2( + $.boundary.points, + $.children.map((c) => c.points), + out + ), group: ($: Group, out?) => { const b = bounds($);