%% student tutorials: plot the world
%% plot the results of the GA on the global with all kinds of cool stuff!
%the code is used after you run the genetic algorithm.

clear all
close all
clc
set(0,'DefaultFigureWindowStyle','docked') %dock the figures..just a personal preference you don't need this.
load('country_lat_long.mat');
locs = country_lat_long.loc
names = country_lat_long.name

Nc = length(locs); %number of countries
load('dist_air.mat')
load('GA_results2.mat')


lat = locs(:,1);
lon = locs(:,2);

%remap
lat_adj  = [];
for i = 1:length(lat)
    if lat(i) > 0
        lat_adj(i) = 90 - lat(i);
    else
        lat_adj(i) = 90 - lat(i);
    end
end

lon_adj = []
for i = 1:length(lon)
    if lon(i) > 0
        lon_adj(i) =  lon(i)-180;
    else
        lon_adj(i) =  lon(i)+180;
    end
end


%convert degs to randians
lat_plot = deg2rad(lat_adj)';
lon_plot = deg2rad(lon_adj)';

%convert to cartesian
R = 1;
loc_x = [];
loc_y = [];
loc_z = [];
loc_x = R .* cos(lon_plot).* sin(lat_plot);
loc_y = R .* sin(lon_plot).* sin(lat_plot);
loc_z = R .*cos(lat_plot);
u =1:size(locs,1); %for adding country names

%use the top path
best_path = path_top(end,:);
%start the path at the north pole!
shift_by = find(best_path == 1);

best_path = circshift(best_path,[0 -shift_by]);
best_path = [1 best_path ];

%get distance between each location, normalize to improve tracking efficiency (see
%code below for use)
each_dist = []
each_dist = diag(dist_air(best_path(1:end-1)',best_path(2:end)'))'/max(diag(dist_air(best_path(1:end-1)',best_path(2:end)'))')


best_names = names(best_path);
best_loc_x = loc_x(best_path)
best_loc_y = loc_y(best_path)
best_loc_z = loc_z(best_path)
%convert to spherical coords
[T,P,R]=cart2sph(best_loc_x,best_loc_y,best_loc_z);
%project onto surface of sphere by making radius constant
R(:)=1.03;
%convert back to cartesian for plotting
[xt,yt,zt]=sph2cart(T,P,R);

%% render out the tracking points..THEN make the video
x0 = 0
y0 = 0
z0 = 0
v_tot = [];
v_idx = [];
Res = 80; %max number of tracking interpolation
for tr = 1:length(xt)-1
    x1 =xt(tr);
    y1 =yt(tr);
    z1 =zt(tr);
    x2 =xt(tr+1);
    y2 =yt(tr+1);
    z2 =zt(tr+1);
    %x2F =xtF(tr+1);
    %y2F =ytF(tr+1);
    %z2F =ztF(tr+1);
    
    v1 = [x1-x0;y1-y0;z1-z0]; % Vector from center to 1st point
    r = norm(v1); % The radius
    v2 = [x2-x0;y2-y0;z2-z0]; % Vector from center to 2nd point
    v3 = cross(cross(v1,v2),v1); % v3 lies in plane of v1 & v2 and is orthog. to v1
    v3 = r*v3/norm(v3); % Make v3 of length r
    % Let t range through the inner angle between v1 and v2
    %lets make the number of points proportional to the distance between
    %the points
    t = linspace(0,atan2(norm(cross(v1,v2)),dot(v1,v2)), ceil(each_dist(tr)*Res));
    v = v1*cos(t)+v3*sin(t); % v traces great circle path, relative to center
    size(v)
    %get listing of ponts for tracking santa flight path
    v_tot = [v_tot v];
    v_idx = [v_idx ceil(each_dist(tr)*Res)];
    tr;
end
v_idx = cumsum(v_idx); %get frames with city is contacted


%now make the listing of the camera aligns

[T,P,R]=cart2sph(v_tot(1,:),v_tot(2,:),v_tot(3,:));
FARR = 10 % how far away should the camera be
[x2F,y2F,z2F]=sph2cart(T,P,FARR);


%% now draw stuff!

%% draw the earth...matlab made this, man..matlab support people, you are amazing! :)
%% plot red dots on the sphere where all the countries are
%create map of the earth using matlab tools!
%adapted from matlab website demo:
%http://www.mathworks.com/products/matlab/examples.html?file=/products/demos/shipping/matlab/earthmap.html

% Clear the axis
cla reset
load('topo.mat','topo','topomap1');
whos topo topomap1
% Create the surface.
[x,y,z] = sphere(50);
props.AmbientStrength = 0.1;
props.DiffuseStrength = 1;
props.SpecularColorReflectance = .5;
props.SpecularExponent = 20;
props.SpecularStrength = 1;
props.FaceColor= 'texture';
props.EdgeColor = 'none';
props.FaceLighting = 'phong';
props.Cdata = topo;
h =surface(x,y,z,props);
colormap(topomap1);
axis square off
view(3)




%% get earth ready to spin and look all cool
axis vis3d %freeze aspect ratio
hold on
plot3(loc_x,loc_y,loc_z,'or','markersize',3,'MarkerFaceColor','y');; %plot country dots
h1 = camlight('right')
time_take1 = []
time_take2 = []
ht=[]
Ho_Time = 40; %how often throughout the entire sequence does santa change his face :P
frames = 1:1:length(v_tot);
t= linspace(0,2*pi, length(frames));
state_x = sin(Ho_Time*t) > 0;
Hn = []
 tm_p = [];
 KK = 1;
 
 %spin the earth!
for TS = 1:3:length(v_tot)
    
    if ~isempty(ht)
        delete(ht);
    end
    
    campos([x2F(TS),y2F(TS),z2F(TS)]); %move the camera to center santa
    camlight(h1,'left');
    drawnow;
    
    %add fire to santas path!..(red to yellow transformation)
    hold on
    for M = 0:20
        if M < TS
            plot3(v_tot(1,TS-M),v_tot(2,TS-M),v_tot(3,TS-M),'dr','markersize',5,'MarkerFaceColor',[1 M/20 0],'MarkeredgeColor',[1 M/20 0]);
        end
    end
        
  
    %draw  ho-ho-hoing santa
    if state_x(TS) 
        ht = text(v_tot(1,TS),v_tot(2,TS),v_tot(3,TS), ['\color{red}*<|\color{white}:\{|\}'],'fontsize',12,'FontWeight','bold','color','w','HorizontalAlignment','center')
        set(ht,'Rotation',-90)
        drawnow
    else
        ht = text(v_tot(1,TS),v_tot(2,TS),v_tot(3,TS), ['\color{red}*<|\color{white}:\{()\}'],'fontsize',12,'FontWeight','bold','color','w','HorizontalAlignment','center')
        set(ht,'Rotation',-90)
        drawnow
    end
    
    %make the cities pop when santa passes over them
    [C id] = min(abs(v_idx -TS))
    if C(1) <= 3
        C(1)
        plot3(xt(id(1)+1),yt(id(1)+1),zt(id(1)+1),'or','markersize',9,'MarkerFaceColor','r');; %plot country dots
        
    end
    

    %print out the images as jpegs
    %eval(['print -djpeg GA_santa_earth_path_',num2str(KK),'.jpeg']);
    KK = KK + 1;

    TS

end

