VexFlowMeasure.ts 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. import Vex = require("vexflow");
  2. import {GraphicalMeasure} from "../GraphicalMeasure";
  3. import {SourceMeasure} from "../../VoiceData/SourceMeasure";
  4. import {Staff} from "../../VoiceData/Staff";
  5. import {StaffLine} from "../StaffLine";
  6. import {SystemLinesEnum} from "../SystemLinesEnum";
  7. import {ClefInstruction, ClefEnum} from "../../VoiceData/Instructions/ClefInstruction";
  8. import {KeyInstruction} from "../../VoiceData/Instructions/KeyInstruction";
  9. import {RhythmInstruction} from "../../VoiceData/Instructions/RhythmInstruction";
  10. import {VexFlowConverter} from "./VexFlowConverter";
  11. import {VexFlowStaffEntry} from "./VexFlowStaffEntry";
  12. import {Beam} from "../../VoiceData/Beam";
  13. import {GraphicalNote} from "../GraphicalNote";
  14. import {GraphicalStaffEntry} from "../GraphicalStaffEntry";
  15. import StaveConnector = Vex.Flow.StaveConnector;
  16. import StaveNote = Vex.Flow.StaveNote;
  17. import StemmableNote = Vex.Flow.StemmableNote;
  18. import NoteSubGroup = Vex.Flow.NoteSubGroup;
  19. import * as log from "loglevel";
  20. import {unitInPixels} from "./VexFlowMusicSheetDrawer";
  21. import {Tuplet} from "../../VoiceData/Tuplet";
  22. import {RepetitionInstructionEnum, RepetitionInstruction, AlignmentType} from "../../VoiceData/Instructions/RepetitionInstruction";
  23. import {SystemLinePosition} from "../SystemLinePosition";
  24. import {StemDirectionType} from "../../VoiceData/VoiceEntry";
  25. import {GraphicalVoiceEntry} from "../GraphicalVoiceEntry";
  26. import {VexFlowVoiceEntry} from "./VexFlowVoiceEntry";
  27. import {Fraction} from "../../../Common/DataObjects/Fraction";
  28. import {Voice} from "../../VoiceData/Voice";
  29. import {LinkedVoice} from "../../VoiceData/LinkedVoice";
  30. import { EngravingRules } from "../EngravingRules";
  31. import {OrnamentContainer} from "../../VoiceData/OrnamentContainer";
  32. import {TechnicalInstruction, TechnicalInstructionType} from "../../VoiceData/Instructions/TechnicalInstruction";
  33. import {PlacementEnum} from "../../VoiceData/Expressions/AbstractExpression";
  34. import {VexFlowGraphicalNote} from "./VexFlowGraphicalNote";
  35. import {AutoBeamOptions} from "../../../OpenSheetMusicDisplay/OSMDOptions";
  36. import {NoteType, Arpeggio} from "../../VoiceData";
  37. export class VexFlowMeasure extends GraphicalMeasure {
  38. constructor(staff: Staff, sourceMeasure: SourceMeasure = undefined, staffLine: StaffLine = undefined) {
  39. super(staff, sourceMeasure, staffLine);
  40. this.minimumStaffEntriesWidth = -1;
  41. /*
  42. * There is no case in which `staffLine === undefined && sourceMeasure === undefined` holds.
  43. * Hence, it is not necessary to specify an `else` case.
  44. * One can verify this through a usage search for this constructor.
  45. */
  46. if (staffLine) {
  47. this.rules = staffLine.ParentMusicSystem.rules;
  48. } else if (sourceMeasure) {
  49. this.rules = sourceMeasure.Rules;
  50. }
  51. this.resetLayout();
  52. }
  53. /** octaveOffset according to active clef */
  54. public octaveOffset: number = 3;
  55. /** The VexFlow Voices in the measure */
  56. public vfVoices: { [voiceID: number]: Vex.Flow.Voice; } = {};
  57. /** Call this function (if present) to x-format all the voices in the measure */
  58. public formatVoices: (width: number) => void;
  59. /** The VexFlow Ties in the measure */
  60. public vfTies: Vex.Flow.StaveTie[] = [];
  61. /** The repetition instructions given as words or symbols (coda, dal segno..) */
  62. public vfRepetitionWords: Vex.Flow.Repetition[] = [];
  63. /** The VexFlow Stave (= one measure in a staffline) */
  64. protected stave: Vex.Flow.Stave;
  65. /** VexFlow StaveConnectors (vertical lines) */
  66. protected connectors: Vex.Flow.StaveConnector[] = [];
  67. /** Intermediate object to construct beams */
  68. private beams: { [voiceID: number]: [Beam, VexFlowVoiceEntry[]][]; } = {};
  69. /** Beams created by (optional) autoBeam function. */
  70. private autoVfBeams: Vex.Flow.Beam[];
  71. /** Beams of tuplet notes created by (optional) autoBeam function. */
  72. private autoTupletVfBeams: Vex.Flow.Beam[];
  73. /** VexFlow Beams */
  74. private vfbeams: { [voiceID: number]: Vex.Flow.Beam[]; };
  75. /** Intermediate object to construct tuplets */
  76. protected tuplets: { [voiceID: number]: [Tuplet, VexFlowVoiceEntry[]][]; } = {};
  77. /** VexFlow Tuplets */
  78. private vftuplets: { [voiceID: number]: Vex.Flow.Tuplet[]; } = {};
  79. // The engraving rules of OSMD.
  80. public rules: EngravingRules;
  81. // Sets the absolute coordinates of the VFStave on the canvas
  82. public setAbsoluteCoordinates(x: number, y: number): void {
  83. this.stave.setX(x).setY(y);
  84. }
  85. /**
  86. * Reset all the geometric values and parameters of this measure and put it in an initialized state.
  87. * This is needed to evaluate a measure a second time by system builder.
  88. */
  89. public resetLayout(): void {
  90. // Take into account some space for the begin and end lines of the stave
  91. // Will be changed when repetitions will be implemented
  92. //this.beginInstructionsWidth = 20 / UnitInPixels;
  93. //this.endInstructionsWidth = 20 / UnitInPixels;
  94. // TODO save beginning and end bar type, set these again after new stave.
  95. this.stave = new Vex.Flow.Stave(0, 0, 0, {
  96. space_above_staff_ln: 0,
  97. space_below_staff_ln: 0,
  98. });
  99. // constructor sets beginning and end bar type to standard
  100. this.stave.setBegBarType(Vex.Flow.Barline.type.NONE); // technically not correct, but we'd need to set the next measure's beginning bar type
  101. if (this.parentSourceMeasure && this.parentSourceMeasure.endingBarStyleEnum === SystemLinesEnum.None) {
  102. // fix for vexflow ignoring ending barline style after new stave, apparently
  103. this.stave.setEndBarType(Vex.Flow.Barline.type.NONE);
  104. }
  105. // the correct bar types seem to be set later
  106. this.updateInstructionWidth();
  107. }
  108. public clean(): void {
  109. this.vfTies.length = 0;
  110. this.connectors = [];
  111. // Clean up instructions
  112. this.resetLayout();
  113. }
  114. /**
  115. * returns the x-width (in units) of a given measure line {SystemLinesEnum}.
  116. * @param line
  117. * @returns the x-width in osmd units
  118. */
  119. public getLineWidth(line: SystemLinesEnum): number {
  120. switch (line) {
  121. // return 0 for the normal lines, as the line width will be considered at the updateInstructionWidth() method using the stavemodifiers.
  122. // case SystemLinesEnum.SingleThin:
  123. // return 5.0 / unitInPixels;
  124. // case SystemLinesEnum.DoubleThin:
  125. // return 5.0 / unitInPixels;
  126. // case SystemLinesEnum.ThinBold:
  127. // return 5.0 / unitInPixels;
  128. // but just add a little extra space for repetitions (cosmetics):
  129. case SystemLinesEnum.BoldThinDots:
  130. case SystemLinesEnum.DotsThinBold:
  131. return 10.0 / unitInPixels;
  132. case SystemLinesEnum.DotsBoldBoldDots:
  133. return 10.0 / unitInPixels;
  134. default:
  135. return 0;
  136. }
  137. }
  138. /**
  139. * adds the given clef to the begin of the measure.
  140. * This has to update/increase BeginInstructionsWidth.
  141. * @param clef
  142. */
  143. public addClefAtBegin(clef: ClefInstruction): void {
  144. this.octaveOffset = clef.OctaveOffset;
  145. if (clef.ClefType === ClefEnum.TAB) {
  146. this.stave.addClef("tab", undefined, undefined, undefined);
  147. } else {
  148. const vfclef: { type: string, size: string, annotation: string } = VexFlowConverter.Clef(clef, "default");
  149. this.stave.addClef(vfclef.type, vfclef.size, vfclef.annotation, Vex.Flow.StaveModifier.Position.BEGIN);
  150. }
  151. this.updateInstructionWidth();
  152. }
  153. /**
  154. * adds the given key to the begin of the measure.
  155. * This has to update/increase BeginInstructionsWidth.
  156. * @param currentKey the new valid key.
  157. * @param previousKey the old cancelled key. Needed to show which accidentals are not valid any more.
  158. * @param currentClef the valid clef. Needed to put the accidentals on the right y-positions.
  159. */
  160. public addKeyAtBegin(currentKey: KeyInstruction, previousKey: KeyInstruction, currentClef: ClefInstruction): void {
  161. this.stave.setKeySignature(
  162. VexFlowConverter.keySignature(currentKey),
  163. VexFlowConverter.keySignature(previousKey),
  164. undefined
  165. );
  166. this.updateInstructionWidth();
  167. }
  168. /**
  169. * adds the given rhythm to the begin of the measure.
  170. * This has to update/increase BeginInstructionsWidth.
  171. * @param rhythm
  172. */
  173. public addRhythmAtBegin(rhythm: RhythmInstruction): void {
  174. const timeSig: Vex.Flow.TimeSignature = VexFlowConverter.TimeSignature(rhythm);
  175. this.stave.addModifier(
  176. timeSig,
  177. Vex.Flow.StaveModifier.Position.BEGIN
  178. );
  179. this.updateInstructionWidth();
  180. }
  181. /**
  182. * adds the given clef to the end of the measure.
  183. * This has to update/increase EndInstructionsWidth.
  184. * @param clef
  185. */
  186. public addClefAtEnd(clef: ClefInstruction): void {
  187. const vfclef: { type: string, size: string, annotation: string } = VexFlowConverter.Clef(clef, "small");
  188. this.stave.setEndClef(vfclef.type, vfclef.size, vfclef.annotation);
  189. this.updateInstructionWidth();
  190. }
  191. public addMeasureLine(lineType: SystemLinesEnum, linePosition: SystemLinePosition): void {
  192. switch (linePosition) {
  193. case SystemLinePosition.MeasureBegin:
  194. switch (lineType) {
  195. case SystemLinesEnum.BoldThinDots:
  196. this.stave.setBegBarType(Vex.Flow.Barline.type.REPEAT_BEGIN);
  197. break;
  198. default:
  199. //this.stave.setBegBarType(Vex.Flow.Barline.type.NONE); // not necessary, it seems
  200. break;
  201. }
  202. break;
  203. case SystemLinePosition.MeasureEnd:
  204. switch (lineType) {
  205. case SystemLinesEnum.DotsBoldBoldDots:
  206. this.stave.setEndBarType(Vex.Flow.Barline.type.REPEAT_BOTH);
  207. break;
  208. case SystemLinesEnum.DotsThinBold:
  209. this.stave.setEndBarType(Vex.Flow.Barline.type.REPEAT_END);
  210. break;
  211. case SystemLinesEnum.DoubleThin:
  212. this.stave.setEndBarType(Vex.Flow.Barline.type.DOUBLE);
  213. break;
  214. case SystemLinesEnum.ThinBold:
  215. this.stave.setEndBarType(Vex.Flow.Barline.type.END);
  216. break;
  217. case SystemLinesEnum.None:
  218. this.stave.setEndBarType(Vex.Flow.Barline.type.NONE);
  219. break;
  220. // TODO: Add support for additional Barline types when VexFlow supports them
  221. default:
  222. break;
  223. }
  224. break;
  225. default:
  226. break;
  227. }
  228. }
  229. /**
  230. * Adds a measure number to the top left corner of the measure
  231. * This method is not used currently in favor of the calculateMeasureNumberPlacement
  232. * method in the MusicSheetCalculator.ts
  233. */
  234. public addMeasureNumber(): void {
  235. const text: string = this.MeasureNumber.toString();
  236. const position: number = StavePositionEnum.ABOVE; //Vex.Flow.StaveModifier.Position.ABOVE;
  237. const options: any = {
  238. justification: 1,
  239. shift_x: 0,
  240. shift_y: 0,
  241. };
  242. this.stave.setText(text, position, options);
  243. }
  244. public addWordRepetition(repetitionInstruction: RepetitionInstruction): void {
  245. let instruction: Vex.Flow.Repetition.type = undefined;
  246. let position: any = Vex.Flow.StaveModifier.Position.END;
  247. switch (repetitionInstruction.type) {
  248. case RepetitionInstructionEnum.Segno:
  249. // create Segno Symbol:
  250. instruction = Vex.Flow.Repetition.type.SEGNO_LEFT;
  251. position = Vex.Flow.StaveModifier.Position.BEGIN;
  252. break;
  253. case RepetitionInstructionEnum.Coda:
  254. // create Coda Symbol:
  255. instruction = Vex.Flow.Repetition.type.CODA_LEFT;
  256. position = Vex.Flow.StaveModifier.Position.BEGIN;
  257. break;
  258. case RepetitionInstructionEnum.DaCapo:
  259. instruction = Vex.Flow.Repetition.type.DC;
  260. break;
  261. case RepetitionInstructionEnum.DalSegno:
  262. instruction = Vex.Flow.Repetition.type.DS;
  263. break;
  264. case RepetitionInstructionEnum.Fine:
  265. instruction = Vex.Flow.Repetition.type.FINE;
  266. break;
  267. case RepetitionInstructionEnum.ToCoda:
  268. //instruction = "To Coda";
  269. break;
  270. case RepetitionInstructionEnum.DaCapoAlFine:
  271. instruction = Vex.Flow.Repetition.type.DC_AL_FINE;
  272. break;
  273. case RepetitionInstructionEnum.DaCapoAlCoda:
  274. instruction = Vex.Flow.Repetition.type.DC_AL_CODA;
  275. break;
  276. case RepetitionInstructionEnum.DalSegnoAlFine:
  277. instruction = Vex.Flow.Repetition.type.DS_AL_FINE;
  278. break;
  279. case RepetitionInstructionEnum.DalSegnoAlCoda:
  280. instruction = Vex.Flow.Repetition.type.DS_AL_CODA;
  281. break;
  282. default:
  283. break;
  284. }
  285. if (instruction !== undefined) {
  286. this.stave.addModifier(new Vex.Flow.Repetition(instruction, 0, 0), position);
  287. return;
  288. }
  289. this.addVolta(repetitionInstruction);
  290. }
  291. private addVolta(repetitionInstruction: RepetitionInstruction): void {
  292. let voltaType: number = Vex.Flow.Volta.type.BEGIN;
  293. if (repetitionInstruction.type === RepetitionInstructionEnum.Ending) {
  294. switch (repetitionInstruction.alignment) {
  295. case AlignmentType.Begin:
  296. if (this.parentSourceMeasure.endsRepetitionEnding()) {
  297. voltaType = Vex.Flow.Volta.type.BEGIN_END;
  298. } else {
  299. voltaType = Vex.Flow.Volta.type.BEGIN;
  300. }
  301. break;
  302. case AlignmentType.End:
  303. if (this.parentSourceMeasure.beginsRepetitionEnding()) {
  304. //voltaType = Vex.Flow.Volta.type.BEGIN_END;
  305. // don't add BEGIN_END volta a second time:
  306. return;
  307. } else {
  308. voltaType = Vex.Flow.Volta.type.END;
  309. }
  310. break;
  311. default:
  312. break;
  313. }
  314. this.stave.setVoltaType(voltaType, repetitionInstruction.endingIndices[0], 0);
  315. }
  316. }
  317. /**
  318. * Sets the overall x-width of the measure.
  319. * @param width
  320. */
  321. public setWidth(width: number): void {
  322. super.setWidth(width);
  323. // Set the width of the Vex.Flow.Stave
  324. this.stave.setWidth(width * unitInPixels);
  325. // Force the width of the Begin Instructions
  326. //this.stave.setNoteStartX(this.beginInstructionsWidth * UnitInPixels);
  327. }
  328. /**
  329. * This method is called after the StaffEntriesScaleFactor has been set.
  330. * Here the final x-positions of the staff entries have to be set.
  331. * (multiply the minimal positions with the scaling factor, considering the BeginInstructionsWidth)
  332. */
  333. public layoutSymbols(): void {
  334. // vexflow does the x-layout
  335. }
  336. /**
  337. * Draw this measure on a VexFlow CanvasContext
  338. * @param ctx
  339. */
  340. public draw(ctx: Vex.IRenderContext): void {
  341. // Draw stave lines
  342. this.stave.setContext(ctx).draw();
  343. // Draw all voices
  344. for (const voiceID in this.vfVoices) {
  345. if (this.vfVoices.hasOwnProperty(voiceID)) {
  346. ctx.save();
  347. this.vfVoices[voiceID].draw(ctx, this.stave);
  348. ctx.restore();
  349. // this.vfVoices[voiceID].tickables.forEach(t => t.getBoundingBox().draw(ctx));
  350. // this.vfVoices[voiceID].tickables.forEach(t => t.getBoundingBox().draw(ctx));
  351. }
  352. }
  353. // Draw beams
  354. for (const voiceID in this.vfbeams) {
  355. if (this.vfbeams.hasOwnProperty(voiceID)) {
  356. for (const beam of this.vfbeams[voiceID]) {
  357. beam.setContext(ctx).draw();
  358. }
  359. }
  360. }
  361. // Draw auto-generated beams from Beam.generateBeams()
  362. if (this.autoVfBeams) {
  363. for (const beam of this.autoVfBeams) {
  364. beam.setContext(ctx).draw();
  365. }
  366. }
  367. if (this.autoTupletVfBeams) {
  368. for (const beam of this.autoTupletVfBeams) {
  369. beam.setContext(ctx).draw();
  370. }
  371. }
  372. // Draw tuplets
  373. for (const voiceID in this.vftuplets) {
  374. if (this.vftuplets.hasOwnProperty(voiceID)) {
  375. for (const tuplet of this.vftuplets[voiceID]) {
  376. tuplet.setContext(ctx).draw();
  377. }
  378. }
  379. }
  380. // Draw ties
  381. for (const tie of this.vfTies) {
  382. tie.setContext(ctx).draw();
  383. }
  384. // Draw vertical lines
  385. for (const connector of this.connectors) {
  386. connector.setContext(ctx).draw();
  387. }
  388. }
  389. // this currently formats multiple measures, see VexFlowMusicSheetCalculator.formatMeasures()
  390. public format(): void {
  391. // If this is the first stave in the vertical measure, call the format
  392. // method to set the width of all the voices
  393. if (this.formatVoices) {
  394. // set the width of the voices to the current measure width:
  395. // (The width of the voices does not include the instructions (StaveModifiers))
  396. this.formatVoices((this.PositionAndShape.Size.width - this.beginInstructionsWidth - this.endInstructionsWidth) * unitInPixels);
  397. }
  398. }
  399. /**
  400. * Returns all the voices that are present in this measure
  401. */
  402. public getVoicesWithinMeasure(): Voice[] {
  403. const voices: Voice[] = [];
  404. for (const gse of this.staffEntries) {
  405. for (const gve of gse.graphicalVoiceEntries) {
  406. if (voices.indexOf(gve.parentVoiceEntry.ParentVoice) === -1) {
  407. voices.push(gve.parentVoiceEntry.ParentVoice);
  408. }
  409. }
  410. }
  411. return voices;
  412. }
  413. /**
  414. * Returns all the graphicalVoiceEntries of a given Voice.
  415. * @param voice the voice for which the graphicalVoiceEntries shall be returned.
  416. */
  417. public getGraphicalVoiceEntriesPerVoice(voice: Voice): GraphicalVoiceEntry[] {
  418. const voiceEntries: GraphicalVoiceEntry[] = [];
  419. for (const gse of this.staffEntries) {
  420. for (const gve of gse.graphicalVoiceEntries) {
  421. if (gve.parentVoiceEntry.ParentVoice === voice) {
  422. voiceEntries.push(gve);
  423. }
  424. }
  425. }
  426. return voiceEntries;
  427. }
  428. /**
  429. * Finds the gaps between the existing notes within a measure.
  430. * Problem here is, that the graphicalVoiceEntry does not exist yet and
  431. * that Tied notes are not present in the normal voiceEntries.
  432. * To handle this, calculation with absolute timestamps is needed.
  433. * And the graphical notes have to be analysed directly (and not the voiceEntries, as it actually should be -> needs refactoring)
  434. * @param voice the voice for which the ghost notes shall be searched.
  435. */
  436. protected getRestFilledVexFlowStaveNotesPerVoice(voice: Voice): GraphicalVoiceEntry[] {
  437. let latestVoiceTimestamp: Fraction = undefined;
  438. const gvEntries: GraphicalVoiceEntry[] = this.getGraphicalVoiceEntriesPerVoice(voice);
  439. for (let idx: number = 0, len: number = gvEntries.length; idx < len; ++idx) {
  440. const gve: GraphicalVoiceEntry = gvEntries[idx];
  441. const gNotesStartTimestamp: Fraction = gve.notes[0].sourceNote.getAbsoluteTimestamp();
  442. // find the voiceEntry end timestamp:
  443. let gNotesEndTimestamp: Fraction = new Fraction();
  444. for (const graphicalNote of gve.notes) {
  445. const noteEnd: Fraction = Fraction.plus(graphicalNote.sourceNote.getAbsoluteTimestamp(), graphicalNote.sourceNote.Length);
  446. if (gNotesEndTimestamp.lt(noteEnd)) {
  447. gNotesEndTimestamp = noteEnd;
  448. }
  449. }
  450. // check if this voice has just been found the first time:
  451. if (latestVoiceTimestamp === undefined) {
  452. // if this voice is new, check for a gap from measure start to the start of the current voice entry:
  453. const gapFromMeasureStart: Fraction = Fraction.minus(gNotesStartTimestamp, this.parentSourceMeasure.AbsoluteTimestamp);
  454. if (gapFromMeasureStart.RealValue > 0) {
  455. log.trace(`Ghost Found at start (measure ${this.MeasureNumber})`); // happens too often for valid measures to be logged to debug
  456. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(gapFromMeasureStart);
  457. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  458. ghostGve.vfStaveNote = vfghost;
  459. gvEntries.splice(0, 0, ghostGve);
  460. idx++;
  461. }
  462. } else {
  463. // get the length of the empty space between notes:
  464. const inBetweenLength: Fraction = Fraction.minus(gNotesStartTimestamp, latestVoiceTimestamp);
  465. if (inBetweenLength.RealValue > 0) {
  466. log.trace(`Ghost Found in between (measure ${this.MeasureNumber})`); // happens too often for valid measures to be logged to debug
  467. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(inBetweenLength);
  468. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  469. ghostGve.vfStaveNote = vfghost;
  470. // add element before current element:
  471. gvEntries.splice(idx, 0, ghostGve);
  472. // and increase index, as we added an element:
  473. idx++;
  474. }
  475. }
  476. // finally set the latest timestamp of this voice to the end timestamp of the longest note in the current voiceEntry:
  477. latestVoiceTimestamp = gNotesEndTimestamp;
  478. }
  479. const measureEndTimestamp: Fraction = Fraction.plus(this.parentSourceMeasure.AbsoluteTimestamp, this.parentSourceMeasure.Duration);
  480. const restLength: Fraction = Fraction.minus(measureEndTimestamp, latestVoiceTimestamp);
  481. if (restLength.RealValue > 0) {
  482. // fill the gap with a rest ghost note
  483. // starting from lastFraction
  484. // with length restLength:
  485. log.trace(`Ghost Found at end (measure ${this.MeasureNumber})`); // happens too often for valid measures to be logged to debug
  486. const vfghost: Vex.Flow.GhostNote = VexFlowConverter.GhostNote(restLength);
  487. const ghostGve: VexFlowVoiceEntry = new VexFlowVoiceEntry(undefined, undefined);
  488. ghostGve.vfStaveNote = vfghost;
  489. gvEntries.push(ghostGve);
  490. }
  491. return gvEntries;
  492. }
  493. /**
  494. * Add a note to a beam
  495. * @param graphicalNote
  496. * @param beam
  497. */
  498. public handleBeam(graphicalNote: GraphicalNote, beam: Beam): void {
  499. const voiceID: number = graphicalNote.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;
  500. let beams: [Beam, VexFlowVoiceEntry[]][] = this.beams[voiceID];
  501. if (beams === undefined) {
  502. beams = this.beams[voiceID] = [];
  503. }
  504. let data: [Beam, VexFlowVoiceEntry[]];
  505. for (const mybeam of beams) {
  506. if (mybeam[0] === beam) {
  507. data = mybeam;
  508. }
  509. }
  510. if (data === undefined) {
  511. data = [beam, []];
  512. beams.push(data);
  513. }
  514. const parent: VexFlowVoiceEntry = graphicalNote.parentVoiceEntry as VexFlowVoiceEntry;
  515. if (data[1].indexOf(parent) < 0) {
  516. data[1].push(parent);
  517. }
  518. }
  519. public handleTuplet(graphicalNote: GraphicalNote, tuplet: Tuplet): void {
  520. const voiceID: number = graphicalNote.sourceNote.ParentVoiceEntry.ParentVoice.VoiceId;
  521. tuplet = graphicalNote.sourceNote.NoteTuplet;
  522. let tuplets: [Tuplet, VexFlowVoiceEntry[]][] = this.tuplets[voiceID];
  523. if (tuplets === undefined) {
  524. tuplets = this.tuplets[voiceID] = [];
  525. }
  526. let currentTupletBuilder: [Tuplet, VexFlowVoiceEntry[]];
  527. for (const t of tuplets) {
  528. if (t[0] === tuplet) {
  529. currentTupletBuilder = t;
  530. }
  531. }
  532. if (currentTupletBuilder === undefined) {
  533. currentTupletBuilder = [tuplet, []];
  534. tuplets.push(currentTupletBuilder);
  535. }
  536. const parent: VexFlowVoiceEntry = graphicalNote.parentVoiceEntry as VexFlowVoiceEntry;
  537. if (currentTupletBuilder[1].indexOf(parent) < 0) {
  538. currentTupletBuilder[1].push(parent);
  539. }
  540. }
  541. /**
  542. * Complete the creation of VexFlow Beams in this measure
  543. */
  544. public finalizeBeams(): void {
  545. // The following line resets the created Vex.Flow Beams and
  546. // created them brand new. Is this needed? And more importantly,
  547. // should the old beams be removed manually by the notes?
  548. this.vfbeams = {};
  549. const beamedNotes: StaveNote[] = []; // already beamed notes, will be ignored by this.autoBeamNotes()
  550. for (const voiceID in this.beams) {
  551. if (this.beams.hasOwnProperty(voiceID)) {
  552. let vfbeams: Vex.Flow.Beam[] = this.vfbeams[voiceID];
  553. if (vfbeams === undefined) {
  554. vfbeams = this.vfbeams[voiceID] = [];
  555. }
  556. for (const beam of this.beams[voiceID]) {
  557. let beamHasQuarterNoteOrLonger: boolean = false;
  558. for (const note of beam[0].Notes) {
  559. if (note.Length.RealValue >= new Fraction(1, 4).RealValue
  560. // check whether the note has a TypeLength that's also not suitable for a beam (bigger than an eigth)
  561. && (note.TypeLength === undefined || note.TypeLength.RealValue > 0.125)) {
  562. beamHasQuarterNoteOrLonger = true;
  563. break;
  564. }
  565. }
  566. if (beamHasQuarterNoteOrLonger) {
  567. log.debug("Beam between note >= quarter, likely tremolo, currently unsupported. continuing.");
  568. continue;
  569. }
  570. const notes: Vex.Flow.StaveNote[] = [];
  571. const psBeam: Beam = beam[0];
  572. const voiceEntries: VexFlowVoiceEntry[] = beam[1];
  573. let autoStemBeam: boolean = true;
  574. for (const gve of voiceEntries) {
  575. if (gve.parentVoiceEntry.ParentVoice === psBeam.Notes[0].ParentVoiceEntry.ParentVoice) {
  576. autoStemBeam = gve.parentVoiceEntry.WantedStemDirection === StemDirectionType.Undefined;
  577. }
  578. }
  579. let isGraceBeam: boolean = false;
  580. let beamColor: string;
  581. const stemColors: string[] = [];
  582. for (const entry of voiceEntries) {
  583. const note: Vex.Flow.StaveNote = ((<VexFlowVoiceEntry>entry).vfStaveNote as StaveNote);
  584. if (note !== undefined) {
  585. notes.push(note);
  586. beamedNotes.push(note);
  587. }
  588. if (entry.parentVoiceEntry.IsGrace) {
  589. isGraceBeam = true;
  590. }
  591. if (entry.parentVoiceEntry.StemColor && this.rules.ColoringEnabled) {
  592. stemColors.push(entry.parentVoiceEntry.StemColor);
  593. }
  594. }
  595. if (notes.length > 1) {
  596. const vfBeam: Vex.Flow.Beam = new Vex.Flow.Beam(notes, autoStemBeam);
  597. if (isGraceBeam) {
  598. // smaller beam, as in Vexflow.GraceNoteGroup.beamNotes()
  599. (<any>vfBeam).render_options.beam_width = 3;
  600. (<any>vfBeam).render_options.partial_beam_length = 4;
  601. }
  602. if (stemColors.length >= 2 && this.rules.ColorBeams) {
  603. beamColor = stemColors[0];
  604. for (const stemColor of stemColors) {
  605. if (stemColor !== beamColor) {
  606. beamColor = undefined;
  607. break;
  608. }
  609. }
  610. vfBeam.setStyle({ fillStyle: beamColor, strokeStyle: beamColor });
  611. }
  612. vfbeams.push(vfBeam);
  613. } else {
  614. log.debug("Warning! Beam with no notes!");
  615. }
  616. }
  617. }
  618. }
  619. if (this.rules.AutoBeamNotes) {
  620. this.autoBeamNotes(beamedNotes); // try to autobeam notes except those that are already beamed (beamedNotes).
  621. }
  622. }
  623. /** Automatically creates beams for notes except beamedNotes, using Vexflow's Beam.generateBeams().
  624. * Takes options from this.rules.AutoBeamOptions.
  625. * @param beamedNotes notes that will not be autobeamed (usually because they are already beamed)
  626. */
  627. private autoBeamNotes(beamedNotes: StemmableNote[]): void {
  628. let notesToAutoBeam: StemmableNote[] = [];
  629. let consecutiveBeamableNotes: StemmableNote[] = [];
  630. let currentTuplet: Tuplet;
  631. let tupletNotesToAutoBeam: StaveNote[] = [];
  632. this.autoTupletVfBeams = [];
  633. const separateAutoBeams: StemmableNote[][] = []; // a set of separate beams, each having a set of notes (StemmableNote[]).
  634. this.autoVfBeams = []; // final Vex.Flow.Beams will be pushed/collected into this
  635. let timeSignature: Fraction = this.parentSourceMeasure.ActiveTimeSignature;
  636. if (timeSignature === undefined) { // this doesn't happen in OSMD, but maybe in a SourceGenerator
  637. timeSignature = this.parentSourceMeasure.Duration; // suboptimal, can be 1/1 in a 4/4 time signature
  638. }
  639. /*if (this.parentSourceMeasure.FirstInstructionsStaffEntries[0]) {
  640. for (const instruction of this.parentSourceMeasure.FirstInstructionsStaffEntries[0].Instructions) {
  641. if (instruction instanceof RhythmInstruction) { // there is not always a RhythmInstruction, but this could be useful some time.
  642. timeSignature = (instruction as RhythmInstruction).Rhythm;
  643. }
  644. }
  645. }*/
  646. for (const staffEntry of this.staffEntries) {
  647. for (const gve of staffEntry.graphicalVoiceEntries) {
  648. const vfStaveNote: StaveNote = <StaveNote> (gve as VexFlowVoiceEntry).vfStaveNote;
  649. const gNote: GraphicalNote = gve.notes[0]; // TODO check for all notes within the graphical voice entry
  650. const isOnBeat: boolean = staffEntry.relInMeasureTimestamp.isOnBeat(timeSignature);
  651. const haveTwoOrMoreNotesToBeamAlready: boolean = consecutiveBeamableNotes.length >= 2;
  652. //const noteIsQuarterOrLonger: boolean = gNote.sourceNote.Length.CompareTo(new Fraction(1, 4)) >= 0; // trusting Fraction class, no float check
  653. const noteIsQuarterOrLonger: boolean = gNote.sourceNote.Length.RealValue - new Fraction(1, 4).RealValue > (-Fraction.FloatInaccuracyTolerance);
  654. const unbeamableNote: boolean =
  655. gve.parentVoiceEntry.IsGrace || // don't beam grace notes
  656. noteIsQuarterOrLonger || // don't beam quarter or longer notes
  657. beamedNotes.contains(vfStaveNote);
  658. if (unbeamableNote || isOnBeat) { // end beam
  659. if (haveTwoOrMoreNotesToBeamAlready) {
  660. // if we already have at least 2 notes to beam, beam them. don't beam notes surrounded by quarter notes etc.
  661. for (const note of consecutiveBeamableNotes) {
  662. notesToAutoBeam.push(note); // "flush" already beamed notes
  663. }
  664. separateAutoBeams.push(notesToAutoBeam.slice()); // copy array, otherwise this beam gets the next notes of next beam later
  665. notesToAutoBeam = []; // reset notesToAutoBeam, otherwise the next beam includes the previous beam's notes too
  666. }
  667. consecutiveBeamableNotes = []; // reset notes to beam
  668. if (unbeamableNote) {
  669. continue;
  670. }
  671. // else, note will be pushed to consecutiveBeamableNotes after tuplet check, also for note on new beat
  672. }
  673. // create beams for tuplets separately
  674. const noteTuplet: Tuplet = gve.notes[0].sourceNote.NoteTuplet;
  675. if (noteTuplet) {
  676. // check if there are quarter notes or longer in the tuplet, then don't beam.
  677. // (TODO: check for consecutiveBeamableNotes inside tuplets like for non-tuplet notes above
  678. // e.g quarter eigth eighth -> beam the two eigth notes)
  679. let tupletContainsUnbeamableNote: boolean = false;
  680. for (const notes of noteTuplet.Notes) {
  681. for (const note of notes) {
  682. //const stavenote: StemmableNote = (gve as VexFlowVoiceEntry).vfStaveNote;
  683. //console.log("note " + note.ToString() + ", stavenote type: " + stavenote.getNoteType());
  684. if (note.NoteTypeXml >= NoteType.QUARTER || // quarter note or longer: don't beam
  685. // TODO: don't take Note (head) type from XML, but from current model,
  686. // so that rendering can react dynamically to changes compared to the XML.
  687. // however, taking the note length as fraction is tricky because of tuplets.
  688. // a quarter in a triplet has length < quarter, but quarter note head, which Vexflow can't beam.
  689. note.ParentVoiceEntry.IsGrace ||
  690. note.isRest() && !this.rules.AutoBeamOptions.beam_rests) {
  691. tupletContainsUnbeamableNote = true;
  692. break;
  693. }
  694. }
  695. if (tupletContainsUnbeamableNote) {
  696. break;
  697. }
  698. }
  699. if (currentTuplet === undefined) {
  700. currentTuplet = noteTuplet;
  701. } else {
  702. if (currentTuplet !== noteTuplet) { // new tuplet, finish old one
  703. if (tupletNotesToAutoBeam.length > 1) {
  704. this.autoTupletVfBeams.push(new Vex.Flow.Beam(tupletNotesToAutoBeam, true));
  705. }
  706. tupletNotesToAutoBeam = [];
  707. currentTuplet = noteTuplet;
  708. }
  709. }
  710. if (!tupletContainsUnbeamableNote) {
  711. tupletNotesToAutoBeam.push(vfStaveNote);
  712. }
  713. continue;
  714. } else {
  715. currentTuplet = undefined;
  716. }
  717. consecutiveBeamableNotes.push(vfStaveNote); // also happens on new beat
  718. }
  719. }
  720. if (tupletNotesToAutoBeam.length >= 2) {
  721. this.autoTupletVfBeams.push(new Vex.Flow.Beam(tupletNotesToAutoBeam, true));
  722. }
  723. if (consecutiveBeamableNotes.length >= 2) {
  724. for (const note of consecutiveBeamableNotes) {
  725. notesToAutoBeam.push(note);
  726. }
  727. separateAutoBeams.push(notesToAutoBeam);
  728. }
  729. // create options for generateBeams
  730. const autoBeamOptions: AutoBeamOptions = this.rules.AutoBeamOptions;
  731. const generateBeamOptions: any = {
  732. beam_middle_only: autoBeamOptions.beam_middle_rests_only,
  733. beam_rests: autoBeamOptions.beam_rests,
  734. maintain_stem_directions: autoBeamOptions.maintain_stem_directions,
  735. };
  736. if (autoBeamOptions.groups && autoBeamOptions.groups.length) {
  737. const groups: Vex.Flow.Fraction[] = [];
  738. for (const fraction of autoBeamOptions.groups) {
  739. groups.push(new Vex.Flow.Fraction(fraction[0], fraction[1]));
  740. }
  741. generateBeamOptions.groups = groups;
  742. }
  743. for (const notesForSeparateAutoBeam of separateAutoBeams) {
  744. const newBeams: Vex.Flow.Beam[] = Vex.Flow.Beam.generateBeams(notesForSeparateAutoBeam, generateBeamOptions);
  745. for (const beam of newBeams) {
  746. this.autoVfBeams.push(beam);
  747. }
  748. }
  749. }
  750. /**
  751. * Complete the creation of VexFlow Tuplets in this measure
  752. */
  753. public finalizeTuplets(): void {
  754. // The following line resets the created Vex.Flow Tuplets and
  755. // created them brand new. Is this needed? And more importantly,
  756. // should the old tuplets be removed manually from the notes?
  757. this.vftuplets = {};
  758. for (const voiceID in this.tuplets) {
  759. if (this.tuplets.hasOwnProperty(voiceID)) {
  760. let vftuplets: Vex.Flow.Tuplet[] = this.vftuplets[voiceID];
  761. if (vftuplets === undefined) {
  762. vftuplets = this.vftuplets[voiceID] = [];
  763. }
  764. for (const tupletBuilder of this.tuplets[voiceID]) {
  765. const tupletStaveNotes: Vex.Flow.StaveNote[] = [];
  766. const tupletVoiceEntries: VexFlowVoiceEntry[] = tupletBuilder[1];
  767. for (const tupletVoiceEntry of tupletVoiceEntries) {
  768. tupletStaveNotes.push(((tupletVoiceEntry).vfStaveNote as StaveNote));
  769. }
  770. if (tupletStaveNotes.length > 1) {
  771. const tuplet: Tuplet = tupletBuilder[0];
  772. const notesOccupied: number = tuplet.Notes[0][0].NormalNotes;
  773. const bracketed: boolean = tuplet.Bracket ||
  774. (tuplet.TupletLabelNumber === 3 && this.rules.TripletsBracketed) ||
  775. (tuplet.TupletLabelNumber !== 3 && this.rules.TupletsBracketed);
  776. vftuplets.push(new Vex.Flow.Tuplet( tupletStaveNotes,
  777. {
  778. bracketed: bracketed,
  779. notes_occupied: notesOccupied,
  780. num_notes: tuplet.TupletLabelNumber, //, location: -1, ratioed: true
  781. ratioed: this.rules.TupletsRatioed,
  782. }));
  783. } else {
  784. log.debug("Warning! Tuplet with no notes! Trying to ignore, but this is a serious problem.");
  785. }
  786. }
  787. }
  788. }
  789. }
  790. public layoutStaffEntry(graphicalStaffEntry: GraphicalStaffEntry): void {
  791. return;
  792. }
  793. public graphicalMeasureCreatedCalculations(): void {
  794. let graceSlur: boolean;
  795. let graceGVoiceEntriesBefore: GraphicalVoiceEntry[] = [];
  796. for (const graphicalStaffEntry of this.staffEntries as VexFlowStaffEntry[]) {
  797. graceSlur = false;
  798. graceGVoiceEntriesBefore = [];
  799. // create vex flow Stave Notes:
  800. for (const gve of graphicalStaffEntry.graphicalVoiceEntries) {
  801. if (gve.parentVoiceEntry.IsGrace) {
  802. // save grace notes for the next non-grace note
  803. graceGVoiceEntriesBefore.push(gve);
  804. if (!graceSlur) {
  805. graceSlur = gve.parentVoiceEntry.GraceSlur;
  806. }
  807. continue;
  808. }
  809. if (gve.notes[0].sourceNote.PrintObject) {
  810. (gve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.StaveNote(gve);
  811. } else {
  812. // note can now also be added as StaveNote instead of GhostNote, because we set it to transparent
  813. (gve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.StaveNote(gve);
  814. // previous method: add as GhostNote instead of StaveNote. Can cause formatting issues if critical notes are missing in the measure
  815. // don't render note. add ghost note, otherwise Vexflow can have issues with layouting when voices not complete.
  816. //(gve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.GhostNote(gve.notes[0].sourceNote.Length);
  817. //graceGVoiceEntriesBefore = []; // if note is not rendered, its grace notes shouldn't be rendered, might need to be removed
  818. //continue;
  819. }
  820. if (graceGVoiceEntriesBefore.length > 0) {
  821. // add grace notes that came before this main note to a GraceNoteGroup in Vexflow, attached to the main note
  822. const graceNotes: Vex.Flow.GraceNote[] = [];
  823. for (let i: number = 0; i < graceGVoiceEntriesBefore.length; i++) {
  824. const gveGrace: VexFlowVoiceEntry = <VexFlowVoiceEntry>graceGVoiceEntriesBefore[i];
  825. //if (gveGrace.notes[0].sourceNote.PrintObject) {
  826. // grace notes should generally be rendered independently of main note instead of skipped if main note is invisible
  827. // could be an option to make grace notes transparent if main note is transparent. set grace notes' PrintObject to false then.
  828. const vfStaveNote: StaveNote = VexFlowConverter.StaveNote(gveGrace);
  829. gveGrace.vfStaveNote = vfStaveNote;
  830. graceNotes.push(vfStaveNote);
  831. }
  832. const graceNoteGroup: Vex.Flow.GraceNoteGroup = new Vex.Flow.GraceNoteGroup(graceNotes, graceSlur);
  833. ((gve as VexFlowVoiceEntry).vfStaveNote as StaveNote).addModifier(0, graceNoteGroup);
  834. graceGVoiceEntriesBefore = [];
  835. }
  836. }
  837. }
  838. // remaining grace notes at end of measure, turned into stand-alone grace notes:
  839. if (graceGVoiceEntriesBefore.length > 0) {
  840. for (const graceGve of graceGVoiceEntriesBefore) {
  841. (graceGve as VexFlowVoiceEntry).vfStaveNote = VexFlowConverter.StaveNote(graceGve);
  842. graceGve.parentVoiceEntry.GraceAfterMainNote = true;
  843. }
  844. }
  845. // const t0: number = performance.now();
  846. this.finalizeBeams();
  847. // const t1: number = performance.now();
  848. // console.log("Call to finalizeBeams in VexFlowMeasure took " + (t1 - t0) + " milliseconds.");
  849. this.finalizeTuplets();
  850. const voices: Voice[] = this.getVoicesWithinMeasure();
  851. for (const voice of voices) {
  852. if (voice === undefined) {
  853. continue;
  854. }
  855. const isMainVoice: boolean = !(voice instanceof LinkedVoice);
  856. // add a vexFlow voice for this voice:
  857. this.vfVoices[voice.VoiceId] = new Vex.Flow.Voice({
  858. beat_value: this.parentSourceMeasure.Duration.Denominator,
  859. num_beats: this.parentSourceMeasure.Duration.Numerator,
  860. resolution: Vex.Flow.RESOLUTION,
  861. }).setMode(Vex.Flow.Voice.Mode.SOFT);
  862. const restFilledEntries: GraphicalVoiceEntry[] = this.getRestFilledVexFlowStaveNotesPerVoice(voice);
  863. // create vex flow voices and add tickables to it:
  864. for (const voiceEntry of restFilledEntries) {
  865. if (voiceEntry.parentVoiceEntry) {
  866. if (voiceEntry.parentVoiceEntry.IsGrace && !voiceEntry.parentVoiceEntry.GraceAfterMainNote) {
  867. continue;
  868. }
  869. }
  870. const vexFlowVoiceEntry: VexFlowVoiceEntry = voiceEntry as VexFlowVoiceEntry;
  871. if (voiceEntry.notes.length === 0 || !voiceEntry.notes[0] || !voiceEntry.notes[0].sourceNote.PrintObject) {
  872. // GhostNote, don't add modifiers like in-measure clefs
  873. this.vfVoices[voice.VoiceId].addTickable(vexFlowVoiceEntry.vfStaveNote);
  874. continue;
  875. }
  876. // check for in-measure clefs:
  877. // only add clefs in main voice (to not add them twice)
  878. if (isMainVoice) {
  879. const vfse: VexFlowStaffEntry = vexFlowVoiceEntry.parentStaffEntry as VexFlowStaffEntry;
  880. if (vfse && vfse.vfClefBefore !== undefined) {
  881. // add clef as NoteSubGroup so that we get modifier layouting
  882. const clefModifier: NoteSubGroup = new NoteSubGroup( [vfse.vfClefBefore] );
  883. // The cast is necesary because...vexflow -> see types
  884. if (vexFlowVoiceEntry.vfStaveNote.getCategory && vexFlowVoiceEntry.vfStaveNote.getCategory() === "stavenotes") {
  885. // GhostNotes and other StemmableNotes don't have this function
  886. (vexFlowVoiceEntry.vfStaveNote as Vex.Flow.StaveNote).addModifier(0, clefModifier);
  887. }
  888. }
  889. }
  890. // add fingering
  891. if (voiceEntry.parentVoiceEntry && this.rules.RenderFingerings) {
  892. this.createFingerings(voiceEntry);
  893. }
  894. // add Arpeggio
  895. if (voiceEntry.parentVoiceEntry && voiceEntry.parentVoiceEntry.Arpeggio !== undefined) {
  896. const arpeggio: Arpeggio = voiceEntry.parentVoiceEntry.Arpeggio;
  897. // TODO right now our arpeggio object has all arpeggio notes from arpeggios across all voices.
  898. // see VoiceGenerator. Doesn't matter for Vexflow for now though
  899. if (voiceEntry.notes && voiceEntry.notes.length > 1) {
  900. const type: Vex.Flow.Stroke.Type = VexFlowConverter.StrokeTypeFromArpeggioType(arpeggio.type);
  901. const stroke: Vex.Flow.Stroke = new Vex.Flow.Stroke(type, {
  902. all_voices: this.rules.ArpeggiosGoAcrossVoices
  903. // default: false. This causes arpeggios to always go across all voices, which is often unwanted.
  904. // also, this can cause infinite height of stroke, see #546
  905. });
  906. //if (arpeggio.notes.length === vexFlowVoiceEntry.notes.length) { // different workaround for endless y bug
  907. if (this.rules.RenderArpeggios) {
  908. vexFlowVoiceEntry.vfStaveNote.addStroke(0, stroke);
  909. }
  910. } else {
  911. log.debug(`[OSMD] arpeggio in measure ${this.MeasureNumber} could not be drawn.
  912. voice entry had less than two notes, arpeggio is likely between voice entries, not currently supported in Vexflow.`);
  913. // TODO: create new arpeggio with all the arpeggio's notes (arpeggio.notes), perhaps with GhostNotes in a new vfStaveNote. not easy.
  914. }
  915. }
  916. this.vfVoices[voice.VoiceId].addTickable(vexFlowVoiceEntry.vfStaveNote);
  917. }
  918. }
  919. this.createArticulations();
  920. this.createOrnaments();
  921. this.setStemDirectionFromVexFlow();
  922. }
  923. /**
  924. * Copy the stem directions chosen by VexFlow to the StemDirection variable of the graphical notes
  925. */
  926. private setStemDirectionFromVexFlow(): void {
  927. //if StemDirection was not set then read out what VexFlow has chosen
  928. for ( const vfStaffEntry of this.staffEntries ) {
  929. for ( const gVoiceEntry of vfStaffEntry.graphicalVoiceEntries) {
  930. for ( const gnote of gVoiceEntry.notes) {
  931. const vfnote: [StaveNote, number] = (gnote as VexFlowGraphicalNote).vfnote;
  932. if (vfnote === undefined || vfnote[0] === undefined) {
  933. continue;
  934. }
  935. const vfStemDir: number = vfnote[0].getStemDirection();
  936. switch (vfStemDir) {
  937. case (Vex.Flow.Stem.UP):
  938. gVoiceEntry.parentVoiceEntry.StemDirection = StemDirectionType.Up;
  939. break;
  940. case (Vex.Flow.Stem.DOWN):
  941. gVoiceEntry.parentVoiceEntry.StemDirection = StemDirectionType.Down;
  942. break;
  943. default:
  944. }
  945. }
  946. }
  947. }
  948. }
  949. /**
  950. * Create the articulations for all notes of the current staff entry
  951. */
  952. protected createArticulations(): void {
  953. for (let idx: number = 0, len: number = this.staffEntries.length; idx < len; ++idx) {
  954. const graphicalStaffEntry: VexFlowStaffEntry = (this.staffEntries[idx] as VexFlowStaffEntry);
  955. // create vex flow articulation:
  956. const graphicalVoiceEntries: GraphicalVoiceEntry[] = graphicalStaffEntry.graphicalVoiceEntries;
  957. for (const gve of graphicalVoiceEntries) {
  958. const vfStaveNote: StemmableNote = (gve as VexFlowVoiceEntry).vfStaveNote;
  959. VexFlowConverter.generateArticulations(vfStaveNote, gve.notes[0].sourceNote.ParentVoiceEntry.Articulations);
  960. }
  961. }
  962. }
  963. /**
  964. * Create the ornaments for all notes of the current staff entry
  965. */
  966. protected createOrnaments(): void {
  967. for (let idx: number = 0, len: number = this.staffEntries.length; idx < len; ++idx) {
  968. const graphicalStaffEntry: VexFlowStaffEntry = (this.staffEntries[idx] as VexFlowStaffEntry);
  969. const gvoices: { [voiceID: number]: GraphicalVoiceEntry; } = graphicalStaffEntry.graphicalVoiceEntries;
  970. for (const voiceID in gvoices) {
  971. if (gvoices.hasOwnProperty(voiceID)) {
  972. const vfStaveNote: StemmableNote = (gvoices[voiceID] as VexFlowVoiceEntry).vfStaveNote;
  973. const ornamentContainer: OrnamentContainer = gvoices[voiceID].notes[0].sourceNote.ParentVoiceEntry.OrnamentContainer;
  974. if (ornamentContainer !== undefined) {
  975. VexFlowConverter.generateOrnaments(vfStaveNote, ornamentContainer);
  976. }
  977. }
  978. }
  979. }
  980. }
  981. protected createFingerings(voiceEntry: GraphicalVoiceEntry): void {
  982. const vexFlowVoiceEntry: VexFlowVoiceEntry = voiceEntry as VexFlowVoiceEntry;
  983. const technicalInstructions: TechnicalInstruction[] = voiceEntry.parentVoiceEntry.TechnicalInstructions;
  984. let fingeringsCount: number = 0;
  985. for (const instruction of technicalInstructions) {
  986. if (instruction.type === TechnicalInstructionType.Fingering) {
  987. fingeringsCount++;
  988. }
  989. }
  990. let fingeringIndex: number = -1;
  991. for (const fingeringInstruction of technicalInstructions) {
  992. if (fingeringInstruction.type !== TechnicalInstructionType.Fingering) {
  993. continue;
  994. }
  995. fingeringIndex++; // 0 for first fingering
  996. let fingeringPosition: PlacementEnum = this.rules.FingeringPosition;
  997. if (fingeringInstruction.placement !== PlacementEnum.NotYetDefined) {
  998. fingeringPosition = fingeringInstruction.placement;
  999. }
  1000. let modifierPosition: any; // Vex.Flow.Stavemodifier.Position
  1001. switch (fingeringPosition) {
  1002. default:
  1003. case PlacementEnum.Left:
  1004. modifierPosition = Vex.Flow.StaveModifier.Position.LEFT;
  1005. break;
  1006. case PlacementEnum.Right:
  1007. modifierPosition = Vex.Flow.StaveModifier.Position.RIGHT;
  1008. break;
  1009. case PlacementEnum.Above:
  1010. modifierPosition = Vex.Flow.StaveModifier.Position.ABOVE;
  1011. break;
  1012. case PlacementEnum.Below:
  1013. modifierPosition = Vex.Flow.StaveModifier.Position.BELOW;
  1014. break;
  1015. case PlacementEnum.NotYetDefined: // automatic fingering placement, could be more complex/customizable
  1016. const sourceStaff: Staff = voiceEntry.parentStaffEntry.sourceStaffEntry.ParentStaff;
  1017. if (voiceEntry.notes.length > 1 || voiceEntry.parentStaffEntry.graphicalVoiceEntries.length > 1) {
  1018. modifierPosition = Vex.Flow.StaveModifier.Position.LEFT;
  1019. } else if (sourceStaff.idInMusicSheet === 0) {
  1020. modifierPosition = Vex.Flow.StaveModifier.Position.ABOVE;
  1021. fingeringPosition = PlacementEnum.Above;
  1022. } else {
  1023. modifierPosition = Vex.Flow.StaveModifier.Position.BELOW;
  1024. fingeringPosition = PlacementEnum.Below;
  1025. }
  1026. }
  1027. const fretFinger: Vex.Flow.FretHandFinger = new Vex.Flow.FretHandFinger(fingeringInstruction.value);
  1028. fretFinger.setPosition(modifierPosition);
  1029. if (fingeringPosition === PlacementEnum.Above || fingeringPosition === PlacementEnum.Below) {
  1030. const offsetYSign: number = fingeringPosition === PlacementEnum.Above ? -1 : 1; // minus y is up
  1031. const ordering: number = fingeringPosition === PlacementEnum.Above ? fingeringIndex :
  1032. fingeringsCount - 1 - fingeringIndex; // reverse order for fingerings below staff
  1033. if (this.rules.FingeringInsideStafflines && fingeringsCount > 1) { // y-shift for single fingering is ok
  1034. // experimental, bounding boxes wrong for fretFinger above/below, better would be creating Labels
  1035. // set y-shift. vexflow fretfinger simply places directly above/below note
  1036. const perFingeringShift: number = fretFinger.getWidth() / 2;
  1037. const shiftCount: number = fingeringsCount * 2.5;
  1038. (<any>fretFinger).setOffsetY(offsetYSign * (ordering + shiftCount) * perFingeringShift);
  1039. } else if (!this.rules.FingeringInsideStafflines) { // use StringNumber for placement above/below stafflines
  1040. const stringNumber: Vex.Flow.StringNumber = new Vex.Flow.StringNumber(fingeringInstruction.value);
  1041. (<any>stringNumber).radius = 0; // hack to remove the circle around the number
  1042. stringNumber.setPosition(modifierPosition);
  1043. stringNumber.setOffsetY(offsetYSign * ordering * stringNumber.getWidth() * 2 / 3);
  1044. // Vexflow made a mess with the addModifier signature that changes through each class so we just cast to any :(
  1045. vexFlowVoiceEntry.vfStaveNote.addModifier((fingeringIndex as any), (stringNumber as any));
  1046. continue;
  1047. }
  1048. }
  1049. if (vexFlowVoiceEntry.vfStaveNote.getCategory() === "tabnotes") {
  1050. // TODO this doesn't work yet. don't add fingering for tabs for now.
  1051. // vexFlowVoiceEntry.vfStaveNote.addModifier(fretFinger, fingeringIndex);
  1052. } else {
  1053. // Vexflow made a mess with the addModifier signature that changes through each class so we just cast to any :(
  1054. vexFlowVoiceEntry.vfStaveNote.addModifier((fingeringIndex as any), (fretFinger as any));
  1055. }
  1056. }
  1057. }
  1058. /**
  1059. * Creates a line from 'top' to this measure, of type 'lineType'
  1060. * @param top
  1061. * @param lineType
  1062. */
  1063. public lineTo(top: VexFlowMeasure, lineType: any): void {
  1064. const connector: StaveConnector = new Vex.Flow.StaveConnector(top.getVFStave(), this.stave);
  1065. connector.setType(lineType);
  1066. this.connectors.push(connector);
  1067. }
  1068. /**
  1069. * Return the VexFlow Stave corresponding to this graphicalMeasure
  1070. * @returns {Vex.Flow.Stave}
  1071. */
  1072. public getVFStave(): Vex.Flow.Stave {
  1073. return this.stave;
  1074. }
  1075. /**
  1076. * After re-running the formatting on the VexFlow Stave, update the
  1077. * space needed by Instructions (in VexFlow: StaveModifiers)
  1078. */
  1079. protected updateInstructionWidth(): void {
  1080. let vfBeginInstructionsWidth: number = 0;
  1081. let vfEndInstructionsWidth: number = 0;
  1082. const modifiers: Vex.Flow.StaveModifier[] = this.stave.getModifiers();
  1083. for (const mod of modifiers) {
  1084. if (mod.getPosition() === StavePositionEnum.BEGIN) { //Vex.Flow.StaveModifier.Position.BEGIN) {
  1085. vfBeginInstructionsWidth += mod.getWidth() + mod.getPadding(undefined);
  1086. } else if (mod.getPosition() === StavePositionEnum.END) { //Vex.Flow.StaveModifier.Position.END) {
  1087. vfEndInstructionsWidth += mod.getWidth() + mod.getPadding(undefined);
  1088. }
  1089. }
  1090. this.beginInstructionsWidth = vfBeginInstructionsWidth / unitInPixels;
  1091. this.endInstructionsWidth = vfEndInstructionsWidth / unitInPixels;
  1092. }
  1093. }
  1094. // Gives the position of the Stave - replaces the function get Position() in the description of class StaveModifier in vexflow.d.ts
  1095. // The latter gave an error because function cannot be defined in the class descriptions in vexflow.d.ts
  1096. export enum StavePositionEnum {
  1097. LEFT = 1,
  1098. RIGHT = 2,
  1099. ABOVE = 3,
  1100. BELOW = 4,
  1101. BEGIN = 5,
  1102. END = 6
  1103. }