All files / Sources/Rendering/WebXR/RenderWindowHelper index.js

11.94% Statements 19/159
0% Branches 0/61
18.75% Functions 3/16
12.02% Lines 19/158

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                1x   1x                                                             1x   1x             1x       1x                                                           1x                                                                                                         1x                                             1x                                                                                       1x                                                                                                                                                                                                                                                                                                   1x               1x                               1x     1x 1x   1x 1x     1x         1x                        
import macro from 'vtk.js/Sources/macros';
import Constants from 'vtk.js/Sources/Rendering/WebXR/RenderWindowHelper/Constants';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkLineSource from 'vtk.js/Sources/Filters/Sources/LineSource';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import { GET_UNDERLYING_CONTEXT } from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow/ContextProxy';
import { vec3 } from 'gl-matrix';
 
const { XrSessionTypes } = Constants;
 
const DEFAULT_RESET_FACTORS = {
  rescaleFactor: 0.25, // isotropic scale factor reduces apparent size of objects
  translateZ: -1.5, // default translation initializes object in front of camera
};
 
function createRay() {
  const targetRayLineSource = vtkLineSource.newInstance();
  const targetRayMapper = vtkMapper.newInstance();
  targetRayMapper.setInputConnection(targetRayLineSource.getOutputPort());
 
  const targetRayActor = vtkActor.newInstance();
  targetRayActor.getProperty().setColor(1, 0, 0);
  targetRayActor.getProperty().setLineWidth(5);
 
  targetRayActor.setMapper(targetRayMapper);
  targetRayActor.setPickable(false);
 
  return {
    lineSource: targetRayLineSource,
    mapper: targetRayMapper,
    actor: targetRayActor,
    visible: false,
  };
}
 
// ----------------------------------------------------------------------------
// vtkWebXRRenderWindowHelper methods
// ----------------------------------------------------------------------------
 
function vtkWebXRRenderWindowHelper(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkWebXRRenderWindowHelper');
 
  publicAPI.initialize = (renderWindow) => {
    if (!model.initialized) {
      model.renderWindow = renderWindow;
      model.initialized = true;
    }
  };
 
  publicAPI.getXrSupported = () => navigator.xr !== undefined;
 
  // Request an XR session on the user device with WebXR,
  // typically in response to a user request such as a button press
  publicAPI.startXR = (xrSessionType) => {
    if (navigator.xr === undefined) {
      throw new Error('WebXR is not available');
    }
 
    model.xrSessionType =
      xrSessionType !== undefined ? xrSessionType : XrSessionTypes.HmdVR;
    const isXrSessionAR = [
      XrSessionTypes.HmdAR,
      XrSessionTypes.MobileAR,
    ].includes(model.xrSessionType);
    const sessionType = isXrSessionAR ? 'immersive-ar' : 'immersive-vr';
    if (!navigator.xr.isSessionSupported(sessionType)) {
      if (isXrSessionAR) {
        throw new Error('Device does not support AR session');
      } else {
        throw new Error('VR display is not available');
      }
    }
    if (model.xrSession === null) {
      navigator.xr.requestSession(sessionType).then(publicAPI.enterXR, () => {
        throw new Error('Failed to create XR session!');
      });
    } else {
      throw new Error('XR Session already exists!');
    }
  };
 
  // When an XR session is available, set up the XRWebGLLayer
  // and request the first animation frame for the device
  publicAPI.enterXR = async (xrSession) => {
    model.xrSession = xrSession;
    model.initCanvasSize = model.renderWindow.getSize();
 
    if (model.xrSession !== null) {
      const gl = model.renderWindow.get3DContext();
      await gl.makeXRCompatible();
 
      // XRWebGLLayer definition is deferred to here to give any WebXR polyfill
      // an opportunity to override this definition.
      const { XRWebGLLayer } = window;
      const glLayer = new XRWebGLLayer(
        model.xrSession,
        // constructor needs unproxied context
        gl[GET_UNDERLYING_CONTEXT]()
      );
      model.renderWindow.setSize(
        glLayer.framebufferWidth,
        glLayer.framebufferHeight
      );
 
      model.xrSession.updateRenderState({
        baseLayer: glLayer,
      });
 
      model.xrSession.requestReferenceSpace('local').then((refSpace) => {
        model.xrReferenceSpace = refSpace;
      });
 
      // Initialize transparent background for augmented reality session
      const isXrSessionAR = [
        XrSessionTypes.HmdAR,
        XrSessionTypes.MobileAR,
      ].includes(model.xrSessionType);
      if (isXrSessionAR) {
        const ren = model.renderWindow.getRenderable().getRenderers()[0];
        model.initBackground = ren.getBackground();
        ren.setBackground([0, 0, 0, 0]);
      }
 
      publicAPI.resetXRScene();
 
      model.renderWindow.getRenderable().getInteractor().switchToXRAnimation();
      model.xrSceneFrame = model.xrSession.requestAnimationFrame(
        model.xrRender
      );
 
      publicAPI.modified();
    } else {
      throw new Error('Failed to enter XR with a null xrSession.');
    }
  };
 
  publicAPI.resetXRScene = (
    rescaleFactor = DEFAULT_RESET_FACTORS.rescaleFactor,
    translateZ = DEFAULT_RESET_FACTORS.translateZ
  ) => {
    // Adjust world-to-physical parameters for different modalities
 
    const ren = model.renderWindow.getRenderable().getRenderers()[0];
    ren.resetCamera();
 
    const camera = ren.getActiveCamera();
    let physicalScale = camera.getPhysicalScale();
    const physicalTranslation = camera.getPhysicalTranslation();
 
    const rescaledTranslateZ = translateZ * physicalScale;
    physicalScale /= rescaleFactor;
    physicalTranslation[2] += rescaledTranslateZ;
 
    camera.setPhysicalScale(physicalScale);
    camera.setPhysicalTranslation(physicalTranslation);
    // Clip at 0.1m, 100.0m in physical space by default
    camera.setClippingRange(0.1 * physicalScale, 100.0 * physicalScale);
  };
 
  publicAPI.stopXR = async () => {
    if (navigator.xr === undefined) {
      // WebXR polyfill not available so nothing to do
      return;
    }
 
    if (model.xrSession !== null) {
      model.xrSession.cancelAnimationFrame(model.xrSceneFrame);
      model.renderWindow
        .getRenderable()
        .getInteractor()
        .returnFromXRAnimation();
      const gl = model.renderWindow.get3DContext();
      gl.bindFramebuffer(gl.FRAMEBUFFER, null);
 
      await model.xrSession.end().catch((error) => {
        if (!(error instanceof DOMException)) {
          throw error;
        }
      });
      model.xrSession = null;
    }
 
    if (model.initCanvasSize !== null) {
      model.renderWindow.setSize(...model.initCanvasSize);
    }
 
    // Reset to default canvas
    const ren = model.renderWindow.getRenderable().getRenderers()[0];
 
    if (model.initBackground != null) {
      ren.setBackground(model.initBackground);
      model.initBackground = null;
    }
 
    ren.getActiveCamera().setProjectionMatrix(null);
    ren.resetCamera();
 
    ren.setViewport(0.0, 0, 1.0, 1.0);
    model.renderWindow.traverseAllPasses();
 
    publicAPI.modified();
  };
 
  model.xrRender = async (t, frame) => {
    const xrSession = frame.session;
    const isXrSessionHMD = [
      XrSessionTypes.HmdVR,
      XrSessionTypes.HmdAR,
    ].includes(model.xrSessionType);
    if (isXrSessionHMD && model.drawControllersRay && model.xrReferenceSpace) {
      const renderer = model.renderWindow.getRenderable().getRenderers()[0];
      const camera = renderer.getActiveCamera();
      const physicalToWorldMatrix = [];
      camera.getPhysicalToWorldMatrix(physicalToWorldMatrix);
 
      xrSession.inputSources.forEach((inputSource) => {
        if (
          inputSource.targetRaySpace == null ||
          inputSource.gripSpace == null ||
          inputSource.targetRayMode !== 'tracked-pointer'
        ) {
          return;
        }
 
        if (model.inputSourceToRay[inputSource.handedness] == null) {
          model.inputSourceToRay[inputSource.handedness] = createRay();
        }
 
        const ray = model.inputSourceToRay[inputSource.handedness];
 
        const targetRayPose = frame.getPose(
          inputSource.targetRaySpace,
          model.xrReferenceSpace
        );
 
        if (targetRayPose == null) {
          return;
        }
 
        const targetRayPosition = vec3.fromValues(
          targetRayPose.transform.position.x,
          targetRayPose.transform.position.y,
          targetRayPose.transform.position.z
        );
 
        const dir = camera.physicalOrientationToWorldDirection([
          targetRayPose.transform.orientation.x,
          targetRayPose.transform.orientation.y,
          targetRayPose.transform.orientation.z,
          targetRayPose.transform.orientation.w,
        ]);
 
        const targetRayWorldPosition = vec3.transformMat4(
          [],
          targetRayPosition,
          physicalToWorldMatrix
        );
 
        const dist = renderer.getActiveCamera().getClippingRange()[1];
 
        if (!ray.visible) {
          renderer.addActor(ray.actor);
          ray.visible = true;
        }
 
        ray.lineSource.setPoint1(
          targetRayWorldPosition[0] - dir[0] * dist,
          targetRayWorldPosition[1] - dir[1] * dist,
          targetRayWorldPosition[2] - dir[2] * dist
        );
        ray.lineSource.setPoint2(...targetRayWorldPosition);
      });
 
      model.renderWindow.render();
    }
 
    model.renderWindow
      .getRenderable()
      .getInteractor()
      .updateXRGamepads(xrSession, frame, model.xrReferenceSpace);
 
    model.xrSceneFrame = model.xrSession.requestAnimationFrame(model.xrRender);
 
    const xrPose = frame.getViewerPose(model.xrReferenceSpace);
 
    if (xrPose) {
      const gl = model.renderWindow.get3DContext();
 
      if (
        model.xrSessionType === XrSessionTypes.MobileAR &&
        model.initCanvasSize !== null
      ) {
        gl.canvas.width = model.initCanvasSize[0];
        gl.canvas.height = model.initCanvasSize[1];
      }
 
      const glLayer = xrSession.renderState.baseLayer;
      gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);
      gl.clear(gl.COLOR_BUFFER_BIT);
      gl.clear(gl.DEPTH_BUFFER_BIT);
      model.renderWindow.setSize(
        glLayer.framebufferWidth,
        glLayer.framebufferHeight
      );
 
      // get the first renderer
      const ren = model.renderWindow.getRenderable().getRenderers()[0];
 
      // Do a render pass for each eye
      xrPose.views.forEach((view, index) => {
        const viewport = glLayer.getViewport(view);
 
        if (isXrSessionHMD) {
          if (view.eye === 'left') {
            ren.setViewport(0, 0, 0.5, 1.0);
          } else if (view.eye === 'right') {
            ren.setViewport(0.5, 0, 1.0, 1.0);
          } else {
            // No handling for non-eye viewport
            return;
          }
        } else if (model.xrSessionType === XrSessionTypes.LookingGlassVR) {
          const startX = viewport.x / glLayer.framebufferWidth;
          const startY = viewport.y / glLayer.framebufferHeight;
          const endX = (viewport.x + viewport.width) / glLayer.framebufferWidth;
          const endY =
            (viewport.y + viewport.height) / glLayer.framebufferHeight;
          ren.setViewport(startX, startY, endX, endY);
        } else {
          ren.setViewport(0, 0, 1, 1);
        }
 
        ren
          .getActiveCamera()
          .computeViewParametersFromPhysicalMatrix(
            view.transform.inverse.matrix
          );
        ren.getActiveCamera().setProjectionMatrix(view.projectionMatrix);
 
        model.renderWindow.traverseAllPasses();
      });
 
      // Reset scissorbox before any subsequent rendering to external displays
      // on frame end, such as rendering to a Looking Glass display.
      gl.scissor(0, 0, glLayer.framebufferWidth, glLayer.framebufferHeight);
      gl.disable(gl.SCISSOR_TEST);
    }
  };
 
  publicAPI.delete = macro.chain(publicAPI.delete);
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
function defaultValues() {
  return {
    initialized: false,
    drawControllersRay: false,
    inputSourceToRay: {},
    initCanvasSize: null,
    initBackground: null,
    renderWindow: null,
    xrSession: null,
    xrSessionType: 0,
    xrReferenceSpace: null,
  };
}
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, defaultValues(), initialValues);
 
  // Build VTK API
  macro.obj(publicAPI, model);
  macro.event(publicAPI, model, 'event');
 
  macro.get(publicAPI, model, ['xrSession']);
  macro.setGet(publicAPI, model, ['renderWindow', 'drawControllersRay']);
 
  // Object methods
  vtkWebXRRenderWindowHelper(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(
  extend,
  'vtkWebXRRenderWindowHelper'
);
 
// ----------------------------------------------------------------------------
 
export default {
  newInstance,
  extend,
  ...Constants,
};