%bauble
% Function which loads a bitmap image and texture maps this to a sphere.
%
% LAST UPDATED by Andy French May 2017

function bauble

%Initialise gloabl variable d to stoe information
global d

%Default background colour
d.background_color = [1,1,1];

%Initialize file counter
d.fc = 1;

%

%Chose image file to load
[d.filename, d.pathname] = uigetfile( {'*.jpg;*.bmp;*.png;*.gif;*tif',...
    'Bitmap images (*.jpg,*.bmp,*.png,*.gif,*.tif)'},...
    'Select location of image file(s)...', ...
    'multiselect', 'off' );
if d.filename == 0
    return
end

%Load image into an NxMx3 matrix of values. i.e. Red, Green and Blue colour
%planes. cmap is the local colormap associated with the image, and alpha is
%a matrix which defines the transparency of the image
[I,cmap,alphamap] = imread( [d.pathname,d.filename] );

%Get image information stored within the file
d.info = imfinfo( [d.pathname,d.filename] );
dim = size(I);

%Set the colour matrix to be within the range 0...1, and a double precision
%number. Most full colour images are stored as 8 bit integers.
if numel(dim) == 2
    %An indexed image like a GIF has a colourmap rather than three R,G,B
    %colour intensities.
    I = 255*ind2rgb(I,cmap);
end
I = double(I)/255;

%Flip image, as pixel(1,1) is by convention the top left rather than the
%bottom left.
I = flipdim(I,1);

%Generate x,y,z matrices of a unit sphere
elev = linspace( -pi/2,pi/2,dim(1) );
azi = linspace( 0, 2*pi, dim(2) );
[azi,elev] = meshgrid(azi,elev);
x = cos(elev).*cos(azi);
y = cos(elev).*sin(azi);
z = sin(elev);

%Create a figure and plot the image
d.fig = figure('color',d.background_color,'name',d.filename,'KeyPressFcn',...
    @keypressfunc,...
    'renderer','opengl');
surf( x,y,z,I);
shading interp;
axis vis3d
axis off;
zoom(1.5)

%%

%Key press handler
function keypressfunc( fig,evnt )

%Allow read-write usage of global variable d
global d

%Get the string of the current key press
k = get( fig,'currentkey');

%Actions, depending on the key pressed...
if strcmp(k,'p') == 1
    %Print JPEG image
    d.fc = d.fc + 1;
    print( gcf, [d.pathname,'bauble ',num2str(d.fc),' ',...
        strrep( d.filename, lower(d.info.Format),'jpg')],'-djpeg','-r300' );
elseif strcmp(k,'b') == 1
    %Change background to black
    d.background_color = [0,0,0];
    set(d.fig,'color',d.background_color);
elseif strcmp(k,'w') == 1
    %Change background to white
    d.background_color = [1,1,1];
    set(d.fig,'color',d.background_color);
elseif strcmp(k,'q') == 1
    %Close figure
    close(gcf);
end

%End of code