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