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