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