home *** CD-ROM | disk | FTP | other *** search
/ Late Night VRML 2.0 with Java CD-ROM / code.zip / Ch15 / utility / Vec3.java < prev   
Encoding:
Java Source  |  1997-02-05  |  2.0 KB  |  69 lines

  1. // Class for handling 3-dimensional vectors
  2.  
  3. // Written by Bernie Roehl, November 1996
  4.  
  5. package utility;
  6.  
  7. import java.util.*;
  8.  
  9. public class Vec3 {
  10.     protected float x, y, z;
  11.     
  12.     public float getX() { return x; }
  13.     public float getY() { return y; }
  14.     public float getZ() { return z; }
  15.  
  16.     public Vec3() { x = y = z = 0; }
  17.  
  18.     public Vec3(float xv, float yv, float zv) { x = xv;  y = yv;  z = zv; }
  19.  
  20.     public Vec3(Float xv, Float yv, Float zv) {
  21.        this(xv.floatValue(), yv.floatValue(), zv.floatValue());
  22.     }
  23.  
  24.     public Vec3(Vec3 value) { x = value.x;  y = value.y;  z = value.z; }
  25.  
  26.     public Vec3(StringTokenizer s) {
  27.         x = new Float(s.nextToken()).floatValue();
  28.         y = new Float(s.nextToken()).floatValue();
  29.         z = new Float(s.nextToken()).floatValue();
  30.     }
  31.  
  32.     public String toString() { return x + " " + y + " " + z; }
  33.  
  34.     public float dot(Vec3 v) { return (float) (x * v.x + y * v.y + z * v.z); }
  35.  
  36.     public float mag() { return (float) Math.sqrt(x * x + y * y + z * z); }
  37.  
  38.     public Vec3 normalize() {
  39.         float m = mag();
  40.         return new Vec3(x /= m, y /= m, z /= m);
  41.     } 
  42.  
  43.     public Vec3 add(Vec3 v) { return new Vec3(x + v.x, y + v.y, z + v.z); }
  44.  
  45.     public Vec3 sub(Vec3 v) { return new Vec3(x - v.x, y - v.y, z - v.z); }
  46.  
  47.     public Vec3 scale(float s) { return new Vec3(x * s, y * s, z * s); }
  48.  
  49.     public Vec3 cross(Vec3 v) {
  50.         Vec3 result = new Vec3();
  51.         result.x = z * v.y - y * v.z;
  52.         result.y = x * v.z - z * v.x;
  53.         result.z = y * v.x - x * v.y;
  54.         return result;
  55.     }
  56.  
  57.     public float angle(Vec3 v) {
  58.         float mag_product = mag() * v.mag();
  59.         if (mag_product == 0.0f)
  60.             return 0.0f;
  61.         float cos_theta = dot(v) / mag_product;
  62.         if (cos_theta <= -1.0)
  63.             return (float) Math.PI;
  64.         if (cos_theta >= 1.0)
  65.             return 0.0f;
  66.         return (float) Math.acos(cos_theta);
  67.     }
  68. }
  69.