For convenience, we assume that the segment, denoted OP
, starts from the origin. (If not, translate all points.)
A point of the segment OP
is given by the vector expression
t.P
with t
in [0, 1]
.
Such a point belongs to the closed rectangle [X0, X1] x [Y0, Y1]
when
X0 ≤ Px.t ≤ X1
Y0 ≤ Py.t ≤ Y1
To discuss these inequations, we have to distinguish nine cases depending on the signs of Px
and Py
.
Let us handle the case of two positives. Then we write
Py.X0 ≤ Px.Py.t ≤ Py.X1
Px.Y0 ≤ Px.Py.t ≤ Px.Y1
together with
0 ≤ Px.Py.t ≤ Px.Py
which expresses the limits of the segment.
Then the solution set is not empty under the condition
Max(Py.X0, Px.Y0, 0) ≤ Min(Py.X1, Px.Y1, Px.Py)
The other cases can be handled similarly. The computational cost is
6 initial subtractions
2 3-way sign tests
5 multiplications
5 comparisons
(when the initial comparisons conclude equality, the expressions simplify a little* and the cost is lower).
Note that this formulation avoids divisions, for efficiency. As said in my other answer, the relevance of <
vs. ≤
is quite debatable (possibly handled with interval arithmetic).
*Let Py=0
, then we write the inequations as
X0 ≤ Px.t ≤ X1
Y0 ≤ 0 ≤ Y1
0 ≤ Px.t ≤ Px
and the condition is
Max(X0, 0) ≤ Min(X1, Px) and Y0 ≤ 0 ≤ Y1.
And obviously, Px=Py=0
is solved with
X0 ≤ 0 ≤ X1 and Y0 ≤ 0 ≤ Y1.