compareTo method

int compareTo(
  1. dynamic obj
)
override

Defines a comparison operation on DepthSegments which orders them left to right. Assumes the segments are normalized.

The definition of the ordering is:

  • -1 : if DS1.seg is left of or below DS2.seg (DS1 < DS2)
  • 1 : if DS1.seg is right of or above DS2.seg (DS1 > DS2)
  • 0 : if the segments are identical

KNOWN BUGS:

  • The logic does not obey the {@link Comparator.compareTo} contract. This is acceptable for the intended usage, but may cause problems if used with some utilities in the Java standard library (e.g. {@link Lists.sort()}.

@param obj a DepthSegment @return the comparison value

Implementation

int compareTo(dynamic obj) {
  DepthSegment other = obj as DepthSegment;

// fast check if segments are trivially ordered along X
  if (upwardSeg.minX() >= other.upwardSeg.maxX()) return 1;
  if (upwardSeg.maxX() <= other.upwardSeg.minX()) return -1;

  /**
   * try and compute a determinate orientation for the segments.
   * Test returns 1 if other is left of this (i.e. this > other)
   */
  int orientIndex = upwardSeg.orientationIndex(other.upwardSeg);
  if (orientIndex != 0) return orientIndex;

  /**
   * If comparison between this and other is indeterminate,
   * try the opposite call order.
   * The sign of the result needs to be flipped.
   */
  orientIndex = -1 * other.upwardSeg.orientationIndex(upwardSeg);
  if (orientIndex != 0) return orientIndex;

// otherwise, use standard lexocographic segment ordering
  return upwardSeg.compareTo(other.upwardSeg);
}