vtkWebGLExporter.cxx 26.4 KB
Newer Older
Zach's avatar
Zach committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkWebGLExporter.cxx

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

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

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

#include "vtkWebGLExporter.h"

#include "vtkObjectFactory.h"
#include "vtkActor2D.h"
#include "vtkActorCollection.h"
#include "vtkBase64Utilities.h"
#include "vtkDiscretizableColorTransferFunction.h"
#include "vtkFollower.h"
#include "vtkRenderer.h"
#include "vtkMapper.h"
#include "vtkSmartPointer.h"
#include "vtkTriangleFilter.h"
#include "vtkCompositeDataSet.h"
#include "vtkCompositeDataGeometryFilter.h"
#include "vtkPolyDataNormals.h"
#include "vtkCellArray.h"
#include "vtkDataSetAttributes.h"
#include "vtkProperty.h"
#include "vtkCamera.h"
#include "vtkViewport.h"
#include "vtkMatrix4x4.h"
#include "vtkMapper2D.h"
#include "vtkCellData.h"
#include "vtkAbstractMapper.h"
#include "vtkGenericCell.h"
#include "vtkPointData.h"
#include "vtkProperty.h"
#include "vtkDataSet.h"
#include "vtkProperty2D.h"
#include "vtkRenderWindow.h"
#include "vtkRendererCollection.h"
#include "vtkScalarBarRepresentation.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkScalarBarActor.h"
#include "vtkWidgetRepresentation.h"

#include "vtkWebGLObject.h"
#include "vtkWebGLPolyData.h"
#include "vtkWebGLWidget.h"

#include <iostream>
#include <sstream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>

#include "glMatrix.h"
#include "webglRenderer.h"

#include "vtksys/MD5.h"

//*****************************************************************************
class vtkWebGLExporter::vtkInternal
{
public:
  std::string LastMetaData;
73 74
  std::map<vtkProp*, vtkMTimeType> ActorTimestamp;
  std::map<vtkProp*, vtkMTimeType> OldActorTimestamp;
Zach's avatar
Zach committed
75 76 77 78 79 80 81 82 83 84 85 86
  std::vector<vtkWebGLObject*> Objects;
  std::vector<vtkWebGLObject*> tempObj;
};
//*****************************************************************************

vtkStandardNewMacro(vtkWebGLExporter);

vtkWebGLExporter::vtkWebGLExporter()
{
  this->meshObjMaxSize = 65532/3;
  this->lineObjMaxSize = 65534/2;
  this->Internal = new vtkInternal();
87
  this->TriangleFilter = nullptr;
Zach's avatar
Zach committed
88 89 90 91 92 93 94 95 96 97
  this->GradientBackground = false;
  this->SetCenterOfRotation(0.0, 0.0, 0.0);
  this->renderersMetaData = "";
  this->SceneSize[0] = 0;
  this->SceneSize[1] = 0;
  this->SceneSize[2] = 0;
  this->hasWidget = false;
}

vtkWebGLExporter::~vtkWebGLExporter()
98
{
99
  while(!this->Internal->Objects.empty())
100
  {
Zach's avatar
Zach committed
101 102 103
    vtkWebGLObject* obj = this->Internal->Objects.back();
    obj->Delete();
    this->Internal->Objects.pop_back();
104
  }
Zach's avatar
Zach committed
105
  delete this->Internal;
106
  if (this->TriangleFilter)
107
  {
108
    this->TriangleFilter->Delete();
109
  }
110
}
Zach's avatar
Zach committed
111 112

void vtkWebGLExporter::SetMaxAllowedSize(int mesh, int lines)
113
{
Zach's avatar
Zach committed
114 115 116 117 118 119 120
  this->meshObjMaxSize = mesh;
  this->lineObjMaxSize = lines;
  if (this->meshObjMaxSize*3 > 65532) this->meshObjMaxSize = 65532/3;
  if (this->lineObjMaxSize*2 > 65534) this->lineObjMaxSize = 65534/2;
  if (this->meshObjMaxSize < 10) this->meshObjMaxSize = 10;
  if (this->lineObjMaxSize < 10) this->lineObjMaxSize = 10;
  for(size_t i=0; i<this->Internal->Objects.size(); i++) this->Internal->Objects[i]->GenerateBinaryData();
121
}
Zach's avatar
Zach committed
122 123

void vtkWebGLExporter::SetMaxAllowedSize(int size)
124
{
Zach's avatar
Zach committed
125
  this->SetMaxAllowedSize(size, size);
126
}
Zach's avatar
Zach committed
127 128

void vtkWebGLExporter::SetCenterOfRotation(float a1, float a2, float a3)
129
{
Zach's avatar
Zach committed
130 131 132
  this->CenterOfRotation[0] = a1;
  this->CenterOfRotation[1] = a2;
  this->CenterOfRotation[2] = a3;
133
}
Zach's avatar
Zach committed
134 135 136


void vtkWebGLExporter::parseRenderer(vtkRenderer *renderer, const char* vtkNotUsed(viewId), bool onlyWidget, void* vtkNotUsed(mapTime))
137
{
Zach's avatar
Zach committed
138 139
  vtkPropCollection* propCollection = renderer->GetViewProps();
  for (int i=0; i<propCollection->GetNumberOfItems(); i++)
140
  {
Zach's avatar
Zach committed
141 142
    vtkProp* prop = (vtkProp*)propCollection->GetItemAsObject(i);
    vtkWidgetRepresentation* trt = vtkWidgetRepresentation::SafeDownCast(prop);
143 144
    if (trt!=nullptr) this->hasWidget = true;
    if ((onlyWidget==false || trt!=nullptr) && prop->GetVisibility())
145
    {
Zach's avatar
Zach committed
146 147 148
      vtkPropCollection* allactors = vtkPropCollection::New();
      prop->GetActors(allactors);
      for (int j=0; j<allactors->GetNumberOfItems(); j++)
149
      {
Zach's avatar
Zach committed
150
        vtkActor* actor = vtkActor::SafeDownCast(allactors->GetItemAsObject(j));
151
        vtkActor* key = actor;
152
        vtkMTimeType previousValue = this->Internal->OldActorTimestamp[key];
153
        this->parseActor(actor, previousValue, (size_t)renderer, renderer->GetLayer(), trt != nullptr);
Zach's avatar
Zach committed
154
      }
155 156
      allactors->Delete();
    }
Zach's avatar
Zach committed
157
    if (onlyWidget==false && prop->GetVisibility())
158
    {
Zach's avatar
Zach committed
159 160 161
      vtkPropCollection* all2dactors = vtkPropCollection::New();
      prop->GetActors2D(all2dactors);
      for (int k=0; k<all2dactors->GetNumberOfItems(); k++)
162
      {
Zach's avatar
Zach committed
163
        vtkActor2D* actor = vtkActor2D::SafeDownCast(all2dactors->GetItemAsObject(k));
164
        vtkActor2D* key = actor;
165
        vtkMTimeType previousValue = this->Internal->OldActorTimestamp[key];
166
        this->parseActor2D(actor, previousValue, (size_t)renderer, renderer->GetLayer(), trt != nullptr);
Zach's avatar
Zach committed
167
      }
168
      all2dactors->Delete();
Zach's avatar
Zach committed
169 170
    }
  }
171
}
Zach's avatar
Zach committed
172

173
void vtkWebGLExporter::parseActor2D(vtkActor2D *actor, vtkMTimeType actorTime, size_t renderId, int layer, bool isWidget)
174
{
175
  vtkActor2D* key = actor;
Zach's avatar
Zach committed
176 177
  vtkScalarBarActor* scalarbar = vtkScalarBarActor::SafeDownCast(actor);

178
  vtkMTimeType dataMTime = actor->GetMTime() + actor->GetRedrawMTime() + actor->GetProperty()->GetMTime();
179
  dataMTime += (vtkMTimeType) actor->GetMapper();
Zach's avatar
Zach committed
180 181
  if (scalarbar) dataMTime += scalarbar->GetLookupTable()->GetMTime();
  if (dataMTime != actorTime && actor->GetVisibility())
182
  {
Zach's avatar
Zach committed
183 184 185
    this->Internal->ActorTimestamp[key] = dataMTime;

    if (actor->GetMapper())
186
    {
Zach's avatar
Zach committed
187 188
      std::string name = actor->GetMapper()->GetClassName();
      if (vtkPolyDataMapper2D::SafeDownCast(actor->GetMapper()))
189
      {
Zach's avatar
Zach committed
190
      }
191
    }
Zach's avatar
Zach committed
192
    else
193
    {
Zach's avatar
Zach committed
194
      if (scalarbar)
195
      {
Zach's avatar
Zach committed
196 197 198 199
        vtkWebGLWidget* obj = vtkWebGLWidget::New();
        obj->GetDataFromColorMap(actor);

        std::stringstream ss;
200
        ss << (size_t)actor;
Zach's avatar
Zach committed
201
        obj->SetId(ss.str());
202
        obj->SetRendererId(static_cast<int>(renderId));
Zach's avatar
Zach committed
203 204 205 206 207 208 209 210
        this->Internal->Objects.push_back(obj);
        obj->SetLayer(layer);
        obj->SetVisibility(actor->GetVisibility() != 0);
        obj->SetIsWidget(isWidget);
        obj->SetInteractAtServer(false);
        obj->GenerateBinaryData();
      }
    }
211
  }
Zach's avatar
Zach committed
212
  else
213
  {
Zach's avatar
Zach committed
214 215
    this->Internal->ActorTimestamp[key] = dataMTime;
    std::stringstream ss;
216
    ss << (vtkMTimeType) actor;
Zach's avatar
Zach committed
217
    for (size_t i=0; i<this->Internal->tempObj.size(); i++)
218
    {
Zach's avatar
Zach committed
219
      if (this->Internal->tempObj[i]->GetId().compare(ss.str()) == 0)
220
      {
Zach's avatar
Zach committed
221 222 223 224 225 226 227
        vtkWebGLObject* obj = this->Internal->tempObj[i];
        this->Internal->tempObj.erase(this->Internal->tempObj.begin()+i);
        obj->SetVisibility(actor->GetVisibility() != 0);
        this->Internal->Objects.push_back(obj);
      }
    }
  }
228
}
Zach's avatar
Zach committed
229

230
void vtkWebGLExporter::parseActor(vtkActor* actor, vtkMTimeType actorTime, size_t rendererId, int layer, bool isWidget)
231
{
Zach's avatar
Zach committed
232 233
  vtkMapper* mapper = actor->GetMapper();
  if (mapper)
234
  {
235
    vtkMTimeType dataMTime;
Zach's avatar
Zach committed
236
    vtkTriangleFilter* polydata = this->GetPolyData(mapper, dataMTime);
237
    vtkActor* key = actor;
Zach's avatar
Zach committed
238 239 240 241 242 243 244
    dataMTime = actor->GetMTime() + mapper->GetLookupTable()->GetMTime();
    dataMTime += actor->GetProperty()->GetMTime() + mapper->GetMTime() + actor->GetRedrawMTime();
    dataMTime += polydata->GetOutput()->GetNumberOfLines() + polydata->GetOutput()->GetNumberOfPolys();
    dataMTime += actor->GetProperty()->GetRepresentation() + mapper->GetScalarMode() + actor->GetVisibility();
    dataMTime += polydata->GetInput()->GetMTime();
    if (vtkFollower::SafeDownCast(actor)) dataMTime += vtkFollower::SafeDownCast(actor)->GetCamera()->GetMTime();
    if(dataMTime != actorTime && actor->GetVisibility())
245
    {
Zach's avatar
Zach committed
246 247 248 249 250
      double bb[6];
      actor->GetBounds(bb);
      double m1 = std::max(bb[1]-bb[0], bb[3]-bb[2]); m1 = std::max(m1, bb[5]-bb[4]);
      double m2 = std::max(this->SceneSize[0], this->SceneSize[1]); m2 = std::max(m2, this->SceneSize[2]);
      if (m1 > m2)
251
      {
Zach's avatar
Zach committed
252 253 254
        this->SceneSize[0] = bb[1]-bb[0];
        this->SceneSize[1] = bb[3]-bb[2];
        this->SceneSize[2] = bb[5]-bb[4];
255
      }
Zach's avatar
Zach committed
256 257

      this->Internal->ActorTimestamp[key] = dataMTime;
258
      vtkWebGLObject* obj = nullptr;
Zach's avatar
Zach committed
259
      std::stringstream ss;
260
      ss << (size_t)actor;
Zach's avatar
Zach committed
261
      for (size_t i=0; i<this->Internal->tempObj.size(); i++)
262
      {
Zach's avatar
Zach committed
263
        if (this->Internal->tempObj[i]->GetId().compare(ss.str()) == 0)
264
        {
Zach's avatar
Zach committed
265 266 267
          obj = this->Internal->tempObj[i];
          this->Internal->tempObj.erase(this->Internal->tempObj.begin()+i);
        }
268
      }
269
      if (obj == nullptr) obj = vtkWebGLPolyData::New();
Zach's avatar
Zach committed
270 271

      if (polydata->GetOutput()->GetNumberOfPolys() != 0)
272
      {
Zach's avatar
Zach committed
273
        if (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)
274
        {
275
          ((vtkWebGLPolyData*)obj)->GetLinesFromPolygon(mapper, actor, this->lineObjMaxSize, nullptr);
276
        }
Zach's avatar
Zach committed
277
        else
278
        {
Zach's avatar
Zach committed
279 280

          if (actor->GetProperty()->GetEdgeVisibility())
281
          {
Zach's avatar
Zach committed
282 283 284 285
            vtkWebGLPolyData* newobj = vtkWebGLPolyData::New();
            double ccc[3]; actor->GetProperty()->GetEdgeColor(&ccc[0]);
            ((vtkWebGLPolyData*)newobj)->GetLinesFromPolygon(mapper, actor, this->lineObjMaxSize, ccc);
            newobj->SetId(ss.str() + "1");
286
            newobj->SetRendererId(static_cast<int>(rendererId));
Zach's avatar
Zach committed
287 288 289 290 291 292 293 294
            this->Internal->Objects.push_back(newobj);
            newobj->SetLayer(layer);
            newobj->SetTransformationMatrix(actor->GetMatrix());
            newobj->SetVisibility(actor->GetVisibility() != 0);
            newobj->SetHasTransparency(actor->HasTranslucentPolygonalGeometry() != 0);
            newobj->SetIsWidget(isWidget);
            newobj->SetInteractAtServer(isWidget);
            newobj->GenerateBinaryData();
295
          }
Zach's avatar
Zach committed
296 297 298


          switch(mapper->GetScalarMode())
299
          {
Zach's avatar
Zach committed
300 301 302 303 304 305 306 307 308 309
            case VTK_SCALAR_MODE_USE_POINT_FIELD_DATA:
               ((vtkWebGLPolyData*)obj)->GetPolygonsFromPointData(polydata, actor, this->meshObjMaxSize);
              break;
            case VTK_SCALAR_MODE_USE_CELL_FIELD_DATA:
              ((vtkWebGLPolyData*)obj)->GetPolygonsFromCellData(polydata, actor, this->meshObjMaxSize);
              break;
            default:
               ((vtkWebGLPolyData*)obj)->GetPolygonsFromPointData(polydata, actor, this->meshObjMaxSize);
              break;
          }
310
        }
Zach's avatar
Zach committed
311
        obj->SetId(ss.str());
312
        obj->SetRendererId(static_cast<int>(rendererId));
Zach's avatar
Zach committed
313 314 315 316 317 318 319 320
        this->Internal->Objects.push_back(obj);
        obj->SetLayer(layer);
        obj->SetTransformationMatrix(actor->GetMatrix());
        obj->SetVisibility(actor->GetVisibility() != 0);
        obj->SetHasTransparency(actor->HasTranslucentPolygonalGeometry() != 0);
        obj->SetIsWidget(isWidget);
        obj->SetInteractAtServer(isWidget);
        obj->GenerateBinaryData();
321
      }
Zach's avatar
Zach committed
322
      else if (polydata->GetOutput()->GetNumberOfLines() != 0)
323
      {
Zach's avatar
Zach committed
324 325
        ((vtkWebGLPolyData*)obj)->GetLines(polydata, actor, this->lineObjMaxSize);
        obj->SetId(ss.str());
326
        obj->SetRendererId(static_cast<int>(rendererId));
Zach's avatar
Zach committed
327 328 329 330 331 332 333 334
        this->Internal->Objects.push_back(obj);
        obj->SetLayer(layer);
        obj->SetTransformationMatrix(actor->GetMatrix());
        obj->SetVisibility(actor->GetVisibility() != 0);
        obj->SetHasTransparency(actor->HasTranslucentPolygonalGeometry() != 0);
        obj->SetIsWidget(isWidget);
        obj->SetInteractAtServer(isWidget);
        obj->GenerateBinaryData();
335
      }
Zach's avatar
Zach committed
336
      else if (polydata->GetOutput()->GetNumberOfPoints() != 0)
337
      {
Zach's avatar
Zach committed
338 339
        ((vtkWebGLPolyData*)obj)->GetPoints(polydata, actor, 65534);//Wendel
        obj->SetId(ss.str());
340
        obj->SetRendererId(static_cast<int>(rendererId));
Zach's avatar
Zach committed
341 342 343 344 345 346 347 348
        this->Internal->Objects.push_back(obj);
        obj->SetLayer(layer);
        obj->SetTransformationMatrix(actor->GetMatrix());
        obj->SetVisibility(actor->GetVisibility() != 0);
        obj->SetHasTransparency(actor->HasTranslucentPolygonalGeometry() != 0);
        obj->SetIsWidget(false);
        obj->SetInteractAtServer(false);
        obj->GenerateBinaryData();
349
      }
Zach's avatar
Zach committed
350 351

      if (polydata->GetOutput()->GetNumberOfPolys() != 0 && polydata->GetOutput()->GetNumberOfLines() != 0)
352
      {
Zach's avatar
Zach committed
353 354 355 356
        obj = vtkWebGLPolyData::New();
        ((vtkWebGLPolyData*)obj)->GetLines(polydata, actor, this->lineObjMaxSize);
        ss << "1";
        obj->SetId(ss.str());
357
        obj->SetRendererId(static_cast<int>(rendererId));
Zach's avatar
Zach committed
358 359 360 361 362 363 364 365
        this->Internal->Objects.push_back(obj);
        obj->SetLayer(layer);
        obj->SetTransformationMatrix(actor->GetMatrix());
        obj->SetVisibility(actor->GetVisibility() != 0);
        obj->SetHasTransparency(actor->HasTranslucentPolygonalGeometry() != 0);
        obj->SetIsWidget(isWidget);
        obj->SetInteractAtServer(isWidget);
        obj->GenerateBinaryData();
366
      }
Zach's avatar
Zach committed
367 368

      if (polydata->GetOutput()->GetNumberOfLines() == 0 && polydata->GetOutput()->GetNumberOfPolys() == 0 && polydata->GetOutput()->GetNumberOfPoints() == 0)
369
      {
Zach's avatar
Zach committed
370 371
        obj->Delete();
      }
372
    }
Zach's avatar
Zach committed
373
    else
374
    {
Zach's avatar
Zach committed
375 376
      this->Internal->ActorTimestamp[key] = actorTime;
      std::stringstream ss;
377
      ss << (size_t)actor;
Zach's avatar
Zach committed
378
      for (size_t i=0; i<this->Internal->tempObj.size(); i++)
379
      {
Zach's avatar
Zach committed
380
        if (this->Internal->tempObj[i]->GetId().compare(ss.str()) == 0)
381
        {
Zach's avatar
Zach committed
382 383 384 385 386 387 388 389
          vtkWebGLObject* obj = this->Internal->tempObj[i];
          this->Internal->tempObj.erase(this->Internal->tempObj.begin()+i);
          obj->SetVisibility(actor->GetVisibility() != 0);
          this->Internal->Objects.push_back(obj);
        }
      }
    }
  }
390
}
Zach's avatar
Zach committed
391 392 393 394 395 396 397 398

void vtkWebGLExporter::parseScene(vtkRendererCollection* renderers, const char* viewId, int parseType)
{
  if (!renderers) return;

  bool onlyWidget = parseType == VTK_ONLYWIDGET;
  bool cameraOnly = onlyWidget && !this->hasWidget;

399
  this->SceneId = viewId? viewId : "";
Zach's avatar
Zach committed
400
  if (cameraOnly)
401
  {
Zach's avatar
Zach committed
402 403
    this->generateRendererData(renderers, viewId);
    return;
404
  }
Zach's avatar
Zach committed
405 406

  if (onlyWidget)
407
  {
Zach's avatar
Zach committed
408
    for (int i= static_cast<int>(this->Internal->Objects.size())-1; i>=0; i--)
409
    {
Zach's avatar
Zach committed
410 411
      vtkWebGLObject* obj = this->Internal->Objects[i];
      if (obj->InteractAtServer())
412
      {
Zach's avatar
Zach committed
413 414 415 416
        this->Internal->tempObj.push_back(obj);
        this->Internal->Objects.erase(this->Internal->Objects.begin()+i);
      }
    }
417
  }
Zach's avatar
Zach committed
418
  else
419
  {
420
    while(!this->Internal->Objects.empty())
421
    {
Zach's avatar
Zach committed
422 423 424
      this->Internal->tempObj.push_back(this->Internal->Objects.back());
      this->Internal->Objects.pop_back();
    }
425
  }
Zach's avatar
Zach committed
426 427 428 429 430

  this->Internal->OldActorTimestamp = this->Internal->ActorTimestamp;
  if (!onlyWidget) this->Internal->ActorTimestamp.clear();
  this->hasWidget = false;
  for(int i=0; i<renderers->GetNumberOfItems(); i++)
431
  {
Zach's avatar
Zach committed
432
    vtkRenderer* renderer = vtkRenderer::SafeDownCast(renderers->GetItemAsObject(i));
433
    if (renderer->GetDraw()) this->parseRenderer(renderer, viewId, onlyWidget, nullptr);
434
  }
435
  while(!this->Internal->tempObj.empty())
436
  {
Zach's avatar
Zach committed
437 438 439
    vtkWebGLObject* obj = this->Internal->tempObj.back();
    this->Internal->tempObj.pop_back();
    obj->Delete();
440
  }
Zach's avatar
Zach committed
441 442 443 444 445

  this->generateRendererData(renderers, viewId);
}

bool sortLayer(vtkRenderer* i,vtkRenderer* j)
446
{
Zach's avatar
Zach committed
447
  return (i->GetLayer() < j->GetLayer());
448
}
Zach's avatar
Zach committed
449 450

void vtkWebGLExporter::generateRendererData(vtkRendererCollection* renderers, const char* vtkNotUsed(viewId))
451
{
Zach's avatar
Zach committed
452 453 454 455 456 457 458
  std::stringstream ss;
  ss << "\"Renderers\": [";

  std::vector<vtkRenderer*> orderedList;
  for(int i=0; i<renderers->GetNumberOfItems(); i++) orderedList.push_back(vtkRenderer::SafeDownCast(renderers->GetItemAsObject(i)));
  std::sort(orderedList.begin(), orderedList.begin()+orderedList.size(), sortLayer);

459
  int *fullSize = nullptr;
Zach's avatar
Zach committed
460
  for(size_t i=0; i<orderedList.size(); i++)
461
  {
Zach's avatar
Zach committed
462 463 464
    vtkRenderer* renderer = orderedList[i];

    if (i == 0)
465
    {
Zach's avatar
Zach committed
466
      fullSize = renderer->GetSize();
467
    }
Zach's avatar
Zach committed
468 469 470 471 472 473 474 475

    double cam[10]; cam[0] = renderer->GetActiveCamera()->GetViewAngle();
    renderer->GetActiveCamera()->GetFocalPoint(&cam[1]);
    renderer->GetActiveCamera()->GetViewUp(&cam[4]);
    renderer->GetActiveCamera()->GetPosition(&cam[7]);
    int* s, *o; s = renderer->GetSize(); o = renderer->GetOrigin();
    ss << "{\"layer\":" << renderer->GetLayer() << ",";     //Render Layer
    if (renderer->GetLayer() == 0)                          //Render Background
476
    {
Zach's avatar
Zach committed
477 478 479
      double back[3]; renderer->GetBackground(back);
      ss << "\"Background1\":[" << back[0] << "," << back[1] << "," << back[2] << "],";
      if (renderer->GetGradientBackground())
480
      {
Zach's avatar
Zach committed
481 482 483
        renderer->GetBackground2(back);
        ss << "\"Background2\":[" << back[0] << "," << back[1] << "," << back[2] << "],";
      }
484
    }
Zach's avatar
Zach committed
485 486 487 488 489 490 491
    ss << "\"LookAt\":[";                                  //Render Camera
    for (int j=0; j<9; j++) ss << cam[j] << ",";
    ss << cam[9] << "], ";
    ss << "\"size\": [" << (float)(s[0]/(float)fullSize[0]) << "," << (float)(s[1]/(float)fullSize[1]) << "],";    //Render Size
    ss << "\"origin\": [" << (float)(o[0]/(float)fullSize[0]) << "," << (float)(o[1]/(float)fullSize[1]) << "]";   //Render Position
    ss << "}";
    if (static_cast<int>(i+1) != renderers->GetNumberOfItems()) ss << ", ";
492
  }
Zach's avatar
Zach committed
493 494
  ss << "]";
  this->renderersMetaData = ss.str();
495
}
Zach's avatar
Zach committed
496

497
vtkTriangleFilter* vtkWebGLExporter::GetPolyData(vtkMapper* mapper, vtkMTimeType& dataMTime)
Zach's avatar
Zach committed
498
{
499
  vtkDataSet* dataset = nullptr;
Zach's avatar
Zach committed
500 501 502 503
  vtkSmartPointer<vtkDataSet> tempDS;
  vtkDataObject* dObj = mapper->GetInputDataObject(0, 0);
  vtkCompositeDataSet* cd = vtkCompositeDataSet::SafeDownCast(dObj);
  if (cd)
504
  {
Zach's avatar
Zach committed
505 506 507 508 509 510 511
    dataMTime = cd->GetMTime();
    vtkCompositeDataGeometryFilter* gf = vtkCompositeDataGeometryFilter::New();
    gf->SetInputData(cd);
    gf->Update();
    tempDS = gf->GetOutput();
    gf->Delete();
    dataset = tempDS;
512
  }
Zach's avatar
Zach committed
513
  else
514
  {
Zach's avatar
Zach committed
515 516
    dataset = mapper->GetInput();
    dataMTime = dataset->GetMTime();
517
  }
Zach's avatar
Zach committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

  // Converting to triangles. WebGL only support triangles.
  if (this->TriangleFilter) this->TriangleFilter->Delete();
  this->TriangleFilter = vtkTriangleFilter::New();
  this->TriangleFilter->SetInputData(dataset);
  this->TriangleFilter->Update();
  return this->TriangleFilter;
}

/*
  Function: GenerateMetaData
  Description:
  - Generates the metadata of the scene in JSON format
  Ex.:
    { "id": ,"LookAt": ,"Background1": ,"Background2":
    "Objects": [{"id": ,"md5": ,"parts": },  {"id": ,"md5": ,"parts": }] }
*/
const char* vtkWebGLExporter::GenerateMetadata()
{
  double max = std::max(this->SceneSize[0], this->SceneSize[1]); max = std::max(max, this->SceneSize[2]);
  std::stringstream ss;

540
  ss << "{\"id\":" << this->SceneId.c_str() << ",";
Zach's avatar
Zach committed
541 542 543 544 545 546 547 548 549 550
  ss << "\"MaxSize\":" << max << ",";
  ss << "\"Center\":[";
  for (int i=0; i<2; i++) ss << this->CenterOfRotation[i] << ", ";
  ss << this->CenterOfRotation[2] << "],";

  ss << this->renderersMetaData << ",";

  ss << " \"Objects\":[";
  bool first = true;
  for (size_t i=0; i<this->Internal->Objects.size(); i++)
551
  {
Zach's avatar
Zach committed
552 553
    vtkWebGLObject* obj = this->Internal->Objects[i];
    if (obj->isVisible())
554
    {
Zach's avatar
Zach committed
555 556 557 558 559 560 561 562 563
      if (first) first = false;
      else ss << ", ";
      ss << "{\"id\":" << obj->GetId() << ", \"md5\":\"" << obj->GetMD5() << "\""
         << ", \"parts\":" << obj->GetNumberOfParts()
         << ", \"interactAtServer\":" << obj->InteractAtServer()
         << ", \"transparency\":" << obj->HasTransparency()
         << ", \"layer\":" << obj->GetLayer()
         << ", \"wireframe\":" << obj->isWireframeMode() << "}";
    }
564
  }
Zach's avatar
Zach committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
  ss << "]}";

  this->Internal->LastMetaData = ss.str();
  return this->Internal->LastMetaData.c_str();
}

const char* vtkWebGLExporter::GenerateExportMetadata()
{
  double max = std::max(this->SceneSize[0], this->SceneSize[1]); max = std::max(max, this->SceneSize[2]);
  std::stringstream ss;

  ss << "{\"id\":" << this->SceneId << ",";
  ss << "\"MaxSize\":" << max << ",";
  ss << "\"Center\":[";
  for (int i=0; i<2; i++) ss << this->CenterOfRotation[i] << ", ";
  ss << this->CenterOfRotation[2] << "],";

  ss << this->renderersMetaData << ",";

  ss << " \"Objects\":[";
  bool first = true;
  for (size_t i=0; i<this->Internal->Objects.size(); i++)
587
  {
Zach's avatar
Zach committed
588 589
    vtkWebGLObject* obj = this->Internal->Objects[i];
    if (obj->isVisible())
590
    {
Zach's avatar
Zach committed
591
      for(int j=0; j<obj->GetNumberOfParts(); j++)
592
      {
Zach's avatar
Zach committed
593 594 595 596 597 598 599 600 601 602
        if (first) first = false;
        else ss << ", ";
        ss << "{\"id\":" << obj->GetId() << ", \"md5\":\"" << obj->GetMD5() << "\""
           << ", \"parts\":" << 1
           << ", \"interactAtServer\":" << obj->InteractAtServer()
           << ", \"transparency\":" << obj->HasTransparency()
           << ", \"layer\":" << obj->GetLayer()
           << ", \"wireframe\":" << obj->isWireframeMode() << "}";
      }
    }
603
  }
Zach's avatar
Zach committed
604 605 606 607 608 609
  ss << "]}";

  this->Internal->LastMetaData = ss.str();
  return this->Internal->LastMetaData.c_str();
}

610
vtkWebGLObject* vtkWebGLExporter::GetWebGLObject(int index)
611
{
Zach's avatar
Zach committed
612
  return this->Internal->Objects[index];
613
}
Zach's avatar
Zach committed
614 615

int vtkWebGLExporter::GetNumberOfObjects()
616
{
Zach's avatar
Zach committed
617
  return static_cast<int>(this->Internal->Objects.size());
618
}
Zach's avatar
Zach committed
619 620 621 622 623 624 625 626

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

const char* vtkWebGLExporter::GetId()
{
627
  return this->SceneId.c_str();
Zach's avatar
Zach committed
628 629 630 631 632 633 634 635 636
}

bool vtkWebGLExporter::hasChanged()
{
  for (size_t i=0; i<this->Internal->Objects.size(); i++) if (this->Internal->Objects[i]->HasChanged()) return true;
  return false;
}

void vtkWebGLExporter::exportStaticScene(vtkRendererCollection *renderers, int width, int height, std::string path)
637
{
Zach's avatar
Zach committed
638 639 640 641 642 643 644 645 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
  std::stringstream ss;
  ss << width << "," << height;
  std::string resultHTML = "<html><head></head><body onload='loadStaticScene();' style='margin: 0px; padding: 0px; position: absolute; overflow: hidden; top:0px; left:0px;'>";
  resultHTML += "<div id='container' onclick='consumeEvent(event);' style='margin: 0px; padding: 0px; position: absolute; overflow: hidden; top:0px; left:0px;'></div></body>\n";
  resultHTML += "<script type='text/javascript'> var rendererWebGL = null;";
  resultHTML += "function reresize(event){ if (rendererWebGL != null) rendererWebGL.setSize(window.innerWidth, window.innerHeight); }";
  resultHTML += "function loadStaticScene(){ ";
  resultHTML += "  var objs=[];";
  resultHTML += "  for(i=0; i<object.length; i++){";
  resultHTML += "  objs[i] = decode64(object[i]);";
  resultHTML += "  }\n object = [];";
  resultHTML += "  rendererWebGL = new WebGLRenderer('webglRenderer-1', '');";
  resultHTML += "  rendererWebGL.init('', '');";
  resultHTML += "  rendererWebGL.bindToElementId('container');";
  resultHTML += "  //rendererWebGL.setSize(" + ss.str() + ");\n";
  resultHTML += "  rendererWebGL.setSize(window.innerWidth, window.innerHeight);";
  resultHTML += "  rendererWebGL.start(metadata, objs);";
  resultHTML += "  window.onresize = reresize;";
  resultHTML += "}\n";
  resultHTML += "function consumeEvent(event) { if (event.preventDefault) { event.preventDefault();} else { event.returnValue= false;} return false;}";

  resultHTML += "function ntos(n){ n=n.toString(16); if (n.length == 1) n='0'+n; n='%'+n; return unescape(n); }";
  resultHTML += "var END_OF_INPUT = -1; var base64Chars = new Array(";
  resultHTML += "'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X',";
  resultHTML += "'Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',";
  resultHTML += "'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/');";
  resultHTML += "var base64Str; var base64Count;";
  resultHTML += "var reverseBase64Chars = new Array();";
  resultHTML += "for (var i=0; i < base64Chars.length; i++){ reverseBase64Chars[base64Chars[i]] = i; }";
  resultHTML += "function readReverseBase64(){ if (!base64Str) return END_OF_INPUT;";
  resultHTML += "while (true){ if (base64Count >= base64Str.length) return END_OF_INPUT;";
  resultHTML += "var nextCharacter = base64Str.charAt(base64Count); base64Count++;";
  resultHTML += "if (reverseBase64Chars[nextCharacter]){ return reverseBase64Chars[nextCharacter]; }";
  resultHTML += "if (nextCharacter == 'A') return 0; } return END_OF_INPUT; }";
  resultHTML += "function decode64(str){";
  resultHTML += "base64Str = str; base64Count = 0; var result = ''; var inBuffer = new Array(4); var done = false;";
  resultHTML += "while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT";
  resultHTML += "&& (inBuffer[1] = readReverseBase64()) != END_OF_INPUT){";
  resultHTML += "inBuffer[2] = readReverseBase64();";
  resultHTML += "inBuffer[3] = readReverseBase64();";
  resultHTML += "result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));";
  resultHTML += "if (inBuffer[2] != END_OF_INPUT){";
  resultHTML += "result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));";
  resultHTML += "if (inBuffer[3] != END_OF_INPUT){";
  resultHTML += "result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));";
  resultHTML += "} else { done = true; }";
  resultHTML += "} else { done = true; } }";
  resultHTML += "return result; }";

  vtkBase64Utilities* base64 = vtkBase64Utilities::New();

  this->parseScene(renderers, "1234567890", VTK_PARSEALL);
  const char * metadata = this->GenerateExportMetadata();
  resultHTML += "var metadata = '" + std::string(metadata) + "';";
  resultHTML += "var object = [";
  for(int i=0; i<this->GetNumberOfObjects(); i++)
694
  {
Zach's avatar
Zach committed
695 696 697
    std::string test;
    int size = 0;

698
    vtkWebGLObject* obj = this->GetWebGLObject(i);
Zach's avatar
Zach committed
699
    if (obj->isVisible())
700
    {
Zach's avatar
Zach committed
701
      for(int j=0; j<obj->GetNumberOfParts(); j++)
702
      {
Zach's avatar
Zach committed
703 704 705 706 707 708 709
        unsigned char* output = new unsigned char[obj->GetBinarySize(j)*2];
        size = base64->Encode(obj->GetBinaryData(j), obj->GetBinarySize(j), output, false);
        test = std::string((const char *)output, size);
        resultHTML += "'" + test + "',\n";
        delete[] output;
      }
    }
710
  }
Zach's avatar
Zach committed
711 712 713 714 715 716 717 718 719 720 721 722 723
  resultHTML += "''];";

  resultHTML += webglRenderer;
  resultHTML += glMatrix;

  resultHTML += "</script></html>";

  ofstream file;
  file.open(path.c_str());
  file << resultHTML;
  file.close();

  base64->Delete();
724
}
Zach's avatar
Zach committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741

//-----------------------------------------------------------------------------
void vtkWebGLExporter::ComputeMD5(const unsigned char* content, int size, std::string &hash)
{
  unsigned char digest[16];
  char md5Hash[33];
  md5Hash[32] = '\0';

  vtksysMD5* md5 = vtksysMD5_New();
  vtksysMD5_Initialize(md5);
  vtksysMD5_Append(md5, content, size);
  vtksysMD5_Finalize(md5, digest);
  vtksysMD5_DigestToHex(digest, md5Hash);
  vtksysMD5_Delete(md5);

  hash = md5Hash;
}