MusicSheetCalculator.ts 216 KB

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