pixel

package module
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: May 23, 2024 License: MIT Imports: 6 Imported by: 0

README

Pixel

Pixel is a hand-crafted 2D game library written by faiface in Go.

The original project has not been actively maintained for several years. This fork was created with the aim of fixing security problems and keeping dependencies up to date, but otherwise not making any breaking changes to the library. The goal of this fork is therefore different from other forks, such as Pixel2, which continue the development of the library and are not 100% backwards compatible.

License

MIT

Documentation

Overview

Package pixel implements platform and backend agnostic core of the Pixel game development library.

It specifies the core Target, Triangles, Picture pattern and implements standard elements, such as Sprite, Batch, Vec, Matrix and RGBA in addition to the basic Triangles and Picture implementations: TrianglesData and PictureData.

Index

Constants

This section is empty.

Variables

View Source
var (
	Center      = Anchor{0.5, 0.5}
	Top         = Anchor{0.5, 0}
	TopRight    = Anchor{0, 0}
	Right       = Anchor{0, 0.5}
	BottomRight = Anchor{0, 1}
	Bottom      = Anchor{0.5, 1}
	BottomLeft  = Anchor{1, 1}
	Left        = Anchor{1, 0.5}
	TopLeft     = Anchor{1, 0}
)
View Source
var IM = Matrix{1, 0, 0, 1, 0, 0}

IM stands for identity matrix. Does nothing, no transformation.

View Source
var RGBAModel = color.ModelFunc(rgbaModel)

RGBAModel converts colors to RGBA format.

View Source
var ZR = Rect{Min: ZV, Max: ZV}

ZR is a zero rectangle.

View Source
var ZV = Vec{0, 0}

ZV is a zero vector.

Functions

func Clamp added in v0.7.0

func Clamp(x, min, max float64) float64

Clamp returns x clamped to the interval [min, max].

If x is less than min, min is returned. If x is more than max, max is returned. Otherwise, x is returned.

Types

type Anchor added in v0.12.0

type Anchor Vec

Anchor is a vector used to define anchors, such as `Center`, `Top`, `TopRight`, etc.

func (Anchor) Opposite added in v0.12.0

func (anchor Anchor) Opposite() Anchor

Opposite returns the opposite position of the anchor (ie. Top -> Bottom; BottomLeft -> TopRight, etc.).

func (Anchor) String added in v0.12.0

func (anchor Anchor) String() string

String returns the string representation of an anchor.

type BasicTarget

type BasicTarget interface {
	Target

	// SetMatrix sets a Matrix that every point will be projected by.
	SetMatrix(Matrix)

	// SetColorMask sets a color that will be multiplied with the TrianglesColor property of all
	// Triangles.
	SetColorMask(color.Color)
}

BasicTarget is a Target with additional basic adjustment methods.

type Batch

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

Batch is a Target that allows for efficient drawing of many objects with the same Picture.

To put an object into a Batch, just draw it onto it:

object.Draw(batch)

func NewBatch

func NewBatch(container Triangles, pic Picture) *Batch

NewBatch creates an empty Batch with the specified Picture and container.

The container is where objects get accumulated. Batch will support precisely those Triangles properties, that the supplied container supports. If you retain access to the container and change it, call Dirty to notify Batch about the change.

Note, that if the container does not support TrianglesColor, color masking will not work.

func (*Batch) Clear

func (b *Batch) Clear()

Clear removes all objects from the Batch.

func (*Batch) Dirty

func (b *Batch) Dirty()

Dirty notifies Batch about an external modification of it's container. If you retain access to the Batch's container and change it, call Dirty to notify Batch about the change.

container := &pixel.TrianglesData{}
batch := pixel.NewBatch(container, nil)
container.SetLen(10) // container changed from outside of Batch
batch.Dirty()        // notify Batch about the change

func (*Batch) Draw

func (b *Batch) Draw(t Target)

Draw draws all objects that are currently in the Batch onto another Target.

func (*Batch) MakePicture

func (b *Batch) MakePicture(p Picture) TargetPicture

MakePicture returns a specialized copy of the provided Picture that draws onto this Batch.

func (*Batch) MakeTriangles

func (b *Batch) MakeTriangles(t Triangles) TargetTriangles

MakeTriangles returns a specialized copy of the provided Triangles that draws onto this Batch.

func (*Batch) SetColorMask

func (b *Batch) SetColorMask(c color.Color)

SetColorMask sets a mask color used in the following draws onto the Batch.

func (*Batch) SetMatrix

func (b *Batch) SetMatrix(m Matrix)

SetMatrix sets a Matrix that every point will be projected by.

type Circle added in v0.12.0

type Circle struct {
	Center Vec
	Radius float64
}

Circle is a 2D circle. It is defined by two properties:

  • Center vector
  • Radius float64

func C added in v0.12.0

func C(center Vec, radius float64) Circle

C returns a new Circle with the given radius and center coordinates.

Note that a negative radius is valid.

func (Circle) Area added in v0.12.0

func (c Circle) Area() float64

Area returns the area of the Circle.

func (Circle) Contains added in v0.12.0

func (c Circle) Contains(u Vec) bool

Contains checks whether a vector `u` is contained within this Circle (including it's perimeter).

func (Circle) Formula added in v0.12.0

func (c Circle) Formula() (h, k float64)

Formula returns the values of h and k, for the equation of the circle: (x-h)^2 + (y-k)^2 = r^2 where r is the radius of the circle.

func (Circle) Intersect added in v0.12.0

func (c Circle) Intersect(d Circle) Circle

Intersect returns the maximal Circle which is covered by both `c` and `d`.

If `c` and `d` don't overlap, this function returns a zero-sized circle at the centerpoint between the two Circle's centers.

func (Circle) IntersectLine added in v0.12.0

func (c Circle) IntersectLine(l Line) Vec

IntersectLine will return the shortest Vec such that if the Circle is moved by the Vec returned, the Line and Rect no longer intersect.

func (Circle) IntersectRect added in v0.12.0

func (c Circle) IntersectRect(r Rect) Vec

IntersectRect returns a minimal required Vector, such that moving the circle by that vector would stop the Circle and the Rect intersecting. This function returns a zero-vector if the Circle and Rect do not overlap, and if only the perimeters touch.

This function will return a non-zero vector if:

  • The Rect contains the Circle, partially or fully
  • The Circle contains the Rect, partially of fully

func (Circle) IntersectionPoints added in v0.12.0

func (c Circle) IntersectionPoints(l Line) []Vec

IntersectionPoints returns all the points where the Circle intersects with the line provided. This can be zero, one or two points, depending on the location of the shapes. The points of intersection will be returned in order of closest-to-l.A to closest-to-l.B.

func (Circle) Moved added in v0.12.0

func (c Circle) Moved(delta Vec) Circle

Moved returns the Circle moved by the given vector delta.

func (Circle) Norm added in v0.12.0

func (c Circle) Norm() Circle

Norm returns the Circle in normalized form - this sets the radius to its absolute value.

c := pixel.C(-10, pixel.ZV) c.Norm() // returns pixel.Circle{pixel.Vec{0, 0}, 10}

func (Circle) Resized added in v0.12.0

func (c Circle) Resized(radiusDelta float64) Circle

Resized returns the Circle resized by the given delta. The Circles center is use as the anchor.

c := pixel.C(pixel.ZV, 10) c.Resized(-5) // returns pixel.Circle{pixel.Vec{0, 0}, 5} c.Resized(25) // returns pixel.Circle{pixel.Vec{0, 0}, 35}

func (Circle) String added in v0.12.0

func (c Circle) String() string

String returns the string representation of the Circle.

c := pixel.C(10.1234, pixel.ZV)
c.String()     // returns "Circle(10.12, Vec(0, 0))"
fmt.Println(c) // Circle(10.12, Vec(0, 0))

func (Circle) Union added in v0.12.0

func (c Circle) Union(d Circle) Circle

Union returns the minimal Circle which covers both `c` and `d`.

type ComposeMethod

type ComposeMethod int

ComposeMethod is a Porter-Duff composition method.

const (
	ComposeOver ComposeMethod = iota
	ComposeIn
	ComposeOut
	ComposeAtop
	ComposeRover
	ComposeRin
	ComposeRout
	ComposeRatop
	ComposeXor
	ComposePlus
	ComposeCopy
)

Here's the list of all available Porter-Duff composition methods. Use ComposeOver for the basic alpha blending.

func (ComposeMethod) Compose

func (cm ComposeMethod) Compose(a, b RGBA) RGBA

Compose composes two colors together according to the ComposeMethod. A is the foreground, B is the background.

type ComposeTarget

type ComposeTarget interface {
	BasicTarget

	// SetComposeMethod sets a Porter-Duff composition method to be used.
	SetComposeMethod(ComposeMethod)
}

ComposeTarget is a BasicTarget capable of Porter-Duff composition.

type Drawer

type Drawer struct {
	Triangles Triangles
	Picture   Picture
	Cached    bool
	// contains filtered or unexported fields
}

Drawer glues all the fundamental interfaces (Target, Triangles, Picture) into a coherent and the only intended usage pattern.

Drawer makes it possible to draw any combination of Triangles and Picture onto any Target efficiently.

To create a Drawer, just assign it's Triangles and Picture fields:

d := pixel.Drawer{Triangles: t, Picture: p}

If Triangles is nil, nothing will be drawn. If Picture is nil, Triangles will be drawn without a Picture.

Whenever you change the Triangles, call Dirty to notify Drawer that Triangles changed. You don't need to notify Drawer about a change of the Picture.

Note, that Drawer caches the results of MakePicture from Targets it's drawn to for each Picture it's set to. What it means is that using a Drawer with an unbounded number of Pictures leads to a memory leak, since Drawer caches them and never forgets. In such a situation, create a new Drawer for each Picture.

func (*Drawer) Dirty

func (d *Drawer) Dirty()

Dirty marks the Triangles of this Drawer as changed. If not called, changes will not be visible when drawing.

func (*Drawer) Draw

func (d *Drawer) Draw(t Target)

Draw efficiently draws Triangles with Picture onto the provided Target.

If Triangles is nil, nothing will be drawn. If Picture is nil, Triangles will be drawn without a Picture.

type Line added in v0.12.0

type Line struct {
	A, B Vec
}

Line is a 2D line segment, between points A and B.

func L added in v0.12.0

func L(from, to Vec) Line

L creates and returns a new Line.

func (Line) Bounds added in v0.12.0

func (l Line) Bounds() Rect

Bounds returns the lines bounding box. This is in the form of a normalized Rect.

func (Line) Center added in v0.12.0

func (l Line) Center() Vec

Center will return the point at center of the line; that is, the point equidistant from either end.

func (Line) Closest added in v0.12.0

func (l Line) Closest(v Vec) Vec

Closest will return the point on the line which is closest to the Vec provided.

func (Line) Contains added in v0.12.0

func (l Line) Contains(v Vec) bool

Contains returns whether the provided Vec lies on the line.

func (Line) Formula added in v0.12.0

func (l Line) Formula() (m, b float64)

Formula will return the values that represent the line in the formula: y = mx + b This function will return math.Inf+, math.Inf- for a vertical line.

func (Line) Intersect added in v0.12.0

func (l Line) Intersect(k Line) (Vec, bool)

Intersect will return the point of intersection for the two line segments. If the line segments do not intersect, this function will return the zero-vector and false.

func (Line) IntersectCircle added in v0.12.0

func (l Line) IntersectCircle(c Circle) Vec

IntersectCircle will return the shortest Vec such that moving the Line by that Vec will cause the Line and Circle to no longer intesect. If they do not intersect at all, this function will return a zero-vector.

func (Line) IntersectRect added in v0.12.0

func (l Line) IntersectRect(r Rect) Vec

IntersectRect will return the shortest Vec such that moving the Line by that Vec will cause the Line and Rect to no longer intesect. If they do not intersect at all, this function will return a zero-vector.

func (Line) Len added in v0.12.0

func (l Line) Len() float64

Len returns the length of the line segment.

func (Line) Moved added in v0.12.0

func (l Line) Moved(delta Vec) Line

Moved will return a line moved by the delta Vec provided.

func (Line) Rotated added in v0.12.0

func (l Line) Rotated(around Vec, angle float64) Line

Rotated will rotate the line around the provided Vec.

func (Line) Scaled added in v0.12.0

func (l Line) Scaled(scale float64) Line

Scaled will return the line scaled around the center point.

func (Line) ScaledXY added in v0.12.0

func (l Line) ScaledXY(around Vec, scale float64) Line

ScaledXY will return the line scaled around the Vec provided.

func (Line) String added in v0.12.0

func (l Line) String() string

type Matrix

type Matrix [6]float64

Matrix is a 2x3 affine matrix that can be used for all kinds of spatial transforms, such as movement, scaling and rotations.

Matrix has a handful of useful methods, each of which adds a transformation to the matrix. For example:

pixel.IM.Moved(pixel.V(100, 200)).Rotated(pixel.ZV, math.Pi/2)

This code creates a Matrix that first moves everything by 100 units horizontally and 200 units vertically and then rotates everything by 90 degrees around the origin.

Layout is: [0] [2] [4] [1] [3] [5]

0   0   1  (implicit row)

func (Matrix) Chained

func (m Matrix) Chained(next Matrix) Matrix

Chained adds another Matrix to this one. All tranformations by the next Matrix will be applied after the transformations of this Matrix.

func (Matrix) Moved

func (m Matrix) Moved(delta Vec) Matrix

Moved moves everything by the delta vector.

func (Matrix) Project

func (m Matrix) Project(u Vec) Vec

Project applies all transformations added to the Matrix to a vector u and returns the result.

Time complexity is O(1).

func (Matrix) Rotated

func (m Matrix) Rotated(around Vec, angle float64) Matrix

Rotated rotates everything around a given point by the given angle in radians.

func (Matrix) Scaled

func (m Matrix) Scaled(around Vec, scale float64) Matrix

Scaled scales everything around a given point by the scale factor.

func (Matrix) ScaledXY

func (m Matrix) ScaledXY(around Vec, scale Vec) Matrix

ScaledXY scales everything around a given point by the scale factor in each axis respectively.

func (Matrix) String

func (m Matrix) String() string

String returns a string representation of the Matrix.

m := pixel.IM
fmt.Println(m) // Matrix(1 0 0 | 0 1 0)

func (Matrix) Unproject

func (m Matrix) Unproject(u Vec) Vec

Unproject does the inverse operation to Project.

Time complexity is O(1).

type Picture

type Picture interface {
	// Bounds returns the rectangle of the Picture. All data is located within this rectangle.
	// Querying properties outside the rectangle should return default value of that property.
	Bounds() Rect
}

Picture represents a rectangular area of raster data, such as a color. It has Bounds which specify the rectangle where data is located.

type PictureColor

type PictureColor interface {
	Picture
	Color(at Vec) RGBA
}

PictureColor specifies Picture with Color property, so that every position inside the Picture's Bounds has a color.

Positions outside the Picture's Bounds must return full transparent (Alpha(0)).

type PictureData

type PictureData struct {
	Pix    []color.RGBA
	Stride int
	Rect   Rect
}

PictureData specifies an in-memory rectangular area of pixels and implements Picture and PictureColor.

Pixels are small rectangles of unit size of form (x, y, x+1, y+1), where x and y are integers. PictureData contains and assigns a color to all pixels that are at least partially contained within it's Bounds (Rect).

The struct's innards are exposed for convenience, manual modification is at your own risk.

The format of the pixels is color.RGBA and not pixel.RGBA for a very serious reason: pixel.RGBA takes up 8x more memory than color.RGBA.

func MakePictureData

func MakePictureData(rect Rect) *PictureData

MakePictureData creates a zero-initialized PictureData covering the given rectangle.

func PictureDataFromImage

func PictureDataFromImage(img image.Image) *PictureData

PictureDataFromImage converts an image.Image into PictureData.

The resulting PictureData's Bounds will be the equivalent of the supplied image.Image's Bounds.

func PictureDataFromPicture

func PictureDataFromPicture(pic Picture) *PictureData

PictureDataFromPicture converts an arbitrary Picture into PictureData (the conversion may be lossy, because PictureData works with unit-sized pixels).

Bounds are preserved.

func (*PictureData) Bounds

func (pd *PictureData) Bounds() Rect

Bounds returns the bounds of this PictureData.

func (*PictureData) Color

func (pd *PictureData) Color(at Vec) RGBA

Color returns the color located at the given position.

func (*PictureData) Image

func (pd *PictureData) Image() *image.RGBA

Image converts PictureData into an image.RGBA.

The resulting image.RGBA's Bounds will be equivalent of the PictureData's Bounds.

func (*PictureData) Index

func (pd *PictureData) Index(at Vec) int

Index returns the index of the pixel at the specified position inside the Pix slice.

type RGBA

type RGBA struct {
	R, G, B, A float64
}

RGBA represents an alpha-premultiplied RGBA color with components within range [0, 1].

The difference between color.RGBA is that the value range is [0, 1] and the values are floats.

func Alpha

func Alpha(a float64) RGBA

Alpha returns a white RGBA color with the given alpha component.

func RGB

func RGB(r, g, b float64) RGBA

RGB returns a fully opaque RGBA color with the given RGB values.

A common way to construct a transparent color is to create one with RGB constructor, then multiply it by a color obtained from the Alpha constructor.

func ToRGBA

func ToRGBA(c color.Color) RGBA

ToRGBA converts a color to RGBA format. Using this function is preferred to using RGBAModel, for performance (using RGBAModel introduces additional unnecessary allocations).

func (RGBA) Add

func (c RGBA) Add(d RGBA) RGBA

Add adds color d to color c component-wise and returns the result (the components are not clamped).

func (RGBA) Mul

func (c RGBA) Mul(d RGBA) RGBA

Mul multiplies color c by color d component-wise (the components are not clamped).

func (RGBA) RGBA

func (c RGBA) RGBA() (r, g, b, a uint32)

RGBA returns alpha-premultiplied red, green, blue and alpha components of the RGBA color.

func (RGBA) Scaled

func (c RGBA) Scaled(scale float64) RGBA

Scaled multiplies each component of color c by scale and returns the result (the components are not clamped).

func (RGBA) Sub

func (c RGBA) Sub(d RGBA) RGBA

Sub subtracts color d from color c component-wise and returns the result (the components are not clamped).

type Rect

type Rect struct {
	Min, Max Vec
}

Rect is a 2D rectangle aligned with the axes of the coordinate system. It is defined by two points, Min and Max.

The invariant should hold, that Max's components are greater or equal than Min's components respectively.

func R

func R(minX, minY, maxX, maxY float64) Rect

R returns a new Rect with given the Min and Max coordinates.

Note that the returned rectangle is not automatically normalized.

func (Rect) AlignedTo added in v0.12.0

func (rect Rect) AlignedTo(anchor Anchor) Rect

AlignedTo returns the rect moved by the given anchor.

func (Rect) AnchorPos added in v0.12.0

func (r Rect) AnchorPos(anchor Anchor) Vec

AnchorPos returns the relative position of the given anchor.

func (Rect) Area added in v0.7.0

func (r Rect) Area() float64

Area returns the area of r. If r is not normalized, area may be negative.

func (Rect) Center

func (r Rect) Center() Vec

Center returns the position of the center of the Rect. `rect.Center()` is equivalent to `rect.Anchor(pixel.Anchor.Center)`

func (Rect) Contains

func (r Rect) Contains(u Vec) bool

Contains checks whether a vector u is contained within this Rect (including it's borders).

func (Rect) Edges added in v0.12.0

func (r Rect) Edges() [4]Line

Edges will return the four lines which make up the edges of the rectangle.

func (Rect) H

func (r Rect) H() float64

H returns the height of the Rect.

func (Rect) Intersect added in v0.7.0

func (r Rect) Intersect(s Rect) Rect

Intersect returns the maximal Rect which is covered by both r and s. Rects r and s must be normalized.

If r and s don't overlap, this function returns a zero-rectangle.

func (Rect) IntersectCircle added in v0.12.0

func (r Rect) IntersectCircle(c Circle) Vec

IntersectCircle returns a minimal required Vector, such that moving the rect by that vector would stop the Circle and the Rect intersecting. This function returns a zero-vector if the Circle and Rect do not overlap, and if only the perimeters touch.

This function will return a non-zero vector if:

  • The Rect contains the Circle, partially or fully
  • The Circle contains the Rect, partially of fully

func (Rect) IntersectLine added in v0.12.0

func (r Rect) IntersectLine(l Line) Vec

IntersectLine will return the shortest Vec such that if the Rect is moved by the Vec returned, the Line and Rect no longer intersect.

func (Rect) IntersectionPoints added in v0.12.0

func (r Rect) IntersectionPoints(l Line) []Vec

IntersectionPoints returns all the points where the Rect intersects with the line provided. This can be zero, one or two points, depending on the location of the shapes. The points of intersection will be returned in order of closest-to-l.A to closest-to-l.B.

func (Rect) Intersects added in v0.12.0

func (r Rect) Intersects(s Rect) bool

Intersects returns whether or not the given Rect intersects at any point with this Rect.

This function is overall about 5x faster than Intersect, so it is better to use if you have no need for the returned Rect from Intersect.

func (Rect) Moved

func (r Rect) Moved(delta Vec) Rect

Moved returns the Rect moved (both Min and Max) by the given vector delta.

func (Rect) Norm

func (r Rect) Norm() Rect

Norm returns the Rect in normal form, such that Max is component-wise greater or equal than Min.

func (Rect) Resized

func (r Rect) Resized(anchor, size Vec) Rect

Resized returns the Rect resized to the given size while keeping the position of the given anchor.

r.Resized(r.Min, size)      // resizes while keeping the position of the lower-left corner
r.Resized(r.Max, size)      // same with the top-right corner
r.Resized(r.Center(), size) // resizes around the center

This function does not make sense for resizing a rectangle of zero area and will panic. Use ResizedMin in the case of zero area.

func (Rect) ResizedMin

func (r Rect) ResizedMin(size Vec) Rect

ResizedMin returns the Rect resized to the given size while keeping the position of the Rect's Min.

Sizes of zero area are safe here.

func (Rect) Size

func (r Rect) Size() Vec

Size returns the vector of width and height of the Rect.

func (Rect) String

func (r Rect) String() string

String returns the string representation of the Rect.

r := pixel.R(100, 50, 200, 300)
r.String()     // returns "Rect(100, 50, 200, 300)"
fmt.Println(r) // Rect(100, 50, 200, 300)

func (Rect) Union added in v0.6.0

func (r Rect) Union(s Rect) Rect

Union returns the minimal Rect which covers both r and s. Rects r and s must be normalized.

func (Rect) Vertices added in v0.12.0

func (r Rect) Vertices() [4]Vec

Vertices returns a slice of the four corners which make up the rectangle.

func (Rect) W

func (r Rect) W() float64

W returns the width of the Rect.

type Sprite

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

Sprite is a drawable frame of a Picture. It's anchored by the center of it's Picture's frame.

Frame specifies a rectangular portion of the Picture that will be drawn. For example, this creates a Sprite that draws the whole Picture:

sprite := pixel.NewSprite(pic, pic.Bounds())

Note, that Sprite caches the results of MakePicture from Targets it's drawn to for each Picture it's set to. What it means is that using a Sprite with an unbounded number of Pictures leads to a memory leak, since Sprite caches them and never forgets. In such a situation, create a new Sprite for each Picture.

func NewSprite

func NewSprite(pic Picture, frame Rect) *Sprite

NewSprite creates a Sprite from the supplied frame of a Picture.

func (*Sprite) Draw

func (s *Sprite) Draw(t Target, matrix Matrix)

Draw draws the Sprite onto the provided Target. The Sprite will be transformed by the given Matrix.

This method is equivalent to calling DrawColorMask with nil color mask.

func (*Sprite) DrawColorMask added in v0.6.0

func (s *Sprite) DrawColorMask(t Target, matrix Matrix, mask color.Color)

DrawColorMask draws the Sprite onto the provided Target. The Sprite will be transformed by the given Matrix and all of it's color will be multiplied by the given mask.

If the mask is nil, a fully opaque white mask will be used, which causes no effect.

func (*Sprite) Frame

func (s *Sprite) Frame() Rect

Frame returns the current Sprite's frame.

func (*Sprite) Picture

func (s *Sprite) Picture() Picture

Picture returns the current Sprite's Picture.

func (*Sprite) Set

func (s *Sprite) Set(pic Picture, frame Rect)

Set sets a new frame of a Picture for this Sprite.

func (*Sprite) SetCached added in v0.12.0

func (s *Sprite) SetCached(cached bool)

SetCached makes the sprite cache all the incoming pictures if the argument is true, and doesn't make it do that if the argument is false.

type Target

type Target interface {
	// MakeTriangles generates a specialized copy of the provided Triangles.
	//
	// When calling Draw method on the returned TargetTriangles, the TargetTriangles will be
	// drawn onto the Target that generated them.
	//
	// Note, that not every Target has to recognize all possible types of Triangles. Some may
	// only recognize TrianglesPosition and TrianglesColor and ignore all other properties (if
	// present) when making new TargetTriangles. This varies from Target to Target.
	MakeTriangles(Triangles) TargetTriangles

	// MakePicture generates a specialized copy of the provided Picture.
	//
	// When calling Draw method on the returned TargetPicture, the TargetPicture will be drawn
	// onto the Target that generated it together with the TargetTriangles supplied to the Draw
	// method.
	MakePicture(Picture) TargetPicture
}

Target is something that can be drawn onto, such as a window, a canvas, and so on.

You can notice, that there are no "drawing" methods in a Target. That's because all drawing happens indirectly through Triangles and Picture instances generated via MakeTriangles and MakePicture method.

type TargetPicture

type TargetPicture interface {
	Picture

	// Draw draws the supplied TargetTriangles (which must be generated by the same Target as
	// this TargetPicture) with this TargetPicture. The TargetTriangles should utilize the data
	// from this TargetPicture in some way.
	Draw(TargetTriangles)
}

TargetPicture is a Picture generated by a Target using MakePicture method. This Picture can be drawn onto that (no other) Target together with a TargetTriangles generated by the same Target.

The TargetTriangles specify where, shape and how the Picture should be drawn.

type TargetTriangles

type TargetTriangles interface {
	Triangles

	// Draw draws Triangles onto an associated Target.
	Draw()
}

TargetTriangles are Triangles generated by a Target with MakeTriangles method. They can be drawn onto that (no other) Target.

type Triangles

type Triangles interface {
	// Len returns the number of vertices. The number of triangles is the number of vertices
	// divided by 3.
	Len() int

	// SetLen resizes Triangles to len vertices. If Triangles B were obtained by calling Slice
	// method on Triangles A, the relationship between A and B is undefined after calling SetLen
	// on either one of them.
	SetLen(len int)

	// Slice returns a sub-Triangles of this Triangles, covering vertices in range [i, j).
	//
	// If Triangles B were obtained by calling Slice(4, 9) on Triangles A, then A and B must
	// share the same underlying data. Modifying B must change the contents of A in range
	// [4, 9). The vertex with index 0 at B is the vertex with index 4 in A, and so on.
	//
	// Returned Triangles must have the same underlying type.
	Slice(i, j int) Triangles

	// Update copies vertex properties from the supplied Triangles into this Triangles.
	//
	// Properies not supported by these Triangles should be ignored. Properties not supported by
	// the supplied Triangles should be left untouched.
	//
	// The two Triangles must have the same Len.
	Update(Triangles)

	// Copy creates an exact independent copy of this Triangles (with the same underlying type).
	Copy() Triangles
}

Triangles represents a list of vertices, where each three vertices form a triangle. (First, second and third is the first triangle, fourth, fifth and sixth is the second triangle, etc.)

type TrianglesClipped added in v0.12.0

type TrianglesClipped interface {
	Triangles
	ClipRect(i int) (rect Rect, is bool)
}

TrianglesClipped specifies Triangles with Clipping Rectangle property.

The first value returned from ClipRect method is the clipping rectangle. The second one specifies if the triangle is clipped.

type TrianglesColor

type TrianglesColor interface {
	Triangles
	Color(i int) RGBA
}

TrianglesColor specifies Triangles with Color property.

type TrianglesData

type TrianglesData []struct {
	Position  Vec
	Color     RGBA
	Picture   Vec
	Intensity float64
	ClipRect  Rect
	IsClipped bool
}

TrianglesData specifies a list of Triangles vertices with three common properties: TrianglesPosition, TrianglesColor and TrianglesPicture.

func MakeTrianglesData

func MakeTrianglesData(len int) *TrianglesData

MakeTrianglesData creates TrianglesData of length len initialized with default property values.

Prefer this function to make(TrianglesData, len), because make zeros them, while this function does the correct intialization.

func (*TrianglesData) ClipRect added in v0.12.0

func (td *TrianglesData) ClipRect(i int) (rect Rect, has bool)

ClipRect returns the clipping rectangle property of the i-th vertex.

func (*TrianglesData) Color

func (td *TrianglesData) Color(i int) RGBA

Color returns the color property of i-th vertex.

func (*TrianglesData) Copy

func (td *TrianglesData) Copy() Triangles

Copy returns an exact independent copy of this TrianglesData.

func (*TrianglesData) Len

func (td *TrianglesData) Len() int

Len returns the number of vertices in TrianglesData.

func (*TrianglesData) Picture

func (td *TrianglesData) Picture(i int) (pic Vec, intensity float64)

Picture returns the picture property of i-th vertex.

func (*TrianglesData) Position

func (td *TrianglesData) Position(i int) Vec

Position returns the position property of i-th vertex.

func (*TrianglesData) SetLen

func (td *TrianglesData) SetLen(len int)

SetLen resizes TrianglesData to len, while keeping the original content.

If len is greater than TrianglesData's current length, the new data is filled with default values ((0, 0), white, (0, 0), 0).

func (*TrianglesData) Slice

func (td *TrianglesData) Slice(i, j int) Triangles

Slice returns a sub-Triangles of this TrianglesData.

func (*TrianglesData) Update

func (td *TrianglesData) Update(t Triangles)

Update copies vertex properties from the supplied Triangles into this TrianglesData.

TrianglesPosition, TrianglesColor and TrianglesTexture are supported.

type TrianglesPicture

type TrianglesPicture interface {
	Triangles
	Picture(i int) (pic Vec, intensity float64)
}

TrianglesPicture specifies Triangles with Picture property.

The first value returned from Picture method is Picture coordinates. The second one specifies the weight of the Picture. Value of 0 means, that Picture should be completely ignored, 1 means that is should be fully included and anything in between means anything in between.

type TrianglesPosition

type TrianglesPosition interface {
	Triangles
	Position(i int) Vec
}

TrianglesPosition specifies Triangles with Position property.

type Vec

type Vec struct {
	X, Y float64
}

Vec is a 2D vector type with X and Y coordinates.

Create vectors with the V constructor:

u := pixel.V(1, 2)
v := pixel.V(8, -3)

Use various methods to manipulate them:

  w := u.Add(v)
  fmt.Println(w)        // Vec(9, -1)
  fmt.Println(u.Sub(v)) // Vec(-7, 5)
  u = pixel.V(2, 3)
  v = pixel.V(8, 1)
  if u.X < 0 {
	     fmt.Println("this won't happen")
  }
  x := u.Unit().Dot(v.Unit())

func Lerp

func Lerp(a, b Vec, t float64) Vec

Lerp returns a linear interpolation between vectors a and b.

This function basically returns a point along the line between a and b and t chooses which one. If t is 0, then a will be returned, if t is 1, b will be returned. Anything between 0 and 1 will return the appropriate point between a and b and so on.

func Unit added in v0.7.0

func Unit(angle float64) Vec

Unit returns a vector of length 1 facing the given angle.

func V

func V(x, y float64) Vec

V returns a new 2D vector with the given coordinates.

func (Vec) Add added in v0.6.0

func (u Vec) Add(v Vec) Vec

Add returns the sum of vectors u and v.

func (Vec) Angle

func (u Vec) Angle() float64

Angle returns the angle between the vector u and the x-axis. The result is in range [-Pi, Pi].

func (Vec) Cross

func (u Vec) Cross(v Vec) float64

Cross return the cross product of vectors u and v.

func (Vec) Dot

func (u Vec) Dot(v Vec) float64

Dot returns the dot product of vectors u and v.

func (Vec) Eq added in v0.12.0

func (u Vec) Eq(v Vec) bool

Eq will compare two vectors and return whether they are equal accounting for rounding errors. At worst, the result is correct to 7 significant digits.

func (Vec) Floor added in v0.12.0

func (u Vec) Floor() Vec

Floor converts x and y to their integer equivalents.

func (Vec) Len

func (u Vec) Len() float64

Len returns the length of the vector u.

func (Vec) Map

func (u Vec) Map(f func(float64) float64) Vec

Map applies the function f to both x and y components of the vector u and returns the modified vector.

u := pixel.V(10.5, -1.5)
v := u.Map(math.Floor)   // v is Vec(10, -2), both components of u floored

func (Vec) Normal added in v0.7.0

func (u Vec) Normal() Vec

Normal returns a vector normal to u. Equivalent to u.Rotated(math.Pi / 2), but faster.

func (Vec) Project added in v0.7.0

func (u Vec) Project(v Vec) Vec

Project returns a projection (or component) of vector u in the direction of vector v.

Behaviour is undefined if v is a zero vector.

func (Vec) Rotated

func (u Vec) Rotated(angle float64) Vec

Rotated returns the vector u rotated by the given angle in radians.

func (Vec) Scaled

func (u Vec) Scaled(c float64) Vec

Scaled returns the vector u multiplied by c.

func (Vec) ScaledXY

func (u Vec) ScaledXY(v Vec) Vec

ScaledXY returns the vector u multiplied by the vector v component-wise.

func (Vec) SqLen added in v0.12.0

func (u Vec) SqLen() float64

SqLen returns the squared length of the vector u (faster to compute than Len).

func (Vec) String

func (u Vec) String() string

String returns the string representation of the vector u.

u := pixel.V(4.5, -1.3)
u.String()     // returns "Vec(4.5, -1.3)"
fmt.Println(u) // Vec(4.5, -1.3)

func (Vec) Sub added in v0.6.0

func (u Vec) Sub(v Vec) Vec

Sub returns the difference betweeen vectors u and v.

func (Vec) To added in v0.7.0

func (u Vec) To(v Vec) Vec

To returns the vector from u to v. Equivalent to v.Sub(u).

func (Vec) Unit

func (u Vec) Unit() Vec

Unit returns a vector of length 1 facing the direction of u (has the same angle).

func (Vec) XY

func (u Vec) XY() (x, y float64)

XY returns the components of the vector in two return values.

Directories

Path Synopsis
Package imdraw implements a basic primitive geometry shape and pictured polygon drawing for Pixel with a nice immediate-mode-like API.
Package imdraw implements a basic primitive geometry shape and pictured polygon drawing for Pixel with a nice immediate-mode-like API.
Package pixelgl implements efficient OpenGL targets and utilities for the Pixel game development library, specifically Window and Canvas.
Package pixelgl implements efficient OpenGL targets and utilities for the Pixel game development library, specifically Window and Canvas.
Package text implements efficient text drawing for the Pixel library.
Package text implements efficient text drawing for the Pixel library.

Jump to

Keyboard shortcuts

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