## Copyright (C) 2015,2016 Philip Nienhuis
##
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .
## -*- texinfo -*-
## @deftypefn {Function File} [@var{orientation}] = isPolygonCW_Clipper (@var{inpol})
## Inspect winding direction of polygon(s).
##
## Based on Clipper library, polyclipping.sf.net, 3rd Party, Matlab
##
## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s)
## whose winding direction should be assessed. Subpolygons are separated by
## [NaN NaN] rows.
##
## Output argument @var{orientation} indicates the winding direction(s) of
## each subpolygon: 0 for clockwise, 1 for counterclockwise.
##
## @end deftypefn
## Author: Philip Nienhuis
## Created: 2015-05-03
## Based on Clipper library, polyclipping.sf.net, 3rd Party, Matlab
function [orientation] = isPolygonCW_Clipper (inpoly)
## Input validation
if (nargin < 1)
print_usage ();
endif
if (! isnumeric (inpoly) || size (inpoly, 2) < 2)
error ("ispolycw: inpoly should be a numeric Nx2 array");
endif
## Convert & scale to int64 (that's what Clipper works with)
## Find (X, Y) translation
xy_mean = mean (inpoly(isfinite (inpoly(:, 1)), :));
## Find (X, Y) magnitude
xy_magn = max (inpoly(isfinite (inpoly(:, 1)), :)) ...
- min (inpoly(isfinite (inpoly(:, 1)), :));
## Apply (X,Y) multiplication (floor (log10 (intmax ("int64"))) = 18)
xy_magn = 10^(17 - ceil (max (log10 (xy_magn))));
## Scale inpoly coordinates to optimally use int64
inpoly(:, 1:2) -= xy_mean;
inpoly *= xy_magn;
idin = [ 0 find(isnan (inpoly (:, 1)))' numel(inpoly (:, 1))+1 ];
for ii=1:numel (idin) - 1
inpol(ii).x = int64 (inpoly(idin(ii)+1:idin(ii+1)-1, 1));
inpol(ii).y = int64 (inpoly(idin(ii)+1:idin(ii+1)-1, 2));
endfor
## Just find out orientation of polygons
orientation = clipper (inpol);
endfunction