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