## Copyright (C) 2019 Markus Mützel
##
## This file is part of Octave.
##
## Octave 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.
##
## Octave 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 Octave; see the file COPYING.  If not, see
## <https://www.gnu.org/licenses/>.

function copl = is_coplanar (x, y, z)

allpoints = [x(:) y(:) z(:)];

## move first to origin
allpoints = allpoints - allpoints(1,:);

## find longest vector
vec_len = sum (allpoints(2:end,:) .* allpoints(2:end,:), 2);
max_len = max (vec_len);
i1 = find (vec_len == max_len, 1, "first") + 1;

idx = 2:rows (allpoints);
idx(i1-1) = [];

for i2 = idx
  ## FIXME: Can we efficiently check whether all vectors are colinear?
  
  ## calculate cross product of longest and other vector
  cross_prod = [allpoints(i1,2)*allpoints(i2,3) - allpoints(i1,3)*allpoints(i2,2); ...
                allpoints(i1,3)*allpoints(i2,1) - allpoints(i1,1)*allpoints(i2,3); ...
                allpoints(i1,1)*allpoints(i2,2) - allpoints(i1,2)*allpoints(i2,1)];

  if (sum (cross_prod.^2) > max_len/10) # FIXME: What is a good measure?
    ## Avoid using (almost) colinear vectors
    break;
  endif
endfor

## calculate volume of tetrahedron formed with all other vectors
idx(idx==i2) = [];
vol = allpoints(idx,:) * cross_prod;

## FIXME: What should we use as a tolerance
tol = eps (max_len)^3;
copl = ! any (abs(vol) > tol);

endfunction
