jpfun 0.5.0 → 0.7.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 (79) hide show
  1. package/dist/converter/midi/convert.d.ts +3 -1
  2. package/dist/converter/midi/convert.js +78 -66
  3. package/dist/converter/musicxml/features.d.ts +19 -5
  4. package/dist/converter/musicxml/features.js +46 -8
  5. package/dist/converter/musicxml/index.js +142 -23
  6. package/dist/converter/musicxml/model.d.ts +15 -0
  7. package/dist/diagnostic.js +1 -1
  8. package/dist/functions/ASTtypes.d.ts +4 -0
  9. package/dist/functions/ASTtypes.js +25 -14
  10. package/dist/functions/adjust/index.js +6 -2
  11. package/dist/functions/arpeggio/index.js +21 -17
  12. package/dist/functions/arpeggio/shape.d.ts +1 -1
  13. package/dist/functions/arpeggio/shape.js +27 -21
  14. package/dist/functions/bar/index.js +37 -36
  15. package/dist/functions/beam/auto.js +18 -24
  16. package/dist/functions/beam/layout.js +15 -23
  17. package/dist/functions/box/index.js +52 -1
  18. package/dist/functions/br/index.js +3 -4
  19. package/dist/functions/default.js +10 -5
  20. package/dist/functions/div/index.js +2 -3
  21. package/dist/functions/gliss/index.d.ts +2 -0
  22. package/dist/functions/gliss/index.js +180 -0
  23. package/dist/functions/grace/index.d.ts +4 -2
  24. package/dist/functions/grace/index.js +19 -11
  25. package/dist/functions/head/index.js +50 -62
  26. package/dist/functions/meter/index.js +45 -24
  27. package/dist/functions/meter/shape.d.ts +3 -0
  28. package/dist/functions/meter/shape.js +43 -0
  29. package/dist/functions/note/accidentals.js +10 -16
  30. package/dist/functions/note/index.js +38 -48
  31. package/dist/functions/ottava/index.d.ts +2 -0
  32. package/dist/functions/ottava/index.js +217 -0
  33. package/dist/functions/page/index.js +3 -3
  34. package/dist/functions/pagebreak/index.d.ts +2 -0
  35. package/dist/functions/pagebreak/index.js +36 -0
  36. package/dist/functions/rest/index.d.ts +2 -0
  37. package/dist/functions/rest/index.js +231 -0
  38. package/dist/functions/slide/index.d.ts +2 -0
  39. package/dist/functions/slide/index.js +132 -0
  40. package/dist/functions/stack/index.js +8 -15
  41. package/dist/functions/symbol/index.d.ts +9 -0
  42. package/dist/functions/symbol/index.js +41 -12
  43. package/dist/functions/symbol/ornament.js +15 -20
  44. package/dist/functions/symbol/shape.js +4 -1
  45. package/dist/functions/symbol/symbols/fine.js +1 -1
  46. package/dist/functions/symbol/symbols/tr.js +46 -1
  47. package/dist/functions/temporal.d.ts +36 -12
  48. package/dist/functions/temporal.js +29 -9
  49. package/dist/functions/tie/index.js +46 -32
  50. package/dist/functions/tuplet/index.js +1 -1
  51. package/dist/functions/up/index.js +51 -33
  52. package/dist/functions/voice/connections.d.ts +19 -0
  53. package/dist/functions/voice/connections.js +90 -0
  54. package/dist/functions/voice/index.js +245 -99
  55. package/dist/functions/volta/index.js +41 -21
  56. package/dist/jpfun.core.min.js +48 -55
  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 +57 -64
  60. package/dist/layout/engine.d.ts +4 -1
  61. package/dist/layout/engine.js +232 -75
  62. package/dist/layout/model.js +22 -66
  63. package/dist/layout/page.d.ts +3 -2
  64. package/dist/layout/page.js +7 -6
  65. package/dist/layout/types.d.ts +34 -45
  66. package/dist/lowering/loweringContext.d.ts +1 -1
  67. package/dist/lowering/loweringContext.js +41 -171
  68. package/dist/parser/parserContext.d.ts +2 -0
  69. package/dist/parser/parserContext.js +31 -14
  70. package/dist/parser/preprocess.js +4 -6
  71. package/dist/playback/compile.js +12 -3
  72. package/dist/playback/types.d.ts +4 -2
  73. package/dist/render/paint.js +1 -1
  74. package/dist/render/svg.js +1 -0
  75. package/dist/render/text.d.ts +1 -1
  76. package/dist/render/text.js +3 -2
  77. package/dist/render/types.d.ts +1 -0
  78. package/grammar.md +221 -257
  79. package/package.json +1 -1
@@ -88,7 +88,6 @@ function fillPlaceholders(columns, F = DEFAULT_F) {
88
88
  if (!sortedCol[rIdx]) {
89
89
  // 保证 margin_L = mexLeft, margin_R = maxRight, 实际宽度为0
90
90
  const elPlaceholder = layoutElement({
91
- anchor: 0,
92
91
  alpha_L: maxLeft,
93
92
  alpha_R: maxRight,
94
93
  }, {
@@ -164,7 +163,6 @@ function normalizeSolverOptions(options) {
164
163
  function solveHorizontal(mat, rows, X, limit, options) {
165
164
  const { damping, maxIter, eps, crossPunish } = options;
166
165
  const numCols = mat.length;
167
- // if (numCols === 0 || rows === 0) return false; layoutHorizontalRegion 已经判断过了
168
166
  // 预排列(仅用前 rows 个元素建立无约束时的位置)
169
167
  const row_x = new Float64Array(rows);
170
168
  for (let c = 0; c < numCols; c++) {
@@ -187,19 +185,18 @@ function solveHorizontal(mat, rows, X, limit, options) {
187
185
  x0 = limit / x0;
188
186
  for (let c = 0; c < numCols; c++)
189
187
  X[c] *= x0;
190
- // --- 预分配物理引擎所需的全部静态缓存空间,杜绝主循环内的 GC 损耗 ---
191
188
  const F_vec = new Float64Array(numCols);
192
- const stiffnessCache = new Float32Array(rows * (numCols + 1));
193
- // 计算全局合力,并就地填充刚度缓存
189
+ // 各声部共享列坐标,刚度按左墙、相邻列、右墙汇总。
190
+ const stiffness = new Float64Array(numCols + 1);
194
191
  function computeForces(cols_X) {
195
192
  F_vec.fill(0);
193
+ stiffness.fill(0);
196
194
  for (let r = 0; r < rows; r++) {
197
- const rowOffset = r * (numCols + 1);
198
195
  // 左墙
199
196
  const el_first = mat[0][r];
200
197
  const res_left = calcLeftWall(el_first, cols_X[0], crossPunish);
201
198
  F_vec[0] += res_left.force;
202
- stiffnessCache[rowOffset] = res_left.stiffness; // 缓存左墙刚度
199
+ stiffness[0] += res_left.stiffness;
203
200
  // 内部链弹簧力传导
204
201
  for (let c = 1; c < numCols; c++) {
205
202
  const el_l = mat[c - 1][r];
@@ -207,74 +204,33 @@ function solveHorizontal(mat, rows, X, limit, options) {
207
204
  const res = calcPairForceAndStiffness(el_l, el_r, cols_X[c - 1], cols_X[c]);
208
205
  F_vec[c - 1] -= res.force;
209
206
  F_vec[c] += res.force;
210
- stiffnessCache[rowOffset + c] = res.stiffness; // 缓存链弹簧刚度
207
+ stiffness[c] += res.stiffness;
211
208
  }
212
209
  // 右墙
213
210
  const el_last = mat[numCols - 1][r];
214
211
  const res_right = calcRightWall(el_last, cols_X[numCols - 1], limit, crossPunish);
215
212
  F_vec[numCols - 1] -= res_right.force;
216
- stiffnessCache[rowOffset + numCols] = res_right.stiffness; // 缓存右墙刚度
213
+ stiffness[numCols] += res_right.stiffness;
217
214
  }
218
215
  return F_vec;
219
216
  }
220
- const Hp = new Float64Array(numCols);
221
- // Hessian 矩阵切向刚度乘以位移向量 p (精简参数,移除了无用的 cols_X)
222
- function multiplyH(p) {
223
- Hp.fill(0);
224
- for (let r = 0, rowOffset = 0; r < rows; r++, rowOffset += (numCols + 1)) {
225
- // 左墙刚度
226
- Hp[0] += stiffnessCache[rowOffset] * p[0];
227
- // 链弹簧二阶切线刚度
228
- for (let c = 1; c < numCols; c++) {
229
- const Kdp = stiffnessCache[rowOffset + c] * (p[c] - p[c - 1]);
230
- Hp[c - 1] -= Kdp;
231
- Hp[c] += Kdp;
232
- }
233
- // 右墙刚度
234
- Hp[numCols - 1] += stiffnessCache[rowOffset + numCols] * p[numCols - 1];
235
- }
236
- // L-M 正则阻尼,保证矩阵严格正定,避免奇异性
237
- const lambda = 1e-4;
238
- for (let i = 0; i < p.length; i++)
239
- Hp[i] += lambda * p[i];
240
- return Hp;
241
- }
242
- function dot(a, b) {
243
- let sum = 0;
244
- for (let i = 0; i < a.length; i++)
245
- sum += a[i] * b[i];
246
- return sum;
247
- }
248
- // 必须用 Float64Array 不然影响收敛
217
+ const diagonal = new Float64Array(numCols);
249
218
  const dx = new Float64Array(numCols);
250
- const R = new Float64Array(numCols);
251
- const P = new Float64Array(numCols);
252
- // 共轭梯度线性解算
253
- function solveCG(F_vec, maxCGIter = 8) {
254
- dx.fill(0);
255
- R.set(F_vec);
256
- P.set(R);
257
- let rsold = dot(R, R);
258
- if (rsold < 1e-12)
259
- return dx;
260
- for (let iter = 0; iter < maxCGIter; iter++) {
261
- const Hp = multiplyH(P);
262
- const p_Hp = dot(P, Hp);
263
- if (Math.abs(p_Hp) < 1e-12)
264
- break;
265
- const alpha = rsold / p_Hp;
266
- for (let i = 0; i < numCols; i++) {
267
- dx[i] += alpha * P[i];
268
- R[i] -= alpha * Hp[i];
269
- }
270
- const rsnew = dot(R, R);
271
- if (Math.sqrt(rsnew) < 1e-6)
272
- break;
273
- const beta = rsnew / rsold;
274
- for (let i = 0; i < numCols; i++) {
275
- P[i] = R[i] + beta * P[i];
219
+ function solveTridiagonal() {
220
+ // H[i,i] = K[i] + K[i+1] + lambda,H[i-1,i] = -K[i]。
221
+ const lambda = 1e-4;
222
+ for (let i = 0; i < numCols; i++) {
223
+ const factor = i === 0 ? 0 : stiffness[i] / diagonal[i - 1];
224
+ const pivot = stiffness[i] + stiffness[i + 1] + lambda - factor * stiffness[i];
225
+ if (!(pivot > 0) || !Number.isFinite(pivot)) {
226
+ throw new Error("Horizontal spring stiffness must produce a finite positive definite system");
276
227
  }
277
- rsold = rsnew;
228
+ diagonal[i] = pivot;
229
+ dx[i] = F_vec[i] + (i === 0 ? 0 : factor * dx[i - 1]);
230
+ }
231
+ dx[numCols - 1] /= diagonal[numCols - 1];
232
+ for (let i = numCols - 2; i >= 0; i--) {
233
+ dx[i] = (dx[i] + stiffness[i + 1] * dx[i + 1]) / diagonal[i];
278
234
  }
279
235
  return dx;
280
236
  }
@@ -290,7 +246,7 @@ function solveHorizontal(mat, rows, X, limit, options) {
290
246
  }
291
247
  if (f_max < eps)
292
248
  break;
293
- const dx = solveCG(F_vec);
249
+ const dx = solveTridiagonal();
294
250
  for (let i = 0; i < numCols; i++) {
295
251
  X[i] += damping * dx[i];
296
252
  }
@@ -19,9 +19,10 @@ export declare const DEFAULT_PAGE_CONFIG: Readonly<PageConfig>;
19
19
  */
20
20
  export declare function normalizePageConfig(source?: Partial<PageConfig>): PageConfig;
21
21
  /**
22
- * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标
22
+ * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标。
23
+ * pageBreaks 按行号索引:undefined 不强制换页,true/false 强制换页并指定上一页是否拉伸。
23
24
  */
24
- export declare function paginateLayoutLines(heights: readonly number[], page: PageConfig): {
25
+ export declare function paginateLayoutLines(heights: readonly number[], page: PageConfig, pageBreaks?: readonly (boolean | undefined)[]): {
25
26
  pages: DocumentLayoutPage[];
26
27
  lineTops: number[];
27
28
  };
@@ -5,10 +5,10 @@ export class PageLayoutError extends Error {
5
5
  availableHeight;
6
6
  constructor(line, requiredHeight, availableHeight) {
7
7
  super(`Page cannot fit layout line ${line}: requires ${requiredHeight}px, available ${availableHeight}px`);
8
- this.name = "PageLayoutError";
9
8
  this.line = line;
10
9
  this.requiredHeight = requiredHeight;
11
10
  this.availableHeight = availableHeight;
11
+ this.name = "PageLayoutError";
12
12
  }
13
13
  }
14
14
  /** 没有 page 函数时使用的默认 A4 近似页面配置 */
@@ -64,9 +64,10 @@ export function normalizePageConfig(source = {}) {
64
64
  return page;
65
65
  }
66
66
  /**
67
- * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标
67
+ * 把已经测好自然高度的谱面行分页,并给出每行的全局顶部坐标。
68
+ * pageBreaks 按行号索引:undefined 不强制换页,true/false 强制换页并指定上一页是否拉伸。
68
69
  */
69
- export function paginateLayoutLines(heights, page) {
70
+ export function paginateLayoutLines(heights, page, pageBreaks = []) {
70
71
  const availableHeight = page.height - page.marginTop - page.marginBottom;
71
72
  const pages = [];
72
73
  const lineTops = new Array(heights.length).fill(0);
@@ -111,9 +112,9 @@ export function paginateLayoutLines(heights, page) {
111
112
  if (Number.isFinite(page.height) && height > availableHeight + 1e-6) {
112
113
  throw new PageLayoutError(i, height, availableHeight);
113
114
  }
114
- // 当前行放不下时先封口已有内容;每页因此至少包含一行
115
- if (Number.isFinite(page.height) && i > start && used + page.lineGap + height > availableHeight + 1e-6) {
116
- closePage(i, true);
115
+ // 强制边界与自然溢出统一封页;无限页高不分配余白
116
+ if (i > start && (pageBreaks[i] !== undefined || Number.isFinite(page.height) && used + page.lineGap + height > availableHeight + 1e-6)) {
117
+ closePage(i, Number.isFinite(page.height) && (pageBreaks[i] ?? true));
117
118
  }
118
119
  used += (i > start ? page.lineGap : 0) + height;
119
120
  contentHeight += height;
@@ -21,7 +21,7 @@ export interface Extent {
21
21
  bottom: number;
22
22
  }
23
23
  /**
24
- * 一个排版对象的完整矩形和两个对齐基准
24
+ * 一个排版对象的定位矩形和两个对齐基准
25
25
  *
26
26
  * prepareLayout 负责填写 w、h、anchor、visualAxis
27
27
  * layout 负责原地修改 x、y
@@ -88,6 +88,8 @@ export interface SubdomainLayout {
88
88
  export type LayoutRange = readonly [from: number, to: number] | readonly [from: LayoutHost, to: LayoutHost];
89
89
  /** attachment 根据当前视觉轴生成几何时需要的完整页面信息 */
90
90
  export interface AttachmentLayoutContext extends LayoutPrepareContext {
91
+ /** 占用测量使用布局位置,最终绘制才应用后置平移 */
92
+ readonly layoutOnly?: boolean;
91
93
  width: number;
92
94
  originX: number;
93
95
  pages: readonly Rect[];
@@ -109,8 +111,12 @@ export interface AttachmentLayoutContext extends LayoutPrepareContext {
109
111
  */
110
112
  getRangeExtents(line: number, columns?: LayoutRange): ReadonlyMap<Track, Readonly<Extent>>;
111
113
  getRangeExtents(line: number, columns: LayoutRange | undefined, track: Track): Readonly<Extent> | undefined;
114
+ /** 按全局 x 区间筛选横向相交的主体及已测附件,返回各轨轴局部占用;空区间返回空 Map */
115
+ getHorizontalExtents(line: number, left: number, right: number): ReadonlyMap<Track, Readonly<Extent>>;
112
116
  /** 读取本轮已完成的 attachment 边界;分组在 endLoweringGroup 才注册,因而组内对象必然排在分组之前 */
113
117
  getAttachmentBox(attachment: LayoutAttachment): Readonly<Rect>;
118
+ /** 读取已测附件的有效占用,保留显式空数组;尚未测量时返回 undefined */
119
+ getAttachmentOccupancy(attachment: LayoutAttachment): readonly LayoutRegion[] | undefined;
114
120
  /** 内容的实际几何并集;只包含作用域内主体与此前已测附件,不代表撑行占用 */
115
121
  getContentBounds(content: LoweringContent): Readonly<Rect> | undefined;
116
122
  }
@@ -126,6 +132,10 @@ export interface AttachmentLayoutContext extends LayoutPrepareContext {
126
132
  export interface LayoutHost extends TimeLineEvent {
127
133
  box: LayoutBox;
128
134
  springConfig: HorizontalSpringConfig;
135
+ /**
136
+ * 内置端口:body.left / body.right、decoration.below、shoulder、tie.top、
137
+ * div.{level}.left / div.{level}.right、dot、lyric;用途与缺省值见 {@link TemporalNodeBase.ports}。
138
+ */
129
139
  ports: Record<string, LayoutPoint>;
130
140
  readonly mergeKey: number;
131
141
  readonly layoutLine: number;
@@ -148,12 +158,14 @@ export interface HorizontalLineView {
148
158
  readonly trackRuns: ReadonlyMap<Track, readonly LayoutHost[]>;
149
159
  /** 主体所在时间列下标;不在本行时返回 -1 */
150
160
  columnOf(host: LayoutHost): number;
161
+ /** 主体在所属 Track 可见序列中的下标;不在本行时返回 -1 */
162
+ trackIndexOf(host: LayoutHost): number;
151
163
  /** 注册横向布局 hook;同一行内按跨度从小到大执行 */
152
164
  registerHorizontalLayoutHook(from: LayoutHost, to: LayoutHost, hook: HorizontalLayoutHook): void;
153
165
  }
154
166
  /**
155
167
  * 相对于对象 LayoutBox 左上角的局部坐标
156
- * tie、beam 等关系函数通过命名端口获取几何位置
168
+ * 装饰布局与 tie、beam 等关系函数通过命名端口获取几何位置
157
169
  */
158
170
  export interface LayoutPoint {
159
171
  x: number;
@@ -167,58 +179,33 @@ context: LayoutPrepareContext) => LayoutDecoration | null;
167
179
  *
168
180
  * 实例有两种来源:Temporal.prepareLayout 可以直接加入;addon 对应的 LayoutDecorationHandler 也可以在主体 prepareLayout 后创建
169
181
  * 两者都在创建时就拿到了宿主,因此回调不再重复传入它;实例可以在返回前调整 host.box,例如 dot 先扩张主体宽度
170
- * 被 arrangeBelowDecorations 使用
182
+ * 由引擎统一分配上下空间,place 的坐标相对主体定位矩形
171
183
  *
172
- * 通用部分只有 paint:主体绘制完成后,引擎调用它绘制当前装饰。
173
- *
174
- * below 是可选的“主体下方空间”子协议,只向下扩张 box.h,不管理主体上方空间
175
- * 上方内容若会改变主体 visualAxis 或内部绘制坐标,应由具体 Temporal 在 prepareLayout 中处理。
184
+ * paint 可省略,此时只预留空间,不进入内容边界
176
185
  *
177
186
  * 当前内置示例:
178
187
  * - dot:handler 生成只负责横向扩宽和绘制的装饰,不声明 below;
179
188
  * - div:handler 生成减时线装饰,使用 order=0,排在主体下方最内层;
180
- * - note 下八度点:prepareLayout 直接加入装饰,使用 order=100,排在减时线之后;
181
- * - note 上八度点不使用 LayoutDecoration,而是主体 prepareLayout 的一部分。
189
+ * - note 八度点:prepareLayout 直接加入装饰,使用 order=100
182
190
  *
183
191
  * LayoutDecoration 不是 addon 语义本身。实例可以用闭包保存本次测量参数和 place 结果,因此必须由 Temporal.decorations 持有到当前 paint 结束。
184
192
  */
185
193
  export interface LayoutDecoration {
186
- paint(painter: Painter): void;
187
- /** 声明后进入主体下方空间管理,引擎只理解这四个字段,不知道空间来自哪个函数 */
188
- below?: {
189
- order: number;
190
- gap?: number;
191
- height?: number;
192
- /**
193
- * 引擎分配好本装饰的下方区域后调用一次,y 是该区域 **顶边到 host.box 顶部** 的距离
194
- *
195
- * 该做的:把这一刻才确定的局部几何存进闭包供 paint 使用(note 存下八度点的 y),
196
- * 以及发布依赖这个位置的端口(div 在这里建 div.N.left/right)。只占位不绘制时可以不实现。
197
- *
198
- * 不该做的:改 box.h(引擎会按 height 统一扩张)、读 box.y 或 box.h (前者尚未求解、后者正在向下累加)。
199
- * 此时只有 box.w/anchor 和 ports 是最终值,因此一律记录相对盒顶的局部坐标,绘制时再加 host.box.x / host.box.y。
200
- *
201
- * 例(一条减时线):
202
- * ```ts
203
- * let lineY = 0; // 闭包保存本轮测量结果
204
- * return {
205
- * below: {
206
- * order: 0,
207
- * height: strokeWidth,
208
- * place(y) {
209
- * lineY = y + strokeWidth / 2;
210
- * host.ports["div.0.left"] = { x: 0, y: lineY };
211
- * },
212
- * },
213
- * paint(painter) {
214
- * const y = host.box.y + lineY; // 此时 box.y 才有意义
215
- * painter.drawLine(host.box.x, y, host.box.x + host.box.w, y, { stroke: "#000", strokeWidth });
216
- * },
217
- * };
218
- * ```
219
- */
220
- place?(y: number): void;
221
- };
194
+ paint?(painter: Painter): void;
195
+ above?: LayoutDecorationSpace;
196
+ below?: LayoutDecorationSpace;
197
+ }
198
+ /** 上下装饰共用由内向外的排列协议 */
199
+ export interface LayoutDecorationSpace {
200
+ order: number;
201
+ gap?: number;
202
+ height?: number;
203
+ /**
204
+ * y 是区域顶边相对 host.box 顶部的坐标,上方区域通常为负数
205
+ * 只保存局部几何并发布端口,不读写正在排列的 box.h 或尚未放置的 box.y
206
+ * 绘制时再加 host.box.x/y,纯留白可以省略 place
207
+ */
208
+ place?(y: number): void;
222
209
  }
223
210
  /**
224
211
  * 一次 attachment 放置产生的完整几何
@@ -238,6 +225,8 @@ export interface AttachmentGeometry {
238
225
  * 实例只保存语义输入和一次横向准备状态,不保存最终 box、regions 或绘制几何。
239
226
  */
240
227
  export interface LayoutAttachment extends LoweringAttachment {
228
+ /** 后置平移仅影响绘制,不参与占用求解 */
229
+ placementOffset?: LayoutPoint;
241
230
  /** 几何端点;端点全部落在同一子域的成员上时,附件属于该子域。不表示内容包含或播放端点投影 */
242
231
  readonly endPoints?: readonly TemporalNodeBase[];
243
232
  /** 相对于 Temporal 主体的绘制层;background 比内容先绘制 */
@@ -57,7 +57,7 @@ export declare class LoweringContext {
57
57
  */
58
58
  lowerDocument(node: ASTNodeBase): LoweringResult;
59
59
  /**
60
- * 固化谱面行号并进行时间状态固化
60
+ * 固化谱面行号、时间状态和最终时长
61
61
  */
62
62
  private solidifyColumns;
63
63
  /**
@@ -51,8 +51,9 @@ export class LoweringContext {
51
51
  for (const functionClass of functionClasses) {
52
52
  if (functionClass.loweringAugment)
53
53
  augmenters.push(functionClass.loweringAugment);
54
- if (functionClass.loweringFinalize)
55
- finalizers.push(functionClass.loweringFinalize);
54
+ const finalize = functionClass.loweringFinalize;
55
+ if (finalize && !finalizers.includes(finalize))
56
+ finalizers.push(finalize); // 判重是因为pb直接引用了br的实现
56
57
  }
57
58
  }
58
59
  /** 供 page 函数调用 */
@@ -75,7 +76,7 @@ export class LoweringContext {
75
76
  const rootTrack = new Track();
76
77
  const duration = new Fraction();
77
78
  const columns = this.trackedEvents(node, duration, rootTrack);
78
- this.solidifyColumns(columns);
79
+ this.solidifyColumns(columns, duration);
79
80
  return this.postprocessResult({
80
81
  diagnostics: this.diagnostics,
81
82
  columns,
@@ -88,16 +89,17 @@ export class LoweringContext {
88
89
  });
89
90
  }
90
91
  /**
91
- * 固化谱面行号并进行时间状态固化
92
+ * 固化谱面行号、时间状态和最终时长
92
93
  */
93
- solidifyColumns(columns) {
94
+ solidifyColumns(columns, duration) {
94
95
  // 同时刻跨轨的 br 已经合成一列,所以取最大;同轨连写仍是多个列,因而累加
95
96
  let line = 0;
96
97
  for (const column of columns) {
97
98
  let offset = 0;
98
99
  for (const node of column) {
99
- if (node.breakBefore > offset)
100
- offset = node.breakBefore;
100
+ const requested = node.addon?.breakBefore ?? 0;
101
+ if (requested > offset)
102
+ offset = requested;
101
103
  }
102
104
  line += offset;
103
105
  // 换行列本身归属于换行之后的那一行
@@ -115,14 +117,45 @@ export class LoweringContext {
115
117
  const programs = new Map();
116
118
  const velocityOf = (track) => velocities.get(track) ?? (track.parent ? velocityOf(track.parent) : DEFAULT_VELOCITY);
117
119
  const programOf = (track) => programs.get(track) ?? (track.parent ? programOf(track.parent) : DEFAULT_PROGRAM);
120
+ const timeOffset = new Fraction();
118
121
  for (const column of columns) {
122
+ if (!timeOffset.isZero())
123
+ column.shiftTime(timeOffset);
124
+ let insertion;
119
125
  for (const node of column) {
126
+ state.currentEvent = node;
120
127
  state.velocity = velocityOf(node.track);
121
128
  state.program = programOf(node.track);
122
- node.onTimeState?.(state);
129
+ const offset = node.onTimeState?.(state);
130
+ if (offset && !offset.isZero() && (!insertion || offset.compare(insertion) > 0)) {
131
+ (insertion ??= new Fraction()).copyFrom(offset);
132
+ }
123
133
  velocities.set(node.track, state.velocity);
124
134
  programs.set(node.track, state.program);
125
135
  }
136
+ // 同列声部一起开始,只在整列固化后累加一次偏移
137
+ if (insertion)
138
+ timeOffset.add(insertion);
139
+ }
140
+ if (timeOffset.isZero())
141
+ return;
142
+ // 偏移非负、同轨时序前进,只需各轨尾节点;programs 已记录全部全局轨道
143
+ const tracks = new Set(programs.keys());
144
+ const end = new Fraction();
145
+ duration.set(0);
146
+ for (let i = columns.length - 1; i >= 0 && tracks.size > 0; i--) {
147
+ const column = columns[i];
148
+ for (let j = column.length - 1; j >= 0; j--) {
149
+ const node = column[j];
150
+ if (!tracks.delete(node.track))
151
+ continue;
152
+ const T = node.T;
153
+ end.copyFrom(node.t);
154
+ if (!T.isZero())
155
+ end.add(T);
156
+ if (end.compare(duration) > 0)
157
+ duration.copyFrom(end);
158
+ }
126
159
  }
127
160
  }
128
161
  /**
@@ -312,169 +345,6 @@ export class LoweringContext {
312
345
  if (l === 1)
313
346
  return tracks[0];
314
347
  const result = [];
315
- if (l === 2) {
316
- // 双轨特化:与下面的堆归并语义等价,改规则必须两边同时改
317
- const track0 = tracks[0], track1 = tracks[1];
318
- const l0 = track0.length, l1 = track1.length;
319
- let i = 0, j = 0;
320
- const idt = new Fraction(), jdt = new Fraction(); // 应用时间偏移一定要紧在 push 前
321
- let a = track0[0], b = track1[0];
322
- const t0 = a.t.clone(), t1 = b.t.clone();
323
- while (true) {
324
- if (a.mergeKey === ANCHOR_KEY) {
325
- // 等待b也遇到anchor
326
- if (b.mergeKey !== ANCHOR_KEY) {
327
- result.push(b);
328
- b = track1[++j];
329
- while (j < l1 && b.mergeKey !== ANCHOR_KEY) {
330
- if (!jdt.isZero())
331
- b.shiftTime(jdt);
332
- result.push(b);
333
- b = track1[++j];
334
- }
335
- if (b) {
336
- b.shiftTime(jdt);
337
- t1.copyFrom(b.t);
338
- }
339
- }
340
- if (j < l1) { // b 也是 anchor
341
- const maxT = t0.compare(t1) >= 0 ? t0 : t1;
342
- idt.add(maxT).sub(t0);
343
- jdt.add(maxT).sub(t1);
344
- a.push(...b);
345
- a.t = maxT;
346
- b = track1[++j];
347
- }
348
- result.push(a);
349
- a = track0[++i];
350
- // 准备下一个
351
- if (a) {
352
- a.shiftTime(idt);
353
- t0.copyFrom(a.t);
354
- }
355
- if (b) {
356
- b.shiftTime(jdt);
357
- t1.copyFrom(b.t);
358
- }
359
- if (!a || !b)
360
- break;
361
- }
362
- if (b.mergeKey === ANCHOR_KEY) {
363
- if (a.mergeKey !== ANCHOR_KEY) {
364
- result.push(a);
365
- a = track0[++i];
366
- while (i < l0 && a.mergeKey !== ANCHOR_KEY) {
367
- if (!idt.isZero())
368
- a.shiftTime(idt);
369
- result.push(a);
370
- a = track0[++i];
371
- }
372
- if (a) {
373
- a.shiftTime(idt);
374
- t0.copyFrom(a.t);
375
- }
376
- }
377
- if (i < l0) {
378
- const maxT = t0.compare(t1) >= 0 ? t0 : t1;
379
- idt.add(maxT).sub(t0);
380
- jdt.add(maxT).sub(t1);
381
- b.push(...a);
382
- b.t = maxT;
383
- a = track0[++i];
384
- }
385
- result.push(b);
386
- b = track1[++j];
387
- if (a) {
388
- a.shiftTime(idt);
389
- t0.copyFrom(a.t);
390
- }
391
- if (b) {
392
- b.shiftTime(jdt);
393
- t1.copyFrom(b.t);
394
- }
395
- if (!a || !b)
396
- break;
397
- }
398
- if (t0.equals(t1)) {
399
- if (a.mergeKey === b.mergeKey) {
400
- a.push(...b);
401
- result.push(a);
402
- a = track0[++i];
403
- b = track1[++j];
404
- if (a) {
405
- a.shiftTime(idt);
406
- t0.copyFrom(a.t);
407
- }
408
- if (b) {
409
- b.shiftTime(jdt);
410
- t1.copyFrom(b.t);
411
- }
412
- if (!a || !b)
413
- break;
414
- }
415
- else if (a.mergeKey < b.mergeKey) {
416
- result.push(a);
417
- a = track0[++i];
418
- if (a) {
419
- a.shiftTime(idt);
420
- t0.copyFrom(a.t);
421
- }
422
- else
423
- break;
424
- }
425
- else {
426
- result.push(b);
427
- b = track1[++j];
428
- if (b) {
429
- b.shiftTime(jdt);
430
- t1.copyFrom(b.t);
431
- }
432
- else
433
- break;
434
- }
435
- continue;
436
- }
437
- if (t0.compare(t1) < 0) {
438
- result.push(a);
439
- a = track0[++i];
440
- if (a) {
441
- a.shiftTime(idt);
442
- t0.copyFrom(a.t);
443
- continue;
444
- }
445
- else
446
- break;
447
- }
448
- if (t1.compare(t0) < 0) {
449
- result.push(b);
450
- b = track1[++j];
451
- if (b) {
452
- b.shiftTime(jdt);
453
- t1.copyFrom(b.t);
454
- continue;
455
- }
456
- else
457
- break;
458
- }
459
- }
460
- if (a)
461
- result.push(a);
462
- while (++i < l0) {
463
- a = track0[i];
464
- if (!idt.isZero())
465
- a.shiftTime(idt);
466
- result.push(a);
467
- }
468
- if (b)
469
- result.push(b);
470
- while (++j < l1) {
471
- b = track1[j];
472
- if (!jdt.isZero())
473
- b.shiftTime(jdt);
474
- result.push(b);
475
- }
476
- return result;
477
- }
478
348
  // 归并多个轨道
479
349
  const p = new Uint16Array(l); // 当前指向第几个
480
350
  const dt = Array.from({ length: l }, () => new Fraction()); // 每个轨道的偏移量
@@ -16,6 +16,8 @@ export declare class ParserContext {
16
16
  readonly source: string;
17
17
  /** 词法层产物,只由 parseSyntax 填充;所有子上下文共享 */
18
18
  readonly syntax: SyntaxAnalysis;
19
+ /** syntax.tokens 前缀注释区间的扫描游标 */
20
+ private commentIndex;
19
21
  /** 解析过程中产生的诊断信息,包含错误和警告 */
20
22
  diagnostics: Diagnostic[];
21
23
  /** 变量表,存储 `@set` 定义的变量,供解析过程中查询和修改,具有局部作用域 */