%{

Matt Montag
University of Miami
EEN502 Project 2

Experimenting with HRTF and Loudspeaker Arrays

%}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PART B %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear all; close all; clc;

% simulation parameters

l = 2.5;					% length of array (meters)
c = 345;					% speed of sound (m/s)
f = [100 500];				% test frequencies
lambda = c./f;				% wavelength
k = 2*pi*f/c;				% wavenumber
rad = pi/2:-0.01:-pi/2;		% theta for hemisphere sweep (radians)

dur = 4;					% sweep duration in sec
fps = 15;					% movie frames per second
sweep = 360;				% beam direction total swept degrees
step = sweep/dur/fps;		% step size for sweep to achieve fps and dur

for i=1:length(f)
	
	% AVI movie setup
	mov = avifile(['partB-',num2str(f(i)),'hz.avi'],'FPS',fps, ...
		'COMPRESSION','Indeo5','QUALITY',95);

	for point= -90:step:(-90+sweep);  % main lobe points this direction
		point = point + .0001; % prevent divide by zero
		if point > 90
			point = 180-point; % sweep back down after it gets to 90
		end
		cs = c/sin(pi*point/180); % equation for sweeping speed
		ks = 2*pi*f/cs; % wavenumber of sweeping speed
		
		% beam pattern
		
		for j = 1:length(rad)
			p(j) = sin(k(i)*l*sin(rad(j))/2-ks(i)*l/2)/ ...
				(k(i)*l*sin(rad(j))/2-ks(i)*l/2);
		end
		subplot(121), polar(rad,abs(p),'m-');
		title(['Beam pattern for ', num2str(l),'m array (l/\lambda=', ...
			num2str(l/lambda(i)),'; f = ', num2str(f(i)),' hz)']);
		
		% displacement pattern
		
		[X,Y] = meshgrid(0:0.2:10,-5:0.2:5); 
		R = sqrt((X.^2)+(Y.^2));
		sin_tn = Y./(sqrt(X.^2+Y.^2)+.0001); % prevent divide by zero
		m = k(i)*l*sin_tn/2;
		s = ks(i)*l/2;
		q = (cos(k(i)*R)./(R+.0001)).*sin(m-s)./(m-s); % prevent div by 0
		subplot(122), surf(X,Y,q), axis ([0 10 -5 5 -5 5]);
		caxis([-5 5]);
		title(['Displacement pattern for ', num2str(l), ...
			'm array (l/\lambda=',num2str(l/lambda(i)),'; f = ', ...
			num2str(f(i)),' hz)']);
		view(45, 30);
		figure(gcf)
		set(gcf,'Position',[100 100 1000 600]);
		F = getframe(gcf); % add to avi file
		mov = addframe(mov,F);
	end
	mov = close(mov);
end