MusicSheetCalculator.ts 195 KB

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