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