jpfun 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +53 -113
  2. package/dist/converter/midi/convert.js +14 -7
  3. package/dist/converter/musicxml/features.d.ts +57 -16
  4. package/dist/converter/musicxml/features.js +204 -42
  5. package/dist/converter/musicxml/index.d.ts +7 -2
  6. package/dist/converter/musicxml/index.js +256 -268
  7. package/dist/converter/musicxml/model.d.ts +36 -7
  8. package/dist/converter/musicxml/resolve.d.ts +10 -0
  9. package/dist/converter/musicxml/resolve.js +152 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/fraction.js +7 -1
  13. package/dist/functions/ASTtypes.d.ts +6 -3
  14. package/dist/functions/ASTtypes.js +30 -23
  15. package/dist/functions/adjust/index.js +10 -50
  16. package/dist/functions/arpeggio/index.js +40 -25
  17. package/dist/functions/beam/auto.js +2 -11
  18. package/dist/functions/box/index.js +132 -82
  19. package/dist/functions/dash/index.js +20 -11
  20. package/dist/functions/default.js +2 -1
  21. package/dist/functions/div/index.d.ts +1 -1
  22. package/dist/functions/div/index.js +9 -10
  23. package/dist/functions/dot/index.js +4 -5
  24. package/dist/functions/dyn/index.js +28 -32
  25. package/dist/functions/grace/index.d.ts +23 -8
  26. package/dist/functions/grace/index.js +138 -119
  27. package/dist/functions/head/index.js +11 -4
  28. package/dist/functions/key/index.js +1 -1
  29. package/dist/functions/meter/index.js +40 -7
  30. package/dist/functions/meter/shape.d.ts +3 -0
  31. package/dist/functions/meter/shape.js +43 -0
  32. package/dist/functions/note/index.d.ts +6 -1
  33. package/dist/functions/note/index.js +60 -57
  34. package/dist/functions/note/source-transform.d.ts +21 -0
  35. package/dist/functions/note/source-transform.js +164 -0
  36. package/dist/functions/page/index.d.ts +5 -0
  37. package/dist/functions/page/index.js +8 -5
  38. package/dist/functions/rest/index.d.ts +2 -0
  39. package/dist/functions/rest/index.js +233 -0
  40. package/dist/functions/set/index.js +5 -1
  41. package/dist/functions/symbol/index.d.ts +2 -0
  42. package/dist/functions/symbol/index.js +1 -1
  43. package/dist/functions/symbol/ornament.d.ts +3 -3
  44. package/dist/functions/symbol/ornament.js +21 -35
  45. package/dist/functions/symbol/symbols/accent.js +5 -5
  46. package/dist/functions/symbol/symbols/fermata.js +5 -4
  47. package/dist/functions/temporal.d.ts +21 -7
  48. package/dist/functions/temporal.js +14 -4
  49. package/dist/functions/tie/index.js +36 -42
  50. package/dist/functions/tuplet/index.js +20 -24
  51. package/dist/functions/up/index.js +54 -34
  52. package/dist/functions/voice/connections.d.ts +19 -0
  53. package/dist/functions/voice/connections.js +88 -0
  54. package/dist/functions/voice/index.js +248 -102
  55. package/dist/functions/volta/index.js +7 -12
  56. package/dist/jpfun.core.min.js +61 -41
  57. package/dist/jpfun.from-midi.min.js +5 -5
  58. package/dist/jpfun.from-musicxml.min.js +8 -8
  59. package/dist/jpfun.min.js +70 -50
  60. package/dist/layout/engine.d.ts +13 -1
  61. package/dist/layout/engine.js +458 -129
  62. package/dist/layout/model.js +22 -66
  63. package/dist/layout/page.js +3 -1
  64. package/dist/layout/range.d.ts +26 -0
  65. package/dist/layout/range.js +75 -0
  66. package/dist/layout/types.d.ts +63 -49
  67. package/dist/lowering/loweringContext.d.ts +1 -1
  68. package/dist/lowering/loweringContext.js +34 -4
  69. package/dist/lowering/types.d.ts +5 -0
  70. package/dist/parser/parse-utils/length-utils.js +2 -0
  71. package/dist/parser/parse-utils/note-utils.d.ts +2 -0
  72. package/dist/parser/parse-utils/note-utils.js +6 -2
  73. package/dist/parser/parserContext.js +5 -9
  74. package/dist/parser/preprocess.js +4 -6
  75. package/dist/playback/compile.d.ts +2 -9
  76. package/dist/playback/compile.js +297 -186
  77. package/dist/playback/event.d.ts +8 -16
  78. package/dist/playback/event.js +13 -3
  79. package/dist/playback/types.d.ts +76 -18
  80. package/dist/playback/types.js +1 -0
  81. package/dist/render/index.d.ts +1 -1
  82. package/dist/render/index.js +1 -1
  83. package/dist/render/paint.js +1 -1
  84. package/dist/render/recording.d.ts +1 -0
  85. package/dist/render/recording.js +21 -0
  86. package/dist/render/translate.d.ts +14 -0
  87. package/dist/render/translate.js +48 -0
  88. package/grammar.md +200 -250
  89. package/package.json +4 -4
@@ -0,0 +1,233 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { Fraction } from "../../fraction.js";
3
+ import { ASTFunctionNode, ASTNodeBase, } from "../ASTtypes.js";
4
+ import { ANCHOR_KEY, isVisualTemporalNode, TemporalNodeBase } from "../temporal.js";
5
+ // 同刻状态先固化,休止只与休止合列,普通音符随后进入
6
+ const REST_KEY = Number.MAX_VALUE;
7
+ const restsByHost = new WeakMap();
8
+ class RestFunction extends ASTFunctionNode {
9
+ static def = {
10
+ name: ["rest"],
11
+ description: "多小节休止",
12
+ details: `\
13
+ ~~~jpfun
14
+ @meter(4,4) | @rest(19) |
15
+ ~~~
16
+ 使用当前拍号产生 19 个整小节的静音(必须先声明拍号)`,
17
+ allowExtraArgs: false,
18
+ args: [
19
+ {
20
+ name: "n",
21
+ description: "休止的小节数",
22
+ type: "number",
23
+ default: 1
24
+ },
25
+ {
26
+ name: "width",
27
+ description: "横线的最小宽度",
28
+ type: "length",
29
+ default: { value: 3, unit: "em" }
30
+ },
31
+ {
32
+ name: "size",
33
+ description: "数字字号与笔画尺寸",
34
+ type: "length",
35
+ default: { value: 1, unit: "em" }
36
+ },
37
+ ],
38
+ };
39
+ count;
40
+ width;
41
+ size;
42
+ font;
43
+ constructor(span, args, ctx, parent = null) {
44
+ super(span, parent);
45
+ const [count, width, size] = this.getArgValue(args, ctx);
46
+ if (!Number.isSafeInteger(count) || count <= 0 || count > 0xffffffff) {
47
+ throw new ErrorDiagnostic("E_REST_COUNT", "@rest 的 n 必须是正安全整数,且小节线数量可由数组表示", span);
48
+ }
49
+ this.count = count;
50
+ this.width = ctx.length2px(width);
51
+ this.size = ctx.length2px(size);
52
+ if (!Number.isFinite(this.width) || this.width < 0 || !Number.isFinite(this.size) || this.size <= 0) {
53
+ throw new ErrorDiagnostic("E_REST_SIZE", "@rest 的 width 必须有限且非负,size 必须有限且为正", span);
54
+ }
55
+ this.font = ctx.variables.numberfont;
56
+ }
57
+ labelable() { return null; }
58
+ loweringEnter() {
59
+ return [new RestTemporal(this)];
60
+ }
61
+ static loweringFinalize(result) {
62
+ // 没有全局休止列时,跳过索引扫描和边界补入
63
+ if (!result.columns.some(column => column.some(node => node.mergeKey === REST_KEY)))
64
+ return;
65
+ let order = 0;
66
+ const onsets = new Map();
67
+ // 扫描完整来源索引,纳入未直接出现在时间列中的折叠成员
68
+ for (const nodes of result.astToTemporal.values()) {
69
+ // 为新增边界预留唯一 order,并记录各宿主的休止代表和最早音符
70
+ for (const node of nodes) {
71
+ order = Math.max(order, node.order + 1);
72
+ if (!(node instanceof RestTemporal)
73
+ && (!(node.ast instanceof ASTFunctionNode)
74
+ || (node.ast.callName !== "note" && node.ast.callName !== "dash")))
75
+ continue;
76
+ let host = node;
77
+ // 沿折叠链找到最外层宿主,将内部成员归到同一主体
78
+ while (host.foldedInto)
79
+ host = host.foldedInto;
80
+ // 私有倚音属于独立轨道,不代表外层宿主的休止或起音
81
+ if (node.track !== host.track)
82
+ continue;
83
+ if (node instanceof RestTemporal) {
84
+ // 非宿主休止不接管外层时间列,同轨最早休止代表宿主
85
+ if (host.mergeKey !== REST_KEY)
86
+ continue;
87
+ const rest = restsByHost.get(host);
88
+ if (!rest || node.order < rest.order)
89
+ restsByHost.set(host, node);
90
+ continue;
91
+ }
92
+ const onset = onsets.get(host);
93
+ if (!onset || node.order < onset.order)
94
+ onsets.set(host, node);
95
+ }
96
+ }
97
+ const columns = [];
98
+ const previous = new Map();
99
+ // 保留原时间列,并在休止列后追加其内部小节边界
100
+ for (const column of result.columns) {
101
+ columns.push(column);
102
+ let longest;
103
+ // 检查各轨是否用增时线延续休止,同时选出同列最长休止
104
+ for (const node of column) {
105
+ if (node.T.compare(0) > 0) {
106
+ const onset = onsets.get(node);
107
+ const before = previous.get(node.track);
108
+ if (before && restsByHost.has(before)
109
+ && onset?.ast instanceof ASTFunctionNode && onset.ast.callName === "dash") {
110
+ throw new ErrorDiagnostic("E_REST_SUSTAIN", "增时线不能延续整小节休止", onset.ast.sourceSpan);
111
+ }
112
+ previous.set(node.track, node);
113
+ }
114
+ const rest = restsByHost.get(node);
115
+ if (rest && (!longest || rest.T.compare(longest.T) > 0))
116
+ longest = rest;
117
+ }
118
+ if (!longest)
119
+ continue;
120
+ const time = longest.t.clone();
121
+ // 按小节时长补入 n−1 个不可见边界;时间已固化,不再参与声部归并
122
+ for (let index = 1; index < longest.ast.count; index++) {
123
+ time.add(longest.measureDuration);
124
+ const boundary = new TemporalNodeBase();
125
+ boundary.ast = new ASTNodeBase(longest.ast.sourceSpan, longest.ast);
126
+ boundary.t.copyFrom(time);
127
+ boundary.track = longest.track;
128
+ boundary.layoutLine = longest.layoutLine;
129
+ boundary.order = order++;
130
+ boundary.mergeKey = ANCHOR_KEY;
131
+ result.astToTemporal.set(boundary.ast, [boundary]);
132
+ columns.push([boundary]);
133
+ }
134
+ }
135
+ result.columns = columns;
136
+ }
137
+ toString() { return `@rest(${this.count})`; }
138
+ }
139
+ export const RestNode = RestFunction;
140
+ class RestTemporal extends TemporalNodeBase {
141
+ measureDuration = new Fraction();
142
+ metrics;
143
+ lineWidth = 0;
144
+ textStyle;
145
+ constructor(ast) {
146
+ super();
147
+ this.ast = ast;
148
+ this.mergeKey = REST_KEY;
149
+ restsByHost.set(this, this);
150
+ this.initLayoutBox();
151
+ this.textStyle = { fontSize: ast.size, fontFamily: ast.font, textAlign: "center" };
152
+ }
153
+ onTimeState(state) {
154
+ const measure = state.meter;
155
+ if (!(measure instanceof Fraction)) {
156
+ throw new ErrorDiagnostic("E_REST_METER", "整小节休止前必须有实际生效的显式拍号", this.ast.sourceSpan);
157
+ }
158
+ if (!Number.isSafeInteger(measure.numerator * this.ast.count)) {
159
+ throw new ErrorDiagnostic("E_REST_COUNT", "@rest 的总时值超出精确整数范围", this.ast.sourceSpan);
160
+ }
161
+ this.measureDuration.copyFrom(measure);
162
+ this.T.copyFrom(measure).mul(this.ast.count);
163
+ this.playbackState = { bpm: state.bpm };
164
+ return this.T;
165
+ }
166
+ emitPlayback(emitter) {
167
+ emitter.span({ start: emitter.start, end: emitter.end });
168
+ }
169
+ prepareLayout(context) {
170
+ const size = this.ast.size;
171
+ // 抵消布局器的时长平方根缩放,左右弹簧自然长度固定为 6px
172
+ const alpha = 6 / Math.sqrt(this.T.toNumber());
173
+ this.springConfig = { alpha_L: alpha, alpha_R: alpha };
174
+ this.metrics = context.textMeasurer.measureText(String(this.ast.count), this.textStyle);
175
+ this.lineWidth = Math.max(this.ast.width, this.metrics.w + size * 0.5);
176
+ this.box.w = this.lineWidth + size * 0.25;
177
+ this.box.h = this.metrics.h + size * 0.5;
178
+ this.box.anchor = size * 0.4;
179
+ this.box.visualAxis = this.box.h - size * 0.65 / 2;
180
+ }
181
+ prepareHorizontal(line) {
182
+ let host = this;
183
+ // 向外寻找实际占据布局列的宿主,让被包装的休止也能注册横向约束
184
+ while (line.columnOf(host) < 0 && host.foldedInto && isVisualTemporalNode(host.foldedInto))
185
+ host = host.foldedInto;
186
+ const column = line.columnOf(host);
187
+ if (column < 0)
188
+ return;
189
+ const barAt = (index) => line.columns[index]?.find(node => node.track === host.track && node.mergeKey === ANCHOR_KEY) ?? host;
190
+ const first = barAt(column - 1);
191
+ const last = barAt(column + 1);
192
+ if (first === last)
193
+ return;
194
+ line.registerHorizontalLayoutHook(first, last, ({ columns, rows, start, end, X, fixed }) => {
195
+ // 锁定休止及相邻小节线之间的列间距,撑满行宽时也不拉开
196
+ for (let i = start; i < end; i++) {
197
+ if (fixed[i])
198
+ continue;
199
+ let distance = 0;
200
+ // 取所有声部所需间距的最大值,避免压紧休止时造成其他声部交叠
201
+ for (let row = 0; row < rows; row++) {
202
+ const left = columns[i][row];
203
+ const right = columns[i + 1][row];
204
+ // 右侧留隙已在休止盒内,只给左侧补同样的墨迹间距
205
+ const rest = restsByHost.get(right.time);
206
+ const gap = rest ? rest.ast.size * 0.25 : 0;
207
+ distance = Math.max(distance, left.WR + right.WL + gap);
208
+ }
209
+ const shift = X[i] + distance - X[i + 1];
210
+ // 平移右侧已锁定的块及其末列,保留连续休止先前确定的间隙
211
+ for (let j = i + 1; j < X.length; j++) {
212
+ X[j] += shift;
213
+ if (!fixed[j])
214
+ break;
215
+ }
216
+ fixed[i] = 1;
217
+ }
218
+ });
219
+ }
220
+ paint(painter) {
221
+ const { size, count } = this.ast;
222
+ const left = this.box.x;
223
+ const right = left + this.lineWidth;
224
+ const axis = this.box.y + this.box.visualAxis;
225
+ const stroke = size * 0.12;
226
+ const barStroke = stroke * 2;
227
+ const halfCap = (size * 0.65 - stroke) / 2;
228
+ painter.drawLine(left + barStroke / 2, axis, right - barStroke / 2, axis, { strokeWidth: barStroke });
229
+ painter.drawLine(left + stroke / 2, axis - halfCap, left + stroke / 2, axis + halfCap, { strokeWidth: stroke });
230
+ painter.drawLine(right - stroke / 2, axis - halfCap, right - stroke / 2, axis + halfCap, { strokeWidth: stroke });
231
+ painter.drawText(String(count), left + this.lineWidth / 2, this.box.y + this.metrics.baseline, this.textStyle);
232
+ }
233
+ }
@@ -62,7 +62,11 @@ class SetFunction extends ASTFunctionNode {
62
62
  }
63
63
  }
64
64
  toString() {
65
- return `@set(${Array.from(this.args, ([key, value]) => `${key}=${typeof value === "string" ? quote(value) : value}`).join(", ")})`;
65
+ return `@set(${Array.from(this.args, ([key, value]) => {
66
+ const text = typeof value === "string" ? quote(value)
67
+ : value && typeof value === "object" && "unit" in value ? `${value.value}${value.unit}` : value;
68
+ return `${key}=${text}`;
69
+ }).join(", ")})`;
66
70
  }
67
71
  }
68
72
  export const SetNode = SetFunction;
@@ -19,6 +19,8 @@ export interface SymbolDefinition {
19
19
  };
20
20
  /** 符号高度 = size × weight,用来修正宽扁字形的视觉重量;默认 1 */
21
21
  readonly weight?: number;
22
+ /** 图形下方留白,使用符号自身坐标并随 scale 缩放;默认 0 */
23
+ readonly paddingBottom?: number;
22
24
  /** 写入本位置之后持续生效的状态,例如力度记号的 velocity */
23
25
  readonly onTimeState?: (state: TimeState) => void;
24
26
  /** 发布系统控制,或注册对同一折叠序列后续音符的局部变换 */
@@ -121,7 +121,7 @@ class SymbolTemporal extends TemporalNodeBase {
121
121
  else {
122
122
  this.scale = this.height / this.bounds.h;
123
123
  this.box.w = this.bounds.w * this.scale;
124
- this.box.h = this.height;
124
+ this.box.h = this.height + (this.ast.definition.paddingBottom ?? 0) * this.scale;
125
125
  }
126
126
  this.box.anchor = this.box.w / 2;
127
127
  this.box.visualAxis = this.box.h / 2;
@@ -6,10 +6,10 @@ interface OrnamentPattern {
6
6
  readonly repeat?: boolean;
7
7
  }
8
8
  /**
9
- * 把一个音按固定音级模式展开成装饰音序列
9
+ * 按调内音级模式拆分传入音段,使用结构完成后的范围和最终播放速度
10
10
  *
11
- * 密度按发声时的速度决定而不是固定的记谱时值:固定 1/8 四分音符在慢速下
12
- * 每秒只有两三次,听起来根本不是颤音。默认速度下仍然恰好是 1/8 四分音符。
11
+ * 重复式模式按速度计算次数,固定模式在整段时值内均分。
12
+ * 派生音段继承轨道和来源,仍只声明音段,不直接发布 NoteOn/NoteOff。
13
13
  */
14
14
  export declare function ornament(pattern: OrnamentPattern): PlaybackTransform;
15
15
  export {};
@@ -6,67 +6,53 @@ const MAX_BPM = 480;
6
6
  /** 一个装饰音能展开的子音上限;防的是 `@tempo(0.01)` 这类手滑 */
7
7
  const MAX_SUBNOTES = 256;
8
8
  /**
9
- * 把一个音按固定音级模式展开成装饰音序列
9
+ * 按调内音级模式拆分传入音段,使用结构完成后的范围和最终播放速度
10
10
  *
11
- * 密度按发声时的速度决定而不是固定的记谱时值:固定 1/8 四分音符在慢速下
12
- * 每秒只有两三次,听起来根本不是颤音。默认速度下仍然恰好是 1/8 四分音符。
11
+ * 重复式模式按速度计算次数,固定模式在整段时值内均分。
12
+ * 派生音段继承轨道和来源,仍只声明音段,不直接发布 NoteOn/NoteOff。
13
13
  */
14
14
  export function ornament(pattern) {
15
15
  return (context, owned) => {
16
- const noteOffs = new Map();
17
- for (const event of owned) {
18
- if (event.kind === "note-off")
19
- noteOffs.set(event.noteId, event);
20
- }
21
- const removed = new Set();
22
- const added = [];
16
+ const result = [];
17
+ // 前一项声音变换可能已产生多个音段,因此逐段处理,不能假定只剩一个宿主音。
23
18
  for (const note of owned) {
24
- if (note.kind !== "note-on" || !note.transpose)
25
- continue;
26
- const off = noteOffs.get(note.noteId);
27
- if (!off)
19
+ // 缺少调内移调能力的目标原样保留,例如固定打击音。
20
+ if (!note.transpose) {
21
+ result.push(note);
28
22
  continue;
29
- const duration = off.at.clone().sub(note.at);
30
- const bpm = context.stateAt(note.at).effectiveBpm;
23
+ }
24
+ const duration = note.end.clone().sub(note.start);
25
+ // 此处读取最终速度,结构延长和其他声部的速度效果都已计入。
26
+ const bpm = context.stateAt(note.start).effectiveBpm;
31
27
  const steps = pattern.repeat ? repeatToFill(pattern.body, duration.toNumber(), bpm) : pattern.body;
32
28
  const step = duration.div(steps.length);
33
- removed.add(note);
34
- removed.add(off);
29
+ // 用 Fraction 等分最终区间,保证首尾边界准确且不会积累浮点时间误差。
35
30
  for (let index = 0; index < steps.length; index++) {
36
31
  const offset = steps[index];
37
- const noteId = context.nextNoteId();
38
- const at = note.at.clone().add(step.clone().mul(index));
39
- const order = note.order + index / steps.length;
40
- const on = {
32
+ const start = step.clone().mul(index).add(note.start);
33
+ result.push({
41
34
  ...note,
42
- at,
43
- noteId,
44
- order,
35
+ start,
36
+ end: start.clone().add(step),
45
37
  // 本音保留主体的临时升降号,只有偏移音才走调内换算
46
38
  midi: offset === 0 ? note.midi : note.transpose(offset),
47
39
  // 后续 ornament 要从这个派生音继续移调,不能仍以最初的宿主为基准
48
40
  transpose: delta => note.transpose(offset + delta),
49
- origins: [...note.origins],
50
- sourceSpans: note.sourceSpans.map(span => ({ ...span })),
51
- };
52
- added.push(on, {
53
- ...off,
54
- at: at.clone().add(step),
55
- noteId,
56
- order,
57
- origins: [...off.origins],
58
41
  });
59
42
  }
60
43
  }
61
- return [...owned.filter(event => !removed.has(event)), ...added];
44
+ return result;
62
45
  };
63
46
  }
47
+ /** 按最终速度计算完整音型的重复次数,并限制总子音数 */
64
48
  function repeatToFill(body, duration, bpm) {
65
49
  // 名义密度与速度无关(秒数里的 bpm 与频率里的 bpm 恰好抵消),只在 bpm 越界时按比例修正
66
50
  const ratio = Math.min(MAX_BPM, Math.max(MIN_BPM, bpm)) / bpm;
51
+ // 预算按完整音型计算,避免在达到子音上限时留下半个音型。
67
52
  const limit = Math.floor(MAX_SUBNOTES / body.length);
68
53
  const cycles = Math.min(limit, Math.max(1, Math.round(duration * NOMINAL_RATE * ratio / body.length)));
69
54
  const result = [];
55
+ // 先得到完整音级序列,调用方再按实际子音总数统一分配宿主时值。
70
56
  for (let i = 0; i < cycles; i++)
71
57
  result.push(...body);
72
58
  return result;
@@ -14,11 +14,11 @@ export const accentSymbol = {
14
14
  style: { stroke: "#000", strokeWidth: 1 },
15
15
  },
16
16
  ],
17
- emitPlayback: emitter => emitter.affectFollowing((_context, events) => {
18
- for (const event of events) {
19
- if (event.kind === "note-on") {
20
- event.velocity = Math.min(MAX_VELOCITY, event.velocity + ACCENT_BOOST);
21
- }
17
+ /** 将重音登记为声音变换,保留音段的结构边界和系统速度 */
18
+ emitPlayback: emitter => emitter.affectFollowing((_context, notes) => {
19
+ // 前序装饰可能已拆出多个子音,逐个增加原有力度并限制到 MIDI 最大力度。
20
+ for (const note of notes) {
21
+ note.velocity = Math.min(MAX_VELOCITY, note.velocity + ACCENT_BOOST);
22
22
  }
23
23
  }),
24
24
  };
@@ -1,7 +1,10 @@
1
+ // 多声部常在同一时段各写一个延长记号;按区间并集减速一次,避免速度随记号数指数下降
2
+ const FERMATA_BPM_SCALE = {};
1
3
  export const fermataSymbol = {
2
4
  name: "fermata",
3
5
  description: "延长记号:覆盖区间速度减半,目标音实际时长翻倍",
4
6
  weight: 0.6,
7
+ paddingBottom: 3,
5
8
  shapes: [
6
9
  {
7
10
  path: [
@@ -17,8 +20,6 @@ export const fermataSymbol = {
17
20
  style: { fill: "#000" },
18
21
  },
19
22
  ],
20
- emitPlayback: emitter => {
21
- emitter.control(emitter.start, state => state.bpmScale.div(2));
22
- emitter.control(emitter.end, state => state.bpmScale.mul(2));
23
- },
23
+ /** 声明同 key 的减速区间,沿逻辑连接延续终点;范围不依赖实际子音的拆分结果 */
24
+ emitPlayback: emitter => emitter.scaleFollowingBpm(FERMATA_BPM_SCALE, 1, 2, { followConnections: true }),
24
25
  };
@@ -12,7 +12,7 @@ import type { Painter } from "../render/types.js";
12
12
  * 沿记谱顺序流动的时间状态
13
13
  *
14
14
  * 速度、力度、调性、音色是系统级字段:有确定的类型和初值,任何时刻都能直接读,不用写兼容分支。
15
- * 其余键由具体函数自行约定,核心不认识。
15
+ * 拍号仅在显式设置后有值;其余自定义键由具体函数约定,核心不认识。
16
16
  *
17
17
  * velocity 和 program 按音轨各自流动,新音轨继承分叉处父轨的值;其余键整篇共享。
18
18
  */
@@ -21,6 +21,8 @@ export interface TimeState {
21
21
  velocity: number;
22
22
  keySignature: string;
23
23
  program: number;
24
+ /** 当前小节时长(QN);尚无显式拍号或散板时为 undefined */
25
+ meter?: Fraction;
24
26
  [key: string]: any;
25
27
  }
26
28
  export declare const DEFAULT_BPM = 120;
@@ -69,14 +71,26 @@ export declare class TemporalNodeBase implements TimeLineEvent {
69
71
  layoutLine: number;
70
72
  /** 不可见状态事件保持 undefined */
71
73
  box?: LayoutBox;
74
+ /** 显式微调时才创建后置平移,折叠成员还会继承外层对象的平移 */
75
+ placementOffset?: LayoutPoint;
72
76
  /**
73
77
  * 横向弹簧布局参数
74
78
  * 大部分对象使用空对象即可采用布局器默认值
75
79
  */
76
80
  springConfig: HorizontalSpringConfig;
77
81
  /**
78
- * 关系函数可使用的命名局部坐标
79
- * prepareLayout 每次执行时由具体节点和装饰函数重新生成
82
+ * 装饰与关系函数使用的命名局部坐标,相对 box 左上角,每轮布局重建。
83
+ *
84
+ * 当前内置端口:
85
+ * - body.left / body.right:主体核心左右边界,供 div、tuplet、volta 使用;缺省为盒左右边界。
86
+ * - decoration.below:下方装饰排列起点(只读 y);缺省为正文 box.h。
87
+ * - shoulder:倚音的纵向定位基准(只读 y);音符提供数字顶边,缺省为盒顶。
88
+ * - tie.top:连音线端点;缺省为 anchor 与内容上沿,up 提供最上层成员的端点。
89
+ * - div.{level}.left / div.{level}.right:从 0 编号的减时线端点,由 div.place 发布,供 beam 接管。
90
+ * - dot:附点起点;缺省为盒右边界与 visualAxis,音符覆盖为字形附近的位置。
91
+ * - lyric:歌词对齐点(voice 只读 x);未提供则不作为歌词目标,note 在 finalizeLayout 发布。
92
+ *
93
+ * up、grace、arpeggio 转发宿主端口并换算局部坐标;端口不表达装饰是否存在。
80
94
  */
81
95
  ports: Record<string, LayoutPoint>;
82
96
  /**
@@ -89,8 +103,8 @@ export declare class TemporalNodeBase implements TimeLineEvent {
89
103
  * 1. layout 的 prepareLayoutHost 开始时创建或清空数组;
90
104
  * 2. Temporal.prepareLayout 可先加入节点自身的装饰,例如下八度点;
91
105
  * 3. 引擎再通过 addon 对应的 layoutDecorationHandler 加入函数装饰;
92
- * 4. arrangeBelowDecorations 按 below.order 分配主体下方空间并调用 below.place;
93
- * 5. 最终 paintLayout 在主体 paint 后依次调用 decoration.paint。
106
+ * 4. 引擎分别按 above/below.order 分配空间并调用 place
107
+ * 5. 最终 paintLayout 在主体 paint 后调用可选的 decoration.paint
94
108
  *
95
109
  * 数组必须保留到绘制结束,因为 decoration 通常以闭包保存本次测量得到的几何。它只属于当前 layout pass,不能跨 pass 复用。
96
110
  * prepare 阶段生成、place 后冻结、paint 后失效
@@ -103,9 +117,9 @@ export declare class TemporalNodeBase implements TimeLineEvent {
103
117
  protected initLayoutBox(): LayoutBox;
104
118
  /**
105
119
  * 时间状态 修改&冻结 入口
106
- * 调用时机在时间位置已经确定之后,处理“调性、速度、拍号”等时间信息的固化
120
+ * 当前列定位后固化状态;偏移仅支持非负值,整列取最大值累加到后续列
107
121
  */
108
- onTimeState?(state: TimeState): void;
122
+ onTimeState?(state: TimeState): Fraction | void;
109
123
  /** 把已固化的音乐语义声明为播放事件;不执行实时播放 */
110
124
  emitPlayback?(emitter: PlaybackEmitter): void;
111
125
  /** 给自己所在的时间列贴播放标记,供控制流游标查询 */
@@ -53,8 +53,18 @@ export class TemporalNodeBase {
53
53
  */
54
54
  springConfig;
55
55
  /**
56
- * 关系函数可使用的命名局部坐标
57
- * prepareLayout 每次执行时由具体节点和装饰函数重新生成
56
+ * 装饰与关系函数使用的命名局部坐标,相对 box 左上角,每轮布局重建。
57
+ *
58
+ * 当前内置端口:
59
+ * - body.left / body.right:主体核心左右边界,供 div、tuplet、volta 使用;缺省为盒左右边界。
60
+ * - decoration.below:下方装饰排列起点(只读 y);缺省为正文 box.h。
61
+ * - shoulder:倚音的纵向定位基准(只读 y);音符提供数字顶边,缺省为盒顶。
62
+ * - tie.top:连音线端点;缺省为 anchor 与内容上沿,up 提供最上层成员的端点。
63
+ * - div.{level}.left / div.{level}.right:从 0 编号的减时线端点,由 div.place 发布,供 beam 接管。
64
+ * - dot:附点起点;缺省为盒右边界与 visualAxis,音符覆盖为字形附近的位置。
65
+ * - lyric:歌词对齐点(voice 只读 x);未提供则不作为歌词目标,note 在 finalizeLayout 发布。
66
+ *
67
+ * up、grace、arpeggio 转发宿主端口并换算局部坐标;端口不表达装饰是否存在。
58
68
  */
59
69
  ports;
60
70
  /**
@@ -67,8 +77,8 @@ export class TemporalNodeBase {
67
77
  * 1. layout 的 prepareLayoutHost 开始时创建或清空数组;
68
78
  * 2. Temporal.prepareLayout 可先加入节点自身的装饰,例如下八度点;
69
79
  * 3. 引擎再通过 addon 对应的 layoutDecorationHandler 加入函数装饰;
70
- * 4. arrangeBelowDecorations 按 below.order 分配主体下方空间并调用 below.place;
71
- * 5. 最终 paintLayout 在主体 paint 后依次调用 decoration.paint。
80
+ * 4. 引擎分别按 above/below.order 分配空间并调用 place
81
+ * 5. 最终 paintLayout 在主体 paint 后调用可选的 decoration.paint
72
82
  *
73
83
  * 数组必须保留到绘制结束,因为 decoration 通常以闭包保存本次测量得到的几何。它只属于当前 layout pass,不能跨 pass 复用。
74
84
  * prepare 阶段生成、place 后冻结、paint 后失效
@@ -2,6 +2,7 @@ import { ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
3
  import { isVisualTemporalNode, } from "../temporal.js";
4
4
  import { pathBounds } from "../../layout/path.js";
5
+ import { getLayoutBounds } from "../../layout/engine.js";
5
6
  /** 三次贝塞尔控制点的抬高系数:两个控制点同高时,实际弧高恰好是抬高的 3/4 */
6
7
  const CUBIC_LIFT = 4 / 3;
7
8
  /** 弧带中部最大厚度与字号之比 */
@@ -14,26 +15,29 @@ class TieFunction extends ASTFunctionNode {
14
15
  ~~~jpfun
15
16
  1@a 2 3@b @tie(a, b, height=0.5em)
16
17
  ~~~
17
- - **位置参数**:端点标签,可传多个,按顺序连接;省略时查找最近的可连接对象
18
- - **height**:弧线高度,默认 \`0.5em\`
18
+ - **位置参数**:端点标签,可传多个,按顺序连接;省略时查找最近的可标记对象,包括增时线
19
+ - **height**:仅命名的弧线高度参数,默认 \`0.5em\`;可用 \`@set(tie.height=0.8em)\` 设置局部默认值,显式传参优先
19
20
 
20
- 同行端点用一条弧线连接,跨行时自动拆成多段`,
21
+ 同行端点用一条弧线连接,跨行时自动拆成多段。同轨同音且时间连续的音段建立播放连接,各段保留自己的装饰,例如 \`1 ^ $tr 1 @tie()\` 的后一音段不继承颤音。涉及增时线的连接仅绘制,不合并播放音符。`,
21
22
  allowExtraArgs: true,
22
23
  extraArgType: "label",
23
- args: []
24
+ args: [{
25
+ name: "height",
26
+ namedOnly: true,
27
+ description: "弧线高度,支持 px/em;em 相对调用处字号,负值按 0 处理",
28
+ type: "length",
29
+ default: { value: 0.5, unit: "em" },
30
+ }]
24
31
  };
25
32
  endPoints = [];
26
33
  height;
27
34
  constructor(sourceSpan, args, ctx, parent = null) {
28
35
  super(sourceSpan, parent);
29
- let height = ctx.variables.fontsize * 0.5;
36
+ // 命名选项统一解析默认值,位置参数仍全部作为端点
37
+ const [height] = this.getArgValue(args, ctx);
30
38
  for (const [key, value] of args) {
31
- if (key === "height") {
32
- const length = ctx.parseArgWithType(value.valueSpan, "length", sourceSpan.start);
33
- if (length)
34
- height = Math.max(0, ctx.length2px(length));
39
+ if (key === "height")
35
40
  continue;
36
- }
37
41
  const v = value instanceof ASTFunctionNode
38
42
  ? value
39
43
  : ctx.parseArgWithType(value.valueSpan, "label", sourceSpan.start);
@@ -50,7 +54,7 @@ class TieFunction extends ASTFunctionNode {
50
54
  }
51
55
  if (this.endPoints.length < 2)
52
56
  throw new ErrorDiagnostic("E_NOT_ENOUGH_ARGS", "@tie 连音线需要至少两个端点", sourceSpan);
53
- this.height = height;
57
+ this.height = Math.max(0, ctx.length2px(height));
54
58
  }
55
59
  /**
56
60
  * tie 不推进时间
@@ -72,7 +76,10 @@ class TieFunction extends ASTFunctionNode {
72
76
  return [];
73
77
  }
74
78
  toString(source) {
75
- return `@tie(${this.endPoints.map(p => `${p.label ?? 'anon'}:[${p.toString(source)}]`).join(", ")})`;
79
+ const labels = this.endPoints.map(endpoint => endpoint.label);
80
+ if (labels.some(label => label === undefined))
81
+ return source.slice(this.sourceSpan.start, this.sourceSpan.end);
82
+ return `@tie(${labels.join(", ")}, height=${this.height}px)`;
76
83
  }
77
84
  }
78
85
  export const TieNode = TieFunction;
@@ -91,39 +98,26 @@ class TieLayoutAttachment {
91
98
  this.thickness = Math.max(1.2, size * THICKNESS_RATIO);
92
99
  }
93
100
  /**
94
- * 只有同轨、同音、演奏时间连续的事件对才合并,其余 tie 纯视觉
95
- *
96
- * 反复会让同一个端点产生多个事件对,所以按首端点的每一个 NoteOn 各串一条链。
101
+ * 为同轨、同音且时间相接的逻辑音段建立连接,各次反复及各段装饰保持独立
102
+ * 此时只匹配来源和逻辑音高,实际子音是否能合并由声音展开后的核心处理
97
103
  */
98
104
  applyPlayback(context) {
99
- const noteOns = () => context.events
100
- .filter((event) => event.kind === "note-on");
101
- const noteOff = (noteId) => context.events
102
- .find((event) => event.kind === "note-off" && event.noteId === noteId);
103
- for (const head of noteOns().filter(note => note.origins.some(origin => origin.node === this.endPoints[0]))) {
104
- for (let i = 1; i < this.endPoints.length; i++) {
105
- const end = noteOff(head.noteId);
106
- if (!end)
107
- break;
108
- const next = noteOns().find(note => note.noteId !== head.noteId
109
- && note.origins.some(origin => origin.node === this.endPoints[i])
110
- && note.track === head.track
111
- && note.midi === head.midi
112
- && note.percussion === head.percussion
113
- && end.at.equals(note.at));
105
+ // 整体端点可能包含和弦多个成员或多遍访问,每个首段分别寻找自己的连接链。
106
+ for (const head of context.notes.filter(note => note.origins.some(origin => origin.node === this.endPoints[0]))) {
107
+ let previous = head;
108
+ // 按显式端点顺序延续;某一端点没有相接音段就停止,不能跨过缺口连接。
109
+ for (let index = 1; index < this.endPoints.length; index++) {
110
+ // connect 同时认领候选:配对冲突时继续找其他成员,重复声明可复用原配对。
111
+ const next = context.notes.find(note => note !== previous
112
+ && note.origins.some(origin => origin.node === this.endPoints[index])
113
+ && note.track === previous.track
114
+ && note.midi === previous.midi
115
+ && note.percussion === previous.percussion
116
+ && previous.end.equals(note.start)
117
+ && context.connect(previous, note));
114
118
  if (!next)
115
119
  break;
116
- const nextOff = noteOff(next.noteId);
117
- if (!nextOff)
118
- break;
119
- head.sourceSpans.push(...next.sourceSpans);
120
- for (const origin of next.origins) {
121
- if (!head.origins.includes(origin))
122
- head.origins.push(origin);
123
- }
124
- nextOff.noteId = head.noteId;
125
- nextOff.origins = [...head.origins];
126
- context.events.splice(0, context.events.length, ...context.events.filter(event => event !== end && event !== next));
120
+ previous = next;
127
121
  }
128
122
  }
129
123
  }
@@ -167,7 +161,7 @@ class TieLayoutAttachment {
167
161
  }
168
162
  return {
169
163
  x: node.box.x + node.box.anchor,
170
- y: node.box.y,
164
+ y: getLayoutBounds(node, true).y,
171
165
  };
172
166
  }
173
167
  /** 根据端点固化后的行号选择同行弧线或跨行分段 */