%Measuring directional characteristics of sound sources
%Made by Benjamin Nimmerrichter 2022/23 for BUT

test = false; %set to true to show random values
factor = 2; %downscale factor, less acurate the higher it gets (recommended 1, 2, 4)
thickness = 5; %size of the squares for each point


scale = 360/factor;
Cmatrix = zeros(scale,scale/2);
offset = scale/2;


a = scale/2;
b = scale+scale/2;

if (test == true)
amt = 300;
in(1,:) = rand(1,amt).*360-180;
in(2,:) = rand(1,amt).*180-90;
in(3,:) = rand (1,amt);
minSpl = 50;
maxSpl = 90;
end

for i = 1:size(in,2)
c = round(in(1,i)/factor); %azimuth
d = round(in(2,i)/factor); %elevation
cpos = (round(offset)+1+c);
dpos = (round(offset/2)+1+d);
    for j = 1:thickness
        for k = 1:thickness
            Cmatrix(cpos+j-round(thickness/2),dpos+k-round(thickness/2)) = in(3,i); %point brightness
        end
    end
end


ICmatrix = interp2(Cmatrix);
IICmatrix = interp2(ICmatrix);

%create a sphere

theta = linspace(0,pi,size(IICmatrix,2));
phi = linspace(-pi,pi,size(IICmatrix,1));
[theta,phi] = meshgrid(theta,phi);

%colormap
color(:,:,1) = ones(size(IICmatrix,1),size(IICmatrix,2)).*IICmatrix;
color(:,:,2) = ones(size(IICmatrix,1),size(IICmatrix,2)).*IICmatrix;
color(:,:,3) = ones(size(IICmatrix,1),size(IICmatrix,2)).*IICmatrix;
rho = 1;

[x,y,z] = sph2cart(theta, phi, rho);
s = surf(x,y,z);

cb = colorbar;
colormap("gray");
cb.TickLabelInterpreter = 'latex';
cb.TicksMode = "manual";
cb.XTick = 0:.25:10;
cb.XTickLabel = string(linspace(minSpl,maxSpl, 5));
cb.Label.String = 'dB(SPL)';
cb.Label.Interpreter = 'latex';
cb.Label.Rotation = 1;
cb.Label.Position = [3.8,0.64];
set(gca,'TickLabelInterpreter','latex')
set(gca,"FontSize",21)
text = "Spherical plot of sound pressure level";
title(text,'interpreter','latex')

s.EdgeColor = 'none';
s.FaceColor = 'interp';
s.CData = color;
s.FaceLighting = "none";
axis equal
view(180,0)