Skip to content

Commit

Permalink
feat(geom): add inscribedSquare*() fns
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Apr 10, 2019
1 parent a9ba010 commit b1790b3
Showing 1 changed file with 52 additions and 2 deletions.
54 changes: 52 additions & 2 deletions packages/geom/src/ctors/rect.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { Attribs } from "@thi.ng/geom-api";
import { sub2, Vec } from "@thi.ng/vectors";
import { Rect } from "../api";
import { centroid } from "@thi.ng/geom-poly-utils";
import { SQRT2_2, SQRT3 } from "@thi.ng/math";
import {
dist,
ReadonlyVec,
sub2,
subN2,
Vec
} from "@thi.ng/vectors";
import { Circle, Polygon, Rect } from "../api";
import { argsVV } from "../internal/args";

export function rect(pos: Vec, size: number | Vec, attribs?: Attribs): Rect;
Expand All @@ -12,3 +20,45 @@ export function rect(...args: any[]) {

export const rectFromMinMax = (min: Vec, max: Vec, attribs?: Attribs) =>
new Rect(min, sub2([], max, min), attribs);

/**
* Returns square inscribed in given circle instance. The circle can also be
* given as centroid & radius.
*
* @param circle
*/
export function inscribedSquare(circle: Circle): Rect;
export function inscribedSquare(pos: ReadonlyVec, r: number): Rect;
export function inscribedSquare(...args: any[]) {
let pos: ReadonlyVec, r: number;
if (args.length === 1) {
const c: Circle = args[0];
pos = c.pos;
r = c.r;
} else {
[pos, r] = args;
}
r *= SQRT2_2;
return rect(subN2([], pos, r), r * 2);
}

/**
* Returns square inscribed in given (unrotated) hexagon. The hexagon
* can be given as `Polygon` or centroid and edge length.
*
* @param hex
*/
export function inscribedSquareHex(hex: Polygon): Rect;
export function inscribedSquareHex(pos: ReadonlyVec, len: number): Rect;
export function inscribedSquareHex(...args: any[]) {
let pos: ReadonlyVec, l: number;
if (args.length === 1) {
const pts = (<Polygon>args[0]).points;
pos = centroid(pts);
l = dist(pts[0], pts[1]);
} else {
[pos, l] = args;
}
l *= 3 - SQRT3;
return rect(subN2([], pos, l / 2), l);
}

0 comments on commit b1790b3

Please sign in to comment.