1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| Coordinates = {
CARTESIAN: 0x01,
SPHERICAL: 0x02,
/** Converts some coordinates from one system to another. */
convert: function(coordinates, context, target) {
// Only the target might be defined. In that case, it is passed as the first parameter.
if(!target) {
if(!context) {
throw new Error("Targeted space required.");
}
target = context;
context = Coordinates.CARTESIAN;
}
var result = null;
if(target != context) {
// Working with 3 dimensions.
while(coordinates.length < 3) {
coordinates.push(0);
}
switch(context) {
case Coordinates.CARTESIAN:
switch(target) {
case Coordinates.SPHERICAL:
with(Math) {
var x = coordinates[0];
var y = coordinates[1];
var z = coordinates[2];
var rho = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
var phi = acos(z / rho) || 0;
var theta = acos(x / sqrt(pow(x, 2) + pow(y, 2))) || 0;
if(y < 0) {
theta = 2 * PI - theta;
}
result = [rho, phi, theta];
}
break;
}
break;
case Coordinates.SPHERICAL:
switch(target) {
case Coordinates.CARTESIAN:
with(Math) {
var rho = coordinates[0];
var phi = coordinates[1];
var theta = coordinates[2];
var x = rho * sin(phi) * cos(theta);
var y = rho * sin(phi) * sin(theta);
var z = rho * cos(phi);
result = [x, y, z];
}
break;
}
break;
}
}
else {
throw new Error("Conversion is to be made between two diferent spaces.");
}
return result;
}
} |
Partager