]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
d31e570186dca277a527ea687262d1abe45dced1
[lilypond.git] / lily / beam.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 /*
22   TODO:
23
24   - Determine auto knees based on positions if it's set by the user.
25
26   - the code is littered with * and / staff_space calls for
27   #'positions. Consider moving to real-world coordinates?
28
29   Problematic issue is user tweaks (user tweaks are in staff-coordinates.)
30
31   Notes:
32
33   - Stems run to the Y-center of the beam.
34
35   - beam_translation is the offset between Y centers of the beam.
36 */
37
38 #include "beam.hh"
39
40 #include "beam-scoring-problem.hh"
41 #include "beaming-pattern.hh"
42 #include "directional-element-interface.hh"
43 #include "grob-array.hh"
44 #include "international.hh"
45 #include "interval-set.hh"
46 #include "item.hh"
47 #include "least-squares.hh"
48 #include "lookup.hh"
49 #include "main.hh"
50 #include "misc.hh"
51 #include "output-def.hh"
52 #include "pointer-group-interface.hh"
53 #include "spanner.hh"
54 #include "staff-symbol-referencer.hh"
55 #include "stem.hh"
56 #include "warn.hh"
57
58 #if DEBUG_BEAM_SCORING
59 #include "text-interface.hh" // debug output.
60 #include "font-interface.hh" // debug output.
61 #endif
62
63 #include <map>
64
65
66 Beam_stem_segment::Beam_stem_segment ()
67 {
68   max_connect_ = 1000;          // infinity
69   stem_ = 0;
70   width_ = 0.0;
71   stem_x_ = 0.0;
72   rank_ = 0;
73   stem_index_ = 0;
74   dir_ = CENTER;
75 }
76
77 Beam_segment::Beam_segment ()
78 {
79   vertical_count_ = 0;
80 }
81
82 void
83 Beam::add_stem (Grob *me, Grob *s)
84 {
85   if (Stem::get_beam (s))
86     {
87       programming_error ("Stem already has beam");
88       return ;
89     }
90
91   Pointer_group_interface::add_grob (me, ly_symbol2scm ("stems"), s);
92   s->set_object ("beam", me->self_scm ());
93   add_bound_item (dynamic_cast<Spanner *> (me), dynamic_cast<Item *> (s));
94 }
95
96 Real
97 Beam::get_beam_thickness (Grob *me)
98 {
99   return robust_scm2double (me->get_property ("beam-thickness"), 0)
100     * Staff_symbol_referencer::staff_space (me);
101 }
102
103 /* Return the translation between 2 adjoining beams. */
104 Real
105 Beam::get_beam_translation (Grob *me)
106 {
107   int beam_count = get_beam_count (me);
108   Real staff_space = Staff_symbol_referencer::staff_space (me);
109   Real line = Staff_symbol_referencer::line_thickness (me);
110   Real beam_thickness = get_beam_thickness (me);
111   Real fract = robust_scm2double (me->get_property ("length-fraction"), 1.0);
112
113   Real beam_translation = beam_count < 4
114     ? (2 * staff_space + line - beam_thickness) / 2.0
115     : (3 * staff_space + line - beam_thickness) / 3.0;
116
117   return fract * beam_translation;
118 }
119
120 /* Maximum beam_count. */
121 int
122 Beam::get_beam_count (Grob *me)
123 {
124   int m = 0;
125
126   extract_grob_set (me, "stems", stems);
127   for (vsize i = 0; i < stems.size (); i++)
128     {
129       Grob *stem = stems[i];
130       m = max (m, (Stem::beam_multiplicity (stem).length () + 1));
131     }
132   return m;
133 }
134
135 MAKE_SCHEME_CALLBACK (Beam, calc_normal_stems, 1);
136 SCM
137 Beam::calc_normal_stems (SCM smob)
138 {
139   Grob *me = unsmob_grob (smob);
140
141   extract_grob_set (me, "stems", stems);
142   SCM val = Grob_array::make_array ();
143   Grob_array *ga = unsmob_grob_array (val);
144   for (vsize i = 0; i < stems.size ();  i++)
145     if (Stem::is_normal_stem (stems[i]))
146       ga->add (stems[i]);
147
148   return val;
149 }
150
151 MAKE_SCHEME_CALLBACK (Beam, calc_direction, 1);
152 SCM
153 Beam::calc_direction (SCM smob)
154 {
155   Grob *me = unsmob_grob (smob);
156
157   /* Beams with less than 2 two stems don't make much sense, but could happen
158      when you do
159
160      r8[ c8 r8]
161
162   */
163
164   Direction dir = CENTER;
165
166   int count = normal_stem_count (me);
167   if (count < 2)
168     {
169       extract_grob_set (me, "stems", stems);
170       if (stems.size () == 0)
171         {
172           me->warning (_ ("removing beam with no stems"));
173           me->suicide ();
174
175           return SCM_UNSPECIFIED;
176         }
177       else
178         {
179           Grob *stem = first_normal_stem (me);
180
181           /*
182             This happens for chord tremolos.
183           */
184           if (!stem)
185             stem = stems[0];
186
187           if (is_direction (stem->get_property_data ("direction")))
188             dir = to_dir (stem->get_property_data ("direction"));
189           else
190             dir = to_dir (stem->get_property ("default-direction"));
191         }
192     }
193
194   if (count >= 1)
195     {
196       if (!dir)
197         dir = get_default_dir (me);
198
199       consider_auto_knees (me);
200     }
201
202   if (dir)
203     {
204       set_stem_directions (me, dir);
205     }
206
207   return scm_from_int (dir);
208 }
209
210
211
212 /* We want a maximal number of shared beams, but if there is choice, we
213  * take the one that is closest to the end of the stem. This is for
214  * situations like
215  *
216  *        x
217  *       |
218  *       |
219  *   |===|
220  *   |=
221  *   |
222  *  x
223  */
224 int
225 position_with_maximal_common_beams (SCM left_beaming, SCM right_beaming,
226                                     Direction left_dir,
227                                     Direction right_dir)
228 {
229   Slice lslice = int_list_to_slice (scm_cdr (left_beaming));
230
231   int best_count = 0;
232   int best_start = 0;
233   for (int i = lslice[-left_dir];
234        (i - lslice[left_dir]) * left_dir <= 0; i += left_dir)
235     {
236       int count = 0;
237       for (SCM s = scm_car (right_beaming); scm_is_pair (s); s = scm_cdr (s))
238         {
239           int k = -right_dir * scm_to_int (scm_car (s)) + i;
240           if (scm_c_memq (scm_from_int (k), left_beaming) != SCM_BOOL_F)
241             count++;
242         }
243
244       if (count >= best_count)
245         {
246           best_count = count;
247           best_start = i;
248         }
249     }
250
251   return best_start;
252 }
253
254 MAKE_SCHEME_CALLBACK (Beam, calc_beaming, 1)
255 SCM
256 Beam::calc_beaming (SCM smob)
257 {
258   Grob *me = unsmob_grob (smob);
259
260   extract_grob_set (me, "stems", stems);
261
262   Slice last_int;
263   last_int.set_empty ();
264
265   SCM last_beaming = scm_cons (SCM_EOL, scm_list_1 (scm_from_int (0)));
266   Direction last_dir = CENTER;
267   for (vsize i = 0; i < stems.size (); i++)
268     {
269       Grob *this_stem = stems[i];
270       SCM this_beaming = this_stem->get_property ("beaming");
271
272       Direction this_dir = get_grob_direction (this_stem);
273       if (scm_is_pair (last_beaming) && scm_is_pair (this_beaming))
274         {
275           int start_point = position_with_maximal_common_beams
276             (last_beaming, this_beaming,
277              last_dir ? last_dir : this_dir,
278              this_dir);
279
280           Direction d = LEFT;
281           Slice new_slice;
282           do
283             {
284               new_slice.set_empty ();
285               SCM s = index_get_cell (this_beaming, d);
286               for (; scm_is_pair (s); s = scm_cdr (s))
287                 {
288                   int new_beam_pos
289                     = start_point - this_dir * scm_to_int (scm_car (s));
290
291                   new_slice.add_point (new_beam_pos);
292                   scm_set_car_x (s, scm_from_int (new_beam_pos));
293                 }
294             }
295           while (flip (&d) != LEFT);
296
297           if (!new_slice.is_empty ())
298             last_int = new_slice;
299         }
300       else
301         {
302           /*
303             FIXME: what's this for?
304            */
305           SCM s = scm_cdr (this_beaming);
306           for (; scm_is_pair (s); s = scm_cdr (s))
307             {
308               int np = -this_dir * scm_to_int (scm_car (s));
309               scm_set_car_x (s, scm_from_int (np));
310               last_int.add_point (np);
311             }
312         }
313
314       if (scm_ilength (scm_cdr (this_beaming)) > 0)
315         {
316           last_beaming = this_beaming;
317           last_dir = this_dir;
318         }
319     }
320
321   return SCM_EOL;
322 }
323
324 bool
325 operator <(Beam_stem_segment const &a,
326            Beam_stem_segment const &b)
327 {
328   return a.rank_ < b.rank_;
329 }
330
331 typedef map<int, vector<Beam_stem_segment> >  Position_stem_segments_map;
332
333 vector<Beam_segment>
334 Beam::get_beam_segments (Grob *me_grob, Grob **common)
335 {
336   /* ugh, this has a side-effect that we need to ensure that
337      Stem #'beaming is correct */
338   (void) me_grob->get_property ("beaming");
339
340   Spanner *me = dynamic_cast<Spanner*> (me_grob);
341
342   extract_grob_set (me, "stems", stems);
343   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
344
345   commonx = me->get_bound (LEFT)->common_refpoint (commonx, X_AXIS);
346   commonx = me->get_bound (RIGHT)->common_refpoint (commonx, X_AXIS);
347
348   *common = commonx;
349
350   int gap_count = robust_scm2int (me->get_property ("gap-count"), 0);
351   Real gap_length = robust_scm2double (me->get_property ("gap"), 0.0);
352
353   Position_stem_segments_map stem_segments;
354   Real lt = me->layout ()->get_dimension (ly_symbol2scm ("line-thickness"));
355
356   /* There are two concepts of "rank" that are used in the following code.
357      The beam_rank is the vertical position of the beam (larger numbers are
358      closer to the noteheads). Beam_stem_segment.rank_, on the other hand,
359      is the horizontal position of the segment (this is incremented by two
360      for each stem; the beam segment on the right side of the stem has
361      a higher rank (by one) than its neighbour to the left). */
362   Slice ranks;
363   for (vsize i = 0; i < stems.size (); i++)
364     {
365       Grob *stem = stems[i];
366       Real stem_width = robust_scm2double (stem->get_property ("thickness"), 1.0) * lt;
367       Real stem_x = stem->relative_coordinate (commonx, X_AXIS);
368       SCM beaming = stem->get_property ("beaming");
369       Direction d = LEFT;
370       do
371         {
372           // Find the maximum and minimum beam ranks.
373           // Given that RANKS is never reset to empty, the interval will always be
374           // smallest for the left beamlet of the first stem, and then it might grow.
375           // Do we really want this? (It only affects the tremolo gaps) --jneem
376           for (SCM s = index_get_cell (beaming, d);
377                scm_is_pair (s); s = scm_cdr (s))
378             {
379               if (!scm_is_integer (scm_car (s)))
380                 continue;
381
382               int beam_rank = scm_to_int (scm_car (s));
383               ranks.add_point (beam_rank);
384             }
385
386           for (SCM s = index_get_cell (beaming, d);
387                scm_is_pair (s); s = scm_cdr (s))
388             {
389               if (!scm_is_integer (scm_car (s)))
390                 continue;
391
392               int beam_rank = scm_to_int (scm_car (s));
393               Beam_stem_segment seg;
394               seg.stem_ = stem;
395               seg.stem_x_ = stem_x;
396               seg.rank_ = 2 * i + (d+1)/2;
397               seg.width_ = stem_width;
398               seg.stem_index_ = i;
399               seg.dir_ = d;
400               seg.max_connect_ = robust_scm2int (stem->get_property ("max-beam-connect"), 1000);
401
402               Direction stem_dir = get_grob_direction (stem);
403
404               seg.gapped_
405                 = (stem_dir * beam_rank < (stem_dir * ranks[-stem_dir] + gap_count));
406               stem_segments[beam_rank].push_back (seg);
407             }
408         }
409       while (flip (&d) != LEFT);
410     }
411
412   Drul_array<Real> break_overshoot
413     = robust_scm2drul (me->get_property ("break-overshoot"),
414                        Drul_array<Real> (-0.5, 0.0));
415
416   vector<Beam_segment> segments;
417   for (Position_stem_segments_map::const_iterator i (stem_segments.begin ());
418        i != stem_segments.end (); i++)
419     {
420       vector<Beam_stem_segment> segs = (*i).second;
421       vector_sort (segs, less<Beam_stem_segment> ());
422
423       Beam_segment current;
424
425       // Iterate over all of the segments of the current beam rank,
426       // merging the adjacent Beam_stem_segments into one Beam_segment
427       // when appropriate.
428       int vertical_count =  (*i).first;
429       for (vsize j = 0; j < segs.size (); j++)
430         {
431           // Keeping track of the different directions here is a little tricky.
432           // segs[j].dir_ is the direction of the beam segment relative to the stem
433           // (ie. segs[j].dir_ == LEFT if the beam segment sticks out to the left of
434           // its stem) whereas event_dir refers to the edge of the beam segment that
435           // we are currently looking at (ie. if segs[j].dir_ == event_dir then we
436           // are looking at that edge of the beam segment that is furthest from its
437           // stem).
438           Direction event_dir = LEFT;
439           Beam_stem_segment const& seg = segs[j];
440           do
441             {
442               Beam_stem_segment const& neighbor_seg = segs[j + event_dir];
443               // TODO: make names clearer? --jneem
444               // on_line_bound: whether the current segment is on the boundary of the WHOLE beam
445               // on_beam_bound: whether the current segment is on the boundary of just that part
446               //   of the beam with the current beam_rank
447               bool on_line_bound = (seg.dir_ == LEFT) ? seg.stem_index_ == 0
448                 : seg.stem_index_ == stems.size() - 1;
449               bool on_beam_bound = (event_dir == LEFT) ? j == 0 :
450                 j == segs.size () - 1;
451               bool inside_stem = (event_dir == LEFT)
452                 ? seg.stem_index_ > 0
453                 : seg.stem_index_ + 1 < stems.size () ;
454
455               bool event = on_beam_bound
456                 || abs (seg.rank_ - neighbor_seg.rank_) > 1
457                 || (abs (vertical_count) >= seg.max_connect_
458                     || abs (vertical_count) >= neighbor_seg.max_connect_);
459
460               if (!event)
461                 // Then this edge of the current segment is irrelevent because it will
462                 // be connected with the next segment in the event_dir direction.
463                 continue;
464
465               current.vertical_count_ = vertical_count;
466               current.horizontal_[event_dir] = seg.stem_x_;
467               if (seg.dir_ == event_dir)
468                 // then we are examining the edge of a beam segment that is furthest
469                 // from its stem.
470                 {
471                   if (on_line_bound
472                       && me->get_bound (event_dir)->break_status_dir ())
473                     {
474                       current.horizontal_[event_dir]
475                         = (robust_relative_extent (me->get_bound (event_dir),
476                                                    commonx, X_AXIS)[RIGHT]
477                            + event_dir * break_overshoot[event_dir]);
478                     }
479                   else
480                     {
481                       Grob *stem = stems[seg.stem_index_];
482                       Drul_array<Real> beamlet_length =
483                         robust_scm2interval (stem->get_property ("beamlet-default-length"), Interval (1.1, 1.1));
484                       Drul_array<Real> max_proportion =
485                         robust_scm2interval (stem->get_property ("beamlet-max-length-proportion"), Interval (0.75, 0.75));
486                       Real length = beamlet_length[seg.dir_];
487
488                       if (inside_stem)
489                         {
490                           Grob *neighbor_stem = stems[seg.stem_index_ + event_dir];
491                           Real neighbor_stem_x = neighbor_stem->relative_coordinate (commonx, X_AXIS);
492
493                           length = min (length,
494                                         fabs (neighbor_stem_x - seg.stem_x_) * max_proportion[seg.dir_]);
495                         }
496                       current.horizontal_[event_dir] += event_dir * length;
497                     }
498                 }
499               else
500                 // we are examining the edge of a beam segment that is closest
501                 // (ie. touching, unless there is a gap) its stem.
502                 {
503                   current.horizontal_[event_dir] += event_dir * seg.width_/2;
504                   if (seg.gapped_)
505                     {
506                       current.horizontal_[event_dir] -= event_dir * gap_length;
507
508                       if (Stem::is_invisible (seg.stem_))
509                         {
510                           /*
511                             Need to do this in case of whole notes. We don't want the
512                             heads to collide with the beams.
513                            */
514                           extract_grob_set (seg.stem_, "note-heads", heads);
515
516                           for (vsize k = 0; k < heads.size (); k ++)
517                             current.horizontal_[event_dir]
518                               = event_dir * min  (event_dir * current.horizontal_[event_dir],
519                                                   - gap_length/2
520                                                   + event_dir
521                                                     * heads[k]->extent (commonx,
522                                                                         X_AXIS)[-event_dir]);
523                         }
524                     }
525                 }
526
527               if (event_dir == RIGHT)
528                 {
529                   segments.push_back (current);
530                   current = Beam_segment ();
531                 }
532             }
533           while (flip (&event_dir) != LEFT);
534         }
535
536     }
537
538   return segments;
539 }
540
541 MAKE_SCHEME_CALLBACK (Beam, print, 1);
542 SCM
543 Beam::print (SCM grob)
544 {
545   Spanner *me = unsmob_spanner (grob);
546   Grob *commonx = 0;
547   vector<Beam_segment> segments = get_beam_segments (me, &commonx);
548
549   Interval span;
550   if (normal_stem_count (me))
551     {
552       span[LEFT] = first_normal_stem (me)->relative_coordinate (commonx, X_AXIS);
553       span[RIGHT] = last_normal_stem (me)->relative_coordinate (commonx, X_AXIS);
554     }
555   else
556     {
557       extract_grob_set (me, "stems", stems);
558       span[LEFT] = stems[0]->relative_coordinate (commonx, X_AXIS);
559       span[RIGHT] = stems.back ()->relative_coordinate (commonx, X_AXIS);
560     }
561
562   Real blot = me->layout ()->get_dimension (ly_symbol2scm ("blot-diameter"));
563
564   SCM posns = me->get_property ("quantized-positions");
565   Interval pos;
566   if (!is_number_pair (posns))
567     {
568       programming_error ("no beam positions?");
569       pos = Interval (0, 0);
570     }
571   else
572     pos = ly_scm2realdrul (posns);
573
574   scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
575
576   Real dy = pos[RIGHT] - pos[LEFT];
577   Real slope = (dy && span.length ()) ? dy / span.length ()  : 0;
578
579   Real beam_thickness = get_beam_thickness (me);
580   Real beam_dy = get_beam_translation (me);
581
582   Direction feather_dir = to_dir (me->get_property ("grow-direction"));
583
584   Stencil the_beam;
585   for (vsize i = 0; i < segments.size (); i ++)
586     {
587       Real local_slope = slope;
588       if (feather_dir)
589         {
590           local_slope += feather_dir * segments[i].vertical_count_ * beam_dy / span.length ();
591         }
592
593       Stencil b = Lookup::beam (local_slope, segments[i].horizontal_.length (), beam_thickness, blot);
594
595       b.translate_axis (segments[i].horizontal_[LEFT], X_AXIS);
596
597       b.translate_axis (local_slope
598                         * (segments[i].horizontal_[LEFT] - span.linear_combination (feather_dir))
599                         + pos.linear_combination (feather_dir)
600                         + beam_dy * segments[i].vertical_count_, Y_AXIS);
601       the_beam.add_stencil (b);
602     }
603
604 #if (DEBUG_BEAM_SCORING)
605   SCM annotation = me->get_property ("annotation");
606   if (!scm_is_string (annotation))
607     {
608       SCM debug = me->layout ()->lookup_variable (ly_symbol2scm ("debug-beam-scoring"));
609       if (to_boolean (debug))
610         annotation = me->get_property ("quant-score");
611     }
612
613   if (scm_is_string (annotation))
614     {
615       extract_grob_set (me, "stems", stems);
616
617       /*
618         This code prints the demerits for each beam. Perhaps this
619         should be switchable for those who want to twiddle with the
620         parameters.
621       */
622       string str;
623       SCM properties = Font_interface::text_font_alist_chain (me);
624
625       Direction stem_dir = stems.size () ? to_dir (stems[0]->get_property ("direction")) : UP;
626
627       Stencil score = *unsmob_stencil (Text_interface::interpret_markup
628                                     (me->layout ()->self_scm (), properties, annotation));
629
630       if (!score.is_empty ())
631         {
632           score.translate_axis (me->relative_coordinate(commonx, X_AXIS), X_AXIS);
633           the_beam.add_at_edge (Y_AXIS, stem_dir, score, 1.0);
634         }
635     }
636 #endif
637
638   the_beam.translate_axis (-me->relative_coordinate (commonx, X_AXIS), X_AXIS);
639   return the_beam.smobbed_copy ();
640 }
641
642 Direction
643 Beam::get_default_dir (Grob *me)
644 {
645   extract_grob_set (me, "stems", stems);
646
647   Drul_array<Real> extremes (0.0, 0.0);
648   for (iterof (s, stems); s != stems.end (); s++)
649     {
650       Interval positions = Stem::head_positions (*s);
651       Direction d = DOWN;
652       do
653         {
654           if (sign (positions[d]) == d)
655             extremes[d] = d * max (d * positions[d], d * extremes[d]);
656         }
657       while (flip (&d) != DOWN);
658     }
659
660   Drul_array<int> total (0, 0);
661   Drul_array<int> count (0, 0);
662
663   bool force_dir = false;
664   for (vsize i = 0; i < stems.size (); i++)
665     {
666       Grob *s = stems[i];
667       Direction stem_dir = CENTER;
668       SCM stem_dir_scm = s->get_property_data ("direction");
669       if (is_direction (stem_dir_scm))
670         {
671           stem_dir = to_dir (stem_dir_scm);
672           force_dir = true;
673         }
674       else
675         stem_dir = to_dir (s->get_property ("default-direction"));
676
677       if (!stem_dir)
678         stem_dir = to_dir (s->get_property ("neutral-direction"));
679
680       if (stem_dir)
681         {
682           count[stem_dir] ++;
683           total[stem_dir] += max (int (- stem_dir * Stem::head_positions (s) [-stem_dir]), 0);
684         }
685     }
686
687
688   if (!force_dir)
689     {
690       if (abs (extremes[UP]) > -extremes[DOWN])
691         return DOWN;
692       else if (extremes[UP] < -extremes[DOWN])
693         return UP;
694     }
695
696   Direction dir = CENTER;
697   Direction d = CENTER;
698   if ((d = (Direction) sign (count[UP] - count[DOWN])))
699     dir = d;
700   else if (count[UP]
701            && count[DOWN]
702            && (d = (Direction)  sign (total[UP] / count[UP] - total[DOWN]/count[DOWN])))
703     dir = d;
704   else if ((d = (Direction)  sign (total[UP] - total[DOWN])))
705     dir = d;
706   else
707     dir = to_dir (me->get_property ("neutral-direction"));
708
709   return dir;
710 }
711
712 /* Set all stems with non-forced direction to beam direction.
713    Urg: non-forced should become `without/with unforced' direction,
714    once stem gets cleaned-up. */
715 void
716 Beam::set_stem_directions (Grob *me, Direction d)
717 {
718   extract_grob_set (me, "stems", stems);
719
720   for (vsize i = 0; i < stems.size (); i++)
721     {
722       Grob *s = stems[i];
723
724       SCM forcedir = s->get_property_data ("direction");
725       if (!to_dir (forcedir))
726         set_grob_direction (s, d);
727     }
728 }
729
730 /*
731   Only try horizontal beams for knees.  No reliable detection of
732   anything else is possible here, since we don't know funky-beaming
733   settings, or X-distances (slopes!)  People that want sloped
734   knee-beams, should set the directions manually.
735
736
737   TODO:
738
739   this routine should take into account the stemlength scoring
740   of a possible knee/nonknee beam.
741 */
742 void
743 Beam::consider_auto_knees (Grob *me)
744 {
745   SCM scm = me->get_property ("auto-knee-gap");
746   if (!scm_is_number (scm))
747     return;
748
749   Interval_set gaps;
750
751   gaps.set_full ();
752
753   extract_grob_set (me, "normal-stems", stems);
754
755   Grob *common = common_refpoint_of_array (stems, me, Y_AXIS);
756   Real staff_space = Staff_symbol_referencer::staff_space (me);
757
758   vector<Interval> head_extents_array;
759   for (vsize i = 0; i < stems.size (); i++)
760     {
761       Grob *stem = stems[i];
762
763       Interval head_extents = Stem::head_positions (stem);
764       if (!head_extents.is_empty ())
765         {
766           head_extents[LEFT] += -1;
767           head_extents[RIGHT] += 1;
768           head_extents *= staff_space * 0.5;
769
770           /*
771             We could subtract beam Y position, but this routine only
772             sets stem directions, a constant shift does not have an
773             influence.
774           */
775           head_extents += stem->pure_relative_y_coordinate (common, 0, INT_MAX);
776
777           if (to_dir (stem->get_property_data ("direction")))
778             {
779               Direction stemdir = to_dir (stem->get_property ("direction"));
780               head_extents[-stemdir] = -stemdir * infinity_f;
781             }
782         }
783       head_extents_array.push_back (head_extents);
784
785       gaps.remove_interval (head_extents);
786     }
787
788   Interval max_gap;
789   Real max_gap_len = 0.0;
790
791   for (vsize i = gaps.allowed_regions_.size () -1; i != VPOS ;i--)
792     {
793       Interval gap = gaps.allowed_regions_[i];
794
795       /*
796         the outer gaps are not knees.
797       */
798       if (isinf (gap[LEFT]) || isinf (gap[RIGHT]))
799         continue;
800
801       if (gap.length () >= max_gap_len)
802         {
803           max_gap_len = gap.length ();
804           max_gap = gap;
805         }
806     }
807
808   Real beam_translation = get_beam_translation (me);
809   Real beam_thickness = Beam::get_beam_thickness (me);
810   int beam_count = Beam::get_beam_count (me);
811   Real height_of_beams = beam_thickness / 2
812     + (beam_count - 1) * beam_translation;
813   Real threshold = scm_to_double (scm) + height_of_beams;
814
815   if (max_gap_len > threshold)
816     {
817       int j = 0;
818       for (vsize i = 0; i < stems.size (); i++)
819         {
820           Grob *stem = stems[i];
821           Interval head_extents = head_extents_array[j++];
822
823           Direction d = (head_extents.center () < max_gap.center ())
824             ? UP : DOWN;
825
826           stem->set_property ("direction", scm_from_int (d));
827
828           head_extents.intersect (max_gap);
829           assert (head_extents.is_empty () || head_extents.length () < 1e-6);
830         }
831     }
832 }
833
834 /* Set stem's shorten property if unset.
835
836 TODO:
837 take some y-position (chord/beam/nearest?) into account
838 scmify forced-fraction
839
840 This is done in beam because the shorten has to be uniform over the
841 entire beam.
842 */
843
844
845
846 void
847 set_minimum_dy (Grob *me, Real *dy)
848 {
849   if (*dy)
850     {
851       /*
852         If dy is smaller than the smallest quant, we
853         get absurd direction-sign penalties.
854       */
855
856       Real ss = Staff_symbol_referencer::staff_space (me);
857       Real beam_thickness = Beam::get_beam_thickness (me) / ss;
858       Real slt = Staff_symbol_referencer::line_thickness (me) / ss;
859       Real sit = (beam_thickness - slt) / 2;
860       Real inter = 0.5;
861       Real hang = 1.0 - (beam_thickness - slt) / 2;
862
863       *dy = sign (*dy) * max (fabs (*dy),
864                               min (min (sit, inter), hang));
865     }
866 }
867
868
869
870 MAKE_SCHEME_CALLBACK (Beam, calc_stem_shorten, 1)
871 SCM
872 Beam::calc_stem_shorten (SCM smob)
873 {
874   Grob *me = unsmob_grob (smob);
875
876   /*
877     shortening looks silly for x staff beams
878   */
879   if (is_knee (me))
880     return scm_from_int (0);
881
882   Real forced_fraction = 1.0 * forced_stem_count (me)
883     / normal_stem_count (me);
884
885   int beam_count = get_beam_count (me);
886
887   SCM shorten_list = me->get_property ("beamed-stem-shorten");
888   if (shorten_list == SCM_EOL)
889     return scm_from_int (0);
890
891   Real staff_space = Staff_symbol_referencer::staff_space (me);
892
893   SCM shorten_elt
894     = robust_list_ref (beam_count -1, shorten_list);
895   Real shorten = scm_to_double (shorten_elt) * staff_space;
896
897   shorten *= forced_fraction;
898
899
900   if (shorten)
901     return scm_from_double (shorten);
902
903   return scm_from_double (0.0);
904 }
905
906
907 Interval
908 Beam::no_visible_stem_positions (Grob *me, Interval default_value)
909 {
910   extract_grob_set (me, "stems", stems);
911   if (stems.empty ())
912     return default_value;
913
914   Interval head_positions;
915   Slice multiplicity;
916   for (vsize i = 0; i < stems.size(); i++)
917     {
918       head_positions.unite (Stem::head_positions (stems[i]));
919       multiplicity.unite (Stem::beam_multiplicity (stems[i]));
920     }
921
922   Direction dir = get_grob_direction (me);
923   Real y = head_positions[dir]
924     * 0.5 * Staff_symbol_referencer::staff_space (me)
925     + dir * get_beam_translation (me) * (multiplicity.length () + 1);
926
927   y /= Staff_symbol_referencer::staff_space (me);
928   return Interval (y,y);
929 }
930
931
932 /*
933   Compute a first approximation to the beam slope.
934 */
935 MAKE_SCHEME_CALLBACK (Beam, calc_least_squares_positions, 2);
936 SCM
937 Beam::calc_least_squares_positions (SCM smob, SCM /* posns */)
938 {
939   Grob *me = unsmob_grob (smob);
940
941   int count = normal_stem_count (me);
942   Interval pos (0,0);
943   if (count < 1)
944     return ly_interval2scm (no_visible_stem_positions (me, pos));
945
946   vector<Real> x_posns;
947   extract_grob_set (me, "normal-stems", stems);
948   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
949   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
950
951   Real my_y = me->relative_coordinate (commony, Y_AXIS);
952
953   Grob *fvs = first_normal_stem (me);
954   Grob *lvs = last_normal_stem (me);
955
956   Interval ideal (Stem::get_stem_info (fvs).ideal_y_
957                   + fvs->relative_coordinate (commony, Y_AXIS) - my_y,
958                   Stem::get_stem_info (lvs).ideal_y_
959                   + lvs->relative_coordinate (commony, Y_AXIS) - my_y);
960
961   Real x0 = first_normal_stem (me)->relative_coordinate (commonx, X_AXIS);
962   for (vsize i = 0; i < stems.size (); i++)
963     {
964       Grob *s = stems[i];
965
966       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
967       x_posns.push_back (x);
968     }
969   Real dx = last_normal_stem (me)->relative_coordinate (commonx, X_AXIS) - x0;
970
971   Real y = 0;
972   Real slope = 0;
973   Real dy = 0;
974   Real ldy = 0.0;
975   if (!ideal.delta ())
976     {
977       Interval chord (Stem::chord_start_y (stems[0]),
978                       Stem::chord_start_y (stems.back ()));
979
980       /* Simple beams (2 stems) on middle line should be allowed to be
981          slightly sloped.
982
983          However, if both stems reach middle line,
984          ideal[LEFT] == ideal[RIGHT] and ideal.delta () == 0.
985
986          For that case, we apply artificial slope */
987       if (!ideal[LEFT] && chord.delta () && count == 2)
988         {
989           /* FIXME. -> UP */
990           Direction d = (Direction) (sign (chord.delta ()) * UP);
991           pos[d] = get_beam_thickness (me) / 2;
992           pos[-d] = -pos[d];
993         }
994       else
995         pos = ideal;
996
997       /*
998         For broken beams this doesn't work well. In this case, the
999         slope esp. of the first part of a broken beam should predict
1000         where the second part goes.
1001       */
1002       ldy = pos[RIGHT] - pos[LEFT];
1003     }
1004   else
1005     {
1006       vector<Offset> ideals;
1007       for (vsize i = 0; i < stems.size (); i++)
1008         {
1009           Grob *s = stems[i];
1010           ideals.push_back (Offset (x_posns[i],
1011                                Stem::get_stem_info (s).ideal_y_
1012                                + s->relative_coordinate (commony, Y_AXIS)
1013                                - my_y));
1014         }
1015
1016       minimise_least_squares (&slope, &y, ideals);
1017
1018       dy = slope * dx;
1019
1020       set_minimum_dy (me, &dy);
1021
1022       ldy = dy;
1023       pos = Interval (y, (y + dy));
1024     }
1025
1026   /*
1027     "position" is relative to the staff.
1028   */
1029   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1030
1031   me->set_property ("least-squares-dy",  scm_from_double (ldy));
1032   return ly_interval2scm (pos);
1033 }
1034
1035 /*
1036   We can't combine with previous function, since check concave and
1037   slope damping comes first.
1038
1039   TODO: we should use the concaveness to control the amount of damping
1040   applied.
1041 */
1042 MAKE_SCHEME_CALLBACK (Beam, shift_region_to_valid, 2);
1043 SCM
1044 Beam::shift_region_to_valid (SCM grob, SCM posns)
1045 {
1046   Grob *me = unsmob_grob (grob);
1047   /*
1048     Code dup.
1049   */
1050   vector<Real> x_posns;
1051   extract_grob_set (me, "stems", stems);
1052   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
1053   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
1054
1055   Grob *fvs = first_normal_stem (me);
1056
1057   if (!fvs)
1058     return posns;
1059
1060   Real x0 = fvs->relative_coordinate (commonx, X_AXIS);
1061   for (vsize i = 0; i < stems.size (); i++)
1062     {
1063       Grob *s = stems[i];
1064
1065       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
1066       x_posns.push_back (x);
1067     }
1068
1069   Grob *lvs = last_normal_stem (me);
1070   if (!lvs)
1071     return posns;
1072
1073   Real dx = lvs->relative_coordinate (commonx, X_AXIS) - x0;
1074
1075   Drul_array<Real> pos = ly_scm2interval (posns);
1076
1077   scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
1078
1079   Real dy = pos[RIGHT] - pos[LEFT];
1080   Real y = pos[LEFT];
1081   Real slope = dx ? (dy / dx) : 0.0;
1082
1083   /*
1084     Shift the positions so that we have a chance of finding good
1085     quants (i.e. no short stem failures.)
1086   */
1087   Interval feasible_left_point;
1088   feasible_left_point.set_full ();
1089   for (vsize i = 0; i < stems.size (); i++)
1090     {
1091       Grob *s = stems[i];
1092       if (Stem::is_invisible (s))
1093         continue;
1094
1095       Direction d = get_grob_direction (s);
1096
1097       Real left_y
1098         = Stem::get_stem_info (s).shortest_y_
1099         - slope * x_posns [i];
1100
1101       /*
1102         left_y is now relative to the stem S. We want relative to
1103         ourselves, so translate:
1104       */
1105       left_y
1106         += + s->relative_coordinate (commony, Y_AXIS)
1107         - me->relative_coordinate (commony, Y_AXIS);
1108
1109       Interval flp;
1110       flp.set_full ();
1111       flp[-d] = left_y;
1112
1113       feasible_left_point.intersect (flp);
1114     }
1115
1116   if (feasible_left_point.is_empty ())
1117     warning (_ ("no viable initial configuration found: may not find good beam slope"));
1118   else if (!feasible_left_point.contains (y))
1119     {
1120       const int REGION_SIZE = 2; // UGH UGH
1121       if (isinf (feasible_left_point[DOWN]))
1122         y = feasible_left_point[UP] - REGION_SIZE;
1123       else if (isinf (feasible_left_point[UP]))
1124         y = feasible_left_point[DOWN]+ REGION_SIZE;
1125       else
1126         y = feasible_left_point.center ();
1127     }
1128
1129   pos = Drul_array<Real> (y, (y + dy));
1130   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1131
1132   return ly_interval2scm (pos);
1133 }
1134
1135 /* This neat trick is by Werner Lemberg,
1136    damped = tanh (slope)
1137    corresponds with some tables in [Wanske] CHECKME */
1138 MAKE_SCHEME_CALLBACK (Beam, slope_damping, 2);
1139 SCM
1140 Beam::slope_damping (SCM smob, SCM posns)
1141 {
1142   Grob *me = unsmob_grob (smob);
1143   Drul_array<Real> pos = ly_scm2interval (posns);
1144
1145   if (normal_stem_count (me) <= 1)
1146     return posns;
1147
1148   SCM s = me->get_property ("damping");
1149   Real damping = scm_to_double (s);
1150   Real concaveness = robust_scm2double (me->get_property ("concaveness"), 0.0);
1151   if (concaveness >= 10000)
1152     {
1153       pos[LEFT] = pos[RIGHT];
1154       me->set_property ("least-squares-dy", scm_from_double (0));
1155       damping = 0;
1156     }
1157
1158   if (damping)
1159     {
1160       scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
1161
1162       Real dy = pos[RIGHT] - pos[LEFT];
1163
1164       Grob *fvs = first_normal_stem (me);
1165       Grob *lvs = last_normal_stem (me);
1166
1167       Grob *commonx = fvs->common_refpoint (lvs, X_AXIS);
1168
1169       Real dx = last_normal_stem (me)->relative_coordinate (commonx, X_AXIS)
1170         - first_normal_stem (me)->relative_coordinate (commonx, X_AXIS);
1171
1172       Real slope = dy && dx ? dy / dx : 0;
1173
1174       slope = 0.6 * tanh (slope) / (damping + concaveness);
1175
1176       Real damped_dy = slope * dx;
1177
1178       set_minimum_dy (me, &damped_dy);
1179
1180       pos[LEFT] += (dy - damped_dy) / 2;
1181       pos[RIGHT] -= (dy - damped_dy) / 2;
1182
1183       scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1184     }
1185
1186   return ly_interval2scm (pos);
1187 }
1188
1189
1190 MAKE_SCHEME_CALLBACK (Beam, quanting, 2);
1191 SCM
1192 Beam::quanting (SCM smob, SCM posns)
1193 {
1194   Grob *me = unsmob_grob (smob);
1195   Drul_array<Real> ys(0, 0);
1196   ys = robust_scm2drul (posns, ys);
1197   Beam_scoring_problem problem (me, ys);
1198
1199   ys = problem.solve ();
1200   return ly_interval2scm (ys);
1201 }
1202
1203
1204 /*
1205   Report slice containing the numbers that are both in (car BEAMING)
1206   and (cdr BEAMING)
1207 */
1208 Slice
1209 where_are_the_whole_beams (SCM beaming)
1210 {
1211   Slice l;
1212
1213   for (SCM s = scm_car (beaming); scm_is_pair (s); s = scm_cdr (s))
1214     {
1215       if (scm_c_memq (scm_car (s), scm_cdr (beaming)) != SCM_BOOL_F)
1216
1217         l.add_point (scm_to_int (scm_car (s)));
1218     }
1219
1220   return l;
1221 }
1222
1223 /* Return the Y position of the stem-end, given the Y-left, Y-right
1224    in POS for stem S.  This Y position is relative to S. */
1225 Real
1226 Beam::calc_stem_y (Grob *me, Grob *stem, Grob **common,
1227                    Real xl, Real xr, Direction feather_dir,
1228                    Drul_array<Real> pos, bool french)
1229 {
1230   Real beam_translation = get_beam_translation (me);
1231   Direction stem_dir = get_grob_direction (stem);
1232
1233   Real dx = xr - xl;
1234   Real relx = dx ? (stem->relative_coordinate (common[X_AXIS], X_AXIS) - xl)/dx : 0;
1235   Real xdir = 2*relx-1;
1236
1237   Real stem_y = linear_combination(pos, xdir);
1238
1239   SCM beaming = stem->get_property ("beaming");
1240
1241   Slice beam_slice (french
1242                     ? where_are_the_whole_beams (beaming)
1243                     : Stem::beam_multiplicity (stem));
1244   if (beam_slice.is_empty ())
1245     beam_slice = Slice (0,0);
1246   Interval beam_multiplicity(beam_slice[LEFT],
1247                              beam_slice[RIGHT]);
1248
1249   /*
1250     feather dir = 1 , relx 0->1 : factor 0 -> 1
1251     feather dir = 0 , relx 0->1 : factor 1 -> 1
1252     feather dir = -1, relx 0->1 : factor 1 -> 0
1253    */
1254   Real feather_factor = 1;
1255   if (feather_dir > 0)
1256     feather_factor = relx;
1257   else if (feather_dir < 0)
1258     feather_factor = 1 - relx;
1259
1260   stem_y += feather_factor * beam_translation
1261     * beam_multiplicity[Direction(((french) ? DOWN : UP)*stem_dir)];
1262   Real id = me->relative_coordinate (common[Y_AXIS], Y_AXIS)
1263     - stem->relative_coordinate (common[Y_AXIS], Y_AXIS);
1264
1265   return stem_y + id;
1266 }
1267
1268 /*
1269   Hmm.  At this time, beam position and slope are determined.  Maybe,
1270   stem directions and length should set to relative to the chord's
1271   position of the beam.  */
1272 MAKE_SCHEME_CALLBACK (Beam, set_stem_lengths, 1);
1273 SCM
1274 Beam::set_stem_lengths (SCM smob)
1275 {
1276   Grob *me = unsmob_grob (smob);
1277
1278   /* trigger callbacks. */
1279   (void) me->get_property ("direction");
1280   (void) me->get_property ("beaming");
1281
1282   SCM posns = me->get_property ("positions");
1283
1284   extract_grob_set (me, "stems", stems);
1285   if (!stems.size ())
1286     return posns;
1287
1288   Grob *common[2];
1289   for (int a = 2; a--;)
1290     common[a] = common_refpoint_of_array (stems, me, Axis (a));
1291
1292   Drul_array<Real> pos = ly_scm2realdrul (posns);
1293   Real staff_space = Staff_symbol_referencer::staff_space (me);
1294   scale_drul (&pos, staff_space);
1295
1296   bool gap = false;
1297   Real thick = 0.0;
1298   if (robust_scm2int (me->get_property ("gap-count"), 0))
1299     {
1300       gap = true;
1301       thick = get_beam_thickness (me);
1302     }
1303
1304   Grob *fvs = first_normal_stem (me);
1305   Grob *lvs = last_normal_stem (me);
1306
1307   Real xl = fvs ? fvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1308   Real xr = lvs ? lvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1309   Direction feather_dir = to_dir (me->get_property ("grow-direction"));
1310
1311   for (vsize i = 0; i < stems.size (); i++)
1312     {
1313       Grob *s = stems[i];
1314
1315       bool french = to_boolean (s->get_property ("french-beaming"));
1316       Real stem_y = calc_stem_y (me, s, common,
1317                                  xl, xr, feather_dir,
1318                                  pos, french && s != lvs && s!= fvs);
1319
1320       /*
1321         Make the stems go up to the end of the beam. This doesn't matter
1322         for normal beams, but for tremolo beams it looks silly otherwise.
1323       */
1324       if (gap
1325           && !Stem::is_invisible (s))
1326         stem_y += thick * 0.5 * get_grob_direction (s);
1327
1328       /*
1329         Do set_stemend for invisible stems too, so tuplet brackets
1330         have a reference point for sloping
1331        */
1332       Stem::set_stemend (s, 2 * stem_y / staff_space);
1333     }
1334
1335   return posns;
1336 }
1337
1338 void
1339 Beam::set_beaming (Grob *me, Beaming_pattern const *beaming)
1340 {
1341   extract_grob_set (me, "stems", stems);
1342
1343   Direction d = LEFT;
1344   for (vsize i = 0; i < stems.size (); i++)
1345     {
1346       /*
1347         Don't overwrite user settings.
1348       */
1349       do
1350         {
1351           Grob *stem = stems[i];
1352           SCM beaming_prop = stem->get_property ("beaming");
1353           if (beaming_prop == SCM_EOL
1354               || index_get_cell (beaming_prop, d) == SCM_EOL)
1355             {
1356               int count = beaming->beamlet_count (i, d);
1357               if (i > 0
1358                   && i + 1 < stems.size ()
1359                   && Stem::is_invisible (stem))
1360                 count = min (count, beaming->beamlet_count (i,-d));
1361
1362               if ( ((i == 0 && d == LEFT)
1363                     || (i == stems.size ()-1 && d == RIGHT))
1364                    && stems.size () > 1
1365                    && to_boolean (me->get_property ("clip-edges")))
1366                 count = 0;
1367
1368               Stem::set_beaming (stem, count, d);
1369             }
1370         }
1371       while (flip (&d) != LEFT);
1372     }
1373 }
1374
1375 int
1376 Beam::forced_stem_count (Grob *me)
1377 {
1378   extract_grob_set (me, "normal-stems", stems);
1379
1380   int f = 0;
1381   for (vsize i = 0; i < stems.size (); i++)
1382     {
1383       Grob *s = stems[i];
1384
1385       /* I can imagine counting those boundaries as a half forced stem,
1386          but let's count them full for now. */
1387       Direction defdir = to_dir (s->get_property ("default-direction"));
1388
1389       if (abs (Stem::chord_start_y (s)) > 0.1
1390           && defdir
1391           && get_grob_direction (s) != defdir)
1392         f++;
1393     }
1394   return f;
1395 }
1396
1397 int
1398 Beam::normal_stem_count (Grob *me)
1399 {
1400   extract_grob_set (me, "normal-stems", stems);
1401   return stems.size ();
1402 }
1403
1404 Grob *
1405 Beam::first_normal_stem (Grob *me)
1406 {
1407   extract_grob_set (me, "normal-stems", stems);
1408   return stems.size () ? stems[0] : 0;
1409 }
1410
1411 Grob *
1412 Beam::last_normal_stem (Grob *me)
1413 {
1414   extract_grob_set (me, "normal-stems", stems);
1415   return stems.size () ? stems.back () : 0;
1416 }
1417
1418 /*
1419   [TODO]
1420
1421   handle rest under beam (do_post: beams are calculated now)
1422   what about combination of collisions and rest under beam.
1423
1424   Should lookup
1425
1426   rest -> stem -> beam -> interpolate_y_position ()
1427 */
1428 MAKE_SCHEME_CALLBACK_WITH_OPTARGS (Beam, rest_collision_callback, 2, 1, "");
1429 SCM
1430 Beam::rest_collision_callback (SCM smob, SCM prev_offset)
1431 {
1432   Grob *rest = unsmob_grob (smob);
1433   if (scm_is_number (rest->get_property ("staff-position")))
1434     return scm_from_int (0);
1435
1436   Real offset = robust_scm2double (prev_offset, 0.0);
1437
1438   Grob *st = unsmob_grob (rest->get_object ("stem"));
1439   Grob *stem = st;
1440   if (!stem)
1441     return scm_from_double (0.0);
1442   Grob *beam = unsmob_grob (stem->get_object ("beam"));
1443   if (!beam
1444       || !Beam::has_interface (beam)
1445       || !Beam::normal_stem_count (beam))
1446     return scm_from_double (0.0);
1447
1448   Drul_array<Real> pos (robust_scm2drul (beam->get_property ("positions"),
1449                                          Drul_array<Real> (0,0)));
1450
1451   Real staff_space = Staff_symbol_referencer::staff_space (rest);
1452
1453   scale_drul (&pos, staff_space);
1454
1455   Real dy = pos[RIGHT] - pos[LEFT];
1456
1457   Drul_array<Grob*> visible_stems (first_normal_stem (beam),
1458                                    last_normal_stem (beam));
1459   extract_grob_set (beam, "stems", stems);
1460
1461   Grob *common = common_refpoint_of_array (stems, beam, X_AXIS);
1462
1463   Real x0 = visible_stems[LEFT]->relative_coordinate (common, X_AXIS);
1464   Real dx = visible_stems[RIGHT]->relative_coordinate (common, X_AXIS) - x0;
1465   Real slope = dy && dx ? dy / dx : 0;
1466
1467   Direction d = get_grob_direction (stem);
1468   Real stem_y = pos[LEFT]
1469     + (stem->relative_coordinate (common, X_AXIS) - x0) * slope;
1470
1471   Real beam_translation = get_beam_translation (beam);
1472   Real beam_thickness = Beam::get_beam_thickness (beam);
1473
1474   /*
1475     TODO: this is not strictly correct for 16th knee beams.
1476   */
1477   int beam_count
1478     = Stem::beam_multiplicity (stem).length () + 1;
1479
1480   Real height_of_my_beams = beam_thickness / 2
1481     + (beam_count - 1) * beam_translation;
1482   Real beam_y = stem_y - d * height_of_my_beams;
1483
1484   Grob *common_y = rest->common_refpoint (beam, Y_AXIS);
1485
1486   Interval rest_extent = rest->extent (rest, Y_AXIS);
1487   rest_extent.translate (offset + rest->get_parent (Y_AXIS)->relative_coordinate (common_y, Y_AXIS));
1488
1489   Real rest_dim = rest_extent[d];
1490   Real minimum_distance
1491     = staff_space * (robust_scm2double (stem->get_property ("stemlet-length"), 0.0)
1492                      + robust_scm2double (rest->get_property ("minimum-distance"), 0.0));
1493
1494   Real shift = d * min (d * (beam_y - d * minimum_distance - rest_dim), 0.0);
1495
1496   shift /= staff_space;
1497   Real rad = Staff_symbol_referencer::line_count (rest) * staff_space / 2;
1498
1499   /* Always move discretely by half spaces */
1500   shift = ceil (fabs (shift * 2.0)) / 2.0 * sign (shift);
1501
1502   /* Inside staff, move by whole spaces*/
1503   if ((rest_extent[d] + staff_space * shift) * d
1504       < rad
1505       || (rest_extent[-d] + staff_space * shift) * -d
1506       < rad)
1507     shift = ceil (fabs (shift)) * sign (shift);
1508
1509   return scm_from_double (offset + staff_space * shift);
1510 }
1511
1512 bool
1513 Beam::is_knee (Grob *me)
1514 {
1515   SCM k = me->get_property ("knee");
1516   if (scm_is_bool (k))
1517     return ly_scm2bool (k);
1518
1519   bool knee = false;
1520   int d = 0;
1521   extract_grob_set (me, "stems", stems);
1522   for (vsize i = stems.size (); i--;)
1523     {
1524       Direction dir = get_grob_direction (stems[i]);
1525       if (d && d != dir)
1526         {
1527           knee = true;
1528           break;
1529         }
1530       d = dir;
1531     }
1532
1533   me->set_property ("knee", ly_bool2scm (knee));
1534
1535   return knee;
1536 }
1537
1538 bool
1539 Beam::is_cross_staff (Grob *me)
1540 {
1541   extract_grob_set (me, "stems", stems);
1542   Grob *staff_symbol = Staff_symbol_referencer::get_staff_symbol (me);
1543   for (vsize i = 0; i < stems.size (); i++)
1544     if (Staff_symbol_referencer::get_staff_symbol (stems[i]) != staff_symbol)
1545       return true;
1546   return false;
1547 }
1548
1549 MAKE_SCHEME_CALLBACK (Beam, calc_cross_staff, 1)
1550 SCM
1551 Beam::calc_cross_staff (SCM smob)
1552 {
1553   return scm_from_bool (is_cross_staff (unsmob_grob (smob)));
1554 }
1555
1556 int
1557 Beam::get_direction_beam_count (Grob *me, Direction d)
1558 {
1559   extract_grob_set (me, "stems", stems);
1560   int bc = 0;
1561
1562   for (vsize i = stems.size (); i--;)
1563     {
1564       /*
1565         Should we take invisible stems into account?
1566       */
1567       if (get_grob_direction (stems[i]) == d)
1568         bc = max (bc, (Stem::beam_multiplicity (stems[i]).length () + 1));
1569     }
1570
1571   return bc;
1572 }
1573
1574 ADD_INTERFACE (Beam,
1575                "A beam.\n"
1576                "\n"
1577                "The @code{beam-thickness} property is the weight of beams,"
1578                " measured in staffspace.  The @code{direction} property is"
1579                " not user-serviceable.  Use the @code{direction} property"
1580                " of @code{Stem} instead.\n"
1581                "\n"
1582                "The following properties may be set in the @code{details}"
1583                " list.\n"
1584                "\n"
1585                "@table @code\n"
1586                "@item stem-length-demerit-factor\n"
1587                "Demerit factor used for inappropriate stem lengths.\n"
1588                "@item secondary-beam-demerit\n"
1589                "Demerit used in quanting calculations for multiple"
1590                " beams.\n"
1591                "@item region-size\n"
1592                "Size of region for checking quant scores.\n"
1593                "@item beam-eps\n"
1594                "Epsilon for beam quant code to check for presence"
1595                " in gap.\n"
1596                "@item stem-length-limit-penalty\n"
1597                "Penalty for differences in stem lengths on a beam.\n"
1598                "@item damping-direction-penalty\n"
1599                "Demerit penalty applied when beam direction is different"
1600                " from damping direction.\n"
1601                "@item hint-direction-penalty\n"
1602                "Demerit penalty applied when beam direction is different"
1603                " from damping direction, but damping slope is"
1604                " <= @code{round-to-zero-slope}.\n"
1605                "@item musical-direction-factor\n"
1606                "Demerit scaling factor for difference between"
1607                " beam slope and music slope.\n"
1608                "@item ideal-slope-factor\n"
1609                "Demerit scaling factor for difference between"
1610                " beam slope and damping slope.\n"
1611                "@item round-to-zero-slope\n"
1612                "Damping slope which is considered zero for purposes of"
1613                " calculating direction penalties.\n"
1614                "@end table\n",
1615
1616                /* properties */
1617                "annotation "
1618                "auto-knee-gap "
1619                "beamed-stem-shorten "
1620                "beaming "
1621                "beam-thickness "
1622                "break-overshoot "
1623                "clip-edges "
1624                "concaveness "
1625                "damping "
1626                "details "
1627                "direction "
1628                "gap "
1629                "gap-count "
1630                "grow-direction "
1631                "inspect-quants "
1632                "knee "
1633                "length-fraction "
1634                "least-squares-dy "
1635                "neutral-direction "
1636                "normal-stems "
1637                "positions "
1638                "quant-score "
1639                "quantized-positions "
1640                "shorten "
1641                "stems "
1642                );