Mega Code Archive
Matrix Utils
//package edu.union;
class FixedPointUtils {
public static final int ONE = 0x10000;
/**
* Convert a float to 16.16 fixed-point representation
* @param val The value to convert
* @return The resulting fixed-point representation
*/
public static int toFixed(float val) {
return (int)(val * 65536F);
}
/**
* Convert an array of floats to 16.16 fixed-point
* @param arr The array
* @return A newly allocated array of fixed-point values.
*/
public static int[] toFixed(float[] arr) {
int[] res = new int[arr.length];
toFixed(arr, res);
return res;
}
/**
* Convert an array of floats to 16.16 fixed-point
* @param arr The array of floats
* @param storage The location to store the fixed-point values.
*/
public static void toFixed(float[] arr, int[] storage)
{
for (int i=0;i> 16));
}
/**
* Divide two fixed-point values.
* @param x
* @param y
* @return
*/
public static int divide (int x, int y) {
long z = (((long) x) << 32);
return (int) ((z / y) >> 16);
}
/**
* Find the sqrt of a fixed-point value.
* @param n
* @return
*/
public static int sqrt (int n) {
int s = (n + 65536) >> 1;
for (int i = 0; i < 8; i++) {
//converge six times
s = (s + divide(n, s)) >> 1;
}
return s;
}
}
class MatrixUtils {
/**
* Returns the transpose of a 4x4 matrix
* @param m The matrix to transpose
* @param result The place to store the transposed matrix
**/
public static void transpose(float[][] m, float[][] result) {
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
result[j][i] = m[i][j];
}
public static void transpose(float[]m, float[] result) {
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
result[j*4+i] = m[i*4+j];
}
/**
* Converts this vector into a normalized (unit length) vector
* Modifies the input parameter
* @param vector The vector to normalize
**/
public static void normalize(float[] vector) {
scalarMultiply(vector, 1/magnitude(vector));
}
/**
* Converts this vector into a normalized (unit length) vector
* Modifies the input parameter
* @param vector The vector to normalize
**/
public static void normalize(int[] vector) {
scalarMultiply(vector, 1/magnitude(vector));
}
/**
* Copy a vector from from
into to
* @param from The source
* @param to The destination
**/
public static void copy(float[] from, float[] to) {
for (int i=0;iModifies the input vector
* @param vector The vector
* @param scalar The scalar
**/
public static void scalarMultiply(float[] vector, float scalar) {
for (int i=0;iModifies the input vector
* @param vector The vector
* @param scalar The scalar
**/
public static void scalarMultiply(int[] vector, int scalar) {
for (int i=0;iModified
**/
public static void homogenize(float[] pt)
{
scalarMultiply(pt, 1/pt[3]);
}
/**
* Pretty print a vector
* @param vec The vector to print
**/
public static void printVector(float[] vec) {
for (int i=0;i