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