% Program to generate movie of scattering pattern of a regular array 
% (M x N) of circular apertures in two dimensions starting with (1x1), then
% (2x1), (5x1), (2x2), (5x5), (5x5)-skewed. 

clear; close all
vid = VideoWriter('farFieldDotArrayDiffraction.mp4','MPEG-4');
vid.Quality = 100;
vid.FrameRate = 30; % 30 frame/s 
open(vid);
figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none');
set(0,'defaultfigurecolor',[1 1 1]);
% Plotting area 
pos1 = [0 0 1 1]; 

ra = 0.05; % Radius of particles
d = 0.5; % Distance between adjacent circles 
N = [1 2 5 2 5 5]; % Columns
M = [1 1 1 2 5 5]; % Rows 
th = 0:2*pi/50:2*pi;
x_circle = ra * cos(th);
y_circle = ra * sin(th);

for jj = 1:size(N,2)
    for nn = 1:N(jj)
        for mm = 1:M(jj) 
            firstCircleX = -d*(N(jj)-1)/2; % x-coordinate of first drawn circle 
            firstCircleY = -d*(M(jj)-1)/2; % y-coordinate of first drawn circle 
            xvals = x_circle + firstCircleX + d*(nn-1);
            yvals = y_circle + firstCircleY + d*(mm-1);
            plot(xvals,yvals,'k','LineStyle','none');
            pp = fill(xvals,yvals,'k');
            hold on 
        end
    end
    % Add white circles at corners to stop saved image shrinking to size of
    % present ensemble 
    for aa = -2:4:2
        for bb = -2:4:2
            x_circle = ra * cos(th) + aa;
            y_circle = ra * sin(th) + bb;
            plot(x_circle, y_circle,'w*','LineStyle','none');
            pp = fill(x_circle, y_circle, 'w');
            pp.LineWidth = 0.0001;
            pp.EdgeColor = [0.99 0.99 0.99];
        end
    end
    axis equal 
    xlim([-2 2])
    ylim([-2 2])
    axis off
    hold off 
    % filename = 'circles.png';
    % myAxes=findobj(pic1,'Type','Axes');
    % exportgraphics(myAxes,filename,'Resolution',300); 
    
    % % Subplot of FT of ensemble 
    % subplot('position',pos2); 
    % I = imread(filename);
    % hold off
    % I1 = double(I);
    % I1=imcomplement(rgb2gray(I1));
    % F = fft2(I1);
    % F = fftshift(F);
    % minInt = min(min((abs(F)).^0.4)); % Power 0.4 compresses intensity scale
    % maxInt = max(max((abs(F)).^0.4));
    % xsize = round(0.1*size(F,1)); % 10% of linear dimension of FT image 
    % F = F(4*xsize:6*xsize,4*xsize:6*xsize); % Central 20% x 20% of FT 
    % imshow(((abs(F)).^0.4),[minInt,maxInt/(1+jj/5)]); % Scale varies with jj to keep nice intensity range
    % greenBlack = customcolormap([0 1], {'#00ff00','#000000'}); % Similar to laser green speckle 
    % colormap(greenBlack);
    frame = getframe(gcf);
    writeVideo(vid,frame);
end
close(vid);
