homemanager-fe/src/modules/house-planner/canvas.ts

502 lines
13 KiB
TypeScript
Raw Normal View History

2023-01-18 18:47:22 +00:00
import { clamp } from '@vueuse/core';
2023-01-19 15:07:57 +00:00
import extractLinePoints from '../../utils/extract-line-points';
2023-01-16 19:37:39 +00:00
import { HousePlannerCanvasGrid } from './grid';
2023-01-17 18:32:15 +00:00
import {
BezierSegment,
2023-01-18 21:20:06 +00:00
ICanvasToolkit,
2023-01-17 18:32:15 +00:00
Layer,
LayerObject,
Line,
LineSegment,
2023-01-18 18:11:54 +00:00
RepositionEvent,
2023-01-17 18:32:15 +00:00
Vec2,
} from './interfaces';
2023-01-16 19:37:39 +00:00
import { HousePlannerCanvasTools } from './tools';
2023-01-19 15:07:57 +00:00
import { LayerObjectType } from './types';
2023-01-16 19:37:39 +00:00
import {
vec2Add,
vec2AngleFromOrigin,
vec2Distance,
vec2DivideScalar,
2023-01-18 21:20:06 +00:00
vec2Equals,
2023-01-18 18:11:54 +00:00
vec2MultiplyScalar,
2023-01-18 18:47:22 +00:00
vec2Snap,
2023-01-18 18:11:54 +00:00
vec2Sub,
2023-01-16 19:37:39 +00:00
} from './utils';
export class HousePlannerCanvas {
public ctx!: CanvasRenderingContext2D;
public layers: Layer[] = [];
2023-01-18 21:20:06 +00:00
public tools?: ICanvasToolkit;
2023-01-16 19:37:39 +00:00
public grid = new HousePlannerCanvasGrid(this, 8);
2023-01-18 18:47:22 +00:00
public mousePosition: Vec2 = [0, 0];
public mouseClickPosition: Vec2 = [0, 0];
public mousePositionSnapped: Vec2 = [0, 0];
private dragging = false;
private pinching = false;
private lastPinchLength = 0;
private moved = false;
private clickedOn: LayerObject | null = null;
2023-01-16 19:37:39 +00:00
2023-01-18 18:11:54 +00:00
constructor(
public canvas: HTMLCanvasElement,
public canvasDim: Vec2,
2023-01-18 18:47:22 +00:00
public canvasPos: Vec2,
public canvasZoom = 1,
public editable = true
2023-01-18 18:11:54 +00:00
) {
2023-01-16 19:37:39 +00:00
this.ctx = this.canvas.getContext('2d')!;
this.setupEvents();
2023-01-18 18:11:54 +00:00
this.resizeCanvas();
2023-01-18 18:47:22 +00:00
if (editable) {
this.tools = new HousePlannerCanvasTools(this);
}
2023-01-16 19:37:39 +00:00
}
get width() {
return this.canvas.width;
}
get height() {
return this.canvas.height;
}
addLayer(layer: Layer) {
this.layers.push(layer);
this.draw();
}
2023-01-18 18:11:54 +00:00
resizeCanvas() {
const [w, h] = this.canvasDim;
this.canvas.width = w;
this.canvas.height = h;
this.draw();
}
2023-01-16 19:37:39 +00:00
cleanUp() {
2023-01-18 18:47:22 +00:00
this.tools?.cleanUp();
2023-01-16 19:37:39 +00:00
window.removeEventListener('keyup', this.boundKeyUpEvent);
window.removeEventListener('keydown', this.boundKeyDownEvent);
}
draw() {
this.ctx.clearRect(0, 0, this.width, this.height);
this.grid.draw();
2023-01-18 18:47:22 +00:00
this.tools?.drawHighlights();
for (const layer of this.layers.slice().reverse()) {
2023-01-16 19:37:39 +00:00
if (!layer.visible) continue;
if (!layer.contents?.length) continue;
this.drawLayer(layer);
}
2023-01-18 18:47:22 +00:00
this.tools?.drawControls();
2023-01-16 19:37:39 +00:00
}
makeBezier(segment: BezierSegment, path: Path2D) {
const bezier = segment as BezierSegment;
const [cp1x, cp1y] = bezier.startControl;
const [cp2x, cp2y] = bezier.endControl;
const [x, y] = bezier.end;
path.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
}
makeLinePath(line: Line) {
const path = new Path2D();
const [firstSegment, ...segments] = line.segments;
// first segment must have a starting point
if (!firstSegment.start) return path;
path.moveTo(...firstSegment.start);
if (line.type === 'curve') {
const lineLength = vec2Distance(firstSegment.start, firstSegment.end);
const lineAngle = vec2AngleFromOrigin(
firstSegment.end,
firstSegment.start!
);
const ninety = lineAngle + Math.PI / 2;
path.moveTo(...firstSegment.end);
path.arc(
firstSegment.start[0],
firstSegment.start[1],
lineLength,
lineAngle,
ninety
);
path.lineTo(...firstSegment.start);
} else if ((firstSegment as BezierSegment).startControl) {
this.makeBezier(firstSegment as BezierSegment, path);
} else {
path.lineTo(...firstSegment.end);
}
for (const segment of segments) {
2023-01-18 19:15:51 +00:00
if (segment.start) {
path.moveTo(...segment.start);
}
2023-01-16 19:37:39 +00:00
if ((segment as BezierSegment).startControl) {
this.makeBezier(segment as BezierSegment, path);
continue;
}
path.lineTo(...segment.end);
}
if (line.closed && line.type !== 'curve') {
path.closePath();
}
return path;
}
setupLine(line: Line, overBounds = 0, overrideColor?: string) {
if (line.lineDash) {
this.ctx.setLineDash(line.lineDash);
}
this.ctx.strokeStyle = overrideColor || line.color || '#000';
this.ctx.lineWidth = line.width + overBounds;
2023-01-18 17:00:51 +00:00
this.ctx.lineCap = line.lineCap || 'butt';
this.ctx.lineJoin = line.lineJoin || 'miter';
2023-01-16 19:37:39 +00:00
}
isOnLine(line: Line, x: number, y: number, selectError = 16) {
let path = line.render || this.makeLinePath(line);
this.setupLine(line, selectError);
return this.ctx.isPointInStroke(path, x, y);
}
isOnSegment(
line: Line,
segment: LineSegment,
lastPoint: Vec2,
x: number,
y: number,
selectError = 16
) {
const fakePath = this.makeLinePath({
...line,
closed: false,
segments: [{ ...segment, start: lastPoint }],
});
this.setupLine(line, selectError);
return this.ctx.isPointInStroke(fakePath, x, y);
}
2023-01-17 18:32:15 +00:00
getLayerById(layerId: number) {
return this.layers.find((layer) => layer.id === layerId);
}
getLayerObjectById(layerId: number, objectId: number) {
const findLayer = this.getLayerById(layerId);
if (!findLayer) return undefined;
const findObject = findLayer.contents.find(
(content) => content.id === objectId
);
if (!findObject) return undefined;
return findObject;
}
updateObjectProperties(
layerId: number,
objectId: number,
properties: Partial<Omit<LayerObject | Line, 'segments'>>
) {
const object = this.getLayerObjectById(layerId, objectId);
if (!object) return;
2023-01-18 18:47:22 +00:00
this.tools?.history.appendToHistory(
2023-01-17 18:32:15 +00:00
Object.keys(properties).map((key) => ({
object,
property: key,
value: object[key as keyof typeof object],
}))
);
Object.assign(object, properties);
this.canvas.dispatchEvent(
new CustomEvent('hpc:update', {
detail: { event: 'properties-object', object },
})
);
this.draw();
return object;
}
updateLayerProperties(
layerId: number,
properties: Partial<Omit<Layer, 'contents'>>
) {
const layer = this.getLayerById(layerId);
if (!layer) return;
2023-01-18 18:47:22 +00:00
this.tools?.history.appendToHistory(
2023-01-17 18:32:15 +00:00
Object.keys(properties).map((key) => ({
object: layer,
property: key,
value: layer[key as keyof typeof layer],
}))
);
Object.assign(layer, properties);
this.canvas.dispatchEvent(
new CustomEvent('hpc:update', {
detail: { event: 'properties-layer', layer },
})
);
this.draw();
return layer;
}
2023-01-18 18:11:54 +00:00
translateCanvas(offset: Vec2) {
const realSize = vec2MultiplyScalar(this.canvasDim, this.canvasZoom);
2023-01-18 18:47:22 +00:00
this.canvasPos = vec2Sub(this.canvasPos, offset);
2023-01-18 18:11:54 +00:00
this.repositionEvent();
}
zoomCanvas(diff: number) {
this.canvasZoom -= diff;
this.repositionEvent();
}
2023-01-18 18:47:22 +00:00
realMousePos(x: number, y: number) {
const rect = this.canvas.getBoundingClientRect();
const scaleX = this.canvas.width / rect.width;
const scaleY = this.canvas.height / rect.height;
this.mousePosition = [(x - rect.left) * scaleX, (y - rect.top) * scaleY];
this.mousePositionSnapped = !!this.grid.gridSnap
? vec2Snap(this.mousePosition, this.grid.gridSnap)
: this.mousePosition;
}
2023-01-19 15:07:57 +00:00
getAllObjectsOfType(type: LayerObjectType) {
const objects: LayerObject[] = [];
this.layers.forEach((layer) => {
objects.push(...layer.contents.filter((object) => object.type === type));
});
return objects;
}
2023-01-16 19:37:39 +00:00
private keyDownEvent(e: KeyboardEvent) {
if (e.target !== document.body && e.target != null) return;
2023-01-18 18:47:22 +00:00
this.tools?.onKeyDown(e);
2023-01-16 19:37:39 +00:00
}
private boundKeyDownEvent = this.keyDownEvent.bind(this);
private keyUpEvent(e: KeyboardEvent) {
if (e.target !== document.body && e.target != null) return;
2023-01-18 18:47:22 +00:00
this.tools?.onKeyUp(e);
2023-01-16 19:37:39 +00:00
}
private boundKeyUpEvent = this.keyUpEvent.bind(this);
private setupEvents() {
window.addEventListener('keyup', this.boundKeyUpEvent);
window.addEventListener('keydown', this.boundKeyDownEvent);
2023-01-18 18:47:22 +00:00
this.canvas.addEventListener('mousemove', (e) => this.onMouseMove(e));
this.canvas.addEventListener('mousedown', (e) => this.onMouseDown(e));
this.canvas.addEventListener('mouseup', (e) => this.onMouseUp(e));
2023-01-16 19:37:39 +00:00
2023-01-18 18:47:22 +00:00
this.canvas.addEventListener('touchmove', (e) => this.onTouchMove(e));
this.canvas.addEventListener('touchstart', (e) => this.onTouchStart(e));
this.canvas.addEventListener('touchend', (e) => this.onTouchEnd(e));
this.canvas.addEventListener('wheel', (e) => this.onMouseWheel(e));
2023-01-16 19:37:39 +00:00
2023-01-18 18:47:22 +00:00
this.canvas.addEventListener('pointerleave', () => this.onPointerLeave());
2023-01-16 19:37:39 +00:00
}
private drawRoomText(line: Line) {
2023-01-19 15:07:57 +00:00
const points = extractLinePoints(line);
2023-01-16 19:37:39 +00:00
const centerPoint = vec2DivideScalar(
2023-01-18 21:20:06 +00:00
points.reduce<Vec2 | null>(
(prev, current) => (prev ? vec2Add(prev, current) : current),
null
) as Vec2,
points.length
2023-01-16 19:37:39 +00:00
);
2023-01-18 21:20:06 +00:00
2023-01-16 19:37:39 +00:00
this.ctx.font = '16px Arial';
this.ctx.fillStyle = line.color;
const { width } = this.ctx.measureText(line.name);
this.ctx.fillText(
line.name,
centerPoint[0] - width / 2,
centerPoint[1] - 8
);
}
private drawLine(line: Line) {
const path = this.makeLinePath(line);
line.render = path;
this.setupLine(line);
this.ctx.stroke(path);
if (line.type === 'room') {
this.drawRoomText(line);
}
}
private drawLayer(layer: Layer) {
for (const item of layer.contents) {
if (!item.visible) continue;
const line = item as Line;
if (line.segments) {
this.drawLine(line);
continue;
}
}
}
2023-01-18 18:11:54 +00:00
2023-01-18 18:47:22 +00:00
onMouseMove(e: MouseEvent) {
this.dragEvent(e.clientX, e.clientY);
}
onMouseDown(e: MouseEvent) {
this.mouseClickPosition = [e.clientX, e.clientY];
this.moved = false;
this.pointerDown();
}
onMouseUp(e: MouseEvent) {
this.dragging = false;
this.pointerUp();
}
onTouchMove(ev: TouchEvent) {
ev.preventDefault();
if (ev.touches.length === 2 && this.pinching) {
const pinchLength = Math.hypot(
ev.touches[0].pageX - ev.touches[1].pageX,
ev.touches[0].pageY - ev.touches[1].pageY
);
if (this.lastPinchLength) {
const delta = pinchLength / this.lastPinchLength;
const scaleX =
(ev.touches[0].clientX - this.canvasPos[0]) / this.canvasZoom;
const scaleY =
(ev.touches[0].clientY - this.canvasPos[1]) / this.canvasZoom;
delta > 0 ? (this.canvasZoom *= delta) : (this.canvasZoom /= delta);
this.canvasZoom = clamp(this.canvasZoom, 1, 100);
this.canvasPos = [
ev.touches[0].clientX - scaleX * this.canvasZoom,
ev.touches[0].clientY - scaleY * this.canvasZoom,
];
this.repositionEvent();
}
this.lastPinchLength = pinchLength;
}
this.dragEvent(ev.touches[0].clientX, ev.touches[0].clientY);
}
onTouchStart(e: TouchEvent) {
e.preventDefault();
const touch = e.touches[0] || e.changedTouches[0];
this.dragging = true;
this.moved = false;
if (e.touches.length === 2) {
this.pinching = true;
}
this.pointerDown();
}
onTouchEnd(e: TouchEvent) {
this.pinching = false;
this.lastPinchLength = 0;
if (!e.touches?.length) {
this.dragging = false;
}
this.pointerUp();
}
onPointerLeave() {
this.dragging = false;
}
private onMouseWheel(e: WheelEvent) {
e.preventDefault();
this.realMousePos(e.clientX, e.clientY);
const scaleX = (e.clientX - this.canvasPos[0]) / this.canvasZoom;
const scaleY = (e.clientY - this.canvasPos[1]) / this.canvasZoom;
e.deltaY < 0 ? (this.canvasZoom *= 1.2) : (this.canvasZoom /= 1.2);
this.canvasZoom = clamp(this.canvasZoom, 0.1, 10);
this.canvasPos = [
e.clientX - scaleX * this.canvasZoom,
e.clientY - scaleY * this.canvasZoom,
];
// this.canvasPos = [
// clamp(this.canvasPos[0], -window.innerWidth / 2, window.innerWidth / 2),
// clamp(this.canvasPos[1], -window.innerHeight / 2, window.innerHeight / 2),
// ];
this.repositionEvent();
}
private dragEvent(x: number, y: number) {
this.moved = true;
const currentPosAbsolute: Vec2 = [...this.mousePosition];
const currentPosSnapped: Vec2 = [
...(!!this.grid.gridSnap
? this.mousePositionSnapped
: this.mousePosition),
];
this.realMousePos(x, y);
let offset = vec2Sub(currentPosSnapped, this.mousePositionSnapped);
let offsetAbsolute = vec2Sub(currentPosAbsolute, this.mousePosition);
this.tools?.mouseMoved(
this.mousePositionSnapped,
offset,
this.mousePosition
);
if (this.dragging) {
const divided = vec2MultiplyScalar(offsetAbsolute, this.canvasZoom);
this.translateCanvas(divided);
// Bias the offset
const [nx, ny] = vec2Add([x, y], divided);
this.realMousePos(nx, ny);
}
}
private pointerDown() {
2023-01-19 15:07:57 +00:00
if (!this.tools) {
this.dragging = true;
return;
}
2023-01-18 18:47:22 +00:00
this.clickedOn = this.tools.getMousedObject();
this.tools.mouseDown(this.clickedOn || undefined);
2023-01-19 15:07:57 +00:00
2023-01-18 18:47:22 +00:00
if (!this.clickedOn) {
this.dragging = true;
}
}
private pointerUp() {
// FIXME: possibly there's a better approach, but right now some clicks do not register
if (
this.moved &&
vec2Distance(this.mouseClickPosition, this.mousePosition) < 0.25
) {
this.moved = false;
}
this.tools?.mouseUp(this.moved);
this.dragging = false;
this.clickedOn = null;
}
2023-01-18 18:11:54 +00:00
private repositionEvent() {
this.canvas.dispatchEvent(
new CustomEvent<RepositionEvent>('hpc:position', {
detail: {
2023-01-18 18:47:22 +00:00
position: this.canvasPos,
2023-01-18 18:11:54 +00:00
zoom: this.canvasZoom,
},
})
);
}
2023-01-16 19:37:39 +00:00
}