[comp.lang.postscript] Vector operators in PostScript

roy@phri.UUCP (Roy Smith) (09/05/88)

	I often have to do vector operations in PostScript.  Since I always
get horribly confused trying to work out the stack manipulations each time,
I came up with a set of vector operations.  These work on 2-vectors (which
is what I need most often), but it should be trivial to extend them to
3-vectors, etc.  Coding general n-vectors might be a trip, however.

	It's not much, but enjoy it anyway.  Also, if anybody can point out
a faster way to do any of these operations, let me know.

/roy

----------------
%
% Vectorops.ps -- vector operators for PostScript.
%
% Copyright 1987 Roy Smith
% Permission is hereby granted for any use of this software other
% than selling it or including it in a commercial product.
%
% $Header: vectorops.ps,v 1.1 87/09/16 20:31:59 roy Exp $
%

% vadd -- add two vectors.
% x1 y1 x2 y2 vadd ==> x1+x2 y1+y2
/vadd
{
	3 -1 roll add		% ==> x1 x2 y2+y1
	3 1 roll add		% ==> y2+y1 x1+x2
	exch			% ==> x1+x2 y2+y1
} def

% vsub -- subtract two vectors.
% x1 y1 x2 y2 vsub ==> x1-x2 y1-y2
/vsub
{
	3 -1 roll sub neg	% ==> x1 x2 -(y2-y1)
	3 1 roll sub		% ==> -(y2-y1) x1-x2
	exch			% ==> x1-x2 -(y2-y1)
} def

% vneg -- take negative of vector (scalar multiply by -1).
% x y vneg ==> -x -y
/vneg
{
	exch neg		% ==> y -x
	exch neg		% ==> -x -y
} def

% vdiv -- divide vector by scalar.
% x y s vdiv ==> x/s y/s
/vdiv
{
	dup			% ==> x y s s
	3 1 roll div		% ==> x s y/s
	3 1 roll div		% ==> y/s x/s
	exch			% ==> x/s y/s
} def

% vmul -- multiply vector by scalar.
% x y s vmul ==> x*s y*s
/vmul
{
	dup			% ==> x y s s
	3 1 roll mul		% ==> x s y*s
	3 1 roll mul		% ==> y*s x*s
	exch			% ==> x*s y*s
} def

% vexch -- exchange two vectors on stack.
% x1 y1 x2 y2 vexch => x2 y2 x1 y1
/vexch
{
	4 2 roll		% ==> x2 y2 x1 y1
} def

% vpop -- pop a vector off the stack.
% x1 y1 vpop => ---
/vpop
{
	pop pop
} def

% vdup -- duplicate a vector on the stack.
% x1 y1 vdup => x1 y1 x1 y1
/vdup
{
	dup			% ==> x1 y1 y1
	3 -1 roll dup		% ==> y1 y1 x1 x1
	4 1 roll exch		% ==> x1 y1 x1 y1
} def
-- 
Roy Smith, System Administrator
Public Health Research Institute
{allegra,philabs,cmcl2,rutgers}!phri!roy -or- phri!roy@uunet.uu.net
"The connector is the network"