Skip to content

Commit

Permalink
Apply some simple optimisations to LineIntersection
Browse files Browse the repository at this point in the history
  • Loading branch information
peterstace committed Aug 2, 2021
1 parent 7f04f1e commit d09fae0
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
11 changes: 3 additions & 8 deletions internal/exact/line.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ func LineIntersection(lineA, lineB Line) Intersection {
d := sub12.Cross(sub34)

if d.Sign() == 0 {
if !collinear(v1, v2, v3) {
sub23 := v2.Sub(v3)
if sub12.Cross(sub23).Sign() != 0 {
return Intersection{Empty: true}
}

Expand All @@ -54,7 +55,7 @@ func LineIntersection(lineA, lineB Line) Intersection {
t := div(sub13.Cross(sub34), d)

// u := [(x2-x1)*(y1-y3)-(y2-y1)*(x1-x3)] / d
sub21 := v2.Sub(v1)
sub21 := sub12.Neg()
u := div(sub21.Cross(sub13), d)

if inUnitInterval(t) && inUnitInterval(u) {
Expand All @@ -64,9 +65,3 @@ func LineIntersection(lineA, lineB Line) Intersection {

return Intersection{Empty: true}
}

func collinear(v1, v2, v3 XYRat) bool {
sub21 := v2.Sub(v1)
sub32 := v3.Sub(v2)
return sub21.Cross(sub32).Sign() == 0
}
6 changes: 6 additions & 0 deletions internal/exact/real.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ func add(a, b *big.Rat) *big.Rat {
return tmp
}

func neg(r *big.Rat) *big.Rat {
tmp := new(big.Rat).Set(r)
tmp.Neg(tmp)
return tmp
}

func inUnitInterval(r *big.Rat) bool {
return r.Sign() >= 0 && r.Cmp(one) <= 0
}
7 changes: 7 additions & 0 deletions internal/exact/xy.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ func (r XYRat) Add(o XYRat) XYRat {
}
}

func (r XYRat) Neg() XYRat {
return XYRat{
neg(r.X),
neg(r.Y),
}
}

func (r XYRat) Max(o XYRat) XYRat {
if r.Less(o) {
return o
Expand Down

0 comments on commit d09fae0

Please sign in to comment.