CoolFace
Apppublic

Omnibus-archive/sim-1

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
utils.js85 linesDownload Raw Back to src
1//2//3//4function wrap (value, min, max) {5  if (value > max)6    value = min;7 8  if (value < min)9    value = max;10 11  return value;12}13 14 15//16//17//18function isNumberBetween (value, min, max) {19  return value >= min && value <= max;20}21 22 23//24// adapted from https://github.com/lovasoa/graham-fast25// licensed under the MIT license26//27function polygonUnion(poly1, poly2) {28  let points = [];29 30  for (let i = 0; i < poly1.length; i++)31    points.push([poly1[i].x, poly1[i].y]);32 33  for (let i = 0; i < poly2.length; i++)34    points.push([poly2[i].x, poly2[i].y]);35 36  // The enveloppe is the points themselves37  if (points.length <= 3)38    return points;39  40  // Find the pivot41  let pivot = points[0];42 43  for (let i = 0; i < points.length; i++)44    if (points[i][1] < pivot[1] || (points[i][1] === pivot[1] && points[i][0] < pivot[0]))45      pivot = points[i];46 47  // Attribute an angle to the points48  for (let i = 0; i < points.length; i++)49    points[i]._graham_angle = Math.atan2(points[i][1] - pivot[1], points[i][0] - pivot[0]);50 51  points.sort(function(a, b){52    return a._graham_angle === b._graham_angle ? a[0] - b[0] : a._graham_angle - b._graham_angle;53  });54 55 56  // Adding points to the result if they "turn left"57  let result = [points[0]];58  let len = 1;59 60  for (let i = 1; i < points.length; i++) {61    let a = result[len-2];62    let b = result[len-1];63    let c = points[i];64 65    while ((len === 1 && b[0] === c[0] && b[1] === c[1]) || (len > 1 && (b[0]-a[0]) * (c[1]-a[1]) <= (b[1]-a[1]) * (c[0]-a[0]))) {66      len--;67      b = a;68      a = result[len-2];69    }70 71    result[len++] = c;72  }73 74  result.length = len;75  76  // create new polygon object77  let polygon = [];78 79  for (let i = 0; i < result.length; i++)80    polygon.push({ x: result[i][0], y: result[i][1] });81 82  return polygon;83}84 85export { wrap, isNumberBetween, polygonUnion };