All files / Sources/Rendering/Core/ScalarBarActor index.js

92.41% Statements 390/422
79.62% Branches 86/108
84% Functions 21/25
92.28% Lines 383/415

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 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993                    1x                                     45x 45x 45x 45x                                               5x     3x 3x 3x 3x   3x 3x 3x 3x     3x 3x 3x           3x       3x   3x     3x 3x         3x                               3x 3x               3x   3x                                         3x                           4x 3x 3x     3x 3x   3x 3x                         4x   4x 4x     4x 4x 4x 4x 4x 4x 4x   4x 4x 4x   4x     4x   5x 4x 4x 4x 4x     5x 5x         5x     5x   5x     5x               4x 4x     4x   4x 3x     1x 1x 1x 1x 1x 1x 1x 1x       1x     1x   4x 4x 4x 4x             4x   4x 4x     4x     4x 4x 4x 4x 4x 4x           4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 33x 33x 33x           33x 33x 33x     33x 18x   33x 4x             4x 4x     4x 37x                         4x 4x 4x 4x 4x     4x 37x 37x     4x   4x 4x   4x     4x   4x   4x   4x       4x   3x   3x                 3x   3x 3x   3x 3x 3x   1x   1x   1x 1x 1x 1x 1x   4x                       4x   4x   4x   4x       4x 4x     13x                   13x   4x       3x     4x       3x     4x         4x   4x 4x       4x         4x 3x 3x 3x           4x             4x               34x 34x       34x 34x     34x 34x 34x   34x 34x     34x 34x 34x 3x 3x   3x 3x       3x   3x 3x     31x 31x   31x 10x 21x 21x   31x 21x 10x         34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x     34x 34x 34x 34x 34x 34x 34x 34x 34x   34x 34x           4x 4x     4x 4x 4x 4x 4x 4x   4x                 4x 4x   4x     4x     4x 4x 4x 3x 3x                           3x 3x     3x                 3x   1x 1x 1x 1x                   4x     4x       4x 4x 13x 13x   4x   9x         9x                         4x     4x   4x 4x 4x   21x   21x 21x                   4x         4x 4x 4x 4x 4x 4x     4x 4x 4x 4x       3x   4x       3x   4x       3x     4x 4x     4x 4x 4x       4x 4x 4x   4x 4x   4x 13x 13x 52x 52x 52x 52x 52x 52x 52x         52x   13x 13x 13x 13x 13x 13x     4x         4x 4x 4x 4x 4x 4x       1x   4x     4x   4x               4x                 4x 4x   4x 4x 4x 4x   4x 4x 4x   4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x     4x   4x                         5x   5x         5x         5x       5x                   5x                                                                   5x   5x 5x 4x     5x   5x 5x   5x                       5x 5x           5x               5x         1x          
import * as d3 from 'd3-scale';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';
import macro from 'vtk.js/Sources/macros';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkScalarsToColors from 'vtk.js/Sources/Common/Core/ScalarsToColors';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkPolyData from 'vtk.js/Sources/Common/DataModel/PolyData';
import vtkTexture from 'vtk.js/Sources/Rendering/Core/Texture';
 
const { VectorMode } = vtkScalarsToColors;
 
// ----------------------------------------------------------------------------
// vtkScalarBarActor
//
// Note log scales are currently not supported
//
// Developer note: This class is broken into the main class and a helper
// class. The main class holds view independent properties (those properties
// that do not change as the view's resolution/aspect ratio change). The
// helper class is instantiated one per view and holds properties that can
// depend on view specific values such as resolution. The helper class code
// could have been left to the View specific implementation (such as
// vtkWebGPUScalarBarActor) but is instead placed here to it can be shared by
// multiple rendering backends.
//
// ----------------------------------------------------------------------------
 
function applyTextStyle(ctx, style) {
  ctx.strokeStyle = style.strokeColor;
  ctx.lineWidth = style.strokeSize;
  ctx.fillStyle = style.fontColor;
  ctx.font = `${style.fontStyle} ${style.fontSize}px ${style.fontFamily}`;
}
 
// ----------------------------------------------------------------------------
// Default autoLayout function
// ----------------------------------------------------------------------------
 
// compute good values to use based on window size etc a bunch of heuristics
// here with hand tuned constants These values worked for me but really this
// method could be redically changed. The basic gist is
// 1) compute a resonable font size
// 2) render the text atlas using those font sizes
// 3) pick horizontal or vertical bsed on window size
// 4) based on the size of the title and tick labels rendered
//    compute the box size and position such that
//    the text will all fit nicely and the bar will be a resonable size
// 5) compute the bar segments based on the above settings
//
// Note that this function can and should read values from the
// ScalarBarActor but should only write values to the view dependent helper
// instance that is provided as those values are the ones that will be used
// for rendering.
//
function defaultAutoLayout(publicAPI, model) {
  return (helper) => {
    // we don't do a linear scale, the proportions for
    // a 700 pixel window differ from a 1400
    const lastSize = helper.getLastSize();
    const xAxisAdjust = (lastSize[0] / 700) ** 0.8;
    const yAxisAdjust = (lastSize[1] / 700) ** 0.8;
    const minAdjust = Math.min(xAxisAdjust, yAxisAdjust);
 
    const axisTextStyle = helper.getAxisTextStyle();
    const tickTextStyle = helper.getTickTextStyle();
    Object.assign(axisTextStyle, model.axisTextStyle);
    Object.assign(tickTextStyle, model.tickTextStyle);
 
    // compute a reasonable font size first
    axisTextStyle.fontSize = Math.max(24 * minAdjust, 12);
    if (helper.getLastAspectRatio() > 1.0) {
      tickTextStyle.fontSize = Math.max(20 * minAdjust, 10);
    } else E{
      tickTextStyle.fontSize = Math.max(16 * minAdjust, 10);
    }
 
    // rebuild the text atlas
    const textSizes = helper.updateTextureAtlas();
 
    // now compute the boxSize and pixel offsets, different algorithm
    // for horizonal versus vertical
    helper.setTopTitle(false);
 
    const boxSize = helper.getBoxSizeByReference();
 
    // if vertical
    if (helper.getLastAspectRatio() > 1.0) {
      helper.setTickLabelPixelOffset(0.3 * tickTextStyle.fontSize);
 
      // if the title will fit within the width of the bar then that looks
      // nicer to put it at the top (helper.topTitle), otherwise rotate it
      // and place it sideways
      Iif (
        textSizes.titleWidth <=
        textSizes.tickWidth +
          helper.getTickLabelPixelOffset() +
          0.8 * tickTextStyle.fontSize
      ) {
        helper.setTopTitle(true);
        helper.setAxisTitlePixelOffset(0.2 * tickTextStyle.fontSize);
        boxSize[0] =
          (2.0 *
            (textSizes.tickWidth +
              helper.getTickLabelPixelOffset() +
              0.8 * tickTextStyle.fontSize)) /
          lastSize[0];
        helper.setBoxPosition([0.98 - boxSize[0], -0.92]);
      } else {
        helper.setAxisTitlePixelOffset(0.2 * tickTextStyle.fontSize);
        boxSize[0] =
          (2.0 *
            (textSizes.titleHeight +
              helper.getAxisTitlePixelOffset() +
              textSizes.tickWidth +
              helper.getTickLabelPixelOffset() +
              0.8 * tickTextStyle.fontSize)) /
          lastSize[0];
        helper.setBoxPosition([0.99 - boxSize[0], -0.92]);
      }
      boxSize[1] = Math.max(1.2, Math.min(1.84 / yAxisAdjust, 1.84));
    } else E{
      // horizontal
      helper.setAxisTitlePixelOffset(1.2 * tickTextStyle.fontSize);
      helper.setTickLabelPixelOffset(0.1 * tickTextStyle.fontSize);
      const titleHeight = // total offset from top of bar (includes ticks)
        (2.0 *
          (0.8 * tickTextStyle.fontSize +
            textSizes.titleHeight +
            helper.getAxisTitlePixelOffset())) /
        lastSize[1];
      const tickWidth = (2.0 * textSizes.tickWidth) / lastSize[0];
      boxSize[0] = Math.min(
        1.9,
        Math.max(1.4, 1.4 * tickWidth * (helper.getTicks().length + 3))
      );
      boxSize[1] = titleHeight;
      helper.setBoxPosition([-0.5 * boxSize[0], -0.97]);
    }
 
    // recomute bar segments based on positioning
    helper.recomputeBarSegments(textSizes);
  };
}
 
// ----------------------------------------------------------------------------
// Default generateTicks function
// ----------------------------------------------------------------------------
 
// This function returns the default function used to generate vtkScalarBarActor ticks.
// The default function makes use of d3.scaleLinear() to generate 5 tick marks between
// the minimum and maximum values of the scalar bar. Customize this behavior by passing
// a function to vtkScalarBarActor.newInstance({ generateTicks: customGenerateTicks })
// or by calling scalarBarActor.setGenerateTicks(customGenerateTicks).
function defaultGenerateTicks(publicApi, model) {
  return (helper) => {
    const lastTickBounds = helper.getLastTickBounds();
    const scale = d3
      .scaleLinear()
      .domain([lastTickBounds[0], lastTickBounds[1]]);
    const ticks = scale.ticks(5);
    const format = scale.tickFormat(5);
 
    helper.setTicks(ticks);
    helper.setTickStrings(ticks.map(format));
  };
}
 
// many properties of this actor depend on the API specific view The main
// dependency being the resolution as that drives what font sizes to use.
// Bacause of this we need to do some of the calculations in a API specific
// subclass. But... we don't want a lot of duplicated code between WebGL and
// WebGPU for example so we have this helper class, that is designed to be
// fairly API independent so that API specific views can call this to do
// most of the work.
function vtkScalarBarActorHelper(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkScalarBarActorHelper');
 
  publicAPI.setRenderable = (renderable) => {
    Iif (model.renderable === renderable) {
      return;
    }
    model.renderable = renderable;
    model.barActor.setProperty(renderable.getProperty());
    model.barActor.setParentProp(renderable);
    model.barActor.setCoordinateSystemToDisplay();
    model.tmActor.setProperty(renderable.getProperty());
    model.tmActor.setParentProp(renderable);
    model.tmActor.setCoordinateSystemToDisplay();
 
    model.generateTicks = renderable.generateTicks;
    model.axisTextStyle = { ...renderable.getAxisTextStyle() };
    model.tickTextStyle = { ...renderable.getTickTextStyle() };
 
    publicAPI.modified();
  };
 
  publicAPI.updateAPISpecificData = (size, camera, renderWindow) => {
    // has the size changed?
    if (model.lastSize[0] !== size[0] || model.lastSize[1] !== size[1]) {
      model.lastSize[0] = size[0];
      model.lastSize[1] = size[1];
      model.lastAspectRatio = size[0] / size[1];
      model.forceUpdate = true;
    }
 
    const scalarsToColors = model.renderable.getScalarsToColors();
    Iif (!scalarsToColors || !model.renderable.getVisibility()) {
      return;
    }
 
    // make sure the lut is assigned to our mapper
    model.barMapper.setLookupTable(scalarsToColors);
 
    // camera should be the same for all views
    model.camera = camera;
 
    model.renderWindow = renderWindow;
 
    // did something significant change? If so rebuild a lot of things
    if (
      model.forceUpdate ||
      Math.max(
        scalarsToColors.getMTime(),
        publicAPI.getMTime(),
        model.renderable.getMTime()
      ) > model.lastRebuildTime.getMTime()
    ) {
      const range = scalarsToColors.getMappingRange();
      model.lastTickBounds = [...range];
 
      // compute tick marks for axes (update for log scale)
      model.renderable.getGenerateTicks()(publicAPI);
 
      if (model.renderable.getAutomated()) {
        model.renderable.getAutoLayout()(publicAPI);
      } else {
        // copy values from renderable
        model.axisTextStyle = { ...model.renderable.getAxisTextStyle() };
        model.tickTextStyle = { ...model.renderable.getTickTextStyle() };
        model.barPosition = [...model.renderable.getBarPosition()];
        model.barSize = [...model.renderable.getBarSize()];
        model.boxPosition = [...model.renderable.getBoxPosition()];
        model.boxSize = [...model.renderable.getBoxSize()];
        model.axisTitlePixelOffset = model.renderable.getAxisTitlePixelOffset();
        model.tickLabelPixelOffset = model.renderable.getTickLabelPixelOffset();
 
        // rebuild the texture only when force or changed bounds, face
        // visibility changes do to change the atlas
        const textSizes = publicAPI.updateTextureAtlas();
 
        // recompute bar segments based on positioning
        publicAPI.recomputeBarSegments(textSizes);
      }
      publicAPI.updatePolyDataForLabels();
      publicAPI.updatePolyDataForBarSegments();
      model.lastRebuildTime.modified();
      model.forceUpdate = false;
    }
  };
 
  // create the texture map atlas that contains the rendering of
  // all the text strings. Only needs to be called when the text strings
  // have changed (labels and ticks)
  publicAPI.updateTextureAtlas = () => {
    // set the text properties
    model.tmContext.textBaseline = 'bottom';
    model.tmContext.textAlign = 'left';
 
    // return some factors about the text atlas
    const results = {};
 
    // first the axislabel
    const newTmAtlas = new Map();
    let maxWidth = 0;
    let totalHeight = 1; // start one pixel in so we have a border
    applyTextStyle(model.tmContext, model.axisTextStyle);
    let metrics = model.tmContext.measureText(model.renderable.getAxisLabel());
    let entry = {
      height: metrics.actualBoundingBoxAscent + 2,
      startingHeight: totalHeight,
      width: metrics.width + 2,
      textStyle: model.axisTextStyle,
    };
    newTmAtlas.set(model.renderable.getAxisLabel(), entry);
    totalHeight += entry.height;
    maxWidth = entry.width;
    results.titleWidth = entry.width;
    results.titleHeight = entry.height;
 
    // and the ticks, NaN Below and Above
    results.tickWidth = 0;
    results.tickHeight = 0;
    applyTextStyle(model.tmContext, model.tickTextStyle);
    const strings = [...publicAPI.getTickStrings(), 'NaN', 'Below', 'Above'];
    for (let t = 0; t < strings.length; t++) {
      if (!newTmAtlas.has(strings[t])) {
        metrics = model.tmContext.measureText(strings[t]);
        entry = {
          height: metrics.actualBoundingBoxAscent + 2,
          startingHeight: totalHeight,
          width: metrics.width + 2,
          textStyle: model.tickTextStyle,
        };
        newTmAtlas.set(strings[t], entry);
        totalHeight += entry.height;
        Iif (maxWidth < entry.width) {
          maxWidth = entry.width;
        }
        if (results.tickWidth < entry.width) {
          results.tickWidth = entry.width;
        }
        if (results.tickHeight < entry.height) {
          results.tickHeight = entry.height;
        }
      }
    }
 
    // always use power of two to avoid interpolation
    // in cases where PO2 is required
    maxWidth = vtkMath.nearestPowerOfTwo(maxWidth);
    totalHeight = vtkMath.nearestPowerOfTwo(totalHeight);
 
    // set the tcoord values
    newTmAtlas.forEach((value) => {
      value.tcoords = [
        0.0,
        (totalHeight - value.startingHeight - value.height) / totalHeight,
        value.width / maxWidth,
        (totalHeight - value.startingHeight - value.height) / totalHeight,
        value.width / maxWidth,
        (totalHeight - value.startingHeight) / totalHeight,
        0.0,
        (totalHeight - value.startingHeight) / totalHeight,
      ];
    });
 
    // make sure we have power of two dimensions
    model.tmCanvas.width = maxWidth;
    model.tmCanvas.height = totalHeight;
    model.tmContext.textBaseline = 'bottom';
    model.tmContext.textAlign = 'left';
    model.tmContext.clearRect(0, 0, maxWidth, totalHeight);
 
    // draw the text onto the texture
    newTmAtlas.forEach((value, key) => {
      applyTextStyle(model.tmContext, value.textStyle);
      model.tmContext.fillText(key, 1, value.startingHeight + value.height - 1);
    });
 
    model.tmTexture.setCanvas(model.tmCanvas);
    // mark as modified since the canvas typically doesn't change
    model.tmTexture.modified();
    model._tmAtlas = newTmAtlas;
 
    return results;
  };
 
  publicAPI.computeBarSize = (textSizes) => {
    // compute orientation
    model.vertical = model.boxSize[1] > model.boxSize[0];
 
    const tickHeight = (2.0 * textSizes.tickHeight) / model.lastSize[1];
 
    const segSize = [1, 1];
 
    // horizontal and vertical have different astetics so adjust based on
    // orientation
    if (model.vertical) {
      const tickWidth =
        (2.0 * (textSizes.tickWidth + model.tickLabelPixelOffset)) /
        model.lastSize[0];
      Iif (model.topTitle) {
        const titleHeight =
          (2.0 * (textSizes.titleHeight + model.axisTitlePixelOffset)) /
          model.lastSize[1];
        model.barSize[0] = model.boxSize[0] - tickWidth;
        model.barSize[1] = model.boxSize[1] - titleHeight;
      } else {
        // rotated title so width is based off height
        const titleWidth =
          (2.0 * (textSizes.titleHeight + model.axisTitlePixelOffset)) /
          model.lastSize[0];
        model.barSize[0] = model.boxSize[0] - titleWidth - tickWidth;
        model.barSize[1] = model.boxSize[1];
      }
      model.barPosition[0] = model.boxPosition[0] + tickWidth;
      model.barPosition[1] = model.boxPosition[1];
      segSize[1] = tickHeight;
    } else {
      const tickWidth = (2.0 * textSizes.tickWidth - 8) / model.lastSize[0];
      const titleHeight =
        (2.0 * (textSizes.titleHeight + model.axisTitlePixelOffset)) /
        model.lastSize[1];
      model.barSize[0] = model.boxSize[0];
      model.barPosition[0] = model.boxPosition[0];
      model.barSize[1] = model.boxSize[1] - titleHeight;
      model.barPosition[1] = model.boxPosition[1];
      segSize[0] = tickWidth;
    }
    return segSize;
  };
 
  // based on all the settins compute a barSegments array
  // containing the segments of the scalar bar
  // each segment contains
  //   corners[4][2]
  //   title - e.g. NaN, Above, ticks
  //   scalars - the normalized scalars values to use for that segment
  //
  // Note that the bar consumes the space in the box that remains after
  // leaving room for the text labels
  publicAPI.recomputeBarSegments = (textSizes) => {
    // first compute the barSize/Position
    const segSize = publicAPI.computeBarSize(textSizes);
 
    model.barSegments = [];
 
    const startPos = [0.0, 0.0];
 
    // horizontal and vertical have different astetics so adjust based on
    // orientation
    const barAxis = model.vertical ? 1 : 0;
    const segSpace = model.vertical ? 0.01 : 0.02;
 
    function pushSeg(title, scalars) {
      model.barSegments.push({
        corners: [
          [...startPos],
          [startPos[0] + segSize[0], startPos[1]],
          [startPos[0] + segSize[0], startPos[1] + segSize[1]],
          [startPos[0], startPos[1] + segSize[1]],
        ],
        scalars,
        title,
      });
      startPos[barAxis] += segSize[barAxis] + segSpace;
    }
    if (
      model.renderable.getDrawNanAnnotation() &&
      model.renderable.getScalarsToColors().getNanColor()
    ) {
      pushSeg('NaN', [NaN, NaN, NaN, NaN]);
    }
 
    if (
      model.renderable.getDrawBelowRangeSwatch() &&
      model.renderable.getScalarsToColors().getUseBelowRangeColor?.()
    ) {
      pushSeg('Below', [-0.1, -0.1, -0.1, -0.1]);
    }
 
    const haveAbove = model.renderable
      .getScalarsToColors()
      .getUseAboveRangeColor?.();
 
    // extra space around the ticks section
    startPos[barAxis] += segSpace;
 
    const oldSegSize = segSize[barAxis];
    segSize[barAxis] = haveAbove
      ? 1.0 - 2.0 * segSpace - segSize[barAxis] - startPos[barAxis]
      : 1.0 - segSpace - startPos[barAxis];
 
    pushSeg(
      'ticks',
      model.vertical ? [0, 0, 0.995, 0.995] : [0, 0.995, 0.995, 0]
    );
 
    if (model.renderable.getDrawAboveRangeSwatch() && haveAbove) {
      segSize[barAxis] = oldSegSize;
      startPos[barAxis] += segSpace;
      pushSeg('Above', [1.1, 1.1, 1.1, 1.1]);
    }
  };
 
  // called by updatePolyDataForLabels
  // modifies class constants tmp2v3
  const tmp2v3 = new Float64Array(3);
 
  // anchor point = pos
  // H alignment = left, middle, right
  // V alignment = bottom, middle, top
  // Text Orientation = horizontal, vertical
  // orientation
  publicAPI.createPolyDataForOneLabel = (
    text,
    pos,
    alignment,
    orientation,
    offset,
    results
  ) => {
    const value = model._tmAtlas.get(text);
    Iif (!value) {
      return;
    }
    // have to find the four corners of the texture polygon for this label
    let ptIdx = results.ptIdx;
    let cellIdx = results.cellIdx;
 
    // get achor point in pixels
    tmp2v3[0] = (0.5 * pos[0] + 0.5) * model.lastSize[0];
    tmp2v3[1] = (0.5 * pos[1] + 0.5) * model.lastSize[1];
    tmp2v3[2] = pos[2];
 
    tmp2v3[0] += offset[0];
    tmp2v3[1] += offset[1];
 
    // get text size in display pixels
    const textSize = [];
    const textAxes = orientation === 'vertical' ? [1, 0] : [0, 1];
    if (orientation === 'vertical') {
      textSize[0] = value.width;
      textSize[1] = -value.height;
      // update anchor point based on alignment
      if (alignment[0] === 'middle') {
        tmp2v3[1] -= value.width / 2.0;
      } else Eif (alignment[0] === 'right') {
        tmp2v3[1] -= value.width;
      }
      Iif (alignment[1] === 'middle') {
        tmp2v3[0] += value.height / 2.0;
      } else if (alignment[1] === 'top') {
        tmp2v3[0] += value.height;
      }
    } else {
      textSize[0] = value.width;
      textSize[1] = value.height;
      // update anchor point based on alignment
      if (alignment[0] === 'middle') {
        tmp2v3[0] -= value.width / 2.0;
      } else if (alignment[0] === 'right') {
        tmp2v3[0] -= value.width;
      }
      if (alignment[1] === 'middle') {
        tmp2v3[1] -= value.height / 2.0;
      } else Iif (alignment[1] === 'top') {
        tmp2v3[1] -= value.height;
      }
    }
 
    results.points[ptIdx * 3] = tmp2v3[0];
    results.points[ptIdx * 3 + 1] = tmp2v3[1];
    results.points[ptIdx * 3 + 2] = tmp2v3[2];
    results.tcoords[ptIdx * 2] = value.tcoords[0];
    results.tcoords[ptIdx * 2 + 1] = value.tcoords[1];
    ptIdx++;
    tmp2v3[textAxes[0]] += textSize[0];
    results.points[ptIdx * 3] = tmp2v3[0];
    results.points[ptIdx * 3 + 1] = tmp2v3[1];
    results.points[ptIdx * 3 + 2] = tmp2v3[2];
    results.tcoords[ptIdx * 2] = value.tcoords[2];
    results.tcoords[ptIdx * 2 + 1] = value.tcoords[3];
    ptIdx++;
    tmp2v3[textAxes[1]] += textSize[1];
    results.points[ptIdx * 3] = tmp2v3[0];
    results.points[ptIdx * 3 + 1] = tmp2v3[1];
    results.points[ptIdx * 3 + 2] = tmp2v3[2];
    results.tcoords[ptIdx * 2] = value.tcoords[4];
    results.tcoords[ptIdx * 2 + 1] = value.tcoords[5];
    ptIdx++;
    tmp2v3[textAxes[0]] -= textSize[0];
    results.points[ptIdx * 3] = tmp2v3[0];
    results.points[ptIdx * 3 + 1] = tmp2v3[1];
    results.points[ptIdx * 3 + 2] = tmp2v3[2];
    results.tcoords[ptIdx * 2] = value.tcoords[6];
    results.tcoords[ptIdx * 2 + 1] = value.tcoords[7];
    ptIdx++;
 
    // add the two triangles to represent the quad
    results.polys[cellIdx * 4] = 3;
    results.polys[cellIdx * 4 + 1] = ptIdx - 4;
    results.polys[cellIdx * 4 + 2] = ptIdx - 3;
    results.polys[cellIdx * 4 + 3] = ptIdx - 2;
    cellIdx++;
    results.polys[cellIdx * 4] = 3;
    results.polys[cellIdx * 4 + 1] = ptIdx - 4;
    results.polys[cellIdx * 4 + 2] = ptIdx - 2;
    results.polys[cellIdx * 4 + 3] = ptIdx - 1;
 
    results.ptIdx += 4;
    results.cellIdx += 2;
  };
 
  // update the polydata associated with drawing the text labels
  // specifically the quads used for each label and their associated tcoords
  // etc. This changes every time the camera viewpoint changes
  const tmpv3 = new Float64Array(3);
  publicAPI.updatePolyDataForLabels = () => {
    // update the polydata
    const numLabels =
      publicAPI.getTickStrings().length + model.barSegments.length;
    const numPts = numLabels * 4;
    const numTris = numLabels * 2;
    const points = new Float64Array(numPts * 3);
    const polys = new Uint16Array(numTris * 4);
    const tcoords = new Float32Array(numPts * 2);
 
    const results = {
      ptIdx: 0,
      cellIdx: 0,
      polys,
      points,
      tcoords,
    };
 
    // compute the direction vector
    const offsetAxis = model.vertical ? 0 : 1;
    const spacedAxis = model.vertical ? 1 : 0;
 
    tmpv3[2] = -0.99; // near plane
 
    // draw the title
    const alignment = model.vertical
      ? ['right', 'middle']
      : ['middle', 'bottom'];
    let dir = [0, 1];
    const tickOffsets = [0, 0];
    if (model.vertical) {
      tickOffsets[0] = -model.tickLabelPixelOffset;
      Iif (model.topTitle) {
        tmpv3[0] = model.boxPosition[0] + 0.5 * model.boxSize[0];
        tmpv3[1] = model.barPosition[1] + model.barSize[1];
 
        // write the axis label
        publicAPI.createPolyDataForOneLabel(
          model.renderable.getAxisLabel(),
          tmpv3,
          ['middle', 'bottom'],
          'horizontal',
          [0, model.axisTitlePixelOffset],
          results
        );
      } else {
        tmpv3[0] = model.barPosition[0] + model.barSize[0];
        tmpv3[1] = model.barPosition[1] + 0.5 * model.barSize[1];
 
        // write the axis label
        publicAPI.createPolyDataForOneLabel(
          model.renderable.getAxisLabel(),
          tmpv3,
          ['middle', 'top'],
          'vertical',
          [model.axisTitlePixelOffset, 0],
          results
        );
      }
      dir = [-1, 0];
    } else {
      tickOffsets[1] = model.tickLabelPixelOffset;
      tmpv3[0] = model.barPosition[0] + 0.5 * model.barSize[0];
      tmpv3[1] = model.barPosition[1] + model.barSize[1];
      publicAPI.createPolyDataForOneLabel(
        model.renderable.getAxisLabel(),
        tmpv3,
        ['middle', 'bottom'],
        'horizontal',
        [0, model.axisTitlePixelOffset],
        results
      );
    }
 
    tmpv3[offsetAxis] =
      model.barPosition[offsetAxis] +
      (0.5 * dir[offsetAxis] + 0.5) * model.barSize[offsetAxis];
    tmpv3[spacedAxis] =
      model.barPosition[spacedAxis] + model.barSize[spacedAxis] * 0.5;
 
    // draw bar segment labels
    let tickSeg = null;
    for (let i = 0; i < model.barSegments.length; i++) {
      const seg = model.barSegments[i];
      if (seg.title === 'ticks') {
        // handle ticks below
        tickSeg = seg;
      } else {
        tmpv3[spacedAxis] =
          model.barPosition[spacedAxis] +
          0.5 *
            model.barSize[spacedAxis] *
            (seg.corners[2][spacedAxis] + seg.corners[0][spacedAxis]);
        publicAPI.createPolyDataForOneLabel(
          seg.title,
          tmpv3,
          alignment,
          'horizontal',
          tickOffsets,
          results
        );
      }
    }
 
    // write the tick labels
    const tickSegmentStart =
      model.barPosition[spacedAxis] +
      model.barSize[spacedAxis] * tickSeg.corners[0][spacedAxis];
    const tickSegmentSize =
      model.barSize[spacedAxis] *
      (tickSeg.corners[2][spacedAxis] - tickSeg.corners[0][spacedAxis]);
    const ticks = publicAPI.getTicks();
    const tickStrings = publicAPI.getTickStrings();
    for (let t = 0; t < ticks.length; t++) {
      const tickPos =
        (ticks[t] - model.lastTickBounds[0]) /
        (model.lastTickBounds[1] - model.lastTickBounds[0]);
      tmpv3[spacedAxis] = tickSegmentStart + tickSegmentSize * tickPos;
      publicAPI.createPolyDataForOneLabel(
        tickStrings[t],
        tmpv3,
        alignment,
        'horizontal',
        tickOffsets,
        results
      );
    }
 
    const tcoordDA = vtkDataArray.newInstance({
      numberOfComponents: 2,
      values: tcoords,
      name: 'TextureCoordinates',
    });
    model.tmPolyData.getPointData().setTCoords(tcoordDA);
    model.tmPolyData.getPoints().setData(points, 3);
    model.tmPolyData.getPoints().modified();
    model.tmPolyData.getPolys().setData(polys, 1);
    model.tmPolyData.getPolys().modified();
    model.tmPolyData.modified();
  };
 
  publicAPI.updatePolyDataForBarSegments = () => {
    const scalarsToColors = model.renderable.getScalarsToColors();
    let numberOfExtraColors = 0;
    if (
      model.renderable.getDrawNanAnnotation() &&
      scalarsToColors.getNanColor()
    ) {
      numberOfExtraColors += 1;
    }
    if (
      model.renderable.getDrawBelowRangeSwatch() &&
      scalarsToColors.getUseBelowRangeColor?.()
    ) {
      numberOfExtraColors += 1;
    }
    if (
      model.renderable.getDrawAboveRangeSwatch() &&
      scalarsToColors.getUseAboveRangeColor?.()
    ) {
      numberOfExtraColors += 1;
    }
 
    const numPts = 4 * (1 + numberOfExtraColors);
    const numQuads = numPts;
 
    // handle vector component mode
    let numComps = 1;
    if (scalarsToColors.getVectorMode() === VectorMode.COMPONENT) {
      numComps = scalarsToColors.getVectorComponent() + 1;
    }
 
    // create the colored bars
    const points = new Float64Array(numPts * 3);
    const cells = new Uint16Array(numQuads * 5);
    const scalars = new Float32Array(numPts * numComps);
 
    let ptIdx = 0;
    let cellIdx = 0;
 
    for (let i = 0; i < model.barSegments.length; i++) {
      const seg = model.barSegments[i];
      for (let e = 0; e < 4; e++) {
        tmpv3[0] = model.barPosition[0] + seg.corners[e][0] * model.barSize[0];
        tmpv3[1] = model.barPosition[1] + seg.corners[e][1] * model.barSize[1];
        points[ptIdx * 3] = (0.5 * tmpv3[0] + 0.5) * model.lastSize[0];
        points[ptIdx * 3 + 1] = (0.5 * tmpv3[1] + 0.5) * model.lastSize[1];
        points[ptIdx * 3 + 2] = tmpv3[2];
        for (let nc = 0; nc < numComps; nc++) {
          scalars[ptIdx * numComps + nc] =
            model.lastTickBounds[0] +
            seg.scalars[e] *
              (model.lastTickBounds[1] - model.lastTickBounds[0]);
        }
        ptIdx++;
      }
      cells[cellIdx * 5] = 4;
      cells[cellIdx * 5 + 1] = ptIdx - 4;
      cells[cellIdx * 5 + 2] = ptIdx - 3;
      cells[cellIdx * 5 + 3] = ptIdx - 2;
      cells[cellIdx * 5 + 4] = ptIdx - 1;
      cellIdx++;
    }
 
    const scalarsDA = vtkDataArray.newInstance({
      numberOfComponents: numComps,
      values: scalars,
      name: 'Scalars',
    });
    model.polyData.getPointData().setScalars(scalarsDA);
    model.polyData.getPoints().setData(points, 3);
    model.polyData.getPoints().modified();
    model.polyData.getPolys().setData(cells, 1);
    model.polyData.getPolys().modified();
    model.polyData.modified();
  };
}
 
const newScalarBarActorHelper = macro.newInstance(
  (publicAPI, model, initialValues = { renderable: null }) => {
    Object.assign(model, {}, initialValues);
 
    // Inheritance
    macro.obj(publicAPI, model);
 
    macro.setGet(publicAPI, model, [
      'axisTitlePixelOffset',
      'tickLabelPixelOffset',
      'renderable',
      'topTitle',
      'ticks',
      'tickStrings',
    ]);
    macro.get(publicAPI, model, [
      'lastSize',
      'lastAspectRatio',
      'lastTickBounds',
      'axisTextStyle',
      'tickTextStyle',
      'barActor',
      'tmActor',
    ]);
    macro.getArray(publicAPI, model, ['boxPosition', 'boxSize']);
    macro.setArray(publicAPI, model, ['boxPosition', 'boxSize'], 2);
 
    model.forceUpdate = false;
    model.lastRebuildTime = {};
    macro.obj(model.lastRebuildTime, { mtime: 0 });
    model.lastSize = [-1, -1];
 
    model.tmCanvas = document.createElement('canvas');
    model.tmContext = model.tmCanvas.getContext('2d');
    model._tmAtlas = new Map();
 
    model.barMapper = vtkMapper.newInstance();
    model.barMapper.setInterpolateScalarsBeforeMapping(true);
    model.barMapper.setUseLookupTableScalarRange(true);
    model.polyData = vtkPolyData.newInstance();
    model.barMapper.setInputData(model.polyData);
    model.barActor = vtkActor.newInstance();
    model.barActor.setMapper(model.barMapper);
 
    // for texture atlas
    model.tmPolyData = vtkPolyData.newInstance();
    model.tmMapper = vtkMapper.newInstance();
    model.tmMapper.setInputData(model.tmPolyData);
    model.tmTexture = vtkTexture.newInstance({ resizable: true });
    model.tmTexture.setInterpolate(false);
    model.tmActor = vtkActor.newInstance({ parentProp: publicAPI });
    model.tmActor.setMapper(model.tmMapper);
    model.tmActor.addTexture(model.tmTexture);
 
    model.barPosition = [0, 0];
    model.barSize = [0, 0];
    model.boxPosition = [0.88, -0.92];
    model.boxSize = [0.1, 1.1];
 
    // internal variables
    model.lastTickBounds = [];
 
    vtkScalarBarActorHelper(publicAPI, model);
  },
  'vtkScalarBarActorHelper'
);
 
//
// Now we define the public class that the application sets view independent
// properties on. This class is fairly small as it mainly just holds
// properties setter and getters leaving all calculations to the helper
// class.
//
function vtkScalarBarActor(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkScalarBarActor');
 
  publicAPI.setTickTextStyle = (tickStyle) => {
    model.tickTextStyle = { ...model.tickTextStyle, ...tickStyle };
    publicAPI.modified();
  };
 
  publicAPI.setAxisTextStyle = (axisStyle) => {
    model.axisTextStyle = { ...model.axisTextStyle, ...axisStyle };
    publicAPI.modified();
  };
 
  publicAPI.resetAutoLayoutToDefault = () => {
    publicAPI.setAutoLayout(defaultAutoLayout(publicAPI, model));
  };
 
  publicAPI.resetGenerateTicksToDefault = () => {
    publicAPI.setGenerateTicks(defaultGenerateTicks(publicAPI, model));
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
function defaultValues(initialValues) {
  return {
    automated: true,
    autoLayout: null,
    axisLabel: 'Scalar Value',
    barPosition: [0, 0],
    barSize: [0, 0],
    boxPosition: [0.88, -0.92],
    boxSize: [0.1, 1.1],
    scalarToColors: null,
    axisTitlePixelOffset: 36.0,
    axisTextStyle: {
      fontColor: 'white',
      fontStyle: 'normal',
      fontSize: 18,
      fontFamily: 'serif',
    },
    tickLabelPixelOffset: 14.0,
    tickTextStyle: {
      fontColor: 'white',
      fontStyle: 'normal',
      fontSize: 14,
      fontFamily: 'serif',
    },
    generateTicks: null,
    drawNanAnnotation: true,
    drawBelowRangeSwatch: true,
    drawAboveRangeSwatch: true,
    ...initialValues,
  };
}
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, defaultValues(initialValues));
 
  if (!model.autoLayout) model.autoLayout = defaultAutoLayout(publicAPI, model);
  if (!model.generateTicks)
    model.generateTicks = defaultGenerateTicks(publicAPI, model);
 
  // Inheritance
  vtkActor.extend(publicAPI, model, initialValues);
 
  publicAPI.getProperty().setDiffuse(0.0);
  publicAPI.getProperty().setAmbient(1.0);
 
  macro.setGet(publicAPI, model, [
    'automated',
    'autoLayout',
    'axisTitlePixelOffset',
    'axisLabel',
    'scalarsToColors',
    'tickLabelPixelOffset',
    'generateTicks',
    'drawNanAnnotation',
    'drawBelowRangeSwatch',
    'drawAboveRangeSwatch',
  ]);
  macro.get(publicAPI, model, ['axisTextStyle', 'tickTextStyle']);
  macro.getArray(publicAPI, model, [
    'barPosition',
    'barSize',
    'boxPosition',
    'boxSize',
  ]);
  macro.setArray(
    publicAPI,
    model,
    ['barPosition', 'barSize', 'boxPosition', 'boxSize'],
    2
  );
 
  // Object methods
  vtkScalarBarActor(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkScalarBarActor');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend, newScalarBarActorHelper };