% Program to generate lego sphere with increasing resolution 
% Uses an adaptation of the function platonic_solid, see 
% https://ch.mathworks.com/matlabcentral/fileexchange/28213-platonic_solid 
% Courtesy Kevin Moerman 

clear; close all;

figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none');
fileName = 'legoSphere.mp4'; % Name of file depends on type of crystal sample 
vid = VideoWriter(fileName,'MPEG-4');
vid.Quality = 100;
vid.FrameRate = 15;
open(vid);
set(0,'defaultfigurecolor',[1 1 1]);
set(gca,'linewidth',7);
set(gca, 'Projection','perspective');
lp = [-1 -1 0.1];
myBlue = [0.5 0.55 0.88]; 
LL = 1.34; 
for ii = 4:100 
    ii
    newplot
    hold off
    xlim([-LL LL]);
    ylim([-LL LL]);
    zlim([-LL LL]);
    
    axis equal
    axis off
    
    for jj = -ii:ii
        for kk = -ii:ii
            for ll = -ii:ii
                radNow = ((jj/ii)^2 + (kk/ii)^2 + (ll/ii)^2)^0.5;
                if (radNow <= 1) && (radNow > 1-1/ii)
                    [V,F] = platonic_solid(2,0.5/(0.57735*ii)); % Cube, size = (3^1/2)/2
                    V(:,1) = V(:,1)+jj/ii;
                    V(:,2) = V(:,2)+kk/ii;
                    V(:,3) = V(:,3)+ll/ii;
                    ps = patch('Faces',F,'Vertices',V,'FaceColor',myBlue,'FaceAlpha',1, ...
                        'EdgeColor','none','FaceLighting','flat','DiffuseStrength',1);
                    hold on                  
                end
            end
        end
    end
    %plot3([-LL LL],[-LL LL],[-LL -LL],'color','white', 'LineWidth', 0.1); % dummy line to keep FOV constant
    axis equal
    axis off
    set(gca, 'Projection','perspective');
    set(gca,'View',[30,32]);
    light('Position',lp,'Style','infinite');
    frame = getframe(gcf);
    writeVideo(vid,frame);
    hold off    
end
% Output the movie as an mpg file
close(vid);
