function indexMatrix = computeTriangulationOfCone(extremeRayMatrix)
% compute the triangulation of a convex cone given by its extreme rays
%
% THIS FUNCTION IS NO USER FUNCTION.

% The elk-library: convex geometry applied to crystallization modeling.
%   Copyright (C) 2012 Alexander Reinhold
%
% 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 <http://www.gnu.org/licenses/>.

% special case
% all the procedures below do not make sense for a cone in 1D and the
% convhulln crashes. in these cases extremRayMatrix is a 1x1 matrix.
if numel(extremeRayMatrix) == 1
    indexMatrix = 1;
    return
end

% normalize to plane
normalVector = mean(extremeRayMatrix, 1);
normalVector = normalVector / norm(normalVector);
for iRay = 1:size(extremeRayMatrix, 1)
    extremeRayMatrix(iRay, :) = extremeRayMatrix(iRay, :) / ...
        (extremeRayMatrix(iRay, :) * normalVector');
end

% use convex hull to calculate the triangulation of the surface
indexMatrix = convhulln(...
    [zeros(1, size(extremeRayMatrix, 2)); extremeRayMatrix], ...
    {'Qt', 'Qs'});

% throw away any patch that contains the origin
indexMatrix(sum(indexMatrix == 1, 2) > 0, :) = [];
indexMatrix = indexMatrix - 1;