function sat(o,d)
% sat(o,d) demonstrates AABB/line segment intersection test based on SAT
%
%   Arg o is the CCW line normal angle in radians, default 0.
%
%   Arg d is the perp distance from the line to the origin, default 0.
%
%   Other config parameters can be changed below.

if (nargin < 2) d = 0; end
if (nargin < 1) o = 0; end

ax = 100; % axis limit
ll = 100; % segment length
lo = 30; % segment offset
rw = 50; rh = 30; % rect dims
rcx = 10; rcy = 20; % rect center

t = o + pi/2; % segment tangent dir
lcx = cos(o)*d+cos(t)*lo; lcy = sin(o)*d+sin(t)*lo; % segment center
ltx = cos(t)*ll/2; lty=sin(t)*ll/2; % segment tangent
rdx = rw/2; rdy = rh/2; % rect diagonal

fprintf('config ll=%f rw=%f rh=%f rcx=%f rcy=%f\n', ll, rw, rh, rcx, rcy);
fprintf('given o=%f, t=%f, d=%f, lcx=%f, lcy=%f\n', o, t, d, lcx, lcy);

clf; hold on; axis([-ax ax -ax ax]); grid on;

plot([lcx+ltx lcx-ltx], [lcy+lty lcy-lty], 'r-'); % segment
plot([rcx+rdx rcx-rdx rcx-rdx rcx+rdx rcx+rdx], ...
     [rcy+rdy rcy+rdy rcy-rdy rcy-rdy rcy+rdy], 'b-'); % rect

% Intersection test code starts here.  At this point the rect is given by its
% center (rcx,rcy) and quadrant I diagonal (rdx, rdy).  The segment is given by
% its center (lcx,lcy) and a vector (ltx,lty) from there to one of its
% endpoints, i.e. the segment endpoints are (lcx+ltx, lcy+lty) and
% (lcx-ltx, lcx-lty).

lcx = lcx-rcx; lcy = lcy-rcy; rcx = 0; rcy = 0; % xform rect center to origin
lnx = -lty; lny = ltx; % segment normal

% test three separating axes
if (rdx < abs(lcx)-abs(ltx)) fprintf('not intersecting (x)\n'); % x axis
elseif (rdy < abs(lcy)-abs(lty)) fprintf('not intersecting (y)\n'); % y axis
elseif ((rdx*abs(lnx)+rdy*abs(lny)) < abs(lcx*lnx+lcy*lny)) ...
      fprintf('not intersecting (l)\n'); % segment normal axis
else fprintf('intersecting\n'); end

end
