File: vtkHardwareSelector.cxx

package info (click to toggle)
vtk6 6.3.0%2Bdfsg2-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 118,880 kB
  • sloc: cpp: 1,442,792; ansic: 113,395; python: 72,383; tcl: 46,998; xml: 8,119; yacc: 4,525; java: 4,239; perl: 3,108; lex: 1,694; sh: 1,093; asm: 154; makefile: 103; objc: 17
file content (807 lines) | stat: -rw-r--r-- 24,352 bytes parent folder | download | duplicates (4)
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkHardwareSelector.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 "vtkHardwareSelector.h"

#include "vtkCommand.h"
#include "vtkDataObject.h"
#include "vtkDataSetAttributes.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkProp.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSmartPointer.h"
#include "vtkStructuredExtent.h"

#include <algorithm>
#include <cassert>
#include <map>
#include <set>

#define ID_OFFSET 1

#ifndef VTK_OPENGL2
#include "vtkPainterDeviceAdapter.h"
#endif

//----------------------------------------------------------------------------
namespace
{
  class PixelInformationComparator
    {
  public:
    bool operator() (const vtkHardwareSelector::PixelInformation& a,
      const vtkHardwareSelector::PixelInformation& b) const
      {
      if (a.Valid != b.Valid)
        {
        return a.Valid < b.Valid;
        }
      if (a.ProcessID != b.ProcessID)
        {
        return a.ProcessID < b.ProcessID;
        }
      if (a.Prop != b.Prop)
        {
        return a.Prop < b.Prop;
        }
      if (a.PropID != b.PropID)
        {
        return a.PropID < b.PropID;
        }
      return a.CompositeID < b.CompositeID;

      // We don't consider AttributeID in this comparison
      }
    };
}

class vtkHardwareSelector::vtkInternals
{
public:
  // Ids for props that were hit.
  std::set<int> HitProps;
  std::map<int, vtkSmartPointer<vtkProp> > Props;

  // state that's managed through the renderer
  double OriginalBackground[3];
  bool OriginalGradient;

  typedef std::map<PixelInformation, std::set<vtkIdType>,
    PixelInformationComparator> MapOfAttributeIds;

  typedef std::map<PixelInformation, vtkIdType,
    PixelInformationComparator> PixelCountType;

  //-----------------------------------------------------------------------------
  vtkSelection* ConvertSelection(
    int fieldassociation, const MapOfAttributeIds& dataMap,
    const PixelCountType& pixelCounts)
    {
    vtkSelection* sel = vtkSelection::New();

    MapOfAttributeIds::const_iterator iter;
    for (iter = dataMap.begin(); iter != dataMap.end(); ++iter)
      {
      const PixelInformation &key = iter->first;
      const std::set<vtkIdType> &id_values = iter->second;
      vtkSelectionNode* child = vtkSelectionNode::New();
      child->SetContentType(vtkSelectionNode::INDICES);
      switch (fieldassociation)
        {
        case vtkDataObject::FIELD_ASSOCIATION_CELLS:
          child->SetFieldType(vtkSelectionNode::CELL);
          break;

        case vtkDataObject::FIELD_ASSOCIATION_POINTS:
          child->SetFieldType(vtkSelectionNode::POINT);
          break;
        }
      child->GetProperties()->Set(vtkSelectionNode::PROP_ID(), key.PropID);
      child->GetProperties()->Set(vtkSelectionNode::PROP(), key.Prop);
      PixelCountType::const_iterator pit = pixelCounts.find(key);
      child->GetProperties()->Set(vtkSelectionNode::PIXEL_COUNT(), pit->second);
      if (key.ProcessID >= 0)
        {
        child->GetProperties()->Set(vtkSelectionNode::PROCESS_ID(),
          key.ProcessID);
        }

      child->GetProperties()->Set(vtkSelectionNode::COMPOSITE_INDEX(),
        key.CompositeID);

      vtkIdTypeArray* ids = vtkIdTypeArray::New();
      ids->SetName("SelectedIds");
      ids->SetNumberOfComponents(1);
      ids->SetNumberOfTuples(iter->second.size());
      vtkIdType* ptr = ids->GetPointer(0);
      std::set<vtkIdType>::const_iterator idIter;
      vtkIdType cc=0;
      for (idIter = id_values.begin(); idIter != id_values.end(); ++idIter, ++cc)
        {
        ptr[cc] = *idIter;
        }
      child->SetSelectionList(ids);
      ids->FastDelete();
      sel->AddNode(child);
      child->FastDelete();
      }

    return sel;
    }

  //-----------------------------------------------------------------------------
  bool PixelInsidePolygon(float x, float y, int* polygonPoints, vtkIdType count)
    {
    // http://en.wikipedia.org/wiki/Point_in_polygon
    // RayCasting method shooting the ray along the x axis, using float
    bool inside = false;
    float xintersection;
    for(vtkIdType i=0; i<count; i+=2)
      {
      float p1X = polygonPoints[i];
      float p1Y = polygonPoints[i+1];
      float p2X = polygonPoints[(i+2) % count];
      float p2Y = polygonPoints[(i+3) % count];

      if (y > std::min(p1Y, p2Y) &&
        y <= std::max(p1Y,p2Y) &&
        p1Y != p2Y)
        {
        if (x <= std::max(p1X, p2X) )
          {
          xintersection = (y - p1Y)*(p2X - p1X)/(p2Y - p1Y) + p1X;
          if ( p1X == p2X || x <= xintersection)
            {
            // each time intersect, toggle inside
            inside = !inside;
            }
          }
        }
      }

    return inside;
    }

};

//----------------------------------------------------------------------------
vtkAbstractObjectFactoryNewMacro(vtkHardwareSelector);

//----------------------------------------------------------------------------
vtkCxxSetObjectMacro(vtkHardwareSelector, Renderer, vtkRenderer);

//----------------------------------------------------------------------------
vtkHardwareSelector::vtkHardwareSelector()
{
  this->Internals = new vtkInternals();
  this->Renderer = 0;
  this->Area[0] = this->Area[1] = this->Area[2] = this->Area[3] = 0;
  this->FieldAssociation = vtkDataObject::FIELD_ASSOCIATION_CELLS;
  this->MaxAttributeId = 0;
  for (int cc=0; cc < 10; cc++)
    {
    this->PixBuffer[cc] = 0;
    }
  this->CurrentPass = -1;
  this->ProcessID = -1;
  this->InPropRender = 0;
  this->UseProcessIdFromData = false;
}

//----------------------------------------------------------------------------
vtkHardwareSelector::~vtkHardwareSelector()
{
  this->SetRenderer(0);
  this->ReleasePixBuffers();
  delete this->Internals;
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::ReleasePixBuffers()
{
  for (int cc=0; cc < 10; cc++)
    {
    delete [] this->PixBuffer[cc];
    this->PixBuffer[cc] = 0;
    }
  //this->Internals->Props.clear();
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::BeginSelection()
{
  this->MaxAttributeId = 0;
  this->Renderer->Clear();
  this->Renderer->SetSelector(this);
  this->Renderer->PreserveDepthBufferOn();
  this->Internals->HitProps.clear();
  this->Internals->Props.clear();
  this->ReleasePixBuffers();
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::EndSelection()
{
  this->Internals->HitProps.clear();
  this->Renderer->SetSelector(NULL);
  this->Renderer->PreserveDepthBufferOff();
}

//----------------------------------------------------------------------------
vtkSelection* vtkHardwareSelector::Select()
{
  vtkSelection* sel = 0;
  if (this->CaptureBuffers())
    {
    sel = this->GenerateSelection();
    this->ReleasePixBuffers();
    }
  return sel;
}

//----------------------------------------------------------------------------
bool vtkHardwareSelector::CaptureBuffers()
{
  if (!this->Renderer)
    {
    vtkErrorMacro("Renderer must be set before calling Select.");
    return false;
    }

  vtkRenderWindow *rwin = this->Renderer->GetRenderWindow();
  int rgba[4];
  rwin->GetColorBufferSizes(rgba);
  if (rgba[0] < 8 || rgba[1] < 8 || rgba[2] < 8)
    {
    vtkErrorMacro("Color buffer depth must be atleast 8 bit. "
      "Currently: " << rgba[0] << ", " << rgba[1] << ", " <<rgba[2]);
    return false;
    }
  this->InvokeEvent(vtkCommand::StartEvent);

  rwin->SwapBuffersOff();

  // Initialize renderer for selection.
  //change the renderer's background to black, which will indicate a miss
  this->Renderer->GetBackground(this->Internals->OriginalBackground);
  this->Renderer->SetBackground(0.0,0.0,0.0);
  this->Internals->OriginalGradient = this->Renderer->GetGradientBackground();
  this->Renderer->GradientBackgroundOff();

  this->BeginSelection();
  for (this->CurrentPass = MIN_KNOWN_PASS;
    this->CurrentPass < MAX_KNOWN_PASS; this->CurrentPass++)
    {
    if (!this->PassRequired(this->CurrentPass))
      {
      continue;
      }
    rwin->Render();
    this->SavePixelBuffer(this->CurrentPass);
    }
  this->EndSelection();

  //restore original background
  this->Renderer->SetBackground(this->Internals->OriginalBackground);
  this->Renderer->SetGradientBackground(this->Internals->OriginalGradient);
  this->Renderer->GetRenderWindow()->SwapBuffersOn();
  this->InvokeEvent(vtkCommand::EndEvent);
  return true;
}

//----------------------------------------------------------------------------
bool vtkHardwareSelector::PassRequired(int pass)
{
  switch (pass)
    {
  case PROCESS_PASS:
    // skip process pass is pid < 0.
    return (this->ProcessID >= 0);

  case ID_MID24:
    return (this->MaxAttributeId >= 0xffffff);

  case ID_HIGH16:
    int upper = (0xffffff & (this->MaxAttributeId >> 24));
    return (upper > 0);
    }
  return true;
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::SavePixelBuffer(int passNo)
{
  delete [] this->PixBuffer[passNo];
  this->PixBuffer[passNo] = this->Renderer->GetRenderWindow()->GetPixelData(
    this->Area[0], this->Area[1], this->Area[2], this->Area[3],
    (this->Renderer->GetRenderWindow()->GetSwapBuffers() == 1)? 1 : 0);

  if (passNo == ACTOR_PASS)
    {
    this->BuildPropHitList(this->PixBuffer[passNo]);
    }
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::BuildPropHitList(unsigned char* pixelbuffer)
{
  for (int yy=0; yy <= static_cast<int>(this->Area[3]-this->Area[1]); yy++)
    {
    for (int xx=0; xx <= static_cast<int>(this->Area[2]-this->Area[0]); xx++)
      {
      int val = this->Convert(xx, yy, pixelbuffer);
      if (val > 0)
        {
        val--;
        if (this->Internals->HitProps.find(val) ==
          this->Internals->HitProps.end())
          {
          this->Internals->HitProps.insert(val);
          }
        }
      }
    }
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::BeginRenderProp()
{
  this->InPropRender++;
  if (this->InPropRender != 1)
    {
    return;
    }

  // device specific prep
  vtkRenderWindow *renWin = this->Renderer->GetRenderWindow();
  this->BeginRenderProp(renWin);

  //cout << "In BeginRenderProp" << endl;
  //glFinish();
#ifndef VTK_OPENGL2
  if (this->CurrentPass == ACTOR_PASS)
    {
    int propid = this->PropID;
    if (propid >= 0xfffffe)
      {
      vtkErrorMacro("Too many props. Currently only " << 0xfffffe
        << " props are supported.");
      return;
      }
    float color[3];
    // Since 0 is reserved for nothing selected, we offset propid by 1.
    propid = propid + 1;
    vtkHardwareSelector::Convert(propid, color);
    renWin->GetPainterDeviceAdapter()->SendAttribute(
      vtkDataSetAttributes::SCALARS, 3, VTK_FLOAT, color);
    }
  else if (this->CurrentPass == PROCESS_PASS)
    {
    float color[3];
    // Since 0 is reserved for nothing selected, we offset propid by 1.
    vtkHardwareSelector::Convert(this->ProcessID + 1, color);
    renWin->GetPainterDeviceAdapter()->SendAttribute(
      vtkDataSetAttributes::SCALARS, 3, VTK_FLOAT, color);
    }
  else
    {
    float color[3] = {0, 0, 0};
    renWin->GetPainterDeviceAdapter()->SendAttribute(
      vtkDataSetAttributes::SCALARS, 3, VTK_FLOAT, color);
    }
#endif
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::EndRenderProp()
{
  if (this->InPropRender)
    {
    this->InPropRender--;

    if (this->InPropRender != 0)
      {
      return;
      }

    // device specific cleanup
    vtkRenderWindow *renWin = this->Renderer->GetRenderWindow();
    this->EndRenderProp(renWin);
    }
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::RenderCompositeIndex(unsigned int index)
{

  if (index > 0xffffff)
    {
    vtkErrorMacro("Indices > 0xffffff are not supported.");
    return;
    }

#ifndef VTK_OPENGL2
  index += ID_OFFSET;

  //glFinish();
  if (this->CurrentPass == COMPOSITE_INDEX_PASS)
    {
    float color[3];
    vtkHardwareSelector::Convert(static_cast<int>(0xffffff & index), color);
    this->Renderer->GetRenderWindow()->GetPainterDeviceAdapter()->SendAttribute(
      vtkDataSetAttributes::SCALARS, 3, VTK_FLOAT, color);
    }
#endif
}

//----------------------------------------------------------------------------
// TODO: make inline
void vtkHardwareSelector::RenderAttributeId(vtkIdType attribid)
{
  if (attribid < 0)
    {
    // negative attribid is valid. It happens when rendering higher order
    // elements where new points are added for rendering smooth surfaces.
    return;
    }

  this->MaxAttributeId = (attribid > this->MaxAttributeId)? attribid :
    this->MaxAttributeId;

  if (this->CurrentPass < ID_LOW24 || this->CurrentPass > ID_HIGH16)
    {
    return;
    }

#ifndef VTK_OPENGL2
  // 0 is reserved.
  attribid += ID_OFFSET;

  for (int cc=0; cc < 3; cc++)
    {
    int words24 = (0xffffff & attribid);
    attribid = attribid >> 24;
    if ((this->CurrentPass - ID_LOW24) == cc)
      {
      float color[3];
      vtkHardwareSelector::Convert(words24, color);
      this->Renderer->GetRenderWindow()->GetPainterDeviceAdapter()->SendAttribute(
        vtkDataSetAttributes::SCALARS, 3, VTK_FLOAT, color);
      break;
      }
    }
#endif
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::RenderProcessId(unsigned int processid)
{
  if (this->CurrentPass == PROCESS_PASS && this->UseProcessIdFromData)
    {
    if (processid >= 0xffffff)
      {
      vtkErrorMacro("Invalid id: " << processid);
      return;
      }

#ifndef VTK_OPENGL2
    float color[3];
    vtkHardwareSelector::Convert(
      static_cast<int>(processid + 1), color);
    this->Renderer->GetRenderWindow()->GetPainterDeviceAdapter()->SendAttribute(
      vtkDataSetAttributes::SCALARS, 3, VTK_FLOAT, color);
#endif
    }
}

//----------------------------------------------------------------------------
int vtkHardwareSelector::Render(vtkRenderer* renderer, vtkProp** propArray,
  int propArrayCount)
{
  if (this->Renderer != renderer)
    {
    vtkErrorMacro("Usage error.");
    return 0;
    }

  int propsRenderered = 0;
  // loop through props and give them a chance to
  // render themselves as opaque geometry
  for (int i = 0; i < propArrayCount; i++ )
    {
    // all props in propArray are already visible, hence no need to check again
    // (vtkRenderer ensures that).
    if (!propArray[i]->GetPickable() || !propArray[i]->GetSupportsSelection())
      {
      continue;
      }
    this->PropID = this->GetPropID(i, propArray[i]);
    this->Internals->Props[this->PropID] = propArray[i];
    if (this->IsPropHit(this->PropID))
      {
      propsRenderered += propArray[i]->RenderOpaqueGeometry(renderer);
      }
    }

  // loop through props and give them a chance to render themselves as
  // overlay geometry. This allows the overlay geometry
  // also being selected. The props in overlay can use Pickable or
  // SupportsSelection variables to decide whether to be included in this pass.
  for (int i = 0; i < propArrayCount; i++ )
    {
    if (!propArray[i]->GetPickable() || !propArray[i]->GetSupportsSelection())
      {
      continue;
      }
    this->PropID = this->GetPropID(i, propArray[i]);
    this->Internals->Props[this->PropID] = propArray[i];
    if (this->IsPropHit(this->PropID))
      {
      propsRenderered += propArray[i]->RenderOverlay(renderer);
      }
    }

  return propsRenderered;
}

//----------------------------------------------------------------------------
vtkProp* vtkHardwareSelector::GetPropFromID(int id)
{
  std::map<int, vtkSmartPointer<vtkProp> >::iterator iter =
    this->Internals->Props.find(id);
  if (iter != this->Internals->Props.end())
    {
    return iter->second;
    }
  return NULL;
}

//----------------------------------------------------------------------------
bool vtkHardwareSelector::IsPropHit(int id)
{
  return (this->Internals->HitProps.size() == 0 ||
    this->Internals->HitProps.find(id) != this->Internals->HitProps.end());
}

//----------------------------------------------------------------------------
vtkHardwareSelector::PixelInformation vtkHardwareSelector::GetPixelInformation(
  const unsigned int in_display_position[2], int maxDistance,
  unsigned int out_selected_position[2])
{
  assert(in_display_position != out_selected_position);

  // Base case
  unsigned int maxDist = (maxDistance < 0) ? 0 : static_cast<unsigned int>(maxDistance);
  if (maxDist == 0)
    {
    out_selected_position[0] = in_display_position[0];
    out_selected_position[1] = in_display_position[1];
    if (in_display_position[0] < this->Area[0] || in_display_position[0] > this->Area[2] ||
      in_display_position[1] < this->Area[1] || in_display_position[1] > this->Area[3])
      {
      return PixelInformation();
      }

    // offset in_display_position based on the lower-left-corner of the Area.
    unsigned int display_position[2] = {
      in_display_position[0] - this->Area[0],
      in_display_position[1] - this->Area[1]};

    int actorid = this->Convert(display_position, this->PixBuffer[ACTOR_PASS]);
    if (actorid <= 0)
      {
      // the pixel did not hit any actor.
      return PixelInformation();
      }

    PixelInformation info;
    info.Valid = true;

    actorid--;
    info.PropID = actorid;
    info.Prop = this->GetPropFromID(actorid);

    int composite_id = this->Convert(display_position,
      this->PixBuffer[COMPOSITE_INDEX_PASS]);
    if (composite_id < 0 || composite_id > 0xffffff)
      {
      composite_id = 0;
      }
    info.CompositeID = static_cast<unsigned int>(composite_id - ID_OFFSET);

    int low24 = this->Convert(display_position, this->PixBuffer[ID_LOW24]);
    int mid24 = this->Convert(display_position, this->PixBuffer[ID_MID24]);
    int high16 = this->Convert(display_position, this->PixBuffer[ID_HIGH16]);
    // id 0 is reserved for nothing present.
    info.AttributeID = (this->GetID(low24, mid24, high16) - ID_OFFSET);
    if (info.AttributeID < 0)
      {
      // the pixel did not hit any cell.
      return PixelInformation();
      }

    info.ProcessID = this->Convert(display_position[0], display_position[1],
      this->PixBuffer[PROCESS_PASS]);
    info.ProcessID--;
    return info;
    }

  // Iterate over successively growing boxes.
  // They recursively call the base case to handle single pixels.
  unsigned int disp_pos[2] = {in_display_position[0], in_display_position[1]};
  unsigned int cur_pos[2] = {0, 0};
  PixelInformation info;
  info = this->GetPixelInformation(in_display_position, 0, out_selected_position);
  if (info.Valid)
    {
    return info;
    }
  for (unsigned int dist = 1; dist < maxDist; ++dist)
    {
    // Vertical sides of box.
    for (unsigned int y = ((disp_pos[1] > dist) ? (disp_pos[1] - dist) : 0); y <= disp_pos[1] + dist; ++y)
      {
      cur_pos[1] = y;
      if (disp_pos[0] >= dist)
        {
        cur_pos[0] = disp_pos[0] - dist;
        info = this->GetPixelInformation(cur_pos, 0, out_selected_position);
        if (info.Valid)
          {
          return info;
          }
        }
      cur_pos[0] = disp_pos[0] + dist;
      info = this->GetPixelInformation(cur_pos, 0, out_selected_position);
      if (info.Valid)
        {
        return info;
        }
      }
    // Horizontal sides of box.
    for (unsigned int x = ((disp_pos[0] >= dist) ? (disp_pos[0] - (dist-1)) : 0); x <= disp_pos[0] + (dist-1); ++x)
      {
      cur_pos[0] = x;
      if (disp_pos[1] >= dist)
        {
        cur_pos[1] = disp_pos[1] - dist;
        info = this->GetPixelInformation(cur_pos, 0, out_selected_position);
        if (info.Valid)
          {
          return info;
          }
        }
      cur_pos[1] = disp_pos[1] + dist;
      info = this->GetPixelInformation(cur_pos, 0, out_selected_position);
      if (info.Valid)
        {
        return info;
        }
      }
    }

  // nothing hit.
  out_selected_position[0] = in_display_position[0];
  out_selected_position[1] = in_display_position[1];
  return PixelInformation();
}

//----------------------------------------------------------------------------
vtkSelection* vtkHardwareSelector::GenerateSelection(
  unsigned int x1, unsigned int y1,
  unsigned int x2, unsigned int y2)
{
  vtkInternals::MapOfAttributeIds dataMap;
  vtkInternals::PixelCountType pixelCounts;

  for (unsigned int yy = y1; yy <= y2; yy++)
    {
    for (unsigned int xx = x1; xx <= x2; xx++)
      {
      unsigned int pos[2] = {xx, yy};
      PixelInformation info = this->GetPixelInformation(pos, 0);
      if (info.Valid)
        {
        dataMap[info].insert(info.AttributeID);
        pixelCounts[info]++;
        }
      }
    }
  return this->Internals->ConvertSelection(
    this->FieldAssociation, dataMap, pixelCounts);
}

//----------------------------------------------------------------------------
vtkSelection* vtkHardwareSelector::GeneratePolygonSelection(
  int* polygonPoints, vtkIdType count)
{
  // we need at least three points (x,y) for a polygon selection.
  if(!polygonPoints || count < 6)
    {
    return NULL;
    }

  int x1=VTK_INT_MAX, x2=VTK_INT_MIN, y1=VTK_INT_MAX, y2=VTK_INT_MIN;
  // Get polygon bounds, so that we only check pixels within the bounds
  for(vtkIdType i=0; i<count; i+=2)
    {
    x1 = std::min(polygonPoints[i], x1);
    x2 = std::max(polygonPoints[i], x2);
    y1 = std::min(polygonPoints[i+1], y1);
    y2 = std::max(polygonPoints[i+1], y2);
    }

  vtkInternals::MapOfAttributeIds dataMap;
  vtkInternals::PixelCountType pixelCounts;
  for (int yy = y1; yy <= y2; yy++)
    {
    for (int xx = x1; xx <= x2; xx++)
      {
      if(this->Internals->PixelInsidePolygon(
        xx, yy, polygonPoints, count))
        {
        unsigned int pos[2] = {static_cast<unsigned int>(xx),
          static_cast<unsigned int>(yy)};
        PixelInformation info = this->GetPixelInformation(pos, 0);
        if (info.Valid)
          {
          dataMap[info].insert(info.AttributeID);
          pixelCounts[info]++;
          }
        }
      }
    }
  return this->Internals->ConvertSelection(
    this->FieldAssociation, dataMap, pixelCounts);
}

//----------------------------------------------------------------------------
void vtkHardwareSelector::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "FieldAssociation: ";
  switch (this->FieldAssociation)
    {
  case vtkDataObject::FIELD_ASSOCIATION_POINTS:
    os << "FIELD_ASSOCIATION_POINTS" << endl;
    break;
  case vtkDataObject::FIELD_ASSOCIATION_CELLS:
    os << "FIELD_ASSOCIATION_CELLS" << endl;
    break;
  case vtkDataObject::FIELD_ASSOCIATION_VERTICES:
    os << "FIELD_ASSOCIATION_VERTICES" << endl;
    break;
  case vtkDataObject::FIELD_ASSOCIATION_EDGES:
    os << "FIELD_ASSOCIATION_EDGES" << endl;
    break;
  case vtkDataObject::FIELD_ASSOCIATION_ROWS:
    os << "FIELD_ASSOCIATION_ROWS" << endl;
    break;
  default:
    os << "--unknown--" << endl;
    }
  os << indent << "ProcessID: " << this->ProcessID << endl;
  os << indent << "CurrentPass: " << this->CurrentPass << endl;
  os << indent << "Area: " << this->Area[0] << ", " << this->Area[1] << ", "
    << this->Area[2] << ", " << this->Area[3] << endl;
  os << indent << "Renderer: " << this->Renderer << endl;
  os << indent << "UseProcessIdFromData: " << this->UseProcessIdFromData <<
    endl;
}