VexFlowMusicSheetCalculator.ts 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. import { MusicSheetCalculator } from "../MusicSheetCalculator";
  2. import { VexFlowGraphicalSymbolFactory } from "./VexFlowGraphicalSymbolFactory";
  3. import { GraphicalMeasure } from "../GraphicalMeasure";
  4. import { StaffLine } from "../StaffLine";
  5. import { VoiceEntry } from "../../VoiceData/VoiceEntry";
  6. import { GraphicalNote } from "../GraphicalNote";
  7. import { GraphicalStaffEntry } from "../GraphicalStaffEntry";
  8. import { GraphicalTie } from "../GraphicalTie";
  9. import { Tie } from "../../VoiceData/Tie";
  10. import { SourceMeasure } from "../../VoiceData/SourceMeasure";
  11. import { MultiExpression } from "../../VoiceData/Expressions/MultiExpression";
  12. import { RepetitionInstruction } from "../../VoiceData/Instructions/RepetitionInstruction";
  13. import { Beam } from "../../VoiceData/Beam";
  14. import { ClefInstruction } from "../../VoiceData/Instructions/ClefInstruction";
  15. import { OctaveEnum, OctaveShift } from "../../VoiceData/Expressions/ContinuousExpressions/OctaveShift";
  16. import { Fraction } from "../../../Common/DataObjects/Fraction";
  17. import { LyricWord } from "../../VoiceData/Lyrics/LyricsWord";
  18. import { OrnamentContainer } from "../../VoiceData/OrnamentContainer";
  19. import { ArticulationEnum } from "../../VoiceData/VoiceEntry";
  20. import { Tuplet } from "../../VoiceData/Tuplet";
  21. import { VexFlowMeasure } from "./VexFlowMeasure";
  22. import { VexFlowTextMeasurer } from "./VexFlowTextMeasurer";
  23. import Vex from "vexflow";
  24. import log from "loglevel";
  25. import { unitInPixels } from "./VexFlowMusicSheetDrawer";
  26. import { VexFlowGraphicalNote } from "./VexFlowGraphicalNote";
  27. import { TechnicalInstruction } from "../../VoiceData/Instructions/TechnicalInstruction";
  28. import { GraphicalLyricEntry } from "../GraphicalLyricEntry";
  29. import { GraphicalLabel } from "../GraphicalLabel";
  30. import { LyricsEntry } from "../../VoiceData/Lyrics/LyricsEntry";
  31. import { GraphicalLyricWord } from "../GraphicalLyricWord";
  32. import { VexFlowStaffEntry } from "./VexFlowStaffEntry";
  33. import { VexFlowOctaveShift } from "./VexFlowOctaveShift";
  34. import { VexFlowInstantaneousDynamicExpression } from "./VexFlowInstantaneousDynamicExpression";
  35. import { Slur } from "../../VoiceData/Expressions/ContinuousExpressions/Slur";
  36. /* VexFlow Version - for later use
  37. // import { VexFlowSlur } from "./VexFlowSlur";
  38. // import { VexFlowStaffLine } from "./VexFlowStaffLine";
  39. // import { VexFlowVoiceEntry } from "./VexFlowVoiceEntry";
  40. */
  41. import { PointF2D } from "../../../Common/DataObjects/PointF2D";
  42. import { TextAlignmentEnum, TextAlignment } from "../../../Common/Enums/TextAlignment";
  43. import { GraphicalSlur } from "../GraphicalSlur";
  44. import { BoundingBox } from "../BoundingBox";
  45. import { ContinuousDynamicExpression } from "../../VoiceData/Expressions/ContinuousExpressions/ContinuousDynamicExpression";
  46. import { VexFlowContinuousDynamicExpression } from "./VexFlowContinuousDynamicExpression";
  47. import { InstantaneousTempoExpression } from "../../VoiceData/Expressions";
  48. import { AlignRestOption } from "../../../OpenSheetMusicDisplay";
  49. import { VexFlowStaffLine } from "./VexFlowStaffLine";
  50. import { EngravingRules } from "../EngravingRules";
  51. import { VexflowStafflineNoteCalculator } from "./VexflowStafflineNoteCalculator";
  52. export class VexFlowMusicSheetCalculator extends MusicSheetCalculator {
  53. /** space needed for a dash for lyrics spacing, calculated once */
  54. private dashSpace: number;
  55. public beamsNeedUpdate: boolean = false;
  56. constructor(rules: EngravingRules) {
  57. super();
  58. this.rules = rules;
  59. MusicSheetCalculator.symbolFactory = new VexFlowGraphicalSymbolFactory();
  60. MusicSheetCalculator.TextMeasurer = new VexFlowTextMeasurer(this.rules);
  61. MusicSheetCalculator.stafflineNoteCalculator = new VexflowStafflineNoteCalculator(this.rules);
  62. }
  63. protected clearRecreatedObjects(): void {
  64. super.clearRecreatedObjects();
  65. MusicSheetCalculator.stafflineNoteCalculator = new VexflowStafflineNoteCalculator(this.rules);
  66. for (const graphicalMeasures of this.graphicalMusicSheet.MeasureList) {
  67. for (const graphicalMeasure of graphicalMeasures) {
  68. (<VexFlowMeasure>graphicalMeasure).clean();
  69. }
  70. }
  71. }
  72. protected formatMeasures(): void {
  73. // let totalFinalizeBeamsTime: number = 0;
  74. for (const verticalMeasureList of this.graphicalMusicSheet.MeasureList) {
  75. const firstMeasure: VexFlowMeasure = verticalMeasureList[0] as VexFlowMeasure;
  76. // first measure has formatting method as lambda function object, but formats all measures. TODO this could be refactored
  77. firstMeasure.format();
  78. for (const measure of verticalMeasureList) {
  79. for (const staffEntry of measure.staffEntries) {
  80. (<VexFlowStaffEntry>staffEntry).calculateXPosition();
  81. }
  82. // const t0: number = performance.now();
  83. if (this.beamsNeedUpdate) { // finalizeBeams takes a few milliseconds, so we can save some performance here
  84. (measure as VexFlowMeasure).finalizeBeams(); // without this, when zooming a lot (e.g. 250%), beams keep their old, now wrong slope.
  85. // totalFinalizeBeamsTime += performance.now() - t0;
  86. // console.log("Total calls to finalizeBeams in VexFlowMusicSheetCalculator took " + totalFinalizeBeamsTime + " milliseconds.");
  87. }
  88. }
  89. }
  90. this.beamsNeedUpdate = false;
  91. }
  92. //protected clearSystemsAndMeasures(): void {
  93. // for (let measure of measures) {
  94. //
  95. // }
  96. //}
  97. /**
  98. * Calculates the x layout of the staff entries within the staff measures belonging to one source measure.
  99. * All staff entries are x-aligned throughout all vertically aligned staff measures.
  100. * This method is called within calculateXLayout.
  101. * The staff entries are aligned with minimum needed x distances.
  102. * The MinimumStaffEntriesWidth of every measure will be set - needed for system building.
  103. * Prepares the VexFlow formatter for later formatting
  104. * Does not calculate measure width from lyrics (which is called from MusicSheetCalculator)
  105. * @param measures
  106. * @returns the minimum required x width of the source measure (=list of staff measures)
  107. */
  108. protected calculateMeasureXLayout(measures: GraphicalMeasure[]): number {
  109. const visibleMeasures: GraphicalMeasure[] = [];
  110. for (const measure of measures) {
  111. visibleMeasures.push(measure);
  112. }
  113. measures = visibleMeasures;
  114. // Format the voices
  115. const allVoices: Vex.Flow.Voice[] = [];
  116. const formatter: Vex.Flow.Formatter = new Vex.Flow.Formatter();
  117. for (const measure of measures) {
  118. const mvoices: { [voiceID: number]: Vex.Flow.Voice; } = (measure as VexFlowMeasure).vfVoices;
  119. const voices: Vex.Flow.Voice[] = [];
  120. for (const voiceID in mvoices) {
  121. if (mvoices.hasOwnProperty(voiceID)) {
  122. voices.push(mvoices[voiceID]);
  123. allVoices.push(mvoices[voiceID]);
  124. }
  125. }
  126. if (voices.length === 0) {
  127. log.debug("Found a measure with no voices. Continuing anyway.", mvoices);
  128. // no need to log this, measures with no voices/notes are fine. see OSMDOptions.fillEmptyMeasuresWithWholeRest
  129. continue;
  130. }
  131. // all voices that belong to one stave are collectively added to create a common context in VexFlow.
  132. formatter.joinVoices(voices);
  133. }
  134. let minStaffEntriesWidth: number = 200;
  135. if (allVoices.length > 0) {
  136. // FIXME: The following ``+ 5.0'' is temporary: it was added as a workaround for
  137. // FIXME: a more relaxed formatting of voices
  138. minStaffEntriesWidth = formatter.preCalculateMinTotalWidth(allVoices) / unitInPixels + 5.0;
  139. // firstMeasure.formatVoices = (w: number) => {
  140. // formatter.format(allVoices, w);
  141. // };
  142. MusicSheetCalculator.setMeasuresMinStaffEntriesWidth(measures, minStaffEntriesWidth);
  143. const formatVoicesDefault: (w: number) => void = (w) => {
  144. formatter.format(allVoices, w);
  145. };
  146. const formatVoicesAlignRests: (w: number) => void = (w) => {
  147. formatter.format(allVoices, w, {
  148. align_rests: true,
  149. context: undefined
  150. });
  151. };
  152. for (const measure of measures) {
  153. // determine whether to align rests
  154. if (this.rules.AlignRests === AlignRestOption.Never) {
  155. (measure as VexFlowMeasure).formatVoices = formatVoicesDefault;
  156. } else if (this.rules.AlignRests === AlignRestOption.Always) {
  157. (measure as VexFlowMeasure).formatVoices = formatVoicesAlignRests;
  158. } else if (this.rules.AlignRests === AlignRestOption.Auto) {
  159. let alignRests: boolean = false;
  160. for (const staffEntry of measure.staffEntries) {
  161. let collidableVoiceEntries: number = 0;
  162. let numberOfRests: number = 0;
  163. for (const voiceEntry of staffEntry.graphicalVoiceEntries) {
  164. if (!voiceEntry.parentVoiceEntry.IsGrace) {
  165. if (voiceEntry && voiceEntry.notes && voiceEntry.notes[0] && voiceEntry.notes[0].sourceNote) {// TODO null chaining, TS 3.7
  166. if (voiceEntry.notes[0].sourceNote.PrintObject) { // only respect collision when not invisible
  167. collidableVoiceEntries++;
  168. }
  169. }
  170. }
  171. if (voiceEntry && voiceEntry.notes && voiceEntry.notes[0] && voiceEntry.notes[0].sourceNote) {// TODO null chaining, TS 3.7
  172. if (voiceEntry.notes[0].sourceNote.isRest() && voiceEntry.notes[0].sourceNote.PrintObject) {
  173. numberOfRests++; // only align rests if there is actually a rest (which could collide)
  174. }
  175. }
  176. if (collidableVoiceEntries > 1 && numberOfRests >= 1) {
  177. // TODO could add further checks like if any of the already checked voice entries actually collide
  178. alignRests = true;
  179. break;
  180. }
  181. }
  182. if (alignRests) {
  183. break;
  184. }
  185. }
  186. // set measure's format function
  187. if (alignRests) {
  188. (measure as VexFlowMeasure).formatVoices = formatVoicesAlignRests;
  189. } else {
  190. (measure as VexFlowMeasure).formatVoices = formatVoicesDefault;
  191. }
  192. }
  193. // format first measure with minimum width
  194. if (measure === measures[0]) {
  195. const vexflowMeasure: VexFlowMeasure = (measure as VexFlowMeasure);
  196. // prepare format function for voices, will be called later for formatting measure again
  197. //vexflowMeasure.formatVoices = formatVoicesDefault;
  198. // format now for minimum width, calculateMeasureWidthFromLyrics later
  199. vexflowMeasure.formatVoices(minStaffEntriesWidth * unitInPixels);
  200. } else {
  201. //(measure as VexFlowMeasure).formatVoices = undefined;
  202. // TODO why was the formatVoices function disabled for other measures? would now disable the new align rests option.
  203. }
  204. }
  205. }
  206. for (const graphicalMeasure of measures) {
  207. for (const staffEntry of graphicalMeasure.staffEntries) {
  208. // here the measure modifiers are not yet set, therefore the begin instruction width will be empty
  209. (<VexFlowStaffEntry>staffEntry).calculateXPosition();
  210. }
  211. }
  212. // calculateMeasureWidthFromLyrics() will be called from MusicSheetCalculator after this
  213. return minStaffEntriesWidth;
  214. }
  215. public calculateMeasureWidthFromLyrics(measuresVertical: GraphicalMeasure[], oldMinimumStaffEntriesWidth: number): number {
  216. let elongationFactorForMeasureWidth: number = 1;
  217. // information we need for the previous lyricsEntries to space the current one
  218. interface LyricEntryInfo {
  219. extend: boolean;
  220. labelWidth: number;
  221. lyricsXPosition: number;
  222. sourceNoteDuration: Fraction;
  223. text: string;
  224. measureNumber: number;
  225. }
  226. // holds lyrics entries for verses i
  227. interface LyricEntryDict {
  228. [i: number]: LyricEntryInfo;
  229. }
  230. for (const measure of measuresVertical) {
  231. const lastLyricEntryDict: LyricEntryDict = {}; // holds info about last lyrics entries for all verses j
  232. // for all staffEntries i, each containing the lyric entry for all verses at that timestamp in the measure
  233. for (let i: number = 0; i < measure.staffEntries.length; i++) {
  234. const staffEntry: GraphicalStaffEntry = measure.staffEntries[i];
  235. if (staffEntry.LyricsEntries.length === 0) {
  236. continue;
  237. }
  238. // for all verses j
  239. for (let j: number = 0; j < staffEntry.LyricsEntries.length; j++) {
  240. const lyricsEntry: GraphicalLyricEntry = staffEntry.LyricsEntries[j];
  241. // const lyricsEntryText = lyricsEntry.LyricsEntry.Text; // for easier debugging
  242. const lyricAlignment: TextAlignmentEnum = lyricsEntry.GraphicalLabel.Label.textAlignment;
  243. let minLyricsSpacing: number = this.rules.HorizontalBetweenLyricsDistance;
  244. // for quarter note in Vexflow, where spacing is halfed for each smaller note duration.
  245. let lyricOverlapAllowedIntoNextMeasure: number =
  246. this.rules.LyricOverlapAllowedIntoNextMeasure;
  247. // TODO allow more overlap if there are no lyrics in next measure
  248. // spacing for multi-syllable words
  249. if (lyricsEntry.ParentLyricWord) {
  250. if (lyricsEntry.LyricsEntry.SyllableIndex > 0) { // syllables after first
  251. // give a little more spacing for dash between syllables
  252. minLyricsSpacing = this.rules.BetweenSyllableMinimumDistance;
  253. if (TextAlignment.IsCenterAligned(lyricsEntry.GraphicalLabel.Label.textAlignment)) {
  254. minLyricsSpacing += 1.0; // TODO check for previous lyric alignment too. though center is not standard
  255. // without this, there's not enough space for dashes between long syllables on eigth notes
  256. }
  257. }
  258. const syllables: LyricsEntry[] = lyricsEntry.ParentLyricWord.GetLyricWord.Syllables;
  259. if (syllables.length > 1) {
  260. if (lyricsEntry.LyricsEntry.SyllableIndex < syllables.length - 1) {
  261. // if a middle syllable of a word, give less measure overlap into next measure, to give room for dash
  262. if (this.dashSpace === undefined) {
  263. this.dashSpace = 1.5;
  264. // better method, doesn't work:
  265. // this.dashLength = new GraphicalLabel(new Label("-"), this.rules.LyricsHeight, TextAlignmentEnum.CenterBottom)
  266. // .PositionAndShape.Size.width; // always returns 0
  267. }
  268. lyricOverlapAllowedIntoNextMeasure -= this.dashSpace;
  269. }
  270. }
  271. }
  272. const lyricsBbox: BoundingBox = lyricsEntry.GraphicalLabel.PositionAndShape;
  273. const lyricsLabelWidth: number = lyricsBbox.Size.width;
  274. const staffEntryXPosition: number = (staffEntry as VexFlowStaffEntry).PositionAndShape.RelativePosition.x;
  275. const lyricsXPosition: number = staffEntryXPosition + lyricsBbox.BorderMarginLeft;
  276. if (lastLyricEntryDict[j] !== undefined) {
  277. if (lastLyricEntryDict[j].extend) {
  278. // TODO handle extend of last entry (extend is stored in lyrics entry of preceding syllable)
  279. // only necessary for center alignment
  280. }
  281. }
  282. let spacingNeededToLastLyric: number;
  283. let currentSpacingToLastLyric: number; // undefined for first lyric in measure
  284. if (lastLyricEntryDict[j]) {
  285. currentSpacingToLastLyric = lyricsXPosition - lastLyricEntryDict[j].lyricsXPosition;
  286. }
  287. let currentSpacingToMeasureEnd: number;
  288. let spacingNeededToMeasureEnd: number;
  289. const maxXInMeasure: number = oldMinimumStaffEntriesWidth * elongationFactorForMeasureWidth;
  290. // when the lyrics are centered, we need to consider spacing differently than when they are left-aligned:
  291. if (TextAlignment.IsCenterAligned(lyricAlignment)) {
  292. lyricOverlapAllowedIntoNextMeasure /= 4; // reserve space for overlap from next measure. its first note can't be spaced.
  293. currentSpacingToMeasureEnd = maxXInMeasure - lyricsXPosition;
  294. spacingNeededToMeasureEnd = (lyricsLabelWidth / 2) - lyricOverlapAllowedIntoNextMeasure;
  295. // spacing to last lyric only done if not first lyric in measure:
  296. if (lastLyricEntryDict[j]) {
  297. spacingNeededToLastLyric =
  298. lastLyricEntryDict[j].labelWidth / 2 + lyricsLabelWidth / 2 + minLyricsSpacing;
  299. }
  300. } else if (TextAlignment.IsLeft(lyricAlignment)) {
  301. currentSpacingToMeasureEnd = maxXInMeasure - lyricsXPosition;
  302. spacingNeededToMeasureEnd = lyricsLabelWidth - lyricOverlapAllowedIntoNextMeasure;
  303. if (lastLyricEntryDict[j]) {
  304. spacingNeededToLastLyric = lastLyricEntryDict[j].labelWidth + minLyricsSpacing;
  305. }
  306. }
  307. // get factor of how much we need to stretch the measure to space the current lyric
  308. let elongationFactorForMeasureWidthForCurrentLyric: number = 1;
  309. const elongationFactorNeededForMeasureEnd: number =
  310. spacingNeededToMeasureEnd / currentSpacingToMeasureEnd;
  311. let elongationFactorNeededForLastLyric: number = 1;
  312. if (lastLyricEntryDict[j]) { // if previous lyric needs more spacing than measure end, take that spacing
  313. const lastNoteDuration: Fraction = lastLyricEntryDict[j].sourceNoteDuration;
  314. elongationFactorNeededForLastLyric = spacingNeededToLastLyric / currentSpacingToLastLyric;
  315. if (lastNoteDuration.Denominator > 4) {
  316. elongationFactorNeededForLastLyric *= 1.1; // from 1.2 upwards, this unnecessarily bloats shorter measures
  317. // spacing in Vexflow depends on note duration, our minSpacing is calibrated for quarter notes
  318. // if we double the measure length, the distance between eigth notes only gets half of the added length
  319. // compared to a quarter note.
  320. }
  321. }
  322. elongationFactorForMeasureWidthForCurrentLyric = Math.max(
  323. elongationFactorNeededForMeasureEnd,
  324. elongationFactorNeededForLastLyric
  325. );
  326. elongationFactorForMeasureWidth = Math.max(
  327. elongationFactorForMeasureWidth,
  328. elongationFactorForMeasureWidthForCurrentLyric
  329. );
  330. // set up information about this lyric entry of verse j for next lyric entry of verse j
  331. lastLyricEntryDict[j] = {
  332. extend: lyricsEntry.LyricsEntry.extend,
  333. labelWidth: lyricsLabelWidth,
  334. lyricsXPosition: lyricsXPosition,
  335. measureNumber: measure.MeasureNumber,
  336. sourceNoteDuration: lyricsEntry.LyricsEntry.Parent.Notes[0].Length,
  337. text: lyricsEntry.LyricsEntry.Text,
  338. };
  339. }
  340. }
  341. }
  342. return oldMinimumStaffEntriesWidth * elongationFactorForMeasureWidth;
  343. }
  344. protected createGraphicalTie(tie: Tie, startGse: GraphicalStaffEntry, endGse: GraphicalStaffEntry,
  345. startNote: GraphicalNote, endNote: GraphicalNote): GraphicalTie {
  346. return new GraphicalTie(tie, startNote, endNote);
  347. }
  348. protected updateStaffLineBorders(staffLine: StaffLine): void {
  349. staffLine.SkyBottomLineCalculator.updateStaffLineBorders();
  350. }
  351. protected graphicalMeasureCreatedCalculations(measure: GraphicalMeasure): void {
  352. (measure as VexFlowMeasure).rules = this.rules;
  353. (measure as VexFlowMeasure).graphicalMeasureCreatedCalculations();
  354. }
  355. /**
  356. * Can be used to calculate articulations, stem directions, helper(ledger) lines, and overlapping note x-displacement.
  357. * Is Excecuted per voice entry of a staff entry.
  358. * After that layoutStaffEntry is called.
  359. * @param voiceEntry
  360. * @param graphicalNotes
  361. * @param graphicalStaffEntry
  362. * @param hasPitchedNote
  363. */
  364. protected layoutVoiceEntry(voiceEntry: VoiceEntry, graphicalNotes: GraphicalNote[], graphicalStaffEntry: GraphicalStaffEntry,
  365. hasPitchedNote: boolean): void {
  366. return;
  367. }
  368. /**
  369. * Do all layout calculations that have to be done per staff entry, like dots, ornaments, arpeggios....
  370. * This method is called after the voice entries are handled by layoutVoiceEntry().
  371. * @param graphicalStaffEntry
  372. */
  373. protected layoutStaffEntry(graphicalStaffEntry: GraphicalStaffEntry): void {
  374. (graphicalStaffEntry.parentMeasure as VexFlowMeasure).layoutStaffEntry(graphicalStaffEntry);
  375. }
  376. /**
  377. * Is called at the begin of the method for creating the vertically aligned staff measures belonging to one source measure.
  378. */
  379. protected initGraphicalMeasuresCreation(): void {
  380. return;
  381. }
  382. /**
  383. * add here all given articulations to the VexFlowGraphicalStaffEntry and prepare them for rendering.
  384. * @param articulations
  385. * @param voiceEntry
  386. * @param graphicalStaffEntry
  387. */
  388. protected layoutArticulationMarks(articulations: ArticulationEnum[], voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry): void {
  389. // uncomment this when implementing:
  390. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  391. return;
  392. }
  393. /**
  394. * Calculate the shape (Bezier curve) for this tie.
  395. * @param tie
  396. * @param tieIsAtSystemBreak
  397. */
  398. protected layoutGraphicalTie(tie: GraphicalTie, tieIsAtSystemBreak: boolean): void {
  399. const startNote: VexFlowGraphicalNote = (tie.StartNote as VexFlowGraphicalNote);
  400. const endNote: VexFlowGraphicalNote = (tie.EndNote as VexFlowGraphicalNote);
  401. let vfStartNote: Vex.Flow.StaveNote = undefined;
  402. let startNoteIndexInTie: number = 0;
  403. if (startNote !== undefined && startNote.vfnote !== undefined && startNote.vfnote.length >= 2) {
  404. vfStartNote = startNote.vfnote[0];
  405. startNoteIndexInTie = startNote.vfnote[1];
  406. }
  407. let vfEndNote: Vex.Flow.StaveNote = undefined;
  408. let endNoteIndexInTie: number = 0;
  409. if (endNote !== undefined && endNote.vfnote !== undefined && endNote.vfnote.length >= 2) {
  410. vfEndNote = endNote.vfnote[0];
  411. endNoteIndexInTie = endNote.vfnote[1];
  412. }
  413. if (tieIsAtSystemBreak) {
  414. // split tie into two ties:
  415. if (vfStartNote) { // first_note or last_note must be not null in Vexflow
  416. const vfTie1: Vex.Flow.StaveTie = new Vex.Flow.StaveTie({
  417. first_indices: [startNoteIndexInTie],
  418. first_note: vfStartNote
  419. });
  420. const measure1: VexFlowMeasure = (startNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  421. measure1.vfTies.push(vfTie1);
  422. }
  423. if (vfEndNote) {
  424. const vfTie2: Vex.Flow.StaveTie = new Vex.Flow.StaveTie({
  425. last_indices: [endNoteIndexInTie],
  426. last_note: vfEndNote
  427. });
  428. const measure2: VexFlowMeasure = (endNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  429. measure2.vfTies.push(vfTie2);
  430. }
  431. } else {
  432. // normal case
  433. if (vfStartNote || vfEndNote) { // one of these must be not null in Vexflow
  434. const vfTie: Vex.Flow.StaveTie = new Vex.Flow.StaveTie({
  435. first_indices: [startNoteIndexInTie],
  436. first_note: vfStartNote,
  437. last_indices: [endNoteIndexInTie],
  438. last_note: vfEndNote
  439. });
  440. const measure: VexFlowMeasure = (endNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  441. measure.vfTies.push(vfTie);
  442. }
  443. }
  444. }
  445. protected calculateDynamicExpressionsForMultiExpression(multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  446. if (measureIndex < this.rules.MinMeasureToDrawIndex || measureIndex > this.rules.MaxMeasureToDrawIndex) {
  447. return;
  448. // we do already use the min/max in MusicSheetCalculator.calculateDynamicsExpressions,
  449. // but this may be necessary for StaffLinkedExpressions, not tested.
  450. }
  451. // calculate absolute Timestamp
  452. const absoluteTimestamp: Fraction = multiExpression.AbsoluteTimestamp;
  453. const measures: GraphicalMeasure[] = this.graphicalMusicSheet.MeasureList[measureIndex];
  454. const staffLine: StaffLine = measures[staffIndex].ParentStaffLine;
  455. const startMeasure: GraphicalMeasure = measures[staffIndex];
  456. const startPosInStaffline: PointF2D = this.getRelativePositionInStaffLineFromTimestamp(
  457. absoluteTimestamp,
  458. staffIndex,
  459. staffLine,
  460. staffLine?.isPartOfMultiStaffInstrument());
  461. const dynamicStartPosition: PointF2D = startPosInStaffline;
  462. if (startPosInStaffline.x <= 0) {
  463. dynamicStartPosition.x = startMeasure.beginInstructionsWidth + this.rules.RhythmRightMargin;
  464. }
  465. if (multiExpression.InstantaneousDynamic) {
  466. const graphicalInstantaneousDynamic: VexFlowInstantaneousDynamicExpression = new VexFlowInstantaneousDynamicExpression(
  467. multiExpression.InstantaneousDynamic,
  468. staffLine,
  469. startMeasure);
  470. this.calculateGraphicalInstantaneousDynamicExpression(graphicalInstantaneousDynamic, dynamicStartPosition);
  471. }
  472. if (multiExpression.StartingContinuousDynamic) {
  473. const continuousDynamic: ContinuousDynamicExpression = multiExpression.StartingContinuousDynamic;
  474. const graphicalContinuousDynamic: VexFlowContinuousDynamicExpression = new VexFlowContinuousDynamicExpression(
  475. multiExpression.StartingContinuousDynamic,
  476. staffLine,
  477. startMeasure.parentSourceMeasure);
  478. graphicalContinuousDynamic.StartMeasure = startMeasure;
  479. if (!graphicalContinuousDynamic.IsVerbal && continuousDynamic.EndMultiExpression) {
  480. try {
  481. this.calculateGraphicalContinuousDynamic(graphicalContinuousDynamic, dynamicStartPosition);
  482. } catch (e) {
  483. // TODO this sometimes fails when the measure range to draw doesn't include all the dynamic's measures, method needs to be adjusted
  484. // see calculateGraphicalContinuousDynamic(), also in MusicSheetCalculator.
  485. }
  486. } else if (graphicalContinuousDynamic.IsVerbal) {
  487. this.calculateGraphicalVerbalContinuousDynamic(graphicalContinuousDynamic, dynamicStartPosition);
  488. } else {
  489. log.warn("This continuous dynamic is not covered");
  490. }
  491. }
  492. }
  493. protected createMetronomeMark(metronomeExpression: InstantaneousTempoExpression): void {
  494. const vfStave: Vex.Flow.Stave = (this.graphicalMusicSheet.MeasureList[0][0] as VexFlowMeasure).getVFStave();
  495. //vfStave.addModifier(new Vex.Flow.StaveTempo( // needs Vexflow PR
  496. vfStave.setTempo(
  497. {
  498. bpm: metronomeExpression.TempoInBpm,
  499. dots: metronomeExpression.dotted,
  500. //duration: metronomeExpression.beatUnit
  501. duration: "q"
  502. },
  503. this.rules.MetronomeMarkYShift * unitInPixels);
  504. // -50, -30), 0); //needs Vexflow PR
  505. //.setShiftX(-50);
  506. (<any>vfStave.getModifiers()[vfStave.getModifiers().length - 1]).setShiftX(
  507. this.rules.MetronomeMarkXShift * unitInPixels
  508. );
  509. // TODO calculate bounding box of metronome mark instead of hacking skyline to fix lyricist collision
  510. const skyline: number[] = this.graphicalMusicSheet.MeasureList[0][0].ParentStaffLine.SkyLine;
  511. skyline[0] = Math.min(skyline[0], -4.5 + this.rules.MetronomeMarkYShift);
  512. // somehow this is called repeatedly in Clementi, so skyline[0] = Math.min instead of -=
  513. }
  514. /**
  515. * Calculate a single OctaveShift for a [[MultiExpression]].
  516. * @param sourceMeasure
  517. * @param multiExpression
  518. * @param measureIndex
  519. * @param staffIndex
  520. */
  521. protected calculateSingleOctaveShift(sourceMeasure: SourceMeasure, multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  522. // calculate absolute Timestamp and startStaffLine (and EndStaffLine if needed)
  523. const octaveShift: OctaveShift = multiExpression.OctaveShiftStart;
  524. const startTimeStamp: Fraction = octaveShift.ParentStartMultiExpression.Timestamp;
  525. const endTimeStamp: Fraction = octaveShift.ParentEndMultiExpression.Timestamp;
  526. const minMeasureToDrawIndex: number = this.rules.MinMeasureToDrawIndex;
  527. const maxMeasureToDrawIndex: number = this.rules.MaxMeasureToDrawIndex;
  528. let startStaffLine: StaffLine = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex].ParentStaffLine;
  529. if (startStaffLine === undefined) { // fix for rendering range set. all of these can probably done cleaner.
  530. startStaffLine = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex].ParentStaffLine;
  531. }
  532. let endMeasure: GraphicalMeasure = undefined;
  533. if (octaveShift.ParentEndMultiExpression !== undefined) {
  534. endMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(octaveShift.ParentEndMultiExpression.SourceMeasureParent,
  535. staffIndex);
  536. } else {
  537. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true); // get last rendered measure
  538. }
  539. if (endMeasure.MeasureNumber > maxMeasureToDrawIndex + 1) { // octaveshift ends in measure not rendered
  540. endMeasure = this.graphicalMusicSheet.getLastGraphicalMeasureFromIndex(staffIndex, true);
  541. }
  542. let startMeasure: GraphicalMeasure = undefined;
  543. if (octaveShift.ParentEndMultiExpression !== undefined) {
  544. startMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(octaveShift.ParentStartMultiExpression.SourceMeasureParent,
  545. staffIndex);
  546. } else {
  547. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  548. }
  549. if (startMeasure.MeasureNumber < minMeasureToDrawIndex + 1) { // octaveshift starts before range of measures selected to render
  550. startMeasure = this.graphicalMusicSheet.MeasureList[minMeasureToDrawIndex][staffIndex]; // first rendered measure
  551. }
  552. if (startMeasure.MeasureNumber < minMeasureToDrawIndex + 1 ||
  553. startMeasure.MeasureNumber > maxMeasureToDrawIndex + 1 ||
  554. endMeasure.MeasureNumber < minMeasureToDrawIndex + 1 ||
  555. endMeasure.MeasureNumber > maxMeasureToDrawIndex + 1) {
  556. // octave shift completely out of drawing range, don't draw anything
  557. return;
  558. }
  559. let endStaffLine: StaffLine = endMeasure.ParentStaffLine;
  560. if (endStaffLine === undefined) {
  561. endStaffLine = startStaffLine;
  562. }
  563. if (endMeasure !== undefined && startStaffLine !== undefined && endStaffLine !== undefined) {
  564. // calculate GraphicalOctaveShift and RelativePositions
  565. const graphicalOctaveShift: VexFlowOctaveShift = new VexFlowOctaveShift(octaveShift, startStaffLine.PositionAndShape);
  566. if (graphicalOctaveShift.getStartNote() === undefined) { // fix for rendering range set
  567. graphicalOctaveShift.setStartNote(startMeasure.staffEntries[0]);
  568. }
  569. if (graphicalOctaveShift.getStartNote() === undefined) { // fix for rendering range set
  570. graphicalOctaveShift.setEndNote(endMeasure.staffEntries.last());
  571. }
  572. startStaffLine.OctaveShifts.push(graphicalOctaveShift);
  573. // calculate RelativePosition and Dashes
  574. let startStaffEntry: GraphicalStaffEntry = startMeasure.findGraphicalStaffEntryFromTimestamp(startTimeStamp);
  575. if (startStaffEntry === undefined) { // fix for rendering range set
  576. startStaffEntry = startMeasure.staffEntries[0];
  577. }
  578. let endStaffEntry: GraphicalStaffEntry = endMeasure.findGraphicalStaffEntryFromTimestamp(endTimeStamp);
  579. if (endStaffEntry === undefined) { // fix for rendering range set
  580. endStaffEntry = endMeasure.staffEntries[endMeasure.staffEntries.length - 1];
  581. }
  582. graphicalOctaveShift.setStartNote(startStaffEntry);
  583. if (endStaffLine !== startStaffLine) {
  584. graphicalOctaveShift.endsOnDifferentStaffLine = true;
  585. let lastMeasure: GraphicalMeasure = startStaffLine.Measures[startStaffLine.Measures.length - 1];
  586. if (lastMeasure === undefined) { // TODO handle this case correctly (when drawUpToMeasureNumber etc set)
  587. lastMeasure = endMeasure;
  588. }
  589. const lastNote: GraphicalStaffEntry = lastMeasure.staffEntries[lastMeasure.staffEntries.length - 1];
  590. graphicalOctaveShift.setEndNote(lastNote);
  591. // Now finish the shift on the next line
  592. const remainingOctaveShift: VexFlowOctaveShift = new VexFlowOctaveShift(octaveShift, endMeasure.PositionAndShape);
  593. endStaffLine.OctaveShifts.push(remainingOctaveShift);
  594. let firstMeasure: GraphicalMeasure = endStaffLine.Measures[0];
  595. if (firstMeasure === undefined) { // TODO handle this case correctly (when drawUpToMeasureNumber etc set)
  596. firstMeasure = startMeasure;
  597. }
  598. const firstNote: GraphicalStaffEntry = firstMeasure.staffEntries[0];
  599. remainingOctaveShift.setStartNote(firstNote);
  600. remainingOctaveShift.setEndNote(endStaffEntry);
  601. this.calculateOctaveShiftSkyBottomLine(startStaffEntry, lastNote, graphicalOctaveShift, startStaffLine);
  602. this.calculateOctaveShiftSkyBottomLine(firstNote, endStaffEntry, remainingOctaveShift, endStaffLine);
  603. } else {
  604. graphicalOctaveShift.setEndNote(endStaffEntry);
  605. this.calculateOctaveShiftSkyBottomLine(startStaffEntry, endStaffEntry, graphicalOctaveShift, startStaffLine);
  606. }
  607. } else {
  608. log.warn("End measure or staffLines for octave shift are undefined! This should not happen!");
  609. }
  610. }
  611. private calculateOctaveShiftSkyBottomLine(startStaffEntry: GraphicalStaffEntry, endStaffEntry: GraphicalStaffEntry,
  612. vfOctaveShift: VexFlowOctaveShift, parentStaffline: StaffLine): void {
  613. const startX: number = startStaffEntry.PositionAndShape.AbsolutePosition.x - startStaffEntry.PositionAndShape.Size.width / 2;
  614. const stopX: number = endStaffEntry.PositionAndShape.AbsolutePosition.x + endStaffEntry.PositionAndShape.Size.width / 2;
  615. vfOctaveShift.PositionAndShape.Size.width = startX - stopX;
  616. const textBracket: Vex.Flow.TextBracket = vfOctaveShift.getTextBracket();
  617. const fontSize: number = (textBracket as any).font.size / 10;
  618. if ((<any>textBracket).position === Vex.Flow.TextBracket.Positions.TOP) {
  619. const headroom: number = Math.ceil(parentStaffline.SkyBottomLineCalculator.getSkyLineMinInRange(startX, stopX));
  620. if (headroom === Infinity) { // will cause Vexflow error
  621. return;
  622. }
  623. (textBracket.start.getStave().options as any).top_text_position = Math.abs(headroom);
  624. parentStaffline.SkyBottomLineCalculator.updateSkyLineInRange(startX, stopX, headroom - fontSize * 2);
  625. } else {
  626. const footroom: number = parentStaffline.SkyBottomLineCalculator.getBottomLineMaxInRange(startX, stopX);
  627. if (footroom === Infinity) { // will cause Vexflow error
  628. return;
  629. }
  630. (textBracket.start.getStave().options as any).bottom_text_position = footroom;
  631. //Vexflow positions top vs. bottom text in a slightly inconsistent way it seems
  632. parentStaffline.SkyBottomLineCalculator.updateBottomLineInRange(startX, stopX, footroom + fontSize * 1.5);
  633. }
  634. }
  635. /**
  636. * Calculate all the textual and symbolic [[RepetitionInstruction]]s (e.g. dal segno) for a single [[SourceMeasure]].
  637. * @param repetitionInstruction
  638. * @param measureIndex
  639. */
  640. protected calculateWordRepetitionInstruction(repetitionInstruction: RepetitionInstruction, measureIndex: number): void {
  641. // find first visible StaffLine
  642. let uppermostMeasure: VexFlowMeasure = undefined;
  643. const measures: VexFlowMeasure[] = <VexFlowMeasure[]>this.graphicalMusicSheet.MeasureList[measureIndex];
  644. for (let idx: number = 0, len: number = measures.length; idx < len; ++idx) {
  645. const graphicalMeasure: VexFlowMeasure = measures[idx];
  646. if (graphicalMeasure.ParentStaffLine !== undefined && graphicalMeasure.ParentStaff.ParentInstrument.Visible) {
  647. uppermostMeasure = <VexFlowMeasure>graphicalMeasure;
  648. break;
  649. }
  650. }
  651. // ToDo: feature/Repetitions
  652. // now create corresponding graphical symbol or Text in VexFlow:
  653. // use top measure and staffline for positioning.
  654. if (uppermostMeasure !== undefined) {
  655. uppermostMeasure.addWordRepetition(repetitionInstruction);
  656. }
  657. }
  658. /**
  659. * Re-adjust the x positioning of expressions. Update the skyline afterwards
  660. */
  661. protected calculateExpressionAlignements(): void {
  662. for (const musicSystem of this.musicSystems) {
  663. for (const staffLine of musicSystem.StaffLines) {
  664. try {
  665. (<VexFlowStaffLine>staffLine).AlignmentManager.alignDynamicExpressions();
  666. staffLine.AbstractExpressions.forEach(ae => {
  667. ae.updateSkyBottomLine();
  668. });
  669. } catch (e) {
  670. // TODO still necessary when calculation of expression fails, see calculateDynamicExpressionsForMultiExpression()
  671. // see calculateGraphicalContinuousDynamic(), also in MusicSheetCalculator.
  672. }
  673. }
  674. }
  675. }
  676. /**
  677. * Check if the tied graphical note belongs to any beams or tuplets and react accordingly.
  678. * @param tiedGraphicalNote
  679. * @param beams
  680. * @param activeClef
  681. * @param octaveShiftValue
  682. * @param graphicalStaffEntry
  683. * @param duration
  684. * @param openTie
  685. * @param isLastTieNote
  686. */
  687. protected handleTiedGraphicalNote(tiedGraphicalNote: GraphicalNote, beams: Beam[], activeClef: ClefInstruction,
  688. octaveShiftValue: OctaveEnum, graphicalStaffEntry: GraphicalStaffEntry, duration: Fraction,
  689. openTie: Tie, isLastTieNote: boolean): void {
  690. return;
  691. }
  692. /**
  693. * Is called if a note is part of a beam.
  694. * @param graphicalNote
  695. * @param beam
  696. * @param openBeams a list of all currently open beams
  697. */
  698. protected handleBeam(graphicalNote: GraphicalNote, beam: Beam, openBeams: Beam[]): void {
  699. (graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure).handleBeam(graphicalNote, beam);
  700. }
  701. protected handleVoiceEntryLyrics(voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry, lyricWords: LyricWord[]): void {
  702. voiceEntry.LyricsEntries.forEach((key: number, lyricsEntry: LyricsEntry) => {
  703. const graphicalLyricEntry: GraphicalLyricEntry = new GraphicalLyricEntry(lyricsEntry,
  704. graphicalStaffEntry,
  705. this.rules.LyricsHeight,
  706. this.rules.StaffHeight);
  707. graphicalStaffEntry.LyricsEntries.push(graphicalLyricEntry);
  708. // create corresponding GraphicalLabel
  709. const graphicalLabel: GraphicalLabel = graphicalLyricEntry.GraphicalLabel;
  710. graphicalLabel.setLabelPositionAndShapeBorders();
  711. if (lyricsEntry.Word !== undefined) {
  712. const lyricsEntryIndex: number = lyricsEntry.Word.Syllables.indexOf(lyricsEntry);
  713. let index: number = lyricWords.indexOf(lyricsEntry.Word);
  714. if (index === -1) {
  715. lyricWords.push(lyricsEntry.Word);
  716. index = lyricWords.indexOf(lyricsEntry.Word);
  717. }
  718. if (this.graphicalLyricWords.length === 0 || index > this.graphicalLyricWords.length - 1) {
  719. const graphicalLyricWord: GraphicalLyricWord = new GraphicalLyricWord(lyricsEntry.Word);
  720. graphicalLyricEntry.ParentLyricWord = graphicalLyricWord;
  721. graphicalLyricWord.GraphicalLyricsEntries[lyricsEntryIndex] = graphicalLyricEntry;
  722. this.graphicalLyricWords.push(graphicalLyricWord);
  723. } else {
  724. const graphicalLyricWord: GraphicalLyricWord = this.graphicalLyricWords[index];
  725. graphicalLyricEntry.ParentLyricWord = graphicalLyricWord;
  726. graphicalLyricWord.GraphicalLyricsEntries[lyricsEntryIndex] = graphicalLyricEntry;
  727. if (graphicalLyricWord.isFilled()) {
  728. lyricWords.splice(index, 1);
  729. this.graphicalLyricWords.splice(this.graphicalLyricWords.indexOf(graphicalLyricWord), 1);
  730. }
  731. }
  732. }
  733. });
  734. }
  735. protected handleVoiceEntryOrnaments(ornamentContainer: OrnamentContainer, voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry): void {
  736. return;
  737. }
  738. /**
  739. * Add articulations to the given vexflow staff entry.
  740. * @param articulations
  741. * @param voiceEntry
  742. * @param graphicalStaffEntry
  743. */
  744. protected handleVoiceEntryArticulations(articulations: ArticulationEnum[],
  745. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  746. // uncomment this when implementing:
  747. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  748. return;
  749. }
  750. /**
  751. * Add technical instructions to the given vexflow staff entry.
  752. * @param technicalInstructions
  753. * @param voiceEntry
  754. * @param staffEntry
  755. */
  756. protected handleVoiceEntryTechnicalInstructions(technicalInstructions: TechnicalInstruction[],
  757. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  758. // uncomment this when implementing:
  759. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  760. return;
  761. }
  762. /**
  763. * Is called if a note is part of a tuplet.
  764. * @param graphicalNote
  765. * @param tuplet
  766. * @param openTuplets a list of all currently open tuplets
  767. */
  768. protected handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet, openTuplets: Tuplet[]): void {
  769. (graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure).handleTuplet(graphicalNote, tuplet);
  770. }
  771. /**
  772. * Find the Index of the item of the array of all VexFlow Slurs that holds a specified slur
  773. * @param gSlurs
  774. * @param slur
  775. */
  776. public findIndexGraphicalSlurFromSlur(gSlurs: GraphicalSlur[], slur: Slur): number {
  777. for (let slurIndex: number = 0; slurIndex < gSlurs.length; slurIndex++) {
  778. if (gSlurs[slurIndex].slur === slur) {
  779. return slurIndex;
  780. }
  781. }
  782. return -1;
  783. }
  784. /* VexFlow Version - for later use
  785. public findIndexVFSlurFromSlur(vfSlurs: VexFlowSlur[], slur: Slur): number {
  786. for (let slurIndex: number = 0; slurIndex < vfSlurs.length; slurIndex++) {
  787. if (vfSlurs[slurIndex].vfSlur === slur) {
  788. return slurIndex;
  789. }
  790. }
  791. }
  792. */
  793. // Generate all Graphical Slurs and attach them to the staffline
  794. protected calculateSlurs(): void {
  795. const openSlursDict: { [staffId: number]: GraphicalSlur[]; } = {};
  796. for (const graphicalMeasure of this.graphicalMusicSheet.MeasureList[0]) { //let i: number = 0; i < this.graphicalMusicSheet.MeasureList[0].length; i++) {
  797. openSlursDict[graphicalMeasure.ParentStaff.idInMusicSheet] = [];
  798. }
  799. /* VexFlow Version - for later use
  800. // Generate an empty dictonary to index an array of VexFlowSlur classes
  801. const vfOpenSlursDict: { [staffId: number]: VexFlowSlur[]; } = {}; //VexFlowSlur[]; } = {};
  802. // use first SourceMeasure to get all graphical measures to know how many staves are currently visible in this musicsheet
  803. // foreach stave: create an empty array. It can later hold open slurs.
  804. // Measure how many staves are visible and reserve space for them.
  805. for (const graphicalMeasure of this.graphicalMusicSheet.MeasureList[0]) { //let i: number = 0; i < this.graphicalMusicSheet.MeasureList[0].length; i++) {
  806. vfOpenSlursDict[graphicalMeasure.ParentStaff.idInMusicSheet] = [];
  807. }
  808. */
  809. for (const musicSystem of this.musicSystems) {
  810. for (const staffLine of musicSystem.StaffLines) {
  811. // if a graphical slur reaches out of the last musicsystem, we have to create another graphical slur reaching into this musicsystem
  812. // (one slur needs 2 graphical slurs)
  813. const openGraphicalSlurs: GraphicalSlur[] = openSlursDict[staffLine.ParentStaff.idInMusicSheet];
  814. for (let slurIndex: number = 0; slurIndex < openGraphicalSlurs.length; slurIndex++) {
  815. const oldGSlur: GraphicalSlur = openGraphicalSlurs[slurIndex];
  816. const newGSlur: GraphicalSlur = new GraphicalSlur(oldGSlur.slur); //Graphicalslur.createFromSlur(oldSlur);
  817. staffLine.addSlurToStaffline(newGSlur); // every VFSlur is added to the array in the VFStaffline!
  818. openGraphicalSlurs[slurIndex] = newGSlur;
  819. }
  820. /* VexFlow Version - for later use
  821. const vfOpenSlurs: VexFlowSlur[] = vfOpenSlursDict[staffLine.ParentStaff.idInMusicSheet];
  822. const vfStaffLine: VexFlowStaffLine = <VexFlowStaffLine> staffLine;
  823. for (let slurIndex: number = 0; slurIndex < vfOpenSlurs.length; slurIndex++) {
  824. const oldVFSlur: VexFlowSlur = vfOpenSlurs[slurIndex];
  825. const newVFSlur: VexFlowSlur = VexFlowSlur.createFromVexflowSlur(oldVFSlur);
  826. newVFSlur.vfStartNote = undefined;
  827. vfStaffLine.addVFSlurToVFStaffline(newVFSlur); // every VFSlur is added to the array in the VFStaffline!
  828. vfOpenSlurs[slurIndex] = newVFSlur;
  829. }
  830. */
  831. // add reference of slur array to the VexFlowStaffline class
  832. for (const graphicalMeasure of staffLine.Measures) {
  833. for (const graphicalStaffEntry of graphicalMeasure.staffEntries) {
  834. // loop over "normal" notes (= no gracenotes)
  835. for (const graphicalVoiceEntry of graphicalStaffEntry.graphicalVoiceEntries) {
  836. for (const graphicalNote of graphicalVoiceEntry.notes) {
  837. for (const slur of graphicalNote.sourceNote.NoteSlurs) {
  838. // extra check for some MusicSheets that have openSlurs (because only the first Page is available -> Recordare files)
  839. if (slur.EndNote === undefined || slur.StartNote === undefined) {
  840. continue;
  841. }
  842. // add new VexFlowSlur to List
  843. if (slur.StartNote === graphicalNote.sourceNote) {
  844. if (graphicalNote.sourceNote.NoteTie !== undefined) {
  845. if (graphicalNote.parentVoiceEntry.parentStaffEntry.getAbsoluteTimestamp() !==
  846. graphicalNote.sourceNote.NoteTie.StartNote.getAbsoluteTimestamp()) {
  847. break;
  848. }
  849. }
  850. // Add a Graphical Slur to the staffline, if the recent note is the Startnote of a slur
  851. const gSlur: GraphicalSlur = new GraphicalSlur(slur);
  852. openGraphicalSlurs.push(gSlur);
  853. staffLine.addSlurToStaffline(gSlur);
  854. /* VexFlow Version - for later use
  855. const vfSlur: VexFlowSlur = new VexFlowSlur(slur);
  856. vfOpenSlurs.push(vfSlur); //add open... adding / removing is JUST DONE in the open... array
  857. vfSlur.vfStartNote = (graphicalVoiceEntry as VexFlowVoiceEntry).vfStaveNote;
  858. vfStaffLine.addVFSlurToVFStaffline(vfSlur); // every VFSlur is added to the array in the VFStaffline!
  859. */
  860. }
  861. if (slur.EndNote === graphicalNote.sourceNote) {
  862. // Remove the Graphical Slur from the staffline if the note is the Endnote of a slur
  863. const index: number = this.findIndexGraphicalSlurFromSlur(openGraphicalSlurs, slur);
  864. if (index >= 0) {
  865. // save Voice Entry in VFSlur and then remove it from array of open VFSlurs
  866. const gSlur: GraphicalSlur = openGraphicalSlurs[index];
  867. if (gSlur.staffEntries.indexOf(graphicalStaffEntry) === -1) {
  868. gSlur.staffEntries.push(graphicalStaffEntry);
  869. }
  870. openGraphicalSlurs.splice(index, 1);
  871. }
  872. /* VexFlow Version - for later use
  873. const vfIndex: number = this.findIndexVFSlurFromSlur(vfOpenSlurs, slur);
  874. if (vfIndex !== undefined) {
  875. // save Voice Entry in VFSlur and then remove it from array of open VFSlurs
  876. const vfSlur: VexFlowSlur = vfOpenSlurs[vfIndex];
  877. vfSlur.vfEndNote = (graphicalVoiceEntry as VexFlowVoiceEntry).vfStaveNote;
  878. vfSlur.createVexFlowCurve();
  879. vfOpenSlurs.splice(vfIndex, 1);
  880. }
  881. */
  882. }
  883. }
  884. }
  885. }
  886. //add the present Staffentry to all open slurs that don't contain this Staffentry already
  887. for (const gSlur of openGraphicalSlurs) {
  888. if (gSlur.staffEntries.indexOf(graphicalStaffEntry) === -1) {
  889. gSlur.staffEntries.push(graphicalStaffEntry);
  890. }
  891. }
  892. } // loop over StaffEntries
  893. } // loop over Measures
  894. } // loop over StaffLines
  895. // Attach vfSlur array to the vfStaffline to be drawn
  896. //vfStaffLine.SlursInVFStaffLine = vfSlurs;
  897. } // loop over MusicSystems
  898. // order slurs that were saved to the Staffline
  899. for (const musicSystem of this.musicSystems) {
  900. for (const staffLine of musicSystem.StaffLines) {
  901. // Sort all gSlurs in the staffline using the Compare function in class GraphicalSlurSorter
  902. const sortedGSlurs: GraphicalSlur[] = staffLine.GraphicalSlurs.sort(GraphicalSlur.Compare);
  903. for (const gSlur of sortedGSlurs) {
  904. // crossed slurs will be handled later:
  905. if (gSlur.slur.isCrossed()) {
  906. continue;
  907. }
  908. gSlur.calculateCurve(this.rules);
  909. }
  910. }
  911. }
  912. }
  913. }