go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/quad/range.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package quad
     9  
    10  // RangeFromPoints returns a new quad range from two given points.
    11  func RangeFromPoints(topLeft, bottomRight Point) Range {
    12  	halfDimensions := Dimension{
    13  		Width:  (bottomRight.X - topLeft.X) / 2,
    14  		Height: (bottomRight.Y - topLeft.Y) / 2,
    15  	}
    16  	center := Point{
    17  		X: topLeft.X + (halfDimensions.Width),
    18  		Y: topLeft.Y + (halfDimensions.Height),
    19  	}
    20  	return Range{
    21  		Center:         center,
    22  		HalfDimensions: halfDimensions,
    23  	}
    24  }
    25  
    26  // Range is a boundary box given
    27  // by a center point and dimensions.
    28  type Range struct {
    29  	Center         Point
    30  	HalfDimensions Dimension
    31  }
    32  
    33  // ContainsPoint returns if a given bounds contains
    34  // a given point.
    35  func (r *Range) ContainsPoint(p Point) bool {
    36  	nw := Point{
    37  		X: r.Center.X - r.HalfDimensions.Width,
    38  		Y: r.Center.Y - r.HalfDimensions.Height,
    39  	}
    40  	se := Point{
    41  		X: r.Center.X + r.HalfDimensions.Width,
    42  		Y: r.Center.Y + r.HalfDimensions.Height,
    43  	}
    44  	return p.X >= nw.X && p.X <= se.X && p.Y >= nw.Y && p.Y <= se.Y
    45  }
    46  
    47  // Intersects returns if a given range intersects with another given range.
    48  func (r *Range) Intersects(other Range) bool {
    49  	box1min := Point{
    50  		X: r.Center.X - r.HalfDimensions.Width,
    51  		Y: r.Center.Y - r.HalfDimensions.Height,
    52  	}
    53  	box1max := Point{
    54  		X: r.Center.X + r.HalfDimensions.Width,
    55  		Y: r.Center.Y + r.HalfDimensions.Height,
    56  	}
    57  	box2min := Point{
    58  		X: other.Center.X - other.HalfDimensions.Width,
    59  		Y: other.Center.Y - other.HalfDimensions.Height,
    60  	}
    61  	box2max := Point{
    62  		X: other.Center.X + other.HalfDimensions.Width,
    63  		Y: other.Center.Y + other.HalfDimensions.Height,
    64  	}
    65  
    66  	return box1max.X >= box2min.X && box2max.X >= box1min.X &&
    67  		box1max.Y >= box2min.Y && box2max.Y >= box1min.Y
    68  }
    69  
    70  // Bounds returns the top left and bottom right points that bound
    71  // the quad range box.
    72  func (r *Range) Bounds() (topLeft Point, bottomRight Point) {
    73  	topLeft.X = r.Center.X - r.HalfDimensions.Width
    74  	topLeft.Y = r.Center.Y - r.HalfDimensions.Height
    75  	bottomRight.X = r.Center.X + r.HalfDimensions.Width
    76  	bottomRight.Y = r.Center.Y + r.HalfDimensions.Height
    77  	return
    78  }