All files / src splitMergePolygons.js

0% Statements 0/437
0% Branches 0/148
0% Functions 0/111
0% Lines 0/415

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { PlanarFaceTree } from 'planar-face-discovery'
import {
  substractVector,
  addVector,
  multiplyVector,
  dotProduct,
  vectorLength,
} from './vector'
import {
  isAlmostSamePoint2D,
  getPointOnLine,
  getDistanceBetweenPoints,
  isPointBetweenSegment,
  isInsidePolygon,
  verticalProjectionOnPlane,
  polygonsHaveSame2DOutline,
  calculateArea,
} from './geometry'
import { groupBy } from 'lodash'
import { Polygon } from './objects/Polygon'
import { defaultBaseHeight, mmTolerance } from './config'
import { generateEdges2D } from './objects/derivedState/nodesEdgesCreation'
import { Point, updateComputedGeometryPolygon } from './objects'
 
export function mergePolygons(polygonIdsToMerge, edges, layer, polygons) {
  const outsideEdge = edges.filter((e) => e.belongsTo.length == 1)
  const insideEdge = edges.filter((e) => e.belongsTo.length == 2)
  const insideEdgeToKeep = insideEdge.filter((e) => {
    return (
      !polygonIdsToMerge.includes(e.belongsTo[0].polygonId) ||
      !polygonIdsToMerge.includes(e.belongsTo[1].polygonId)
    )
  })
  const newEdges = [...outsideEdge, ...insideEdgeToKeep]
  //nodeList:
  let dirtyNodeList = []
  newEdges.forEach((edge) => {
    dirtyNodeList.push(edge.outline[0])
    dirtyNodeList.push(edge.outline[1])
  })
  const nodeList = []
  for (let node of dirtyNodeList) {
    const nodeFound = nodeList.find((n) => {
      return n && isAlmostSamePoint2D(n, node, mmTolerance)
    })
    if (!nodeFound) {
      nodeList.push(node)
    }
  }
  //edgeList (just in term of indexes)
  const edgeList = getEdgeListSimple(nodeList, newEdges)
  const outlineList = getOutlineList(nodeList, edgeList)
 
  const polygonList = []
  for (let k = 0; k < outlineList.length; k++) {
    //check if roof with same outline already exist:
    let polygon = polygons.find((polygon) =>
      polygonsHaveSame2DOutline(outlineList[k], polygon.outline)
    )
    if (!polygon) {
      let newPolygon = new Polygon(outlineList[k], layer)
      polygonList.push(newPolygon)
    } else {
      polygonList.push(polygon)
    }
  }
  return polygonList
}
 
/**
 * @deprecated use splitPolygonsV2 instead
 */
export async function trySplitPolygons(
  constructionPolyline,
  edges,
  roofs,
  isClosedContructionPolyline
) {
  let result = roofs
  try {
    result = splitPolygons(
      constructionPolyline,
      edges,
      roofs,
      isClosedContructionPolyline
    )
  } catch (error) {
    console.error('An error occurred:', error)
  } finally {
    return result
  }
}
 
/**
 * @param {Array<Polygon>} polygons - polygons to split
 * @returns {Array<Polygon>} new polygons
 */
export function splitPolygonsV2(polygons) {
  try {
    const constructionPolygons = polygons.filter(
      (polygon) => polygon.layer === 'construction'
    )
    const edges = generateEdges2D(polygons)
    const intersections = getEdgeIntersections(edges)
    const nodeList = getNodeList(intersections, edges)
    const edgeList = getEdgeListV2(nodeList, intersections, edges)
    const outlines = getOutlineList(nodeList, edgeList, polygons)
    const newPolygons = []
    outlines.forEach((outline) => {
      // check if outline has points that are intersections to determine if it is split/untouched
      const outlineIntersections = []
      let numberOfIntersectionPoints = 0
      outline.forEach((point) => {
        const result = intersections.filter((n) =>
          isAlmostSamePoint2D(point, n.point, mmTolerance)
        )
        if (result.length) {
          numberOfIntersectionPoints++
          outlineIntersections.push(...result)
        }
      })
 
      if (numberOfIntersectionPoints > 0) {
        // split polygons
        let originalPolygonCanditates = []
        let originalPolygon = null
        for (let i = 0; i < polygons.length; i++) {
          const candidate = polygons[i]
          // check if all points are within the candidate
          let pointsInsidePolygon = 0
          for (let j = 0; j < outline.length; j++) {
            const point = outline[j]
            const isInsideCandidate =
              isInsidePolygon(point, candidate.outline) ||
              candidate.outline.findIndex((n) =>
                isAlmostSamePoint2D(point, n, mmTolerance)
              ) >= 0
            if (!isInsideCandidate) {
              break
            }
            pointsInsidePolygon++
          }
          if (pointsInsidePolygon === outline.length) {
            // add to original polygon candidate list if all points are inside
            originalPolygonCanditates.push(candidate)
          }
        }
 
        if (
          originalPolygonCanditates.length === 1 &&
          originalPolygonCanditates[0].layer === 'construction'
        ) {
          // construction polygon outside other roofs
          // we cannot project the outline to the construction polygon
          const candidate = originalPolygonCanditates[0]
          let intersectedEdges = {}
          outlineIntersections.forEach((intersection) => {
            const edge1 = edges[intersection.edge_index_1]
            const edge2 = edges[intersection.edge_index_2]
 
            for (let i = 0; i < edge1.belongsTo.length; i++) {
              if (edge1.belongsTo[i].polygonId === candidate.id) {
                if (!intersectedEdges[edge2.id]) {
                  intersectedEdges[edge2.id] = {
                    count: 0,
                    edge: edge2,
                  }
                }
                intersectedEdges[edge2.id].count++
                break
              }
            }
 
            for (let i = 0; i < edge2.belongsTo.length; i++) {
              if (edge2.belongsTo[i].polygonId === candidate.id) {
                if (!intersectedEdges[edge1.id]) {
                  intersectedEdges[edge1.id] = {
                    count: 0,
                    edge: edge1,
                  }
                }
                intersectedEdges[edge1.id].count++
                break
              }
            }
          })
 
          const commmonEdgeId = Object.keys(intersectedEdges).find(
            (edgeId) =>
              intersectedEdges[edgeId].count === numberOfIntersectionPoints
          )
 
          if (commmonEdgeId) {
            const edge = intersectedEdges[commmonEdgeId].edge
            const parentPolygons = edge.belongsTo.map(
              (element) => element.polygon
            )
            parentPolygons.sort(
              (a, b) => calculateArea(b.outline) - calculateArea(a.outline)
            )
            if (Math.abs(edge.outline[0].z - edge.outline[1].z) < mmTolerance) {
              // edge is flat horizontally, create a flat polygon to project to
              const flatOutline = parentPolygons[0].outline.map((point) => {
                return {
                  x: point.x,
                  y: point.y,
                  z: edge.outline[0].z,
                }
              })
              const flatPolygon = new Polygon(flatOutline, 'roof')
              updateComputedGeometryPolygon(flatPolygon)
              originalPolygon = flatPolygon
            } else {
              originalPolygon = parentPolygons[0]
            }
          }
        } else {
          originalPolygonCanditates = originalPolygonCanditates.filter(
            (candidate) => !constructionPolygons.includes(candidate)
          )
          // sort candidates by highest average height. Relevant for cases where there is multiple candidates
          originalPolygonCanditates.sort((a, b) => {
            const getAverageHeight = (outline) => {
              let totalHeight = 0
              outline.forEach((point) => {
                totalHeight += point.z
              })
              return totalHeight / outline.length
            }
            return getAverageHeight(b.outline) - getAverageHeight(a.outline)
          })
 
          // Preference for highest polygon average height as original polygon
          originalPolygon = originalPolygonCanditates[0]
        }
 
        const normalVector = originalPolygon
          ? originalPolygon.normalVector
          : new Point(0, 0, 1)
        const referencePoint = originalPolygon
          ? originalPolygon.flatOutline[0]
          : new Point(0, 0, defaultBaseHeight)
        // vertically project each point to original polygon
        outline.forEach((p) => {
          const zValue = verticalProjectionOnPlane(
            p,
            normalVector,
            referencePoint
          ).z
          // set 0 as minimum z value
          p.z = Math.max(zValue, 0)
        })
      }
 
      // check if there is an existing polygon with the same outline
      const polygon = polygons.find((polygon) =>
        polygonsHaveSame2DOutline(outline, polygon.outline)
      )
      if (polygon && !constructionPolygons.includes(polygon)) {
        newPolygons.push(polygon)
      } else {
        const newPolygon = new Polygon(outline, 'roof')
        if (polygon && !constructionPolygons.includes(polygon)) {
          newPolygons.push(polygon)
        } else {
          newPolygons.push(newPolygon)
        }
      }
    })
    // filter out polygons that will cause errors
    const validPolygons = []
    newPolygons.forEach((polygon) => {
      try {
        updateComputedGeometryPolygon(polygon)
        validPolygons.push(polygon)
      } catch (error) {
        console.error(error, polygon)
      }
    })
    return validPolygons
  } catch (error) {
    console.error(error)
    return polygons
  }
}
 
/**
 * @deprecated use splitPolygonsV2 instead
 */
export async function splitPolygons(
  constructionPolyline,
  edges,
  roofs,
  isClosedContructionPolyline
) {
  constructionPolyline.outline.forEach((p) => {
    let supportRoof = roofs.find((roof) => isInsidePolygon(p, roof.outline))
    if (supportRoof) {
      p.z = verticalProjectionOnPlane(
        p,
        supportRoof.normalVector,
        supportRoof.flatOutline[0]
      ).z
    } else {
      p.z = defaultBaseHeight
    }
  })
 
  isClosedContructionPolyline = isClosedContructionPolyline ? 1 : 0
  //1. find intersection between constructionPolyline and edges
  const roofEdge = edges.filter((e) => e.layer == 'roof')
  let intersections = getIntersections(
    constructionPolyline,
    roofEdge,
    isClosedContructionPolyline
  )
  //2. gather all nodes+intersection in a list[[x,y],[x,y]]
  const nodeList = getNodeList(intersections, roofEdge, constructionPolyline)
  //3. generate all edges not cut, those cut and those from construction polyline
  const edgeList = getEdgeList(
    nodeList,
    intersections,
    roofEdge,
    constructionPolyline,
    isClosedContructionPolyline
  )
  //4. run planar-face-discovery to get all cycles and rebuild our polygons
  const outlineList = getOutlineList(nodeList, edgeList, roofs)
  const polygonList = []
  for (let k = 0; k < outlineList.length; k++) {
    //check if roof with same outline already exist:
    let roof = roofs.find((roof) =>
      polygonsHaveSame2DOutline(outlineList[k], roof.outline)
    )
    if (roof) {
      polygonList.push(roof)
    } else {
      let newRoof = new Polygon(outlineList[k], 'roof')
      polygonList.push(newRoof)
    }
  }
  return polygonList
}
 
export function getIntersections(
  constructionPolyline,
  edges,
  isClosedContructionPolyline = 0
) {
  let intersections = []
  const polylineLength = constructionPolyline.outline.length
  for (let k = 0; k < polylineLength - 1 + isClosedContructionPolyline; k++) {
    const segStart = constructionPolyline.outline[k]
    const segEnd = constructionPolyline.outline[(k + 1) % polylineLength]
    for (let j = 0; j < edges.length; j++) {
      const edgeStart = edges[j].outline[0]
      const edgeEnd = edges[j].outline[1]
      const inters = getIntersectionSegmentWithParams(
        segStart,
        segEnd,
        edgeStart,
        edgeEnd
      )
      inters.forEach((inter) => {
        intersections.push({
          polylineIndex: k,
          edgeIndex: j,
          polylineParam: inter.param1,
          edgeParam: inter.param2,
          point: inter.point,
        })
      })
    }
  }
  intersections = intersections.filter(
    (inter) =>
      inter.polylineParam >= 0 &&
      inter.polylineParam <= 1 &&
      inter.edgeParam >= 0 &&
      inter.edgeParam <= 1
  )
  return intersections
}
 
/**
 *
 * @param {Array<edge>} edges
 * @returns {Array<point>} intersections
 */
export function getEdgeIntersections(edges) {
  const result = []
  edges.forEach((edge, index) => {
    for (let i = index; i < edges.length; i++) {
      const nextEdge = edges[i]
      // skip check with own edges
      let skipNextEdge = false
      edge.belongsTo.forEach((edgeParent) => {
        nextEdge.belongsTo.forEach((nextEdgeParent) => {
          if (edgeParent.polygonId === nextEdgeParent.polygonId) {
            skipNextEdge = true
          }
        })
      })
 
      if (skipNextEdge) {
        skipNextEdge = false
        continue
      }
      const intersections = getIntersectionSegmentWithParams(
        edge.outline[0],
        edge.outline[1],
        nextEdge.outline[0],
        nextEdge.outline[1]
      )
      intersections.forEach((intersection) => {
        if (
          intersection.param1 >= 0 &&
          intersection.param1 <= 1 &&
          intersection.param2 >= 0 &&
          intersection.param2 <= 1
        ) {
          result.push({
            edge_index_1: index,
            edge_index_2: i,
            edge_param_1: intersection.param1,
            edge_param_2: intersection.param2,
            point: intersection.point,
          })
        }
      })
    }
  })
  return result
}
 
export function getNodeList(intersections, edges, constructionPolyline) {
  let nodeList = []
  edges.forEach((edge) => {
    nodeList.push(edge.outline[0])
    nodeList.push(edge.outline[1])
  })
 
  if (constructionPolyline) {
    constructionPolyline.outline.forEach((p) => {
      const node = nodeList.find((n) => {
        return isAlmostSamePoint2D(p, n, mmTolerance)
      })
      if (!node) {
        nodeList.push(p)
      }
    })
    const polylineLength = constructionPolyline.outline.length
    const polylineStart = nodeList.find((p) => {
      return isAlmostSamePoint2D(
        p,
        constructionPolyline.outline[0],
        mmTolerance
      )
    })
    const polylineEnd = nodeList.find((p) =>
      isAlmostSamePoint2D(
        p,
        constructionPolyline.outline[polylineLength - 1],
        mmTolerance
      )
    )
    constructionPolyline.outline.forEach((p, index) => {
      if (p.z == defaultBaseHeight || !p.z) {
        p.z =
          polylineStart.z +
          (index / (polylineLength - 1)) * (polylineEnd.z - polylineStart.z)
      }
      nodeList.push(p)
    })
  }
 
  intersections.forEach((inter) => {
    nodeList.push(inter.point)
  })
 
  const nodeListClean = []
  for (let k = 0; k < nodeList.length; k++) {
    const node = nodeList[k]
    const newNode = nodeListClean.find((n) => {
      return n && isAlmostSamePoint2D(n, node, mmTolerance)
    })
    if (!newNode) {
      nodeListClean.push(node)
    }
  }
  return nodeListClean
}
 
function getEdgeListSimple(nodeList, edges) {
  //create a list of edge in term of node Index from nodeList
  const edgeList = []
  for (let index in edges) {
    const node_0_index = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(edges[index].outline[0], n, mmTolerance)
    )
    const node_1_index = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(edges[index].outline[1], n, mmTolerance)
    )
    edgeList.push([node_0_index, node_1_index])
  }
 
  const cleanEdgeList = []
  edgeList.forEach((edge) => {
    const cleanEdge = cleanEdgeList.find(
      (cleanEdge) => edge[0] == cleanEdge[0] && edge[1] == cleanEdge[1]
    )
    if (!cleanEdge && edge[0] != edge[1]) {
      cleanEdgeList.push(edge)
    }
  })
  return cleanEdgeList
}
 
export function getEdgeList(
  nodeList,
  intersections,
  edges,
  constructionPolyline,
  isClosedContructionPolyline
) {
  //to find all edges, edges untouched and untouched construction line are first added
  //then we sort intersection according to their ratio within an edge to add cut edges,
  //same operation for construction line.
  const edgeList = []
  let intersectionByEdge = groupBy(intersections, (inter) => {
    return inter.edgeIndex
  })
  let intersectionByPolyline = groupBy(intersections, (inter) => {
    return inter.polylineIndex
  })
  intersectionByEdge = Object.values(intersectionByEdge)
  intersectionByPolyline = Object.values(intersectionByPolyline)
  intersectionByEdge.forEach((intersections) =>
    intersections.sort((a, b) => {
      return a.edgeParam - b.edgeParam
    })
  )
  intersectionByPolyline.forEach((intersections) =>
    intersections.sort((a, b) => {
      return a.polylineParam - b.polylineParam
    })
  )
  //get used and untouched edge from polyline and edges
 
  const polylineUsedIndexes = intersectionByPolyline.map(
    (i) => i[0].polylineIndex
  )
  const edgeUsedIndexes = intersectionByEdge.map((i) => i[0].edgeIndex)
 
  const untouchedEdgeIndexes = [...Array(edges.length).keys()].filter(
    (k) => !edgeUsedIndexes.includes(k)
  )
 
  const untouchedPolylineIndexes = [
    ...Array(
      constructionPolyline.outline.length - 1 + isClosedContructionPolyline
    ).keys(),
  ].filter((k) => !polylineUsedIndexes.includes(k))
 
  //get untouchEdge edge
  untouchedEdgeIndexes.forEach((index) => {
    const node_0_index = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(edges[index].outline[0], n, mmTolerance)
    )
    const node_1_index = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(edges[index].outline[1], n, mmTolerance)
    )
    edgeList.push([node_0_index, node_1_index])
  })
  //get untouchPolyline edge
  untouchedPolylineIndexes.forEach((index) => {
    const length = constructionPolyline.outline.length
    const node_0_index = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(constructionPolyline.outline[index], n, mmTolerance)
    )
    const node_1_index = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(
        constructionPolyline.outline[(index + 1) % length],
        n,
        mmTolerance
      )
    )
    edgeList.push([node_0_index, node_1_index])
  })
  //get touchedEdge edge
  intersectionByEdge.forEach((intersectionOnEdge) => {
    const length = intersectionOnEdge.length
    const node_0_index_start = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(
        edges[intersectionOnEdge[0].edgeIndex].outline[0],
        n,
        mmTolerance
      )
    )
    const node_1_index_start = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(intersectionOnEdge[0].point, n, mmTolerance)
    )
    edgeList.push([node_0_index_start, node_1_index_start])
 
    for (let k = 0; k < length - 1; k++) {
      const node_0_index = nodeList.findIndex((n) =>
        isAlmostSamePoint2D(intersectionOnEdge[k].point, n, mmTolerance)
      )
      const node_1_index = nodeList.findIndex((n) =>
        isAlmostSamePoint2D(
          intersectionOnEdge[(k + 1) % length].point,
          n,
          mmTolerance
        )
      )
      edgeList.push([node_0_index, node_1_index])
    }
 
    const node_0_index_end = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(intersectionOnEdge[length - 1].point, n, mmTolerance)
    )
    const node_1_index_end = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(
        edges[intersectionOnEdge[0].edgeIndex].outline[1],
        n,
        mmTolerance
      )
    )
    edgeList.push([node_0_index_end, node_1_index_end])
  })
  //get touchedPolyline edge
  intersectionByPolyline.forEach((intersectionOnPolyline) => {
    const length = intersectionOnPolyline.length
    const lengthPolyline = constructionPolyline.outline.length
    const node_0_index_start = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(
        constructionPolyline.outline[intersectionOnPolyline[0].polylineIndex],
        n,
        mmTolerance
      )
    )
    const node_1_index_start = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(intersectionOnPolyline[0].point, n, mmTolerance)
    )
    edgeList.push([node_0_index_start, node_1_index_start])
 
    for (let k = 0; k < length - 1; k++) {
      const node_0_index = nodeList.findIndex((n) =>
        isAlmostSamePoint2D(intersectionOnPolyline[k].point, n, mmTolerance)
      )
      const node_1_index = nodeList.findIndex((n) =>
        isAlmostSamePoint2D(
          intersectionOnPolyline[(k + 1) % length].point,
          n,
          mmTolerance
        )
      )
      edgeList.push([node_0_index, node_1_index])
    }
 
    const node_0_index_end = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(
        intersectionOnPolyline[length - 1].point,
        n,
        mmTolerance
      )
    )
    const node_1_index_end = nodeList.findIndex((n) =>
      isAlmostSamePoint2D(
        constructionPolyline.outline[
          (intersectionOnPolyline[0].polylineIndex + 1) % lengthPolyline
        ],
        n,
        mmTolerance
      )
    )
    edgeList.push([node_0_index_end, node_1_index_end])
  })
 
  const cleanEdgeList = []
  edgeList.forEach((edge) => {
    const cleanEdge = cleanEdgeList.find(
      (cleanEdge) => edge[0] == cleanEdge[0] && edge[1] == cleanEdge[1]
    )
    if (!cleanEdge && edge[0] != edge[1]) {
      cleanEdgeList.push(edge)
    }
  })
 
  return cleanEdgeList
}
 
/**
 *
 * @param {Array<point>} nodes
 * @param {Array<point>} intersections
 * @param {Array<edge>} edges
 * @returns {Array<[index1, index2]>} Array of indices indicating which nodes create an edge
 */
function getEdgeListV2(nodes, intersections, edges) {
  const edgeList = []
  const groupedIntersections = {}
  intersections.forEach((intersection) => {
    const { edge_index_1, edge_index_2 } = intersection
    groupedIntersections[edge_index_1] =
      groupedIntersections[edge_index_1] || []
    groupedIntersections[edge_index_2] =
      groupedIntersections[edge_index_2] || []
    groupedIntersections[edge_index_1].push({
      ...intersection,
      param: intersection.edge_param_1,
    })
    groupedIntersections[edge_index_2].push({
      ...intersection,
      param: intersection.edge_param_2,
    })
  })
  Object.values(groupedIntersections).forEach((intersections) =>
    intersections.sort((a, b) => {
      return a.param - b.param
    })
  )
 
  edges.forEach((edge, index) => {
    const isIntersected = groupedIntersections[index] ? true : false
    if (!isIntersected) {
      // untouched edge
      edgeList.push([
        nodes.findIndex((n) =>
          isAlmostSamePoint2D(edge.outline[0], n, mmTolerance)
        ),
        nodes.findIndex((n) =>
          isAlmostSamePoint2D(edge.outline[1], n, mmTolerance)
        ),
      ])
    } else {
      // intersected edge needs to be split into several edges
      const intersections = groupedIntersections[index]
      const tempNodes = [
        edge.outline[0],
        ...intersections.map((intersection) => intersection.point),
        edge.outline[1],
      ]
      for (let i = 0; i < tempNodes.length - 1; i++) {
        edgeList.push([
          nodes.findIndex((n) =>
            isAlmostSamePoint2D(tempNodes[i], n, mmTolerance)
          ),
          nodes.findIndex((n) =>
            isAlmostSamePoint2D(tempNodes[i + 1], n, mmTolerance)
          ),
        ])
      }
    }
  })
 
  const cleanEdgeList = []
  edgeList.forEach((edge) => {
    const cleanEdge = cleanEdgeList.find(
      (cleanEdge) => edge[0] == cleanEdge[0] && edge[1] == cleanEdge[1]
    )
    if (!cleanEdge && edge[0] != edge[1]) {
      cleanEdgeList.push(edge)
    }
  })
 
  return cleanEdgeList
}
 
function forestRecursion(cycleTree) {
  if (cycleTree.children.length > 0) {
    let cycles = cycleTree.children.reduce(function (done, curr) {
      done.push(...forestRecursion(curr))
      return done
    }, [])
    if (cycleTree.cycle.length) {
      cycles.push(cycleTree.cycle)
    }
    return cycles
  } else {
    return [cycleTree.cycle]
  }
}
 
export function getOutlineList(nodeList, edgeList, roofs = []) {
  const mode = 'outline'
  const minX = Math.min(...nodeList.map((n) => n.x))
  const minY = Math.min(...nodeList.map((n) => n.y))
  const nodes = nodeList.map((n) => [n.x - minX, n.y - minY])
  const solver = new PlanarFaceTree()
  const result = solver.discover(nodes, edgeList)
  const cycles = []
  if (mode == 'forest') {
    return result.forest
  }
  for (let k in result.forest) {
    const cycleTree = result.forest[k]
    let cycleArray = forestRecursion(cycleTree)
    cycles.push(...cycleArray)
  }
  let outlines = cycles
    .map((cycle) => {
      return cycle.map((index) => {
        return {
          x: nodeList[index].x,
          y: nodeList[index].y,
          z: nodeList[index].z,
        }
      })
    })
    .filter((outline) => outline.length > 0)
  outlines.forEach((outline) => outline.pop())
 
  //check for existing roofs(for z value)
  outlines = outlines.map((outline) => {
    let roof = roofs.find((roof) =>
      polygonsHaveSame2DOutline(outline, roof.outline)
    )
    if (roof) {
      outline = JSON.parse(JSON.stringify(roof.outline))
    }
    return outline
  })
  return outlines
}
 
function getIntersectionSegmentWithParams(A, B, C, D) {
  A = { ...A, z: 0 }
  B = { ...B, z: 0 }
  C = { ...C, z: 0 }
  D = { ...D, z: 0 }
  const u = substractVector(B, A)
  const v = substractVector(D, C)
  let h, j, M, P
  //A+hu=C+jv
  const u_normal = { x: -u.y, y: u.x, z: 0 }
  const v_normal = { x: -v.y, y: v.x, z: 0 }
  const denom_u = dotProduct(v, u_normal)
  const denom_v = dotProduct(u, v_normal)
  const AB = vectorLength(u)
  const CD = vectorLength(v)
  if (AB < mmTolerance && CD < mmTolerance) {
    if (getDistanceBetweenPoints(A, C) < mmTolerance * 2) {
      return [
        {
          point: A,
          param1: 0.5,
          param2: 0.5,
        },
      ]
    }
  } else if (AB == 0) {
    //let's check if CD go through A
    P = getPointOnLine(A, C, D)
    if (getDistanceBetweenPoints(P, A) < mmTolerance) {
      j = vectorLength(substractVector(C, A)) / CD
      return [
        {
          point: A,
          param1: 0,
          param2: j,
        },
      ]
    }
  } else if (CD == 0) {
    //let's check if AB go through C
    M = getPointOnLine(C, A, B)
    if (getDistanceBetweenPoints(M, C) < mmTolerance) {
      h = vectorLength(substractVector(C, A)) / AB
      return [
        {
          point: C,
          param1: h,
          param2: 0,
        },
      ]
    }
  }
  if (Math.abs(denom_u) / (AB * CD) < 0.01) {
    //u,v parallel
    //let's check if they are close
    //distance from A to CD
    P = getPointOnLine(A, C, D)
    M = getPointOnLine(B, C, D)
    if (
      getDistanceBetweenPoints(A, P) < mmTolerance ||
      getDistanceBetweenPoints(B, M) < mmTolerance
    ) {
      //AB and CD are colinear
      //let's find which point are in the middle
      const intersections = []
      //A between CD?
      if (isPointBetweenSegment(A, C, D)) {
        j = getDistanceBetweenPoints(A, C) / CD
        intersections.push({
          point: A,
          param1: 0,
          param2: j,
        })
      }
      //B between CD
      if (isPointBetweenSegment(B, C, D)) {
        j = getDistanceBetweenPoints(B, C) / CD
        intersections.push({
          point: B,
          param1: 1,
          param2: j,
        })
      }
      //C between AB
      if (isPointBetweenSegment(C, A, B)) {
        h = getDistanceBetweenPoints(A, C) / AB
        intersections.push({
          point: C,
          param1: h,
          param2: 0,
        })
      }
      //D between AB
      if (isPointBetweenSegment(D, A, B)) {
        h = getDistanceBetweenPoints(A, D) / AB
        intersections.push({
          point: D,
          param1: h,
          param2: 1,
        })
      }
      return intersections
    }
    return []
  }
  j = dotProduct(substractVector(A, C), u_normal) / denom_u
  h = dotProduct(substractVector(C, A), v_normal) / denom_v
  if (j < 0 || j > 1 || h < 0 || h > 1) {
    return []
  }
  const point = addVector(A, multiplyVector(h, u))
  point.z = C.z + j * (D.z - C.z)
  return [
    {
      point,
      param1: h,
      param2: j,
    },
  ]
}