]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
67d9b664ce3f0fce0dc1022535d2283d2c8af30d
[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--2002 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7     Jan Nieuwenhuizen <janneke@gnu.org>
8
9 */
10
11 /*
12   [TODO]
13
14   * different left/right quanting: slope, multiplicity
15   
16   * Fix TODO
17   
18   * Junk stem_info.
19   
20   * Remove #'direction from beam.  A beam has no direction per se.
21     It may only set directions for stems.
22
23   * Rewrite stem_beams.
24     
25   */
26
27
28 #include <math.h> // tanh.
29
30 #include "molecule.hh" 
31 #include "directional-element-interface.hh"
32 #include "beaming.hh"
33 #include "beam.hh"
34 #include "misc.hh"
35 #include "least-squares.hh"
36 #include "stem.hh"
37 #include "paper-def.hh"
38 #include "lookup.hh"
39 #include "group-interface.hh"
40 #include "staff-symbol-referencer.hh"
41 #include "item.hh"
42 #include "spanner.hh"
43 #include "warn.hh"
44
45 void
46 Beam::add_stem (Grob *me, Grob *s)
47 {
48   Pointer_group_interface::add_grob (me, ly_symbol2scm ("stems"), s);
49   
50   s->add_dependency (me);
51
52   assert (!Stem::beam_l (s));
53   s->set_grob_property ("beam", me->self_scm ());
54
55   add_bound_item (dynamic_cast<Spanner*> (me), dynamic_cast<Item*> (s));
56 }
57
58 int
59 Beam::get_multiplicity (Grob *me) 
60 {
61   int m = 0;
62   for (SCM s = me->get_grob_property ("stems"); gh_pair_p (s); s = ly_cdr (s))
63     {
64       Grob *sc = unsmob_grob (ly_car (s));
65
66       if (Stem::has_interface (sc))
67         m = m >? Stem::beam_count (sc, LEFT) >? Stem::beam_count (sc, RIGHT);
68     }
69   return m;
70 }
71
72 /* After pre-processing all directions should be set.
73    Several post-processing routines (stem, slur, script) need stem/beam
74    direction.
75    Currenly, this means that beam has set all stem's directions.
76    [Alternatively, stems could set its own directions, according to
77    their beam, during 'final-pre-processing'.] */
78 MAKE_SCHEME_CALLBACK (Beam, before_line_breaking, 1);
79 SCM
80 Beam::before_line_breaking (SCM smob)
81 {
82   Grob *me =  unsmob_grob (smob);
83
84   /* Beams with less than 2 two stems don't make much sense, but could happen
85      when you do
86      
87      [r8 c8 r8].
88      
89     For a beam that  only has one stem, we try to do some disappearance magic:
90     we revert the flag, and move on to The Eternal Engraving Fields. */
91
92   int count = visible_stem_count (me);
93   if (count < 2)
94     {
95       me->warning (_ ("beam has less than two visible stems"));
96
97       SCM stems = me->get_grob_property ("stems");
98       if (scm_ilength (stems) == 1)
99         {
100           me->warning (_ ("Beam has less than two stems. Removing beam."));
101
102           unsmob_grob (gh_car (stems))->remove_grob_property ("beam");
103           me->suicide ();
104
105           return SCM_UNSPECIFIED;
106         }
107       else if (scm_ilength (stems) == 0)
108         {
109           me->suicide ();
110           return SCM_UNSPECIFIED;         
111         }
112     }
113   if (count >= 1)
114     {
115       if (!Directional_element_interface::get (me))
116         Directional_element_interface::set (me, get_default_dir (me));
117       
118       consider_auto_knees (me);
119       set_stem_directions (me);
120       set_stem_shorten (me);
121     }
122   return SCM_EOL;
123 }
124
125 Direction
126 Beam::get_default_dir (Grob *me) 
127 {
128   Drul_array<int> total;
129   total[UP]  = total[DOWN] = 0;
130   Drul_array<int> count; 
131   count[UP]  = count[DOWN] = 0;
132   Direction d = DOWN;
133
134   Link_array<Item> stems=
135         Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
136
137   for (int i=0; i <stems.size (); i++)
138     do {
139       Grob *s = stems[i];
140       Direction sd = Directional_element_interface::get (s);
141       int current = sd  ? (1 + d * sd)/2
142         : Stem::get_center_distance (s, (Direction)-d);
143
144       if (current)
145         {
146           total[d] += current;
147           count[d] ++;
148         }
149
150     } while (flip (&d) != DOWN);
151   
152   SCM func = me->get_grob_property ("dir-function");
153   SCM s = gh_call2 (func,
154                     gh_cons (gh_int2scm (count[UP]),
155                              gh_int2scm (count[DOWN])),
156                     gh_cons (gh_int2scm (total[UP]),
157                              gh_int2scm (total[DOWN])));
158
159   if (gh_number_p (s) && gh_scm2int (s))
160     return to_dir (s);
161   
162   /* If dir is not determined: get default */
163   return to_dir (me->get_grob_property ("neutral-direction"));
164 }
165
166
167 /* Set all stems with non-forced direction to beam direction.
168    Urg: non-forced should become `without/with unforced' direction,
169    once stem gets cleaned-up. */
170 void
171 Beam::set_stem_directions (Grob *me)
172 {
173   Link_array<Item> stems
174     =Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
175   Direction d = Directional_element_interface::get (me);
176   
177   for (int i=0; i <stems.size (); i++)
178     {
179       Grob *s = stems[i];
180       SCM force = s->remove_grob_property ("dir-forced");
181       if (!gh_boolean_p (force) || !gh_scm2bool (force))
182         Directional_element_interface::set (s, d);
183     }
184
185
186 /* Simplistic auto-knees; only consider vertical gap between two
187    adjacent chords.
188
189   `Forced' stem directions are ignored.  If you don't want auto-knees,
190   don't set, or unset auto-knee-gap. */
191 void
192 Beam::consider_auto_knees (Grob *me)
193 {
194   SCM scm = me->get_grob_property ("auto-knee-gap");
195
196   if (gh_number_p (scm))
197     {
198       bool knee_b = false;
199       Real knee_y = 0;
200       Real staff_space = Staff_symbol_referencer::staff_space (me);
201       Real gap = gh_scm2double (scm) / staff_space;
202
203       Direction d = Directional_element_interface::get (me);
204       Link_array<Item> stems=
205         Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
206       
207       Grob *common = me->common_refpoint (stems[0], Y_AXIS);
208       for (int i=1; i < stems.size (); i++)
209         if (!Stem::invisible_b (stems[i]))
210           common = common->common_refpoint (stems[i], Y_AXIS);
211
212       int l = 0;
213       for (int i=1; i < stems.size (); i++)
214         {
215           if (!Stem::invisible_b (stems[i-1]))
216             l = i - 1;
217           if (Stem::invisible_b (stems[l]))
218             continue;
219           if (Stem::invisible_b (stems[i]))
220             continue;
221           
222           Real left = Stem::extremal_heads (stems[l])[d]
223             ->relative_coordinate (common, Y_AXIS);
224           Real right = Stem::extremal_heads (stems[i])[-d]
225             ->relative_coordinate (common, Y_AXIS);
226
227           Real dy = right - left;
228
229           if (abs (dy) >= gap)
230             {
231               knee_y = (right + left) / 2;
232               knee_b = true;
233               break;
234             }
235         }
236       
237       if (knee_b)
238         {
239           for (int i=0; i < stems.size (); i++)
240             {
241               if (Stem::invisible_b (stems[i]))
242                 continue;
243               Item *s = stems[i];         
244               Real y = Stem::extremal_heads (stems[i])[d]
245                 ->relative_coordinate (common, Y_AXIS);
246
247               Directional_element_interface::set (s, y < knee_y ? UP : DOWN);
248               s->set_grob_property ("dir-forced", SCM_BOOL_T);
249             }
250         }
251     }
252 }
253
254 /* Set stem's shorten property if unset.
255    TODO:
256    take some y-position (chord/beam/nearest?) into account
257    scmify forced-fraction */
258 void
259 Beam::set_stem_shorten (Grob *m)
260 {
261   Spanner*me = dynamic_cast<Spanner*> (m);
262
263   Real forced_fraction = forced_stem_count (me) / visible_stem_count (me);
264
265   int multiplicity = get_multiplicity (me);
266
267   SCM shorten = me->get_grob_property ("beamed-stem-shorten");
268   if (shorten == SCM_EOL)
269     return;
270
271   int sz = scm_ilength (shorten);
272   
273   Real staff_space = Staff_symbol_referencer::staff_space (me);
274   SCM shorten_elt = scm_list_ref (shorten,
275                                   gh_int2scm (multiplicity <? (sz - 1)));
276   Real shorten_f = gh_scm2double (shorten_elt) * staff_space;
277
278   /* your similar cute comment here */
279   shorten_f *= forced_fraction;
280   
281   me->set_grob_property ("shorten", gh_double2scm (shorten_f));
282 }
283
284 /*  Call list of y-dy-callbacks, that handle setting of
285     grob-properties y, dy.
286     
287     User may set grob-properties: y-position-hs and height-hs
288     (to be fixed) that override the calculated y and dy.
289     
290     Because y and dy cannot be calculated and quanted separately, we
291     always calculate both, then check for user override. */
292 MAKE_SCHEME_CALLBACK (Beam, after_line_breaking, 1);
293 SCM
294 Beam::after_line_breaking (SCM smob)
295 {
296   Grob *me = unsmob_grob (smob);
297   
298   /* Copy to mutable list. */
299   SCM s = ly_deep_copy (me->get_grob_property ("positions"));
300   me->set_grob_property ("positions", s);
301
302   if (ly_car (s) != SCM_BOOL_F)
303     return SCM_UNSPECIFIED;
304
305   SCM callbacks = me->get_grob_property ("position-callbacks");
306   for (SCM i = callbacks; gh_pair_p (i); i = ly_cdr (i))
307     gh_call1 (ly_car (i), smob);
308
309   return SCM_UNSPECIFIED;
310 }
311
312
313 MAKE_SCHEME_CALLBACK (Beam, least_squares, 1);
314 SCM
315 Beam::least_squares (SCM smob)
316 {
317   Grob *me = unsmob_grob (smob);
318
319   int count = visible_stem_count (me);
320   Interval pos (0, 0);
321   
322   if (count <= 1)
323     {
324       me->set_grob_property ("positions", ly_interval2scm (pos));
325       return SCM_UNSPECIFIED;
326     }
327   
328   Direction dir = Directional_element_interface::get (me);
329
330   Interval ideal (Stem::calc_stem_info (first_visible_stem (me)).idealy_f_,
331                   Stem::calc_stem_info (last_visible_stem (me)).idealy_f_);
332   if (!ideal.delta ())
333     {
334       Interval chord (Stem::chord_start_f (first_visible_stem (me)),
335                       Stem::chord_start_f (last_visible_stem (me)));
336       
337       /* Make simple beam on middle line have small tilt */
338       if (!ideal[LEFT] && chord.delta () && count == 2)
339         {
340           Direction d = (Direction)(sign (chord.delta ()) * dir);
341           pos[d] = gh_scm2double (me->get_grob_property ("thickness")) / 2
342             * dir;
343           pos[-d] = - pos[d];
344         }
345       else
346         pos = ideal;
347     }
348   else
349     {
350       Array<Offset> ideals;
351
352       // ugh -> use commonx
353       Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
354       Link_array<Item> stems=
355         Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
356
357       for (int i=0; i < stems.size (); i++)
358         {
359           Item* s = stems[i];
360           if (Stem::invisible_b (s))
361             continue;
362           ideals.push (Offset (s->relative_coordinate (0, X_AXIS) - x0,
363                                Stem::calc_stem_info (s).idealy_f_));
364         }
365       Real y; 
366       Real dydx;
367       minimise_least_squares (&dydx, &y, ideals);
368
369       Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
370       Real dy = dydx * dx;
371       me->set_grob_property ("least-squares-dy", gh_double2scm (dy * dir));
372
373       pos = Interval (y*dir, (y+dy) * dir);
374     }
375
376   me->set_grob_property ("positions", ly_interval2scm (pos));
377   return SCM_UNSPECIFIED;
378 }
379
380 MAKE_SCHEME_CALLBACK (Beam, check_concave, 1);
381 SCM
382 Beam::check_concave (SCM smob)
383 {
384   Grob *me = unsmob_grob (smob);
385
386   Link_array<Item> stems = 
387     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
388
389   for (int i = 0; i < stems.size ();)
390     {
391       if (Stem::invisible_b (stems[i]))
392         stems.del (i);
393       else
394         i++;
395     }
396   
397   if (stems.size () < 3)
398     return SCM_UNSPECIFIED;
399
400   /* Concaveness try #2: Sum distances of inner noteheads that
401      fall outside the interval of the two outer noteheads */
402   Real concave = 0;
403   Interval iv (Stem::chord_start_f (stems[0]),
404                Stem::chord_start_f (stems.top ()));
405   
406   if (iv[MAX] < iv[MIN])
407     iv.swap ();
408   
409   for (int i = 1; i < stems.size () - 1; i++)
410     {
411       Real c = 0;
412       Real f = Stem::chord_start_f (stems[i]);
413       if ((c = f - iv[MAX]) > 0)
414         concave += c;
415       else if ((c = f - iv[MIN]) < 0)
416         concave += c;
417     }
418   concave *= Directional_element_interface::get (me);
419       
420   Real concaveness = concave / (stems.size () - 2);
421   /* ugh: this is the a kludge to get input/regression/beam-concave.ly
422      to behave as baerenreiter. */
423   concaveness /= (stems.size () - 2);
424   
425   Real r = gh_scm2double (me->get_grob_property ("concaveness-threshold"));
426
427   /* TODO: some sort of damping iso -> plain horizontal */
428   if (concaveness > r)
429     {
430       Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
431       Real r = pos.linear_combination (0);
432       me->set_grob_property ("positions", ly_interval2scm (Interval (r, r)));
433       me->remove_grob_property ("least-squares-dy");
434     }
435
436   return SCM_UNSPECIFIED;
437 }
438
439 /* This neat trick is by Werner Lemberg,
440    damped = tanh (slope)
441    corresponds with some tables in [Wanske] CHECKME */
442 MAKE_SCHEME_CALLBACK (Beam, slope_damping, 1);
443 SCM
444 Beam::slope_damping (SCM smob)
445 {
446   Grob *me = unsmob_grob (smob);
447
448   if (visible_stem_count (me) <= 1)
449     return SCM_UNSPECIFIED;
450
451   SCM s = me->get_grob_property ("damping"); 
452   int damping = gh_scm2int (s);
453
454   if (damping)
455     {
456       Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
457       Real dy = pos.delta ();
458       
459       // ugh -> use commonx
460       Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS)
461         - first_visible_stem (me)->relative_coordinate (0, X_AXIS);
462       Real dydx = dy && dx ? dy/dx : 0;
463       dydx = 0.6 * tanh (dydx) / damping;
464
465       Real damped_dy = dydx * dx;
466       pos[LEFT] += (dy - damped_dy) / 2;
467       pos[RIGHT] -= (dy - damped_dy) / 2;
468       
469       me->set_grob_property ("positions", ly_interval2scm (pos));
470     }
471     return SCM_UNSPECIFIED;
472 }
473
474
475 /* Prevent interference from stafflines. */
476 Interval
477 Beam::quantise_interval (Grob *me, Interval pos, Direction quant_dir)
478 {
479   int multiplicity = get_multiplicity (me);
480
481   Real staff_space = Staff_symbol_referencer::staff_space (me);
482   Real thick = me->paper_l ()->get_var ("stafflinethickness");
483   Direction dir = Directional_element_interface::get (me);
484   Real dy = pos.delta ();
485
486   Drul_array<Interval> bounds;
487   Direction d = LEFT;
488   do
489     {
490       SCM proc = d == LEFT
491         ? me->get_grob_property ("left-position-quant-function")
492         : me->get_grob_property ("right-position-quant-function");
493       
494       SCM quants = scm_apply (proc,
495                               me->self_scm (),
496                               scm_list_n (gh_int2scm (multiplicity),
497                                           gh_double2scm (dir),
498                                           gh_double2scm (dy),
499                                           gh_double2scm (thick / staff_space),
500                                           /* HUH? */
501                                           SCM_EOL,
502                                           SCM_UNDEFINED));
503       
504       Array<Real> a;
505       for (SCM i = quants; gh_pair_p (i); i = ly_cdr (i))
506         a.push (gh_scm2double (ly_car (i)));
507       
508       if (a.size () <= 1)
509         return pos;
510       
511       bounds[d] = quantise_iv (a, pos[d]*dir/staff_space) * staff_space;
512     }
513   while (flip (&d) != LEFT);
514   
515   Real ady = abs (dy);
516
517   // quant direction hints disabled for now
518   int q = 0;//(int)quant_dir;
519
520   /* TODO: make smart choice, find best left/right quants pair.
521
522      Slope should never be steeper than least_squares (before damping)
523      (save that value?)
524      Slope should never be reduced to zero.
525    */
526   SCM s = me->get_grob_property ("least-squares-dy");
527   Real lsdy = gh_number_p (s) ? gh_scm2double (s) : 0;
528     
529   //  Interval qpos (0, 1000 * sign (dy));
530   Interval qpos;
531   Real epsilon = staff_space / 10;
532   Direction ldir = LEFT;
533   do
534     {
535       Direction rdir = LEFT;
536       do
537         {
538           Interval i (bounds[LEFT][ldir]*dir, bounds[RIGHT][rdir]*dir);
539           if ((!lsdy
540                || (abs (i.delta ()) <= abs (lsdy) + epsilon
541                    && sign (i.delta ()) == sign (lsdy)))
542               && (abs (abs (i.delta ()) - ady)
543                   <= abs (abs (qpos.delta ()) - ady))
544               && sign (i.delta ()) == sign (pos.delta ())
545               && (!q
546                   || (i[LEFT]*q >= pos[LEFT]*q && i[RIGHT]*q
547                       >= pos[RIGHT]*q)))
548             qpos = i;
549         }
550       while (flip (&rdir) != LEFT);
551     }
552   while (flip (&ldir) != LEFT);
553   
554   return qpos;
555 }
556
557
558 /* Quantise vertical position (left and right) of beam.
559    Generalisation of [Ross]. */
560 MAKE_SCHEME_CALLBACK (Beam, quantise_position, 1);
561 SCM
562 Beam::quantise_position (SCM smob)
563 {
564   Grob *me = unsmob_grob (smob);
565
566   Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
567   Real y_shift = check_stem_length_f (me, pos);
568   pos += y_shift;
569   Real staff_space = Staff_symbol_referencer::staff_space (me);
570
571   Direction dir = Directional_element_interface::get (me);
572   for (int i = 0; i < 10; i++)
573     {
574       Interval qpos = quantise_interval (me, pos, CENTER);
575       // how to check for uninitised interval,  (inf, -inf)?
576       if (qpos[LEFT] < 1000)
577         {
578           y_shift = check_stem_length_f (me, qpos);
579           if (y_shift * dir < staff_space / 2)
580             {
581               pos = qpos;
582               break;
583             }
584         }
585       pos += ((i + 1) * ((i % 2) * -2 + 1)) *  dir * staff_space / 4;
586     }
587       
588   
589   me->set_grob_property ("positions", ly_interval2scm (pos));
590   set_stem_lengths (me);
591
592 #if 0  
593   pos = ly_scm2interval (me->get_grob_property ("positions"));
594   
595   y_shift = check_stem_length_f (me, pos);
596
597   Real half_space = Staff_symbol_referencer::staff_space (me) / 2;
598   /* HMMM */
599   if (y_shift > half_space / 4)
600     {
601       pos += y_shift;
602       int quant_dir = 0;
603       /* for significantly lengthened or shortened stems,
604          request quanting the other way.
605          HMMM */
606       if (abs (y_shift) > half_space / 2)
607         quant_dir = sign (y_shift) * Directional_element_interface::get (me);
608       pos = quantise_interval (me, pos, (Direction)quant_dir);
609     }
610   
611   me->set_grob_property ("positions", ly_interval2scm (pos));
612 #endif
613   
614   return SCM_UNSPECIFIED;
615 }
616
617 MAKE_SCHEME_CALLBACK (Beam, end_after_line_breaking, 1);
618 SCM
619 Beam::end_after_line_breaking (SCM smob)
620 {
621   Grob *me = unsmob_grob (smob);
622   set_stem_lengths (me);
623   
624   return SCM_UNSPECIFIED;
625 }
626
627 Real
628 Beam::calc_stem_y_f (Grob *me, Item* s, Interval pos)
629 {
630   int beam_multiplicity = get_multiplicity (me);
631   int stem_multiplicity = (Stem::flag_i (s) - 2) >? 0;
632
633   SCM space_proc = me->get_grob_property ("space-function");
634   SCM space = gh_call1 (space_proc, gh_int2scm (beam_multiplicity));
635
636   Real thick = gh_scm2double (me->get_grob_property ("thickness"));
637   Real interbeam_f = gh_scm2double (space);
638
639   // ugh -> use commonx
640   Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
641   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
642   Real dy = pos.delta ();
643   Real stem_y = (dy && dx
644                  ? (s->relative_coordinate (0, X_AXIS) - x0) / dx
645                  * dy
646                  : 0) + pos[LEFT];
647
648   /* knee */
649   Direction dir  = Directional_element_interface::get (me);
650   Direction sdir = Directional_element_interface::get (s);
651   
652   /* knee */
653   if (dir!= sdir)
654     {
655       stem_y -= dir * (thick / 2 + (beam_multiplicity - 1) * interbeam_f);
656       
657       // huh, why not for first visible?
658       if (Staff_symbol_referencer::staff_symbol_l (s)
659           != Staff_symbol_referencer::staff_symbol_l (last_visible_stem (me)))
660         stem_y += Directional_element_interface::get (me)
661           * (beam_multiplicity - stem_multiplicity) * interbeam_f;
662     }
663
664   return stem_y;
665 }
666
667 /* Make very sure that we don't have stems that are too short.
668    Try our best not to have stems that are too long (think: knees).
669    
670    Optionally (testing): try to lengthen more, to reach more ideal
671    stem lengths */
672 Real
673 Beam::check_stem_length_f (Grob *me, Interval pos)
674 {
675   Real shorten = 0;
676   Real lengthen = 0;
677   Direction dir = Directional_element_interface::get (me);
678
679   Link_array<Item> stems=
680     Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
681
682   bool knee = false;
683   int ideal_lengthen_count = 0;
684   Real ideal_lengthen = 0;
685   int ideal_shorten_count = 0;
686   Real ideal_shorten = 0;
687   
688   for (int i=0; i < stems.size (); i++)
689     {
690       Item* s = stems[i];
691       if (Stem::invisible_b (s))
692         continue;
693
694       knee |= dir != Directional_element_interface::get (s);
695
696       Real stem_y = calc_stem_y_f (me, s, pos);
697       
698       stem_y *= dir;
699       Stem_info info = Stem::calc_stem_info (s);
700
701       shorten = shorten <? info.maxy_f_ - stem_y;
702       lengthen = lengthen >? info.miny_f_ - stem_y;
703
704       if (info.idealy_f_ - stem_y > 0)
705         {
706 #if 0     
707           ideal_lengthen += info.idealy_f_ - stem_y;
708           ideal_lengthen_count++;
709 #else
710           ideal_lengthen = ideal_lengthen >? info.idealy_f_ - stem_y;
711           ideal_lengthen_count = 1;
712 #endif    
713         }
714       else if (info.idealy_f_ - stem_y < 0)
715         {
716 #if 0     
717           ideal_shorten += info.idealy_f_ - stem_y;
718           ideal_shorten_count++;
719 #else
720           ideal_shorten = ideal_shorten <? info.idealy_f_ - stem_y;
721           ideal_shorten_count = 1;
722 #endif    
723         }
724     }
725   
726   if (lengthen && shorten)
727     me->warning (_ ("weird beam vertical offset"));
728
729   if (ideal_lengthen_count)
730     lengthen = (ideal_lengthen / ideal_lengthen_count) >? lengthen;
731   if (knee && ideal_shorten_count)
732     shorten = (ideal_shorten / ideal_shorten_count) <? shorten;
733
734   if (lengthen && shorten)
735     return dir * (lengthen + shorten);
736     
737   return dir * (shorten ? shorten : lengthen);
738 }
739
740 /*
741   Hmm.  At this time, beam position and slope are determined.  Maybe,
742   stem directions and length should set to relative to the chord's
743   position of the beam.  */
744 void
745 Beam::set_stem_lengths (Grob *me)
746 {
747   Link_array<Item> stems=
748     Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
749
750   if (stems.size () <= 1)
751     return;
752   
753   Grob *common = me->common_refpoint (stems[0], Y_AXIS);
754   for (int i=1; i < stems.size (); i++)
755     if (!Stem::invisible_b (stems[i]))
756       common = common->common_refpoint (stems[i], Y_AXIS);
757
758   Direction dir = Directional_element_interface::get (me);
759   Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
760   Real staff_space = Staff_symbol_referencer::staff_space (me);
761   Real thick = gh_scm2double (me->get_grob_property ("thickness"));
762   bool ps_testing = to_boolean (ly_symbol2scm ("ps-testing"));
763   for (int i=0; i < stems.size (); i++)
764     {
765       Item* s = stems[i];
766       if (Stem::invisible_b (s))
767         continue;
768
769       Real stem_y = calc_stem_y_f (me, s, pos);
770
771       // doesn't play well with dvips
772       if (ps_testing)
773         if (Stem::get_direction (s) == dir)
774           stem_y += Stem::get_direction (s) * thick / 2;
775       
776       /* caution: stem measures in staff-positions */
777       Real id = me->relative_coordinate (common, Y_AXIS)
778         - stems[i]->relative_coordinate (common, Y_AXIS);
779       Stem::set_stemend (s, (stem_y + id) / staff_space * 2);
780     }
781 }
782
783 void
784 Beam::set_beaming (Grob *me, Beaming_info_list *beaming)
785 {
786   Link_array<Grob> stems=
787     Pointer_group_interface__extract_grobs (me, (Grob *)0, "stems");
788   
789   Direction d = LEFT;
790   for (int i=0; i  < stems.size (); i++)
791     {
792       do
793         {
794           /* Don't overwrite user override (?) */
795           if (Stem::beam_count (stems[i], d) == -1
796               /* Don't set beaming for outside of outer stems */
797               && ! (d == LEFT && i == 0)
798               && ! (d == RIGHT && i == stems.size () -1))
799             {
800               int b = beaming->infos_.elem (i).beams_i_drul_[d];
801               Stem::set_beaming (stems[i], b, d);
802             }
803         }
804       while (flip (&d) != LEFT);
805     }
806 }
807
808
809
810 /*
811   beams to go with one stem.
812
813   FIXME: clean me up.
814   */
815 Molecule
816 Beam::stem_beams (Grob *me, Item *here, Item *next, Item *prev, Real dydx)
817 {
818   // ugh -> use commonx
819   if ((next
820        && !(next->relative_coordinate (0, X_AXIS)
821             > here->relative_coordinate (0, X_AXIS)))
822       || (prev
823           && !(prev->relative_coordinate (0, X_AXIS)
824                < here->relative_coordinate (0, X_AXIS))))
825     programming_error ("Beams are not left-to-right");
826
827   int multiplicity = get_multiplicity (me);
828
829   SCM space_proc = me->get_grob_property ("space-function");
830   SCM space = gh_call1 (space_proc, gh_int2scm (multiplicity));
831
832   Real thick = gh_scm2double (me->get_grob_property ("thickness"));
833   Real interbeam_f = gh_scm2double (space);
834     
835   Real bdy = interbeam_f;
836   
837   Molecule leftbeams;
838   Molecule rightbeams;
839
840   Real nw_f;
841   if (!Stem::first_head (here))
842     nw_f = 0;
843   else {
844     int t = Stem::type_i (here); 
845
846     SCM proc = me->get_grob_property ("flag-width-function");
847     SCM result = gh_call1 (proc, gh_int2scm (t));
848     nw_f = gh_scm2double (result);
849   }
850
851
852   Direction dir = Directional_element_interface::get (me);
853
854   /* [Tremolo] beams on whole notes may not have direction set? */
855  if (dir == CENTER)
856     dir = Directional_element_interface::get (here);
857
858
859   /* half beams extending to the left. */
860   if (prev)
861     {
862       int lhalfs= lhalfs = Stem::beam_count (here, LEFT)
863         - Stem::beam_count (prev, RIGHT);
864       int lwholebeams= Stem::beam_count (here, LEFT)
865         <? Stem::beam_count (prev, RIGHT);
866       
867       /* Half beam should be one note-width,
868          but let's make sure two half-beams never touch */
869
870       // FIXME: TODO (check) stem width / sloped beams
871       Real w = here->relative_coordinate (0, X_AXIS)
872         - prev->relative_coordinate (0, X_AXIS);
873       Real stem_w = gh_scm2double (prev->get_grob_property ("thickness"))
874         // URG
875         * me->paper_l ()->get_var ("stafflinethickness");
876
877       w = w/2 <? nw_f;
878       Molecule a;
879       if (lhalfs)               // generates warnings if not
880         a =  Lookup::beam (dydx, w + stem_w, thick);
881       a.translate (Offset (-w, -w * dydx));
882       a.translate_axis (-stem_w/2, X_AXIS);
883       for (int j = 0; j  < lhalfs; j++)
884         {
885           Molecule b (a);
886           b.translate_axis (-dir * bdy * (lwholebeams+j), Y_AXIS);
887           leftbeams.add_molecule (b);
888         }
889     }
890
891   if (next)
892     {
893       int rhalfs  = Stem::beam_count (here, RIGHT)
894         - Stem::beam_count (next, LEFT);
895       int rwholebeams= Stem::beam_count (here, RIGHT)
896         <? Stem::beam_count (next, LEFT);
897
898       Real w = next->relative_coordinate (0, X_AXIS)
899         - here->relative_coordinate (0, X_AXIS);
900
901       Real stem_w = gh_scm2double (next->get_grob_property ("thickness"))
902         // URG
903         * me->paper_l ()->get_var ("stafflinethickness");
904
905       Molecule a = Lookup::beam (dydx, w + stem_w, thick);
906       a.translate_axis (- stem_w/2, X_AXIS);
907       int j = 0;
908       Real gap_f = 0;
909       
910       SCM gap = me->get_grob_property ("gap");
911       if (gh_number_p (gap))
912         {
913           int gap_i = gh_scm2int ((gap));
914           int nogap = rwholebeams - gap_i;
915           
916           for (; j  < nogap; j++)
917             {
918               Molecule b (a);
919               b.translate_axis (-dir  * bdy * j, Y_AXIS);
920               rightbeams.add_molecule (b);
921             }
922           if (Stem::invisible_b (here))
923             gap_f = nw_f;
924           else
925             gap_f = nw_f / 2;
926           w -= 2 * gap_f;
927           a = Lookup::beam (dydx, w + stem_w, thick);
928         }
929
930       for (; j  < rwholebeams; j++)
931         {
932           Molecule b (a);
933           Real tx = 0;
934           if (Stem::invisible_b (here))
935             // ugh, see chord-tremolo.ly
936             tx = (-dir + 1) / 2 * nw_f * 1.5 + gap_f/4;
937           else
938             tx = gap_f;
939           b.translate (Offset (tx, -dir * bdy * j));
940           rightbeams.add_molecule (b);
941         }
942
943       w = w/2 <? nw_f;
944       if (rhalfs)
945         a = Lookup::beam (dydx, w, thick);
946
947       for (; j  < rwholebeams + rhalfs; j++)
948         {
949           Molecule b (a);
950           b.translate_axis (- dir * bdy * j, Y_AXIS);
951           rightbeams.add_molecule (b);
952         }
953
954     }
955   leftbeams.add_molecule (rightbeams);
956
957   /* Does beam quanting think  of the asymetry of beams? 
958      Refpoint is on bottom of symbol. (FIXTHAT) --hwn. */
959   return leftbeams;
960 }
961
962 MAKE_SCHEME_CALLBACK (Beam, brew_molecule, 1);
963 SCM
964 Beam::brew_molecule (SCM smob)
965 {
966   Grob *me =unsmob_grob (smob);
967
968   Molecule mol;
969   if (!gh_pair_p (me->get_grob_property ("stems")))
970     return SCM_EOL;
971   Real x0, dx;
972   Link_array<Item>stems = 
973     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");  
974   if (visible_stem_count (me))
975     {
976       // ugh -> use commonx
977       x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
978       dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
979     }
980   else
981     {
982       x0 = stems[0]->relative_coordinate (0, X_AXIS);
983       dx = stems.top ()->relative_coordinate (0, X_AXIS) - x0;
984     }
985
986   Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
987   Real dy = pos.delta ();
988   Real dydx = dy && dx ? dy/dx : 0;
989
990   for (int i=0; i < stems.size (); i++)
991     {
992       Item *item = stems[i];
993       Item *prev = (i > 0)? stems[i-1] : 0;
994       Item *next = (i < stems.size ()-1) ? stems[i+1] :0;
995
996       Molecule sb = stem_beams (me, item, next, prev, dydx);
997       Real x = item->relative_coordinate (0, X_AXIS) - x0;
998       sb.translate (Offset (x, x * dydx + pos[LEFT]));
999       mol.add_molecule (sb);
1000     }
1001   
1002   mol.translate_axis (x0 
1003                       - dynamic_cast<Spanner*> (me)
1004                       ->get_bound (LEFT)->relative_coordinate (0, X_AXIS),
1005                       X_AXIS);
1006
1007   return mol.smobbed_copy ();
1008 }
1009
1010 int
1011 Beam::forced_stem_count (Grob *me) 
1012 {
1013   Link_array<Item>stems = 
1014     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
1015   int f = 0;
1016   for (int i=0; i < stems.size (); i++)
1017     {
1018       Item *s = stems[i];
1019
1020       if (Stem::invisible_b (s))
1021         continue;
1022
1023       if (((int)Stem::chord_start_f (s)) 
1024         && (Stem::get_direction (s) != Stem::get_default_dir (s)))
1025         f++;
1026     }
1027   return f;
1028 }
1029
1030
1031
1032
1033 /* TODO:
1034    use filter and standard list functions.
1035  */
1036 int
1037 Beam::visible_stem_count (Grob *me) 
1038 {
1039   Link_array<Item>stems = 
1040     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
1041   int c = 0;
1042   for (int i = stems.size (); i--;)
1043     {
1044       if (!Stem::invisible_b (stems[i]))
1045         c++;
1046     }
1047   return c;
1048 }
1049
1050 Item*
1051 Beam::first_visible_stem (Grob *me) 
1052 {
1053   Link_array<Item>stems = 
1054     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
1055   
1056   for (int i = 0; i < stems.size (); i++)
1057     {
1058       if (!Stem::invisible_b (stems[i]))
1059         return stems[i];
1060     }
1061   return 0;
1062 }
1063
1064 Item*
1065 Beam::last_visible_stem (Grob *me) 
1066 {
1067   Link_array<Item>stems = 
1068     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
1069   for (int i = stems.size (); i--;)
1070     {
1071       if (!Stem::invisible_b (stems[i]))
1072         return stems[i];
1073     }
1074   return 0;
1075 }
1076
1077
1078 /*
1079   [TODO]
1080   handle rest under beam (do_post: beams are calculated now)
1081   what about combination of collisions and rest under beam.
1082
1083   Should lookup
1084     
1085     rest -> stem -> beam -> interpolate_y_position ()
1086 */
1087 MAKE_SCHEME_CALLBACK (Beam, rest_collision_callback, 2);
1088 SCM
1089 Beam::rest_collision_callback (SCM element_smob, SCM axis)
1090 {
1091   Grob *rest = unsmob_grob (element_smob);
1092   Axis a = (Axis) gh_scm2int (axis);
1093   
1094   assert (a == Y_AXIS);
1095
1096   Grob *st = unsmob_grob (rest->get_grob_property ("stem"));
1097   Grob *stem = st;
1098   if (!stem)
1099     return gh_double2scm (0.0);
1100   Grob *beam = unsmob_grob (stem->get_grob_property ("beam"));
1101   if (!beam
1102       || !Beam::has_interface (beam)
1103       || !Beam::visible_stem_count (beam))
1104     return gh_double2scm (0.0);
1105
1106   // make callback for rest from this.
1107   // todo: make sure this calced already.
1108
1109   //  Interval pos = ly_scm2interval (beam->get_grob_property ("positions"));
1110   Interval pos (0, 0);
1111   SCM s = beam->get_grob_property ("positions");
1112   if (gh_pair_p (s) && gh_number_p (ly_car (s)))
1113     pos = ly_scm2interval (s);
1114
1115   Real dy = pos.delta ();
1116   // ugh -> use commonx
1117   Real x0 = first_visible_stem (beam)->relative_coordinate (0, X_AXIS);
1118   Real dx = last_visible_stem (beam)->relative_coordinate (0, X_AXIS) - x0;
1119   Real dydx = dy && dx ? dy/dx : 0;
1120   
1121   Direction d = Stem::get_direction (stem);
1122   Real beamy = (stem->relative_coordinate (0, X_AXIS) - x0) * dydx + pos[LEFT];
1123
1124   Real staff_space =   Staff_symbol_referencer::staff_space (rest);
1125
1126   
1127   Real rest_dim = rest->extent (rest, Y_AXIS)[d]*2.0 / staff_space; // refp??
1128
1129   Real minimum_dist
1130     = gh_scm2double (rest->get_grob_property ("minimum-beam-collision-distance"));
1131   Real dist =
1132     minimum_dist +  -d  * (beamy - rest_dim) >? 0;
1133
1134   int stafflines = Staff_symbol_referencer::line_count (rest);
1135
1136   // move discretely by half spaces.
1137   int discrete_dist = int (ceil (dist));
1138
1139   // move by whole spaces inside the staff.
1140   if (discrete_dist < stafflines+1)
1141     discrete_dist = int (ceil (discrete_dist / 2.0)* 2.0);
1142
1143   return gh_double2scm (-d *  discrete_dist);
1144 }
1145
1146
1147 bool
1148 Beam::has_interface (Grob *me)
1149 {
1150   return me->has_interface (ly_symbol2scm ("beam-interface"));
1151 }
1152