%% Reset

clear all
close all
clc

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

%% Choose the parameters

Npatches    	= 100;
overlap_ratio   = 0.1;

%% Load the data

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

%% Segment the mesh

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

clear options

%% Grow the patches

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

clear options

%% Display the results 

figure

p = patch(FV);

set(p, 'AmbientStrength', 0, 'DiffuseStrength', 1, 'SpecularStrength', 0, 'FaceLighting', 'phong');
light('Position', [0 0 1], 'Style', 'infinite');
title('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