vtkSMTKModelRepresentation.cxx 47.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt 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 <vtkActor.h>
#include <vtkAlgorithmOutput.h>
#include <vtkCompositeDataDisplayAttributes.h>
13
#include <vtkCompositeDataIterator.h>
14
#include <vtkCompositePolyDataMapper2.h>
15
#include <vtkFieldData.h>
16 17 18 19 20
#include <vtkGlyph3DMapper.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkMath.h>
#include <vtkMatrix4x4.h>
21
#include <vtkMultiBlockDataSet.h>
22
#include <vtkObjectFactory.h>
23
#include <vtkProperty.h>
24 25
#include <vtkRenderer.h>
#include <vtkStreamingDemandDrivenPipeline.h>
26
#include <vtkStringArray.h>
27 28
#include <vtkTransform.h>
#include <vtksys/SystemTools.hxx>
29 30 31 32 33

#include <vtkPVCacheKeeper.h>
#include <vtkPVRenderView.h>
#include <vtkPVTrivialProducer.h>

34 35 36 37
#include "vtkDataObjectTreeIterator.h"

#include "smtk/extension/paraview/server/vtkSMTKModelReader.h"
#include "smtk/extension/paraview/server/vtkSMTKModelRepresentation.h"
38
#include "smtk/extension/paraview/server/vtkSMTKWrapper.h"
39
#include "smtk/extension/vtk/source/vtkModelMultiBlockSource.h"
40 41 42 43

#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/ReferenceItem.h"

44 45
#include "smtk/model/AuxiliaryGeometry.h"
#include "smtk/model/CellEntity.h"
46
#include "smtk/model/Entity.h"
47 48
#include "smtk/model/Group.h"
#include "smtk/model/Model.h"
49
#include "smtk/model/Resource.h"
50

51
#include "smtk/resource/Component.h"
52
#include "smtk/resource/Manager.h"
53

54
#include "smtk/view/Selection.h"
55

56 57 58 59 60 61 62
namespace
{

void ColorBlockAsEntity(vtkCompositePolyDataMapper2* mapper, vtkDataObject* block,
  const std::string& uuid, const smtk::resource::ResourcePtr& res)
{
  using namespace smtk::model;
63 64
  auto modelResource = std::static_pointer_cast<Resource>(res);
  EntityRef entity(modelResource, smtk::common::UUID(uuid));
65 66 67 68 69 70 71 72
  FloatList color = entity.color();
  color = color[3] < 0 ? FloatList({ 1., 1., 1., 1. }) : color;

  // FloatList is a typedef for std::vector<double>, so it is safe to
  // pass the raw pointer to its data.
  auto atts = mapper->GetCompositeDataDisplayAttributes();
  atts->SetBlockColor(block, color.data());
}
73

74 75
void AddRenderables(
  vtkMultiBlockDataSet* data, vtkSMTKModelRepresentation::RenderableDataMap& renderables)
76
{
77
  if (!data)
78 79 80
  {
    return;
  }
81 82 83 84 85 86 87
  auto mbit = data->NewTreeIterator();
  mbit->VisitOnlyLeavesOn();
  for (mbit->GoToFirstItem(); !mbit->IsDoneWithTraversal(); mbit->GoToNextItem())
  {
    auto obj = mbit->GetCurrentDataObject();
    auto uid = vtkModelMultiBlockSource::GetDataObjectUUID(mbit->GetCurrentMetaData());
    if (!obj || !uid)
88
    {
89
      continue;
90
    }
91 92 93
    renderables[uid] = obj;
  }
  mbit->Delete();
94 95
}

96 97
} // anonymous namespace

98
///////////////////////////////////////////////////////////////////////////////
99 100 101
vtkStandardNewMacro(vtkSMTKModelRepresentation);

vtkSMTKModelRepresentation::vtkSMTKModelRepresentation()
102
  : Superclass()
103
  , Wrapper(nullptr)
104
  , SelectionObserver(-1)
105
  , EntityMapper(vtkSmartPointer<vtkCompositePolyDataMapper2>::New())
106
  , SelectedEntityMapper(vtkSmartPointer<vtkCompositePolyDataMapper2>::New())
107
  , EntityCacheKeeper(vtkSmartPointer<vtkPVCacheKeeper>::New())
108 109 110 111 112 113
  , GlyphMapper(vtkSmartPointer<vtkGlyph3DMapper>::New())
  , SelectedGlyphMapper(vtkSmartPointer<vtkGlyph3DMapper>::New())
  , Entities(vtkSmartPointer<vtkActor>::New())
  , SelectedEntities(vtkSmartPointer<vtkActor>::New())
  , GlyphEntities(vtkSmartPointer<vtkActor>::New())
  , SelectedGlyphEntities(vtkSmartPointer<vtkActor>::New())
114
  , ApplyStyle(ApplyDefaultStyle)
115 116 117 118 119
{
  this->SetupDefaults();
  this->SetNumberOfInputPorts(3);
}

120 121 122 123
vtkSMTKModelRepresentation::~vtkSMTKModelRepresentation()
{
  this->SetWrapper(nullptr);
}
124 125 126

void vtkSMTKModelRepresentation::SetupDefaults()
{
127
  vtkNew<vtkCompositeDataDisplayAttributes> compAtt;
128 129
  this->EntityMapper->SetCompositeDataDisplayAttributes(compAtt);

130 131 132
  vtkNew<vtkCompositeDataDisplayAttributes> selCompAtt;
  this->SelectedEntityMapper->SetCompositeDataDisplayAttributes(selCompAtt);

133 134 135 136 137 138
  vtkNew<vtkCompositeDataDisplayAttributes> glyphAtt;
  this->GlyphMapper->SetBlockAttributes(glyphAtt);

  vtkNew<vtkCompositeDataDisplayAttributes> selGlyphAtt;
  this->SelectedGlyphMapper->SetBlockAttributes(selGlyphAtt);

139 140 141 142
  this->Entities->SetMapper(this->EntityMapper);
  this->SelectedEntities->SetMapper(this->SelectedEntityMapper);
  this->GlyphEntities->SetMapper(this->GlyphMapper);
  this->SelectedGlyphEntities->SetMapper(this->SelectedGlyphMapper);
143 144 145 146

  // Share vtkProperty between model mappers
  this->Property = this->Entities->GetProperty();
  this->GlyphEntities->SetProperty(this->Property);
147 148
}

149 150 151 152 153 154 155 156 157 158 159 160
void vtkSMTKModelRepresentation::SetOutputExtent(vtkAlgorithmOutput* output, vtkInformation* inInfo)
{
  if (inInfo->Has(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()))
  {
    vtkPVTrivialProducer* prod = vtkPVTrivialProducer::SafeDownCast(output->GetProducer());
    if (prod)
    {
      prod->SetWholeExtent(inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()));
    }
  }
}

161
bool vtkSMTKModelRepresentation::GetModelBounds()
162
{
163 164
  // Entity tessellation bounds
  double entityBounds[6];
165
  this->GetEntityBounds(this->GetInternalOutputPort(0)->GetProducer()->GetOutputDataObject(0),
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    entityBounds, this->EntityMapper->GetCompositeDataDisplayAttributes());

  // Instance placement bounds
  double* instanceBounds = this->GlyphMapper->GetBounds();

  vtkBoundingBox bbox;
  if (vtkBoundingBox::IsValid(entityBounds))
  {
    bbox.AddPoint(entityBounds[0], entityBounds[2], entityBounds[4]);
    bbox.AddPoint(entityBounds[1], entityBounds[3], entityBounds[5]);
  }

  if (vtkBoundingBox::IsValid(instanceBounds))
  {
    bbox.AddPoint(instanceBounds[0], instanceBounds[2], instanceBounds[4]);
    bbox.AddPoint(instanceBounds[1], instanceBounds[3], instanceBounds[5]);
  }

  if (bbox.IsValid())
  {
    bbox.GetBounds(this->DataBounds);
    return true;
  }

190
  vtkMath::UninitializeBounds(this->DataBounds);
191 192
  return false;
}
193

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
bool vtkSMTKModelRepresentation::GetEntityBounds(
  vtkDataObject* dataObject, double bounds[6], vtkCompositeDataDisplayAttributes* cdAttributes)
{
  vtkMath::UninitializeBounds(bounds);
  if (vtkCompositeDataSet* cd = vtkCompositeDataSet::SafeDownCast(dataObject))
  {
    // computing bounds with only visible blocks
    vtkCompositeDataDisplayAttributes::ComputeVisibleBounds(cdAttributes, cd, bounds);
    if (vtkBoundingBox::IsValid(bounds))
    {
      return true;
    }
  }
  return false;
}

210 211 212
int vtkSMTKModelRepresentation::RequestData(
  vtkInformation* request, vtkInformationVector** inVec, vtkInformationVector* outVec)
{
213
  this->EntityCacheKeeper->RemoveAllCaches();
214 215 216 217 218 219
  if (inVec[0]->GetNumberOfInformationObjects() == 1)
  {
    vtkInformation* inInfo = inVec[0]->GetInformationObject(0);
    this->SetOutputExtent(this->GetInternalOutputPort(0), inInfo);

    // Model entities
220
    this->EntityCacheKeeper->SetInputConnection(this->GetInternalOutputPort(0));
221 222 223 224

    // Glyph points (2) and prototypes (1)
    this->GlyphMapper->SetInputConnection(this->GetInternalOutputPort(2));
    this->GlyphMapper->SetInputConnection(1, this->GetInternalOutputPort(1));
225
    this->ConfigureGlyphMapper(this->GlyphMapper.GetPointer());
226 227 228 229

    this->SelectedGlyphMapper->SetInputConnection(this->GetInternalOutputPort(2));
    this->SelectedGlyphMapper->SetInputConnection(1, this->GetInternalOutputPort(1));
    this->ConfigureGlyphMapper(this->SelectedGlyphMapper.GetPointer());
230
  }
231
  this->EntityCacheKeeper->Update();
232 233 234 235

  this->EntityMapper->Modified();
  this->GlyphMapper->Modified();

236
  this->GetModelBounds();
David Thompson's avatar
David Thompson committed
237 238 239

  // New input data requires updated block colors:
  this->UpdateColorBy = true;
240
  return Superclass::RequestData(request, inVec, outVec);
241 242 243 244 245
}

int vtkSMTKModelRepresentation::ProcessViewRequest(
  vtkInformationRequestKey* request_type, vtkInformation* inInfo, vtkInformation* outInfo)
{
246
  if (!Superclass::ProcessViewRequest(request_type, inInfo, outInfo))
247 248 249 250 251 252 253
  {
    // i.e. this->GetVisibility() == false, hence nothing to do.
    return 0;
  }

  if (request_type == vtkPVView::REQUEST_UPDATE())
  {
254
    // provide the "geometry" to the view so the view can deliver it to the
255 256 257 258 259
    // rendering nodes as and when needed.
    // When this process doesn't have any valid input, the cache-keeper is setup
    // to provide a place-holder dataset of the right type. This is essential
    // since the vtkPVRenderView uses the type specified to decide on the
    // delivery mechanism, among other things.
260
    vtkPVRenderView::SetPiece(inInfo, this, this->EntityCacheKeeper->GetOutputDataObject(0), 0, 0);
261 262 263 264 265 266 267 268 269

    // Since we are rendering polydata, it can be redistributed when ordered
    // compositing is needed. So let the view know that it can feel free to
    // redistribute data as and when needed.
    vtkPVRenderView::MarkAsRedistributable(inInfo, this);

    // Tell the view if this representation needs ordered compositing. We need
    // ordered compositing when rendering translucent geometry. We need to extend
    // this condition to consider translucent LUTs once we start supporting them.
270
    if (this->Entities->HasTranslucentPolygonalGeometry() ||
David Thompson's avatar
David Thompson committed
271 272 273
      this->GlyphEntities->HasTranslucentPolygonalGeometry() ||
      this->SelectedEntities->HasTranslucentPolygonalGeometry() ||
      this->SelectedGlyphEntities->HasTranslucentPolygonalGeometry())
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    {
      outInfo->Set(vtkPVRenderView::NEED_ORDERED_COMPOSITING(), 1);
    }

    // Finally, let the view know about the geometry bounds. The view uses this
    // information for resetting camera and clip planes. Since this
    // representation allows users to transform the geometry, we need to ensure
    // that the bounds we report include the transformation as well.
    vtkNew<vtkMatrix4x4> matrix;
    this->Entities->GetMatrix(matrix.GetPointer());
    vtkPVRenderView::SetGeometryBounds(inInfo, this->DataBounds, matrix.GetPointer());
  }
  else if (request_type == vtkPVView::REQUEST_UPDATE_LOD())
  {
    /// TODO Add LOD Mappers
  }
  else if (request_type == vtkPVView::REQUEST_RENDER())
  {
292 293 294 295 296 297
    // Update model entity and glyph attributes
    // vtkDataObject* (blocks) in the multi-block may have changed after
    // updating the pipeline, so UpdateEntityAttributes and UpdateInstanceAttributes
    // are called here to ensure the block attributes are updated with the current
    // block pointers. To do this, it uses the flat-index mapped attributes stored in
    // this class.
298 299
    auto producerPort = vtkPVRenderView::GetPieceProducer(inInfo, this, 0);
    this->EntityMapper->SetInputConnection(0, producerPort);
300
    this->SelectedEntityMapper->SetInputConnection(0, producerPort);
301 302
    auto producer = producerPort->GetProducer();
    auto data = producer->GetOutputDataObject(vtkModelMultiBlockSource::MODEL_ENTITY_PORT);
303 304
    this->UpdateColoringParameters(data);
    this->UpdateRepresentationSubtype();
305

306 307 308
    // Entities
    auto multiblockModel = vtkMultiBlockDataSet::SafeDownCast(data);
    // Glyphs
309 310 311
    data = producer->GetNumberOfOutputPorts() > 1
      ? producer->GetOutputDataObject(vtkModelMultiBlockSource::INSTANCE_PORT)
      : nullptr;
312 313 314 315 316 317
    auto multiblockInstance = vtkMultiBlockDataSet::SafeDownCast(data);

    // If the input has changed, update the map of polydata pointers in RenderableData:
    this->UpdateRenderableData(multiblockModel, multiblockInstance);
    // If the selection has changed, update the visual properties of blocks:
    this->UpdateDisplayAttributesFromSelection(multiblockModel, multiblockInstance);
318 319 320 321 322 323 324
  }

  return 1;
}

void vtkSMTKModelRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
325
  Superclass::PrintSelf(os, indent);
326 327 328 329 330 331 332 333 334
}

bool vtkSMTKModelRepresentation::AddToView(vtkView* view)
{
  vtkPVRenderView* rview = vtkPVRenderView::SafeDownCast(view);
  if (rview)
  {
    rview->GetRenderer()->AddActor(this->Entities);
    rview->GetRenderer()->AddActor(this->GlyphEntities);
335
    rview->GetRenderer()->AddActor(this->SelectedEntities);
336 337
    rview->GetRenderer()->AddActor(this->SelectedGlyphEntities);

Alvaro Sanchez's avatar
Alvaro Sanchez committed
338 339 340 341 342
    rview->RegisterPropForHardwareSelection(this, this->Entities);
    rview->RegisterPropForHardwareSelection(this, this->GlyphEntities);
    rview->RegisterPropForHardwareSelection(this, this->SelectedEntities);
    rview->RegisterPropForHardwareSelection(this, this->SelectedGlyphEntities);

343
    return Superclass::AddToView(view);
344 345 346 347 348 349 350 351 352 353 354
  }
  return false;
}

bool vtkSMTKModelRepresentation::RemoveFromView(vtkView* view)
{
  vtkPVRenderView* rview = vtkPVRenderView::SafeDownCast(view);
  if (rview)
  {
    rview->GetRenderer()->RemoveActor(this->Entities);
    rview->GetRenderer()->RemoveActor(this->GlyphEntities);
355
    rview->GetRenderer()->RemoveActor(this->SelectedEntities);
356
    rview->GetRenderer()->RemoveActor(this->SelectedGlyphEntities);
357

Alvaro Sanchez's avatar
Alvaro Sanchez committed
358 359 360 361 362
    rview->UnRegisterPropForHardwareSelection(this, this->Entities);
    rview->UnRegisterPropForHardwareSelection(this, this->GlyphEntities);
    rview->UnRegisterPropForHardwareSelection(this, this->SelectedEntities);
    rview->UnRegisterPropForHardwareSelection(this, this->SelectedGlyphEntities);

363
    return Superclass::RemoveFromView(view);
364 365 366 367 368 369 370 371
  }
  return false;
}

void vtkSMTKModelRepresentation::SetVisibility(bool val)
{
  this->Entities->SetVisibility(val);
  this->GlyphEntities->SetVisibility(val);
372 373

  this->SelectedEntities->SetVisibility(val);
374 375
  this->SelectedGlyphEntities->SetVisibility(val);

376
  Superclass::SetVisibility(val);
377 378
}

379 380 381 382 383 384 385 386 387
void vtkSMTKModelRepresentation::GetEntityVisibilities(std::map<smtk::common::UUID, int>& visdata)
{
  visdata.clear();
  for (auto entry : this->ComponentState)
  {
    visdata[entry.first] = entry.second.m_visibility;
  }
}

388 389
bool vtkSMTKModelRepresentation::SetEntityVisibility(
  smtk::resource::PersistentObjectPtr ent, bool visible)
390
{
391 392
  bool didChange = false;
  if (!ent || !ent->id())
393
  {
394
    return didChange;
395
  }
396 397 398 399 400 401 402 403 404 405 406 407

  auto csit = this->ComponentState.find(ent->id());
  if (csit == this->ComponentState.end() && visible)
  { // No change from the presumed default.
    return didChange;
  }
  else if (csit == this->ComponentState.end())
  { // No previous visibility entry. Add one and update.
    csit = this->ComponentState.insert(std::make_pair(ent->id(), State())).first;
    didChange = true;
  }
  if (!!csit->second.m_visibility != visible || didChange)
408
  {
409
    csit->second.m_visibility = (visible ? 1 : 0);
410 411 412
    didChange = true;
    auto dataIt = this->RenderableData.find(csit->first);
    if (dataIt != this->RenderableData.end())
413
    {
414
      // Tell both the entity and glyph mappers that, should they encounter the data object,
415
      // use the provided visibility.
416
      this->EntityMapper->GetCompositeDataDisplayAttributes()->SetBlockVisibility(
417 418 419
        dataIt->second, !!csit->second.m_visibility);
      this->SelectedEntityMapper->GetCompositeDataDisplayAttributes()->SetBlockVisibility(
        dataIt->second, !csit->second.m_visibility);
420
      this->GlyphMapper->GetBlockAttributes()->SetBlockVisibility(
421 422 423
        dataIt->second, !!csit->second.m_visibility);
      this->SelectedGlyphMapper->GetBlockAttributes()->SetBlockVisibility(
        dataIt->second, !csit->second.m_visibility);
424 425 426
      // Mark the mappers as modified or the new visibility info will not be updated:
      this->EntityMapper->Modified();
      this->GlyphMapper->Modified();
427 428
    }
  }
429
  return didChange;
430 431
}

432 433 434 435
bool vtkSMTKModelRepresentation::ApplyDefaultStyle(
  smtk::view::SelectionPtr seln, RenderableDataMap& renderables, vtkSMTKModelRepresentation* self)
{
  bool atLeastOneSelected = false;
436
  smtk::attribute::Attribute::Ptr attr;
437 438 439 440 441 442 443 444
  for (auto& item : seln->currentSelection())
  {
    if (item.second <= 0)
    {
      // Should never happen.
      continue;
    }

445 446 447 448
    // If the item is an attribute, it will not be directly renderable,
    // so preview its associated entities.
    attr = item.first->as<smtk::attribute::Attribute>();
    if (attr)
449
    {
450
      if (attr->associations())
451
      {
452 453 454 455 456
        for (auto obj : *attr->associations())
        {
          atLeastOneSelected |=
            self->SelectComponentFootprint(obj, /*selnBit TODO*/ 1, renderables);
        }
457 458 459 460 461
      }
    }
    else
    {
      atLeastOneSelected |= self->SelectComponentFootprint(item.first, item.second, renderables);
462 463 464 465 466 467
    }
  }

  return atLeastOneSelected;
}

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
bool vtkSMTKModelRepresentation::SelectComponentFootprint(
  smtk::resource::PersistentObjectPtr item, int selnBits, RenderableDataMap& renderables)
{
  bool atLeastOneSelected = false;
  if (!item)
  {
    return atLeastOneSelected;
  }

  // Determine the actor-pair we are dealing with (normal or instanced):
  auto entity = item->as<smtk::model::Entity>();
  bool isGlyphed = entity && entity->isInstance();

  // Determine if the user has hidden the entity
  auto& smap = this->GetComponentState();
  auto cstate = smap.find(item->id());
  bool hidden = (cstate != smap.end() && !cstate->second.m_visibility);

  // TODO: A single persistent object may have a "footprint"
  // (i.e., a set<vtkDataObject*>) that represents it.
  // In this case, we should set the selected state for all
  // of the footprint. However, this is complicated by the fact
  // that some of the footprint entries might correspond to
  // children (boundary) objects that might be controlled
  // independently.
  //
  // For now, assume each persistent object has at most 1
  // vtkDataObject associated with it.
  auto dataIt = renderables.find(item->id());
  if (dataIt != renderables.end())
  {
    this->SetSelectedState(dataIt->second, hidden ? -1 : selnBits, isGlyphed);
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
    atLeastOneSelected |= !hidden;
  }
  else
  {
    // The component does not have any geometry of its own... but perhaps
    // we can render its children highlighted instead.
    auto ent = item->as<smtk::model::Entity>();
    if (ent)
    {
      if (ent->isGroup())
      {
        auto members = smtk::model::Group(ent).members<smtk::model::EntityRefs>();
        atLeastOneSelected |= this->SelectComponentFootprint(members, selnBits, renderables);
      }
      else if (ent->isModel())
      {
        auto model = smtk::model::Model(ent);
        auto cells = model.cellsAs<smtk::model::EntityRefs>();
        for (auto cell : cells)
        {
          // If the cell has no geometry, then add its boundary cells.
          if (renderables.find(cell.entity()) == renderables.end())
          {
            auto bdys = smtk::model::CellEntity(cell).boundingCellsAs<smtk::model::EntityRefs>();
            cells.insert(bdys.begin(), bdys.end());
          }
        }
        atLeastOneSelected |= this->SelectComponentFootprint(cells, selnBits, renderables);

        auto groups = model.groups();
        for (auto group : groups)
        {
          auto members = group.members<smtk::model::EntityRefs>();
          atLeastOneSelected |= this->SelectComponentFootprint(members, selnBits, renderables);
        }

        // TODO: Auxiliary geometry may also be handled by a separate representation.
        //       Need to ensure that representation also renders selection properly.
        auto auxGeoms = model.auxiliaryGeometry();
        // Convert auxGeoms to EntityRefs to match SelectComponentFootprint() API:
        smtk::model::EntityRefs auxEnts;
        for (auto auxGeom : auxGeoms)
        {
          auxEnts.insert(auxGeom);
        }
        atLeastOneSelected |= this->SelectComponentFootprint(auxEnts, selnBits, renderables);
      }
      else if (ent->isCellEntity())
      {
        auto bdys = smtk::model::CellEntity(ent).boundingCellsAs<smtk::model::EntityRefs>();
        atLeastOneSelected |= this->SelectComponentFootprint(bdys, selnBits, renderables);
      }
    }
  }
  return atLeastOneSelected;
}

bool vtkSMTKModelRepresentation::SelectComponentFootprint(
  const smtk::model::EntityRefs& items, int selnBits, RenderableDataMap& renderables)
{
  bool atLeastOneSelected = false;
  auto& smap = this->GetComponentState();
  for (auto item : items)
  {
    auto dataIt = renderables.find(item.entity());
    auto cstate = smap.find(item.entity());
    bool hidden = (cstate != smap.end() && !cstate->second.m_visibility);
    if (dataIt != renderables.end())
    {
      this->SetSelectedState(dataIt->second, hidden ? -1 : selnBits, item.isInstance());
      atLeastOneSelected |= !hidden;
    }
572 573 574 575
  }
  return atLeastOneSelected;
}

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
int vtkSMTKModelRepresentation::FillInputPortInformation(int port, vtkInformation* info)
{
  // Saying INPUT_IS_OPTIONAL() is essential, since representations don't have
  // any inputs on client-side (in client-server, client-render-server mode) and
  // render-server-side (in client-render-server mode).
  if (port == 0)
  {
    // Entity tessellations
    info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
    info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet");
    return 1;
  }
  if (port == 1)
  {
    // Glyph vertices
    info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
    info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet");
    return 1;
  }
  else if (port == 2)
  {
    // Glyph sources
    info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1);
    info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObjectTree");
    info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData");
    return 1;
  }

  return 0;
}
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638

void vtkSMTKModelRepresentation::ConfigureGlyphMapper(vtkGlyph3DMapper* mapper)
{
  mapper->SetUseSourceTableTree(true);

  mapper->SetSourceIndexArray(VTK_INSTANCE_SOURCE);
  mapper->SetSourceIndexing(true);

  mapper->SetScaleArray(VTK_INSTANCE_SCALE);
  mapper->SetScaling(true);

  mapper->SetOrientationArray(VTK_INSTANCE_ORIENTATION);
  mapper->SetOrientationMode(vtkGlyph3DMapper::ROTATION);

  mapper->SetMaskArray(VTK_INSTANCE_VISIBILITY);
  mapper->SetMasking(true);
}

void vtkSMTKModelRepresentation::SetMapScalars(int val)
{
  if (val < 0 || val > 1)
  {
    vtkWarningMacro(<< "Invalid parameter for vtkSMTKModelRepresentation::SetMapScalars: " << val);
    val = 0;
  }

  int mapToColorMode[] = { VTK_COLOR_MODE_DIRECT_SCALARS, VTK_COLOR_MODE_MAP_SCALARS };
  this->EntityMapper->SetColorMode(mapToColorMode[val]);
  this->GlyphMapper->SetColorMode(mapToColorMode[val]);
}
639

640 641 642 643 644 645
void vtkSMTKModelRepresentation::SetInterpolateScalarsBeforeMapping(int val)
{
  this->EntityMapper->SetInterpolateScalarsBeforeMapping(val);
  this->GlyphMapper->SetInterpolateScalarsBeforeMapping(val);
}

646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
void vtkSMTKModelRepresentation::UpdateRenderableData(
  vtkMultiBlockDataSet* modelData, vtkMultiBlockDataSet* instanceData)
{
  if ((modelData && modelData->GetMTime() > this->RenderableTime) ||
    (instanceData && instanceData->GetMTime() > this->RenderableTime) ||
    (this->SelectionTime > this->RenderableTime))
  {
    this->RenderableData.clear();
    AddRenderables(instanceData, this->RenderableData);
    AddRenderables(modelData, this->RenderableData);
    this->RenderableTime.Modified();
  }
}

void vtkSMTKModelRepresentation::UpdateDisplayAttributesFromSelection(
  vtkMultiBlockDataSet* modelData, vtkMultiBlockDataSet* instanceData)
{
  auto rm = this->GetWrapper();
  auto sm = rm ? rm->GetSelection() : nullptr;
  if (!sm)
  {
    this->Entities->SetVisibility(1);
    this->GlyphEntities->SetVisibility(1);
    this->SelectedEntities->SetVisibility(0);
    this->SelectedGlyphEntities->SetVisibility(0);
    return;
  }
  else
  {
    this->SelectedEntities->SetVisibility(1);
    this->SelectedGlyphEntities->SetVisibility(1);
  }

  if (!modelData)
  {
    return;
  }

  if (modelData->GetMTime() < this->ApplyStyleTime &&
    (!instanceData || instanceData->GetMTime() < this->ApplyStyleTime) &&
    this->RenderableTime < this->ApplyStyleTime && this->SelectionTime < this->ApplyStyleTime)
  {
    return;
  }

  // We are about to manually set block visibilities for the selection,
  // so reset what's there now to reflect nothing being selected (i.e.,
  // only blocks hidden by user should have visibility entries and those
  // should be false).
  auto nrme = this->EntityMapper->GetCompositeDataDisplayAttributes();
  auto nrmg = this->GlyphMapper->GetBlockAttributes();
  nrme->RemoveBlockVisibilities();
  nrmg->RemoveBlockVisibilities();
  // Similarly, the selected-entity and selected-glyph block visibilities
  // should *all* be present but set to false.
  auto seda = this->SelectedEntityMapper->GetCompositeDataDisplayAttributes();
  auto sgda = this->SelectedGlyphMapper->GetBlockAttributes();
  for (auto entry : this->RenderableData)
  {
    seda->SetBlockVisibility(entry.second, false);
    sgda->SetBlockVisibility(entry.second, false);
  }

  // Add user-specified visibility
  for (auto entry : this->ComponentState)
  {
    auto rit = this->RenderableData.find(entry.first);
    if (rit == this->RenderableData.end())
    {
      continue;
    }
717 718
    nrme->SetBlockVisibility(rit->second, !!entry.second.m_visibility);
    nrmg->SetBlockVisibility(rit->second, !!entry.second.m_visibility);
719 720 721 722 723 724
    // We don't need to set visibility on seda/sgda here since
    // it will always be false (no selection being processed yet).
  }

  // Finally, ask our "style" functor to update selection visibility/color info
  // on the mappers by calling SetSelectedState() on entries in this->RenderableData.
725 726 727 728 729 730 731 732
  bool atLeastOneSelected = this->ApplyStyle(sm, this->RenderableData, this);
  (void)atLeastOneSelected;

  // This is necessary to force an update in the mapper
  this->Entities->GetMapper()->Modified();
  this->GlyphEntities->GetMapper()->Modified();
  this->SelectedEntities->GetMapper()->Modified();
  this->SelectedGlyphEntities->GetMapper()->Modified();
733 734 735 736

  this->ApplyStyleTime.Modified();
}

737
void vtkSMTKModelRepresentation::UpdateSelection(
738
  vtkMultiBlockDataSet* data, vtkCompositeDataDisplayAttributes* blockAttr, vtkActor* actor)
739
{
740
  auto rm = this->GetWrapper(); // vtkSMTKWrapper::Instance(); // TODO: Remove the need for this.
741
  auto sm = rm ? rm->GetSelection() : nullptr;
742
  // std::cout << "rep " << this << " wrapper " << rm << " seln " << sm << "\n";
743 744
  if (!sm)
  {
745
    actor->SetVisibility(0);
746 747
    return;
  }
748

749
  auto selection = sm->currentSelection();
750 751 752 753 754
  if (selection.empty())
  {
    actor->SetVisibility(0);
    return;
  }
755

756
  // std::cout << "Updating rep selection from " << sm << ", have " << selection.size() << " entries in map\n";
757

758
  int propVis = 0;
759 760 761 762
  this->ClearSelection(actor->GetMapper()); // FIXME: ClearSelection does stupid things.
  // FIXME: This is the wrong thing to loop over -- since we don't have a map
  //        from component (or UUID) to block ID, the call to FindNode is slow.
  //        If we loop over blocks instead, we can search the selection map quickly!
763 764
  for (auto& item : selection)
  {
765 766 767 768
    if (item.second <= 0)
    {
      continue;
    }
769 770 771
    auto matchedBlock = this->FindNode(data, item.first->id().toString());
    if (matchedBlock)
    {
772
      propVis = 1;
773
      blockAttr->SetBlockVisibility(matchedBlock, true);
774 775
      blockAttr->SetBlockColor(
        matchedBlock, item.second > 1 ? this->HoverColor : this->SelectionColor);
776 777
    }
  }
778
  actor->SetVisibility(propVis);
779

780
  // This is necessary to force an update in the mapper
781
  actor->GetMapper()->Modified();
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
}

vtkDataObject* vtkSMTKModelRepresentation::FindNode(
  vtkMultiBlockDataSet* data, const std::string& uuid)
{
  const int numBlocks = data->GetNumberOfBlocks();
  for (int index = 0; index < numBlocks; index++)
  {
    auto currentBlock = data->GetBlock(index);
    if (data->HasMetaData(index))
    {
      auto currentId = data->GetMetaData(index)->Get(vtkModelMultiBlockSource::ENTITYID());
      if (currentId)
      {
        const std::string currentIdStr = currentId;
        if (currentIdStr.compare(uuid) == 0)
        {
          return currentBlock;
        }
      }
    }

804
    auto childBlock = vtkMultiBlockDataSet::SafeDownCast(currentBlock);
805 806
    if (childBlock)
    {
807 808 809 810 811
      auto matchedNode = this->FindNode(childBlock, uuid);
      if (matchedNode)
      {
        return matchedNode;
      }
812 813 814 815 816
    }
  }

  return nullptr;
}
817

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
void vtkSMTKModelRepresentation::ClearSelection(vtkMapper* mapper)
{
  auto clearAttributes = [](vtkCompositeDataDisplayAttributes* attr) {
    attr->RemoveBlockVisibilities();
    attr->RemoveBlockColors();
  };

  auto cpdm = vtkCompositePolyDataMapper2::SafeDownCast(mapper);
  if (cpdm)
  {
    auto blockAttr = cpdm->GetCompositeDataDisplayAttributes();
    clearAttributes(blockAttr);
    auto data = cpdm->GetInputDataObject(0, 0);

    // For vtkCompositePolyDataMapper2, setting the top node as false is enough
    // since the state of the top node will stream down to its nodes.
    blockAttr->SetBlockVisibility(data, false);
    return;
  }

  auto gm = vtkGlyph3DMapper::SafeDownCast(mapper);
  if (gm)
  {
    auto blockAttr = gm->GetBlockAttributes();
    clearAttributes(blockAttr);

    // Glyph3DMapper does not behave as vtkCompositePolyDataMapper2, hence it is
    // necessary to update the block visibility of each node directly.
    auto mbds = vtkMultiBlockDataSet::SafeDownCast(gm->GetInputDataObject(0, 0));
    vtkCompositeDataIterator* iter = mbds->NewIterator();

    iter->GoToFirstItem();
    while (!iter->IsDoneWithTraversal())
    {
      auto dataObj = iter->GetCurrentDataObject();
      blockAttr->SetBlockVisibility(dataObj, false);
      iter->GoToNextItem();
    }
    iter->Delete();
    return;
  }
}

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
void vtkSMTKModelRepresentation::SetResource(smtk::resource::ResourcePtr res)
{
  this->Resource = res;
}

void vtkSMTKModelRepresentation::SetColorBy(const char* type)
{
  if (vtksys::SystemTools::Strucmp(type, "Entity") == 0)
  {
    this->SetColorBy(ENTITY);
  }
  else if (vtksys::SystemTools::Strucmp(type, "Volume") == 0)
  {
    this->SetColorBy(VOLUME);
  }
876
  else if (vtksys::SystemTools::Strucmp(type, "Field") == 0)
877
  {
878
    this->SetColorBy(FIELD);
879 880 881 882 883 884 885 886 887 888 889 890 891 892
  }
  else
  {
    vtkErrorMacro("Invalid type: " << type);
  }

  // Foce update of ColorBy
  this->UpdateColorBy = true;

  // Force update of internal attributes
  this->BlockAttrChanged = true;
  this->InstanceAttrChanged = true;
}

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
void vtkSMTKModelRepresentation::SelectionModified()
{
  this->SelectionTime.Modified();
}

void vtkSMTKModelRepresentation::SetWrapper(vtkSMTKWrapper* wrapper)
{
  if (wrapper == this->Wrapper)
  {
    return;
  }
  if (this->Wrapper)
  {
    auto oldSeln = this->Wrapper->GetSelection();
    if (oldSeln)
    {
      oldSeln->unobserve(this->SelectionObserver);
    }
    this->SelectionObserver = -1;
    this->Wrapper->UnRegister(this);
  }
  this->Wrapper = wrapper;
  if (this->Wrapper)
  {
    this->Wrapper->Register(this);
    // Observe the Wrapper's selection and mark when we need
    // to rebuild visual properties (due to selection changes).
    auto newSeln = this->Wrapper->GetSelection();
    this->SelectionObserver = newSeln
      ? newSeln->observe(
          [this](const std::string&, smtk::view::Selection::Ptr) { this->SelectionModified(); })
      : -1;
  }
  this->Modified();
}

929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
void vtkSMTKModelRepresentation::SetRepresentation(const char* type)
{
  if (vtksys::SystemTools::Strucmp(type, "Points") == 0)
  {
    this->SetRepresentation(POINTS);
  }
  else if (vtksys::SystemTools::Strucmp(type, "Wireframe") == 0)
  {
    this->SetRepresentation(WIREFRAME);
  }
  else if (vtksys::SystemTools::Strucmp(type, "Surface") == 0)
  {
    this->SetRepresentation(SURFACE);
  }
  else if (vtksys::SystemTools::Strucmp(type, "Surface With Edges") == 0)
  {
    this->SetRepresentation(SURFACE_WITH_EDGES);
  }
  else
  {
    vtkErrorMacro("Invalid type: " << type);
  }
}

953 954 955 956 957 958
void vtkSMTKModelRepresentation::SetSelectionPointSize(double val)
{
  this->SelectedEntities->GetProperty()->SetPointSize(val);
  this->SelectedGlyphEntities->GetProperty()->SetPointSize(val);
}

959 960 961 962 963 964
void vtkSMTKModelRepresentation::SetLookupTable(vtkScalarsToColors* val)
{
  this->EntityMapper->SetLookupTable(val);
  this->GlyphMapper->SetLookupTable(val);
}

965 966 967 968 969 970
void vtkSMTKModelRepresentation::SetSelectionLineWidth(double val)
{
  this->SelectedEntities->GetProperty()->SetLineWidth(val);
  this->SelectedGlyphEntities->GetProperty()->SetLineWidth(val);
}

971 972
void vtkSMTKModelRepresentation::SetPointSize(double val)
{
973
  this->Property->SetPointSize(val);
974
}
975

976 977
void vtkSMTKModelRepresentation::SetLineWidth(double val)
{
978 979 980 981 982 983
  this->Property->SetLineWidth(val);
}

void vtkSMTKModelRepresentation::SetLineColor(double r, double g, double b)
{
  this->Property->SetEdgeColor(r, g, b);
984 985
}

986 987
void vtkSMTKModelRepresentation::SetOpacity(double val)
{
988
  this->Property->SetOpacity(val);
989 990 991 992 993
}

void vtkSMTKModelRepresentation::SetPosition(double x, double y, double z)
{
  this->Entities->SetPosition(x, y, z);
994
  this->SelectedEntities->SetPosition(x, y, z);
995
  this->GlyphEntities->SetPosition(x, y, z);
996
  this->SelectedGlyphEntities->SetPosition(x, y, z);
997 998 999 1000 1001
}

void vtkSMTKModelRepresentation::SetScale(double x, double y, double z)
{
  this->Entities->SetScale(x, y, z);
1002
  this->SelectedEntities->SetScale(x, y, z);
1003
  this->GlyphEntities->SetScale(x, y, z);
1004
  this->SelectedGlyphEntities->SetScale(x, y, z);
1005 1006 1007 1008 1009
}

void vtkSMTKModelRepresentation::SetOrientation(double x, double y, double z)
{
  this->Entities->SetOrientation(x, y, z);
1010
  this->SelectedEntities->SetOrientation(x, y, z);
1011
  this->GlyphEntities->SetOrientation(x, y, z);
1012
  this->SelectedGlyphEntities->SetOrientation(x, y, z);
1013 1014 1015 1016 1017
}

void vtkSMTKModelRepresentation::SetOrigin(double x, double y, double z)
{
  this->Entities->SetOrigin(x, y, z);
1018
  this->SelectedEntities->SetOrigin(x, y, z);
1019
  this->GlyphEntities->SetOrigin(x, y, z);
1020
  this->SelectedGlyphEntities->SetOrigin(x, y, z);
1021 1022 1023 1024 1025 1026 1027
}

void vtkSMTKModelRepresentation::SetUserTransform(const double matrix[16])
{
  vtkNew<vtkTransform> transform;
  transform->SetMatrix(matrix);
  this->Entities->SetUserTransform(transform.GetPointer());
1028
  this->SelectedEntities->SetUserTransform(transform.GetPointer());
1029
  this->GlyphEntities->SetUserTransform(transform.GetPointer());
1030
  this->SelectedGlyphEntities->SetUserTransform(transform.GetPointer());
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
}

void vtkSMTKModelRepresentation::SetPickable(int val)
{
  this->Entities->SetPickable(val);
  this->GlyphEntities->SetPickable(val);
}

void vtkSMTKModelRepresentation::SetTexture(vtkTexture* val)
{
  this->Entities->SetTexture(val);
  this->GlyphEntities->SetTexture(val);
}

void vtkSMTKModelRepresentation::SetSpecularPower(double val)
{
1047
  this->Property->SetSpecularPower(val);
1048 1049
}

1050 1051
void vtkSMTKModelRepresentation::SetSpecular(double val)
{
1052
  this->Property->SetSpecular(val);
1053 1054
}

1055 1056
void vtkSMTKModelRepresentation::SetAmbient(double val)
{
1057
  this->Property->SetAmbient(val);
1058 1059 1060 1061
}

void vtkSMTKModelRepresentation::SetDiffuse(double val)
{
1062
  this->Property->SetDiffuse(val);
1063 1064
}

1065
void vtkSMTKModelRepresentation::UpdateRepresentationSubtype()
1066
{
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  // Adjust material properties.
  double diffuse = this->Diffuse;
  double specular = this->Specular;
  double ambient = this->Ambient;

  if (this->Representation != SURFACE && this->Representation != SURFACE_WITH_EDGES)
  {
    diffuse = 0.0;
    ambient = 1.0;
  }

  this->Property->SetAmbient(ambient);
  this->Property->SetSpecular(specular);
  this->Property->SetDiffuse(diffuse);

  switch (this->Representation)
  {
    case SURFACE_WITH_EDGES:
      this->Property->SetEdgeVisibility(1);
      this->Property->SetRepresentation(VTK_SURFACE);
      break;

    default:
      this->Property->SetEdgeVisibility(0);
      this->Property->SetRepresentation(this->Representation);
  }
}

void vtkSMTKModelRepresentation::UpdateColoringParameters(vtkDataObject* data)
{
  auto multiBlock = vtkMultiBlockDataSet::SafeDownCast(data);
  switch (this->ColorBy)
  {
    case VOLUME:
      this->ColorByVolume(multiBlock);
      break;
    case ENTITY:
      this->ColorByEntity(multiBlock);
      break;
1106 1107
    case FIELD:
      this->ColorByField();
1108 1109
      break;
    default:
1110
      this->ColorByEntity(multiBlock);
1111 1112 1113 1114 1115 1116 1117 1118 1119
      break;
  }

  if (this->UseInternalAttributes)
  {
    this->ApplyInternalBlockAttributes();
  }
}

1120
void vtkSMTKModelRepresentation::ColorByField()
1121 1122 1123
{
  this->EntityMapper->GetCompositeDataDisplayAttributes()->RemoveBlockColors();

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
  bool using_scalar_coloring = false;
  vtkInformation* info = this->GetInputArrayInformation(0);
  if (info && info->Has(vtkDataObject::FIELD_ASSOCIATION()) &&
    info->Has(vtkDataObject::FIELD_NAME()))
  {
    const char* colorArrayName = info->Get(vtkDataObject::FIELD_NAME());
    int fieldAssociation = info->Get(vtkDataObject::FIELD_ASSOCIATION());
    if (colorArrayName && colorArrayName[0])
    {
      this->EntityMapper->SetScalarVisibility(1);
      this->EntityMapper->SelectColorArray(colorArrayName);
      this->EntityMapper->SetUseLookupTableScalarRange(1);
      this->GlyphMapper->SetScalarVisibility(1);
      this->GlyphMapper->SelectColorArray(colorArrayName);
      this->GlyphMapper->SetUseLookupTableScalarRange(1);
      switch (fieldAssociation)
      {
        case vtkDataObject::FIELD_ASSOCIATION_CELLS:
          this->EntityMapper->SetScalarMode(VTK_SCALAR_MODE_USE_CELL_FIELD_DATA);
          this->GlyphMapper->SetScalarMode(VTK_SCALAR_MODE_USE_CELL_FIELD_DATA);
          break;

        case vtkDataObject::FIELD_ASSOCIATION_NONE:
          this->EntityMapper->SetScalarMode(VTK_SCALAR_MODE_USE_FIELD_DATA);
          this->GlyphMapper->SetScalarMode(VTK_SCALAR_MODE_USE_FIELD_DATA);
          // Color entire block by zeroth tuple in the field data
          this->EntityMapper->SetFieldDataTupleId(0);
          this->GlyphMapper->SetFieldDataTupleId(0);
          break;

        case vtkDataObject::FIELD_ASSOCIATION_POINTS:
        default:
          this->EntityMapper->SetScalarMode(VTK_SCALAR_MODE_USE_POINT_FIELD_DATA);
          this->GlyphMapper->SetScalarMode(VTK_SCALAR_MODE_USE_POINT_FIELD_DATA);
          break;
      }
      using_scalar_coloring = true;
    }
  }

  if (!using_scalar_coloring)
  {
    this->EntityMapper->SetScalarVisibility(0);
    this->EntityMapper->SelectColorArray(nullptr);
    this->GlyphMapper->SetScalarVisibility(0);
    this->GlyphMapper->SelectColorArray(nullptr);
  }
}

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
void vtkSMTKModelRepresentation::ColorByVolume(vtkCompositeDataSet* data)
{
  if (!this->UpdateColorBy)
    return;

  // Traverse the blocks and set the volume's color
  this->EntityMapper->GetCompositeDataDisplayAttributes()->RemoveBlockColors();
  vtkCompositeDataIterator* it = data->NewIterator();
  it->GoToFirstItem();
  while (!it->IsDoneWithTraversal())
  {
    auto dataObj = it->GetCurrentDataObject();
    auto arr = vtkStringArray::SafeDownCast(
      dataObj->GetFieldData()->GetAbstractArray(vtkModelMultiBlockSource::GetVolumeTagName()));
    if (arr)
    {
      if (!this->Resource)
      {
        vtkErrorMacro(<< "Invalid Resource!");
        return;
      }

      // FIXME Do something with additional volumes this block might be bounding
      // (currently only using the first one)
      ColorBlockAsEntity(this->EntityMapper, dataObj, arr->GetValue(0), this->Resource);
    }
    else
    {
      // Set a default color
      std::array<double, 3> white = { { 1., 1., 1. } };
      this->EntityMapper->GetCompositeDataDisplayAttributes()->SetBlockColor(dataObj, white.data());
    }
    it->GoToNextItem();
  }
  it->Delete();
  this->UpdateColorBy = false;
}

void vtkSMTKModelRepresentation::ColorByEntity(vtkMultiBlockDataSet* data)
{
  if (!this->UpdateColorBy)
    return;

  // Traverse the blocks and set the entity's color
  this->EntityMapper->GetCompositeDataDisplayAttributes()->RemoveBlockColors();
  vtkCompositeDataIterator* it = data->NewIterator();
  it->GoToFirstItem();
  while (!it->IsDoneWithTraversal())
  {
    auto dataObj = it->GetCurrentDataObject();
    if (data->HasMetaData(it))
    {
      auto uuid = data->GetMetaData(it)->Get(vtkModelMultiBlockSource::ENTITYID());
      if (uuid)
      {
David Thompson's avatar
David Thompson committed
1228 1229
        // FIXME? Check whether UUID corresponds to an instance or not.
        //        Instances should use the GlyphMapper rather than the EntityMapper.
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        ColorBlockAsEntity(this->EntityMapper, dataObj, uuid, this->Resource);
      }
    }
    it->GoToNextItem();
  }
  it->Delete();
  this->UpdateColorBy = false;
}

void vtkSMTKModelRepresentation::ApplyInternalBlockAttributes()
{
  // Update glyph attributes
  auto data = this->GetInternalOutputPort(0)->GetProducer()->GetOutputDataObject(0);
  if (this->BlockAttributeTime < data->GetMTime() || this->BlockAttrChanged)
  {
    this->ApplyEntityAttributes(this->EntityMapper.GetPointer());
    this->BlockAttributeTime.Modified();
    this->BlockAttrChanged = false;
  }

  data = this->GetInternalOutputPort(2)->GetProducer()->GetOutputDataObject(0);
  if (this->InstanceAttributeTime < data->GetMTime() || this->InstanceAttrChanged)
  {
    this->ApplyGlyphBlockAttributes(this->GlyphMapper.GetPointer());
    this->InstanceAttributeTime.Modified();
    this->InstanceAttrChanged = false;
  }
}

void vtkSMTKModelRepresentation::ApplyEntityAttributes(vtkMapper* mapper)
1260 1261 1262 1263 1264 1265 1266 1267
{
  auto cpm = vtkCompositePolyDataMapper2::SafeDownCast(mapper);
  if (!cpm)
  {
    vtkErrorMacro(<< "Invalid mapper!");
    return;
  }

1268 1269 1270 1271
  // TODO: Should we re-apply BlockVisibilities or ComponentState?
  //       If restoring visibility from a file, ParaView will probably
  //       provide via BlockVisibilities. Otherwise we should use
  //       ComponentState.
1272

1273 1274
  // Do not call RemoveBlockColors, since some block attributes could
  // have been set through ColorBy mode
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
  for (auto const& item : this->BlockColors)
  {
    auto& arr = item.second;
    double color[3] = { arr[0], arr[1], arr[2] };
    cpm->SetBlockColor(item.first, color);
  }

  cpm->RemoveBlockOpacities();
  for (auto const& item : this->BlockOpacities)
  {
    cpm->SetBlockOpacity(item.first, item.second);
  }
}

1289
void vtkSMTKModelRepresentation::ApplyGlyphBlockAttributes(vtkGlyph3DMapper* mapper)
1290 1291
{
  auto instanceData = mapper->GetInputDataObject(0, 0);
1292 1293 1294 1295
  auto blockAttr = mapper->GetBlockAttributes();

  blockAttr->RemoveBlockVisibilities();
  for (auto const& item : this->InstanceVisibilities)
1296
  {
1297 1298
    unsigned int currentIdx = 0;
    auto dob = blockAttr->DataObjectFromIndex(item.first, instanceData, currentIdx);
1299

1300 1301 1302
    if (dob)
    {
      blockAttr->SetBlockVisibility(dob, item.second);
1303
    }
1304
  }
1305

1306 1307 1308 1309 1310
  blockAttr->RemoveBlockColors();
  for (auto const& item : this->InstanceColors)
  {
    unsigned int currentIdx = 0;
    auto dob = blockAttr->DataObjectFromIndex(item.first, instanceData, currentIdx);
1311

1312 1313 1314 1315 1316
    if (dob)
    {
      auto& arr = item.second;
      double color[3] = { arr[0], arr[1], arr[2] };
      blockAttr->SetBlockColor(dob, color);
1317
    }
1318 1319 1320 1321 1322
  }
  // Opacity currently not supported by vtkGlyph3DMapper

  mapper->Modified();
}
1323

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
void vtkSMTKModelRepresentation::SetBlockVisibility(unsigned int index, bool visible)
{
  this->BlockVisibilities[index] = visible;
  this->BlockAttrChanged = true;
}

bool vtkSMTKModelRepresentation::GetBlockVisibility(unsigned int index) const
{
  auto it = this->BlockVisibilities.find(index);
  if (it == this->BlockVisibilities.cend())
  {
    return true;
  }
  return it->second;
}

void vtkSMTKModelRepresentation::RemoveBlockVisibility(unsigned int index, bool)
{
  auto it = this->BlockVisibilities.find(index);
  if (it == this->BlockVisibilities.cend())
  {
    return;
  }
  this->BlockVisibilities.erase(it);
  this->BlockAttrChanged = true;
}

void vtkSMTKModelRepresentation::RemoveBlockVisibilities()
{
  this->BlockVisibilities.clear();
  this->BlockAttrChanged = true;
}

void vtkSMTKModelRepresentation::SetBlockColor(unsigned int index, double r, double g, double b)
{
  std::array<double, 3> color = { { r, g, b } };
  this->BlockColors[index] = color;
  this->BlockAttrChanged = true;
}

void vtkSMTKModelRepresentation::SetBlockColor(unsigned int index, double* color)
{
  if (color)
  {
    this->SetBlockColor(index, color[0], color[1], color[2]);
  }
}

double* vtkSMTKModelRepresentation::GetBlockColor(unsigned int index)
{
  auto it = this->BlockColors.find(index);
  if (it == this->BlockColors.cend())
  {
    return nullptr;
  }
  return it->second.data();
}

void vtkSMTKModelRepresentation::RemoveBlockColor(unsigned int index)
{
  auto it = this->BlockColors.find(index);
  if (it == this->BlockColors.cend())
  {
    return;
  }
  this->BlockColors.erase(it);
  this->BlockAttrChanged = true;
}

void vtkSMTKModelRepresentation::RemoveBlockColors()
{
  this->BlockColors.clear();
  this->BlockAttrChanged = true;
}

void vtkSMTKModelRepresentation::SetBlockOpacity(unsigned int index, double opacity)
{
  this->BlockOpacities[index] = opacity;
  this->BlockAttrChanged = true;
}

void vtkSMTKModelRepresentation::SetBlockOpacity(unsigned int index, double* opacity)
{
  if (opacity)
  {
    this->SetBlockOpacity(index, *opacity);
  }
}

double vtkSMTKModelRepresentation::GetBlockOpacity(unsigned int index)
{
  auto it = this->BlockOpacities.find(index);
  if (it == this->BlockOpacities.cend())
  {
    return 0.0;
  }
  return it->second;
}

void vtkSMTKModelRepresentation::RemoveBlockOpacity(unsigned int index)
{
  auto it = this->BlockOpacities.find(index);
  if (it == this->BlockOpacities.cend())
  {
    return;
  }
  this->BlockOpacities.erase(it);
  this->BlockAttrChanged = true;
}

void vtkSMTKModelRepresentation::RemoveBlockOpacities()
{
  this->BlockOpacities.clear();
  this->BlockAttrChanged = true;
}

1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
void vtkSMTKModelRepresentation::SetSelectedState(
  vtkDataObject* data, int selectionValue, bool isGlyph)
{
  auto nrm = isGlyph ? this->GlyphMapper->GetBlockAttributes()
                     : this->EntityMapper->GetCompositeDataDisplayAttributes();
  auto sel = isGlyph ? this->SelectedGlyphMapper->GetBlockAttributes()
                     : this->SelectedEntityMapper->GetCompositeDataDisplayAttributes();
  if (selectionValue > 0)
  {
    sel->SetBlockColor(data, selectionValue > 1 ? this->HoverColor : this->SelectionColor);
  }
  sel->SetBlockVisibility(data, selectionValue > 0);
  nrm->SetBlockVisibility(data, selectionValue == 0);
}

1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
void vtkSMTKModelRepresentation::SetInstanceVisibility(unsigned int index, bool visible)
{
  this->InstanceVisibilities[index] = visible;
  this->InstanceAttrChanged = true;
}

bool vtkSMTKModelRepresentation::GetInstanceVisibility(unsigned int index) const
{
  auto it = this->InstanceVisibilities.find(index);
  if (it == this->InstanceVisibilities.cend())
  {
    return true;
1467
  }
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
  return it->second;
}

void vtkSMTKModelRepresentation::RemoveInstanceVisibility(unsigned int index, bool)
{
  auto it = this->InstanceVisibilities.find(index);
  if (it == this->InstanceVisibilities.cend())
  {
    return;
  }
  this->InstanceVisibilities.erase(it);
  this->InstanceAttrChanged = true;
}

void vtkSMTKModelRepresentation::RemoveInstanceVisibilities()
{
  this->InstanceVisibilities.clear();
  this->InstanceAttrChanged = true;
}

void vtkSMTKModelRepresentation::SetInstanceColor(unsigned int index, double r, double g, double b)
{
  std::array<double, 3> color = { { r, g, b } };
  this->InstanceColors[index] = color;
  this->InstanceAttrChanged = true;
}

void vtkSMTKModelRepresentation::SetInstanceColor(unsigned int index, double* color)
{
  if (color)
  {
    this->SetInstanceColor(index, color[0], color[1], color[2]);
  }
}

double* vtkSMTKModelRepresentation::GetInstanceColor(unsigned int index)
{
  auto it = this->InstanceColors.find(index);
  if (it == this->InstanceColors.cend())
  {
    return nullptr;
  }
  return it->second.data();
}

void vtkSMTKModelRepresentation::RemoveInstanceColor(unsigned int index)
{
  auto it = this->InstanceColors.find(index);
  if (it == this->InstanceColors.cend())
  {
    return;
  }
  this->InstanceColors.erase(it);
  this->InstanceAttrChanged = true;
}

void vtkSMTKModelRepresentation::RemoveInstanceColors()
{
  this->InstanceColors.clear();
  this->InstanceAttrChanged = true;
1528
}
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540

void vtkSMTKModelRepresentation::SetUseInternalAttributes(bool enable)
{
  this->UseInternalAttributes = enable;

  // Force update of internal attributes
  this->BlockAttrChanged = true;
  this->InstanceAttrChanged = true;

  // Force update of ColorBy
  this->UpdateColorBy = true;
}