]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
Use smaller font for beam debug output.
[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       properties = scm_cons(scm_acons (ly_symbol2scm ("font-size"), scm_from_int (-3), SCM_EOL),
626                             properties);
627       
628       Direction stem_dir = stems.size () ? to_dir (stems[0]->get_property ("direction")) : UP;
629
630       Stencil score = *unsmob_stencil (Text_interface::interpret_markup
631                                        (me->layout ()->self_scm (), properties, annotation));
632
633       if (!score.is_empty ())
634         {
635           score.translate_axis (me->relative_coordinate(commonx, X_AXIS), X_AXIS);
636           the_beam.add_at_edge (Y_AXIS, stem_dir, score, 1.0);
637         }
638     }
639 #endif
640
641   the_beam.translate_axis (-me->relative_coordinate (commonx, X_AXIS), X_AXIS);
642   return the_beam.smobbed_copy ();
643 }
644
645 Direction
646 Beam::get_default_dir (Grob *me)
647 {
648   extract_grob_set (me, "stems", stems);
649
650   Drul_array<Real> extremes (0.0, 0.0);
651   for (iterof (s, stems); s != stems.end (); s++)
652     {
653       Interval positions = Stem::head_positions (*s);
654       Direction d = DOWN;
655       do
656         {
657           if (sign (positions[d]) == d)
658             extremes[d] = d * max (d * positions[d], d * extremes[d]);
659         }
660       while (flip (&d) != DOWN);
661     }
662
663   Drul_array<int> total (0, 0);
664   Drul_array<int> count (0, 0);
665
666   bool force_dir = false;
667   for (vsize i = 0; i < stems.size (); i++)
668     {
669       Grob *s = stems[i];
670       Direction stem_dir = CENTER;
671       SCM stem_dir_scm = s->get_property_data ("direction");
672       if (is_direction (stem_dir_scm))
673         {
674           stem_dir = to_dir (stem_dir_scm);
675           force_dir = true;
676         }
677       else
678         stem_dir = to_dir (s->get_property ("default-direction"));
679
680       if (!stem_dir)
681         stem_dir = to_dir (s->get_property ("neutral-direction"));
682
683       if (stem_dir)
684         {
685           count[stem_dir] ++;
686           total[stem_dir] += max (int (- stem_dir * Stem::head_positions (s) [-stem_dir]), 0);
687         }
688     }
689
690
691   if (!force_dir)
692     {
693       if (abs (extremes[UP]) > -extremes[DOWN])
694         return DOWN;
695       else if (extremes[UP] < -extremes[DOWN])
696         return UP;
697     }
698
699   Direction dir = CENTER;
700   Direction d = CENTER;
701   if ((d = (Direction) sign (count[UP] - count[DOWN])))
702     dir = d;
703   else if (count[UP]
704            && count[DOWN]
705            && (d = (Direction)  sign (total[UP] / count[UP] - total[DOWN]/count[DOWN])))
706     dir = d;
707   else if ((d = (Direction)  sign (total[UP] - total[DOWN])))
708     dir = d;
709   else
710     dir = to_dir (me->get_property ("neutral-direction"));
711
712   return dir;
713 }
714
715 /* Set all stems with non-forced direction to beam direction.
716    Urg: non-forced should become `without/with unforced' direction,
717    once stem gets cleaned-up. */
718 void
719 Beam::set_stem_directions (Grob *me, Direction d)
720 {
721   extract_grob_set (me, "stems", stems);
722
723   for (vsize i = 0; i < stems.size (); i++)
724     {
725       Grob *s = stems[i];
726
727       SCM forcedir = s->get_property_data ("direction");
728       if (!to_dir (forcedir))
729         set_grob_direction (s, d);
730     }
731 }
732
733 /*
734   Only try horizontal beams for knees.  No reliable detection of
735   anything else is possible here, since we don't know funky-beaming
736   settings, or X-distances (slopes!)  People that want sloped
737   knee-beams, should set the directions manually.
738
739
740   TODO:
741
742   this routine should take into account the stemlength scoring
743   of a possible knee/nonknee beam.
744 */
745 void
746 Beam::consider_auto_knees (Grob *me)
747 {
748   SCM scm = me->get_property ("auto-knee-gap");
749   if (!scm_is_number (scm))
750     return;
751
752   Interval_set gaps;
753
754   gaps.set_full ();
755
756   extract_grob_set (me, "normal-stems", stems);
757
758   Grob *common = common_refpoint_of_array (stems, me, Y_AXIS);
759   Real staff_space = Staff_symbol_referencer::staff_space (me);
760
761   vector<Interval> head_extents_array;
762   for (vsize i = 0; i < stems.size (); i++)
763     {
764       Grob *stem = stems[i];
765
766       Interval head_extents = Stem::head_positions (stem);
767       if (!head_extents.is_empty ())
768         {
769           head_extents[LEFT] += -1;
770           head_extents[RIGHT] += 1;
771           head_extents *= staff_space * 0.5;
772
773           /*
774             We could subtract beam Y position, but this routine only
775             sets stem directions, a constant shift does not have an
776             influence.
777           */
778           head_extents += stem->pure_relative_y_coordinate (common, 0, INT_MAX);
779
780           if (to_dir (stem->get_property_data ("direction")))
781             {
782               Direction stemdir = to_dir (stem->get_property ("direction"));
783               head_extents[-stemdir] = -stemdir * infinity_f;
784             }
785         }
786       head_extents_array.push_back (head_extents);
787
788       gaps.remove_interval (head_extents);
789     }
790
791   Interval max_gap;
792   Real max_gap_len = 0.0;
793
794   for (vsize i = gaps.allowed_regions_.size () -1; i != VPOS ;i--)
795     {
796       Interval gap = gaps.allowed_regions_[i];
797
798       /*
799         the outer gaps are not knees.
800       */
801       if (isinf (gap[LEFT]) || isinf (gap[RIGHT]))
802         continue;
803
804       if (gap.length () >= max_gap_len)
805         {
806           max_gap_len = gap.length ();
807           max_gap = gap;
808         }
809     }
810
811   Real beam_translation = get_beam_translation (me);
812   Real beam_thickness = Beam::get_beam_thickness (me);
813   int beam_count = Beam::get_beam_count (me);
814   Real height_of_beams = beam_thickness / 2
815     + (beam_count - 1) * beam_translation;
816   Real threshold = scm_to_double (scm) + height_of_beams;
817
818   if (max_gap_len > threshold)
819     {
820       int j = 0;
821       for (vsize i = 0; i < stems.size (); i++)
822         {
823           Grob *stem = stems[i];
824           Interval head_extents = head_extents_array[j++];
825
826           Direction d = (head_extents.center () < max_gap.center ())
827             ? UP : DOWN;
828
829           stem->set_property ("direction", scm_from_int (d));
830
831           head_extents.intersect (max_gap);
832           assert (head_extents.is_empty () || head_extents.length () < 1e-6);
833         }
834     }
835 }
836
837 /* Set stem's shorten property if unset.
838
839 TODO:
840 take some y-position (chord/beam/nearest?) into account
841 scmify forced-fraction
842
843 This is done in beam because the shorten has to be uniform over the
844 entire beam.
845 */
846
847
848
849 void
850 set_minimum_dy (Grob *me, Real *dy)
851 {
852   if (*dy)
853     {
854       /*
855         If dy is smaller than the smallest quant, we
856         get absurd direction-sign penalties.
857       */
858
859       Real ss = Staff_symbol_referencer::staff_space (me);
860       Real beam_thickness = Beam::get_beam_thickness (me) / ss;
861       Real slt = Staff_symbol_referencer::line_thickness (me) / ss;
862       Real sit = (beam_thickness - slt) / 2;
863       Real inter = 0.5;
864       Real hang = 1.0 - (beam_thickness - slt) / 2;
865
866       *dy = sign (*dy) * max (fabs (*dy),
867                               min (min (sit, inter), hang));
868     }
869 }
870
871
872
873 MAKE_SCHEME_CALLBACK (Beam, calc_stem_shorten, 1)
874 SCM
875 Beam::calc_stem_shorten (SCM smob)
876 {
877   Grob *me = unsmob_grob (smob);
878
879   /*
880     shortening looks silly for x staff beams
881   */
882   if (is_knee (me))
883     return scm_from_int (0);
884
885   Real forced_fraction = 1.0 * forced_stem_count (me)
886     / normal_stem_count (me);
887
888   int beam_count = get_beam_count (me);
889
890   SCM shorten_list = me->get_property ("beamed-stem-shorten");
891   if (shorten_list == SCM_EOL)
892     return scm_from_int (0);
893
894   Real staff_space = Staff_symbol_referencer::staff_space (me);
895
896   SCM shorten_elt
897     = robust_list_ref (beam_count -1, shorten_list);
898   Real shorten = scm_to_double (shorten_elt) * staff_space;
899
900   shorten *= forced_fraction;
901
902
903   if (shorten)
904     return scm_from_double (shorten);
905
906   return scm_from_double (0.0);
907 }
908
909
910 Interval
911 Beam::no_visible_stem_positions (Grob *me, Interval default_value)
912 {
913   extract_grob_set (me, "stems", stems);
914   if (stems.empty ())
915     return default_value;
916
917   Interval head_positions;
918   Slice multiplicity;
919   for (vsize i = 0; i < stems.size(); i++)
920     {
921       head_positions.unite (Stem::head_positions (stems[i]));
922       multiplicity.unite (Stem::beam_multiplicity (stems[i]));
923     }
924
925   Direction dir = get_grob_direction (me);
926   Real y = head_positions[dir]
927     * 0.5 * Staff_symbol_referencer::staff_space (me)
928     + dir * get_beam_translation (me) * (multiplicity.length () + 1);
929
930   y /= Staff_symbol_referencer::staff_space (me);
931   return Interval (y,y);
932 }
933
934
935 /*
936   Compute a first approximation to the beam slope.
937 */
938 MAKE_SCHEME_CALLBACK (Beam, calc_least_squares_positions, 2);
939 SCM
940 Beam::calc_least_squares_positions (SCM smob, SCM /* posns */)
941 {
942   Grob *me = unsmob_grob (smob);
943
944   int count = normal_stem_count (me);
945   Interval pos (0,0);
946   if (count < 1)
947     return ly_interval2scm (no_visible_stem_positions (me, pos));
948
949   vector<Real> x_posns;
950   extract_grob_set (me, "normal-stems", stems);
951   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
952   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
953
954   Real my_y = me->relative_coordinate (commony, Y_AXIS);
955
956   Grob *fvs = first_normal_stem (me);
957   Grob *lvs = last_normal_stem (me);
958
959   Interval ideal (Stem::get_stem_info (fvs).ideal_y_
960                   + fvs->relative_coordinate (commony, Y_AXIS) - my_y,
961                   Stem::get_stem_info (lvs).ideal_y_
962                   + lvs->relative_coordinate (commony, Y_AXIS) - my_y);
963
964   Real x0 = first_normal_stem (me)->relative_coordinate (commonx, X_AXIS);
965   for (vsize i = 0; i < stems.size (); i++)
966     {
967       Grob *s = stems[i];
968
969       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
970       x_posns.push_back (x);
971     }
972   Real dx = last_normal_stem (me)->relative_coordinate (commonx, X_AXIS) - x0;
973
974   Real y = 0;
975   Real slope = 0;
976   Real dy = 0;
977   Real ldy = 0.0;
978   if (!ideal.delta ())
979     {
980       Interval chord (Stem::chord_start_y (stems[0]),
981                       Stem::chord_start_y (stems.back ()));
982
983       /* Simple beams (2 stems) on middle line should be allowed to be
984          slightly sloped.
985
986          However, if both stems reach middle line,
987          ideal[LEFT] == ideal[RIGHT] and ideal.delta () == 0.
988
989          For that case, we apply artificial slope */
990       if (!ideal[LEFT] && chord.delta () && count == 2)
991         {
992           /* FIXME. -> UP */
993           Direction d = (Direction) (sign (chord.delta ()) * UP);
994           pos[d] = get_beam_thickness (me) / 2;
995           pos[-d] = -pos[d];
996         }
997       else
998         pos = ideal;
999
1000       /*
1001         For broken beams this doesn't work well. In this case, the
1002         slope esp. of the first part of a broken beam should predict
1003         where the second part goes.
1004       */
1005       ldy = pos[RIGHT] - pos[LEFT];
1006     }
1007   else
1008     {
1009       vector<Offset> ideals;
1010       for (vsize i = 0; i < stems.size (); i++)
1011         {
1012           Grob *s = stems[i];
1013           ideals.push_back (Offset (x_posns[i],
1014                                Stem::get_stem_info (s).ideal_y_
1015                                + s->relative_coordinate (commony, Y_AXIS)
1016                                - my_y));
1017         }
1018
1019       minimise_least_squares (&slope, &y, ideals);
1020
1021       dy = slope * dx;
1022
1023       set_minimum_dy (me, &dy);
1024
1025       ldy = dy;
1026       pos = Interval (y, (y + dy));
1027     }
1028
1029   /*
1030     "position" is relative to the staff.
1031   */
1032   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1033
1034   me->set_property ("least-squares-dy",  scm_from_double (ldy));
1035   return ly_interval2scm (pos);
1036 }
1037
1038 /*
1039   We can't combine with previous function, since check concave and
1040   slope damping comes first.
1041
1042   TODO: we should use the concaveness to control the amount of damping
1043   applied.
1044 */
1045 MAKE_SCHEME_CALLBACK (Beam, shift_region_to_valid, 2);
1046 SCM
1047 Beam::shift_region_to_valid (SCM grob, SCM posns)
1048 {
1049   Grob *me = unsmob_grob (grob);
1050   /*
1051     Code dup.
1052   */
1053   vector<Real> x_posns;
1054   extract_grob_set (me, "stems", stems);
1055   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
1056   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
1057
1058   Grob *fvs = first_normal_stem (me);
1059
1060   if (!fvs)
1061     return posns;
1062
1063   Real x0 = fvs->relative_coordinate (commonx, X_AXIS);
1064   for (vsize i = 0; i < stems.size (); i++)
1065     {
1066       Grob *s = stems[i];
1067
1068       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
1069       x_posns.push_back (x);
1070     }
1071
1072   Grob *lvs = last_normal_stem (me);
1073   if (!lvs)
1074     return posns;
1075
1076   Real dx = lvs->relative_coordinate (commonx, X_AXIS) - x0;
1077
1078   Drul_array<Real> pos = ly_scm2interval (posns);
1079
1080   scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
1081
1082   Real dy = pos[RIGHT] - pos[LEFT];
1083   Real y = pos[LEFT];
1084   Real slope = dx ? (dy / dx) : 0.0;
1085
1086   /*
1087     Shift the positions so that we have a chance of finding good
1088     quants (i.e. no short stem failures.)
1089   */
1090   Interval feasible_left_point;
1091   feasible_left_point.set_full ();
1092   for (vsize i = 0; i < stems.size (); i++)
1093     {
1094       Grob *s = stems[i];
1095       if (Stem::is_invisible (s))
1096         continue;
1097
1098       Direction d = get_grob_direction (s);
1099
1100       Real left_y
1101         = Stem::get_stem_info (s).shortest_y_
1102         - slope * x_posns [i];
1103
1104       /*
1105         left_y is now relative to the stem S. We want relative to
1106         ourselves, so translate:
1107       */
1108       left_y
1109         += + s->relative_coordinate (commony, Y_AXIS)
1110         - me->relative_coordinate (commony, Y_AXIS);
1111
1112       Interval flp;
1113       flp.set_full ();
1114       flp[-d] = left_y;
1115
1116       feasible_left_point.intersect (flp);
1117     }
1118
1119   if (feasible_left_point.is_empty ())
1120     warning (_ ("no viable initial configuration found: may not find good beam slope"));
1121   else if (!feasible_left_point.contains (y))
1122     {
1123       const int REGION_SIZE = 2; // UGH UGH
1124       if (isinf (feasible_left_point[DOWN]))
1125         y = feasible_left_point[UP] - REGION_SIZE;
1126       else if (isinf (feasible_left_point[UP]))
1127         y = feasible_left_point[DOWN]+ REGION_SIZE;
1128       else
1129         y = feasible_left_point.center ();
1130     }
1131
1132   pos = Drul_array<Real> (y, (y + dy));
1133   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1134
1135   return ly_interval2scm (pos);
1136 }
1137
1138 /* This neat trick is by Werner Lemberg,
1139    damped = tanh (slope)
1140    corresponds with some tables in [Wanske] CHECKME */
1141 MAKE_SCHEME_CALLBACK (Beam, slope_damping, 2);
1142 SCM
1143 Beam::slope_damping (SCM smob, SCM posns)
1144 {
1145   Grob *me = unsmob_grob (smob);
1146   Drul_array<Real> pos = ly_scm2interval (posns);
1147
1148   if (normal_stem_count (me) <= 1)
1149     return posns;
1150
1151   SCM s = me->get_property ("damping");
1152   Real damping = scm_to_double (s);
1153   Real concaveness = robust_scm2double (me->get_property ("concaveness"), 0.0);
1154   if (concaveness >= 10000)
1155     {
1156       pos[LEFT] = pos[RIGHT];
1157       me->set_property ("least-squares-dy", scm_from_double (0));
1158       damping = 0;
1159     }
1160
1161   if (damping)
1162     {
1163       scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
1164
1165       Real dy = pos[RIGHT] - pos[LEFT];
1166
1167       Grob *fvs = first_normal_stem (me);
1168       Grob *lvs = last_normal_stem (me);
1169
1170       Grob *commonx = fvs->common_refpoint (lvs, X_AXIS);
1171
1172       Real dx = last_normal_stem (me)->relative_coordinate (commonx, X_AXIS)
1173         - first_normal_stem (me)->relative_coordinate (commonx, X_AXIS);
1174
1175       Real slope = dy && dx ? dy / dx : 0;
1176
1177       slope = 0.6 * tanh (slope) / (damping + concaveness);
1178
1179       Real damped_dy = slope * dx;
1180
1181       set_minimum_dy (me, &damped_dy);
1182
1183       pos[LEFT] += (dy - damped_dy) / 2;
1184       pos[RIGHT] -= (dy - damped_dy) / 2;
1185
1186       scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1187     }
1188
1189   return ly_interval2scm (pos);
1190 }
1191
1192
1193 MAKE_SCHEME_CALLBACK (Beam, quanting, 2);
1194 SCM
1195 Beam::quanting (SCM smob, SCM posns)
1196 {
1197   Grob *me = unsmob_grob (smob);
1198   Drul_array<Real> ys(0, 0);
1199   ys = robust_scm2drul (posns, ys);
1200   Beam_scoring_problem problem (me, ys);
1201
1202   ys = problem.solve ();
1203   return ly_interval2scm (ys);
1204 }
1205
1206
1207 /*
1208   Report slice containing the numbers that are both in (car BEAMING)
1209   and (cdr BEAMING)
1210 */
1211 Slice
1212 where_are_the_whole_beams (SCM beaming)
1213 {
1214   Slice l;
1215
1216   for (SCM s = scm_car (beaming); scm_is_pair (s); s = scm_cdr (s))
1217     {
1218       if (scm_c_memq (scm_car (s), scm_cdr (beaming)) != SCM_BOOL_F)
1219
1220         l.add_point (scm_to_int (scm_car (s)));
1221     }
1222
1223   return l;
1224 }
1225
1226 /* Return the Y position of the stem-end, given the Y-left, Y-right
1227    in POS for stem S.  This Y position is relative to S. */
1228 Real
1229 Beam::calc_stem_y (Grob *me, Grob *stem, Grob **common,
1230                    Real xl, Real xr, Direction feather_dir,
1231                    Drul_array<Real> pos, bool french)
1232 {
1233   Real beam_translation = get_beam_translation (me);
1234   Direction stem_dir = get_grob_direction (stem);
1235
1236   Real dx = xr - xl;
1237   Real relx = dx ? (stem->relative_coordinate (common[X_AXIS], X_AXIS) - xl)/dx : 0;
1238   Real xdir = 2*relx-1;
1239
1240   Real stem_y = linear_combination(pos, xdir);
1241
1242   SCM beaming = stem->get_property ("beaming");
1243
1244   Slice beam_slice (french
1245                     ? where_are_the_whole_beams (beaming)
1246                     : Stem::beam_multiplicity (stem));
1247   if (beam_slice.is_empty ())
1248     beam_slice = Slice (0,0);
1249   Interval beam_multiplicity(beam_slice[LEFT],
1250                              beam_slice[RIGHT]);
1251
1252   /*
1253     feather dir = 1 , relx 0->1 : factor 0 -> 1
1254     feather dir = 0 , relx 0->1 : factor 1 -> 1
1255     feather dir = -1, relx 0->1 : factor 1 -> 0
1256    */
1257   Real feather_factor = 1;
1258   if (feather_dir > 0)
1259     feather_factor = relx;
1260   else if (feather_dir < 0)
1261     feather_factor = 1 - relx;
1262
1263   stem_y += feather_factor * beam_translation
1264     * beam_multiplicity[Direction(((french) ? DOWN : UP)*stem_dir)];
1265   Real id = me->relative_coordinate (common[Y_AXIS], Y_AXIS)
1266     - stem->relative_coordinate (common[Y_AXIS], Y_AXIS);
1267
1268   return stem_y + id;
1269 }
1270
1271 /*
1272   Hmm.  At this time, beam position and slope are determined.  Maybe,
1273   stem directions and length should set to relative to the chord's
1274   position of the beam.  */
1275 MAKE_SCHEME_CALLBACK (Beam, set_stem_lengths, 1);
1276 SCM
1277 Beam::set_stem_lengths (SCM smob)
1278 {
1279   Grob *me = unsmob_grob (smob);
1280
1281   /* trigger callbacks. */
1282   (void) me->get_property ("direction");
1283   (void) me->get_property ("beaming");
1284
1285   SCM posns = me->get_property ("positions");
1286
1287   extract_grob_set (me, "stems", stems);
1288   if (!stems.size ())
1289     return posns;
1290
1291   Grob *common[2];
1292   for (int a = 2; a--;)
1293     common[a] = common_refpoint_of_array (stems, me, Axis (a));
1294
1295   Drul_array<Real> pos = ly_scm2realdrul (posns);
1296   Real staff_space = Staff_symbol_referencer::staff_space (me);
1297   scale_drul (&pos, staff_space);
1298
1299   bool gap = false;
1300   Real thick = 0.0;
1301   if (robust_scm2int (me->get_property ("gap-count"), 0))
1302     {
1303       gap = true;
1304       thick = get_beam_thickness (me);
1305     }
1306
1307   Grob *fvs = first_normal_stem (me);
1308   Grob *lvs = last_normal_stem (me);
1309
1310   Real xl = fvs ? fvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1311   Real xr = lvs ? lvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1312   Direction feather_dir = to_dir (me->get_property ("grow-direction"));
1313
1314   for (vsize i = 0; i < stems.size (); i++)
1315     {
1316       Grob *s = stems[i];
1317
1318       bool french = to_boolean (s->get_property ("french-beaming"));
1319       Real stem_y = calc_stem_y (me, s, common,
1320                                  xl, xr, feather_dir,
1321                                  pos, french && s != lvs && s!= fvs);
1322
1323       /*
1324         Make the stems go up to the end of the beam. This doesn't matter
1325         for normal beams, but for tremolo beams it looks silly otherwise.
1326       */
1327       if (gap
1328           && !Stem::is_invisible (s))
1329         stem_y += thick * 0.5 * get_grob_direction (s);
1330
1331       /*
1332         Do set_stemend for invisible stems too, so tuplet brackets
1333         have a reference point for sloping
1334        */
1335       Stem::set_stemend (s, 2 * stem_y / staff_space);
1336     }
1337
1338   return posns;
1339 }
1340
1341 void
1342 Beam::set_beaming (Grob *me, Beaming_pattern const *beaming)
1343 {
1344   extract_grob_set (me, "stems", stems);
1345
1346   Direction d = LEFT;
1347   for (vsize i = 0; i < stems.size (); i++)
1348     {
1349       /*
1350         Don't overwrite user settings.
1351       */
1352       do
1353         {
1354           Grob *stem = stems[i];
1355           SCM beaming_prop = stem->get_property ("beaming");
1356           if (beaming_prop == SCM_EOL
1357               || index_get_cell (beaming_prop, d) == SCM_EOL)
1358             {
1359               int count = beaming->beamlet_count (i, d);
1360               if (i > 0
1361                   && i + 1 < stems.size ()
1362                   && Stem::is_invisible (stem))
1363                 count = min (count, beaming->beamlet_count (i,-d));
1364
1365               if ( ((i == 0 && d == LEFT)
1366                     || (i == stems.size ()-1 && d == RIGHT))
1367                    && stems.size () > 1
1368                    && to_boolean (me->get_property ("clip-edges")))
1369                 count = 0;
1370
1371               Stem::set_beaming (stem, count, d);
1372             }
1373         }
1374       while (flip (&d) != LEFT);
1375     }
1376 }
1377
1378 int
1379 Beam::forced_stem_count (Grob *me)
1380 {
1381   extract_grob_set (me, "normal-stems", stems);
1382
1383   int f = 0;
1384   for (vsize i = 0; i < stems.size (); i++)
1385     {
1386       Grob *s = stems[i];
1387
1388       /* I can imagine counting those boundaries as a half forced stem,
1389          but let's count them full for now. */
1390       Direction defdir = to_dir (s->get_property ("default-direction"));
1391
1392       if (abs (Stem::chord_start_y (s)) > 0.1
1393           && defdir
1394           && get_grob_direction (s) != defdir)
1395         f++;
1396     }
1397   return f;
1398 }
1399
1400 int
1401 Beam::normal_stem_count (Grob *me)
1402 {
1403   extract_grob_set (me, "normal-stems", stems);
1404   return stems.size ();
1405 }
1406
1407 Grob *
1408 Beam::first_normal_stem (Grob *me)
1409 {
1410   extract_grob_set (me, "normal-stems", stems);
1411   return stems.size () ? stems[0] : 0;
1412 }
1413
1414 Grob *
1415 Beam::last_normal_stem (Grob *me)
1416 {
1417   extract_grob_set (me, "normal-stems", stems);
1418   return stems.size () ? stems.back () : 0;
1419 }
1420
1421 /*
1422   [TODO]
1423
1424   handle rest under beam (do_post: beams are calculated now)
1425   what about combination of collisions and rest under beam.
1426
1427   Should lookup
1428
1429   rest -> stem -> beam -> interpolate_y_position ()
1430 */
1431 MAKE_SCHEME_CALLBACK_WITH_OPTARGS (Beam, rest_collision_callback, 2, 1, "");
1432 SCM
1433 Beam::rest_collision_callback (SCM smob, SCM prev_offset)
1434 {
1435   Grob *rest = unsmob_grob (smob);
1436   if (scm_is_number (rest->get_property ("staff-position")))
1437     return scm_from_int (0);
1438
1439   Real offset = robust_scm2double (prev_offset, 0.0);
1440
1441   Grob *st = unsmob_grob (rest->get_object ("stem"));
1442   Grob *stem = st;
1443   if (!stem)
1444     return scm_from_double (0.0);
1445   Grob *beam = unsmob_grob (stem->get_object ("beam"));
1446   if (!beam
1447       || !Beam::has_interface (beam)
1448       || !Beam::normal_stem_count (beam))
1449     return scm_from_double (0.0);
1450
1451   Drul_array<Real> pos (robust_scm2drul (beam->get_property ("positions"),
1452                                          Drul_array<Real> (0,0)));
1453
1454   Real staff_space = Staff_symbol_referencer::staff_space (rest);
1455
1456   scale_drul (&pos, staff_space);
1457
1458   Real dy = pos[RIGHT] - pos[LEFT];
1459
1460   Drul_array<Grob*> visible_stems (first_normal_stem (beam),
1461                                    last_normal_stem (beam));
1462   extract_grob_set (beam, "stems", stems);
1463
1464   Grob *common = common_refpoint_of_array (stems, beam, X_AXIS);
1465
1466   Real x0 = visible_stems[LEFT]->relative_coordinate (common, X_AXIS);
1467   Real dx = visible_stems[RIGHT]->relative_coordinate (common, X_AXIS) - x0;
1468   Real slope = dy && dx ? dy / dx : 0;
1469
1470   Direction d = get_grob_direction (stem);
1471   Real stem_y = pos[LEFT]
1472     + (stem->relative_coordinate (common, X_AXIS) - x0) * slope;
1473
1474   Real beam_translation = get_beam_translation (beam);
1475   Real beam_thickness = Beam::get_beam_thickness (beam);
1476
1477   /*
1478     TODO: this is not strictly correct for 16th knee beams.
1479   */
1480   int beam_count
1481     = Stem::beam_multiplicity (stem).length () + 1;
1482
1483   Real height_of_my_beams = beam_thickness / 2
1484     + (beam_count - 1) * beam_translation;
1485   Real beam_y = stem_y - d * height_of_my_beams;
1486
1487   Grob *common_y = rest->common_refpoint (beam, Y_AXIS);
1488
1489   Interval rest_extent = rest->extent (rest, Y_AXIS);
1490   rest_extent.translate (offset + rest->get_parent (Y_AXIS)->relative_coordinate (common_y, Y_AXIS));
1491
1492   Real rest_dim = rest_extent[d];
1493   Real minimum_distance
1494     = staff_space * (robust_scm2double (stem->get_property ("stemlet-length"), 0.0)
1495                      + robust_scm2double (rest->get_property ("minimum-distance"), 0.0));
1496
1497   Real shift = d * min (d * (beam_y - d * minimum_distance - rest_dim), 0.0);
1498
1499   shift /= staff_space;
1500   Real rad = Staff_symbol_referencer::line_count (rest) * staff_space / 2;
1501
1502   /* Always move discretely by half spaces */
1503   shift = ceil (fabs (shift * 2.0)) / 2.0 * sign (shift);
1504
1505   /* Inside staff, move by whole spaces*/
1506   if ((rest_extent[d] + staff_space * shift) * d
1507       < rad
1508       || (rest_extent[-d] + staff_space * shift) * -d
1509       < rad)
1510     shift = ceil (fabs (shift)) * sign (shift);
1511
1512   return scm_from_double (offset + staff_space * shift);
1513 }
1514
1515 bool
1516 Beam::is_knee (Grob *me)
1517 {
1518   SCM k = me->get_property ("knee");
1519   if (scm_is_bool (k))
1520     return ly_scm2bool (k);
1521
1522   bool knee = false;
1523   int d = 0;
1524   extract_grob_set (me, "stems", stems);
1525   for (vsize i = stems.size (); i--;)
1526     {
1527       Direction dir = get_grob_direction (stems[i]);
1528       if (d && d != dir)
1529         {
1530           knee = true;
1531           break;
1532         }
1533       d = dir;
1534     }
1535
1536   me->set_property ("knee", ly_bool2scm (knee));
1537
1538   return knee;
1539 }
1540
1541 bool
1542 Beam::is_cross_staff (Grob *me)
1543 {
1544   extract_grob_set (me, "stems", stems);
1545   Grob *staff_symbol = Staff_symbol_referencer::get_staff_symbol (me);
1546   for (vsize i = 0; i < stems.size (); i++)
1547     if (Staff_symbol_referencer::get_staff_symbol (stems[i]) != staff_symbol)
1548       return true;
1549   return false;
1550 }
1551
1552 MAKE_SCHEME_CALLBACK (Beam, calc_cross_staff, 1)
1553 SCM
1554 Beam::calc_cross_staff (SCM smob)
1555 {
1556   return scm_from_bool (is_cross_staff (unsmob_grob (smob)));
1557 }
1558
1559 int
1560 Beam::get_direction_beam_count (Grob *me, Direction d)
1561 {
1562   extract_grob_set (me, "stems", stems);
1563   int bc = 0;
1564
1565   for (vsize i = stems.size (); i--;)
1566     {
1567       /*
1568         Should we take invisible stems into account?
1569       */
1570       if (get_grob_direction (stems[i]) == d)
1571         bc = max (bc, (Stem::beam_multiplicity (stems[i]).length () + 1));
1572     }
1573
1574   return bc;
1575 }
1576
1577 ADD_INTERFACE (Beam,
1578                "A beam.\n"
1579                "\n"
1580                "The @code{beam-thickness} property is the weight of beams,"
1581                " measured in staffspace.  The @code{direction} property is"
1582                " not user-serviceable.  Use the @code{direction} property"
1583                " of @code{Stem} instead.\n"
1584                "\n"
1585                "The following properties may be set in the @code{details}"
1586                " list.\n"
1587                "\n"
1588                "@table @code\n"
1589                "@item stem-length-demerit-factor\n"
1590                "Demerit factor used for inappropriate stem lengths.\n"
1591                "@item secondary-beam-demerit\n"
1592                "Demerit used in quanting calculations for multiple"
1593                " beams.\n"
1594                "@item region-size\n"
1595                "Size of region for checking quant scores.\n"
1596                "@item beam-eps\n"
1597                "Epsilon for beam quant code to check for presence"
1598                " in gap.\n"
1599                "@item stem-length-limit-penalty\n"
1600                "Penalty for differences in stem lengths on a beam.\n"
1601                "@item damping-direction-penalty\n"
1602                "Demerit penalty applied when beam direction is different"
1603                " from damping direction.\n"
1604                "@item hint-direction-penalty\n"
1605                "Demerit penalty applied when beam direction is different"
1606                " from damping direction, but damping slope is"
1607                " <= @code{round-to-zero-slope}.\n"
1608                "@item musical-direction-factor\n"
1609                "Demerit scaling factor for difference between"
1610                " beam slope and music slope.\n"
1611                "@item ideal-slope-factor\n"
1612                "Demerit scaling factor for difference between"
1613                " beam slope and damping slope.\n"
1614                "@item round-to-zero-slope\n"
1615                "Damping slope which is considered zero for purposes of"
1616                " calculating direction penalties.\n"
1617                "@end table\n",
1618
1619                /* properties */
1620                "annotation "
1621                "auto-knee-gap "
1622                "beamed-stem-shorten "
1623                "beaming "
1624                "beam-thickness "
1625                "break-overshoot "
1626                "clip-edges "
1627                "concaveness "
1628                "damping "
1629                "details "
1630                "direction "
1631                "gap "
1632                "gap-count "
1633                "grow-direction "
1634                "inspect-quants "
1635                "knee "
1636                "length-fraction "
1637                "least-squares-dy "
1638                "neutral-direction "
1639                "normal-stems "
1640                "positions "
1641                "quant-score "
1642                "quantized-positions "
1643                "shorten "
1644                "stems "
1645                );