]> git.donarmstrong.com Git - lilypond.git/blob - lily/tie-formatting-problem.cc
skyline vertical spacing.
[lilypond.git] / lily / tie-formatting-problem.cc
1 /*
2   tie-formatting-problem.cc -- implement Tie_formatting_problem
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 2005--2006 Han-Wen Nienhuys <hanwen@xs4all.nl>
7
8 */
9
10 #include "tie-formatting-problem.hh"
11
12 #include "paper-column.hh"
13 #include "bezier.hh" 
14 #include "directional-element-interface.hh"
15 #include "item.hh"
16 #include "libc-extension.hh"
17 #include "misc.hh"
18 #include "note-head.hh"
19 #include "rhythmic-head.hh"
20 #include "spanner.hh" 
21 #include "staff-symbol-referencer.hh"
22 #include "stem.hh"
23 #include "tie-configuration.hh"
24 #include "tie.hh"
25 #include "warn.hh"
26
27
28 void
29 Tie_formatting_problem::print_ties_configuration (Ties_configuration const *ties)
30 {
31   for (vsize i = 0; i < ties->size (); i++)
32     {
33       char const *man_pos = (specifications_[i].has_manual_position_) ? "(M)" : "";
34       char const *man_dir = (specifications_[i].has_manual_dir_) ? "(M)" : "";
35       char const *dir = (ties->at (i).dir_ == UP) ? "up" : "dn";
36       
37       printf ("(P%d%s, %s%s) ", ties->at (i).position_, man_pos, dir, man_dir);
38     }
39   printf ("\n");
40 }
41
42 Interval
43 Tie_formatting_problem::get_attachment (Real y, Drul_array<int> columns) const
44 {
45   Interval attachments (0,0);
46   Direction d = LEFT;
47   do
48     {
49       Tuple2<int> key (columns[d], int (d));
50       Chord_outline_map::const_iterator i (chord_outlines_.find (key));
51       if (i == chord_outlines_.end ())
52         programming_error ("Can't find chord outline");
53       else
54         attachments[d] = i->second.height (y);
55     }
56   while (flip (&d) != LEFT);
57   
58   return attachments;
59 }
60
61 Tie_formatting_problem::Tie_formatting_problem()
62 {
63   x_refpoint_ = 0;
64 }
65
66 Tie_formatting_problem::~Tie_formatting_problem ()
67 {
68   for (Tie_configuration_map::const_iterator i (possibilities_.begin ());
69        i != possibilities_.end (); i++)
70     delete (*i).second;
71 }
72
73 void
74 Tie_formatting_problem::set_column_chord_outline (vector<Item*> bounds,
75                                                   Direction dir,
76                                                   int column_rank)
77 {
78   Real staff_space = Staff_symbol_referencer::staff_space (bounds[0]);
79
80   vector<Box> boxes;
81   vector<Box> head_boxes;
82
83   Grob *stem = 0;
84   for (vsize i = 0; i < bounds.size (); i++)
85     {
86       Grob *head = bounds[i];
87       if (!Note_head::has_interface (head))
88         continue;
89           
90       if (!stem)
91         stem = unsmob_grob (head->get_object ("stem"));
92           
93       Real p = Staff_symbol_referencer::get_position (head);
94       Interval y ((p-1) * 0.5 * staff_space,
95                   (p+1) * 0.5 * staff_space);
96
97       Interval x = head->extent (x_refpoint_, X_AXIS);
98       head_boxes.push_back (Box (x, y));
99       boxes.push_back (Box (x, y));
100
101       Grob *dots = Rhythmic_head::get_dots (head);
102       if (dir == LEFT && dots)
103         {
104           Interval x = dots->extent (x_refpoint_, X_AXIS);
105           int p = int (Staff_symbol_referencer::get_position (dots));
106
107           dot_positions_.insert (p);
108           dot_x_.unite (x);
109
110           Interval y (dots->extent (dots, Y_AXIS));
111           y.translate (p * staff_space * 0.5);
112           
113           boxes.push_back (Box (x, y));
114         }
115     }
116
117   Tuple2<int> key (column_rank, int (dir));
118
119   if (stem
120       && !Stem::is_invisible (stem))
121     {
122       Interval x;
123       x.add_point (stem->relative_coordinate (x_refpoint_, X_AXIS));
124       x.widen (staff_space / 20); // ugh.
125       Interval y;
126       y.add_point (Stem::stem_end_position (stem) * staff_space * .5);
127
128       Direction stemdir = get_grob_direction (stem);
129       y.add_point (Stem::head_positions (stem)[-stemdir]
130                    * staff_space * .5);
131
132       boxes.push_back (Box (x, y));
133
134       stem_extents_[key].unite (Box (x,y));
135
136       if (dir == LEFT)
137         {
138           Box flag_box = Stem::get_translated_flag (stem).extent_box ();
139           flag_box.translate( Offset (x[RIGHT], X_AXIS));
140           boxes.push_back (flag_box);
141         }
142     }
143   else if (stem)
144     {
145       Grob *head = Stem::support_head (stem);
146
147       /*
148         In case of invisible stem, don't pass x-center of heads.
149        */
150       Real x_center = head->extent (x_refpoint_, X_AXIS).center ();
151       Interval x_ext;
152       x_ext[-dir] = x_center;
153       Interval y_ext;
154       for (vsize j = 0; j < head_boxes.size (); j++)
155         y_ext.unite (head_boxes[j][Y_AXIS]);
156
157       boxes.push_back (Box (x_ext, y_ext));
158     }
159   
160   Direction updowndir = DOWN;
161   do
162     {
163       Interval x;
164       Interval y;
165       if (head_boxes.size())
166         {
167           Box b = boundary (head_boxes, updowndir, 0);
168           x = b[X_AXIS];
169           x[-dir] =  b[X_AXIS].linear_combination (-dir / 2);
170           y[-updowndir] = b[Y_AXIS][updowndir];
171           y[updowndir] = updowndir * infinity_f;
172         }
173
174       if (!x.is_empty ())
175         boxes.push_back (Box (x, y));
176     }
177   while (flip (&updowndir) != DOWN);
178   
179   chord_outlines_[key] = Skyline (boxes, Y_AXIS, -dir);
180   if (bounds[0]->break_status_dir ())
181     {
182       Real x = robust_relative_extent (bounds[0],  x_refpoint_, X_AXIS)[-dir];
183       chord_outlines_[key].set_minimum_height (x);
184     }
185   else
186     {
187       Interval x;
188       for (vsize j = 0; j < head_boxes.size (); j++)
189         {
190           x.unite (head_boxes[j][X_AXIS]);
191         }
192       
193       chord_outlines_[key].set_minimum_height (x[dir]);
194     }
195
196   head_extents_[key].set_empty ();
197   for (vsize i = 0; i < head_boxes.size (); i++)
198     {
199       head_extents_[key].unite (head_boxes[i]);
200     }
201 }
202
203 void
204 Tie_formatting_problem::set_chord_outline (vector<Item*> bounds,
205                                            Direction dir)
206
207 {
208   vector<int> ranks;
209   for (vsize i = 0; i < bounds.size (); i++)
210     ranks.push_back (bounds[i]->get_column ()->get_rank ());
211
212   vector_sort (ranks, less<int> ());
213   uniq (ranks);
214
215   for (vsize i = 0; i < ranks.size (); i++)
216     {
217       vector<Item*> col_items;
218       for (vsize j = 0; j < bounds.size (); j ++)
219         {
220           if (bounds[j]->get_column ()->get_rank () == ranks[i])
221             col_items.push_back (bounds[j]);
222         }
223
224       set_column_chord_outline (col_items, dir, ranks[i]);
225     }
226 }
227   
228
229
230 void
231 Tie_formatting_problem::from_tie (Grob *tie)
232 {
233   vector<Grob*> ties;
234   ties.push_back (tie);
235   from_ties (ties);
236
237   details_.from_grob (tie);
238 }
239
240 Grob *
241 Tie_formatting_problem::common_x_refpoint () const
242 {
243   return x_refpoint_;
244 }
245
246 void
247 Tie_formatting_problem::from_ties (vector<Grob*> const &ties)
248 {
249   if (ties.empty ())
250     return;
251   
252   x_refpoint_ = ties[0];
253   for (vsize i = 0; i < ties.size (); i++)
254     {
255       x_refpoint_ = dynamic_cast<Spanner*> (ties[i])->get_bound (LEFT)->common_refpoint (x_refpoint_, X_AXIS); 
256       x_refpoint_ = dynamic_cast<Spanner*> (ties[i])->get_bound (RIGHT)->common_refpoint (x_refpoint_, X_AXIS); 
257     }
258
259   details_.from_grob (ties[0]);
260   
261   Direction d = LEFT;
262   do
263     {
264       vector<Item*> bounds;
265       
266       for (vsize i = 0; i < ties.size (); i++)
267         {
268           Item *it = dynamic_cast<Spanner*> (ties[i])->get_bound (d);
269                                              
270           bounds.push_back (it);
271         }
272       
273       set_chord_outline (bounds, d);
274     }
275   while (flip (&d) != LEFT);
276
277
278   for (vsize i = 0; i < ties.size (); i++)
279     {
280       Tie_specification spec;
281
282       spec.get_tie_manual_settings (ties[i]);
283       
284
285       
286       do
287         {
288           spec.note_head_drul_[d] = Tie::head (ties[i], d);
289           spec.column_ranks_[d] =
290             dynamic_cast<Spanner*> (ties[i])->get_bound (d)->get_column ()->get_rank ();
291         }
292       while (flip (&d) != LEFT);
293       specifications_.push_back (spec);
294     }
295 }
296
297 void
298 Tie_formatting_problem::from_semi_ties (vector<Grob*> const &semi_ties, Direction head_dir)
299 {
300   if (semi_ties.empty ())
301     return;
302   
303   details_.from_grob (semi_ties[0]);
304   vector<Item*> heads;
305
306   int column_rank = -1;
307   for (vsize i = 0; i < semi_ties.size (); i++)
308     {
309       Tie_specification spec;
310       Item *head = unsmob_item (semi_ties[i]->get_object ("note-head"));
311        
312       if (!head)
313         programming_error ("LV tie without head?!");
314
315       if (head)
316         {
317           spec.position_ = int (Staff_symbol_referencer::get_position (head));
318         }
319
320       spec.get_tie_manual_settings (semi_ties[i]);
321       
322       spec.note_head_drul_[head_dir] = head;
323       column_rank = dynamic_cast<Item*> (head)->get_column ()->get_rank ();
324       spec.column_ranks_ = Drul_array<int> (column_rank, column_rank);
325       heads.push_back (head);
326       specifications_.push_back (spec);
327     }
328
329   x_refpoint_ = semi_ties [0];
330   for (vsize i = 0; i < semi_ties.size (); i++)
331     x_refpoint_ = semi_ties[i]->common_refpoint (x_refpoint_, X_AXIS); 
332   for (vsize i = 0; i < heads.size (); i++)
333     x_refpoint_ = heads[i]->common_refpoint (x_refpoint_, X_AXIS); 
334
335   set_chord_outline (heads, head_dir);
336
337   Tuple2<int> head_key (column_rank, head_dir);
338   Tuple2<int> open_key (column_rank, -head_dir);
339   Real extremal = chord_outlines_[head_key].max_height ();
340
341   chord_outlines_[open_key] = Skyline (head_dir);
342   chord_outlines_[open_key].set_minimum_height (extremal - head_dir * 1.5);
343 }
344
345
346 Tie_specification
347 Tie_formatting_problem::get_tie_specification (int i) const
348 {
349   return specifications_[i];
350 }
351
352
353 /*
354   Return configuration, create it if necessary. 
355 */
356 Tie_configuration*
357 Tie_formatting_problem::get_configuration (int pos, Direction dir, Drul_array<int> columns) const
358 {
359   int key_components[] = {
360     pos, dir, columns[LEFT], columns[RIGHT]
361   };
362   Tuple<int,4> key (key_components);
363     
364   Tie_configuration_map::const_iterator f = possibilities_.find (key);
365   if (f != possibilities_.end ())
366     {
367       return (*f).second;
368     }
369
370   
371   Tie_configuration *conf = generate_configuration (pos, dir, columns);
372   ((Tie_formatting_problem*) this)->possibilities_[key] = conf;
373   return conf;
374 }
375
376 Tie_configuration*
377 Tie_formatting_problem::generate_configuration (int pos, Direction dir,
378                                                 Drul_array<int> columns) const
379 {
380   Tie_configuration *conf = new Tie_configuration;
381   conf->position_ = pos;
382   conf->dir_ = dir;
383   
384   conf->column_ranks_ = columns;
385   
386   Real y = conf->position_ * 0.5 * details_.staff_space_;
387
388   bool y_tune = true;
389   if (dot_positions_.find (pos) != dot_positions_.end ())
390     {
391       conf->delta_y_ += dir * 0.25 * details_.staff_space_;
392       y_tune = false;
393     }
394   
395   if (y_tune
396       && max (fabs (get_head_extent (columns[LEFT], LEFT, Y_AXIS)[dir] - y),
397               fabs (get_head_extent (columns[RIGHT], RIGHT, Y_AXIS)[dir] - y)) < 0.25
398       && !Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos))
399     {
400       conf->delta_y_ =
401         (get_head_extent (columns[LEFT], LEFT, Y_AXIS)[dir] - y)
402         + dir * details_.outer_tie_vertical_gap_;
403     }
404
405   if (y_tune)
406     {
407       conf->attachment_x_ = get_attachment (y + conf->delta_y_, conf->column_ranks_);
408       Real h =  conf->height (details_);
409       
410       /*
411         TODO:
412
413         - should make sliding criterion, should flatten ties if
414
415         - they're just the wrong (ie. touching line at top & bottom)
416         size.
417         
418        */
419       if (h < details_.intra_space_threshold_ * 0.5 * details_.staff_space_)
420         {
421           if (!Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos)
422               && abs (pos) < 2 * Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_))
423             {
424               conf->center_tie_vertically (details_);
425             }
426           else if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos))
427             {
428               conf->delta_y_ += dir *
429                 details_.tip_staff_line_clearance_ * 0.5 *  details_.staff_space_;
430             }
431         }
432       else 
433         {
434           Real top_y = y + conf->delta_y_ + conf->dir_ * h;
435           Real top_pos = top_y / (0.5*details_.staff_space_);
436           int round_pos = int (my_round (top_pos));
437
438           /* TODO: should use other variable? */
439           Real clearance = details_.center_staff_line_clearance_;
440           if (fabs (top_pos - round_pos) < clearance
441               && Staff_symbol_referencer::on_staff_line (details_.staff_symbol_referencer_,
442                                                          round_pos))
443             {
444               Real new_y = (round_pos + clearance * conf->dir_) * 0.5 * details_.staff_space_;
445               conf->delta_y_ = (new_y - top_y);
446             }
447         }
448     }
449   
450   conf->attachment_x_ = get_attachment (y + conf->delta_y_, conf->column_ranks_);
451   if (conf->height (details_) < details_.intra_space_threshold_ * 0.5 * details_.staff_space_)
452     {
453       /*
454         This is less sensible for long ties, since those are more
455         horizontal.
456       */
457       Interval close_by = get_attachment (y
458                                           + conf->delta_y_
459                                           + (dir * details_.intra_space_threshold_ * 0.25
460                                              * details_.staff_space_),
461                                           conf->column_ranks_);
462       
463       conf->attachment_x_.intersect (close_by);
464     }
465
466   conf->attachment_x_.widen ( - details_.x_gap_);
467
468   if (conf->column_span_length ())
469     {
470       /*
471         avoid the stems that we attach to as well. We don't do this
472         for semities (span length = 0)
473
474         It would be better to check D against HEAD-DIRECTION if
475         applicable.
476       */
477       Direction d = LEFT;
478       do
479         {
480           Real y = conf->position_ * details_.staff_space_ * 0.5 + conf->delta_y_;
481           if (get_stem_extent (conf->column_ranks_[d], d, X_AXIS).is_empty ()
482               || !get_stem_extent (conf->column_ranks_[d], d, Y_AXIS).contains (y))
483             continue;
484
485           conf->attachment_x_[d] =
486             d * min (d * conf->attachment_x_[d],
487                      d * (get_stem_extent (conf->column_ranks_[d], d, X_AXIS)[-d] - d * details_.stem_gap_));
488         }
489       while (flip (&d) != LEFT);
490     }  
491   return conf;
492 }
493
494 Interval
495 Tie_formatting_problem::get_head_extent (int col, Direction d, Axis a) const
496 {
497   return (*head_extents_.find (Tuple2<int> (col, int (d)))).second[a];
498 }
499
500 Interval
501 Tie_formatting_problem::get_stem_extent (int col, Direction d, Axis a) const
502 {
503   return (*stem_extents_.find (Tuple2<int> (col, int (d)))).second[a];
504 }
505
506 /**
507    TIE_IDX and TIES_CONF are optional.
508  */
509 Real
510 Tie_formatting_problem::score_aptitude (Tie_configuration *conf,
511                                         Tie_specification const &spec,
512                                         Ties_configuration *ties_conf, int tie_idx) const
513 {
514   Real penalty = 0.0;
515   Real curve_y = conf->position_ * details_.staff_space_ * 0.5 + conf->delta_y_;
516   Real tie_y = spec.position_ * details_.staff_space_ * 0.5;
517   if (sign (curve_y - tie_y) != conf->dir_)
518     {
519       Real p =  details_.wrong_direction_offset_penalty_;
520       if (ties_conf)
521         ties_conf->add_tie_score (p, tie_idx, "wrong dir");
522       else
523         penalty += p;
524     }
525
526   {
527     Real p = details_.vertical_distance_penalty_factor_ * fabs (curve_y - tie_y);
528     if (ties_conf)
529       ties_conf->add_tie_score (p, tie_idx, "vdist");
530     else
531       penalty += p; 
532   }
533   
534   Direction d = LEFT;
535   do
536     {
537       if (!spec.note_head_drul_[d])
538         continue;
539       
540       Interval head_x = spec.note_head_drul_[d]->extent (x_refpoint_, X_AXIS);
541       Real dist = head_x.distance (conf->attachment_x_[d]);
542
543       /*
544         TODO: flatten with log or sqrt.
545        */
546       Real p = details_.horizontal_distance_penalty_factor_ * dist;
547       if (ties_conf)
548         ties_conf->add_tie_score (p, tie_idx,
549                                   (d == LEFT) ? "lhdist" : "rhdist");
550       else
551         penalty += p;
552     }
553   while (flip (&d) != LEFT);
554
555   return penalty;
556 }
557
558 void
559 Tie_formatting_problem::score_configuration (Tie_configuration *conf) const
560 {
561   if (conf->scored_)
562     {
563       return ;
564     }
565   
566   Real length = conf->attachment_x_.length ();
567
568   conf->add_score (details_.min_length_penalty_factor_
569                    * peak_around (0.33 * details_.min_length_, details_.min_length_, length),
570                    "minlength");
571   
572   Real tip_pos = conf->position_ + conf->delta_y_ / 0.5 * details_.staff_space_;
573   Real tip_y = tip_pos * details_.staff_space_ * 0.5;
574   Real height =  conf->height (details_);
575
576   Real top_y = tip_y + conf->dir_ * height;
577   Real top_pos = 2 * top_y / details_.staff_space_;
578   Real round_top_pos = rint (top_pos);
579   if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_,
580                                                 int (round_top_pos))
581       && Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_) > top_y)
582     {
583       conf->add_score (
584         details_.staff_line_collision_penalty_
585         * peak_around (0.1 * details_.center_staff_line_clearance_,
586                      details_.center_staff_line_clearance_,
587                        fabs (top_pos - round_top_pos)),
588         "line center");
589     }
590   
591   if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_,
592                                         int (rint (tip_pos))))
593     {
594       conf->add_score (details_.staff_line_collision_penalty_
595                        * peak_around (0.1 * details_.tip_staff_line_clearance_,
596                                       details_.tip_staff_line_clearance_,
597                                       fabs (tip_pos - rint (tip_pos))),
598                        "tipline");
599     }
600
601   if (!dot_x_.is_empty ())
602     {
603       /* use left edge? */
604       Real x = dot_x_.center ();
605       
606       Bezier b = conf->get_transformed_bezier (details_);
607       if (b.control_point_extent (X_AXIS).contains (x))
608         {
609           Real y = b.get_other_coordinate (X_AXIS, x);
610
611           for (set<int>::const_iterator i (dot_positions_.begin ());
612                i != dot_positions_.end (); i ++)
613             {
614               int dot_pos = (*i);
615               conf->add_score (details_.dot_collision_penalty_
616                 * peak_around (.1 * details_.dot_collision_clearance_,
617                                details_.dot_collision_clearance_,
618                                fabs (dot_pos * details_.staff_space_ * 0.5 - y)),
619                                "dot collision");
620             }
621         }
622     }
623
624   conf->scored_ = true;
625 }
626
627 Tie_configuration
628 Tie_formatting_problem::find_optimal_tie_configuration (Tie_specification const &spec) const
629 {
630   vector<Tie_configuration*> confs;
631
632   int pos = spec.position_;
633   Direction dir = spec.manual_dir_;
634
635   for (int i = 0; i < details_.single_tie_region_size_; i ++)
636     {
637       confs.push_back (generate_configuration (pos + i * dir, dir,
638                                                spec.column_ranks_));
639       
640       if (spec.has_manual_position_)
641         {
642           confs.back ()->delta_y_
643             = (spec.manual_position_ - spec.position_)
644             * 0.5 * details_.staff_space_;
645
646           break;
647         }
648     }
649
650   vector<Real> scores;
651
652   int best_idx = -1;
653   Real best_score = 1e6;
654   for (vsize i = 0; i < confs.size (); i ++)
655     {
656       score_configuration (confs[i]);
657       Real score = score_aptitude (confs[i], spec, 0, 0)
658         + confs[i]->score ();
659
660       if (score < best_score)
661         {
662           best_score = score;
663           best_idx = i;
664         }
665     }
666
667   if (best_idx < 0)
668     programming_error ("No best tie configuration found.");
669
670   Tie_configuration best
671     = (best_idx >= 0) ?  *confs[best_idx] : *confs[0];
672   
673   for (vsize i = 0; i < confs.size (); i++)
674     delete confs[i];
675
676   return best;
677 }
678
679 Tie_specification::Tie_specification ()
680 {
681   has_manual_position_ = false;
682   has_manual_dir_ = false;
683   position_ = 0;
684   manual_position_ = 0;
685   manual_dir_ = CENTER;
686   note_head_drul_[LEFT] =
687     note_head_drul_[RIGHT] = 0;
688   column_ranks_[RIGHT] =
689     column_ranks_[LEFT] = 0;
690 }
691
692
693 void
694 Tie_specification::get_tie_manual_settings (Grob *tie)
695 {
696   if (scm_is_number (tie->get_property_data ("direction")))
697     {
698       manual_dir_ = to_dir (tie->get_property ("direction"));
699       has_manual_dir_ = true;
700     }
701   
702   position_ = Tie::get_position (tie);
703   if (scm_is_number (tie->get_property ("staff-position")))
704     {
705       manual_position_ = scm_to_double (tie->get_property ("staff-position"));
706       has_manual_position_ = true;
707       position_ = int (my_round (manual_position_));
708     }
709 }
710
711 int
712 Tie_specification::column_span () const
713 {
714   return column_ranks_[RIGHT] - column_ranks_[LEFT];
715 }
716
717 void
718 Tie_formatting_problem::score_ties_aptitude (Ties_configuration *ties) const
719 {
720   if  (ties->size () != specifications_.size ())
721     {
722       programming_error ("Huh? Mismatch between sizes.");
723       return;
724     }
725
726   for (vsize i = 0; i < ties->size (); i++)
727     score_aptitude (&ties->at (i), specifications_[i],
728                     ties, i);
729 }
730
731 void
732 Tie_formatting_problem::score_ties (Ties_configuration *ties) const
733 {
734   if (ties->scored_)
735     return;
736   
737   score_ties_configuration (ties);
738   score_ties_aptitude (ties);
739   ties->scored_ = true;
740 }
741
742 void
743 Tie_formatting_problem::score_ties_configuration (Ties_configuration *ties) const
744 {
745   for (vsize i = 0; i < ties->size (); i++)
746     {
747       score_configuration (&ties->at (i));
748       ties->add_tie_score (ties->at (i).score (), i, "conf");
749     }
750   
751   Real last_edge = 0.0;
752   Real last_center = 0.0;
753   for (vsize i = 0; i < ties->size (); i++)
754     {
755       Bezier b (ties->at (i).get_transformed_bezier (details_));
756         
757       Real center = b.curve_point (0.5)[Y_AXIS];
758       Real edge = b.curve_point (0.0)[Y_AXIS];
759       
760       if (i)
761         {
762           if (edge <= last_edge)
763             ties->add_score (details_.tie_column_monotonicity_penalty_, "monoton edge");
764           if (center <= last_center)
765             ties->add_score (details_.tie_column_monotonicity_penalty_, "monoton cent");
766
767           ties->add_score (details_.tie_tie_collision_penalty_ *
768                            peak_around (0.1 * details_.tie_tie_collision_distance_,
769                                         details_.tie_tie_collision_distance_,
770                                         fabs (center - last_center)),
771                            "tietie center");
772           ties->add_score (details_.tie_tie_collision_penalty_ *
773                            peak_around (0.1 * details_.tie_tie_collision_distance_,
774                                         details_.tie_tie_collision_distance_,
775                                         fabs (edge - last_edge)), "tietie edge");
776         }
777
778       last_edge = edge;
779       last_center = center;
780     }
781
782   ties->add_score (details_.outer_tie_length_symmetry_penalty_factor_
783                    * fabs (ties->at (0).attachment_x_.length () - ties->back ().attachment_x_.length ()),
784                    "length symm");
785   
786   ties->add_score (details_.outer_tie_vertical_distance_symmetry_penalty_factor_
787                    * fabs (fabs (specifications_[0].position_ * 0.5 * details_.staff_space_
788                                  - (ties->at (0).position_ * 0.5 * details_.staff_space_
789                                     + ties->at (0).delta_y_))
790                            -
791                            fabs (specifications_.back ().position_ * 0.5 * details_.staff_space_
792                                  - (ties->back ().position_ * 0.5 * details_.staff_space_
793                                     + ties->back ().delta_y_))),
794                    "pos symmetry");
795 }
796
797 /*
798   Generate with correct X-attachments and beziers, copying delta_y_
799   from TIES_CONFIG if necessary.
800 */
801 Ties_configuration
802 Tie_formatting_problem::generate_ties_configuration (Ties_configuration const &ties_config)
803 {
804   Ties_configuration copy;
805   for (vsize i = 0; i < ties_config.size (); i++)
806     {
807       Tie_configuration * ptr = get_configuration (ties_config[i].position_, ties_config[i].dir_,
808                                                    ties_config[i].column_ranks_);
809       if (specifications_[i].has_manual_position_)
810         {
811           ptr->delta_y_
812             = (specifications_[i].manual_position_ - ties_config[i].position_)
813             * 0.5 * details_.staff_space_;
814         }
815       copy.push_back (*ptr);
816     }
817   
818   return copy;
819 }
820
821 Ties_configuration
822 Tie_formatting_problem::generate_base_chord_configuration () 
823 {
824   Ties_configuration ties_config;
825   for (vsize i = 0;  i < specifications_.size (); i ++)
826     {
827       Tie_configuration conf;
828       if (specifications_[i].has_manual_dir_)
829         conf.dir_ = specifications_[i].manual_dir_;
830       if (specifications_[i].has_manual_position_)
831         {
832           conf.position_ = (int) my_round (specifications_[i].manual_position_);
833           conf.delta_y_ = (specifications_[i].manual_position_ - conf.position_)
834             * 0.5 * details_.staff_space_;
835         }
836       else
837         {
838           conf.position_ = specifications_[i].position_;
839         }
840
841       conf.column_ranks_ = specifications_[i].column_ranks_;
842       ties_config.push_back (conf);
843     }
844
845   set_ties_config_standard_directions (&ties_config);
846   for (vsize i = 0; i < ties_config.size (); i++)
847     if (!specifications_[i].manual_position_)
848       ties_config[i].position_ += ties_config[i].dir_;
849
850   ties_config = generate_ties_configuration (ties_config);
851   
852   return ties_config;
853 }
854
855 Ties_configuration
856 Tie_formatting_problem::find_best_variation (Ties_configuration const &base,
857                                              vector<Tie_configuration_variation> vars)
858 {
859   Ties_configuration best = base;
860   
861   /*
862     This simply is 1-opt: we have K substitions, and we try applying
863     exactly every one for each.
864   */
865   for (vsize i = 0; i < vars.size (); i++)
866     {
867       Ties_configuration variant (base);
868       variant[vars[i].index_] = *vars[i].suggestion_;
869
870       variant.reset_score ();
871       score_ties (&variant);
872       
873       if (variant.score () < best.score ())
874         {
875           best = variant;
876         }
877     }
878
879   return best;
880 }
881   
882                                        
883
884 Ties_configuration
885 Tie_formatting_problem::generate_optimal_chord_configuration ()
886 {
887   Ties_configuration base = generate_base_chord_configuration ();
888   vector<Tie_configuration_variation> vars = generate_collision_variations (base);
889   
890   score_ties (&base);
891   Ties_configuration best = find_best_variation (base, vars);
892   vars = generate_extremal_tie_variations (best);
893   best = find_best_variation (best, vars);
894
895   return best;
896 }
897
898 void
899 Tie_formatting_problem::set_ties_config_standard_directions (Ties_configuration *tie_configs)
900 {
901   if (tie_configs->empty ())
902     return ;
903
904   if (!tie_configs->at (0).dir_)
905     {
906       if (tie_configs->size () == 1)
907         tie_configs->at (0).dir_ = Direction (sign (tie_configs->at (0).position_));
908
909       if (!tie_configs->at (0).dir_)
910         tie_configs->at (0).dir_ = DOWN;
911     }
912   
913   if (!tie_configs->back ().dir_)
914     tie_configs->back ().dir_ = UP;
915
916   /*
917     Seconds
918    */
919   for (vsize i = 1; i < tie_configs->size (); i++)
920     {
921       Real diff = (tie_configs->at (i).position_
922                    -tie_configs->at (i-1).position_);
923                    
924       Real span_diff 
925         = specifications_[i].column_span () - specifications_[i-1].column_span ();
926       if (span_diff && fabs (diff) <= 2)
927         {
928           if  (span_diff > 0)
929             tie_configs->at (i).dir_ = UP;
930           else if (span_diff < 0)
931             tie_configs->at (i-1).dir_ = DOWN;  
932         }
933       else if (fabs (diff) <= 1)
934         {
935           if (!tie_configs->at (i-1).dir_)
936             tie_configs->at (i-1).dir_ = DOWN;
937           if (!tie_configs->at (i).dir_)
938             tie_configs->at (i).dir_ = UP;
939         }
940     }
941
942   for (vsize i = 1; i < tie_configs->size() - 1; i++)
943     {
944       Tie_configuration &conf = tie_configs->at (i);
945       if (conf.dir_)
946         continue;
947
948       Direction position_dir =
949         Direction (sign (conf.position_));
950       if (!position_dir)
951         position_dir = DOWN;
952
953       conf.dir_ = position_dir;
954     }
955 }
956
957 Tie_configuration_variation::Tie_configuration_variation ()
958 {
959   index_ = 0;
960   suggestion_ = 0;
961 }
962
963 vector<Tie_configuration_variation>
964 Tie_formatting_problem::generate_extremal_tie_variations (Ties_configuration const &ties) const
965 {
966   vector<Tie_configuration_variation> vars;
967   Direction d = DOWN;
968   do
969     {
970       if (boundary (ties, d, 0).dir_ == d
971           && !boundary (specifications_, d, 0).has_manual_position_)
972         for (int i = 1; i <= details_.multi_tie_region_size_; i++)
973           {
974             Tie_configuration_variation var;
975             var.index_ = (d == DOWN) ? 0 : ties.size () - 1;
976             var.suggestion_ = get_configuration (boundary (ties, d, 0).position_
977                                                  + d * i, d,
978                                                  boundary (ties, d, 0).column_ranks_);
979             vars.push_back (var);
980           }
981     }
982   while (flip (&d) !=  DOWN);
983
984   return vars;
985 }
986
987
988 vector<Tie_configuration_variation>
989 Tie_formatting_problem::generate_collision_variations (Ties_configuration const &ties) const
990 {
991   Real center_distance_tolerance = 0.25;
992   
993   vector<Tie_configuration_variation> vars;
994   Real last_center = 0.0;
995   for (vsize i = 0; i < ties.size (); i++)
996     {
997       Bezier b (ties[i].get_transformed_bezier (details_));
998         
999       Real center = b.curve_point (0.5)[Y_AXIS];
1000       
1001       if (i)
1002         {
1003           if (center <= last_center + center_distance_tolerance)
1004             {
1005               if (!specifications_[i].has_manual_dir_)
1006                 {
1007                   Tie_configuration_variation var;
1008                   var.index_ = i;
1009                   var.suggestion_ = get_configuration (specifications_[i].position_
1010                                                        - ties[i].dir_,
1011                                                        - ties[i].dir_,
1012
1013                                                        ties[i].column_ranks_
1014                                                        );
1015
1016                   vars.push_back (var);
1017                 }
1018
1019               if (!specifications_[i-1].has_manual_dir_)
1020                 {
1021                   Tie_configuration_variation var;
1022                   var.index_ = i-1;
1023                   var.suggestion_ = get_configuration (specifications_[i-1].position_
1024                                                        - ties[i-1].dir_,
1025                                                        - ties[i-1].dir_,
1026                                                        specifications_[i-1].column_ranks_);
1027
1028                   vars.push_back (var);
1029                 }
1030
1031               if (i == 1 && !specifications_[i-1].has_manual_position_
1032                   && ties[i-1].dir_ == DOWN)
1033                 {
1034                   Tie_configuration_variation var;
1035                   var.index_ = i-1;
1036                   var.suggestion_ = get_configuration (specifications_[i-1].position_ - 1, DOWN,
1037                                                        specifications_[i-1].column_ranks_);
1038                   vars.push_back (var);
1039                 }
1040               if (i == ties.size() && !specifications_[i].has_manual_position_
1041                   && ties[i].dir_ == UP)
1042                 {
1043                   Tie_configuration_variation var;
1044                   var.index_ = i;
1045                   var.suggestion_ = get_configuration (specifications_[i].position_
1046                                                        + 1, UP,
1047                                                        specifications_[i].column_ranks_);
1048                   vars.push_back (var);
1049                 }
1050             }
1051           else if (dot_positions_.find (ties[i].position_) != dot_positions_.end ()
1052                    && !specifications_[i].has_manual_position_)
1053             {
1054               Tie_configuration_variation var;
1055               var.index_ = i;
1056               var.suggestion_ = get_configuration (ties[i].position_  + ties[i].dir_,
1057                                                    ties[i].dir_,
1058                                                    ties[i].column_ranks_);
1059               vars.push_back (var);
1060             }
1061           
1062         }
1063
1064       last_center = center;
1065     }
1066
1067
1068   return vars;
1069 }
1070
1071 void
1072 Tie_formatting_problem::set_manual_tie_configuration (SCM manual_configs)
1073 {
1074   vsize k = 0;
1075   for (SCM s = manual_configs;
1076        scm_is_pair (s) && k < specifications_.size (); s = scm_cdr (s))
1077     {
1078       SCM entry = scm_car (s);
1079       if (scm_is_pair (entry))
1080         {
1081           Tie_specification &spec = specifications_[k];
1082
1083           if (scm_is_number (scm_car (entry)))
1084             {
1085               spec.has_manual_position_ = true;
1086               spec.manual_position_ = scm_to_double (scm_car (entry));
1087             }
1088           if (scm_is_number (scm_cdr (entry)))
1089             {
1090               spec.has_manual_dir_ = true;
1091               spec.manual_dir_ = Direction (scm_to_int (scm_cdr (entry)));
1092             }
1093         }         
1094       k ++;
1095     }
1096 }
1097