
headshape = ft_read_headshape('flattenedspherical-head.stl');
helmet = ft_read_headshape('flattenedspherical-helmet.stl');

nas = [+100 0 -10];
ini = [-100 0 -10];
lpa = [0 +80 -10];
rpa = [0 -80 -10];

headshape.fid.pos = [
  nas
  ini
  lpa
  rpa
  ];

headshape.fid.label = {
  'nas'
  'ini'
  'lpa'
  'rpa'
  };

figure
ft_plot_headshape(headshape, 'facecolor', 'skin_light', 'axes', true)
alpha 0.5 % slightly transparent
ft_headlight

%%

% specify the XYZ coordinate system as ALS or anterior-left-superior
% it is not CTF, since the axes don't go through the nasion and ears
headshape.coordsys = 'als';
helmet.coordsys = 'als';

%%

% this places a lot of electrodes, see https://doi.org/10.1016/s1388-2457(00)00527-7
cfg = [];
cfg.fiducial.nas   = nas;
cfg.fiducial.ini   = ini;
cfg.fiducial.lpa   = lpa;
cfg.fiducial.rpa   = rpa;
cfg.method = '1020';
cfg.feedback = 'yes';
elec = ft_electrodeplacement(cfg, headshape);

%%

chansel = ft_channelselection({'eeg1020', '-Fpz', '-Oz'}, elec.label);

cfg = [];
cfg.elec = elec;
cfg.channel = chansel;
cfg.outwardshift = 5; % in mm

cfg.template = 'fieldline_sensor.stl';
sensor = ft_sensorplacement(cfg, headshape);

cfg.template = 'fieldline_holder.stl';
holder = ft_sensorplacement(cfg, headshape);

cfg.template = 'fieldline_cuttingtool.stl';
cuttingtool = ft_sensorplacement(cfg, headshape);

%%

figure
ft_plot_headshape(headshape, 'facecolor', 'skin', 'facealpha', 0.5, 'axes', 1);
ft_plot_mesh(helmet, 'facecolor', 'lightgray', 'facealpha', 0.5);

for i=1:numel(sensor)
  disp(chansel{i});
  ft_plot_headshape(sensor(i), 'facecolor', 'r', 'facealpha', 1);
  ft_plot_headshape(holder(i), 'facecolor', 'g', 'facealpha', 1);
  ft_plot_headshape(cuttingtool(i), 'facecolor', 'b', 'facealpha', 0.5);
end
ft_headlight


%%

mkdir flattenedspherical

for i=1:numel(sensor)
  disp(chansel{i});
  filename = sprintf('flattenedspherical/sensor-%s.stl', chansel{i});
  ft_write_headshape(filename, sensor(i), 'fileformat', 'stl');
  filename = sprintf('flattenedspherical/holder-%s.stl', chansel{i});
  ft_write_headshape(filename, sensor(i), 'fileformat', 'stl');
  filename = sprintf('flattenedspherical/cuttingtool-%s.stl', chansel{i});
  ft_write_headshape(filename, sensor(i), 'fileformat', 'stl');
end
