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