//----plant-creating-algorithm----
//--------------------------------
//---------------by---------------
//--------Stephan-Saalfeld--------
//-----stephansaalfeld@gmx.de-----
//--------------------------------
//---------use-it-for-free--------
//-----including-this-comments----

#macro plant (rad,old_rad,ori,dir,ct,is_it_a_branch)
  #if (rad > min_rad)
    #if (ct < 1)
      #local rad_l = (tru.x+(.5-rand(rnd))*tru.y)*rad*rd;
      #local dir_l = vnormalize (vcross (light-ori,dir));
      #local dir_l = vaxis_rotate (vaxis_rotate (dir_l,vcross(dir_l,dir),90-tru.z),dir,360*rand(rnd));
      plant (rad_l,old_rad,ori,dir_l,ct_m.u+rand(rnd)*(ct_m.v-.5),no)
      #local rad_l = max((bra.x+(.5-rand(rnd))*bra.y)*rad*rd,min_rad*rd);
      #local dir_l = vnormalize (vcross (light-ori,dir));
      #local dir_l = vaxis_rotate (vaxis_rotate (dir_l,vcross(dir_l,dir),90-bra.z),dir,360*rand(rnd));
      plant (rad_l,old_rad,ori,dir_l,ct_m.u+rand(rnd)*(ct_m.v-.5),yes) 
      #local bra_l = bra_c-1;
      #while (bra_l > 0)
        #local rad_l = max((bra.x+(.5-rand(rnd))*bra.y)*rad*rd,min_rad*rd);
        #local dir_l = vaxis_rotate (dir_l,dir,360/bra_c);
        plant (rad_l,old_rad,ori,dir_l,ct_m.u+rand(rnd)*(ct_m.v-.5),yes)
        #local bra_l = bra_l-1;
      #end
    #else
      #local len_l = len.x+rad*len.y+(.5-rand(rnd))*len.z;
      #local fin = <(1-2*rand(rnd)),(1-2*rand(rnd)),(1-2*rand(rnd))>;
      #local dir_l = vnormalize(dir+max_var*fin+light_s*vnormalize(light-ori)+grv_s.x*(grv_s.y+grv_s.z*min_rad/rad)*<0,-1,0>);
      #local fac = sqrt(len_l*len_l/(dir_l.x*dir_l.x+dir_l.y*dir_l.y+dir_l.z*dir_l.z));
      #local fin = ori+fac*dir_l;
      element (ori, old_rad, fin, rad)
      plant (rad*rd,rad,fin,dir_l,ct-1,is_it_a_branch)
    #end
  #else
    #if (is_it_a_branch)
      #local len_l = sta_len.x+rad*sta_len.y+(.5-rand(rnd))*sta_len.z;
      #local fin = <(1-2*rand(rnd)),(1-2*rand(rnd)),(1-2*rand(rnd))>;
      #local dir_l = vnormalize(<dir.x,.1,dir.z>+max_var*(fin+light_s*vnormalize(light-ori)+grv_s.x*(grv_s.y+grv_s.z*min_rad/rad)*<0,-1,0>));
      #local fac = sqrt(len_l*len_l/(dir_l.x*dir_l.x+dir_l.y*dir_l.y+dir_l.z*dir_l.z));
      #local fin = ori+fac*dir_l;
      #local y_tu = vnormalize(<dir_l.x,0,dir_l.z>);
      #if (y_tu.z >=0)
        #local y_tu = <0,degrees(asin(y_tu.x)),0>;
      #else
        #local y_tu = <0,180+degrees(asin(-y_tu.x)),0>;
      #end
      element (ori, old_rad, fin, rad)
      sphere {fin, rad
        material {branch_mat}
        }
      #local x_rot = lf_ang.u*(1+lf_ang.v*(.5-rand(rnd)));
      object {leaf
        scale (lf_siz.x+(lf_siz.y+lf_siz.z*(.5-rand(rnd)))*old_rad)
        rotate x*(x_rot+(180-x_rot)*(1-1/(1+grv_s.x*4)))
        rotate y_tu
        rotate <light_s*degrees(asin(vnormalize(light-ori).z)),0,-light_s*degrees(asin(vnormalize(light-ori).x))>
        translate fin
        }
    #else
      fruit (rad,old_rad,ori,dir)
    #end 
  #end
#end
