All files / Sources/Rendering/OpenGL/Skybox index.js

96.51% Statements 83/86
77.41% Branches 24/31
100% Functions 6/6
96.47% Lines 82/85

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                        1x               3x     3x 4x 2x   2x 2x 2x 2x 2x 2x           3x 4x 2x     2x       3x 4x 2x   2x   2x       2x   2x 2x   2x   2x 2x 2x 2x   2x 1x 1x         2x     2x         2x   2x       3x   2x 2x 2x 8x 8x 8x   2x       2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x         2x             2x 2x   2x                       1x                                                                         2x   1x                                             2x   2x   2x                                     2x 2x     2x 2x 2x                 1x             3x     3x   3x 3x   3x 3x 3x           3x   3x     3x         1x             1x  
import { mat3, mat4 } from 'gl-matrix';
 
import * as macro from 'vtk.js/Sources/macros';
import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray';
import vtkHelper from 'vtk.js/Sources/Rendering/OpenGL/Helper';
import vtkViewNode from 'vtk.js/Sources/Rendering/SceneGraph/ViewNode';
import vtkOpenGLTexture from 'vtk.js/Sources/Rendering/OpenGL/Texture';
 
import { Representation } from 'vtk.js/Sources/Rendering/Core/Property/Constants';
 
import { registerOverride } from 'vtk.js/Sources/Rendering/OpenGL/ViewNodeFactory';
 
const { vtkErrorMacro } = macro;
 
// ----------------------------------------------------------------------------
// vtkOpenGLSkybox methods
// ----------------------------------------------------------------------------
 
function vtkOpenGLSkybox(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOpenGLSkybox');
 
  // Builds myself.
  publicAPI.buildPass = (prepass) => {
    if (prepass) {
      model._openGLRenderer =
        publicAPI.getFirstAncestorOfType('vtkOpenGLRenderer');
      model._openGLRenderWindow = model._openGLRenderer.getParent();
      model.context = model._openGLRenderWindow.getContext();
      model.tris.setOpenGLRenderWindow(model._openGLRenderWindow);
      model.openGLTexture.setOpenGLRenderWindow(model._openGLRenderWindow);
      const ren = model._openGLRenderer.getRenderable();
      model.openGLCamera = model._openGLRenderer.getViewNodeFor(
        ren.getActiveCamera()
      );
    }
  };
 
  publicAPI.queryPass = (prepass, renderPass) => {
    if (prepass) {
      Iif (!model.renderable || !model.renderable.getVisibility()) {
        return;
      }
      renderPass.incrementOpaqueActorCount();
    }
  };
 
  publicAPI.opaquePass = (prepass, renderPass) => {
    if (prepass && !model._openGLRenderer.getSelector()) {
      publicAPI.updateBufferObjects();
 
      model.context.depthMask(true);
 
      model._openGLRenderWindow
        .getShaderCache()
        .readyShaderProgram(model.tris.getProgram());
 
      model.openGLTexture.render(model._openGLRenderWindow);
 
      const texUnit = model.openGLTexture.getTextureUnit();
      model.tris.getProgram().setUniformi('sbtexture', texUnit);
 
      const ren = model._openGLRenderer.getRenderable();
 
      const keyMats = model.openGLCamera.getKeyMatrices(ren);
      const imat = new Float64Array(16);
      mat4.invert(imat, keyMats.wcpc);
      model.tris.getProgram().setUniformMatrix('IMCPCMatrix', imat);
 
      if (model.lastFormat === 'box') {
        const camPos = ren.getActiveCamera().getPosition();
        model.tris
          .getProgram()
          .setUniform3f('camPos', camPos[0], camPos[1], camPos[2]);
      }
 
      model.tris.getVAO().bind();
 
      // draw polygons
      model.context.drawArrays(
        model.context.TRIANGLES,
        0,
        model.tris.getCABO().getElementCount()
      );
      model.tris.getVAO().release();
 
      model.openGLTexture.deactivate();
    }
  };
 
  publicAPI.updateBufferObjects = () => {
    // build the VBO if needed, only happens once
    if (!model.tris.getCABO().getElementCount()) {
      const ptsArray = new Float32Array(12);
      for (let i = 0; i < 4; i++) {
        ptsArray[i * 3] = (i % 2) * 2 - 1.0;
        ptsArray[i * 3 + 1] = i > 1 ? 1.0 : -1.0;
        ptsArray[i * 3 + 2] = 1.0;
      }
      const points = vtkDataArray.newInstance({
        numberOfComponents: 3,
        values: ptsArray,
      });
      points.setName('points');
 
      const cellArray = new Uint16Array(8);
      cellArray[0] = 3;
      cellArray[1] = 0;
      cellArray[2] = 1;
      cellArray[3] = 3;
      cellArray[4] = 3;
      cellArray[5] = 0;
      cellArray[6] = 3;
      cellArray[7] = 2;
      const cells = vtkDataArray.newInstance({
        numberOfComponents: 1,
        values: cellArray,
      });
 
      model.tris.getCABO().createVBO(cells, 'polys', Representation.SURFACE, {
        points,
        cellOffset: 0,
      });
    }
 
    // update the program?
    if (model.renderable.getFormat() !== model.lastFormat) {
      model.lastFormat = model.renderable.getFormat();
 
      if (model.lastFormat === 'box') {
        // we invert Y below because opengl is messed up!
        // Cube Maps have been specified to follow the RenderMan
        // specification (for whatever reason), and RenderMan
        // assumes the images' origin being in the upper left,
        // contrary to the usual OpenGL behaviour of having the
        // image origin in the lower left. That's why things get
        // swapped in the Y direction. It totally breaks with the usual
        // OpenGL semantics and doesn't make sense at all.
        // But now we're stuck with it.  From
        // https://stackoverflow.com/questions/11685608/convention-of-faces-in-opengl-cubemapping
        //
        model.tris.setProgram(
          model._openGLRenderWindow.getShaderCache().readyShaderProgramArray(
            `//VTK::System::Dec
             attribute vec3 vertexMC;
             uniform mat4 IMCPCMatrix;
             varying vec3 TexCoords;
             void main () {
              gl_Position = vec4(vertexMC.xyz, 1.0);
              vec4 wpos = IMCPCMatrix * gl_Position;
              TexCoords = wpos.xyz/wpos.w;
             }`,
            `//VTK::System::Dec
             //VTK::Output::Dec
             varying vec3 TexCoords;
             uniform samplerCube sbtexture;
             uniform vec3 camPos;
             void main () {
               // skybox looks from inside out
               // which means we have to adjust
               // our tcoords. Otherwise text would
               // be flipped
               vec3 tc = normalize(TexCoords - camPos);
               if (abs(tc.z) < max(abs(tc.x),abs(tc.y)))
               {
                 tc = vec3(1.0, 1.0, -1.0) * tc;
               }
               else
               {
                 tc = vec3(-1.0, 1.0, 1.0) * tc;
               }
               gl_FragData[0] = textureCube(sbtexture, tc);
             }`,
            ''
          )
        );
      }
 
      if (model.lastFormat === 'background') {
        // maps the texture to the window
        model.tris.setProgram(
          model._openGLRenderWindow.getShaderCache().readyShaderProgramArray(
            `//VTK::System::Dec
             attribute vec3 vertexMC;
             uniform mat4 IMCPCMatrix;
             varying vec2 TexCoords;
             void main () {
              gl_Position = vec4(vertexMC.xyz, 1.0);
              vec4 wpos = IMCPCMatrix * gl_Position;
              TexCoords = vec2(vertexMC.x, vertexMC.y)*0.5 + 0.5;
             }`,
            `//VTK::System::Dec
             //VTK::Output::Dec
             varying vec2 TexCoords;
             uniform sampler2D sbtexture;
             void main () {
               gl_FragData[0] = texture2D(sbtexture, TexCoords);
             }`,
            ''
          )
        );
      }
 
      model.tris.getShaderSourceTime().modified();
 
      model.tris.getVAO().bind();
 
      Iif (
        !model.tris
          .getVAO()
          .addAttributeArray(
            model.tris.getProgram(),
            model.tris.getCABO(),
            'vertexMC',
            model.tris.getCABO().getVertexOffset(),
            model.tris.getCABO().getStride(),
            model.context.FLOAT,
            3,
            model.context.FALSE
          )
      ) {
        vtkErrorMacro('Error setting vertexMC in shader VAO.');
      }
    }
 
    // set/update the texture map if needed
    const tmaps = model.renderable.getTextures();
    Iif (!tmaps.length) {
      vtkErrorMacro('vtkSkybox requires a texture map');
    }
    if (model.openGLTexture.getRenderable() !== tmaps[0]) {
      model.openGLTexture.releaseGraphicsResources(model._openGLRenderWindow);
      model.openGLTexture.setRenderable(tmaps[0]);
    }
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  context: null,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Inheritance
  vtkViewNode.extend(publicAPI, model, initialValues);
 
  model.openGLTexture = vtkOpenGLTexture.newInstance();
  model.tris = vtkHelper.newInstance();
 
  model.keyMatrixTime = {};
  macro.obj(model.keyMatrixTime, { mtime: 0 });
  model.keyMatrices = {
    normalMatrix: mat3.identity(new Float64Array(9)),
    mcwc: mat4.identity(new Float64Array(16)),
  };
 
  // Build VTK API
  macro.setGet(publicAPI, model, ['context']);
 
  macro.get(publicAPI, model, ['activeTextures']);
 
  // Object methods
  vtkOpenGLSkybox(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend);
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };
 
// Register ourself to OpenGL backend if imported
registerOverride('vtkSkybox', newInstance);