imstkVTKRenderer.cpp 23.3 KB
Newer Older
Alexis Girault's avatar
Alexis Girault committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*=========================================================================

   Library: iMSTK

   Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
   & Imaging in Medicine, Rensselaer Polytechnic Institute.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

20
=========================================================================*/
Alexis Girault's avatar
Alexis Girault committed
21

22
#include "imstkVTKRenderer.h"
23
#include "imstkCamera.h"
24
25
26
#include "imstkDirectionalLight.h"
#include "imstkPointLight.h"
#include "imstkSpotLight.h"
27
#include "imstkLogger.h"
28
#include "imstkScene.h"
Sreekanth Arikatla's avatar
Sreekanth Arikatla committed
29
#include "imstkSceneObject.h"
30
#include "imstkTextureManager.h"
31
#include "imstkVisualModel.h"
32
#include "imstkVTKSurfaceMeshRenderDelegate.h"
Alexis Girault's avatar
Alexis Girault committed
33

34
#include <vtkAxesActor.h>
35
36
#include <vtkCameraActor.h>
#include <vtkCullerCollection.h>
37
#include <vtkLight.h>
38
#include <vtkLightActor.h>
Andrew Wilson's avatar
Andrew Wilson committed
39

40
#include <vtkAxis.h>
Andrew Wilson's avatar
Andrew Wilson committed
41
42
43
#include <vtkChartXY.h>
#include <vtkContextActor.h>
#include <vtkContextScene.h>
44
#include <vtkDoubleArray.h>
Andrew Wilson's avatar
Andrew Wilson committed
45
46
#include <vtkPlotBar.h>
#include <vtkStringArray.h>
47
#include <vtkTable.h>
Andrew Wilson's avatar
Andrew Wilson committed
48
#include <vtkTextProperty.h>
49

50
#include <vtkCameraPass.h>
51
#include <vtkOpenVRCamera.h>
52
53
54
55
56
57
#include <vtkOpenVRRenderer.h>
#include <vtkRenderPassCollection.h>
#include <vtkRenderStepsPass.h>
#include <vtkSequencePass.h>
#include <vtkSSAOPass.h>
#include <vtkProperty.h>
58

59
60
namespace imstk
{
61
VTKRenderer::VTKRenderer(std::shared_ptr<Scene> scene, const bool enableVR) :
Sreekanth Arikatla's avatar
Sreekanth Arikatla committed
62
    m_scene(scene),
63
64
    m_textureManager(std::make_shared<TextureManager<VTKTextureDelegate>>()),
    m_ssaoPass(vtkSmartPointer<vtkSSAOPass>::New()),
65
    m_renderStepsPass(vtkSmartPointer<vtkRenderStepsPass>::New())
Alexis Girault's avatar
Alexis Girault committed
66
{
67
    // create m_vtkRenderer depending on enableVR
68
    m_VrEnabled = enableVR;
69
70
71
72
73
74
75
    if (!enableVR)
    {
        m_vtkRenderer = vtkSmartPointer<vtkRenderer>::New();
    }
    else
    {
        m_vtkRenderer = vtkSmartPointer<vtkOpenVRRenderer>::New();
76
77
        vtkOpenVRRenderer::SafeDownCast(m_vtkRenderer)->SetAutomaticLightCreation(false);
        vtkOpenVRRenderer::SafeDownCast(m_vtkRenderer)->SetLightFollowCamera(false);
78
    }
79

80
    // Process all the changes initially (add all the delegates)
81
    sceneModifed(nullptr);
82
    this->updateRenderDelegates();
Alexis Girault's avatar
Alexis Girault committed
83
84

    // Lights and light actors
85
    for (const auto& light : scene->getLights())
Alexis Girault's avatar
Alexis Girault committed
86
    {
87
88
        std::string name = light->getTypeName();
        if (name == "DirectionalLight")
Alexis Girault's avatar
Alexis Girault committed
89
        {
90
91
92
93
94
95
            auto lightVtk = vtkSmartPointer<vtkLight>::New();
            lightVtk->SetPositional(false);
            const Color& color = light->getColor();
            lightVtk->SetColor(color.r, color.g, color.b);
            lightVtk->SetIntensity(light->getIntensity());
            lightVtk->SetFocalPoint(light->getFocalPoint().data());
96
            lightVtk->SetPosition(0.0, 0.0, 0.0);
97
98
99
            lightVtk->SetAttenuationValues(light->getAttenuationValues().data());

            m_vtkLights.push_back(VtkLightPair(light, lightVtk));
100
        }
101
        else if (name == "SpotLight")
102
        {
103
104
105
106
107
108
            auto lightVtk = vtkSmartPointer<vtkLight>::New();
            lightVtk->SetPositional(true);
            const Color& color = light->getColor();
            lightVtk->SetColor(color.r, color.g, color.b);
            lightVtk->SetIntensity(light->getIntensity());
            lightVtk->SetFocalPoint(light->getFocalPoint().data());
109
110

            auto spotLight = std::dynamic_pointer_cast<SpotLight>(light);
111
112
113
            lightVtk->SetPosition(spotLight->getPosition().data());
            lightVtk->SetConeAngle(spotLight->getSpotAngle());
            lightVtk->SetAttenuationValues(light->getAttenuationValues().data());
114

115
            m_vtkLights.push_back(VtkLightPair(light, lightVtk));
116
117

            auto lightActorSpot = vtkSmartPointer<vtkLightActor>::New();
118
            lightActorSpot->SetLight(lightVtk);
119
120
            m_debugVtkActors.push_back(lightActorSpot);
        }
121
        else if (name == "PointLight")
122
        {
123
124
125
126
127
128
129
            auto lightVtk = vtkSmartPointer<vtkLight>::New();
            lightVtk->SetPositional(true);
            const Color& color = light->getColor();
            lightVtk->SetColor(color.r, color.g, color.b);
            lightVtk->SetIntensity(light->getIntensity());
            lightVtk->SetFocalPoint(light->getFocalPoint().data());
            lightVtk->SetAttenuationValues(light->getAttenuationValues().data());
130
131

            auto pointLight = std::dynamic_pointer_cast<PointLight>(light);
132
            lightVtk->SetPosition(pointLight->getPosition().data());
133

134
            m_vtkLights.push_back(VtkLightPair(light, lightVtk));
135
136

            auto lightActorPoint = vtkSmartPointer<vtkLightActor>::New();
137
            lightActorPoint->SetLight(lightVtk);
138
139
            m_debugVtkActors.push_back(lightActorPoint);
        }
140
141
        else
        {
142
            LOG(WARNING) << "Light type undefined!";
Alexis Girault's avatar
Alexis Girault committed
143
144
145
        }
    }

146
147
    for (const auto& light : m_vtkLights)
    {
148
        m_vtkRenderer->AddLight(light.second);
149
150
    }

151
    // Global Axis
152
153
    m_AxesActor = vtkSmartPointer<vtkAxesActor>::New();
    m_AxesActor->SetShaftType(vtkAxesActor::CYLINDER_SHAFT);
154
    m_AxesActor->SetAxisLabels(false);
155
    m_debugVtkActors.push_back(m_AxesActor);
156

Alexis Girault's avatar
Alexis Girault committed
157
    // Camera and camera actor
158
159
    if (!enableVR)
    {
160
        m_camera = vtkSmartPointer<vtkCamera>::New();
161
162
163
    }
    else
    {
164
        m_camera = vtkSmartPointer<vtkOpenVRCamera>::New();
165
    }
166
167

    updateCamera();
168
    vtkNew<vtkCameraActor> camActor;
169
    camActor->SetCamera(m_camera);
170
    m_debugVtkActors.push_back(camActor);
Alexis Girault's avatar
Alexis Girault committed
171
172

    // Customize background colors
173
174
    m_vtkRenderer->SetBackground(m_config->m_BGColor1.r, m_config->m_BGColor1.g, m_config->m_BGColor1.b);
    m_vtkRenderer->SetBackground2(m_config->m_BGColor2.r, m_config->m_BGColor2.g, m_config->m_BGColor2.b);
175

Alexis Girault's avatar
Alexis Girault committed
176
    m_vtkRenderer->GradientBackgroundOn();
177

178
179
180
181
182
183
184
    ///TODO : only on deformable objects with UseBounds (need vtk update)
    // Remove culling
    if (auto culler = m_vtkRenderer->GetCullers()->GetLastItem())
    {
        m_vtkRenderer->RemoveCuller(culler);
    }

185
186
187
    // Observe changes to the scene
    connect<Event>(m_scene, &Scene::modified, this, &VTKRenderer::sceneModifed);

Andrew Wilson's avatar
Andrew Wilson committed
188
189
    {
        // Add the benchmarking chart
190
        m_timeTableChart = vtkSmartPointer<vtkChartXY>::New();
Andrew Wilson's avatar
Andrew Wilson committed
191
        vtkSmartPointer<vtkContextScene> m_benchmarkChartScene = vtkSmartPointer<vtkContextScene>::New();
192
193
        m_timeTableChartActor = vtkSmartPointer<vtkContextActor>::New();
        m_vtkRenderer->AddActor(m_timeTableChartActor);
Andrew Wilson's avatar
Andrew Wilson committed
194
195
        m_benchmarkChartScene->SetRenderer(m_vtkRenderer);

196
197
        m_timeTableChart->SetAutoSize(true);
        m_timeTableChart->SetSize(vtkRectf(0.0, 0.0, 600.0, 600.0));
Andrew Wilson's avatar
Andrew Wilson committed
198

199
200
201
        m_benchmarkChartScene->AddItem(m_timeTableChart);
        m_timeTableChartActor->SetScene(m_benchmarkChartScene);
        m_timeTableChartActor->SetVisibility(false);
Andrew Wilson's avatar
Andrew Wilson committed
202

203
204
205
206
207
208
209
        m_timeTablePlot = vtkPlotBar::SafeDownCast(m_timeTableChart->AddPlot(vtkChart::BAR));
        m_timeTablePlot->SetColor(0.6, 0.1, 0.1);
        m_timeTablePlot->SetOrientation(vtkPlotBar::HORIZONTAL);
        m_timeTableChart->GetAxis(vtkAxis::BOTTOM)->SetTitle("ms");
        m_timeTableChart->GetAxis(vtkAxis::LEFT)->SetTitle("");
        m_timeTableChart->GetAxis(vtkAxis::LEFT)->GetLabelProperties()->SetVerticalJustification(VTK_TEXT_CENTERED);
        m_timeTableChart->GetAxis(vtkAxis::LEFT)->GetLabelProperties()->SetJustification(VTK_TEXT_RIGHT);
Andrew Wilson's avatar
Andrew Wilson committed
210

211
        m_timeTable = vtkSmartPointer<vtkTable>::New();
Andrew Wilson's avatar
Andrew Wilson committed
212
213
214
215
216
217
218
219
220
        vtkSmartPointer<vtkDoubleArray> xIndices = vtkSmartPointer<vtkDoubleArray>::New();
        xIndices->SetName("Indices");
        xIndices->SetNumberOfValues(0);
        vtkSmartPointer<vtkDoubleArray> yElapsedTimes = vtkSmartPointer<vtkDoubleArray>::New();
        yElapsedTimes->SetName("Elapsed Times");
        yElapsedTimes->SetNumberOfValues(0);
        vtkSmartPointer<vtkStringArray> labels = vtkSmartPointer<vtkStringArray>::New();
        labels->SetName("Labels");
        labels->SetNumberOfValues(0);
221
222
223
224
        m_timeTable->AddColumn(xIndices);
        m_timeTable->AddColumn(yElapsedTimes);
        m_timeTable->AddColumn(labels);
        m_timeTablePlot->SetInputData(m_timeTable, 0, 1);
Andrew Wilson's avatar
Andrew Wilson committed
225

226
        m_timeTableChart->GetAxis(vtkAxis::BOTTOM)->GetLabelProperties()->SetColor(1.0, 1.0, 1.0);
227
        vtkAxis* axisY = m_timeTableChart->GetAxis(vtkAxis::LEFT);
228
229
        axisY->GetLabelProperties()->SetColor(1.0, 1.0, 1.0);
        axisY->SetGridVisible(false);
Andrew Wilson's avatar
Andrew Wilson committed
230
231
        axisY->SetCustomTickPositions(xIndices, labels);
    }
232
233

    // Prepare screen space ambient occlusion effect
234
    m_ssaoPass->SetDelegatePass(m_renderStepsPass);
Furkan Dinç's avatar
Furkan Dinç committed
235

236
    this->setConfig(this->m_config);
Alexis Girault's avatar
Alexis Girault committed
237
238
239
}

void
240
VTKRenderer::setMode(const Renderer::Mode mode, const bool enableVR)
Alexis Girault's avatar
Alexis Girault committed
241
{
242
243
    if (enableVR)
    {
244
        return;
245
    }
246
    if (mode == Mode::Empty && m_currentMode != Mode::Empty)
Alexis Girault's avatar
Alexis Girault committed
247
248
249
250
    {
        this->removeActors(m_objectVtkActors);
        m_vtkRenderer->RemoveAllLights();

251
        if (m_currentMode == Mode::Debug)
Alexis Girault's avatar
Alexis Girault committed
252
253
254
255
        {
            this->removeActors(m_debugVtkActors);
        }
    }
256
    else if (mode == Mode::Debug && m_currentMode != Mode::Debug)
Alexis Girault's avatar
Alexis Girault committed
257
258
259
    {
        this->addActors(m_debugVtkActors);

260
        if (m_currentMode == Mode::Empty)
Alexis Girault's avatar
Alexis Girault committed
261
262
        {
            this->addActors(m_objectVtkActors);
263
            for (const auto& light : m_vtkLights)
Alexis Girault's avatar
Alexis Girault committed
264
            {
265
                m_vtkRenderer->AddLight(light.second);
Alexis Girault's avatar
Alexis Girault committed
266
267
268
            }
        }
    }
269
    else if (mode == Mode::Simulation && m_currentMode != Mode::Simulation)
Alexis Girault's avatar
Alexis Girault committed
270
    {
271
        if (m_currentMode == Mode::Empty)
Alexis Girault's avatar
Alexis Girault committed
272
273
        {
            this->addActors(m_objectVtkActors);
274
            for (const auto& light : m_vtkLights)
Alexis Girault's avatar
Alexis Girault committed
275
            {
276
                m_vtkRenderer->AddLight(light.second);
Alexis Girault's avatar
Alexis Girault committed
277
278
            }
        }
279
        else if (m_currentMode == Mode::Debug)
Alexis Girault's avatar
Alexis Girault committed
280
281
        {
            this->removeActors(m_debugVtkActors);
282
        }
Alexis Girault's avatar
Alexis Girault committed
283
284
    }

285
    // Reset the camera
286
    m_camera = vtkSmartPointer<vtkCamera>::New();
287

288
    Renderer::setMode(mode, enableVR);
Alexis Girault's avatar
Alexis Girault committed
289
290
}

291
void
292
VTKRenderer::setAxesLength(const double x, const double y, const double z)
293
294
295
296
{
    m_AxesActor->SetTotalLength(x, y, z);
}

297
298
299
300
301
302
303
void
VTKRenderer::setAxesLength(const Vec3d& len)
{
    m_AxesActor->SetTotalLength(len.x(), len.y(), len.z());
}

Vec3d
304
305
VTKRenderer::getAxesLength()
{
Sreekanth Arikatla's avatar
Sreekanth Arikatla committed
306
307
    const auto ptr = m_AxesActor->GetTotalLength();
    return Vec3d(ptr[0], ptr[1], ptr[2]);
308
309
310
311
312
313
314
315
316
317
318
319
320
321
}

void
VTKRenderer::setAxesVisibility(const bool visible)
{
    m_AxesActor->SetVisibility(visible);
}

bool
VTKRenderer::getAxesVisibility() const
{
    return m_AxesActor->GetVisibility();
}

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
void
VTKRenderer::setTimeTable(const std::unordered_map<std::string, double>& timeTable)
{
    // Sort by elapsed times
    std::vector<std::pair<std::string, double>> nameToTimesVec(timeTable.begin(), timeTable.end());
    std::sort(nameToTimesVec.begin(), nameToTimesVec.end(),
        [](const std::pair<std::string, double>& a, const std::pair<std::string, double>& b) { return a.second < b.second; });

    // Construct vtkTable from provided data
    vtkSmartPointer<vtkDoubleArray> xIndices      = vtkDoubleArray::SafeDownCast(m_timeTable->GetColumn(0));
    vtkSmartPointer<vtkDoubleArray> yElapsedTimes = vtkDoubleArray::SafeDownCast(m_timeTable->GetColumn(1));
    vtkSmartPointer<vtkStringArray> labels = vtkStringArray::SafeDownCast(m_timeTable->GetColumn(2));

    labels->SetNumberOfValues(nameToTimesVec.size());
    xIndices->SetNumberOfValues(nameToTimesVec.size());
    yElapsedTimes->SetNumberOfValues(nameToTimesVec.size());
    for (size_t i = 0; i < nameToTimesVec.size(); i++)
    {
        labels->SetValue(i, nameToTimesVec[i].first.c_str());
        xIndices->SetValue(i, i + 1);
        yElapsedTimes->SetValue(i, nameToTimesVec[i].second);
    }

    // The range for the x axis is based on history of the elapsed times
    vtkAxis* botAxis = m_timeTableChart->GetAxis(vtkAxis::BOTTOM);

    // Get the previous and current range
    double newMaxElapsed = yElapsedTimes->GetRange()[1];
    yElapsedTimes->Modified();
    double currMaxElapsed = botAxis->GetMaximum();

    // Always respect the max as all information should be shown
    if (newMaxElapsed > currMaxElapsed)
    {
        botAxis->SetRange(0.0, newMaxElapsed);
    }
    // But if current elapsed is less than the existing one we can lag
    else
    {
        // Lag downscaling by 400 iterations
        if (m_timeTableIter % 400 == 0)
        {
            botAxis->SetRange(0.0, newMaxElapsed);
        }
        else
        {
            botAxis->SetRange(0.0, currMaxElapsed);
        }
        m_timeTableIter++;
    }
    botAxis->Modified();

    vtkAxis* leftAxis = m_timeTableChart->GetAxis(vtkAxis::LEFT);
    leftAxis->SetRange(xIndices->GetRange());
    leftAxis->SetCustomTickPositions(xIndices, labels);

    m_timeTable->Modified();
}

void
VTKRenderer::setTimeTableVisibility(const bool visible)
{
    m_timeTableChartActor->SetVisibility(visible);
}

bool
VTKRenderer::getTimeTableVisibility() const
{
    return m_timeTableChartActor->GetVisibility();
}
Andrew Wilson's avatar
Andrew Wilson committed
392

393
void
394
VTKRenderer::updateCamera()
395
{
396
    std::shared_ptr<Camera> cam = m_scene->getActiveCamera();
397
    getVtkRenderer()->SetActiveCamera(m_camera);
398
399
400
401
402
403
404

    // Update the camera to obtain corrected view/proj matrices
    cam->update();

    // Get the view matrix
    const Mat4d& invView = cam->getInvView();

Andrew Wilson's avatar
Andrew Wilson committed
405
    const double eyePos[3]  = { invView(0, 3), invView(1, 3), invView(2, 3) };
406
    const double forward[3] = { invView(0, 2), invView(1, 2), invView(2, 2) };
Andrew Wilson's avatar
Andrew Wilson committed
407
    const double up[3]      = { invView(0, 1), invView(1, 1), invView(2, 1) };
408
409
410
411
412
413

    m_camera->SetPosition(eyePos);
    m_camera->SetFocalPoint(eyePos[0] - forward[0], eyePos[1] - forward[1], eyePos[2] - forward[2]);
    m_camera->SetViewUp(up[0], up[1], up[2]);
    m_camera->SetViewAngle(cam->getFieldOfView());
    m_camera->SetClippingRange(cam->getNearZ(), cam->getFarZ());
414
415

    // Copy the projection back to the camera
Connor Bowley's avatar
Connor Bowley committed
416
    auto projVtk = vtkSmartPointer<vtkMatrix4x4>::Take(m_camera->GetProjectionTransformMatrix(m_vtkRenderer));
417
418
419
420
421
422
423
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            cam->m_proj(i, j) = projVtk->GetElement(j, i);
        }
    }
424
425
}

426
void
427
VTKRenderer::updateRenderDelegates()
428
{
429
430
431
432
433
    // Update their render delegates
    for (auto delegate : m_renderDelegates)
    {
        delegate.second->update();
    }
434
435
436
437
438
439
440
441
442
443
444
445
446
447

    // Update all lights (we don't use render delegates for these as there usually aren't
    // all that many lights)
    for (auto light : m_vtkLights)
    {
        std::shared_ptr<Light>    lightImstk = light.first;
        vtkSmartPointer<vtkLight> lightVtk   = light.second;
        std::string               lightName  = lightImstk->getTypeName();
        if (lightName == "DirectionalLight")
        {
            const Color& color = lightImstk->getColor();
            lightVtk->SetColor(color.r, color.g, color.b);
            lightVtk->SetIntensity(lightImstk->getIntensity());
            lightVtk->SetFocalPoint(lightImstk->getFocalPoint().data());
448
            lightVtk->SetPosition(0.0, 0.0, 0.0);
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
            lightVtk->SetAttenuationValues(lightImstk->getAttenuationValues().data());
        }
        else if (lightName == "SpotLight")
        {
            const Color& color = lightImstk->getColor();
            lightVtk->SetColor(color.r, color.g, color.b);
            lightVtk->SetIntensity(lightImstk->getIntensity());
            lightVtk->SetFocalPoint(lightImstk->getFocalPoint().data());

            auto spotLight = std::dynamic_pointer_cast<SpotLight>(lightImstk);
            lightVtk->SetPosition(spotLight->getPosition().data());
            lightVtk->SetConeAngle(spotLight->getSpotAngle());
            lightVtk->SetAttenuationValues(lightImstk->getAttenuationValues().data());
        }
        else if (lightName == "PointLight")
        {
            const Color& color = lightImstk->getColor();
            lightVtk->SetColor(color.r, color.g, color.b);
            lightVtk->SetIntensity(lightImstk->getIntensity());
            lightVtk->SetFocalPoint(lightImstk->getFocalPoint().data());
            lightVtk->SetAttenuationValues(lightImstk->getAttenuationValues().data());

            auto pointLight = std::dynamic_pointer_cast<PointLight>(lightImstk);
            lightVtk->SetPosition(pointLight->getPosition().data());
        }
    }
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
}

void
VTKRenderer::removeActors(const std::vector<vtkSmartPointer<vtkProp>>& actorList)
{
    for (const auto& actor : actorList)
    {
        m_vtkRenderer->RemoveActor(actor);
    }
}

void
VTKRenderer::addActors(const std::vector<vtkSmartPointer<vtkProp>>& actorList)
{
    for (const auto& actor : actorList)
    {
        m_vtkRenderer->AddActor(actor);
    }
}

void
VTKRenderer::addSceneObject(std::shared_ptr<SceneObject> sceneObject)
{
    m_renderedObjects.insert(sceneObject);
    m_renderedVisualModels[sceneObject] = std::unordered_set<std::shared_ptr<VisualModel>>();
    sceneObjectModified(sceneObject);
    // Observe changes on this SceneObject
    connect<Event>(sceneObject, &SceneObject::modified, this, &VTKRenderer::sceneObjectModified);
}

void
VTKRenderer::addVisualModel(std::shared_ptr<SceneObject> sceneObject, std::shared_ptr<VisualModel> visualModel)
{
    // Create a delegate for the visual m odel
    auto renderDelegate = m_renderDelegates[visualModel] = VTKRenderDelegate::makeDelegate(visualModel);
    if (renderDelegate == nullptr)
    {
512
        LOG(WARNING) << "error: Could not create render delegate for '"
513
514
515
                     << sceneObject->getName() << "'.";
        return;
    }
516
    renderDelegate->setTextureManager(m_textureManager);
517
518
519
520
521

    m_renderedVisualModels[sceneObject].insert(visualModel);
    m_objectVtkActors.push_back(renderDelegate->getVtkActor());
    m_vtkRenderer->AddActor(renderDelegate->getVtkActor());

522
    if (auto smRenderDelegate = std::dynamic_pointer_cast<VTKSurfaceMeshRenderDelegate>(renderDelegate))
523
    {
524
        smRenderDelegate->initializeTextures();
525
526
527
528
529
530
531
532
533
534
535
    }

    visualModel->setRenderDelegateCreated(this, true);
}

std::unordered_set<std::shared_ptr<VisualModel>>::iterator
VTKRenderer::removeVisualModel(std::shared_ptr<SceneObject> sceneObject, std::shared_ptr<VisualModel> visualModel)
{
    auto renderDelegate = m_renderDelegates[visualModel];
    auto iter = std::find(m_objectVtkActors.begin(), m_objectVtkActors.end(), renderDelegate->getVtkActor());
    if (iter != m_objectVtkActors.end())
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
        m_objectVtkActors.erase(iter);
    }
    m_vtkRenderer->RemoveActor(renderDelegate->getVtkActor());

    m_renderDelegates.erase(visualModel);
    return m_renderedVisualModels[sceneObject].erase(m_renderedVisualModels[sceneObject].find(visualModel));
}

std::unordered_set<std::shared_ptr<SceneObject>>::iterator
VTKRenderer::removeSceneObject(std::shared_ptr<SceneObject> sceneObject)
{
    auto iter = m_renderedObjects.erase(m_renderedObjects.find(sceneObject));

    // Remove every delegate associated and remove its actors from the scene
    for (auto visualModel : sceneObject->getVisualModels())
    {
        removeVisualModel(sceneObject, visualModel);
    }

    m_renderedVisualModels.erase(sceneObject);

    // Stop observing changes on the scene object
    disconnect(sceneObject, this, &SceneObject::modified);
    return iter;
}

void
VTKRenderer::sceneModifed(Event* imstkNotUsed(e))
{
    // If the SceneObject is in the scene but not being rendered
    for (auto sceneObject : m_scene->getSceneObjects())
    {
        if (m_renderedObjects.count(sceneObject) == 0)
570
        {
571
572
573
574
575
576
            addSceneObject(sceneObject);
        }
    }
    // If the SceneObject is being rendered but not in the scene
    for (auto i = m_renderedObjects.begin(); i != m_renderedObjects.end(); i++)
    {
577
578
        auto sos = m_scene->getSceneObjects();
        if (sos.find(*i) == sos.end())
579
580
        {
            i = removeSceneObject(*i);
581
582
        }
    }
583
584
}

Alexis Girault's avatar
Alexis Girault committed
585
void
586
VTKRenderer::sceneObjectModified(Event* e)
Alexis Girault's avatar
Alexis Girault committed
587
{
588
589
    SceneObject* sceneObject = static_cast<SceneObject*>(e->m_sender);
    if (sceneObject != nullptr)
Alexis Girault's avatar
Alexis Girault committed
590
    {
591
592
593
594
595
596
597
        // Note: All other solutions lead to some ugly variant, I went with this one
        auto iter = std::find_if(m_renderedObjects.begin(), m_renderedObjects.end(),
            [sceneObject](const std::shared_ptr<SceneObject>& i) { return i.get() == sceneObject; });
        if (iter != m_renderedObjects.end())
        {
            sceneObjectModified(*iter);
        }
Alexis Girault's avatar
Alexis Girault committed
598
599
600
601
    }
}

void
602
VTKRenderer::sceneObjectModified(std::shared_ptr<SceneObject> sceneObject)
Alexis Girault's avatar
Alexis Girault committed
603
{
604
605
    // Only diff a sceneObject being rendered
    if (m_renderedObjects.count(sceneObject) == 0 || m_renderedVisualModels.count(sceneObject) == 0)
Alexis Girault's avatar
Alexis Girault committed
606
    {
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
        return;
    }

    // Now check for added/removed VisualModels

    // If the VisualModel of the SceneObject is in the SceneObject but not being rendered
    for (auto visualModel : sceneObject->getVisualModels())
    {
        if (m_renderedVisualModels[sceneObject].count(visualModel) == 0)
        {
            addVisualModel(sceneObject, visualModel);
        }
    }
    // If the VisualModel of the SceneObject is being rendered but not part of the SceneObject anymore
    const auto& visualModels = sceneObject->getVisualModels();
    for (auto i = m_renderedVisualModels[sceneObject].begin(); i != m_renderedVisualModels[sceneObject].end(); i++)
    {
        auto iter = std::find(visualModels.begin(), visualModels.end(), *i);
        if (iter == visualModels.end()) // If end, it is not part of the SceneObject anymore
        {
            i = removeVisualModel(sceneObject, *i);
        }
Alexis Girault's avatar
Alexis Girault committed
629
630
    }
}
631

632
void
633
VTKRenderer::updateBackground(const Vec3d backgroundOne, const Vec3d backgroundTwo /*= Vec3d::Zero()*/, const bool gradientBackground /*= false*/)
634
635
636
637
638
639
640
641
642
643
644
645
{
    m_vtkRenderer->SetBackground(backgroundOne.x(), backgroundOne.y(), backgroundOne.z());
    if (gradientBackground)
    {
        m_vtkRenderer->SetBackground2(backgroundTwo.x(), backgroundTwo.y(), backgroundTwo.z());
        m_vtkRenderer->GradientBackgroundOn();
    }
    else
    {
        m_vtkRenderer->GradientBackgroundOff();
    }
}
646
647

void
648
VTKRenderer::setConfig(std::shared_ptr<RendererConfig> config)
649
{
650
    m_config = config;
651

652
653
    // update SSAO if enabled
    if (m_config->m_ssaoConfig.m_enableSSAO)
654
    {
655
656
657
658
        m_config->m_ssaoConfig.m_SSAOBlur ? m_ssaoPass->BlurOn() : m_ssaoPass->BlurOff(); // Blur on/off
        m_ssaoPass->SetRadius(m_config->m_ssaoConfig.m_SSAORadius);                       // comparison radius
        m_ssaoPass->SetBias(m_config->m_ssaoConfig.m_SSAOBias);                           // comparison bias
        m_ssaoPass->SetKernelSize(m_config->m_ssaoConfig.m_KernelSize);                   // number of samples used
Furkan Dinç's avatar
Furkan Dinç committed
659

660
661
        m_ssaoPass->SetDelegatePass(m_renderStepsPass);
        m_vtkRenderer->SetPass(m_ssaoPass);
Furkan Dinç's avatar
Furkan Dinç committed
662
663
664
    }
    else
    {
665
        m_vtkRenderer->SetPass(nullptr);
666
    }
667
668
669
670

    // update background colors
    m_vtkRenderer->SetBackground(m_config->m_BGColor1.r, m_config->m_BGColor1.g, m_config->m_BGColor1.b);
    m_vtkRenderer->SetBackground2(m_config->m_BGColor2.r, m_config->m_BGColor2.g, m_config->m_BGColor2.b);
671
}
672
673
674
675
676
677
678
679
680
681

void
VTKRenderer::setDebugActorsVisible(const bool debugActorsVisible)
{
    m_debugActorsVisible = debugActorsVisible;
    for (auto debugActors : m_debugVtkActors)
    {
        debugActors->SetVisibility(debugActorsVisible);
    }
}
682
} // imstk