Math::Vec(3pm)

πŸ“¦
version 1.01 Β· 5 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– Math::Vec πŸ’–

okay bestie, welcome to Math::Vec β€” it's part of the User Contributed Perl Documentation and it is literally Object-Oriented Vector Math Methods in Perl. vectors!! in perl!! we're doing math and we're doing it cutely πŸ’…


✨ SYNOPSIS ✨

use Math::Vec;
$v = Math::Vec->new(0,1,2);

or

use Math::Vec qw(NewVec);
$v = NewVec(0,1,2);
@res = $v->Cross([1,2.5,0]);
$p = NewVec(@res);
$q = $p->Dot([0,1,0]);

or

use Math::Vec qw(:terse);
$v = V(0,1,2);
$q = ($v x [1,2.5,0]) * [0,1,0];

three whole ways to enter the chat, we love options 🫢


🚨 NOTICE 🚨

ngl, this module is still somewhat incomplete. if a function does nothing, there is likely a really good reason. please have a look at the code if you are trying to use this in a production environment. no cap, read the source first πŸ’€


πŸ‘‘ AUTHOR πŸ‘‘

Eric L. Wilhelm <ewilhelm at cpan dot org>

http://scratchcomputing.com


πŸ¦‹ DESCRIPTION πŸ¦‹

so this module was adapted from Math::Vector, written by Wayne M. Syvinski. iconic of him.

it uses most of the same algorithms, and currently preserves the same names as the original functions, though some aliases have been added to make the interface more natural (at least to the way I think.) your girl has opinions about naming and honestly? fair 🌸

the "object" for the object oriented calling style is a blessed array reference which contains a vector of the form [x,y,z]. methods will typically return a list. remember that, it matters, it's the whole vibe of this module.


Copyright (C) 2003-2006 Eric Wilhelm

portions Copyright 2003 Wayne M. Syvinski


πŸ’€ NO WARRANTY πŸ’€

Absolutely, positively NO WARRANTY, neither express or implied, is offered with this software. you use this software at your own risk. in case of loss, neither Wayne M. Syvinski, Eric Wilhelm, nor anyone else, owes you anything whatseover. you have been warned. (the typo is canon, bestie, I'm not touching it πŸ™ˆ)

Note that this includes NO GUARANTEE of MATHEMATICAL CORRECTNESS. if you are going to use this code in a production environment, it is YOUR RESPONSIBILITY to verify that the methods return the correct values. fr fr, this is the scary one. it could just be wrong math and nobody's legally obligated to care 😭

βš–οΈ LICENSE βš–οΈ

you may use this software under one of the following licenses:

  1. GNU General Public License (found at http://www.gnu.org/copyleft/gpl.html)
  2. Artistic License (found at http://www.perl.com/pub/language/misc/Artistic.html)

pick your fighter πŸŽ€


🌈 SEE ALSO 🌈

  • Math::Vector

🧚 Constructor 🧚

new

Returns a blessed array reference to cartesian point ($x, $y, $z), where $z is optional. note the feed-me-list, get-back-reference syntax here. this is the opposite of the rest of the methods for a good reason (it allows nesting of function calls.) we love a deliberate inconsistency with an explanation 🫢

the z value is optional, (and so are x and y.) Undefined values are silently translated into zeros upon construction. zero thoughts, zero values, same energy πŸ’…

$vec = Math::Vec->new($x, $y, $z);

NewVec

this is simply a shortcut to Math::Vec->new($x, $y, $z) for those of you who don't want to type so much so often. also makes it easier to nest / chain your function calls. note that methods will typically output lists (e.g. the answer to your question.) while you can simply [bracket] the answer to make an array reference, you need that to be blessed in order to use the $object->method(@args) syntax. this function does that blessing. lowkey it's a fairy godmother situation 🧚

this function is exported as an option. to use it, simply use Math::Vec qw(NewVec); at the start of your code.

use Math::Vec qw(NewVec);
$vec = NewVec($x, $y, $z);
$diff = NewVec($vec->Minus([$ovec->ScalarMult(0.5)]));

⭐ Terse Functions ⭐

these are all one-letter shortcuts which are imported to your namespace with the :terse flag. one letter. maximum efficiency. main character typing energy ⌨️

use Math::Vec qw(:terse);

V

this is the same as Math::Vec->new($x,$y,$z).

$vec = V($x, $y, $z);

U

shortcut to V($x,$y,$z)->UnitVector()

$unit = U($x, $y, $z);

this will also work if called with a vector object:

$unit = U($vector);

X

Returns an x-axis unit vector.

$xvec = X();

Y

Returns a y-axis unit vector.

$yvec = Y();

Z

Returns a z-axis unit vector.

$zvec = Z();

πŸŽ€ Overloading πŸŽ€

best used with the :terse functions, the Overloading scheme introduces an interface which is unique from the Methods interface. where the methods take references and return lists, the overloaded operators will return references. this allows vector arithmetic to be chained together more easily. of course, you can easily dereference these with @{$vec}.

the following sections contain equivelant expressions from the longhand and terse interfaces, respectively. (yes it says "equivelant", we are keeping it, it's part of the lore 😌)

Negation:

@a = NewVec->(0,1,1)->ScalarMult(-1);
@a = @{-V(0,1,1)};

Stringification:

this also performs concatenation and other string operations.

print join(", ", 0,1,1), "\n";

print V(0,1,1), "\n";

$v = V(0,1,1);
print "$v\n";
print "$v" . "\n";
print $v, "\n";

Addition:

@a = NewVec(0,1,1)->Plus([2,2]);

@a = @{V(0,1,1) + V(2,2)};

# only one argument needs to be blessed:
@a = @{V(0,1,1) + [2,2]};

# and which one is blessed doesn't matter:
@a = @{[0,1,1] + V(2,2)};

Subtraction:

@a = NewVec(0,1,1)->Minus([2,2]);

@a = @{[0,1,1] - V(2,2)};

Scalar Multiplication:

@a = NewVec(0,1,1)->ScalarMult(2);

@a = @{V(0,1,1) * 2};

@a = @{2 * V(0,1,1)};

Scalar Division:

@a = NewVec(0,1,1)->ScalarMult(1/2);

# order matters!
@a = @{V(0,1,1) / 2};

Cross Product:

@a = NewVec(0,1,1)->Cross([0,1]);

@a = @{V(0,1,1) x [0,1]};

@a = @{[0,1,1] x V(0,1)};

Dot Product:

also known as the "Scalar Product".

$a = NewVec(0,1,1)->Dot([0,1]);

$a = V(0,1,1) * [0,1];
Note: Not using the . operator here makes everything more efficient. I know, the * is not a dot, but at least it's a mathematical operator (perl does some implied string concatenation somewhere which drove me to avoid the dot.) we are NOT talking about the implied string concatenation incident πŸ™ˆ

Comparison:

the == and != operators will compare vectors for equal direction and magnitude. no attempt is made to apply tolerance to this equality. so like, exact vibes only. if you're off by 0.0000001 that's a you problem πŸ’€

Length:

$a = NewVec(0,1,1)->Length();

$a = abs(V(0,1,1));

Vector Projection:

this one is a little different. where the method is written $a->Proj($b) to give the projection of $b onto $a, this reads like you would say it (b projected onto a): $b>>$a.

@a = NewVec(0,1,1)->Proj([0,0,1]);

@a = @{V(0,0,1)>>[0,1,1]};

πŸ”₯ Chaining Operations πŸ”₯

the above examples simply show how to go from the method interface to the overloaded interface, but where the overloading really shines is in chaining multiple operations together. because the return values from the overloaded operators are all references, you dereference them only when you are done. it's giving pipeline. it's giving flow state. it's giving slay πŸ¦‹

Unit Vector left of a line

this comes from the CAD::Calc::line_to_rectangle() function.

use Math::Vec qw(:terse);
@line = ([0,1],[1,0]);
my ($a, $b) = map({V(@$_)} @line);
$unit = U($b - $a);
$left = $unit x -Z();

Length of a cross product

$length = abs($va x $vb);

Vectors as coordinate axes

this is useful in drawing eliptical arcs using dxf data.

$val = 3.14159;                             # the 'start parameter'
@c = (14.15973317961194, 6.29684276451746); # codes 10, 20, 30
@e = (6.146127847120538, 0);                # codes 11, 21, 31
@ep = @{V(@c) + \@e};                       # that's the axis endpoint
$ux = U(@e);                                # unit on our x' axis
$uy = U($ux x -Z());                       # y' is left of x'
$center = V(@c);
# autodesk gives you this:
@pt = ($a * cos($val), $b * sin($val));
# but they don't tell you about the major/minor axis issue:
@pt = @{$center + $ux * $pt[0] + $uy * $pt[1]};;

(that double semicolon at the end? iconic. we're leaving it, it's load-bearing ✨)


πŸ’… Precedence πŸ’…

the operator precedence is going to be whatever perl wants it to be. I have not yet investigated this to see if it matches standard vector arithmetic notation. if in doubt, use parentheses. genuinely, just use parentheses, bestie 🫢

one item of note here is that the 'x' and '*' operators have the same precedence, so the leftmost wins. in the following example, you can get away without parentheses if you have the cross-product first.

# dot product of a cross product:
$v1 x $v2 * $v3
($v1 x $v2) * $v3

# scalar crossed with a vector (illegal!)
$v3 * $v1 x $v2
ok so that last one is ILLEGAL. do not do it. crossing a scalar with a vector is not a thing and perl will not save you. the parens-less version is only safe when the cross product comes first β€” otherwise you've reordered the whole math and nothing is fine 😭

and that's part 1, bestie β€” there's literally more coming πŸ’– don't go anywhere

✨ METHODS ✨

okay so here's the whole vibe of the methods, bestie πŸ’– the typical theme is that methods want array references as input and they hand you back lists. which means you get to choose: build an anonymous array ref to feed straight into another call (chaining, yay), or just grab the list and use it as-is. no wrong answers ✨

Methods that return a scalar or a list of scalars β€” in the mathematical sense, not the Perl SV sense, mind you β€” they're exempt from the theme. but any method that returns something that could become one vector? yeah, it returns that as a list. periodt.

if you wanna chain calls together, either use the NewVec constructor, or wrap the call in square brackets to make an anonymous array out of the result πŸŽ€

  my $vec = NewVec(@pt);
  my $doubled = NewVec($vec->ScalarMult(0.5));
  my $other = NewVec($vec->Plus([0,2,1], [4,2,3]));
  my @result = $other->Minus($doubled);
  $unit = NewVec(NewVec(@result)->UnitVector());

the vector objects are literally just blessed array references πŸ’… which makes for a fairly limited amount of manipulation, but vector math is not complicated stuff, so it's fine. hopefully you can save at least two lines of code per calculation using this module 🫢


🌸 Dot 🌸

returns the dot product of $vec 'dot' $othervec.

  $vec->Dot($othervec);

🌸 DotProduct 🌸

alias to Dot()

  $number = $vec->DotProduct($othervec);

🌸 Cross 🌸

returns $vec x $other_vec

  @list = $vec->Cross($other_vec);
  # or, to use the result as a vec:
  $cvec = NewVec($vec->Cross($other_vec));

🌸 CrossProduct 🌸

alias to Cross() β€” and the source has notes that this should really strip out all of this clunkiness and go to operator overloading, but that gets into other hairiness πŸ™ˆ

  $vec->CrossProduct();

🌸 Length 🌸

returns the length of $vec

  $length = $vec->Length();

🌸 Magnitude 🌸

  $vec->Magnitude();

🌸 UnitVector 🌸

  $vec->UnitVector();

🌸 ScalarMult 🌸

factors each element of $vec by $factor.

  @new = $vec->ScalarMult($factor);

🌸 Minus 🌸

subtracts an arbitrary number of vectors. 🩷

  @result = $vec->Minus($other_vec, $another_vec?);

this would be equivelant to:

  @result = $vec->Minus([$other_vec->Plus(@list_of_vectors)]);

🌸 VecSub 🌸

alias to Minus()

  $vec->VecSub();

🌸 InnerAngle 🌸

returns the acute angle (in radians) in the plane defined by the two vectors.

  $vec->InnerAngle($other_vec);

🌸 DirAngles 🌸

  $vec->DirAngles();

🌸 Plus 🌸

adds an arbitrary number of vectors. ✨

  @result = $vec->Plus($other_vec, $another_vec);

🌸 PlanarAngles 🌸

if called in list context, returns the angle of the vector in each of the primary planes. if called in scalar context, returns only the angle in the xy plane. angles are returned in radians, counter-clockwise from the primary axis (the one listed first in the pairs below.)

  ($xy_ang, $xz_ang, $yz_ang) = $vec->PlanarAngles();

🌸 Ang 🌸

a simpler alias to PlanarAngles() which eliminates the concerns about context and simply returns the angle in the xy plane. so chill of it honestly 🧚

  $xy_ang = $vec->Ang();

🌸 VecAdd 🌸

  $vec->VecAdd();

🌸 UnitVectorPoints 🌸

returns a unit vector which points from $A to $B.

  $A->UnitVectorPoints($B);

🌸 InnerAnglePoints 🌸

returns the InnerAngle() between the three points. $Vert is the vertex of the points.

  $Vert->InnerAnglePoints($endA, $endB);

🌸 PlaneUnitNormal 🌸

returns a unit vector normal to the plane described by the three points. the sense of this vector is according to the right-hand rule and the order of the given points. the $Vert vector is taken as the vertex of the three points. e.g. if $Vert is the origin of a coordinate system where the x-axis is $A and the y-axis is $B, then the return value would be a unit vector along the positive z-axis. πŸ‘‘

  $Vert->PlaneUnitNormal($A, $B);

🌸 TriAreaPoints 🌸

returns the angle of the triangle formed by the three points.

  $A->TriAreaPoints($B, $C);

🌸 Comp 🌸

returns the scalar projection of $B onto $A (also called the component of $B along $A.)

  $A->Comp($B);

🌸 Proj 🌸

returns the vector projection of $B onto $A.

  $A->Proj($B);

🌸 PerpFoot 🌸

returns a point on line $A,$B which is as close to $pt as possible (and therefore perpendicular to the line.)

  $pt->PerpFoot($A, $B);

πŸ¦‹ INCOMPLETE METHODS πŸ¦‹

ngl, these ones have yet to be translated into this interface 😭 they're shown here simply because the author intended to fully preserve the function names from the original Math::Vector module written by Wayne M. Syvinski. respect the lineage fr fr 🫢

πŸŽ€ TripleProduct πŸŽ€

  $vec->TripleProduct();

πŸŽ€ IJK πŸŽ€

  $vec->IJK();

πŸŽ€ OrdTrip πŸŽ€

  $vec->OrdTrip();

πŸŽ€ STV πŸŽ€

  $vec->STV();

πŸŽ€ Equil πŸŽ€

  $vec->Equil();

and that's a wrap on the whole page, bestie πŸ’– this one shipped as perl v5.36.0, dated 2022-10-22, and it's Math::Vec(3pm) if you wanna look it up again. go do some vector math, you're gonna ate it up, no cap βœ¨πŸ‘‘πŸ’…

πŸ“¦ where this page comes from