% Archana Gupta
% Project
% Function to find diffused normals

function [areatri, vold, ndiffnorm, centroid]=diffnorm(v,f) 

vold=v;

f1=f(:,1);
f2=f(:,2);
f3=f(:,3);

frow=size(f,1);
areatri=[];
centroid=[];

%find area and centroid of each triangle in mesh
for i=1:frow
    v1=v(f1(i),1:3);
    v2=v(f2(i),1:3);
    v3=v(f3(i),1:3);
    
    a=norm(v1-v2);
    b=norm(v2-v3);
    c=norm(v3-v1);
    
    angc=acos((a^2 + b^2 - c^2)/(2*a*b));
    
    areatri(i,1)=0.5*a*b*sin(angc);
    
    centroid(i,1:3)=(v1+v2+v3)/3;
end

%find normals and normalise   
normal = findnormals(v,f);
nnormal = normalize(normal);

diffnorm=[];

% find diffused normals(area weighted average normals)
for j=1:frow
   
   % find for each triangle the position of vertices or edges common to
   % triangle under consideration
   neigh=find(f==f(j,1)|f==f(j,2)|f==f(j,3));
   %call to function uniqueneigh to find unique index positions of the
   %vertices or edges common to triangle under consideration
   unineigh=uniqueneigh(neigh,frow);
   
   usize=size(unineigh,1);
   
   areatot=0;
   summation=[0 0 0];
   
   for i=1:usize
       areatot = areatot + areatri(unineigh(i));
   end
 
   for i=1:usize
       summation = summation + (areatri(unineigh(i)) * nnormal(unineigh(i),1:3));
   end
      
   diffnorm(j,1:3) = summation/areatot;
end

%normalize diffused normals
ndiffnorm=normalize(diffnorm);
 
 

        
