]> git.donarmstrong.com Git - lilypond.git/blobdiff - lily/tie-formatting-problem.cc
Merge with master
[lilypond.git] / lily / tie-formatting-problem.cc
index 1d6ea31c300d14db12e4936d51d1813e1ed9ed79..6c7e2a024f091d0f5af9adae860c0a790b1cb80c 100644 (file)
@@ -3,15 +3,15 @@
 
   source file of the GNU LilyPond music typesetter
 
-  (c) 2005--2006 Han-Wen Nienhuys <hanwen@xs4all.nl>
+  (c) 2005--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
 
 */
 
 #include "tie-formatting-problem.hh"
 
+#include "paper-column.hh"
 #include "bezier.hh" 
 #include "directional-element-interface.hh"
-#include "item.hh"
 #include "libc-extension.hh"
 #include "misc.hh"
 #include "note-head.hh"
@@ -22,7 +22,8 @@
 #include "tie-configuration.hh"
 #include "tie.hh"
 #include "warn.hh"
-
+#include "pointer-group-interface.hh"
+#include "output-def.hh"
 
 void
 Tie_formatting_problem::print_ties_configuration (Ties_configuration const *ties)
@@ -39,13 +40,18 @@ Tie_formatting_problem::print_ties_configuration (Ties_configuration const *ties
 }
 
 Interval
-Tie_formatting_problem::get_attachment (Real y) const
+Tie_formatting_problem::get_attachment (Real y, Drul_array<int> columns) const
 {
-  Interval attachments;
+  Interval attachments (0,0);
   Direction d = LEFT;
   do
     {
-      attachments[d] = skyline_height (chord_outlines_[d], y, -d);
+      Tuple2<int> key (columns[d], int (d));
+      Chord_outline_map::const_iterator i (chord_outlines_.find (key));
+      if (i == chord_outlines_.end ())
+       programming_error ("Cannot find chord outline");
+      else
+       attachments[d] = i->second.height (y);
     }
   while (flip (&d) != LEFT);
   
@@ -65,8 +71,9 @@ Tie_formatting_problem::~Tie_formatting_problem ()
 }
 
 void
-Tie_formatting_problem::set_chord_outline (vector<Item*> bounds,
-                                          Direction dir)
+Tie_formatting_problem::set_column_chord_outline (vector<Item*> bounds,
+                                                 Direction dir,
+                                                 int column_rank)
 {
   Real staff_space = Staff_symbol_referencer::staff_space (bounds[0]);
 
@@ -79,7 +86,7 @@ Tie_formatting_problem::set_chord_outline (vector<Item*> bounds,
       Grob *head = bounds[i];
       if (!Note_head::has_interface (head))
        continue;
-      
+         
       if (!stem)
        stem = unsmob_grob (head->get_object ("stem"));
          
@@ -97,6 +104,9 @@ Tie_formatting_problem::set_chord_outline (vector<Item*> bounds,
          Interval x = dots->extent (x_refpoint_, X_AXIS);
          int p = int (Staff_symbol_referencer::get_position (dots));
 
+         /*
+           TODO: shouldn't this use column-rank dependent key?  
+         */
          dot_positions_.insert (p);
          dot_x_.unite (x);
 
@@ -107,51 +117,78 @@ Tie_formatting_problem::set_chord_outline (vector<Item*> bounds,
        }
     }
 
-  chord_outlines_[dir] = empty_skyline (-dir);
-  if (bounds[0]->break_status_dir ())
-    {
-      Real x = robust_relative_extent (bounds[0],  x_refpoint_, X_AXIS)[-dir];
-      chord_outlines_[dir].at (0).height_ = x; 
-    }
-  else
+  Tuple2<int> key (column_rank, int (dir));
+
+  if (stem)
     {
-      Interval x;      
-      for (vsize i = 0; i < head_boxes.size (); i++)
+      if (Stem::is_normal_stem (stem))
        {
-         x.unite (head_boxes[i][X_AXIS]);
-       }
-
-      chord_outlines_[dir].at (0).height_ = x[dir];
-    }
+         
+         Interval x;
+         x.add_point (stem->relative_coordinate (x_refpoint_, X_AXIS));
+         x.widen (staff_space / 20); // ugh.
+         Interval y;
+         y.add_point (Stem::stem_end_position (stem) * staff_space * .5);
+
+         Direction stemdir = get_grob_direction (stem);
+         y.add_point (Stem::head_positions (stem)[-stemdir]
+                      * staff_space * .5);
+
+         /*
+           add extents of stem.
+         */
+         boxes.push_back (Box (x, y));
 
-  for (vsize i = 0; i < boxes.size (); i++)
-    insert_extent_into_skyline (&chord_outlines_[dir]  ,
-                               boxes[i], Y_AXIS, -dir);
+         stem_extents_[key].unite (Box (x,y));
 
-  if (stem
-      && !Stem::is_invisible (stem))
-    {
-      Interval x;
-      x.add_point (stem->relative_coordinate (x_refpoint_, X_AXIS));
-      x.widen (staff_space / 20); // ugh.
-      Interval y;
-      y.add_point (Stem::stem_end_position (stem) * staff_space * .5);
+         if (dir == LEFT)
+           {
+             Box flag_box = Stem::get_translated_flag (stem).extent_box ();
+             flag_box.translate( Offset (x[RIGHT], X_AXIS));
+             boxes.push_back (flag_box);
+           }
+       }
+      else
+       {
+         Grob *head = Stem::support_head (stem);
+
+         /*
+           In case of invisible stem, don't pass x-center of heads.
+         */
+         Real x_center = head->extent (x_refpoint_, X_AXIS).center ();
+         Interval x_ext;
+         x_ext[-dir] = x_center;
+         Interval y_ext;
+         for (vsize j = 0; j < head_boxes.size (); j++)
+           y_ext.unite (head_boxes[j][Y_AXIS]);
+
+         boxes.push_back (Box (x_ext, y_ext));
+       }
 
-      Direction stemdir = get_grob_direction (stem);
-      y.add_point (Stem::head_positions (stem)[-stemdir]
-                  * staff_space * .5);
+      extract_grob_set (stem, "note-heads", heads);
+      for (vsize i = 0; i < heads.size(); i ++)
+       {
+         if (find (bounds.begin(), bounds.end (), dynamic_cast<Item*> (heads[i])) ==  bounds.end ())
+           {
+             /*
+               other untied notes in the same chord.
+             */
          
-      insert_extent_into_skyline (&chord_outlines_[dir], Box (x,y), Y_AXIS, -dir);
-
-      stem_extents_[dir].unite (Box (x,y));
+             Interval y = Staff_symbol_referencer::extent_in_staff (heads[i]);
+             Interval x = heads[i]->extent (x_refpoint_, X_AXIS);
+             boxes.push_back (Box (x, y));
+           }
+         
+         Grob *acc = unsmob_grob (heads[i]->get_object ("accidental-grob"));
+         if (acc && acc->is_live () && dir == RIGHT)
+           {
+             boxes.push_back (Box (acc->extent (x_refpoint_, X_AXIS),
+                                   Staff_symbol_referencer::extent_in_staff (acc)));
+           }
 
-      if (dir == LEFT)
-       {
-         Box flag_box = Stem::get_translated_flag (stem).extent_box ();
-         flag_box.translate( Offset (x[RIGHT], X_AXIS));
-         insert_extent_into_skyline (&chord_outlines_[dir], flag_box,
-                                     Y_AXIS, -dir);
+         head_positions_[column_rank].add_point (int (Staff_symbol_referencer::get_position (heads[i])));
        }
+      
     }
   
   Direction updowndir = DOWN;
@@ -169,18 +206,61 @@ Tie_formatting_problem::set_chord_outline (vector<Item*> bounds,
        }
 
       if (!x.is_empty ())
-       insert_extent_into_skyline (&chord_outlines_[dir],
-                                   Box (x,y),
-                                   Y_AXIS, -dir);
+       boxes.push_back (Box (x, y));
     }
   while (flip (&updowndir) != DOWN);
-  
-  head_extents_[dir].set_empty ();
+
+  /* todo: the horizon_padding is somewhat arbitrary */
+  chord_outlines_[key] = Skyline (boxes, details_.skyline_padding_, Y_AXIS, -dir);
+  if (bounds[0]->break_status_dir ())
+    {
+      Real x = robust_relative_extent (bounds[0],  x_refpoint_, X_AXIS)[-dir];
+      
+      chord_outlines_[key].set_minimum_height (x);
+    }
+  else
+    {
+      Interval x;
+      for (vsize j = 0; j < head_boxes.size (); j++)
+       {
+         x.unite (head_boxes[j][X_AXIS]);
+       }
+      
+      chord_outlines_[key].set_minimum_height (x[dir]);
+    }
+
+  head_extents_[key].set_empty ();
   for (vsize i = 0; i < head_boxes.size (); i++)
     {
-      head_extents_[dir].unite (head_boxes[i]);
+      head_extents_[key].unite (head_boxes[i]);
+    }
+}
+
+void
+Tie_formatting_problem::set_chord_outline (vector<Item*> bounds,
+                                          Direction dir)
+
+{
+  vector<int> ranks;
+  for (vsize i = 0; i < bounds.size (); i++)
+    ranks.push_back (bounds[i]->get_column ()->get_rank ());
+
+  vector_sort (ranks, less<int> ());
+  uniq (ranks);
+
+  for (vsize i = 0; i < ranks.size (); i++)
+    {
+      vector<Item*> col_items;
+      for (vsize j = 0; j < bounds.size (); j ++)
+       {
+         if (bounds[j]->get_column ()->get_rank () == ranks[i])
+           col_items.push_back (bounds[j]);
+       }
+
+      set_column_chord_outline (col_items, dir, ranks[i]);
     }
 }
+  
 
 
 void
@@ -222,8 +302,19 @@ Tie_formatting_problem::from_ties (vector<Grob*> const &ties)
       for (vsize i = 0; i < ties.size (); i++)
        {
          Item *it = dynamic_cast<Spanner*> (ties[i])->get_bound (d);
-                                            
-         bounds.push_back (it);
+         if (it->break_status_dir ())
+           {
+             Item *sep
+               = dynamic_cast<Item*> (unsmob_grob (ties[i]->get_object ("separation-item")));
+             if (sep && sep->get_column () == it->get_column ())
+               it = sep;
+
+             bounds.push_back (it);
+           }
+         else 
+           {
+             bounds.push_back (it);
+           }
        }
       
       set_chord_outline (bounds, d);
@@ -234,38 +325,32 @@ Tie_formatting_problem::from_ties (vector<Grob*> const &ties)
   for (vsize i = 0; i < ties.size (); i++)
     {
       Tie_specification spec;
+      spec.from_grob (ties[i]);
       
-      if (scm_is_number (ties[i]->get_property_data (ly_symbol2scm ("direction"))))
-       {
-         spec.manual_dir_ = to_dir (ties[i]->get_property ("direction"));
-         spec.has_manual_dir_ = true;
-       }
-         
-      spec.position_ = Tie::get_position (ties[i]);
-
       do
        {
          spec.note_head_drul_[d] = Tie::head (ties[i], d);
+         spec.column_ranks_[d] = Tie::get_column_rank (ties[i], d);
        }
       while (flip (&d) != LEFT);
-      
       specifications_.push_back (spec);
     }
 }
 
 void
-Tie_formatting_problem::from_semi_ties (vector<Grob*> const &lv_ties, Direction head_dir)
+Tie_formatting_problem::from_semi_ties (vector<Grob*> const &semi_ties, Direction head_dir)
 {
-  if (lv_ties.empty ())
+  if (semi_ties.empty ())
     return;
   
-  details_.from_grob (lv_ties[0]);
+  details_.from_grob (semi_ties[0]);
   vector<Item*> heads;
-  
-  for (vsize i = 0; i < lv_ties.size (); i++)
+
+  int column_rank = -1;
+  for (vsize i = 0; i < semi_ties.size (); i++)
     {
       Tie_specification spec;
-      Item *head = unsmob_item (lv_ties[i]->get_object ("note-head"));
+      Item *head = unsmob_item (semi_ties[i]->get_object ("note-head"));
        
       if (!head)
        programming_error ("LV tie without head?!");
@@ -275,32 +360,29 @@ Tie_formatting_problem::from_semi_ties (vector<Grob*> const &lv_ties, Direction
          spec.position_ = int (Staff_symbol_referencer::get_position (head));
        }
 
+      spec.from_grob (semi_ties[i]);
+      
       spec.note_head_drul_[head_dir] = head;
+      column_rank = Tie::get_column_rank (semi_ties[i], head_dir);
+      spec.column_ranks_ = Drul_array<int> (column_rank, column_rank);
       heads.push_back (head);
       specifications_.push_back (spec);
     }
 
-  x_refpoint_ = lv_ties [0];
-  for (vsize i = 0; i < lv_ties.size (); i++)
-    x_refpoint_ = lv_ties[i]->common_refpoint (x_refpoint_, X_AXIS); 
+  x_refpoint_ = semi_ties [0];
+  for (vsize i = 0; i < semi_ties.size (); i++)
+    x_refpoint_ = semi_ties[i]->common_refpoint (x_refpoint_, X_AXIS); 
   for (vsize i = 0; i < heads.size (); i++)
     x_refpoint_ = heads[i]->common_refpoint (x_refpoint_, X_AXIS); 
 
   set_chord_outline (heads, head_dir);
 
-  Real extremal = head_dir * infinity_f;   
+  Tuple2<int> head_key (column_rank, head_dir);
+  Tuple2<int> open_key (column_rank, -head_dir);
+  Real extremal = chord_outlines_[head_key].max_height ();
 
-  for (vsize i = 0; i < chord_outlines_[head_dir].size (); i++)
-    {
-      extremal = head_dir * min (head_dir * extremal,
-                                  head_dir * chord_outlines_[head_dir][i].height_);
-    }
-
-  Skyline_entry right_entry;
-  right_entry.width_.set_full ();
-  right_entry.height_ = extremal - head_dir * 1.5;
-  
-  chord_outlines_[-head_dir].push_back (right_entry);
+  chord_outlines_[open_key] = Skyline (head_dir);
+  chord_outlines_[open_key].set_minimum_height (extremal - head_dir * 1.5);
 }
 
 
@@ -311,54 +393,61 @@ Tie_formatting_problem::get_tie_specification (int i) const
 }
 
 
+/*
+  Return configuration, create it if necessary. 
+*/
 Tie_configuration*
-Tie_formatting_problem::get_configuration (int pos, Direction dir) const
+Tie_formatting_problem::get_configuration (int pos, Direction dir, Drul_array<int> columns,
+                                          bool tune_dy) const
 {
-  pair<int,int> key (pos, dir);
+  int key_components[] = {
+    pos, dir, columns[LEFT], columns[RIGHT]
+  };
+  Tuple<int,4> key (key_components);
+    
   Tie_configuration_map::const_iterator f = possibilities_.find (key);
-                                                             
   if (f != possibilities_.end ())
     {
       return (*f).second;
     }
 
   
-  Tie_configuration *conf = generate_configuration (pos, dir);
+  Tie_configuration *conf = generate_configuration (pos, dir, columns, tune_dy);
   ((Tie_formatting_problem*) this)->possibilities_[key] = conf;
   return conf;
 }
 
 Tie_configuration*
-Tie_formatting_problem::generate_configuration (int pos, Direction dir) const
+Tie_formatting_problem::generate_configuration (int pos, Direction dir,
+                                               Drul_array<int> columns, bool y_tune) const
 {
   Tie_configuration *conf = new Tie_configuration;
   conf->position_ = pos;
   conf->dir_ = dir;
+  
+  conf->column_ranks_ = columns;
+  
   Real y = conf->position_ * 0.5 * details_.staff_space_;
 
-
-  bool y_tune = true;
   if (dot_positions_.find (pos) != dot_positions_.end ())
     {
       conf->delta_y_ += dir * 0.25 * details_.staff_space_;
       y_tune = false;
     }
-               
-          
   
   if (y_tune
-      && max (fabs (head_extents_[LEFT][Y_AXIS][dir] - y),
-             fabs (head_extents_[RIGHT][Y_AXIS][dir] - y)) < 0.25
+      && max (fabs (get_head_extent (columns[LEFT], LEFT, Y_AXIS)[dir] - y),
+             fabs (get_head_extent (columns[RIGHT], RIGHT, Y_AXIS)[dir] - y)) < 0.25
       && !Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos))
     {
       conf->delta_y_ =
-       (head_extents_[LEFT][Y_AXIS][dir] - y)
+       (get_head_extent (columns[LEFT], LEFT, Y_AXIS)[dir] - y)
        + dir * details_.outer_tie_vertical_gap_;
     }
 
   if (y_tune)
     {
-      conf->attachment_x_ = get_attachment (y + conf->delta_y_);
+      conf->attachment_x_ = get_attachment (y + conf->delta_y_, conf->column_ranks_);
       Real h =  conf->height (details_);
       
       /*
@@ -370,38 +459,42 @@ Tie_formatting_problem::generate_configuration (int pos, Direction dir) const
        size.
        
        */
-      if (h < details_.intra_space_threshold_ * 0.5 * details_.staff_space_)
+      if (head_positions_slice (columns[LEFT]).contains (pos)
+         || head_positions_slice (columns[RIGHT]).contains (pos)
+         || abs (pos) < 2 * Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_))
        {
-         if (!Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos)
-             && abs (pos) < 2 * Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_))
-           {
-             conf->center_tie_vertically (details_);
-           }
-         else if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos))
+         if (h < details_.intra_space_threshold_ * 0.5 * details_.staff_space_)
            {
-             conf->delta_y_ += dir *
-               details_.tip_staff_line_clearance_ * 0.5 *  details_.staff_space_;
+             if (!Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos)
+                 && abs (pos) < 2 * Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_))
+               {
+                 conf->center_tie_vertically (details_);
+               }
+             else if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos))
+               {
+                 conf->delta_y_ += dir *
+                   details_.tip_staff_line_clearance_ * 0.5 *  details_.staff_space_;
+               }
            }
-       }
-      else 
-       {
-         Real top_y = y + conf->delta_y_ + conf->dir_ * h;
-         Real top_pos = top_y / (0.5*details_.staff_space_);
-         int round_pos = int (my_round (top_pos));
-
-         /* TODO: should use other variable? */
-         Real clearance = details_.center_staff_line_clearance_;
-         if (fabs (top_pos - round_pos) < clearance
-             && Staff_symbol_referencer::on_staff_line (details_.staff_symbol_referencer_,
-                                                        round_pos))
+         else 
            {
-             Real new_y = (round_pos + clearance * conf->dir_) * 0.5 * details_.staff_space_;
-             conf->delta_y_ = (new_y - top_y);
+             Real top_y = y + conf->delta_y_ + conf->dir_ * h;
+             Real top_pos = top_y / (0.5*details_.staff_space_);
+             int round_pos = int (my_round (top_pos));
+
+             /* TODO: should use other variable? */
+             Real clearance = details_.center_staff_line_clearance_;
+             if (fabs (top_pos - round_pos) < clearance
+                 && Staff_symbol_referencer::on_staff_line (details_.staff_symbol_referencer_,
+                                                            round_pos))
+               {
+                 Real new_y = (round_pos + clearance * conf->dir_) * 0.5 * details_.staff_space_;
+                 conf->delta_y_ = (new_y - top_y);
+               }
            }
        }
-    }
-  
-  conf->attachment_x_ = get_attachment (y + conf->delta_y_);
+    }  
+  conf->attachment_x_ = get_attachment (y + conf->delta_y_, conf->column_ranks_);
   if (conf->height (details_) < details_.intra_space_threshold_ * 0.5 * details_.staff_space_)
     {
       /*
@@ -411,29 +504,60 @@ Tie_formatting_problem::generate_configuration (int pos, Direction dir) const
       Interval close_by = get_attachment (y
                                          + conf->delta_y_
                                          + (dir * details_.intra_space_threshold_ * 0.25
-                                            * details_.staff_space_));
+                                            * details_.staff_space_),
+                                         conf->column_ranks_);
       
       conf->attachment_x_.intersect (close_by);
     }
 
   conf->attachment_x_.widen ( - details_.x_gap_);
 
-  Direction d = LEFT;
-  do
+  if (conf->column_span_length ())
     {
-      Real y = conf->position_ * details_.staff_space_ * 0.5 + conf->delta_y_;
-      if (stem_extents_[d][X_AXIS].is_empty ()
-         || !stem_extents_[d][Y_AXIS].contains (y))
-       continue;
+      /*
+       avoid the stems that we attach to as well. We don't do this
+       for semities (span length = 0)
 
-      conf->attachment_x_[d] =
-       d* min (d * conf->attachment_x_[d],
-               d * (stem_extents_[d][X_AXIS][-d] - d * details_.stem_gap_));
-    }
-  while (flip (&d) != LEFT);
+       It would be better to check D against HEAD-DIRECTION if
+       applicable.
+      */
+      Direction d = LEFT;
+      do
+       {
+         Real y = conf->position_ * details_.staff_space_ * 0.5 + conf->delta_y_;
+         if (get_stem_extent (conf->column_ranks_[d], d, X_AXIS).is_empty ()
+             || !get_stem_extent (conf->column_ranks_[d], d, Y_AXIS).contains (y))
+           continue;
+
+         conf->attachment_x_[d] =
+           d * min (d * conf->attachment_x_[d],
+                    d * (get_stem_extent (conf->column_ranks_[d], d, X_AXIS)[-d] - d * details_.stem_gap_));
+       }
+      while (flip (&d) != LEFT);
+    }  
   return conf;
 }
 
+Interval
+Tie_formatting_problem::get_head_extent (int col, Direction d, Axis a) const
+{
+  Column_extent_map::const_iterator i = head_extents_.find (Tuple2<int> (col, int (d)));
+  if (i != head_extents_.end ())
+    return (*i).second[a];
+  else
+    return Interval ();
+}
+
+Interval
+Tie_formatting_problem::get_stem_extent (int col, Direction d, Axis a) const
+{
+  Column_extent_map::const_iterator i = stem_extents_.find (Tuple2<int> (col, int (d)));
+  if (i != stem_extents_.end ())
+    return (*i).second[a];
+  else
+    return Interval ();
+}
+
 /**
    TIE_IDX and TIES_CONF are optional.
  */
@@ -455,7 +579,8 @@ Tie_formatting_problem::score_aptitude (Tie_configuration *conf,
     }
 
   {
-    Real p = details_.vertical_distance_penalty_factor_ * fabs (curve_y - tie_y);
+    Real relevant_dist = max (fabs (curve_y - tie_y) - 0.5, 0.0);
+    Real p = details_.vertical_distance_penalty_factor_ * convex_amplifier (1.0, 0.9, relevant_dist);
     if (ties_conf)
       ties_conf->add_tie_score (p, tie_idx, "vdist");
     else
@@ -470,22 +595,79 @@ Tie_formatting_problem::score_aptitude (Tie_configuration *conf,
       
       Interval head_x = spec.note_head_drul_[d]->extent (x_refpoint_, X_AXIS);
       Real dist = head_x.distance (conf->attachment_x_[d]);
+      
 
       /*
        TODO: flatten with log or sqrt.
        */
-      Real p = details_.horizontal_distance_penalty_factor_ * dist;
+      Real p = details_.horizontal_distance_penalty_factor_
+       * convex_amplifier (1.25, 1.0, dist);
       if (ties_conf)
        ties_conf->add_tie_score (p, tie_idx,
                                  (d == LEFT) ? "lhdist" : "rhdist");
       else
        penalty += p;
+
+    }
+  while (flip (&d) != LEFT);
+
+  if (ties_conf
+      && ties_conf->size() == 1)
+    {
+      Direction d = LEFT;
+      Drul_array<Grob*> stems (0, 0);
+      do
+       {
+         if (!spec.note_head_drul_[d])
+           continue;
+
+         Grob *stem = unsmob_grob (spec.note_head_drul_[d]->get_object ("stem"));
+         if (stem
+             && Stem::is_normal_stem (stem))
+           stems[d] = stem;
+       }
+      while (flip (&d) != LEFT);
+
+      bool tie_stem_dir_ok = true;
+      bool tie_position_dir_ok = true;
+      if (stems[LEFT] && !stems[RIGHT])
+       tie_stem_dir_ok = conf->dir_ != get_grob_direction (stems[LEFT]);
+      else if (!stems[LEFT] && stems[RIGHT])
+       tie_stem_dir_ok = conf->dir_ != get_grob_direction (stems[RIGHT]);
+      else if (stems[LEFT] && stems[RIGHT]
+         && get_grob_direction (stems[LEFT]) == get_grob_direction (stems[RIGHT]))
+       tie_stem_dir_ok = conf->dir_ != get_grob_direction (stems[LEFT]);
+      else if (spec.position_)
+       tie_position_dir_ok = conf->dir_ == sign (spec.position_);
+
+      if (!tie_stem_dir_ok)
+       ties_conf->add_score (details_.same_dir_as_stem_penalty_, "tie/stem dir");
+      if (!tie_position_dir_ok)
+       ties_conf->add_score (details_.same_dir_as_stem_penalty_, "tie/pos dir");
     }
   while (flip (&d) != LEFT);
 
+           
   return penalty;
 }
 
+
+Slice
+Tie_formatting_problem::head_positions_slice (int rank) const
+{
+  Position_extent_map::const_iterator i (head_positions_.find (rank));
+  if (i != head_positions_.end ())
+    {
+      return  (*i).second; 
+    }
+  Slice empty;
+  return empty;
+}
+
+/*
+  Score a configuration, ie. how well these ties looks without regard
+  to the note heads that they should connect to.
+ */
 void
 Tie_formatting_problem::score_configuration (Tie_configuration *conf) const
 {
@@ -514,13 +696,17 @@ Tie_formatting_problem::score_configuration (Tie_configuration *conf) const
       conf->add_score (
        details_.staff_line_collision_penalty_
        * peak_around (0.1 * details_.center_staff_line_clearance_,
-                    details_.center_staff_line_clearance_,
+                      details_.center_staff_line_clearance_,
                       fabs (top_pos - round_top_pos)),
        "line center");
     }
-  
-  if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_,
-                                       int (rint (tip_pos))))
+
+  int rounded_tip_pos = int (rint (tip_pos));
+  if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, rounded_tip_pos)
+      && (head_positions_slice (conf->column_ranks_[LEFT]).contains (rounded_tip_pos)
+         || head_positions_slice (conf->column_ranks_[RIGHT]).contains (rounded_tip_pos)
+         || abs (rounded_tip_pos) < 2 * Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_))
+         )
     {
       conf->add_score (details_.staff_line_collision_penalty_
                       * peak_around (0.1 * details_.tip_staff_line_clearance_,
@@ -555,55 +741,6 @@ Tie_formatting_problem::score_configuration (Tie_configuration *conf) const
   conf->scored_ = true;
 }
 
-Tie_configuration
-Tie_formatting_problem::find_optimal_tie_configuration (Tie_specification const &spec) const
-{
-  vector<Tie_configuration*> confs;
-
-  int pos = spec.position_;
-  Direction dir = spec.manual_dir_;
-
-  for (int i = 0; i < details_.single_tie_region_size_; i ++)
-    {
-      confs.push_back (generate_configuration (pos + i * dir, dir));
-    }
-
-  vector<Real> scores;
-
-  int best_idx = -1;
-  Real best_score = 1e6;
-  for (vsize i = 0; i < confs.size (); i ++)
-    {
-      score_configuration (confs[i]);
-      Real score = score_aptitude (confs[i], spec, 0, 0)
-       + confs[i]->score ();
-
-      if (score < best_score)
-       {
-         best_score = score;
-         best_idx = i;
-       }
-    }
-
-  Tie_configuration best = *confs[best_idx];
-  for (vsize i = 0; i < confs.size (); i++)
-    delete confs[i];
-
-  return best;
-}
-
-Tie_specification::Tie_specification ()
-{
-  has_manual_position_ = false;
-  has_manual_dir_ = false;
-  position_ = 0;
-  manual_position_ = 0;
-  manual_dir_ = CENTER;
-  note_head_drul_[LEFT] =
-    note_head_drul_[RIGHT] = 0;
-}
-
-
 void
 Tie_formatting_problem::score_ties_aptitude (Ties_configuration *ties) const
 {
@@ -669,21 +806,23 @@ Tie_formatting_problem::score_ties_configuration (Ties_configuration *ties) cons
       last_center = center;
     }
 
-  ties->add_score (details_.outer_tie_length_symmetry_penalty_factor_
-                  * fabs (ties->at (0).attachment_x_.length () - ties->back ().attachment_x_.length ()),
-                  "length symm");
+  if (ties->size () > 1)
+    {
+      ties->add_score (details_.outer_tie_length_symmetry_penalty_factor_
+                      * fabs (ties->at (0).attachment_x_.length () - ties->back ().attachment_x_.length ()),
+                      "length symm");
   
-  ties->add_score (details_.outer_tie_vertical_distance_symmetry_penalty_factor_
-                  * fabs (fabs (specifications_[0].position_ * 0.5 * details_.staff_space_
-                                - (ties->at (0).position_ * 0.5 * details_.staff_space_
-                                   + ties->at (0).delta_y_))
-                          -
-                          fabs (specifications_.back ().position_ * 0.5 * details_.staff_space_
-                                - (ties->back ().position_ * 0.5 * details_.staff_space_
-                                   + ties->back ().delta_y_))),
-                  "pos symmetry");
+      ties->add_score (details_.outer_tie_vertical_distance_symmetry_penalty_factor_
+                      * fabs (fabs (specifications_[0].position_ * 0.5 * details_.staff_space_
+                                    - (ties->at (0).position_ * 0.5 * details_.staff_space_
+                                       + ties->at (0).delta_y_))
+                              -
+                              fabs (specifications_.back ().position_ * 0.5 * details_.staff_space_
+                                    - (ties->back ().position_ * 0.5 * details_.staff_space_
+                                       + ties->back ().delta_y_))),
+                      "pos symmetry");
+    }
 }
-
 /*
   Generate with correct X-attachments and beziers, copying delta_y_
   from TIES_CONFIG if necessary.
@@ -694,8 +833,10 @@ Tie_formatting_problem::generate_ties_configuration (Ties_configuration const &t
   Ties_configuration copy;
   for (vsize i = 0; i < ties_config.size (); i++)
     {
-      Tie_configuration * ptr = get_configuration (ties_config[i].position_, ties_config[i].dir_);
-      if (specifications_[i].has_manual_position_)
+      Tie_configuration * ptr = get_configuration (ties_config[i].position_, ties_config[i].dir_,
+                                                  ties_config[i].column_ranks_,
+                                                  !specifications_[i].has_manual_delta_y_);
+      if (specifications_[i].has_manual_delta_y_)
        {
          ptr->delta_y_
            = (specifications_[i].manual_position_ - ties_config[i].position_)
@@ -719,13 +860,16 @@ Tie_formatting_problem::generate_base_chord_configuration ()
       if (specifications_[i].has_manual_position_)
        {
          conf.position_ = (int) my_round (specifications_[i].manual_position_);
-         conf.delta_y_ = (specifications_[i].manual_position_ - conf.position_)
-           * 0.5 * details_.staff_space_;
+         if (specifications_[i].has_manual_delta_y_)
+           conf.delta_y_ = (specifications_[i].manual_position_ - conf.position_)
+             * 0.5 * details_.staff_space_;
        }
       else
        {
          conf.position_ = specifications_[i].position_;
        }
+
+      conf.column_ranks_ = specifications_[i].column_ranks_;
       ties_config.push_back (conf);
     }
 
@@ -741,7 +885,7 @@ Tie_formatting_problem::generate_base_chord_configuration ()
 
 Ties_configuration
 Tie_formatting_problem::find_best_variation (Ties_configuration const &base,
-                                            vector<Tie_configuration_variation> vars)
+                                            vector<Tie_configuration_variation> const &vars)
 {
   Ties_configuration best = base;
   
@@ -769,17 +913,24 @@ Tie_formatting_problem::find_best_variation (Ties_configuration const &base,
                                       
 
 Ties_configuration
-Tie_formatting_problem::generate_optimal_chord_configuration ()
+Tie_formatting_problem::generate_optimal_configuration ()
 {
-  
   Ties_configuration base = generate_base_chord_configuration ();
-  vector<Tie_configuration_variation> vars = generate_collision_variations (base);
-  
   score_ties (&base);
+
+  vector<Tie_configuration_variation> vars;  
+  if (specifications_.size () > 1)
+    vars = generate_collision_variations (base);
+  else
+    vars = generate_single_tie_variations (base);
+
   Ties_configuration best = find_best_variation (base, vars);
-  vars = generate_extremal_tie_variations (best);
-  best = find_best_variation (best, vars);
 
+  if (specifications_.size () > 1)
+    {
+      vars = generate_extremal_tie_variations (best);
+      best = find_best_variation (best, vars);
+    }
   return best;
 }
 
@@ -788,9 +939,16 @@ Tie_formatting_problem::set_ties_config_standard_directions (Ties_configuration
 {
   if (tie_configs->empty ())
     return ;
-  
+
   if (!tie_configs->at (0).dir_)
-    tie_configs->at (0).dir_ = DOWN;
+    {
+      if (tie_configs->size () == 1)
+       tie_configs->at (0).dir_ = Direction (sign (tie_configs->at (0).position_));
+
+      if (!tie_configs->at (0).dir_)
+       tie_configs->at (0).dir_ = DOWN;
+    }
+  
   if (!tie_configs->back ().dir_)
     tie_configs->back ().dir_ = UP;
 
@@ -799,10 +957,19 @@ Tie_formatting_problem::set_ties_config_standard_directions (Ties_configuration
    */
   for (vsize i = 1; i < tie_configs->size (); i++)
     {
-      Real diff = (tie_configs->at (i-1).position_
-                  - tie_configs->at (i).position_);
-
-      if (fabs (diff) <= 1)
+      Real diff = (tie_configs->at (i).position_
+                  -tie_configs->at (i-1).position_);
+                  
+      Real span_diff 
+       = specifications_[i].column_span () - specifications_[i-1].column_span ();
+      if (span_diff && fabs (diff) <= 2)
+       {
+         if  (span_diff > 0)
+           tie_configs->at (i).dir_ = UP;
+         else if (span_diff < 0)
+           tie_configs->at (i-1).dir_ = DOWN;  
+       }
+      else if (fabs (diff) <= 1)
        {
          if (!tie_configs->at (i-1).dir_)
            tie_configs->at (i-1).dir_ = DOWN;
@@ -811,7 +978,7 @@ Tie_formatting_problem::set_ties_config_standard_directions (Ties_configuration
        }
     }
 
-  for (vsize i = 1; i < tie_configs->size() - 1; i++)
+  for (vsize i = 1; i + 1 < tie_configs->size (); i++)
     {
       Tie_configuration &conf = tie_configs->at (i);
       if (conf.dir_)
@@ -846,7 +1013,9 @@ Tie_formatting_problem::generate_extremal_tie_variations (Ties_configuration con
            Tie_configuration_variation var;
            var.index_ = (d == DOWN) ? 0 : ties.size () - 1;
            var.suggestion_ = get_configuration (boundary (ties, d, 0).position_
-                                                + d * i, d);
+                                                + d * i, d,
+                                                boundary (ties, d, 0).column_ranks_,
+                                                true);
            vars.push_back (var);
          }
     }
@@ -855,6 +1024,41 @@ Tie_formatting_problem::generate_extremal_tie_variations (Ties_configuration con
   return vars;
 }
 
+vector<Tie_configuration_variation>
+Tie_formatting_problem::generate_single_tie_variations (Ties_configuration const &ties) const
+{
+  vector<Tie_configuration_variation> vars;
+
+  int sz = details_.single_tie_region_size_;
+  if (specifications_[0].has_manual_position_)
+    sz = 1;
+  for (int i = 0; i < sz; i ++)
+    {
+      Direction d = LEFT;
+      do
+       {
+         if (i == 0
+             && ties[0].dir_ == d)
+           continue;
+         
+         int p = ties[0].position_ + i * d;
+         
+         if (!specifications_[0].has_manual_dir_
+             || d == specifications_[0].manual_dir_)
+           {
+             Tie_configuration_variation var;
+             var.index_ = 0;
+             var.suggestion_ = get_configuration (p,
+                                                  d, specifications_[0].column_ranks_,
+                                                  !specifications_[0].has_manual_delta_y_);
+             vars.push_back (var);
+           }
+       }
+      while (flip (&d) != LEFT);
+    }
+  return vars;
+}
+
 
 vector<Tie_configuration_variation>
 Tie_formatting_problem::generate_collision_variations (Ties_configuration const &ties) const
@@ -879,7 +1083,11 @@ Tie_formatting_problem::generate_collision_variations (Ties_configuration const
                  var.index_ = i;
                  var.suggestion_ = get_configuration (specifications_[i].position_
                                                       - ties[i].dir_,
-                                                      -ties[i].dir_);
+                                                      - ties[i].dir_,
+
+                                                      ties[i].column_ranks_,
+                                                      !specifications_[i].has_manual_delta_y_
+                                                      );
 
                  vars.push_back (var);
                }
@@ -890,7 +1098,10 @@ Tie_formatting_problem::generate_collision_variations (Ties_configuration const
                  var.index_ = i-1;
                  var.suggestion_ = get_configuration (specifications_[i-1].position_
                                                       - ties[i-1].dir_,
-                                                      - ties[i-1].dir_);
+                                                      - ties[i-1].dir_,
+                                                      specifications_[i-1].column_ranks_,
+                                                      !specifications_[i-1].has_manual_delta_y_
+                                                      );
 
                  vars.push_back (var);
                }
@@ -900,8 +1111,11 @@ Tie_formatting_problem::generate_collision_variations (Ties_configuration const
                {
                  Tie_configuration_variation var;
                  var.index_ = i-1;
-                 var.suggestion_ = get_configuration (specifications_[i-1].position_
-                                                      - 1, DOWN);
+                 var.suggestion_ = get_configuration (specifications_[i-1].position_ - 1, DOWN,
+                                                      specifications_[i-1].column_ranks_,
+                                                      !specifications_[i-1].has_manual_delta_y_
+
+                                                      );
                  vars.push_back (var);
                }
              if (i == ties.size() && !specifications_[i].has_manual_position_
@@ -910,7 +1124,10 @@ Tie_formatting_problem::generate_collision_variations (Ties_configuration const
                  Tie_configuration_variation var;
                  var.index_ = i;
                  var.suggestion_ = get_configuration (specifications_[i].position_
-                                                      + 1, UP);
+                                                      + 1, UP,
+                                                      specifications_[i].column_ranks_,
+                                                      !specifications_[i].has_manual_delta_y_
+                                                      );
                  vars.push_back (var);
                }
            }
@@ -920,7 +1137,10 @@ Tie_formatting_problem::generate_collision_variations (Ties_configuration const
              Tie_configuration_variation var;
              var.index_ = i;
              var.suggestion_ = get_configuration (ties[i].position_  + ties[i].dir_,
-                                                  ties[i].dir_);
+                                                  ties[i].dir_,
+                                                  ties[i].column_ranks_,
+                                                  !specifications_[i].has_manual_delta_y_
+                                                  );
              vars.push_back (var);
            }
          
@@ -949,7 +1169,9 @@ Tie_formatting_problem::set_manual_tie_configuration (SCM manual_configs)
            {
              spec.has_manual_position_ = true;
              spec.manual_position_ = scm_to_double (scm_car (entry));
+             spec.has_manual_delta_y_ = (scm_inexact_p (scm_car (entry)) == SCM_BOOL_T);
            }
+         
          if (scm_is_number (scm_cdr (entry)))
            {
              spec.has_manual_dir_ = true;
@@ -960,3 +1182,20 @@ Tie_formatting_problem::set_manual_tie_configuration (SCM manual_configs)
     }
 }
 
+
+void
+Tie_formatting_problem::set_debug_scoring (Ties_configuration const &base)
+{
+#if DEBUG_TIE_SCORING
+  if (to_boolean (x_refpoint_->layout ()
+                 ->lookup_variable (ly_symbol2scm ("debug-tie-scoring"))))
+    {
+      for (vsize i = 0; i < base.size(); i++)
+       {
+         string card = base.complete_tie_card (i);
+         specifications_[i].tie_grob_->set_property ("quant-score",
+                                                     ly_string2scm (card));
+       }
+    }
+#endif
+}