unit() now asserts error for zero-length vector unless dflt= arg is given.

This commit is contained in:
Garth Minette
2020-07-10 00:03:55 -07:00
parent a0d8c0a5c3
commit dde616dad5
5 changed files with 53 additions and 45 deletions

View File

@@ -105,18 +105,25 @@ function vceil(v) = [for (x=v) ceil(x)];
// Function: unit()
// Usage:
// unit(v, [dflt]);
// Description:
// Returns unit length normalized version of vector v.
// If passed a zero-length vector, returns the unchanged vector.
// Returns unit length normalized version of vector v. If passed a zero-length vector,
// asserts an error unless `dflt` is given, in which case the value of `dflt` is returned.
// Arguments:
// v = The vector to normalize.
// dflt = If given, and input is a zero-length vector, this value is returned. Default: `undef` (assert error on zero-length vector)
// Examples:
// unit([10,0,0]); // Returns: [1,0,0]
// unit([0,10,0]); // Returns: [0,1,0]
// unit([0,0,10]); // Returns: [0,0,1]
// unit([0,-10,0]); // Returns: [0,-1,0]
// unit([0,0,0]); // Returns: [0,0,0]
function unit(v) = assert(is_vector(v),str(v)) norm(v)<=EPSILON? v : v/norm(v);
// unit([0,0,0],[1,2,3]); // Returns: [1,2,3]
// unit([0,0,0]); // Asserts an error.
function unit(v, dflt) =
assert(is_vector(v), str("Expected a vector. Got: ",v))
norm(v)<EPSILON? (is_undef(dflt)? assert(norm(v)>=EPSILON) : dflt) :
v/norm(v);
// Function: vector_angle()