]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
5b50831fca15d6a80e39da9839420cd8e0edc6be
[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--2000 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7     Jan Nieuwenhuizen <janneke@gnu.org>
8
9 */
10
11 /*
12   [TODO]
13     * less hairy code
14     * move paper vars to scm
15
16     remove *-hs variables.
17 */
18
19
20 #include <math.h> // tanh.
21 #include "directional-element-interface.hh"
22 #include "beaming.hh"
23 #include "dimensions.hh"
24 #include "beam.hh"
25 #include "misc.hh"
26 #include "debug.hh"
27 #include "least-squares.hh"
28 #include "stem.hh"
29 #include "paper-def.hh"
30 #include "lookup.hh"
31 #include "group-interface.hh"
32 #include "staff-symbol-referencer.hh"
33 #include "cross-staff.hh"
34
35 Beam::Beam (SCM s)
36   : Spanner (s)
37 {
38   Pointer_group_interface g (this, "stems");
39   g.set_interface ();
40
41   set_elt_property ("height", gh_int2scm (0)); // ugh.
42   set_elt_property ("y-position" ,gh_int2scm (0));
43 }
44
45 void
46 Beam::add_stem (Stem*s)
47 {
48   Pointer_group_interface gi (this, "stems");
49   gi.add_element (s);
50   
51   s->add_dependency (this);
52
53   assert (!s->beam_l ());
54   s->set_elt_pointer ("beam", self_scm_);
55
56   add_bound_item (this, s);
57 }
58
59 int
60 Beam::get_multiplicity () const
61 {
62   int m = 0;
63   for (SCM s = get_elt_pointer ("stems"); gh_pair_p (s); s = gh_cdr (s))
64     {
65       Score_element * sc = unsmob_element (gh_car (s));
66
67       if (Stem * st = dynamic_cast<Stem*> (sc))
68         m = m >? st->beam_count (LEFT) >? st->beam_count (RIGHT);
69     }
70   return m;
71 }
72
73 /*
74   After pre-processing all directions should be set.
75   Several post-processing routines (stem, slur, script) need stem/beam
76   direction.
77   Currenly, this means that beam has set all stem's directions.
78   [Alternatively, stems could set its own directions, according to
79    their beam, during 'final-pre-processing'.]
80  */
81 GLUE_SCORE_ELEMENT(Beam,before_line_breaking);
82 SCM
83 Beam::member_before_line_breaking ()
84 {
85   // Why?
86   if (visible_stem_count () < 2)
87     {
88       warning (_ ("beam has less than two stems"));
89
90     }
91
92   if (!Directional_element_interface (this).get ())
93     Directional_element_interface (this).set (get_default_dir ());
94
95   auto_knees ();
96   set_stem_directions ();
97   set_stem_shorten ();
98
99   return SCM_EOL;
100 }
101
102 /*
103  FIXME
104  */
105 Direction
106 Beam::get_default_dir () const
107 {
108   Drul_array<int> total;
109   total[UP]  = total[DOWN] = 0;
110   Drul_array<int> count; 
111   count[UP]  = count[DOWN] = 0;
112   Direction d = DOWN;
113
114   for (int i=0; i <stem_count (); i++)
115     do { // HUH -- waar slaat dit op?
116       Stem *s = stem (i);
117       Direction sd = Directional_element_interface (s).get ();
118       int current = sd  ? (1 + d * sd)/2
119         : s->get_center_distance ((Direction)-d);
120
121       if (current)
122         {
123           total[d] += current;
124           count[d] ++;
125         }
126
127     } while (flip(&d) != DOWN);
128   
129
130   SCM s = scm_eval (gh_list (ly_symbol2scm ("beam-dir-algorithm"),
131                              ly_quote_scm (gh_cons (gh_int2scm (count[UP]),
132                                                     gh_int2scm (count[DOWN]))),
133                              ly_quote_scm (gh_cons (gh_int2scm (total[UP]),
134                                                     gh_int2scm (total[DOWN]))),
135                              SCM_UNDEFINED));
136   if (gh_number_p (s) && gh_scm2int (s))
137     return to_dir (s);
138   
139   /*
140     If dir is not determined: get from paper
141   */
142   return (Direction)(int)
143     paper_l ()->get_var ("stem_default_neutral_direction");
144 }
145
146
147 /*
148   Set all stems with non-forced direction to beam direction.
149   Urg: non-forced should become `without/with unforced' direction,
150        once stem gets cleaned-up.
151  */
152 void
153 Beam::set_stem_directions ()
154 {
155   Direction d = Directional_element_interface (this).get ();
156   for (int i=0; i <stem_count (); i++)
157     {
158       Stem *s = stem (i);
159       SCM force = s->remove_elt_property ("dir-forced");
160       if (!gh_boolean_p (force) || !gh_scm2bool (force))
161         Directional_element_interface (s).set (d);
162     }
163
164
165 void
166 Beam::auto_knees ()
167 {
168   if (!auto_knee ("auto-interstaff-knee-gap", true))
169     auto_knee ("auto-knee-gap", false);
170 }
171
172 /*
173   Simplistic auto-knees; only consider vertical gap between two
174   adjacent chords.
175
176   `Forced' stem directions are ignored.  If you don't want auto-knees,
177   don't set, or unset autoKneeGap/autoInterstaffKneeGap.
178  */
179 bool
180 Beam::auto_knee (String gap_str, bool interstaff_b)
181 {
182   bool knee_b = false;
183   int knee_y = 0;
184   SCM gap = get_elt_property (gap_str);
185   Direction d = Directional_element_interface (this).get ();
186   
187   if (gh_number_p (gap))
188     {
189       int auto_gap_i = gh_scm2int (gap);
190       for (int i=1; i < stem_count (); i++)
191         {
192           bool is_b = (bool)(calc_interstaff_dist (stem (i), this) 
193             - calc_interstaff_dist (stem (i-1), this));
194           int l_y = (int)(stem (i-1)->head_positions()[d])
195             + (int)calc_interstaff_dist (stem (i-1), this);
196           int r_y = (int)(stem (i)->head_positions()[d])
197             + (int)calc_interstaff_dist (stem (i), this);
198           int gap_i = r_y - l_y;
199
200           if ((abs (gap_i) >= auto_gap_i) && (!interstaff_b || is_b))
201             {
202               knee_y = (r_y + l_y) / 2;
203               knee_b = true;
204               break;
205             }
206         }
207     }
208   if (knee_b)
209     {
210       for (int i=0; i < stem_count (); i++)
211         {
212           Item *s = stem(i);      
213           int y = (int)(stem (i)->head_positions()[d])
214             + (int)calc_interstaff_dist (s, this);
215
216
217           Directional_element_interface (s).set (y < knee_y ? UP : DOWN);
218           s->set_elt_property ("dir-forced", SCM_BOOL_T);
219         }
220     }
221   return knee_b;
222 }
223
224 /*
225  Set stem's shorten property if unset.
226  TODO:
227     take some y-position (chord/beam/nearest?) into account
228     scmify forced-fraction
229  */
230 void
231 Beam::set_stem_shorten ()
232 {
233   if (!visible_stem_count ())
234     return;
235
236   Real forced_fraction = forced_stem_count () / visible_stem_count ();
237   if (forced_fraction < 0.5)
238     return;
239
240   int multiplicity = get_multiplicity ();
241
242   // grace stems?
243   SCM shorten = scm_eval (ly_symbol2scm ("beamed-stem-shorten"));
244
245   if (shorten == SCM_EOL)
246     return;
247
248   int sz = scm_ilength (shorten);
249   
250   Staff_symbol_referencer_interface st (this);
251   Real staff_space = st.staff_space ();
252   SCM shorten_elt = scm_list_ref (shorten, gh_int2scm (multiplicity <? (sz - 1)));
253   Real shorten_f = gh_scm2double (shorten_elt) * staff_space;
254
255   /* cute, but who invented this -- how to customise ? */
256   if (forced_fraction < 1)
257     shorten_f /= 2;
258
259   for (int i=0; i < stem_count (); i++)
260     {
261       Stem* s = stem (i);
262       if (s->invisible_b ())
263         continue;
264       if (gh_number_p (s->get_elt_property ("shorten")))
265         s->set_elt_property ("shorten", gh_double2scm (shorten_f));
266     }
267 }
268
269 /*
270   Set elt properties height and y-position if not set.
271   Adjust stem lengths to reach beam.
272  */
273 GLUE_SCORE_ELEMENT(Beam,after_line_breaking);
274 SCM
275 Beam::member_after_line_breaking ()
276 {
277   /* first, calculate y, dy */
278   Real y, dy;
279   calc_default_position_and_height (&y, &dy);
280   if (visible_stem_count ())
281     {
282       if (suspect_slope_b (y, dy))
283         dy = 0;
284
285       Real damped_dy = calc_slope_damping_f (dy);
286       Real quantised_dy = quantise_dy_f (damped_dy);
287
288       y += (dy - quantised_dy) / 2;
289       dy = quantised_dy;
290     }
291   /*
292     until here, we used only stem_info, which acts as if dir=up
293    */
294   y *= Directional_element_interface (this).get ();
295   dy *= Directional_element_interface (this).get ();
296
297   Staff_symbol_referencer_interface st (this);
298   Real half_space = st.staff_space () / 2;
299
300   /* check for user-override of dy */
301   SCM s = remove_elt_property ("height-hs");
302   if (gh_number_p (s))
303     {
304       dy = gh_scm2double (s) * half_space;
305     }
306   set_elt_property ("height", gh_double2scm (dy));
307
308   /* check for user-override of y */
309   s = remove_elt_property ("y-position-hs");
310   if (gh_number_p (s))
311     {
312       y = gh_scm2double (s) * half_space;
313     }
314   else
315     { 
316       /* we can modify y, so we should quantise y */
317       Real y_shift = check_stem_length_f (y, dy);
318       y += y_shift;
319       y = quantise_y_f (y, dy, 0);
320       set_stem_length (y, dy);
321       y_shift = check_stem_length_f (y, dy);
322
323       if (y_shift > half_space / 4)
324         {
325           y += y_shift;
326
327           /*
328             for significantly lengthened or shortened stems,
329             request quanting the other way.
330           */
331           int quant_dir = 0;
332           if (abs (y_shift) > half_space / 2)
333             quant_dir = sign (y_shift) * Directional_element_interface (this).get ();
334           y = quantise_y_f (y, dy, quant_dir);
335         }
336     }
337   // UGH. Y is not in staff position unit?
338   // Ik dacht datwe daar juist van weg wilden?
339   set_stem_length (y, dy);
340   set_elt_property ("y-position", gh_double2scm (y));
341
342
343   return SCM_UNDEFINED;
344 }
345
346 /*
347   See Documentation/tex/fonts.doc
348  */
349 void
350 Beam::calc_default_position_and_height (Real* y, Real* dy) const
351 {
352   *y = 0;
353   *dy = 0;  
354   if (visible_stem_count () <= 1)
355     return;
356
357   Real first_ideal = first_visible_stem ()->calc_stem_info ().idealy_f_;
358   if (first_ideal == last_visible_stem ()->calc_stem_info ().idealy_f_)
359     {
360       *dy = 0;
361       *y = first_ideal;
362       return;
363     }
364
365   Array<Offset> ideals;
366   Real x0 = first_visible_stem ()->relative_coordinate (0, X_AXIS);
367   for (int i=0; i < stem_count (); i++)
368     {
369       Stem* s = stem (i);
370       if (s->invisible_b ())
371         continue;
372       ideals.push (Offset (s->relative_coordinate (0, X_AXIS) - x0, 
373                            s->calc_stem_info ().idealy_f_));
374     }
375   Real dydx;
376   minimise_least_squares (&dydx, y, ideals); // duh, takes references
377
378   Real dx = last_visible_stem ()->relative_coordinate (0, X_AXIS) - x0;
379   *dy = dydx * dx;
380 }
381
382 bool
383 Beam::suspect_slope_b (Real y, Real dy) const
384 {
385   /* first, calculate y, dy */
386   /*
387     steep slope running against lengthened stem is suspect
388   */
389   Real first_ideal = first_visible_stem ()->calc_stem_info ().idealy_f_;
390   Real last_ideal = last_visible_stem ()->calc_stem_info ().idealy_f_;
391   Real lengthened = paper_l ()->get_var ("beam_lengthened");
392   Real steep = paper_l ()->get_var ("beam_steep_slope");
393
394   Real dx = last_visible_stem ()->relative_coordinate (0, X_AXIS) - first_visible_stem ()->relative_coordinate (0, X_AXIS);
395   Real dydx = dy && dx ? dy/dx : 0;
396
397   if (((y - first_ideal > lengthened) && (dydx > steep))
398       || ((y + dy - last_ideal > lengthened) && (dydx < -steep)))
399     {
400       return true;
401     }
402   return false;
403 }
404
405 /*
406   This neat trick is by Werner Lemberg,
407   damped = tanh (slope)
408   corresponds with some tables in [Wanske]
409 */
410 Real
411 Beam::calc_slope_damping_f (Real dy) const
412 {
413   SCM damp = get_elt_property ("damping"); // remove?
414   int damping = 1;              // ugh.
415   if (gh_number_p (damp))
416     damping = gh_scm2int (damp);
417
418   if (damping)
419     {
420       Real dx = last_visible_stem ()->relative_coordinate (0, X_AXIS)
421         - first_visible_stem ()->relative_coordinate (0, X_AXIS);
422       Real dydx = dy && dx ? dy/dx : 0;
423       dydx = 0.6 * tanh (dydx) / damping;
424       return dydx * dx;
425     }
426   return dy;
427 }
428
429 Real
430 Beam::calc_stem_y_f (Stem* s, Real y, Real dy) const
431 {
432   Real thick = gh_scm2double (get_elt_property ("beam-thickness"));
433   thick *= paper_l ()->get_var ("staffspace");
434   
435   int beam_multiplicity = get_multiplicity ();
436   int stem_multiplicity = (s->flag_i () - 2) >? 0;
437
438   Real interbeam_f = paper_l ()->interbeam_f (beam_multiplicity);
439   Real x0 = first_visible_stem ()->relative_coordinate (0, X_AXIS);
440   Real dx = last_visible_stem ()->relative_coordinate (0, X_AXIS) - x0;
441   Real stem_y = (dy && dx ? (s->relative_coordinate (0, X_AXIS) - x0) / dx * dy : 0) + y;
442
443   /* knee */
444    Direction dir  = Directional_element_interface(this).get ();
445    Direction sdir = Directional_element_interface (s).get ();
446    
447     /* knee */
448    if (dir!= sdir)
449       {
450        stem_y -= dir 
451         * (thick / 2 + (beam_multiplicity - 1) * interbeam_f);
452
453       Staff_symbol_referencer_interface me (s);
454       Staff_symbol_referencer_interface last (last_visible_stem ());
455       
456       // huh, why not for first visible?
457       if (//(s != first_visible_stem ()) &&
458           me.staff_symbol_l () != last.staff_symbol_l ())
459         stem_y += Directional_element_interface (this).get ()
460           * (beam_multiplicity - stem_multiplicity) * interbeam_f;
461     }
462   return stem_y;
463 }
464
465 Real
466 Beam::check_stem_length_f (Real y, Real dy) const
467 {
468   Real shorten = 0;
469   Real lengthen = 0;
470   Direction dir = Directional_element_interface (this).get ();
471   
472   for (int i=0; i < stem_count (); i++)
473     {
474       Stem* s = stem (i);
475       if (s->invisible_b ())
476         continue;
477
478       Real stem_y = calc_stem_y_f (s, y, dy);
479         
480       stem_y *= dir;
481       Stem_info info = s->calc_stem_info ();
482
483       // if (0 > info.maxy_f_ - stem_y)
484       shorten = shorten <? info.maxy_f_ - stem_y;
485       // if (0 < info.miny_f_ - stem_y)
486       lengthen = lengthen >? info.miny_f_ - stem_y; 
487     }
488
489   if (lengthen && shorten)
490     warning (_ ("weird beam vertical offset"));
491
492   /* when all stems are too short, normal stems win */
493   return dir * ((shorten) ?  shorten : lengthen);
494 }
495
496 /*
497   Hmm.  At this time, beam position and slope are determined.  Maybe,
498   stem directions and length should set to relative to the chord's
499   position of the beam.  */
500 void
501 Beam::set_stem_length (Real y, Real dy)
502 {
503   Staff_symbol_referencer_interface st (this);
504   Real half_space = st.staff_space ()/2;
505   for (int i=0; i < stem_count (); i++)
506     {
507       Stem* s = stem (i);
508       if (s->invisible_b ())
509         continue;
510
511       Real stem_y = calc_stem_y_f (s, y, dy);
512
513       /* caution: stem measures in staff-positions */
514       s->set_stemend ((stem_y + calc_interstaff_dist (s, this)) / half_space);
515     }
516 }
517
518 /*
519   [Ross] (simplification of)
520   Set dy complying with:
521     - zero
522     - thick / 2 + staffline_f / 2
523     - thick + staffline_f
524   + n * staff_space
525 */
526 Real
527 Beam::quantise_dy_f (Real dy) const
528 {
529   Array<Real> a;
530   for (SCM s = scm_eval (ly_symbol2scm ("beam-height-quants")); s !=SCM_EOL; s = gh_cdr (s))
531     a.push (gh_scm2double (gh_car (s)));
532   
533   if (a.size () <= 1)
534     return dy;
535
536   Staff_symbol_referencer_interface st (this);
537   Real staff_space = st.staff_space ();
538   
539   Interval iv = quantise_iv (a, abs (dy)/staff_space) * staff_space;
540   Real q = (abs (dy) - iv[SMALLER] <= iv[BIGGER] - abs (dy))
541     ? iv[SMALLER]
542     : iv[BIGGER];
543   
544   return q * sign (dy);
545 }
546
547 /*
548   Prevent interference from stafflines and beams.
549   See Documentation/tex/fonts.doc
550
551   We only need to quantise the (left) y-position of the beam,
552   since dy is quantised too.
553   if extend_b then stems must *not* get shorter
554  */
555 Real
556 Beam::quantise_y_f (Real y, Real dy, int quant_dir)
557 {
558   int multiplicity = get_multiplicity ();
559   Staff_symbol_referencer_interface st (this);
560   Real staff_space = st.staff_space ();
561   SCM quants = scm_eval (gh_list (ly_symbol2scm ("beam-vertical-position-quants"),
562                                   gh_int2scm (multiplicity),
563                                   gh_double2scm (dy/staff_space),
564                                   SCM_UNDEFINED));
565
566   Array<Real> a;
567
568   for (; quants != SCM_EOL; quants = gh_cdr (quants))
569     a.push (gh_scm2double (gh_car (quants)));
570
571   if (a.size () <= 1)
572     return y;
573
574   Real up_y = Directional_element_interface (this).get () * y;
575   Interval iv = quantise_iv (a, up_y/staff_space) * staff_space;
576
577   Real q = up_y - iv[SMALLER] <= iv[BIGGER] - up_y 
578     ? iv[SMALLER] : iv[BIGGER];
579   if (quant_dir)
580     q = iv[(Direction)quant_dir];
581
582   return q * Directional_element_interface (this).get ();
583 }
584
585 void
586 Beam::set_beaming (Beaming_info_list *beaming)
587 {
588   Direction d = LEFT;
589   for (int i=0; i  < stem_count (); i++)
590     {
591       do
592         {
593           if (stem (i)->beam_count (d) == 0)
594             stem (i)->set_beaming ( beaming->infos_.elem (i).beams_i_drul_[d],d);
595         }
596       while (flip (&d) != LEFT);
597     }
598 }
599
600
601
602 /*
603   beams to go with one stem.
604
605   BURP
606   clean  me up.
607   */
608 Molecule
609 Beam::stem_beams (Stem *here, Stem *next, Stem *prev) const
610 {
611   if ((next && !(next->relative_coordinate (0, X_AXIS) > here->relative_coordinate (0, X_AXIS))) ||
612       (prev && !(prev->relative_coordinate (0, X_AXIS) < here->relative_coordinate (0, X_AXIS))))
613       programming_error ("Beams are not left-to-right");
614
615   Real staffline_f = paper_l ()->get_var ("stafflinethickness");
616   int multiplicity = get_multiplicity ();
617
618
619   Real interbeam_f = paper_l ()->interbeam_f (multiplicity);
620   Real thick = gh_scm2double (get_elt_property ("beam-thickness"));
621   thick *= paper_l ()->get_var ("staffspace");
622     
623   Real bdy = interbeam_f;
624   Real stemdx = staffline_f;
625
626   Real dx = visible_stem_count () ?
627     last_visible_stem ()->relative_coordinate (0, X_AXIS) - first_visible_stem ()->relative_coordinate (0, X_AXIS)
628     : 0.0;
629   Real dy = gh_scm2double (get_elt_property ("height"));
630   Real dydx = dy && dx ? dy/dx : 0;
631
632   Molecule leftbeams;
633   Molecule rightbeams;
634
635   // UGH
636   Real nw_f;
637   if (!here->first_head ())
638     nw_f = 0;
639   else if (here->type_i ()== 1)
640     nw_f = paper_l ()->get_var ("wholewidth");
641   else if (here->type_i () == 2)
642     nw_f = paper_l ()->get_var ("notewidth") * 0.8;
643   else
644     nw_f = paper_l ()->get_var ("quartwidth");
645
646
647   Direction dir = Directional_element_interface (this).get ();
648   
649   /* half beams extending to the left. */
650   if (prev)
651     {
652       int lhalfs= lhalfs = here->beam_count (LEFT) - prev->beam_count (RIGHT);
653       int lwholebeams= here->beam_count (LEFT) <? prev->beam_count (RIGHT) ;
654       /*
655        Half beam should be one note-width, 
656        but let's make sure two half-beams never touch
657        */
658       Real w = here->relative_coordinate (0, X_AXIS) - prev->relative_coordinate (0, X_AXIS);
659       w = w/2 <? nw_f;
660       Molecule a;
661       if (lhalfs)               // generates warnings if not
662         a =  lookup_l ()->beam (dydx, w, thick);
663       a.translate (Offset (-w, -w * dydx));
664       for (int j = 0; j  < lhalfs; j++)
665         {
666           Molecule b (a);
667           b.translate_axis (-dir * bdy * (lwholebeams+j), Y_AXIS);
668           leftbeams.add_molecule (b);
669         }
670     }
671
672   if (next)
673     {
674       int rhalfs  = here->beam_count (RIGHT) - next->beam_count (LEFT);
675       int rwholebeams= here->beam_count (RIGHT) <? next->beam_count (LEFT) ;
676
677       Real w = next->relative_coordinate (0, X_AXIS) - here->relative_coordinate (0, X_AXIS);
678       Molecule a = lookup_l ()->beam (dydx, w + stemdx, thick);
679       a.translate_axis( - stemdx/2, X_AXIS);
680       int j = 0;
681       Real gap_f = 0;
682
683       SCM gap = get_elt_property ("beam-gap");
684       if (gh_number_p (gap))
685         {
686           int gap_i = gh_scm2int ( (gap));
687           int nogap = rwholebeams - gap_i;
688           
689           for (; j  < nogap; j++)
690             {
691               Molecule b (a);
692               b.translate_axis (-dir  * bdy * j, Y_AXIS);
693               rightbeams.add_molecule (b);
694             }
695           // TODO: notehead widths differ for different types
696           gap_f = nw_f / 2;
697           w -= 2 * gap_f;
698           a = lookup_l ()->beam (dydx, w + stemdx, thick);
699         }
700
701       for (; j  < rwholebeams; j++)
702         {
703           Molecule b (a);
704           b.translate (Offset (here->invisible_b () ? 0 : gap_f, -dir * bdy * j));
705           rightbeams.add_molecule (b);
706         }
707
708       w = w/2 <? nw_f;
709       if (rhalfs)
710         a = lookup_l ()->beam (dydx, w, thick);
711
712       for (; j  < rwholebeams + rhalfs; j++)
713         {
714           Molecule b (a);
715           b.translate_axis (- dir * bdy * j, Y_AXIS);
716           rightbeams.add_molecule (b);
717         }
718
719     }
720   leftbeams.add_molecule (rightbeams);
721
722   /*
723     Does beam quanting think  of the asymetry of beams? 
724     Refpoint is on bottom of symbol. (FIXTHAT) --hwn.
725    */
726   return leftbeams;
727 }
728
729 GLUE_SCORE_ELEMENT(Beam,brew_molecule);
730 SCM
731 Beam::member_brew_molecule () const
732 {
733   Molecule mol;
734   if (!stem_count ())
735     return SCM_EOL;
736   Real x0,dx;
737   if (visible_stem_count ())
738     {
739       x0 = first_visible_stem ()->relative_coordinate (0, X_AXIS);
740       dx = last_visible_stem ()->relative_coordinate (0, X_AXIS) - x0;
741     }
742   else
743     {
744       x0 = stem (0)->relative_coordinate (0, X_AXIS);
745       dx = stem_top ()->relative_coordinate (0, X_AXIS) - x0;
746     }
747   
748   
749   Real dy = gh_scm2double (get_elt_property ("height"));
750   Real dydx = dy && dx ? dy/dx : 0;
751   Real y = gh_scm2double (get_elt_property ("y-position"));
752   for (int j=0; j <stem_count (); j++)
753     {
754       Stem *i = stem (j);
755       Stem * prev = (j > 0)? stem (j-1) : 0;
756       Stem * next = (j < stem_count ()-1) ? stem (j+1) :0;
757
758       Molecule sb = stem_beams (i, next, prev);
759       Real x = i->relative_coordinate (0, X_AXIS)-x0;
760       sb.translate (Offset (x, x * dydx + y));
761       mol.add_molecule (sb);
762     }
763   mol.translate_axis (x0 
764     - get_bound (LEFT)->relative_coordinate (0, X_AXIS), X_AXIS);
765
766   return mol.create_scheme ();
767 }
768
769 int
770 Beam::forced_stem_count () const
771 {
772   int f = 0;
773   for (int i=0; i < stem_count (); i++)
774     {
775       Stem *s = stem (i);
776
777       if (s->invisible_b ())
778         continue;
779
780       if (((int)s->chord_start_f ()) 
781         && (s->get_direction () != s->get_default_dir ()))
782         f++;
783     }
784   return f;
785 }
786
787 /*
788   TODO: Fix this class. This is wildly inefficient.
789   And it sux.  Yet another array/list 'interface'.
790  */
791 Stem *
792 Beam::stem (int i) const
793 {
794   return Pointer_group_interface__extract_elements ((Beam*) this, (Stem*) 0, "stems")[i];
795 }
796
797 int
798 Beam::stem_count () const
799 {
800   Pointer_group_interface gi (this, "stems");
801   return gi.count ();
802 }
803
804 Stem*
805 Beam::stem_top () const
806 {
807   SCM s = get_elt_pointer ("stems");
808   
809   return gh_pair_p (s) ? dynamic_cast<Stem*> (unsmob_element (gh_car (s))) : 0;
810 }
811
812 /* burp */
813 int
814 Beam::visible_stem_count () const
815 {
816   int c = 0;
817   for (int i = 0; i < stem_count (); i++)
818     {
819       if (!stem (i)->invisible_b ())
820         c++;
821     }
822   return c;
823 }
824
825 Stem*
826 Beam::first_visible_stem () const
827 {
828   for (int i = 0; i < stem_count (); i++)
829     {
830       Stem* s = stem (i);
831       if (!s->invisible_b ())
832         return s;
833     }
834   return 0;
835 }
836
837 Stem*
838 Beam::last_visible_stem () const
839 {
840   for (int i = stem_count (); i > 0; i--)
841     {
842       Stem* s = stem (i - 1);
843       if (!s->invisible_b ())
844         return s;
845     }
846   return 0;
847 }
848
849
850 /*
851   [TODO]
852   handle rest under beam (do_post: beams are calculated now)
853   what about combination of collisions and rest under beam.
854
855   Should lookup
856     
857     rest -> stem -> beam -> interpolate_y_position ()
858 */
859 Real
860 Beam::rest_collision_callback (Score_element const *rest, Axis a )
861 {
862   assert (a == Y_AXIS);
863
864   Score_element * st = unsmob_element (rest->get_elt_pointer ("stem"));
865   Stem * stem  = dynamic_cast<Stem*> (st);
866   if (!stem)
867     return 0.0;
868   Beam * beam = dynamic_cast<Beam*> (unsmob_element (stem->get_elt_pointer ("beam"))); 
869   if (!beam || !beam->visible_stem_count ())
870     return 0.0;
871
872   // make callback for rest from this.
873   Real beam_dy = 0;
874   Real beam_y = 0;
875
876
877   // todo: make sure this calced already.
878   SCM s = beam->get_elt_property ("height");
879   if (gh_number_p (s))
880     beam_dy = gh_scm2double (s);
881   
882   s = beam->get_elt_property ("y-position");
883   if (gh_number_p (s))
884     beam_y = gh_scm2double (s);
885   
886   Real x0 = beam->first_visible_stem ()->relative_coordinate (0, X_AXIS);
887   Real dx = beam->last_visible_stem ()->relative_coordinate (0, X_AXIS) - x0;
888   Real dydx = beam_dy && dx ? beam_dy/dx : 0;
889
890   Direction d = stem->get_direction ();
891   Real beamy = (stem->relative_coordinate (0, X_AXIS) - x0) * dydx + beam_y;
892
893   Staff_symbol_referencer_interface si (rest);
894
895   Real staff_space = si.staff_space ();      
896   Real rest_dim = rest->extent (Y_AXIS)[d]*2.0 / staff_space ;
897
898   Real minimum_dist
899     = gh_scm2double (rest->get_elt_property ("minimum-beam-collision-distance"));
900   Real dist =
901     minimum_dist +  -d  * (beamy - rest_dim) >? 0;
902
903   int stafflines = si.line_count ();
904
905   // move discretely by half spaces.
906   int discrete_dist = int (ceil (dist));
907
908   // move by whole spaces inside the staff.
909   if (discrete_dist < stafflines+1)
910     discrete_dist = int (ceil (discrete_dist / 2.0)* 2.0);
911
912   return  (-d *  discrete_dist);
913 }