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