All files / Sources/Widgets/Representations/WidgetRepresentation index.js

76.56% Statements 98/128
54.44% Branches 49/90
77.77% Functions 21/27
76.61% Lines 95/124

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                      1x     1x     65x 65x 65x 195x 195x 195x 195x 195x               1x 1x 3x 3x 15x 15x   15x 30x 8x       1x           1x   1x 5x 5x       1x 5x 5x                                     43x 43x 16x     16x   16x   43x 43x     43x     43x 23x   43x                         301x   301x           31x 31x 31x 31x       31x           31x 31x   31x             31x     31x   270x 20x   301x                 35x     35x   35x                   169x 35x     35x 35x 35x       35x     35x 92x               92x 92x 92x     92x 104x     92x     35x                     35x         9x 9x   9x   9x               9x 9x 18x         18x     9x 9x 9x           35x             35x 65x       65x       35x               35x                                                                           35x 35x 35x         35x       35x               35x                      
import macro from 'vtk.js/Sources/macros';
import vtkProp from 'vtk.js/Sources/Rendering/Core/Prop';
 
import vtkCellArray from 'vtk.js/Sources/Common/Core/CellArray';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkPoints from 'vtk.js/Sources/Common/Core/Points';
import { Behavior } from 'vtk.js/Sources/Widgets/Representations/WidgetRepresentation/Constants';
import { RenderingTypes } from 'vtk.js/Sources/Widgets/Core/WidgetManager/Constants';
import { CATEGORIES } from 'vtk.js/Sources/Rendering/Core/Mapper/CoincidentTopologyHelper';
import { POLYDATA_FIELDS } from 'vtk.js/Sources/Common/DataModel/PolyData/Constants';
 
const { vtkErrorMacro, vtkWarningMacro } = macro;
 
// ----------------------------------------------------------------------------
const STYLE_CATEGORIES = ['active', 'inactive', 'static'];
 
function applyCoincidentTopologyParametersToMapper(mapper, parameters) {
  if (mapper && mapper.setResolveCoincidentTopologyToPolygonOffset) {
    mapper.setResolveCoincidentTopologyToPolygonOffset();
    CATEGORIES.forEach((category) => {
      if (parameters[category]) {
        const methodName = `setRelativeCoincidentTopology${category}OffsetParameters`;
        if (mapper[methodName]) {
          const { factor, offset } = parameters[category];
          mapper[methodName](factor, offset);
        }
      }
    });
  }
}
 
export function mergeStyles(elementNames, ...stylesToMerge) {
  const newStyleObject = { active: {}, inactive: {}, static: {} };
  STYLE_CATEGORIES.forEach((category) => {
    const cat = newStyleObject[category];
    elementNames.forEach((name) => {
      if (!cat[name]) {
        cat[name] = {};
      }
      stylesToMerge
        .filter((s) => s && s[category] && s[category][name])
        .forEach((s) => Object.assign(cat[name], s[category][name]));
    });
  });
 
  return newStyleObject;
}
 
// ----------------------------------------------------------------------------
 
export function applyStyles(pipelines, styles, activeActor) {
  if (!activeActor) {
    // static
    Object.keys(styles.static).forEach((name) => {
      if (pipelines[name]) {
        pipelines[name].actor.getProperty().set(styles.static[name]);
      }
    });
    // inactive
    Object.keys(styles.inactive).forEach((name) => {
      if (pipelines[name]) {
        pipelines[name].actor.getProperty().set(styles.inactive[name]);
      }
    });
  } else E{
    Object.keys(pipelines).forEach((name) => {
      const style =
        pipelines[name].actor === activeActor
          ? styles.active[name]
          : styles.inactive[name];
      if (style) {
        pipelines[name].actor.getProperty().set(style);
      }
    });
  }
}
 
// ----------------------------------------------------------------------------
 
export function connectPipeline(pipeline) {
  let source = pipeline.source;
  if (pipeline.filter) {
    Iif (source.isA('vtkDataSet')) {
      pipeline.filter.setInputData(source);
    } else {
      pipeline.filter.setInputConnection(source.getOutputPort());
    }
    source = pipeline.filter;
  }
  if (source) {
    Iif (source.isA('vtkDataSet')) {
      pipeline.mapper.setInputData(source);
    } else {
      pipeline.mapper.setInputConnection(source.getOutputPort());
    }
  }
  if (pipeline.glyph) {
    pipeline.mapper.setInputConnection(pipeline.glyph.getOutputPort(), 1);
  }
  pipeline.actor.setMapper(pipeline.mapper);
}
 
// Internal convenient function to create a data array:
export function allocateArray(
  polyData,
  name,
  numberOfTuples,
  dataType,
  numberOfComponents
) {
  // Check first whether name is points, verts, lines, polys, otherwise it is a point data array.
  let dataArray =
    polyData[`get${macro.capitalize(name)}`]?.() ||
    polyData.getPointData().getArrayByName(name);
  if (
    !dataArray ||
    (dataType !== undefined && dataArray.getDataType() !== dataType) ||
    (numberOfComponents !== undefined &&
      dataArray.getNumberOfComponents() !== numberOfComponents)
  ) {
    let arrayType = vtkDataArray;
    let arrayDataType = dataType;
    let arrayNumberOfComponents = numberOfComponents;
    Iif (name === 'points') {
      arrayType = vtkPoints;
      arrayDataType = arrayDataType ?? 'Float32Array';
      arrayNumberOfComponents = numberOfComponents ?? 3;
    } else Iif (POLYDATA_FIELDS.includes(name)) {
      arrayType = vtkCellArray;
      arrayDataType = arrayDataType ?? 'Uint16Array';
      arrayNumberOfComponents = numberOfComponents ?? 1;
    } else {
      // data array
      arrayDataType = arrayDataType ?? 'Float32Array';
      arrayNumberOfComponents = numberOfComponents ?? 1;
    }
    dataArray = arrayType.newInstance({
      name,
      dataType: arrayDataType,
      numberOfComponents: arrayNumberOfComponents,
      size: arrayNumberOfComponents * numberOfTuples,
      empty: numberOfTuples === 0,
    });
    Iif (name === 'points' || POLYDATA_FIELDS.includes(name)) {
      polyData[`set${macro.capitalize(name)}`](dataArray);
    } else {
      polyData.getPointData().addArray(dataArray);
    }
  } else if (dataArray.getNumberOfTuples() !== numberOfTuples) {
    dataArray.resize(numberOfTuples);
  }
  return dataArray;
}
 
// ----------------------------------------------------------------------------
// vtkWidgetRepresentation
// ----------------------------------------------------------------------------
 
function vtkWidgetRepresentation(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkWidgetRepresentation');
 
  // Internal cache
  const cache = { mtimes: {}, states: [] };
 
  model._onCoincidentTopologyParametersChanged = () => {
    publicAPI.getActors().forEach((actor) => {
      applyCoincidentTopologyParametersToMapper(
        actor.getMapper(),
        model.coincidentTopologyParameters
      );
    });
  };
 
  // --------------------------------------------------------------------------
  publicAPI.getActors = () => model.actors;
  publicAPI.getNestedProps = publicAPI.getActors;
  // --------------------------------------------------------------------------
 
  publicAPI.setLabels = (...labels) => {
    if (labels.length === 1) {
      model.labels = [].concat(labels[0]);
    } else E{
      model.labels = labels;
    }
    publicAPI.modified();
  };
 
  publicAPI.getRepresentationStates = (input = model.inputData[0]) => {
    Iif (
      cache.mtimes.representation === publicAPI.getMTime() &&
      cache.mtimes.input === input.getMTime()
    ) {
      return cache.states;
    }
 
    // Reinitialize cache
    cache.mtimes.representation = publicAPI.getMTime();
    cache.mtimes.input = input.getMTime();
    cache.states = [];
 
    // Fill states that are going to be used in the representation
    model.labels.forEach((name) => {
      cache.states = cache.states.concat(input.getStatesWithLabel(name) || []);
    });
 
    return cache.states;
  };
 
  publicAPI.getSelectedState = (prop, compositeID) => {
    const representationStates = publicAPI.getRepresentationStates();
    if (compositeID < representationStates.length) {
      return representationStates[compositeID];
    }
    vtkErrorMacro(
      `Representation ${publicAPI.getClassName()} should implement getSelectedState(prop, compositeID) method.`
    );
    return null;
  };
 
  publicAPI.updateActorVisibility = (
    renderingType = RenderingTypes.FRONT_BUFFER,
    ctxVisible = true,
    handleVisible = true
  ) => {
    let otherFlag = true;
    switch (model.behavior) {
      case Behavior.HANDLE:
        otherFlag =
          renderingType === RenderingTypes.PICKING_BUFFER || handleVisible;
        break;
      case Behavior.CONTEXT:
        otherFlag = ctxVisible;
        break;
      default:
        otherFlag = true;
        break;
    }
    const visibilityFlag = otherFlag;
    for (let i = 0; i < model.actors.length; i++) {
      Iif (model.visibilityFlagArray) {
        model.actors[i].setVisibility(
          visibilityFlag && model.visibilityFlagArray[i]
        );
      } else {
        model.actors[i].setVisibility(visibilityFlag);
      }
    }
    if (model.alwaysVisibleActors) {
      for (let i = 0; i < model.alwaysVisibleActors.length; i++) {
        model.alwaysVisibleActors[i].setVisibility(true);
      }
    }
  };
 
  // Add warning to model.actors.push
  model.actors.push = (...args) => {
    vtkWarningMacro(
      'You should use publicAPI.addActor() to initialize the actor properly'
    );
    args.forEach((actor) => publicAPI.addActor(actor));
  };
 
  publicAPI.addActor = (actor) => {
    applyCoincidentTopologyParametersToMapper(
      actor.getMapper(),
      model.coincidentTopologyParameters
    );
    Array.prototype.push.apply(model.actors, [actor]);
  };
 
  // Make sure setting the labels at build time works with string/array...
  publicAPI.setLabels(model.labels);
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
function defaultValues(initialValues) {
  return {
    activeScaleFactor: 1.2,
    activeColor: 1,
    useActiveColor: true,
    actors: [],
    labels: [],
    behavior: Behavior.CONTEXT,
    coincidentTopologyParameters: {
      Point: {
        factor: -1.0,
        offset: -1.0,
      },
      Line: {
        factor: -1.0,
        offset: -1.0,
      },
      Polygon: {
        factor: -1.0,
        offset: -1.0,
      },
    },
    scaleInPixels: false,
    displayScaleParams: {
      dispHeightFactor: 1,
      cameraPosition: [0, 0, 0],
      cameraDir: [1, 0, 0],
      isParallel: false,
      rendererPixelDims: [1, 1],
    },
    _internalArrays: {},
    ...initialValues,
  };
}
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  // Object methods
  vtkProp.extend(publicAPI, model, defaultValues(initialValues));
  macro.algo(publicAPI, model, 1, 1);
  macro.get(publicAPI, model, [
    'labels',
    'displayScaleParams',
    'coincidentTopologyParameters',
  ]);
  macro.set(publicAPI, model, [
    { type: 'object', name: 'displayScaleParams' },
    { type: 'object', name: 'coincidentTopologyParameters' },
  ]);
  macro.setGet(publicAPI, model, [
    'scaleInPixels',
    'activeScaleFactor',
    'activeColor',
    'useActiveColor',
  ]);
 
  // Object specific methods
  vtkWidgetRepresentation(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export default {
  extend,
  mergeStyles,
  applyStyles,
  connectPipeline,
};