VexFlowMusicSheetCalculator.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 {MusicSystem} from "../MusicSystem";
  7. import {GraphicalNote} from "../GraphicalNote";
  8. import {GraphicalStaffEntry} from "../GraphicalStaffEntry";
  9. import {GraphicalMusicPage} from "../GraphicalMusicPage";
  10. import {GraphicalTie} from "../GraphicalTie";
  11. import {Tie} from "../../VoiceData/Tie";
  12. import {SourceMeasure} from "../../VoiceData/SourceMeasure";
  13. import {MultiExpression} from "../../VoiceData/Expressions/MultiExpression";
  14. import {RepetitionInstruction} from "../../VoiceData/Instructions/RepetitionInstruction";
  15. import {Beam} from "../../VoiceData/Beam";
  16. import {ClefInstruction} from "../../VoiceData/Instructions/ClefInstruction";
  17. import {OctaveEnum, OctaveShift} from "../../VoiceData/Expressions/ContinuousExpressions/OctaveShift";
  18. import {Fraction} from "../../../Common/DataObjects/Fraction";
  19. import {LyricWord} from "../../VoiceData/Lyrics/LyricsWord";
  20. import {OrnamentContainer} from "../../VoiceData/OrnamentContainer";
  21. import {ArticulationEnum} from "../../VoiceData/VoiceEntry";
  22. import {Tuplet} from "../../VoiceData/Tuplet";
  23. import {VexFlowMeasure} from "./VexFlowMeasure";
  24. import {VexFlowTextMeasurer} from "./VexFlowTextMeasurer";
  25. import Vex = require("vexflow");
  26. import * as log from "loglevel";
  27. import {unitInPixels} from "./VexFlowMusicSheetDrawer";
  28. import {VexFlowGraphicalNote} from "./VexFlowGraphicalNote";
  29. import {TechnicalInstruction} from "../../VoiceData/Instructions/TechnicalInstruction";
  30. import {GraphicalLyricEntry} from "../GraphicalLyricEntry";
  31. import {GraphicalLabel} from "../GraphicalLabel";
  32. import {LyricsEntry} from "../../VoiceData/Lyrics/LyricsEntry";
  33. import {GraphicalLyricWord} from "../GraphicalLyricWord";
  34. import {VexFlowStaffEntry} from "./VexFlowStaffEntry";
  35. import { VexFlowOctaveShift } from "./VexFlowOctaveShift";
  36. import { VexFlowInstantaniousDynamicExpression } from "./VexFlowInstantaniousDynamicExpression";
  37. export class VexFlowMusicSheetCalculator extends MusicSheetCalculator {
  38. constructor() {
  39. super();
  40. MusicSheetCalculator.symbolFactory = new VexFlowGraphicalSymbolFactory();
  41. MusicSheetCalculator.TextMeasurer = new VexFlowTextMeasurer();
  42. }
  43. protected clearRecreatedObjects(): void {
  44. super.clearRecreatedObjects();
  45. for (const staffMeasures of this.graphicalMusicSheet.MeasureList) {
  46. for (const staffMeasure of staffMeasures) {
  47. (<VexFlowMeasure>staffMeasure).clean();
  48. }
  49. }
  50. }
  51. protected formatMeasures(): void {
  52. for (const staffMeasures of this.graphicalMusicSheet.MeasureList) {
  53. for (const staffMeasure of staffMeasures) {
  54. (<VexFlowMeasure>staffMeasure).format();
  55. for (const staffEntry of staffMeasure.staffEntries) {
  56. (<VexFlowStaffEntry>staffEntry).calculateXPosition();
  57. }
  58. }
  59. }
  60. }
  61. //protected clearSystemsAndMeasures(): void {
  62. // for (let measure of measures) {
  63. //
  64. // }
  65. //}
  66. /**
  67. * Calculates the x layout of the staff entries within the staff measures belonging to one source measure.
  68. * All staff entries are x-aligned throughout all vertically aligned staff measures.
  69. * This method is called within calculateXLayout.
  70. * The staff entries are aligned with minimum needed x distances.
  71. * The MinimumStaffEntriesWidth of every measure will be set - needed for system building.
  72. * @param measures
  73. * @returns the minimum required x width of the source measure (=list of staff measures)
  74. */
  75. protected calculateMeasureXLayout(measures: GraphicalMeasure[]): number {
  76. // Finalize beams
  77. /*for (let measure of measures) {
  78. (measure as VexFlowMeasure).finalizeBeams();
  79. (measure as VexFlowMeasure).finalizeTuplets();
  80. }*/
  81. // Format the voices
  82. const allVoices: Vex.Flow.Voice[] = [];
  83. const formatter: Vex.Flow.Formatter = new Vex.Flow.Formatter({align_rests: true,
  84. });
  85. for (const measure of measures) {
  86. const mvoices: { [voiceID: number]: Vex.Flow.Voice; } = (measure as VexFlowMeasure).vfVoices;
  87. const voices: Vex.Flow.Voice[] = [];
  88. for (const voiceID in mvoices) {
  89. if (mvoices.hasOwnProperty(voiceID)) {
  90. voices.push(mvoices[voiceID]);
  91. allVoices.push(mvoices[voiceID]);
  92. }
  93. }
  94. if (voices.length === 0) {
  95. log.warn("Found a measure with no voices... Continuing anyway.", mvoices);
  96. continue;
  97. }
  98. formatter.joinVoices(voices);
  99. }
  100. let width: number = 200;
  101. if (allVoices.length > 0) {
  102. // FIXME: The following ``+ 5.0'' is temporary: it was added as a workaround for
  103. // FIXME: a more relaxed formatting of voices
  104. width = formatter.preCalculateMinTotalWidth(allVoices) / unitInPixels + 5.0;
  105. // firstMeasure.formatVoices = (w: number) => {
  106. // formatter.format(allVoices, w);
  107. // };
  108. for (const measure of measures) {
  109. measure.minimumStaffEntriesWidth = width;
  110. if (measure !== measures[0]) {
  111. (measure as VexFlowMeasure).formatVoices = undefined;
  112. } else {
  113. (measure as VexFlowMeasure).formatVoices = (w: number) => {
  114. formatter.format(allVoices, w);
  115. };
  116. }
  117. }
  118. }
  119. return width;
  120. }
  121. protected createGraphicalTie(tie: Tie, startGse: GraphicalStaffEntry, endGse: GraphicalStaffEntry,
  122. startNote: GraphicalNote, endNote: GraphicalNote): GraphicalTie {
  123. return new GraphicalTie(tie, startNote, endNote);
  124. }
  125. protected updateStaffLineBorders(staffLine: StaffLine): void {
  126. return;
  127. }
  128. protected staffMeasureCreatedCalculations(measure: GraphicalMeasure): void {
  129. (measure as VexFlowMeasure).staffMeasureCreatedCalculations();
  130. }
  131. /**
  132. * Can be used to calculate articulations, stem directions, helper(ledger) lines, and overlapping note x-displacement.
  133. * Is Excecuted per voice entry of a staff entry.
  134. * After that layoutStaffEntry is called.
  135. * @param voiceEntry
  136. * @param graphicalNotes
  137. * @param graphicalStaffEntry
  138. * @param hasPitchedNote
  139. * @param isGraceStaffEntry
  140. */
  141. protected layoutVoiceEntry(voiceEntry: VoiceEntry, graphicalNotes: GraphicalNote[], graphicalStaffEntry: GraphicalStaffEntry,
  142. hasPitchedNote: boolean, isGraceStaffEntry: boolean): void {
  143. return;
  144. }
  145. /**
  146. * Do all layout calculations that have to be done per staff entry, like dots, ornaments, arpeggios....
  147. * This method is called after the voice entries are handled by layoutVoiceEntry().
  148. * @param graphicalStaffEntry
  149. */
  150. protected layoutStaffEntry(graphicalStaffEntry: GraphicalStaffEntry): void {
  151. (graphicalStaffEntry.parentMeasure as VexFlowMeasure).layoutStaffEntry(graphicalStaffEntry);
  152. }
  153. /**
  154. * calculates the y positions of the staff lines within a system and
  155. * furthermore the y positions of the systems themselves.
  156. */
  157. protected calculateSystemYLayout(): void {
  158. for (let idx: number = 0, len: number = this.graphicalMusicSheet.MusicPages.length; idx < len; ++idx) {
  159. const graphicalMusicPage: GraphicalMusicPage = this.graphicalMusicSheet.MusicPages[idx];
  160. if (!this.leadSheet) {
  161. let globalY: number = this.rules.PageTopMargin + this.rules.TitleTopDistance + this.rules.SheetTitleHeight +
  162. this.rules.TitleBottomDistance;
  163. for (let idx2: number = 0, len2: number = graphicalMusicPage.MusicSystems.length; idx2 < len2; ++idx2) {
  164. const musicSystem: MusicSystem = graphicalMusicPage.MusicSystems[idx2];
  165. // calculate y positions of stafflines within system
  166. let y: number = 0;
  167. for (const line of musicSystem.StaffLines) {
  168. line.PositionAndShape.RelativePosition.y = y;
  169. y += 10;
  170. }
  171. // set y positions of systems using the previous system and a fixed distance.
  172. musicSystem.PositionAndShape.BorderBottom = y + 0;
  173. musicSystem.PositionAndShape.RelativePosition.x = this.rules.PageLeftMargin + this.rules.SystemLeftMargin;
  174. musicSystem.PositionAndShape.RelativePosition.y = globalY;
  175. globalY += y + 5;
  176. }
  177. }
  178. }
  179. }
  180. /**
  181. * Is called at the begin of the method for creating the vertically aligned staff measures belonging to one source measure.
  182. */
  183. protected initStaffMeasuresCreation(): void {
  184. return;
  185. }
  186. /**
  187. * add here all given articulations to the VexFlowGraphicalStaffEntry and prepare them for rendering.
  188. * @param articulations
  189. * @param voiceEntry
  190. * @param graphicalStaffEntry
  191. */
  192. protected layoutArticulationMarks(articulations: ArticulationEnum[], voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry): void {
  193. // uncomment this when implementing:
  194. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  195. return;
  196. }
  197. /**
  198. * Calculate the shape (Bezier curve) for this tie.
  199. * @param tie
  200. * @param tieIsAtSystemBreak
  201. */
  202. protected layoutGraphicalTie(tie: GraphicalTie, tieIsAtSystemBreak: boolean): void {
  203. const startNote: VexFlowGraphicalNote = (tie.StartNote as VexFlowGraphicalNote);
  204. const endNote: VexFlowGraphicalNote = (tie.EndNote as VexFlowGraphicalNote);
  205. let vfStartNote: Vex.Flow.StaveNote = undefined;
  206. let startNoteIndexInTie: number = 0;
  207. if (startNote !== undefined) {
  208. vfStartNote = startNote.vfnote[0];
  209. startNoteIndexInTie = startNote.vfnote[1];
  210. }
  211. let vfEndNote: Vex.Flow.StaveNote = undefined;
  212. let endNoteIndexInTie: number = 0;
  213. if (endNote !== undefined) {
  214. vfEndNote = endNote.vfnote[0];
  215. endNoteIndexInTie = endNote.vfnote[1];
  216. }
  217. if (tieIsAtSystemBreak) {
  218. // split tie into two ties:
  219. const vfTie1: Vex.Flow.StaveTie = new Vex.Flow.StaveTie({
  220. first_indices: [startNoteIndexInTie],
  221. first_note: vfStartNote
  222. });
  223. const measure1: VexFlowMeasure = (startNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  224. measure1.vfTies.push(vfTie1);
  225. const vfTie2: Vex.Flow.StaveTie = new Vex.Flow.StaveTie({
  226. last_indices: [endNoteIndexInTie],
  227. last_note: vfEndNote
  228. });
  229. const measure2: VexFlowMeasure = (endNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  230. measure2.vfTies.push(vfTie2);
  231. } else {
  232. // normal case
  233. const vfTie: Vex.Flow.StaveTie = new Vex.Flow.StaveTie({
  234. first_indices: [startNoteIndexInTie],
  235. first_note: vfStartNote,
  236. last_indices: [endNoteIndexInTie],
  237. last_note: vfEndNote
  238. });
  239. const measure: VexFlowMeasure = (endNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure);
  240. measure.vfTies.push(vfTie);
  241. }
  242. }
  243. protected calculateDynamicExpressionsForSingleMultiExpression(multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  244. if (multiExpression.InstantaniousDynamic) {
  245. const timeStamp: Fraction = multiExpression.Timestamp;
  246. const measure: StaffMeasure = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex];
  247. const startStaffEntry: GraphicalStaffEntry = measure.findGraphicalStaffEntryFromTimestamp(timeStamp);
  248. const idx: VexFlowInstantaniousDynamicExpression = new VexFlowInstantaniousDynamicExpression(multiExpression.InstantaniousDynamic, startStaffEntry);
  249. (measure as VexFlowMeasure).instantaniousDynamics.push(idx);
  250. }
  251. }
  252. /**
  253. * Calculate a single OctaveShift for a [[MultiExpression]].
  254. * @param sourceMeasure
  255. * @param multiExpression
  256. * @param measureIndex
  257. * @param staffIndex
  258. */
  259. protected calculateSingleOctaveShift(sourceMeasure: SourceMeasure, multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  260. // calculate absolute Timestamp and startStaffLine (and EndStaffLine if needed)
  261. const octaveShift: OctaveShift = multiExpression.OctaveShiftStart;
  262. const startTimeStamp: Fraction = octaveShift.ParentStartMultiExpression.Timestamp;
  263. const endTimeStamp: Fraction = octaveShift.ParentEndMultiExpression.Timestamp;
  264. const startStaffLine: StaffLine = this.graphicalMusicSheet.MeasureList[measureIndex][staffIndex].ParentStaffLine;
  265. let endMeasure: StaffMeasure = undefined;
  266. if (octaveShift.ParentEndMultiExpression !== undefined) {
  267. endMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(octaveShift.ParentEndMultiExpression.SourceMeasureParent,
  268. staffIndex);
  269. }
  270. let startMeasure: StaffMeasure = undefined;
  271. if (octaveShift.ParentEndMultiExpression !== undefined) {
  272. startMeasure = this.graphicalMusicSheet.getGraphicalMeasureFromSourceMeasureAndIndex(octaveShift.ParentStartMultiExpression.SourceMeasureParent,
  273. staffIndex);
  274. }
  275. if (endMeasure !== undefined) {
  276. // calculate GraphicalOctaveShift and RelativePositions
  277. const graphicalOctaveShift: VexFlowOctaveShift = new VexFlowOctaveShift(octaveShift, startStaffLine.PositionAndShape);
  278. startStaffLine.OctaveShifts.push(graphicalOctaveShift);
  279. // calculate RelativePosition and Dashes
  280. const startStaffEntry: GraphicalStaffEntry = startMeasure.findGraphicalStaffEntryFromTimestamp(startTimeStamp);
  281. const endStaffEntry: GraphicalStaffEntry = endMeasure.findGraphicalStaffEntryFromTimestamp(endTimeStamp);
  282. graphicalOctaveShift.setStartNote(startStaffEntry);
  283. graphicalOctaveShift.setEndNote(endStaffEntry);
  284. }
  285. }
  286. /**
  287. * Calculate all the textual and symbolic [[RepetitionInstruction]]s (e.g. dal segno) for a single [[SourceMeasure]].
  288. * @param repetitionInstruction
  289. * @param measureIndex
  290. */
  291. protected calculateWordRepetitionInstruction(repetitionInstruction: RepetitionInstruction, measureIndex: number): void {
  292. // find first visible StaffLine
  293. let uppermostMeasure: VexFlowMeasure = undefined;
  294. const measures: VexFlowMeasure[] = <VexFlowMeasure[]>this.graphicalMusicSheet.MeasureList[measureIndex];
  295. for (let idx: number = 0, len: number = measures.length; idx < len; ++idx) {
  296. const graphicalMeasure: VexFlowMeasure = measures[idx];
  297. if (graphicalMeasure.ParentStaffLine !== undefined && graphicalMeasure.ParentStaff.ParentInstrument.Visible) {
  298. uppermostMeasure = <VexFlowMeasure>graphicalMeasure;
  299. break;
  300. }
  301. }
  302. // ToDo: feature/Repetitions
  303. // now create corresponding graphical symbol or Text in VexFlow:
  304. // use top measure and staffline for positioning.
  305. if (uppermostMeasure !== undefined) {
  306. uppermostMeasure.addWordRepetition(repetitionInstruction.type);
  307. }
  308. }
  309. protected calculateMoodAndUnknownExpression(multiExpression: MultiExpression, measureIndex: number, staffIndex: number): void {
  310. return;
  311. }
  312. /**
  313. * Check if the tied graphical note belongs to any beams or tuplets and react accordingly.
  314. * @param tiedGraphicalNote
  315. * @param beams
  316. * @param activeClef
  317. * @param octaveShiftValue
  318. * @param graphicalStaffEntry
  319. * @param duration
  320. * @param openTie
  321. * @param isLastTieNote
  322. */
  323. protected handleTiedGraphicalNote(tiedGraphicalNote: GraphicalNote, beams: Beam[], activeClef: ClefInstruction,
  324. octaveShiftValue: OctaveEnum, graphicalStaffEntry: GraphicalStaffEntry, duration: Fraction,
  325. openTie: Tie, isLastTieNote: boolean): void {
  326. return;
  327. }
  328. /**
  329. * Is called if a note is part of a beam.
  330. * @param graphicalNote
  331. * @param beam
  332. * @param openBeams a list of all currently open beams
  333. */
  334. protected handleBeam(graphicalNote: GraphicalNote, beam: Beam, openBeams: Beam[]): void {
  335. (graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure).handleBeam(graphicalNote, beam);
  336. }
  337. protected handleVoiceEntryLyrics(voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry, lyricWords: LyricWord[]): void {
  338. voiceEntry.LyricsEntries.forEach((key: number, lyricsEntry: LyricsEntry) => {
  339. const graphicalLyricEntry: GraphicalLyricEntry = new GraphicalLyricEntry(lyricsEntry,
  340. graphicalStaffEntry,
  341. this.rules.LyricsHeight,
  342. this.rules.StaffHeight);
  343. graphicalStaffEntry.LyricsEntries.push(graphicalLyricEntry);
  344. // create corresponding GraphicalLabel
  345. const graphicalLabel: GraphicalLabel = graphicalLyricEntry.GraphicalLabel;
  346. graphicalLabel.setLabelPositionAndShapeBorders();
  347. if (lyricsEntry.Word !== undefined) {
  348. const lyricsEntryIndex: number = lyricsEntry.Word.Syllables.indexOf(lyricsEntry);
  349. let index: number = lyricWords.indexOf(lyricsEntry.Word);
  350. if (index === -1) {
  351. lyricWords.push(lyricsEntry.Word);
  352. index = lyricWords.indexOf(lyricsEntry.Word);
  353. }
  354. if (this.graphicalLyricWords.length === 0 || index > this.graphicalLyricWords.length - 1) {
  355. const graphicalLyricWord: GraphicalLyricWord = new GraphicalLyricWord(lyricsEntry.Word);
  356. graphicalLyricEntry.ParentLyricWord = graphicalLyricWord;
  357. graphicalLyricWord.GraphicalLyricsEntries[lyricsEntryIndex] = graphicalLyricEntry;
  358. this.graphicalLyricWords.push(graphicalLyricWord);
  359. } else {
  360. const graphicalLyricWord: GraphicalLyricWord = this.graphicalLyricWords[index];
  361. graphicalLyricEntry.ParentLyricWord = graphicalLyricWord;
  362. graphicalLyricWord.GraphicalLyricsEntries[lyricsEntryIndex] = graphicalLyricEntry;
  363. if (graphicalLyricWord.isFilled()) {
  364. lyricWords.splice(index, 1);
  365. this.graphicalLyricWords.splice(this.graphicalLyricWords.indexOf(graphicalLyricWord), 1);
  366. }
  367. }
  368. }
  369. });
  370. }
  371. protected handleVoiceEntryOrnaments(ornamentContainer: OrnamentContainer, voiceEntry: VoiceEntry, graphicalStaffEntry: GraphicalStaffEntry): void {
  372. return;
  373. }
  374. /**
  375. * Add articulations to the given vexflow staff entry.
  376. * @param articulations
  377. * @param voiceEntry
  378. * @param graphicalStaffEntry
  379. */
  380. protected handleVoiceEntryArticulations(articulations: ArticulationEnum[],
  381. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  382. // uncomment this when implementing:
  383. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  384. return;
  385. }
  386. /**
  387. * Add technical instructions to the given vexflow staff entry.
  388. * @param technicalInstructions
  389. * @param voiceEntry
  390. * @param staffEntry
  391. */
  392. protected handleVoiceEntryTechnicalInstructions(technicalInstructions: TechnicalInstruction[],
  393. voiceEntry: VoiceEntry, staffEntry: GraphicalStaffEntry): void {
  394. // uncomment this when implementing:
  395. // let vfse: VexFlowStaffEntry = (graphicalStaffEntry as VexFlowStaffEntry);
  396. return;
  397. }
  398. /**
  399. * Is called if a note is part of a tuplet.
  400. * @param graphicalNote
  401. * @param tuplet
  402. * @param openTuplets a list of all currently open tuplets
  403. */
  404. protected handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet, openTuplets: Tuplet[]): void {
  405. (graphicalNote.parentVoiceEntry.parentStaffEntry.parentMeasure as VexFlowMeasure).handleTuplet(graphicalNote, tuplet);
  406. }
  407. }