%% Sea shell using parametric equations https://www.youtube.com/watch?v=yvouHwWRDro
clear all; close all;
%create parameter domains
U = linspace(0,4*pi,50);
V = linspace(0,2*pi,50);

clear x y z

[U,V] = meshgrid(U,V);
% at this point you could just calculate x,y,z for all U,V
% to do this you would do :
% x = 2 * (1-exp(U/(6*pi))) .*cos(U) *cos(V/2) .^2; % and so on
% but instead, we want to simulate growth, so we loop over all the
% possible u,v pairs (our angles), and plot a movie.


% keep track of our previous x,y,z
% store these in xold, yold, zold
% then we can plot two values at a time and get a line that connects them.
xold = [0 0];
yold = [0 0];
zold = [0 0];
iter = 0;
f = 0; %important to file names
for j = 1:size(U,2)
    for i = 1:size(U,1)
        iter = iter +1;
        u = U(i,j); v = V(i,j);
        x = 2 * (1-exp(u/(6*pi))) .*cos(u) *cos(v/2) .^2;
        y = 2 * (-1+exp(u/(6*pi))) .* sin(u) .*cos(v/2) .^2;
        z = 2*(1-exp(u/(3*pi)) -sin(v) +exp(u/(6*pi)) .*sin(v));
        
        set(gcf, 'Position', [0, 0, 1000, 400]); %plots are same shape, length/idth proportions
        
        subplot(1,2,1)
        view([-5 -5])
        plot3([xold x],[yold y],[zold z],'o-','MarkerSize',1,'MarkerFaceColor','k','LineWidth',1)
        pause(0.0000001)
        hold on
        % these 3 lines are optional-- depends if you want
        % the same axis the whole time or if you want it to rescale
        xlim([-2 2])
        ylim([-4 3])
        zlim([-8 1])
        
        
        
        subplot(1,2,2)
        view([0 90])
        plot3([xold x], [yold y], [zold z],'.-','MarkerSize',1,'MarkerFaceColor','k','LineWidth',1)
        pause(0.01)
        hold on
        if j > 40
        xlim([-2.5 2])
        ylim([-2 1.5])
        zlim([-4 1])
        end
        hold on
        
        
        xold = x;
        yold = y;
        zold = z;
        



%save every 25th frame:
        if mod(iter+24,25) == 0
            f=f+1;
            fname = ['spiral_',sprintf('%03d',f),'.png'];
            saveas(gcf, fname)
            disp(['saving ' fname])
        end
    end
end
