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