/**
   * Determine closest point on hyperbolic arm to a point pt
   *
   * @param pt : point
   * @return t value for closest point; not necessarily within clipped range
   */
  public double closestPointTo(FPoint2 pt) {

    final boolean db = false;

    pt = toCurveSpace(pt, null);

    double U = B + 1;
    double V = -pt.y;
    double W = B * pt.x;

    Polyn p =
        new Polyn( //
            B * U * U, //
            2 * B * U * V, //
            B * V * V + A * U * U - W * W, //
            2 * A * U * V, //
            A * V * V //
            );

    if (db) Streams.out.println("closestPointTo, pt=" + pt + "\n" + p);
    double ret = 0;

    try {
      DArray r = new DArray();

      if (Math.abs(p.c(0)) < 1e-5) r.addDouble(0);
      else p.solve(r);

      if (r.isEmpty()) {
        throw new FPError("can't find closest point, poly=\n" + p);
      }

      double bestDist = 0;

      for (int i = 0; i < r.size(); i++) {
        double t = r.getDouble(i);
        FPoint2 apt = calcPoint(t);
        double dist = apt.distance(pt);
        if (i == 0 || dist < bestDist) {
          bestDist = dist;
          ret = t;
        }
      }
    } catch (FPError e) {
      Tools.warn("caught FPError");
      //      Streams.out.println("caught:\n" + e);
      ret = (this.minParameter() + this.maxParameter()) * .5;
    }

    return ret;
  }
  /**
   * Calculate dx, dy values for a point
   *
   * @param t : parameter
   * @param delta : where to store dx, dy values
   */
  private void calcTangentAt(double t, FPoint2 delta) {
    final boolean db = false;
    if (db) {
      System.out.println("calcTangentAt " + t);
    }
    t = toInt(t);
    if (db) {
      System.out.println(" flipped=" + flipped() + " ti=" + t);
    }
    double a = toW2.get(0, 0), b = toW2.get(0, 1), c = toW2.get(0, 2);
    double d = toW2.get(1, 0), e = toW2.get(1, 1), f = toW2.get(1, 2);
    if (db) {
      System.out.println(" a=" + a + " b=" + b + " c=" + c + "\n d=" + d + " e=" + e + " f=" + f);
    }
    double rt = Polyn.sqrt(A + B * t * t);
    double dx = a * B * t / rt + b;
    double dy = d * B * t / rt + e;

    if (flipped()) {
      dx = -dx;
      dy = -dy;
    }
    if (db) {
      System.out.println(" dx=" + dx + "\n dy=" + dy);
      System.out.println(" ratio=" + (dy / dx));
    }
    delta.setLocation(dx, dy);
  }
 /**
  * Determine where point is relative to arm
  *
  * @param x :
  * @param y : point to test
  * @return an integer, which is 0 if it's on the arm, 1 if it's to the right of the arm, -1 if
  *     it's to the left of the arm
  */
 public int testPoint(double x, double y) {
   final FPoint2 ept = new FPoint2(), eps = new FPoint2();
   eps.setLocation(x, y);
   toCurveSpace(eps, ept);
   FPoint2 as = calcPointInArmSpace(toExt(ept.y));
   int out = 0;
   double diff = ept.x - as.x;
   if (diff > 0) {
     out = 1;
   } else if (diff < 0) {
     out = -1;
   }
   if (flipped()) {
     out = -out;
   }
   return out;
 }
  /**
   * Construct a hyperbola
   *
   * @param f1 FPoint2 : first focus
   * @param f2 FPoint2 : second focus
   * @param interceptDistance : closest distance of point on arm to f1
   */
  public Hyperbola(FPoint2 f1, FPoint2 f2, double interceptDistance) {
    double fDist = f2.distance(f1);
    if (!(interceptDistance >= 0 && interceptDistance <= fDist))
      throw new FPError(
          "Hyperbola construction: icept="
              + Tools.f(interceptDistance)
              + " of max "
              + Tools.f(fDist)
              + "\n f1="
              + f1
              + " f2="
              + f2);

    double ratio = 0;
    if (fDist > 0) {
      ratio = interceptDistance / fDist;
    }
    FPoint2 pt = FPoint2.interpolate(f1, f2, ratio);
    construct(f1, f2, pt);
  }
  /**
   * Test program for Hyperbola class
   *
   * @param args String[]
   */
  public static void main(String[] args) {

    final double[] pts = { //
      100, 0, -100, 0, 75, 20,

      //  120, 30, -100, -10, 70, 50,
    };

    for (int i = 0; i < pts.length; i += 6) {
      try {
        Hyperbola h =
            new Hyperbola(
                new FPoint2(pts[i + 0], pts[i + 1]),
                new FPoint2(pts[i + 2], pts[i + 3]),
                new FPoint2(pts[i + 4], pts[i + 5]));
        System.out.println("Constructed:\n" + h);

        for (double t = -50; t <= 50; t += 10) {

          FPoint2 pt = h.calcPoint(t);

          FPoint2 pt2 = new FPoint2(pt.x, pt.y + 5);

          double tClosest = h.closestPointTo(pt2);

          System.out.println("t=" + Tools.f(t) + " pt=" + pt + " closest=" + tClosest);

          if (t == -20) {
            for (double t2 = tClosest - .1; t2 <= tClosest + .1; t2 += .01) {
              FPoint2 pt3 = h.calcPoint(t2);
              Streams.out.println("t2=" + t2 + " dist=" + pt3.distance(pt2));
            }
          }
        }

      } catch (TBError e) {
        System.out.println(e.toString());
      }
    }
  }
  private void construct(EdDisc a, EdDisc b) {
    this.discA = a;
    this.discB = b;

    if (EdDisc.partiallyDisjoint(a, b)) {

      // if (!UHullMain.oldBitanMethod())
      {
        final boolean db = false;

        if (a.getRadius() == b.getRadius()) {
          FPoint2 oa = a.getOrigin(), ob = b.getOrigin();

          FPoint2 n = new FPoint2(-(ob.y - oa.y), ob.x - oa.x);
          n.normalize();
          n.x *= a.getRadius();
          n.y *= a.getRadius();
          seg = new DirSeg(FPoint2.add(oa, n, null), FPoint2.add(ob, n, null));
          return;
        }

        boolean swap = a.getRadius() > b.getRadius();

        if (swap) {
          b = (EdDisc) discA;
          a = (EdDisc) discB;
        }

        if (db && T.update())
          T.msg(
              "BiTangent construct, arad="
                  + Tools.f(a.getRadius())
                  + " brad="
                  + Tools.f(b.getRadius())
                  + " swap="
                  + swap
                  + " origin.a="
                  + T.show(a.getOrigin()));

        FPoint2 oa = a.getOrigin();
        FPoint2 ob = b.getOrigin();

        double U = ob.x, V = ob.y;
        double A = oa.x - U, B = oa.y - V;
        double R1 = a.getRadius();
        double R2 = b.getRadius();
        double S = R2 - R1;

        double x1, y1, x2, y2;
        x1 = A;
        y1 = B;

        boolean secondRoot;
        boolean altSlope = Math.abs(B) < Math.abs(A);
        if (!altSlope) {

          double C1 = S * S / B, C2 = -A / B;
          double qA = 1 + C2 * C2, qB = 2 * C1 * C2, qC = C1 * C1 - S * S;
          double root = Math.sqrt(qB * qB - 4 * qA * qC);
          x2 = (-qB - root) / (2 * qA);
          y2 = C1 + C2 * x2;

          secondRoot = MyMath.sideOfLine(x2, y2, A, B, 0, 0) < 0;

          if (swap ^ secondRoot) {
            x2 = (-qB + root) / (2 * qA);
            y2 = C1 + C2 * x2;
          }
        } else {

          double C1 = S * S / A, C2 = -B / A;
          double qA = 1 + C2 * C2, qB = 2 * C1 * C2, qC = C1 * C1 - S * S;
          double root = Math.sqrt(qB * qB - 4 * qA * qC);
          y2 = (-qB - root) / (2 * qA);
          x2 = C1 + C2 * y2;

          secondRoot = MyMath.sideOfLine(x2, y2, A, B, 0, 0) < 0;

          if (swap ^ secondRoot) {
            y2 = (-qB + root) / (2 * qA);
            x2 = C1 + C2 * y2;
          }
        }
        // now grow both discs back to r1, r2

        double tx = U;
        double ty = V;

        //        if (S == 0) {
        //          FPoint2 unit = new FPoint2(-A, -B);
        //          if (swap) {
        //            unit.x = -unit.x;
        //            unit.y = -unit.y;
        //          }
        //          unit.normalize();
        //          tx += -unit.y * R1;
        //          ty += unit.x * R1;
        //        } else
        {
          double F = R1 / S;
          tx += x2 * F;
          ty += y2 * F;
        }

        if (db && T.update())
          T.msg("adding offset to both points: " + tx + ", " + ty + T.show(new FPoint2(tx, ty)));
        x1 += tx;
        y1 += ty;
        x2 += tx;
        y2 += ty;
        FPoint2 p1 = new FPoint2(x1, y1);
        FPoint2 p2 = new FPoint2(x2, y2);
        if (swap) {
          FPoint2 tmp = p1;
          p1 = p2;
          p2 = tmp;
        }

        seg = new DirSeg(p1, p2);

        if (db && T.update())
          T.msg(
              "swap="
                  + swap
                  + " altSlope="
                  + altSlope
                  + " secondRoot="
                  + secondRoot
                  + " dirseg="
                  + EdSegment.showDirected(p1, p2));
      }
      //      else {
      //
      //        double th = calcTheta(a, b);
      //        LineEqn eqn = new LineEqn(a.polarPoint(th + Math.PI / 2), th);
      //        double ta = eqn.parameterFor(a.getOrigin());
      //        double tb = eqn.parameterFor(b.getOrigin());
      //        seg = new DirSeg(eqn.pt(ta), eqn.pt(tb));
      //
      //      }
    }
  }
  public void render(Color c, int stroke, int markType) {
    final boolean db = false;
    // Get array of visible segments.  If no such array exists,
    // use default.
    DArray vseg = visSeg;
    boolean dashed = false;

    //    if (step == 0) {
    double step = renderStep();
    //    }
    //    vp V = TestBed.view();

    if (db) Streams.out.println(" step=" + step);

    // plot each visible segment

    for (int seg = 0; seg < vseg.size(); seg += 2) {
      double t0 = vseg.getDouble(seg + 0), t1 = vseg.getDouble(seg + 1);
      t0 = MyMath.clamp(t0, -500.0, 500.0);
      t1 = MyMath.clamp(t1, -500.0, 500.0);

      // render() expects external parameters.

      double s0 = toExt(t0), s1 = toExt(t1);
      if (s0 > s1) {
        double tmp = s0;
        s0 = s1;
        s1 = tmp;
      }
      FPoint2 p0 = calcPoint(s0), p1 = calcPoint(s1);
      if (db) Streams.out.println(" p0=" + p0 + ", p1=" + p1);
      if (isLine() && !dashed) {
        V.drawLine(p0, p1);
      } else {

        /*
                  if (Math.abs(s0) >= 500
           ||Math.abs(s1) >= 500)
         System.out.println("Rendering "+t0+" to "+t1+" step "+step);
        */
        if (dashed) V.pushStroke(Globals.STRK_RUBBERBAND);
        {
          //          int count = 0;
          boolean first = true;
          for (double t = t0; ; t += step) { // , count++) {
            boolean last = (t >= t1);
            if (last) {
              t = t1;
            }
            calcPointInternal(t, p1);

            if (!p1.isValid()) {
              if (last) {
                break;
              }
              continue;
            }

            if (db) {
              System.out.println(" calcPt " + Tools.f(toExt(t)) + " = " + p1.x + "," + p1.y);
            }
            if (!first) {
              V.drawLine(p0, p1);
              if (false) {
                Tools.warn("highlighting int");
                V.mark(p0);
              }
            }
            if (last) {
              break;
            }
            p0.setLocation(p1);
            first = false;
          }
        }
        if (dashed) V.popStroke();
      }
    }
  }
  /**
   * Constructor
   *
   * @param f1 FPoint2
   * @param f2 FPoint2
   * @param pt FPoint2, or null for bisector
   */
  private void construct(FPoint2 f1, FPoint2 f2, FPoint2 pt) {

    //    userData[LEFT] = new DArray();
    //    userData[RIGHT]  =new DArray();

    final boolean db = false;
    if (db) {
      System.out.println("Hyperbola constructor\n f1=" + f1 + "\n f2=" + f2 + "\n pt=" + pt);
    }
    boolean bisector = (pt == null);
    initializeVisibleSegments();

    // if point on arm is closer to f2 than f1, swap f1 & f2.

    if (!bisector && FPoint2.distanceSquared(f1, pt) > FPoint2.distanceSquared(f2, pt)) {
      flipped = true;
    }

    this.foci[RIGHT] = new FPoint2(f1);
    this.foci[LEFT] = new FPoint2(f2);
    if (!bisector) {
      this.pt = new FPoint2(pt);
    }

    double fociDist = FPoint2.distance(f1, f2);
    if (fociDist == 0) {
      throw new FPError("Hyperbola foci are same point");
    }

    c = fociDist * .5;

    // calculate the translation of the hyperbola away from
    // standard position.

    FPoint2 rFocus = getFocus(0), lFocus = getFocus(1);

    origin = new FPoint2(.5 * (rFocus.x + lFocus.x), .5 * (rFocus.y + lFocus.y));

    // calculate the angle of rotation of the hyperbola away
    // from the standard position.

    double theta = Math.atan2(rFocus.y - lFocus.y, rFocus.x - lFocus.x);

    Matrix fromCenterInW = Matrix.getTranslate(origin, true);
    Matrix rotToE = Matrix.getRotate(-theta);

    toE2 = rotToE;
    Matrix.mult(toE2, fromCenterInW, toE2);
    // calculate inverse

    toW2 = toE2.invert(null);

    //      Matrix toCenterInW = Matrix.translationMatrix(origin, false);
    //      Matrix rotToW = Matrix.getRotate2D(theta);
    //
    //      toW2 = toCenterInW;
    //      Matrix.mult(toW2, rotToW, toW2);
    //      Tools.warn("just invert matrix here");
    //

    if (bisector) {
      valid = true;
    } else {
      // get the arm point in hyperbola space.
      FPoint2 workPt = toE2.apply(pt, null);

      double xs = workPt.x * workPt.x;
      double cs = c * c;

      Polyn q = new Polyn(1, -(cs + xs + workPt.y * workPt.y), cs * xs);
      if (db) {
        System.out.println("a2 quadratic:\n" + q);
      }
      final DArray qsoln = new DArray();
      q.solve(qsoln);
      if (db) {
        Streams.out.println(qsoln);
      }
      double val = q.c(1) * -.5;
      int ql = qsoln.size();
      if (ql >= 1) {
        val = qsoln.getDouble(0);
      }

      // choose the root that is less than c*c.

      if (ql == 2) {
        if (val > qsoln.getDouble(1)) {
          val = qsoln.getDouble(1);
          if (db) {
            System.out.println(" two roots, choosing smaller.");
          }
        }
      }
      if (db) {
        System.out.println(" root chosen=" + val);
      }

      a = Polyn.sqrt(val);
      A = a * a;
      B = A / (c * c - A);
    }
    valid = true;
    if (db) {
      System.out.println(" ==> " + this);
    }
  }