All files / jianpu-renderer/core/layout SystemLayoutEngine.ts

0% Statements 0/637
0% Branches 0/1
0% Functions 0/1
0% Lines 0/637

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/**
 * 行布局引擎
 * 
 * @description 将小节分配到不同的行(System),支持自动换行
 * 
 * 核心功能:
 * 1. 根据行宽度自动分配小节到不同行
 * 2. 计算每行的Y坐标
 * 3. 确保小节不被拆分
 * 4. 支持多声部的行高计算
 * 
 * 换行策略:
 * - 当累计小节宽度超过行宽度时,在上一个小节处换行
 * - 确保每行至少有一个小节
 * - 最后一行不做特殊处理(保持自然宽度)
 */

import { JianpuMeasure, JianpuSystem } from '../../models';
import { RenderConfig, DEFAULT_RENDER_CONFIG } from '../config/RenderConfig';

// ==================== 类型定义 ====================

/** 行布局配置 */
export interface SystemLayoutConfig {
  /** 行宽度(像素) */
  systemWidth: number;
  /** 行高度(像素,单声部基准高度) */
  systemHeight: number;
  /** 行间距(像素) */
  systemSpacing: number;
  /** 声部间距(像素) */
  voiceSpacing: number;
  /** 页边距左(像素) */
  marginLeft: number;
  /** 页边距上(像素) */
  marginTop: number;
  /** 是否拉伸最后一行(填满行宽) */
  stretchLastSystem: boolean;
  /** 是否在首行显示谱号 */
  showClefOnFirstSystem: boolean;
  /** 是否在首行显示声部名称 */
  showPartNamesOnFirstSystem: boolean;
  /** 最小每行小节数(防止单个小节占一行) */
  minMeasuresPerSystem: number;
}

/** 行布局结果 */
export interface SystemLayoutResult {
  /** 所有行 */
  systems: JianpuSystem[];
  /** 布局统计 */
  stats: SystemLayoutStats;
}

/** 行布局统计 */
export interface SystemLayoutStats {
  /** 总行数 */
  systemCount: number;
  /** 总小节数 */
  measureCount: number;
  /** 最大每行小节数 */
  maxMeasuresPerSystem: number;
  /** 最小每行小节数 */
  minMeasuresPerSystem: number;
  /** 平均每行小节数 */
  avgMeasuresPerSystem: number;
  /** 总高度 */
  totalHeight: number;
  /** 布局耗时(ms) */
  layoutTime: number;
}

/** 行分配方案 */
interface SystemAllocation {
  /** 该行包含的小节索引(起始) */
  startIndex: number;
  /** 该行包含的小节索引(结束,不含) */
  endIndex: number;
  /** 该行小节总宽度 */
  totalWidth: number;
  /** 需要的拉伸比例 */
  stretchRatio: number;
}

// ==================== 默认配置 ====================

const DEFAULT_SYSTEM_CONFIG: SystemLayoutConfig = {
  systemWidth: DEFAULT_RENDER_CONFIG.systemWidth,
  systemHeight: DEFAULT_RENDER_CONFIG.systemHeight,
  systemSpacing: DEFAULT_RENDER_CONFIG.systemSpacing,
  voiceSpacing: 60,
  marginLeft: 20,
  marginTop: 50,
  stretchLastSystem: false,
  showClefOnFirstSystem: false,
  showPartNamesOnFirstSystem: false,
  minMeasuresPerSystem: 1,
};

// ==================== 主类 ====================

/**
 * 行布局引擎
 */
export class SystemLayoutEngine {
  /** 布局配置 */
  private config: SystemLayoutConfig;

  /**
   * 构造函数
   * @param config 布局配置(可选)
   */
  constructor(config: Partial<SystemLayoutConfig> = {}) {
    this.config = { ...DEFAULT_SYSTEM_CONFIG, ...config };
  }

  /**
   * 将小节分配到行
   * 
   * @param measures 小节数组(已完成小节宽度计算)
   * @returns 行布局结果
   */
  layoutSystems(measures: JianpuMeasure[]): SystemLayoutResult {
    const startTime = performance.now();
    
    // 处理空数组
    if (!measures || measures.length === 0) {
      return {
        systems: [],
        stats: this.createEmptyStats(startTime),
      };
    }

    // 1. 计算行分配方案
    const allocations = this.calculateSystemAllocations(measures);

    // 2. 创建行对象并计算Y坐标
    const systems = this.createSystems(measures, allocations);

    // 3. 更新小节的X、Y坐标
    this.updateMeasurePositions(systems);

    // 4. 计算统计信息
    const stats = this.calculateStats(systems, startTime);

    return { systems, stats };
  }

  /**
   * 计算行分配方案
   * 
   * 算法:贪心算法,尽可能多地将小节放入当前行
   * 
   * @param measures 小节数组
   * @returns 行分配方案数组
   */
  private calculateSystemAllocations(measures: JianpuMeasure[]): SystemAllocation[] {
    const { systemWidth, marginLeft, minMeasuresPerSystem } = this.config;
    const availableWidth = systemWidth - marginLeft * 2; // 可用宽度(减去左右边距)
    
    const allocations: SystemAllocation[] = [];
    let currentStartIndex = 0;
    let currentWidth = 0;

    for (let i = 0; i < measures.length; i++) {
      const measure = measures[i];
      const measureWidth = measure.width;

      // 检查是否需要换行
      const wouldExceed = currentWidth + measureWidth > availableWidth;
      const hasMinMeasures = i - currentStartIndex >= minMeasuresPerSystem;
      
      if (wouldExceed && hasMinMeasures && currentStartIndex < i) {
        // 当前行已满,保存并开始新行
        allocations.push(this.createAllocation(
          currentStartIndex,
          i,
          currentWidth,
          availableWidth
        ));
        
        // 开始新行
        currentStartIndex = i;
        currentWidth = measureWidth;
      } else {
        // 继续添加到当前行
        currentWidth += measureWidth;
      }
    }

    // 处理最后一行
    if (currentStartIndex < measures.length) {
      allocations.push(this.createAllocation(
        currentStartIndex,
        measures.length,
        currentWidth,
        availableWidth
      ));
    }

    return allocations;
  }

  /**
   * 创建行分配对象
   */
  private createAllocation(
    startIndex: number,
    endIndex: number,
    totalWidth: number,
    availableWidth: number
  ): SystemAllocation {
    return {
      startIndex,
      endIndex,
      totalWidth,
      stretchRatio: availableWidth / totalWidth, // 拉伸比例
    };
  }

  /**
   * 创建行对象
   * 
   * @param measures 小节数组
   * @param allocations 行分配方案
   * @returns 行数组
   */
  private createSystems(
    measures: JianpuMeasure[],
    allocations: SystemAllocation[]
  ): JianpuSystem[] {
    const { 
      systemWidth, 
      systemHeight, 
      systemSpacing, 
      marginLeft, 
      marginTop,
      voiceSpacing,
      stretchLastSystem,
      showClefOnFirstSystem,
      showPartNamesOnFirstSystem,
    } = this.config;

    const systems: JianpuSystem[] = [];
    let currentY = marginTop;

    for (let sysIndex = 0; sysIndex < allocations.length; sysIndex++) {
      const allocation = allocations[sysIndex];
      const isFirstSystem = sysIndex === 0;
      const isLastSystem = sysIndex === allocations.length - 1;
      
      // 提取该行的小节
      const systemMeasures = measures.slice(allocation.startIndex, allocation.endIndex);
      
      // 计算该行的声部数量(取该行所有小节的最大声部数)
      const maxVoices = Math.max(
        1,
        ...systemMeasures.map(m => m.voices.length)
      );
      
      // 计算行高度(基于声部数量)
      const height = this.calculateSystemHeight(maxVoices);
      
      // 是否需要拉伸(非最后一行,或配置了拉伸最后一行)
      const shouldStretch = !isLastSystem || stretchLastSystem;
      
      // 创建行对象
      const system: JianpuSystem = {
        index: sysIndex,
        measures: systemMeasures,
        x: marginLeft,
        y: currentY,
        width: shouldStretch ? systemWidth - marginLeft * 2 : allocation.totalWidth,
        height,
        showPartNames: isFirstSystem && showPartNamesOnFirstSystem,
        showClef: isFirstSystem && showClefOnFirstSystem,
      };

      // 如果需要拉伸,更新小节宽度
      if (shouldStretch && allocation.stretchRatio > 1) {
        this.stretchSystemMeasures(system, allocation.stretchRatio);
      }

      systems.push(system);
      
      // 更新Y坐标(下一行的起始位置)
      currentY += height + systemSpacing;
    }

    return systems;
  }

  /**
   * 计算行高度
   * 
   * @param voiceCount 声部数量
   * @returns 行高度
   */
  private calculateSystemHeight(voiceCount: number): number {
    const { systemHeight, voiceSpacing } = this.config;
    
    if (voiceCount <= 1) {
      return systemHeight;
    }
    
    // 多声部:基础高度 + (声部数-1) * 声部间距
    return systemHeight + (voiceCount - 1) * voiceSpacing;
  }

  /**
   * 拉伸行内的小节以填满行宽
   * 
   * @param system 行对象
   * @param stretchRatio 拉伸比例
   */
  private stretchSystemMeasures(system: JianpuSystem, stretchRatio: number): void {
    for (const measure of system.measures) {
      // 拉伸小节宽度
      measure.width *= stretchRatio;
      
      // 拉伸音符位置(保持相对比例)
      for (const voice of measure.voices) {
        for (const note of voice) {
          // 只拉伸相对于小节起点的偏移,不改变小节起始X
          const relativeX = note.x - measure.x;
          note.x = measure.x + relativeX * stretchRatio;
        }
      }
    }
  }

  /**
   * 更新小节的X、Y坐标
   * 
   * @param systems 行数组
   */
  private updateMeasurePositions(systems: JianpuSystem[]): void {
    for (const system of systems) {
      let currentX = system.x;
      
      for (const measure of system.measures) {
        // 计算小节X坐标偏移(相对于原来的X坐标)
        const xOffset = currentX - measure.x;
        
        // 更新小节X、Y坐标
        measure.x = currentX;
        measure.y = system.y;
        
        // 更新小节内所有音符的X、Y坐标
        for (const voice of measure.voices) {
          for (const note of voice) {
            // 更新X坐标(如果有偏移)
            if (xOffset !== 0) {
              note.x += xOffset;
            }
            // 重要:更新Y坐标,使音符跟随所在行的Y位置
            // 音符Y = 行Y + 行高度的一半(垂直居中)
            note.y = system.y + this.config.systemHeight / 2;
          }
        }
        
        // 累加X坐标
        currentX += measure.width;
      }
    }
  }

  /**
   * 计算统计信息
   */
  private calculateStats(systems: JianpuSystem[], startTime: number): SystemLayoutStats {
    const measureCounts = systems.map(s => s.measures.length);
    const totalMeasures = measureCounts.reduce((a, b) => a + b, 0);
    
    return {
      systemCount: systems.length,
      measureCount: totalMeasures,
      maxMeasuresPerSystem: measureCounts.length > 0 ? Math.max(...measureCounts) : 0,
      minMeasuresPerSystem: measureCounts.length > 0 ? Math.min(...measureCounts) : 0,
      avgMeasuresPerSystem: systems.length > 0 ? totalMeasures / systems.length : 0,
      totalHeight: this.calculateTotalHeight(systems),
      layoutTime: performance.now() - startTime,
    };
  }

  /**
   * 计算总高度
   */
  private calculateTotalHeight(systems: JianpuSystem[]): number {
    if (systems.length === 0) return 0;
    
    const lastSystem = systems[systems.length - 1];
    return lastSystem.y + lastSystem.height;
  }

  /**
   * 创建空统计对象
   */
  private createEmptyStats(startTime: number): SystemLayoutStats {
    return {
      systemCount: 0,
      measureCount: 0,
      maxMeasuresPerSystem: 0,
      minMeasuresPerSystem: 0,
      avgMeasuresPerSystem: 0,
      totalHeight: 0,
      layoutTime: performance.now() - startTime,
    };
  }

  // ==================== 公共方法 ====================

  /**
   * 获取当前配置
   */
  getConfig(): SystemLayoutConfig {
    return { ...this.config };
  }

  /**
   * 更新配置
   */
  updateConfig(config: Partial<SystemLayoutConfig>): void {
    Object.assign(this.config, config);
  }

  /**
   * 计算指定小节数所需的最小行数
   * 
   * @param measureWidths 小节宽度数组
   * @returns 最小行数
   */
  estimateSystemCount(measureWidths: number[]): number {
    const { systemWidth, marginLeft } = this.config;
    const availableWidth = systemWidth - marginLeft * 2;
    
    let systemCount = 1;
    let currentWidth = 0;
    
    for (const width of measureWidths) {
      if (currentWidth + width > availableWidth && currentWidth > 0) {
        systemCount++;
        currentWidth = width;
      } else {
        currentWidth += width;
      }
    }
    
    return systemCount;
  }

  /**
   * 计算给定小节在第几行
   * 
   * @param systems 行数组
   * @param measureIndex 小节索引
   * @returns 行索引(未找到返回-1)
   */
  findSystemForMeasure(systems: JianpuSystem[], measureIndex: number): number {
    for (let i = 0; i < systems.length; i++) {
      const system = systems[i];
      for (const measure of system.measures) {
        if (measure.index === measureIndex) {
          return i;
        }
      }
    }
    return -1;
  }

  /**
   * 获取指定行的小节范围
   * 
   * @param systems 行数组
   * @param systemIndex 行索引
   * @returns 小节范围 [start, end](未找到返回null)
   */
  getMeasureRange(systems: JianpuSystem[], systemIndex: number): [number, number] | null {
    if (systemIndex < 0 || systemIndex >= systems.length) {
      return null;
    }
    
    const system = systems[systemIndex];
    if (system.measures.length === 0) {
      return null;
    }
    
    const start = system.measures[0].index;
    const end = system.measures[system.measures.length - 1].index;
    return [start, end];
  }
}

// ==================== 工厂函数 ====================

/**
 * 创建行布局引擎
 */
export function createSystemLayoutEngine(config?: Partial<SystemLayoutConfig>): SystemLayoutEngine {
  return new SystemLayoutEngine(config);
}

// ==================== 工具函数 ====================

/**
 * 计算最优行分配
 * 
 * 使用动态规划找到最均衡的行分配方案
 * 
 * @param measureWidths 小节宽度数组
 * @param systemWidth 行宽度
 * @param marginLeft 左边距
 * @returns 每行的小节数数组
 */
export function calculateOptimalSystemAllocation(
  measureWidths: number[],
  systemWidth: number,
  marginLeft: number = 20
): number[] {
  const availableWidth = systemWidth - marginLeft * 2;
  const n = measureWidths.length;
  
  if (n === 0) return [];
  if (n === 1) return [1];
  
  // 计算前缀和,用于快速计算区间宽度
  const prefixSum = [0];
  for (const w of measureWidths) {
    prefixSum.push(prefixSum[prefixSum.length - 1] + w);
  }
  
  // 计算从i到j的小节总宽度
  const getRangeWidth = (i: number, j: number) => prefixSum[j + 1] - prefixSum[i];
  
  // 贪心分配
  const result: number[] = [];
  let start = 0;
  
  while (start < n) {
    let end = start;
    let currentWidth = measureWidths[start];
    
    // 尽可能多地添加小节
    while (end + 1 < n && currentWidth + measureWidths[end + 1] <= availableWidth) {
      end++;
      currentWidth += measureWidths[end];
    }
    
    result.push(end - start + 1);
    start = end + 1;
  }
  
  return result;
}

/**
 * 验证行布局结果
 * 
 * @param systems 行数组
 * @param systemWidth 期望的行宽度
 * @returns 验证结果
 */
export function validateSystemLayout(
  systems: JianpuSystem[],
  systemWidth: number
): { valid: boolean; errors: string[] } {
  const errors: string[] = [];
  
  for (let i = 0; i < systems.length; i++) {
    const system = systems[i];
    
    // 检查行是否为空
    if (system.measures.length === 0) {
      errors.push(`行 ${i} 没有小节`);
    }
    
    // 检查小节总宽度是否超过行宽度(允许1像素误差)
    const totalMeasureWidth = system.measures.reduce((sum, m) => sum + m.width, 0);
    if (totalMeasureWidth > system.width + 1) {
      errors.push(`行 ${i} 小节总宽度 ${totalMeasureWidth.toFixed(2)} 超过行宽度 ${system.width}`);
    }
    
    // 检查小节X坐标连续性
    let expectedX = system.x;
    for (const measure of system.measures) {
      if (Math.abs(measure.x - expectedX) > 0.01) {
        errors.push(`行 ${i} 小节 ${measure.index} X坐标不连续: 期望 ${expectedX.toFixed(2)}, 实际 ${measure.x.toFixed(2)}`);
      }
      expectedX += measure.width;
    }
    
    // 检查小节Y坐标
    for (const measure of system.measures) {
      if (measure.y !== system.y) {
        errors.push(`行 ${i} 小节 ${measure.index} Y坐标错误: 期望 ${system.y}, 实际 ${measure.y}`);
      }
    }
  }
  
  // 检查行Y坐标递增
  for (let i = 1; i < systems.length; i++) {
    if (systems[i].y <= systems[i - 1].y) {
      errors.push(`行 ${i} Y坐标 ${systems[i].y} 应该大于行 ${i - 1} Y坐标 ${systems[i - 1].y}`);
    }
  }
  
  return {
    valid: errors.length === 0,
    errors,
  };
}

/**
 * 获取小节所在行的信息
 * 
 * @param systems 行数组
 * @param measureIndex 小节索引
 * @returns 行信息(未找到返回null)
 */
export function getSystemInfoForMeasure(
  systems: JianpuSystem[],
  measureIndex: number
): { system: JianpuSystem; systemIndex: number; measureIndexInSystem: number } | null {
  for (let sysIndex = 0; sysIndex < systems.length; sysIndex++) {
    const system = systems[sysIndex];
    for (let i = 0; i < system.measures.length; i++) {
      if (system.measures[i].index === measureIndex) {
        return {
          system,
          systemIndex: sysIndex,
          measureIndexInSystem: i,
        };
      }
    }
  }
  return null;
}