All files / Sources/Proxy/Core/ProxyManager state.js

2.1% Statements 2/95
0% Branches 0/24
4% Functions 1/25
2.15% Lines 2/93

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                                3x                                                                                                                                                                                                                                             3x                                                                                                                                                                                                                
import vtk from 'vtk.js/Sources/vtk';
import vtkPiecewiseFunctionProxy from 'vtk.js/Sources/Proxy/Core/PiecewiseFunctionProxy';
 
function getProperties(proxy) {
  const props = {};
  proxy.listPropertyNames().forEach((name) => {
    props[name] = proxy.getPropertyByName(name).value;
  });
  return props;
}
 
// ----------------------------------------------------------------------------
// Proxy State Handling
// ----------------------------------------------------------------------------
 
export default function addStateAPI(publicAPI, model) {
  publicAPI.loadState = (state, options = {}) =>
    new Promise((resolve, reject) => {
      const proxyMapping = {};
      const $oldToNewIdMapping = {};
      const cameras = {};
      const datasetHandler = options.datasetHandler || vtk;
      const sourcePromises = [];
 
      state.sources.forEach(({ id, group, name, props }) => {
        sourcePromises.push(
          Promise.resolve(datasetHandler(props.dataset)).then((dataset) => {
            if (dataset) {
              const proxy = publicAPI.createProxy(group, name);
              proxy.setName(props.name);
              proxy.setInputData(dataset, props.type);
              proxyMapping[id] = proxy;
              return proxy;
            }
            return null;
          })
        );
      });
 
      Promise.all(sourcePromises)
        .then(() => {
          const views = publicAPI.getViews();
          state.views.forEach(({ id, group, name, props, camera }) => {
            let proxy = null;
            if (state.options.recycleViews) {
              proxy = views.find(
                (v) =>
                  v.getProxyGroup() === group &&
                  v.getProxyName() === name &&
                  v.getName() === props.name
              );
            }
            if (!proxy) {
              proxy = publicAPI.createProxy(group, name, {
                disableAnimation: true,
              });
            } else {
              proxy.setDisableAnimation(true);
            }
 
            proxy.set(props, true);
            proxyMapping[id] = proxy;
            cameras[id] = camera;
          });
 
          function updateView(view) {
            if (!proxyMapping[view] || !cameras[view]) {
              return;
            }
            proxyMapping[view].resetOrientation().then(() => {
              proxyMapping[view].getCamera().set(cameras[view]);
              proxyMapping[view]
                .getRenderer()
                .updateLightsGeometryToFollowCamera();
              proxyMapping[view].renderLater();
            });
          }
 
          state.representations.forEach(({ source, view, props }) => {
            const proxy = publicAPI.getRepresentation(
              proxyMapping[source],
              proxyMapping[view]
            );
            proxy.set(props, true);
            updateView(view);
          });
 
          // restore luts and pwfs after restoring reps to avoid
          // rep initialization from resetting restored luts/pwfs
          Object.keys(state.fields).forEach((fieldName) => {
            const { lookupTable, piecewiseFunction } = state.fields[fieldName];
            const lutProxy = publicAPI.getLookupTable(fieldName, lookupTable);
            lutProxy.setPresetName(lookupTable.presetName);
            lutProxy.setDataRange(...lookupTable.dataRange);
            const pwfProxy = publicAPI.getPiecewiseFunction(
              fieldName,
              piecewiseFunction
            );
            switch (piecewiseFunction.mode) {
              case vtkPiecewiseFunctionProxy.Mode.Gaussians:
                pwfProxy.setGaussians(piecewiseFunction.gaussians);
                break;
              case vtkPiecewiseFunctionProxy.Mode.Points:
                pwfProxy.setPoints(piecewiseFunction.points);
                break;
              case vtkPiecewiseFunctionProxy.Mode.Nodes:
                pwfProxy.setNodes(piecewiseFunction.nodes);
                break;
              default:
                // nothing that we can do
                break;
            }
            pwfProxy.setMode(piecewiseFunction.mode);
            pwfProxy.setDataRange(...piecewiseFunction.dataRange);
          });
 
          // Apply camera no matter what
          Object.keys(cameras).forEach(updateView);
 
          // Create id mapping
          Object.keys(proxyMapping).forEach((originalId) => {
            const newId = proxyMapping[originalId].getProxyId();
            $oldToNewIdMapping[originalId] = newId;
          });
 
          // Re-enable animation on views
          state.views.forEach(({ id }) => {
            proxyMapping[id].setDisableAnimation(false);
          });
 
          resolve({ ...state.userData, $oldToNewIdMapping });
        })
        .catch(reject);
    });
 
  publicAPI.saveState = (options = {}, userData = {}) =>
    new Promise((resolve, reject) => {
      const sources = publicAPI.getSources();
      // const representations = publicAPI.getRepresentations();
      const views = publicAPI.getViews();
 
      // Extract handlers
      const datasetHandler = options.datasetHandler || ((d) => d.getState());
      delete options.datasetHandler;
      const datasets = [];
 
      const fieldNames = new Set();
      const state = {
        userData,
        options,
        sources: [],
        views: [],
        representations: [],
        fields: {},
      };
      sources.forEach((source) => {
        const dataset = Promise.resolve(
          datasetHandler(source.getDataset(), source)
        );
        datasets.push(dataset);
        state.sources.push({
          id: source.getProxyId(),
          group: source.getProxyGroup(),
          name: source.getProxyName(),
          props: {
            name: source.getName(),
            type: source.getType(),
            dataset,
          },
        });
      });
      views.forEach((view) => {
        const camera = view.getCamera().get('position', 'viewUp', 'focalPoint');
        state.views.push({
          id: view.getProxyId(),
          group: view.getProxyGroup(),
          name: view.getProxyName(),
          props: Object.assign(
            getProperties(view),
            view.get('axis', 'orientation', 'viewUp')
          ),
          camera,
        });
 
        // Loop over view representations
        const representations = view.getRepresentations();
        representations.forEach((representation) => {
          state.representations.push({
            source: representation.getInput().getProxyId(),
            view: view.getProxyId(),
            props: getProperties(representation),
          });
          fieldNames.add(representation.getColorBy()[0]);
        });
      });
 
      fieldNames.forEach((fieldName) => {
        state.fields[fieldName] = {
          lookupTable: publicAPI
            .getLookupTable(fieldName)
            .get(
              'mode',
              'presetName',
              'rgbPoints',
              'hsvPoints',
              'nodes',
              'arrayName',
              'arrayLocation',
              'dataRange'
            ),
          piecewiseFunction: publicAPI
            .getPiecewiseFunction(fieldName)
            .get(
              'mode',
              'gaussians',
              'points',
              'nodes',
              'arrayName',
              'arrayLocation',
              'dataRange'
            ),
        };
      });
 
      Promise.all(datasets)
        .then(() => {
          // Patch datasets in state to the result of the promises
          for (let i = 0; i < state.sources.length; i++) {
            state.sources[i].props.dataset.then((value) => {
              state.sources[i].props.dataset = value;
            });
          }
 
          // provide valide state
          resolve(state);
        })
        .catch(reject);
    });
}