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