% Movie of RF cavity E-field oscillations 

clear; close all; 
vid = VideoWriter('rfCavity.mp4','MPEG-4'); 
vid.Quality = 100; 
vid.FrameRate = 30; 
open(vid); 
figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none'); 
set(0,'defaultfigurecolor',[1 1 1]);
set(gca,'linewidth',7); 
set(gca,'View',[0,0]); 
set(gca, 'Projection','perspective');

hold off; 
lp = [0 -1 0.4]; 
light('Position',lp,'Style','infinite');
for i = 0:pi/60:2*pi-pi/60 
    newplot; 
    xcoords = [-1.5 -1.025 -1.025 1.025 1.025 1.5]; % Draw cavity walls
    ycoords = [0.2 0.2 1 1 0.2 0.2]; 
    plot3(xcoords,[0 0 0 0 0 0],ycoords,'color',[0.4,0.4,0.4], 'LineWidth', 8.0); % plot in red 
    hold on 
    plot3(xcoords,[0 0 0 0 0 0],-ycoords,'color',[0.4,0.4,0.4], 'LineWidth', 8.0); % plot in red 
    lArrow = sin(i);
    bcol = (1 - sin(i))/2; % Colour arrows according to the phase of the RF cycle 
    rcol = (sin(i) + 1)/2; 
    stemwidth = 0.0125;
    tipwidth = 0.025;
    for jj = -0.80:0.16:0.80
        mArrow3([-lArrow 0 jj],[lArrow 0 jj],'color',[rcol 0.0 bcol],'stemWidth',stemwidth,'tipWidth',tipwidth,'facealpha',1 - abs(jj)); % E-field
    end
    r = 0.08;
    hold on; 
    if (i <= pi) 
        [x,y,z] = sphere(64); surf(-1.6 + 0.6*i/pi +x*r,y*r,z*r,'FaceColor',[0.28 0.32 0.64],'EdgeColor','none');
    end 
    if (i > pi) 
        dacc = (i - pi)*0.6/pi + (1.4/pi)*((i - pi) - sin(i - pi));
        [x,y,z] = sphere(50); surf(-1.6 + 0.6*i/pi + dacc + x*r,y*r,z*r,'FaceColor',[0.28 0.32 0.64],'EdgeColor','none');
    end 

    axis square;
    axis off;
    light('Position',lp,'Style','infinite');
    LL = 1.5;
    xlim([-LL LL]);
    ylim([-LL LL]);
    zlim([-LL LL]);
    view(0,0);
    hold off;
    % Store the frame
    frame = getframe(gcf); 
    writeVideo(vid,frame); 
    hold off; 
end
hold off;
% Output the movie as an mpg file
close(vid);