Esempio n. 1
0
 /**
  * Add an edge along this line. Overlapping edges are merged.
  *
  * @param e1 The first edge end
  * @param e2 The second edge end
  */
 public void add(int e1, int e2) {
   // sort the ends
   int min = (e1 < e2) ? e1 : e2;
   e2 = (e1 > e2) ? e1 : e2;
   e1 = min;
   // state of the current segment end : first end or last end of the
   // current segment
   boolean first = true;
   boolean inMerge = false;
   for (int i = 0; i < edges.size(); ++i) {
     int end = edges.get(i).intValue();
     // wait till newsegment match this interval in edges list order
     if (e1 > end) {
       first = !first;
       continue;
     }
     // now e1<=end. Handle case where end is the first segment end
     if (first) {
       // If not already merging, see if merging is necessary
       if (!inMerge) {
         // segments overlap => extend existing segment to match
         // the new one
         if (end <= e2) {
           edges.set(i, new Integer(e1));
           inMerge = true; // now merging the new segment
         } else {
           // Segments do not overlap => add a new segment,
           // finished
           edges.add(i, new Integer(e2)); // insert e2 before
           // the current end
           edges.add(i, new Integer(e1)); // insert e1 before
           // e2
           return;
         }
         // In merge already => it normal that e1<=end. Let's
         // check e2
       } else {
         // new segment terminates before current segment
         // => add the new point, finished
         if (e2 < end) {
           edges.add(i, new Integer(e2));
           return;
           // new segment terminates after or inside current
           // segment => merge this end
         } else if (e2 >= end) {
           // remove this end, as the segments merge to make
           // one bigger segment
           edges.remove(i--); // remove corresponding index too
         }
       }
     }
     // Handle second case : end is the last end of the segment.
     // Note: e1<=end, see above
     else {
       // new segment terminates inside current one
       // => end of the merge, keep this segment's end
       if (e2 <= end) return;
       // New segment terminates strictly after current segment
       // remove this end, as the segments merge to make one bigger
       // segment
       edges.remove(i--); // remove corresponding index too
       // If not already merging, this is necessary
       inMerge = true; // now merging the new segment
     }
     first = !first;
   }
   // Still here? => new segment terminates after any existing segment
   // If not merging, must add the first end of the new segment since
   // it was larger than all existing segment ends
   if (!inMerge) edges.add(new Integer(e1));
   // Close the new segment
   edges.add(new Integer(e2));
 }