forked from Kitware/VTK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vtkWebApplication.cxx
465 lines (408 loc) · 14.3 KB
/
vtkWebApplication.cxx
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
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
131
132
133
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
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
214
215
216
217
218
219
220
221
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*=========================================================================
Program: Visualization Toolkit
Module: vtkWebApplication.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 "vtkWebApplication.h"
#include "vtkBase64Utilities.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkImageData.h"
#include "vtkJPEGWriter.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkObjectIdMap.h"
#include "vtkPNGWriter.h"
#include "vtkDataEncoder.h"
#include "vtkWebInteractionEvent.h"
#include "vtkPointData.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRendererCollection.h"
#include "vtkSmartPointer.h"
#include "vtkTimerLog.h"
#include "vtkUnsignedCharArray.h"
#include "vtkWebGLExporter.h"
#include "vtkWebGLObject.h"
#include "vtkWindowToImageFilter.h"
#include <cassert>
#include <cmath>
#include <map>
#include <sstream>
class vtkWebApplication::vtkInternals
{
public:
struct ImageCacheValueType
{
public:
vtkSmartPointer<vtkUnsignedCharArray> Data;
bool NeedsRender;
bool HasImagesBeingProcessed;
vtkObject* ViewPointer;
unsigned long ObserverId;
ImageCacheValueType() : NeedsRender(true), HasImagesBeingProcessed(false), ViewPointer(nullptr), ObserverId(0) { }
void SetListener(vtkObject* view)
{
if(this->ViewPointer == view)
{
return;
}
if(this->ViewPointer && this->ObserverId)
{
this->ViewPointer->RemoveObserver(this->ObserverId);
this->ObserverId = 0;
}
this->ViewPointer = view;
if(this->ViewPointer)
{
this->ObserverId = this->ViewPointer->AddObserver(vtkCommand::AnyEvent, this, &ImageCacheValueType::ViewEventListener);
}
}
void RemoveListener(vtkObject* view)
{
if(this->ViewPointer && this->ViewPointer == view && this->ObserverId)
{
this->ViewPointer->RemoveObserver(this->ObserverId);
this->ObserverId = 0;
this->ViewPointer = nullptr;
}
}
void ViewEventListener(vtkObject*, unsigned long, void*)
{
this->NeedsRender = true;
}
};
typedef std::map<void*, ImageCacheValueType> ImageCacheType;
ImageCacheType ImageCache;
typedef std::map<void*, unsigned int > ButtonStatesType;
ButtonStatesType ButtonStates;
vtkNew<vtkDataEncoder> Encoder;
// WebGL related struct
struct WebGLObjCacheValue
{
public:
int ObjIndex;
std::map<int, std::string> BinaryParts;
};
// map for <vtkWebGLExporter, <webgl-objID, WebGLObjCacheValue> >
typedef std::map<std::string, WebGLObjCacheValue> WebGLObjId2IndexMap;
std::map<vtkWebGLExporter*, WebGLObjId2IndexMap> WebGLExporterObjIdMap;
// map for <vtkRenderWindow, vtkWebGLExporter>
std::map<vtkRenderWindow*, vtkSmartPointer<vtkWebGLExporter> > ViewWebGLMap;
std::string LastAllWebGLBinaryObjects;
vtkNew<vtkObjectIdMap> ObjectIdMap;
};
vtkStandardNewMacro(vtkWebApplication);
//----------------------------------------------------------------------------
vtkWebApplication::vtkWebApplication():
ImageEncoding(ENCODING_BASE64),
ImageCompression(COMPRESSION_JPEG),
Internals(new vtkWebApplication::vtkInternals())
{
}
//----------------------------------------------------------------------------
vtkWebApplication::~vtkWebApplication()
{
delete this->Internals;
this->Internals = nullptr;
}
//----------------------------------------------------------------------------
void vtkWebApplication::SetNumberOfEncoderThreads(vtkTypeUInt32 numThreads)
{
this->Internals->Encoder->SetMaxThreads(numThreads);
this->Internals->Encoder->Initialize();
}
//----------------------------------------------------------------------------
vtkTypeUInt32 vtkWebApplication::GetNumberOfEncoderThreads()
{
return this->Internals->Encoder->GetMaxThreads();
}
//----------------------------------------------------------------------------
bool vtkWebApplication::GetHasImagesBeingProcessed(vtkRenderWindow* view)
{
const vtkInternals::ImageCacheValueType& value = this->Internals->ImageCache[view];
return value.HasImagesBeingProcessed;
}
//----------------------------------------------------------------------------
vtkUnsignedCharArray* vtkWebApplication::InteractiveRender(vtkRenderWindow* view, int quality)
{
// for now, just do the same as StillRender().
return this->StillRender(view, quality);
}
//----------------------------------------------------------------------------
void vtkWebApplication::InvalidateCache(vtkRenderWindow* view)
{
this->Internals->ImageCache[view].NeedsRender = true;
}
//----------------------------------------------------------------------------
vtkUnsignedCharArray* vtkWebApplication::StillRender(vtkRenderWindow* view, int quality)
{
if (!view)
{
vtkErrorMacro("No view specified.");
return nullptr;
}
vtkInternals::ImageCacheValueType& value = this->Internals->ImageCache[view];
value.SetListener(view);
if (value.NeedsRender == false &&
value.Data != nullptr /* FIXME SEB &&
view->HasDirtyRepresentation() == false */)
{
//cout << "Reusing cache" << endl;
bool latest = this->Internals->Encoder->GetLatestOutput(this->Internals->ObjectIdMap->GetGlobalId(view), value.Data);
value.HasImagesBeingProcessed = !latest;
return value.Data;
}
//cout << "Regenerating " << endl;
//vtkTimerLog::ResetLog();
//vtkTimerLog::CleanupLog();
//vtkTimerLog::MarkStartEvent("StillRenderToString");
//vtkTimerLog::MarkStartEvent("CaptureWindow");
view->Render();
// TODO: We should add logic to check if a new rendering needs to be done and
// then alone do a new rendering otherwise use the cached image.
vtkNew<vtkWindowToImageFilter> w2i;
w2i->SetInput(view);
w2i->SetScale(1);
w2i->ReadFrontBufferOff();
w2i->ShouldRerenderOff();
w2i->FixBoundaryOn();
w2i->Update();
vtkImageData* image = vtkImageData::New();
image->ShallowCopy(w2i->GetOutput());
//vtkTimerLog::MarkEndEvent("CaptureWindow");
//vtkTimerLog::MarkEndEvent("StillRenderToString");
//vtkTimerLog::DumpLogWithIndents(&cout, 0.0);
this->Internals->Encoder->PushAndTakeReference(this->Internals->ObjectIdMap->GetGlobalId(view), image, quality);
assert(image == nullptr);
if (value.Data == nullptr)
{
// we need to wait till output is processed.
//cout << "Flushing" << endl;
this->Internals->Encoder->Flush(this->Internals->ObjectIdMap->GetGlobalId(view));
//cout << "Done Flushing" << endl;
}
bool latest = this->Internals->Encoder->GetLatestOutput(this->Internals->ObjectIdMap->GetGlobalId(view), value.Data);
value.HasImagesBeingProcessed = !latest;
value.NeedsRender = false;
return value.Data;
}
//----------------------------------------------------------------------------
const char* vtkWebApplication::StillRenderToString(vtkRenderWindow* view, vtkMTimeType time, int quality)
{
vtkUnsignedCharArray* array = this->StillRender(view, quality);
if (array && array->GetMTime() != time)
{
this->LastStillRenderToMTime = array->GetMTime();
//cout << "Image size: " << array->GetNumberOfTuples() << endl;
return reinterpret_cast<char*>(array->GetPointer(0));
}
return nullptr;
}
//----------------------------------------------------------------------------
bool vtkWebApplication::HandleInteractionEvent(
vtkRenderWindow* view, vtkWebInteractionEvent* event)
{
vtkRenderWindowInteractor *iren = nullptr;
if (view)
{
iren = view->GetInteractor();
}
else
{
vtkErrorMacro("Interaction not supported for view : " << view);
return false;
}
int ctrlKey =
(event->GetModifiers() & vtkWebInteractionEvent::CTRL_KEY) != 0? 1: 0;
int shiftKey =
(event->GetModifiers() & vtkWebInteractionEvent::SHIFT_KEY) != 0? 1: 0;
// Handle scroll action if any
if(event->GetScroll()) {
iren->SetEventInformation(0, 0, ctrlKey, shiftKey, event->GetKeyCode(), 0);
iren->MouseMoveEvent();
iren->RightButtonPressEvent();
iren->SetEventInformation(0, event->GetScroll()*10, ctrlKey, shiftKey, event->GetKeyCode(), 0);
iren->MouseMoveEvent();
iren->RightButtonReleaseEvent();
this->Internals->ImageCache[view].NeedsRender = true;
return true;
}
int *viewSize = view->GetSize();
int posX = std::floor(viewSize[0] * event->GetX() + 0.5);
int posY = std::floor(viewSize[1] * event->GetY() + 0.5);
iren->SetEventInformation(posX, posY, ctrlKey, shiftKey, event->GetKeyCode(), event->GetRepeatCount());
unsigned int prev_buttons = this->Internals->ButtonStates[view];
unsigned int changed_buttons = (event->GetButtons() ^ prev_buttons);
iren->MouseMoveEvent();
if ( (changed_buttons & vtkWebInteractionEvent::LEFT_BUTTON) != 0 )
{
if ( (event->GetButtons() & vtkWebInteractionEvent::LEFT_BUTTON) != 0)
{
iren->LeftButtonPressEvent();
if(event->GetRepeatCount() > 0)
{
iren->LeftButtonReleaseEvent();
}
}
else
{
iren->LeftButtonReleaseEvent();
}
}
if ( (changed_buttons & vtkWebInteractionEvent::RIGHT_BUTTON) != 0 )
{
if ( (event->GetButtons() & vtkWebInteractionEvent::RIGHT_BUTTON) != 0)
{
iren->RightButtonPressEvent();
if(event->GetRepeatCount() > 0)
{
iren->RightButtonPressEvent();
}
}
else
{
iren->RightButtonReleaseEvent();
}
}
if ( (changed_buttons & vtkWebInteractionEvent::MIDDLE_BUTTON) != 0 )
{
if ( (event->GetButtons() & vtkWebInteractionEvent::MIDDLE_BUTTON) != 0)
{
iren->MiddleButtonPressEvent();
if(event->GetRepeatCount() > 0)
{
iren->MiddleButtonPressEvent();
}
}
else
{
iren->MiddleButtonReleaseEvent();
}
}
this->Internals->ButtonStates[view] = event->GetButtons();
bool needs_render = (changed_buttons != 0 || event->GetButtons());
this->Internals->ImageCache[view].NeedsRender = needs_render;
return needs_render;
}
// ---------------------------------------------------------------------------
const char* vtkWebApplication::GetWebGLSceneMetaData(vtkRenderWindow* view)
{
if (!view)
{
vtkErrorMacro("No view specified.");
return nullptr;
}
// We use the camera focal point to be the center of rotation
double centerOfRotation[3];
vtkCamera *cam = view->GetRenderers()->GetFirstRenderer()->GetActiveCamera();
cam->GetFocalPoint(centerOfRotation);
if(this->Internals->ViewWebGLMap.find(view) ==
this->Internals->ViewWebGLMap.end())
{
this->Internals->ViewWebGLMap[view] =
vtkSmartPointer<vtkWebGLExporter>::New();
}
std::stringstream globalIdAsString;
globalIdAsString << this->Internals->ObjectIdMap->GetGlobalId(view);
vtkWebGLExporter* webglExporter = this->Internals->ViewWebGLMap[view];
webglExporter->parseScene(
view->GetRenderers(), globalIdAsString.str().c_str(), VTK_PARSEALL);
vtkInternals::WebGLObjId2IndexMap webglMap;
for(int i=0; i<webglExporter->GetNumberOfObjects(); ++i)
{
vtkWebGLObject* wObj = webglExporter->GetWebGLObject(i);
if(wObj && wObj->isVisible())
{
vtkInternals::WebGLObjCacheValue val;
val.ObjIndex = i;
for(int j=0; j<wObj->GetNumberOfParts(); ++j)
{
val.BinaryParts[j] = "";
}
webglMap[wObj->GetId()] = val;
}
}
this->Internals->WebGLExporterObjIdMap[webglExporter] = webglMap;
webglExporter->SetCenterOfRotation(
static_cast<float>(centerOfRotation[0]),
static_cast<float>(centerOfRotation[1]),
static_cast<float>(centerOfRotation[2]));
return webglExporter->GenerateMetadata();
}
//----------------------------------------------------------------------------
const char* vtkWebApplication::GetWebGLBinaryData(
vtkRenderWindow* view, const char* id, int part)
{
if (!view)
{
vtkErrorMacro("No view specified.");
return nullptr;
}
if(this->Internals->ViewWebGLMap.find(view) ==
this->Internals->ViewWebGLMap.end())
{
if(this->GetWebGLSceneMetaData(view) == nullptr)
{
vtkErrorMacro("Failed to generate WebGL MetaData for: " << view);
return nullptr;
}
}
vtkWebGLExporter* webglExporter = this->Internals->ViewWebGLMap[view];
if(webglExporter == nullptr)
{
vtkErrorMacro("There is no cached WebGL Exporter for: " << view);
return nullptr;
}
if(!this->Internals->WebGLExporterObjIdMap[webglExporter].empty() &&
this->Internals->WebGLExporterObjIdMap[webglExporter].find(id) !=
this->Internals->WebGLExporterObjIdMap[webglExporter].end())
{
vtkInternals::WebGLObjCacheValue* cachedVal =
&(this->Internals->WebGLExporterObjIdMap[webglExporter][id]);
if(cachedVal->BinaryParts.find(part) != cachedVal->BinaryParts.end())
{
if(cachedVal->BinaryParts[part].empty())
{
vtkWebGLObject* obj = webglExporter->GetWebGLObject(cachedVal->ObjIndex);
if(obj && obj->isVisible())
{
// Manage Base64
vtkNew<vtkBase64Utilities> base64;
unsigned char* output = new unsigned char[obj->GetBinarySize(part)*2];
int size = base64->Encode(
obj->GetBinaryData(part), obj->GetBinarySize(part), output, false);
cachedVal->BinaryParts[part] = std::string((const char *)output, size);
delete[] output;
}
}
return cachedVal->BinaryParts[part].c_str();
}
}
return nullptr;
}
//----------------------------------------------------------------------------
void vtkWebApplication::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ImageEncoding: " << this->ImageEncoding << endl;
os << indent << "ImageCompression: " << this->ImageCompression << endl;
}
//----------------------------------------------------------------------------
vtkObjectIdMap* vtkWebApplication::GetObjectIdMap()
{
return this->Internals->ObjectIdMap;
}
//----------------------------------------------------------------------------
std::string vtkWebApplication::GetObjectId(vtkObject* obj)
{
std::ostringstream oss;
oss << std::hex << static_cast<void*>(obj);
return oss.str();
}