%% Reset

clear all
close all
clc

addpath ./src/
addpath ./mex/
addpath ./utils/

%% Choose the parameters

Npatches    	= 100;
overlap_ratio   = 0.5;

%% Load the data

[FV.vertices, FV.faces] = read_ply('./data/dino/dino.ply');

load ./data/dino/dino_sym_indices
load ./save/dsym/DsymDino

%% Segment the mesh

options.verbose                         = true;
[sampled_keypoints, I_vertex_nkeypoint] = segment_mesh_uni(FV, Npatches, options);

clear options

options.verbose                                 = true;
options.Dsym_vertex                          	= Dsym_vertex;
[sampled_sym_keypoints, Isym_vertex_nkeypoint] 	= segment_mesh_uni_sym(FV, Npatches, sym_indices, options);

clear options

%% Grow the patches

options.verbose = true;
grown_patches   = grow_patches_proj(FV, sampled_keypoints, I_vertex_nkeypoint(:, end), overlap_ratio, options);

clear options

options.verbose     = true;
grown_sym_patches   = grow_patches_proj_sym(FV, sampled_sym_keypoints, Isym_vertex_nkeypoint(:, end), sym_indices, overlap_ratio, options);

clear options

%% Display

figure

subplot(1, 2, 1)

p = patch(FV);

set(p, 'AmbientStrength', 0, 'DiffuseStrength', 1, 'SpecularStrength', 0, 'FaceLighting', 'phong');
light('Position', [0 0 1], 'Style', 'infinite');
title('Asymmetric uniform segmentation')

hold on
axis equal
axis off

map = jet(Npatches);
map = map(randperm(Npatches), :);

cdata = zeros(size(FV.vertices, 1), 3);
ndata = zeros(size(FV.vertices, 1), 1);

for i = 1: Npatches
    tmp_indices             = grown_patches{i};
    cdata(tmp_indices, 1)   = cdata(tmp_indices, 1) + map(i, 1);
    cdata(tmp_indices, 2)   = cdata(tmp_indices, 2) + map(i, 2);
    cdata(tmp_indices, 3)   = cdata(tmp_indices, 3) + map(i, 3);
    ndata(tmp_indices)      = ndata(tmp_indices) + 1;
end
cdata = cdata ./ repmat(ndata, 1, 3);

set(p, 'FaceColor', 'interp', 'FaceVertexCData', cdata, 'LineStyle', 'none')

clear cdata ndata i p map tmp_indices

subplot(1, 2, 2)

Nsym_patches = length(grown_sym_patches);

p = patch(FV);

set(p, 'AmbientStrength', 0, 'DiffuseStrength', 1, 'SpecularStrength', 0, 'FaceLighting', 'phong');
light('Position', [0 0 1], 'Style', 'infinite');
title('Symmetric uniform segmentation')

hold on
axis equal
axis off
  
map = jet(Nsym_patches);
map = map(randperm(Nsym_patches), :);

cdata = zeros(size(FV.vertices, 1), 3);
ndata = zeros(size(FV.vertices, 1), 1);
 
for i = 1: Nsym_patches
    tmp_indices             = grown_sym_patches{i}(:);
    cdata(tmp_indices, 1)   = cdata(tmp_indices, 1) + map(i, 1);
    cdata(tmp_indices, 2)   = cdata(tmp_indices, 2) + map(i, 2);
    cdata(tmp_indices, 3)   = cdata(tmp_indices, 3) + map(i, 3);
    ndata(tmp_indices)      = ndata(tmp_indices) + 1;
end
cdata = cdata ./ repmat(ndata, 1, 3);

set(p, 'FaceColor', 'interp', 'FaceVertexCData', cdata, 'LineStyle', 'none')

clear cdata ndata i p map tmp_indices Nsym_patches