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