classdef helperGlobeView < handle
    properties
        FigureHandle
        EarthImage = 'EarthMap.jpg'
        NumPanels = 180;
        FaceAlpha = 1;
        Radius = 6371000; % Earth radius in meters
        Rotation = 0; % Ration angle in degrees
        RotationRate = 0.004178; % Earth rotation rate in degrees/sec;
        ViewAngles % View angels [azimuth,elevation] in degerees
        Globe % Handle to the globe surf plot.
        SpaceColor = 'k';
    end
    
    methods
        function viewer = helperGlobeView(initialRotation,viewAngles,figureHandle)
            if nargin <3
                figureHandle = figure;
                if nargin < 2
                    viewAngles = [0 0];
                    if nargin < 1
                        initialRotation = 0;
                    end
                end
            end
            
            viewer.FigureHandle = figureHandle;
            viewer.ViewAngles = viewAngles;
            viewer.Rotation = initialRotation;
            
            if isempty(viewer.FigureHandle.Children) % When the figure does not have an Axes, create one.
                axes(viewer.FigureHandle,'NextPlot','add', 'Visible','off',...
                    'Position', [0 0 1 1]);
            else
                set(viewer.FigureHandle.Children,'NextPlot','add', 'Visible','off',...
                    'Position', [0 0 1 1]);
            end
            
            % Create a sphere use the generated ellipsoid/sphere.
            [x,y,z] = ellipsoid(0,0,0,viewer.Radius,viewer.Radius,viewer.Radius,...
                viewer.NumPanels); % Assume spherical earth
            viewer.Globe = surf(viewer.FigureHandle.Children,...
                x, y, -z, 'FaceColor', 'none', 'EdgeColor', 0.5*[1 1 1]);
            
            % Set initial rotation using hgtransform.
            if viewer.Rotation
                hgx = hgtransform;
                set(hgx,'Matrix', makehgtform('zrotate',viewer.Rotation * pi/180));
                set(viewer.Globe,'Parent',hgx);
            end
            
            % Add/patch earth map on the globe.
            cdata = imread(viewer.EarthImage);
            set(viewer.Globe, 'FaceColor', 'texturemap', 'CData', cdata,...
                'FaceAlpha', viewer.FaceAlpha, 'EdgeColor', 'none');
            
            % Change view and set background colors.
            set(viewer.FigureHandle,'Color', viewer.SpaceColor);
            set(viewer.FigureHandle.Children, 'Color',viewer.SpaceColor);
            view(viewAngles);
            axis equal;
        end
        
        % Rotate earth for a specfied time step dt.
        function rotate(viewer,dt)
            deletaAngle = viewer.RotationRate * dt;
            hgx = hgtransform;
            viewer.Rotation = mod(viewer.Rotation + deletaAngle, 360);
            set(hgx,'Matrix', makehgtform('zrotate',viewer.Rotation *pi/180));
            set(viewer.Globe,'Parent',hgx);
        end
        
        
    end
    
    
end