vtkCompositeDataReader.cxx 18.4 KB
Newer Older
1 2 3
/*=========================================================================

  Program:   Visualization Toolkit
4
  Module:    vtkCompositeDataReader.cxx
5 6 7 8 9 10 11 12 13 14 15 16

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

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

=========================================================================*/
#include "vtkCompositeDataReader.h"

Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
17 18
#include "vtkAMRBox.h"
#include "vtkAMRInformation.h"
19
#include "vtkDataObjectTypes.h"
20
#include "vtkDoubleArray.h"
21
#include "vtkFieldData.h"
22
#include "vtkGenericDataObjectReader.h"
23 24 25
#include "vtkHierarchicalBoxDataSet.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
26
#include "vtkIntArray.h"
27 28
#include "vtkMultiBlockDataSet.h"
#include "vtkMultiPieceDataSet.h"
29
#include "vtkNonOverlappingAMR.h"
30
#include "vtkObjectFactory.h"
31
#include "vtkOverlappingAMR.h"
32
#include "vtkStreamingDemandDrivenPipeline.h"
33
#include "vtkUniformGrid.h"
34

35
#include <vtksys/RegularExpression.hxx>
36
#include <vtksys/SystemTools.hxx>
37
#include <sstream>
38

Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
39 40
#include <vector>

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
vtkStandardNewMacro(vtkCompositeDataReader);
//----------------------------------------------------------------------------
vtkCompositeDataReader::vtkCompositeDataReader()
{
}

//----------------------------------------------------------------------------
vtkCompositeDataReader::~vtkCompositeDataReader()
{
}

//----------------------------------------------------------------------------
vtkCompositeDataSet* vtkCompositeDataReader::GetOutput()
{
  return this->GetOutput(0);
}

//----------------------------------------------------------------------------
vtkCompositeDataSet* vtkCompositeDataReader::GetOutput(int idx)
{
  return vtkCompositeDataSet::SafeDownCast(this->GetOutputDataObject(idx));
}

//----------------------------------------------------------------------------
void vtkCompositeDataReader::SetOutput(vtkCompositeDataSet *output)
{
  this->GetExecutive()->SetOutputData(0, output);
}

//----------------------------------------------------------------------------
int vtkCompositeDataReader::RequestUpdateExtent(
  vtkInformation *, vtkInformationVector **, vtkInformationVector *outputVector)
{
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  int piece, numPieces, ghostLevel;

  piece = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
  numPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES());
  ghostLevel = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS());

  // make sure piece is valid
  if (piece < 0 || piece >= numPieces)
    {
    return 1;
    }

  if (ghostLevel < 0)
    {
    return 1;
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkCompositeDataReader::FillOutputPortInformation(int, vtkInformation* info)
{
  info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkCompositeDataSet");
  return 1;
}

//----------------------------------------------------------------------------
int vtkCompositeDataReader::ProcessRequest(vtkInformation* request,
  vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
  // generate the data
  if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA_OBJECT()))
    {
    return this->RequestDataObject(request, inputVector, outputVector);
    }
  return this->Superclass::ProcessRequest(request, inputVector, outputVector);
}

//----------------------------------------------------------------------------
int vtkCompositeDataReader::RequestDataObject(vtkInformation *,
  vtkInformationVector **, vtkInformationVector *outputVector)
{
  int output_type = this->ReadOutputType();
  if (output_type < 0)
    {
    vtkErrorMacro("Failed to read data-type.");
    return 0;
    }

  vtkDataObject* output = vtkDataObject::GetData(outputVector, 0);
  if (!output ||
    !output->IsA(vtkDataObjectTypes::GetClassNameFromTypeId(output_type)))
    {
    output = vtkDataObjectTypes::NewDataObject(output_type);
131 132 133
    outputVector->GetInformationObject(0)->Set(
      vtkDataObject::DATA_OBJECT(),
      output);
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    output->FastDelete();
    }
  return 1;
}

//----------------------------------------------------------------------------
int vtkCompositeDataReader::ReadOutputType()
{
  char line[256];
  if (!this->OpenVTKFile() || !this->ReadHeader())
    {
    return -1;
    }

  // Determine dataset type
  //
  if (!this->ReadString(line))
    {
    vtkDebugMacro(<< "Premature EOF reading dataset keyword");
    return -1;
    }

  if (strncmp(this->LowerCase(line),"dataset",static_cast<unsigned long>(7)) == 0)
    {
    // See iftype is recognized.
    //
    if (!this->ReadString(line))
      {
      vtkDebugMacro(<< "Premature EOF reading type");
      this->CloseVTKFile ();
      return -1;
      }
    this->CloseVTKFile();

    if (strncmp(this->LowerCase(line), "multiblock", strlen("multiblock")) == 0)
      {
      return VTK_MULTIBLOCK_DATA_SET;
      }
172 173 174 175
    if (strncmp(this->LowerCase(line), "multipiece", strlen("multipiece")) == 0)
      {
      return VTK_MULTIPIECE_DATA_SET;
      }
176 177 178 179 180 181 182 183
    if (strncmp(this->LowerCase(line), "overlapping_amr", strlen("overlapping_amr")) == 0)
      {
      return VTK_OVERLAPPING_AMR;
      }
    if (strncmp(this->LowerCase(line), "non_overlapping_amr", strlen("non_overlapping_amr")) == 0)
      {
      return VTK_NON_OVERLAPPING_AMR;
      }
184 185 186 187 188
    if (strncmp(this->LowerCase(line), "hierarchical_box",
        strlen("hierarchical_box")) == 0)
      {
      return VTK_HIERARCHICAL_BOX_DATA_SET;
      }
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    }

  return -1;
}

//----------------------------------------------------------------------------
int vtkCompositeDataReader::RequestData(vtkInformation *, vtkInformationVector **,
  vtkInformationVector *outputVector)
{
  if (!(this->OpenVTKFile()) || !this->ReadHeader())
    {
    return 0;
    }

  vtkMultiBlockDataSet* mb = vtkMultiBlockDataSet::GetData(outputVector, 0);
  vtkMultiPieceDataSet* mp = vtkMultiPieceDataSet::GetData(outputVector, 0);
  vtkHierarchicalBoxDataSet* hb = vtkHierarchicalBoxDataSet::GetData(outputVector, 0);
206 207
  vtkOverlappingAMR* oamr = vtkOverlappingAMR::GetData(outputVector, 0);
  vtkNonOverlappingAMR* noamr = vtkNonOverlappingAMR::GetData(outputVector, 0);
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

  // Read the data-type description line which was already read in
  // RequestDataObject() so we just skip it here without any additional
  // validation.
  char line[256];
  if (!this->ReadString(line) || !this->ReadString(line))
    {
    vtkErrorMacro(<<"Data file ends prematurely!");
    this->CloseVTKFile ();
    return 0;
    }

  if (mb)
    {
    this->ReadCompositeData(mb);
    }
  else if (mp)
    {
    this->ReadCompositeData(mp);
    }
  else if (hb)
    {
    this->ReadCompositeData(hb);
    }
232 233 234 235 236 237 238 239
  else if (oamr)
    {
    this->ReadCompositeData(oamr);
    }
  else if (noamr)
    {
    this->ReadCompositeData(noamr);
    }
240 241 242 243 244 245 246 247

  return 1;
}

//----------------------------------------------------------------------------
bool vtkCompositeDataReader::ReadCompositeData(vtkMultiBlockDataSet* mb)
{
  char line[256];
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
  if (!this->ReadString(line))
    {
    vtkErrorMacro("Failed to read block-count");
    return false;
    }

  if (strncmp(this->LowerCase(line), "children", strlen("children")) != 0)
    {
    vtkErrorMacro("Failed to read CHILDREN.");
    return false;
    }

  unsigned int num_blocks = 0;
  if (!this->Read(&num_blocks))
    {
    vtkErrorMacro("Failed to read number of blocks");
    return false;
    }

  mb->SetNumberOfBlocks(num_blocks);
  for (unsigned int cc=0; cc < num_blocks; cc++)
    {
    if (!this->ReadString(line))
      {
      vtkErrorMacro("Failed to read 'CHILD <type>' line");
      return false;
      }

    int type;
    if (!this->Read(&type))
      {
      vtkErrorMacro("Failed to read child type.");
      return false;
      }
    // eat up the "\n" and other whitespace at the end of CHILD <type>.
    this->ReadLine(line);
285 286 287 288 289 290 291
    // if "line" has text enclosed in [] then that's the composite name.
    vtksys::RegularExpression regEx("\\s*\\[(.*)\\]");
    if (regEx.find(line))
      {
      std::string name = regEx.match(1);
      mb->GetMetaData(cc)->Set(vtkCompositeDataSet::NAME(), name.c_str());
      }
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

    if (type != -1)
      {
      vtkDataObject* child = this->ReadChild();
      if (!child)
        {
        vtkErrorMacro("Failed to read child.");
        return false;
        }
      mb->SetBlock(cc, child);
      child->FastDelete();
      }
    else
      {
      // eat up the ENDCHILD marker.
      this->ReadString(line);
      }
    }

311 312 313 314 315 316
  if (this->ReadString(line) && strncmp(this->LowerCase(line),"field",5) == 0)
    {
    vtkSmartPointer< vtkFieldData > fd = vtkSmartPointer< vtkFieldData >::Take(this->ReadFieldData());
    mb->SetFieldData(fd);
    }

317 318 319 320 321 322
  return true;
}

//----------------------------------------------------------------------------
bool vtkCompositeDataReader::ReadCompositeData(vtkHierarchicalBoxDataSet* hb)
{
323 324
  (void)hb;
  vtkErrorMacro("This isn't supported yet.");
325 326 327
  return false;
}

328 329 330 331
//----------------------------------------------------------------------------
bool vtkCompositeDataReader::ReadCompositeData(vtkOverlappingAMR* oamr)
{
  char line[256];
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
332 333 334 335 336 337

  // read GRID_DESCRIPTION.
  int description;
  if (!this->ReadString(line) ||
    strncmp(this->LowerCase(line), "grid_description", strlen("grid_description")) != 0 ||
    !this->Read(&description))
338
    {
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
339
    vtkErrorMacro("Failed to read GRID_DESCRIPTION (or its value).");
340 341 342
    return false;
    }

Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
343 344 345 346 347 348
  // read ORIGIN
  double origin[3];
  if (!this->ReadString(line) ||
    strncmp(this->LowerCase(line), "origin", strlen("origin")) != 0 ||
    !this->Read(&origin[0]) || !this->Read(&origin[1]) ||
    !this->Read(&origin[2]))
349
    {
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
350
    vtkErrorMacro("Failed to read ORIGIN (or its value).");
351 352 353
    return false;
    }

Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
354 355 356 357 358
  // read LEVELS.
  int num_levels;
  if (!this->ReadString(line) ||
    strncmp(this->LowerCase(line), "levels", strlen("levels")) != 0 ||
    !this->Read(&num_levels))
359
    {
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
360
    vtkErrorMacro("Failed to read LEVELS (or its value).");
361 362 363
    return false;
    }

Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
364 365 366 367 368
  std::vector<int> blocksPerLevel;
  blocksPerLevel.resize(num_levels);

  std::vector<double> spacing;
  spacing.resize(num_levels * 3);
369

Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
370 371
  int total_blocks = 0;
  for (int cc=0; cc < num_levels; cc++)
372
    {
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
373
    if (!this->Read(&blocksPerLevel[cc]))
374 375 376 377
      {
      vtkErrorMacro("Failed to read number of datasets for level " << cc);
      return false;
      }
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
378 379
    if (!this->Read(&spacing[3*cc +0]) || !this->Read(&spacing[3*cc +1]) ||
      !this->Read(&spacing[3*cc+2]))
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
380 381 382 383 384
      {
      vtkErrorMacro("Failed to read spacing for level " << cc);
      return false;
      }
    total_blocks += blocksPerLevel[cc];
385
    }
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
386 387

  // initialize the AMR.
388
  oamr->Initialize(num_levels, &blocksPerLevel[0]);
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
389 390 391 392
  oamr->SetGridDescription(description);
  oamr->SetOrigin(origin);
  for (int cc=0; cc < num_levels; cc++)
    {
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
393
    oamr->GetAMRInfo()->SetSpacing(cc, &spacing[3*cc]);
Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
394 395
    }

Yuanxin Liu's avatar
Yuanxin Liu committed
396 397 398 399 400 401 402
  //read in the amr boxes0
  if (!this->ReadString(line))
    {
    vtkErrorMacro("Failed to read AMRBOXES' line");
    }
  else
    {
403
    if (strncmp(this->LowerCase(line), "amrboxes", strlen("amrboxes")) != 0)
Yuanxin Liu's avatar
Yuanxin Liu committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417
      {
      vtkErrorMacro("Failed to read AMRBOXES' line");
      }
    else
      {
      // now read the amrbox information.
      int num_tuples, num_components;
      if (!this->Read(&num_tuples) || !this->Read(&num_components))
        {
        vtkErrorMacro("Failed to read values for AMRBOXES.");
        return false;
        }

      vtkSmartPointer<vtkIntArray> idata;
418
      idata.TakeReference(vtkArrayDownCast<vtkIntArray>(
Yuanxin Liu's avatar
Yuanxin Liu committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
                            this->ReadArray("int", num_tuples, num_components)));
      if (!idata || idata->GetNumberOfComponents() != 6 ||
          idata->GetNumberOfTuples() != static_cast<vtkIdType>(oamr->GetTotalNumberOfBlocks()))
        {
        vtkErrorMacro("Failed to read meta-data");
        return false;
        }

      unsigned int metadata_index = 0;
      for (int level=0; level < num_levels; level++)
        {
        unsigned int num_datasets = oamr->GetNumberOfDataSets(level);
        for (unsigned int index=0; index < num_datasets; index++, metadata_index++)
          {
          int tuple[6];
David C. Lonie's avatar
David C. Lonie committed
434
          idata->GetTypedTuple(metadata_index, tuple);
Yuanxin Liu's avatar
Yuanxin Liu committed
435 436 437 438 439 440 441 442 443 444 445 446 447

          vtkAMRBox box;
          box.SetDimensions(&tuple[0], &tuple[3], description);
          oamr->SetAMRBox(level, index, box);
          }
        }
      }
    }


  //read in the actual data


Utkarsh Ayachit's avatar
Utkarsh Ayachit committed
448
  for (int cc=0; cc < total_blocks; cc++)
449 450 451
    {
    if (!this->ReadString(line))
      {
452 453 454
      // we may reach end of file sooner than total_blocks since not all blocks
      // may be present in the data.
      break;
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
      }

    if (strncmp(this->LowerCase(line), "child", strlen("child")) == 0)
      {
      unsigned int level=0, index=0;
      if (!this->Read(&level) || !this->Read(&index))
        {
        vtkErrorMacro("Failed to read level and index information");
        return false;
        }
      this->ReadLine(line);
      vtkDataObject* child = this->ReadChild();
      if (!child)
        {
        vtkErrorMacro("Failed to read dataset at " << level << ", " << index);
        return false;
        }
      if (child->IsA("vtkImageData"))
        {
        vtkUniformGrid* grid = vtkUniformGrid::New();
        grid->ShallowCopy(child);
        oamr->SetDataSet(level, index, grid);
        grid->FastDelete();
        child->Delete();
        }
      else
        {
        vtkErrorMacro("vtkImageData expected at " << level << ", " << index);
        child->Delete();
        return false;
        }
      }
    else
      {
489
      vtkErrorMacro("Failed to read 'CHILD' line");
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
      return false;
      }
    }

  return true;
}

//----------------------------------------------------------------------------
bool vtkCompositeDataReader::ReadCompositeData(vtkNonOverlappingAMR* hb)
{
  (void)hb;
  vtkErrorMacro("This isn't supported yet.");
  return false;
}

505 506 507
//----------------------------------------------------------------------------
bool vtkCompositeDataReader::ReadCompositeData(vtkMultiPieceDataSet* mp)
{
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
  char line[256];
  if (!this->ReadString(line))
    {
    vtkErrorMacro("Failed to read block-count");
    return false;
    }

  if (strncmp(this->LowerCase(line), "children", strlen("children")) != 0)
    {
    vtkErrorMacro("Failed to read CHILDREN.");
    return false;
    }

  unsigned int num_pieces = 0;
  if (!this->Read(&num_pieces))
    {
    vtkErrorMacro("Failed to read number of pieces.");
    return false;
    }

  mp->SetNumberOfPieces(num_pieces);
  for (unsigned int cc=0; cc < num_pieces; cc++)
    {
    if (!this->ReadString(line))
      {
      vtkErrorMacro("Failed to read 'CHILD <type>' line");
      return false;
      }

    int type;
    if (!this->Read(&type))
      {
      vtkErrorMacro("Failed to read child type.");
      return false;
      }
    // eat up the "\n" and other whitespace at the end of CHILD <type>.
    this->ReadLine(line);
545 546 547 548 549 550 551
    // if "line" has text enclosed in [] then that's the composite name.
    vtksys::RegularExpression regEx("\\s*\\[(.*)\\]");
    if (regEx.find(line))
      {
      std::string name = regEx.match(1);
      mp->GetMetaData(cc)->Set(vtkCompositeDataSet::NAME(), name.c_str());
      }
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

    if (type != -1)
      {
      vtkDataObject* child = this->ReadChild();
      if (!child)
        {
        vtkErrorMacro("Failed to read child.");
        return false;
        }
      mp->SetPiece(cc, child);
      child->FastDelete();
      }
    else
      {
      // eat up the ENDCHILD marker.
      this->ReadString(line);
      }
    }

  return true;
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
}

//----------------------------------------------------------------------------
vtkDataObject* vtkCompositeDataReader::ReadChild()
{
  // This is tricky. Simplistically speaking, we need to read the string for the
  // child and then pass it to a vtkGenericDataObjectReader and get it read.
  // Identifying where the child ends can be tricky since the child itself may
  // be a composite-dataset. Also, we need to avoid copy memory if we are
  // already reading from a string.

  // We can optimize this further when reading in from a string buffer to avoid
  // copying. But we'll do that later.

  unsigned int child_stack_depth = 1;

588
  std::ostringstream child_data;
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 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 639 640 641 642 643 644 645 646 647 648 649 650
  char line[512];
  while (child_stack_depth > 0)
    // read until ENDCHILD (passing over any nested CHILD-ENDCHILD correctly).
    {
    bool new_line = true;
    while (true)
      // read a full line until "\n". This maybe longer than 512 and hence this
      // extra loop.
      {
      this->IS->get(line, 512);
      if (this->IS->fail())
        {
        if (this->IS->eof())
          {
          vtkErrorMacro("Premature EOF.");
          return NULL;
          }
        else
          {
          // else it's possible that we read in an empty line. istream still marks
          // that as fail().
          this->IS->clear();
          }
        }

      if (new_line)
        {
        // these comparisons need to happen only when a new line is
        // started, hence this "if".
        if (strncmp(line, "ENDCHILD", strlen("ENDCHILD")) == 0)
          {
          child_stack_depth--;
          }
        else if (strncmp(line, "CHILD", strlen("CHILD")) == 0)
          {
          // should not match CHILDREN :(
          if (strncmp(line, "CHILDREN", strlen("CHILDREN")) != 0)
            {
            child_stack_depth++;
            }
          }
        }

      if (child_stack_depth > 0)
        {
        // except the last ENDCHILD, all the read content is to passed to the
        // child-reader.
        child_data.write(line, this->IS->gcount());
        }
      new_line = false;
      if (this->IS->peek() == '\n')
        {
        this->IS->ignore(VTK_INT_MAX, '\n');
        // end of line reached.
        child_data << '\n';
        break;
        }
      } // while (true);
    } // while (child_stack_depth > 0);

  vtkGenericDataObjectReader* reader = vtkGenericDataObjectReader::New();
  reader->SetBinaryInputString(child_data.str().c_str(),
651
    static_cast<int>(child_data.str().size()));
652 653
  reader->ReadFromInputStringOn();
  reader->Update();
654 655 656 657 658 659

  vtkDataObject* child = reader->GetOutput(0);
  if (child)
    {
    child->Register(this);
    }
660 661 662 663 664 665 666 667 668
  reader->Delete();
  return child;
}

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