ms2

package
v0.0.0-...-a2463fe Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2024 License: MIT Imports: 4 Imported by: 13

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Collinear

func Collinear(a, b, c Vec, tol float32) bool

Collinear returns true if 3 points lie on a single line to within tol.

func CopyOrientation

func CopyOrientation(f float32, p1, p2, p3 Vec) float32

Orientation calculates the orientation in the plane of 3 points and applies it to f.

  • f returned for counter-clockwise orientation
  • -f returned for clockwise orientation
  • 0 returned for 3 colinear points

func Cos

func Cos(p, q Vec) float32

Cos returns the cosine of the opening angle between p and q.

func Cross

func Cross(p, q Vec) float32

Cross returns the cross product p×q.

func Dot

func Dot(p, q Vec) float32

Dot returns the dot product p·q.

func EqualElem

func EqualElem(a, b Vec, tol float32) bool

EqualElem checks equality between vector elements to within a tolerance.

func EqualMat2

func EqualMat2(a, b Mat2, tolerance float32) bool

EqualMat2 tests the equality of 2x2 matrices.

func Norm

func Norm(p Vec) float32

Norm returns the Euclidean norm of p

|p| = sqrt(p_x^2 + p_y^2).

func Norm2

func Norm2(p Vec) float32

Norm2 returns the Euclidean squared norm of p

|p|^2 = p_x^2 + p_y^2

Types

type Box

type Box struct {
	Min, Max Vec
}

Box is a 2D bounding box. Well formed Boxes Min components are smaller than Max components. Max is the most positive/largest vertex, Min is the most negative/smallest vertex.

func NewBox

func NewBox(x0, y0, x1, y1 float32) Box

NewBox is shorthand for Box{Min:Vec{x0,y0}, Max:Vec{x1,y1}}. The sides are swapped so that the resulting Box is well formed.

func NewCenteredBox

func NewCenteredBox(center, size Vec) Box

NewCenteredBox returns a box centered around center with size dimensions.

func (Box) Add

func (a Box) Add(v Vec) Box

Add adds v to the bounding box components. It is the equivalent of translating the Box by v.

func (Box) Area

func (a Box) Area() float32

Area returns the area of the box. Returns 0 for malformed boxes.

func (Box) Canon

func (a Box) Canon() Box

Canon returns the canonical version of a. The returned Box has minimum and maximum coordinates swapped if necessary so that it is well-formed.

func (Box) Center

func (a Box) Center() Vec

Center returns the center of the Box.

func (Box) Contains

func (a Box) Contains(point Vec) bool

Contains returns true if point is contained within the bounds of the Box.

func (Box) Diagonal

func (a Box) Diagonal() float32

Diagonal returns a's diagonal length: sqrt(L*L + W*W).

func (Box) Empty

func (a Box) Empty() bool

IsEmpty returns true if a Box's volume is zero or if a Min component is greater than its Max component.

func (Box) Equal

func (a Box) Equal(b Box, tol float32) bool

Equal returns true if a and b are within tol of eachother for each box limit component.

func (Box) IncludePoint

func (a Box) IncludePoint(point Vec) Box

IncludePoint returns a box containing both the receiver and the argument point.

func (Box) Intersect

func (a Box) Intersect(b Box) (intersect Box)

Intersect returns a box enclosing the box space shared by both boxes.

func (Box) Scale

func (a Box) Scale(scale Vec) Box

Scale scales the box dimensions and positions in 3 directions. Does not preserve box center. Negative elements of scale can be used to mirror box dimension.

func (Box) ScaleCentered

func (a Box) ScaleCentered(scale Vec) Box

ScaleCentered returns a new Box scaled by a size vector around its center. The scaling is done element wise which is to say the Box's X dimension is scaled by scale.X. Negative elements of scale are interpreted as zero.

func (Box) Size

func (a Box) Size() Vec

Size returns the size of the Box.

func (Box) Union

func (a Box) Union(b Box) Box

Union returns a box enclosing both the receiver and argument Boxes.

func (Box) Vertices

func (a Box) Vertices() [4]Vec

Vertices returns a slice of the 4 vertices corresponding to each of the Box's corners.

The order of the vertices is CCW in the XY plane starting at the box minimum. If viewing box from +Z position the ordering is as follows:

  1. Bottom left.
  2. Bottom right.
  3. Top right.
  4. Top left.

type Line

type Line [2]Vec

Line is an infinite 3D Line defined by two points on the Line.

func (Line) Distance

func (l Line) Distance(p Vec) float32

Distance returns the minimum euclidean Distance of point p to the line.

func (Line) Interpolate

func (l Line) Interpolate(t float32) Vec

Interpolate takes a value between 0 and 1 to linearly interpolate a point on the line.

Interpolate(0) returns l[0]
Interpolate(1) returns l[1]

type Mat2

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

Mat2 is a 2x2 matrix.

func AddMat2

func AddMat2(a, b Mat2) Mat2

AddMat2 adds two 2x2 matrices together.

func IdentityMat2

func IdentityMat2() Mat2

IdentityMat2 returns the 2x2 identity matrix.

func MulMat2

func MulMat2(a, b Mat2) Mat2

MulMat2 multiplies two 2x2 matrices.

func NewMat2

func NewMat2(v []float32) (m Mat2)

NewMat2 instantiates a new matrix from the first 4 floats, row major order. If v is of insufficient length NewMat2 panics.

func Prod

func Prod(v1, v2t Vec) Mat2

Prod performs vector multiplication as if they were matrices

m = v1 * v2ᵀ

func RotationMat2

func RotationMat2(a float32) Mat2

Rotate returns an orthographic 2x2 rotation matrix (right hand rule).

func ScaleMat2

func ScaleMat2(a Mat2, k float32) Mat2

ScaleMat2 multiplies each 2x2 matrix component by a scalar.

func (Mat2) Array

func (m Mat2) Array() (rowmajor [4]float32)

Array returns the matrix values in a static array copy in row major order.

func (Mat2) Determinant

func (a Mat2) Determinant() float32

Determinant returns the determinant of a 2x2 matrix.

func (Mat2) Inverse

func (a Mat2) Inverse() Mat2

Inverse returns the inverse of a 2x2 matrix.

func (Mat2) Put

func (m Mat2) Put(b []float32)

Put stores the matrix values into slice b in row major order. If b is not of length 4 or greater Put panics.

func (Mat2) Transpose

func (a Mat2) Transpose() Mat2

Transpose returns the transpose of a.

func (Mat2) VecCol

func (m Mat2) VecCol(j int) Vec

VecCol returns the jth column as a Vec. VecCol panics if j is not 0 or 1.

func (Mat2) VecRow

func (m Mat2) VecRow(i int) Vec

VecRow returns the ith row as a Vec. VecRow panics if i is not 0 or 1.

type PolygonBuilder

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

PolygonBuilder facilitates polygon construction with arcs, smoothing and chamfers with the PolygonControlPoint type.

func (*PolygonBuilder) Add

Add adds a point in absolute cartesian coordinates to the polygon being built.

func (*PolygonBuilder) AddPolarRTheta

func (p *PolygonBuilder) AddPolarRTheta(r, theta float32) *PolygonControlPoint

AddPolarRTheta adds a point in absolute polar coordinates to the polygon being built.

func (*PolygonBuilder) AddRelative

func (p *PolygonBuilder) AddRelative(v Vec) *PolygonControlPoint

AddRelative adds a point in absolute cartesian coordinates to the polygon being built, relative to last vertex added. If no vertices present then takes origin (x=0,y=0) as reference.

func (*PolygonBuilder) AddRelativeXY

func (p *PolygonBuilder) AddRelativeXY(x, y float32) *PolygonControlPoint

AddRelativeXY is shorthand for PolygonBuilder.AddRelative(Vec{x,y}).

func (*PolygonBuilder) AddXY

func (p *PolygonBuilder) AddXY(x, y float32) *PolygonControlPoint

AddXY adds a point in absolute cartesian coordinates to the polygon being built.

func (*PolygonBuilder) AppendVecs

func (p *PolygonBuilder) AppendVecs(buf []Vec) ([]Vec, error)

AppendVecs appends the Polygon's discretized representation to the argument Vec buffer and returns the result. It does not change the internal state of the PolygonBuilder and thus can be called repeatedly.

func (*PolygonBuilder) DropLast

func (p *PolygonBuilder) DropLast()

DropLast drops the last vertex. Can be called multiple times to drop several vertices.

func (*PolygonBuilder) Nagon

func (p *PolygonBuilder) Nagon(n int, centerDistance float32)

Nagon sets the vertices of p to that of a N sided regular polygon. If n<3 then Nagon does nothing.

func (*PolygonBuilder) NagonSmoothed

func (p *PolygonBuilder) NagonSmoothed(n int, centerDistance float32, facets int, radius float32)

NagonSmoothed sets the vertices of p to that of a N sided regular polygon and smoothes the result. If n<3 or radius<centerDistance then Nagon does nothing.

func (*PolygonBuilder) Reset

func (p *PolygonBuilder) Reset()

Reset resets all polygon builder state dropping all vertices.

type PolygonControlPoint

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

PolygonControlPoint represents a polygon point joined by two edges, or alternatively a smoothed control point, in which case the vertex does not lie in the polygon. It is used by the PolygonBuilder type and notably returned by the Add* methods so that the user may control the polygon's shape. By default represents a vertex joining two other neighboring vertices.

func (*PolygonControlPoint) Arc

func (v *PolygonControlPoint) Arc(radius float32, facets int)

Arc creates an arc between this and the previous PolygonVertex discretised by facets starting at previous radius.

A positive radius specifies counter-clockwise path, a negative radius specifies a clockwise path.

func (*PolygonControlPoint) Chamfer

func (v *PolygonControlPoint) Chamfer(size float32)

Chamfer is a smoothing of a single facet of length `size`.

func (*PolygonControlPoint) Smooth

func (v *PolygonControlPoint) Smooth(radius float32, facets int)

Smooth smoothes this polygon vertex by a radius and discretises the smoothing in facets.

type Spline3

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

Spline3 implements uniform cubic spline logic (degree 3). Keep in mind the iteration over the spline points and how the points are interpreted depend on the type of spline being worked with.

Bézier example:

const Nsamples = 64 // Number of times to sample each set of two Bézier points.
var spline []ms2.Vec = makeBezierSpline()
bz := ms2.SplineBezier()
var curve []ms2.Vec
for i := 0; i < len(spline); i += 4 {
	p0, cp0, cp1, p1 := spline[4*i], spline[4*i+1], spline[4*i+2], spline[4*i+3]
	for t := float32(0.0); t<1; t+=1./Nsamples {
		xy := bz.Evaluate(t, p0, cp0, cp1, p1)
		curve = append(curve, xy)
	}
}
plot(curve)

func NewSpline3

func NewSpline3(matrix4x4 []float32) Spline3

NewSpline3 returns a Spline3 ready for use. See Freya Holmér's video on splines for more information on how a matrix represents a uniform cubic spline.

func SplineBasis

func SplineBasis() Spline3

SplineBasis returns a B-Spline interpreter. Result splines have the following characteristics:

  • C² continuous.
  • No point interpolation.
  • Automatic tangents.
  • Ideal for curvature-sensitive shapes and animations such as camera paths. Used in industrial design.

func SplineBezierCubic

func SplineBezierCubic() Spline3

SplineBezierCubic returns a Bézier cubic spline interpreter. Result splines have the following characteristics:

  • C¹/C⁰ continuous.
  • Interpolates some points.
  • Manual tangents, second and third vectors are control points.
  • Uses in shapes and vector graphics.

Iterate every 3 points. Point0, ControlPoint0, ControlPoint1, Point1.

func SplineBezierQuadratic

func SplineBezierQuadratic() Spline3

SplineBezierQuadratic returns a quadratic spline interpreter (fourth point is inneffective).

  • C¹ continuous.
  • Interpolates all points.
  • Manual tangents.
  • Used in fonts. Cubic beziers are superior.

Iterate every 2 points. Point0, ControlPoint, Point1. Keep in mind this is an innefficient implementation of a quadratic bezier. Is here for convenience.

func SplineCardinal

func SplineCardinal(scale float32) Spline3

SplineCardinal returns a cardinal cubic spline interpreter.

func SplineCatmullRom

func SplineCatmullRom() Spline3

SplineCatmullRom returns a Catmull-Rom cubic spline interpreter, a special case of Cardinal spline when scale=0.5. Result splines have the following characteristics:

  • C¹ continuous.
  • Interpolates all points.
  • Automatic tangents.
  • Used for animation and path smoothing.

func SplineHermite

func SplineHermite() Spline3

SplineHermite returns a Hermite cubic spline interpreter. Result splines have the following characteristics:

  • C¹/C⁰ continuous.
  • Interpolates all points.
  • Explicit tangents. Second and fourth vector arguments specify velocities.
  • Uses in animation, physics simulations and interpolation.

Iterate every 2 points, Point0, Velocity0, Point1, Velocity1.

func (Spline3) BasisFuncs

func (s Spline3) BasisFuncs() (bs [4]func(float32) float32)

BasisFuncs returns the basis functions of the cubic spline corresponding to each of 4 control points.

func (Spline3) BasisFuncsDiff

func (s Spline3) BasisFuncsDiff() (bs [4]func(float32) float32)

BasisFuncs returns the differentiaed basis functions of the cubic spline.

func (Spline3) BasisFuncsDiff2

func (s Spline3) BasisFuncsDiff2() (bs [4]func(float32) float32)

BasisFuncsDiff2 returns the twice-differentiaed basis functions of the cubic spline.

func (Spline3) BasisFuncsDiff3

func (s Spline3) BasisFuncsDiff3() (bs [4]func(float32) float32)

BasisFuncsDiff3 returns the thrice-differentiaed basis functions of the cubic spline.

func (Spline3) Evaluate

func (s Spline3) Evaluate(t float32, v0, v1, v2, v3 Vec) (res Vec)

Evaluate evaluates the cubic spline over 4 points with a value of t. t is usually between 0 and 1 to interpolate the spline.

func (Spline3) Mat4Array

func (s Spline3) Mat4Array() [16]float32

Mat4Array returns a row-major ordered copy of the values of the cubic spline 4x4 matrix.

type Spline3Sampler

type Spline3Sampler struct {
	Spline Spline3

	// Tolerance sets the maximum permissible error for sampling the cubic spline.
	// That is to say the resulting sampled set of line segments will approximate the curve to within Tolerance.
	Tolerance float32
	// contains filtered or unexported fields
}

Spline3Sampler implements algorithms for sampling points of a cubic spline Spline3.

func (*Spline3Sampler) Evaluate

func (s *Spline3Sampler) Evaluate(t float32) Vec

Evaluate evaluates a point on the spline with points set by Spline3Sampler.SetSplinePoints. It calls Spline3.Evaluate with t and the set points.

func (*Spline3Sampler) SampleBisect

func (s *Spline3Sampler) SampleBisect(dst []Vec, maxDepth int) []Vec

SampleBisect samples the cubic spline using bisection method to find points which discretize the curve to within [Spline3Sampler.Tol] error These points are then appended to dst and the result returned.

It does not append points at extremes t=0 and t=1. maxDepth determines the max amount of times to subdivide the curve. The max amount of subdivisions (points appended) is given by 2**maxDepth.

func (*Spline3Sampler) SampleBisectWithExtremes

func (s *Spline3Sampler) SampleBisectWithExtremes(dst []Vec, maxDepth int) []Vec

SampleBisectWithExtremes is same as Spline3Sampler.SampleBisect but adding start and end points at t=0, t=1.

func (*Spline3Sampler) SetSplinePoints

func (s *Spline3Sampler) SetSplinePoints(v0, v1, v2, v3 Vec)

SetSplinePoints sets the 4 [Vec]s which define a cubic spline. They are passed to the Spline on Evaluate calls.

type Triangle

type Triangle [3]Vec

Triangle represents a triangle in 2D space and is composed by 3 vectors corresponding to the position of each of the vertices. Ordering of these vertices decides the "normal" direction. Inverting ordering of two vertices inverts the resulting direction.

func (Triangle) Area

func (t Triangle) Area() float32

Area returns the surface area of the triangle.

func (Triangle) Centroid

func (t Triangle) Centroid() Vec

Centroid returns the intersection of the three medians of the triangle as a point in space.

func (Triangle) IsDegenerate

func (t Triangle) IsDegenerate(tol float32) bool

IsDegenerate returns true if all of triangle's vertices are within tol distance of its longest side.

type Vec

type Vec struct {
	X, Y float32
}

Vec is a 2D vector. It is composed of 2 float32 fields for x and y values in that order.

func AbsElem

func AbsElem(a Vec) Vec

AbsElem returns the vector with components set to their absolute value.

func Add

func Add(p, q Vec) Vec

Add returns the vector sum of p and q.

func AddScalar

func AddScalar(f float32, v Vec) Vec

AddScalar adds f to all of v's components and returns the result.

func AppendGrid

func AppendGrid(dst []Vec, bounds Box, nx, ny int) []Vec

AppendGrid splits the argument bounds Box x,y axes by nx,ny, respectively and generates points on the vertices generated by the division and appends them to dst, returning the result.

Indexing is x-major:

grid := ms2.AppendGrid(nil, bb, nx, ny)
ix, iy := 1, 0
pos := grid[iy*nx + ix]

func CeilElem

func CeilElem(a Vec) Vec

CeilElem returns a with Ceil applied to each component.

func ClampElem

func ClampElem(v, Min, Max Vec) Vec

Clamp returns v with its elements clamped to Min and Max's components.

func CosElem

func CosElem(a Vec) Vec

CosElem returns cos(a) component-wise.

func DivElem

func DivElem(a, b Vec) Vec

DivElem returns the Hadamard product between vector a and the inverse components of vector b.

v = {a.X/b.X, a.Y/b.Y}

func FloorElem

func FloorElem(a Vec) Vec

FloorElem returns a with Floor applied to each component.

func InterpElem

func InterpElem(x, y, a Vec) Vec

InterpElem performs a linear interpolation between x and y's elements, mapping with a's values in interval [0,1]. This function is also known as "mix" in OpenGL.

func MaxElem

func MaxElem(a, b Vec) Vec

MaxElem return a vector with the maximum components of two vectors.

func MinElem

func MinElem(a, b Vec) Vec

MinElem return a vector with the minimum components of two vectors.

func MulElem

func MulElem(a, b Vec) Vec

MulElem returns the Hadamard product between vectors a and b.

v = {a.X*b.X, a.Y*b.Y}

func MulMatVec

func MulMatVec(m Mat2, v Vec) (result Vec)

MulMatVec performs matrix multiplication on v:

result = M * v

func MulMatVecTrans

func MulMatVecTrans(m Mat2, v Vec) (result Vec)

MulMatVecTrans Performs transposed matrix multiplication on v:

result = Mᵀ * v

func RoundElem

func RoundElem(a Vec) Vec

Round rounds the individual elements of a vector.

func Scale

func Scale(f float32, p Vec) Vec

Scale returns the vector p scaled by f.

func SignElem

func SignElem(a Vec) Vec

Sign returns sign function applied to each individual component of a. If a component is zero then zero is returned.

func SinElem

func SinElem(a Vec) Vec

SinElem returns sin(a) component-wise.

func SincosElem

func SincosElem(a Vec) (s, c Vec)

SincosElem returns (sin(a), cos(a)). Is more efficient than calling both SinElem and CosElem.

func SmoothStepElem

func SmoothStepElem(e0, e1, x Vec) Vec

SmoothStepElem performs element-wise smooth cubic hermite interpolation between 0 and 1 when e0 < x < e1.

func Sub

func Sub(p, q Vec) Vec

Sub returns the vector sum of p and -q.

func Unit

func Unit(p Vec) Vec

Unit returns the unit vector colinear to p. Unit returns {NaN,NaN,NaN} for the zero vector.

func (Vec) AllNonzero

func (a Vec) AllNonzero() bool

AllNonzero returns true if all elements of a are nonzero.

func (Vec) Array

func (a Vec) Array() [2]float32

Array returns the ordered components of Vec in a 2 element array [a.x,a.y].

func (Vec) Max

func (a Vec) Max() float32

Max returns the maximum component of a.

func (Vec) Min

func (a Vec) Min() float32

Min returns the minimum component of a.

Jump to

Keyboard shortcuts

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