gmath

package module
v0.0.0-...-541a76d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2025 License: MIT Imports: 9 Imported by: 55

Documentation

Index

Constants

View Source
const Epsilon = 1e-9

Variables

This section is empty.

Functions

func Abs

func Abs[T float](x T) T

func ArcContains

func ArcContains(angle, measure Rad, pos, point Vec) bool

func ArcSectionContains

func ArcSectionContains(angle, measure Rad, r float64, pos, point Vec) bool

func Clamp

func Clamp[T numeric](v, min, max T) T

func ClampMax

func ClampMax[T numeric](v, max T) T

func ClampMin

func ClampMin[T numeric](v, min T) T

func Deviation

func Deviation[T float](x, y T) T

Deviation reports the weight of the difference between x and y.

In other words, it returns the multiplier to make the lower value between the two identical to other.

Some examples: * (1, 2) => 2 (1*2 = 2) * (10, 2) => 5 (2*5 = 10) * (3, 3) => 1

The order of parameters do not affect the result.

func EqualApprox

func EqualApprox[T float](a, b T) bool

func InBounds

func InBounds[T numeric](v, min, max T) bool

InBounds reports whether v is in the specified inclusive range.

func InvLerp

func InvLerp[T float](from, to, value T) T

InvLerp returns an interpolation or extrapolation factor considering the given range and weight [t]. The [t] value is usually in the range from 0 to 1.

func Iround

func Iround(x float64) int

Iround is a helper to perform int(math.Round(x)) operation.

This function reduces the number of parenthesis the final expression will have.

func Lerp

func Lerp[T float](from, to, t T) T

Lerp linearly interpolates between [from] and [to] using the weight [t]. The [t] value is usually in the range from 0 to 1.

func LerpClamped

func LerpClamped[T float](from, to, t T) T

LerpClamped linearly interpolates between [from] and [to] using the weight [t]. The [t] value is clamped to the range from 0 to 1.

func Percentage

func Percentage[T numeric](value, max T) T

func RadToDeg

func RadToDeg(r Rad) float64

func RandElem

func RandElem[T any](r *Rand, slice []T) (elem T)

func RandIndex

func RandIndex[T any](r *Rand, slice []T) int

func RandIterate

func RandIterate[T any](r *Rand, slice []T, f func(x T) bool) T

func RandIterateRef

func RandIterateRef[T any](r *Rand, slice []T, f func(x *T) bool) *T

func Remap

func Remap[T float](fromMin, fromMax, toMin, toMax, value T) T

Remap maps a value from one range to another.

The first range is defined by a pair of [fromMin] and [fromMax]. The second range is defined by a pair of [toMin] and [toMax]. The [t] value is usually in the range from 0 to 1.

func Scale

func Scale[T integer](value T, m float64) T

Scale multiplies value by m.

For a floating-point value this operation would not make any sense as it can be expressed value*m, but integer value scaling with a floating point m involves conversions and rounding.

This function rounds the scaled integer to the nearest integer result. For example:

  • Scale(1, 1.8) => 2 (rounds up)
  • Scale(1, 1.4) => 1 (rounds down)
  • Scale(1, 1) => 1
  • Scale(1, 0) => 0

func Shuffle

func Shuffle[T any](r *Rand, slice []T)

Types

type Circle

type Circle struct {
	Center Vec

	Radius float64
}

type Pos

type Pos struct {
	Base   *Vec
	Offset Vec
}

Pos represents a position with optional offset relative to its base.

func MakePos

func MakePos(base Vec) Pos

func (Pos) Resolve

func (p Pos) Resolve() Vec

func (*Pos) Set

func (p *Pos) Set(base *Vec, offsetX, offsetY float64)

func (*Pos) SetBase

func (p *Pos) SetBase(base Vec)

func (Pos) WithOffset

func (p Pos) WithOffset(offsetX, offsetY float64) Pos

type Rad

type Rad float64

Rad represents a radian value. It's not capped in [0, 2*Pi] range.

In terms of the orientations, Pi rotation points the object down (South). Zero radians point towards the right side (East).

func DegToRad

func DegToRad(deg float64) Rad

func (Rad) Abs

func (r Rad) Abs() float64

func (Rad) AngleDelta

func (r Rad) AngleDelta(r2 Rad) Rad

AngleDelta returns an angle delta between two radian values. The sign is preserved.

When using this function to calculate a rotation direction (CW vs CCW), r is a current rotation and r2 is a target rotation.

It doesn't need the angles to be normalized, r=0 and r=2*Pi are considered to have no delta. The return value is always normalized.

func (Rad) Cos

func (r Rad) Cos() float64

func (Rad) EqualApprox

func (r Rad) EqualApprox(other Rad) bool

EqualApprox compares two radian values using EqualApprox function. Note that you may want to normalize the operands in some way before doing this.

func (Rad) LerpAngle

func (r Rad) LerpAngle(toAngle Rad, weight float64) Rad

func (Rad) Normalized

func (r Rad) Normalized() Rad

Normalized returns the equivalent radians value in [0, 2*Pi] range. For example, 3*Pi becomes just Pi.

func (Rad) Positive

func (r Rad) Positive() Rad

Positive returns the equivalent radian value expressed as a positive value.

func (Rad) RotatedTowards

func (r Rad) RotatedTowards(toAngle, amount Rad) Rad

func (Rad) Sin

func (r Rad) Sin() float64

type Rand

type Rand struct {
	// contains filtered or unexported fields
}

func (*Rand) Bool

func (r *Rand) Bool() bool

func (*Rand) Chance

func (r *Rand) Chance(probability float64) bool

func (*Rand) Float

func (r *Rand) Float() float64

func (*Rand) FloatRange

func (r *Rand) FloatRange(min, max float64) float64

func (*Rand) IntRange

func (r *Rand) IntRange(min, max int) int

func (*Rand) Offset

func (r *Rand) Offset(min, max float64) Vec

func (*Rand) PositiveInt

func (r *Rand) PositiveInt() int

func (*Rand) PositiveInt64

func (r *Rand) PositiveInt64() int64

func (*Rand) Rad

func (r *Rand) Rad() Rad

func (*Rand) SetSeed

func (r *Rand) SetSeed(seed int64)

func (*Rand) SetSource

func (r *Rand) SetSource(source rand.Source)

func (*Rand) Uint32

func (r *Rand) Uint32() uint32

func (*Rand) Uint64

func (r *Rand) Uint64() uint64

type RandPicker

type RandPicker[T any] struct {
	// contains filtered or unexported fields
}

RandPicker performs a uniformly distributed random probing among the given objects with weights. Higher the weight, higher the chance of that object of being picked.

func NewRandPicker

func NewRandPicker[T any](r *Rand) *RandPicker[T]

func (*RandPicker[T]) AddOption

func (p *RandPicker[T]) AddOption(value T, weight float64)

func (*RandPicker[T]) IsEmpty

func (p *RandPicker[T]) IsEmpty() bool

func (*RandPicker[T]) Pick

func (p *RandPicker[T]) Pick() T

func (*RandPicker[T]) Reset

func (p *RandPicker[T]) Reset()

type RandSource

type RandSource struct {
	// contains filtered or unexported fields
}

RandSource is a PCG-64 implementation of a rand source.

Its benefits are: * efficient storage (2 uints instead of tables) * can save/load the source state (just 1 uint64 for a state) * fast seeding/reseeding

A zero value of this rand source is not enough. Call [Seed] before using it or load the existing state.

func (*RandSource) GetState

func (s *RandSource) GetState() uint64

func (*RandSource) Int63

func (s *RandSource) Int63() int64

func (*RandSource) Seed

func (s *RandSource) Seed(v int64)

func (*RandSource) SetState

func (s *RandSource) SetState(state uint64)

func (*RandSource) Uint64

func (s *RandSource) Uint64() uint64

type Range

type Range[T numeric] struct {
	Min T
	Max T
}

func MakeRange

func MakeRange[T numeric](min, max T) Range[T]

func (Range[T]) InBounds

func (rng Range[T]) InBounds(minValue, maxValue T) bool

func (Range[T]) IsValid

func (rng Range[T]) IsValid() bool

func (Range[T]) IsZero

func (rng Range[T]) IsZero() bool

func (Range[T]) Len

func (rng Range[T]) Len() int

type Rect

type Rect struct {
	Min Vec
	Max Vec
}

func RectFromStd

func RectFromStd(src image.Rectangle) Rect

RectFromStd converts an image.Rectangle into a Rect. There is Rect.ToStd method to reverse it.

func (Rect) Add

func (r Rect) Add(p Vec) Rect

func (Rect) Center

func (r Rect) Center() Vec

Center returns the center point of this rectangle.

This center point may need some rounding, since a rect of a 3x3 size would return {1.5, 1.5}.

func (Rect) Contains

func (r Rect) Contains(p Vec) bool

func (Rect) ContainsRect

func (r Rect) ContainsRect(other Rect) bool

func (Rect) Height

func (r Rect) Height() float64

func (Rect) Intersects

func (r Rect) Intersects(other Rect) bool

Intersects reports whether r and other have a common intersection.

func (Rect) IsEmpty

func (r Rect) IsEmpty() bool

func (Rect) IsZero

func (r Rect) IsZero() bool

func (Rect) Size

func (r Rect) Size() Vec

Size returns r dimensions in the form of a Vec. In other words, it's identical to Vec{X: r.Width(), Y: r.Height()}.

func (Rect) ToStd

func (r Rect) ToStd() image.Rectangle

ToStd converts an Rect into a image.Rectangle. There is RectFromStd function to reverse it.

func (Rect) Width

func (r Rect) Width() float64

func (Rect) X1

func (r Rect) X1() float64

func (Rect) X2

func (r Rect) X2() float64

func (Rect) Y1

func (r Rect) Y1() float64

func (Rect) Y2

func (r Rect) Y2() float64

type RunningWeightedAverage

type RunningWeightedAverage[T numeric] struct {
	TotalWeight T
	TotalValue  T
}

func (*RunningWeightedAverage[T]) Add

func (avg *RunningWeightedAverage[T]) Add(value, weight T)

func (*RunningWeightedAverage[T]) Scale

func (avg *RunningWeightedAverage[T]) Scale(v float64)

func (*RunningWeightedAverage[T]) Value

func (avg *RunningWeightedAverage[T]) Value() T

type Slider

type Slider struct {

	// Clamp makes the slider use clamping overflow/underflow strategy
	// instead of the default wrapping around strategy.
	Clamp bool
	// contains filtered or unexported fields
}

Slider is a value that can be increased and decreased with a custom overflow/underflow behavior.

Min/Max fields control the range of the accepted values.

It's a useful foundation for more high-level concepts like progress bars and gauges, paginators, option button selector, etc.

func (*Slider) Add

func (s *Slider) Add(v int)

Add adds v to the current slider value. The overflow/underflow behavior depends on the slider settings.

func (*Slider) Dec

func (s *Slider) Dec()

Dec subtracts 1 from the slider value. Semantically identical to Sub(1), but more efficient.

func (*Slider) Inc

func (s *Slider) Inc()

Inc adds 1 to the slider value. Semantically identical to Add(1), but more efficient.

func (*Slider) Len

func (s *Slider) Len() int

Len returns the range of the values. Basically, it returns the max-min result.

func (*Slider) SetBounds

func (s *Slider) SetBounds(min, max int)

SetBounds sets the slider values range. It also sets the current value to min. Use TrySetValue if you need to override that.

If max<min, this method panics.

func (*Slider) Sub

func (s *Slider) Sub(v int)

Sub subtracts v from the current slider value. The overflow/underflow behavior depends on the slider settings.

func (*Slider) TrySetValue

func (s *Slider) TrySetValue(v int) bool

TrySetValue assigns the v value to the slider if it fits its range. Returns true whether the slider value was assigned.

func (*Slider) Value

func (s *Slider) Value() int

Value returns the current slider value. The returned value is guarandeed to be in [min, max] range.

type Vec

type Vec = vec[float64]

Vec is a 2-element structure that is used to represent positions, velocities, and other kinds numerical pairs.

Its implementation as well as its API is inspired by Vector2 type of the Godot game engine. Where feasible, its adjusted to fit Go coding conventions better. Also, earlier versions of Godot used 32-bit values for X and Y; our vector uses 64-bit values.

Since Go has no operator overloading, we implement scalar forms of operations with "f" suffix. So, Add() is used to add two vectors while Addf() is used to add scalar to the vector.

If you need float32 components, use Vec32 type, but keep in mind that Vec should be preferred most of the time.

func RadToVec

func RadToVec(angle Rad) Vec

RadToVec converts a given angle into a normalized vector that encodes that direction.

func VecFromStd

func VecFromStd(src image.Point) Vec

VecFromStd converts an image.Point into a Vec. There is [Vec.ToStd] method to reverse it.

type Vec32

type Vec32 = vec[float32]

Vec32 is like Vec, but with float32-typed fields. You should generally prefer Vec, but for some specific low-level stuff you might want to use a float32 variant.

Most functions of this package operate on Vec, so you will lose some of the convenience while using Vec32.

If anything, Vec32 will be slower on most operations due to the intermediate float32->float64 conversions that will happen here and there. It should be only used as a space optimization, when you need to store lots of vectors and memory locality dominates a small processing overhead. If in doubts, use Vec.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL