Skip to content

Commit

Permalink
refactor(geom): update centroid() for complexpoly
Browse files Browse the repository at this point in the history
- re-use migrated fn from thi.ng/geom-poly-utils
  • Loading branch information
postspectacular committed May 6, 2024
1 parent 9b38f31 commit 58ac296
Showing 1 changed file with 11 additions and 27 deletions.
38 changes: 11 additions & 27 deletions packages/geom/src/centroid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";

Expand Down Expand Up @@ -75,28 +75,12 @@ export const centroid: MultiFn1O<IShape, Vec, Maybe<Vec>> = 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($);
Expand Down

0 comments on commit 58ac296

Please sign in to comment.