Line2D Module
Intersections, point-to-line distance, and projection tests for infinite 2D lines and segments.
Turn the guide into code
Take the key idea from this page into the playground and validate it in a real shader instead of leaving it as theory.
Open PlaygroundIntersections, point-to-line distance, and projection tests for infinite 2D lines and segments.
Import
import Line2D
This module has no module imports.
Usage Examples
Distance to an Edge
Use Line2D for screen-space or UV-space geometry: anti-aliased lines, half-plane masks, or finding where two guides cross.
import Line2D
float2 A = float2(0.1, 0.2);
float2 B = float2(0.9, 0.7);
// Signed: positive on the left of A -> B.
float d = Line2D::distanceFromPointToLine(input.uv, A, B);
float onSegment = Line2D::isPointPerpendicularToLine(A, B, input.uv) ? 1.0 : 0.0;
float line = (1.0 - smoothstep(0.0, 0.004, abs(d))) * onSegment;
output.color = float4(float3(line), 1.0);
Intersect Two Lines
Check hasUniqueIntersection before using point; parallel, collinear, and degenerate inputs leave it false.
import Line2D
Line2D::LineIntersection hit = Line2D::intersection(
float2(0.0, 0.0), float2(1.0, 1.0),
float2(0.0, 1.0), float2(1.0, 0.0),
);
float2 crossing = hit.hasUniqueIntersection ? hit.point : float2(-1.0);
Constants
const float LINE_EPSILON = 1e-6Structs
LineIntersection
struct LineIntersection {
bool hasUniqueIntersection;
bool isCollinear;
float2 point;
float lineAParameter;
float lineBParameter;
};
Enums
No enums found.
Functions
intersection
Intersects the infinite lines through A-B and C-D. hasUniqueIntersection is false for parallel, collinear, and degenerate lines. For a unique intersection, point is the location and the parameters satisfy point = A + lineAParameter * (B - A) and point = C + lineBParameter * (D - C).
intersection :: (float2 A, float2 B, float2 C, float2 D) -> LineIntersection
isPointPerpendicularToLine
Returns true when the perpendicular projection of point onto the infinite line A-B lies on the closed segment A-B. Returns false when A and B describe a degenerate segment.
isPointPerpendicularToLine :: (float2 A, float2 B, float2 point) -> bool
distanceFromPointToLine
Returns the signed distance from point to the infinite line A-B. Positive values are on the left of the directed line A -> B. A degenerate line is treated as the point A and returns an unsigned point distance.
distanceFromPointToLine :: (float2 point, float2 A, float2 B) -> float
Source
Generated from compiler-reference/modules/Line2D.bwsl.