001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math3.geometry.euclidean.twod;
018
019import java.util.ArrayList;
020import java.util.List;
021
022import org.apache.commons.math3.geometry.Point;
023import org.apache.commons.math3.geometry.euclidean.oned.Euclidean1D;
024import org.apache.commons.math3.geometry.euclidean.oned.Interval;
025import org.apache.commons.math3.geometry.euclidean.oned.IntervalsSet;
026import org.apache.commons.math3.geometry.euclidean.oned.OrientedPoint;
027import org.apache.commons.math3.geometry.euclidean.oned.Vector1D;
028import org.apache.commons.math3.geometry.partitioning.AbstractSubHyperplane;
029import org.apache.commons.math3.geometry.partitioning.BSPTree;
030import org.apache.commons.math3.geometry.partitioning.Hyperplane;
031import org.apache.commons.math3.geometry.partitioning.Region;
032import org.apache.commons.math3.geometry.partitioning.Region.Location;
033import org.apache.commons.math3.geometry.partitioning.Side;
034import org.apache.commons.math3.geometry.partitioning.SubHyperplane;
035import org.apache.commons.math3.util.FastMath;
036
037/** This class represents a sub-hyperplane for {@link Line}.
038 * @since 3.0
039 */
040public class SubLine extends AbstractSubHyperplane<Euclidean2D, Euclidean1D> {
041
042    /** Default value for tolerance. */
043    private static final double DEFAULT_TOLERANCE = 1.0e-10;
044
045    /** Simple constructor.
046     * @param hyperplane underlying hyperplane
047     * @param remainingRegion remaining region of the hyperplane
048     */
049    public SubLine(final Hyperplane<Euclidean2D> hyperplane,
050                   final Region<Euclidean1D> remainingRegion) {
051        super(hyperplane, remainingRegion);
052    }
053
054    /** Create a sub-line from two endpoints.
055     * @param start start point
056     * @param end end point
057     * @param tolerance tolerance below which points are considered identical
058     * @since 3.3
059     */
060    public SubLine(final Vector2D start, final Vector2D end, final double tolerance) {
061        super(new Line(start, end, tolerance), buildIntervalSet(start, end, tolerance));
062    }
063
064    /** Create a sub-line from two endpoints.
065     * @param start start point
066     * @param end end point
067     * @deprecated as of 3.3, replaced with {@link #SubLine(Vector2D, Vector2D, double)}
068     */
069    @Deprecated
070    public SubLine(final Vector2D start, final Vector2D end) {
071        this(start, end, DEFAULT_TOLERANCE);
072    }
073
074    /** Create a sub-line from a segment.
075     * @param segment single segment forming the sub-line
076     */
077    public SubLine(final Segment segment) {
078        super(segment.getLine(),
079              buildIntervalSet(segment.getStart(), segment.getEnd(), segment.getLine().getTolerance()));
080    }
081
082    /** Get the endpoints of the sub-line.
083     * <p>
084     * A subline may be any arbitrary number of disjoints segments, so the endpoints
085     * are provided as a list of endpoint pairs. Each element of the list represents
086     * one segment, and each segment contains a start point at index 0 and an end point
087     * at index 1. If the sub-line is unbounded in the negative infinity direction,
088     * the start point of the first segment will have infinite coordinates. If the
089     * sub-line is unbounded in the positive infinity direction, the end point of the
090     * last segment will have infinite coordinates. So a sub-line covering the whole
091     * line will contain just one row and both elements of this row will have infinite
092     * coordinates. If the sub-line is empty, the returned list will contain 0 segments.
093     * </p>
094     * @return list of segments endpoints
095     */
096    public List<Segment> getSegments() {
097
098        final Line line = (Line) getHyperplane();
099        final List<Interval> list = ((IntervalsSet) getRemainingRegion()).asList();
100        final List<Segment> segments = new ArrayList<Segment>(list.size());
101
102        for (final Interval interval : list) {
103            final Vector2D start = line.toSpace((Point<Euclidean1D>) new Vector1D(interval.getInf()));
104            final Vector2D end   = line.toSpace((Point<Euclidean1D>) new Vector1D(interval.getSup()));
105            segments.add(new Segment(start, end, line));
106        }
107
108        return segments;
109
110    }
111
112    /** Get the intersection of the instance and another sub-line.
113     * <p>
114     * This method is related to the {@link Line#intersection(Line)
115     * intersection} method in the {@link Line Line} class, but in addition
116     * to compute the point along infinite lines, it also checks the point
117     * lies on both sub-line ranges.
118     * </p>
119     * @param subLine other sub-line which may intersect instance
120     * @param includeEndPoints if true, endpoints are considered to belong to
121     * instance (i.e. they are closed sets) and may be returned, otherwise endpoints
122     * are considered to not belong to instance (i.e. they are open sets) and intersection
123     * occurring on endpoints lead to null being returned
124     * @return the intersection point if there is one, null if the sub-lines don't intersect
125     */
126    public Vector2D intersection(final SubLine subLine, final boolean includeEndPoints) {
127
128        // retrieve the underlying lines
129        Line line1 = (Line) getHyperplane();
130        Line line2 = (Line) subLine.getHyperplane();
131
132        // compute the intersection on infinite line
133        Vector2D v2D = line1.intersection(line2);
134        if (v2D == null) {
135            return null;
136        }
137
138        // check location of point with respect to first sub-line
139        Location loc1 = getRemainingRegion().checkPoint(line1.toSubSpace((Point<Euclidean2D>) v2D));
140
141        // check location of point with respect to second sub-line
142        Location loc2 = subLine.getRemainingRegion().checkPoint(line2.toSubSpace((Point<Euclidean2D>) v2D));
143
144        if (includeEndPoints) {
145            return ((loc1 != Location.OUTSIDE) && (loc2 != Location.OUTSIDE)) ? v2D : null;
146        } else {
147            return ((loc1 == Location.INSIDE) && (loc2 == Location.INSIDE)) ? v2D : null;
148        }
149
150    }
151
152    /** Build an interval set from two points.
153     * @param start start point
154     * @param end end point
155     * @param tolerance tolerance below which points are considered identical
156     * @return an interval set
157     */
158    private static IntervalsSet buildIntervalSet(final Vector2D start, final Vector2D end, final double tolerance) {
159        final Line line = new Line(start, end, tolerance);
160        return new IntervalsSet(line.toSubSpace((Point<Euclidean2D>) start).getX(),
161                                line.toSubSpace((Point<Euclidean2D>) end).getX(),
162                                tolerance);
163    }
164
165    /** {@inheritDoc} */
166    @Override
167    protected AbstractSubHyperplane<Euclidean2D, Euclidean1D> buildNew(final Hyperplane<Euclidean2D> hyperplane,
168                                                                       final Region<Euclidean1D> remainingRegion) {
169        return new SubLine(hyperplane, remainingRegion);
170    }
171
172    /** {@inheritDoc} */
173    @Override
174    public Side side(final Hyperplane<Euclidean2D> hyperplane) {
175
176        final Line    thisLine  = (Line) getHyperplane();
177        final Line    otherLine = (Line) hyperplane;
178        final Vector2D crossing  = thisLine.intersection(otherLine);
179
180        if (crossing == null) {
181            // the lines are parallel,
182            final double global = otherLine.getOffset(thisLine);
183            return (global < -1.0e-10) ? Side.MINUS : ((global > 1.0e-10) ? Side.PLUS : Side.HYPER);
184        }
185
186        // the lines do intersect
187        final boolean direct = FastMath.sin(thisLine.getAngle() - otherLine.getAngle()) < 0;
188        final Vector1D x = thisLine.toSubSpace((Point<Euclidean2D>) crossing);
189        return getRemainingRegion().side(new OrientedPoint(x, direct, thisLine.getTolerance()));
190
191    }
192
193    /** {@inheritDoc} */
194    @Override
195    public SplitSubHyperplane<Euclidean2D> split(final Hyperplane<Euclidean2D> hyperplane) {
196
197        final Line    thisLine  = (Line) getHyperplane();
198        final Line    otherLine = (Line) hyperplane;
199        final Vector2D crossing = thisLine.intersection(otherLine);
200        final double tolerance  = thisLine.getTolerance();
201
202        if (crossing == null) {
203            // the lines are parallel
204            final double global = otherLine.getOffset(thisLine);
205            return (global < -1.0e-10) ?
206                   new SplitSubHyperplane<Euclidean2D>(null, this) :
207                   new SplitSubHyperplane<Euclidean2D>(this, null);
208        }
209
210        // the lines do intersect
211        final boolean direct = FastMath.sin(thisLine.getAngle() - otherLine.getAngle()) < 0;
212        final Vector1D x      = thisLine.toSubSpace((Point<Euclidean2D>) crossing);
213        final SubHyperplane<Euclidean1D> subPlus  =
214                new OrientedPoint(x, !direct, tolerance).wholeHyperplane();
215        final SubHyperplane<Euclidean1D> subMinus =
216                new OrientedPoint(x,  direct, tolerance).wholeHyperplane();
217
218        final BSPTree<Euclidean1D> splitTree = getRemainingRegion().getTree(false).split(subMinus);
219        final BSPTree<Euclidean1D> plusTree  = getRemainingRegion().isEmpty(splitTree.getPlus()) ?
220                                               new BSPTree<Euclidean1D>(Boolean.FALSE) :
221                                               new BSPTree<Euclidean1D>(subPlus, new BSPTree<Euclidean1D>(Boolean.FALSE),
222                                                                        splitTree.getPlus(), null);
223        final BSPTree<Euclidean1D> minusTree = getRemainingRegion().isEmpty(splitTree.getMinus()) ?
224                                               new BSPTree<Euclidean1D>(Boolean.FALSE) :
225                                               new BSPTree<Euclidean1D>(subMinus, new BSPTree<Euclidean1D>(Boolean.FALSE),
226                                                                        splitTree.getMinus(), null);
227
228        return new SplitSubHyperplane<Euclidean2D>(new SubLine(thisLine.copySelf(), new IntervalsSet(plusTree, tolerance)),
229                                                   new SubLine(thisLine.copySelf(), new IntervalsSet(minusTree, tolerance)));
230
231    }
232
233}