UNPKG

gojs

Version:

Interactive diagrams, charts, and graphs, such as trees, flowcharts, orgcharts, UML, BPMN, or business diagrams

1,124 lines (980 loc) 90.4 kB
/* * Copyright (C) 1998-2020 by Northwoods Software Corporation * All Rights Reserved. * * FLOOR PLANNER: WALL RESHAPING TOOL * Used to reshape walls via their endpoints in a Floorplan */ import * as go from 'gojs'; import { Floorplan } from './Floorplan.js'; import { WallBuildingTool } from './WallBuildingTool.js'; export class WallReshapingTool extends go.Tool { private _handleArchetype: go.Shape; private _handle: go.GraphObject | null; private _adornedShape: go.Shape | null; private _angle: number; private _length: number; private _reshapeObjectName: string; private _isBuilding: boolean; private _returnData: any; private _returnPoint: go.Point | null; private _isIntersecting: boolean; // whether the reshaping wall is intersecting at least one other wall. if so, ignore grid snap private _wallIntersecting: go.Group | null; // the wall the reshaping endpoint is currently intersecting // the wall(s) made after a reshape event by combining some colinear walls // this will only not be an empty Set if the reshape has resulted in the joining of some colinear wall(s), at either the reshaping wall's reshaping endpoint or returnPoint private _joinedWalls: go.Set<go.Group>; /** * @constructor * This tool is responsible for allowing walls in a Floorplan to be reshaped via handles on either side. */ constructor() { super(); const h: go.Shape = new go.Shape(); h.figure = 'Diamond'; h.desiredSize = new go.Size(12, 12); h.fill = 'lightblue'; h.stroke = 'dodgerblue'; h.cursor = 'move'; this._handleArchetype = h; this._handle = null; this._adornedShape = null; this._reshapeObjectName = 'SHAPE'; this._angle = 0; this._length = 0; this._isBuilding = false; // only true when a wall is first being constructed, set in WallBuildingTool's doMouseUp function this._isIntersecting = false; this._joinedWalls = new go.Set<go.Group>(); this._returnPoint = null; // used if reshape is cancelled; return reshaping wall endpoint to its previous location this._returnData = null; // used if reshape is cancelled; return all windows/doors of a reshaped wall to their old place this._joinedWalls = new go.Set<go.Group>(); this._wallIntersecting = null; } // Get the archetype for the handle (a Shape) get handleArchetype() { return this._handleArchetype; } // Get / set current handle being used to reshape the wall get handle(): go.GraphObject | null { return this._handle; } set handle(value: go.GraphObject | null) { this._handle = value; } // Get / set adorned shape (shape of the Wall Group being reshaped) get adornedShape(): go.Shape | null { return this._adornedShape; } set adornedShape(value: go.Shape | null) { this._adornedShape = value; } // Get / set current angle get angle(): number { return this._angle; } set angle(value: number) { this._angle = value; } // Get / set length of the wall being reshaped (used only with SHIFT + drag) get length(): number { return this._length; } set length(value: number) { this._length = value; } // Get / set the name of the object being reshaped get reshapeObjectName(): string { return this._reshapeObjectName; } set reshapeObjectName(value: string) { this._reshapeObjectName = value; } // Get / set flag telling tool whether it's reshaping a new wall (isBuilding = true) or reshaping an old wall (isBuilding = false) get isBuilding(): boolean { return this._isBuilding; } set isBuilding(value: boolean) { this._isBuilding = value; } // Get set loc data for wallParts to return to if reshape is cancelled get returnData(): any { return this._returnData; } set returnData(value: any) { this._returnData = value; } // Get / set the point to return the reshaping wall endpoint to if reshape is cancelled get returnPoint(): go.Point | null { return this._returnPoint; } set returnPoint(value: go.Point | null) { this._returnPoint = value; } // Get / set whether the reshaping wall is intersecting at least one other wall. if so, ignore grid snap get isIntersecting(): boolean { return this._isIntersecting; } set isIntersecting(value: boolean) { this._isIntersecting = value; } // Get / set the wall the reshaping endpoint is currently intersecting get wallIntersecting(): go.Group | null { return this._wallIntersecting; } set wallIntersecting(value: go.Group | null) { this._wallIntersecting = value; } // Get / set the wall created during after a reshape event by combining some colinear walls get joinedWalls(): go.Set<go.Group> { return this._joinedWalls; } set joinedWalls(value: go.Set<go.Group>) { this._joinedWalls = value; } /** * Places reshape handles on either end of a wall node. * @param {go.Part} part The wall to adorn */ public updateAdornments(part: go.Part): void { if (part === null || part instanceof go.Link) return; if (part.isSelected && !this.diagram.isReadOnly) { const seleltgo: go.GraphObject | null = part.findObject(this.reshapeObjectName); if (seleltgo !== null && seleltgo.part !== null && seleltgo.part.data.category === 'WallGroup') { const selelt: go.Shape = seleltgo as go.Shape; let adornment: go.Adornment | null = part.findAdornment(this.name); if (adornment === null) { adornment = this.makeAdornment(selelt); } if (adornment !== null && selelt.part !== null && selelt.geometry != null) { // update the position/alignment of each handle const geo: go.Geometry = selelt.geometry; const b: go.Rect = geo.bounds; const pb: go.Rect = selelt.part.actualBounds; // update the size of the adornment const graphObj = adornment.findObject('BODY'); if (graphObj === null) return; graphObj.desiredSize = b.size; adornment.elements.each(function(h) { if (h.name === undefined) return; let x: number = 0; let y: number = 0; switch (h.name) { case 'sPt': { x = part.data.startpoint.x - pb.x; y = part.data.startpoint.y - pb.y; break; } case 'ePt': { x = part.data.endpoint.x - pb.x; y = part.data.endpoint.y - pb.y; break; } } let xCheck: number = Math.min((x - b.x) / b.width, 1); let yCheck: number = Math.min((y - b.y) / b.height, 1); if (xCheck < 0) xCheck = 0; if (yCheck < 0) yCheck = 0; if (xCheck > 1) xCheck = 1; if (yCheck > 1) yCheck = 1; if (isNaN(xCheck)) xCheck = 0; if (isNaN(yCheck)) yCheck = 0; h.alignment = new go.Spot(Math.max(0, xCheck), Math.max(0, yCheck)); }); part.addAdornment(this.name, adornment); adornment.location = selelt.getDocumentPoint(go.Spot.Center); return; } } } part.removeAdornment(this.name); } /** * If the user has clicked down at a visible handle on a wall node, then the tool may start. * @return {boolean} */ public canStart(): boolean { if (!this.isEnabled) return false; const diagram: go.Diagram = this.diagram; if (diagram === null || diagram.isReadOnly) return false; if (!diagram.allowReshape) return false; if (!diagram.lastInput.left) return false; const h: go.GraphObject | null = this.findToolHandleAt(diagram.firstInput.documentPoint, this.name); return (h !== null || this.isBuilding); } /** * Start a new transaction for the wall reshaping. * Store pre-reshape location of reshaping wall's reshaping endpoint. * Store pre-reshape locations of all wall's members (windows / doors). */ public doActivate(): void { const diagram: go.Diagram = this.diagram; if (diagram === null) return; if (this.isBuilding) { // this.adornedShape has already been set in WallBuildingTool's doMouseDown function if (this.adornedShape !== null && this.adornedShape.part !== null) { const wall: go.Group = this.adornedShape.part as go.Group; this.handle = this.findToolHandleAt(wall.data.endpoint, this.name); this.returnPoint = wall.data.startpoint; } } else { this.handle = this.findToolHandleAt(diagram.firstInput.documentPoint, this.name); if (this.handle === null) return; const adorn: go.Adornment = this.handle.part as go.Adornment; const shape: go.Shape = adorn.adornedObject as go.Shape; const wall: go.Group = shape.part as go.Group; if (!shape) return; this.adornedShape = shape; // store pre-reshape location of wall's reshaping endpoint this.returnPoint = this.handle.name === 'sPt' ? wall.data.startpoint : wall.data.endpoint; // store pre-reshape locations of all wall's members (windows / doors) const wallParts: go.Iterator<go.Part> = wall.memberParts; if (wallParts.count !== 0) { const locationsMap: go.Map<string, go.Point> = new go.Map<string, go.Point>(); wallParts.iterator.each(function(wallPart) { locationsMap.add(wallPart.data.key, wallPart.location); }); this.returnData = locationsMap; } } // diagram.isMouseCaptured = true; this.startTransaction(this.name); this.isActive = true; } /** * Adjust the handle's coordinates, along with the wall's points. */ public doMouseMove(): void { const fp: Floorplan = this.diagram as Floorplan; const tool: WallReshapingTool = this; if (tool.handle === null) return; const adorn: go.Adornment = tool.handle.part as go.Adornment; const wall: go.Group = adorn.adornedPart as go.Group; // the stationaryPt let mousePt: go.Point = fp.lastInput.documentPoint; if (tool.isActive && fp !== null) { // if user is holding shift, make sure the angle of the reshaping wall (from stationaryPt to mousePt) is a multiple of 45 if (fp.lastInput.shift) { // what's the current angle made from stationaryPt to mousePt? const type = tool.handle.name; const stationaryPt: go.Point = (type === 'sPt') ? wall.data.endpoint : wall.data.startpoint; let ang: number = stationaryPt.directionPoint(mousePt); const length: number = Math.sqrt(stationaryPt.distanceSquaredPoint(mousePt)); ang = Math.round(ang / 45) * 45; let newPoint: go.Point = new go.Point(stationaryPt.x + length, stationaryPt.y); // rotate the new point ang degrees const dx: number = stationaryPt.x; const dy = stationaryPt.y; newPoint = newPoint.offset(-dx, -dy); // move point to origin newPoint = newPoint.rotate(ang); // rotate ang degrees around origin newPoint = newPoint.offset(dx, dy); // add back offset mousePt = newPoint; } // if the mousePt is close to some wall's endpoint, snap the mousePt to that endpoint const walls: go.Iterator<go.Group> = fp.findNodesByExample({ category: 'WallGroup' }) as go.Iterator<go.Group>; walls.iterator.each(function(w: go.Group) { if (w.data.key !== wall.data.key) { const spt: go.Point = w.data.startpoint; const ept: go.Point = w.data.endpoint; // if the mousePt is inside the geometry of another wall, project the point onto that wall if (fp.isPointInWall(w, mousePt)) { mousePt = mousePt.projectOntoLineSegmentPoint(w.data.startpoint, w.data.endpoint); tool.isIntersecting = true; // yes, the current reshaping wall is intersecting another wall } // if the mousePt is close to some wall's endpoint, snap the mousePt to that endpoint if (Math.sqrt(spt.distanceSquaredPoint(mousePt)) < 10) { mousePt = spt; } else if (Math.sqrt(ept.distanceSquaredPoint(mousePt)) < 10) { mousePt = ept; } } }); // if the resulting segment between stationary pt and mousePt would intersect other wall(s), project mousePt onto the first wall it would intersect const iw = tool.getClosestIntersectingWall(mousePt); // if we are or just were intersecting some wall, miter it if (iw === null || tool.wallIntersecting !== null) { if (tool.wallIntersecting !== null && tool.wallIntersecting !== undefined && tool.wallIntersecting.data !== null) { tool.performMiteringOnWall(tool.wallIntersecting); } } if (iw != null) { tool.isIntersecting = true; // yes, the current reshaping wall is intersecting another wall tool.wallIntersecting = iw; mousePt = mousePt.projectOntoLineSegmentPoint(iw.data.startpoint, iw.data.endpoint); // if the mousePt is really close to an endpoint of its intersecting wall, make it that endpoint const distToSpt: number = Math.sqrt(mousePt.distanceSquaredPoint(iw.data.startpoint)); const distToEpt: number = Math.sqrt(mousePt.distanceSquaredPoint(iw.data.endpoint)); if (distToSpt < 25) { mousePt = iw.data.startpoint; } else if (distToEpt < 10) { mousePt = iw.data.endpoint; } } else { tool.isIntersecting = false; // if the wall we were previously intersecting is not touching the reshaping wall, forget it if (tool.wallIntersecting !== null && tool.wallIntersecting !== undefined && tool.wallIntersecting.data !== null && fp.getWallsIntersection(wall, tool.wallIntersecting) === null) { tool.wallIntersecting = null; } } tool.calcAngleAndLengthFromHandle(mousePt); // sets this.angle and this.length (useful for when SHIFT is held) tool.reshape(mousePt); } tool.performMiteringOnWall(wall); fp.updateWallDimensions(); fp.updateWallAngles(); } /** * Get the closest wall the reshaping wall intersects with. * Returns null if reshaping wall does not intersect with any other wall. * @param {go.Point} proposedPt The proposed point for the reshaping wall's moving pt * @return {go.Group | null} The closest wall the reshaping wall's reshaping endpoint intersects with */ private getClosestIntersectingWall(proposedPt: go.Point): go.Group | null { const tool: WallReshapingTool = this; if (tool.handle === null) return null; const adorn: go.Adornment = tool.handle.part as go.Adornment; const wall: go.Group = adorn.adornedPart as go.Group; const type = tool.handle.name; const stationaryPt: go.Point = (type === 'sPt') ? wall.data.endpoint : wall.data.startpoint; // dummy wall is used for intersection checks, since the reshaping wall has not had its data yet set const dummyWallData: any = { key: 'wall', category: 'WallGroup', caption: 'Wall', type: 'Wall', startpoint: stationaryPt, smpt1: stationaryPt, smpt2: stationaryPt, endpoint: proposedPt, empt1: proposedPt, empt2: proposedPt, thickness: parseFloat(tool.diagram.model.modelData.wallThickness), isGroup: true, notes: '' }; tool.diagram.model.addNodeData(dummyWallData); const dummyWall: go.Group = tool.diagram.findPartForKey(dummyWallData.key) as go.Group; const fp: Floorplan = tool.diagram as Floorplan; const walls: go.Iterator<go.Group> = tool.diagram.findNodesByExample({ category: 'WallGroup' }) as go.Iterator<go.Group>; let closestWall: go.Group | null = null; let closestDistance: number = Number.MAX_VALUE; walls.iterator.each(function(w) { if (w.data.key !== wall.data.key && w.data.key !== dummyWall.data.key) { // check if wall and w intersect, and if so, where const intersectPoint: go.Point | null = fp.getWallsIntersection(dummyWall, w); // also, don't project onto a wall the stationaryPt is already along (this would make two walls on top of each other) let isStationaryPtOnW = false; const ab: number = parseFloat(Math.sqrt(w.data.startpoint.distanceSquaredPoint(stationaryPt)).toFixed(2)); const bc: number = parseFloat(Math.sqrt(stationaryPt.distanceSquaredPoint(w.data.endpoint)).toFixed(2)); const ac: number = parseFloat(Math.sqrt(w.data.startpoint.distanceSquaredPoint(w.data.endpoint)).toFixed(2)); if (Math.abs((ab + bc) - ac) <= .1) { isStationaryPtOnW = true; } if (intersectPoint !== null && !isStationaryPtOnW) { // calc distance from stationaryPoint to proposed intersection point const dist: number = Math.sqrt(stationaryPt.distanceSquaredPoint(intersectPoint)); if (dist < closestDistance) { closestDistance = dist; closestWall = w; } } } }); // remove the dummy wall fp.remove(dummyWall); return closestWall; } /** * Returns whether or not 2 points are "close enough" to each other. * "Close enough" is, by default, defined as a point whose x and y values are within .05 * document units of another point's x and y values. * @param {go.Point} p1 * @param {go.Point} p2 * @return {boolean} */ public pointsApproximatelyEqual(p1: go.Point, p2: go.Point): boolean { const x1: number = p1.x; const x2: number = p2.x; const y1: number = p1.y; const y2: number = p2.y; const diff1: number = Math.abs(x2 - x1); const diff2: number = Math.abs(y2 - y1); if (diff2 < .05 && diff1 < .05) { return true; } return false; } /** * Sets the counterclockwise mitering point for wallA / clockwise mitering point for wallB. * This algorithm based on https://math.stackexchange.com/questions/1849784/calculate-miter-points-of-stroked-vectors-in-cartesian-plane. * @param {go.Group} wa wallA * @param {go.Group} wb wallB */ private performMitering(wa: go.Group, wb: go.Group): void { const tool = this; const diagram: Floorplan = this.diagram as Floorplan; // wall endpoints, thicknesses, lengths const as: go.Point = wa.data.startpoint; const ae: go.Point = wa.data.endpoint; const bs: go.Point = wb.data.startpoint; const be: go.Point = wb.data.endpoint; const wat: number = wa.data.thickness; const wbt: number = wb.data.thickness; const wal: number = Math.sqrt(as.distanceSquaredPoint(ae)); const wbl: number = Math.sqrt(bs.distanceSquaredPoint(be)); // points const B: go.Point | null = diagram.getWallsIntersection(wa, wb); // intersection point if (B === null) { return; } let A: go.Point = (tool.pointsApproximatelyEqual(as, B)) ? ae : as; // wallA non-intersection point let C: go.Point = (tool.pointsApproximatelyEqual(bs, B)) ? be : bs; // wallB non-intersection point // edge case: non-endpoint intersection // must know which wall is outer wall (the one who has no endpoint in the intersection) // and which wall is inner wall (the one with an endpoint in the intersection) let ow: go.Group | null = null; let iw: go.Group | null = null; if (!tool.pointsApproximatelyEqual(as, B) && !tool.pointsApproximatelyEqual(ae, B)) { ow = wa; iw = wb; } else if (!tool.pointsApproximatelyEqual(bs, B) && !tool.pointsApproximatelyEqual(be, B)) { ow = wb; iw = wa; } // if wall A is the inner wall, use the endpoint of wall B that counterclockwise from point A for point C if (ow !== null && iw !== null && wa.data.key === iw.data.key) { if (tool.isClockwise(A, B, ow.data.startpoint)) { C = ow.data.startpoint; } else { C = ow.data.endpoint; } } // if wall B is the inner wall, use endpoint of wall A that's clockwise from point C for point A if (ow !== null && iw !== null && wb.data.key === iw.data.key) { if (tool.isClockwise(B, C, ow.data.startpoint)) { A = ow.data.startpoint; } else { A = ow.data.endpoint; } } // angle between wallA and wallB, clockwise, in degrees const a1: number = B.directionPoint(A); const a2: number = B.directionPoint(C); let ang: number = Math.abs(a1 - a2 + 360) % 360; if (Math.abs(ang - 180) < .1) { return; } ang = ang * (Math.PI / 180); // radians // create a parallelogram with altitudes wat/2 and wbt/2, s.t. u and v are the lengths from B to reach D (counterclockwise mitering point) const u: number = Math.abs(wbt / (2 * (Math.sin(ang)))); const v: number = Math.abs(wat / (2 * (Math.sin(ang)))); // get u and v vectors const ab: number = Math.sqrt(A.distanceSquaredPoint(B)); const bc: number = Math.sqrt(B.distanceSquaredPoint(C)); const ux: number = ((A.x - B.x) / ab) * u; const uy: number = ((A.y - B.y) / ab) * u; // only for endpoint-endpoint? const vx: number = ((C.x - B.x) / bc) * v; const vy: number = ((C.y - B.y) / bc) * v; // these are the mitering points const D: go.Point = new go.Point(B.x + ux + vx, B.y + uy + vy); const E: go.Point = new go.Point(B.x - ux - vx, B.y - uy - vy); // miter limit TODO??? const minLength: number = Math.min(wal, wbl); if (Math.sqrt(D.distanceSquaredPoint(B)) > minLength) { return; } // mitering point / other mitering point const mpt: go.Point = tool.isClockwise(B, A, D) ? E : D; if (isNaN(mpt.x) || isNaN(mpt.y)) { return; } // now figure out which mitering point of wallA's data to modify // only modify a mitering point in data if B is one of wallA's endpoints if (tool.pointsApproximatelyEqual(as, B) || tool.pointsApproximatelyEqual(ae, B)) { let prop: string | null = null; // wall A's direction to point B is from startpoint to endpoint if (tool.pointsApproximatelyEqual(A, as)) { // if ang2 is clockwise of ang1, update empt1 if (tool.isClockwise(A, B, mpt)) { prop = 'empt1'; } else { prop = 'empt2'; } } else if (tool.pointsApproximatelyEqual(A, ae)) { // wall A's direction to point B is from endpoint to startpoint if (tool.isClockwise(A, B, mpt)) { prop = 'smpt2'; } else { prop = 'smpt1'; } } if (prop !== null) { diagram.model.setDataProperty(wa.data, prop, mpt); diagram.updateWall(wa); } } // same, but for wall B if (tool.pointsApproximatelyEqual(bs, B) || tool.pointsApproximatelyEqual(be, B)) { let prop: string | null = null; // wall A's direction to point B is from startpoint to endpoint if (tool.pointsApproximatelyEqual(C, bs)) { // if ang2 < ang1, update empt1 if (tool.isClockwise(C, B, mpt)) { prop = 'empt1'; } else { prop = 'empt2'; } } else if (tool.pointsApproximatelyEqual(C, be)) { // wall A's direction to point B is from endpoint to startpoint if (tool.isClockwise(C, B, mpt)) { prop = 'smpt2'; } else { prop = 'smpt1'; } } if (prop !== null) { diagram.model.setDataProperty(wb.data, prop, mpt); diagram.updateWall(wb); } } } /** * Returns a set of all the wall intersections in the entire floorplan. * Each entry is a stringified points (i.e. "0 0"). * @return {go.Set<string>} */ public getAllWallIntersectionPoints(): go.Set<string> { const tool: WallReshapingTool = this; const diagram: Floorplan = tool.diagram as Floorplan; // get all walls const walls: go.Iterator<go.Group> = diagram.findNodesByExample({ category: 'WallGroup' }) as go.Iterator<go.Group>; const intersectionPoints: go.Set<string> = new go.Set(); // set of Points where walls intersect walls.iterator.each(function(w) { // for each wall, go through all other walls; if this wall intersects another wall, mark it as an intersection point const otherWalls: go.Iterator<go.Group> = diagram.findNodesByExample({ category: 'WallGroup' }) as go.Iterator<go.Group>; otherWalls.iterator.each(function(ow) { if (ow.data.key === w.data.key) return; // do not check for intersection with self const ip: go.Point | null = diagram.getWallsIntersection(w, ow); let doAdd: boolean = true; if (ip !== null) { // make sure there is not already an intersection point in the set that's really close to this one intersectionPoints.iterator.each(function(ips) { const ip2: go.Point = go.Point.parse(ips); if (tool.pointsApproximatelyEqual(ip2, ip)) { doAdd = false; } }); if (doAdd) { intersectionPoints.add(go.Point.stringify(ip)); } } }); }); return intersectionPoints; } /** * Get all the walls with an endpoint at a given Point. * Returns a List of all walls involved in that intersection. * @param {go.Point | null} intersectionPoint * @param {boolean} includeDividers Whether or not to also include Room Dividers with endpoints at intersectionPoint. Default is true. * @return {go.List<go.Group>} */ public getAllWallsAtIntersection(intersectionPoint: go.Point | null, includeDividers?: boolean): go.List<go.Group> { if (includeDividers === undefined || includeDividers === null) { includeDividers = true; } const tool: WallReshapingTool = this; const diagram: Floorplan = tool.diagram as Floorplan; const wallsInvolved: go.List<go.Group> = new go.List(); // list of walls, which will be sorted clockwise if (intersectionPoint === null) { return wallsInvolved; } diagram.findObjectsNear( intersectionPoint, 1, function(x: go.GraphObject) { if (x.part !== null) { return x.part; } return null; }, function(p) { if (!(p instanceof go.Group && p.category === 'WallGroup' && (includeDividers || !p.data.isDivider) && !wallsInvolved.contains(p))) return false; // make sure the wall's segment includes ip const s: go.Point = p.data.startpoint; const e: go.Point = p.data.endpoint; return tool.isPointOnSegment(s, e, intersectionPoint); }, true, wallsInvolved ); return wallsInvolved; } /** * Returns whether or not 2 walls share at least one endpoint * @param {go.Group} wa * @param {go.Group} wb * @return {boolean} */ private doWallsShareAnEndpoint(wa: go.Group, wb: go.Group): boolean { const tool: WallReshapingTool = this; const as: go.Point = wa.data.startpoint; const ae: go.Point = wa.data.endpoint; const bs: go.Point = wb.data.startpoint; const be: go.Point = wb.data.endpoint; if (tool.pointsApproximatelyEqual(as, bs) || tool.pointsApproximatelyEqual(as, be) || tool.pointsApproximatelyEqual(ae, bs) || tool.pointsApproximatelyEqual(ae, be)) { return true; } return false; } /** * This function, called on {@link doMouseUp} event, checks if the reshaping wall's reshaping endpoint is now intersecting a wall. * If so, that intersected wall is split into 2 walls at the intersection point. All walls at the intersection point are then mitered. * Next, it checks if the reshapingWall has become a new, big wall (via {@link joinColinearWalls}). * If so, we must split the new wall at any points it intersects with others. * Room boundary data that depended on the split wall is then updated to reflect the split. */ public maybeSplitWall(): void { const tool: WallReshapingTool = this; if (tool.handle === null) return; const adorn: go.Adornment = tool.handle.part as go.Adornment; const reshapingWall: go.Group = adorn.adornedPart as go.Group; const movingProp: string = tool.handle.name; const movingPt: go.Point = movingProp === 'sPt' ? reshapingWall.data.startpoint : reshapingWall.data.endpoint; const jw: go.Set<go.Group> = tool.joinedWalls; const wallsAtEndpoint: go.List<go.Group> = tool.getAllWallsAtIntersection(movingPt); // exclude the reshapingWall from wallsAtEndpoint wallsAtEndpoint.remove(reshapingWall); jw.iterator.each(function(ww: go.Group) { wallsAtEndpoint.remove(ww); }); if (wallsAtEndpoint.count === 1) { const wallToSplit: go.Group | null = wallsAtEndpoint.first(); if (wallToSplit !== null) { // make sure this is not an endpoint to endpoint connection if (!tool.doWallsShareAnEndpoint(reshapingWall, wallToSplit)) { tool.maybePerformWallSplit(wallToSplit, movingPt); } } } // if we're building a wall, it's possible we need to split at the stationary pt too if (tool.isBuilding) { const stationaryPt: go.Point = movingPt === reshapingWall.data.startpoint ? reshapingWall.data.endpoint : reshapingWall.data.startpoint; const wallsAtStationaryPt: go.List<go.Group> = tool.getAllWallsAtIntersection(stationaryPt); wallsAtStationaryPt.remove(reshapingWall); jw.iterator.each(function(ww: go.Group) { wallsAtEndpoint.remove(ww); }); if (wallsAtStationaryPt.count === 1) { const wallToSplit: go.Group | null = wallsAtStationaryPt.first(); if (wallToSplit !== null) { // make sure this is not an endpoint to endpoint connection if (!tool.doWallsShareAnEndpoint(reshapingWall, wallToSplit)) { tool.maybePerformWallSplit(wallToSplit, stationaryPt); } } } } // if this reshape event has created a big joined wall, the joined wall may need to be split // find out if either endpoint of the original reshaping wall is NOT one of the endpoints of joinedWall // if so, split the joinedWall at that endpoint if (jw !== null) { jw.iterator.each(function(ww: go.Group) { // find all points along the joined wall where it intersects with other walls and split along them tool.splitNewWall(ww); }); } } /** * Finds all points along a new wall (created via {@link joinColinearWalls}) and splits / miters at each. * @param w The newly joined wall */ private splitNewWall(w: go.Group): void { const tool: WallReshapingTool = this; const fp: Floorplan = this.diagram as Floorplan; // find all walls that intersect this wall const walls: go.Iterator<go.Group> = fp.findNodesByExample({ category: 'WallGroup' }) as go.Iterator<go.Group>; const ips: go.Set<go.Point> = new go.Set<go.Point>(); walls.iterator.each(function(ww: go.Group) { const ip: go.Point | null = fp.getWallsIntersection(w, ww); if (ip !== null) { ips.add(ip); } }); ips.iterator.each(function(ip: go.Point) { const wi: go.List<go.Group> = tool.getAllWallsAtIntersection(ip); wi.iterator.each(function(ww: go.Group) { const s: go.Point = ww.data.startpoint; const e: go.Point = ww.data.endpoint; if (!tool.pointsApproximatelyEqual(s, ip) && !tool.pointsApproximatelyEqual(e, ip)) { tool.maybePerformWallSplit(ww, ip); } }); }); } /** * Split a given wall into 2 at a given intersection point, if the given point is on the wall and not on one of the wall's endpoints. * The resultant two walls are then mitered. * Room boundary data that depended on the split wall is then updated to reflect the split. * @param {go.Group} w wall to split * @param {go.Point} ip intersection point where the split should occur */ private maybePerformWallSplit(w: go.Group, ip: go.Point): void { const tool: WallReshapingTool = this; const fp: Floorplan = tool.diagram as Floorplan; const s: go.Point = w.data.startpoint; const e: go.Point = w.data.endpoint; const type: string = w.data.isDivider ? 'Divider' : 'Wall'; // this wall has neither endpoint in the intersection -- it must be split into 2 walls const data1 = { key: 'wall', category: 'WallGroup', caption: type, type: type, color: w.data.color, startpoint: s, endpoint: ip, smpt1: s, smpt2: s, empt1: ip, empt2: ip, thickness: w.data.thickness, isGroup: true, notes: '', isDivider: w.data.isDivider }; const data2 = { key: 'wall', category: 'WallGroup', caption: type, type: type, color: w.data.color, startpoint: ip, endpoint: e, smpt1: ip, smpt2: ip, empt1: e, empt2: e, thickness: w.data.thickness, isGroup: true, notes: '', isDivider: w.data.isDivider }; // only actually split the wall if the 2 new walls would both have at least length 1 // and if there are no walls with endpoints very close to these proposed ones const l1: number = Math.sqrt(data1.startpoint.distanceSquaredPoint(data1.endpoint)); const l2: number = Math.sqrt(data2.startpoint.distanceSquaredPoint(data2.endpoint)); const walls: go.Iterator<go.Group> = fp.findNodesByExample({ category: 'WallGroup' }) as go.Iterator<go.Group>; let alreadyExists: boolean = false; walls.iterator.each(function(wc: go.Group) { const ws: go.Point = wc.data.startpoint; const we: go.Point = wc.data.endpoint; if ((tool.pointsApproximatelyEqual(s, ws) && tool.pointsApproximatelyEqual(ip, we)) || (tool.pointsApproximatelyEqual(s, we) && tool.pointsApproximatelyEqual(ip, ws))) { alreadyExists = true; } if ((tool.pointsApproximatelyEqual(ip, ws) && tool.pointsApproximatelyEqual(e, we)) || (tool.pointsApproximatelyEqual(ip, we) && tool.pointsApproximatelyEqual(e, ws))) { alreadyExists = true; } }); if (l1 > 1 && l2 > 1 && !alreadyExists) { fp.model.addNodeData(data1); fp.model.addNodeData(data2); const w1: go.Group = fp.findNodeForData(data1) as go.Group; const w2: go.Group = fp.findNodeForData(data2) as go.Group; // Before removing the original wall from the Floorplan, update relevant room boundarywalls data // iff this method is being called as a result of a user-prompted wall reshape action // needed so proper mitering side of replacement entry walls can be determined tool.premiterWall(w1); tool.premiterWall(w2); tool.performMiteringAtPoint(ip, false); if (tool.handle !== null) { const rooms: go.Iterator<go.Node> = fp.findNodesByExample({ category: 'RoomNode' }); const adorn: go.Adornment = tool.handle.part as go.Adornment; const rw: go.Group = adorn.adornedPart as go.Group; // reshaping wall // go through rooms, find any whose boundary walls contain w (the wall that was split, soon to be removed) rooms.iterator.each(function(r: go.Node) { const bw: Array<any> = r.data.boundaryWalls; for (let i: number = 0; i < bw.length; i++) { const entry: any = bw[i]; const wk: string = entry[0]; if (wk === w.data.key) { // then, find out if the reshaping wall, at the non-ip endpoint, is connected to another wall in that room's boundary walls let isConnectedToBounds: boolean = false; const nonIpEndpoint: go.Point = (tool.pointsApproximatelyEqual(rw.data.startpoint, ip)) ? rw.data.endpoint : rw.data.startpoint; const iw: go.List<go.Group> = tool.getAllWallsAtIntersection(nonIpEndpoint); iw.iterator.each(function(ww: go.Group) { // if boundary walls contains ww and ww is not the reshaping wall, reshaping wall is connected to room boundary walls at non ip endpoint for (let j = 0; j < bw.length; j++) { const ee: any = bw[j]; const wk2: string = ee[0]; if (ww.data.key === wk2 && ww.data.key !== rw.data.key) { isConnectedToBounds = true; } } }); // if yes, replace the w entry in boundary walls with just one new entry, using the split wall that is connected to some other wall in bounds if (isConnectedToBounds) { // find out whether w1 or w2 is connected to another wall in boundary walls let isW1ConnectedToBounds: boolean = false; const w1NonIpEndpoint: go.Point = (tool.pointsApproximatelyEqual(w1.data.startpoint, ip)) ? w1.data.endpoint : w1.data.startpoint; const iw2: go.List<go.Group> = tool.getAllWallsAtIntersection(w1NonIpEndpoint); iw2.remove(w); // do not include the wall soon to be destroyed // go through all walls at w1's non-ip endpoint and find out if one of those is in r's boundary walls iw2.iterator.each(function(ww: go.Group) { for (let j: number = 0; j < bw.length; j++) { const entry2: any = bw[j]; const wk2: string = entry2[0]; if (ww.data.key === wk2 && w1.data.key !== ww.data.key) { // additional followup -- make sure ww2 is still connected to r's boundary walls at other endpoint (not connected to w1NonIpEndpoint) const ww2: go.Group = fp.findNodeForKey(wk2) as go.Group; const ww2OtherEndpoint: go.Point = (tool.pointsApproximatelyEqual(ww2.data.startpoint, w1NonIpEndpoint)) ? ww2.data.endpoint : ww2.data.startpoint; const iw3: go.List<go.Group> = tool.getAllWallsAtIntersection(ww2OtherEndpoint); iw3.iterator.each(function(ww3: go.Group) { for (let k = 0; k < bw.length; k++) { const entry3: any = bw[k]; const wk3: string = entry3[0]; if (wk3 === ww3.data.key && wk3 !== ww2.data.key) { isW1ConnectedToBounds = true; } } }); } } }); // replace this entry of r's boundary walls with the replacementWall const replacementWall: go.Group = (isW1ConnectedToBounds) ? w1 : w2; const replacementEntry = tool.getUpdatedEntry(entry, replacementWall); fp.startTransaction(); const newBounds: Array<any> = bw.slice(); newBounds[i] = replacementEntry; fp.model.setDataProperty(r.data, 'boundaryWalls', newBounds); fp.commitTransaction(); } else { // if no, replace the w entry with both split walls. Order those 2 entries CC, relative to reshaping wall // get a List of walls involved (reshaping wall, w1, and w2) let wi: go.List<go.Group> = new go.List<go.Group>(); wi.add(rw); wi.add(w1); wi.add(w2); wi = fp.sortWallsClockwiseWithSetStartWall(wi, rw); // get replacement entries for the entry with w const replacementEntry2: any = tool.getUpdatedEntry(entry, wi.toArray()[1]); const replacementEntry1: any = tool.getUpdatedEntry(entry, wi.toArray()[2]); // insert these replacement entries into the bw at index i, remove fp.startTransaction(); const newBounds: Array<any> = bw.slice(); newBounds.splice(i, 1, replacementEntry1); newBounds.splice(i + 1, 0, replacementEntry2); fp.model.setDataProperty(r.data, 'boundaryWalls', newBounds); fp.commitTransaction(); } } } }); // end rooms iteration } // Maintain wall parts that were on the big wall -- give them new locations on the most appropriate of the split walls, if possible const wallParts: go.Iterator<go.Node> = fp.findNodesByExample({ group: w.data.key }); const wallsSet: go.Set<go.Group> = new go.Set<go.Group>(); wallsSet.add(w1); wallsSet.add(w2); tool.maintainWallParts(wallParts, wallsSet); // remove original wall fp.remove(w); // perform mitering tool.premiterWall(w1); tool.premiterWall(w2); const w1op: go.Point = tool.pointsApproximatelyEqual(w1.data.startpoint, ip) ? w1.data.endpoint : w1.data.startpoint; const w2op: go.Point = tool.pointsApproximatelyEqual(w2.data.startpoint, ip) ? w2.data.endpoint : w2.data.startpoint; tool.performMiteringAtPoint(ip, false); tool.performMiteringAtPoint(w1op, false); tool.performMiteringAtPoint(w2op, false); } } /** * Go through all walls -- if a wall crosses another at a non-endpoint-to-endpoint connection, split that wall in 2 * such that only endpoint to endpoint connections exist (this makes mitering much easier). * NOTE: Since this goes through all walls in the Floorplan, performance can get bad quickly. Use this method sparingly, if at all */ public splitAllWalls(): void { const tool = this; const intersectionPoints: go.Set<string> = tool.getAllWallIntersectionPoints(); intersectionPoints.iterator.each(function(ips: string) { const ip: go.Point = go.Point.parse(ips); const wallsInvolved: go.List<go.Group> = tool.getAllWallsAtIntersection(ip); // find all walls involved that do not have their start or endpoint at the intersection point wallsInvolved.iterator.each(function(w) { const s: go.Point = w.data.startpoint; const e: go.Point = w.data.endpoint; if (!tool.pointsApproximatelyEqual(s, ip) && !tool.pointsApproximatelyEqual(e, ip)) { tool.maybePerformWallSplit(w, ip); } }); }); } /** * Return whether or not wall A is parallel to wall B. * @param {go.Group} wa Wall A * @param {go.Group} wb Wall B * @return {boolean} */ private areWallsParallel(wa: go.Group, wb: go.Group): boolean { const tool: WallReshapingTool = this; const fp: Floorplan = this.diagram as Floorplan; const as: go.Point = wa.data.startpoint; const ae: go.Point = wa.data.endpoint; const bs: go.Point = wb.data.startpoint; const be: go.Point = wb.data.endpoint; let isParallel: boolean = false; const a1: number = +as.directionPoint(ae); const a2: number = +bs.directionPoint(be); if (Math.abs(a1 - a2) < 1 || (Math.abs(a1 - a2) > 179 && Math.abs(a1 - a2) < 181)) { isParallel = true; } return isParallel; } /** * Returns whether wall B is colinear to wall A. * Wall A is colinear with Wall B if it: * 0) Is the same wall type as Wall B (wall | divider) * 1) Is parallel with Wall B * 2) Shares an endpoint, 'p', with Wall B, and * 2a) Any / all walls with endpoints at p are all parallel to wall A / B * @param {go.Group} wa wall A * @param {go.Group} wb wall B * @return {boolean} */ public isWallColinear(wa: go.Group, wb: go.Group): boolean { const tool: WallReshapingTool = this; const fp: Floorplan = this.diagram as Floorplan; if (wa.data.isDivider !== wb.data.isDivider) { return false; } const as: go.Point = wa.data.startpoint; const ae: go.Point = wa.data.endpoint; const bs: go.Point = wb.data.startpoint; const be: go.Point = wb.data.endpoint; let isColinear: boolean = false; // 1) Is wall A parallel with Wall B? (or close enough to parallel) if (tool.areWallsParallel(wa, wb)) { // get the endpoint shared by wa and wb, if it exists let sharedEndpoint: go.Point | null = null; if (tool.pointsApproximatelyEqual(as, bs) || tool.pointsApproximatelyEqual(as, be)) { sharedEndpoint = as; } else if (tool.pointsApproximatelyEqual(ae, bs) || tool.pointsApproximatelyEqual(ae, be)) { sharedEndpoint = ae; } if (sharedEndpoint !== null) { // Make sure all walls with an endpoint at sharedEndpoint are parallel to wa const wi: go.List<go.Group> = tool.getAllWallsAtIntersection(sharedEndpoint); let endpointHasNonColinearWall: boolean = false; wi.iterator.each(function(w: go.Group) { if (!tool.areWallsParallel(w, wa)) { endpointHasNonColinearWall = true; } }); if (!endpointHasNonColinearWall) { isColinear = true; } } } return isColinear; } /** * Get all walls colinear to wall w and store them in a given Set. * @param {go.Group} w * @param {go.Set<go.Group>} set Optional * @return {go.Set<go.Group>} */ private findAllColinearWalls(w: go.Group, set?: go.Set<go.Group>): go.Set<go.Group> { if (set === null || set === undefined) { set = new go.Set<go.Group>(); } // make sure Set contains w set.add(w); const tool: WallReshapingTool = this; const diagram: Floorplan = tool.diagram as Floorplan; const walls: go.Iterator<go.Group> = diagram.findNodesByExample({ category: 'WallGroup' }) as go.Iterator<go.Group>; walls.iterator.each(function(ow) { if (tool.isWallColinear(w, ow) && set !== undefined && !set.contains(ow)) { set.add(ow); tool.findAllColinearWalls(ow, set); } }); return set; } /** * This function, called after each {@link doMouseUp} event, checks for colinear pairs of walls at two places. * First, it checks for colinear walls with the reshaping wall. * Second, it checks for colinear walls at {@link returnPoint}. * If there are colinear walls found, they are joined into one big wall. Resultant wall(s) are then mitered. * Additionally, any rooms whose geometries depended on one of the walls that was just joined have their data updated, * replacing the old (removed) wall(s) in data with the new one. * Note: These rooms will have the final update to their geometry / data done later, in updateRoomBoundaries(). * The data manipulation done here is just to ensure the walls removed by this function are not referenced anywhere in room data anymore. */ public joinColinearWalls(): void { const tool: WallReshapingTool = this; if (tool.handle === null) return; // 1) Check if the reshaping wall is colinear with another wall at one of its endpoints const adorn: go.Adornment = tool.handle.part as go.Adornment; const reshapingWall: go.Group = adorn.adornedPart as go.Group; const cw1: go.Set<go.Group> = tool.findAllColinearWalls(reshapingWall); const jw: go.Group | null = tool.performColinearWallJoining(cw1, reshapingWall); if (jw !== null) { tool.joinedWalls.add(jw); } // 2) Check if there are 2 colinear walls at returnPoint (where the reshaping endpoint originally was) const wallsAtReturnPoint: go.List<go.Group> = tool.getAllWallsAtIntersection(tool.returnPoint); if (wallsAtReturnPoint.count === 2) { const wallsArr: Array<go.Group> = wallsAtReturnPoint.toArray(); const w1: go.Group = wallsArr[0]; const w2: go.Group = wallsArr[1]; if (tool.isWallColinear(w1, w2)) { const cw2: go.Set<go.Group> = new go.Set<go.Group>(); cw2.add(w1); cw2.add(w2); const jw2: go.Group | null = tool.performColinearWallJoining(cw2, w1); if (jw2 !== null) { tool.joinedWalls.add(jw2); } } } } /** * Join a set of colinear walls into one big wall. The big wall is then mitered. * Constituent walls in colinear wall set are removed. * As such, if any rooms depend on them for boundary data, those room's data is updated * @param {go.Set<go.Group>} colinearWalls The set of colinear walls * @param {go.Group} w The wall to use as reference for color / thickness when joining the walls. * If this is not supplied, the first wall in the colinearWalls set is used * @return {go.Group | null} The new, big wall created by joining colinear walls */ private performColinearWallJoining(colinearWalls: go.Set<go.Group>, w?: go.Group): go.Group | null { const tool: WallReshapingTool = this; const fp: Floorplan = tool.diagram as Floorplan; const garbage: go.Set<go.Group> = new go.Set<go.Group>(); // all colinear "walls" must be Walls OR they must all be Room Dividers, they may not be a mix const cwf = colinearWalls.first(); if (cwf === null) { return null; } if (w === undefined) { w = cwf; } const acceptedCategory: string = cwf.data.category; colinearWalls.iterator.each(function(cw: go.Group) { if (cw.data.category !== acceptedCategory) { return; } }); // Find the 2 farthest endpoints in colinear walls set if (colinearWalls.count > 1) { let pt1: go.Point | null = null; let pt2: go.Point | null = null; let farthestDist: number = 0;