//

import java.awt.*;
import render.*;

public class misc
{
   static public void transform(double xyz[], Matrix m) {
      double x = xyz[0], y = xyz[1], z = xyz[2];
      xyz[0] = m.get(0,0) * x + m.get(0,1) * y + m.get(0,2) * z + m.get(0,3);
      xyz[1] = m.get(1,0) * x + m.get(1,1) * y + m.get(1,2) * z + m.get(1,3);
      xyz[2] = m.get(2,0) * x + m.get(2,1) * y + m.get(2,2) * z + m.get(2,3);
   }

   static public void aimXY(Matrix m, double X[], double Y[]) {
      double Z[] = {0,0,0};
      Vec.normalize(X);
      set(m, 0, X);
      Vec.cross(Y,X,Z);
      Vec.normalize(Z);
      set(m, 2, Z);
      Vec.cross(X,Z,Y);
      Vec.normalize(Y);
      set(m, 1, Y);
   }

   static public void set(Matrix m, int col, double V[]) {
      m.set(0,col, V[0]);
      m.set(1,col, V[1]);
      m.set(2,col, V[2]);
   }

   static public double lerp(double t, double a, double b) {
      return a + t * (b - a);
   }

   static public double clip(double t, double lo, double hi) {
      return Math.max(lo, Math.min(hi, t));
   }

   static double spline(double S[], double t) {
      if (t < 0) return S[1];
      for (int i = 0 ; i < S.length-2 ; i += 2)
         if (t >= S[i] && t < S[i+2])
	    return lerp((t - S[i]) / (S[i+2] - S[i]), S[i+1], S[i+3]);
      return S[S.length-1];
   }

   static public double bias(double a, double b) {
      if (a < .001)
         return 0.;
      else if (a > .999)
         return 1.;
      else if (b < .001)
         return 0.;
      else if (b > .999)
         return 1.;
      else
         return Math.pow(a, Math.log(b) / LOG_HALF);
   }

   static public double gain(double a, double b) {
      double p;

      if (a<.001)
        return 0.;
      else if (a>.999)
         return 1;

      b = (b<.001) ? .0001 : (b>.999) ? .999 : b;
      p = Math.log(1. - b) / LOG_HALF;
      if (a < 0.5)
         return Math.pow(2 * a, p) / 2;
      else
         return 1. - Math.pow(2 * (1. - a), p) / 2;
   }

   static private final double LOG_HALF = Math.log(0.5);

   static int stringWidth(String s, Graphics g) {
      return g.getFontMetrics(g.getFont()).stringWidth(s);
   }
}