jpfun 0.6.0 → 0.8.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 (134) hide show
  1. package/Bravura-LICENSE.txt +93 -0
  2. package/README.md +49 -146
  3. package/dist/Bravura-LICENSE.txt +93 -0
  4. package/dist/converter/midi/convert.d.ts +3 -11
  5. package/dist/converter/midi/convert.js +89 -67
  6. package/dist/converter/musicxml/features.d.ts +34 -12
  7. package/dist/converter/musicxml/features.js +131 -24
  8. package/dist/converter/musicxml/index.js +221 -54
  9. package/dist/converter/musicxml/model.d.ts +24 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/diagnostic.d.ts +7 -1
  13. package/dist/diagnostic.js +40 -88
  14. package/dist/fraction.js +3 -2
  15. package/dist/functions/ASTtypes.d.ts +2 -18
  16. package/dist/functions/ASTtypes.js +0 -16
  17. package/dist/functions/arpeggio/index.js +17 -22
  18. package/dist/functions/arpeggio/shape.d.ts +1 -1
  19. package/dist/functions/arpeggio/shape.js +27 -21
  20. package/dist/functions/bar/index.d.ts +8 -0
  21. package/dist/functions/bar/index.js +139 -36
  22. package/dist/functions/beam/auto.d.ts +1 -2
  23. package/dist/functions/beam/auto.js +44 -27
  24. package/dist/functions/beam/index.js +2 -3
  25. package/dist/functions/beam/layout.d.ts +1 -1
  26. package/dist/functions/beam/layout.js +16 -24
  27. package/dist/functions/br/index.d.ts +34 -2
  28. package/dist/functions/br/index.js +8 -8
  29. package/dist/functions/dash/index.js +6 -6
  30. package/dist/functions/default.js +10 -5
  31. package/dist/functions/div/index.d.ts +1 -0
  32. package/dist/functions/div/index.js +8 -4
  33. package/dist/functions/dot/index.js +2 -2
  34. package/dist/functions/dyn/index.js +49 -31
  35. package/dist/functions/gliss/index.d.ts +2 -0
  36. package/dist/functions/gliss/index.js +202 -0
  37. package/dist/functions/grace/index.d.ts +1 -7
  38. package/dist/functions/grace/index.js +11 -19
  39. package/dist/functions/head/index.js +41 -60
  40. package/dist/functions/key/index.js +8 -10
  41. package/dist/functions/meter/index.d.ts +56 -1
  42. package/dist/functions/meter/index.js +30 -24
  43. package/dist/functions/note/accidentals.js +10 -16
  44. package/dist/functions/note/index.js +18 -8
  45. package/dist/functions/note/noteName.d.ts +16 -0
  46. package/dist/functions/note/noteName.js +88 -0
  47. package/dist/functions/note/source-transform.js +6 -5
  48. package/dist/functions/ottava/index.d.ts +2 -0
  49. package/dist/functions/ottava/index.js +233 -0
  50. package/dist/functions/page/index.d.ts +1 -0
  51. package/dist/functions/page/index.js +22 -13
  52. package/dist/functions/pagebreak/index.d.ts +2 -0
  53. package/dist/functions/pagebreak/index.js +36 -0
  54. package/dist/functions/rest/index.js +15 -15
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.d.ts +2 -0
  57. package/dist/functions/slide/index.js +132 -0
  58. package/dist/functions/stack/index.js +8 -15
  59. package/dist/functions/symbol/index.d.ts +30 -2
  60. package/dist/functions/symbol/index.js +93 -19
  61. package/dist/functions/symbol/ornament.d.ts +1 -2
  62. package/dist/functions/symbol/ornament.js +14 -19
  63. package/dist/functions/symbol/shape.d.ts +6 -0
  64. package/dist/functions/symbol/shape.js +20 -4
  65. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  66. package/dist/functions/symbol/symbols/coda.js +56 -0
  67. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  68. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  69. package/dist/functions/symbol/symbols/fine.js +1 -1
  70. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  72. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/marcato.js +22 -0
  74. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  75. package/dist/functions/symbol/symbols/staccato.js +24 -0
  76. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  78. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  79. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  80. package/dist/functions/symbol/symbols/tr.js +46 -1
  81. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  82. package/dist/functions/symbol/symbols/turn.js +50 -0
  83. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  84. package/dist/functions/symbol/symbols/wheel.js +36 -0
  85. package/dist/functions/temporal.d.ts +17 -6
  86. package/dist/functions/temporal.js +17 -6
  87. package/dist/functions/text/index.js +15 -6
  88. package/dist/functions/tie/index.js +64 -30
  89. package/dist/functions/tremolo/index.d.ts +2 -0
  90. package/dist/functions/tremolo/index.js +319 -0
  91. package/dist/functions/tuplet/index.js +4 -8
  92. package/dist/functions/up/index.js +7 -9
  93. package/dist/functions/voice/connections.js +7 -5
  94. package/dist/functions/voice/index.js +19 -11
  95. package/dist/functions/volta/index.js +41 -21
  96. package/dist/jpfun.core.min.js +64 -80
  97. package/dist/jpfun.from-midi.min.js +5 -5
  98. package/dist/jpfun.from-musicxml.min.js +8 -8
  99. package/dist/jpfun.min.js +69 -85
  100. package/dist/layout/default.d.ts +0 -1
  101. package/dist/layout/default.js +0 -1
  102. package/dist/layout/engine.d.ts +1 -0
  103. package/dist/layout/engine.js +42 -11
  104. package/dist/layout/page.d.ts +3 -2
  105. package/dist/layout/page.js +6 -5
  106. package/dist/layout/types.d.ts +4 -0
  107. package/dist/lowering/loweringContext.d.ts +11 -13
  108. package/dist/lowering/loweringContext.js +30 -197
  109. package/dist/lowering/types.d.ts +1 -3
  110. package/dist/parser/parse-utils/note-utils.d.ts +1 -1
  111. package/dist/parser/parse-utils/note-utils.js +8 -9
  112. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  113. package/dist/parser/parse-utils/string-utils.js +16 -3
  114. package/dist/parser/parserContext.d.ts +2 -0
  115. package/dist/parser/parserContext.js +36 -8
  116. package/dist/pipeline.js +0 -1
  117. package/dist/playback/compile.js +131 -72
  118. package/dist/playback/event.d.ts +1 -1
  119. package/dist/playback/event.js +9 -9
  120. package/dist/playback/time.js +42 -31
  121. package/dist/playback/types.d.ts +7 -3
  122. package/dist/render/canvas.d.ts +2 -0
  123. package/dist/render/canvas.js +25 -22
  124. package/dist/render/recording.js +1 -4
  125. package/dist/render/svg.js +1 -0
  126. package/dist/render/text.d.ts +1 -1
  127. package/dist/render/text.js +3 -2
  128. package/dist/render/translate.d.ts +0 -1
  129. package/dist/render/translate.js +6 -23
  130. package/dist/render/types.d.ts +1 -0
  131. package/grammar.md +52 -25
  132. package/package.json +3 -3
  133. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  134. package/dist/functions/note/noteNameFSM.js +0 -181
@@ -8,36 +8,41 @@ import { DivNode } from "./div/index.js";
8
8
  import { DotNode } from "./dot/index.js";
9
9
  import { DynNode } from "./dyn/index.js";
10
10
  import { GraceNode } from "./grace/index.js";
11
+ import { GlissNode } from "./gliss/index.js";
12
+ import { SlideNode } from "./slide/index.js";
11
13
  import { HeadNode } from "./head/index.js";
12
14
  import { KeyNode } from "./key/index.js";
13
15
  import { MeterNode } from "./meter/index.js";
14
16
  import { BrNode } from "./br/index.js";
15
17
  import { NoteNode } from "./note/index.js";
18
+ import { OttavaNode } from "./ottava/index.js";
16
19
  import { RestNode } from "./rest/index.js";
17
20
  import { UpNode, DownNode } from "./up/index.js";
18
21
  import { PageNode } from "./page/index.js";
22
+ import { PageBreakNode } from "./pagebreak/index.js";
19
23
  import { ProgramNode } from "./program/index.js";
20
24
  import { StackNode } from "./stack/index.js";
21
25
  import { SymbolNode } from "./symbol/index.js";
22
26
  import { SetNode } from "./set/index.js";
23
27
  import { TempoNode } from "./tempo/index.js";
24
28
  import { TextNode } from "./text/index.js";
29
+ import { TremoloNode } from "./tremolo/index.js";
25
30
  import { VoltaNode } from "./volta/index.js";
26
31
  import { TieNode } from "./tie/index.js";
27
32
  import { TupletNode } from "./tuplet/index.js";
28
33
  import { VoiceNode, VoicesNode } from "./voice/index.js";
29
34
  export const defaultFunctions = [
30
35
  NoteNode, DashNode, RestNode, BarNode,
31
- DivNode, DotNode, TupletNode, // 装饰性
36
+ DivNode, DotNode, TupletNode, TremoloNode, // 装饰性
32
37
  VoiceNode, VoicesNode, // 歌词和声部
33
- BrNode, // 排版
38
+ BrNode, PageBreakNode, // 排版
34
39
  PageNode, HeadNode, // 文档页面与谱头
35
40
  StackNode, // 时间同步
36
41
  UpNode, DownNode,
37
42
  ArpeggioNode,
38
- GraceNode, // 倚音
39
- TieNode, BeamNode, DynNode,
40
- BoxNode, VoltaNode,
43
+ GraceNode, SlideNode, // 倚音与滑入滑出
44
+ TieNode, BeamNode, GlissNode, DynNode,
45
+ BoxNode, VoltaNode, OttavaNode,
41
46
  AdjustNode, // 手工微调
42
47
  SetNode, KeyNode, MeterNode, TempoNode, ProgramNode, // 设置
43
48
  TextNode, SymbolNode,
@@ -53,6 +53,7 @@ declare class DivFunction extends ASTFunctionNode {
53
53
  static layoutDecorationHandler: LayoutDecorationHandler;
54
54
  loweringEnter(ctx: LoweringContext): never[];
55
55
  loweringExit(ctx: LoweringContext): never[];
56
+ private static loweringFinalize;
56
57
  content: ASTNodeBase;
57
58
  n: number;
58
59
  /** parse 时冻结;只控制不同 div 之间的自动连接,不影响当前 div 内部连接 */
@@ -1,5 +1,6 @@
1
1
  import { ASTFunctionNode, functionAddonKey } from "../ASTtypes.js";
2
2
  import { WarningDiagnostic } from "../../diagnostic.js";
3
+ import { createAutomaticBeamAttachments } from "../beam/auto.js";
3
4
  const DIV_FUNC_NAME = "div";
4
5
  export const DIV_ADDON_KEY = functionAddonKey(DIV_FUNC_NAME);
5
6
  /** div 暴露自己的线段端口,不依赖任何关系函数 */
@@ -174,10 +175,11 @@ class DivFunction extends ASTFunctionNode {
174
175
  };
175
176
  loweringEnter(ctx) {
176
177
  const count = this.n;
178
+ if (count === 0)
179
+ return [];
180
+ ctx.deferFinalize(DivFunction.loweringFinalize, -5);
177
181
  ctx.beginLoweringGroup(this, {
178
182
  onTemporal(node) {
179
- if (count === 0)
180
- return;
181
183
  const addon = node.addon ??= {};
182
184
  addon[DIV_ADDON_KEY] = (Number(addon[DIV_ADDON_KEY]) || 0) + count;
183
185
  node.T.divPow2(count);
@@ -186,9 +188,11 @@ class DivFunction extends ASTFunctionNode {
186
188
  return [];
187
189
  }
188
190
  loweringExit(ctx) {
189
- ctx.endLoweringGroup(this);
191
+ if (this.n > 0)
192
+ ctx.endLoweringGroup(this);
190
193
  return [];
191
194
  }
195
+ static loweringFinalize = createAutomaticBeamAttachments;
192
196
  content;
193
197
  n;
194
198
  /** parse 时冻结;只控制不同 div 之间的自动连接,不影响当前 div 内部连接 */
@@ -207,7 +211,7 @@ class DivFunction extends ASTFunctionNode {
207
211
  this.content.parent = this;
208
212
  const n = Math.max(0, Math.trunc(this.n));
209
213
  if (n !== this.n) {
210
- ctx.diagnostics.push(new WarningDiagnostic("W_DIV_INVALID_N", `@div 的数量参数 n 必须为非负整数,已被修正为 ${n}`, this.sourceSpan));
214
+ ctx.diagnostics.push(new WarningDiagnostic("W_DIV_INVALID_N", "@div 的数量参数 n 必须为非负整数,已被修正为 {n}", this.sourceSpan, { n }));
211
215
  this.n = n;
212
216
  }
213
217
  }
@@ -130,7 +130,7 @@ class DotFunction extends ASTFunctionNode {
130
130
  loweringExit(ctx) {
131
131
  const group = ctx.endLoweringGroup(this);
132
132
  if (group.temporalCount !== 1) {
133
- throw new ErrorDiagnostic("E_DOT_INVALID_CONTENT", `函数 @dot 只能接收 1个元素,但找到了 ${group.temporalCount} 个`, this.sourceSpan);
133
+ throw new ErrorDiagnostic("E_DOT_INVALID_CONTENT", "函数 @dot 只能接收 1个元素,但找到了 {count} 个", this.sourceSpan, { count: group.temporalCount });
134
134
  }
135
135
  return [];
136
136
  }
@@ -149,7 +149,7 @@ class DotFunction extends ASTFunctionNode {
149
149
  this.content.parent = this;
150
150
  const n = Math.max(0, Math.trunc(this.n));
151
151
  if (n !== this.n) {
152
- ctx.diagnostics.push(new WarningDiagnostic("W_DOT_INVALID_N", `@dot 的数量参数 n 必须为非负整数,已被修正为 ${n}`, this.sourceSpan));
152
+ ctx.diagnostics.push(new WarningDiagnostic("W_DOT_INVALID_N", "@dot 的数量参数 n 必须为非负整数,已被修正为 {n}", this.sourceSpan, { n }));
153
153
  this.n = n;
154
154
  }
155
155
  }
@@ -1,6 +1,19 @@
1
1
  import { Diagnostic, ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
2
  import { isVisualTemporalNode, } from "../temporal.js";
3
3
  import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ function findRecordBoundary(records, time, after = false) {
5
+ let low = 0;
6
+ let high = records.length;
7
+ while (low < high) {
8
+ const middle = (low + high) >>> 1;
9
+ const cmp = records[middle].host.t.compare(time);
10
+ if (after ? cmp <= 0 : cmp < 0)
11
+ low = middle + 1;
12
+ else
13
+ high = middle;
14
+ }
15
+ return low;
16
+ }
4
17
  class DynFunction extends ASTFunctionNode {
5
18
  static def = {
6
19
  name: ["dyn"],
@@ -20,12 +33,12 @@ class DynFunction extends ASTFunctionNode {
20
33
  { name: "dv", description: "力度变化量,正数渐强,负数渐弱", type: "number", default: null },
21
34
  ],
22
35
  };
23
- static loweringFinalize = (result) => {
36
+ static loweringFinalize(result) {
24
37
  const dynamics = result.attachments.filter((attachment) => attachment instanceof DynAttachment);
25
38
  if (dynamics.length === 0)
26
39
  return;
27
- // astToTemporal 包含不进入全局 columns 的和弦、倚音成员;host 只用于统一时间和音轨
28
- const records = [];
40
+ // 仅收集存在 @dyn 的音轨上的记录,避免无关声部也分配包装对象与排序
41
+ const recordsByTrack = new Map(dynamics.map(d => [d.track, []]));
29
42
  for (const nodes of result.astToTemporal.values()) {
30
43
  for (const node of nodes) {
31
44
  const velocity = node.playbackState?.velocity;
@@ -34,48 +47,52 @@ class DynFunction extends ASTFunctionNode {
34
47
  let host = node;
35
48
  while (host.foldedInto)
36
49
  host = host.foldedInto;
37
- records.push({ node, host, velocity, increment: 0 });
50
+ recordsByTrack.get(host.track)?.push({ node, host, velocity, increment: 0 });
38
51
  }
39
52
  }
40
- records.sort((left, right) => left.host.t.compare(right.host.t) || left.node.order - right.node.order);
53
+ for (const list of recordsByTrack.values()) {
54
+ list.sort((left, right) => left.host.t.compare(right.host.t) || left.node.order - right.node.order);
55
+ }
41
56
  // 先累计全部 dyn 的贡献,最后统一写回,避免声明顺序改变后续 dyn 读取的原始力度
42
57
  for (const dynamic of dynamics) {
43
- let endVelocity = dynamic.end.playbackState?.velocity
44
- ?? records.find(record => record.host === dynamic.toHost)?.velocity;
45
- for (let index = records.length - 1; endVelocity === undefined && index >= 0; index--) {
46
- const record = records[index];
47
- if (record.host.track === dynamic.track && record.host.t.compare(dynamic.toHost.t) <= 0) {
48
- endVelocity = record.velocity;
49
- }
58
+ const records = recordsByTrack.get(dynamic.track);
59
+ const endStart = findRecordBoundary(records, dynamic.toHost.t);
60
+ const afterEnd = findRecordBoundary(records, dynamic.toHost.t, true);
61
+ let endVelocity = dynamic.end.playbackState?.velocity;
62
+ for (let i = endStart; endVelocity === undefined && i < afterEnd; i++) {
63
+ if (records[i].host === dynamic.toHost)
64
+ endVelocity = records[i].velocity;
50
65
  }
66
+ endVelocity ??= records[afterEnd - 1]?.velocity;
51
67
  if (endVelocity === undefined) {
52
68
  result.diagnostics.push(new WarningDiagnostic("W_DYN_NO_VELOCITY", "@dyn 终点及此前同轨没有可用的力度基准,仅绘制渐变线", dynamic.sourceSpan));
53
69
  continue;
54
70
  }
55
71
  // 终点后保持完整增量,直到原始力度相对终点再次发生变化
56
- const stop = records.find(record => record.host.track === dynamic.track
57
- && record.host.t.compare(dynamic.toHost.t) > 0
58
- && record.velocity !== endVelocity)?.host.t;
72
+ let stopIndex = records.length;
73
+ for (let i = afterEnd; i < records.length; i++) {
74
+ if (records[i].velocity !== endVelocity) {
75
+ stopIndex = findRecordBoundary(records, records[i].host.t);
76
+ break;
77
+ }
78
+ }
79
+ const startIndex = findRecordBoundary(records, dynamic.fromHost.t);
59
80
  const duration = dynamic.toHost.t.clone().sub(dynamic.fromHost.t);
81
+ for (let i = startIndex; i < stopIndex; i++) {
82
+ const progress = i >= endStart ? 1
83
+ : records[i].host.t.clone().sub(dynamic.fromHost.t).div(duration).toNumber();
84
+ records[i].increment += dynamic.dv * progress;
85
+ }
86
+ }
87
+ for (const records of recordsByTrack.values()) {
60
88
  for (const record of records) {
61
- if (record.host.track !== dynamic.track)
62
- continue;
63
- const fromStart = record.host.t.compare(dynamic.fromHost.t);
64
- if (fromStart < 0 || (stop && record.host.t.compare(stop) >= 0))
89
+ if (record.increment === 0)
65
90
  continue;
66
- const progress = record.host.t.compare(dynamic.toHost.t) >= 0
67
- ? 1
68
- : record.host.t.clone().sub(dynamic.fromHost.t).div(duration).toNumber();
69
- record.increment += dynamic.dv * progress;
91
+ const velocity = Math.max(1, Math.min(127, record.velocity + record.increment));
92
+ record.node.playbackState = { ...record.node.playbackState, velocity };
70
93
  }
71
94
  }
72
- for (const record of records) {
73
- if (record.increment === 0)
74
- continue;
75
- const velocity = Math.max(1, Math.min(127, record.velocity + record.increment));
76
- record.node.playbackState = { ...record.node.playbackState, velocity };
77
- }
78
- };
95
+ }
79
96
  from;
80
97
  to;
81
98
  dv;
@@ -109,6 +126,7 @@ class DynFunction extends ASTFunctionNode {
109
126
  else {
110
127
  ctx.addAttachment(new DynAttachment(this, from, toHost, fromHost));
111
128
  }
129
+ ctx.deferFinalize(DynFunction.loweringFinalize);
112
130
  return [];
113
131
  }
114
132
  constructor(span, args, ctx, parent = null) {
@@ -120,7 +138,7 @@ class DynFunction extends ASTFunctionNode {
120
138
  }
121
139
  dv = Math.max(-127, Math.min(127, dv));
122
140
  if (dv !== inputDv) {
123
- ctx.diagnostics.push(new WarningDiagnostic("W_DYN_DELTA_CLAMPED", `@dyn 的 dv 必须在 -127 到 127 之间,已被限制为 ${dv}`, span));
141
+ ctx.diagnostics.push(new WarningDiagnostic("W_DYN_DELTA_CLAMPED", "@dyn 的 dv 必须在 -127 到 127 之间,已被限制为 {dv}", span, { dv }));
124
142
  }
125
143
  this.from = from;
126
144
  this.to = to;
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const GlissNode: ASTFunctionClass;
@@ -0,0 +1,202 @@
1
+ import { ErrorDiagnostic, WarningDiagnostic } from "../../diagnostic.js";
2
+ import { pathBounds } from "../../layout/path.js";
3
+ import { ASTFunctionNode, } from "../ASTtypes.js";
4
+ import { isVisualTemporalNode } from "../temporal.js";
5
+ // gliss 判断音高的准则是 resolvedMidi 属性
6
+ function pitchOf(node) {
7
+ const { resolvedMidi } = node;
8
+ return typeof resolvedMidi === "number" ? resolvedMidi : undefined;
9
+ }
10
+ function findPitchNode(columns, node) {
11
+ if ("resolvedMidi" in node)
12
+ return pitchOf(node) !== undefined ? node : undefined;
13
+ const host = layoutHost(node);
14
+ for (let i = columns.findIndex(col => col.includes(host)) - 1; i >= 0; i--) {
15
+ const previous = columns[i].find(item => item.track === host.track && "resolvedMidi" in item);
16
+ if (previous)
17
+ return pitchOf(previous) !== undefined ? previous : undefined;
18
+ }
19
+ }
20
+ class GlissFunction extends ASTFunctionNode {
21
+ static def = {
22
+ name: ["gliss"],
23
+ description: "滑音连线",
24
+ details: `\
25
+ ~~~jpfun
26
+ 1 -@a 5@b @gliss(a, b)
27
+ ~~~
28
+ 若附属对象无音高,将使用前面最近的同轨有音高对象的音高;播放时从起点音段按半音阶离散过渡至终点音高。`,
29
+ allowExtraArgs: false,
30
+ args: [
31
+ {
32
+ type: "label",
33
+ default: null,
34
+ description: "一个端点的标签,先后按谱面时间确定"
35
+ },
36
+ {
37
+ type: "label",
38
+ default: null,
39
+ description: "另一个端点的标签"
40
+ },
41
+ ],
42
+ };
43
+ from;
44
+ to;
45
+ constructor(span, args, ctx, parent = null) {
46
+ super(span, parent);
47
+ [this.from, this.to] = this.getArgValue(args, ctx);
48
+ }
49
+ loweringEnter(ctx) {
50
+ const from = ctx.getTemporalNodes(this.from).at(-1);
51
+ const to = ctx.getTemporalNodes(this.to).at(-1);
52
+ if (!from || !to || !isVisualTemporalNode(from) || !isVisualTemporalNode(to)) {
53
+ throw new ErrorDiagnostic("E_GLISS_ENDPOINT", "@gliss 的标签必须指向已生成且具有排版盒子的对象", this.sourceSpan);
54
+ }
55
+ const attachment = new GlissAttachment(from, to, this.sourceSpan);
56
+ ctx.addAttachment(attachment);
57
+ ctx.deferFinalize(result => attachment.finalize(result), 1);
58
+ return [];
59
+ }
60
+ toString(source) {
61
+ const from = this.from instanceof ASTFunctionNode ? this.from.label : undefined;
62
+ const to = this.to instanceof ASTFunctionNode ? this.to.label : undefined;
63
+ return from && to ? `@gliss(${from}, ${to})` : source.slice(this.sourceSpan.start, this.sourceSpan.end);
64
+ }
65
+ }
66
+ export const GlissNode = GlissFunction;
67
+ function layoutHost(node, line) {
68
+ while (node.foldedInto && isVisualTemporalNode(node.foldedInto) && (!line || line.columnOf(node) < 0)) {
69
+ node = node.foldedInto;
70
+ }
71
+ return node;
72
+ }
73
+ class GlissAttachment {
74
+ sourceSpan;
75
+ layer = "foreground";
76
+ endPoints;
77
+ direction;
78
+ constructor(from, to, sourceSpan) {
79
+ this.sourceSpan = sourceSpan;
80
+ this.endPoints = [from, to];
81
+ }
82
+ finalize({ columns, diagnostics }) {
83
+ const [a, b] = this.endPoints;
84
+ const fromHost = layoutHost(a);
85
+ const toHost = layoutHost(b);
86
+ if (fromHost.t.equals(toHost.t)) {
87
+ throw new ErrorDiagnostic("E_GLISS_ORDER", "@gliss 两个端点不能位于同一时刻", this.sourceSpan);
88
+ }
89
+ if (fromHost.layoutLine !== toHost.layoutLine) {
90
+ throw new ErrorDiagnostic("E_GLISS_CROSS_LINE", "@gliss 不支持跨谱面行", this.sourceSpan);
91
+ }
92
+ if (fromHost.t.compare(toHost.t) > 0)
93
+ this.endPoints = [b, a];
94
+ const [endpoint, target] = this.endPoints;
95
+ const sourcePitchNode = findPitchNode(columns, endpoint);
96
+ const targetPitchNode = findPitchNode(columns, target);
97
+ if (!sourcePitchNode || !targetPitchNode) {
98
+ diagnostics.push(new WarningDiagnostic("W_GLISS_NO_PITCH", "@gliss 端点没有可用音高", this.sourceSpan));
99
+ return;
100
+ }
101
+ this.direction = Math.sign(pitchOf(targetPitchNode) - pitchOf(sourcePitchNode));
102
+ const emit = endpoint.emitPlayback;
103
+ const targetMidi = pitchOf(targetPitchNode) + (targetPitchNode.playbackState?.pitchShift ?? 0);
104
+ endpoint.emitPlayback = emitter => {
105
+ emit?.call(endpoint, emitter);
106
+ const { start: glissStart, end: glissEnd } = emitter;
107
+ emitter.defer(context => {
108
+ for (let i = context.notes.length - 1; i >= 0; i--) {
109
+ const note = context.notes[i];
110
+ if (note.track !== emitter.track)
111
+ continue;
112
+ if (note.end.equals(glissEnd)) {
113
+ context.transform(note, (_ctx, owned) => {
114
+ const item = owned.at(-1);
115
+ const startFrom = glissStart.compare(item.start) > 0 ? glissStart : item.start;
116
+ const fromMidi = item.midi;
117
+ const steps = Math.abs(targetMidi - fromMidi);
118
+ if (item.end.compare(startFrom) <= 0 || steps <= 1)
119
+ return;
120
+ const dir = targetMidi > fromMidi ? 1 : -1;
121
+ const step = item.end.clone().sub(startFrom).div(steps);
122
+ const out = owned.slice(0, -1);
123
+ for (let k = 0; k < steps; k++) {
124
+ out.push({
125
+ ...item,
126
+ start: k === 0 ? item.start.clone() : step.clone().mul(k).add(startFrom),
127
+ end: step.clone().mul(k + 1).add(startFrom),
128
+ midi: fromMidi + k * dir,
129
+ });
130
+ }
131
+ return out;
132
+ });
133
+ }
134
+ break;
135
+ }
136
+ });
137
+ };
138
+ }
139
+ /** 定位端点所在时间列,并为箭头登记水平留白 */
140
+ prepareHorizontal(lines) {
141
+ const [endpoint, target] = this.endPoints;
142
+ const line = lines[endpoint.layoutLine];
143
+ const from = line && layoutHost(endpoint, line);
144
+ const to = line && layoutHost(target, line);
145
+ const start = from ? line.columnOf(from) : -1;
146
+ const end = to ? line.columnOf(to) : -1;
147
+ if (!line || start < 0 || end <= start) {
148
+ throw new ErrorDiagnostic("E_GLISS_DOMAIN", "@gliss 的端点必须位于同一排版域的不同时间列", this.sourceSpan);
149
+ }
150
+ const right = from.box.w - from.box.anchor + Math.max(endpoint.ast.size, target.ast.size) * 1.4;
151
+ // 只扩张求解器占位,不改变端点图形、附点位置或下一轮的 box
152
+ line.registerHorizontalLayoutHook(from, to, ({ columns }) => {
153
+ // 留白作用于起点整列;取最大值,避免多条关系重复累加占位。
154
+ for (const element of columns[start])
155
+ element.WR = Math.max(element.WR, right);
156
+ });
157
+ }
158
+ createGeometry() {
159
+ const [from, to] = this.endPoints;
160
+ const size = Math.max(from.ast.size, to.ast.size);
161
+ const gap = size * 0.12;
162
+ const start = { x: from.box.x + from.box.w + gap, y: from.box.y + from.box.visualAxis };
163
+ const end = { x: to.box.x - gap, y: to.box.y + to.box.visualAxis };
164
+ if (from.track === to.track) {
165
+ if (this.direction === undefined) {
166
+ end.y = start.y;
167
+ }
168
+ else {
169
+ start.y += this.direction * size * 0.24;
170
+ end.y -= this.direction * size * 0.24;
171
+ }
172
+ }
173
+ if (end.x <= start.x) {
174
+ throw new ErrorDiagnostic("E_GLISS_SPACE", "@gliss 的端点之间没有可用的水平绘制空间", this.sourceSpan);
175
+ }
176
+ const angle = Math.atan2(end.y - start.y, end.x - start.x);
177
+ const length = Math.min(size * 0.3, Math.hypot(end.x - start.x, end.y - start.y) * 0.35);
178
+ const wing = (offset) => ({
179
+ x: end.x - length * Math.cos(angle + offset),
180
+ y: end.y - length * Math.sin(angle + offset),
181
+ });
182
+ const commands = [
183
+ { op: "M", ...start }, { op: "L", ...end },
184
+ { op: "M", ...wing(-Math.PI / 6) }, { op: "L", ...end },
185
+ { op: "L", ...wing(Math.PI / 6) },
186
+ ];
187
+ const strokeWidth = size * 0.05;
188
+ const bounds = pathBounds(commands);
189
+ const region = {
190
+ x: bounds.x - strokeWidth / 2, y: bounds.y - strokeWidth / 2,
191
+ w: bounds.w + strokeWidth, h: bounds.h + strokeWidth,
192
+ };
193
+ return {
194
+ regions: [{ ...region, line: from.layoutLine, track: from.track }],
195
+ // 跨轨连线不把整段高度算到起点轨,否则纵向求解会反复撑开两轨
196
+ occupancy: from.track === to.track ? [{ ...region, line: from.layoutLine, track: from.track }] : [],
197
+ paint: (painter) => {
198
+ painter.drawPath(commands, { fill: "none", stroke: "#000", strokeWidth });
199
+ },
200
+ };
201
+ }
202
+ }
@@ -67,13 +67,7 @@ export declare class GraceTemporal extends TemporalNodeBase {
67
67
  /** 成员共享全局时间状态,按发声顺序固化 */
68
68
  onTimeState(state: TimeState): void | Fraction;
69
69
  prepareHorizontal(line: HorizontalLineView): void;
70
- /**
71
- * 播放时倚音从宿主借走的时值(前倚音从开头、后倚音从末尾)
72
- *
73
- * 比例 = 倚音块字面时长 / 四分音符,而四分音符 T=1,所以直接取各声部最晚的局部终点。
74
- * 基准取宿主经过 div 与 dot 后的实际时值;延时线是独立事件、tie 不改 T,天然不计入。
75
- * 局部时间按同一比例映射进借走的时值,各声部因此同时起奏。
76
- */
70
+ /** 按最长声部的书写时长 × 1/4 借时,最多占宿主一半;前倚音借开头,后倚音借末尾。 */
77
71
  emitPlayback(emitter: PlaybackEmitter): void;
78
72
  /**
79
73
  * 宿主留在轨道基线上,倚音整体抬到它的左上或右上角
@@ -2,7 +2,7 @@ import { ErrorDiagnostic } from "../../diagnostic.js";
2
2
  import { getLayoutBounds, layoutLocalSequence } from "../../layout/engine.js";
3
3
  import { Fraction } from "../../fraction.js";
4
4
  import { Track } from "../../lowering/track.js";
5
- import { isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
5
+ import { transferFunctionAddons, isVisualTemporalNode, TemporalNodeBase, } from "../temporal.js";
6
6
  import { ASTBraceNode, ASTFunctionNode, ASTLabelNode, ASTTextNode, } from "../ASTtypes.js";
7
7
  import { createBeamLayoutAttachment } from "../beam/layout.js";
8
8
  import { DIV_ADDON_KEY } from "../div/index.js";
@@ -237,7 +237,7 @@ class GraceFunction extends ASTFunctionNode {
237
237
  throw new ErrorDiagnostic("E_GRACE_INVALID_HOST", "@grace 的宿主必须恰好产生一个可见 Temporal", host.sourceSpan);
238
238
  }
239
239
  const events = columns.flat();
240
- if (!events.some(isVisualTemporalNode) || events.some(event => event.breakBefore > 0)) {
240
+ if (!events.some(isVisualTemporalNode) || events.some(event => (event.addon?.breakBefore ?? 0) > 0)) {
241
241
  throw new ErrorDiagnostic("E_GRACE_INVALID_CONTENT", "@grace 的倚音至少产生一个可见对象,且不能换行", grace.sourceSpan);
242
242
  }
243
243
  const composite = new GraceTemporal(this, hostNode, columns, root, attachments, this.side);
@@ -267,8 +267,6 @@ const HOOK_COMMANDS = [
267
267
  const HOOK_WIDTH = 0.07;
268
268
  /** 倚音块底边到宿主肩线的视觉间隙;倚音线会探进这段空间指向宿主 */
269
269
  const GRACE_RISE = 0.18;
270
- /** 倚音向宿主借时值的上限,防止宿主被偷光;只读 */
271
- const MAX_STEAL_RATIO = new Fraction(3, 4);
272
270
  /** 倚音复合体:宿主与倚音都折叠在这一个盒子里,对外只是一个可见事件 */
273
271
  export class GraceTemporal extends TemporalNodeBase {
274
272
  host;
@@ -369,13 +367,7 @@ export class GraceTemporal extends TemporalNodeBase {
369
367
  prepareHorizontal(line) {
370
368
  this.host.prepareHorizontal?.(line);
371
369
  }
372
- /**
373
- * 播放时倚音从宿主借走的时值(前倚音从开头、后倚音从末尾)
374
- *
375
- * 比例 = 倚音块字面时长 / 四分音符,而四分音符 T=1,所以直接取各声部最晚的局部终点。
376
- * 基准取宿主经过 div 与 dot 后的实际时值;延时线是独立事件、tie 不改 T,天然不计入。
377
- * 局部时间按同一比例映射进借走的时值,各声部因此同时起奏。
378
- */
370
+ /** 按最长声部的书写时长 × 1/4 借时,最多占宿主一半;前倚音借开头,后倚音借末尾。 */
379
371
  emitPlayback(emitter) {
380
372
  const written = new Fraction();
381
373
  const end = new Fraction();
@@ -384,12 +376,15 @@ export class GraceTemporal extends TemporalNodeBase {
384
376
  if (end.compare(written) > 0)
385
377
  written.copyFrom(end);
386
378
  });
387
- const ratio = written.compare(MAX_STEAL_RATIO) > 0 ? MAX_STEAL_RATIO : written;
388
379
  const total = emitter.end.clone().sub(emitter.start);
389
- const steal = total.clone().mul(ratio);
380
+ const scale = new Fraction(1, 4);
381
+ const steal = written.clone().mul(scale);
382
+ const limit = total.clone().divPow2();
383
+ if (steal.compare(limit) > 0) {
384
+ scale.copyFrom(limit).div(written);
385
+ steal.copyFrom(limit);
386
+ }
390
387
  const hostDuration = total.sub(steal);
391
- // 全是零时长标记时块长为 0,成员都落在借时起点
392
- const scale = written.isZero() ? new Fraction() : steal.clone().div(written);
393
388
  const base = this.side === "pre" ? emitter.start.clone() : emitter.start.clone().add(hostDuration);
394
389
  if (this.side === "post")
395
390
  emitter.play(this.host, emitter.start.clone(), hostDuration);
@@ -408,10 +403,7 @@ export class GraceTemporal extends TemporalNodeBase {
408
403
  prepareLayout(context) {
409
404
  // lowering 期间修饰挂在复合体上(augmenter 要看到整体节奏),渲染时交给宿主:
410
405
  // 减时线要落在宿主数字与下八度点之间,而不是压在整个倚音盒下面
411
- if (this.addon) {
412
- this.host.addon = this.addon;
413
- this.addon = void 0;
414
- }
406
+ transferFunctionAddons(this, this.host);
415
407
  const block = context.layoutSubdomain(this, this.graceColumns, this.root, this.attachments);
416
408
  const hostWidth = layoutLocalSequence([this.host], context);
417
409
  this.springConfig = { ...this.host.springConfig, ...this.springConfig };