BoundingIntervalHierarchy.h 43.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//============================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt 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.
//
//  Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
//  Copyright 2014 UT-Battelle, LLC.
//  Copyright 2014 Los Alamos National Security.
//
//  Under the terms of Contract DE-NA0003525 with NTESS,
//  the U.S. Government retains certain rights in this software.
//
//  Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
//  Laboratory (LANL), the U.S. Government retains certain rights in
//  this software.
//============================================================================

#ifndef vtk_m_cont_BoundingIntervalHierarchy_h
#define vtk_m_cont_BoundingIntervalHierarchy_h

24
25
#include <type_traits>

26
27
28
29
30
31
32
33
34
35
36
37
#include <vtkm/Bounds.h>
#include <vtkm/Types.h>
#include <vtkm/VecFromPortalPermute.h>
#include <vtkm/cont/ArrayHandle.h>
#include <vtkm/cont/ArrayHandleConstant.h>
#include <vtkm/cont/ArrayHandleCounting.h>
#include <vtkm/cont/ArrayHandlePermutation.h>
#include <vtkm/cont/ArrayHandleReverse.h>
#include <vtkm/cont/ArrayHandleTransform.h>
#include <vtkm/cont/BoundingIntervalHierarchyNode.h>
#include <vtkm/cont/CellLocator.h>
#include <vtkm/cont/DeviceAdapterAlgorithm.h>
38
#include <vtkm/cont/ErrorBadDevice.h>
39
#include <vtkm/cont/Timer.h>
40
#include <vtkm/cont/cuda/DeviceAdapterCuda.h>
41
#include <vtkm/cont/internal/DeviceAdapterListHelpers.h>
42
#include <vtkm/exec/BoundingIntervalHierarchyExec.h>
43
44
45
46
47
48
49
50
51
#include <vtkm/worklet/DispatcherMapField.h>
#include <vtkm/worklet/DispatcherMapTopology.h>
#include <vtkm/worklet/WorkletMapField.h>
#include <vtkm/worklet/WorkletMapTopology.h>

namespace vtkm
{
namespace cont
{
52
namespace detail
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
{

#define START_TIMER(x) Timer x;
#define PRINT_TIMER(x, y)                                                                          \
  std::cout << "Step " << x << " time : " << y.GetElapsedTime() << std::endl;
#define Output(x) OutputArray(x, #x);

template <typename T, typename S>
void OutputArray(const vtkm::cont::ArrayHandle<T, S>& outputArray, const char* name = "")
{
  typedef vtkm::cont::internal::Storage<T, S> StorageType;
  typedef typename StorageType::PortalConstType PortalConstType;
  PortalConstType readPortal = outputArray.GetPortalConstControl();
  vtkm::Id numElements = readPortal.GetNumberOfValues();
  std::cout << name << " = " << numElements << " [";
  for (vtkm::Id i = 0; i < numElements; i++)
    std::cout << readPortal.Get(i) << ((i < numElements - 1) ? ", " : "");
  std::cout << "]\n";
}

struct TreeNode
{
  vtkm::Float64 LMax;
  vtkm::Float64 RMin;
  vtkm::IdComponent Dimension;
78
79
80
81
82
83
84

  TreeNode()
    : LMax()
    , RMin()
    , Dimension()
  {
  }
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
}; // struct TreeNode

template <typename S>
void OutputArray(const vtkm::cont::ArrayHandle<TreeNode, S>& outputArray, const char* name = "")
{
  typedef vtkm::cont::internal::Storage<TreeNode, S> StorageType;
  typedef typename StorageType::PortalConstType PortalConstType;
  PortalConstType readPortal = outputArray.GetPortalConstControl();
  vtkm::Id numElements = readPortal.GetNumberOfValues();
  std::cout << name << " = " << numElements << " [";
  for (vtkm::Id i = 0; i < numElements; i++)
  {
    auto n = readPortal.Get(i);
    std::cout << "{ LM = " << n.LMax << ", RM = " << n.RMin << ", D = " << n.Dimension << " }"
              << ((i < numElements - 1) ? ", " : "");
  }
  std::cout << "]\n";
}
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
template <typename S>
void OutputArray(const vtkm::cont::ArrayHandle<BoundingIntervalHierarchyNode, S>& outputArray,
                 const char* name = "")
{
  typedef vtkm::cont::internal::Storage<BoundingIntervalHierarchyNode, S> StorageType;
  typedef typename StorageType::PortalConstType PortalConstType;
  PortalConstType readPortal = outputArray.GetPortalConstControl();
  vtkm::Id numElements = readPortal.GetNumberOfValues();
  std::cout << name << " = " << numElements << " [";
  for (vtkm::Id i = 0; i < numElements; i++)
  {
    auto n = readPortal.Get(i);
    if (n.ChildIndex > 0)
    {
      std::cout << "{ D = " << n.Dimension << ", CI = " << n.ChildIndex << ", LM = " << n.Node.LMax
                << ", RM = " << n.Node.RMin << " }" << ((i < numElements - 1) ? ", " : "");
    }
    else
    {
      std::cout << "{ D = " << n.Dimension << ", CI = " << n.ChildIndex << ", St = " << n.Leaf.Start
                << ", Sz = " << n.Leaf.Size << " }" << ((i < numElements - 1) ? ", " : "");
    }
  }
  std::cout << "]\n";
}

struct SplitProperties
{
  vtkm::Float64 Plane;
  vtkm::Id NumLeftPoints;
  vtkm::Id NumRightPoints;
  vtkm::Float64 LMax;
  vtkm::Float64 RMin;
  vtkm::Float64 Cost;
138
139
140
141
142
143
144
145
146
147

  SplitProperties()
    : Plane()
    , NumLeftPoints()
    , NumRightPoints()
    , LMax()
    , RMin()
    , Cost()
  {
  }
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
}; // struct SplitProperties

struct CellRangesExtracter : public vtkm::worklet::WorkletMapPointToCell
{
  typedef void ControlSignature(CellSetIn,
                                WholeArrayIn<>,
                                FieldOutCell<>,
                                FieldOutCell<>,
                                FieldOutCell<>,
                                FieldOutCell<>,
                                FieldOutCell<>,
                                FieldOutCell<>);
  typedef void ExecutionSignature(_1, PointIndices, _2, _3, _4, _5, _6, _7, _8);

  template <typename CellShape, typename PointIndicesVec, typename PointsPortal>
  VTKM_EXEC void operator()(CellShape vtkmNotUsed(shape),
                            const PointIndicesVec& pointIndices,
                            const PointsPortal& points,
                            vtkm::Range& rangeX,
                            vtkm::Range& rangeY,
                            vtkm::Range& rangeZ,
                            vtkm::Float64& centerX,
                            vtkm::Float64& centerY,
                            vtkm::Float64& centerZ) const
  {
    vtkm::Bounds bounds;
    vtkm::VecFromPortalPermute<PointIndicesVec, PointsPortal> cellPoints(&pointIndices, points);
    vtkm::IdComponent numPoints = cellPoints.GetNumberOfComponents();
    for (vtkm::IdComponent i = 0; i < numPoints; ++i)
    {
      bounds.Include(cellPoints[i]);
    }
    rangeX = bounds.X;
    rangeY = bounds.Y;
    rangeZ = bounds.Z;
    vtkm::Vec<vtkm::Float64, 3> center = bounds.Center();
    centerX = center[0];
    centerY = center[1];
    centerZ = center[2];
  }
}; // struct CellRangesExtracter

struct LEQWorklet : public vtkm::worklet::WorkletMapField
{
public:
  typedef void ControlSignature(FieldIn<>, FieldIn<>, FieldOut<>, FieldOut<>);
  typedef void ExecutionSignature(_1, _2, _3, _4);
  using InputDomain = _1;

  VTKM_EXEC
  void operator()(const vtkm::Float64& value,
                  const vtkm::Float64& planeValue,
                  vtkm::Id& leq,
                  vtkm::Id& r) const
  {
    leq = value <= planeValue;
    r = !leq;
  }
}; // struct LEQWorklet

template <bool LEQ>
struct FilterRanges : public vtkm::worklet::WorkletMapField
{
public:
  typedef void ControlSignature(FieldIn<>, FieldIn<>, FieldIn<>, FieldOut<>);
  typedef void ExecutionSignature(_1, _2, _3, _4);
  using InputDomain = _1;

  VTKM_EXEC
  void operator()(const vtkm::Float64& value,
                  const vtkm::Float64& planeValue,
                  const vtkm::Range& cellBounds,
                  vtkm::Range& outBounds) const
  {
    if (LEQ)
    {
      outBounds = (value <= planeValue) ? cellBounds : vtkm::Range();
    }
    else
    {
      outBounds = (value > planeValue) ? cellBounds : vtkm::Range();
    }
  }
}; // struct FilterRanges

struct SplitPlaneCalculatorWorklet : public vtkm::worklet::WorkletMapField
{
public:
  typedef void ControlSignature(FieldIn<>, FieldOut<>);
  typedef void ExecutionSignature(_1, _2);
  using InputDomain = _1;

  VTKM_CONT
  SplitPlaneCalculatorWorklet(vtkm::IdComponent planeIdx, vtkm::IdComponent numPlanes)
    : Scale(static_cast<vtkm::Float64>(planeIdx + 1) / static_cast<vtkm::Float64>(numPlanes + 1))
  {
  }

  VTKM_EXEC
  void operator()(const vtkm::Range& range, vtkm::Float64& splitPlane) const
  {
    splitPlane = range.Min + Scale * (range.Max - range.Min);
  }

  vtkm::Float64 Scale;
};

struct SplitPropertiesCalculator : public vtkm::worklet::WorkletMapField
{
public:
  typedef void ControlSignature(FieldIn<>,
                                FieldIn<>,
                                FieldIn<>,
                                FieldIn<>,
                                FieldIn<>,
                                WholeArrayInOut<>);
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, InputIndex);
  using InputDomain = _1;

  VTKM_CONT
  SplitPropertiesCalculator(vtkm::IdComponent index, vtkm::Id stride)
    : Index(index)
    , Stride(stride)
  {
  }

  template <typename SplitPropertiesPortal>
  VTKM_EXEC void operator()(const vtkm::Id& pointsToLeft,
                            const vtkm::Id& pointsToRight,
                            const vtkm::Range& lMaxRanges,
                            const vtkm::Range& rMinRanges,
                            const vtkm::Float64& planeValue,
                            SplitPropertiesPortal& splits,
                            vtkm::Id inputIndex) const
  {
    SplitProperties split;
    split.Plane = planeValue;
    split.NumLeftPoints = pointsToLeft;
    split.NumRightPoints = pointsToRight;
    split.LMax = lMaxRanges.Max;
    split.RMin = rMinRanges.Min;
    split.Cost = vtkm::Abs(split.LMax * static_cast<vtkm::Float64>(pointsToLeft) -
                           split.RMin * static_cast<vtkm::Float64>(pointsToRight));
    if (vtkm::IsNan(split.Cost))
    {
      split.Cost = vtkm::Infinity64();
    }
    splits.Set(inputIndex * Stride + Index, split);
    //printf("Plane = %lf, NL = %lld, NR = %lld, LM = %lf, RM = %lf, C = %lf\n", split.Plane, split.NumLeftPoints, split.NumRightPoints, split.LMax, split.RMin, split.Cost);
  }

  vtkm::IdComponent Index;
  vtkm::Id Stride;
};

struct SplitSelector : public vtkm::worklet::WorkletMapField
{
public:
  typedef void ControlSignature(FieldIn<>,
                                WholeArrayIn<>,
                                WholeArrayIn<>,
                                WholeArrayIn<>,
                                FieldIn<>,
                                FieldOut<>,
                                FieldOut<>,
                                FieldOut<>);
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7, _8);
  using InputDomain = _1;

  VTKM_CONT
  SplitSelector(vtkm::IdComponent numPlanes,
                vtkm::IdComponent maxLeafSize,
                vtkm::IdComponent stride)
    : NumPlanes(numPlanes)
    , MaxLeafSize(maxLeafSize)
    , Stride(stride)
  {
  }

  template <typename SplitPropertiesPortal>
  VTKM_EXEC void operator()(vtkm::Id index,
                            const SplitPropertiesPortal& xSplits,
                            const SplitPropertiesPortal& ySplits,
                            const SplitPropertiesPortal& zSplits,
                            const vtkm::Id& segmentSize,
                            TreeNode& node,
                            vtkm::Float64& plane,
                            vtkm::Id& choice) const
  {
    if (segmentSize <= MaxLeafSize)
    {
      node.Dimension = -1;
      choice = 0;
      return;
    }
    choice = 1;
    using Split = SplitProperties;
    vtkm::Float64 minCost = vtkm::Infinity64();
    const Split& xSplit = xSplits[ArgMin(xSplits, index * Stride, Stride)];
    bool found = false;
    if (xSplit.Cost < minCost && xSplit.NumLeftPoints != 0 && xSplit.NumRightPoints != 0)
    {
      minCost = xSplit.Cost;
      node.Dimension = 0;
      node.LMax = xSplit.LMax;
      node.RMin = xSplit.RMin;
      plane = xSplit.Plane;
      found = true;
    }
    const Split& ySplit = ySplits[ArgMin(ySplits, index * Stride, Stride)];
    if (ySplit.Cost < minCost && ySplit.NumLeftPoints != 0 && ySplit.NumRightPoints != 0)
    {
      minCost = ySplit.Cost;
      node.Dimension = 1;
      node.LMax = ySplit.LMax;
      node.RMin = ySplit.RMin;
      plane = ySplit.Plane;
      found = true;
    }
    const Split& zSplit = zSplits[ArgMin(zSplits, index * Stride, Stride)];
    if (zSplit.Cost < minCost && zSplit.NumLeftPoints != 0 && zSplit.NumRightPoints != 0)
    {
      minCost = zSplit.Cost;
      node.Dimension = 2;
      node.LMax = zSplit.LMax;
      node.RMin = zSplit.RMin;
      plane = zSplit.Plane;
      found = true;
    }
    if (!found)
    {
      const Split& xMSplit = xSplits[NumPlanes];
      minCost = xMSplit.Cost;
      node.Dimension = 0;
      node.LMax = xMSplit.LMax;
      node.RMin = xMSplit.RMin;
      plane = xMSplit.Plane;
      const Split& yMSplit = ySplits[NumPlanes];
      if (yMSplit.Cost < minCost && yMSplit.NumLeftPoints != 0 && yMSplit.NumRightPoints != 0)
      {
        minCost = yMSplit.Cost;
        node.Dimension = 1;
        node.LMax = yMSplit.LMax;
        node.RMin = yMSplit.RMin;
        plane = yMSplit.Plane;
      }
      const Split& zMSplit = zSplits[NumPlanes];
      if (zMSplit.Cost < minCost && zMSplit.NumLeftPoints != 0 && zMSplit.NumRightPoints != 0)
      {
        minCost = zMSplit.Cost;
        node.Dimension = 2;
        node.LMax = zMSplit.LMax;
        node.RMin = zMSplit.RMin;
        plane = zMSplit.Plane;
      }
    }
    //printf("Selected plane %lf, with cost %lf [%d, %lf, %lf]\n", plane, minCost, node.Dimension, node.LMax, node.RMin);
  }

  template <typename ArrayPortal>
  VTKM_EXEC vtkm::Id ArgMin(const ArrayPortal& values, vtkm::Id start, vtkm::Id length) const
  {
    vtkm::Id minIdx = start;
    for (vtkm::Id i = start; i < (start + length); ++i)
    {
      if (values[i].Cost < values[minIdx].Cost)
      {
        minIdx = i;
      }
    }
    return minIdx;
  }

  vtkm::IdComponent NumPlanes;
  vtkm::IdComponent MaxLeafSize;
  vtkm::Id Stride;
};

struct CalculateSplitDirectionFlag : public vtkm::worklet::WorkletMapField
{
  typedef void ControlSignature(FieldIn<>, FieldIn<>, FieldIn<>, FieldIn<>, FieldIn<>, FieldOut<>);
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6);
  using InputDomain = _1;

  VTKM_EXEC
  void operator()(const vtkm::Float64& x,
                  const vtkm::Float64& y,
                  const vtkm::Float64& z,
                  const TreeNode& split,
                  const vtkm::Float64& plane,
                  vtkm::Id& flag) const
  {
    if (split.Dimension >= 0)
    {
      const vtkm::Vec<vtkm::Float64, 3> point(x, y, z);
      const vtkm::Float64& c = point[split.Dimension];
      // We use 0 to signify left child, 1 for right child
      flag = 1 - static_cast<vtkm::Id>(c <= plane);
    }
    else
    {
      flag = 0;
    }
  }
}; // struct CalculateSplitDirectionFlag

struct SegmentSplitter : public vtkm::worklet::WorkletMapField
{
  typedef void ControlSignature(FieldIn<>, FieldIn<>, FieldIn<>, FieldOut<>);
  typedef void ExecutionSignature(_1, _2, _3, _4);
  using InputDomain = _1;

  VTKM_CONT
  SegmentSplitter(vtkm::IdComponent maxLeafSize)
    : MaxLeafSize(maxLeafSize)
  {
  }

  VTKM_EXEC
  void operator()(const vtkm::Id& segmentId,
                  const vtkm::Id& leqFlag,
                  const vtkm::Id& segmentSize,
                  vtkm::Id& newSegmentId) const
  {
    if (segmentSize <= MaxLeafSize)
    {
      // We do not split the segments which have cells fewer than MaxLeafSize, moving them to left
      newSegmentId = 2 * segmentId;
    }
    else
    {
      newSegmentId = 2 * segmentId + leqFlag;
    }
  }

  vtkm::IdComponent MaxLeafSize;
}; // struct SegmentSplitter

struct SplitIndicesCalculator : public vtkm::worklet::WorkletMapField
{
public:
  typedef void ControlSignature(FieldIn<>, FieldIn<>, FieldIn<>, FieldIn<>, FieldIn<>, FieldOut<>);
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6);
  using InputDomain = _1;

  VTKM_EXEC
  void operator()(const vtkm::Id& leqFlag,
                  const vtkm::Id& trueFlagCount,
                  const vtkm::Id& countPreviousSegment,
                  const vtkm::Id& runningFalseFlagCount,
                  const vtkm::Id& totalFalseFlagCount,
                  vtkm::Id& scatterIndex) const
  {
    if (leqFlag)
    {
      scatterIndex = countPreviousSegment + totalFalseFlagCount + trueFlagCount;
    }
    else
    {
      scatterIndex = countPreviousSegment + runningFalseFlagCount - 1;
    }
  }
}; // struct SplitIndicesCalculator

struct Scatter : public vtkm::worklet::WorkletMapField
{
  typedef void ControlSignature(FieldIn<>, FieldIn<>, WholeArrayOut<>);
  typedef void ExecutionSignature(_1, _2, _3);
  using InputDomain = _1;

  template <typename InputType, typename OutputPortalType>
  VTKM_EXEC void operator()(const InputType& in, const vtkm::Id& idx, OutputPortalType& out) const
  {
    out.Set(idx, in);
  }
}; // struct Scatter

template <typename ValueArrayHandle, typename IndexArrayHandle>
ValueArrayHandle ScatterArray(const ValueArrayHandle& input, const IndexArrayHandle& indices)
{
  ValueArrayHandle output;
  output.Allocate(input.GetNumberOfValues());
  vtkm::worklet::DispatcherMapField<Scatter>().Invoke(input, indices, output);
  return output;
}

struct NonSplitIndexCalculator : public vtkm::worklet::WorkletMapField
{
  typedef void ControlSignature(FieldIn<>, FieldOut<>);
  typedef void ExecutionSignature(_1, _2);
  using InputDomain = _1;

  VTKM_CONT
  NonSplitIndexCalculator(vtkm::IdComponent maxLeafSize)
    : MaxLeafSize(maxLeafSize)
  {
  }

  VTKM_EXEC void operator()(const vtkm::Id& inSegmentSize, vtkm::Id& outSegmentSize) const
  {
    if (inSegmentSize <= MaxLeafSize)
    {
      outSegmentSize = inSegmentSize;
    }
    else
    {
      outSegmentSize = 0;
    }
  }

  vtkm::Id MaxLeafSize;
}; // struct NonSplitIndexCalculator

struct TreeLevelAdder : public vtkm::worklet::WorkletMapField
{
  typedef void ControlSignature(FieldIn<>,
                                FieldIn<>,
                                FieldIn<>,
                                FieldIn<>,
                                FieldIn<>,
                                WholeArrayInOut<>);
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6);
  using InputDomain = _1;

  VTKM_CONT
  TreeLevelAdder(vtkm::Id cellIdsOffset, vtkm::Id treeOffset, vtkm::IdComponent maxLeafSize)
    : CellIdsOffset(cellIdsOffset)
    , TreeOffset(treeOffset)
    , MaxLeafSize(maxLeafSize)
  {
  }

  template <typename BoundingIntervalHierarchyPortal>
  VTKM_EXEC void operator()(const vtkm::Id& index,
                            const TreeNode& split,
                            const vtkm::Id& start,
                            const vtkm::Id& count,
                            const vtkm::Id& numPreviousSplits,
                            BoundingIntervalHierarchyPortal& treePortal) const
  {
    BoundingIntervalHierarchyNode node;
    if (count > MaxLeafSize)
    {
      node.Dimension = split.Dimension;
      node.ChildIndex = TreeOffset + 2 * numPreviousSplits;
      node.Node.LMax = split.LMax;
      node.Node.RMin = split.RMin;
    }
    else
    {
      node.ChildIndex = -1;
      node.Leaf.Start = CellIdsOffset + start;
      node.Leaf.Size = count;
    }
    treePortal.Set(index, node);
  }

  vtkm::Id CellIdsOffset;
  vtkm::Id TreeOffset;
  vtkm::IdComponent MaxLeafSize;
}; // struct TreeLevelAdder

template <typename T, class BinaryFunctor, typename DeviceAdapter>
vtkm::cont::ArrayHandle<T> ReverseScanInclusiveByKey(const vtkm::cont::ArrayHandle<T>& keys,
                                                     const vtkm::cont::ArrayHandle<T>& values,
                                                     BinaryFunctor binaryFunctor,
                                                     DeviceAdapter)
{
  using Algorithms = typename vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter>;

  vtkm::cont::ArrayHandle<T> result;
  auto reversedResult = vtkm::cont::make_ArrayHandleReverse(result);

  Algorithms::ScanInclusiveByKey(vtkm::cont::make_ArrayHandleReverse(keys),
                                 vtkm::cont::make_ArrayHandleReverse(values),
                                 reversedResult,
                                 binaryFunctor);

  return result;
}

template <typename T, typename U, typename DeviceAdapter>
vtkm::cont::ArrayHandle<T> CopyIfArray(const vtkm::cont::ArrayHandle<T>& input,
                                       const vtkm::cont::ArrayHandle<U>& stencil,
                                       DeviceAdapter)
{
  using Algorithms = typename vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter>;

  vtkm::cont::ArrayHandle<T> result;
  Algorithms::CopyIf(input, stencil, result);

  return result;
}

VTKM_CONT
struct Invert
{
  VTKM_EXEC
  vtkm::Id operator()(const vtkm::Id& value) const { return 1 - value; }
}; // struct Invert

VTKM_CONT
struct RangeAdd
{
  VTKM_EXEC
  vtkm::Range operator()(const vtkm::Range& accumulator, const vtkm::Range& value) const
  {
    if (value.IsNonEmpty())
    {
      return accumulator.Union(value);
    }
    else
    {
      return accumulator;
    }
  }
}; // struct RangeAdd

666
} // namespace detail
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681


class BoundingIntervalHierarchy : public vtkm::cont::CellLocator
{
private:
  using IdArrayHandle = vtkm::cont::ArrayHandle<vtkm::Id>;
  using IdPermutationArrayHandle = vtkm::cont::ArrayHandlePermutation<IdArrayHandle, IdArrayHandle>;
  using BoundsArrayHandle = vtkm::cont::ArrayHandle<vtkm::Bounds>;
  using CoordsArrayHandle = vtkm::cont::ArrayHandle<vtkm::Float64>;
  using CoordsPermutationArrayHandle =
    vtkm::cont::ArrayHandlePermutation<IdArrayHandle, CoordsArrayHandle>;
  using CountingIdArrayHandle = vtkm::cont::ArrayHandleCounting<vtkm::Id>;
  using RangeArrayHandle = vtkm::cont::ArrayHandle<vtkm::Range>;
  using RangePermutationArrayHandle =
    vtkm::cont::ArrayHandlePermutation<IdArrayHandle, RangeArrayHandle>;
682
  using SplitArrayHandle = vtkm::cont::ArrayHandle<detail::TreeNode>;
683
684
  using SplitPermutationArrayHandle =
    vtkm::cont::ArrayHandlePermutation<IdArrayHandle, SplitArrayHandle>;
685
  using SplitPropertiesArrayHandle = vtkm::cont::ArrayHandle<detail::SplitProperties>;
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

  class BuildFunctor
  {
  protected:
    BoundingIntervalHierarchy* Self;

  public:
    VTKM_CONT
    BuildFunctor(BoundingIntervalHierarchy* self)
      : Self(self)
    {
    }

    template <typename DeviceAdapter>
    VTKM_CONT bool operator()(DeviceAdapter)
    {
      VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapter);
      // Accomodate into a Functor, so that this could be used with TryExecute
      using Algorithms = typename vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter>;
      using Timer = typename vtkm::cont::Timer<DeviceAdapter>;

      Timer totalTimer;

      vtkm::cont::DynamicCellSet cellSet = Self->GetCellSet();
      vtkm::Id numCells = cellSet.GetNumberOfCells();
711
      vtkm::cont::CoordinateSystem coords = Self->GetCoordinates();
712
713
      vtkm::cont::ArrayHandleVirtualCoordinates points = coords.GetData();

714
715
716
      //std::cout << "No of cells: " << numCells << "\n";
      //std::cout.precision(3);
      //START_TIMER(s11);
717
718
719
720
      IdArrayHandle cellIds;
      Algorithms::Copy(CountingIdArrayHandle(0, 1, numCells), cellIds);
      IdArrayHandle segmentIds;
      Algorithms::Copy(vtkm::cont::ArrayHandleConstant<vtkm::Id>(0, numCells), segmentIds);
721
      //PRINT_TIMER("1.1", s11);
722

723
      //START_TIMER(s12);
724
725
      CoordsArrayHandle centerXs, centerYs, centerZs;
      RangeArrayHandle xRanges, yRanges, zRanges;
726
      vtkm::worklet::DispatcherMapTopology<detail::CellRangesExtracter, DeviceAdapter>().Invoke(
727
        cellSet, points, xRanges, yRanges, zRanges, centerXs, centerYs, centerZs);
728
      //PRINT_TIMER("1.2", s12);
729
730

      bool done = false;
731
      //vtkm::IdComponent iteration = 0;
732
733
734
735
736
737
738
739
740
741
742
743
      vtkm::Id nodesIndexOffset = 0;
      vtkm::Id numSegments = 1;
      IdArrayHandle discardKeys;
      IdArrayHandle segmentStarts;
      IdArrayHandle segmentSizes;
      segmentSizes.Allocate(1);
      segmentSizes.GetPortalControl().Set(0, numCells);
      Self->ProcessedCellIds.Allocate(numCells);
      vtkm::Id cellIdsOffset = 0;

      while (!done)
      {
744
        //std::cout << "**** Iteration " << (++iteration) << " ****\n";
745
746
747
        Timer iterationTimer;

        //Output(segmentSizes);
748
        //START_TIMER(s21);
749
750
751
752
753
        // Calculate the X, Y, Z bounding ranges for each segment
        RangeArrayHandle perSegmentXRanges, perSegmentYRanges, perSegmentZRanges;
        Algorithms::ReduceByKey(segmentIds, xRanges, discardKeys, perSegmentXRanges, vtkm::Add());
        Algorithms::ReduceByKey(segmentIds, yRanges, discardKeys, perSegmentYRanges, vtkm::Add());
        Algorithms::ReduceByKey(segmentIds, zRanges, discardKeys, perSegmentZRanges, vtkm::Add());
754
        //PRINT_TIMER("2.1", s21);
755
756
757
758
759
760

        // Expand the per segment bounding ranges, to per cell;
        RangePermutationArrayHandle segmentXRanges(segmentIds, perSegmentXRanges);
        RangePermutationArrayHandle segmentYRanges(segmentIds, perSegmentYRanges);
        RangePermutationArrayHandle segmentZRanges(segmentIds, perSegmentZRanges);

761
        //START_TIMER(s22);
762
763
        // Calculate split costs for NumPlanes split planes, across X, Y and Z dimensions
        vtkm::Id numSplitPlanes = numSegments * (Self->NumPlanes + 1);
764
        vtkm::cont::ArrayHandle<detail::SplitProperties> xSplits, ySplits, zSplits;
765
766
767
768
769
770
771
772
773
        xSplits.Allocate(numSplitPlanes);
        ySplits.Allocate(numSplitPlanes);
        zSplits.Allocate(numSplitPlanes);
        Self->CalculateSplitCosts(
          segmentXRanges, xRanges, centerXs, segmentIds, xSplits, DeviceAdapter());
        Self->CalculateSplitCosts(
          segmentYRanges, yRanges, centerYs, segmentIds, ySplits, DeviceAdapter());
        Self->CalculateSplitCosts(
          segmentZRanges, zRanges, centerZs, segmentIds, zSplits, DeviceAdapter());
774
        //PRINT_TIMER("2.2", s22);
775

776
        //START_TIMER(s23);
777
778
779
780
        // Select best split plane and dimension across X, Y, Z dimension, per segment
        SplitArrayHandle segmentSplits;
        vtkm::cont::ArrayHandle<vtkm::Float64> segmentPlanes;
        vtkm::cont::ArrayHandle<vtkm::Id> splitChoices;
781
782
        detail::SplitSelector worklet(Self->NumPlanes, Self->MaxLeafSize, Self->NumPlanes + 1);
        vtkm::worklet::DispatcherMapField<detail::SplitSelector> splitSelectorDispatcher(worklet);
783
784
785
786
787
788
789
790
791
        CountingIdArrayHandle indices(0, 1, numSegments);
        splitSelectorDispatcher.Invoke(indices,
                                       xSplits,
                                       ySplits,
                                       zSplits,
                                       segmentSizes,
                                       segmentSplits,
                                       segmentPlanes,
                                       splitChoices);
792
        //PRINT_TIMER("2.3", s23);
793
794
795
796
797

        // Expand the per segment split plane to per cell
        SplitPermutationArrayHandle splits(segmentIds, segmentSplits);
        CoordsPermutationArrayHandle planes(segmentIds, segmentPlanes);

798
        //START_TIMER(s31);
799
        IdArrayHandle leqFlags;
800
801
        vtkm::worklet::DispatcherMapField<detail::CalculateSplitDirectionFlag>
          computeFlagDispatcher;
802
        computeFlagDispatcher.Invoke(centerXs, centerYs, centerZs, splits, planes, leqFlags);
803
        //PRINT_TIMER("3.1", s31);
804

805
        //START_TIMER(s32);
806
807
808
809
        IdArrayHandle scatterIndices =
          Self->CalculateSplitScatterIndices(cellIds, leqFlags, segmentIds, DeviceAdapter());
        IdArrayHandle newSegmentIds;
        IdPermutationArrayHandle sizes(segmentIds, segmentSizes);
810
811
        vtkm::worklet::DispatcherMapField<detail::SegmentSplitter>(
          detail::SegmentSplitter(Self->MaxLeafSize))
812
          .Invoke(segmentIds, leqFlags, sizes, newSegmentIds);
813
        //PRINT_TIMER("3.2", s32);
814

815
        //START_TIMER(s33);
816
817
        vtkm::cont::ArrayHandle<vtkm::Id> choices;
        Algorithms::Copy(IdPermutationArrayHandle(segmentIds, splitChoices), choices);
818
819
820
821
822
823
824
825
826
827
        cellIds = detail::ScatterArray(cellIds, scatterIndices);
        segmentIds = detail::ScatterArray(segmentIds, scatterIndices);
        newSegmentIds = detail::ScatterArray(newSegmentIds, scatterIndices);
        xRanges = detail::ScatterArray(xRanges, scatterIndices);
        yRanges = detail::ScatterArray(yRanges, scatterIndices);
        zRanges = detail::ScatterArray(zRanges, scatterIndices);
        centerXs = detail::ScatterArray(centerXs, scatterIndices);
        centerYs = detail::ScatterArray(centerYs, scatterIndices);
        centerZs = detail::ScatterArray(centerZs, scatterIndices);
        choices = detail::ScatterArray(choices, scatterIndices);
828
        //PRINT_TIMER("3.3", s33);
829
830

        // Move the cell ids at leafs to the processed cellids list
831
        //START_TIMER(s41);
832
        IdArrayHandle nonSplitSegmentSizes;
833
834
        vtkm::worklet::DispatcherMapField<detail::NonSplitIndexCalculator>(
          detail::NonSplitIndexCalculator(Self->MaxLeafSize))
835
836
837
838
839
          .Invoke(segmentSizes, nonSplitSegmentSizes);
        IdArrayHandle nonSplitSegmentIndices;
        Algorithms::ScanExclusive(nonSplitSegmentSizes, nonSplitSegmentIndices);
        IdArrayHandle runningSplitSegmentCounts;
        Algorithms::ScanExclusive(splitChoices, runningSplitSegmentCounts);
840
        //PRINT_TIMER("4.1", s41);
841

842
        //START_TIMER(s42);
843
        IdArrayHandle doneCellIds;
844
        Algorithms::CopyIf(cellIds, choices, doneCellIds, detail::Invert());
845
846
847
        Algorithms::CopySubRange(
          doneCellIds, 0, doneCellIds.GetNumberOfValues(), Self->ProcessedCellIds, cellIdsOffset);

848
849
850
851
852
853
854
855
        cellIds = detail::CopyIfArray(cellIds, choices, DeviceAdapter());
        newSegmentIds = detail::CopyIfArray(newSegmentIds, choices, DeviceAdapter());
        xRanges = detail::CopyIfArray(xRanges, choices, DeviceAdapter());
        yRanges = detail::CopyIfArray(yRanges, choices, DeviceAdapter());
        zRanges = detail::CopyIfArray(zRanges, choices, DeviceAdapter());
        centerXs = detail::CopyIfArray(centerXs, choices, DeviceAdapter());
        centerYs = detail::CopyIfArray(centerYs, choices, DeviceAdapter());
        centerZs = detail::CopyIfArray(centerZs, choices, DeviceAdapter());
856
        //PRINT_TIMER("4.2", s42);
857

858
        //START_TIMER(s43);
859
860
861
862
863
864
865
        // Make a new nodes with enough nodes for the currnt level, copying over the old one
        vtkm::Id nodesSize = Self->Nodes.GetNumberOfValues() + numSegments;
        vtkm::cont::ArrayHandle<BoundingIntervalHierarchyNode> newTree;
        newTree.Allocate(nodesSize);
        Algorithms::CopySubRange(Self->Nodes, 0, Self->Nodes.GetNumberOfValues(), newTree);

        CountingIdArrayHandle nodesIndices(nodesIndexOffset, 1, numSegments);
866
867
        detail::TreeLevelAdder nodesAdder(cellIdsOffset, nodesSize, Self->MaxLeafSize);
        vtkm::worklet::DispatcherMapField<detail::TreeLevelAdder>(nodesAdder)
868
869
870
871
872
873
874
875
876
          .Invoke(nodesIndices,
                  segmentSplits,
                  nonSplitSegmentIndices,
                  segmentSizes,
                  runningSplitSegmentCounts,
                  newTree);
        nodesIndexOffset = nodesSize;
        cellIdsOffset += doneCellIds.GetNumberOfValues();
        Self->Nodes = newTree;
877
878
        //PRINT_TIMER("4.3", s43);
        //START_TIMER(s51);
879
880
881
882
883
884
885
886
887
888
        segmentIds = newSegmentIds;
        segmentSizes =
          Self->CalculateSegmentSizes<DeviceAdapter>(segmentIds, segmentIds.GetNumberOfValues());
        segmentIds =
          Self->GenerateSegmentIds<DeviceAdapter>(segmentSizes, segmentIds.GetNumberOfValues());
        IdArrayHandle uniqueSegmentIds;
        Algorithms::Copy(segmentIds, uniqueSegmentIds);
        Algorithms::Unique(uniqueSegmentIds);
        numSegments = uniqueSegmentIds.GetNumberOfValues();
        done = segmentIds.GetNumberOfValues() == 0;
889
890
        //PRINT_TIMER("5.1", s51);
        //std::cout << "Iteration time: " << iterationTimer.GetElapsedTime() << "\n";
891
      }
892
      //std::cout << "Total time: " << totalTimer.GetElapsedTime() << "\n";
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
      return true;
    }
  };

  template <typename DeviceAdapter>
  VTKM_CONT IdArrayHandle CalculateSegmentSizes(const IdArrayHandle& segmentIds, vtkm::Id numCells)
  {
    using Algorithms = typename vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter>;
    IdArrayHandle discardKeys;
    IdArrayHandle segmentSizes;
    Algorithms::ReduceByKey(segmentIds,
                            vtkm::cont::ArrayHandleConstant<vtkm::Id>(1, numCells),
                            discardKeys,
                            segmentSizes,
                            vtkm::Add());
    return segmentSizes;
  }

  template <typename DeviceAdapter>
  VTKM_CONT IdArrayHandle GenerateSegmentIds(const IdArrayHandle& segmentSizes, vtkm::Id numCells)
  {
    // Compact segment ids, removing non-contiguous values.
    using Algorithms = typename vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter>;
    // 1. Perform ScanInclusive to calculate the end positions of each segment
    IdArrayHandle segmentEnds;
    Algorithms::ScanInclusive(segmentSizes, segmentEnds);
    // 2. Perform UpperBounds to perform the final compaction.
    IdArrayHandle segmentIds;
    Algorithms::UpperBounds(
      segmentEnds, vtkm::cont::ArrayHandleCounting<vtkm::Id>(0, 1, numCells), segmentIds);
    return segmentIds;
  }

  template <typename SegmentRangeArrayHandle, typename RangeArrayHandle, typename DeviceAdapter>
  VTKM_CONT void CalculateSplitCosts(SegmentRangeArrayHandle segmentRanges,
                                     RangeArrayHandle ranges,
                                     CoordsArrayHandle& coords,
                                     IdArrayHandle& segmentIds,
931
                                     vtkm::cont::ArrayHandle<detail::SplitProperties>& splits,
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
                                     DeviceAdapter)
  {
    for (vtkm::IdComponent planeIndex = 0; planeIndex < NumPlanes; ++planeIndex)
    {
      CalculatePlaneSplitCost(planeIndex,
                              NumPlanes,
                              segmentRanges,
                              ranges,
                              coords,
                              segmentIds,
                              splits,
                              planeIndex,
                              DeviceAdapter());
    }
    // Calculate median costs
    CalculatePlaneSplitCost(
      0, 1, segmentRanges, ranges, coords, segmentIds, splits, NumPlanes, DeviceAdapter());
  }

  template <typename SegmentRangeArrayHandle, typename RangeArrayHandle, typename DeviceAdapter>
  VTKM_CONT void CalculatePlaneSplitCost(vtkm::IdComponent planeIndex,
                                         vtkm::IdComponent numPlanes,
                                         SegmentRangeArrayHandle segmentRanges,
                                         RangeArrayHandle ranges,
                                         CoordsArrayHandle& coords,
                                         IdArrayHandle& segmentIds,
958
                                         vtkm::cont::ArrayHandle<detail::SplitProperties>& splits,
959
960
961
962
963
964
                                         vtkm::IdComponent index,
                                         DeviceAdapter)
  {
    using Algorithms = typename vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter>;
    // Make candidate split plane array
    vtkm::cont::ArrayHandle<vtkm::Float64> splitPlanes;
965
966
967
    detail::SplitPlaneCalculatorWorklet splitPlaneCalcWorklet(planeIndex, numPlanes);
    vtkm::worklet::DispatcherMapField<detail::SplitPlaneCalculatorWorklet, DeviceAdapter>
      splitDispatcher(splitPlaneCalcWorklet);
968
969
970
971
    splitDispatcher.Invoke(segmentRanges, splitPlanes);

    // Check if a point is to the left of the split plane or right
    vtkm::cont::ArrayHandle<vtkm::Id> isLEQOfSplitPlane, isROfSplitPlane;
972
    vtkm::worklet::DispatcherMapField<detail::LEQWorklet, DeviceAdapter>().Invoke(
973
974
975
976
977
978
979
980
981
982
983
984
985
986
      coords, splitPlanes, isLEQOfSplitPlane, isROfSplitPlane);

    // Count of points to the left
    vtkm::cont::ArrayHandle<vtkm::Id> pointsToLeft;
    IdArrayHandle discardKeys;
    Algorithms::ReduceByKey(segmentIds, isLEQOfSplitPlane, discardKeys, pointsToLeft, vtkm::Add());

    // Count of points to the right
    vtkm::cont::ArrayHandle<vtkm::Id> pointsToRight;
    Algorithms::ReduceByKey(segmentIds, isROfSplitPlane, discardKeys, pointsToRight, vtkm::Add());

    // Calculate Lmax and Rmin
    vtkm::cont::ArrayHandle<vtkm::Range> leqRanges;
    vtkm::cont::ArrayHandle<vtkm::Range> rRanges;
987
    vtkm::worklet::DispatcherMapField<detail::FilterRanges<true>>().Invoke(
988
      coords, splitPlanes, ranges, leqRanges);
989
    vtkm::worklet::DispatcherMapField<detail::FilterRanges<false>>().Invoke(
990
991
992
993
      coords, splitPlanes, ranges, rRanges);

    vtkm::cont::ArrayHandle<vtkm::Range> lMaxRanges;
    vtkm::cont::ArrayHandle<vtkm::Range> rMinRanges;
994
995
    Algorithms::ReduceByKey(segmentIds, leqRanges, discardKeys, lMaxRanges, detail::RangeAdd());
    Algorithms::ReduceByKey(segmentIds, rRanges, discardKeys, rMinRanges, detail::RangeAdd());
996
997
998
999
1000
1001

    vtkm::cont::ArrayHandle<vtkm::Float64> segmentedSplitPlanes;
    Algorithms::ReduceByKey(
      segmentIds, splitPlanes, discardKeys, segmentedSplitPlanes, vtkm::Minimum());

    // Calculate costs
1002
1003
    detail::SplitPropertiesCalculator splitPropertiesCalculator(index, NumPlanes + 1);
    vtkm::worklet::DispatcherMapField<detail::SplitPropertiesCalculator>(splitPropertiesCalculator)
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
      .Invoke(pointsToLeft, pointsToRight, lMaxRanges, rMinRanges, segmentedSplitPlanes, splits);
  }

  template <typename DeviceAdapter>
  VTKM_CONT IdArrayHandle CalculateSplitScatterIndices(const IdArrayHandle& cellIds,
                                                       const IdArrayHandle& leqFlags,
                                                       const IdArrayHandle& segmentIds,
                                                       DeviceAdapter)
  {
    using Algorithms = typename vtkm::cont::DeviceAdapterAlgorithm<DeviceAdapter>;
    // Count total number of true flags preceding in segment
    IdArrayHandle trueFlagCounts;
    Algorithms::ScanExclusiveByKey(segmentIds, leqFlags, trueFlagCounts);

    // Make a counting iterator.
    CountingIdArrayHandle counts(0, 1, cellIds.GetNumberOfValues());

    // Total number of elements in previous segment
    vtkm::cont::ArrayHandle<vtkm::Id> countPreviousSegments;
    Algorithms::ScanInclusiveByKey(segmentIds, counts, countPreviousSegments, vtkm::Minimum());

    // Total number of false flags so far in segment
1026
1027
    vtkm::cont::ArrayHandleTransform<IdArrayHandle, detail::Invert> flagsInverse(leqFlags,
                                                                                 detail::Invert());
1028
1029
1030
1031
    vtkm::cont::ArrayHandle<vtkm::Id> runningFalseFlagCount;
    Algorithms::ScanInclusiveByKey(segmentIds, flagsInverse, runningFalseFlagCount, vtkm::Add());

    // Total number of false flags in segment
1032
    IdArrayHandle totalFalseFlagSegmentCount = detail::ReverseScanInclusiveByKey(
1033
1034
1035
1036
1037
1038
1039
      segmentIds, runningFalseFlagCount, vtkm::Maximum(), DeviceAdapter());

    // if point is to the left,
    //    index = total number in  previous segments + total number of false flags in this segment + total number of trues in previous segment
    // else
    //    index = total number in previous segments + number of falses preceeding it in the segment.
    IdArrayHandle scatterIndices;
1040
1041
1042
1043
1044
1045
1046
    vtkm::worklet::DispatcherMapField<detail::SplitIndicesCalculator>().Invoke(
      leqFlags,
      trueFlagCounts,
      countPreviousSegments,
      runningFalseFlagCount,
      totalFalseFlagSegmentCount,
      scatterIndices);
1047
1048
1049
    return scatterIndices;
  }

1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
  struct PrepareForExecutionFunctor
  {
  public:
    template <typename DeviceAdapter>
    VTKM_CONT void operator()(DeviceAdapter,
                              const vtkm::cont::BoundingIntervalHierarchy* bih,
                              const vtkm::exec::CellLocator** bihExec) const
    {
      using LocatorHandle = vtkm::cont::VirtualObjectHandle<vtkm::exec::CellLocator>;
      vtkm::cont::DynamicCellSet cellSet = bih->GetCellSet();
      if (cellSet.IsType<vtkm::cont::CellSetExplicit<>>())
      {
        using CellSetType = vtkm::cont::CellSetExplicit<>;
        using ExecutionType = vtkm::exec::BoundingIntervalHierarchyExec<DeviceAdapter, CellSetType>;
        ExecutionType* execObject = new ExecutionType(bih->Nodes,
                                                      bih->ProcessedCellIds,
                                                      bih->GetCellSet().Cast<CellSetType>(),
1067
                                                      bih->GetCoordinates().GetData(),
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
                                                      DeviceAdapter());
        *bihExec = (new LocatorHandle(execObject, false))->PrepareForExecution(DeviceAdapter());
      }
      else if (cellSet.IsType<vtkm::cont::CellSetStructured<2>>())
      {
        using CellSetType = vtkm::cont::CellSetStructured<2>;
        using ExecutionType = vtkm::exec::BoundingIntervalHierarchyExec<DeviceAdapter, CellSetType>;
        ExecutionType* execObject = new ExecutionType(bih->Nodes,
                                                      bih->ProcessedCellIds,
                                                      bih->GetCellSet().Cast<CellSetType>(),
1078
                                                      bih->GetCoordinates().GetData(),
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
                                                      DeviceAdapter());
        *bihExec = (new LocatorHandle(execObject, false))->PrepareForExecution(DeviceAdapter());
      }
      else if (cellSet.IsType<vtkm::cont::CellSetStructured<3>>())
      {
        using CellSetType = vtkm::cont::CellSetStructured<3>;
        using ExecutionType = vtkm::exec::BoundingIntervalHierarchyExec<DeviceAdapter, CellSetType>;
        ExecutionType* execObject = new ExecutionType(bih->Nodes,
                                                      bih->ProcessedCellIds,
                                                      bih->GetCellSet().Cast<CellSetType>(),
1089
                                                      bih->GetCoordinates().GetData(),
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
                                                      DeviceAdapter());
        *bihExec = (new LocatorHandle(execObject, false))->PrepareForExecution(DeviceAdapter());
      }
      else if (cellSet.IsType<vtkm::cont::CellSetSingleType<>>())
      {
        using CellSetType = vtkm::cont::CellSetSingleType<>;
        using ExecutionType = vtkm::exec::BoundingIntervalHierarchyExec<DeviceAdapter, CellSetType>;
        ExecutionType* execObject = new ExecutionType(bih->Nodes,
                                                      bih->ProcessedCellIds,
                                                      bih->GetCellSet().Cast<CellSetType>(),
1100
                                                      bih->GetCoordinates().GetData(),
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
                                                      DeviceAdapter());
        *bihExec = (new LocatorHandle(execObject, false))->PrepareForExecution(DeviceAdapter());
      }
      else
      {
        throw vtkm::cont::ErrorBadType("Could not determine type to write out.");
      }
    }
  };

public:
  VTKM_CONT
  BoundingIntervalHierarchy(vtkm::IdComponent numPlanes = 4, vtkm::IdComponent maxLeafSize = 5)
    : NumPlanes(numPlanes)
    , MaxLeafSize(maxLeafSize)
1116
1117
    , Nodes()
    , ProcessedCellIds()
1118
1119
1120
  {
  }

1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
  VTKM_CONT
  void SetNumberOfSplittingPlanes(vtkm::IdComponent numPlanes)
  {
    NumPlanes = numPlanes;
    SetDirty();
  }

  VTKM_CONT
  vtkm::IdComponent GetNumberOfSplittingPlanes() { return NumPlanes; }

  VTKM_CONT
  void SetMaxLeafSize(vtkm::IdComponent maxLeafSize)
  {
    MaxLeafSize = maxLeafSize;
    SetDirty();
  }

  VTKM_CONT
  vtkm::Id GetMaxLeafSize() { return MaxLeafSize; }


protected:
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
  VTKM_CONT
  void Build() override
  {
    BuildFunctor functor(this);
    vtkm::cont::TryExecute(functor);
  }

  VTKM_CONT
  const vtkm::exec::CellLocator* PrepareForExecutionImpl(const vtkm::Int8 device) const override
  {
1153
    using DeviceList = VTKM_DEFAULT_DEVICE_ADAPTER_LIST_TAG;
1154
1155
1156
1157
1158
1159
1160
    const vtkm::exec::CellLocator* toReturn;
    vtkm::cont::internal::FindDeviceAdapterTagAndCall(
      device, DeviceList(), PrepareForExecutionFunctor(), this, &toReturn);
    return toReturn;
  }

private:
1161
1162
1163
1164
1165
  vtkm::IdComponent NumPlanes;
  vtkm::IdComponent MaxLeafSize;
  vtkm::cont::ArrayHandle<BoundingIntervalHierarchyNode> Nodes;
  IdArrayHandle ProcessedCellIds;
};
1166
1167
1168

} // namespace cont
} // namespace vtkm
1169
1170

#endif // vtk_m_cont_BoundingIntervalHierarchy_h