% Plot commands for the 3D voronoi polyhedra.

function vorPlot3dV02(M)

currentMax = 0;
j=0;

for i=1:(size(M,1))
    for j=1:(size(M,1))
        if dist3d(M(i,2), M(i,3), M(i,4), M(j,2), M(j,3), M(j,4))>currentMax
            x=0
            currentMax = dist3d(M(i,2), M(i,3), M(i,4), M(j,2), M(j,3), M(j,4));
        end
    end
end

radius = currentMax;


% find the center of mass by summing the x, y, and z values of each point,
% then dividing by the number of points

currentX = 0;
currentY = 0;
currentZ = 0;

for i=1:(size(M,1))
    currentX = (M(i,2))+currentX;
    currentY = (M(i,3))+currentY;
    currentZ = (M(i,4))+currentZ;
end

centerX = currentX/(size(M,1));
centerY = currentY/(size(M,1));
centerZ = currentZ/(size(M,1));
center = [centerX, centerY, centerZ];

% define a regular dodecahedron, centered at the origin with radius of one.

BOUND = [[.3568220896, -.9341723582, 0.]; [-.3568220896, -.9341723582, 0.]; [-.5773502686, -.5773502686, .5773502686]; [0., -.3568220896, .9341723586]; [.5773502686, -.5773502686, .5773502686]; [0., .3568220896, -.9341723582]; [-.5773502686, .5773502686, -.5773502686]; [-.3568220896, .9341723586, 0.]; [.3568220896, .9341723586, 0.]; [.5773502686, .5773502686, -.5773502686]; [0., -.3568220896, -.9341723582]; [-.5773502686, -.5773502686, -.5773502686]; [-.9341723582, 0., -.3568220896]; [-.9341723582, 0., .3568220896]; [-.5773502686, .5773502686, .5773502686]; [0., .3568220896, .9341723586]; [.5773502686, .5773502686, .5773502686]; [.9341723586, 0., .3568220896]; [.9341723586, 0., -.3568220896]; [.5773502686, -.5773502686, -.5773502686]];

% explode BOUND about the origin

BOUND = BOUND*radius*1.5; 

M = remindex(M);
for i = 1:size(BOUND,1)
    BOUND(i,1)=BOUND(i,1)+centerX;
    BOUND(i,2)=BOUND(i,2)+centerY;
    BOUND(i,3)=BOUND(i,3)+centerZ;
end
F = [M; BOUND];


[V,C] = voronoin(F);

hold on;
figure(1)
for hull = 1:size(M,1);
    % For each volume 'hull'
    X = V(C{hull},:)      % View hull Voronoi cell.
    K = convhulln(X);
    
  
    d = [1:size(K,2), 1];
    % d = [1 2 3 1];       % Index into K
    % For each face i;
    for i = 1:size(K,1)
        j = K(i,d);
        % Plot a polygon that is white with black lines, on each face i
        h(i)=patch(X(j,1),X(j,2),X(j,3),'w');
        
        % Uncomment this for transparent polyhedra.
        % set(h(i),'facecolor', 'none');
    end
end

view(3)
axis equal
title('The total voronoi volume')
rotate3d;
