All files / src/objects/derivedState updateComputedGeometryPolygon.js

0% Statements 0/139
0% Branches 0/51
0% Functions 0/22
0% Lines 0/126

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import {
  meanVector,
  substractVector,
  multiplyVector,
  addVector,
  normalizeVector,
} from '../../vector'
import {
  verticalProjectionOnPlane,
  inclineWithNormalVector,
  directionWithNormalVector,
  isClockWise,
  calculateArea,
  getConcaveOutline,
  normalizedVectorTowardInsideAngle,
  isAlmostSamePoint2D,
} from '../../geometry'
import { maximumGapLimit, mmTolerance } from '../../config'
import { SVD } from 'svd-js'
import { updateMarginOutlinePolygon } from './AddMargin'
 
//This function calculate derived field from polygon outline and margin outline
export function updateComputedGeometryState(state) {
  state.polygons.forEach((polygon) => {
    updateComputedGeometryPolygon(polygon)
  })
  return state
}
export function updateOutlineFromInclineDirection(
  incline,
  direction,
  outline,
  initialAverageHeight,
  isRoofOnRoof = false
) {
  const newNormalVector = {}
  newNormalVector.x =
    Math.sin((incline * Math.PI) / 180) * Math.sin((direction * Math.PI) / 180)
  newNormalVector.y =
    Math.sin((incline * Math.PI) / 180) * Math.cos((direction * Math.PI) / 180)
  newNormalVector.z = Math.cos((incline * Math.PI) / 180)
  let meanPoint = meanVector(outline)
  meanPoint.z = initialAverageHeight
  let newOutline = outline.map((p) => {
    return verticalProjectionOnPlane(p, newNormalVector, meanPoint)
  })
  //if some points are with negative altitude, we offset the whole roof
  let altitudeOffset
  let minAltitude = Math.min(...outline.map((p) => p.z))
  let maxAltitude = Math.max(...outline.map((p) => p.z))
  let newMinAltitude = Math.min(...newOutline.map((p) => p.z))
  let newMaxAltitude = Math.max(...newOutline.map((p) => p.z))
  if (isRoofOnRoof && maxAltitude != 0) {
    altitudeOffset = newMaxAltitude - maxAltitude
  } else {
    altitudeOffset = newMinAltitude - minAltitude
  }
  newOutline.forEach((p) => (p.z -= altitudeOffset))
 
  //if some points are with altitude>50000, we limit those points
  newOutline.forEach((p) => (p.z = Math.max(0, Math.min(p.z, 50000))))
 
  return newOutline
}
export function updateComputedGeometryPolygon(polygon) {
  if (!['roof', 'obstacle', 'moduleField'].includes(polygon.layer)) {
    return polygon
  }
  let newOutline = [...polygon.outline]
  if (
    newOutline.length > 0 &&
    isAlmostSamePoint2D(newOutline[0], newOutline[newOutline.length - 1], 10)
  ) {
    console.log(
      'Outline warning: first and last points of outline not far enough:',
      newOutline
    )
    newOutline.pop()
  }
  newOutline = calculateValidOutlineFromPolygon(newOutline)
 
  if (newOutline.length < 3) {
    throw new Error('outline not valid')
  }
  polygon.outline = newOutline
  const {
    projectedOutline,
    maximumGap,
    normalVector,
    meanPoint,
    incline,
    direction,
  } = calculateBestFittingPlanePolygon(polygon.outline)
  polygon.flatOutline = projectedOutline
  polygon.maximumGap = maximumGap
  polygon.isFlat = maximumGap < maximumGapLimit
  polygon.normalVector = normalVector
  polygon.meanPoint = meanPoint
  polygon.incline = incline
  polygon.direction = direction
  polygon.area = calculateArea(polygon.flatOutline) / 1000000
  polygon.isClockwise = isClockWise(polygon.outline)
  polygon = updateMarginOutlinePolygon(polygon)
  if (polygon.layer == 'moduleField') {
    let trimedOutline = []
    if (polygon.panels.length > 0) {
      trimedOutline = getConcaveOutline(
        polygon.panels,
        polygon.panels[0].outline
      )
      if (polygon.roof) {
        trimedOutline = trimedOutline.map((p) => {
          return {
            x: p.x,
            y: p.y,
            z: verticalProjectionOnPlane(
              p,
              polygon.roof.normalVector,
              polygon.roof.flatOutline[0]
            ).z,
          }
        })
      }
    }
    polygon.trimedOutline = trimedOutline
  }
  return polygon
}
export function calculateValidOutlineFromPolygon(outline) {
  //check if two nodes are same
  outline = [...outline]
  const nodeIndexToSplit = []
  const nodesToRemove = []
  for (let k = 0; k < outline.length - 1; k++) {
    for (let i = k + 1; i < outline.length; i++) {
      if (isAlmostSamePoint2D(outline[k], outline[i], 2 * mmTolerance)) {
        if (i == k + 1) {
          nodesToRemove.push(i)
        } else {
          nodeIndexToSplit.push([k, i])
        }
      }
    }
  }
 
  for (let coupleToSplit of nodeIndexToSplit) {
    const A = outline[(coupleToSplit[0] - 1 + outline.length) % outline.length]
    const B = outline[coupleToSplit[0]]
    const C = outline[(coupleToSplit[0] + 1) % outline.length]
    const D = outline[(coupleToSplit[1] - 1 + outline.length) % outline.length]
    const E = outline[coupleToSplit[1]]
    const F = outline[(coupleToSplit[1] + 1) % outline.length]
    let u = normalizedVectorTowardInsideAngle(A, B, C)
    let v = normalizedVectorTowardInsideAngle(D, E, F)
 
    outline[coupleToSplit[0]] = {
      ...outline[coupleToSplit[0]],
      ...addVector(multiplyVector(-mmTolerance, u), B),
      z: outline[coupleToSplit[0]].z,
    }
    outline[coupleToSplit[1]] = {
      ...outline[coupleToSplit[1]],
      ...addVector(multiplyVector(mmTolerance, v), E),
      z: outline[coupleToSplit[1]].z,
    }
  }
  for (let index = nodesToRemove.length - 1; index >= 0; index--) {
    outline.splice(nodesToRemove[index], 1)
  }
  if (nodeIndexToSplit.length) {
    console.log(
      'two nodes of the outline are too close one to another:',
      nodeIndexToSplit,
      outline,
      ' - tolerance:',
      2 * mmTolerance,
      'mm'
    )
  }
  if (nodesToRemove.length) {
    console.log(
      'two consecutive nodes of the outline are too close one to another:',
      nodesToRemove,
      outline,
      ' - tolerance:',
      2 * mmTolerance,
      'mm'
    )
  }
  return outline
}
 
export function calculateBestFittingPlanePolygon(fullOutline) {
  if (fullOutline.length < 3 || fullOutline.some((p) => isNaN(p.z))) {
    return null
  }
  let outline = fullOutline
  if (outline.length < 3) {
    outline = fullOutline
  }
  const meanPoint = meanVector(outline)
 
  const centralizedOutline = outline.map((p) => substractVector(p, meanPoint))
  const a = centralizedOutline.map((p) => [p.x, p.y, p.z])
 
  let { v, q } = SVD(a, false)
  let vt = [[], [], []]
  for (let i in v) {
    for (let j in v[i]) {
      vt[j][i] = v[i][j]
    }
  }
  v = vt
  let normalVectorIndex = 0
  for (let index in q) {
    if (!isNaN(q[index]) && q[index] < q[normalVectorIndex]) {
      normalVectorIndex = index
    }
  }
  let normalVectorArray = v[normalVectorIndex]
  let normalVector = { x: 0, y: 0, z: 1 }
  if (!normalVectorArray || isNaN(normalVectorArray[0])) {
    console.error(
      'no normalVector found for:q',
      q,
      'v',
      v,
      'meanPoint',
      meanPoint,
      'a',
      a,
      'normal index',
      normalVectorIndex,
      'v',
      v,
      'outline',
      outline
    )
  } else {
    normalVector.x = normalVectorArray[0]
    normalVector.y = normalVectorArray[1]
    normalVector.z = normalVectorArray[2]
  }
 
  if (normalVector.z < 0) {
    normalVector = multiplyVector(-1, normalVector)
  }
  //gard to prevent crazy inclinaison roof
  if (normalVector.z < 0.1) {
    normalVector = { x: 0, y: 0, z: 1 }
  }
  //plane equation is ax+by+cz=d
  //where normalvector=(a,b,c)
  //let's calculate d knowing our plane passes by the point with the
  const projectedOutline = fullOutline.map((p) => {
    const proj = verticalProjectionOnPlane(p, normalVector, meanPoint)
    return {
      x: proj.x,
      y: proj.y,
      z: Math.max(0, Math.min(50000, proj.z)),
    }
  })
  const gaps = fullOutline.map((p, index) => {
    let gap = Math.abs(p.z - projectedOutline[index].z)
    return gap
  })
  const maximumGap = Math.max(...gaps)
  //let's find the the biggest positive gap to reposition the plan passing by this point in order to have an always visible plane
 
  let biggestPositivGap = Math.max(
    ...fullOutline.map((p, index) => p.z - projectedOutline[index].z)
  )
  projectedOutline.forEach((p) => (p.z += biggestPositivGap))
 
  //if less than 3 unselected node=>flat roof on top.
  const biggestAbsoluteGap = Math.max(
    ...fullOutline.map((p, index) => Math.abs(p.z - projectedOutline[index].z))
  )
  for (let index in fullOutline) {
    let p = fullOutline[index]
    let hasWarning =
      Math.abs(p.z - projectedOutline[index].z) == biggestAbsoluteGap &&
      biggestAbsoluteGap > maximumGapLimit
    //I add warning if hasWarning and I remove it if shift is smaller then maxGapLimit. Otherwise, I do not change anything
    p.hasWarning = hasWarning
      ? hasWarning
      : Math.abs(p.z - projectedOutline[index].z) < maximumGapLimit
      ? false
      : p.hasWarning
  }
 
  //set warning to the furthest
  const incline = inclineWithNormalVector(normalVector)
  const direction = directionWithNormalVector(normalVector)
  return {
    projectedOutline,
    maximumGap,
    normalVector,
    meanPoint,
    incline,
    direction,
    gaps,
  }
}