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