clc
clear all

%参考四面体
%顶点1-[1,0,0] 2-[0,1,0] 3-[0,0,1] 4-[0,0,1]

% 算例配置（改波长/材料/边界请编辑 case_config.m）
[phy, cfg] = case_config();

%读取网格
load(cfg.meshMatFile);
mesh.incIndex=findTri(phy.inc,mesh);
mesh.outIndex=findTri(phy.out,mesh);
[mesh.PBCIndex,mesh.origIndex]=findPBCIndex(phy.src,phy.dst,cfg.pbcAngle,mesh);
mesh.PBCphi=cfg.pbcPhi;

%矩阵组装
solver.Ai=[];solver.Aj=[];solver.Av=[];
solver.dof=mesh.NbrEdge*2+mesh.NbrFace*2;
solver.b=zeros(solver.dof,1);
solver=assembly_equ(phy,mesh,solver);
%出射处理
solver=assembly_out(phy,mesh,solver);
%入射处理
solver=assembly_inc(phy,mesh,solver);
solver.A=sparse(solver.Ai,solver.Aj,solver.Av);
%Bloch boundary
solver=assembly_rbc(mesh,solver);

%求解
solver.A=solver.P'*solver.A*solver.P;
solver.b=solver.P'*solver.b;
r=symamd(solver.A);
solver.A=solver.A(r,r);
solver.b=solver.b(r);
solver.x=solver.A\solver.b;
q=zeros(length(r),1);
for i=1:length(r)
    q(r(i))=i;
end
solver.x=solver.x(q); 
solver.x=solver.P*solver.x;

%计算电场
triIndex=findTri([2,5],mesh);
[x,y,z,normE]=get_ele(triIndex,mesh,solver);
patch(x,z,normE,'EdgeAlpha',0)
axis equal;
colormap jet;
colorbar
max(max(normE))