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