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