1//////////////////////////////////////////////////////////////////////
  2// LibFile: coords.scad
  3//   Coordinate transformations and coordinate system conversions.
  4// Includes:
  5//   include <BOSL2/std.scad>
  6// FileGroup: Math
  7// FileSummary: Conversions between coordinate systems.
  8// FileFootnotes: STD=Included in std.scad
  9//////////////////////////////////////////////////////////////////////
 10
 11
 12// Section: Coordinate Manipulation
 13
 14// Function: point2d()
 15// Synopsis: Convert a vector to 2D. 
 16// Topics: Coordinates, Points
 17// See Also: path2d(), point3d(), path3d()
 18// Usage:
 19//   pt = point2d(p, [fill]);
 20// Description:
 21//   Returns a 2D vector/point from a 2D or 3D vector.  If given a 3D point, removes the Z coordinate.
 22// Arguments:
 23//   p = The coordinates to force into a 2D vector/point.
 24//   fill = Value to fill missing values in vector with.  Default: 0
 25function point2d(p, fill=0) = assert(is_list(p)) [for (i=[0:1]) (p[i]==undef)? fill : p[i]];
 26
 27
 28// Function: path2d()
 29// Synopsis: Convert a path to 2D. 
 30// SynTags: Path
 31// Topics: Coordinates, Points, Paths
 32// See Also: point2d(), point3d(), path3d()
 33// Usage:
 34//   pts = path2d(points);
 35// Description:
 36//   Returns a list of 2D vectors/points from a list of 2D, 3D or higher dimensional vectors/points.
 37//   Removes the extra coordinates from higher dimensional points.  The input must be a path, where
 38//   every vector has the same length.
 39// Arguments:
 40//   points = A list of 2D or 3D points/vectors.
 41function path2d(points) =
 42    assert(is_path(points,dim=undef,fast=true),"Input to path2d is not a path")
 43    let (result = points * concat(ident(2), repeat([0,0], len(points[0])-2)))
 44    assert(is_def(result), "Invalid input to path2d")
 45    result;
 46
 47
 48// Function: point3d()
 49// Synopsis: Convert a vector to 3D. 
 50// Topics: Coordinates, Points
 51// See Also: path2d(), point2d(), path3d()
 52// Usage:
 53//   pt = point3d(p, [fill]);
 54// Description:
 55//   Returns a 3D vector/point from a 2D or 3D vector.
 56// Arguments:
 57//   p = The coordinates to force into a 3D vector/point.
 58//   fill = Value to fill missing values in vector with.  Default: 0
 59function point3d(p, fill=0) =
 60    assert(is_list(p)) 
 61    [for (i=[0:2]) (p[i]==undef)? fill : p[i]];
 62
 63
 64// Function: path3d()
 65// Synopsis: Convert a path to 3D. 
 66// SynTags: Path
 67// Topics: Coordinates, Points, Paths
 68// See Also: point2d(), path2d(), point3d()
 69// Usage:
 70//   pts = path3d(points, [fill]);
 71// Description:
 72//   Returns a list of 3D vectors/points from a list of 2D or higher dimensional vectors/points
 73//   by removing extra coordinates or adding the z coordinate.  
 74// Arguments:
 75//   points = A list of 2D, 3D or higher dimensional points/vectors.
 76//   fill = Value to fill missing values in vectors with (in the 2D case).  Default: 0
 77function path3d(points, fill=0) =
 78    assert(is_num(fill))
 79    assert(is_path(points, dim=undef, fast=true), "Input to path3d is not a path")
 80    let (
 81        change = len(points[0])-3,
 82        M = change < 0? [[1,0,0],[0,1,0]] : 
 83            concat(ident(3), repeat([0,0,0],change)),
 84        result = points*M
 85    )
 86    assert(is_def(result), "Input to path3d is invalid")
 87    fill == 0 || change>=0 ? result : result + repeat([0,0,fill], len(result));
 88
 89
 90// Function: point4d()
 91// Synopsis: Convert a vector to 4d. 
 92// Topics: Coordinates, Points
 93// See Also: point2d(), path2d(), point3d(), path3d(), path4d()
 94// Usage:
 95//   pt = point4d(p, [fill]);
 96// Description:
 97//   Returns a 4D vector/point from a 2D or 3D vector.
 98// Arguments:
 99//   p = The coordinates to force into a 4D vector/point.
100//   fill = Value to fill missing values in vector with.  Default: 0
101function point4d(p, fill=0) = assert(is_list(p))
102                              [for (i=[0:3]) (p[i]==undef)? fill : p[i]];
103
104
105// Function: path4d()
106// Synopsis: Convert a path to 4d.  
107// SynTags: Path
108// Topics: Coordinates, Points, Paths
109// See Also: point2d(), path2d(), point3d(), path3d(), point4d()
110// Usage:
111//   pt = path4d(points, [fill]);
112// Description:
113//   Returns a list of 4D vectors/points from a list of 2D or 3D vectors/points.
114// Arguments:
115//   points = A list of 2D or 3D points/vectors.
116//   fill = Value to fill missing values in vectors with.  Default: 0 
117function path4d(points, fill=0) = 
118   assert(is_num(fill) || is_vector(fill))
119   assert(is_path(points, dim=undef, fast=true), "Input to path4d is not a path")
120   let (
121      change = len(points[0])-4,
122      M = change < 0 ? select(ident(4), 0, len(points[0])-1) :
123                       concat(ident(4), repeat([0,0,0,0],change)),
124      result = points*M
125   ) 
126   assert(is_def(result), "Input to path4d is invalid")
127   fill == 0 || change >= 0 ? result :
128    let(
129      addition = is_list(fill) ? concat(0*points[0],fill) :
130                                 concat(0*points[0],repeat(fill,-change))
131    )
132    assert(len(addition) == 4, "Fill is the wrong length")
133    result + repeat(addition, len(result));
134
135
136
137// Section: Coordinate Systems
138
139// Function: polar_to_xy()
140// Synopsis: Convert 2D polar coordinates to cartesian coordinates. 
141// SynTags: Path
142// Topics: Coordinates, Points, Paths
143// See Also: xy_to_polar(), xyz_to_cylindrical(), cylindrical_to_xyz(), xyz_to_spherical(), spherical_to_xyz()
144// Usage:
145//   pt = polar_to_xy(r, theta);
146//   pt = polar_to_xy([R, THETA]);
147//   pts = polar_to_xy([[R,THETA], [R,THETA], ...]);
148// Description:
149//   Called with two arguments, converts the `r` and `theta` 2D polar coordinate into an `[X,Y]` cartesian coordinate.
150//   Called with one `[R,THETA]` vector argument, converts the 2D polar coordinate into an `[X,Y]` cartesian coordinate.
151//   Called with a list of `[R,THETA]` vector arguments, converts each 2D polar coordinate into `[X,Y]` cartesian coordinates.
152//   Theta is the angle counter-clockwise of X+ on the XY plane.
153// Arguments:
154//   r = distance from the origin.
155//   theta = angle in degrees, counter-clockwise of X+.
156// Example:
157//   xy = polar_to_xy(20,45);    // Returns: ~[14.1421365, 14.1421365]
158//   xy = polar_to_xy(40,30);    // Returns: ~[34.6410162, 15]
159//   xy = polar_to_xy([40,30]);  // Returns: ~[34.6410162, 15]
160//   xy = polar_to_xy([[40,30],[20,120]]);  // Returns: ~[[34.6410162, 15], [-10, 17.3205]]
161// Example(2D):
162//   r=40; ang=30; $fn=36;
163//   pt = polar_to_xy(r,ang);
164//   stroke(circle(r=r), closed=true, width=0.5);
165//   color("black") stroke([[r,0], [0,0], pt], width=0.5);
166//   color("black") stroke(arc(r=15, angle=ang), width=0.5);
167//   color("red") move(pt) circle(d=3);
168function polar_to_xy(r,theta) =
169    theta != undef
170      ? assert(is_num(r) && is_num(theta), "Bad Arguments.")
171        [r*cos(theta), r*sin(theta)]
172      : assert(is_list(r), "Bad Arguments")
173        is_num(r.x)
174          ? polar_to_xy(r.x, r.y)
175          : [for(p = r) polar_to_xy(p.x, p.y)];
176
177
178// Function: xy_to_polar()
179// Synopsis: Convert 2D cartesian coordinates to polar coordinates (radius and angle)
180// Topics: Coordinates, Points, Paths
181// See Also: polar_to_xy(), xyz_to_cylindrical(), cylindrical_to_xyz(), xyz_to_spherical(), spherical_to_xyz()
182// Usage:
183//   r_theta = xy_to_polar(x,y);
184//   r_theta = xy_to_polar([X,Y]);
185//   r_thetas = xy_to_polar([[X,Y], [X,Y], ...]);
186// Description:
187//   Called with two arguments, converts the `x` and `y` 2D cartesian coordinate into a `[RADIUS,THETA]` polar coordinate.
188//   Called with one `[X,Y]` vector argument, converts the 2D cartesian coordinate into a `[RADIUS,THETA]` polar coordinate.
189//   Called with a list of `[X,Y]` vector arguments, converts each 2D cartesian coordinate into `[RADIUS,THETA]` polar coordinates.
190//   Theta is the angle counter-clockwise of X+ on the XY plane.
191// Arguments:
192//   x = X coordinate.
193//   y = Y coordinate.
194// Example:
195//   plr = xy_to_polar(20,30);
196//   plr = xy_to_polar([40,60]);
197//   plrs = xy_to_polar([[40,60],[-10,20]]);
198// Example(2D):
199//   pt = [-20,30]; $fn = 36;
200//   rt = xy_to_polar(pt);
201//   r = rt[0]; ang = rt[1];
202//   stroke(circle(r=r), closed=true, width=0.5);
203//   zrot(ang) stroke([[0,0],[r,0]],width=0.5);
204//   color("red") move(pt) circle(d=3);
205function xy_to_polar(x, y) =
206    y != undef
207      ? assert(is_num(x) && is_num(y), "Bad Arguments.")
208        [norm([x, y]), atan2(y, x)]
209      : assert(is_list(x), "Bad Arguments")
210        is_num(x.x)
211          ? xy_to_polar(x.x, x.y)
212          : [for(p = x) xy_to_polar(p.x, p.y)];
213
214
215// Function: project_plane()
216// Synopsis: Project a set of points onto a specified plane, returning 2D points.  
217// SynTags: Path
218// Topics: Coordinates, Points, Paths
219// See Also: lift_plane()
220// Usage: 
221//   xy = project_plane(plane, p);
222// Usage: To get a transform matrix
223//   M = project_plane(plane)
224// Description:
225//   Maps the provided 3D point(s) from 3D coordinates to a 2D coordinate system defined by `plane`.  Points that are not
226//   on the specified plane will be projected orthogonally onto the plane.  This coordinate system is useful if you need
227//   to perform 2D operations on a coplanar set of data.  After those operations are done you can return the data
228//   to 3D with `lift_plane()`.  You could also use this to force approximately coplanar data to be exactly coplanar.
229//   The parameter p can be a point, path, region, bezier patch or VNF.
230//   The plane can be specified as
231//   - A list of three points.  The planar coordinate system will have [0,0] at plane[0], and plane[1] will lie on the Y+ axis.
232//   - A list of coplanar points that define a plane (not-collinear)
233//   - A plane definition `[A,B,C,D]` where `Ax+By+CZ=D`.  The closest point on that plane to the origin will map to the origin in the new coordinate system.
234//   .
235//   If you omit the point specification then `project_plane()` returns a rotation matrix that maps the specified plane to the XY plane.
236//   Note that if you apply this transformation to data lying on the plane it will produce 3D points with the Z coordinate of zero.
237// Arguments:
238//   plane = plane specification or point list defining the plane
239//   p = 3D point, path, region, VNF or bezier patch to project
240// Example:
241//   pt = [5,-5,5];
242//   a=[0,0,0];  b=[10,-10,0];  c=[10,0,10];
243//   xy = project_plane([a,b,c],pt);
244// Example(3D): The yellow points in 3D project onto the red points in 2D
245//   M = [[-1, 2, -1, -2], [-1, -3, 2, -1], [2, 3, 4, 53], [0, 0, 0, 1]];
246//   data = apply(M,path3d(circle(r=10, $fn=20)));
247//   move_copies(data) sphere(r=1);
248//   color("red") move_copies(project_plane(data, data)) sphere(r=1);
249// Example:
250//   xyzpath = move([10,20,30], p=yrot(25, p=path3d(circle(d=100))));
251//   mat = project_plane(xyzpath);
252//   xypath = path2d(apply(mat, xyzpath));
253//   #stroke(xyzpath,closed=true);
254//   stroke(xypath,closed=true);
255function project_plane(plane,p) =
256      is_matrix(plane,3,3) && is_undef(p) ? // no data, 3 points given
257          assert(!is_collinear(plane),"Points defining the plane must not be collinear")
258          let(
259              v = plane[2]-plane[0],
260              y = unit(plane[1]-plane[0]),        // y axis goes to point b
261              x = unit(v-(v*y)*y)   // x axis 
262          )            
263          frame_map(x,y) * move(-plane[0])
264    : is_vector(plane,4) && is_undef(p) ?            // no data, plane given in "plane"
265          assert(_valid_plane(plane), "Plane is not valid")
266          let(
267               n = point3d(plane),
268               cp = n * plane[3] / (n*n)
269          )
270          rot(from=n, to=UP) * move(-cp)
271    : is_path(plane,3) && is_undef(p) ?               // no data, generic point list plane
272          assert(len(plane)>=3, "Need three points to define a plane")
273          let(plane = plane_from_points(plane))
274          assert(is_def(plane), "Point list is not coplanar")
275          project_plane(plane)
276    : assert(is_def(p), str("Invalid plane specification: ",plane))
277      is_vnf(p) ? [project_plane(plane,p[0]), p[1]] 
278    : is_list(p) && is_list(p[0]) && is_vector(p[0][0],3) ?  // bezier patch or region
279           [for(plist=p) project_plane(plane,plist)]
280    : assert(is_vector(p,3) || is_path(p,3),str("Data must be a 3D point, path, region, vnf or bezier patch",p))
281      is_matrix(plane,3,3) ?
282          assert(!is_collinear(plane),"Points defining the plane must not be collinear")
283          let(
284              v = plane[2]-plane[0],
285              y = unit(plane[1]-plane[0]),        // y axis goes to point b
286              x = unit(v-(v*y)*y)  // x axis 
287          ) move(-plane[0],p) * transpose([x,y])
288    : is_vector(p) ? point2d(apply(project_plane(plane),p))
289    : path2d(apply(project_plane(plane),p));
290
291
292
293// Function: lift_plane()
294// Synopsis: Map a list of 2D points onto a plane in 3D. 
295// SynTags: Path
296// Topics: Coordinates, Points, Paths
297// See Also: project_plane()
298// Usage: 
299//   xyz = lift_plane(plane, p);
300// Usage: to get transform matrix
301//   M =  lift_plane(plane);
302// Description:
303//   Converts the given 2D point on the plane to 3D coordinates of the specified plane.
304//   The parameter p can be a point, path, region, bezier patch or VNF.
305//   The plane can be specified as
306//   - A list of three points.  The planar coordinate system will have [0,0] at plane[0], and plane[1] will lie on the Y+ axis.
307//   - A list of coplanar points that define a plane (not-collinear)
308//   - A plane definition `[A,B,C,D]` where `Ax+By+CZ=D`.  The closest point on that plane to the origin will map to the origin in the new coordinate system.
309// If you do not supply `p` then you get a transformation matrix which operates in 3D, assuming that the Z coordinate of the points is zero.
310// This matrix is a rotation, the inverse of the one produced by project_plane.
311// Arguments:
312//   plane = Plane specification or list of points to define a plane
313//   p = points, path, region, VNF, or bezier patch to transform. 
314function lift_plane(plane, p) =
315      is_matrix(plane,3,3) && is_undef(p) ? // no data, 3 p given
316          let(
317              v = plane[2]-plane[0],
318              y = unit(plane[1]-plane[0]),        // y axis goes to point b
319              x = unit(v-(v*y)*y)   // x axis 
320          )            
321          move(plane[0]) * frame_map(x,y,reverse=true)
322    : is_vector(plane,4) && is_undef(p) ?            // no data, plane given in "plane"
323          assert(_valid_plane(plane), "Plane is not valid")
324          let(
325               n = point3d(plane),
326               cp = n * plane[3] / (n*n)
327          )
328          move(cp) * rot(from=UP, to=n)
329    : is_path(plane,3) && is_undef(p) ?               // no data, generic point list plane
330          assert(len(plane)>=3, "Need three p to define a plane")
331          let(plane = plane_from_points(plane))
332          assert(is_def(plane), "Point list is not coplanar")
333          lift_plane(plane)
334    : is_vnf(p) ? [lift_plane(plane,p[0]), p[1]] 
335    : is_list(p) && is_list(p[0]) && is_vector(p[0][0],3) ?  // bezier patch or region
336           [for(plist=p) lift_plane(plane,plist)]
337    : assert(is_vector(p,2) || is_path(p,2),"Data must be a 2D point, path, region, vnf or bezier patch")
338      is_matrix(plane,3,3) ?
339          let(
340              v = plane[2]-plane[0],
341              y = unit(plane[1]-plane[0]),        // y axis goes to point b
342              x = unit(v-(v*y)*y)  // x axis 
343          ) move(plane[0],p * [x,y])
344    : apply(lift_plane(plane),is_vector(p) ? point3d(p) : path3d(p));
345
346
347// Function: cylindrical_to_xyz()
348// Synopsis: Convert cylindrical coordinates to cartesian coordinates. 
349// SynTags: Path
350// Topics: Coordinates, Points, Paths
351// See Also: xyz_to_cylindrical(), xy_to_polar(), polar_to_xy(), xyz_to_spherical(), spherical_to_xyz()
352// Usage:
353//   pt = cylindrical_to_xyz(r, theta, z);
354//   pt = cylindrical_to_xyz([RADIUS,THETA,Z]);
355//   pts = cylindrical_to_xyz([[RADIUS,THETA,Z], [RADIUS,THETA,Z], ...]);
356// Description:
357//   Called with three arguments, converts the `r`, `theta`, and 'z' 3D cylindrical coordinate into an `[X,Y,Z]` cartesian coordinate.
358//   Called with one `[RADIUS,THETA,Z]` vector argument, converts the 3D cylindrical coordinate into an `[X,Y,Z]` cartesian coordinate.
359//   Called with a list of `[RADIUS,THETA,Z]` vector arguments, converts each 3D cylindrical coordinate into `[X,Y,Z]` cartesian coordinates.
360//   Theta is the angle counter-clockwise of X+ on the XY plane.  Z is height above the XY plane.
361// Arguments:
362//   r = distance from the Z axis.
363//   theta = angle in degrees, counter-clockwise of X+ on the XY plane.
364//   z = Height above XY plane.
365// Example:
366//   xyz = cylindrical_to_xyz(20,30,40);
367//   xyz = cylindrical_to_xyz([40,60,50]);
368function cylindrical_to_xyz(r,theta,z) =
369    theta != undef
370      ? assert(is_num(r) && is_num(theta) && is_num(z), "Bad Arguments.")
371        [r*cos(theta), r*sin(theta), z]
372      : assert(is_list(r), "Bad Arguments")
373        is_num(r.x)
374          ? cylindrical_to_xyz(r.x, r.y, r.z)
375          : [for(p = r) cylindrical_to_xyz(p.x, p.y, p.z)];
376
377
378// Function: xyz_to_cylindrical()
379// Synopsis: Convert 3D cartesian coordinates to cylindrical coordinates. 
380// Topics: Coordinates, Points, Paths
381// See Also: cylindrical_to_xyz(), xy_to_polar(), polar_to_xy(), xyz_to_spherical(), spherical_to_xyz()
382// Usage:
383//   rtz = xyz_to_cylindrical(x,y,z);
384//   rtz = xyz_to_cylindrical([X,Y,Z]);
385//   rtzs = xyz_to_cylindrical([[X,Y,Z], [X,Y,Z], ...]);
386// Description:
387//   Called with three arguments, converts the `x`, `y`, and `z` 3D cartesian coordinate into a `[RADIUS,THETA,Z]` cylindrical coordinate.
388//   Called with one `[X,Y,Z]` vector argument, converts the 3D cartesian coordinate into a `[RADIUS,THETA,Z]` cylindrical coordinate.
389//   Called with a list of `[X,Y,Z]` vector arguments, converts each 3D cartesian coordinate into `[RADIUS,THETA,Z]` cylindrical coordinates.
390//   Theta is the angle counter-clockwise of X+ on the XY plane.  Z is height above the XY plane.
391// Arguments:
392//   x = X coordinate.
393//   y = Y coordinate.
394//   z = Z coordinate.
395// Example:
396//   cyl = xyz_to_cylindrical(20,30,40);
397//   cyl = xyz_to_cylindrical([40,50,70]);
398//   cyls = xyz_to_cylindrical([[40,50,70], [-10,15,-30]]);
399function xyz_to_cylindrical(x,y,z) =
400    y != undef
401      ? assert(is_num(x) && is_num(y) && is_num(z), "Bad Arguments.")
402        [norm([x,y]), atan2(y,x), z]
403      : assert(is_list(x), "Bad Arguments")
404        is_num(x.x)
405          ? xyz_to_cylindrical(x.x, x.y, x.z)
406          : [for(p = x) xyz_to_cylindrical(p.x, p.y, p.z)];
407
408
409// Function: spherical_to_xyz()
410// Synopsis: Convert spherical coordinates to 3D cartesian coordinates. 
411// SynTags: Path
412// Topics: Coordinates, Points, Paths
413// See Also: cylindrical_to_xyz(), xyz_to_spherical(), xyz_to_cylindrical(), altaz_to_xyz(), xyz_to_altaz()
414// Usage:
415//   pt = spherical_to_xyz(r, theta, phi);
416//   pt = spherical_to_xyz([RADIUS,THETA,PHI]);
417//   pts = spherical_to_xyz([[RADIUS,THETA,PHI], [RADIUS,THETA,PHI], ...]);
418// Description:
419//   Called with three arguments, converts the `r`, `theta`, and 'phi' 3D spherical coordinate into an `[X,Y,Z]` cartesian coordinate.
420//   Called with one `[RADIUS,THETA,PHI]` vector argument, converts the 3D spherical coordinate into an `[X,Y,Z]` cartesian coordinate.
421//   Called with a list of `[RADIUS,THETA,PHI]` vector arguments, converts each 3D spherical coordinate into `[X,Y,Z]` cartesian coordinates.
422//   Theta is the angle counter-clockwise of X+ on the XY plane.  Phi is the angle down from the Z+ pole.
423// Arguments:
424//   r = distance from origin.
425//   theta = angle in degrees, counter-clockwise of X+ on the XY plane.
426//   phi = angle in degrees from the vertical Z+ axis.
427// Example:
428//   xyz = spherical_to_xyz(20,30,40);
429//   xyz = spherical_to_xyz([40,60,50]);
430//   xyzs = spherical_to_xyz([[40,60,50], [50,120,100]]);
431function spherical_to_xyz(r,theta,phi) =
432    theta != undef
433      ? assert(is_num(r) && is_num(theta) && is_num(phi), "Bad Arguments.")
434        r*[cos(theta)*sin(phi), sin(theta)*sin(phi), cos(phi)]
435      : assert(is_list(r), "Bad Arguments")
436        is_num(r.x)
437          ? spherical_to_xyz(r.x, r.y, r.z)
438          : [for(p = r) spherical_to_xyz(p.x, p.y, p.z)];
439
440
441// Function: xyz_to_spherical()
442// Usage:
443//   r_theta_phi = xyz_to_spherical(x,y,z)
444//   r_theta_phi = xyz_to_spherical([X,Y,Z])
445//   r_theta_phis = xyz_to_spherical([[X,Y,Z], [X,Y,Z], ...])
446// Topics: Coordinates, Points, Paths
447// Synopsis: Convert 3D cartesian coordinates to spherical coordinates. 
448// See Also: cylindrical_to_xyz(), spherical_to_xyz(), xyz_to_cylindrical(), altaz_to_xyz(), xyz_to_altaz()
449// Description:
450//   Called with three arguments, converts the `x`, `y`, and `z` 3D cartesian coordinate into a `[RADIUS,THETA,PHI]` spherical coordinate.
451//   Called with one `[X,Y,Z]` vector argument, converts the 3D cartesian coordinate into a `[RADIUS,THETA,PHI]` spherical coordinate.
452//   Called with a list of `[X,Y,Z]` vector arguments, converts each 3D cartesian coordinate into `[RADIUS,THETA,PHI]` spherical coordinates.
453//   Theta is the angle counter-clockwise of X+ on the XY plane.  Phi is the angle down from the Z+ pole.
454// Arguments:
455//   x = X coordinate.
456//   y = Y coordinate.
457//   z = Z coordinate.
458// Example:
459//   sph = xyz_to_spherical(20,30,40);
460//   sph = xyz_to_spherical([40,50,70]);
461//   sphs = xyz_to_spherical([[40,50,70], [25,-14,27]]);
462function xyz_to_spherical(x,y,z) =
463    y != undef
464      ? assert(is_num(x) && is_num(y) && is_num(z), "Bad Arguments.")
465        [norm([x,y,z]), atan2(y,x), atan2(norm([x,y]),z)]
466      : assert(is_list(x), "Bad Arguments")
467        is_num(x.x)
468          ? xyz_to_spherical(x.x, x.y, x.z)
469          : [for(p = x) xyz_to_spherical(p.x, p.y, p.z)];
470
471
472// Function: altaz_to_xyz()
473// Synopsis: Convert altitude/azimuth/range to 3D cartesian coordinates. 
474// SynTags: Path
475// Topics: Coordinates, Points, Paths
476// See Also: cylindrical_to_xyz(), xyz_to_spherical(), spherical_to_xyz(), xyz_to_cylindrical(), xyz_to_altaz()
477// Usage:
478//   pt = altaz_to_xyz(alt, az, r);
479//   pt = altaz_to_xyz([ALT,AZ,R]);
480//   pts = altaz_to_xyz([[ALT,AZ,R], [ALT,AZ,R], ...]);
481// Description:
482//   Convert altitude/azimuth/range coordinates to 3D cartesian coordinates.
483//   Called with three arguments, converts the `alt`, `az`, and 'r' 3D altitude-azimuth coordinate into an `[X,Y,Z]` cartesian coordinate.
484//   Called with one `[ALTITUDE,AZIMUTH,RANGE]` vector argument, converts the 3D alt-az coordinate into an `[X,Y,Z]` cartesian coordinate.
485//   Called with a list of `[ALTITUDE,AZIMUTH,RANGE]` vector arguments, converts each 3D alt-az coordinate into `[X,Y,Z]` cartesian coordinates.
486//   Altitude is the angle above the XY plane, Azimuth is degrees clockwise of Y+ on the XY plane, and Range is the distance from the origin.
487// Arguments:
488//   alt = altitude angle in degrees above the XY plane.
489//   az = azimuth angle in degrees clockwise of Y+ on the XY plane.
490//   r = distance from origin.
491// Example:
492//   xyz = altaz_to_xyz(20,30,40);
493//   xyz = altaz_to_xyz([40,60,50]);
494function altaz_to_xyz(alt,az,r) =
495    az != undef
496      ? assert(is_num(alt) && is_num(az) && is_num(r), "Bad Arguments.")
497        r*[cos(90-az)*cos(alt), sin(90-az)*cos(alt), sin(alt)]
498      : assert(is_list(alt), "Bad Arguments")
499        is_num(alt.x)
500          ? altaz_to_xyz(alt.x, alt.y, alt.z)
501          : [for(p = alt) altaz_to_xyz(p.x, p.y, p.z)];
502
503
504
505// Function: xyz_to_altaz()
506// Synopsis: Convert 3D cartesian coordinates to [altitude,azimuth,range]. 
507// Topics: Coordinates, Points, Paths
508// See Also: cylindrical_to_xyz(), xyz_to_spherical(), spherical_to_xyz(), xyz_to_cylindrical(), altaz_to_xyz()
509// Usage:
510//   alt_az_r = xyz_to_altaz(x,y,z);
511//   alt_az_r = xyz_to_altaz([X,Y,Z]);
512//   alt_az_rs = xyz_to_altaz([[X,Y,Z], [X,Y,Z], ...]);
513// Description:
514//   Converts 3D cartesian coordinates to altitude/azimuth/range coordinates.
515//   Called with three arguments, converts the `x`, `y`, and `z` 3D cartesian coordinate into an `[ALTITUDE,AZIMUTH,RANGE]` coordinate.
516//   Called with one `[X,Y,Z]` vector argument, converts the 3D cartesian coordinate into a `[ALTITUDE,AZIMUTH,RANGE]` coordinate.
517//   Called with a list of `[X,Y,Z]` vector arguments, converts each 3D cartesian coordinate into `[ALTITUDE,AZIMUTH,RANGE]` coordinates.
518//   Altitude is the angle above the XY plane, Azimuth is degrees clockwise of Y+ on the XY plane, and Range is the distance from the origin.
519// Arguments:
520//   x = X coordinate.
521//   y = Y coordinate.
522//   z = Z coordinate.
523// Example:
524//   aa = xyz_to_altaz(20,30,40);
525//   aa = xyz_to_altaz([40,50,70]);
526function xyz_to_altaz(x,y,z) =
527    y != undef
528      ? assert(is_num(x) && is_num(y) && is_num(z), "Bad Arguments.")
529        [atan2(z,norm([x,y])), atan2(x,y), norm([x,y,z])]
530      : assert(is_list(x), "Bad Arguments")
531        is_num(x.x)
532          ? xyz_to_altaz(x.x, x.y, x.z)
533          : [for(p = x) xyz_to_altaz(p.x, p.y, p.z)];
534
535
536
537// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap