clc
clear all
% 从 COMSOL Fem4.mph 导出 MeshData2x.mat（Mesh + Physic + Material）
% 若已有 MeshData2x.mat 仅含 Mesh，运行本脚本会补全 Physic/Material 并覆盖保存

rootDir = fileparts(mfilename('fullpath'));
outFile = fullfile(rootDir, 'MeshData2x.mat');
mphFile = fullfile(rootDir, 'Fem4.mph');

if exist(mphFile, 'file')
    try
        model = mphload('Fem4.mph');
        [~, m2] = mphmeshstats(model);
        Mesh.Nodes = m2.vertex';
        Elements = m2.elem{4}' + 1;
        Mesh.Elements = sort(Elements, 2);
        Mesh.Domains = m2.elementity{4};
        Faces = m2.elem{3}' + 1;
        Mesh.Faces = sort(Faces, 2);
        Mesh.FacesIndex = m2.elementity{3};
        fprintf('Exported mesh from Fem4.mph: %d nodes, %d tets\n', ...
            size(Mesh.Nodes, 1), size(Mesh.Elements, 1));
    catch e
        warning('mphload failed: %s', e.message);
        if ~exist(outFile, 'file')
            rethrow(e);
        end
        load(outFile, 'Mesh');
        fprintf('Keeping existing Mesh from MeshData2x.mat\n');
    end
elseif exist(outFile, 'file')
    load(outFile, 'Mesh');
    fprintf('Fem4.mph not found — keeping existing Mesh in MeshData2x.mat\n');
else
    error('Neither Fem4.mph nor MeshData2x.mat found.');
end

[Physic, Material, ~, ~] = configPhysicMaterialFem4();
save(outFile, 'Mesh', 'Physic', 'Material', '-v7.3');
fprintf('Saved %s\n', outFile);
