]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
* flower/include/axis.hh: rename from axes.hh
[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 "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_property ("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_c_procedure_p (func))
76     {
77       SCM s = scm_call_2 (func, me->self_scm (), scm_int2num (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   for (SCM s = me->get_property ("stems"); scm_is_pair (s); s = scm_cdr (s))
92     {
93       Grob *stem = unsmob_grob (scm_car (s));
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_make_real (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       SCM stems = me->get_property ("stems");
143       if (scm_ilength (stems) == 1)
144         {
145           me->warning (_ ("removing beam with less than two stems"));
146
147           unsmob_grob (scm_car (stems))->set_property ("beam", SCM_EOL);
148           me->suicide ();
149
150           return SCM_UNSPECIFIED;
151         }
152       else if (scm_ilength (stems) == 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_int2num (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   Link_array<Grob> stems
219     = extract_grob_array (me, ly_symbol2scm ("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_int2num (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_int2num (np));
268               last_int.add_point (np);
269             }
270         }
271
272       if (i == stems.size () -1)
273         {
274           scm_set_cdr_x (this_beaming, SCM_EOL);
275         }
276
277       if (scm_ilength (scm_cdr (this_beaming)) > 0)
278         {
279           last_beaming = this_beaming;
280           last_dir = this_dir;
281         }
282     }
283 }
284
285 /*
286   TODO: should not make beams per stem, but per Y-level.
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   Link_array<Grob> stems
296     = extract_grob_array (me, ly_symbol2scm ("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 *st = (i < stems.size ()) ? stems[i] : 0;
345
346       SCM this_beaming = st ? st->get_property ("beaming") : SCM_EOL;
347       Real xposn = st ? st->relative_coordinate (xcommon, X_AXIS) : 0.0;
348       Real stem_width = st ? robust_scm2double (st->get_property ("thickness"), 1.0) * lt : 0;
349       Direction stem_dir = st ? to_dir (st->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 = st ? 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             {
368               full_beams.push (b);
369             }
370           else
371             {
372               lfliebertjes.push (b);
373             }
374         }
375       for (SCM s = right;
376            scm_is_pair (s); s = scm_cdr (s))
377         {
378           int b = scm_to_int (scm_car (s));
379           if (scm_c_memq (scm_car (s), left) == SCM_BOOL_F)
380             {
381               rfliebertjes.push (b);
382             }
383         }
384
385       /*
386         how much to stick out for beams across linebreaks
387       */
388       Real break_overshoot = 3.0;
389       Real w = (i > 0 && st) ? (xposn - last_xposn) : break_overshoot;
390
391       Real stem_offset = 0.0;
392       if (i > 0)
393         {
394           w += last_stem_width / 2;
395           stem_offset = -last_stem_width / 2;
396         }
397
398       if (st)
399         w += stem_width / 2;
400
401       Real blot = me->get_layout ()->get_dimension (ly_symbol2scm ("blotdiameter"));
402       Stencil whole = Lookup::beam (slope, w, thick, blot);
403       Stencil gapped;
404
405       int gap_count = 0;
406       if (scm_is_number (me->get_property ("gap-count")))
407         {
408           gap_count = scm_to_int (me->get_property ("gap-count"));
409           gapped = Lookup::beam (slope, w - 2 * gap_length, thick, blot);
410
411           full_beams.sort (default_compare);
412           if (stem_dir == UP)
413             full_beams.reverse ();
414         }
415
416       int k = 0;
417       for (int j = full_beams.size (); j--;)
418         {
419           Stencil b (whole);
420
421           if (k++ < gap_count)
422             {
423               b = gapped;
424               b.translate_axis (gap_length, X_AXIS);
425             }
426           b.translate_axis (last_xposn - x0 + stem_offset, X_AXIS);
427           b.translate_axis (slope * (last_xposn - x0) + bdy * full_beams[j], Y_AXIS);
428
429           the_beam.add_stencil (b);
430         }
431
432       if (lfliebertjes.size () || rfliebertjes.size ())
433         {
434           Real nw_f;
435
436           if (st)
437             {
438               int t = Stem::duration_log (st);
439
440               SCM proc = me->get_property ("flag-width-function");
441               SCM result = scm_call_1 (proc, scm_int2num (t));
442               nw_f = scm_to_double (result);
443             }
444           else
445             nw_f = break_overshoot / 2;
446
447           /* Half beam should be one note-width,
448              but let's make sure two half-beams never touch */
449           Real lw = nw_f;
450           Real rw = nw_f;
451           if (i > 0)
452             rw = min (nw_f, ((xposn - last_xposn) / 2));
453           else
454             /*
455               TODO: 0.5 is a guess.
456             */
457             rw = xposn - me->get_bound (LEFT)->extent (xcommon, X_AXIS)[RIGHT]
458               - 0.5;
459
460           if (st)
461             lw = min (nw_f, ((xposn - last_xposn) / 2));
462           else
463             lw = me->get_bound (RIGHT)->relative_coordinate (xcommon, X_AXIS)
464               - last_xposn;
465
466           Stencil rhalf = Lookup::beam (slope, rw, thick, blot);
467           Stencil lhalf = Lookup::beam (slope, lw, thick, blot);
468           for (int j = lfliebertjes.size (); j--;)
469             {
470               Stencil b (lhalf);
471               b.translate_axis (last_xposn - x0, X_AXIS);
472               b.translate_axis (slope * (last_xposn - x0) + bdy * lfliebertjes[j], 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, X_AXIS);
479               b.translate_axis (slope * (xposn - x0 -rw) + 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), X_AXIS);
490   the_beam.translate_axis (pos[LEFT], Y_AXIS);
491
492 #if (DEBUG_QUANTING)
493   SCM quant_score = me->get_property ("quant-score");
494   if (to_boolean (me->get_layout ()->lookup_variable (ly_symbol2scm ("debug-beam-quanting")))
495       && scm_is_string (quant_score))
496     {
497
498       /*
499         This code prints the demerits for each beam. Perhaps this
500         should be switchable for those who want to twiddle with the
501         parameters.
502       */
503       String str;
504       SCM properties = Font_interface::text_font_alist_chain (me);
505
506       Direction stem_dir = stems.size () ? to_dir (stems[0]->get_property ("direction")) : UP;
507
508       Stencil tm = *unsmob_stencil (Text_interface::interpret_markup
509                                     (me->get_layout ()->self_scm (), properties, quant_score));
510       the_beam.add_at_edge (Y_AXIS, stem_dir, tm, 1.0, 0);
511     }
512 #endif
513
514   return the_beam.smobbed_copy ();
515 }
516
517 Direction
518 Beam::get_default_dir (Grob *me)
519 {
520   Drul_array<int> total;
521   total[UP] = total[DOWN] = 0;
522   Drul_array<int> count;
523   count[UP] = count[DOWN] = 0;
524   Direction d = DOWN;
525
526   Link_array<Grob> stems
527     = extract_grob_array (me, ly_symbol2scm ("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_int2num (count[UP]),
549                                 scm_int2num (count[DOWN])),
550                       scm_cons (scm_int2num (total[UP]),
551                                 scm_int2num (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   Link_array<Grob> stems
567     = extract_grob_array (me, ly_symbol2scm ("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   Link_array<Grob> stems
603     = extract_grob_array (me, ly_symbol2scm ("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_int2num (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_make_real (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   Link_array<Grob> stems
809     = extract_grob_array (me, ly_symbol2scm ("stems"));
810   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
811   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
812
813   Real my_y = me->relative_coordinate (commony, Y_AXIS);
814
815   Grob *fvs = first_visible_stem (me);
816   Grob *lvs = last_visible_stem (me);
817
818   Interval ideal (Stem::get_stem_info (fvs).ideal_y_
819                   + fvs->relative_coordinate (commony, Y_AXIS) -my_y,
820                   Stem::get_stem_info (lvs).ideal_y_
821                   + lvs->relative_coordinate (commony, Y_AXIS) - my_y);
822
823   Real x0 = first_visible_stem (me)->relative_coordinate (commonx, X_AXIS);
824   for (int i = 0; i < stems.size (); i++)
825     {
826       Grob *s = stems[i];
827
828       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
829       x_posns.push (x);
830     }
831   Real dx = last_visible_stem (me)->relative_coordinate (commonx, X_AXIS) - x0;
832
833   Real y = 0;
834   Real slope = 0;
835   Real dy = 0;
836
837   if (!ideal.delta ())
838     {
839       Interval chord (Stem::chord_start_y (first_visible_stem (me)),
840                       Stem::chord_start_y (last_visible_stem (me)));
841
842       /* Simple beams (2 stems) on middle line should be allowed to be
843          slightly sloped.
844
845          However, if both stems reach middle line,
846          ideal[LEFT] == ideal[RIGHT] and ideal.delta () == 0.
847
848          For that case, we apply artificial slope */
849       if (!ideal[LEFT] && chord.delta () && count == 2)
850         {
851           /* FIXME. -> UP */
852           Direction d = (Direction) (sign (chord.delta ()) * UP);
853           pos[d] = get_thickness (me) / 2;
854           pos[-d] = -pos[d];
855         }
856       else
857         {
858           pos = ideal;
859         }
860
861       /*
862         For broken beams this doesn't work well. In this case, the
863         slope esp. of the first part of a broken beam should predict
864         where the second part goes.
865       */
866       me->set_property ("least-squares-dy",
867                         scm_make_real (pos[RIGHT] - pos[LEFT]));
868     }
869   else
870     {
871       Array<Offset> ideals;
872       for (int i = 0; i < stems.size (); i++)
873         {
874           Grob *s = stems[i];
875           if (Stem::is_invisible (s))
876             continue;
877           ideals.push (Offset (x_posns[i],
878                                Stem::get_stem_info (s).ideal_y_
879                                + s->relative_coordinate (commony, Y_AXIS)
880                                - my_y));
881         }
882
883       minimise_least_squares (&slope, &y, ideals);
884
885       dy = slope * dx;
886
887       set_minimum_dy (me, &dy);
888       me->set_property ("least-squares-dy", scm_make_real (dy));
889       pos = Interval (y, (y + dy));
890     }
891
892   /*
893     "position" is relative to the staff.
894   */
895   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
896
897   me->set_property ("positions", ly_interval2scm (pos));
898
899   return SCM_UNSPECIFIED;
900 }
901
902 /*
903   We can't combine with previous function, since check concave and
904   slope damping comes first.
905
906   TODO: we should use the concaveness to control the amount of damping
907   applied.
908 */
909 MAKE_SCHEME_CALLBACK (Beam, shift_region_to_valid, 1);
910 SCM
911 Beam::shift_region_to_valid (SCM grob)
912 {
913   Grob *me = unsmob_grob (grob);
914   /*
915     Code dup.
916   */
917   Array<Real> x_posns;
918   Link_array<Grob> stems
919     = extract_grob_array (me, ly_symbol2scm ("stems"));
920   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
921   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
922
923   Grob *fvs = first_visible_stem (me);
924
925   if (!fvs)
926     return SCM_UNSPECIFIED;
927
928   Real x0 = fvs->relative_coordinate (commonx, X_AXIS);
929   for (int i = 0; i < stems.size (); i++)
930     {
931       Grob *s = stems[i];
932
933       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
934       x_posns.push (x);
935     }
936
937   Grob *lvs = last_visible_stem (me);
938   if (!lvs)
939     return SCM_UNSPECIFIED;
940
941   Real dx = lvs->relative_coordinate (commonx, X_AXIS) - x0;
942
943   Drul_array<Real> pos = ly_scm2interval (me->get_property ("positions"));
944
945   scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
946
947   Real dy = pos[RIGHT] - pos[LEFT];
948   Real y = pos[LEFT];
949   Real slope = dy / dx;
950
951   /*
952     Shift the positions so that we have a chance of finding good
953     quants (i.e. no short stem failures.)
954   */
955   Interval feasible_left_point;
956   feasible_left_point.set_full ();
957   for (int i = 0; i < stems.size (); i++)
958     {
959       Grob *s = stems[i];
960       if (Stem::is_invisible (s))
961         continue;
962
963       Direction d = Stem::get_direction (s);
964
965       Real left_y
966         = Stem::get_stem_info (s).shortest_y_
967         - slope * x_posns [i];
968
969       /*
970         left_y is now relative to the stem S. We want relative to
971         ourselves, so translate:
972       */
973       left_y
974         += + s->relative_coordinate (commony, Y_AXIS)
975         - me->relative_coordinate (commony, Y_AXIS);
976
977       Interval flp;
978       flp.set_full ();
979       flp[-d] = left_y;
980
981       feasible_left_point.intersect (flp);
982     }
983
984   if (feasible_left_point.is_empty ())
985     warning (_ ("no viable initial configuration found: may not find good beam slope"));
986   else if (!feasible_left_point.contains (y))
987     {
988       if (isinf (feasible_left_point[DOWN]))
989         y = feasible_left_point[UP] - REGION_SIZE;
990       else if (isinf (feasible_left_point[UP]))
991         y = feasible_left_point[DOWN]+ REGION_SIZE;
992       else
993         y = feasible_left_point.center ();
994     }
995
996   pos = Drul_array<Real> (y, (y + dy));
997   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
998
999   me->set_property ("positions", ly_interval2scm (pos));
1000   return SCM_UNSPECIFIED;
1001 }
1002
1003 /* This neat trick is by Werner Lemberg,
1004    damped = tanh (slope)
1005    corresponds with some tables in [Wanske] CHECKME */
1006 MAKE_SCHEME_CALLBACK (Beam, slope_damping, 1);
1007 SCM
1008 Beam::slope_damping (SCM smob)
1009 {
1010   Grob *me = unsmob_grob (smob);
1011
1012   if (visible_stem_count (me) <= 1)
1013     return SCM_UNSPECIFIED;
1014
1015   SCM s = me->get_property ("damping");
1016   Real damping = scm_to_double (s);
1017
1018   if (damping)
1019     {
1020       Drul_array<Real> pos = ly_scm2interval (me->get_property ("positions"));
1021       scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
1022
1023       Real dy = pos[RIGHT] - pos[LEFT];
1024
1025       Grob *fvs = first_visible_stem (me);
1026       Grob *lvs = last_visible_stem (me);
1027
1028       Grob *commonx = fvs->common_refpoint (lvs, X_AXIS);
1029
1030       Real dx = last_visible_stem (me)->relative_coordinate (commonx, X_AXIS)
1031         - first_visible_stem (me)->relative_coordinate (commonx, X_AXIS);
1032
1033       Real slope = dy && dx ? dy / dx : 0;
1034
1035       Real concaveness = robust_scm2double (me->get_property ("concaveness"), 0.0);
1036
1037       slope = 0.6 * tanh (slope) / (damping + concaveness);
1038
1039       Real damped_dy = slope * dx;
1040
1041       set_minimum_dy (me, &damped_dy);
1042
1043       pos[LEFT] += (dy - damped_dy) / 2;
1044       pos[RIGHT] -= (dy - damped_dy) / 2;
1045
1046       scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1047
1048       me->set_property ("positions", ly_interval2scm (pos));
1049     }
1050   return SCM_UNSPECIFIED;
1051 }
1052
1053 /*
1054   Report slice containing the numbers that are both in (car BEAMING)
1055   and (cdr BEAMING)
1056 */
1057 Slice
1058 where_are_the_whole_beams (SCM beaming)
1059 {
1060   Slice l;
1061
1062   for (SCM s = scm_car (beaming); scm_is_pair (s); s = scm_cdr (s))
1063     {
1064       if (scm_c_memq (scm_car (s), scm_cdr (beaming)) != SCM_BOOL_F)
1065
1066         l.add_point (scm_to_int (scm_car (s)));
1067     }
1068
1069   return l;
1070 }
1071
1072 /* Return the Y position of the stem-end, given the Y-left, Y-right
1073    in POS for stem S.  This Y position is relative to S. */
1074 Real
1075 Beam::calc_stem_y (Grob *me, Grob *s, Grob ** common,
1076                    Real xl, Real xr,
1077                    Drul_array<Real> pos, bool french)
1078 {
1079   Real beam_translation = get_beam_translation (me);
1080
1081   Real r = s->relative_coordinate (common[X_AXIS], X_AXIS) - xl;
1082   Real dy = pos[RIGHT] - pos[LEFT];
1083   Real dx = xr - xl;
1084   Real stem_y_beam0 = (dy && dx
1085                        ? r / dx
1086                        * dy
1087                        : 0) + pos[LEFT];
1088
1089   Direction my_dir = get_grob_direction (s);
1090   SCM beaming = s->get_property ("beaming");
1091
1092   Real stem_y = stem_y_beam0;
1093   if (french)
1094     {
1095       Slice bm = where_are_the_whole_beams (beaming);
1096       if (!bm.is_empty ())
1097         stem_y += beam_translation * bm[-my_dir];
1098     }
1099   else
1100     {
1101       Slice bm = Stem::beam_multiplicity (s);
1102       if (!bm.is_empty ())
1103         stem_y += bm[my_dir] * beam_translation;
1104     }
1105
1106   Real id = me->relative_coordinate (common[Y_AXIS], Y_AXIS)
1107     - s->relative_coordinate (common[Y_AXIS], Y_AXIS);
1108
1109   return stem_y + id;
1110 }
1111
1112 /*
1113   Hmm.  At this time, beam position and slope are determined.  Maybe,
1114   stem directions and length should set to relative to the chord's
1115   position of the beam.  */
1116 void
1117 Beam::set_stem_lengths (Grob *me)
1118 {
1119   Link_array<Grob> stems
1120     = extract_grob_array (me, ly_symbol2scm ("stems"));
1121
1122   if (!stems.size ())
1123     return;
1124
1125   Grob *common[2];
1126   for (int a = 2; a--;)
1127     common[a] = common_refpoint_of_array (stems, me, Axis (a));
1128
1129   Drul_array<Real> pos = ly_scm2realdrul (me->get_property ("positions"));
1130   Real staff_space = Staff_symbol_referencer::staff_space (me);
1131   scale_drul (&pos, staff_space);
1132
1133   bool gap = false;
1134   Real thick = 0.0;
1135   if (scm_is_number (me->get_property ("gap-count"))
1136       &&scm_to_int (me->get_property ("gap-count")))
1137     {
1138       gap = true;
1139       thick = get_thickness (me);
1140     }
1141
1142   // ugh -> use commonx
1143   Grob *fvs = first_visible_stem (me);
1144   Grob *lvs = last_visible_stem (me);
1145
1146   Real xl = fvs ? fvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1147   Real xr = lvs ? lvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1148
1149   for (int i = 0; i < stems.size (); i++)
1150     {
1151       Grob *s = stems[i];
1152       if (Stem::is_invisible (s))
1153         continue;
1154
1155       bool french = to_boolean (s->get_property ("french-beaming"));
1156       Real stem_y = calc_stem_y (me, s, common,
1157                                  xl, xr,
1158                                  pos, french && s != lvs && s!= fvs);
1159
1160       /*
1161         Make the stems go up to the end of the beam. This doesn't matter
1162         for normal beams, but for tremolo beams it looks silly otherwise.
1163       */
1164       if (gap)
1165         stem_y += thick * 0.5 * get_grob_direction (s);
1166
1167       Stem::set_stemend (s, 2 * stem_y / staff_space);
1168     }
1169 }
1170
1171 void
1172 Beam::set_beaming (Grob *me, Beaming_info_list *beaming)
1173 {
1174   Link_array<Grob> stems
1175     = extract_grob_array (me, ly_symbol2scm ("stems"));
1176
1177   Direction d = LEFT;
1178   for (int i = 0; i < stems.size (); i++)
1179     {
1180       /*
1181         Don't overwrite user settings.
1182       */
1183
1184       do
1185         {
1186           /* Don't set beaming for outside of outer stems */
1187           if ((d == LEFT && i == 0)
1188               || (d == RIGHT && i == stems.size () -1))
1189             continue;
1190
1191           Grob *st = stems[i];
1192           SCM beaming_prop = st->get_property ("beaming");
1193           if (beaming_prop == SCM_EOL
1194               || index_get_cell (beaming_prop, d) == SCM_EOL)
1195             {
1196               int b = beaming->infos_.elem (i).beams_i_drul_[d];
1197               if (i > 0
1198                   && i < stems.size () -1
1199                   && Stem::is_invisible (st))
1200                 b = min (b, beaming->infos_.elem (i).beams_i_drul_[-d]);
1201
1202               Stem::set_beaming (st, b, d);
1203             }
1204         }
1205       while (flip (&d) != LEFT);
1206     }
1207 }
1208
1209 int
1210 Beam::forced_stem_count (Grob *me)
1211 {
1212   Link_array<Grob> stems
1213     = extract_grob_array (me, ly_symbol2scm ("stems"));
1214   int f = 0;
1215   for (int i = 0; i < stems.size (); i++)
1216     {
1217       Grob *s = stems[i];
1218
1219       if (Stem::is_invisible (s))
1220         continue;
1221
1222       /* I can imagine counting those boundaries as a half forced stem,
1223          but let's count them full for now. */
1224       if (abs (Stem::chord_start_y (s)) > 0.1
1225           && (Stem::get_direction (s) != Stem::get_default_dir (s)))
1226         f++;
1227     }
1228   return f;
1229 }
1230
1231 int
1232 Beam::visible_stem_count (Grob *me)
1233 {
1234   Link_array<Grob> stems
1235     = extract_grob_array (me, ly_symbol2scm ("stems"));
1236   int c = 0;
1237   for (int i = stems.size (); i--;)
1238     {
1239       if (!Stem::is_invisible (stems[i]))
1240         c++;
1241     }
1242   return c;
1243 }
1244
1245 Grob *
1246 Beam::first_visible_stem (Grob *me)
1247 {
1248   Link_array<Grob> stems
1249     = extract_grob_array (me, ly_symbol2scm ("stems"));
1250
1251   for (int i = 0; i < stems.size (); i++)
1252     {
1253       if (!Stem::is_invisible (stems[i]))
1254         return stems[i];
1255     }
1256   return 0;
1257 }
1258
1259 Grob *
1260 Beam::last_visible_stem (Grob *me)
1261 {
1262   Link_array<Grob> stems
1263     = extract_grob_array (me, ly_symbol2scm ("stems"));
1264   for (int i = stems.size (); i--;)
1265     {
1266       if (!Stem::is_invisible (stems[i]))
1267         return stems[i];
1268     }
1269   return 0;
1270 }
1271
1272 /*
1273   [TODO]
1274
1275   handle rest under beam (do_post: beams are calculated now)
1276   what about combination of collisions and rest under beam.
1277
1278   Should lookup
1279
1280   rest -> stem -> beam -> interpolate_y_position ()
1281 */
1282 MAKE_SCHEME_CALLBACK (Beam, rest_collision_callback, 2);
1283 SCM
1284 Beam::rest_collision_callback (SCM element_smob, SCM axis)
1285 {
1286   Grob *rest = unsmob_grob (element_smob);
1287   (void) axis;
1288
1289   if (scm_is_number (rest->get_property ("staff-position")))
1290     return scm_int2num (0);
1291
1292   assert (scm_to_int (axis) == Y_AXIS);
1293
1294   Grob *st = unsmob_grob (rest->get_property ("stem"));
1295   Grob *stem = st;
1296   if (!stem)
1297     return scm_make_real (0.0);
1298   Grob *beam = unsmob_grob (stem->get_property ("beam"));
1299   if (!beam
1300       || !Beam::has_interface (beam)
1301       || !Beam::visible_stem_count (beam))
1302     return scm_make_real (0.0);
1303
1304   Drul_array<Real> pos (0, 0);
1305   SCM s = beam->get_property ("positions");
1306   if (scm_is_pair (s) && scm_is_number (scm_car (s)))
1307     pos = ly_scm2interval (s);
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_make_real (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   for (SCM s = me->get_property ("stems"); scm_is_pair (s); s = scm_cdr (s))
1370     {
1371       Direction dir = get_grob_direction (unsmob_grob (scm_car (s)));
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   Link_array<Grob> stems
1389     = extract_grob_array (me, ly_symbol2scm ("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, and is measured "
1407                "in  staffspace",
1408                "knee positioning-done position-callbacks "
1409                "concaveness dir-function quant-score auto-knee-gap gap "
1410                "gap-count chord-tremolo beamed-stem-shorten shorten least-squares-dy "
1411                "damping inspect-quants flag-width-function neutral-direction positions space-function "
1412                "thickness");
1413