MusicSheetCalculator.ts 218 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768
  1. import { GraphicalStaffEntry } from "./GraphicalStaffEntry";
  2. import { StaffLine } from "./StaffLine";
  3. import { GraphicalMusicSheet } from "./GraphicalMusicSheet";
  4. import { EngravingRules } from "./EngravingRules";
  5. import { Tie } from "../VoiceData/Tie";
  6. import { Fraction } from "../../Common/DataObjects/Fraction";
  7. import { Note } from "../VoiceData/Note";
  8. import { MusicSheet } from "../MusicSheet";
  9. import { GraphicalMeasure } from "./GraphicalMeasure";
  10. import {ClefInstruction, ClefEnum} from "../VoiceData/Instructions/ClefInstruction";
  11. import { LyricWord } from "../VoiceData/Lyrics/LyricsWord";
  12. import { SourceMeasure } from "../VoiceData/SourceMeasure";
  13. import { GraphicalMusicPage } from "./GraphicalMusicPage";
  14. import { GraphicalNote } from "./GraphicalNote";
  15. import { Beam } from "../VoiceData/Beam";
  16. import { OctaveEnum } from "../VoiceData/Expressions/ContinuousExpressions/OctaveShift";
  17. import { VoiceEntry, StemDirectionType } from "../VoiceData/VoiceEntry";
  18. import { OrnamentContainer } from "../VoiceData/OrnamentContainer";
  19. import { Articulation } from "../VoiceData/Articulation";
  20. import { Tuplet } from "../VoiceData/Tuplet";
  21. import { MusicSystem } from "./MusicSystem";
  22. import { GraphicalTie } from "./GraphicalTie";
  23. import { RepetitionInstruction } from "../VoiceData/Instructions/RepetitionInstruction";
  24. import { MultiExpression, MultiExpressionEntry } from "../VoiceData/Expressions/MultiExpression";
  25. import { StaffEntryLink } from "../VoiceData/StaffEntryLink";
  26. import { MusicSystemBuilder } from "./MusicSystemBuilder";
  27. import { MultiTempoExpression } from "../VoiceData/Expressions/MultiTempoExpression";
  28. import { Repetition } from "../MusicSource/Repetition";
  29. import { PointF2D } from "../../Common/DataObjects/PointF2D";
  30. import { SourceStaffEntry } from "../VoiceData/SourceStaffEntry";
  31. import { BoundingBox } from "./BoundingBox";
  32. import { Instrument } from "../Instrument";
  33. import { GraphicalLabel } from "./GraphicalLabel";
  34. import { TextAlignmentEnum } from "../../Common/Enums/TextAlignment";
  35. import { VerticalGraphicalStaffEntryContainer } from "./VerticalGraphicalStaffEntryContainer";
  36. import { KeyInstruction } from "../VoiceData/Instructions/KeyInstruction";
  37. import { AbstractNotationInstruction } from "../VoiceData/Instructions/AbstractNotationInstruction";
  38. import { TechnicalInstruction, TechnicalInstructionType } from "../VoiceData/Instructions/TechnicalInstruction";
  39. import { Pitch } from "../../Common/DataObjects/Pitch";
  40. import { LinkedVoice } from "../VoiceData/LinkedVoice";
  41. import { ColDirEnum } from "./BoundingBox";
  42. import { IGraphicalSymbolFactory } from "../Interfaces/IGraphicalSymbolFactory";
  43. import { ITextMeasurer } from "../Interfaces/ITextMeasurer";
  44. import { ITransposeCalculator } from "../Interfaces/ITransposeCalculator";
  45. import { OctaveShiftParams } from "./OctaveShiftParams";
  46. import { AccidentalCalculator } from "./AccidentalCalculator";
  47. import { MidiInstrument } from "../VoiceData/Instructions/ClefInstruction";
  48. import { Staff } from "../VoiceData/Staff";
  49. import { OctaveShift } from "../VoiceData/Expressions/ContinuousExpressions/OctaveShift";
  50. import log from "loglevel";
  51. import { Dictionary } from "typescript-collections";
  52. import { GraphicalLyricEntry } from "./GraphicalLyricEntry";
  53. import { GraphicalLyricWord } from "./GraphicalLyricWord";
  54. import { GraphicalLine } from "./GraphicalLine";
  55. import { Label } from "../Label";
  56. import { GraphicalVoiceEntry } from "./GraphicalVoiceEntry";
  57. import { VerticalSourceStaffEntryContainer } from "../VoiceData/VerticalSourceStaffEntryContainer";
  58. import { SkyBottomLineCalculator } from "./SkyBottomLineCalculator";
  59. import { PlacementEnum } from "../VoiceData/Expressions/AbstractExpression";
  60. import { AbstractGraphicalInstruction } from "./AbstractGraphicalInstruction";
  61. import { GraphicalInstantaneousTempoExpression } from "./GraphicalInstantaneousTempoExpression";
  62. import { InstantaneousTempoExpression, TempoEnum } from "../VoiceData/Expressions/InstantaneousTempoExpression";
  63. import { ContinuousTempoExpression } from "../VoiceData/Expressions/ContinuousExpressions/ContinuousTempoExpression";
  64. import { FontStyles } from "../../Common/Enums/FontStyles";
  65. import { AbstractTempoExpression } from "../VoiceData/Expressions/AbstractTempoExpression";
  66. import { GraphicalInstantaneousDynamicExpression } from "./GraphicalInstantaneousDynamicExpression";
  67. import { ContDynamicEnum } from "../VoiceData/Expressions/ContinuousExpressions/ContinuousDynamicExpression";
  68. import { GraphicalContinuousDynamicExpression } from "./GraphicalContinuousDynamicExpression";
  69. import { FillEmptyMeasuresWithWholeRests } from "../../OpenSheetMusicDisplay/OSMDOptions";
  70. import { JustifiedMusicSystemBuilder } from "./JustifiedMusicSystemBuilder";
  71. import { IStafflineNoteCalculator } from "../Interfaces/IStafflineNoteCalculator";
  72. import { GraphicalUnknownExpression } from "./GraphicalUnknownExpression";
  73. import { GraphicalChordSymbolContainer } from ".";
  74. import { LyricsEntry } from "../VoiceData/Lyrics/LyricsEntry";
  75. import { Voice } from "../VoiceData/Voice";
  76. import { TabNote } from "../VoiceData/TabNote";
  77. /**
  78. * Class used to do all the calculations in a MusicSheet, which in the end populates a GraphicalMusicSheet.
  79. */
  80. export abstract class MusicSheetCalculator {
  81. public static symbolFactory: IGraphicalSymbolFactory;
  82. public static transposeCalculator: ITransposeCalculator;
  83. public static stafflineNoteCalculator: IStafflineNoteCalculator;
  84. protected static textMeasurer: ITextMeasurer;
  85. protected staffEntriesWithGraphicalTies: GraphicalStaffEntry[] = [];
  86. protected staffEntriesWithOrnaments: GraphicalStaffEntry[] = [];
  87. protected staffEntriesWithChordSymbols: GraphicalStaffEntry[] = [];
  88. protected staffLinesWithLyricWords: StaffLine[] = [];
  89. protected graphicalLyricWords: GraphicalLyricWord[] = [];
  90. protected graphicalMusicSheet: GraphicalMusicSheet;
  91. protected rules: EngravingRules;
  92. protected musicSystems: MusicSystem[];
  93. private abstractNotImplementedErrorMessage: string = "abstract, not implemented";
  94. public static get TextMeasurer(): ITextMeasurer {
  95. return MusicSheetCalculator.textMeasurer;
  96. }
  97. public static set TextMeasurer(value: ITextMeasurer) {
  98. MusicSheetCalculator.textMeasurer = value;
  99. }
  100. protected get leadSheet(): boolean {
  101. return this.graphicalMusicSheet.LeadSheet;
  102. }
  103. protected static setMeasuresMinStaffEntriesWidth(measures: GraphicalMeasure[], minimumStaffEntriesWidth: number): void {
  104. for (let idx: number = 0, len: number = measures.length; idx < len; ++idx) {
  105. const measure: GraphicalMeasure = measures[idx];
  106. if (measure) {
  107. measure.minimumStaffEntriesWidth = minimumStaffEntriesWidth;
  108. }
  109. }
  110. }
  111. public initialize(graphicalMusicSheet: GraphicalMusicSheet): void {
  112. this.graphicalMusicSheet = graphicalMusicSheet;
  113. this.rules = graphicalMusicSheet.ParentMusicSheet.Rules;
  114. this.rules.clearMusicSheetObjects();
  115. this.prepareGraphicalMusicSheet();
  116. //this.calculate();
  117. }
  118. /**
  119. * Build the 2D [[GraphicalMeasure]] list needed for the [[MusicSheetCalculator]].
  120. * Internally it creates [[GraphicalMeasure]]s, [[GraphicalStaffEntry]]'s and [[GraphicalNote]]s.
  121. */
  122. public prepareGraphicalMusicSheet(): void {
  123. // Clear the stored system images dict - all systems have to be redrawn.
  124. // Not necessary now. TODO Check
  125. // this.graphicalMusicSheet.SystemImages.length = 0;
  126. const musicSheet: MusicSheet = this.graphicalMusicSheet.ParentMusicSheet;
  127. this.staffEntriesWithGraphicalTies = [];
  128. this.staffEntriesWithOrnaments = [];
  129. this.staffEntriesWithChordSymbols = [];
  130. this.staffLinesWithLyricWords = [];
  131. // this.staffLinesWithGraphicalExpressions = [];
  132. this.graphicalMusicSheet.Initialize();
  133. const measureList: GraphicalMeasure[][] = this.graphicalMusicSheet.MeasureList;
  134. // one AccidentalCalculator for each Staff (regardless of Instrument)
  135. const accidentalCalculators: AccidentalCalculator[] = this.createAccidentalCalculators();
  136. // List of Active ClefInstructions
  137. const activeClefs: ClefInstruction[] = this.graphicalMusicSheet.initializeActiveClefs();
  138. // LyricWord - GraphicalLyricWord Lists
  139. const lyricWords: LyricWord[] = [];
  140. const completeNumberOfStaves: number = musicSheet.getCompleteNumberOfStaves();
  141. // Octave Shifts List
  142. const openOctaveShifts: OctaveShiftParams[] = [];
  143. // TieList - timestampsArray
  144. for (let i: number = 0; i < completeNumberOfStaves; i++) {
  145. openOctaveShifts.push(undefined);
  146. }
  147. // go through all SourceMeasures (taking into account normal SourceMusicParts and Repetitions)
  148. for (let idx: number = 0, len: number = musicSheet.SourceMeasures.length; idx < len; ++idx) {
  149. const sourceMeasure: SourceMeasure = musicSheet.SourceMeasures[idx];
  150. const graphicalMeasures: GraphicalMeasure[] = this.createGraphicalMeasuresForSourceMeasure(
  151. sourceMeasure,
  152. accidentalCalculators,
  153. lyricWords,
  154. openOctaveShifts,
  155. activeClefs
  156. );
  157. measureList.push(graphicalMeasures);
  158. if (sourceMeasure.multipleRestMeasures > 0 && this.rules.RenderMultipleRestMeasures) {
  159. // multiRest given in XML, skip the next measures included
  160. sourceMeasure.isReducedToMultiRest = true;
  161. sourceMeasure.multipleRestMeasureNumber = 1;
  162. const measuresToSkip: number = sourceMeasure.multipleRestMeasures - 1;
  163. // console.log(`skipping ${measuresToSkip} measures for measure #${sourceMeasure.MeasureNumber}.`);
  164. idx += measuresToSkip;
  165. for (let idx2: number = 1; idx2 <= measuresToSkip; idx2++) {
  166. const nextMeasureIndex: number = musicSheet.SourceMeasures.indexOf(sourceMeasure) + idx2;
  167. // note that if there are pickup measures in the sheet, the measure index is not MeasureNumber - 1.
  168. // (if first measure in the sheet is a pickup measure, its index and measure number will be 0)
  169. if (nextMeasureIndex >= musicSheet.SourceMeasures.length) {
  170. break; // shouldn't happen, but for safety.
  171. }
  172. const nextSourceMeasure: SourceMeasure = musicSheet.SourceMeasures[nextMeasureIndex];
  173. // TODO handle the case that a measure after the first multiple rest measure can't be reduced
  174. nextSourceMeasure.multipleRestMeasureNumber = idx2 + 1;
  175. nextSourceMeasure.isReducedToMultiRest = true;
  176. measureList.push([undefined]);
  177. // TODO we could push an object here or push nothing entirely,
  178. // but then the index doesn't correspond to measure numbers anymore.
  179. }
  180. }
  181. }
  182. if (this.rules.AutoGenerateMultipleRestMeasuresFromRestMeasures && this.rules.RenderMultipleRestMeasures) {
  183. //track number of multirests
  184. let beginMultiRestMeasure: SourceMeasure = undefined;
  185. let multiRestCount: number = 0;
  186. //go through all source measures again. Need to calc auto-multi-rests
  187. for (let idx: number = 0, len: number = musicSheet.SourceMeasures.length; idx < len; ++idx) {
  188. const sourceMeasure: SourceMeasure = musicSheet.SourceMeasures[idx];
  189. // console.log(sourceMeasure.MeasureNumber + " can be reduced: " + sourceMeasure.canBeReducedToMultiRest());
  190. if (!sourceMeasure.isReducedToMultiRest && sourceMeasure.canBeReducedToMultiRest()) {
  191. //we've already been initialized, we are in the midst of a multirest sequence
  192. if (multiRestCount > 0) {
  193. beginMultiRestMeasure.isReducedToMultiRest = true;
  194. beginMultiRestMeasure.multipleRestMeasureNumber = 1;
  195. multiRestCount++;
  196. sourceMeasure.multipleRestMeasureNumber = multiRestCount;
  197. sourceMeasure.isReducedToMultiRest = true;
  198. //clear out these measures. We know now that we are in multirest mode
  199. for (let idx2: number = 0; idx2 < measureList[idx].length; idx2++) {
  200. measureList[idx][idx2] = undefined;
  201. }
  202. } else { //else this is the (potential) beginning
  203. beginMultiRestMeasure = sourceMeasure;
  204. multiRestCount = 1;
  205. }
  206. } else { //not multirest measure
  207. if (multiRestCount > 1) { //Actual multirest sequence just happened. Process
  208. beginMultiRestMeasure.multipleRestMeasures = multiRestCount;
  209. //regen graphical measures for this source measure
  210. const graphicalMeasures: GraphicalMeasure[] = this.createGraphicalMeasuresForSourceMeasure(
  211. beginMultiRestMeasure,
  212. accidentalCalculators,
  213. lyricWords,
  214. openOctaveShifts,
  215. activeClefs
  216. );
  217. measureList[beginMultiRestMeasure.measureListIndex] = graphicalMeasures;
  218. multiRestCount = 0;
  219. beginMultiRestMeasure = undefined;
  220. } else { //had a potential multirest sequence, but didn't pan out. only one measure was rests
  221. multiRestCount = 0;
  222. beginMultiRestMeasure = undefined;
  223. }
  224. }
  225. }
  226. //If we reached the end of the sheet and have pending multirest measure, process
  227. if (multiRestCount > 1) {
  228. beginMultiRestMeasure.multipleRestMeasures = multiRestCount;
  229. beginMultiRestMeasure.isReducedToMultiRest = true;
  230. //regen graphical measures for this source measure
  231. const graphicalMeasures: GraphicalMeasure[] = this.createGraphicalMeasuresForSourceMeasure(
  232. beginMultiRestMeasure,
  233. accidentalCalculators,
  234. lyricWords,
  235. openOctaveShifts,
  236. activeClefs
  237. );
  238. measureList[beginMultiRestMeasure.measureListIndex] = graphicalMeasures;
  239. multiRestCount = 0;
  240. beginMultiRestMeasure = undefined;
  241. }
  242. }
  243. const staffIsPercussionArray: Array<boolean> =
  244. activeClefs.map(clef => (clef.ClefType === ClefEnum.percussion));
  245. this.handleStaffEntries(staffIsPercussionArray);
  246. this.calculateVerticalContainersList();
  247. this.setIndicesToVerticalGraphicalContainers();
  248. }
  249. /**
  250. * The main method for the Calculator.
  251. */
  252. public calculate(): void {
  253. this.musicSystems = [];
  254. this.clearSystemsAndMeasures();
  255. // delete graphicalObjects (currently: ties) that will be recalculated, newly create GraphicalObjects streching over a single StaffEntry
  256. this.clearRecreatedObjects();
  257. // this.graphicalMusicSheet.initializeActiveClefs(); // could have been changed since last render?
  258. this.createGraphicalTies();
  259. // calculate SheetLabelBoundingBoxes
  260. this.calculateSheetLabelBoundingBoxes();
  261. this.calculateXLayout(this.graphicalMusicSheet, this.maxInstrNameLabelLength());
  262. // create List<MusicPage>
  263. this.graphicalMusicSheet.MusicPages.length = 0;
  264. // create new MusicSystems and StaffLines (as many as necessary) and populate them with Measures from measureList
  265. this.calculateMusicSystems();
  266. // Add some white space at the end of the piece:
  267. //this.graphicalMusicSheet.MusicPages[0].PositionAndShape.BorderMarginBottom += 9;
  268. // transform Relative to Absolute Positions
  269. //This is called for each measure in calculate music systems (calculateLines -> calculateSkyBottomLines)
  270. GraphicalMusicSheet.transformRelativeToAbsolutePosition(this.graphicalMusicSheet);
  271. }
  272. public calculateXLayout(graphicalMusicSheet: GraphicalMusicSheet, maxInstrNameLabelLength: number): void {
  273. // for each inner List in big Measure List calculate new Positions for the StaffEntries
  274. // and adjust Measures sizes
  275. // calculate max measure length for maximum zoom in.
  276. // let minLength: number = 0; // currently unused
  277. // const maxInstructionsLength: number = this.rules.MaxInstructionsConstValue;
  278. if (this.graphicalMusicSheet.MeasureList.length > 0) {
  279. /** list of vertically ordered measures belonging to one bar */
  280. // let measures: GraphicalMeasure[] = this.graphicalMusicSheet.MeasureList[0];
  281. // let minimumStaffEntriesWidth: number = this.calculateMeasureXLayout(measures);
  282. // minimumStaffEntriesWidth = this.calculateMeasureWidthFromStaffEntries(measures, minimumStaffEntriesWidth);
  283. // MusicSheetCalculator.setMeasuresMinStaffEntriesWidth(measures, minimumStaffEntriesWidth);
  284. // minLength = minimumStaffEntriesWidth * 1.2 + maxInstrNameLabelLength + maxInstructionsLength;
  285. let maxWidth: number = 0;
  286. let measures: GraphicalMeasure[];
  287. for (let i: number = 0; i < this.graphicalMusicSheet.MeasureList.length; i++) {
  288. measures = this.graphicalMusicSheet.MeasureList[i];
  289. let minimumStaffEntriesWidth: number = this.calculateMeasureXLayout(measures);
  290. minimumStaffEntriesWidth = this.calculateMeasureWidthFromStaffEntries(measures, minimumStaffEntriesWidth);
  291. if (minimumStaffEntriesWidth > maxWidth) {
  292. maxWidth = minimumStaffEntriesWidth;
  293. }
  294. //console.log(`min width for measure ${measures[0].MeasureNumber}: ${minimumStaffEntriesWidth}`);
  295. MusicSheetCalculator.setMeasuresMinStaffEntriesWidth(measures, minimumStaffEntriesWidth);
  296. // minLength = Math.max(minLength, minimumStaffEntriesWidth * 1.2 + maxInstructionsLength);
  297. }
  298. if (this.rules.FixedMeasureWidth) {
  299. // experimental: use the same measure width for all measures
  300. // here we take the maximum measure width for now,
  301. // otherwise Vexflow's layout can get completely messed up and place everything on top of each other,
  302. // if it gets less width than it says it needs as a minimum for a measure. (formatter.preCalculateMinTotalWidth)
  303. let targetWidth: number = maxWidth;
  304. if (this.rules.FixedMeasureWidthFixedValue) {
  305. targetWidth = this.rules.FixedMeasureWidthFixedValue;
  306. }
  307. for (let i: number = 0; i < this.graphicalMusicSheet.MeasureList.length; i++) {
  308. measures = this.graphicalMusicSheet.MeasureList[i];
  309. if (!this.rules.FixedMeasureWidthUseForPickupMeasures && measures[0]?.parentSourceMeasure.ImplicitMeasure) {
  310. // note that measures[0] is undefined for multi-measure rests
  311. continue;
  312. }
  313. MusicSheetCalculator.setMeasuresMinStaffEntriesWidth(measures, targetWidth);
  314. }
  315. }
  316. }
  317. // this.graphicalMusicSheet.MinAllowedSystemWidth = minLength; // currently unused
  318. }
  319. public calculateMeasureWidthFromStaffEntries(measuresVertical: GraphicalMeasure[], oldMinimumStaffEntriesWidth: number): number {
  320. throw new Error(this.abstractNotImplementedErrorMessage);
  321. }
  322. protected formatMeasures(): void {
  323. throw new Error(this.abstractNotImplementedErrorMessage);
  324. }
  325. /**
  326. * Calculates the x layout of the staff entries within the staff measures belonging to one source measure.
  327. * All staff entries are x-aligned throughout all the measures.
  328. * @param measures - The minimum required x width of the source measure
  329. */
  330. protected calculateMeasureXLayout(measures: GraphicalMeasure[]): number {
  331. throw new Error(this.abstractNotImplementedErrorMessage);
  332. }
  333. /**
  334. * Called for every source measure when generating the list of staff measures for it.
  335. */
  336. protected initGraphicalMeasuresCreation(): void {
  337. throw new Error(this.abstractNotImplementedErrorMessage);
  338. }
  339. protected handleBeam(graphicalNote: GraphicalNote, beam: Beam, openBeams: Beam[]): void {
  340. throw new Error(this.abstractNotImplementedErrorMessage);
  341. }
  342. /**
  343. * Check if the tied graphical note belongs to any beams or tuplets and react accordingly.
  344. * @param tiedGraphicalNote
  345. * @param beams
  346. * @param activeClef
  347. * @param octaveShiftValue
  348. * @param graphicalStaffEntry
  349. * @param duration
  350. * @param openTie
  351. * @param isLastTieNote
  352. */
  353. protected handleTiedGraphicalNote(tiedGraphicalNote: GraphicalNote, beams: Beam[], activeClef: ClefInstruction,
  354. octaveShiftValue: OctaveEnum, graphicalStaffEntry: GraphicalStaffEntry, duration: Fraction,
  355. openTie: Tie, isLastTieNote: boolean): void {
  356. throw new Error(this.abstractNotImplementedErrorMessage);
  357. }
  358. protected handleVoiceEntryLyrics(voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry,
  359. openLyricWords: LyricWord[]): void {
  360. throw new Error(this.abstractNotImplementedErrorMessage);
  361. }
  362. protected handleVoiceEntryOrnaments(ornamentContainer: OrnamentContainer, voiceEntry: VoiceEntry,
  363. graphicalStaffEntry: GraphicalStaffEntry): void {
  364. throw new Error(this.abstractNotImplementedErrorMessage);
  365. }
  366. protected handleVoiceEntryArticulations(articulations: Articulation[],
  367. voiceEntry: VoiceEntry,
  368. staffEntry: GraphicalStaffEntry): void {
  369. throw new Error(this.abstractNotImplementedErrorMessage);
  370. }
  371. /**
  372. * Adds a technical instruction at the given staff entry.
  373. * @param technicalInstructions
  374. * @param voiceEntry
  375. * @param staffEntry
  376. */
  377. protected handleVoiceEntryTechnicalInstructions(technicalInstructions: TechnicalInstruction[],
  378. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  379. throw new Error(this.abstractNotImplementedErrorMessage);
  380. }
  381. protected handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet, openTuplets: Tuplet[]): void {
  382. throw new Error(this.abstractNotImplementedErrorMessage);
  383. }
  384. protected layoutVoiceEntry(voiceEntry: VoiceEntry, graphicalNotes: GraphicalNote[],
  385. graphicalStaffEntry: GraphicalStaffEntry, hasPitchedNote: boolean): void {
  386. throw new Error(this.abstractNotImplementedErrorMessage);
  387. }
  388. protected layoutStaffEntry(graphicalStaffEntry: GraphicalStaffEntry): void {
  389. throw new Error(this.abstractNotImplementedErrorMessage);
  390. }
  391. protected createGraphicalTie(tie: Tie, startGse: GraphicalStaffEntry, endGse: GraphicalStaffEntry, startNote: GraphicalNote,
  392. endNote: GraphicalNote): GraphicalTie {
  393. throw new Error(this.abstractNotImplementedErrorMessage);
  394. }
  395. protected updateStaffLineBorders(staffLine: StaffLine): void {
  396. throw new Error(this.abstractNotImplementedErrorMessage);
  397. }
  398. /**
  399. * Iterate through all Measures and calculates the MeasureNumberLabels.
  400. * @param musicSystem
  401. */
  402. protected calculateMeasureNumberPlacement(musicSystem: MusicSystem): void {
  403. const staffLine: StaffLine = musicSystem.StaffLines[0];
  404. if (!staffLine || !staffLine.Measures[0]) {
  405. log.warn("calculateMeasureNumberPlacement: measure undefined for system.Id " + musicSystem.Id);
  406. return; // TODO apparently happens in script sometimes (mp #70)
  407. }
  408. let previousMeasureNumber: number = staffLine.Measures[0].MeasureNumber;
  409. let labelOffsetX: number = 0;
  410. for (let i: number = 0; i < staffLine.Measures.length; i++) {
  411. const measure: GraphicalMeasure = staffLine.Measures[i];
  412. let skip: boolean = this.rules.RenderMeasureNumbersOnlyAtSystemStart && i > 1;
  413. if (i === 1 && staffLine.Measures[0].parentSourceMeasure.ImplicitMeasure) {
  414. skip = false; // if the first measure (i=0) is a pickup measure, we shouldn't skip measure number 1 (i=1)
  415. }
  416. if (skip) {
  417. return; // no more measures number labels need to be rendered for this system, so we can just return instead of continue.
  418. }
  419. if (measure.MeasureNumber === 0 || measure.MeasureNumber === 1) {
  420. previousMeasureNumber = measure.MeasureNumber;
  421. // for the first measure, this label still needs to be created. Afterwards, this variable will hold the previous label's measure number.
  422. }
  423. if (measure !== staffLine.Measures[0] && this.rules.MeasureNumberLabelXOffset) {
  424. labelOffsetX = this.rules.MeasureNumberLabelXOffset;
  425. } else {
  426. labelOffsetX = 0; // don't offset label for first measure in staffline
  427. }
  428. const isFirstMeasureAndNotPrintedOne: boolean = this.rules.UseXMLMeasureNumbers &&
  429. measure.MeasureNumber === 1 && measure.parentSourceMeasure.getPrintedMeasureNumber() !== 1;
  430. if ((measure.MeasureNumber === previousMeasureNumber ||
  431. measure.MeasureNumber >= previousMeasureNumber + this.rules.MeasureNumberLabelOffset) &&
  432. !measure.parentSourceMeasure.ImplicitMeasure ||
  433. isFirstMeasureAndNotPrintedOne) {
  434. if (measure.MeasureNumber !== 1 ||
  435. (measure.MeasureNumber === 1 && measure !== staffLine.Measures[0]) ||
  436. isFirstMeasureAndNotPrintedOne
  437. ) {
  438. this.calculateSingleMeasureNumberPlacement(measure, staffLine, musicSystem, labelOffsetX);
  439. }
  440. previousMeasureNumber = measure.MeasureNumber;
  441. }
  442. }
  443. }
  444. /// <summary>
  445. /// This method calculates a single MeasureNumberLabel and adds it to the graphical label list of the music system
  446. /// </summary>
  447. /// <param name="measure"></param>
  448. /// <param name="staffLine"></param>
  449. /// <param name="musicSystem"></param>
  450. private calculateSingleMeasureNumberPlacement(measure: GraphicalMeasure, staffLine: StaffLine, musicSystem: MusicSystem,
  451. labelOffsetX: number = 0): void {
  452. const labelNumber: string = measure.parentSourceMeasure.getPrintedMeasureNumber().toString();
  453. const label: Label = new Label(labelNumber);
  454. // maybe give rules as argument instead of just setting fontStyle and maybe other settings manually afterwards
  455. const graphicalLabel: GraphicalLabel = new GraphicalLabel(label, this.rules.MeasureNumberLabelHeight,
  456. TextAlignmentEnum.LeftBottom, this.rules);
  457. const skyBottomLineCalculator: SkyBottomLineCalculator = staffLine.SkyBottomLineCalculator;
  458. // calculate LabelBoundingBox and set PSI parent
  459. graphicalLabel.setLabelPositionAndShapeBorders();
  460. graphicalLabel.PositionAndShape.Parent = musicSystem.PositionAndShape;
  461. // calculate relative Position
  462. const relativeX: number = staffLine.PositionAndShape.RelativePosition.x +
  463. measure.PositionAndShape.RelativePosition.x - graphicalLabel.PositionAndShape.BorderMarginLeft +
  464. labelOffsetX;
  465. let relativeY: number;
  466. // and the corresponding SkyLine indices
  467. let start: number = relativeX;
  468. let end: number = relativeX - graphicalLabel.PositionAndShape.BorderLeft + graphicalLabel.PositionAndShape.BorderRight;
  469. start -= staffLine.PositionAndShape.RelativePosition.x;
  470. end -= staffLine.PositionAndShape.RelativePosition.x;
  471. // correct for hypersensitive collision checks, notes having skyline extend too far to left and right
  472. const startCollisionCheck: number = start + 0.5;
  473. const endCollisionCheck: number = end - 0.5;
  474. // get the minimum corresponding SkyLine value
  475. const skyLineMinValue: number = skyBottomLineCalculator.getSkyLineMinInRange(startCollisionCheck, endCollisionCheck);
  476. if (measure === staffLine.Measures[0]) {
  477. // must take into account possible MusicSystem Brackets
  478. let minBracketTopBorder: number = 0;
  479. if (musicSystem.GroupBrackets.length > 0) {
  480. for (const groupBracket of musicSystem.GroupBrackets) {
  481. minBracketTopBorder = Math.min(minBracketTopBorder, groupBracket.PositionAndShape.BorderTop);
  482. }
  483. } else if (measure.ParentStaff.ParentInstrument.Parent) { // Parent InstrumentalGroup
  484. // note that GroupBracket creation is currently done after measure number creation, so we have to check it indirectly.
  485. minBracketTopBorder = -1;
  486. }
  487. relativeY = Math.min(skyLineMinValue, minBracketTopBorder);
  488. } else {
  489. relativeY = skyLineMinValue;
  490. }
  491. relativeY = Math.min(0, relativeY);
  492. graphicalLabel.PositionAndShape.RelativePosition = new PointF2D(relativeX, relativeY);
  493. musicSystem.MeasureNumberLabels.push(graphicalLabel);
  494. }
  495. //So we can apply slurs first, then do these
  496. private calculateMeasureNumberSkyline(musicSystem: MusicSystem): void {
  497. const staffLine: StaffLine = musicSystem.StaffLines[0];
  498. for(const measureNumberLabel of musicSystem.MeasureNumberLabels) {
  499. // and the corresponding SkyLine indices
  500. let start: number = measureNumberLabel.PositionAndShape.RelativePosition.x;
  501. let end: number = start - measureNumberLabel.PositionAndShape.BorderLeft + measureNumberLabel.PositionAndShape.BorderRight;
  502. start -= staffLine.PositionAndShape.RelativePosition.x;
  503. end -= staffLine.PositionAndShape.RelativePosition.x;
  504. staffLine.SkyBottomLineCalculator.updateSkyLineInRange(start, end,
  505. measureNumberLabel.PositionAndShape.RelativePosition.y + measureNumberLabel.PositionAndShape.BorderMarginTop);
  506. }
  507. }
  508. /**
  509. * Calculate the shape (Bézier curve) for this tie.
  510. * @param tie
  511. * @param tieIsAtSystemBreak
  512. */
  513. protected layoutGraphicalTie(tie: GraphicalTie, tieIsAtSystemBreak: boolean, isTab: boolean): void {
  514. throw new Error(this.abstractNotImplementedErrorMessage);
  515. }
  516. /**
  517. * Calculate the Lyrics YPositions for a single [[StaffLine]].
  518. * @param staffLine
  519. * @param lyricVersesNumber
  520. */
  521. protected calculateSingleStaffLineLyricsPosition(staffLine: StaffLine, lyricVersesNumber: string[]): GraphicalStaffEntry[] {
  522. let numberOfVerses: number = 0;
  523. let lyricsStartYPosition: number = this.rules.StaffHeight; // Add offset to prevent collision
  524. const relevantVerseNumbers: Map<string, boolean> = new Map<string, boolean>();
  525. const lyricsStaffEntriesList: GraphicalStaffEntry[] = [];
  526. const skyBottomLineCalculator: SkyBottomLineCalculator = staffLine.SkyBottomLineCalculator;
  527. // first find maximum Ycoordinate for the whole StaffLine
  528. let len: number = staffLine.Measures.length;
  529. for (let idx: number = 0; idx < len; ++idx) {
  530. const measure: GraphicalMeasure = staffLine.Measures[idx];
  531. const measureRelativePosition: PointF2D = measure.PositionAndShape.RelativePosition;
  532. const len2: number = measure.staffEntries.length;
  533. for (let idx2: number = 0; idx2 < len2; ++idx2) {
  534. const staffEntry: GraphicalStaffEntry = measure.staffEntries[idx2];
  535. // Collect relevant verse numbers
  536. const len3: number = staffEntry.LyricsEntries.length;
  537. for (let idx3: number = 0; idx3 < len3; ++idx3) {
  538. const lyricsEntry: LyricsEntry = staffEntry.LyricsEntries[idx3].LyricsEntry;
  539. relevantVerseNumbers[lyricsEntry.VerseNumber] = lyricsEntry.IsChorus;
  540. }
  541. if (len3 > 0) {
  542. lyricsStaffEntriesList.push(staffEntry);
  543. numberOfVerses = Math.max(numberOfVerses, staffEntry.LyricsEntries.length);
  544. // Position of Staffentry relative to StaffLine
  545. const staffEntryPositionX: number = staffEntry.PositionAndShape.RelativePosition.x +
  546. measureRelativePosition.x;
  547. let minMarginLeft: number = Number.MAX_VALUE;
  548. let maxMarginRight: number = Number.MIN_VALUE;
  549. // if more than one LyricEntry in StaffEntry, find minMarginLeft, maxMarginRight of all corresponding Labels
  550. for (let i: number = 0; i < staffEntry.LyricsEntries.length; i++) {
  551. const lyricsEntryLabel: GraphicalLabel = staffEntry.LyricsEntries[i].GraphicalLabel;
  552. minMarginLeft = Math.min(minMarginLeft, staffEntryPositionX + lyricsEntryLabel.PositionAndShape.BorderMarginLeft);
  553. maxMarginRight = Math.max(maxMarginRight, staffEntryPositionX + lyricsEntryLabel.PositionAndShape.BorderMarginRight);
  554. }
  555. // check BottomLine in this range and take the maximum between the two values
  556. const bottomLineMax: number = skyBottomLineCalculator.getBottomLineMaxInRange(minMarginLeft, maxMarginRight);
  557. lyricsStartYPosition = Math.max(lyricsStartYPosition, bottomLineMax + this.rules.LyricsYMarginToBottomLine);
  558. }
  559. }
  560. }
  561. let maxPosition: number = 0;
  562. // iterate again through the Staffentries with LyricEntries
  563. len = lyricsStaffEntriesList.length;
  564. for (const staffEntry of lyricsStaffEntriesList) {
  565. // Filter verse numbers
  566. const filteredLyricVersesNumber: string[] = [];
  567. let isChorus: boolean = true;
  568. for (let i: number = 0; i < staffEntry.LyricsEntries.length; i++) {
  569. isChorus &&= staffEntry.LyricsEntries[i].LyricsEntry.IsChorus;
  570. }
  571. for (const lyricVerseNumber of lyricVersesNumber){
  572. if (relevantVerseNumbers[lyricVerseNumber] === isChorus) {
  573. filteredLyricVersesNumber.push(lyricVerseNumber);
  574. }
  575. }
  576. // set LyricEntryLabel RelativePosition
  577. for (let i: number = 0; i < staffEntry.LyricsEntries.length; i++) {
  578. const lyricEntry: GraphicalLyricEntry = staffEntry.LyricsEntries[i];
  579. const lyricsEntryLabel: GraphicalLabel = lyricEntry.GraphicalLabel;
  580. // read the verseNumber and get index of this number in the sorted LyricVerseNumbersList of Instrument
  581. // eg verseNumbers: 2,3,4,6 => 1,2,3,4
  582. const verseNumber: string = lyricEntry.LyricsEntry.VerseNumber;
  583. const sortedLyricVerseNumberIndex: number = filteredLyricVersesNumber.indexOf(verseNumber);
  584. const firstPosition: number = lyricsStartYPosition + this.rules.LyricsHeight + this.rules.VerticalBetweenLyricsDistance +
  585. this.rules.LyricsYOffsetToStaffHeight;
  586. // Y-position calculated according to aforementioned mapping
  587. const position: number = firstPosition + (this.rules.VerticalBetweenLyricsDistance + this.rules.LyricsHeight) * sortedLyricVerseNumberIndex;
  588. // TODO not sure what this leadsheet lyrics positioning was supposed to be, but it seems to ALWAYS put the lyrics inside the stafflines now.
  589. // if (this.leadSheet) {
  590. // position = 3.4 + (this.rules.VerticalBetweenLyricsDistance + this.rules.LyricsHeight) * (sortedLyricVerseNumberIndex);
  591. // }
  592. const previousRelativeX: number = lyricsEntryLabel.PositionAndShape.RelativePosition.x;
  593. lyricsEntryLabel.PositionAndShape.RelativePosition = new PointF2D(previousRelativeX, position);
  594. lyricsEntryLabel.Label.fontStyle = lyricEntry.LyricsEntry.FontStyle;
  595. maxPosition = Math.max(maxPosition, position);
  596. }
  597. }
  598. // update BottomLine (on the whole StaffLine's length)
  599. if (lyricsStaffEntriesList.length > 0) {
  600. const endX: number = staffLine.PositionAndShape.Size.width;
  601. let startX: number = lyricsStaffEntriesList[0].PositionAndShape.RelativePosition.x +
  602. lyricsStaffEntriesList[0].PositionAndShape.BorderMarginLeft +
  603. lyricsStaffEntriesList[0].parentMeasure.PositionAndShape.RelativePosition.x;
  604. startX = startX > endX ? endX : startX;
  605. skyBottomLineCalculator.updateBottomLineInRange(startX, endX, maxPosition);
  606. }
  607. return lyricsStaffEntriesList;
  608. }
  609. /**
  610. * calculates the dashes of lyric words and the extending underscore lines of syllables sung on more than one note.
  611. * @param lyricsStaffEntries
  612. */
  613. protected calculateLyricsExtendsAndDashes(lyricsStaffEntries: GraphicalStaffEntry[]): void {
  614. // iterate again to create now the extend lines and dashes for words
  615. for (let idx: number = 0, len: number = lyricsStaffEntries.length; idx < len; ++idx) {
  616. const staffEntry: GraphicalStaffEntry = lyricsStaffEntries[idx];
  617. // set LyricEntryLabel RelativePosition
  618. for (let i: number = 0; i < staffEntry.LyricsEntries.length; i++) {
  619. const lyricEntry: GraphicalLyricEntry = staffEntry.LyricsEntries[i];
  620. // calculate LyricWord's Dashes and underscoreLine
  621. if (lyricEntry.ParentLyricWord &&
  622. lyricEntry.ParentLyricWord.GraphicalLyricsEntries[lyricEntry.ParentLyricWord.GraphicalLyricsEntries.length - 1] !== lyricEntry) {
  623. this.calculateSingleLyricWord(lyricEntry);
  624. }
  625. // calculate the underscore line extend if needed
  626. if (lyricEntry.LyricsEntry.extend) {
  627. this.calculateLyricExtend(lyricEntry);
  628. }
  629. }
  630. }
  631. }
  632. /**
  633. * Calculate a single OctaveShift for a [[MultiExpression]].
  634. * @param sourceMeasure
  635. * @param multiExpression
  636. * @param measureIndex
  637. * @param staffIndex
  638. */
  639. protected calculateSingleOctaveShift(sourceMeasure: SourceMeasure, multiExpression: MultiExpression,
  640. measureIndex: number, staffIndex: number): void {
  641. throw new Error(this.abstractNotImplementedErrorMessage);
  642. }
  643. /**
  644. * Calculate a single Pedal for a [[MultiExpression]].
  645. * @param sourceMeasure
  646. * @param multiExpression
  647. * @param measureIndex
  648. * @param staffIndex
  649. */
  650. protected abstract calculateSinglePedal(sourceMeasure: SourceMeasure, multiExpression: MultiExpression,
  651. measureIndex: number, staffIndex: number): void;
  652. /**
  653. * Calculate a single Wavy Line for a [[MultiExpression]].
  654. * @param sourceMeasure
  655. * @param multiExpression
  656. * @param measureIndex
  657. * @param staffIndex
  658. */
  659. protected abstract calculateSingleWavyLine(sourceMeasure: SourceMeasure, multiExpression: MultiExpression,
  660. measureIndex: number, staffIndex: number): void;
  661. /**
  662. * Calculate all the textual [[RepetitionInstruction]]s (e.g. dal segno) for a single [[SourceMeasure]].
  663. * @param repetitionInstruction
  664. * @param measureIndex
  665. */
  666. protected calculateWordRepetitionInstruction(repetitionInstruction: RepetitionInstruction,
  667. measureIndex: number): void {
  668. throw new Error(this.abstractNotImplementedErrorMessage);
  669. }
  670. /**
  671. * Calculate all the Mood and Unknown Expressions for a single [[MultiExpression]].
  672. * @param multiExpression
  673. * @param measureIndex
  674. * @param staffIndex
  675. */
  676. protected calculateMoodAndUnknownExpression(multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  677. // calculate absolute Timestamp
  678. const absoluteTimestamp: Fraction = multiExpression.AbsoluteTimestamp;
  679. const measures: GraphicalMeasure[] = this.graphicalMusicSheet.MeasureList[measureIndex];
  680. let relative: PointF2D = new PointF2D();
  681. const defaultYXml: number = multiExpression.UnknownList[0]?.defaultYXml;
  682. if ((multiExpression.MoodList.length > 0) || (multiExpression.UnknownList.length > 0)) {
  683. let combinedExprString: string = "";
  684. for (let idx: number = 0, len: number = multiExpression.EntriesList.length; idx < len; ++idx) {
  685. const entry: MultiExpressionEntry = multiExpression.EntriesList[idx];
  686. if (entry.prefix !== "") {
  687. if (combinedExprString === "") {
  688. combinedExprString += entry.prefix;
  689. } else {
  690. combinedExprString += " " + entry.prefix;
  691. }
  692. }
  693. if (combinedExprString === "") {
  694. combinedExprString += entry.label;
  695. } else {
  696. combinedExprString += " " + entry.label;
  697. }
  698. }
  699. const staffLine: StaffLine = measures[staffIndex].ParentStaffLine;
  700. if (!staffLine) {
  701. log.debug("MusicSheetCalculator.calculateMoodAndUnknownExpression: staffLine undefined. Returning.");
  702. return;
  703. }
  704. relative = this.getRelativePositionInStaffLineFromTimestamp(absoluteTimestamp, staffIndex, staffLine, staffLine?.isPartOfMultiStaffInstrument());
  705. if (Math.abs(relative.x - 0) < 0.0001) {
  706. relative.x = measures[staffIndex].beginInstructionsWidth + this.rules.RhythmRightMargin;
  707. }
  708. const fontHeight: number = this.rules.UnknownTextHeight;
  709. const placement: PlacementEnum = multiExpression.getPlacementOfFirstEntry();
  710. const graphLabel: GraphicalLabel = this.calculateLabel(staffLine,
  711. relative, combinedExprString,
  712. multiExpression.getFontstyleOfFirstEntry(),
  713. placement,
  714. fontHeight);
  715. if (this.rules.PlaceWordsInsideStafflineFromXml) {
  716. if (defaultYXml < 0 && defaultYXml > -50) { // within staffline
  717. let newY: number = defaultYXml / 10; // OSMD units
  718. newY += this.rules.PlaceWordsInsideStafflineYOffset;
  719. graphLabel.PositionAndShape.RelativePosition.y = newY;
  720. }
  721. }
  722. const gue: GraphicalUnknownExpression = new GraphicalUnknownExpression(
  723. staffLine, graphLabel, placement, measures[staffIndex]?.parentSourceMeasure, multiExpression);
  724. // multiExpression); // TODO would be nice to hand over and save reference to original expression,
  725. // but MultiExpression is not an AbstractExpression.
  726. staffLine.AbstractExpressions.push(gue);
  727. }
  728. }
  729. /**
  730. * Delete all Objects that must be recalculated.
  731. * If graphicalMusicSheet.reCalculate has been called, then this method will be called to reset or remove all flexible
  732. * graphical music symbols (e.g. Ornaments, Lyrics, Slurs) graphicalMusicSheet will have MusicPages, they will have MusicSystems etc...
  733. */
  734. protected clearRecreatedObjects(): void {
  735. // Clear StaffEntries with GraphicalTies
  736. for (let idx: number = 0, len: number = this.staffEntriesWithGraphicalTies.length; idx < len; ++idx) {
  737. const staffEntriesWithGraphicalTie: GraphicalStaffEntry = this.staffEntriesWithGraphicalTies[idx];
  738. staffEntriesWithGraphicalTie.GraphicalTies.length = 0;
  739. }
  740. this.staffEntriesWithGraphicalTies.length = 0;
  741. return;
  742. }
  743. /**
  744. * This method handles a [[StaffEntryLink]].
  745. * @param graphicalStaffEntry
  746. * @param staffEntryLinks
  747. */
  748. protected handleStaffEntryLink(graphicalStaffEntry: GraphicalStaffEntry,
  749. staffEntryLinks: StaffEntryLink[]): void {
  750. log.debug("handleStaffEntryLink not implemented");
  751. }
  752. /**
  753. * Store the newly computed [[Measure]]s in newly created [[MusicSystem]]s.
  754. */
  755. protected calculateMusicSystems(): void {
  756. if (!this.graphicalMusicSheet.MeasureList) {
  757. return;
  758. }
  759. const allMeasures: GraphicalMeasure[][] = this.graphicalMusicSheet.MeasureList;
  760. if (!allMeasures) {
  761. return;
  762. }
  763. if (this.rules.MinMeasureToDrawIndex > allMeasures.length - 1) {
  764. log.debug("minimum measure to draw index out of range. resetting min measure index to limit.");
  765. this.rules.MinMeasureToDrawIndex = allMeasures.length - 1;
  766. }
  767. // visible 2D-MeasureList
  768. const visibleMeasureList: GraphicalMeasure[][] = [];
  769. for (let idx: number = this.rules.MinMeasureToDrawIndex, len: number = allMeasures.length;
  770. idx < len && idx <= this.rules.MaxMeasureToDrawIndex; ++idx) {
  771. const graphicalMeasures: GraphicalMeasure[] = allMeasures[idx];
  772. const visiblegraphicalMeasures: GraphicalMeasure[] = [];
  773. for (let idx2: number = 0, len2: number = graphicalMeasures.length; idx2 < len2; ++idx2) {
  774. const graphicalMeasure: GraphicalMeasure = allMeasures[idx][idx2];
  775. if (graphicalMeasure?.isVisible()) {
  776. visiblegraphicalMeasures.push(graphicalMeasure);
  777. if (this.rules.ColoringEnabled) {
  778. // (re-)color notes
  779. for (const staffEntry of graphicalMeasure.staffEntries) {
  780. for (const gve of staffEntry.graphicalVoiceEntries) {
  781. gve.color();
  782. }
  783. }
  784. }
  785. }
  786. }
  787. visibleMeasureList.push(visiblegraphicalMeasures);
  788. }
  789. // find out how many StaffLine Instances we need
  790. let numberOfStaffLines: number = 0;
  791. for (let idx: number = 0, len: number = visibleMeasureList.length; idx < len; ++idx) {
  792. const gmlist: GraphicalMeasure[] = visibleMeasureList[idx];
  793. numberOfStaffLines = Math.max(gmlist.length, numberOfStaffLines);
  794. break;
  795. }
  796. if (numberOfStaffLines === 0) {
  797. return;
  798. }
  799. // build the MusicSystems
  800. let musicSystemBuilder: MusicSystemBuilder;
  801. const measureCount: number = allMeasures.length;
  802. if (!this.rules.UseJustifiedBuilder ||
  803. measureCount === 1 ||
  804. this.rules.RenderSingleHorizontalStaffline) {
  805. musicSystemBuilder = new MusicSystemBuilder();
  806. // JustifiedMusicSystemBuilder makes measures way too large with
  807. // only one measure or RenderSingleHorizontalStaffline.
  808. } else {
  809. musicSystemBuilder = new JustifiedMusicSystemBuilder();
  810. }
  811. musicSystemBuilder.initialize(this.graphicalMusicSheet, visibleMeasureList, numberOfStaffLines);
  812. this.musicSystems = musicSystemBuilder.buildMusicSystems();
  813. this.formatMeasures();
  814. // check for Measures with only WholeRestNotes and correct their X-Position (middle of Measure)
  815. // this.checkMeasuresForWholeRestNotes(); // this currently does nothing
  816. if (!this.leadSheet) {
  817. // calculate Beam Placement
  818. // this.calculateBeams(); // does nothing for now, because layoutBeams() is an empty method
  819. // possible Displacement of RestNotes
  820. this.optimizeRestPlacement();
  821. // possible Displacement of RestNotes
  822. this.calculateStaffEntryArticulationMarks();
  823. if (this.rules.RenderSlurs) { // technically we should separate slurs and ties, but shouldn't be relevant for now
  824. // calculate Ties
  825. this.calculateTieCurves();
  826. }
  827. }
  828. // calculate Sky- and BottomLine
  829. // will have reasonable values only between ObjectsBorders (eg StaffEntries)
  830. this.calculateSkyBottomLines();
  831. // calculate TupletsNumbers
  832. this.calculateTupletNumbers();
  833. // calculate MeasureNumbers
  834. if (this.rules.RenderMeasureNumbers) {
  835. for (let idx: number = 0, len: number = this.musicSystems.length; idx < len; ++idx) {
  836. const musicSystem: MusicSystem = this.musicSystems[idx];
  837. this.calculateMeasureNumberPlacement(musicSystem);
  838. }
  839. }
  840. if (this.rules.RenderFingerings) {
  841. this.calculateFingerings(); // if this is done after slurs, fingerings can be on top of slurs
  842. }
  843. // calculate Slurs
  844. if (!this.leadSheet && this.rules.RenderSlurs) {
  845. this.calculateSlurs();
  846. }
  847. this.calculateGlissandi();
  848. //Calculate measure number skyline AFTER slurs
  849. if (this.rules.RenderMeasureNumbers) {
  850. for (let idx: number = 0, len: number = this.musicSystems.length; idx < len; ++idx) {
  851. const musicSystem: MusicSystem = this.musicSystems[idx];
  852. this.calculateMeasureNumberSkyline(musicSystem);
  853. }
  854. }
  855. // calculate StaffEntry Ornaments
  856. // (must come after Slurs)
  857. if (!this.leadSheet) {
  858. this.calculateOrnaments();
  859. }
  860. // calculate StaffEntry ChordSymbols
  861. this.calculateChordSymbols();
  862. if (!this.leadSheet) {
  863. // calculate all Instantaneous/Continuous Dynamics Expressions
  864. this.calculateDynamicExpressions();
  865. // calculate all Mood and Unknown Expression
  866. this.calculateMoodAndUnknownExpressions();
  867. // Calculate the alignment of close expressions
  868. this.calculateExpressionAlignements();
  869. // calculate all OctaveShifts
  870. this.calculateOctaveShifts();
  871. if (this.rules.RenderPedals) {
  872. // calculate all Pedal Expressions
  873. this.calculatePedals();
  874. }
  875. //calculate all wavy lines (vibrato, trill marks)
  876. if (this.rules.RenderWavyLines) {
  877. this.calculateWavyLines();
  878. }
  879. // calcualte RepetitionInstructions (Dal Segno, Coda, etc)
  880. this.calculateWordRepetitionInstructions();
  881. }
  882. // calculate endings last, so they appear above measure numbers
  883. this.calculateRepetitionEndings();
  884. // calcualte all Tempo Expressions
  885. if (!this.leadSheet) {
  886. this.calculateTempoExpressions();
  887. }
  888. this.calculateRehearsalMarks();
  889. // calculate all LyricWords Positions
  890. this.calculateLyricsPosition();
  891. // update all StaffLine's Borders
  892. // create temporary Object, just to call the methods (in order to avoid declaring them static)
  893. for (let idx2: number = 0, len2: number = this.musicSystems.length; idx2 < len2; ++idx2) {
  894. const musicSystem: MusicSystem = this.musicSystems[idx2];
  895. for (let idx3: number = 0, len3: number = musicSystem.StaffLines.length; idx3 < len3; ++idx3) {
  896. const staffLine: StaffLine = musicSystem.StaffLines[idx3];
  897. this.updateStaffLineBorders(staffLine);
  898. }
  899. }
  900. // calculate Y-spacing -> MusicPages are created here
  901. musicSystemBuilder.calculateSystemYLayout();
  902. // calculate marked Areas for Systems
  903. this.calculateMarkedAreas();
  904. // the following must be done after Y-spacing, when the MusicSystems's final Dimensions are set
  905. // set the final yPositions of Objects such as SystemLabels and SystemLinesContainers,
  906. // create all System Lines, Brackets and MeasureNumbers (for all systems and for all pages)
  907. for (let idx: number = 0, len: number = this.graphicalMusicSheet.MusicPages.length; idx < len; ++idx) {
  908. const graphicalMusicPage: GraphicalMusicPage = this.graphicalMusicSheet.MusicPages[idx];
  909. for (let idx2: number = 0, len2: number = graphicalMusicPage.MusicSystems.length; idx2 < len2; ++idx2) {
  910. const isFirstSystem: boolean = idx === 0 && idx2 === 0;
  911. const musicSystem: MusicSystem = graphicalMusicPage.MusicSystems[idx2];
  912. musicSystem.setMusicSystemLabelsYPosition();
  913. if (!this.leadSheet) {
  914. musicSystem.setYPositionsToVerticalLineObjectsAndCreateLines(this.rules);
  915. musicSystem.createSystemLeftLine(this.rules.SystemThinLineWidth, this.rules.SystemLabelsRightMargin, isFirstSystem);
  916. musicSystem.createInstrumentBrackets(this.graphicalMusicSheet.ParentMusicSheet.Instruments, this.rules.StaffHeight);
  917. musicSystem.createGroupBrackets(this.graphicalMusicSheet.ParentMusicSheet.InstrumentalGroups, this.rules.StaffHeight, 0);
  918. musicSystem.alignBeginInstructions();
  919. } else if (musicSystem === musicSystem.Parent.MusicSystems[0]) {
  920. musicSystem.createSystemLeftLine(this.rules.SystemThinLineWidth, this.rules.SystemLabelsRightMargin, isFirstSystem);
  921. }
  922. musicSystem.calculateBorders(this.rules);
  923. }
  924. const distance: number = graphicalMusicPage.MusicSystems[0].PositionAndShape.BorderTop;
  925. for (let idx2: number = 0, len2: number = graphicalMusicPage.MusicSystems.length; idx2 < len2; ++idx2) {
  926. const musicSystem: MusicSystem = graphicalMusicPage.MusicSystems[idx2];
  927. // let newPosition: PointF2D = new PointF2D(musicSystem.PositionAndShape.RelativePosition.x,
  928. // musicSystem.PositionAndShape.RelativePosition.y - distance);
  929. musicSystem.PositionAndShape.RelativePosition =
  930. new PointF2D(musicSystem.PositionAndShape.RelativePosition.x, musicSystem.PositionAndShape.RelativePosition.y - distance);
  931. }
  932. // add ActivitySymbolClickArea - currently unused, extends boundingbox of MusicSystem unnecessarily -> PageRightMargin 0 impossible
  933. // for (let idx2: number = 0, len2: number = graphicalMusicPage.MusicSystems.length; idx2 < len2; ++idx2) {
  934. // const musicSystem: MusicSystem = graphicalMusicPage.MusicSystems[idx2];
  935. // for (let idx3: number = 0, len3: number = musicSystem.StaffLines.length; idx3 < len3; ++idx3) {
  936. // const staffLine: StaffLine = musicSystem.StaffLines[idx3];
  937. // staffLine.addActivitySymbolClickArea();
  938. // }
  939. // }
  940. // calculate TopBottom Borders for all elements recursively
  941. // necessary for composer label (page labels) for high notes in first system
  942. graphicalMusicPage.PositionAndShape.calculateTopBottomBorders();
  943. // TODO how much performance does this cost? can we reduce the amount of calculations, e.g. only checking top?
  944. // calculate all Labels's Positions for the first Page
  945. if (graphicalMusicPage === this.graphicalMusicSheet.MusicPages[0]) {
  946. this.calculatePageLabels(graphicalMusicPage);
  947. }
  948. // calculate TopBottom Borders for all elements recursively
  949. graphicalMusicPage.PositionAndShape.calculateTopBottomBorders(); // this is where top bottom borders were originally calculated (only once)
  950. }
  951. }
  952. protected calculateMarkedAreas(): void {
  953. //log.debug("calculateMarkedAreas not implemented");
  954. return;
  955. }
  956. protected calculateChordSymbols(): void {
  957. for (const musicSystem of this.musicSystems) {
  958. for (const staffLine of musicSystem.StaffLines) {
  959. const skybottomcalculator: SkyBottomLineCalculator = staffLine.SkyBottomLineCalculator;
  960. let minimumOffset: number = Number.MAX_SAFE_INTEGER; // only calculated if option set
  961. if (this.rules.ChordSymbolYAlignment && this.rules.ChordSymbolYAlignmentScope === "staffline") {
  962. // get the max y position of all chord symbols in the staffline in advance
  963. const alignmentScopedStaffEntries: GraphicalStaffEntry[] = [];
  964. for (const measure of staffLine.Measures) {
  965. alignmentScopedStaffEntries.push(...measure.staffEntries);
  966. }
  967. minimumOffset = this.calculateAlignedChordSymbolsOffset(alignmentScopedStaffEntries, skybottomcalculator);
  968. }
  969. for (let measureStafflineIndex: number = 0; measureStafflineIndex < staffLine.Measures.length; measureStafflineIndex++) {
  970. const measure: GraphicalMeasure = staffLine.Measures[measureStafflineIndex];
  971. if (this.rules.ChordSymbolYAlignment && this.rules.ChordSymbolYAlignmentScope === "measure") {
  972. minimumOffset = this.calculateAlignedChordSymbolsOffset(measure.staffEntries, skybottomcalculator);
  973. }
  974. let previousChordContainer: GraphicalChordSymbolContainer;
  975. for (const staffEntry of measure.staffEntries) {
  976. if (!staffEntry.graphicalChordContainers || staffEntry.graphicalChordContainers.length === 0) {
  977. continue;
  978. }
  979. for (let i: number = 0; i < staffEntry.graphicalChordContainers.length; i++) {
  980. const graphicalChordContainer: GraphicalChordSymbolContainer = staffEntry.graphicalChordContainers[i];
  981. // check for chord not over a note
  982. if (staffEntry.graphicalVoiceEntries.length === 0 && staffEntry.relInMeasureTimestamp.RealValue > 0) {
  983. // re-position (second chord symbol on whole measure rest)
  984. let firstNoteStartX: number = 0;
  985. if (measure.staffEntries[0].relInMeasureTimestamp.RealValue === 0) {
  986. firstNoteStartX = measure.staffEntries[0].PositionAndShape.RelativePosition.x;
  987. if (measure.MeasureNumber === 1) {
  988. firstNoteStartX += this.rules.ChordSymbolWholeMeasureRestXOffsetMeasure1;
  989. // shift second chord same way as first chord
  990. }
  991. }
  992. const measureEndX: number = measure.PositionAndShape.Size.width - measure.endInstructionsWidth;
  993. const proportionInMeasure: number = staffEntry.relInMeasureTimestamp.RealValue / measure.parentSourceMeasure.Duration.RealValue;
  994. let newStartX: number = firstNoteStartX + (measureEndX - firstNoteStartX) * proportionInMeasure +
  995. graphicalChordContainer.PositionAndShape.BorderMarginLeft; // negative -> shift a bit left to where it starts visually
  996. if (previousChordContainer) {
  997. // prevent overlap to previous chord symbol
  998. newStartX = Math.max(newStartX, previousChordContainer.PositionAndShape.RelativePosition.x +
  999. previousChordContainer.GraphicalLabel.PositionAndShape.Size.width +
  1000. this.rules.ChordSymbolXSpacing);
  1001. }
  1002. graphicalChordContainer.PositionAndShape.RelativePosition.x = newStartX;
  1003. graphicalChordContainer.PositionAndShape.Parent = measure.staffEntries[0].PositionAndShape.Parent;
  1004. // TODO it would be more clean to set the staffEntry relative position instead of the container's,
  1005. // so that the staff entry also gets a valid position (and not relative 0),
  1006. // but this is tricky with elongationFactor, skyline etc, would need some adjustments
  1007. // // graphicalChordContainer.PositionAndShape.Parent = measure.staffEntries[0].PositionAndShape.Parent; // not here
  1008. // // don't switch parent from StaffEntry if setting staffEntry.x
  1009. // staffEntry.PositionAndShape.RelativePosition.x = newStartX;
  1010. // staffEntry.PositionAndShape.calculateAbsolutePosition();
  1011. }
  1012. const gps: BoundingBox = graphicalChordContainer.PositionAndShape;
  1013. const parentBbox: BoundingBox = gps.Parent; // usually the staffEntry (bbox), but sometimes measure (for whole measure rests)
  1014. if (parentBbox.DataObject instanceof GraphicalMeasure) {
  1015. if (staffEntry.relInMeasureTimestamp.RealValue === 0) {
  1016. gps.RelativePosition.x = Math.max(measure.beginInstructionsWidth, gps.RelativePosition.x);
  1017. // beginInstructionsWidth wasn't set correctly before this
  1018. if (measure.MeasureNumber === 1 && gps.RelativePosition.x > 3) {
  1019. gps.RelativePosition.x += this.rules.ChordSymbolWholeMeasureRestXOffsetMeasure1;
  1020. }
  1021. }
  1022. }
  1023. // check if there already exists a vertical staffentry with the same relative timestamp,
  1024. // use its relativePosition (= x-align chord symbols to vertical staffentries in other measures)
  1025. if (staffEntry.PositionAndShape.RelativePosition.x === 0) {
  1026. const verticalMeasures: GraphicalMeasure[] = musicSystem.GraphicalMeasures[measureStafflineIndex];
  1027. for (const verticalMeasure of verticalMeasures) {
  1028. let positionFound: boolean = false;
  1029. for (const verticalSe of verticalMeasure.staffEntries) {
  1030. if (verticalSe.relInMeasureTimestamp === staffEntry.relInMeasureTimestamp &&
  1031. verticalSe.PositionAndShape.RelativePosition.x !== 0) {
  1032. gps.RelativePosition.x = verticalSe.PositionAndShape.RelativePosition.x;
  1033. positionFound = true;
  1034. break;
  1035. }
  1036. }
  1037. if (positionFound) {
  1038. break;
  1039. }
  1040. }
  1041. }
  1042. const start: number = gps.BorderMarginLeft + parentBbox.AbsolutePosition.x + gps.RelativePosition.x;
  1043. const end: number = gps.BorderMarginRight + parentBbox.AbsolutePosition.x + gps.RelativePosition.x;
  1044. if (!this.rules.ChordSymbolYAlignment || minimumOffset > 0) {
  1045. //minimumOffset = this.calculateAlignedChordSymbolsOffset([staffEntry], skybottomcalculator);
  1046. minimumOffset = skybottomcalculator.getSkyLineMinInRange(start, end); // same as above, less code executed
  1047. }
  1048. let yShift: number = 0;
  1049. if (i === 0) {
  1050. yShift += this.rules.ChordSymbolYOffset;
  1051. yShift += 0.1; // above is a bit closer to the notes than below ones for some reason
  1052. } else {
  1053. yShift += this.rules.ChordSymbolYPadding;
  1054. }
  1055. yShift *= -1;
  1056. const gLabel: GraphicalLabel = graphicalChordContainer.GraphicalLabel;
  1057. gLabel.PositionAndShape.RelativePosition.y = minimumOffset + yShift;
  1058. gLabel.setLabelPositionAndShapeBorders();
  1059. gLabel.PositionAndShape.calculateBoundingBox();
  1060. skybottomcalculator.updateSkyLineInRange(start, end, minimumOffset + gLabel.PositionAndShape.BorderMarginTop);
  1061. previousChordContainer = graphicalChordContainer;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. protected calculateAlignedChordSymbolsOffset(staffEntries: GraphicalStaffEntry[], sbc: SkyBottomLineCalculator): number {
  1069. let minimumOffset: number = Number.MAX_SAFE_INTEGER;
  1070. for (const staffEntry of staffEntries) {
  1071. for (const graphicalChordContainer of staffEntry.graphicalChordContainers) {
  1072. const gps: BoundingBox = graphicalChordContainer.PositionAndShape;
  1073. const parentBbox: BoundingBox = gps.Parent; // usually the staffEntry (bbox), but sometimes measure (for whole measure rests)
  1074. let start: number = gps.BorderMarginLeft + parentBbox.AbsolutePosition.x;
  1075. let end: number = gps.BorderMarginRight + parentBbox.AbsolutePosition.x;
  1076. if (parentBbox.DataObject instanceof GraphicalMeasure) {
  1077. start += (parentBbox.DataObject as GraphicalMeasure).beginInstructionsWidth;
  1078. end += (parentBbox.DataObject as GraphicalMeasure).beginInstructionsWidth;
  1079. }
  1080. minimumOffset = Math.min(minimumOffset, sbc.getSkyLineMinInRange(start, end));
  1081. }
  1082. }
  1083. return minimumOffset;
  1084. }
  1085. /**
  1086. * Do layout on staff measures which only consist of a full rest.
  1087. * @param rest
  1088. * @param gse
  1089. * @param measure
  1090. */
  1091. protected layoutMeasureWithWholeRest(rest: GraphicalNote, gse: GraphicalStaffEntry,
  1092. measure: GraphicalMeasure): void {
  1093. return;
  1094. }
  1095. protected layoutBeams(staffEntry: GraphicalStaffEntry): void {
  1096. return;
  1097. }
  1098. protected layoutArticulationMarks(articulations: Articulation[], voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry): void {
  1099. return;
  1100. }
  1101. protected layoutOrnament(ornaments: OrnamentContainer, voiceEntry: VoiceEntry,
  1102. graphicalStaffEntry: GraphicalStaffEntry): void {
  1103. return;
  1104. }
  1105. protected calculateRestNotePlacementWithinGraphicalBeam(graphicalStaffEntry: GraphicalStaffEntry,
  1106. restNote: GraphicalNote,
  1107. previousNote: GraphicalNote,
  1108. nextStaffEntry: GraphicalStaffEntry,
  1109. nextNote: GraphicalNote): void {
  1110. return;
  1111. }
  1112. protected calculateTupletNumbers(): void {
  1113. if (!this.rules.TupletNumberLimitConsecutiveRepetitions) {
  1114. return;
  1115. }
  1116. let currentTupletNumber: number = -1;
  1117. let currentTypeLength: Fraction = undefined;
  1118. let consecutiveTupletCount: number = 0;
  1119. let currentTuplet: Tuplet = undefined;
  1120. let skipTuplet: Tuplet = undefined; // if set, ignore (further) handling of this tuplet
  1121. const disabledPerVoice: Object = {};
  1122. for (const instrument of this.graphicalMusicSheet.ParentMusicSheet.Instruments) {
  1123. for (const voice of instrument.Voices) {
  1124. consecutiveTupletCount = 0; // reset for next voice
  1125. disabledPerVoice[voice.VoiceId] = {};
  1126. for (const ve of voice.VoiceEntries) {
  1127. if (ve.Notes.length > 0) {
  1128. const firstNote: Note = ve.Notes[0];
  1129. if (!firstNote.NoteTuplet ||
  1130. firstNote.NoteTuplet.shouldBeBracketed(
  1131. this.rules.TupletsBracketedUseXMLValue,
  1132. this.rules.TupletsBracketed,
  1133. this.rules.TripletsBracketed
  1134. )
  1135. ) {
  1136. // don't disable tuplet numbers under these conditions, reset consecutive tuplet count
  1137. currentTupletNumber = -1;
  1138. consecutiveTupletCount = 0;
  1139. currentTuplet = undefined;
  1140. currentTypeLength = undefined;
  1141. continue;
  1142. }
  1143. if (firstNote.NoteTuplet === skipTuplet) {
  1144. continue;
  1145. }
  1146. let typeLength: Fraction = firstNote.TypeLength;
  1147. if (!typeLength) {
  1148. // shouldn't happen, now that rest notes have TypeLength set too, see VoiceGenerator.addRestNote(), addSingleNote()
  1149. // see test_tuplets_starting_with_rests_layout.mxl (first measure bass)
  1150. log.warn("note missing TypeLength");
  1151. typeLength = firstNote.NoteTuplet.Fractions[0];
  1152. }
  1153. if (firstNote.NoteTuplet !== currentTuplet) {
  1154. if (disabledPerVoice[voice.VoiceId][firstNote.NoteTuplet.TupletLabelNumber]) {
  1155. if (disabledPerVoice[voice.VoiceId][firstNote.NoteTuplet.TupletLabelNumber][typeLength.RealValue]) {
  1156. firstNote.NoteTuplet.RenderTupletNumber = false;
  1157. skipTuplet = firstNote.NoteTuplet;
  1158. continue;
  1159. }
  1160. }
  1161. }
  1162. if (firstNote.NoteTuplet.TupletLabelNumber !== currentTupletNumber ||
  1163. !typeLength.Equals(currentTypeLength) ||
  1164. firstNote.NoteTuplet.Bracket) {
  1165. currentTupletNumber = firstNote.NoteTuplet.TupletLabelNumber;
  1166. currentTypeLength = typeLength;
  1167. consecutiveTupletCount = 0;
  1168. }
  1169. currentTuplet = firstNote.NoteTuplet;
  1170. consecutiveTupletCount++;
  1171. if (consecutiveTupletCount <= this.rules.TupletNumberMaxConsecutiveRepetitions) {
  1172. firstNote.NoteTuplet.RenderTupletNumber = true; // need to re-activate after re-render when it was set to false
  1173. }
  1174. if (consecutiveTupletCount > this.rules.TupletNumberMaxConsecutiveRepetitions) {
  1175. firstNote.NoteTuplet.RenderTupletNumber = false;
  1176. if (this.rules.TupletNumberAlwaysDisableAfterFirstMax) {
  1177. if (!disabledPerVoice[voice.VoiceId][currentTupletNumber]) {
  1178. disabledPerVoice[voice.VoiceId][currentTupletNumber] = {};
  1179. }
  1180. disabledPerVoice[voice.VoiceId][currentTupletNumber][typeLength.RealValue] = true;
  1181. }
  1182. }
  1183. skipTuplet = currentTuplet;
  1184. }
  1185. }
  1186. }
  1187. }
  1188. return;
  1189. }
  1190. protected calculateSlurs(): void {
  1191. return;
  1192. }
  1193. protected calculateGlissandi(): void {
  1194. return;
  1195. }
  1196. protected calculateDynamicExpressionsForMultiExpression(multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  1197. return;
  1198. }
  1199. /**
  1200. * This method calculates the RelativePosition of a single verbal GraphicalContinuousDynamic.
  1201. * @param graphicalContinuousDynamic Graphical continous dynamic to be calculated
  1202. * @param startPosInStaffline Starting point in staff line
  1203. */
  1204. protected calculateGraphicalVerbalContinuousDynamic(graphicalContinuousDynamic: GraphicalContinuousDynamicExpression,
  1205. startPosInStaffline: PointF2D): void {
  1206. // if ContinuousDynamicExpression is given from words
  1207. const graphLabel: GraphicalLabel = graphicalContinuousDynamic.Label;
  1208. const left: number = startPosInStaffline.x + graphLabel.PositionAndShape.BorderMarginLeft;
  1209. const right: number = startPosInStaffline.x + graphLabel.PositionAndShape.BorderMarginRight;
  1210. // placement always below the currentStaffLine, with the exception of Voice Instrument (-> above)
  1211. const placement: PlacementEnum = graphicalContinuousDynamic.ContinuousDynamic.Placement;
  1212. const staffLine: StaffLine = graphicalContinuousDynamic.ParentStaffLine;
  1213. const skyBottomLineCalculator: SkyBottomLineCalculator = staffLine.SkyBottomLineCalculator;
  1214. let drawingHeight: number;
  1215. if (placement === PlacementEnum.Below) {
  1216. drawingHeight = skyBottomLineCalculator.getBottomLineMaxInRange(left, right); // Bottom line
  1217. graphLabel.PositionAndShape.RelativePosition = new PointF2D(startPosInStaffline.x, drawingHeight - graphLabel.PositionAndShape.BorderMarginTop);
  1218. } else {
  1219. drawingHeight = skyBottomLineCalculator.getSkyLineMinInRange(left, right);
  1220. graphLabel.PositionAndShape.RelativePosition = new PointF2D(startPosInStaffline.x, drawingHeight - graphLabel.PositionAndShape.BorderMarginBottom);
  1221. }
  1222. }
  1223. /**
  1224. * This method calculates the RelativePosition of a single GraphicalContinuousDynamic.
  1225. * @param graphicalContinuousDynamic Graphical continous dynamic to be calculated
  1226. * @param startPosInStaffline Starting point in staff line
  1227. */
  1228. public calculateGraphicalContinuousDynamic(graphicalContinuousDynamic: GraphicalContinuousDynamicExpression, startPosInStaffline: PointF2D): void {
  1229. const isSoftAccent: boolean = graphicalContinuousDynamic.IsSoftAccent;
  1230. const staffIndex: number = graphicalContinuousDynamic.ParentStaffLine.ParentStaff.idInMusicSheet;
  1231. // TODO: Previously the staffIndex was passed down. BUT you can (and this function actually does this) get it from
  1232. // the musicSystem OR from the ParentStaffLine. Is this the same index?
  1233. // const staffIndex: number = musicSystem.StaffLines.indexOf(staffLine);
  1234. // We know we have an end measure because otherwise we won't be called
  1235. const endMeasure: GraphicalMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(
  1236. graphicalContinuousDynamic.ContinuousDynamic.EndMultiExpression.SourceMeasureParent, staffIndex);
  1237. if (!endMeasure) {
  1238. log.warn("MusicSheetCalculator.calculateGraphicalContinuousDynamic: No endMeasure found");
  1239. return;
  1240. }
  1241. graphicalContinuousDynamic.EndMeasure = endMeasure;
  1242. const staffLine: StaffLine = graphicalContinuousDynamic.ParentStaffLine;
  1243. const endStaffLine: StaffLine = endMeasure.ParentStaffLine;
  1244. // check if Expression spreads over the same StaffLine or not
  1245. const sameStaffLine: boolean = endStaffLine && staffLine === endStaffLine;
  1246. let isPartOfMultiStaffInstrument: boolean = false;
  1247. if (endStaffLine) { // unfortunately we can't do something like (endStaffLine?.check() || staffLine?.check()) in this typescript version
  1248. isPartOfMultiStaffInstrument = endStaffLine?.isPartOfMultiStaffInstrument();
  1249. } else if (staffLine) {
  1250. isPartOfMultiStaffInstrument = staffLine?.isPartOfMultiStaffInstrument();
  1251. }
  1252. const endAbsoluteTimestamp: Fraction = Fraction.createFromFraction(graphicalContinuousDynamic.ContinuousDynamic.EndMultiExpression.AbsoluteTimestamp);
  1253. const container: VerticalGraphicalStaffEntryContainer = this.graphicalMusicSheet.GetVerticalContainerFromTimestamp(endAbsoluteTimestamp);
  1254. const parentMeasure: GraphicalMeasure = container.getFirstNonNullStaffEntry().parentMeasure;
  1255. const endOfMeasure: number = parentMeasure.PositionAndShape.AbsolutePosition.x + parentMeasure.PositionAndShape.BorderRight;
  1256. let maxNoteLength: Fraction = new Fraction(0, 0, 0);
  1257. for (const staffEntry of container.StaffEntries) {
  1258. const currentMaxLength: Fraction = staffEntry?.sourceStaffEntry?.calculateMaxNoteLength(false);
  1259. if ( currentMaxLength?.gt(maxNoteLength) ) {
  1260. maxNoteLength = currentMaxLength;
  1261. }
  1262. }
  1263. const useStaffEntryBorderLeft: boolean = !isSoftAccent &&
  1264. graphicalContinuousDynamic.ContinuousDynamic.DynamicType === ContDynamicEnum.diminuendo;
  1265. const endPosInStaffLine: PointF2D = this.getRelativePositionInStaffLineFromTimestamp(
  1266. endAbsoluteTimestamp, staffIndex, endStaffLine, isPartOfMultiStaffInstrument, 0,
  1267. useStaffEntryBorderLeft);
  1268. const beginOfNextNote: Fraction = Fraction.plus(endAbsoluteTimestamp, maxNoteLength);
  1269. // TODO for the last note of the piece (wedge ending after last note), this timestamp is incorrect, being after the last note
  1270. // but there's a workaround in getRelativePositionInStaffLineFromTimestamp() via the variable endAfterRightStaffEntry
  1271. const nextNotePosInStaffLine: PointF2D = this.getRelativePositionInStaffLineFromTimestamp(
  1272. beginOfNextNote, staffIndex, endStaffLine, isPartOfMultiStaffInstrument, 0,
  1273. graphicalContinuousDynamic.ContinuousDynamic.DynamicType === ContDynamicEnum.diminuendo);
  1274. const wedgePadding: number = this.rules.SoftAccentWedgePadding;
  1275. const staffEntryWidth: number = container.getFirstNonNullStaffEntry().PositionAndShape.Size.width; // staff entry widths for whole notes is too long
  1276. const sizeFactor: number = this.rules.SoftAccentSizeFactor;
  1277. //const standardWidth: number = 2;
  1278. //If the next note position is not on the next staffline
  1279. //extend close to the next note
  1280. if (isSoftAccent) {
  1281. //startPosInStaffline.x -= 1;
  1282. startPosInStaffline.x -= staffEntryWidth / 2 * sizeFactor + wedgePadding;
  1283. endPosInStaffLine.x = startPosInStaffline.x + staffEntryWidth / 2 * sizeFactor;
  1284. } else if (nextNotePosInStaffLine.x > endPosInStaffLine.x && nextNotePosInStaffLine.x < endOfMeasure) {
  1285. endPosInStaffLine.x += (nextNotePosInStaffLine.x - endPosInStaffLine.x) / this.rules.WedgeEndDistanceBetweenTimestampsFactor;
  1286. } else { //Otherwise extend to the end of the measure
  1287. endPosInStaffLine.x = endOfMeasure - this.rules.WedgeHorizontalMargin;
  1288. }
  1289. const startCollideBox: BoundingBox =
  1290. this.dynamicExpressionMap.get(graphicalContinuousDynamic.ContinuousDynamic.StartMultiExpression.AbsoluteTimestamp.RealValue);
  1291. if (startCollideBox) {
  1292. if ((startCollideBox.DataObject as any).ParentStaffLine === staffLine) {
  1293. // TODO the dynamicExpressionMap doesn't distinguish between staffLines, so we may react to a different staffline otherwise
  1294. // so the more fundamental solution would be to fix dynamicExpressionMap mapping across stafflines.
  1295. startPosInStaffline.x = startCollideBox.RelativePosition.x + this.rules.WedgeHorizontalMargin;
  1296. startPosInStaffline.x += startCollideBox.BorderMarginRight;
  1297. }
  1298. }
  1299. //currentMusicSystem and currentStaffLine
  1300. const musicSystem: MusicSystem = staffLine.ParentMusicSystem;
  1301. const currentStaffLineIndex: number = musicSystem.StaffLines.indexOf(staffLine);
  1302. const skyBottomLineCalculator: SkyBottomLineCalculator = staffLine.SkyBottomLineCalculator;
  1303. // let expressionIndex: number;
  1304. // placement always below the currentStaffLine, with the exception of Voice Instrument (-> above)
  1305. const placement: PlacementEnum = graphicalContinuousDynamic.ContinuousDynamic.Placement;
  1306. // if ContinuousDynamicExpression is given from wedge
  1307. let endGraphicalContinuousDynamic: GraphicalContinuousDynamicExpression = undefined;
  1308. // last length check
  1309. if (sameStaffLine && endPosInStaffLine.x - startPosInStaffline.x < this.rules.WedgeMinLength && !isSoftAccent) {
  1310. endPosInStaffLine.x = startPosInStaffline.x + this.rules.WedgeMinLength;
  1311. }
  1312. // First staff wedge always starts at the given position and the last and inbetween wedges always start at the begin of measure
  1313. // TODO: rename upper / lower to first / last, now that we can have inbetween wedges, though this creates a huge diff, and this should be clear now.
  1314. const upperStartX: number = startPosInStaffline.x;
  1315. let lowerStartX: number = endStaffLine.Measures[0].beginInstructionsWidth - this.rules.WedgeHorizontalMargin - 2;
  1316. //TODO fix this when a range of measures to draw is given that doesn't include all the dynamic's measures (e.g. for crescendo)
  1317. let upperEndX: number = 0;
  1318. let lowerEndX: number = 0;
  1319. /** Wedges between first and last staffline, in case we span more than 2 stafflines. */
  1320. const inbetweenWedges: GraphicalContinuousDynamicExpression[] = [];
  1321. if (!sameStaffLine) {
  1322. // add wedge in all stafflines between (including) start and end measure
  1323. upperEndX = staffLine.PositionAndShape.Size.width;
  1324. lowerEndX = endPosInStaffLine.x;
  1325. // get all stafflines between start measure and end measure, and add wedges for them.
  1326. // This would be less lines of code if there was already a list of stafflines for the sheet.
  1327. const stafflinesCovered: StaffLine[] = [staffLine, endStaffLine]; // start and end staffline already get a wedge
  1328. const startMeasure: GraphicalMeasure = graphicalContinuousDynamic.StartMeasure;
  1329. let nextMeasure: GraphicalMeasure = startMeasure;
  1330. let iterations: number = 0; // safety measure against infinite loop
  1331. let sourceMeasureIndex: number = startMeasure.parentSourceMeasure.measureListIndex;
  1332. while (nextMeasure !== endMeasure && iterations < 1000) {
  1333. const nextSourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[sourceMeasureIndex];
  1334. const potentialNextMeasure: GraphicalMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(
  1335. nextSourceMeasure, staffIndex
  1336. );
  1337. if (potentialNextMeasure) {
  1338. nextMeasure = potentialNextMeasure;
  1339. const nextStaffline: StaffLine = nextMeasure.ParentStaffLine;
  1340. if (!stafflinesCovered.includes(nextStaffline)) {
  1341. stafflinesCovered.push(nextStaffline);
  1342. const newWedge: GraphicalContinuousDynamicExpression =
  1343. new GraphicalContinuousDynamicExpression(
  1344. graphicalContinuousDynamic.ContinuousDynamic,
  1345. nextStaffline,
  1346. nextStaffline.Measures[0].parentSourceMeasure
  1347. );
  1348. newWedge.IsSplittedPart = true;
  1349. inbetweenWedges.push(newWedge);
  1350. }
  1351. }
  1352. sourceMeasureIndex++;
  1353. iterations++;
  1354. }
  1355. // last wedge at endMeasure
  1356. endGraphicalContinuousDynamic = new GraphicalContinuousDynamicExpression(
  1357. graphicalContinuousDynamic.ContinuousDynamic, endStaffLine, endMeasure.parentSourceMeasure);
  1358. endGraphicalContinuousDynamic.IsSplittedPart = true;
  1359. graphicalContinuousDynamic.IsSplittedPart = true;
  1360. } else {
  1361. upperEndX = endPosInStaffLine.x;
  1362. }
  1363. if (isSoftAccent) {
  1364. // secondGraphicalContinuousDynamic = new GraphicalContinuousDynamicExpression(
  1365. // graphicalContinuousDynamic.ContinuousDynamic,
  1366. // graphicalContinuousDynamic.ParentStaffLine,
  1367. // graphicalContinuousDynamic.StartMeasure.parentSourceMeasure
  1368. // );
  1369. // secondGraphicalContinuousDynamic.StartIsEnd = true;
  1370. // doesn't work well with secondGraphicalDynamic, positions/rendering messed up
  1371. lowerStartX = endPosInStaffLine.x + wedgePadding;
  1372. lowerEndX = lowerStartX + staffEntryWidth / 2 * sizeFactor;
  1373. }
  1374. // the Height of the Expression's placement
  1375. let idealY: number = 0;
  1376. let endIdealY: number = 0;
  1377. if (placement === PlacementEnum.Below) {
  1378. // can be a single Staff Instrument or an Instrument with 2 Staves
  1379. let nextStaffLineIndex: number = 0;
  1380. if (currentStaffLineIndex < musicSystem.StaffLines.length - 1) {
  1381. nextStaffLineIndex = currentStaffLineIndex + 1;
  1382. }
  1383. // check, maybe currentStaffLine is the last of the MusicSystem (and it has a ContinuousDynamicExpression with placement below)
  1384. if (nextStaffLineIndex > currentStaffLineIndex) {
  1385. // currentStaffLine isn't the last of the MusicSystem
  1386. const nextStaffLine: StaffLine = musicSystem.StaffLines[nextStaffLineIndex];
  1387. const distanceBetweenStaffLines: number = nextStaffLine.PositionAndShape.RelativePosition.y -
  1388. staffLine.PositionAndShape.RelativePosition.y -
  1389. this.rules.StaffHeight;
  1390. // ideal Height is exactly between the two StaffLines
  1391. idealY = this.rules.StaffHeight + distanceBetweenStaffLines / 2;
  1392. } else {
  1393. // currentStaffLine is the MusicSystem's last
  1394. idealY = this.rules.WedgePlacementBelowY;
  1395. }
  1396. // must consider the upperWedge starting/ending tip for the comparison with the BottomLine
  1397. idealY -= this.rules.WedgeOpeningLength / 2;
  1398. if (!sameStaffLine) {
  1399. // Set the value for the splitted y position to the ideal position before we check and modify it with
  1400. // the skybottom calculator detection
  1401. endIdealY = idealY;
  1402. }
  1403. // must check BottomLine for possible collisions within the Length of the Expression
  1404. // find the corresponding max value for the given Length
  1405. let maxBottomLineValueForExpressionLength: number = skyBottomLineCalculator.getBottomLineMaxInRange(upperStartX, upperEndX);
  1406. // if collisions, then set the Height accordingly
  1407. if (maxBottomLineValueForExpressionLength > idealY) {
  1408. idealY = maxBottomLineValueForExpressionLength;
  1409. }
  1410. // special case - wedge must be drawn within the boundaries of a crossedBeam
  1411. const withinCrossedBeam: boolean = false;
  1412. if (currentStaffLineIndex < musicSystem.StaffLines.length - 1) {
  1413. // find GraphicalStaffEntries closest to wedge's xPositions
  1414. const closestToEndStaffEntry: GraphicalStaffEntry = staffLine.findClosestStaffEntry(upperEndX);
  1415. const closestToStartStaffEntry: GraphicalStaffEntry = staffLine.findClosestStaffEntry(upperStartX);
  1416. if (closestToStartStaffEntry && closestToEndStaffEntry) {
  1417. // must check both StaffLines
  1418. const startVerticalContainer: VerticalGraphicalStaffEntryContainer = closestToStartStaffEntry.parentVerticalContainer;
  1419. // const endVerticalContainer: VerticalGraphicalStaffEntryContainer = closestToEndStaffEntry.parentVerticalContainer;
  1420. if (startVerticalContainer) {
  1421. // TODO: Needs to be implemented?
  1422. // withinCrossedBeam = areStaffEntriesWithinCrossedBeam(startVerticalContainer,
  1423. // endVerticalContainer, currentStaffLineIndex, nextStaffLineIndex);
  1424. }
  1425. if (withinCrossedBeam) {
  1426. const nextStaffLine: StaffLine = musicSystem.StaffLines[nextStaffLineIndex];
  1427. const nextStaffLineMinSkyLineValue: number = nextStaffLine.SkyBottomLineCalculator.getSkyLineMinInRange(upperStartX, upperEndX);
  1428. const distanceBetweenStaffLines: number = nextStaffLine.PositionAndShape.RelativePosition.y -
  1429. staffLine.PositionAndShape.RelativePosition.y;
  1430. const relativeSkyLineHeight: number = distanceBetweenStaffLines + nextStaffLineMinSkyLineValue;
  1431. if (relativeSkyLineHeight - this.rules.WedgeOpeningLength > this.rules.StaffHeight) {
  1432. idealY = relativeSkyLineHeight - this.rules.WedgeVerticalMargin;
  1433. } else {
  1434. idealY = this.rules.StaffHeight + this.rules.WedgeOpeningLength;
  1435. }
  1436. graphicalContinuousDynamic.NotToBeRemoved = true;
  1437. }
  1438. }
  1439. }
  1440. // do the same in case of a Wedge ending at another StaffLine
  1441. if (!sameStaffLine) {
  1442. maxBottomLineValueForExpressionLength = endStaffLine.SkyBottomLineCalculator.getBottomLineMaxInRange(lowerStartX, lowerEndX);
  1443. if (maxBottomLineValueForExpressionLength > endIdealY) {
  1444. endIdealY = maxBottomLineValueForExpressionLength;
  1445. }
  1446. endIdealY += this.rules.WedgeOpeningLength / 2;
  1447. endIdealY += this.rules.WedgeVerticalMargin;
  1448. }
  1449. if (!withinCrossedBeam) {
  1450. idealY += this.rules.WedgeOpeningLength / 2;
  1451. idealY += this.rules.WedgeVerticalMargin;
  1452. }
  1453. } else if (placement === PlacementEnum.Above) {
  1454. // single Staff Instrument (eg Voice)
  1455. if (staffLine.ParentStaff.ParentInstrument.Staves.length === 1) {
  1456. // single Staff Voice Instrument
  1457. idealY = this.rules.WedgePlacementAboveY;
  1458. } else {
  1459. // Staff = not the first Staff of a 2-staved Instrument
  1460. let previousStaffLineIndex: number = 0;
  1461. if (currentStaffLineIndex > 0) {
  1462. previousStaffLineIndex = currentStaffLineIndex - 1;
  1463. }
  1464. const previousStaffLine: StaffLine = musicSystem.StaffLines[previousStaffLineIndex];
  1465. const distanceBetweenStaffLines: number = staffLine.PositionAndShape.RelativePosition.y -
  1466. previousStaffLine.PositionAndShape.RelativePosition.y -
  1467. this.rules.StaffHeight;
  1468. // ideal Height is exactly between the two StaffLines
  1469. idealY = -distanceBetweenStaffLines / 2;
  1470. }
  1471. // must consider the upperWedge starting/ending tip for the comparison with the SkyLine
  1472. idealY += this.rules.WedgeOpeningLength / 2;
  1473. if (!sameStaffLine) {
  1474. endIdealY = idealY;
  1475. }
  1476. // must check SkyLine for possible collisions within the Length of the Expression
  1477. // find the corresponding min value for the given Length
  1478. let minSkyLineValueForExpressionLength: number = skyBottomLineCalculator.getSkyLineMinInRange(upperStartX, upperEndX);
  1479. // if collisions, then set the Height accordingly
  1480. if (minSkyLineValueForExpressionLength < idealY) {
  1481. idealY = minSkyLineValueForExpressionLength;
  1482. }
  1483. const withinCrossedBeam: boolean = false;
  1484. // special case - wedge must be drawn within the boundaries of a crossedBeam
  1485. if (staffLine.ParentStaff.ParentInstrument.Staves.length > 1 && currentStaffLineIndex > 0) {
  1486. // find GraphicalStaffEntries closest to wedge's xPositions
  1487. const closestToStartStaffEntry: GraphicalStaffEntry = staffLine.findClosestStaffEntry(upperStartX);
  1488. const closestToEndStaffEntry: GraphicalStaffEntry = staffLine.findClosestStaffEntry(upperEndX);
  1489. if (closestToStartStaffEntry && closestToEndStaffEntry) {
  1490. // must check both StaffLines
  1491. const startVerticalContainer: VerticalGraphicalStaffEntryContainer = closestToStartStaffEntry.parentVerticalContainer;
  1492. // const endVerticalContainer: VerticalGraphicalStaffEntryContainer = closestToEndStaffEntry.parentVerticalContainer;
  1493. const formerStaffLineIndex: number = currentStaffLineIndex - 1;
  1494. if (startVerticalContainer) {
  1495. // withinCrossedBeam = this.areStaffEntriesWithinCrossedBeam(startVerticalContainer,
  1496. // endVerticalContainer, currentStaffLineIndex, formerStaffLineIndex);
  1497. }
  1498. if (withinCrossedBeam) {
  1499. const formerStaffLine: StaffLine = musicSystem.StaffLines[formerStaffLineIndex];
  1500. const formerStaffLineMaxBottomLineValue: number = formerStaffLine.SkyBottomLineCalculator.
  1501. getBottomLineMaxInRange(upperStartX, upperEndX);
  1502. const distanceBetweenStaffLines: number = staffLine.PositionAndShape.RelativePosition.y -
  1503. formerStaffLine.PositionAndShape.RelativePosition.y;
  1504. const relativeSkyLineHeight: number = distanceBetweenStaffLines - formerStaffLineMaxBottomLineValue;
  1505. idealY = (relativeSkyLineHeight - this.rules.StaffHeight) / 2 + this.rules.StaffHeight;
  1506. }
  1507. }
  1508. }
  1509. // do the same in case of a Wedge ending at another StaffLine
  1510. if (!sameStaffLine) {
  1511. minSkyLineValueForExpressionLength = endStaffLine.SkyBottomLineCalculator.getSkyLineMinInRange(lowerStartX, lowerEndX);
  1512. if (minSkyLineValueForExpressionLength < endIdealY) {
  1513. endIdealY = minSkyLineValueForExpressionLength;
  1514. }
  1515. endIdealY -= this.rules.WedgeOpeningLength / 2;
  1516. }
  1517. if (!withinCrossedBeam) {
  1518. idealY -= this.rules.WedgeOpeningLength / 2;
  1519. idealY -= this.rules.WedgeVerticalMargin;
  1520. }
  1521. if (!sameStaffLine) {
  1522. endIdealY -= this.rules.WedgeVerticalMargin;
  1523. }
  1524. }
  1525. // now we have the correct placement Height for the Expression
  1526. // the idealY is calculated relative to the currentStaffLine
  1527. graphicalContinuousDynamic.Lines.clear();
  1528. // create wedges (crescendo / decrescendo lines)
  1529. if (isSoftAccent) {
  1530. graphicalContinuousDynamic.createFirstHalfCrescendoLines(upperStartX, upperEndX, idealY);
  1531. graphicalContinuousDynamic.createSecondHalfDiminuendoLines(lowerStartX, lowerEndX, idealY);
  1532. graphicalContinuousDynamic.calcPsi();
  1533. } else if (sameStaffLine && !isSoftAccent) {
  1534. // either create crescendo or decrescendo lines, same principle / parameters.
  1535. graphicalContinuousDynamic.createLines(upperStartX, upperEndX, idealY);
  1536. graphicalContinuousDynamic.calcPsi();
  1537. } else {
  1538. // two+ different Wedges
  1539. // first wedge
  1540. graphicalContinuousDynamic.createFirstHalfLines(upperStartX, upperEndX, idealY);
  1541. graphicalContinuousDynamic.calcPsi();
  1542. // inbetween wedges
  1543. for (let i: number = 0; i < inbetweenWedges.length; i++) {
  1544. const inbetweenWedge: GraphicalContinuousDynamicExpression = inbetweenWedges[i];
  1545. const inbetweenStaffline: StaffLine = inbetweenWedge.ParentStaffLine;
  1546. let betweenIdealY: number = endIdealY;
  1547. if (placement === PlacementEnum.Below) {
  1548. const maxBottomLineValueForExpressionLength: number =
  1549. endStaffLine.SkyBottomLineCalculator.getBottomLineMaxInRange(lowerStartX, upperEndX);
  1550. if (maxBottomLineValueForExpressionLength > betweenIdealY) {
  1551. betweenIdealY = maxBottomLineValueForExpressionLength;
  1552. }
  1553. betweenIdealY += this.rules.WedgeOpeningLength / 2;
  1554. betweenIdealY += this.rules.WedgeVerticalMargin;
  1555. } else if (placement === PlacementEnum.Above) {
  1556. const minSkyLineValueForExpressionLength: number =
  1557. inbetweenStaffline.SkyBottomLineCalculator.getSkyLineMinInRange(lowerStartX, lowerEndX);
  1558. if (minSkyLineValueForExpressionLength < endIdealY) {
  1559. betweenIdealY = minSkyLineValueForExpressionLength;
  1560. }
  1561. betweenIdealY -= this.rules.WedgeOpeningLength / 2;
  1562. }
  1563. if (graphicalContinuousDynamic.ContinuousDynamic.DynamicType === ContDynamicEnum.crescendo) {
  1564. inbetweenWedge.createSecondHalfCrescendoLines(0, inbetweenStaffline.PositionAndShape.Size.width, betweenIdealY);
  1565. // for crescendo, we want the same look as on the last staffline: not starting with an intersection / starting wedge
  1566. } else {
  1567. inbetweenWedge.createFirstHalfDiminuendoLines(0, inbetweenStaffline.PositionAndShape.Size.width, betweenIdealY);
  1568. // for diminuendo, we want the same look as on the first staffline: not ending in an intersection / looking finished
  1569. }
  1570. inbetweenWedge.calcPsi();
  1571. }
  1572. // last wedge
  1573. endGraphicalContinuousDynamic.createSecondHalfLines(lowerStartX, lowerEndX, endIdealY);
  1574. endGraphicalContinuousDynamic.calcPsi();
  1575. }
  1576. this.dynamicExpressionMap.set(endAbsoluteTimestamp.RealValue, graphicalContinuousDynamic.PositionAndShape);
  1577. }
  1578. /**
  1579. * This method calculates the RelativePosition of a single GraphicalInstantaneousDynamicExpression.
  1580. * @param graphicalInstantaneousDynamic Dynamic expression to be calculated
  1581. * @param startPosInStaffline Starting point in staff line
  1582. */
  1583. protected calculateGraphicalInstantaneousDynamicExpression(graphicalInstantaneousDynamic: GraphicalInstantaneousDynamicExpression,
  1584. startPosInStaffline: PointF2D, timestamp: Fraction): void {
  1585. // get Margin Dimensions
  1586. const staffLine: StaffLine = graphicalInstantaneousDynamic.ParentStaffLine;
  1587. if (!staffLine) {
  1588. return; // TODO can happen when drawing range modified (osmd.setOptions({drawFromMeasureNumber...}))
  1589. }
  1590. const left: number = startPosInStaffline.x + graphicalInstantaneousDynamic.PositionAndShape.BorderMarginLeft;
  1591. const right: number = startPosInStaffline.x + graphicalInstantaneousDynamic.PositionAndShape.BorderMarginRight;
  1592. const skyBottomLineCalculator: SkyBottomLineCalculator = staffLine.SkyBottomLineCalculator;
  1593. let yPosition: number = 0;
  1594. // calculate yPosition according to Placement
  1595. if (graphicalInstantaneousDynamic.Placement === PlacementEnum.Above) {
  1596. const skyLineValue: number = skyBottomLineCalculator.getSkyLineMinInRange(left, right);
  1597. // if StaffLine part of multiStaff Instrument and not the first one, ideal yPosition middle of distance between Staves
  1598. if (staffLine.isPartOfMultiStaffInstrument() && staffLine.ParentStaff !== staffLine.ParentStaff.ParentInstrument.Staves[0]) {
  1599. const formerStaffLine: StaffLine = staffLine.ParentMusicSystem.StaffLines[staffLine.ParentMusicSystem.StaffLines.indexOf(staffLine) - 1];
  1600. const difference: number = staffLine.PositionAndShape.RelativePosition.y -
  1601. formerStaffLine.PositionAndShape.RelativePosition.y - this.rules.StaffHeight;
  1602. // take always into account the size of the Dynamic
  1603. if (skyLineValue > -difference / 2) {
  1604. yPosition = -difference / 2;
  1605. } else {
  1606. yPosition = skyLineValue - graphicalInstantaneousDynamic.PositionAndShape.BorderMarginBottom;
  1607. }
  1608. } else {
  1609. yPosition = skyLineValue - graphicalInstantaneousDynamic.PositionAndShape.BorderMarginBottom;
  1610. }
  1611. graphicalInstantaneousDynamic.PositionAndShape.RelativePosition = new PointF2D(startPosInStaffline.x, yPosition);
  1612. } else if (graphicalInstantaneousDynamic.Placement === PlacementEnum.Below) {
  1613. const bottomLineValue: number = skyBottomLineCalculator.getBottomLineMaxInRange(left, right);
  1614. // if StaffLine part of multiStaff Instrument and not the last one, ideal yPosition middle of distance between Staves
  1615. const lastStaff: Staff = staffLine.ParentStaff.ParentInstrument.Staves[staffLine.ParentStaff.ParentInstrument.Staves.length - 1];
  1616. if (staffLine.isPartOfMultiStaffInstrument() && staffLine.ParentStaff !== lastStaff) {
  1617. const nextStaffLine: StaffLine = staffLine.ParentMusicSystem.StaffLines[staffLine.ParentMusicSystem.StaffLines.indexOf(staffLine) + 1];
  1618. const difference: number = nextStaffLine.PositionAndShape.RelativePosition.y -
  1619. staffLine.PositionAndShape.RelativePosition.y - this.rules.StaffHeight;
  1620. const border: number = graphicalInstantaneousDynamic.PositionAndShape.BorderMarginBottom;
  1621. // take always into account the size of the Dynamic
  1622. if (bottomLineValue + border < this.rules.StaffHeight + difference / 2) {
  1623. yPosition = this.rules.StaffHeight + difference / 2;
  1624. } else {
  1625. yPosition = bottomLineValue - graphicalInstantaneousDynamic.PositionAndShape.BorderMarginTop;
  1626. }
  1627. } else {
  1628. yPosition = bottomLineValue - graphicalInstantaneousDynamic.PositionAndShape.BorderMarginTop;
  1629. }
  1630. graphicalInstantaneousDynamic.PositionAndShape.RelativePosition = new PointF2D(startPosInStaffline.x, yPosition);
  1631. }
  1632. graphicalInstantaneousDynamic.updateSkyBottomLine();
  1633. }
  1634. protected calcGraphicalRepetitionEndingsRecursively(repetition: Repetition): void {
  1635. return;
  1636. }
  1637. /**
  1638. * Calculate a single GraphicalRepetition.
  1639. * @param start
  1640. * @param end
  1641. * @param numberText
  1642. * @param offset
  1643. * @param leftOpen
  1644. * @param rightOpen
  1645. */
  1646. protected layoutSingleRepetitionEnding(start: GraphicalMeasure, end: GraphicalMeasure, numberText: string,
  1647. offset: number, leftOpen: boolean, rightOpen: boolean): void {
  1648. return;
  1649. }
  1650. protected calculateLabel(staffLine: StaffLine,
  1651. relative: PointF2D,
  1652. combinedString: string,
  1653. style: FontStyles,
  1654. placement: PlacementEnum,
  1655. fontHeight: number,
  1656. textAlignment: TextAlignmentEnum = TextAlignmentEnum.CenterBottom,
  1657. yPadding: number = 0): GraphicalLabel {
  1658. const label: Label = new Label(combinedString, textAlignment);
  1659. label.fontStyle = style;
  1660. label.fontHeight = fontHeight;
  1661. // TODO_RR: TextHeight from first Entry
  1662. const graphLabel: GraphicalLabel = new GraphicalLabel(label, fontHeight, label.textAlignment, this.rules, staffLine.PositionAndShape);
  1663. const marginFactor: number = 1.1;
  1664. if (placement === PlacementEnum.Below) {
  1665. graphLabel.Label.textAlignment = TextAlignmentEnum.LeftTop;
  1666. }
  1667. graphLabel.setLabelPositionAndShapeBorders();
  1668. graphLabel.PositionAndShape.BorderMarginBottom *= marginFactor;
  1669. graphLabel.PositionAndShape.BorderMarginTop *= marginFactor;
  1670. graphLabel.PositionAndShape.BorderMarginLeft *= marginFactor;
  1671. graphLabel.PositionAndShape.BorderMarginRight *= marginFactor;
  1672. let left: number = relative.x + graphLabel.PositionAndShape.BorderMarginLeft;
  1673. let right: number = relative.x + graphLabel.PositionAndShape.BorderMarginRight;
  1674. // check if GraphicalLabel exceeds the StaffLine's borders.
  1675. if (right > staffLine.PositionAndShape.Size.width) {
  1676. right = staffLine.PositionAndShape.Size.width - this.rules.MeasureRightMargin;
  1677. left = right - graphLabel.PositionAndShape.MarginSize.width;
  1678. relative.x = left - graphLabel.PositionAndShape.BorderMarginLeft;
  1679. }
  1680. // find allowed position (where the Label can be positioned) from Sky- BottomLine
  1681. let drawingHeight: number;
  1682. const skyBottomLineCalculator: SkyBottomLineCalculator = staffLine.SkyBottomLineCalculator;
  1683. if (placement === PlacementEnum.Below) {
  1684. drawingHeight = skyBottomLineCalculator.getBottomLineMaxInRange(left, right) + yPadding;
  1685. } else {
  1686. drawingHeight = skyBottomLineCalculator.getSkyLineMinInRange(left, right) - yPadding;
  1687. }
  1688. // set RelativePosition
  1689. graphLabel.PositionAndShape.RelativePosition = new PointF2D(relative.x, drawingHeight);
  1690. // update Sky- BottomLine
  1691. if (placement === PlacementEnum.Below) {
  1692. skyBottomLineCalculator.updateBottomLineInRange(left, right, graphLabel.PositionAndShape.BorderMarginBottom + drawingHeight);
  1693. } else {
  1694. skyBottomLineCalculator.updateSkyLineInRange(left, right, graphLabel.PositionAndShape.BorderMarginTop + drawingHeight);
  1695. }
  1696. return graphLabel;
  1697. }
  1698. protected calculateTempoExpressionsForMultiTempoExpression(sourceMeasure: SourceMeasure, multiTempoExpression: MultiTempoExpression,
  1699. measureIndex: number): void {
  1700. // calculate absolute Timestamp
  1701. const absoluteTimestamp: Fraction = Fraction.plus(sourceMeasure.AbsoluteTimestamp, multiTempoExpression.Timestamp);
  1702. const measures: GraphicalMeasure[] = this.graphicalMusicSheet.MeasureList[measureIndex];
  1703. let relative: PointF2D = new PointF2D();
  1704. if (multiTempoExpression.ContinuousTempo || multiTempoExpression.InstantaneousTempo) {
  1705. // TempoExpressions always on the first visible System's StaffLine // TODO is it though?
  1706. if (this.rules.MinMeasureToDrawIndex > 0) {
  1707. return; // assuming that the tempo is always in measure 1 (idx 0), adding the expression causes issues when we don't draw measure 1
  1708. }
  1709. if (!measures[0]) {
  1710. return;
  1711. }
  1712. let staffLine: StaffLine = measures[0].ParentStaffLine;
  1713. let firstVisibleMeasureX: number = measures[0].PositionAndShape.RelativePosition.x;
  1714. let verticalIndex: number = 0;
  1715. for (let j: number = 0; j < measures.length; j++) {
  1716. if (!measures[j].ParentStaffLine || measures[j].ParentStaffLine.Measures.length === 0) {
  1717. continue;
  1718. }
  1719. if (measures[j].ParentStaffLine.Measures.length > 0) {
  1720. staffLine = measures[j].ParentStaffLine;
  1721. firstVisibleMeasureX = measures[j].PositionAndShape.RelativePosition.x;
  1722. verticalIndex = j;
  1723. break;
  1724. }
  1725. }
  1726. relative = this.getRelativePositionInStaffLineFromTimestamp(absoluteTimestamp,
  1727. verticalIndex,
  1728. staffLine,
  1729. staffLine.isPartOfMultiStaffInstrument(),
  1730. firstVisibleMeasureX);
  1731. // also placement Above
  1732. if (multiTempoExpression.EntriesList.length > 0 &&
  1733. multiTempoExpression.EntriesList[0].Expression instanceof InstantaneousTempoExpression) {
  1734. const instantaniousTempo: InstantaneousTempoExpression = (multiTempoExpression.EntriesList[0].Expression as InstantaneousTempoExpression);
  1735. instantaniousTempo.Placement = PlacementEnum.Above;
  1736. // if an InstantaniousTempoExpression exists at the very beginning then
  1737. // check if expression is positioned at first ever StaffEntry and
  1738. // check if MusicSystem is first MusicSystem
  1739. if (staffLine.Measures[0].staffEntries.length > 0 &&
  1740. Math.abs(relative.x - staffLine.Measures[0].staffEntries[0].PositionAndShape.RelativePosition.x) === 0 &&
  1741. staffLine.ParentMusicSystem === this.musicSystems[0]) {
  1742. const firstInstructionEntry: GraphicalStaffEntry = staffLine.Measures[0].FirstInstructionStaffEntry;
  1743. if (firstInstructionEntry) {
  1744. const lastInstruction: AbstractGraphicalInstruction = firstInstructionEntry.GraphicalInstructions.last();
  1745. relative.x = lastInstruction.PositionAndShape.RelativePosition.x;
  1746. }
  1747. if (this.rules.CompactMode) {
  1748. relative.x = staffLine.PositionAndShape.RelativePosition.x +
  1749. staffLine.Measures[0].PositionAndShape.RelativePosition.x;
  1750. }
  1751. }
  1752. }
  1753. // const addAtLastList: GraphicalObject[] = [];
  1754. for (const entry of multiTempoExpression.EntriesList) {
  1755. let textAlignment: TextAlignmentEnum = TextAlignmentEnum.CenterBottom;
  1756. if (this.rules.CompactMode) {
  1757. textAlignment = TextAlignmentEnum.LeftBottom;
  1758. }
  1759. const graphLabel: GraphicalLabel = this.calculateLabel(staffLine,
  1760. relative,
  1761. entry.label,
  1762. multiTempoExpression.getFontstyleOfFirstEntry(),
  1763. entry.Expression.Placement,
  1764. this.rules.UnknownTextHeight,
  1765. textAlignment,
  1766. this.rules.TempoYSpacing);
  1767. if (entry.Expression.ColorXML && this.rules.ExpressionsUseXMLColor) {
  1768. graphLabel.ColorXML = entry.Expression.ColorXML;
  1769. }
  1770. if (entry.Expression instanceof InstantaneousTempoExpression) {
  1771. //already added?
  1772. for (const expr of staffLine.AbstractExpressions) {
  1773. if (expr instanceof GraphicalInstantaneousTempoExpression &&
  1774. (expr.SourceExpression as AbstractTempoExpression).Label === entry.Expression.Label) {
  1775. //already added
  1776. continue;
  1777. }
  1778. }
  1779. const graphicalTempoExpr: GraphicalInstantaneousTempoExpression = new GraphicalInstantaneousTempoExpression(entry.Expression, graphLabel);
  1780. if (!graphicalTempoExpr.ParentStaffLine) {
  1781. log.warn("Adding staffline didn't work");
  1782. // I am actually fooling the linter here and use the created object. This method needs refactoring,
  1783. // all graphical expression creations should be in one place and have basic stuff like labels, lines, ...
  1784. // in their constructor
  1785. }
  1786. // in case of metronome mark:
  1787. if (this.rules.MetronomeMarksDrawn) {
  1788. if ((entry.Expression as InstantaneousTempoExpression).Enum === TempoEnum.metronomeMark) {
  1789. this.createMetronomeMark((entry.Expression as InstantaneousTempoExpression));
  1790. continue;
  1791. }
  1792. }
  1793. } else if (entry.Expression instanceof ContinuousTempoExpression) {
  1794. for (const expr of staffLine.AbstractExpressions) {
  1795. if (expr instanceof GraphicalInstantaneousTempoExpression &&
  1796. (expr.SourceExpression as AbstractTempoExpression).Label === entry.Expression.Label) {
  1797. continue; // already added
  1798. }
  1799. }
  1800. // TODO maybe create GraphicalContinuousTempoExpression class,
  1801. // though the ContinuousTempoExpressions we have currently behave the same graphically (accelerando, ritardando, etc).
  1802. // The behavior difference rather affects playback (e.g. ritardando, which gradually changes tempo)
  1803. staffLine.AbstractExpressions.push(new GraphicalInstantaneousTempoExpression(entry.Expression, graphLabel));
  1804. }
  1805. }
  1806. }
  1807. }
  1808. protected createMetronomeMark(metronomeExpression: InstantaneousTempoExpression): void {
  1809. throw new Error(this.abstractNotImplementedErrorMessage);
  1810. }
  1811. protected graphicalMeasureCreatedCalculations(measure: GraphicalMeasure): void {
  1812. return;
  1813. }
  1814. protected clearSystemsAndMeasures(): void {
  1815. for (let idx: number = 0, len: number = this.graphicalMusicSheet.MusicPages.length; idx < len; ++idx) {
  1816. const graphicalMusicPage: GraphicalMusicPage = this.graphicalMusicSheet.MusicPages[idx];
  1817. for (let idx2: number = 0, len2: number = graphicalMusicPage.MusicSystems.length; idx2 < len2; ++idx2) {
  1818. const musicSystem: MusicSystem = graphicalMusicPage.MusicSystems[idx2];
  1819. for (let idx3: number = 0, len3: number = musicSystem.StaffLines.length; idx3 < len3; ++idx3) {
  1820. const staffLine: StaffLine = musicSystem.StaffLines[idx3];
  1821. for (let idx4: number = 0, len4: number = staffLine.Measures.length; idx4 < len4; ++idx4) {
  1822. const graphicalMeasure: GraphicalMeasure = staffLine.Measures[idx4];
  1823. if (graphicalMeasure.FirstInstructionStaffEntry) {
  1824. const index: number = graphicalMeasure.PositionAndShape.ChildElements.indexOf(
  1825. graphicalMeasure.FirstInstructionStaffEntry.PositionAndShape
  1826. );
  1827. if (index > -1) {
  1828. graphicalMeasure.PositionAndShape.ChildElements.splice(index, 1);
  1829. }
  1830. graphicalMeasure.FirstInstructionStaffEntry = undefined;
  1831. graphicalMeasure.beginInstructionsWidth = 0.0;
  1832. }
  1833. if (graphicalMeasure.LastInstructionStaffEntry) {
  1834. const index: number = graphicalMeasure.PositionAndShape.ChildElements.indexOf(
  1835. graphicalMeasure.LastInstructionStaffEntry.PositionAndShape
  1836. );
  1837. if (index > -1) {
  1838. graphicalMeasure.PositionAndShape.ChildElements.splice(index, 1);
  1839. }
  1840. graphicalMeasure.LastInstructionStaffEntry = undefined;
  1841. graphicalMeasure.endInstructionsWidth = 0.0;
  1842. }
  1843. }
  1844. staffLine.Measures = [];
  1845. staffLine.PositionAndShape.ChildElements = [];
  1846. }
  1847. musicSystem.StaffLines.length = 0;
  1848. musicSystem.PositionAndShape.ChildElements = [];
  1849. }
  1850. graphicalMusicPage.MusicSystems = [];
  1851. graphicalMusicPage.PositionAndShape.ChildElements = [];
  1852. }
  1853. this.graphicalMusicSheet.MusicPages = [];
  1854. }
  1855. protected handleVoiceEntry(voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry,
  1856. accidentalCalculator: AccidentalCalculator, openLyricWords: LyricWord[],
  1857. activeClef: ClefInstruction,
  1858. openTuplets: Tuplet[], openBeams: Beam[],
  1859. octaveShiftValue: OctaveEnum, staffIndex: number,
  1860. linkedNotes: Note[] = undefined,
  1861. sourceStaffEntry: SourceStaffEntry = undefined): OctaveEnum {
  1862. if (voiceEntry.StemDirectionXml !== StemDirectionType.Undefined &&
  1863. this.rules.SetWantedStemDirectionByXml &&
  1864. voiceEntry.StemDirectionXml !== undefined) {
  1865. voiceEntry.WantedStemDirection = voiceEntry.StemDirectionXml;
  1866. } else {
  1867. this.calculateStemDirectionFromVoices(voiceEntry);
  1868. }
  1869. // if GraphicalStaffEntry has been created earlier (because of Tie), then the GraphicalNotesLists have also been created
  1870. const gve: GraphicalVoiceEntry = graphicalStaffEntry.findOrCreateGraphicalVoiceEntry(voiceEntry);
  1871. gve.octaveShiftValue = octaveShiftValue;
  1872. // check for Tabs:
  1873. const tabStaffEntry: GraphicalStaffEntry = graphicalStaffEntry.tabStaffEntry;
  1874. let graphicalTabVoiceEntry: GraphicalVoiceEntry;
  1875. if (tabStaffEntry) {
  1876. graphicalTabVoiceEntry = tabStaffEntry.findOrCreateGraphicalVoiceEntry(voiceEntry);
  1877. }
  1878. for (let idx: number = 0, len: number = voiceEntry.Notes.length; idx < len; ++idx) {
  1879. const note: Note = voiceEntry.Notes[idx];
  1880. if (!note) {
  1881. continue;
  1882. }
  1883. if (sourceStaffEntry !== undefined && sourceStaffEntry.Link !== undefined && linkedNotes !== undefined && linkedNotes.indexOf(note) > -1) {
  1884. continue;
  1885. }
  1886. let graphicalNote: GraphicalNote;
  1887. if (voiceEntry.IsGrace) {
  1888. graphicalNote = MusicSheetCalculator.symbolFactory.createGraceNote(note, gve, activeClef, this.rules, octaveShiftValue);
  1889. } else {
  1890. graphicalNote = MusicSheetCalculator.symbolFactory.createNote(note, gve, activeClef, octaveShiftValue, this.rules, undefined);
  1891. MusicSheetCalculator.stafflineNoteCalculator.trackNote(graphicalNote);
  1892. }
  1893. if (note.Pitch) {
  1894. this.checkNoteForAccidental(graphicalNote, accidentalCalculator, activeClef, octaveShiftValue);
  1895. }
  1896. this.resetYPositionForLeadSheet(graphicalNote.PositionAndShape);
  1897. graphicalStaffEntry.addGraphicalNoteToListAtCorrectYPosition(gve, graphicalNote);
  1898. graphicalNote.PositionAndShape.calculateBoundingBox();
  1899. if (!this.leadSheet) {
  1900. if (note.NoteBeam !== undefined && note.PrintObject) {
  1901. if (!(note instanceof TabNote) || this.rules.TabBeamsRendered) {
  1902. this.handleBeam(graphicalNote, note.NoteBeam, openBeams);
  1903. }
  1904. }
  1905. if (note.NoteTuplet !== undefined && note.PrintObject) {
  1906. this.handleTuplet(graphicalNote, note.NoteTuplet, openTuplets);
  1907. }
  1908. }
  1909. // handle TabNotes:
  1910. if (graphicalTabVoiceEntry) {
  1911. // notes should be either TabNotes or RestNotes -> add all:
  1912. const graphicalTabNote: GraphicalNote = MusicSheetCalculator.symbolFactory.createNote(
  1913. note,
  1914. graphicalTabVoiceEntry,
  1915. activeClef,
  1916. octaveShiftValue,
  1917. this.rules,
  1918. undefined);
  1919. tabStaffEntry.addGraphicalNoteToListAtCorrectYPosition(graphicalTabVoiceEntry, graphicalTabNote);
  1920. graphicalTabNote.PositionAndShape.calculateBoundingBox();
  1921. if (!this.leadSheet) {
  1922. if (note.NoteTuplet) {
  1923. this.handleTuplet(graphicalTabNote, note.NoteTuplet, openTuplets);
  1924. }
  1925. }
  1926. }
  1927. }
  1928. if (voiceEntry.Articulations.length > 0) {
  1929. this.handleVoiceEntryArticulations(voiceEntry.Articulations, voiceEntry, graphicalStaffEntry);
  1930. }
  1931. if (voiceEntry.TechnicalInstructions.length > 0) {
  1932. this.handleVoiceEntryTechnicalInstructions(voiceEntry.TechnicalInstructions, voiceEntry, graphicalStaffEntry);
  1933. }
  1934. if (voiceEntry.LyricsEntries.size() > 0) {
  1935. this.handleVoiceEntryLyrics(voiceEntry, graphicalStaffEntry, openLyricWords);
  1936. }
  1937. if (voiceEntry.OrnamentContainer) {
  1938. this.handleVoiceEntryOrnaments(voiceEntry.OrnamentContainer, voiceEntry, graphicalStaffEntry);
  1939. }
  1940. return octaveShiftValue;
  1941. }
  1942. protected resetYPositionForLeadSheet(psi: BoundingBox): void {
  1943. if (this.leadSheet) {
  1944. psi.RelativePosition = new PointF2D(psi.RelativePosition.x, 0.0);
  1945. }
  1946. }
  1947. protected layoutVoiceEntries(graphicalStaffEntry: GraphicalStaffEntry, staffIndex: number): void {
  1948. graphicalStaffEntry.PositionAndShape.RelativePosition = new PointF2D(0.0, 0.0);
  1949. if (!this.leadSheet) {
  1950. for (const gve of graphicalStaffEntry.graphicalVoiceEntries) {
  1951. const graphicalNotes: GraphicalNote[] = gve.notes;
  1952. if (graphicalNotes.length === 0) {
  1953. continue;
  1954. }
  1955. const voiceEntry: VoiceEntry = graphicalNotes[0].sourceNote.ParentVoiceEntry;
  1956. const hasPitchedNote: boolean = graphicalNotes[0].sourceNote.Pitch !== undefined;
  1957. this.layoutVoiceEntry(voiceEntry, graphicalNotes, graphicalStaffEntry, hasPitchedNote);
  1958. }
  1959. }
  1960. }
  1961. protected maxInstrNameLabelLength(): number {
  1962. let maxLabelLength: number = 0.0;
  1963. for (const instrument of this.graphicalMusicSheet.ParentMusicSheet.Instruments) {
  1964. if (instrument.NameLabel?.print && instrument.Voices.length > 0 && instrument.Voices[0].Visible) {
  1965. let renderedLabel: Label = instrument.NameLabel;
  1966. if (!this.rules.RenderPartNames) {
  1967. renderedLabel = new Label("", renderedLabel.textAlignment, renderedLabel.font);
  1968. }
  1969. const graphicalLabel: GraphicalLabel = new GraphicalLabel(
  1970. renderedLabel, this.rules.InstrumentLabelTextHeight, TextAlignmentEnum.LeftCenter, this.rules);
  1971. graphicalLabel.setLabelPositionAndShapeBorders();
  1972. maxLabelLength = Math.max(maxLabelLength, graphicalLabel.PositionAndShape.MarginSize.width);
  1973. }
  1974. }
  1975. if (!this.rules.RenderPartNames) {
  1976. return 0;
  1977. }
  1978. return maxLabelLength;
  1979. }
  1980. protected calculateSheetLabelBoundingBoxes(): void {
  1981. const musicSheet: MusicSheet = this.graphicalMusicSheet.ParentMusicSheet;
  1982. const defaultColorTitle: string = this.rules.DefaultColorTitle; // can be undefined => black
  1983. if (musicSheet.Title !== undefined && this.rules.RenderTitle) {
  1984. const title: GraphicalLabel = new GraphicalLabel(musicSheet.Title, this.rules.SheetTitleHeight, TextAlignmentEnum.CenterBottom, this.rules);
  1985. title.Label.IsCreditLabel = true;
  1986. title.Label.colorDefault = defaultColorTitle;
  1987. this.graphicalMusicSheet.Title = title;
  1988. title.setLabelPositionAndShapeBorders();
  1989. } else if (!this.rules.RenderTitle) {
  1990. this.graphicalMusicSheet.Title = undefined; // clear label if rendering it was disabled after last render
  1991. }
  1992. if (musicSheet.Subtitle !== undefined && this.rules.RenderSubtitle) {
  1993. const subtitle: GraphicalLabel = new GraphicalLabel(
  1994. musicSheet.Subtitle, this.rules.SheetSubtitleHeight, TextAlignmentEnum.CenterCenter, this.rules);
  1995. subtitle.Label.IsCreditLabel = true;
  1996. subtitle.Label.colorDefault = defaultColorTitle;
  1997. this.graphicalMusicSheet.Subtitle = subtitle;
  1998. subtitle.setLabelPositionAndShapeBorders();
  1999. } else if (!this.rules.RenderSubtitle) {
  2000. this.graphicalMusicSheet.Subtitle = undefined;
  2001. }
  2002. if (musicSheet.Composer !== undefined && this.rules.RenderComposer) {
  2003. const composer: GraphicalLabel = new GraphicalLabel(
  2004. musicSheet.Composer, this.rules.SheetComposerHeight, TextAlignmentEnum.RightCenter, this.rules);
  2005. composer.Label.IsCreditLabel = true;
  2006. composer.Label.colorDefault = defaultColorTitle;
  2007. this.graphicalMusicSheet.Composer = composer;
  2008. composer.setLabelPositionAndShapeBorders();
  2009. } else if (!this.rules.RenderComposer) {
  2010. this.graphicalMusicSheet.Composer = undefined;
  2011. }
  2012. if (musicSheet.Lyricist !== undefined && this.rules.RenderLyricist) {
  2013. const lyricist: GraphicalLabel = new GraphicalLabel(
  2014. musicSheet.Lyricist, this.rules.SheetAuthorHeight, TextAlignmentEnum.LeftCenter, this.rules);
  2015. lyricist.Label.IsCreditLabel = true;
  2016. lyricist.Label.colorDefault = defaultColorTitle;
  2017. this.graphicalMusicSheet.Lyricist = lyricist;
  2018. lyricist.setLabelPositionAndShapeBorders();
  2019. } else if (!this.rules.RenderLyricist) {
  2020. this.graphicalMusicSheet.Lyricist = undefined;
  2021. }
  2022. if (musicSheet.Copyright !== undefined && this.rules.RenderCopyright) {
  2023. const copyright: GraphicalLabel = new GraphicalLabel(
  2024. musicSheet.Copyright, this.rules.SheetCopyrightHeight, TextAlignmentEnum.CenterBottom, this.rules);
  2025. copyright.Label.IsCreditLabel = true;
  2026. copyright.Label.colorDefault = defaultColorTitle;
  2027. this.graphicalMusicSheet.Copyright = copyright;
  2028. copyright.setLabelPositionAndShapeBorders();
  2029. } else if (!this.rules.RenderCopyright) {
  2030. this.graphicalMusicSheet.Copyright = undefined;
  2031. }
  2032. }
  2033. protected checkMeasuresForWholeRestNotes(): void {
  2034. for (let idx2: number = 0, len2: number = this.musicSystems.length; idx2 < len2; ++idx2) {
  2035. const musicSystem: MusicSystem = this.musicSystems[idx2];
  2036. for (let idx3: number = 0, len3: number = musicSystem.StaffLines.length; idx3 < len3; ++idx3) {
  2037. const staffLine: StaffLine = musicSystem.StaffLines[idx3];
  2038. for (let idx4: number = 0, len4: number = staffLine.Measures.length; idx4 < len4; ++idx4) {
  2039. const measure: GraphicalMeasure = staffLine.Measures[idx4];
  2040. if (measure.staffEntries.length === 1) {
  2041. const gse: GraphicalStaffEntry = measure.staffEntries[0];
  2042. if (gse.graphicalVoiceEntries.length > 0 && gse.graphicalVoiceEntries[0].notes.length === 1) {
  2043. const graphicalNote: GraphicalNote = gse.graphicalVoiceEntries[0].notes[0];
  2044. if (!graphicalNote.sourceNote.Pitch && (new Fraction(1, 2)).lt(graphicalNote.sourceNote.Length)) {
  2045. this.layoutMeasureWithWholeRest(graphicalNote, gse, measure);
  2046. }
  2047. }
  2048. }
  2049. }
  2050. }
  2051. }
  2052. }
  2053. protected optimizeRestNotePlacement(graphicalStaffEntry: GraphicalStaffEntry, measure: GraphicalMeasure): void {
  2054. if (graphicalStaffEntry.graphicalVoiceEntries.length === 0) {
  2055. return;
  2056. }
  2057. const voice1Notes: GraphicalNote[] = graphicalStaffEntry.graphicalVoiceEntries[0].notes;
  2058. if (voice1Notes.length === 0) {
  2059. return;
  2060. }
  2061. const voice1Note1: GraphicalNote = voice1Notes[0];
  2062. const voice1Note1IsRest: boolean = voice1Note1.sourceNote.isRest();
  2063. if (graphicalStaffEntry.graphicalVoiceEntries.length === 2) {
  2064. let voice2Note1IsRest: boolean = false;
  2065. const voice2Notes: GraphicalNote[] = graphicalStaffEntry.graphicalVoiceEntries[1].notes;
  2066. if (voice2Notes.length > 0) {
  2067. const voice2Note1: GraphicalNote = voice2Notes[0];
  2068. voice2Note1IsRest = voice2Note1.sourceNote.isRest();
  2069. }
  2070. if (voice1Note1IsRest && voice2Note1IsRest) {
  2071. this.calculateTwoRestNotesPlacementWithCollisionDetection(graphicalStaffEntry);
  2072. } else if (voice1Note1IsRest || voice2Note1IsRest) {
  2073. this.calculateRestNotePlacementWithCollisionDetectionFromGraphicalNote(graphicalStaffEntry);
  2074. }
  2075. } else if (voice1Note1IsRest && graphicalStaffEntry !== measure.staffEntries[0] &&
  2076. graphicalStaffEntry !== measure.staffEntries[measure.staffEntries.length - 1]) {
  2077. const staffEntryIndex: number = measure.staffEntries.indexOf(graphicalStaffEntry);
  2078. const previousStaffEntry: GraphicalStaffEntry = measure.staffEntries[staffEntryIndex - 1];
  2079. const nextStaffEntry: GraphicalStaffEntry = measure.staffEntries[staffEntryIndex + 1];
  2080. if (previousStaffEntry.graphicalVoiceEntries.length === 1) {
  2081. const previousNote: GraphicalNote = previousStaffEntry.graphicalVoiceEntries[0].notes[0];
  2082. if (previousNote.sourceNote.NoteBeam !== undefined && nextStaffEntry.graphicalVoiceEntries.length === 1) {
  2083. const nextNote: GraphicalNote = nextStaffEntry.graphicalVoiceEntries[0].notes[0];
  2084. if (nextNote.sourceNote.NoteBeam !== undefined && previousNote.sourceNote.NoteBeam === nextNote.sourceNote.NoteBeam) {
  2085. this.calculateRestNotePlacementWithinGraphicalBeam(
  2086. graphicalStaffEntry, voice1Note1, previousNote,
  2087. nextStaffEntry, nextNote
  2088. );
  2089. graphicalStaffEntry.PositionAndShape.calculateBoundingBox();
  2090. }
  2091. }
  2092. }
  2093. }
  2094. }
  2095. protected getRelativePositionInStaffLineFromTimestamp(
  2096. timestamp: Fraction, verticalIndex: number, staffLine: StaffLine,
  2097. multiStaffInstrument: boolean, firstVisibleMeasureRelativeX: number = 0.0,
  2098. useLeftStaffEntryBorder: boolean = false
  2099. ): PointF2D {
  2100. let relative: PointF2D = new PointF2D();
  2101. let leftStaffEntry: GraphicalStaffEntry = undefined;
  2102. let rightStaffEntry: GraphicalStaffEntry = undefined;
  2103. const numEntries: number = this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers.length;
  2104. const index: number = this.graphicalMusicSheet.GetInterpolatedIndexInVerticalContainers(timestamp);
  2105. const leftIndex: number = Math.min(Math.floor(index), numEntries - 1);
  2106. const rightIndex: number = Math.min(Math.ceil(index), numEntries - 1);
  2107. if (leftIndex < 0 || verticalIndex < 0) {
  2108. return relative;
  2109. }
  2110. leftStaffEntry = this.getFirstLeftNotNullStaffEntryFromContainer(leftIndex, verticalIndex, multiStaffInstrument);
  2111. rightStaffEntry = this.getFirstRightNotNullStaffEntryFromContainer(rightIndex, verticalIndex, multiStaffInstrument);
  2112. if (leftStaffEntry && rightStaffEntry) {
  2113. let measureRelativeX: number = leftStaffEntry.parentMeasure.PositionAndShape.RelativePosition.x;
  2114. if (firstVisibleMeasureRelativeX > 0) {
  2115. measureRelativeX = firstVisibleMeasureRelativeX;
  2116. }
  2117. let leftX: number = leftStaffEntry.PositionAndShape.RelativePosition.x + measureRelativeX;
  2118. let rightX: number = rightStaffEntry.PositionAndShape.RelativePosition.x + rightStaffEntry.parentMeasure.PositionAndShape.RelativePosition.x;
  2119. const endAfterRightStaffEntry: boolean = timestamp.RealValue > rightStaffEntry.getAbsoluteTimestamp().RealValue;
  2120. // endAfterRightStaffEntry is an unfortunate case where the timestamp isn't correct for the last note in the piece,
  2121. // see test_wedge_diminuendo_duplicated.musicxml
  2122. if (firstVisibleMeasureRelativeX > 0) {
  2123. rightX = rightStaffEntry.PositionAndShape.RelativePosition.x + measureRelativeX;
  2124. } else if (useLeftStaffEntryBorder &&
  2125. (leftStaffEntry.getAbsoluteTimestamp().RealValue === timestamp.RealValue || endAfterRightStaffEntry)
  2126. ) {
  2127. leftX = leftStaffEntry.PositionAndShape.RelativePosition.x + leftStaffEntry.PositionAndShape.BorderLeft + measureRelativeX;
  2128. rightX = leftX;
  2129. }
  2130. let timestampQuotient: number = 0.0;
  2131. if (leftStaffEntry !== rightStaffEntry) {
  2132. const leftTimestamp: Fraction = leftStaffEntry.getAbsoluteTimestamp();
  2133. const rightTimestamp: Fraction = rightStaffEntry.getAbsoluteTimestamp();
  2134. const leftDifference: Fraction = Fraction.minus(timestamp, leftTimestamp);
  2135. timestampQuotient = leftDifference.RealValue / Fraction.minus(rightTimestamp, leftTimestamp).RealValue;
  2136. }
  2137. if (leftStaffEntry.parentMeasure.ParentStaffLine !== rightStaffEntry.parentMeasure.ParentStaffLine) {
  2138. if (leftStaffEntry.parentMeasure.ParentStaffLine === staffLine) {
  2139. rightX = staffLine.PositionAndShape.Size.width;
  2140. } else {
  2141. leftX = staffLine.PositionAndShape.RelativePosition.x;
  2142. }
  2143. }
  2144. relative = new PointF2D(leftX + (rightX - leftX) * timestampQuotient, 0.0);
  2145. }
  2146. return relative;
  2147. }
  2148. protected getRelativeXPositionFromTimestamp(timestamp: Fraction): number {
  2149. const numEntries: number = this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers.length;
  2150. const index: number = this.graphicalMusicSheet.GetInterpolatedIndexInVerticalContainers(timestamp);
  2151. const discreteIndex: number = Math.max(0, Math.min(Math.round(index), numEntries - 1));
  2152. const gse: GraphicalStaffEntry = this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[discreteIndex].getFirstNonNullStaffEntry();
  2153. const posX: number = gse.PositionAndShape.RelativePosition.x + gse.parentMeasure.PositionAndShape.RelativePosition.x;
  2154. return posX;
  2155. }
  2156. protected calculatePageLabels(page: GraphicalMusicPage): void {
  2157. if (this.rules.RenderSingleHorizontalStaffline) {
  2158. page.PositionAndShape.BorderRight = page.PositionAndShape.Size.width;
  2159. //page.PositionAndShape.BorderRight = page.PositionAndShape.Size.width + this.rules.PageRightMargin;
  2160. page.PositionAndShape.calculateBoundingBox();
  2161. this.graphicalMusicSheet.ParentMusicSheet.pageWidth = page.PositionAndShape.Size.width;
  2162. }
  2163. // The PositionAndShape child elements of page need to be manually connected to the lyricist, composer, subtitle, etc.
  2164. // because the page is only available now
  2165. let firstSystemAbsoluteTopMargin: number = 10;
  2166. let lastSystemAbsoluteBottomMargin: number = -1;
  2167. if (page.MusicSystems.length > 0) {
  2168. const firstMusicSystem: MusicSystem = page.MusicSystems[0];
  2169. firstSystemAbsoluteTopMargin = firstMusicSystem.PositionAndShape.RelativePosition.y + firstMusicSystem.PositionAndShape.BorderTop;
  2170. const lastMusicSystem: MusicSystem = page.MusicSystems[page.MusicSystems.length - 1];
  2171. lastSystemAbsoluteBottomMargin = lastMusicSystem.PositionAndShape.RelativePosition.y + lastMusicSystem.PositionAndShape.BorderBottom;
  2172. }
  2173. //const firstStaffLine: StaffLine = this.graphicalMusicSheet.MusicPages[0].MusicSystems[0].StaffLines[0];
  2174. if (this.graphicalMusicSheet.Title && this.rules.RenderTitle) {
  2175. const title: GraphicalLabel = this.graphicalMusicSheet.Title;
  2176. title.PositionAndShape.Parent = page.PositionAndShape;
  2177. //title.PositionAndShape.Parent = firstStaffLine.PositionAndShape;
  2178. const relative: PointF2D = new PointF2D();
  2179. relative.x = this.graphicalMusicSheet.ParentMusicSheet.pageWidth / 2;
  2180. //relative.x = firstStaffLine.PositionAndShape.RelativePosition.x + firstStaffLine.PositionAndShape.Size.width / 2; // half of first staffline width
  2181. relative.y = this.rules.TitleTopDistance + this.rules.SheetTitleHeight;
  2182. title.PositionAndShape.RelativePosition = relative;
  2183. page.Labels.push(title);
  2184. }
  2185. if (this.graphicalMusicSheet.Subtitle && this.rules.RenderTitle && this.rules.RenderSubtitle) {
  2186. const subtitle: GraphicalLabel = this.graphicalMusicSheet.Subtitle;
  2187. // subtitle.PositionAndShape.Parent = firstStaffLine.PositionAndShape;
  2188. subtitle.PositionAndShape.Parent = page.PositionAndShape;
  2189. const relative: PointF2D = new PointF2D();
  2190. relative.x = this.graphicalMusicSheet.ParentMusicSheet.pageWidth / 2;
  2191. //relative.x = firstStaffLine.PositionAndShape.RelativePosition.x + firstStaffLine.PositionAndShape.Size.width / 2; // half of first staffline width
  2192. relative.y = this.rules.TitleTopDistance + this.rules.SheetTitleHeight + this.rules.SheetMinimumDistanceBetweenTitleAndSubtitle;
  2193. const lines: number = subtitle.TextLines?.length;
  2194. if (lines > 1) { // Don't want to affect existing behavior. but this doesn't check bboxes for clip
  2195. relative.y += subtitle.PositionAndShape.BorderBottom * (lines - 1) / (lines);
  2196. }
  2197. subtitle.PositionAndShape.RelativePosition = relative;
  2198. page.Labels.push(subtitle);
  2199. }
  2200. // Get the first system, first staffline skybottomcalculator
  2201. // const topStaffline: StaffLine = page.MusicSystems[0].StaffLines[0];
  2202. // const skyBottomLineCalculator: SkyBottomLineCalculator = topStaffline.SkyBottomLineCalculator;
  2203. // we don't need a skybottomcalculator currently, labels are put above system skyline anyways.
  2204. const composer: GraphicalLabel = this.graphicalMusicSheet.Composer;
  2205. let composerRelativeY: number;
  2206. if (composer && this.rules.RenderComposer) {
  2207. composer.PositionAndShape.Parent = page.PositionAndShape; // if using pageWidth. (which can currently be too wide) TODO fix pageWidth (#578)
  2208. //composer.PositionAndShape.Parent = topStaffline.PositionAndShape; // if using firstStaffLine...width.
  2209. // y-collision problems, harder to y-align with lyrics
  2210. composer.setLabelPositionAndShapeBorders();
  2211. const relative: PointF2D = new PointF2D();
  2212. //const firstStaffLineEndX: number = this.rules.PageLeftMargin + this.rules.SystemLeftMargin + this.rules.left
  2213. // firstStaffLine.PositionAndShape.RelativePosition.x + firstStaffLine.PositionAndShape.Size.width;
  2214. //relative.x = Math.min(this.graphicalMusicSheet.ParentMusicSheet.pageWidth - this.rules.PageRightMargin,
  2215. // firstStaffLineEndX); // awkward with 2-bar score
  2216. relative.x = this.graphicalMusicSheet.ParentMusicSheet.pageWidth - this.rules.PageRightMargin;
  2217. //relative.x = firstStaffLine.PositionAndShape.Size.width;
  2218. //when this is less, goes higher.
  2219. //So 0 is top of the sheet, 22 or so is touching the music system margin
  2220. relative.y = firstSystemAbsoluteTopMargin;
  2221. //relative.y = - this.rules.SystemComposerDistance;
  2222. //relative.y = -firstStaffLine.PositionAndShape.Size.height;
  2223. // TODO only add measure label height if rendering labels and composer measure has label
  2224. // TODO y-align with lyricist? which is harder if they have different bbox parents (page and firstStaffLine).
  2225. // when the pageWidth gets fixed, we could use page as parent again.
  2226. //Sufficient for now to just use the longest composer entry instead of bottom.
  2227. //Otherwise we need to construct a 'bottom line' for the text block
  2228. // const endX: number = topStaffline.PositionAndShape.BorderMarginRight;
  2229. // const startX: number = endX - composer.PositionAndShape.Size.width;
  2230. // const currentMin: number = skyBottomLineCalculator.getSkyLineMinInRange(startX, endX);
  2231. relative.y -= this.rules.SystemComposerDistance;
  2232. const lines: number = composer.TextLines?.length;
  2233. if (lines > 1) { //Don't want to affect existing behavior. but this doesn't check bboxes for clip
  2234. relative.y -= composer.PositionAndShape.BorderBottom * (lines - 1) / (lines);
  2235. }
  2236. //const newSkylineY: number = currentMin; // don't add composer label height to skyline
  2237. //- firstSystemAbsoluteTopMargin - this.rules.SystemComposerDistance - composer.PositionAndShape.MarginSize.height;
  2238. //skyBottomLineCalculator.updateSkyLineInRange(startX, endX, newSkylineY); // this can fix skyline for generateImages for some reason
  2239. composerRelativeY = relative.y; // for lyricist label
  2240. composer.PositionAndShape.RelativePosition = relative;
  2241. page.Labels.push(composer);
  2242. }
  2243. const lyricist: GraphicalLabel = this.graphicalMusicSheet.Lyricist;
  2244. if (lyricist && this.rules.RenderLyricist) {
  2245. lyricist.PositionAndShape.Parent = page.PositionAndShape;
  2246. lyricist.setLabelPositionAndShapeBorders();
  2247. const relative: PointF2D = new PointF2D();
  2248. relative.x = this.rules.PageLeftMargin;
  2249. relative.y = firstSystemAbsoluteTopMargin;
  2250. // const startX: number = topStaffline.PositionAndShape.BorderMarginLeft - relative.x;
  2251. // const endX: number = startX + lyricist.PositionAndShape.Size.width;
  2252. // const currentMin: number = skyBottomLineCalculator.getSkyLineMinInRange(startX, endX);
  2253. relative.y -= this.rules.SystemLyricistDistance;
  2254. relative.y += lyricist.PositionAndShape.BorderBottom;
  2255. relative.y = Math.min(relative.y, composerRelativeY ?? Number.MAX_SAFE_INTEGER);
  2256. // same height as composer label (at least not lower). ?? prevents undefined -> Math.min returns NaN
  2257. //skyBottomLineCalculator.updateSkyLineInRange(startX, endX, currentMin - lyricist.PositionAndShape.MarginSize.height);
  2258. //relative.y = Math.max(relative.y, composer.PositionAndShape.RelativePosition.y);
  2259. lyricist.PositionAndShape.RelativePosition = relative;
  2260. page.Labels.push(lyricist);
  2261. }
  2262. const copyright: GraphicalLabel = this.graphicalMusicSheet.Copyright;
  2263. if (copyright && this.rules.RenderCopyright) {
  2264. copyright.PositionAndShape.Parent = page.PositionAndShape;
  2265. copyright.setLabelPositionAndShapeBorders();
  2266. const relative: PointF2D = new PointF2D();
  2267. relative.x = page.PositionAndShape.Size.width / 2;
  2268. relative.y = lastSystemAbsoluteBottomMargin + this.rules.SheetCopyrightMargin;
  2269. relative.y -= copyright.PositionAndShape.BorderTop;
  2270. copyright.PositionAndShape.RelativePosition = relative;
  2271. page.Labels.push(copyright);
  2272. }
  2273. }
  2274. protected createGraphicalTies(): void {
  2275. for (let measureIndex: number = 0; measureIndex < this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length; measureIndex++) {
  2276. const sourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[measureIndex];
  2277. for (let staffIndex: number = 0; staffIndex < sourceMeasure.CompleteNumberOfStaves; staffIndex++) {
  2278. for (let j: number = 0; j < sourceMeasure.VerticalSourceStaffEntryContainers.length; j++) {
  2279. const sourceStaffEntry: SourceStaffEntry = sourceMeasure.VerticalSourceStaffEntryContainers[j].StaffEntries[staffIndex];
  2280. if (sourceStaffEntry) {
  2281. const startStaffEntry: GraphicalStaffEntry = this.graphicalMusicSheet.findGraphicalStaffEntryFromMeasureList(
  2282. staffIndex, measureIndex, sourceStaffEntry
  2283. );
  2284. if (startStaffEntry) {
  2285. startStaffEntry.GraphicalTies.clear(); // don't duplicate ties when calling render() again
  2286. startStaffEntry.ties.clear();
  2287. }
  2288. for (let idx: number = 0, len: number = sourceStaffEntry.VoiceEntries.length; idx < len; ++idx) {
  2289. const voiceEntry: VoiceEntry = sourceStaffEntry.VoiceEntries[idx];
  2290. for (let idx2: number = 0, len2: number = voiceEntry.Notes.length; idx2 < len2; ++idx2) {
  2291. const note: Note = voiceEntry.Notes[idx2];
  2292. if (note.NoteTie) {
  2293. const tie: Tie = note.NoteTie;
  2294. if (note === note.NoteTie.Notes.last()) {
  2295. continue; // nothing to do on last note. don't create last tie twice.
  2296. }
  2297. if (startStaffEntry) {
  2298. for (const gTie of startStaffEntry.GraphicalTies) {
  2299. if (gTie.Tie === tie) {
  2300. continue; // don't handle the same tie on the same startStaffEntry twice
  2301. }
  2302. }
  2303. }
  2304. this.handleTie(tie, startStaffEntry, staffIndex, measureIndex);
  2305. }
  2306. }
  2307. }
  2308. this.setTieDirections(startStaffEntry);
  2309. }
  2310. }
  2311. }
  2312. }
  2313. }
  2314. private handleTie(tie: Tie, startGraphicalStaffEntry: GraphicalStaffEntry, staffIndex: number, measureIndex: number): void {
  2315. if (!startGraphicalStaffEntry) {
  2316. // console.log('tie not found in measure number ' + measureIndex - 1);
  2317. return;
  2318. }
  2319. startGraphicalStaffEntry.ties.push(tie);
  2320. let startGse: GraphicalStaffEntry = startGraphicalStaffEntry;
  2321. let startNote: GraphicalNote = undefined;
  2322. let endGse: GraphicalStaffEntry = undefined;
  2323. let endNote: GraphicalNote = undefined;
  2324. for (let i: number = 1; i < tie.Notes.length; i++) {
  2325. startNote = startGse.findTieGraphicalNoteFromNote(tie.Notes[i - 1]);
  2326. endGse = this.graphicalMusicSheet.GetGraphicalFromSourceStaffEntry(tie.Notes[i].ParentStaffEntry);
  2327. if (!endGse) {
  2328. continue;
  2329. }
  2330. endNote = endGse.findTieGraphicalNoteFromNote(tie.Notes[i]);
  2331. if (startNote !== undefined && endNote !== undefined && endGse) {
  2332. if (!startNote.sourceNote.PrintObject || !endNote.sourceNote.PrintObject) {
  2333. continue;
  2334. }
  2335. const graphicalTie: GraphicalTie = this.createGraphicalTie(tie, startGse, endGse, startNote, endNote);
  2336. startGse.GraphicalTies.push(graphicalTie);
  2337. if (this.staffEntriesWithGraphicalTies.indexOf(startGse) >= 0) {
  2338. this.staffEntriesWithGraphicalTies.push(startGse);
  2339. }
  2340. }
  2341. startGse = endGse;
  2342. }
  2343. }
  2344. private setTieDirections(staffEntry: GraphicalStaffEntry): void {
  2345. if (!staffEntry) {
  2346. return;
  2347. }
  2348. const ties: Tie[] = staffEntry.ties;
  2349. if (ties.length === 1) {
  2350. const tie: Tie = ties[0];
  2351. if (tie.TieDirection === PlacementEnum.NotYetDefined) {
  2352. const voiceId: number = tie.Notes[0].ParentVoiceEntry.ParentVoice.VoiceId;
  2353. // put ties of second voices (e.g. 2 for right hand, 6 left hand) below by default
  2354. // TODO could be more precise but also more complex by checking lower notes, other notes, etc.
  2355. if (voiceId === 2 || voiceId === 6) {
  2356. tie.TieDirection = PlacementEnum.Below;
  2357. }
  2358. }
  2359. }
  2360. if (ties.length > 1) {
  2361. let highestNote: Note = undefined;
  2362. for (const gseTie of ties) {
  2363. const tieNote: Note = gseTie.Notes[0];
  2364. if (!highestNote || tieNote.Pitch.getHalfTone() > highestNote.Pitch.getHalfTone()) {
  2365. highestNote = tieNote;
  2366. }
  2367. }
  2368. for (const gseTie of ties) {
  2369. if (gseTie.TieDirection === PlacementEnum.NotYetDefined) { // only set/change if not already set by xml
  2370. if (gseTie.Notes[0] === highestNote) {
  2371. gseTie.TieDirection = PlacementEnum.Above;
  2372. } else {
  2373. gseTie.TieDirection = PlacementEnum.Below;
  2374. }
  2375. }
  2376. }
  2377. }
  2378. }
  2379. private createAccidentalCalculators(): AccidentalCalculator[] {
  2380. const accidentalCalculators: AccidentalCalculator[] = [];
  2381. const firstSourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.getFirstSourceMeasure();
  2382. if (firstSourceMeasure) {
  2383. for (let i: number = 0; i < firstSourceMeasure.CompleteNumberOfStaves; i++) {
  2384. const accidentalCalculator: AccidentalCalculator = new AccidentalCalculator();
  2385. accidentalCalculators.push(accidentalCalculator);
  2386. if (firstSourceMeasure.FirstInstructionsStaffEntries[i]) {
  2387. for (let idx: number = 0, len: number = firstSourceMeasure.FirstInstructionsStaffEntries[i].Instructions.length; idx < len; ++idx) {
  2388. const abstractNotationInstruction: AbstractNotationInstruction = firstSourceMeasure.FirstInstructionsStaffEntries[i].Instructions[idx];
  2389. if (abstractNotationInstruction instanceof KeyInstruction) {
  2390. const keyInstruction: KeyInstruction = <KeyInstruction>abstractNotationInstruction;
  2391. accidentalCalculator.ActiveKeyInstruction = keyInstruction;
  2392. }
  2393. }
  2394. }
  2395. }
  2396. }
  2397. return accidentalCalculators;
  2398. }
  2399. private calculateVerticalContainersList(): void {
  2400. const numberOfEntries: number = this.graphicalMusicSheet.MeasureList[0].length;
  2401. for (let i: number = 0; i < this.graphicalMusicSheet.MeasureList.length; i++) {
  2402. for (let j: number = 0; j < numberOfEntries; j++) {
  2403. const measure: GraphicalMeasure = this.graphicalMusicSheet.MeasureList[i][j];
  2404. if (!measure) {
  2405. continue;
  2406. }
  2407. for (let idx: number = 0, len: number = measure.staffEntries.length; idx < len; ++idx) {
  2408. const graphicalStaffEntry: GraphicalStaffEntry = measure.staffEntries[idx];
  2409. const verticalContainer: VerticalGraphicalStaffEntryContainer =
  2410. this.graphicalMusicSheet.getOrCreateVerticalContainer(graphicalStaffEntry.getAbsoluteTimestamp());
  2411. if (verticalContainer) {
  2412. verticalContainer.StaffEntries[j] = graphicalStaffEntry;
  2413. graphicalStaffEntry.parentVerticalContainer = verticalContainer;
  2414. }
  2415. }
  2416. }
  2417. }
  2418. }
  2419. private setIndicesToVerticalGraphicalContainers(): void {
  2420. for (let i: number = 0; i < this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers.length; i++) {
  2421. this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[i].Index = i;
  2422. }
  2423. }
  2424. private createGraphicalMeasuresForSourceMeasure(sourceMeasure: SourceMeasure, accidentalCalculators: AccidentalCalculator[],
  2425. openLyricWords: LyricWord[],
  2426. openOctaveShifts: OctaveShiftParams[], activeClefs: ClefInstruction[]): GraphicalMeasure[] {
  2427. this.initGraphicalMeasuresCreation();
  2428. const verticalMeasureList: GraphicalMeasure[] = []; // (VexFlowMeasure, extends GraphicalMeasure)
  2429. const openBeams: Beam[] = [];
  2430. const openTuplets: Tuplet[] = [];
  2431. const staffEntryLinks: StaffEntryLink[] = [];
  2432. let restInAllGraphicalMeasures: boolean = true;
  2433. for (let staffIndex: number = 0; staffIndex < sourceMeasure.CompleteNumberOfStaves; staffIndex++) {
  2434. const measure: GraphicalMeasure = this.createGraphicalMeasure( // (VexFlowMeasure)
  2435. sourceMeasure, openTuplets, openBeams,
  2436. accidentalCalculators[staffIndex], activeClefs, openOctaveShifts, openLyricWords, staffIndex, staffEntryLinks
  2437. );
  2438. restInAllGraphicalMeasures = restInAllGraphicalMeasures && measure.hasOnlyRests;
  2439. verticalMeasureList.push(measure);
  2440. }
  2441. sourceMeasure.allRests = restInAllGraphicalMeasures;
  2442. sourceMeasure.VerticalMeasureList = verticalMeasureList; // much easier way to link sourceMeasure to graphicalMeasures than Dictionary
  2443. //this.graphicalMusicSheet.sourceToGraphicalMeasureLinks.setValue(sourceMeasure, verticalMeasureList); // overwrites entries because:
  2444. //this.graphicalMusicSheet.sourceToGraphicalMeasureLinks[sourceMeasure] = verticalMeasureList; // can't use SourceMeasure as key.
  2445. // to save the reference by dictionary we would need two Dictionaries, id -> sourceMeasure and id -> GraphicalMeasure.
  2446. return verticalMeasureList;
  2447. }
  2448. private createGraphicalMeasure(sourceMeasure: SourceMeasure, openTuplets: Tuplet[], openBeams: Beam[],
  2449. accidentalCalculator: AccidentalCalculator, activeClefs: ClefInstruction[],
  2450. openOctaveShifts: OctaveShiftParams[], openLyricWords: LyricWord[], staffIndex: number,
  2451. staffEntryLinks: StaffEntryLink[]): GraphicalMeasure {
  2452. const staff: Staff = this.graphicalMusicSheet.ParentMusicSheet.getStaffFromIndex(staffIndex);
  2453. let measure: GraphicalMeasure = undefined;
  2454. if (activeClefs[staffIndex].ClefType === ClefEnum.TAB) {
  2455. staff.isTab = true;
  2456. measure = MusicSheetCalculator.symbolFactory.createTabStaffMeasure(sourceMeasure, staff);
  2457. } else if (sourceMeasure.multipleRestMeasures && this.rules.RenderMultipleRestMeasures) {
  2458. measure = MusicSheetCalculator.symbolFactory.createMultiRestMeasure(sourceMeasure, staff);
  2459. } else if (sourceMeasure.multipleRestMeasureNumber > 1) {
  2460. return undefined; // don't need to create a graphical measure that is within a multiple rest measure
  2461. } else {
  2462. measure = MusicSheetCalculator.symbolFactory.createGraphicalMeasure(sourceMeasure, staff);
  2463. }
  2464. measure.hasError = sourceMeasure.getErrorInMeasure(staffIndex);
  2465. // check for key instruction changes
  2466. if (sourceMeasure.FirstInstructionsStaffEntries[staffIndex]) {
  2467. for (let idx: number = 0, len: number = sourceMeasure.FirstInstructionsStaffEntries[staffIndex].Instructions.length; idx < len; ++idx) {
  2468. const instruction: AbstractNotationInstruction = sourceMeasure.FirstInstructionsStaffEntries[staffIndex].Instructions[idx];
  2469. if (instruction instanceof KeyInstruction) {
  2470. const key: KeyInstruction = KeyInstruction.copy(instruction);
  2471. const transposeHalftones: number = measure.getTransposedHalftones();
  2472. if (transposeHalftones !== 0 &&
  2473. measure.ParentStaff.ParentInstrument.MidiInstrumentId !== MidiInstrument.Percussion &&
  2474. MusicSheetCalculator.transposeCalculator) {
  2475. MusicSheetCalculator.transposeCalculator.transposeKey(
  2476. key, transposeHalftones
  2477. );
  2478. }
  2479. accidentalCalculator.ActiveKeyInstruction = key;
  2480. }
  2481. }
  2482. }
  2483. // check for octave shifts
  2484. const octaveShifts: MultiExpression[] = [];
  2485. for (let idx: number = 0, len: number = sourceMeasure.StaffLinkedExpressions[staffIndex].length; idx < len; ++idx) {
  2486. const multiExpression: MultiExpression = sourceMeasure.StaffLinkedExpressions[staffIndex][idx];
  2487. let targetOctaveShift: OctaveShift;
  2488. if (multiExpression.OctaveShiftStart) {
  2489. targetOctaveShift = multiExpression.OctaveShiftStart;
  2490. } else if (multiExpression.OctaveShiftEnd) {
  2491. // also check for octave shift that is ending here but starting in earlier measure, see test_octaveshift_notes_shifted_octave_shift_end.musicxml
  2492. targetOctaveShift = multiExpression.OctaveShiftEnd;
  2493. }
  2494. if (targetOctaveShift) {
  2495. octaveShifts.push(multiExpression);
  2496. const openOctaveShift: OctaveShift = targetOctaveShift;
  2497. let absoluteEnd: Fraction = openOctaveShift?.ParentEndMultiExpression?.AbsoluteTimestamp;
  2498. if (!openOctaveShift?.ParentEndMultiExpression) {
  2499. const measureEndTimestamp: Fraction = Fraction.plus(sourceMeasure.AbsoluteTimestamp, sourceMeasure.Duration);
  2500. absoluteEnd = measureEndTimestamp;
  2501. // TODO better handling if end expression missing
  2502. // old comment:
  2503. // TODO check if octaveshift end exists, otherwise set to last measure end. only necessary if xml was cut manually and is incomplete
  2504. }
  2505. openOctaveShifts[staffIndex] = new OctaveShiftParams(
  2506. openOctaveShift, openOctaveShift.ParentStartMultiExpression.AbsoluteTimestamp,
  2507. //openOctaveShift, multiExpression?.AbsoluteTimestamp,
  2508. absoluteEnd
  2509. );
  2510. }
  2511. }
  2512. // create GraphicalStaffEntries - always check for possible null Entry
  2513. for (let entryIndex: number = 0; entryIndex < sourceMeasure.VerticalSourceStaffEntryContainers.length; entryIndex++) {
  2514. const sourceStaffEntry: SourceStaffEntry = sourceMeasure.VerticalSourceStaffEntryContainers[entryIndex].StaffEntries[staffIndex];
  2515. // is there a SourceStaffEntry at this Index
  2516. if (sourceStaffEntry) {
  2517. // a SourceStaffEntry exists
  2518. // is there an inStaff ClefInstruction? -> update activeClef
  2519. for (let idx: number = 0, len: number = sourceStaffEntry.Instructions.length; idx < len; ++idx) {
  2520. const abstractNotationInstruction: AbstractNotationInstruction = sourceStaffEntry.Instructions[idx];
  2521. if (abstractNotationInstruction instanceof ClefInstruction) {
  2522. activeClefs[staffIndex] = <ClefInstruction>abstractNotationInstruction;
  2523. }
  2524. }
  2525. // create new GraphicalStaffEntry
  2526. const graphicalStaffEntry: GraphicalStaffEntry = MusicSheetCalculator.symbolFactory.createStaffEntry(sourceStaffEntry, measure);
  2527. if (entryIndex < measure.staffEntries.length) {
  2528. // a GraphicalStaffEntry has been inserted already at this Index (from Tie)
  2529. measure.addGraphicalStaffEntryAtTimestamp(graphicalStaffEntry);
  2530. } else {
  2531. measure.addGraphicalStaffEntry(graphicalStaffEntry);
  2532. }
  2533. const linkedNotes: Note[] = [];
  2534. if (sourceStaffEntry.Link) {
  2535. sourceStaffEntry.findLinkedNotes(linkedNotes);
  2536. this.handleStaffEntryLink(graphicalStaffEntry, staffEntryLinks);
  2537. }
  2538. // check for possible OctaveShift
  2539. let octaveShiftValue: OctaveEnum = OctaveEnum.NONE;
  2540. if (openOctaveShifts[staffIndex]) {
  2541. if (openOctaveShifts[staffIndex].getAbsoluteStartTimestamp.lte(sourceStaffEntry.AbsoluteTimestamp) &&
  2542. sourceStaffEntry.AbsoluteTimestamp.lte(openOctaveShifts[staffIndex].getAbsoluteEndTimestamp)) {
  2543. octaveShiftValue = openOctaveShifts[staffIndex].getOpenOctaveShift.Type;
  2544. }
  2545. }
  2546. if (octaveShiftValue === OctaveEnum.NONE) {
  2547. // check for existing octave shifts outside openOctaveShifts
  2548. for (const octaveShift of octaveShifts) {
  2549. let targetOctaveShift: OctaveShift;
  2550. if (octaveShift.OctaveShiftStart) {
  2551. targetOctaveShift = octaveShift.OctaveShiftStart;
  2552. } else if (octaveShift.OctaveShiftEnd) {
  2553. targetOctaveShift = octaveShift.OctaveShiftEnd;
  2554. }
  2555. if (targetOctaveShift?.ParentStartMultiExpression?.AbsoluteTimestamp.lte(sourceStaffEntry.AbsoluteTimestamp) &&
  2556. !targetOctaveShift.ParentEndMultiExpression?.AbsoluteTimestamp.lt(sourceStaffEntry.AbsoluteTimestamp)) {
  2557. octaveShiftValue = targetOctaveShift.Type;
  2558. break;
  2559. }
  2560. }
  2561. }
  2562. // for each visible Voice create the corresponding GraphicalNotes
  2563. for (let idx: number = 0, len: number = sourceStaffEntry.VoiceEntries.length; idx < len; ++idx) {
  2564. const voiceEntry: VoiceEntry = sourceStaffEntry.VoiceEntries[idx];
  2565. // Normal Notes...
  2566. octaveShiftValue = this.handleVoiceEntry(
  2567. voiceEntry, graphicalStaffEntry,
  2568. accidentalCalculator, openLyricWords,
  2569. activeClefs[staffIndex], openTuplets,
  2570. openBeams, octaveShiftValue, staffIndex,
  2571. linkedNotes, sourceStaffEntry
  2572. );
  2573. }
  2574. // SourceStaffEntry has inStaff ClefInstruction -> create graphical clef
  2575. if (sourceStaffEntry.Instructions.length > 0) {
  2576. const clefInstruction: ClefInstruction = <ClefInstruction>sourceStaffEntry.Instructions[0];
  2577. MusicSheetCalculator.symbolFactory.createInStaffClef(graphicalStaffEntry, clefInstruction);
  2578. }
  2579. if (this.rules.RenderChordSymbols && sourceStaffEntry.ChordContainers?.length > 0) {
  2580. sourceStaffEntry.ParentStaff.ParentInstrument.HasChordSymbols = true;
  2581. MusicSheetCalculator.symbolFactory.createChordSymbols(
  2582. sourceStaffEntry,
  2583. graphicalStaffEntry,
  2584. accidentalCalculator.ActiveKeyInstruction,
  2585. this.graphicalMusicSheet.ParentMusicSheet.Transpose);
  2586. }
  2587. }
  2588. }
  2589. accidentalCalculator.doCalculationsAtEndOfMeasure();
  2590. // update activeClef given at end of measure if needed
  2591. if (sourceMeasure.LastInstructionsStaffEntries[staffIndex]) {
  2592. const lastStaffEntry: SourceStaffEntry = sourceMeasure.LastInstructionsStaffEntries[staffIndex];
  2593. for (let idx: number = 0, len: number = lastStaffEntry.Instructions.length; idx < len; ++idx) {
  2594. const abstractNotationInstruction: AbstractNotationInstruction = lastStaffEntry.Instructions[idx];
  2595. if (abstractNotationInstruction instanceof ClefInstruction) {
  2596. activeClefs[staffIndex] = <ClefInstruction>abstractNotationInstruction;
  2597. }
  2598. }
  2599. }
  2600. for (let idx: number = 0, len: number = sourceMeasure.StaffLinkedExpressions[staffIndex].length; idx < len; ++idx) {
  2601. const multiExpression: MultiExpression = sourceMeasure.StaffLinkedExpressions[staffIndex][idx];
  2602. if (multiExpression.OctaveShiftEnd !== undefined && openOctaveShifts[staffIndex] !== undefined &&
  2603. multiExpression.OctaveShiftEnd === openOctaveShifts[staffIndex].getOpenOctaveShift) {
  2604. openOctaveShifts[staffIndex] = undefined;
  2605. }
  2606. }
  2607. // check wantedStemDirections of beam notes at end of measure (e.g. for beam with grace notes)
  2608. for (const staffEntry of measure.staffEntries) {
  2609. for (const voiceEntry of staffEntry.graphicalVoiceEntries) {
  2610. this.setBeamNotesWantedStemDirections(voiceEntry.parentVoiceEntry);
  2611. }
  2612. }
  2613. // if there are no staffEntries in this measure, create a rest for the whole measure:
  2614. // check OSMDOptions.fillEmptyMeasuresWithWholeRest
  2615. if (this.rules.FillEmptyMeasuresWithWholeRest >= 1) { // fill measures with no notes given with whole rests, visible (1) or invisible (2)
  2616. if (measure.staffEntries.length === 0) {
  2617. const sourceStaffEntry: SourceStaffEntry = new SourceStaffEntry(
  2618. new VerticalSourceStaffEntryContainer(measure.parentSourceMeasure,
  2619. measure.parentSourceMeasure.AbsoluteTimestamp,
  2620. measure.parentSourceMeasure.CompleteNumberOfStaves),
  2621. staff);
  2622. if (staff.Voices.length === 0) {
  2623. const newVoice: Voice = new Voice(measure.ParentStaff.ParentInstrument, -1);
  2624. // this is problematic because we don't know the MusicXML voice ids and how many voices with which ids will be created after this.
  2625. // but it should only happen when the first measure of the piece is empty.
  2626. staff.Voices.push(newVoice);
  2627. }
  2628. const voiceEntry: VoiceEntry = new VoiceEntry(new Fraction(0, 1), staff.Voices[0], sourceStaffEntry);
  2629. let duration: Fraction = sourceMeasure.Duration;
  2630. if (duration.RealValue === 0) {
  2631. duration = sourceMeasure.ActiveTimeSignature.clone();
  2632. }
  2633. const note: Note = new Note(voiceEntry, sourceStaffEntry, duration, undefined, sourceMeasure, true);
  2634. note.IsWholeMeasureRest = true; // there may be a more elegant solution
  2635. note.PrintObject = this.rules.FillEmptyMeasuresWithWholeRest === FillEmptyMeasuresWithWholeRests.YesVisible;
  2636. // don't display whole rest that wasn't given in XML, only for layout/voice completion
  2637. voiceEntry.addNote(note);
  2638. const graphicalStaffEntry: GraphicalStaffEntry = MusicSheetCalculator.symbolFactory.createStaffEntry(sourceStaffEntry, measure);
  2639. measure.addGraphicalStaffEntry(graphicalStaffEntry);
  2640. graphicalStaffEntry.relInMeasureTimestamp = voiceEntry.Timestamp;
  2641. const gve: GraphicalVoiceEntry = MusicSheetCalculator.symbolFactory.createVoiceEntry(voiceEntry, graphicalStaffEntry);
  2642. graphicalStaffEntry.graphicalVoiceEntries.push(gve);
  2643. const graphicalNote: GraphicalNote = MusicSheetCalculator.symbolFactory.createNote(
  2644. note,
  2645. gve,
  2646. new ClefInstruction(),
  2647. OctaveEnum.NONE,
  2648. this.rules);
  2649. MusicSheetCalculator.stafflineNoteCalculator.trackNote(graphicalNote);
  2650. gve.notes.push(graphicalNote);
  2651. }
  2652. }
  2653. measure.hasOnlyRests = true;
  2654. //if staff entries empty, loop will not start. so true is valid
  2655. for (const graphicalStaffEntry of measure.staffEntries) {
  2656. //Loop until we get just one false
  2657. measure.hasOnlyRests = graphicalStaffEntry.hasOnlyRests();
  2658. if (!measure.hasOnlyRests) {
  2659. break;
  2660. }
  2661. }
  2662. return measure;
  2663. }
  2664. private checkNoteForAccidental(graphicalNote: GraphicalNote, accidentalCalculator: AccidentalCalculator, activeClef: ClefInstruction,
  2665. octaveEnum: OctaveEnum): void {
  2666. let pitch: Pitch = graphicalNote.sourceNote.Pitch;
  2667. const transposeHalftones: number = graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure.getTransposedHalftones();
  2668. if (transposeHalftones !== 0 && graphicalNote.sourceNote.ParentStaffEntry.ParentStaff.ParentInstrument.MidiInstrumentId !== MidiInstrument.Percussion) {
  2669. pitch = graphicalNote.Transpose(
  2670. accidentalCalculator.ActiveKeyInstruction, activeClef, transposeHalftones, octaveEnum
  2671. );
  2672. graphicalNote.sourceNote.TransposedPitch = pitch;
  2673. }
  2674. graphicalNote.sourceNote.halfTone = pitch.getHalfTone();
  2675. accidentalCalculator.checkAccidental(graphicalNote, pitch);
  2676. }
  2677. // private createStaffEntryForTieNote(measure: StaffMeasure, absoluteTimestamp: Fraction, openTie: Tie): GraphicalStaffEntry {
  2678. // let graphicalStaffEntry: GraphicalStaffEntry;
  2679. // graphicalStaffEntry = MusicSheetCalculator.symbolFactory.createStaffEntry(openTie.Start.ParentStaffEntry, measure);
  2680. // graphicalStaffEntry.relInMeasureTimestamp = Fraction.minus(absoluteTimestamp, measure.parentSourceMeasure.AbsoluteTimestamp);
  2681. // this.resetYPositionForLeadSheet(graphicalStaffEntry.PositionAndShape);
  2682. // measure.addGraphicalStaffEntryAtTimestamp(graphicalStaffEntry);
  2683. // return graphicalStaffEntry;
  2684. // }
  2685. private handleStaffEntries(staffIsPercussionArray: Array<boolean>): void {
  2686. for (let idx: number = 0, len: number = this.graphicalMusicSheet.MeasureList.length; idx < len; ++idx) {
  2687. const measures: GraphicalMeasure[] = this.graphicalMusicSheet.MeasureList[idx];
  2688. for (let idx2: number = 0, len2: number = measures.length; idx2 < len2; ++idx2) {
  2689. const measure: GraphicalMeasure = measures[idx2];
  2690. if (!measure) {
  2691. continue;
  2692. }
  2693. //This property is active...
  2694. if (this.rules.PercussionOneLineCutoff > 0 && !this.rules.PercussionUseCajon2NoteSystem) {
  2695. //We have a percussion clef, check to see if this property applies...
  2696. if (staffIsPercussionArray[idx2]) {
  2697. //-1 means always trigger, or we are under the cutoff number specified
  2698. if (this.rules.PercussionOneLineCutoff === -1 ||
  2699. MusicSheetCalculator.stafflineNoteCalculator.getStafflineUniquePositionCount(idx2) < this.rules.PercussionOneLineCutoff) {
  2700. measure.ParentStaff.StafflineCount = 1;
  2701. }
  2702. }
  2703. }
  2704. for (const graphicalStaffEntry of measure.staffEntries) {
  2705. if (graphicalStaffEntry.parentMeasure !== undefined
  2706. && graphicalStaffEntry.graphicalVoiceEntries.length > 0
  2707. && graphicalStaffEntry.graphicalVoiceEntries[0].notes.length > 0) {
  2708. this.layoutVoiceEntries(graphicalStaffEntry, idx2);
  2709. this.layoutStaffEntry(graphicalStaffEntry);
  2710. }
  2711. }
  2712. this.graphicalMeasureCreatedCalculations(measure);
  2713. }
  2714. }
  2715. }
  2716. protected calculateSkyBottomLines(): void {
  2717. // override
  2718. }
  2719. /**
  2720. * Re-adjust the x positioning of expressions.
  2721. */
  2722. protected calculateExpressionAlignements(): void {
  2723. // override
  2724. }
  2725. // does nothing for now, because layoutBeams() is an empty method
  2726. // private calculateBeams(): void {
  2727. // for (let idx2: number = 0, len2: number = this.musicSystems.length; idx2 < len2; ++idx2) {
  2728. // const musicSystem: MusicSystem = this.musicSystems[idx2];
  2729. // for (let idx3: number = 0, len3: number = musicSystem.StaffLines.length; idx3 < len3; ++idx3) {
  2730. // const staffLine: StaffLine = musicSystem.StaffLines[idx3];
  2731. // for (let idx4: number = 0, len4: number = staffLine.Measures.length; idx4 < len4; ++idx4) {
  2732. // const measure: GraphicalMeasure = staffLine.Measures[idx4];
  2733. // for (let idx5: number = 0, len5: number = measure.staffEntries.length; idx5 < len5; ++idx5) {
  2734. // const staffEntry: GraphicalStaffEntry = measure.staffEntries[idx5];
  2735. // this.layoutBeams(staffEntry);
  2736. // }
  2737. // }
  2738. // }
  2739. // }
  2740. // }
  2741. private calculateStaffEntryArticulationMarks(): void {
  2742. for (let idx2: number = 0, len2: number = this.musicSystems.length; idx2 < len2; ++idx2) {
  2743. const system: MusicSystem = this.musicSystems[idx2];
  2744. for (let idx3: number = 0, len3: number = system.StaffLines.length; idx3 < len3; ++idx3) {
  2745. const line: StaffLine = system.StaffLines[idx3];
  2746. for (let idx4: number = 0, len4: number = line.Measures.length; idx4 < len4; ++idx4) {
  2747. const measure: GraphicalMeasure = line.Measures[idx4];
  2748. for (let idx5: number = 0, len5: number = measure.staffEntries.length; idx5 < len5; ++idx5) {
  2749. const graphicalStaffEntry: GraphicalStaffEntry = measure.staffEntries[idx5];
  2750. for (let idx6: number = 0, len6: number = graphicalStaffEntry.sourceStaffEntry.VoiceEntries.length; idx6 < len6; ++idx6) {
  2751. const voiceEntry: VoiceEntry = graphicalStaffEntry.sourceStaffEntry.VoiceEntries[idx6];
  2752. if (voiceEntry.Articulations.length > 0) {
  2753. this.layoutArticulationMarks(voiceEntry.Articulations, voiceEntry, graphicalStaffEntry);
  2754. }
  2755. }
  2756. }
  2757. }
  2758. }
  2759. }
  2760. }
  2761. private calculateOrnaments(): void {
  2762. for (let idx2: number = 0, len2: number = this.musicSystems.length; idx2 < len2; ++idx2) {
  2763. const system: MusicSystem = this.musicSystems[idx2];
  2764. for (let idx3: number = 0, len3: number = system.StaffLines.length; idx3 < len3; ++idx3) {
  2765. const line: StaffLine = system.StaffLines[idx3];
  2766. for (let idx4: number = 0, len4: number = line.Measures.length; idx4 < len4; ++idx4) {
  2767. const measure: GraphicalMeasure = line.Measures[idx4];
  2768. for (let idx5: number = 0, len5: number = measure.staffEntries.length; idx5 < len5; ++idx5) {
  2769. const graphicalStaffEntry: GraphicalStaffEntry = measure.staffEntries[idx5];
  2770. for (let idx6: number = 0, len6: number = graphicalStaffEntry.sourceStaffEntry.VoiceEntries.length; idx6 < len6; ++idx6) {
  2771. const voiceEntry: VoiceEntry = graphicalStaffEntry.sourceStaffEntry.VoiceEntries[idx6];
  2772. if (voiceEntry.OrnamentContainer) {
  2773. if (voiceEntry.hasTie() && !graphicalStaffEntry.relInMeasureTimestamp.Equals(voiceEntry.Timestamp)) {
  2774. continue;
  2775. }
  2776. this.layoutOrnament(voiceEntry.OrnamentContainer, voiceEntry, graphicalStaffEntry);
  2777. if (!(this.staffEntriesWithOrnaments.indexOf(graphicalStaffEntry) !== -1)) {
  2778. this.staffEntriesWithOrnaments.push(graphicalStaffEntry);
  2779. }
  2780. }
  2781. }
  2782. }
  2783. }
  2784. }
  2785. }
  2786. }
  2787. private getFingeringPlacement(measure: GraphicalMeasure): PlacementEnum {
  2788. let placement: PlacementEnum = this.rules.FingeringPosition;
  2789. if (placement === PlacementEnum.NotYetDefined || placement === PlacementEnum.AboveOrBelow) {
  2790. placement = measure.isUpperStaffOfInstrument() ? PlacementEnum.Above : PlacementEnum.Below;
  2791. }
  2792. return placement;
  2793. }
  2794. public calculateFingerings(): void {
  2795. if (this.rules.FingeringPosition === PlacementEnum.Left ||
  2796. this.rules.FingeringPosition === PlacementEnum.Right) {
  2797. return;
  2798. }
  2799. for (const system of this.musicSystems) {
  2800. for (const line of system.StaffLines) {
  2801. for (const measure of line.Measures) {
  2802. if (measure.isTabMeasure && !this.rules.TabFingeringsRendered) {
  2803. continue; // don't duplicate fingerings into tab measures. tab notes are already
  2804. }
  2805. const placement: PlacementEnum = this.getFingeringPlacement(measure);
  2806. for (const gse of measure.staffEntries) {
  2807. gse.FingeringEntries = [];
  2808. const skybottomcalculator: SkyBottomLineCalculator = line.SkyBottomLineCalculator;
  2809. const staffEntryPositionX: number = gse.PositionAndShape.RelativePosition.x +
  2810. measure.PositionAndShape.RelativePosition.x;
  2811. const fingerings: TechnicalInstruction[] = [];
  2812. for (const voiceEntry of gse.graphicalVoiceEntries) {
  2813. if (voiceEntry.parentVoiceEntry.IsGrace) {
  2814. continue;
  2815. }
  2816. // Sibelius: can have multiple fingerings per note, so we need to check voice entry instructions, not note.Fingering
  2817. for (const instruction of voiceEntry.parentVoiceEntry.TechnicalInstructions) {
  2818. if (instruction.type === TechnicalInstructionType.Fingering) {
  2819. fingerings.push(instruction);
  2820. }
  2821. }
  2822. // for (const note of voiceEntry.notes) {
  2823. // const sourceNote: Note = note.sourceNote;
  2824. // if (sourceNote.Fingering && !sourceNote.IsGraceNote) {
  2825. // fingerings.push(sourceNote.Fingering);
  2826. // }
  2827. // }
  2828. }
  2829. if (placement === PlacementEnum.Below) {
  2830. fingerings.reverse();
  2831. }
  2832. for (let i: number = 0; i < fingerings.length; i++) {
  2833. const fingering: TechnicalInstruction = fingerings[i];
  2834. const alignment: TextAlignmentEnum =
  2835. placement === PlacementEnum.Above ? TextAlignmentEnum.CenterBottom : TextAlignmentEnum.CenterTop;
  2836. const label: Label = new Label(fingering.value, alignment);
  2837. const gLabel: GraphicalLabel = new GraphicalLabel(
  2838. label, this.rules.FingeringTextSize, label.textAlignment, this.rules, line.PositionAndShape);
  2839. const marginLeft: number = staffEntryPositionX + gLabel.PositionAndShape.BorderMarginLeft;
  2840. const marginRight: number = staffEntryPositionX + gLabel.PositionAndShape.BorderMarginRight;
  2841. let skybottomFurthest: number = undefined;
  2842. if (placement === PlacementEnum.Above) {
  2843. skybottomFurthest = skybottomcalculator.getSkyLineMinInRange(marginLeft, marginRight);
  2844. } else {
  2845. skybottomFurthest = skybottomcalculator.getBottomLineMaxInRange(marginLeft, marginRight);
  2846. }
  2847. let yShift: number = 0;
  2848. if (i === 0) {
  2849. yShift += this.rules.FingeringOffsetY;
  2850. if (placement === PlacementEnum.Above) {
  2851. yShift += 0.1; // above fingerings are a bit closer to the notes than below ones for some reason
  2852. }
  2853. } else {
  2854. yShift += this.rules.FingeringPaddingY;
  2855. }
  2856. if (placement === PlacementEnum.Above) {
  2857. yShift *= -1;
  2858. }
  2859. gLabel.PositionAndShape.RelativePosition.y += skybottomFurthest + yShift;
  2860. gLabel.PositionAndShape.RelativePosition.x = staffEntryPositionX;
  2861. gLabel.setLabelPositionAndShapeBorders();
  2862. gLabel.PositionAndShape.calculateBoundingBox();
  2863. gse.FingeringEntries.push(gLabel);
  2864. const start: number = gLabel.PositionAndShape.RelativePosition.x + gLabel.PositionAndShape.BorderLeft;
  2865. //start -= line.PositionAndShape.RelativePosition.x;
  2866. const end: number = start - gLabel.PositionAndShape.BorderLeft + gLabel.PositionAndShape.BorderRight;
  2867. if (placement === PlacementEnum.Above) {
  2868. skybottomcalculator.updateSkyLineInRange(
  2869. start, end, gLabel.PositionAndShape.RelativePosition.y + gLabel.PositionAndShape.BorderTop); // BorderMarginTop too much
  2870. } else if (placement === PlacementEnum.Below) {
  2871. skybottomcalculator.updateBottomLineInRange(
  2872. start, end, gLabel.PositionAndShape.RelativePosition.y + gLabel.PositionAndShape.BorderBottom);
  2873. }
  2874. }
  2875. }
  2876. }
  2877. }
  2878. }
  2879. }
  2880. private optimizeRestPlacement(): void {
  2881. for (let idx2: number = 0, len2: number = this.musicSystems.length; idx2 < len2; ++idx2) {
  2882. const system: MusicSystem = this.musicSystems[idx2];
  2883. for (let idx3: number = 0, len3: number = system.StaffLines.length; idx3 < len3; ++idx3) {
  2884. const line: StaffLine = system.StaffLines[idx3];
  2885. for (let idx4: number = 0, len4: number = line.Measures.length; idx4 < len4; ++idx4) {
  2886. const measure: GraphicalMeasure = line.Measures[idx4];
  2887. for (let idx5: number = 0, len5: number = measure.staffEntries.length; idx5 < len5; ++idx5) {
  2888. const graphicalStaffEntry: GraphicalStaffEntry = measure.staffEntries[idx5];
  2889. this.optimizeRestNotePlacement(graphicalStaffEntry, measure);
  2890. }
  2891. }
  2892. }
  2893. }
  2894. }
  2895. private calculateTwoRestNotesPlacementWithCollisionDetection(graphicalStaffEntry: GraphicalStaffEntry): void {
  2896. const firstRestNote: GraphicalNote = graphicalStaffEntry.graphicalVoiceEntries[0].notes[0];
  2897. const secondRestNote: GraphicalNote = graphicalStaffEntry.graphicalVoiceEntries[1].notes[0];
  2898. secondRestNote.PositionAndShape.RelativePosition = new PointF2D(0.0, 2.5);
  2899. graphicalStaffEntry.PositionAndShape.calculateAbsolutePositionsRecursiveWithoutTopelement();
  2900. firstRestNote.PositionAndShape.computeNonOverlappingPositionWithMargin(
  2901. graphicalStaffEntry.PositionAndShape, ColDirEnum.Up,
  2902. new PointF2D(0.0, secondRestNote.PositionAndShape.RelativePosition.y)
  2903. );
  2904. const relative: PointF2D = firstRestNote.PositionAndShape.RelativePosition;
  2905. relative.y -= 1.0;
  2906. firstRestNote.PositionAndShape.RelativePosition = relative;
  2907. graphicalStaffEntry.PositionAndShape.calculateBoundingBox();
  2908. }
  2909. private calculateRestNotePlacementWithCollisionDetectionFromGraphicalNote(graphicalStaffEntry: GraphicalStaffEntry): void {
  2910. let restNote: GraphicalNote;
  2911. let graphicalNotes: GraphicalNote[];
  2912. if (graphicalStaffEntry.graphicalVoiceEntries[0].notes[0].sourceNote.isRest()) {
  2913. restNote = graphicalStaffEntry.graphicalVoiceEntries[0].notes[0];
  2914. graphicalNotes = graphicalStaffEntry.graphicalVoiceEntries[1].notes;
  2915. } else {
  2916. graphicalNotes = graphicalStaffEntry.graphicalVoiceEntries[0].notes;
  2917. restNote = graphicalStaffEntry.graphicalVoiceEntries[1].notes[0];
  2918. }
  2919. //restNote.parallelVoiceEntryNotes = graphicalNotes; // TODO maybe save potentially colliding notes, check them in VexFlowConverter.StaveNote
  2920. let collision: boolean = false;
  2921. graphicalStaffEntry.PositionAndShape.calculateAbsolutePositionsRecursiveWithoutTopelement();
  2922. for (let idx: number = 0, len: number = graphicalNotes.length; idx < len; ++idx) {
  2923. const graphicalNote: GraphicalNote = graphicalNotes[idx];
  2924. if (restNote.PositionAndShape.marginCollisionDetection(graphicalNote.PositionAndShape)) {
  2925. // TODO bounding box of graphical note isn't set correctly yet.
  2926. // we could do manual collision checking here
  2927. collision = true;
  2928. break;
  2929. }
  2930. }
  2931. if (collision) {
  2932. if (restNote.sourceNote.ParentVoiceEntry.ParentVoice instanceof LinkedVoice) {
  2933. const bottomBorder: number = graphicalNotes[0].PositionAndShape.BorderMarginBottom + graphicalNotes[0].PositionAndShape.RelativePosition.y;
  2934. restNote.PositionAndShape.RelativePosition = new PointF2D(0.0, bottomBorder - restNote.PositionAndShape.BorderMarginTop + 0.5);
  2935. } else {
  2936. const last: GraphicalNote = graphicalNotes[graphicalNotes.length - 1];
  2937. const topBorder: number = last.PositionAndShape.BorderMarginTop + last.PositionAndShape.RelativePosition.y;
  2938. if (graphicalNotes[0].sourceNote.ParentVoiceEntry.ParentVoice instanceof LinkedVoice) {
  2939. restNote.PositionAndShape.RelativePosition = new PointF2D(0.0, topBorder - restNote.PositionAndShape.BorderMarginBottom - 0.5);
  2940. } else {
  2941. const bottomBorder: number = graphicalNotes[0].PositionAndShape.BorderMarginBottom + graphicalNotes[0].PositionAndShape.RelativePosition.y;
  2942. if (bottomBorder < 2.0) {
  2943. restNote.PositionAndShape.RelativePosition = new PointF2D(0.0, bottomBorder - restNote.PositionAndShape.BorderMarginTop + 0.5);
  2944. } else {
  2945. restNote.PositionAndShape.RelativePosition = new PointF2D(0.0, topBorder - restNote.PositionAndShape.BorderMarginBottom - 0.0);
  2946. }
  2947. }
  2948. }
  2949. }
  2950. graphicalStaffEntry.PositionAndShape.calculateBoundingBox();
  2951. }
  2952. private calculateTieCurves(): void {
  2953. for (const musicSystem of this.musicSystems) {
  2954. for (const staffLine of musicSystem.StaffLines) {
  2955. for (const measure of staffLine.Measures) {
  2956. for (const staffEntry of measure.staffEntries) {
  2957. for (const graphicalTie of staffEntry.GraphicalTies) {
  2958. if (graphicalTie.StartNote !== undefined && graphicalTie.StartNote.parentVoiceEntry.parentStaffEntry === staffEntry) {
  2959. const tieIsAtSystemBreak: boolean = (
  2960. graphicalTie.StartNote.parentVoiceEntry.parentStaffEntry.parentMeasure.ParentStaffLine !==
  2961. graphicalTie.EndNote.parentVoiceEntry.parentStaffEntry.parentMeasure.ParentStaffLine
  2962. );
  2963. this.layoutGraphicalTie(graphicalTie, tieIsAtSystemBreak, measure.ParentStaff.isTab);
  2964. }
  2965. }
  2966. }
  2967. }
  2968. }
  2969. }
  2970. }
  2971. private calculateLyricsPosition(): void {
  2972. const lyricStaffEntriesDict: Dictionary<StaffLine, GraphicalStaffEntry[]> = new Dictionary<StaffLine, GraphicalStaffEntry[]>();
  2973. // sort the lyriceVerseNumbers for every Instrument that has Lyrics
  2974. for (let idx: number = 0, len: number = this.graphicalMusicSheet.ParentMusicSheet.Instruments.length; idx < len; ++idx) {
  2975. const instrument: Instrument = this.graphicalMusicSheet.ParentMusicSheet.Instruments[idx];
  2976. if (instrument.HasLyrics && instrument.LyricVersesNumbers.length > 0) {
  2977. instrument.LyricVersesNumbers.sort();
  2978. }
  2979. }
  2980. // first calc lyrics text positions
  2981. for (let idx2: number = 0, len2: number = this.musicSystems.length; idx2 < len2; ++idx2) {
  2982. const musicSystem: MusicSystem = this.musicSystems[idx2];
  2983. for (let idx3: number = 0, len3: number = musicSystem.StaffLines.length; idx3 < len3; ++idx3) {
  2984. const staffLine: StaffLine = musicSystem.StaffLines[idx3];
  2985. const lyricsStaffEntries: GraphicalStaffEntry[] =
  2986. this.calculateSingleStaffLineLyricsPosition(staffLine, staffLine.ParentStaff.ParentInstrument.LyricVersesNumbers);
  2987. lyricStaffEntriesDict.setValue(staffLine, lyricsStaffEntries);
  2988. this.calculateLyricsExtendsAndDashes(lyricStaffEntriesDict.getValue(staffLine));
  2989. }
  2990. }
  2991. // then fill in the lyric word dashes and lyrics extends/underscores
  2992. for (let idx2: number = 0, len2: number = this.musicSystems.length; idx2 < len2; ++idx2) {
  2993. const musicSystem: MusicSystem = this.musicSystems[idx2];
  2994. for (let idx3: number = 0, len3: number = musicSystem.StaffLines.length; idx3 < len3; ++idx3) {
  2995. const staffLine: StaffLine = musicSystem.StaffLines[idx3];
  2996. this.calculateLyricsExtendsAndDashes(lyricStaffEntriesDict.getValue(staffLine));
  2997. }
  2998. }
  2999. }
  3000. /**
  3001. * This method calculates the dashes within the syllables of a LyricWord
  3002. * @param lyricEntry
  3003. */
  3004. private calculateSingleLyricWord(lyricEntry: GraphicalLyricEntry): void {
  3005. // const skyBottomLineCalculator: SkyBottomLineCalculator = new SkyBottomLineCalculator (this.rules);
  3006. const graphicalLyricWord: GraphicalLyricWord = lyricEntry.ParentLyricWord;
  3007. const index: number = graphicalLyricWord.GraphicalLyricsEntries.indexOf(lyricEntry);
  3008. let nextLyricEntry: GraphicalLyricEntry = undefined;
  3009. if (index >= 0) {
  3010. nextLyricEntry = graphicalLyricWord.GraphicalLyricsEntries[index + 1];
  3011. }
  3012. if (!nextLyricEntry) {
  3013. return;
  3014. }
  3015. const startStaffLine: StaffLine = <StaffLine>lyricEntry.StaffEntryParent.parentMeasure.ParentStaffLine;
  3016. const nextStaffLine: StaffLine = <StaffLine>nextLyricEntry.StaffEntryParent.parentMeasure.ParentStaffLine;
  3017. const startStaffEntry: GraphicalStaffEntry = lyricEntry.StaffEntryParent;
  3018. const endStaffentry: GraphicalStaffEntry = nextLyricEntry.StaffEntryParent;
  3019. // if on the same StaffLine
  3020. if (lyricEntry.StaffEntryParent.parentMeasure.ParentStaffLine === nextLyricEntry.StaffEntryParent.parentMeasure.ParentStaffLine) {
  3021. // start- and End margins from the text Labels
  3022. const startX: number = startStaffEntry.parentMeasure.PositionAndShape.RelativePosition.x +
  3023. startStaffEntry.PositionAndShape.RelativePosition.x +
  3024. lyricEntry.GraphicalLabel.PositionAndShape.RelativePosition.x +
  3025. lyricEntry.GraphicalLabel.PositionAndShape.BorderMarginRight -
  3026. lyricEntry.GraphicalLabel.CenteringXShift; // TODO not sure why this is necessary, see Christbaum measure 9+11, Land der Berge 11-12
  3027. const endX: number = endStaffentry.parentMeasure.PositionAndShape.RelativePosition.x +
  3028. endStaffentry.PositionAndShape.RelativePosition.x +
  3029. lyricEntry.GraphicalLabel.PositionAndShape.RelativePosition.x +
  3030. nextLyricEntry.GraphicalLabel.PositionAndShape.BorderMarginLeft;
  3031. const y: number = lyricEntry.GraphicalLabel.PositionAndShape.RelativePosition.y;
  3032. let numberOfDashes: number = 1;
  3033. if ((endX - startX) > this.rules.MinimumDistanceBetweenDashes * 3) {
  3034. // *3: need distance between word to first dash, dash to dash, dash to next word
  3035. numberOfDashes = Math.floor((endX - startX) / this.rules.MinimumDistanceBetweenDashes) - 1;
  3036. }
  3037. // check distance and create the adequate number of Dashes
  3038. if (numberOfDashes === 1) {
  3039. // distance between the two GraphicalLyricEntries is big for only one Dash, position in the middle
  3040. this.calculateSingleDashForLyricWord(startStaffLine, startX, endX, y);
  3041. } else {
  3042. // distance is big enough for more Dashes
  3043. // calculate the adequate number of Dashes from the distance between the two LyricEntries
  3044. // distance between the Dashes should be equal
  3045. this.calculateDashes(startStaffLine, startX, endX, y);
  3046. }
  3047. } else {
  3048. // start and end on different StaffLines
  3049. // start margin from the text Label until the End of StaffLine
  3050. const startX: number = startStaffEntry.parentMeasure.PositionAndShape.RelativePosition.x +
  3051. startStaffEntry.PositionAndShape.RelativePosition.x +
  3052. lyricEntry.GraphicalLabel.PositionAndShape.BorderMarginRight;
  3053. const lastGraphicalMeasure: GraphicalMeasure = startStaffLine.Measures[startStaffLine.Measures.length - 1];
  3054. const endX: number = lastGraphicalMeasure.PositionAndShape.RelativePosition.x + lastGraphicalMeasure.PositionAndShape.Size.width;
  3055. let y: number = lyricEntry.GraphicalLabel.PositionAndShape.RelativePosition.y;
  3056. // calculate Dashes for the first StaffLine
  3057. this.calculateDashes(startStaffLine, startX, endX, y);
  3058. // calculate Dashes for the second StaffLine (only if endStaffEntry isn't the first StaffEntry of the StaffLine)
  3059. if (nextStaffLine && // check for undefined objects e.g. when drawingRange given
  3060. nextStaffLine.Measures[0] &&
  3061. endStaffentry.parentMeasure.ParentStaffLine &&
  3062. !(endStaffentry === endStaffentry.parentMeasure.staffEntries[0] &&
  3063. endStaffentry.parentMeasure === endStaffentry.parentMeasure.ParentStaffLine.Measures[0])) {
  3064. const secondStartX: number = nextStaffLine.Measures[0].staffEntries[0].PositionAndShape.RelativePosition.x;
  3065. const secondEndX: number = endStaffentry.parentMeasure.PositionAndShape.RelativePosition.x +
  3066. endStaffentry.PositionAndShape.RelativePosition.x +
  3067. nextLyricEntry.GraphicalLabel.PositionAndShape.BorderMarginLeft;
  3068. y = nextLyricEntry.GraphicalLabel.PositionAndShape.RelativePosition.y;
  3069. this.calculateDashes(nextStaffLine, secondStartX, secondEndX, y);
  3070. }
  3071. }
  3072. }
  3073. /**
  3074. * This method calculates Dashes for a LyricWord.
  3075. * @param staffLine
  3076. * @param startX
  3077. * @param endX
  3078. * @param y
  3079. */
  3080. private calculateDashes(staffLine: StaffLine, startX: number, endX: number, y: number): void {
  3081. let distance: number = endX - startX;
  3082. if (distance < this.rules.MinimumDistanceBetweenDashes * 3) {
  3083. this.calculateSingleDashForLyricWord(staffLine, startX, endX, y);
  3084. } else {
  3085. // enough distance for more Dashes
  3086. const numberOfDashes: number = Math.floor(distance / this.rules.MinimumDistanceBetweenDashes) - 1;
  3087. const distanceBetweenDashes: number = distance / (numberOfDashes + 1);
  3088. let counter: number = 0;
  3089. startX += distanceBetweenDashes;
  3090. endX -= distanceBetweenDashes;
  3091. while (counter <= Math.floor(numberOfDashes / 2.0) && endX > startX) {
  3092. distance = this.calculateRightAndLeftDashesForLyricWord(staffLine, startX, endX, y);
  3093. startX += distanceBetweenDashes;
  3094. endX -= distanceBetweenDashes;
  3095. counter++;
  3096. }
  3097. // if the remaining distance isn't big enough for two Dashes,
  3098. // but long enough for a middle dash inbetween,
  3099. // then put the last Dash in the middle of the remaining distance
  3100. if (distance > distanceBetweenDashes * 2) {
  3101. this.calculateSingleDashForLyricWord(staffLine, startX, endX, y);
  3102. }
  3103. }
  3104. }
  3105. /**
  3106. * This method calculates a single Dash for a LyricWord, positioned in the middle of the given distance.
  3107. * @param {StaffLine} staffLine
  3108. * @param {number} startX
  3109. * @param {number} endX
  3110. * @param {number} y
  3111. */
  3112. private calculateSingleDashForLyricWord(staffLine: StaffLine, startX: number, endX: number, y: number): void {
  3113. const label: Label = new Label("-");
  3114. label.colorDefault = this.rules.DefaultColorLyrics; // if undefined, no change. saves an if check
  3115. let textHeight: number = this.rules.LyricsHeight;
  3116. if (endX - startX < 0.8) {
  3117. textHeight *= 0.8;
  3118. y -= 0.1 * textHeight; // dash moves downwards when textHeight is reduced. counteract that.
  3119. //xShift = -0.1;
  3120. // x-position is situational, sometimes it's slightly right-leaning and tends to overlap with the right LyricsEntry
  3121. // (see Cornelius - Christbaum, measure 9 and 11 ("li-che", "li-ger"), due to centering x-shift = GraphicalLabel.CenteringXShift)
  3122. // sometimes the x-position is perfect and the interval is extremely narrow
  3123. // (see Mozart/Holzer Land der Berge measure 11-12)
  3124. // or even slightly too far left (Beethoven Geliebte measure 4, due to centering x-shift = GraphicalLabel.CenteringXShift)
  3125. }
  3126. const dash: GraphicalLabel = new GraphicalLabel(
  3127. label, textHeight, TextAlignmentEnum.CenterBottom, this.rules);
  3128. dash.setLabelPositionAndShapeBorders();
  3129. staffLine.LyricsDashes.push(dash);
  3130. if (this.staffLinesWithLyricWords.indexOf(staffLine) === -1) {
  3131. this.staffLinesWithLyricWords.push(staffLine);
  3132. }
  3133. dash.PositionAndShape.Parent = staffLine.PositionAndShape;
  3134. const relative: PointF2D = new PointF2D(startX + (endX - startX) / 2, y);
  3135. dash.PositionAndShape.RelativePosition = relative;
  3136. }
  3137. /**
  3138. * Layouts the underscore line when a lyric entry is marked as extend
  3139. * @param {GraphicalLyricEntry} lyricEntry
  3140. */
  3141. private calculateLyricExtend(lyricEntry: GraphicalLyricEntry): void {
  3142. let startY: number = lyricEntry.GraphicalLabel.PositionAndShape.RelativePosition.y;
  3143. const startStaffEntry: GraphicalStaffEntry = lyricEntry.StaffEntryParent;
  3144. const startStaffLine: StaffLine = startStaffEntry.parentMeasure.ParentStaffLine;
  3145. // find endstaffEntry and staffLine
  3146. let endStaffEntry: GraphicalStaffEntry = undefined;
  3147. let endStaffLine: StaffLine = undefined;
  3148. const staffIndex: number = startStaffEntry.parentMeasure.ParentStaff.idInMusicSheet;
  3149. for (let index: number = startStaffEntry.parentVerticalContainer.Index + 1;
  3150. index < this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers.length;
  3151. ++index) {
  3152. const gse: GraphicalStaffEntry = this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[index].StaffEntries[staffIndex];
  3153. if (!gse) {
  3154. continue;
  3155. }
  3156. if (gse.hasOnlyRests()) {
  3157. break;
  3158. }
  3159. if (gse.LyricsEntries.length > 0) {
  3160. break;
  3161. }
  3162. endStaffEntry = gse;
  3163. endStaffLine = endStaffEntry.parentMeasure.ParentStaffLine;
  3164. if (!endStaffLine) {
  3165. endStaffLine = startStaffEntry.parentMeasure.ParentStaffLine;
  3166. }
  3167. }
  3168. if (!endStaffEntry || !endStaffLine) {
  3169. return;
  3170. }
  3171. // if on the same StaffLine
  3172. if (startStaffLine === endStaffLine && endStaffEntry.parentMeasure.ParentStaffLine) {
  3173. // start- and End margins from the text Labels
  3174. const startX: number = startStaffEntry.parentMeasure.PositionAndShape.RelativePosition.x +
  3175. startStaffEntry.PositionAndShape.RelativePosition.x +
  3176. lyricEntry.GraphicalLabel.PositionAndShape.BorderMarginRight;
  3177. // + startStaffLine.PositionAndShape.AbsolutePosition.x; // doesn't work, done in drawer
  3178. const endX: number = endStaffEntry.parentMeasure.PositionAndShape.RelativePosition.x +
  3179. endStaffEntry.PositionAndShape.RelativePosition.x +
  3180. endStaffEntry.PositionAndShape.BorderMarginRight;
  3181. // + endStaffLine.PositionAndShape.AbsolutePosition.x; // doesn't work, done in drawer
  3182. // TODO maybe add half-width of following note.
  3183. // though we don't have the vexflow note's bbox yet and extend layouting is unconstrained,
  3184. // we have more room for spacing without it.
  3185. // needed in order to line up with the Label's text bottom line (is the y position of the underscore)
  3186. startY -= lyricEntry.GraphicalLabel.PositionAndShape.Size.height / 4;
  3187. // create a Line (as underscore after the LyricLabel's End)
  3188. this.calculateSingleLyricWordWithUnderscore(startStaffLine, startX, endX, startY);
  3189. } else { // start and end on different StaffLines
  3190. // start margin from the text Label until the End of StaffLine
  3191. const lastMeasureBb: BoundingBox = startStaffLine.Measures[startStaffLine.Measures.length - 1].PositionAndShape;
  3192. const startX: number = startStaffEntry.parentMeasure.PositionAndShape.RelativePosition.x +
  3193. startStaffEntry.PositionAndShape.RelativePosition.x +
  3194. lyricEntry.GraphicalLabel.PositionAndShape.BorderMarginRight;
  3195. const endX: number = lastMeasureBb.RelativePosition.x +
  3196. lastMeasureBb.Size.width;
  3197. // needed in order to line up with the Label's text bottom line
  3198. startY -= lyricEntry.GraphicalLabel.PositionAndShape.Size.height / 4;
  3199. // first Underscore until the StaffLine's End
  3200. this.calculateSingleLyricWordWithUnderscore(startStaffLine, startX, endX, startY);
  3201. if (!endStaffEntry) {
  3202. return;
  3203. }
  3204. // second Underscore in the endStaffLine until endStaffEntry (if endStaffEntry isn't the first StaffEntry of the StaffLine))
  3205. if (endStaffEntry.parentMeasure.ParentStaffLine && endStaffEntry.parentMeasure.staffEntries &&
  3206. !(endStaffEntry === endStaffEntry.parentMeasure.staffEntries[0] &&
  3207. endStaffEntry.parentMeasure === endStaffEntry.parentMeasure.ParentStaffLine.Measures[0])) {
  3208. const secondStartX: number = endStaffLine.Measures[0].staffEntries[0].PositionAndShape.RelativePosition.x;
  3209. const secondEndX: number = endStaffEntry.parentMeasure.PositionAndShape.RelativePosition.x +
  3210. endStaffEntry.PositionAndShape.RelativePosition.x +
  3211. endStaffEntry.PositionAndShape.BorderMarginRight;
  3212. this.calculateSingleLyricWordWithUnderscore(endStaffLine, secondStartX, secondEndX, startY);
  3213. }
  3214. }
  3215. }
  3216. /**
  3217. * This method calculates a single underscoreLine.
  3218. * @param staffLine
  3219. * @param startX
  3220. * @param end
  3221. * @param y
  3222. */
  3223. private calculateSingleLyricWordWithUnderscore(staffLine: StaffLine, startX: number, endX: number, y: number): void {
  3224. const lineStart: PointF2D = new PointF2D(startX, y);
  3225. const lineEnd: PointF2D = new PointF2D(endX, y);
  3226. const graphicalLine: GraphicalLine = new GraphicalLine(lineStart, lineEnd, this.rules.LyricUnderscoreLineWidth);
  3227. graphicalLine.colorHex = this.rules.DefaultColorLyrics; // if undefined, no change. saves an if check
  3228. staffLine.LyricLines.push(graphicalLine);
  3229. if (this.staffLinesWithLyricWords.indexOf(staffLine) === -1) {
  3230. this.staffLinesWithLyricWords.push(staffLine);
  3231. }
  3232. }
  3233. /**
  3234. * This method calculates two Dashes for a LyricWord, positioned at the the two ends of the given distance.
  3235. * @param {StaffLine} staffLine
  3236. * @param {number} startX
  3237. * @param {number} endX
  3238. * @param {number} y
  3239. * @returns {number}
  3240. */
  3241. private calculateRightAndLeftDashesForLyricWord(staffLine: StaffLine, startX: number, endX: number, y: number): number {
  3242. const leftLabel: Label = new Label("-");
  3243. leftLabel.colorDefault = this.rules.DefaultColorLyrics; // if undefined, no change. saves an if check
  3244. const leftDash: GraphicalLabel = new GraphicalLabel(
  3245. leftLabel, this.rules.LyricsHeight, TextAlignmentEnum.CenterBottom, this.rules);
  3246. leftDash.setLabelPositionAndShapeBorders();
  3247. staffLine.LyricsDashes.push(leftDash);
  3248. if (this.staffLinesWithLyricWords.indexOf(staffLine) === -1) {
  3249. this.staffLinesWithLyricWords.push(staffLine);
  3250. }
  3251. leftDash.PositionAndShape.Parent = staffLine.PositionAndShape;
  3252. const leftDashRelative: PointF2D = new PointF2D(startX, y);
  3253. leftDash.PositionAndShape.RelativePosition = leftDashRelative;
  3254. const rightLabel: Label = new Label("-");
  3255. const rightDash: GraphicalLabel = new GraphicalLabel(
  3256. rightLabel, this.rules.LyricsHeight, TextAlignmentEnum.CenterBottom, this.rules);
  3257. rightDash.setLabelPositionAndShapeBorders();
  3258. staffLine.LyricsDashes.push(rightDash);
  3259. rightDash.PositionAndShape.Parent = staffLine.PositionAndShape;
  3260. const rightDashRelative: PointF2D = new PointF2D(endX, y);
  3261. rightDash.PositionAndShape.RelativePosition = rightDashRelative;
  3262. return (rightDash.PositionAndShape.RelativePosition.x - leftDash.PositionAndShape.RelativePosition.x);
  3263. }
  3264. //So we can track shared notes bounding boxes to avoid collision + skyline issues
  3265. protected dynamicExpressionMap: Map<number, BoundingBox> = new Map<number, BoundingBox>();
  3266. private calculateDynamicExpressions(): void {
  3267. const maxIndex: number = Math.min(this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length - 1, this.rules.MaxMeasureToDrawIndex);
  3268. const minIndex: number = Math.min(this.rules.MinMeasureToDrawIndex, this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length);
  3269. for (let i: number = minIndex; i <= maxIndex; i++) {
  3270. const sourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[i];
  3271. //Reset, beginning of new measure
  3272. this.dynamicExpressionMap.clear();
  3273. for (let j: number = 0; j < sourceMeasure.StaffLinkedExpressions.length; j++) {
  3274. if (!this.graphicalMusicSheet.MeasureList[i] || !this.graphicalMusicSheet.MeasureList[i][j]) {
  3275. continue;
  3276. }
  3277. if (this.graphicalMusicSheet.MeasureList[i][j].ParentStaff.ParentInstrument.Visible) {
  3278. for (let k: number = 0; k < sourceMeasure.StaffLinkedExpressions[j].length; k++) {
  3279. if (sourceMeasure.StaffLinkedExpressions[j][k].InstantaneousDynamic !== undefined ||
  3280. (sourceMeasure.StaffLinkedExpressions[j][k].StartingContinuousDynamic !== undefined &&
  3281. sourceMeasure.StaffLinkedExpressions[j][k].StartingContinuousDynamic.StartMultiExpression ===
  3282. sourceMeasure.StaffLinkedExpressions[j][k] && sourceMeasure.StaffLinkedExpressions[j][k].UnknownList.length === 0)
  3283. ) {
  3284. this.calculateDynamicExpressionsForMultiExpression(sourceMeasure.StaffLinkedExpressions[j][k], i, j);
  3285. }
  3286. }
  3287. }
  3288. }
  3289. }
  3290. this.dynamicExpressionMap.clear();
  3291. }
  3292. private calculateOctaveShifts(): void {
  3293. for (let i: number = 0; i < this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length; i++) {
  3294. const sourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[i];
  3295. for (let j: number = 0; j < sourceMeasure.StaffLinkedExpressions.length; j++) {
  3296. if (!this.graphicalMusicSheet.MeasureList[i] || !this.graphicalMusicSheet.MeasureList[i][j]) {
  3297. continue;
  3298. }
  3299. if (this.graphicalMusicSheet.MeasureList[i][j].ParentStaff.ParentInstrument.Visible) {
  3300. for (let k: number = 0; k < sourceMeasure.StaffLinkedExpressions[j].length; k++) {
  3301. if ((sourceMeasure.StaffLinkedExpressions[j][k].OctaveShiftStart)) {
  3302. this.calculateSingleOctaveShift(sourceMeasure, sourceMeasure.StaffLinkedExpressions[j][k], i, j);
  3303. }
  3304. }
  3305. }
  3306. }
  3307. }
  3308. }
  3309. private calculatePedals(): void {
  3310. for (let i: number = 0; i < this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length; i++) {
  3311. const sourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[i];
  3312. for (let j: number = 0; j < sourceMeasure.StaffLinkedExpressions.length; j++) {
  3313. if (!this.graphicalMusicSheet.MeasureList[i] || !this.graphicalMusicSheet.MeasureList[i][j]) {
  3314. continue;
  3315. }
  3316. if (this.graphicalMusicSheet.MeasureList[i][j].ParentStaff.ParentInstrument.Visible) {
  3317. for (let k: number = 0; k < sourceMeasure.StaffLinkedExpressions[j].length; k++) {
  3318. if ((sourceMeasure.StaffLinkedExpressions[j][k].PedalStart)) {
  3319. this.calculateSinglePedal(sourceMeasure, sourceMeasure.StaffLinkedExpressions[j][k], i, j);
  3320. }
  3321. }
  3322. }
  3323. }
  3324. }
  3325. }
  3326. private calculateWavyLines(): void {
  3327. for (let i: number = 0; i < this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length; i++) {
  3328. const sourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[i];
  3329. for (let j: number = 0; j < sourceMeasure.StaffLinkedExpressions.length; j++) {
  3330. if (!this.graphicalMusicSheet.MeasureList[i] || !this.graphicalMusicSheet.MeasureList[i][j]) {
  3331. continue;
  3332. }
  3333. if (this.graphicalMusicSheet.MeasureList[i][j].ParentStaff.ParentInstrument.Visible) {
  3334. for (let k: number = 0; k < sourceMeasure.StaffLinkedExpressions[j].length; k++) {
  3335. if ((sourceMeasure.StaffLinkedExpressions[j][k].WavyLineStart)) {
  3336. this.calculateSingleWavyLine(sourceMeasure, sourceMeasure.StaffLinkedExpressions[j][k], i, j);
  3337. }
  3338. }
  3339. }
  3340. }
  3341. }
  3342. }
  3343. private getFirstLeftNotNullStaffEntryFromContainer(horizontalIndex: number, verticalIndex: number, multiStaffInstrument: boolean): GraphicalStaffEntry {
  3344. if (this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[horizontalIndex].StaffEntries[verticalIndex]) {
  3345. return this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[horizontalIndex].StaffEntries[verticalIndex];
  3346. }
  3347. for (let i: number = horizontalIndex - 1; i >= 0; i--) {
  3348. if (this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[i].StaffEntries[verticalIndex]) {
  3349. return this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[i].StaffEntries[verticalIndex];
  3350. }
  3351. }
  3352. return undefined;
  3353. }
  3354. private getFirstRightNotNullStaffEntryFromContainer(horizontalIndex: number, verticalIndex: number, multiStaffInstrument: boolean): GraphicalStaffEntry {
  3355. if (this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[horizontalIndex].StaffEntries[verticalIndex]) {
  3356. return this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[horizontalIndex].StaffEntries[verticalIndex];
  3357. }
  3358. for (let i: number = horizontalIndex + 1; i < this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers.length; i++) {
  3359. if (this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[i].StaffEntries[verticalIndex]) {
  3360. return this.graphicalMusicSheet.VerticalGraphicalStaffEntryContainers[i].StaffEntries[verticalIndex];
  3361. }
  3362. }
  3363. return undefined;
  3364. }
  3365. private calculateWordRepetitionInstructions(): void {
  3366. for (let i: number = 0; i < this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length; i++) {
  3367. const sourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[i];
  3368. for (let idx: number = 0, len: number = sourceMeasure.FirstRepetitionInstructions.length; idx < len; ++idx) {
  3369. const instruction: RepetitionInstruction = sourceMeasure.FirstRepetitionInstructions[idx];
  3370. this.calculateWordRepetitionInstruction(instruction, i);
  3371. }
  3372. for (let idx: number = 0, len: number = sourceMeasure.LastRepetitionInstructions.length; idx < len; ++idx) {
  3373. const instruction: RepetitionInstruction = sourceMeasure.LastRepetitionInstructions[idx];
  3374. this.calculateWordRepetitionInstruction(instruction, i);
  3375. }
  3376. }
  3377. }
  3378. private calculateRepetitionEndings(): void {
  3379. const musicsheet: MusicSheet = this.graphicalMusicSheet.ParentMusicSheet;
  3380. for (let idx: number = 0, len: number = musicsheet.Repetitions.length; idx < len; ++idx) {
  3381. const repetition: Repetition = musicsheet.Repetitions[idx];
  3382. this.calcGraphicalRepetitionEndingsRecursively(repetition);
  3383. }
  3384. }
  3385. private calculateTempoExpressions(): void {
  3386. const maxIndex: number = Math.min(this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length - 1, this.rules.MaxMeasureToDrawIndex);
  3387. const minIndex: number = this.rules.MinMeasureToDrawIndex;
  3388. for (let i: number = minIndex; i <= maxIndex; i++) {
  3389. const sourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[i];
  3390. for (let j: number = 0; j < sourceMeasure.TempoExpressions.length; j++) {
  3391. this.calculateTempoExpressionsForMultiTempoExpression(sourceMeasure, sourceMeasure.TempoExpressions[j], i);
  3392. }
  3393. }
  3394. }
  3395. private calculateRehearsalMarks(): void {
  3396. if (!this.rules.RenderRehearsalMarks) {
  3397. return;
  3398. }
  3399. for (const measure of this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures) {
  3400. this.calculateRehearsalMark(measure);
  3401. }
  3402. }
  3403. protected calculateRehearsalMark(measure: SourceMeasure): void {
  3404. throw new Error(this.abstractNotImplementedErrorMessage);
  3405. }
  3406. private calculateMoodAndUnknownExpressions(): void {
  3407. for (let i: number = 0; i < this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures.length; i++) {
  3408. const sourceMeasure: SourceMeasure = this.graphicalMusicSheet.ParentMusicSheet.SourceMeasures[i];
  3409. for (let j: number = 0; j < sourceMeasure.StaffLinkedExpressions.length; j++) {
  3410. if (!this.graphicalMusicSheet.MeasureList[i] || !this.graphicalMusicSheet.MeasureList[i][j]) {
  3411. continue;
  3412. }
  3413. if (this.graphicalMusicSheet.MeasureList[i][j].ParentStaff.ParentInstrument.Visible) {
  3414. for (let k: number = 0; k < sourceMeasure.StaffLinkedExpressions[j].length; k++) {
  3415. if ((sourceMeasure.StaffLinkedExpressions[j][k].MoodList.length > 0) ||
  3416. (sourceMeasure.StaffLinkedExpressions[j][k].UnknownList.length > 0)) {
  3417. this.calculateMoodAndUnknownExpression(sourceMeasure.StaffLinkedExpressions[j][k], i, j);
  3418. }
  3419. }
  3420. }
  3421. }
  3422. }
  3423. }
  3424. /**
  3425. * Calculates the desired stem direction depending on the number (or type) of voices.
  3426. * If more than one voice is there, the main voice (typically the first or upper voice) will get stem up direction.
  3427. * The others get stem down direction.
  3428. * @param voiceEntry the voiceEntry for which the stem direction has to be calculated
  3429. */
  3430. private calculateStemDirectionFromVoices(voiceEntry: VoiceEntry): void {
  3431. // Stem direction calculation:
  3432. const hasLink: boolean = voiceEntry.ParentSourceStaffEntry.Link !== undefined;
  3433. if (hasLink) {
  3434. // in case of StaffEntryLink don't check mainVoice / linkedVoice
  3435. if (voiceEntry === voiceEntry.ParentSourceStaffEntry.VoiceEntries[0]) {
  3436. // set stem up:
  3437. voiceEntry.WantedStemDirection = StemDirectionType.Up;
  3438. return;
  3439. } else {
  3440. // set stem down:
  3441. voiceEntry.WantedStemDirection = StemDirectionType.Down;
  3442. return;
  3443. }
  3444. } else {
  3445. if (voiceEntry.ParentVoice instanceof LinkedVoice) {
  3446. // Linked voice: set stem down:
  3447. voiceEntry.WantedStemDirection = StemDirectionType.Down;
  3448. } else {
  3449. // if this voiceEntry belongs to the mainVoice:
  3450. // check first that there are also more voices present:
  3451. if (voiceEntry.ParentSourceStaffEntry.VoiceEntries.length > 1) {
  3452. // as this voiceEntry belongs to the mainVoice: stem Up
  3453. voiceEntry.WantedStemDirection = StemDirectionType.Up;
  3454. }
  3455. }
  3456. }
  3457. // setBeamNotesWantedStemDirections() will be called at end of measure (createGraphicalMeasure)
  3458. }
  3459. /** Sets a voiceEntry's stem direction to one already set in other notes in its beam, if it has one. */
  3460. private setBeamNotesWantedStemDirections(voiceEntry: VoiceEntry): void {
  3461. if (!(voiceEntry.Notes.length > 0)) {
  3462. return;
  3463. }
  3464. // don't just set direction if undefined. if there's a note in the beam with a different stem direction, Vexflow draws it with an unending stem.
  3465. // if (voiceEntry.WantedStemDirection === StemDirectionType.Undefined) {
  3466. const beam: Beam = voiceEntry.Notes[0].NoteBeam;
  3467. if (beam) {
  3468. // if there is a beam, find any already set stemDirection in the beam:
  3469. for (const note of beam.Notes) {
  3470. // if (note.ParentVoiceEntry === voiceEntry) {
  3471. // continue; // this could cause a misreading, also potentially in cross-staf beams, in any case it's unnecessary.
  3472. //} else if
  3473. if (note.ParentVoiceEntry.WantedStemDirection !== StemDirectionType.Undefined) {
  3474. if (note.ParentVoiceEntry.ParentSourceStaffEntry.ParentStaff.Id === voiceEntry.ParentSourceStaffEntry.ParentStaff.Id) {
  3475. // set the stem direction
  3476. voiceEntry.WantedStemDirection = note.ParentVoiceEntry.WantedStemDirection;
  3477. break;
  3478. }
  3479. }
  3480. }
  3481. }
  3482. }
  3483. }