Updates will be applied April 15th at 12pm EDT (UTC-0400). GitLab could be a little slow between 12 - 12:45pm EDT.

vtkPVDataDeliveryManager.cxx 28.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*=========================================================================

  Program:   ParaView
  Module:    $RCSfile$

  Copyright (c) Kitware, Inc.
  All rights reserved.
  See Copyright.txt or http://www.paraview.org/HTML/Copyright.html 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.

=========================================================================*/
15
#include "vtkPVDataDeliveryManager.h"
16 17

#include "vtkAlgorithmOutput.h"
18
#include "vtkAMRBox.h"
19
#include "vtkAMRVolumeRepresentation.h"
20
#include "vtkBSPCutsGenerator.h"
21
#include "vtkCamera.h"
22 23
#include "vtkDataObject.h"
#include "vtkMath.h"
24
#include "vtkMPIMoveData.h"
25
#include "vtkMultiBlockDataSet.h"
26 27 28 29
#include "vtkMultiProcessController.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkOrderedCompositeDistributor.h"
30
#include "vtkOverlappingAMR.h"
31
#include "vtkPKdTree.h"
32
#include "vtkPointData.h"
33 34
#include "vtkPVDataRepresentation.h"
#include "vtkPVDataRepresentationPipeline.h"
35
#include "vtkPVRenderView.h"
36
#include "vtkPVTrivialProducer.h"
37
#include "vtkRenderer.h"
38
#include "vtkSmartPointer.h"
39
#include "vtkStreamingDemandDrivenPipeline.h"
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
40
#include "vtkTimerLog.h"
41 42 43
#include "vtkUniformGridAMRDataIterator.h"
#include "vtkUniformGrid.h"
#include "vtkUnsignedIntArray.h"
44
#include "vtkWeakPointer.h"
45 46

#include <assert.h>
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
#include <map>
#include <queue>
#include <utility>

//*****************************************************************************
class vtkPVDataDeliveryManager::vtkInternals
{
public:

  class vtkPriorityQueueItem
    {
  public:
    unsigned int RepresentationId;
    unsigned int BlockId;
    unsigned int Level;
    unsigned int Index;
    double Priority;

    vtkPriorityQueueItem() :
      RepresentationId(0), BlockId(0),
      Level(0), Index(0), Priority(0)
    {
    }

    bool operator < (const vtkPriorityQueueItem& other) const
      {
      return this->Priority < other.Priority;
      }
    };

  typedef std::priority_queue<vtkPriorityQueueItem> PriorityQueueType;
  PriorityQueueType PriorityQueue;

  class vtkItem
    {
    vtkSmartPointer<vtkPVTrivialProducer> Producer;
83 84

    // Data object produced by the representation.
85
    vtkWeakPointer<vtkDataObject> DataObject;
86 87 88 89 90 91 92 93

    // Data object available after delivery to the "rendering" node.
    vtkSmartPointer<vtkDataObject> DeliveredDataObject;

    // Data object after re-distributing when using ordered compositing, for
    // example.
    vtkSmartPointer<vtkDataObject> RedistributedDataObject;

94 95 96
    unsigned long TimeStamp;
    unsigned long ActualMemorySize;
  public:
97 98 99
    vtkWeakPointer<vtkAlgorithmOutput> ImageDataProducer;
      // <-- HACK for image data volume rendering.

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    vtkWeakPointer<vtkPVDataRepresentation> Representation;
    bool AlwaysClone;
    bool Redistributable;
    bool Streamable;

    vtkItem() :
      Producer(vtkSmartPointer<vtkPVTrivialProducer>::New()),
      TimeStamp(0),
      ActualMemorySize(0),
      AlwaysClone(false),
      Redistributable(false),
      Streamable(false)
    { }

    void SetDataObject(vtkDataObject* data)
115
      {
116 117
      this->DataObject = data;
      this->ActualMemorySize = data? data->GetActualMemorySize() : 0;
118 119 120

      vtkTimeStamp ts; ts.Modified();
      this->TimeStamp = ts;
121 122
      }

123 124
    void SetDeliveredDataObject(vtkDataObject* data)
      {
125 126 127 128 129 130
      this->DeliveredDataObject = data;
      }

    void SetRedistributedDataObject(vtkDataObject* data)
      {
      this->RedistributedDataObject = data;
131 132 133 134
      }

    vtkDataObject* GetDeliveredDataObject()
      {
135 136 137 138 139 140 141 142 143
      return this->DeliveredDataObject.GetPointer();
      }

    vtkDataObject* GetRedistributedDataObject()
      {
      return this->RedistributedDataObject.GetPointer();
      }

    vtkPVTrivialProducer* GetProducer(bool use_redistributed_data)
144
      {
145 146 147 148 149 150 151 152 153
      if (use_redistributed_data && this->Redistributable)
        {
        this->Producer->SetOutput(this->RedistributedDataObject);
        }
      else
        {
        this->Producer->SetOutput(this->DeliveredDataObject);
        }
      return this->Producer.GetPointer();
154 155
      }

156 157 158 159
    vtkDataObject* GetDataObject() const
      { return this->DataObject.GetPointer(); }
    unsigned long GetTimeStamp() const
      { return this->TimeStamp; }
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
    unsigned long GetVisibleDataSize()
      {
      if (this->Representation && this->Representation->GetVisibility())
        {
        return this->ActualMemorySize;
        }
      return 0;
      }
    };

  typedef std::map<unsigned int, std::pair<vtkItem, vtkItem> > ItemsMapType;

  vtkItem* GetItem(unsigned int index, bool use_second)
    {
    if (this->ItemsMap.find(index) != this->ItemsMap.end())
      {
      return use_second? &(this->ItemsMap[index].second) :
        &(this->ItemsMap[index].first);
      }
    return NULL;
    }

  vtkItem* GetItem(vtkPVDataRepresentation* repr, bool use_second)
    {
    RepresentationToIdMapType::iterator iter =
      this->RepresentationToIdMap.find(repr);
    if (iter != this->RepresentationToIdMap.end())
      {
      unsigned int index = iter->second;
      return use_second? &(this->ItemsMap[index].second) :
        &(this->ItemsMap[index].first);
      }

    return NULL;
    }

  unsigned long GetVisibleDataSize(bool use_second_if_available)
    {
    unsigned long size = 0;
    ItemsMapType::iterator iter;
    for (iter = this->ItemsMap.begin(); iter != this->ItemsMap.end(); ++iter)
      {
      if (use_second_if_available && iter->second.second.GetDataObject())
        {
        size += iter->second.second.GetVisibleDataSize();
        }
      else
        {
        size += iter->second.first.GetVisibleDataSize();
        }
      }
    return size;
    }
214

215 216 217 218 219 220 221
  typedef std::map<vtkPVDataRepresentation*, unsigned int>
    RepresentationToIdMapType;

  RepresentationToIdMapType RepresentationToIdMap;
  ItemsMapType ItemsMap;
};
//*****************************************************************************
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
namespace
{
  // this code is stolen from vtkFrustumCoverageCuller.
  double vtkComputeScreenCoverage(const double planes[24],
    const double bounds[6], double &distance)
    {
    distance = 0.0;

    // a duff dataset like a polydata with no cells will have bad bounds
    if (!vtkMath::AreBoundsInitialized(const_cast<double*>(bounds)))
      {
      return 0.0;
      }
    double screen_bounds[4];

    double center[3];
    center[0] = (bounds[0] + bounds[1]) / 2.0;
    center[1] = (bounds[2] + bounds[3]) / 2.0;
    center[2] = (bounds[4] + bounds[5]) / 2.0;
    double radius = 0.5 * sqrt(
      ( bounds[1] - bounds[0] ) * ( bounds[1] - bounds[0] ) +
      ( bounds[3] - bounds[2] ) * ( bounds[3] - bounds[2] ) +
      ( bounds[5] - bounds[4] ) * ( bounds[5] - bounds[4] ) );
    for (int i = 0; i < 6; i++ )
      {
      // Compute how far the center of the sphere is from this plane
      double d = planes[i*4 + 0] * center[0] +
        planes[i*4 + 1] * center[1] +
        planes[i*4 + 2] * center[2] +
        planes[i*4 + 3];
      // If d < -radius the prop is not within the view frustum
      if ( d < -radius )
        {
        return 0.0;
        }

      // The first four planes are the ones bounding the edges of the
      // view plane (the last two are the near and far planes) The
      // distance from the edge of the sphere to these planes is stored
      // to compute coverage.
      if ( i < 4 )
        {
        screen_bounds[i] = d - radius;
        }
      // The fifth plane is the near plane - use the distance to
      // the center (d) as the value to sort by
      if ( i == 4 )
        {
        distance = d;
        }
      }

    // If the prop wasn't culled during the plane tests...
    // Compute the width and height of this slice through the
    // view frustum that contains the center of the sphere
    double full_w = screen_bounds[0] + screen_bounds[1] + 2.0 * radius;
    double full_h = screen_bounds[2] + screen_bounds[3] + 2.0 * radius;
    // Subtract from the full width to get the width of the square
    // enclosing the circle slice from the sphere in the plane
    // through the center of the sphere. If the screen bounds for
    // the left and right planes (0,1) are greater than zero, then
    // the edge of the sphere was a positive distance away from the
    // plane, so there is a gap between the edge of the plane and
    // the edge of the box.
    double part_w = full_w;
    if ( screen_bounds[0] > 0.0 )
      {
      part_w -= screen_bounds[0];
      }
    if ( screen_bounds[1] > 0.0 )
      {
      part_w -= screen_bounds[1];
      }
    // Do the same thing for the height with the top and bottom
    // planes (2,3).
    double part_h = full_h;
    if ( screen_bounds[2] > 0.0 )
      {
      part_h -= screen_bounds[2];
      }
    if ( screen_bounds[3] > 0.0 )
      {
      part_h -= screen_bounds[3];
      }

    // Compute the fraction of coverage
    if ((full_w * full_h)!=0.0)
      {
      return (part_w * part_h) / (full_w * full_h);
      }

    return 0;
    }
};

317 318 319
//*****************************************************************************

vtkStandardNewMacro(vtkPVDataDeliveryManager);
320
//----------------------------------------------------------------------------
321
vtkPVDataDeliveryManager::vtkPVDataDeliveryManager()
322 323 324 325 326
  : Internals(new vtkInternals())
{
}

//----------------------------------------------------------------------------
327
vtkPVDataDeliveryManager::~vtkPVDataDeliveryManager()
328 329 330 331 332
{
  delete this->Internals;
  this->Internals = 0;
}

333
//----------------------------------------------------------------------------
334
void vtkPVDataDeliveryManager::SetRenderView(vtkPVRenderView* view)
335
{
336
  this->RenderView = view;
337 338
}

339
//----------------------------------------------------------------------------
340
vtkPVRenderView* vtkPVDataDeliveryManager::GetRenderView()
341
{
342
  return this->RenderView;
343 344
}

Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
345
//----------------------------------------------------------------------------
346
unsigned long vtkPVDataDeliveryManager::GetVisibleDataSize(bool low_res)
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
347 348 349
{
  return this->Internals->GetVisibleDataSize(low_res);
}
350 351

//----------------------------------------------------------------------------
352
void vtkPVDataDeliveryManager::RegisterRepresentation(
353
  unsigned int id, vtkPVDataRepresentation* repr)
354 355 356 357 358
{
  this->Internals->RepresentationToIdMap[repr] = id;

  vtkInternals::vtkItem item;
  item.Representation = repr;
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
359 360 361 362 363
  this->Internals->ItemsMap[id].first = item;

  vtkInternals::vtkItem item2;
  item2.Representation = repr;
  this->Internals->ItemsMap[id].second= item2;
364 365 366
}

//----------------------------------------------------------------------------
367
void vtkPVDataDeliveryManager::UnRegisterRepresentation(
368 369 370 371 372 373 374 375 376 377 378 379 380
  vtkPVDataRepresentation* repr)
{
  vtkInternals::RepresentationToIdMapType::iterator iter =
    this->Internals->RepresentationToIdMap.find(repr);
  if (iter == this->Internals->RepresentationToIdMap.end())
    {
    vtkErrorMacro("Invalid argument.");
    return;
    }
  this->Internals->ItemsMap.erase(iter->second);
  this->Internals->RepresentationToIdMap.erase(iter);
}

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
//----------------------------------------------------------------------------
unsigned int vtkPVDataDeliveryManager::GetRepresentationId(
  vtkPVDataRepresentation* repr)
{
  vtkInternals::RepresentationToIdMapType::iterator iter =
    this->Internals->RepresentationToIdMap.find(repr);
  if (iter == this->Internals->RepresentationToIdMap.end())
    {
    vtkErrorMacro("Invalid argument.");
    return 0;
    }
  return iter->second;
}

//----------------------------------------------------------------------------
vtkPVDataRepresentation* vtkPVDataDeliveryManager::GetRepresentation(
  unsigned int index)
{
  vtkInternals::vtkItem* item = this->Internals->GetItem(index, false);
  return item? item->Representation : NULL;
}

403
//----------------------------------------------------------------------------
404
void vtkPVDataDeliveryManager::SetDeliverToAllProcesses(
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
405
  vtkPVDataRepresentation* repr, bool mode, bool low_res)
406
{
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
407
  vtkInternals::vtkItem* item = this->Internals->GetItem(repr, low_res);
408 409
  if (item)
    {
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
410
    item->AlwaysClone = mode;
411 412 413 414 415 416 417
    }
  else
    {
    vtkErrorMacro("Invalid argument.");
    }
}

418
//----------------------------------------------------------------------------
419
void vtkPVDataDeliveryManager::MarkAsRedistributable(
420 421 422 423 424 425 426 427 428 429 430 431 432 433
  vtkPVDataRepresentation* repr)
{
  vtkInternals::vtkItem* item = this->Internals->GetItem(repr, false);
  vtkInternals::vtkItem* low_item = this->Internals->GetItem(repr, true);
  if (item)
    {
    item->Redistributable = true;
    low_item->Redistributable = true;
    }
  else
    {
    vtkErrorMacro("Invalid argument.");
    }
}
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
434

435
//----------------------------------------------------------------------------
436
void vtkPVDataDeliveryManager::SetStreamable(
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  vtkPVDataRepresentation* repr, bool val)
{
  if (!repr->IsA("vtkAMRVolumeRepresentation") && val == true)
    {
    vtkWarningMacro(
      "Only vtkAMRVolumeRepresentation streaming is currently supported.");
    return;
    }

  vtkInternals::vtkItem* item = this->Internals->GetItem(repr, false);
  vtkInternals::vtkItem* low_item = this->Internals->GetItem(repr, true);
  if (item)
    {
    item->Streamable = val;
    low_item->Streamable = val;
    }
  else
    {
    vtkErrorMacro("Invalid argument.");
    }
}

459
//----------------------------------------------------------------------------
460
void vtkPVDataDeliveryManager::SetPiece(
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
461
  vtkPVDataRepresentation* repr, vtkDataObject* data, bool low_res)
462
{
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
463
  vtkInternals::vtkItem* item = this->Internals->GetItem(repr, low_res);
464 465
  if (item)
    {
466 467
    vtkPVDataRepresentationPipeline* executive =
      vtkPVDataRepresentationPipeline::SafeDownCast(repr->GetExecutive());
468 469

    // SetPiece() is called in every REQUEST_UPDATE() or REQUEST_UPDATE_LOD()
470
    // pass irrespective of whether the data has actually changed.
471 472 473 474 475 476 477 478 479 480
    // (I think that's a mistake, but the fact that representations can be
    // updated without view makes it tricky since we cannot set the data to
    // deliver in vtkPVDataRepresentation::RequestData() easily). Hence we need
    // to ensure that the data we are getting is newer than what we have.
    unsigned long data_time = executive? executive->GetDataTime() : 0;
    if (data && (data->GetMTime() > data_time))
      {
      data_time = data->GetMTime();
      }
    if (data_time > item->GetTimeStamp())
481 482 483
      {
      item->SetDataObject(data);
      }
484 485
    }
  else
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
486 487 488 489 490 491
    {
    vtkErrorMacro("Invalid argument.");
    }
}

//----------------------------------------------------------------------------
492
vtkAlgorithmOutput* vtkPVDataDeliveryManager::GetProducer(
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
493 494 495 496
  vtkPVDataRepresentation* repr, bool low_res)
{
  vtkInternals::vtkItem* item = this->Internals->GetItem(repr, low_res);
  if (!item)
497 498
    {
    vtkErrorMacro("Invalid arguments.");
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
499 500 501
    return NULL;
    }

502 503
  return item->GetProducer(
    this->RenderView->GetUseOrderedCompositing())->GetOutputPort(0);
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
504 505 506
}

//----------------------------------------------------------------------------
507
void vtkPVDataDeliveryManager::SetPiece(unsigned int id, vtkDataObject* data, bool
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
508 509 510 511 512 513 514 515 516 517
  low_res)
{
  vtkInternals::vtkItem* item = this->Internals->GetItem(id, low_res);
  if (item)
    {
    item->SetDataObject(data);
    }
  else
    {
    vtkErrorMacro("Invalid argument.");
518 519 520
    }
}

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
//----------------------------------------------------------------------------
void vtkPVDataDeliveryManager::SetImageDataProducer(
  vtkPVDataRepresentation* repr, vtkAlgorithmOutput *producer)
{
  vtkInternals::vtkItem* item = this->Internals->GetItem(repr, false);
  if (item)
    {
    item->ImageDataProducer = producer;
    }
  else
    {
    vtkErrorMacro("Invalid argument.");
    }
}

536
//----------------------------------------------------------------------------
537
vtkAlgorithmOutput* vtkPVDataDeliveryManager::GetProducer(
538
  unsigned int id, bool low_res)
539
{
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
540
  vtkInternals::vtkItem* item = this->Internals->GetItem(id, low_res);
541 542 543 544 545 546
  if (!item)
    {
    vtkErrorMacro("Invalid arguments.");
    return NULL;
    }

547 548
  return item->GetProducer(
    this->RenderView->GetUseOrderedCompositing())->GetOutputPort(0);
549 550
}

551
//----------------------------------------------------------------------------
552
bool vtkPVDataDeliveryManager::NeedsDelivery(
553
  unsigned long timestamp,
554
  std::vector<unsigned int> &keys_to_deliver, bool use_low)
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
{
  vtkInternals::ItemsMapType::iterator iter;
  for (iter = this->Internals->ItemsMap.begin();
    iter != this->Internals->ItemsMap.end(); ++iter)
    {
    vtkInternals::vtkItem& item = use_low? iter->second.second : iter->second.first;
    if (item.Representation &&
      item.Representation->GetVisibility() &&
      item.GetTimeStamp() > timestamp)
      {
      keys_to_deliver.push_back(iter->first);
      }
    }
  return keys_to_deliver.size() > 0;
}

//----------------------------------------------------------------------------
572
void vtkPVDataDeliveryManager::Deliver(int use_lod, unsigned int size, unsigned int *values)
573 574

{
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
  // This method gets called on all processes with the list of representations
  // to "deliver". We check with the view what mode we're operating in and
  // decide where the data needs to be delivered.
  //
  // Representations can provide overrides, e.g. though the view says data is
  // merely "pass-through", some representation says we need to clone the data
  // everywhere. That makes it critical that this method is called on all
  // processes at the same time to avoid deadlocks and other complications.
  //
  // This method will be implemented in "view-specific" subclasses since how the
  // data is delivered is very view specific.

  vtkTimerLog::MarkStartEvent(use_lod?
    "LowRes Data Migration" : "FullRes Data Migration");

  bool using_remote_rendering =
591 592 593
    use_lod? this->RenderView->GetUseDistributedRenderingForInteractiveRender() :
    this->RenderView->GetUseDistributedRenderingForStillRender();
  int mode = this->RenderView->GetDataDistributionMode(using_remote_rendering);
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
594

595 596 597 598 599 600
  for (unsigned int cc=0; cc < size; cc++)
    {
    vtkInternals::vtkItem* item = this->Internals->GetItem(values[cc], use_lod !=0);

    vtkDataObject* data = item->GetDataObject();

601
    if (data->IsA("vtkUniformGridAMR"))
602
      {
603 604
      // we are dealing with AMR datasets.
      // We assume for now we're not running in render-server mode. We can
605
      // ensure that at some point in future.
606 607 608
      // So we are either in pass-through or collect mode.

      // FIXME: check that the mode flags are "suitable" for AMR.
609
      }
610

611 612 613 614 615
    vtkNew<vtkMPIMoveData> dataMover;
    dataMover->InitializeForCommunicationForParaView();
    dataMover->SetOutputDataType(data->GetDataObjectType());
    dataMover->SetMoveMode(mode);
    if (item->AlwaysClone)
616
      {
617
      dataMover->SetMoveModeToClone();
618
      }
619 620
    dataMover->SetInputData(data);

621 622 623 624 625 626
    if (dataMover->GetOutputGeneratedOnProcess())
      {
      // release old memory (not necessarily, but try).
      item->SetDeliveredDataObject(NULL);
      }
    dataMover->Update();
627
    if (item->GetDeliveredDataObject() == NULL)
628 629 630
      {
      item->SetDeliveredDataObject(dataMover->GetOutputDataObject(0));
      }
631
    }
632

633 634 635
  vtkTimerLog::MarkEndEvent(use_lod?
    "LowRes Data Migration" : "FullRes Data Migration");
}
636

637 638 639 640 641
//----------------------------------------------------------------------------
void vtkPVDataDeliveryManager::RedistributeDataForOrderedCompositing(
  bool use_lod)
{
  if (this->RenderView->GetUpdateTimeStamp() > this->RedistributionTimeStamp)
642
    {
643 644 645 646
    vtkTimerLog::MarkStartEvent("Regenerate Kd-Tree");
    // need to re-generate the kd-tree.
    this->RedistributionTimeStamp.Modified();

647 648 649 650 651 652 653
    vtkNew<vtkBSPCutsGenerator> cutsGenerator;
    vtkInternals::ItemsMapType::iterator iter;
    for (iter = this->Internals->ItemsMap.begin();
      iter != this->Internals->ItemsMap.end(); ++iter)
      {
      vtkInternals::vtkItem& item =  iter->second.first;
      if (item.Representation &&
654
        item.Representation->GetVisibility())
655
        {
656 657 658 659 660 661 662 663
        if (item.Redistributable)
          {
          cutsGenerator->AddInputData(item.GetDeliveredDataObject());
          }
        else if (item.ImageDataProducer)
          {
          cutsGenerator->AddInputConnection(item.ImageDataProducer);
          }
664 665 666 667 668 669 670 671 672 673 674 675
        }
      }

    vtkMultiProcessController* controller =
      vtkMultiProcessController::GetGlobalController();
    vtkStreamingDemandDrivenPipeline *sddp = vtkStreamingDemandDrivenPipeline::
      SafeDownCast(cutsGenerator->GetExecutive());
    sddp->SetUpdateExtent
      (0,controller->GetLocalProcessId(),controller->GetNumberOfProcesses(),0);
    sddp->Update(0);

    this->KdTree = cutsGenerator->GetPKdTree();
676
    vtkTimerLog::MarkEndEvent("Regenerate Kd-Tree");
677
    }
678 679

  if (this->KdTree == NULL)
680
    {
681
    return;
682 683
    }

684 685 686 687
  vtkTimerLog::MarkStartEvent("Redistributing Data for Ordered Compositing");
  vtkInternals::ItemsMapType::iterator iter;
  for (iter = this->Internals->ItemsMap.begin();
    iter != this->Internals->ItemsMap.end(); ++iter)
688
    {
689 690 691 692 693 694 695 696
    vtkInternals::vtkItem& item = use_lod? iter->second.second : iter->second.first;

    if (!item.Redistributable ||
      item.Representation == NULL ||
      item.Representation->GetVisibility() == false ||

      // delivered object can be null in case we're updating lod and the
      // representation doeesn't have any LOD data.
697
      item.GetDeliveredDataObject() == NULL)
698
      {
699 700
      continue;
      }
701

702 703 704 705 706 707 708 709 710 711 712 713
    if (item.GetRedistributedDataObject() &&

      // input-data didn't change
      (item.GetDeliveredDataObject()->GetMTime() <
       item.GetRedistributedDataObject()->GetMTime()) &&

      // kd-tree didn't change
      (item.GetRedistributedDataObject()->GetMTime() >
       this->KdTree->GetMTime()))
      {
      // skip redistribution.
      continue;
714 715
      }

716 717
    // release old memory (not necessarily, but try).
    item.SetRedistributedDataObject(NULL);
718

719 720 721 722 723 724 725 726 727
    vtkNew<vtkOrderedCompositeDistributor> redistributor;
    redistributor->SetController(vtkMultiProcessController::GetGlobalController());
    redistributor->SetInputData(item.GetDeliveredDataObject());
    redistributor->SetPKdTree(this->KdTree);
    redistributor->SetPassThrough(0);
    redistributor->Update();
    item.SetRedistributedDataObject(redistributor->GetOutputDataObject(0));
    }
  vtkTimerLog::MarkEndEvent("Redistributing Data for Ordered Compositing");
728 729
}

730
//----------------------------------------------------------------------------
731
vtkPKdTree* vtkPVDataDeliveryManager::GetKdTree()
732 733 734
{
  return this->KdTree;
}
735 736

//----------------------------------------------------------------------------
737
bool vtkPVDataDeliveryManager::BuildPriorityQueue(double planes[24])
738
{
739
  cout << "BuildPriorityQueue" << endl;
740 741 742 743 744
  // just find the first visible AMR dataset and build priority queue for that
  // dataset alone. In future, we can fix it to use information provided by
  // representation indicating if streaming is possible (since not every AMR
  // source is streambale).

745

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
  this->Internals->PriorityQueue = vtkInternals::PriorityQueueType();

  vtkOverlappingAMR* oamr = NULL;

  vtkInternals::ItemsMapType::iterator iter;
  for (iter = this->Internals->ItemsMap.begin();
    iter != this->Internals->ItemsMap.end(); ++iter)
    {
    vtkInternals::vtkItem& item = iter->second.first;
    if (item.Representation &&
      item.Representation->GetVisibility() &&
      item.Streamable &&
      item.GetDataObject() &&
      item.GetDataObject()->IsA("vtkOverlappingAMR"))
      {
      oamr = vtkOverlappingAMR::SafeDownCast(item.GetDataObject());
      break;
      }
    }
  if (oamr == NULL)
    {
    return true;
    }

  // note: amr block ids currently don't match up with composite dataset ids :/.
  // now build a priority queue for absent blocks using the current camera.
772 773

  //double planes[24];
774
  //vtkRenderer* ren = this->RenderView->GetRenderer();
775 776 777
  //ren->GetActiveCamera()->GetFrustumPlanes(
  //  ren->GetTiledAspectRatio(), planes);

778 779 780 781 782 783 784
  for (unsigned int level=0; level < oamr->GetNumberOfLevels(); level++)
    {
    for (unsigned int index=0;
      index < oamr->GetNumberOfDataSets(level); index++)
      {
      if (oamr->GetDataSet(level, index) == NULL)
        {
785 786
        vtkAMRBox amrBox = oamr->GetAMRBox(level,index);
        if (amrBox.IsInvalid())
787 788 789 790 791 792
          {
          vtkWarningMacro("Missing AMRBox meta-data for "
            << level << ", " << index);
          continue;
          }

793 794
        vtkInternals::vtkPriorityQueueItem item;
        item.RepresentationId = iter->first;
795
        item.BlockId = oamr->GetCompositeIndex(level, index);
796 797
        item.Level = level;
        item.Index = index;
798 799

        double bounds[6];
800
        oamr->GetBounds(level,index,bounds);
801 802 803 804 805 806 807 808 809 810
        double depth = 1.0;
        double coverage = vtkComputeScreenCoverage(planes, bounds, depth);
        //cout << level <<"," << index << "(" << item.BlockId << ")" << " = " << coverage << ", " << depth << endl;
        if (coverage == 0.0)
          {
          // skip blocks that are not covered in the view.
          continue;
          }

        item.Priority = coverage / (depth > 1? depth : 1.0);
811 812 813 814 815 816 817 818
        this->Internals->PriorityQueue.push(item);
        }
      }
    }
  return true;
}

//----------------------------------------------------------------------------
819
void vtkPVDataDeliveryManager::StreamingDeliver(unsigned int key)
820 821
{
  vtkInternals::vtkItem* item = this->Internals->GetItem(key, false);
822
  if (vtkOverlappingAMR::SafeDownCast(item->GetDataObject()) == NULL)
823 824 825 826 827 828 829
    {
    cout << "ERROR: StreamingDeliver can only deliver AMR datasets for now" << endl;
    abort();
    }

  if (this->Internals->PriorityQueue.empty())
    {
830 831 832
    vtkOverlappingAMR* oamr = vtkOverlappingAMR::SafeDownCast(
      item->GetDeliveredDataObject());

833 834 835
    // client side.
    vtkNew<vtkMPIMoveData> dataMover;
    dataMover->InitializeForCommunicationForParaView();
836
    dataMover->SetOutputDataType(VTK_MULTIBLOCK_DATA_SET);
837 838 839 840 841
    dataMover->SetMoveModeToCollect();
    dataMover->SetInputConnection(NULL);
    dataMover->Update();

    // now put the piece in right place.
842
    vtkMultiBlockDataSet* mb = vtkMultiBlockDataSet::SafeDownCast(
843
      dataMover->GetOutputDataObject(0));
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859

    if (mb->GetNumberOfBlocks() == 1 && mb->GetBlock(0) != NULL)
      {
      vtkNew<vtkUniformGrid> ug;
      ug->ShallowCopy(mb->GetBlock(0));

      vtkUnsignedIntArray* array = vtkUnsignedIntArray::SafeDownCast(
        ug->GetPointData()->GetArray("AMRIndex"));
      unsigned int index, level;
      level = array->GetValue(0);
      index = array->GetValue(1);
      ug->GetPointData()->RemoveArray("AMRIndex");
      oamr->SetDataSet(level, index, ug.GetPointer());
      oamr->Modified();
      }
    else
860
      {
861
      // vtkWarningMacro("Empty data (or incorrect data) received");
862 863 864 865 866 867 868 869 870 871 872 873
      }
    }
  else
    {
    vtkInternals::vtkPriorityQueueItem qitem =
      this->Internals->PriorityQueue.top();
    this->Internals->PriorityQueue.pop();
    assert(qitem.RepresentationId == key);

    vtkAMRVolumeRepresentation* repr = vtkAMRVolumeRepresentation::SafeDownCast(
      item->Representation);
    repr->SetStreamingBlockId(qitem.BlockId);
874
    this->RenderView->StreamingUpdate();
875 876
    repr->ResetStreamingBlockId();

877 878
    vtkOverlappingAMR* oamr = vtkOverlappingAMR::SafeDownCast(
      item->GetDataObject());
879 880 881 882 883 884

    vtkNew<vtkMultiBlockDataSet> mb;

    vtkUniformGrid* piece = oamr->GetDataSet(qitem.Level, qitem.Index);
    if (piece == NULL)
      {
885
      // vtkWarningMacro("Null piece delivered!");
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
      }
    else
      {
      vtkNew<vtkImageData> img;
      img->ShallowCopy(piece);
      mb->SetBlock(0, img.GetPointer());

      vtkNew<vtkUnsignedIntArray> indexArray;
      indexArray->SetName("AMRIndex");
      indexArray->SetNumberOfComponents(2);
      indexArray->SetNumberOfTuples(1);
      indexArray->SetValue(0, qitem.Level);
      indexArray->SetValue(1, qitem.Index);

      // this should be added in field data, however
      // vtkStructuredPointsReader/Writer get confused when field data is
      // present. So adding this as point data for now.
      img->GetPointData()->AddArray(indexArray.GetPointer());
      }

906 907 908 909
    // the one bad thing about this is that we are sending the full amr
    // meta-data again. We can do better here and not send it again.
    vtkNew<vtkMPIMoveData> dataMover;
    dataMover->InitializeForCommunicationForParaView();
910
    dataMover->SetOutputDataType(VTK_MULTIBLOCK_DATA_SET);
911
    dataMover->SetMoveModeToCollect();
912
    dataMover->SetInputData(mb.GetPointer());
913 914 915 916 917
    dataMover->Update();
    }
}

//----------------------------------------------------------------------------
918
unsigned int vtkPVDataDeliveryManager::GetRepresentationIdFromQueue()
919 920 921 922 923 924 925 926 927
{
  if (!this->Internals->PriorityQueue.empty())
    {
    return this->Internals->PriorityQueue.top().RepresentationId;
    }

  return 0;
}

928
//----------------------------------------------------------------------------
929
void vtkPVDataDeliveryManager::PrintSelf(ostream& os, vtkIndent indent)
930 931 932
{
  this->Superclass::PrintSelf(os, indent);
}