math

package
v0.3.24 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package math provides mathematical utilities for the game engine.

Package math provides mathematical utilities for the game engine.

Package math provides mathematical utilities for the game engine.

Package math provides mathematical utilities for the game engine.

Index

Constants

This section is empty.

Variables

View Source
var (
	Black       = NewColor(0, 0, 0, 255)
	White       = NewColor(255, 255, 255, 255)
	Red         = NewColor(255, 0, 0, 255)
	Green       = NewColor(0, 255, 0, 255)
	Blue        = NewColor(0, 0, 255, 255)
	Yellow      = NewColor(255, 255, 0, 255)
	Magenta     = NewColor(255, 0, 255, 255)
	Cyan        = NewColor(0, 255, 255, 255)
	Transparent = NewColor(0, 0, 0, 0)
	Gray        = NewColor(128, 128, 128, 255)
	LightGray   = NewColor(192, 192, 192, 255)
	DarkGray    = NewColor(64, 64, 64, 255)
)

Predefined colors for convenience

Functions

func DegreesToRadians

func DegreesToRadians(degrees float64) float64

DegreesToRadians converts degrees to radians.

func DominantHue added in v0.3.14

func DominantHue(img image.Image) float64

DominantHue returns the dominant hue of an image in degrees [0, 360), computed as the circular mean of each pixel's hue weighted by its saturation and alpha. Transparent and near-gray pixels contribute little, so a sprite's background and shadows don't skew the result. Returns 0 for an image with no colorful pixels (e.g. a grayscale texture).

func HueOf added in v0.3.14

func HueOf(r, g, b float64) float64

HueOf returns the hue of an RGB color in degrees [0, 360). Neutral (gray) colors have no hue; it returns 0 for them.

func RadiansToDegrees

func RadiansToDegrees(radians float64) float64

RadiansToDegrees converts radians to degrees.

Types

type Border added in v0.3.21

type Border struct {
	Left   float64 `json:"left"`
	Top    float64 `json:"top"`
	Right  float64 `json:"right"`
	Bottom float64 `json:"bottom"`
}

Border defines the 9-slice insets, in texture pixels, that split a texture into nine regions: four corners (drawn at natural size), four edges (stretched along one axis), and a center (stretched along both). A zero value means "no border": the whole texture is a single stretchable region.

type Color

type Color struct {
	R uint8 `json:"r"`
	G uint8 `json:"g"`
	B uint8 `json:"b"`
	A uint8 `json:"a"`
}

Color represents a 32-bit RGBA color with 8 bits per channel. This is a common format for graphics APIs and image processing.

The json tags let a color be configured from component args as {"r":255,"g":0,"b":0,"a":255}.

func NewColor

func NewColor(r, g, b, a uint8) Color

NewColor creates a new color from RGBA values (0-255).

func NewColorFromFloats

func NewColorFromFloats(r, g, b, a float64) Color

NewColorFromFloats creates a new color from float values (0.0 to 1.0).

func NewColorFromHex

func NewColorFromHex(hex uint32) Color

NewColorFromHex creates a color from a hexadecimal value (0xRRGGBBAA or 0xRRGGBB).

func ParseHex added in v0.3.0

func ParseHex(s string) (Color, error)

ParseHex parses a color from a hex string. Accepts "#RGB", "#RGBA", "#RRGGBB", and "#RRGGBBAA" (the leading "#" is optional). Returns an error on invalid input.

func (Color) Equals

func (c Color) Equals(other Color) bool

Equals checks if two colors are exactly equal.

func (Color) Hex

func (c Color) Hex() uint32

Hex returns the color as a 32-bit hexadecimal value (0xRRGGBBAA).

func (Color) Lerp

func (c Color) Lerp(target Color, t float64) Color

Lerp linearly interpolates between this color and another by t (0 to 1).

func (Color) Multiply

func (c Color) Multiply(other Color) Color

Multiply multiplies the color by another color (component-wise multiplication).

func (Color) Premultiplied added in v0.3.14

func (c Color) Premultiplied() (r, g, b, a float64)

Premultiplied returns the color's RGBA premultiplied by alpha, as floats in [0, 1]. Straight RGBA is (r, g, b, a); premultiplied is (r*a, g*a, b*a, a). Pipelines that operate on premultiplied-alpha colors (e.g. a color scale applied to a texture) need this form.

func (Color) Scale

func (c Color) Scale(factor float64) Color

Scale scales the color by a scalar factor (multiplies all components).

func (Color) String

func (c Color) String() string

String returns a string representation of the color.

func (Color) ToFloats

func (c Color) ToFloats() (r, g, b, a float64)

ToFloats converts the color to float values (0.0 to 1.0).

func (*Color) UnmarshalJSON added in v0.3.14

func (c *Color) UnmarshalJSON(data []byte) error

UnmarshalJSON lets a Color be configured from either an RGBA object ({"r":255,"g":0,"b":0,"a":255}) or a hex string ("#RRGGBB"). The alpha channel defaults to 255 (opaque) when omitted. A JSON null is a no-op, matching the encoding/json convention.

func (Color) WithAlpha

func (c Color) WithAlpha(alpha uint8) Color

WithAlpha returns a new color with the specified alpha value.

func (Color) WithAlphaFloat

func (c Color) WithAlphaFloat(alpha float64) Color

WithAlphaFloat returns a new color with the specified alpha value (0.0 to 1.0).

type ColorMatrix added in v0.3.14

type ColorMatrix struct {
	M [4][4]float64 // M[out][in]
	T [4]float64    // T[out] constant
}

ColorMatrix is a 4x5 affine transform on straight-alpha RGBA colors in [0,1]. Rows are the output channels R,G,B,A; columns are the input channels R,G,B,A plus a constant. Applying computes out = M*in + T and clamps each channel to [0,1].

func IdentityColorMatrix added in v0.3.14

func IdentityColorMatrix() ColorMatrix

IdentityColorMatrix returns the identity color matrix.

func (ColorMatrix) Apply added in v0.3.14

func (m ColorMatrix) Apply(r, g, b, a float64) (float64, float64, float64, float64)

Apply applies the matrix to a straight-alpha color in [0,1], clamping to [0,1].

func (ColorMatrix) Mul added in v0.3.14

Mul composes two matrices: (m.Mul(n)).Apply(v) == m.Apply(n.Apply(v)). In other words, n is applied first, then m.

type ColorTransform added in v0.3.14

type ColorTransform struct {
	// Tint is the multiply color applied after any grayscale/hue work. It can only
	// darken, never brighten. Default is white (identity). When Solid is true, Tint
	// is instead the flat fill color of the silhouette.
	Tint Color `json:"tint"`

	// Hue rotates the hue forward by this many degrees (0 = none).
	Hue float64 `json:"hue"`

	// HueTo, when set, rotates the texture's dominant hue to this color's hue. Hue
	// (if non-zero) is added on top as an extra offset. Works best on sprites
	// dominated by a single hue family; a grayscale texture has no dominant hue.
	HueTo *Color `json:"hue_to"`

	// Grayscale desaturates fully, keeping only perceived brightness (luma).
	Grayscale bool `json:"grayscale"`

	// Solid replaces the opaque pixels' RGB with Tint, keeping the source alpha
	// (the sprite's shape). Hue/Grayscale are ignored in this mode.
	Solid bool `json:"solid"`

	// Brightness adds a constant to each RGB channel after the grayscale/hue/tint
	// pipeline, in [-1, 1]. Positive lightens toward white, negative darkens toward
	// black. Unlike Tint (a multiply that can only darken), this can brighten, so it
	// is used for state tinting such as a hover highlight.
	Brightness float64 `json:"brightness"`
}

ColorTransform groups the knobs that recolor a sprite's texture. A sprite's `color` JSON arg maps onto this struct. The knobs compose in a fixed pipeline (see Matrix), so results are predictable.

func (ColorTransform) IsIdentity added in v0.3.14

func (t ColorTransform) IsIdentity() bool

IsIdentity reports whether the transform does nothing (a plain draw).

func (ColorTransform) Matrix added in v0.3.14

func (t ColorTransform) Matrix(dominantHue float64) ColorMatrix

Matrix resolves the transform into a single ColorMatrix, applying the knobs in this fixed order: grayscale -> hue -> tint (multiply) -> solid.

dominantHue is the source texture's dominant hue in degrees and is used only by HueTo; pass 0 when it is unknown. Callers with the texture compute it with DominantHue.

type Rect

type Rect struct {
	Position Vector2 // Top-left corner position
	Size     Vector2 // Width and height
}

Rect represents an axis-aligned rectangle (AABB) in 2D space. Commonly used for collision detection, drawing areas, and UI elements.

func NewRect

func NewRect(x, y, width, height float64) Rect

NewRect creates a new rectangle with given position and size.

func NewRectFromVectors

func NewRectFromVectors(position, size Vector2) Rect

NewRectFromVectors creates a new rectangle from Vector2 position and size.

func (Rect) Area

func (r Rect) Area() float64

Area returns the area of the rectangle.

func (Rect) Bottom

func (r Rect) Bottom() float64

Bottom returns the Y coordinate of the bottom edge.

func (Rect) Center

func (r Rect) Center() Vector2

Center returns the center point of the rectangle.

func (Rect) ContainsPoint

func (r Rect) ContainsPoint(point Vector2) bool

ContainsPoint checks if a point is inside the rectangle (inclusive).

func (Rect) ContainsRect

func (r Rect) ContainsRect(other Rect) bool

ContainsRect checks if this rectangle completely contains another rectangle.

func (Rect) Height

func (r Rect) Height() float64

Height returns the height of the rectangle.

func (Rect) Intersection

func (r Rect) Intersection(other Rect) Rect

Intersection returns the overlapping area between two rectangles. Returns zero rectangle if they don't overlap.

func (Rect) Left

func (r Rect) Left() float64

Left returns the X coordinate of the left edge.

func (Rect) Overlaps

func (r Rect) Overlaps(other Rect) bool

Overlaps checks if this rectangle overlaps with another rectangle.

func (Rect) Perimeter

func (r Rect) Perimeter() float64

Perimeter returns the perimeter (circumference) of the rectangle.

func (Rect) Right

func (r Rect) Right() float64

Right returns the X coordinate of the right edge.

func (Rect) Scale

func (r Rect) Scale(scaleX, scaleY float64) Rect

Scale scales the rectangle around its center by the given factors.

func (Rect) String

func (r Rect) String() string

String returns a string representation of the rectangle.

func (Rect) Top

func (r Rect) Top() float64

Top returns the Y coordinate of the top edge.

func (Rect) Translate

func (r Rect) Translate(offset Vector2) Rect

Translate moves the rectangle by the given offset.

func (Rect) Union

func (r Rect) Union(other Rect) Rect

Union returns the smallest rectangle that contains both rectangles.

func (Rect) Width

func (r Rect) Width() float64

Width returns the width of the rectangle.

func (Rect) X

func (r Rect) X() float64

X returns the X coordinate of the left edge.

func (Rect) Y

func (r Rect) Y() float64

Y returns the Y coordinate of the top edge.

type Slice added in v0.3.21

type Slice struct {
	Src Rect
	Dst Rect
}

Slice is one of the up-to-nine regions of a 9-slice: the source rectangle in the texture (texture pixels) and the destination rectangle it fills (in the target's coordinate space, top-left origin).

func Slice9 added in v0.3.21

func Slice9(texW, texH float64, border Border, dst Rect) []Slice

Slice9 splits a texW×texH texture into up to nine source/destination regions that together fill dst. Regions with a zero or negative source or destination area are omitted, so a degenerate target simply produces fewer slices.

Source regions always use the original texture-pixel borders. When the target is smaller than the border sum on an axis, that axis's borders are scaled down proportionally so the corners shrink to fit instead of overflowing the target.

type Transform

type Transform struct {
	Position Vector2 // Translation in world space
	Rotation float64 // Rotation in radians (0 = facing right, positive = counter-clockwise)
	Scale    Vector2 // Scale factors (1,1 = original size)
}

Transform represents a 2D transformation (position, rotation, scale). This is a core component for positioning game objects in the world.

func Identity

func Identity() Transform

Identity returns an identity transform (no translation, rotation, or scale).

func NewTransform

func NewTransform() Transform

NewTransform creates a new transform with default values.

func NewTransformWithPosition

func NewTransformWithPosition(x, y float64) Transform

NewTransformWithPosition creates a new transform with the given position.

func (Transform) Combine

func (t Transform) Combine(other Transform) Transform

Combine combines this transform with another (applies other transform first, then this one).

func (Transform) GetForward

func (t Transform) GetForward() Vector2

GetForward returns the forward direction vector (facing direction based on rotation).

func (Transform) GetRight

func (t Transform) GetRight() Vector2

GetRight returns the right direction vector (perpendicular to forward).

func (Transform) Inverse

func (t Transform) Inverse() Transform

Inverse returns the inverse transform.

func (Transform) LocalToWorld

func (t Transform) LocalToWorld(localPoint Vector2) Vector2

LocalToWorld transforms a local point to world space.

func (Transform) LookAt

func (t Transform) LookAt(target Vector2) Transform

LookAt rotates the transform to look at a target point.

func (Transform) Rotate

func (t Transform) Rotate(angle float64) Transform

Rotate rotates the transform by the given angle (in radians).

func (Transform) ScaleBy

func (t Transform) ScaleBy(scaleX, scaleY float64) Transform

ScaleBy scales the transform by the given factors.

func (Transform) String

func (t Transform) String() string

String returns a string representation of the transform.

func (Transform) Translate

func (t Transform) Translate(offset Vector2) Transform

Translate moves the transform by the given offset.

func (Transform) UniformScale

func (t Transform) UniformScale(factor float64) Transform

UniformScale scales the transform uniformly (same factor for X and Y).

func (Transform) WorldToLocal

func (t Transform) WorldToLocal(worldPoint Vector2) Vector2

WorldToLocal transforms a world point to local space (inverse transform).

type Vector2

type Vector2 struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

Vector2 represents a 2D vector with X and Y coordinates. We use float64 for precision in game calculations.

func NewVector2

func NewVector2(x, y float64) Vector2

NewVector2 creates a new Vector2 with the given coordinates.

func One

func One() Vector2

One returns a vector with both components set to 1.

func Zero

func Zero() Vector2

Zero returns a zero vector (0, 0).

func (Vector2) Add

func (v Vector2) Add(other Vector2) Vector2

Add returns the sum of this vector and another.

func (Vector2) Distance

func (v Vector2) Distance(other Vector2) float64

Distance returns the distance between this vector and another.

func (Vector2) DistanceSquared

func (v Vector2) DistanceSquared(other Vector2) float64

DistanceSquared returns the squared distance (faster than Distance).

func (Vector2) Divide

func (v Vector2) Divide(scalar float64) Vector2

Divide scales the vector by dividing by a scalar value. Returns zero vector if scalar is zero to avoid division by zero.

func (Vector2) Dot

func (v Vector2) Dot(other Vector2) float64

Dot returns the dot product of this vector and another.

func (Vector2) Equals

func (v Vector2) Equals(other Vector2, epsilon float64) bool

Equals checks if two vectors are approximately equal (within epsilon).

func (Vector2) Length

func (v Vector2) Length() float64

Length returns the magnitude (length) of the vector.

func (Vector2) LengthSquared

func (v Vector2) LengthSquared() float64

LengthSquared returns the squared length of the vector (faster than Length).

func (Vector2) Lerp

func (v Vector2) Lerp(target Vector2, t float64) Vector2

Lerp linearly interpolates between this vector and another by t (0 to 1).

func (Vector2) Multiply

func (v Vector2) Multiply(scalar float64) Vector2

Multiply scales the vector by a scalar value.

func (Vector2) Normalize

func (v Vector2) Normalize() Vector2

Normalize returns a unit vector (length 1) in the same direction. If the vector is zero, returns zero vector.

func (Vector2) String

func (v Vector2) String() string

String returns a string representation of the vector.

func (Vector2) Subtract

func (v Vector2) Subtract(other Vector2) Vector2

Subtract returns the difference between this vector and another.

Jump to

Keyboard shortcuts

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