All files / src/graph gateway-router.ts

100% Statements 284/284
100% Branches 185/185
100% Functions 34/34
100% Lines 280/280

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 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811                                                                                                  115x 18x   97x 97x   97x 714x 27x 12x       85x               170x 17x   153x 153x   153x 1272x 286x 18x       135x       73x         73x 8x   65x               9x 9x 9x 9x 9x               25x 25x 25x 25x 25x                           70x 70x 70x 70x   70x 57x 57x 55x                   2x 2x 16x 6x     2x 2x               13x 70x     70x 70x                 11x 11x 11x 11x 11x               12x 12x 12x 12x 12x               54x 54x 54x 54x   54x 39x           15x 54x 54x                           154x 5x   149x   1565x                       6x 6x 24x 4x     6x       4x 4x 5x 3x     4x       6x   6x     6x 4x             2x       12x 12x 12x 12x   12x   12x 3x         3x 2x         10x     12x 4x 1x         3x             6x 6x 12x 12x     12x         12x 5x                 1x               10x 10x 10x 10x   10x   10x 3x         3x 2x         8x     10x 4x 1x         3x             4x 4x 10x 10x     10x         10x 3x                 1x                         16x 1x   15x 15x 15x               15x       32x 1x   31x 31x 31x               31x       14x 14x 14x 14x               14x       13x 13x 13x 13x               13x                   82x 82x 82x   82x 126x 126x 126x 23x 103x 46x   57x       82x 82x   82x                         61x 61x 61x   61x 77x 77x 77x 21x 56x 17x   39x       61x 61x   61x                                                 82x 82x     82x 16x 16x 16x           12x 12x         82x 32x 32x 32x           28x 28x         82x 82x               61x 61x   61x 14x 14x 14x 11x 11x       61x 13x 13x 13x 12x 12x       61x 61x                   86x 9x           77x 7x           70x               12x           28x                 82x 82x 82x     82x 82x   82x 130x 130x 4x 4x 4x   126x       82x             82x 82x         82x 12x       12x     82x 28x       28x     82x 80x 80x   82x   82x 82x 86x               86x 86x     82x             61x 61x 61x 61x   61x 61x   61x 83x 83x 6x 6x 6x   77x       61x           61x 61x         61x 11x       11x     61x 12x       12x     61x 61x 54x 54x 54x     61x    
import type { Bounds, Point } from '../types';
import { routeOrthogonalEdge } from './orthogonal-router';
 
export interface GatewayFlowInfo {
  flow: any;
  targetBounds: Bounds;
  isFeedback?: boolean;
  targetPort?: 'top' | 'bottom' | 'left' | 'right';
}
 
export interface GatewayIncomingFlowInfo {
  flow: any;
  sourceBounds: Bounds;
  isFeedback?: boolean;
}
 
export interface GatewayRouteOptions {
  gatewayBounds: Bounds;
  allBounds?: Bounds[];
  hasIncomingFeedback?: boolean;
  usedPorts?: Set<'top' | 'bottom' | 'left' | 'right'>;
}
 
export interface GatewayIncomingRouteOptions {
  gatewayBounds: Bounds;
  allBounds?: Bounds[];
  hasIncomingFeedback?: boolean;
  usedPorts?: Set<'top' | 'bottom' | 'left' | 'right'>;
}
 
export interface LinearSpan {
  start: number;
  end: number;
}
 
interface CorridorEndpoints {
  vStart: number;
  vEnd: number;
  hStart: number;
  hEnd: number;
  hY: number;
  vX: number;
}
 
export function isVerticalCorridorClear(
  x: number,
  span: LinearSpan,
  obstacles?: Bounds[]
): boolean {
  if (!obstacles || obstacles.length === 0) {
    return true;
  }
  const minY = Math.min(span.start, span.end);
  const maxY = Math.max(span.start, span.end);
 
  for (const b of obstacles) {
    if (x > b.x && x < b.x + b.width) {
      if (Math.max(minY, b.y) < Math.min(maxY, b.y + b.height)) {
        return false;
      }
    }
  }
  return true;
}
 
export function isHorizontalCorridorClear(
  y: number,
  span: LinearSpan,
  obstacles?: Bounds[]
): boolean {
  if (!obstacles || obstacles.length === 0) {
    return true;
  }
  const minX = Math.min(span.start, span.end);
  const maxX = Math.max(span.start, span.end);
 
  for (const b of obstacles) {
    if (y > b.y && y < b.y + b.height) {
      if (Math.max(minX, b.x) < Math.min(maxX, b.x + b.width)) {
        return false;
      }
    }
  }
  return true;
}
 
function checkDirectPortClear(endpoints: CorridorEndpoints, obstacles?: Bounds[]): boolean {
  const vClear = isVerticalCorridorClear(
    endpoints.vX,
    { start: endpoints.vStart, end: endpoints.vEnd },
    obstacles
  );
  if (!vClear) {
    return false;
  }
  return isHorizontalCorridorClear(
    endpoints.hY,
    { start: endpoints.hStart, end: endpoints.hEnd },
    obstacles
  );
}
 
function routeDirectTop(gw: Bounds, tgt: Bounds): Point[] {
  const exitX = Math.round(gw.x + gw.width / 2);
  const exitY = gw.y;
  const entryX = tgt.x;
  const entryY = Math.round(tgt.y + tgt.height / 2);
  return [
    { x: exitX, y: exitY },
    { x: exitX, y: entryY },
    { x: entryX, y: entryY },
  ];
}
 
function routeDirectBottom(gw: Bounds, tgt: Bounds): Point[] {
  const exitX = Math.round(gw.x + gw.width / 2);
  const exitY = gw.y + gw.height;
  const entryX = tgt.x;
  const entryY = Math.round(tgt.y + tgt.height / 2);
  return [
    { x: exitX, y: exitY },
    { x: exitX, y: entryY },
    { x: entryX, y: entryY },
  ];
}
 
interface DirectRightOptions {
  stepXOffset: number;
  collinearTgtX?: number;
  allBounds?: Bounds[];
}
 
function routeDirectRight(gw: Bounds, tgt: Bounds, opts: DirectRightOptions): Point[] {
  const exitX = gw.x + gw.width;
  const exitY = Math.round(gw.y + gw.height / 2);
  const entryX = tgt.x;
  const entryY = Math.round(tgt.y + tgt.height / 2);
 
  if (exitY === entryY) {
    const obstacles = getOtherObstacles({ allBounds: opts.allBounds, gw }, tgt);
    if (isHorizontalCorridorClear(exitY, { start: exitX, end: entryX }, obstacles)) {
      return [
        { x: exitX, y: exitY },
        { x: entryX, y: entryY },
      ];
    }
    // Something now sits between the gateway and its collinear target on
    // this same row (e.g. a chain of same-track nodes a bypass edge jumps
    // over, per issue #88). Detour below it: corridor routing is currently
    // unwired (#81), so this is the only avoidance a multi-rank collinear
    // edge gets.
    let channelY = exitY;
    for (const b of obstacles) {
      if (Math.max(exitX, b.x) < Math.min(entryX, b.x + b.width)) {
        channelY = Math.max(channelY, b.y + b.height);
      }
    }
    channelY += 40;
    return [
      { x: exitX, y: exitY },
      { x: exitX, y: channelY },
      { x: entryX, y: channelY },
      { x: entryX, y: entryY },
    ];
  }
 
  const defaultStepX = entryX - exitX > 100 ? entryX - 30 : Math.round((exitX + entryX) / 2);
  const baseStepX = opts.collinearTgtX
    ? Math.round((exitX + opts.collinearTgtX) / 2)
    : defaultStepX;
  const stepX = baseStepX + opts.stepXOffset;
  return [
    { x: exitX, y: exitY },
    { x: stepX, y: exitY },
    { x: stepX, y: entryY },
    { x: entryX, y: entryY },
  ];
}
 
function routeDirectIncomingTop(src: Bounds, gw: Bounds): Point[] {
  const exitX = src.x + src.width;
  const exitY = Math.round(src.y + src.height / 2);
  const entryX = Math.round(gw.x + gw.width / 2);
  const entryY = gw.y;
  return [
    { x: exitX, y: exitY },
    { x: entryX, y: exitY },
    { x: entryX, y: entryY },
  ];
}
 
function routeDirectIncomingBottom(src: Bounds, gw: Bounds): Point[] {
  const exitX = src.x + src.width;
  const exitY = Math.round(src.y + src.height / 2);
  const entryX = Math.round(gw.x + gw.width / 2);
  const entryY = gw.y + gw.height;
  return [
    { x: exitX, y: exitY },
    { x: entryX, y: exitY },
    { x: entryX, y: entryY },
  ];
}
 
function routeDirectIncomingLeft(src: Bounds, gw: Bounds, stepXOffset = 0): Point[] {
  const exitX = src.x + src.width;
  const exitY = Math.round(src.y + src.height / 2);
  const entryX = gw.x;
  const entryY = Math.round(gw.y + gw.height / 2);
 
  if (exitY === entryY) {
    return [
      { x: exitX, y: exitY },
      { x: entryX, y: entryY },
    ];
  }
 
  const baseStepX = entryX - exitX > 100 ? entryX - 30 : Math.round((exitX + entryX) / 2);
  const stepX = baseStepX + stepXOffset;
  return [
    { x: exitX, y: exitY },
    { x: stepX, y: exitY },
    { x: stepX, y: entryY },
    { x: entryX, y: entryY },
  ];
}
 
interface ObstaclesContext {
  allBounds?: Bounds[];
  gw: Bounds;
}
 
function getOtherObstacles(ctx: ObstaclesContext, other: Bounds): Bounds[] {
  if (!ctx.allBounds) {
    return [];
  }
  return ctx.allBounds.filter(
    (b) =>
      !(b.x === ctx.gw.x && b.y === ctx.gw.y && b.width === ctx.gw.width) &&
      !(b.x === other.x && b.y === other.y && b.width === other.width)
  );
}
 
interface TargetPortRouteOptions {
  exitPort: 'right' | 'bottom' | 'top';
  allBounds?: Bounds[];
  collinearTgtX?: number;
}
 
function findObstacleAboveTarget(entryX: number, tgtY: number, obstacles: Bounds[]): number {
  let maxObstacleBottom = -Infinity;
  for (const b of obstacles) {
    if (entryX > b.x && entryX < b.x + b.width && b.y + b.height <= tgtY) {
      maxObstacleBottom = Math.max(maxObstacleBottom, b.y + b.height);
    }
  }
  return maxObstacleBottom;
}
 
function findObstacleBelowTarget(entryX: number, tgtBottomY: number, obstacles: Bounds[]): number {
  let minObstacleTop = Infinity;
  for (const b of obstacles) {
    if (entryX > b.x && entryX < b.x + b.width && b.y >= tgtBottomY) {
      minObstacleTop = Math.min(minObstacleTop, b.y);
    }
  }
  return minObstacleTop;
}
 
function routeOppositePortStep(exit: Point, entry: Point, obstacles: Bounds[]): Point[] | null {
  const midY = Math.round((exit.y + entry.y) / 2);
  const stepClear =
    isVerticalCorridorClear(exit.x, { start: exit.y, end: midY }, obstacles) &&
    isHorizontalCorridorClear(midY, { start: exit.x, end: entry.x }, obstacles) &&
    isVerticalCorridorClear(entry.x, { start: midY, end: entry.y }, obstacles);
  if (stepClear) {
    return [
      { x: exit.x, y: exit.y },
      { x: exit.x, y: midY },
      { x: entry.x, y: midY },
      { x: entry.x, y: entry.y },
    ];
  }
  return null;
}
 
function routeToTargetTop(gw: Bounds, tgt: Bounds, opts: TargetPortRouteOptions): Point[] {
  const exitX = opts.exitPort === 'bottom' ? Math.round(gw.x + gw.width / 2) : gw.x + gw.width;
  const exitY = opts.exitPort === 'bottom' ? gw.y + gw.height : Math.round(gw.y + gw.height / 2);
  const entryX = Math.round(tgt.x + tgt.width / 2);
  const entryY = tgt.y;
 
  const obstacles = getOtherObstacles({ allBounds: opts.allBounds, gw }, tgt);
 
  if (opts.exitPort === 'bottom') {
    const stepPts = routeOppositePortStep(
      { x: exitX, y: exitY },
      { x: entryX, y: entryY },
      obstacles
    );
    if (stepPts) {
      return stepPts;
    }
  }
 
  const directClear =
    isHorizontalCorridorClear(exitY, { start: exitX, end: entryX }, obstacles) &&
    isVerticalCorridorClear(entryX, { start: exitY, end: entryY }, obstacles);
 
  if (directClear) {
    if (exitY === entryY) {
      return [
        { x: exitX, y: exitY },
        { x: entryX, y: entryY },
      ];
    }
    return [
      { x: exitX, y: exitY },
      { x: entryX, y: exitY },
      { x: entryX, y: entryY },
    ];
  }
 
  const maxBottom = findObstacleAboveTarget(entryX, entryY, obstacles);
  const gapY = maxBottom > -Infinity ? Math.round((maxBottom + entryY) / 2) : entryY - 30;
  const defaultStepX = entryX - exitX > 100 ? Math.round((exitX + entryX) / 2) : entryX - 30;
  const stepX = opts.collinearTgtX ? Math.round((exitX + opts.collinearTgtX) / 2) : defaultStepX;
 
  const stepClear =
    isHorizontalCorridorClear(exitY, { start: exitX, end: stepX }, obstacles) &&
    isVerticalCorridorClear(stepX, { start: exitY, end: gapY }, obstacles) &&
    isHorizontalCorridorClear(gapY, { start: stepX, end: entryX }, obstacles) &&
    isVerticalCorridorClear(entryX, { start: gapY, end: entryY }, obstacles);
 
  if (stepClear) {
    return [
      { x: exitX, y: exitY },
      { x: stepX, y: exitY },
      { x: stepX, y: gapY },
      { x: entryX, y: gapY },
      { x: entryX, y: entryY },
    ];
  }
 
  return [
    { x: exitX, y: exitY },
    { x: entryX, y: exitY },
    { x: entryX, y: entryY },
  ];
}
 
function routeToTargetBottom(gw: Bounds, tgt: Bounds, opts: TargetPortRouteOptions): Point[] {
  const exitX = opts.exitPort === 'top' ? Math.round(gw.x + gw.width / 2) : gw.x + gw.width;
  const exitY = opts.exitPort === 'top' ? gw.y : Math.round(gw.y + gw.height / 2);
  const entryX = Math.round(tgt.x + tgt.width / 2);
  const entryY = tgt.y + tgt.height;
 
  const obstacles = getOtherObstacles({ allBounds: opts.allBounds, gw }, tgt);
 
  if (opts.exitPort === 'top') {
    const stepPts = routeOppositePortStep(
      { x: exitX, y: exitY },
      { x: entryX, y: entryY },
      obstacles
    );
    if (stepPts) {
      return stepPts;
    }
  }
 
  const directClear =
    isHorizontalCorridorClear(exitY, { start: exitX, end: entryX }, obstacles) &&
    isVerticalCorridorClear(entryX, { start: entryY, end: exitY }, obstacles);
 
  if (directClear) {
    if (exitY === entryY) {
      return [
        { x: exitX, y: exitY },
        { x: entryX, y: entryY },
      ];
    }
    return [
      { x: exitX, y: exitY },
      { x: entryX, y: exitY },
      { x: entryX, y: entryY },
    ];
  }
 
  const minTop = findObstacleBelowTarget(entryX, entryY, obstacles);
  const gapY = minTop < Infinity ? Math.round((entryY + minTop) / 2) : entryY + 30;
  const defaultStepX = entryX - exitX > 100 ? Math.round((exitX + entryX) / 2) : entryX - 30;
  const stepX = opts.collinearTgtX ? Math.round((exitX + opts.collinearTgtX) / 2) : defaultStepX;
 
  const stepClear =
    isHorizontalCorridorClear(exitY, { start: exitX, end: stepX }, obstacles) &&
    isVerticalCorridorClear(stepX, { start: exitY, end: gapY }, obstacles) &&
    isHorizontalCorridorClear(gapY, { start: stepX, end: entryX }, obstacles) &&
    isVerticalCorridorClear(entryX, { start: gapY, end: entryY }, obstacles);
 
  if (stepClear) {
    return [
      { x: exitX, y: exitY },
      { x: stepX, y: exitY },
      { x: stepX, y: gapY },
      { x: entryX, y: gapY },
      { x: entryX, y: entryY },
    ];
  }
 
  return [
    { x: exitX, y: exitY },
    { x: entryX, y: exitY },
    { x: entryX, y: entryY },
  ];
}
 
interface PortCheckContext {
  obstacles?: Bounds[];
  targetPort?: 'top' | 'bottom' | 'left' | 'right';
}
 
function canUseTopPort(gw: Bounds, tgt: Bounds, ctx?: PortCheckContext): boolean {
  if (ctx?.targetPort === 'bottom' && gw.y - (tgt.y + tgt.height) < 40) {
    return false;
  }
  const exitX = Math.round(gw.x + gw.width / 2);
  const entryY = Math.round(tgt.y + tgt.height / 2);
  const endpoints: CorridorEndpoints = {
    vX: exitX,
    vStart: entryY,
    vEnd: gw.y,
    hY: entryY,
    hStart: exitX,
    hEnd: tgt.x,
  };
  return checkDirectPortClear(endpoints, ctx?.obstacles);
}
 
function canUseBottomPort(gw: Bounds, tgt: Bounds, ctx?: PortCheckContext): boolean {
  if (ctx?.targetPort === 'top' && tgt.y - (gw.y + gw.height) < 40) {
    return false;
  }
  const exitX = Math.round(gw.x + gw.width / 2);
  const entryY = Math.round(tgt.y + tgt.height / 2);
  const endpoints: CorridorEndpoints = {
    vX: exitX,
    vStart: gw.y + gw.height,
    vEnd: entryY,
    hY: entryY,
    hStart: exitX,
    hEnd: tgt.x,
  };
  return checkDirectPortClear(endpoints, ctx?.obstacles);
}
 
function canUseIncomingTopPort(src: Bounds, gw: Bounds, obstacles?: Bounds[]): boolean {
  const exitX = src.x + src.width;
  const exitY = Math.round(src.y + src.height / 2);
  const entryX = Math.round(gw.x + gw.width / 2);
  const endpoints: CorridorEndpoints = {
    vX: entryX,
    vStart: exitY,
    vEnd: gw.y,
    hY: exitY,
    hStart: exitX,
    hEnd: entryX,
  };
  return checkDirectPortClear(endpoints, obstacles);
}
 
function canUseIncomingBottomPort(src: Bounds, gw: Bounds, obstacles?: Bounds[]): boolean {
  const exitX = src.x + src.width;
  const exitY = Math.round(src.y + src.height / 2);
  const entryX = Math.round(gw.x + gw.width / 2);
  const endpoints: CorridorEndpoints = {
    vX: entryX,
    vStart: gw.y + gw.height,
    vEnd: exitY,
    hY: exitY,
    hStart: exitX,
    hEnd: entryX,
  };
  return checkDirectPortClear(endpoints, obstacles);
}
 
interface CategorizedFlows {
  above: GatewayFlowInfo[];
  center: GatewayFlowInfo[];
  below: GatewayFlowInfo[];
}
 
function categorizeFlows(flows: GatewayFlowInfo[], gwCenterY: number): CategorizedFlows {
  const above: GatewayFlowInfo[] = [];
  const center: GatewayFlowInfo[] = [];
  const below: GatewayFlowInfo[] = [];
 
  for (const f of flows) {
    const tgtCenterY = f.targetBounds.y + f.targetBounds.height / 2;
    const diff = tgtCenterY - gwCenterY;
    if (diff < -2) {
      above.push(f);
    } else if (diff > 2) {
      below.push(f);
    } else {
      center.push(f);
    }
  }
 
  above.sort((a, b) => a.targetBounds.y - b.targetBounds.y);
  below.sort((a, b) => b.targetBounds.y - a.targetBounds.y);
 
  return { above, center, below };
}
 
interface CategorizedIncomingFlows {
  above: GatewayIncomingFlowInfo[];
  center: GatewayIncomingFlowInfo[];
  below: GatewayIncomingFlowInfo[];
}
 
function categorizeIncomingFlows(
  flows: GatewayIncomingFlowInfo[],
  gwCenterY: number
): CategorizedIncomingFlows {
  const above: GatewayIncomingFlowInfo[] = [];
  const center: GatewayIncomingFlowInfo[] = [];
  const below: GatewayIncomingFlowInfo[] = [];
 
  for (const f of flows) {
    const srcCenterY = f.sourceBounds.y + f.sourceBounds.height / 2;
    const diff = srcCenterY - gwCenterY;
    if (diff < -2) {
      above.push(f);
    } else if (diff > 2) {
      below.push(f);
    } else {
      center.push(f);
    }
  }
 
  above.sort((a, b) => a.sourceBounds.y - b.sourceBounds.y);
  below.sort((a, b) => b.sourceBounds.y - a.sourceBounds.y);
 
  return { above, center, below };
}
 
interface PortAssignments {
  topFlow?: GatewayFlowInfo;
  bottomFlow?: GatewayFlowInfo;
  rightFlows: GatewayFlowInfo[];
}
 
interface IncomingPortAssignments {
  topFlow?: GatewayIncomingFlowInfo;
  bottomFlow?: GatewayIncomingFlowInfo;
  leftFlows: GatewayIncomingFlowInfo[];
}
 
interface AssignmentContext {
  gw: Bounds;
  allBounds?: Bounds[];
}
 
function computePortAssignments(
  cat: CategorizedFlows,
  freePorts: { top: boolean; bottom: boolean; right: boolean },
  ctx: AssignmentContext
): PortAssignments {
  const assignments: PortAssignments = { rightFlows: [] };
  const obstaclesParams: ObstaclesContext = { allBounds: ctx.allBounds, gw: ctx.gw };
 
  // Assign Top port
  if (freePorts.top && cat.above.length > 0) {
    const candidate = cat.above[0];
    const obstacles = getOtherObstacles(obstaclesParams, candidate.targetBounds);
    if (
      canUseTopPort(ctx.gw, candidate.targetBounds, {
        obstacles,
        targetPort: candidate.targetPort,
      })
    ) {
      assignments.topFlow = candidate;
      cat.above.shift();
    }
  }
 
  // Assign Bottom port
  if (freePorts.bottom && cat.below.length > 0) {
    const candidate = cat.below[0];
    const obstacles = getOtherObstacles(obstaclesParams, candidate.targetBounds);
    if (
      canUseBottomPort(ctx.gw, candidate.targetBounds, {
        obstacles,
        targetPort: candidate.targetPort,
      })
    ) {
      assignments.bottomFlow = candidate;
      cat.below.shift();
    }
  }
 
  // All remaining flows exit Right
  assignments.rightFlows.push(...cat.center, ...cat.above, ...cat.below);
  return assignments;
}
 
function computeIncomingPortAssignments(
  cat: CategorizedIncomingFlows,
  freePorts: { top: boolean; bottom: boolean; left: boolean },
  ctx: AssignmentContext
): IncomingPortAssignments {
  const assignments: IncomingPortAssignments = { leftFlows: [] };
  const obstaclesParams: ObstaclesContext = { allBounds: ctx.allBounds, gw: ctx.gw };
 
  if (freePorts.top && cat.above.length > 0) {
    const candidate = cat.above[0];
    const obstacles = getOtherObstacles(obstaclesParams, candidate.sourceBounds);
    if (canUseIncomingTopPort(candidate.sourceBounds, ctx.gw, obstacles)) {
      assignments.topFlow = candidate;
      cat.above.shift();
    }
  }
 
  if (freePorts.bottom && cat.below.length > 0) {
    const candidate = cat.below[0];
    const obstacles = getOtherObstacles(obstaclesParams, candidate.sourceBounds);
    if (canUseIncomingBottomPort(candidate.sourceBounds, ctx.gw, obstacles)) {
      assignments.bottomFlow = candidate;
      cat.below.shift();
    }
  }
 
  assignments.leftFlows.push(...cat.center, ...cat.above, ...cat.below);
  return assignments;
}
 
interface RightFlowRouteContext {
  allBounds?: Bounds[];
  stepOffset: number;
  collinearTgtX?: number;
}
 
function routeRightFlow(gw: Bounds, rf: GatewayFlowInfo, ctx: RightFlowRouteContext): Point[] {
  if (rf.targetPort === 'top') {
    return routeToTargetTop(gw, rf.targetBounds, {
      exitPort: 'right',
      allBounds: ctx.allBounds,
      collinearTgtX: ctx.collinearTgtX,
    });
  }
  if (rf.targetPort === 'bottom') {
    return routeToTargetBottom(gw, rf.targetBounds, {
      exitPort: 'right',
      allBounds: ctx.allBounds,
      collinearTgtX: ctx.collinearTgtX,
    });
  }
  return routeDirectRight(gw, rf.targetBounds, {
    stepXOffset: ctx.stepOffset,
    collinearTgtX: ctx.collinearTgtX,
    allBounds: ctx.allBounds,
  });
}
 
function routeTopFlow(gw: Bounds, tf: GatewayFlowInfo, allBounds?: Bounds[]): Point[] {
  return tf.targetPort === 'bottom'
    ? routeToTargetBottom(gw, tf.targetBounds, { exitPort: 'top', allBounds })
    : routeDirectTop(gw, tf.targetBounds);
}
 
function routeBottomFlow(gw: Bounds, bf: GatewayFlowInfo, allBounds?: Bounds[]): Point[] {
  return bf.targetPort === 'top'
    ? routeToTargetTop(gw, bf.targetBounds, { exitPort: 'bottom', allBounds })
    : routeDirectBottom(gw, bf.targetBounds);
}
 
export function routeGatewayOutgoingEdges(
  flows: GatewayFlowInfo[],
  options: GatewayRouteOptions
): Map<string, Point[]> {
  const result = new Map<string, Point[]>();
  const gw = options.gatewayBounds;
  const gwCenterY = gw.y + gw.height / 2;
 
  // Separate feedback loops from forward flows
  const forwardFlows: GatewayFlowInfo[] = [];
  let hasOutgoingFeedback = false;
 
  for (const f of flows) {
    const isBackwards = f.targetBounds.x < gw.x + gw.width;
    if (f.isFeedback || isBackwards) {
      hasOutgoingFeedback = true;
      const waypoints = routeOrthogonalEdge(gw, f.targetBounds, options.allBounds);
      result.set(f.flow.id, waypoints);
    } else {
      forwardFlows.push(f);
    }
  }
 
  const freePorts = {
    top: !options.usedPorts?.has('top'),
    bottom:
      !options.usedPorts?.has('bottom') && !hasOutgoingFeedback && !options.hasIncomingFeedback,
    right: true,
  };
 
  const cat = categorizeFlows(forwardFlows, gwCenterY);
  const assignments = computePortAssignments(cat, freePorts, {
    gw,
    allBounds: options.allBounds,
  });
 
  if (assignments.topFlow) {
    result.set(
      assignments.topFlow.flow.id,
      routeTopFlow(gw, assignments.topFlow, options.allBounds)
    );
    options.usedPorts?.add('top');
  }
 
  if (assignments.bottomFlow) {
    result.set(
      assignments.bottomFlow.flow.id,
      routeBottomFlow(gw, assignments.bottomFlow, options.allBounds)
    );
    options.usedPorts?.add('bottom');
  }
 
  const collinearFlow = assignments.rightFlows.find((rf) => {
    const tgtCenterY = Math.round(rf.targetBounds.y + rf.targetBounds.height / 2);
    return tgtCenterY === Math.round(gw.y + gw.height / 2);
  });
  const collinearTgtX = collinearFlow?.targetBounds.x;
 
  let stepOffset = 0;
  for (const rf of assignments.rightFlows) {
    result.set(
      rf.flow.id,
      routeRightFlow(gw, rf, {
        allBounds: options.allBounds,
        stepOffset,
        collinearTgtX,
      })
    );
    options.usedPorts?.add('right');
    stepOffset += 10;
  }
 
  return result;
}
 
export function routeGatewayIncomingEdges(
  flows: GatewayIncomingFlowInfo[],
  options: GatewayIncomingRouteOptions
): { routes: Map<string, Point[]>; usedPorts: Set<'top' | 'bottom' | 'left' | 'right'> } {
  const routes = new Map<string, Point[]>();
  const usedPorts = options.usedPorts || new Set<'top' | 'bottom' | 'left' | 'right'>();
  const gw = options.gatewayBounds;
  const gwCenterY = gw.y + gw.height / 2;
 
  const forwardFlows: GatewayIncomingFlowInfo[] = [];
  let hasIncomingFeedback = Boolean(options.hasIncomingFeedback);
 
  for (const f of flows) {
    const isBackwards = f.sourceBounds.x + f.sourceBounds.width > gw.x;
    if (f.isFeedback || isBackwards) {
      hasIncomingFeedback = true;
      const waypoints = routeOrthogonalEdge(f.sourceBounds, gw, options.allBounds);
      routes.set(f.flow.id, waypoints);
    } else {
      forwardFlows.push(f);
    }
  }
 
  const freePorts = {
    top: !usedPorts.has('top'),
    bottom: !usedPorts.has('bottom') && !hasIncomingFeedback,
    left: true,
  };
 
  const cat = categorizeIncomingFlows(forwardFlows, gwCenterY);
  const assignments = computeIncomingPortAssignments(cat, freePorts, {
    gw,
    allBounds: options.allBounds,
  });
 
  if (assignments.topFlow) {
    routes.set(
      assignments.topFlow.flow.id,
      routeDirectIncomingTop(assignments.topFlow.sourceBounds, gw)
    );
    usedPorts.add('top');
  }
 
  if (assignments.bottomFlow) {
    routes.set(
      assignments.bottomFlow.flow.id,
      routeDirectIncomingBottom(assignments.bottomFlow.sourceBounds, gw)
    );
    usedPorts.add('bottom');
  }
 
  let stepOffset = 0;
  for (const lf of assignments.leftFlows) {
    routes.set(lf.flow.id, routeDirectIncomingLeft(lf.sourceBounds, gw, stepOffset));
    usedPorts.add('left');
    stepOffset -= 10;
  }
 
  return { routes, usedPorts };
}