MusicSheetCalculator.ts 170 KB

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