File: vtkOSPRayPass.cxx

package info (click to toggle)
paraview 5.11.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 497,236 kB
  • sloc: cpp: 3,171,290; ansic: 1,315,072; python: 134,290; xml: 103,324; sql: 65,887; sh: 5,286; javascript: 4,901; yacc: 4,383; java: 3,977; perl: 2,363; lex: 1,909; f90: 1,255; objc: 143; makefile: 119; tcl: 59; pascal: 50; fortran: 29
file content (585 lines) | stat: -rw-r--r-- 17,678 bytes parent folder | download
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/*=========================================================================

  Prograxq:   Visualization Toolkit
  Module:    vtkOSPRayPass.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include <vtk_glew.h>

#include "vtkCamera.h"
#include "vtkCameraPass.h"
#include "vtkFrameBufferObjectBase.h"
#include "vtkLightsPass.h"
#include "vtkOSPRayPass.h"
#include "vtkOSPRayRendererNode.h"
#include "vtkOSPRayViewNodeFactory.h"
#include "vtkObjectFactory.h"
#include "vtkOpaquePass.h"
#include "vtkOpenGLQuadHelper.h"
#include "vtkOpenGLRenderUtilities.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLState.h"
#include "vtkOverlayPass.h"
#include "vtkRenderPassCollection.h"
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtkSequencePass.h"
#include "vtkShaderProgram.h"
#include "vtkTextureObject.h"
#include "vtkVolumetricPass.h"

#include "RTWrapper/RTWrapper.h"

#include <sstream>

#ifdef _MSC_VER
#include <intrin.h>
#endif

#ifdef __APPLE__
#include <sys/sysctl.h>
#include <sys/types.h>
#endif

VTK_ABI_NAMESPACE_BEGIN
class vtkOSPRayPassInternals : public vtkRenderPass
{
public:
  static vtkOSPRayPassInternals* New();
  vtkTypeMacro(vtkOSPRayPassInternals, vtkRenderPass);

  vtkOSPRayPassInternals() = default;

  ~vtkOSPRayPassInternals() override { delete this->QuadHelper; }

  void Init(vtkOpenGLRenderWindow* context, const std::string& renType, vtkRenderer* ren)
  {
    std::string FSSource = vtkOpenGLRenderUtilities::GetFullScreenQuadFragmentShaderTemplate();

    vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Decl",
      "uniform sampler2D colorTexture;\n"
      "uniform sampler2D depthTexture;\n");

    std::stringstream ss;
    ss << "vec4 color = texture(colorTexture, texCoord);\n"
       << "gl_FragDepth = texture(depthTexture, texCoord).r;\n";

    // The framebuffer are linear, a conversion to sRGB is required
    // This is particularly important for OSPRay pathtracer but for compatibility
    // with legacy behavior we keep the old behavior with the sciviz backend
    if (renType == "pathtracer")
    {
      // If the background image is an hdri (= mode in environment mode)
      // we need to have an opaque background but ospray set it transparent
      // Set it to opaque to let the tone mapping be applied on the background
      auto bgMode = vtkOSPRayRendererNode::GetBackgroundMode(ren);
      bool useHdri = ren->GetUseImageBasedLighting() && ren->GetEnvironmentTexture() &&
        bgMode == vtkOSPRayRendererNode::Environment;
      ss << "gl_FragData[0] = vec4(pow(color.rgb, vec3(1.0/2.2)), "
         << (useHdri ? "1.0)" : "color.a)") << ";\n";
      this->BgMode = bgMode;
    }
    else
    {
      ss << "gl_FragData[0] = color;\n";
    }

    vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Impl", ss.str());

    this->QuadHelper = new vtkOpenGLQuadHelper(context,
      vtkOpenGLRenderUtilities::GetFullScreenQuadVertexShader().c_str(), FSSource.c_str(), "");

    this->ColorTexture->SetContext(context);
    this->ColorTexture->AutoParametersOff();
    this->DepthTexture->SetContext(context);
    this->DepthTexture->AutoParametersOff();
    this->SharedColorTexture->SetContext(context);
    this->SharedColorTexture->AutoParametersOff();
    this->SharedDepthTexture->SetContext(context);
    this->SharedDepthTexture->AutoParametersOff();

    this->RendererType = renType;
  }

  void Render(const vtkRenderState* s) override { this->Parent->RenderInternal(s); }

  vtkNew<vtkOSPRayViewNodeFactory> Factory;
  vtkOSPRayPass* Parent = nullptr;
  std::string RendererType;
  vtkOSPRayRendererNode::BackgroundMode BgMode;

  // OpenGL-based display
  vtkOpenGLQuadHelper* QuadHelper = nullptr;
  vtkNew<vtkTextureObject> ColorTexture;
  vtkNew<vtkTextureObject> DepthTexture;
  vtkNew<vtkTextureObject> SharedColorTexture;
  vtkNew<vtkTextureObject> SharedDepthTexture;
};

int vtkOSPRayPass::RTDeviceRefCount = 0;

//------------------------------------------------------------------------------
vtkStandardNewMacro(vtkOSPRayPassInternals);

//------------------------------------------------------------------------------
vtkStandardNewMacro(vtkOSPRayPass);

//------------------------------------------------------------------------------
vtkOSPRayPass::vtkOSPRayPass()
{
  this->SceneGraph = nullptr;

  vtkOSPRayPass::RTInit();

  this->Internal = vtkOSPRayPassInternals::New();
  this->Internal->Parent = this;

  this->CameraPass = vtkCameraPass::New();
  this->LightsPass = vtkLightsPass::New();
  this->SequencePass = vtkSequencePass::New();
  this->VolumetricPass = vtkVolumetricPass::New();
  this->OverlayPass = vtkOverlayPass::New();

  this->RenderPassCollection = vtkRenderPassCollection::New();
  this->RenderPassCollection->AddItem(this->LightsPass);
  this->RenderPassCollection->AddItem(this->Internal);
  this->RenderPassCollection->AddItem(this->OverlayPass);

  this->SequencePass->SetPasses(this->RenderPassCollection);
  this->CameraPass->SetDelegatePass(this->SequencePass);

  this->PreviousType = "none";
}

//------------------------------------------------------------------------------
vtkOSPRayPass::~vtkOSPRayPass()
{
  this->SetSceneGraph(nullptr);
  this->Internal->Delete();
  this->Internal = 0;
  if (this->CameraPass)
  {
    this->CameraPass->Delete();
    this->CameraPass = 0;
  }
  if (this->LightsPass)
  {
    this->LightsPass->Delete();
    this->LightsPass = 0;
  }
  if (this->SequencePass)
  {
    this->SequencePass->Delete();
    this->SequencePass = 0;
  }
  if (this->VolumetricPass)
  {
    this->VolumetricPass->Delete();
    this->VolumetricPass = 0;
  }
  if (this->OverlayPass)
  {
    this->OverlayPass->Delete();
    this->OverlayPass = 0;
  }
  if (this->RenderPassCollection)
  {
    this->RenderPassCollection->Delete();
    this->RenderPassCollection = 0;
  }
  vtkOSPRayPass::RTShutdown();
}

//------------------------------------------------------------------------------
void vtkOSPRayPass::RTInit()
{
  if (!vtkOSPRayPass::IsSupported())
  {
    return;
  }
  if (RTDeviceRefCount == 0)
  {
    rtwInit();
  }
  RTDeviceRefCount++;
}

//------------------------------------------------------------------------------
void vtkOSPRayPass::RTShutdown()
{
  if (!vtkOSPRayPass::IsSupported())
  {
    return;
  }
  --RTDeviceRefCount;
  if (RTDeviceRefCount == 0)
  {
    rtwShutdown();
  }
}

//------------------------------------------------------------------------------
void vtkOSPRayPass::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//------------------------------------------------------------------------------
vtkCxxSetObjectMacro(vtkOSPRayPass, SceneGraph, vtkOSPRayRendererNode);

//------------------------------------------------------------------------------
void vtkOSPRayPass::Render(const vtkRenderState* s)
{
  if (!vtkOSPRayPass::IsSupported())
  {
    static bool warned = false;
    if (!warned)
    {
      vtkWarningMacro(<< "Ignoring render request because OSPRay is not supported.");
      warned = true;
    }
    return;
  }

  vtkRenderer* ren = s->GetRenderer();
  if (ren)
  {
    std::string type = vtkOSPRayRendererNode::GetRendererType(ren);
    if (this->PreviousType != type && this->SceneGraph)
    {
      this->SceneGraph->Delete();
      this->SceneGraph = nullptr;
    }
    if (!this->SceneGraph)
    {
      this->SceneGraph =
        vtkOSPRayRendererNode::SafeDownCast(this->Internal->Factory->CreateNode(ren));
    }
    this->PreviousType = type;
  }

  this->CameraPass->Render(s);
}

//------------------------------------------------------------------------------
void vtkOSPRayPass::RenderInternal(const vtkRenderState* s)
{
  if (!vtkOSPRayPass::IsSupported())
  {
    static bool warned = false;
    if (!warned)
    {
      vtkWarningMacro(<< "Ignoring render request because OSPRay is not supported.");
      warned = true;
    }
    return;
  }

  this->NumberOfRenderedProps = 0;

  if (this->SceneGraph)
  {
    vtkRenderer* ren = s->GetRenderer();

    vtkFrameBufferObjectBase* fbo = s->GetFrameBuffer();
    int viewportX, viewportY;
    int viewportWidth, viewportHeight;
    double tileViewport[4];
    int tileScale[2];
    if (fbo)
    {
      viewportX = 0;
      viewportY = 0;
      fbo->GetLastSize(viewportWidth, viewportHeight);

      tileViewport[0] = tileViewport[1] = 0.0;
      tileViewport[2] = tileViewport[3] = 1.0;
      tileScale[0] = tileScale[1] = 1;
    }
    else
    {
      ren->GetTiledSizeAndOrigin(&viewportWidth, &viewportHeight, &viewportX, &viewportY);

      vtkWindow* win = ren->GetVTKWindow();
      win->GetTileViewport(tileViewport);
      win->GetTileScale(tileScale);
    }

    vtkOSPRayRendererNode* oren =
      vtkOSPRayRendererNode::SafeDownCast(this->SceneGraph->GetViewNodeFor(ren));

    oren->SetSize(viewportWidth, viewportHeight);
    oren->SetViewport(tileViewport);
    oren->SetScale(tileScale);

    this->SceneGraph->TraverseAllPasses();

    if (oren->GetBackend() == nullptr)
    {
      return;
    }

    // copy the result to the window

    vtkRenderWindow* rwin = vtkRenderWindow::SafeDownCast(ren->GetVTKWindow());

    const int colorTexGL = this->SceneGraph->GetColorBufferTextureGL();
    const int depthTexGL = this->SceneGraph->GetDepthBufferTextureGL();

    vtkOpenGLRenderWindow* windowOpenGL = vtkOpenGLRenderWindow::SafeDownCast(rwin);

    std::string renType = vtkOSPRayRendererNode::GetRendererType(ren);
    int bgMode = vtkOSPRayRendererNode::GetBackgroundMode(ren);
    if (this->Internal->QuadHelper &&
      (this->Internal->RendererType != renType || this->Internal->BgMode != bgMode))
    {
      delete this->Internal->QuadHelper;
      this->Internal->QuadHelper = nullptr;
    }

    if (!this->Internal->QuadHelper)
    {
      this->Internal->Init(windowOpenGL, renType, ren);
    }
    else
    {
      windowOpenGL->GetShaderCache()->ReadyShaderProgram(this->Internal->QuadHelper->Program);
    }

    if (!this->Internal->QuadHelper->Program || !this->Internal->QuadHelper->Program->GetCompiled())
    {
      vtkErrorMacro("Couldn't build the shader program.");
      return;
    }

    windowOpenGL->MakeCurrent();

    vtkTextureObject* usedColorTex = nullptr;
    vtkTextureObject* usedDepthTex = nullptr;

    if (colorTexGL != 0 && depthTexGL != 0 && windowOpenGL != nullptr)
    {
      // for visRTX, re-use existing OpenGL texture provided
      this->Internal->SharedColorTexture->AssignToExistingTexture(colorTexGL, GL_TEXTURE_2D);
      this->Internal->SharedDepthTexture->AssignToExistingTexture(depthTexGL, GL_TEXTURE_2D);

      usedColorTex = this->Internal->SharedColorTexture;
      usedDepthTex = this->Internal->SharedDepthTexture;
    }
    else
    {
      // upload to the texture
      this->Internal->ColorTexture->Create2DFromRaw(
        viewportWidth, viewportHeight, 4, VTK_FLOAT, this->SceneGraph->GetBuffer());
      this->Internal->DepthTexture->CreateDepthFromRaw(viewportWidth, viewportHeight,
        vtkTextureObject::Float32, VTK_FLOAT, this->SceneGraph->GetZBuffer());

      usedColorTex = this->Internal->ColorTexture;
      usedDepthTex = this->Internal->DepthTexture;
    }

    usedColorTex->Activate();
    usedDepthTex->Activate();

    this->Internal->QuadHelper->Program->SetUniformi(
      "colorTexture", usedColorTex->GetTextureUnit());
    this->Internal->QuadHelper->Program->SetUniformi(
      "depthTexture", usedDepthTex->GetTextureUnit());

    vtkOpenGLState* ostate = windowOpenGL->GetState();

    vtkOpenGLState::ScopedglEnableDisable dsaver(ostate, GL_DEPTH_TEST);
    vtkOpenGLState::ScopedglEnableDisable bsaver(ostate, GL_BLEND);
    vtkOpenGLState::ScopedglDepthFunc dfsaver(ostate);
    vtkOpenGLState::ScopedglBlendFuncSeparate bfsaver(ostate);

    ostate->vtkglViewport(viewportX, viewportY, viewportWidth, viewportHeight);
    ostate->vtkglScissor(viewportX, viewportY, viewportWidth, viewportHeight);

    ostate->vtkglEnable(GL_DEPTH_TEST);

    if (ren->GetLayer() == 0)
    {
      ostate->vtkglDisable(GL_BLEND);
      ostate->vtkglDepthFunc(GL_ALWAYS);
    }
    else
    {
      ostate->vtkglEnable(GL_BLEND);
      ostate->vtkglDepthFunc(GL_LESS);
      if (vtkOSPRayRendererNode::GetCompositeOnGL(ren))
      {
        ostate->vtkglBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
      }
      else
      {
        ostate->vtkglBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO);
      }
    }

    this->Internal->QuadHelper->Render();

    usedDepthTex->Deactivate();
    usedColorTex->Deactivate();
  }
}

//------------------------------------------------------------------------------
bool vtkOSPRayPass::IsSupported()
{
  static bool detected = false;
  static bool is_supported = true;

  // Short-circuit to avoid querying on every call.
  if (detected)
  {
    return is_supported;
  }

  //////////////////////////////////////////////////////////////////////////////
  // Note that this class is used for OSPRay and OptiX (in addition to any
  // other RayTracing backends). Currently the only "spoiling" detections are
  // Apple's Rosetta not supporting AVX and older processors that don't support
  // SSE4.1. Since the only other backend is OptiX today and is not supported
  // on macOS within VTK anyways, there is no conflict. Older processors
  // without SSE4.1 may be rejected here even if OptiX is supported, but such
  // old hardware with new video cards is considered a reasonable loss to avoid
  // crashing outright otherwise.
  //////////////////////////////////////////////////////////////////////////////

#ifdef __APPLE__
  // Detect if we are being translated by Rosetta. OSPRay uses AVX instructions
  // which are not supported.
  {
    int is_translated = 0;
    size_t size = sizeof(is_translated);
    if (sysctlbyname("sysctl.proc_translated", &is_translated, &size, nullptr, 0) == -1)
    {
      if (errno == ENOENT)
      {
        is_translated = 0;
      }
      else
      {
        // Error occurred. Just continue and let it work if it can or crash if
        // it doesn't.
      }
    }
    if (is_translated)
    {
      is_supported = false;
    }
  }
#endif

#ifdef __x86_64__
#if defined(__has_builtin)
#if __has_builtin(__builtin_cpu_init)
#define vtkOSPRayPass_has_builtin_cpu_init 1
#endif
#elif defined(__clang__) // Only supported in Clang 6 and up.
#if __clang_major__ >= 6
#define vtkOSPRayPass_has_builtin_cpu_init 1
#endif
#elif defined(__GNUC__) // GCC has always provided this mechanism
#define vtkOSPRayPass_has_builtin_cpu_init 1
#endif
#ifndef vtkOSPRayPass_has_builtin_cpu_init
#define vtkOSPRayPass_has_builtin_cpu_init 0
#endif

  // ISPC detects AVX2, AVX, and SSE4.1 instruction sets. If none are
  // supported, an `abort()` awaits pretty much any ISPC call. Detect SSE4.1
  // and, if missing, disable OSPRay support.
  //
  // CPU features are detected here:
  // https://github.com/ispc/ispc/blob/bf959a96af1a362b1fe16895aa2ae997355ea05b/builtins/dispatch.ll#L132-L133
#if vtkOSPRayPass_has_builtin_cpu_init
  // Most compilers have a good CPU feature abstraction, so use it if
  // available.
  {
    __builtin_cpu_init();
    if (!__builtin_cpu_supports("sse4.1"))
    {
      is_supported = false;
    }
  }
#elif defined(_MSC_VER)
  // Query the CPU for instruction support using MSVC intrinsics.
  // https://learn.microsoft.com/en-us/cpp/intrinsics/cpuid-cpuidex
  {
    // Storage for `cpuid` results.
    std::array<int, 4> cpui;

    // First query how many function IDs are supported.
    __cpuid(cpui.data(), 0);
    int const nids = cpui[0];

    constexpr int FeatureBitFunctionId = 1;
    constexpr size_t Ecx = 2;
    constexpr int SSE4_1_bit = 19;

    // SSE4.1 support lives in the first function ID vector.
    // https://en.wikipedia.org/wiki/CPUID#EAX=1:_Processor_Info_and_Feature_Bits
    if (nids >= FeatureBitFunctionId)
    {
      __cpuid(cpui.data(), FeatureBitFunctionId);

      // The `ecx` return is in index 2; bit 19 holds SSE4.1 information.
      int const sse42_container = cpui[Ecx];
      if (!(sse42_container & (1 << SSE4_1_bit)))
      {
        is_supported = false;
      }
    }
    else
    {
      // No feature bit vector present? Something is up; assume the worst and
      // disable support.
      is_supported = false;
    }
  }
#endif
#endif

  //////////////////////////////////////////////////////////////////////////////
  // See the comment at the beginning of any conditions.
  //////////////////////////////////////////////////////////////////////////////

  detected = true;
  return is_supported;
}

//------------------------------------------------------------------------------
bool vtkOSPRayPass::IsBackendAvailable(const char* choice)
{
  if (!vtkOSPRayPass::IsSupported())
  {
    return false;
  }
  std::set<RTWBackendType> bends = rtwGetAvailableBackends();
  if (!strcmp(choice, "OSPRay raycaster"))
  {
    return (bends.find(RTW_BACKEND_OSPRAY) != bends.end());
  }
  if (!strcmp(choice, "OSPRay pathtracer"))
  {
    return (bends.find(RTW_BACKEND_OSPRAY) != bends.end());
  }
  if (!strcmp(choice, "OptiX pathtracer"))
  {
    return (bends.find(RTW_BACKEND_VISRTX) != bends.end());
  }
  return false;
}
VTK_ABI_NAMESPACE_END