]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam-quanting.cc
Adds programming error for empty config vector in beam-quanting.cc.
[lilypond.git] / lily / beam-quanting.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 1997--2011 Han-Wen Nienhuys <hanwen@xs4all.nl>
5   Jan Nieuwenhuizen <janneke@gnu.org>
6
7   LilyPond is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   LilyPond is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "beam-scoring-problem.hh"
22
23 #include <algorithm>
24 #include <queue>  
25 #include <set>
26 using namespace std;
27
28 #include "align-interface.hh"
29 #include "beam.hh"
30 #include "direction.hh"
31 #include "directional-element-interface.hh"
32 #include "grob.hh"
33 #include "international.hh"
34 #include "libc-extension.hh"
35 #include "main.hh"
36 #include "output-def.hh"
37 #include "pointer-group-interface.hh"
38 #include "staff-symbol-referencer.hh"
39 #include "stencil.hh"
40 #include "stem.hh"
41 #include "warn.hh"
42
43 Real
44 get_detail (SCM alist, SCM sym, Real def)
45 {
46   SCM entry = scm_assq (sym, alist);
47
48   if (scm_is_pair (entry))
49     return robust_scm2double (scm_cdr (entry), def);
50   return def;
51 }
52
53 void
54 Beam_quant_parameters::fill (Grob *him)
55 {
56   SCM details = him->get_property ("details");
57
58   // General
59   BEAM_EPS = get_detail (details, ly_symbol2scm ("beam-eps"), 1e-3);
60   REGION_SIZE = get_detail (details, ly_symbol2scm ("region-size"), 2);
61
62   // forbidden quants
63   SECONDARY_BEAM_DEMERIT = get_detail (details, ly_symbol2scm ("secondary-beam-demerit"), 10.0);
64   STEM_LENGTH_DEMERIT_FACTOR = get_detail (details, ly_symbol2scm ("stem-length-demerit-factor"), 5);
65   HORIZONTAL_INTER_QUANT_PENALTY = get_detail (details, ly_symbol2scm ("horizontal-inter-quant"), 500);
66
67   STEM_LENGTH_LIMIT_PENALTY = get_detail (details, ly_symbol2scm ("stem-length-limit-penalty"), 5000);
68   DAMPING_DIRECTION_PENALTY = get_detail (details, ly_symbol2scm ("damping-direction-penalty"), 800);
69   HINT_DIRECTION_PENALTY = get_detail (details, ly_symbol2scm ("hint-direction-penalty"), 20);
70   MUSICAL_DIRECTION_FACTOR = get_detail (details, ly_symbol2scm ("musical-direction-factor"), 400);
71   IDEAL_SLOPE_FACTOR = get_detail (details, ly_symbol2scm ("ideal-slope-factor"), 10);
72   ROUND_TO_ZERO_SLOPE = get_detail (details, ly_symbol2scm ("round-to-zero-slope"), 0.02);
73
74   // Collisions
75   COLLISION_PENALTY = get_detail (details, ly_symbol2scm ("collision-penalty"), 500);
76   COLLISION_PADDING = get_detail (details, ly_symbol2scm ("collision-padding"), 0.5);
77   STEM_COLLISION_FACTOR = get_detail (details, ly_symbol2scm ("stem-collision-factor"), 0.1);
78 }
79
80 // Add x if x is positive, add |x|*fac if x is negative.
81 static Real
82 shrink_extra_weight (Real x, Real fac)
83 {
84   return fabs (x) * ((x < 0) ? fac : 1.0);
85 }
86
87 /****************************************************************/
88
89 Beam_configuration::Beam_configuration ()
90 {
91   y = Interval (0.0, 0.0);
92   demerits = 0.0;
93   next_scorer_todo = ORIGINAL_DISTANCE;
94 }
95
96 bool Beam_configuration::done () const
97 {
98   return next_scorer_todo >= NUM_SCORERS;
99 }
100
101 void Beam_configuration::add (Real demerit, const string &reason)
102 {
103   demerits += demerit;
104
105 #if DEBUG_BEAM_SCORING
106   if (demerit) 
107     score_card_ += to_string (" %s %.2f", reason.c_str (), demerit);
108 #endif
109 }
110   
111 Beam_configuration* Beam_configuration::new_config (Interval start,
112                                                     Interval offset)
113 {
114   Beam_configuration* qs = new Beam_configuration;
115   qs->y = Interval (int (start[LEFT]) + offset[LEFT],
116                     int (start[RIGHT]) + offset[RIGHT]);
117
118   // This orders the sequence so we try combinations closest to the
119   // the ideal offset first.
120   Real start_score = abs (offset[RIGHT]) + abs (offset[LEFT]);
121   qs->demerits = start_score / 1000.0;
122   qs->next_scorer_todo = ORIGINAL_DISTANCE + 1;
123   
124   return qs;
125 }
126
127 Real
128 Beam_scoring_problem::y_at (Real x, Beam_configuration const* p) const {
129   return p->y[LEFT] + (x - x_span[LEFT]) * p->y.delta() / x_span.delta();
130 }
131
132 /****************************************************************/
133
134 /*
135   TODO:
136
137   - Make all demerits customisable
138
139   - Add demerits for quants per se, as to forbid a specific quant
140   entirely
141 */
142
143 // This is a temporary hack to see how much we can gain by using a
144 // priority queue on the beams to score.
145 static int score_count = 0;
146 LY_DEFINE (ly_beam_score_count, "ly:beam-score-count", 0, 0, 0,
147            (),
148            "count number of beam scores.") {
149   return scm_from_int (score_count);
150 }
151
152 void Beam_scoring_problem::add_collision (Real x, Interval y,
153                                           Real score_factor)
154 {
155   if (edge_dirs[LEFT] == edge_dirs[RIGHT]) {
156     Direction d = edge_dirs[LEFT];
157
158     Real quant_range_y = quant_range[LEFT][-d] +
159       (x - x_span[LEFT]) * (quant_range[RIGHT][-d] - quant_range[LEFT][-d]) / x_span.delta();
160
161     if (d*(quant_range_y - minmax(d, y[UP], y[DOWN])) > 0) {
162       return;
163     }
164   }
165
166   Beam_collision c;
167   c.beam_y_.set_empty ();
168
169   for (vsize j = 0; j < segments_.size (); j++)
170     {
171       if (segments_[j].horizontal_.contains(x))
172         c.beam_y_.add_point (segments_[j].vertical_count_ * beam_translation);
173       if (segments_[j].horizontal_[LEFT] > x)
174         break;
175     }
176   c.beam_y_.widen (0.5 * beam_thickness);
177   
178   c.x_ = x;
179   c.y_ = y;
180   c.base_penalty_ = score_factor;
181   collisions_.push_back (c);
182 }
183
184 void Beam_scoring_problem::init_collisions (vector<Grob*> grobs)
185 {
186   Grob* common_x = NULL;
187   segments_ = Beam::get_beam_segments (beam, &common_x);
188   vector_sort (segments_, beam_segment_less);
189   if (common[X_AXIS] != common_x)
190     {
191       programming_error ("Disagree on common x. Skipping collisions in beam scoring.");
192       return;
193     }
194
195   set<Grob*> stems;
196   for (vsize i = 0; i < grobs.size (); i++) {
197     Box b;
198     for (Axis a = X_AXIS; a < NO_AXES; incr (a))
199       b[a] = grobs[i]->extent(common[a], a);
200
201     Real width = b[X_AXIS].length ();
202     Real width_factor = sqrt (width / staff_space);
203
204     Direction d = LEFT;
205     do
206       add_collision (b[X_AXIS][d], b[Y_AXIS], width_factor);
207     while (flip (&d) != LEFT);
208
209     Grob* stem = unsmob_grob (grobs[i]->get_object ("stem"));
210     if (stem && Stem::has_interface (stem) && Stem::is_normal_stem (stem))
211       {
212         stems.insert (stem);
213       }
214   }
215   
216   for (set<Grob*>::const_iterator it(stems.begin ()); it != stems.end (); it++)
217     {
218       Grob *s = *it;
219       Real x = s->extent (common[X_AXIS], X_AXIS).center();
220
221       Direction stem_dir = get_grob_direction (*it);
222       Interval y;
223       y.set_full ();
224       y[-stem_dir] = Stem::chord_start_y (*it) + (*it)->relative_coordinate (common[Y_AXIS], Y_AXIS)
225         - beam->relative_coordinate (common[Y_AXIS], Y_AXIS);
226
227       Real factor = parameters.STEM_COLLISION_FACTOR;
228       if (!unsmob_grob (s->get_object ("beam"))
229           && !Stem::flag (s).is_empty ())
230         factor = 1.0; 
231       add_collision (x, y, factor);
232     }
233 }
234   
235 void Beam_scoring_problem::init_stems ()
236 {
237   extract_grob_set (beam, "covered-grobs", collisions);
238   extract_grob_set (beam, "stems", stems);
239   for (int a = 2; a--;)
240     {
241       common[a] = common_refpoint_of_array (stems, beam, Axis (a));
242       common[a] = common_refpoint_of_array (collisions, common[a], Axis (a));
243     }
244   
245   Drul_array<Grob *> edge_stems(Beam::first_normal_stem (beam),
246                                 Beam::last_normal_stem (beam));
247   Direction d = LEFT;
248   do
249     x_span[d] = edge_stems[d] ? edge_stems[d]->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
250   while (flip (&d) != LEFT);
251   
252   Drul_array<bool> dirs_found (0, 0);
253   for (vsize i = 0; i < stems.size (); i++)
254     {
255       Grob *s = stems[i];
256       if (!Stem::is_normal_stem (s))
257         continue;
258       
259       Stem_info si (Stem::get_stem_info (s));
260       si.scale (1 / staff_space);
261       stem_infos.push_back (si);
262       dirs_found[si.dir_] = true;
263
264       bool f = to_boolean (s->get_property ("french-beaming"))
265         && s != edge_stems[LEFT] && s != edge_stems[RIGHT];
266
267       Real y = Beam::calc_stem_y (beam, s, common, x_span[LEFT], x_span[RIGHT], CENTER, 
268                                   Interval (0, 0), f);
269       base_lengths.push_back (y / staff_space);
270       stem_xpositions.push_back (s->relative_coordinate (common[X_AXIS], X_AXIS));
271     }
272   
273   edge_dirs = Drul_array<Direction> (CENTER, CENTER);
274   if (stem_infos.size ())
275     {
276       edge_dirs = Drul_array<Direction> (stem_infos[0].dir_,
277                                          stem_infos.back().dir_);
278     }
279
280   is_xstaff = Align_interface::has_interface (common[Y_AXIS]);
281   is_knee = dirs_found[LEFT] && dirs_found[RIGHT];
282   
283   staff_radius = Staff_symbol_referencer::staff_radius (beam);
284   edge_beam_counts =  Drul_array<int>
285     (Stem::beam_multiplicity (stems[0]).length () + 1,
286      Stem::beam_multiplicity (stems.back ()).length () + 1);
287
288   // TODO - why are we dividing by staff_space?
289   beam_translation = Beam::get_beam_translation (beam) / staff_space;
290
291   d = LEFT;
292   do
293     {
294       quant_range[d].set_full ();
295       if (!edge_stems[d])
296         continue;
297       
298       Real stem_offset = edge_stems[d]->relative_coordinate (common[Y_AXIS], Y_AXIS)
299         - beam->relative_coordinate (common[Y_AXIS], Y_AXIS);
300       Interval heads = Stem::head_positions(edge_stems[d]) * 0.5 * staff_space;
301
302       Direction ed = edge_dirs[d];
303       heads.widen(0.5 * staff_space
304                   + (edge_beam_counts[d] - 1) * beam_translation + beam_thickness * .5);
305       quant_range[d][-ed] = heads[ed] + stem_offset;
306     }
307   while (flip (&d) != LEFT);
308
309   init_collisions (collisions);
310 }
311
312 Beam_scoring_problem::Beam_scoring_problem (Grob *me, Drul_array<Real> ys)
313 {
314   beam = me;
315   unquanted_y = ys;
316     
317   /*
318     Calculations are relative to a unit-scaled staff, i.e. the quants are
319     divided by the current staff_space.
320   */
321   staff_space = Staff_symbol_referencer::staff_space (me);
322   beam_thickness = Beam::get_beam_thickness (me) / staff_space;
323   line_thickness = Staff_symbol_referencer::line_thickness (me) / staff_space;
324
325   // This is the least-squares DY, corrected for concave beams.
326   musical_dy = robust_scm2double (me->get_property ("least-squares-dy"), 0);
327
328   parameters.fill (me);
329   init_stems ();
330 }
331
332 void
333 Beam_scoring_problem::generate_quants (vector<Beam_configuration*> *scores) const
334 {
335   int region_size = (int) parameters.REGION_SIZE;
336
337   // Knees and collisions are harder, lets try some more possibilities
338   if (is_knee)
339     region_size += 2;
340   if (collisions_.size ())
341     region_size += 2;
342   
343   Real straddle = 0.0;
344   Real sit = (beam_thickness - line_thickness) / 2;
345   Real inter = 0.5;
346   Real hang = 1.0 - (beam_thickness - line_thickness) / 2;
347   Real base_quants [] = {straddle, sit, inter, hang};
348   int num_base_quants = int (sizeof (base_quants) / sizeof (Real));
349
350   /*
351     Asymetry ? should run to <= region_size ?
352   */
353   vector<Real> unshifted_quants;
354   for (int i = -region_size; i < region_size; i++)
355     for (int j = 0; j < num_base_quants; j++)
356       {
357         unshifted_quants.push_back (i + base_quants[j]);
358       }
359
360   for (vsize i = 0; i < unshifted_quants.size (); i++)
361     for (vsize j = 0; j < unshifted_quants.size (); j++)
362       {
363         Beam_configuration *c =
364           Beam_configuration::new_config (unquanted_y,
365                                           Interval (unshifted_quants[i],
366                                                     unshifted_quants[j]));
367         
368         Direction d = LEFT;
369         do
370           {
371             if (!quant_range[d].contains (c->y[d]))
372               {
373                 delete c;
374                 c = NULL;
375                 break;
376               }
377           }
378         while (flip (&d) != LEFT);
379         if (c)   
380           scores->push_back (c);
381       }
382     
383 }
384
385
386 void Beam_scoring_problem::one_scorer (Beam_configuration* config) const
387 {
388   score_count ++;
389   switch (config->next_scorer_todo) {
390   case SLOPE_IDEAL:
391     score_slope_ideal (config);
392     break;
393   case SLOPE_DIRECTION:
394     score_slope_direction (config);
395     break;
396   case SLOPE_MUSICAL:
397     score_slope_musical (config);
398     break;
399   case FORBIDDEN:
400     score_forbidden_quants (config);
401     break;
402   case STEM_LENGTHS:
403     score_stem_lengths (config);
404     break;
405   case COLLISIONS:
406     score_collisions (config);
407     break;
408   case HORIZONTAL_INTER:
409     score_horizontal_inter_quants (config);
410     break;
411     
412   case NUM_SCORERS:
413   case ORIGINAL_DISTANCE:
414   default:
415     assert (false);
416   }
417   config->next_scorer_todo++;
418 }                                  
419
420
421 Beam_configuration *
422 Beam_scoring_problem::force_score (SCM inspect_quants, const vector<Beam_configuration*> &configs) const
423 {
424   Drul_array<Real> ins = ly_scm2interval (inspect_quants);
425   Real mindist = 1e6;
426   Beam_configuration *best = NULL; 
427   for (vsize i = 0; i < configs.size (); i++)
428     {
429       Real d = fabs (configs[i]->y[LEFT]- ins[LEFT]) + fabs (configs[i]->y[RIGHT] - ins[RIGHT]);
430       if (d < mindist)
431         {
432           best = configs[i];
433           mindist = d;
434         }
435     }
436   if (mindist > 1e5)
437     programming_error ("cannot find quant");
438
439   while (!best->done ())
440     one_scorer (best);
441       
442   return best;
443 }
444
445 Drul_array<Real>
446 Beam_scoring_problem::solve () const {
447   vector<Beam_configuration*> configs;
448   generate_quants (&configs);
449
450   if (configs.empty ())
451     {
452       programming_error ("No viable beam quanting found.  Using unquanted y value.");
453       return unquanted_y;
454     }
455
456   Beam_configuration *best = NULL;  
457
458   bool debug =
459     to_boolean (beam->layout ()->lookup_variable (ly_symbol2scm ("debug-beam-scoring")));
460   SCM inspect_quants = beam->get_property ("inspect-quants");
461   if (scm_is_pair (inspect_quants)) 
462     {
463       debug = true;
464       best = force_score (inspect_quants, configs);
465     }
466   else
467     {
468       std::priority_queue<Beam_configuration*, std::vector<Beam_configuration*>,
469                           Beam_configuration_less> queue;
470       for (vsize i = 0; i < configs.size(); i++)
471         queue.push(configs[i]);
472
473       /*
474         TODO
475
476         It would be neat if we generated new configurations on the
477         fly, depending on the best complete score so far, eg.
478
479         if (best->done()) {
480           if (best->demerits < sqrt(queue.size())
481             break;
482           while (best->demerits > sqrt(queue.size()) {
483             generate and insert new configuration
484           }
485         }
486
487         that would allow us to do away with region_size altogether.
488       */
489       while (true) {
490         best = queue.top ();
491         if (best->done ())
492           break;
493
494         queue.pop ();
495         one_scorer (best);
496         queue.push (best);
497       }
498     }
499
500   Interval final_positions = best->y;
501
502 #if DEBUG_BEAM_SCORING
503   if (debug)
504     {
505       // debug quanting
506       int completed = 0;
507       for (vsize i = 0; i < configs.size (); i++)
508         {
509           if (configs[i]->done ())
510             completed++;
511         }
512
513       string card = best->score_card_ + to_string (" c%d/%d", completed, configs.size());
514       beam->set_property ("annotation", ly_string2scm (card));
515     }
516 #endif
517
518   junk_pointers (configs);
519   return final_positions;
520 }
521
522 void
523 Beam_scoring_problem::score_stem_lengths (Beam_configuration* config) const
524 {
525   Real limit_penalty = parameters.STEM_LENGTH_LIMIT_PENALTY;
526   Drul_array<Real> score (0, 0);
527   Drul_array<int> count (0, 0);
528
529   for (vsize i = 0; i < stem_xpositions.size (); i++)
530     {
531       Real x = stem_xpositions[i];
532       Real dx = x_span.delta ();
533       Real beam_y = dx
534         ? config->y[RIGHT] * (x - x_span[LEFT]) / dx + config->y[LEFT] * (x_span[RIGHT] - x) / dx
535         : (config->y[RIGHT] + config->y[LEFT]) / 2;
536       Real current_y = beam_y + base_lengths[i];
537       Real length_pen = parameters.STEM_LENGTH_DEMERIT_FACTOR;
538
539       Stem_info info = stem_infos[i];
540       Direction d = info.dir_;
541
542       score[d] += limit_penalty * max (0.0, (d * (info.shortest_y_ - current_y)));
543
544       Real ideal_diff = d * (current_y - info.ideal_y_);
545       Real ideal_score = shrink_extra_weight (ideal_diff, 1.5);
546
547       /* We introduce a power, to make the scoring strictly
548          convex. Otherwise a symmetric knee beam (up/down/up/down)
549          does not have an optimum in the middle. */
550       if (is_knee)
551         ideal_score = pow (ideal_score, 1.1);
552
553       score[d] += length_pen * ideal_score;
554       count[d]++;
555     }
556
557   /* Divide by number of stems, to make the measure scale-free. */
558   Direction d = DOWN;
559   do
560     score[d] /= max (count[d], 1);
561   while (flip (&d) != DOWN);
562
563   config->add (score[LEFT] + score[RIGHT], "L");
564 }
565
566 void
567 Beam_scoring_problem::score_slope_direction (Beam_configuration *config) const
568 {
569   Real dy = config->y.delta ();
570   Real damped_dy = unquanted_y.delta();
571   Real dem = 0.0;
572   /*
573     DAMPING_DIRECTION_PENALTY is a very harsh measure, while for
574     complex beaming patterns, horizontal is often a good choice.
575
576     TODO: find a way to incorporate the complexity of the beam in this
577     penalty.
578   */
579   if (sign (damped_dy) != sign (dy))
580     {
581       if (!dy)
582         {
583           if (fabs (damped_dy / x_span.delta ()) > parameters.ROUND_TO_ZERO_SLOPE)
584             dem += parameters.DAMPING_DIRECTION_PENALTY;
585           else
586             dem += parameters.HINT_DIRECTION_PENALTY;
587         }
588       else
589         dem += parameters.DAMPING_DIRECTION_PENALTY;
590     }
591
592   config->add (dem, "Sd");
593 }
594
595 // Score for going against the direction of the musical pattern 
596 void
597 Beam_scoring_problem::score_slope_musical (Beam_configuration *config) const
598 {
599   Real dy = config->y.delta ();
600   Real dem = parameters.MUSICAL_DIRECTION_FACTOR
601     * max (0.0, (fabs (dy) - fabs (musical_dy)));
602   config->add (dem, "Sm");
603 }
604
605 // Score deviation from calculated ideal slope.
606 void
607 Beam_scoring_problem::score_slope_ideal (Beam_configuration *config) const
608 {
609   Real dy = config->y.delta ();
610   Real damped_dy = unquanted_y.delta();
611   Real dem = 0.0;
612   
613   Real slope_penalty = parameters.IDEAL_SLOPE_FACTOR;
614
615   /* Xstaff beams tend to use extreme slopes to get short stems. We
616      put in a penalty here. */
617   if (is_xstaff)
618     slope_penalty *= 10;
619
620   /* Huh, why would a too steep beam be better than a too flat one ? */
621   dem += shrink_extra_weight (fabs (damped_dy) - fabs (dy), 1.5)
622     * slope_penalty;
623
624   config->add (dem, "Si");
625 }
626
627 static Real
628 my_modf (Real x)
629 {
630   return x - floor (x);
631 }
632
633 // TODO - there is some overlap with forbidden quants, but for
634 // horizontal beams, it is much more serious to have stafflines
635 // appearing in the wrong place, so we have a separate scorer.
636 void
637 Beam_scoring_problem::score_horizontal_inter_quants (Beam_configuration *config) const
638 {
639   if (config->y.delta () == 0.0
640       && abs (config->y[LEFT]) < staff_radius * staff_space)
641     {
642       Real yshift = config->y[LEFT] - 0.5 * staff_space;
643       if (fabs (my_round (yshift) - yshift) < 0.01 * staff_space)
644         config->add (parameters.HORIZONTAL_INTER_QUANT_PENALTY, "H");
645     }
646 }
647
648 /*
649   TODO: The fixed value SECONDARY_BEAM_DEMERIT is probably flawed:
650   because for 32nd and 64th beams the forbidden quants are relatively
651   more important than stem lengths.
652 */
653 void
654 Beam_scoring_problem::score_forbidden_quants (Beam_configuration *config) const
655 {
656   Real dy = config->y.delta ();
657
658   Real extra_demerit = parameters.SECONDARY_BEAM_DEMERIT /
659     max (edge_beam_counts[LEFT], edge_beam_counts[RIGHT]);
660
661   Direction d = LEFT;
662   Real dem = 0.0;
663   Real eps = parameters.BEAM_EPS;
664   
665   do
666     {
667       for (int j = 1; j <= edge_beam_counts[d]; j++)
668         {
669           Direction stem_dir = edge_dirs[d];
670
671           /*
672             The 2.2 factor is to provide a little leniency for
673             borderline cases. If we do 2.0, then the upper outer line
674             will be in the gap of the (2, sit) quant, leading to a
675             false demerit.
676           */
677           Real gap1 = config->y[d] - stem_dir * ((j - 1) * beam_translation + beam_thickness / 2 - line_thickness / 2.2);
678           Real gap2 = config->y[d] - stem_dir * (j * beam_translation - beam_thickness / 2 + line_thickness / 2.2);
679
680           Interval gap;
681           gap.add_point (gap1);
682           gap.add_point (gap2);
683
684           for (Real k = -staff_radius;
685                k <= staff_radius + eps; k += 1.0)
686             if (gap.contains (k))
687               {
688                 Real dist = min (fabs (gap[UP] - k), fabs (gap[DOWN] - k));
689
690                 /*
691                   this parameter is tuned to grace-stem-length.ly
692                 */
693                 Real fixed_demerit = 0.4;
694
695                 dem += extra_demerit
696                   * (fixed_demerit
697                      + (1 - fixed_demerit) * (dist / gap.length ()) * 2);
698               }
699         }
700     }
701   while ((flip (&d)) != LEFT);
702
703   if (max (edge_beam_counts[LEFT], edge_beam_counts[RIGHT]) >= 2)
704     {
705       Real straddle = 0.0;
706       Real sit = (beam_thickness - line_thickness) / 2;
707       Real inter = 0.5;
708       Real hang = 1.0 - (beam_thickness - line_thickness) / 2;
709
710       Direction d = LEFT;
711       do
712         {
713           if (edge_beam_counts[d] >= 2
714               && fabs (config->y[d] - edge_dirs[d] * beam_translation) < staff_radius + inter)
715             {
716               // TODO up/down symmetry.
717               if (edge_dirs[d] == UP && dy <= eps
718                   && fabs (my_modf (config->y[d]) - sit) < eps)
719                 dem += extra_demerit;
720
721               if (edge_dirs[d] == DOWN && dy >= eps
722                   && fabs (my_modf (config->y[d]) - hang) < eps)
723                 dem += extra_demerit;
724             }
725
726           if (edge_beam_counts[d] >= 3
727               && fabs (config->y[d] - 2 * edge_dirs[d] * beam_translation) < staff_radius + inter)
728             {
729               // TODO up/down symmetry.
730               if (edge_dirs[d] == UP && dy <= eps
731                   && fabs (my_modf (config->y[d]) - straddle) < eps)
732                 dem += extra_demerit;
733
734               if (edge_dirs[d] == DOWN && dy >= eps
735                   && fabs (my_modf (config->y[d]) - straddle) < eps)
736                 dem += extra_demerit;
737             }
738         }
739       while (flip (&d) != LEFT);
740     }
741
742   config->add (dem, "F");
743 }
744
745 void
746 Beam_scoring_problem::score_collisions (Beam_configuration *config) const
747 {  
748   Real demerits = 0.0;
749   for (vsize i = 0; i < collisions_.size (); i++)
750     {
751       Interval collision_y = collisions_[i].y_;
752       Real x = collisions_[i].x_;
753
754       Real center_beam_y = y_at (x, config);
755       Interval beam_y = center_beam_y + collisions_[i].beam_y_;
756
757       Real dist = infinity_f;
758       if (!intersection (beam_y, collision_y).is_empty ())
759         dist = 0.0;
760       else
761         dist = min (beam_y.distance (collision_y[DOWN]),
762                     beam_y.distance (collision_y[UP]));
763
764       Real scale_free = 
765         max (parameters.COLLISION_PADDING - dist, 0.0)/
766         parameters.COLLISION_PADDING;
767       demerits +=
768         collisions_[i].base_penalty_ *
769         pow (scale_free, 3) * parameters.COLLISION_PENALTY;
770     }
771
772   config->add (demerits, "C");
773