advent22/ui/src/components/rects/rectangles.ts

98 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-01-17 00:51:52 +00:00
export class Vector2D {
private _x: number;
private _y: number;
constructor(x = 0, y = 0) {
this._x = x;
this._y = y;
}
public get x(): number {
return this._x;
}
public get y(): number {
return this._y;
}
public plus(other: Vector2D): Vector2D {
return new Vector2D(this._x + other._x, this._y + other._y);
}
public minus(other: Vector2D): Vector2D {
return new Vector2D(this._x - other._x, this._y - other._y);
}
}
export class Rectangle {
private _corner_1: Vector2D;
private _corner_2: Vector2D;
constructor(corner_1: Vector2D, corner_2: Vector2D) {
this._corner_1 = corner_1;
this._corner_2 = corner_2;
}
public get origin(): Vector2D {
return this._corner_1;
}
public get left(): number {
return this.origin.x;
}
public get top(): number {
return this.origin.y;
}
2023-01-17 23:34:42 +00:00
public get corner(): Vector2D {
return this._corner_2;
}
2023-01-17 00:51:52 +00:00
public get size(): Vector2D {
return this._corner_2.minus(this._corner_1);
}
public get width(): number {
return this.size.x;
}
public get height(): number {
return this.size.y;
}
2023-01-17 14:26:39 +00:00
public get area(): number {
return this.width * this.height;
}
2023-01-17 23:50:25 +00:00
public contains(point: Vector2D): boolean {
const test_rect = this.normalize();
return point.x >= test_rect._corner_1.x &&
point.y >= test_rect._corner_1.y &&
point.x <= test_rect._corner_2.x &&
point.y <= test_rect._corner_2.y
}
2023-01-17 00:51:52 +00:00
public normalize(): Rectangle {
let left = this.left;
let top = this.top;
let width = this.width;
let height = this.height;
if (width < 0) {
width *= -1;
left -= width;
}
if (height < 0) {
height *= -1;
top -= height;
}
const corner_tl = new Vector2D(left, top);
const size = new Vector2D(width, height);
return new Rectangle(corner_tl, corner_tl.plus(size));
}
}