% Animation of movement of a grating and detector in order to capture the
% energy spectrum from a point source sitting on the Rowland circle.

clear; close all;
vid = VideoWriter('sphericalGratingMovement.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);

% Create rgb progression through a rainbow
bot = 0:8:120; % 0 to 7f in 16 steps
top = 128:8:248; % 80 to ff
all = 0:16:240; % 0 to ff
botc = 0*all; % vector of zeros
midc = botc + 127; % vector of 127s
topc = botc + 255; % vector of 255s
rcomp = [top topc topc flip(all) botc botc bot flip(bot)]/256; % R in rgb
gcomp = [botc bot top flip(top) midc flip(bot) botc botc]/256; % G in rgb
bcomp = [botc botc botc botc bot midc midc flip(bot)]/256; % B in rgb


LL = 11;
r = 10;
grey = [0.5 0.5 0.5];
phistep = pi/360; % Step size in creating crystal surface
phipos = -pi/12:phistep:pi/12; % Vector of angles moving in positive direction from -15 to +15 deg
phineg = flip(phipos); % Vector of angles moving in negative direction from +15 to -15 deg

fwd = 1:128;

for i = [fwd flip(fwd)]
    phi = 10 + (i-1)*70/128;
    newplot
    hold off
    plot([0 0],[-r 2*r],'Color','black','LineWidth',2,'LineStyle','-.'); % vertical line along which the center of the grating moves
    hold on
    j = 128 - i + 1;
    plot([0 0],[0 2*r*sind(phi)],'Color',[rcomp(j) gcomp(j) bcomp(j)],'LineWidth',2);
    len = 2*r*sind(phi);
    plot([0 len*sind(2*phi)],[len len*(1+cosd(2*phi))],'Color',...
        [rcomp(j) gcomp(j) bcomp(j)],'LineWidth',2);
    xstx1 = r*(1 - cos(phipos)); % x-coords of inner edge of bent crystal
    xstx2 = r*1.05*(1 - cos(phineg)) - r*0.05; % x-coords of outer edge of bent crystal
    xstx = [xstx1 xstx2];   % x-coords of bent crystal via concatenation
    xsty1 = r*sin(phipos)+2*r*sind(phi); % y-coords of inner edge of bent crystal
    xsty2 = r*1.05*sin(phineg)+2*r*sind(phi); % y-coords of outer edge of bent crystal
    xsty = [xsty1 xsty2]; % y-coords of bent crystal via concatenation
    xst = fill(xstx,xsty,grey,'LineStyle','none');
    rotate(xst,[0 0 1],-phi,[0,2*r*sind(phi),0]);
    
    xc = r*cosd(phi);
    yc = r*sind(phi);
    viscircles([xc yc],r,'LineStyle','-.','LineWidth',2); % Dot-dashed Rowland circle
    viscircles([0 0],0.05,'Color','black','LineWidth',5); % Rotation point of Rowland circle
    axis equal
    axis off
    xlim([-LL 2*LL]);
    ylim([-LL 2*LL]);
    
    frame = getframe(gcf);
    writeVideo(vid,frame);
end
% Output the movie as an mpg file
close(vid);