1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.ink.geometry
18 
19 import androidx.annotation.FloatRange
20 import androidx.annotation.RestrictTo
21 import kotlin.math.hypot
22 
23 /** Represents a directed line segment between two points. */
24 public abstract class Segment internal constructor() {
25     public abstract val start: Vec
26     public abstract val end: Vec
27 
28     /** The length of the [Segment]. */
29     @FloatRange(from = 0.0)
computeLengthnull30     public fun computeLength(): Float = hypot(start.x - end.x, start.y - end.y)
31 
32     /**
33      * Returns an ImmutableVec with the displacement from start to end. This is equivalent to
34      * `subtract(end, start, output)`.
35      *
36      * For performance-sensitive code, prefer to use [computeDisplacement] with a pre-allocated
37      * instance of [MutableVec].
38      */
39     public fun computeDisplacement(): ImmutableVec = ImmutableVec(end.x - start.x, end.y - start.y)
40 
41     /**
42      * Populates [outVec] with the displacement from start to end. This is equivalent to
43      * `subtract(end, start, output)`. Returns [outVec].
44      */
45     public fun computeDisplacement(outVec: MutableVec): MutableVec {
46         outVec.x = end.x - start.x
47         outVec.y = end.y - start.y
48         return outVec
49     }
50 
51     /**
52      * Returns an [ImmutableVec] that lies halfway along the segment.
53      *
54      * For performance-sensitive code, prefer to use [computeMidpoint] with a pre-allocated instance
55      * of [MutableVec].
56      */
computeMidpointnull57     public fun computeMidpoint(): ImmutableVec =
58         ImmutableVec((start.x + end.x) / 2, (start.y + end.y) / 2)
59 
60     /** Populates [outVec] with the point halfway along the segment. */
61     public fun computeMidpoint(outVec: MutableVec): MutableVec {
62         outVec.x = (start.x + end.x) / 2
63         outVec.y = (start.y + end.y) / 2
64         return outVec
65     }
66 
67     /**
68      * Returns the minimum bounding box containing the [Segment].
69      *
70      * For performance-sensitive code, prefer to use [computeBoundingBox] with a pre-allocated
71      * instance of [MutableBox].
72      */
computeBoundingBoxnull73     public fun computeBoundingBox(): ImmutableBox {
74         // TODO(b/354236964): Optimize unnecessary allocations
75         val (minX, maxX, minY, maxY) = getBoundingXYCoordinates(this)
76         return ImmutableBox.fromTwoPoints(ImmutableVec(minX, minY), ImmutableVec(maxX, maxY))
77     }
78 
79     /** Populates [outBox] with the minimum bounding box containing the [Segment]. */
computeBoundingBoxnull80     public fun computeBoundingBox(outBox: MutableBox): MutableBox {
81         // TODO(b/354236964): Optimize unnecessary allocations
82         val (minX, maxX, minY, maxY) = getBoundingXYCoordinates(this)
83         outBox.setXBounds(minX, maxX)
84         outBox.setYBounds(minY, maxY)
85         return outBox
86     }
87 
88     /**
89      * Returns the point on the segment at the given ratio of the segment's length, measured from
90      * the start point. You may also think of this as linearly interpolating from the start of the
91      * segment to the end. Values outside the interval [0, 1] will be extrapolated along the
92      * infinite line passing through this segment. This is the inverse of [project].
93      *
94      * For performance-sensitive code, prefer to use [computeLerpPoint] with a pre-allocated
95      * instance of [MutableVec].
96      */
computeLerpPointnull97     public fun computeLerpPoint(ratio: Float): ImmutableVec =
98         ImmutableVec(
99             (1.0f - ratio) * start.x + ratio * end.x,
100             (1.0f - ratio) * start.y + ratio * end.y
101         )
102 
103     /**
104      * Fills [outVec] with the point on the segment at the given ratio of the segment's length,
105      * measured from the start point. You may also think of this as linearly interpolating from the
106      * start of the segment to the end. Values outside the interval [0, 1] will be extrapolated
107      * along the infinite line passing through this segment. This is the inverse of [project].
108      */
109     public fun computeLerpPoint(ratio: Float, outVec: MutableVec): MutableVec {
110         outVec.x = (1.0f - ratio) * start.x + ratio * end.x
111         outVec.y = (1.0f - ratio) * start.y + ratio * end.y
112         return outVec
113     }
114 
115     /**
116      * Returns the multiple of the segment's length at which the infinite extrapolation of this
117      * segment is closest to [pointToProject]. This is the inverse of [computeLerpPoint]. If the
118      * [computeLength] of this segment is zero, then the projection is undefined and this will throw
119      * an error. Note that the [computeLength] may be zero even if [start] and [end] are not equal,
120      * if they are sufficiently close that floating-point underflow occurs.
121      */
projectnull122     public fun project(pointToProject: Vec): Float {
123         // TODO(b/354236964): Optimize unnecessary allocations
124         if (Vec.areEquivalent(start, end)) {
125             throw IllegalArgumentException("Projecting onto a segment of zero length is undefined.")
126         }
127         // Sometimes start is not exactly equal to the end, but close enough that the
128         // magnitude-squared still is not positive due to floating-point
129         // loss-of-precision.
130         val displacementX = end.x - start.x
131         val displacementY = end.y - start.y
132         val magnitudeSquared = displacementX * displacementX + displacementY * displacementY
133         if (magnitudeSquared <= 0) {
134             throw IllegalArgumentException("Projecting onto a segment of zero length is undefined.")
135         }
136         val scaledDifferenceX = (pointToProject.x - start.x) * displacementX
137         val scaledDifferenceY = (pointToProject.y - start.y) * displacementY
138         return (scaledDifferenceX + scaledDifferenceY) / magnitudeSquared
139     }
140 
141     /**
142      * Returns an immutable copy of this object. This will return itself if called on an immutable
143      * instance.
144      */
asImmutablenull145     @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public abstract fun asImmutable(): ImmutableSegment
146 
147     /**
148      * Compares this [Segment] with [other], and returns true if both [start] points are considered
149      * almost equal with the given [tolerance], and likewise for both [end] points.
150      */
151     public fun isAlmostEqual(other: Segment, @FloatRange(from = 0.0) tolerance: Float): Boolean =
152         start.isAlmostEqual(other.start, tolerance) && end.isAlmostEqual(other.end, tolerance)
153 
154     public companion object {
155         /**
156          * Returns true if [first] and [second] have the same values for all properties of
157          * [Segment].
158          */
159         internal fun areEquivalent(first: Segment, second: Segment): Boolean {
160             return Vec.areEquivalent(first.start, second.start) &&
161                 Vec.areEquivalent(first.end, second.end)
162         }
163 
164         /** Returns a hash code for [segment] using its [Segment] properties. */
165         internal fun hash(segment: Segment): Int =
166             31 * segment.start.hashCode() + segment.end.hashCode()
167 
168         /** Returns a string representation for [segment] using its [Segment] properties. */
169         internal fun string(segment: Segment): String =
170             "Segment(start=${segment.start}, end=${segment.end})"
171 
172         /**
173          * Returns the minimum and maximum x and y coordinates for all points inside [segment].
174          *
175          * This function returns four floats corresponding to the (minX, maxX, minY, maxY)
176          * coordinates of the segment. These coordinates are used to compute the bounding rectangle
177          * of [segment].
178          */
179         private fun getBoundingXYCoordinates(segment: Segment) =
180             arrayOf(
181                 minOf(segment.start.x, segment.end.x),
182                 maxOf(segment.start.x, segment.end.x),
183                 minOf(segment.start.y, segment.end.y),
184                 maxOf(segment.start.y, segment.end.y),
185             )
186     }
187 }
188