partitioning.cpp 15.8 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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* The copyright in this software is being made available under the BSD
 * Licence, included below.  This software may be subject to other third
 * party and contributor rights, including patent rights, and no such
 * rights are granted under this licence.
 *
 * Copyright (c) 2017-2018, ISO/IEC
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of the ISO/IEC nor the names of its contributors
 *   may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "partitioning.h"

#include <algorithm>
#include <cstdlib>
40
41
#include <map>
#include <stdint.h>
42
43
44

namespace pcc {

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//============================================================================
// Determine whether half of slices are smaller than maxPoints

bool
halfQualified(const std::vector<Partition> slices, int maxPoints)
{
  int Qualified = 0;
  for (int i = 0; i < slices.size(); i++) {
    if (slices[i].pointIndexes.size() < maxPoints)
      Qualified++;
  }

  return ((double)Qualified / (double)slices.size()) > 0.5;
}

60
61
62
63
//============================================================================

template<typename T>
static int
64
longestAxis(const Box3<T>& curBox)
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
{
  int edgeAxis = 0;

  for (int i = 1; i < 3; i++) {
    T axisLength = curBox.max[i] - curBox.min[i];
    T longestLength = curBox.max[edgeAxis] - curBox.min[edgeAxis];
    if (axisLength > longestLength)
      edgeAxis = i;
  }

  return edgeAxis;
}

//----------------------------------------------------------------------------

template<typename T>
static int
82
shortestAxis(const Box3<T>& curBox)
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
{
  int edgeAxis = 0;

  for (int i = 1; i < 3; i++) {
    T axisLength = curBox.max[i] - curBox.min[i];
    T shortestLength = curBox.max[edgeAxis] - curBox.min[edgeAxis];
    if (axisLength < shortestLength)
      edgeAxis = i;
  }

  return edgeAxis;
}

//----------------------------------------------------------------------------
// Split point cloud into slices along the longest axis.
// numPartitions describes the number of slices to produce (if zero, the
// ratio of longest:shortest axis is used).
// No tile metadata is generated.

102
103
std::vector<Partition>
partitionByUniformGeom(
104
105
106
107
  const PartitionParams& params,
  const PCCPointSet3& cloud,
  int tileID,
  int partitionBoundaryLog2)
108
{
109
  std::vector<Partition> slices;
110

111
  Box3<double> bbox = cloud.computeBoundingBox();
112
113
114
115
116
117
118

  int maxEdgeAxis = longestAxis(bbox);
  int maxEdge = bbox.max[maxEdgeAxis] - bbox.min[maxEdgeAxis];

  int minEdgeAxis = shortestAxis(bbox);
  int minEdge = bbox.max[minEdgeAxis] - bbox.min[minEdgeAxis];

119
120
  int sliceNum = minEdge ? (maxEdge / minEdge) : 1;
  int sliceSize = minEdge ? minEdge : maxEdge;
121

122
123
124
125
126
127
128
  // In order to avoid issues with trisoup, don't partition points within
  // a trisoup node, otherwise there will be issues fitting triangles.
  int partitionBoundary = 1 << partitionBoundaryLog2;
  if (sliceSize % partitionBoundary) {
    sliceSize = (1 + sliceSize / partitionBoundary) * partitionBoundary;
  }

129
130
131
132
133
134
135
136
137
138
  while (1) {
    slices.clear();
    slices.resize(sliceNum);

    for (int i = 0; i < sliceNum; i++) {
      auto& slice = slices[i];
      slice.sliceId = i;
      slice.tileId = tileID;
      slice.origin = Vec3<int>{0};
    }
139

140
141
142
143
144
145
    for (int n = 0; n < cloud.getPointCount(); n++) {
      for (int p = sliceNum - 1; p >= 0; p--) {
        if (
          cloud[n][maxEdgeAxis]
          >= int(p * sliceSize + bbox.min[maxEdgeAxis])) {
          auto& slice = slices[p];
146

147
148
149
          slice.pointIndexes.push_back(n);
          break;
        }
150
151
      }
    }
152
153
154
155
156
157

    if (halfQualified(slices, params.sliceMaxPoints))
      break;

    sliceNum *= 2;
    sliceSize = maxEdge / sliceNum;
158
159
160
  }

  // Delete the slice that with no points
161
  slices.erase(
162
    std::remove_if(
163
      slices.begin(), slices.end(),
164
      [](const Partition& p) { return p.pointIndexes.empty(); }),
165
    slices.end());
166

167
  return slices;
168
169
}

170
171
172
173
//----------------------------------------------------------------------------
// Split point cloud into several parts according to octree depth.
// No tile metadata is generated.

174
175
176
177
178
179
std::vector<Partition>
partitionByOctreeDepth(
  const PartitionParams& params,
  const PCCPointSet3& cloud,
  int tileID,
  bool splitByDepth)
180
{
181
  std::vector<Partition> slices;
182
183
184
185

  // noting that there is a correspondence between point position
  // and octree node, calculate the position mask and shift required
  // to determine the node address for a point.
186
  Box3<double> bbox = cloud.computeBoundingBox();
187
188
189
  int maxBb = (int)std::max({bbox.max[0], bbox.max[1], bbox.max[2]});

  int cloudSizeLog2 = ceillog2(maxBb + 1);
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
  int depOctree = splitByDepth ? params.octreeDepth : 1;

  do {
    slices.clear();
    int posShift = cloudSizeLog2 - depOctree;
    int posMask = (1 << depOctree) - 1;

    // initially: number of points in each partition
    // then: mapping of partId to sliceId
    std::vector<int> partMap(1 << (3 * depOctree));

    // per-point indexes used for assigning to a partition
    std::vector<int> pointToPartId(cloud.getPointCount());

    // for each point, determine a partition based upon the position
    for (int i = 0, last = cloud.getPointCount(); i < last; i++) {
      int x = ((int(cloud[i].x()) >> posShift) & posMask) << (2 * depOctree);
      int y = ((int(cloud[i].y()) >> posShift) & posMask) << depOctree;
      int z = (int(cloud[i].z()) >> posShift) & posMask;
      int partId = x | y | z;
      partMap[partId]++;
      pointToPartId[i] = partId;
    }
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
    // generate slice mapping
    //  - allocate slice map storage and determine contiguous sliceIds
    //    NB: the sliceIds replace partPointCount.
    //  - map points to each slice.

    int numSlices =
      partMap.size() - std::count(partMap.begin(), partMap.end(), 0);
    slices.resize(numSlices);

    int sliceId = 0;
    for (auto& part : partMap) {
      if (!part)
        continue;

      auto& slice = slices[sliceId];
      slice.sliceId = sliceId;
      slice.tileId = tileID;
      slice.origin = Vec3<int>{0};
      slice.pointIndexes.reserve(part);
      part = sliceId++;
    }

    for (int i = 0, last = cloud.getPointCount(); i < last; i++) {
      int partId = pointToPartId[i];
      int sliceId = partMap[partId];
      slices[sliceId].pointIndexes.push_back(i);
    }

    if (halfQualified(slices, params.sliceMaxPoints))
      break;

    depOctree++;
  } while (!splitByDepth);

  return slices;
}

//=============================================================================
// Split point cloud into several tiles according to tileSize

std::vector<std::vector<int32_t>>
tilePartition(const PartitionParams& params, const PCCPointSet3& cloud)
{
  std::vector<std::vector<int32_t>> tilePartition;
  int tileSize = params.tileSize;

  // for each point determine the tile to which it belongs
  // let tile_origin = floor(pos / tile_size)
  // append pointIdx to tileMap[tile_origin]
  Box3<double> bbox = cloud.computeBoundingBox();
  int maxtileNum =
    std::ceil(std::max({bbox.max[0], bbox.max[1], bbox.max[2]}) / tileSize);
  int tileNumlog2 = ceillog2(maxtileNum);
  std::vector<int> partMap(1 << (3 * tileNumlog2));
268
269

  // per-point indexes used for assigning to a partition
270
  std::vector<uint64_t> pointToPartId(cloud.getPointCount());
271
272

  // for each point, determine a partition based upon the position
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
  std::vector<uint8_t> tilePos(3);
  uint64_t mortonTileID;
  for (int32_t i = 0, last = cloud.getPointCount(); i < last; i++) {
    mortonTileID = 0;
    for (int k = 0; k < 3; k++) {
      tilePos[k] = std::floor(cloud[i][k] / tileSize);
    }

    for (int p = 0; p < 8; p++) {
      mortonTileID |= ((tilePos[0] >> p) & 1) << (3 * p + 2);
      mortonTileID |= ((tilePos[1] >> p) & 1) << (3 * p + 1);
      mortonTileID |= ((tilePos[2] >> p) & 1) << (3 * p);
    }

    partMap[mortonTileID]++;
    pointToPartId[i] = mortonTileID;
289
290
  }

291
292
293
294
  // generate tile mapping
  // - allocate tile map storage and determine contiguous tileIds
  //   NB: the tileIds replace partPointCount.
  // - map points to each tile.
295

296
  int numTiles =
297
    partMap.size() - std::count(partMap.begin(), partMap.end(), 0);
298
  tilePartition.resize(numTiles);
299

300
  int tileId = 0;
301
302
303
304
  for (auto& part : partMap) {
    if (!part)
      continue;

305
306
    tilePartition[tileId].reserve(part);
    part = tileId++;
307
308
309
310
  }

  for (int i = 0, last = cloud.getPointCount(); i < last; i++) {
    int partId = pointToPartId[i];
311
312
    int tileId = partMap[partId];
    tilePartition[tileId].push_back(i);
313
314
  }

315
  return tilePartition;
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
//=============================================================================

Vec3<int>
minOrigin(const Vec3<int> a, const Vec3<int> b)
{
  Vec3<int> newOrigin;
  for (int i = 0; i < 3; i++) {
    newOrigin[i] = (a[i] < b[i]) ? a[i] : b[i];
  }
  return newOrigin;
}

//----------------------------------------------------------------------------
// get the axis of the longest edge

int
maxEdgeAxis(const PCCPointSet3& cloud, std::vector<int32_t>& sliceIndexes)
{
  int maxEdge = 0;
  int maxAxis = 0;
  for (int i = 0; i < 3; i++) {
    int maxpoint, minpoint;
    maxpoint = minpoint = cloud[sliceIndexes[0]][i];

    for (int k = 1; k < sliceIndexes.size(); k++) {
      if (cloud[sliceIndexes[k]][i] < minpoint)
        minpoint = cloud[sliceIndexes[k]][i];
      else if (cloud[sliceIndexes[k]][i] > maxpoint)
        maxpoint = cloud[sliceIndexes[k]][i];
    }

    if (maxEdge < (maxpoint - minpoint)) {
      maxEdge = maxpoint - minpoint;
      maxAxis = i;
    }
  }

  return maxAxis;
}

//============================================================================
// evenly split slice into several partitions no larger than maxPoints

std::vector<Partition>::iterator
splitSlice(
  const PCCPointSet3& cloud,
  std::vector<Partition>& slices,
  std::vector<Partition>::iterator toBeSplit,
  int maxPoints)
{
  auto& sliceA = (*toBeSplit);
  auto& AIndexes = sliceA.pointIndexes;

  // Split along the longest edge at the median point
  int splitAxis = maxEdgeAxis(cloud, AIndexes);
  std::stable_sort(
    AIndexes.begin(), AIndexes.end(), [&](int32_t a, int32_t b) {
      return cloud[a][splitAxis] < cloud[b][splitAxis];
    });

  int numSplit = std::ceil((double)AIndexes.size() / (double)maxPoints);
  int splitsize = AIndexes.size() / numSplit;
  std::vector<Partition> splitPartitions;
  splitPartitions.resize(numSplit);

  // The 2nd to the penultimate partitions
  for (int i = 1; i < numSplit - 1; i++) {
    splitPartitions[i].sliceId = sliceA.sliceId + i;
    splitPartitions[i].tileId = sliceA.tileId;
    splitPartitions[i].origin = Vec3<int>{0};

    auto& Indexes = splitPartitions[i].pointIndexes;
    Indexes.insert(
      Indexes.begin(), AIndexes.begin() + i * splitsize,
      AIndexes.begin() + (i + 1) * splitsize);
  }
  // The last split partition
  auto& Indexes = splitPartitions[numSplit - 1].pointIndexes;
  Indexes.insert(
    Indexes.begin(), AIndexes.begin() + (numSplit - 1) * splitsize,
    AIndexes.end());

  AIndexes.erase(AIndexes.begin() + splitsize, AIndexes.end());

  toBeSplit = slices.insert(
    toBeSplit + 1, splitPartitions.begin() + 1, splitPartitions.end());

  return toBeSplit + (numSplit - 1);
}

//----------------------------------------------------------------------------
// combine the two slices into one

std::vector<Partition>::iterator
mergeSlice(
  std::vector<Partition>& slices,
  std::vector<Partition>::iterator a,
  std::vector<Partition>::iterator b)
{
  auto& AIndexes = (*a).pointIndexes;
  auto& BIndexes = (*b).pointIndexes;

  AIndexes.insert(AIndexes.end(), BIndexes.begin(), BIndexes.end());
  (*a).origin = minOrigin((*a).origin, (*b).origin);

  return slices.erase(b);
}

//=============================================================================
// first split slices still having too many points(more than maxPoints)
// then merge slices with too few points(less than minPoints)

void
refineSlices(
  const PartitionParams& params,
  const PCCPointSet3& cloud,
  std::vector<Partition>& slices)
{
  int maxPoints = params.sliceMaxPoints;
  int minPoints = params.sliceMinPoints;

  std::vector<Partition>::iterator it = slices.begin();
  while (it != slices.end()) {
    if ((*it).pointIndexes.size() > maxPoints) {
      it = splitSlice(cloud, slices, it, maxPoints);
    } else {
      it++;
    }
  }

  it = slices.begin();
  while (it != slices.end() && slices.size() > 1) {
    if ((*it).pointIndexes.size() < minPoints) {
      std::vector<Partition>::iterator toBeMerge;
      bool isFront = 0;

      // - a slice could only merge with the one before or after it
      // - the first/last slice could only merge with the next/front one
      // - let mergerfront = point number of slice after merging with the front one
      //   mergenext = point number of slice after merging with the subsquent one
      // - if both mergefront and mergenext < maxPoints, choose the larger one;
      // - if one of them < maxPoints and another > maxPoints,
      //     choose the small one to meet the requirement
      // - if both mergefront and mergenext > maxPoints, choose the larger one
      //     and do one more split after merge. We deem the slice after split
      //     as acceptable whether they are larger than minPoints or not
      // NB: if the merger slice is still smaller than minPoints,
      //     go on merging the same slice
      if (it == slices.begin()) {
        assert(it + 1 != slices.end());
        toBeMerge = it + 1;
        isFront = 0;
      } else if (it == slices.end() - 1) {
        assert(it - 1 != slices.end());
        toBeMerge = it - 1;
        isFront = 1;
      } else {
        int mergefront =
          (*it).pointIndexes.size() + (*(it - 1)).pointIndexes.size();
        int mergenext =
          (*it).pointIndexes.size() + (*(it + 1)).pointIndexes.size();

        if (
          (mergefront > maxPoints && mergenext > maxPoints)
          || (mergefront < maxPoints && mergenext < maxPoints)) {
          toBeMerge = mergefront > mergenext ? (it - 1) : (it + 1);
          isFront = mergefront > mergenext ? 1 : 0;
        } else {
          toBeMerge = mergefront < mergenext ? (it - 1) : (it + 1);
          isFront = mergefront < mergenext ? 1 : 0;
        }
      }

      it = isFront ? mergeSlice(slices, toBeMerge, it)
                   : mergeSlice(slices, it, toBeMerge);

      if ((*(it - 1)).pointIndexes.size() > maxPoints)
        it = splitSlice(cloud, slices, it - 1, maxPoints);
      else if ((*(it - 1)).pointIndexes.size() < minPoints)
        it--;

    } else {
      it++;
    }
  }

  for (int i = 0; i < slices.size(); i++) {
    auto& slice = slices[i];
    slice.sliceId = i;
    slice.tileId = -1;
  }
}

511
512
513
//============================================================================

}  // namespace pcc