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