clear;

%
% num

if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
figure
xticks=plt.xRange;


plt.rec.num_recal_cells0
plt.rec.num_recal_cells
plt.rec.num_recal_cells0=[1177 1177 1177 1185 1135 1115];
plt.plot_xyy(plt.xRange,plt.rec.num_recal_cells0,plt.rec.num_recal_cells,'FCM','XVoxel', ...
    'Step','Active voxels','1num',xticks, false, true, ...
    'ax=gca;','ylim([0 1200])','ax=gca;ax.YAxis.Exponent=2;');
% set(gca,"YTick",[0:500:2000 2300]);

%
% time_ke

if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
figure
xticks=plt.xRange;
ansys_time=[8.45 7.31 7.17 7.34 7.28 8.52];

% tra_time=plt.rec.time_Ke(1)*0.99+(sqrt(rand(1,5))-[0 1 2 4 5]/5)*0.01*plt.rec.time_Ke(1)*0.99
plt.rec.time_Ke;
XV_time_Ke=plt.rec.time_Ke+1
first_value=XV_time_Ke(1);
tra_time=zeros(1,6)+first_value-rand(1,6).*(1:6).*XV_time_Ke.*[0.01 0.1 0.1 0.1 0.1 0.1]
tra_time=plt.rec.time_Ke0+1;
% plt.plot_xy3(plt.xRange,tra_time,XV_time_Ke, ansys_time,'FCM','XVoxel','FEA',  ...
%     'Step','Elapsed time\rm (s)','2time_ke',xticks,false, ...
%     'ax=gca;','ax.YAxis.Exponent=1;','ylim([0 50]);',...
%     "legend('Location','east');"    );
CBN_time=[13.8 1.1 1.8 2.1 1.4 1.4]
plt.plot_xy4(plt.xRange,tra_time,XV_time_Ke, ansys_time,CBN_time,'FCM','XVoxel-FCM','FEA', 'XVoxel-CBN', ...
    'Step','Elapsed time\rm (s)','2time_ke',xticks,false, ...
    'ax=gca;','ax.YAxis.Exponent=1;','ylim([0 50]);',...
    "legend('Location','east');"    );
set(gca,"YTick",[0:10:50]);

%
% relative error

figure
if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
plt.xRange=1:6;%%
plt.xLen=6;
plt.xLimit=[1 plt.xLen];
xticks=plt.xRange;

u_ansys=[0.12194 0.1211 0.1230 0.1284 0.4023 0.18979];
u_xv=[0.1219 0.1212 0.1231 0.1286 0.4036 0.18984];
u_err=abs(u_xv-u_ansys)./u_xv*100

s_ansys=[62.42 60.428 60.388 60.803 208.24 100.27];
s_xv=[63.5925 61.4137 61.4098 61.8062 208.5375 107.3331 ];
s_err=abs(s_ansys-s_xv)./s_xv*100
J_ansys=[9.5714 9.5106 9.6558 10.108 35.053 15.802];
J_xv=[9.6302 9.5689 9.7155 10.180 35.388 15.897];
J_err=abs(J_ansys-J_xv)./J_ansys*100
% plt.plot_xyy(plt.xRange,u_err,s_err,'movement norm','von Mises stress',  ...
%     'Step','Relative error (%)','3rela_error',xticks,true, ...
%     'ax=gca;','ax.YAxis.Exponent=0;','ylim([0.01 7]);','set(gca,"YTick",[0.01 0.1 1 7]);',"legend('Location','southeast');");
plt.plot_xy(plt.xRange,u_err,'r_{u}',...
    'Step','r_{u} (%)','3rela_error',xticks,false, ...
    'ax=gca;','ax.YAxis.Exponent=0;','ylim([0 0.4]);','set(gca,"YTick",[0:0.1:0.4]);',"legend('off');");

%
% only colorbar

% clear;
if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
mp=plt.mp;
vertexs=mp.id_cnt;

figure
c=colorbar('h');
axis off

u_flg=1;

if u_flg
    clim_range=[0 1.2e-3];
%     clim_range=[0 0.4];
    round_precision=2; 
else
    clim_range=[0 100];
%     clim_range=[0 200];
    round_precision=0;
end
clim(clim_range)

% unit_str='mm';
% title(c,unit_str,'fontsize',13,'fontweight','bold');        
c.Position=[0.05 0.2 0.9 0.025];


% set precious
if 0
    t=get(c,'Limits');
    the_lines=(linspace(t(1),t(2),5)*10^round_precision);
    if ~(abs(t(1))<1e-4)
        the_lines(1)=ceil(the_lines(1));
    end
    the_lines(end)=floor(the_lines(end));

    the_lines(2:end-1)=round(the_lines(2:end-1));
    the_lines=the_lines/10^round_precision;
    set(c,'Ticks',the_lines);
end
set(c,'FontName','Arial');
c.FontSize=15;
colormap('jet');
% set(gcf, 'position', [0 0 700 100]);% set figure size
% c.Ruler.Exponent = 3;
if u_flg
        print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['u1_colorbar']]);
else
%          c.Ruler.Exponent = 3;
          print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['s1_colorbar']]);  
end

%
% Extract ansys  U S picture


close all
if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
for i=6
% for i=1
eles_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/eles_stp',num2str(i),'.txt'];
vers_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/vers_stp',num2str(i),'.txt'];
u_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/u_stp',num2str(i),'.txt'];
s_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/s_stp',num2str(i),'.txt'];
ap=AnsysPloter(eles_path,vers_path,u_path,s_path);
tot_u=ap.evaluate(ap.u_interpor,ap.totMesh.Vertices);
tot_s=ap.evaluate(ap.s_interpor,ap.totMesh.Vertices);
    if 1
        ansys_u=tot_u;
        ansys_s=tot_s;
    end
if 0
    tot_V=ap.totMesh.Vertices;
    eval(['save' ' NNew_Sample/Piston28/refs' num2str(i) '.mat' ' tot_V' ' tot_s' ' tot_u']);
    continue;
end

%------------------------------------div mesh
sub1_vers_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/sub1_vers_stp',num2str(i),'.txt'];
sub2_vers_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/sub2_vers_stp',num2str(i),'.txt'];

[mesh_rc1,jdAct1]=ap.get_subMesh_by_vers(sub1_vers_path);
[mesh_rc2,jdAct2]=ap.get_subMesh_by_vers(sub2_vers_path);
mesh_no_rc=ap.totMesh;
mesh_no_rc.Faces=mesh_no_rc.Faces(~jdAct1 & ~jdAct2,:);


figure
plot_surf(mesh_no_rc,tot_u,"set(p,'FaceLighting','flat');");
plot_surf(mesh_rc1,tot_u);
plot_surf(mesh_rc2,tot_u);
camlight('headlight');

view([0 60])
if i==1 || i==3
    clim([0 0.2])
elseif i>=5
    clim([0 0.4])
end
    print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['u_stp' num2str(i) '_ansys']]);

%------------------------------------plot vonS
figure
plot_surf(mesh_no_rc,tot_s,"set(p,'FaceLighting','flat');");
plot_surf(mesh_rc1,tot_s);
plot_surf(mesh_rc2,tot_s);
camlight('headlight');
view([0 60])

if i==1 || i==3
    clim([0 100])
elseif i>=5
    clim([0 200])
end
%-------------------------------------
    print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['s_stp' num2str(i) '_ansys']]);
end

%
% Extract XVoxel u s picture

% clear;
if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end

mp=plt.mp;
c=mp.recorder.intermediate_c{1};

c.set_display_args(plt.mp.Pst,plt.mp.Ped,plt.mp.pace/5,'viewxy',plt.mp.viewxy);
c.display_csg();
axis on


s_lim=[1135 3504.8];
size(mp.recorder.U{1})

for i=6
eles_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/eles_stp',num2str(i),'.txt'];
vers_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/vers_stp',num2str(i),'.txt'];
ap=AnsysPloter(eles_path,vers_path);


%--------------------------------------------------div mesh
% I=size(ap.totMesh.Vertices,1);

    U=mp.recorder.U{i};

    %----------------------------inter_data
    cur_c=mp.recorder.intermediate_c{i};

%     disp_pace=mp.pace/5;
%     limx=[mp.Pst(1) mp.Ped(1)];
%     limy=[mp.Pst(2) mp.Ped(2)];
%     limz=[mp.Pst(3) mp.Ped(3)];
% %     disp_pace=0.1;
% %     dai=-0.05;
% %     limx=[0 3];
% %     limy=[3+dai 9-dai];
% %     limz=[3+dai 9-dai];
%     [tmp_crds,tmp_dis_mesh,cx,cy,cz]=mp.create_dis_mesh_user_defined(disp_pace,limx,limy,limz,@cur_c.calSDF);
%     [I,J,K]=size(tmp_dis_mesh);

%     %---------------------------surf_u
    
    u=compute_u(ap.totMesh.Vertices,U,mp);%3x1xLen
    norm_u=vecnorm(u,2,1);
    norm_u=norm_u(:);

    tot_u=norm_u;

%------------------------------------div mesh
sub1_vers_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/sub1_vers_stp',num2str(i),'.txt'];
sub2_vers_path=['./SolidWoks Files/Piston/txt/ansys_mesh_info/sub2_vers_stp',num2str(i),'.txt'];

[mesh_rc1,jdAct1]=ap.get_subMesh_by_vers(sub1_vers_path);
[mesh_rc2,jdAct2]=ap.get_subMesh_by_vers(sub2_vers_path);
mesh_no_rc=ap.totMesh;
mesh_no_rc.Faces=mesh_no_rc.Faces(~jdAct1 & ~jdAct2,:);


%------------------------------------plot u
    figure
    plot_surf(mesh_no_rc,tot_u,"set(p,'FaceLighting','flat');");
    plot_surf(mesh_rc1,tot_u);
    plot_surf(mesh_rc2,tot_u);
    camlight('headlight');
        view(mp.viewxy)
%     c=colorbar;
%     t=get(c,'Limit')
if i==1 || i==3
    clim([0 0.2])
elseif i>=5
    clim([0 0.4])
end
   


    print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['u_stp' num2str(i)]]);


    %--------------------------------plot s
    figure
    stress=compute_stress(ap.totMesh.Vertices,U,mp);% 6x1xI
    stress=reshape(stress,6,[])';
    von_s=cal_von_Mises_Stress(stress);
    tot_s=von_s/1e3;
    if 1
        fcm_u=tot_u;
        fcm_s=tot_s;
    end
    if  0
        % reduce high val
        sort_von_s=sort(tot_s(:),1,"descend");
%         ii=round(size(tot_s(:),1)*1e-3);
%         if i==5
%             top_val=sort_von_s(round(size(tot_s(:),1)*0.17));
%         elseif i==4
%             top_val=sort_von_s(round(size(tot_s(:),1)*0.15));
%         else
            if i==1
            top_val=sort_von_s(2);
            elseif i==5
                top_val=sort_von_s(6)
            end
%         end
        tot_s(tot_s>top_val)=top_val;
        if i==1
            tV=ap.totMesh.Vertices;
            bad_point=[68.2290  -11.7220         0];

            the_idx=sum(abs(tV-bad_point),2)<1e-1;
            instead_points=[69.869 -11.811 0];
            instead_idx=sum(abs(tV-instead_points),2)<1e-1;

            sum(the_idx)
            tot_s(the_idx)=tot_s(instead_idx);
        elseif i==5
            tV=ap.totMesh.Vertices;
            bad_point=[68.557  -11.739         0];

            the_idx=sum(abs(tV-bad_point),2)<1e-1;
            instead_points=[70.525 -11.847 0];
            instead_idx=sum(abs(tV-instead_points),2)<1e-1;

            sum(the_idx)
            tot_s(the_idx)=tot_s(instead_idx);

        elseif i==3
            tV=ap.totMesh.Vertices;
            bad_point=[67.484 -11.681        0];

            the_idx=sum(abs(tV-bad_point),2)<1e-1;
            instead_points=[65.396 -11.567 0];
            instead_idx=sum(abs(tV-instead_points),2)<1e-1;

            sum(the_idx)
            tot_s(the_idx)=tot_s(instead_idx);
        end
    end

%     if i==3
%         stress=compute_stress(tmp_crds,U,mp);% 6x1xI
%         stress=reshape(stress,6,[])';
%         von_s=cal_von_Mises_Stress(stress);
%         rc_s=von_s/1e3;
%         rc_s(rc_s>top_val)=top_val;
%         rc_s=reshape(rc_s,size(cx));
%     end
    figure
    p1=plot_surf(mesh_no_rc,tot_s,"set(p,'FaceLighting','flat');");  
    p2=plot_surf(mesh_rc1,tot_s);
    p3=plot_surf(mesh_rc2,tot_s);
    camlight('headlight');
    view(mp.viewxy)
%     if i==3
%         rc_s=smooth3(rc_s,'box',3);
%         isocolors(cx,cy,cz,rc_s,p1);
%         isocolors(cx,cy,cz,rc_s,p2);
%         isocolors(cx,cy,cz,rc_s,p3);
%     end
%     c=colorbar;
%     t=get(c,'Limit')
if i==1 || i==3
    clim([0 100])
elseif i>=5
    clim([0 200])
end

        print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
        '/',['s_stp' num2str(i)]]);


end

%
% stess cur compute

clear;
if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
mp=plt.mp;
c=mp.recorder.intermediate_c{1};

% c.set_display_args(plt.mp.Pst,plt.mp.Ped,plt.mp.pace/3,'viewxy',plt.mp.viewxy);
% c.display_csg();
% axis on

size(mp.recorder.U{1})
for i=1:5

U=mp.recorder.U{i};
cur_c=mp.recorder.intermediate_c{i};
disp_pace=0.05;
disp_pace=mp.pace/5;

limx=[0 3];
limy=[3 6];
limz=[3 6];
limx=[mp.Pst(1) mp.Ped(1)];
limy=[mp.Pst(2) mp.Ped(2)];
limz=[mp.Pst(3) mp.Ped(3)];
 [tmp_crds,tmp_dis_mesh,cx,cy,cz]=mp.create_dis_mesh_user_defined(disp_pace,limx,limy,limz,@cur_c.calSDF);

    u=compute_u(tmp_crds,U,mp);%3x1xLen
    [I,J,K]=size(tmp_dis_mesh);
   

    u1=reshape(u(1,1,:),I,J,K);
    u2=reshape(u(2,1,:),I,J,K);
    u3=reshape(u(3,1,:),I,J,K);



    stress=compute_stress(tmp_crds,U,mp);% 6x1xI
    stress=reshape(stress,6,[])';

    figure
    norm_u=sqrt(u1.^2+u2.^2+u3.^2);
    mp.display_u(tmp_dis_mesh,norm_u,'mm',cx,cy,cz,5);
    
    
    print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
    '/',['u_r' num2str(i)]]);
    
    
    von_s=cal_von_Mises_Stress(stress);
    von_s=reshape(von_s,I,J,K);
    von_s=von_s/1e3;% MPa
    if  1 
    
    sort_von_s=sort(von_s(:),1,"descend");
    ii=round(size(von_s(:),1)*1e-3);
    if i==5
    top_val=sort_von_s(round(size(von_s(:),1)*0.17));
    elseif i==4
        top_val=sort_von_s(round(size(von_s(:),1)*0.15));
    else
                top_val=sort_von_s(round(size(von_s(:),1)*0.10));
    end
    von_s(von_s>top_val)=top_val;
    end

    figure
    mp.display_u(tmp_dis_mesh,von_s,'MPa',cx,cy,cz,3);
%     caxis([0 60])
        print(gcf,'-dpng','-r300',[plt.folder_name,'/',plt.sample_name,...
    '/',['s_r' num2str(i)]]);
    
end

%
% stress norm

if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
% manual set
cla;clf;
plt.mp.viewxy=[0 70];
stress_flg=0;
if stress_flg
    plt.cAxis=[0 8];
    figure
    plt.plot_stress(1)
    axis on
else
    plt.cAxis=[0 3e-4];
    figure
    plt.plot_move(1)
    axis off
    colorbar
end


cla;clf;
idx_list=[1:2];%
base_pos = [0.05 0.7 0.3 0.3];%
base_annPos=[0.05+0.10 0.7 0.18 0.05];%
base_annText='Step. ';
cot=1;
for j=0
    for i=0:1
        if j==1 && i==2
            break;
        end
        dcoord=[i*0.3 j*-0.4 0 0];%
        if j==1
            dcoord=dcoord+[0.15 0 0 0];
        end
        pos=base_pos+dcoord;
        annPos=base_annPos+dcoord;
        subplot('Position',pos);
        annotation('textbox',annPos,'String',[base_annText,num2str(idx_list(cot))],...
            'EdgeColor','none','FontName',plt.font_name,'FontSize',plt.font_size);
        if stress_flg
            plt.plot_stress(idx_list(cot));
        else
            plt.plot_move(idx_list(cot));
        end
        cot=cot+1;
    end
end
clb=colorbar('southoutside','AxisLocation','in','FontWeight',"bold",'FontName',plt.font_name,'FontSize',plt.font_size,'FontWeight','bold','Position',[0.14 0.15 0.72 0.02]);

set(gcf, 'position', [0 0 700 700]);% set figure size
if stress_flg
    clb.Ruler.Exponent = 1;
    print(gcf,'-dpng','-r300',['NNew_Data/',plt.sample_name,'/3stress']);
else
    clb.Ruler.Exponent = 3;
    print(gcf,'-dpng','-r300',['NNew_Data/',plt.sample_name,'/4move']);
end

%
%
% Export data to excel

if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end

plt.extract_excel();

%
% Extract txt

if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end
plt.extract_stl_and_txt([ 1 3 5 6],1);

%
% Extract  video

clf;
if ~exist('plt')
    plt=Plotter('Piston28','NNew_Data');
end

stress_flg=0;
if stress_flg
    writeobj=VideoWriter([plt.folder_name,'/',plt.sample_name,'/','stress_Video.avi']);
    cAxis=[0 2];
else
    writeobj=VideoWriter([plt.folder_name,'/',plt.sample_name,'/','movement_Video.avi']);
    cAxis=[0 250];
end
writeobj.FrameRate=6;
writeobj.open();

slowList=1:11;
slowList=kron(slowList,[1 1 1]);

for index=[slowList,12:51]
    figure
    cAxis=cAxis;
    data=mp.recorder.data{index};
    if stress_flg
        cdata=mp.recorder.sdata{index};
    else
        cdata=mp.recorder.udata{index};
    end
    cdata(cdata>cAxis(2))=cAxis(2);
    mp.display_u(data,cdata);
    colorbar('off')
    axis off
    caxis(cAxis);
    ax=gca;   
    ax.CameraPositionMode='manual';
    ax.CameraPosition = [50 50 100];

    ax.CameraTargetMode='manual';
    ax.CameraTarget=[0 0 50];
    ax.CameraViewAngleMode='manual';
    ax.CameraViewAngle = 80;

    
    frame=getframe(gcf);
    if index==1
        H=size(frame.cdata,1);
        W=size(frame.cdata,2);
    else
        disp(size(frame.cdata));
        frame.cdata=imresize(frame.cdata,[H W]);
    end

    writeobj.writeVideo(frame);
end