All files / Sources/IO/Misc/OBJReader index.js

85.14% Statements 172/202
70.73% Branches 58/82
83.33% Functions 15/18
85.71% Lines 162/189

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                          1x         177646x 473717x             7x 7x 7x 7x 7x 7x 7x           415560x 138528x 138528x 138528x 138528x   138528x 138528x   138528x           112352x 21x   112331x 112331x 16x 16x 16x 16x 112315x 24441x 24441x 24441x 87874x 16957x 16957x 70917x 24692x 24692x 24692x 46225x   46176x 3x   46176x 46176x 138528x 46176x 46176x 46176x 138528x               7x 7x 7x 7x 7x 19x 19x 19x 19x     19x     2x 2x   2x 6x 6x 18x 18x 18x 14x 10x   4x 4x     14x       2x 2x 2x 10x   10x     10x 4x 4x   4x         19x 19x 19x 19x 19x 19x   19x 19x 46176x 46176x 46176x 138528x 138528x 138528x 59221x     59221x 59221x 59221x 59221x   59221x 59204x     138528x   46176x     19x 19x 2x       2x   19x   19x 19x         19x     19x 16x         16x       19x                                                                                           5x 5x 5x     5x 5x 5x 5x 5x   3x           3x     5x     1x                   8x     8x 8x         4x       8x 4x       4x     4x 4x 4x       4x       8x 4x 4x     8x 7x     7x 7x   7x 7x 7x 7x 7x 7x     8x         8x   8x             1x                         8x     8x 8x 8x         8x 8x     8x         1x          
import macro from 'vtk.js/Sources/macros';
import DataAccessHelper from 'vtk.js/Sources/IO/Core/DataAccessHelper';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkPolyData from 'vtk.js/Sources/Common/DataModel/PolyData';
 
// Enable several sources for DataAccessHelper
import 'vtk.js/Sources/IO/Core/DataAccessHelper/LiteHttpDataAccessHelper'; // Just need HTTP
// import 'vtk.js/Sources/IO/Core/DataAccessHelper/HttpDataAccessHelper'; // HTTP + gz
// import 'vtk.js/Sources/IO/Core/DataAccessHelper/HtmlDataAccessHelper'; // html + base64 + zip
// import 'vtk.js/Sources/IO/Core/DataAccessHelper/JSZipDataAccessHelper'; // zip
 
// ----------------------------------------------------------------------------
 
const data = {};
 
// ----------------------------------------------------------------------------
 
function copyVector(src, srcOffset, dst, dstOffset, vectorSize) {
  for (let i = 0; i < vectorSize; i++) {
    dst[dstOffset + i] = src[srcOffset + i];
  }
}
 
// ----------------------------------------------------------------------------
 
function begin(splitMode) {
  data.splitOn = splitMode;
  data.pieces = [];
  data.v = [];
  data.vt = [];
  data.vn = [];
  data.f = [[]];
  data.size = 0;
}
 
// ----------------------------------------------------------------------------
 
function faceMap(str) {
  const idxs = str.split('/').map((i) => Number(i));
  let vertexIdx = idxs[0] - 1;
  vertexIdx = vertexIdx < 0 ? vertexIdx + 1 + data.v.length / 3 : vertexIdx;
  let textCoordIdx = idxs[1] ? idxs[1] - 1 : vertexIdx;
  textCoordIdx =
    textCoordIdx < 0 ? textCoordIdx + 1 + data.vt.length / 2 : textCoordIdx;
  let vertexNormal = idxs[2] ? idxs[2] - 1 : vertexIdx;
  vertexNormal =
    vertexNormal < 0 ? vertexNormal + 1 + data.vn.length / 3 : vertexNormal;
  return [vertexIdx, textCoordIdx, vertexNormal];
}
 
// ----------------------------------------------------------------------------
 
function parseLine(line) {
  if (line[0] === '#') {
    return;
  }
  const tokens = line.split(/[ \t]+/);
  if (tokens[0] === data.splitOn) {
    tokens.shift();
    data.pieces.push(tokens.join(' ').trim());
    data.f.push([]);
    data.size++;
  } else if (tokens[0] === 'v') {
    data.v.push(Number(tokens[1]));
    data.v.push(Number(tokens[2]));
    data.v.push(Number(tokens[3]));
  } else if (tokens[0] === 'vt') {
    data.vt.push(Number(tokens[1]));
    data.vt.push(Number(tokens[2]));
  } else if (tokens[0] === 'vn') {
    data.vn.push(Number(tokens[1]));
    data.vn.push(Number(tokens[2]));
    data.vn.push(Number(tokens[3]));
  } else if (tokens[0] === 'f') {
    // Handle triangles for now
    if (data.size === 0) {
      data.size++;
    }
    const cells = data.f[data.size - 1];
    tokens.shift();
    const faces = tokens.filter((s) => s.length > 0 && s !== '\r');
    const size = faces.length;
    cells.push(size);
    for (let i = 0; i < size; i++) {
      cells.push(faceMap(faces[i]));
    }
  }
}
 
// ----------------------------------------------------------------------------
 
function end(model) {
  const hasTcoords = !!data.vt.length;
  const hasNormals = !!data.vn.length;
  if (model.splitMode) {
    model.numberOfOutputs = data.size;
    for (let idx = 0; idx < data.size; idx++) {
      const polyIn = data.f[idx];
      const nbElems = polyIn.length;
      const nbPoints = data.v.length / 3;
      const keyPointId = {};
      let pointDuplicatesReferences;
 
      if (model.trackDuplicates) {
        // In trackDuplicates mode, we want the following point layout:
        // [pt0, pt1, pt2, ... ptN, pt0d1, pt0d2, pt1d1]
        const pointKeys = [];
        let duplicatesCount = 0;
 
        for (let offset = 0; offset < nbElems; ) {
          const cellSize = polyIn[offset++];
          for (let pIdx = 0; pIdx < cellSize; pIdx++) {
            const [vIdx, tcIdx, nIdx] = polyIn[offset++];
            const key = `${vIdx}/${tcIdx}/${nIdx}`;
            if (keyPointId[key] === undefined) {
              if (pointKeys[vIdx] === undefined) {
                pointKeys[vIdx] = [key];
              } else {
                pointKeys[vIdx].push(key);
                ++duplicatesCount;
              }
              // will be overwritten for duplicates
              keyPointId[key] = vIdx;
            }
          }
        }
        pointDuplicatesReferences = new Uint16Array(nbPoints + duplicatesCount);
        let duplicates = 0;
        for (let pointId = 0; pointId < pointKeys.length; ++pointId) {
          const usageCount = pointKeys[pointId] ? pointKeys[pointId].length : 0;
          // Set the first duplicate index on the original point
          pointDuplicatesReferences[pointId] =
            usageCount > 1 ? nbPoints + duplicates : pointId;
          // Set the original index on each duplicated point
          for (let duplicateId = 1; duplicateId < usageCount; ++duplicateId) {
            const finalDuplicateId = nbPoints + duplicates++;
            pointDuplicatesReferences[finalDuplicateId] = pointId;
            // Associate the duplicate index to the key
            keyPointId[pointKeys[pointId][duplicateId]] = finalDuplicateId;
          }
        }
      }
 
      const ctMapping = {};
      const polydata = vtkPolyData.newInstance({ name: data.pieces[idx] });
      const pts = [];
      const tc = [];
      const normals = [];
      const polys = [];
 
      let offset = 0;
      while (offset < nbElems) {
        const cellSize = polyIn[offset];
        polys.push(cellSize);
        for (let pIdx = 0; pIdx < cellSize; pIdx++) {
          const [vIdx, tcIdx, nIdx] = polyIn[offset + pIdx + 1];
          const key = `${vIdx}/${tcIdx}/${nIdx}`;
          if (ctMapping[key] === undefined) {
            const dstOffset = model.trackDuplicates
              ? keyPointId[key]
              : pts.length / 3;
            ctMapping[key] = dstOffset;
            copyVector(data.v, vIdx * 3, pts, dstOffset * 3, 3);
            if (hasTcoords) {
              copyVector(data.vt, tcIdx * 2, tc, dstOffset * 2, 2);
            }
            if (hasNormals) {
              copyVector(data.vn, nIdx * 3, normals, dstOffset * 3, 3);
            }
          }
          polys.push(ctMapping[key]);
        }
        offset += cellSize + 1;
      }
 
      polydata.getPoints().setData(Float32Array.from(pts), 3);
      if (model.trackDuplicates) {
        const duplicatesArray = vtkDataArray.newInstance({
          name: 'Duplicates',
          values: pointDuplicatesReferences,
        });
        polydata.getPointData().addArray(duplicatesArray);
      }
      polydata.getPolys().setData(Uint32Array.from(polys));
 
      if (hasTcoords) {
        const tcoords = vtkDataArray.newInstance({
          numberOfComponents: 2,
          values: Float32Array.from(tc),
          name: 'TextureCoordinates',
        });
        polydata.getPointData().setTCoords(tcoords);
      }
 
      if (hasNormals) {
        const normalsArray = vtkDataArray.newInstance({
          numberOfComponents: 3,
          values: Float32Array.from(normals),
          name: 'Normals',
        });
        polydata.getPointData().setNormals(normalsArray);
      }
 
      // register in output
      model.output[idx] = polydata;
    }
  } else E{
    model.numberOfOutputs = 1;
    const polydata = vtkPolyData.newInstance();
    polydata.getPoints().setData(Float32Array.from(data.v), 3);
    if (hasTcoords && data.v.length / 3 === data.vt.length / 2) {
      const tcoords = vtkDataArray.newInstance({
        numberOfComponents: 2,
        values: Float32Array.from(data.vt),
        name: 'TextureCoordinates',
      });
      polydata.getPointData().setTCoords(tcoords);
    }
    if (hasNormals && data.v.length === data.vn.length) {
      const normalsArray = vtkDataArray.newInstance({
        numberOfComponents: 3,
        values: Float32Array.from(data.vn),
        name: 'Normals',
      });
      polydata.getPointData().setNormals(normalsArray);
    }
 
    const polys = [];
    const polyIn = data.f[0];
    const nbElems = polyIn.length;
    let offset = 0;
    while (offset < nbElems) {
      const cellSize = polyIn[offset];
      polys.push(cellSize);
      for (let pIdx = 0; pIdx < cellSize; pIdx++) {
        const [vIdx] = polyIn[offset + pIdx + 1];
        polys.push(vIdx);
      }
      offset += cellSize + 1;
    }
    polydata.getPolys().setData(Uint32Array.from(polys));
    model.output[0] = polydata;
  }
}
 
// ----------------------------------------------------------------------------
// Static API
// ----------------------------------------------------------------------------
 
function getPointDuplicateIds(polyData, pointId) {
  const res = [];
  const duplicates = polyData.getPointData().getArrayByName('Duplicates');
  Iif (duplicates == null) {
    return res;
  }
  const duplicatesData = duplicates.getData();
  const originalPointId = Math.min(pointId, duplicatesData[pointId]);
  res.push(originalPointId);
  let duplicateId = duplicatesData[originalPointId];
  if (duplicateId !== originalPointId) {
    // point has duplicates
    while (
      duplicateId < duplicatesData.length &&
      duplicatesData[duplicateId] === originalPointId
    ) {
      // Duplicated points must be next to each other and original point must
      // reference first duplicate
      res.push(duplicateId++);
    }
  }
  return res;
}
 
export const STATIC = {
  getPointDuplicateIds,
};
 
// ----------------------------------------------------------------------------
// vtkOBJReader methods
// ----------------------------------------------------------------------------
 
function vtkOBJReader(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOBJReader');
 
  // Create default dataAccessHelper if not available
  if (!model.dataAccessHelper) {
    model.dataAccessHelper = DataAccessHelper.get('http');
  }
 
  // Internal method to fetch Array
  function fetchData(url, option = {}) {
    return model.dataAccessHelper.fetchText(publicAPI, url, option);
  }
 
  // Set DataSet url
  publicAPI.setUrl = (url, option = {}) => {
    Iif (url.indexOf('.obj') === -1 && !option.fullpath) {
      model.baseURL = url;
      model.url = `${url}/index.obj`;
    } else {
      model.url = url;
 
      // Remove the file in the URL
      const path = url.split('/');
      path.pop();
      model.baseURL = path.join('/');
    }
 
    // Fetch metadata
    return publicAPI.loadData(option);
  };
 
  // Fetch the actual data arrays
  publicAPI.loadData = (option = {}) =>
    fetchData(model.url, option).then((content) =>
      publicAPI.isDeleted() ? false : publicAPI.parseAsText(content)
    );
 
  publicAPI.parseAsText = (content) => {
    Iif (!content) {
      return true;
    }
    if (content !== model.parseData) {
      publicAPI.modified();
    }
    model.parseData = content;
    model.numberOfOutputs = 0;
    begin(model.splitMode);
    content.split('\n').forEach(parseLine);
    end(model);
    return true;
  };
 
  publicAPI.requestData = (inData, outData) => {
    publicAPI.parseAsText(model.parseData);
  };
 
  // return Busy state
  publicAPI.isBusy = () => !!model.requestCount;
 
  publicAPI.getNumberOfOutputPorts = () => model.numberOfOutputs;
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  numberOfOutputs: 1,
  requestCount: 0,
  splitMode: null,
  trackDuplicates: false,
  // baseURL: null,
  // dataAccessHelper: null,
  // url: null,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Build VTK API
  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, ['url', 'baseURL']);
  macro.setGet(publicAPI, model, [
    'dataAccessHelper',
    'splitMode',
    'trackDuplicates',
  ]);
  macro.algo(publicAPI, model, 0, 1);
  macro.event(publicAPI, model, 'busy');
 
  // Object methods
  vtkOBJReader(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkOBJReader');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend, ...STATIC };