ebiten/vector/path.go

685 lines
18 KiB
Go
Raw Normal View History

2019-04-13 17:16:18 +02:00
// Copyright 2019 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package vector provides functions for vector graphics rendering.
//
// This package is under experiments and the API might be changed with breaking backward compatibility.
package vector
import (
2021-07-16 09:58:20 +02:00
"math"
2020-10-03 19:35:13 +02:00
"github.com/hajimehoshi/ebiten/v2"
2019-04-13 17:16:18 +02:00
)
// Direction represents clockwise or counterclockwise.
2021-07-17 09:41:12 +02:00
type Direction int
const (
Clockwise Direction = iota
CounterClockwise
)
func abs(x float32) float32 {
if x < 0 {
return -x
}
return x
}
type point struct {
x float32
y float32
2019-04-13 17:16:18 +02:00
}
type subpath struct {
points []point
closed bool
}
func (s *subpath) currentPosition() (point, bool) {
if len(s.points) == 0 {
return point{}, false
}
if s.closed {
return point{}, false
}
return s.points[len(s.points)-1], true
}
func (s *subpath) pointCount() int {
return len(s.points)
}
func (s *subpath) lastPoint() point {
return s.points[len(s.points)-1]
}
func (s *subpath) appendPoint(pt point) {
if s.closed {
panic("vector: a closed subpathment cannot append a new point")
}
// Do not add a too close point to the last point.
// This can cause unexpected rendering results.
if lp := s.lastPoint(); abs(lp.x-pt.x) < 1e-2 && abs(lp.y-pt.y) < 1e-2 {
return
}
s.points = append(s.points, pt)
}
func (s *subpath) close() {
if s.closed {
return
}
s.appendPoint(s.points[0])
s.closed = true
}
// Path represents a collection of path subpathments.
2019-04-13 17:16:18 +02:00
type Path struct {
subpaths []*subpath
2019-04-13 17:16:18 +02:00
}
// MoveTo starts a new subpath with the given position (x, y) without adding a subpath,
2019-04-13 17:16:18 +02:00
func (p *Path) MoveTo(x, y float32) {
p.subpaths = append(p.subpaths, &subpath{
points: []point{
{x: x, y: y},
},
})
2019-04-13 17:16:18 +02:00
}
// LineTo adds a line segment to the path, which starts from the last position of the current subpath
// and ends to the given position (x, y).
// If p doesn't have any subpaths or the last subpath is closed, LineTo sets (x, y) as the start position of a new subpath.
2019-04-13 17:16:18 +02:00
func (p *Path) LineTo(x, y float32) {
if len(p.subpaths) == 0 || p.subpaths[len(p.subpaths)-1].closed {
p.subpaths = append(p.subpaths, &subpath{
points: []point{
{x: x, y: y},
},
})
2021-07-16 18:29:41 +02:00
return
2019-04-13 19:34:42 +02:00
}
p.subpaths[len(p.subpaths)-1].appendPoint(point{x: x, y: y})
2019-04-13 17:16:18 +02:00
}
// QuadTo adds a quadratic Bézier curve to the path.
// (x1, y1) is the control point, and (x2, y2) is the destination.
2021-07-14 16:25:59 +02:00
func (p *Path) QuadTo(x1, y1, x2, y2 float32) {
2022-10-14 15:36:31 +02:00
p.quadTo(point{x: x1, y: y1}, point{x: x2, y: y2}, 0)
}
2022-10-14 12:28:01 +02:00
// lineForTwoPoints returns parameters for a line passing through p0 and p1.
func lineForTwoPoints(p0, p1 point) (a, b, c float32) {
// Line passing through p0 and p1 in the form of ax + by + c = 0
a = p1.y - p0.y
b = -(p1.x - p0.x)
c = (p1.x-p0.x)*p0.y - (p1.y-p0.y)*p0.x
return
}
// isPointCloseToSegment detects the distance between a segment (x0, y0)-(x1, y1) and a point (x, y) is less than allow.
2022-10-14 15:36:31 +02:00
func isPointCloseToSegment(p, p0, p1 point, allow float32) bool {
a, b, c := lineForTwoPoints(p0, p1)
// The distance between a line ax+by+c=0 and (x0, y0) is
// |ax0 + by0 + c| / √(a² + b²)
2022-10-14 15:36:31 +02:00
return allow*allow*(a*a+b*b) > (a*p.x+b*p.y+c)*(a*p.x+b*p.y+c)
2019-12-28 17:47:18 +01:00
}
2022-10-14 12:28:01 +02:00
// crossingPointForTwoLines returns a crossing point for two lines.
func crossingPointForTwoLines(p00, p01, p10, p11 point) point {
a0, b0, c0 := lineForTwoPoints(p00, p01)
a1, b1, c1 := lineForTwoPoints(p10, p11)
det := a0*b1 - a1*b0
return point{
x: (b0*c1 - b1*c0) / det,
y: (a1*c0 - a0*c1) / det,
}
}
func (p *Path) currentPosition() (point, bool) {
if len(p.subpaths) == 0 {
return point{}, false
}
return p.subpaths[len(p.subpaths)-1].currentPosition()
}
2022-10-14 15:36:31 +02:00
func (p *Path) quadTo(p1, p2 point, level int) {
if level > 10 {
return
}
p0, ok := p.currentPosition()
if !ok {
p0 = p1
}
2022-10-14 15:36:31 +02:00
if isPointCloseToSegment(p1, p0, p2, 0.5) {
p.LineTo(p2.x, p2.y)
return
2019-12-28 16:05:03 +01:00
}
2022-10-14 15:36:31 +02:00
p01 := point{
x: (p0.x + p1.x) / 2,
y: (p0.y + p1.y) / 2,
}
p12 := point{
x: (p1.x + p2.x) / 2,
y: (p1.y + p2.y) / 2,
}
p012 := point{
x: (p01.x + p12.x) / 2,
y: (p01.y + p12.y) / 2,
}
p.quadTo(p01, p012, level+1)
p.quadTo(p12, p2, level+1)
2019-12-28 16:05:03 +01:00
}
2020-03-16 15:49:55 +01:00
// CubicTo adds a cubic Bézier curve to the path.
// (x1, y1) and (x2, y2) are the control points, and (x3, y3) is the destination.
2021-07-14 16:25:59 +02:00
func (p *Path) CubicTo(x1, y1, x2, y2, x3, y3 float32) {
2022-10-14 15:36:31 +02:00
p.cubicTo(point{x: x1, y: y1}, point{x: x2, y: y2}, point{x: x3, y: y3}, 0)
}
2022-10-14 15:36:31 +02:00
func (p *Path) cubicTo(p1, p2, p3 point, level int) {
if level > 10 {
return
}
p0, ok := p.currentPosition()
if !ok {
p0 = p1
}
2022-10-14 15:36:31 +02:00
if isPointCloseToSegment(p1, p0, p3, 0.5) && isPointCloseToSegment(p2, p0, p3, 0.5) {
p.LineTo(p3.x, p3.y)
return
}
2022-10-14 15:36:31 +02:00
p01 := point{
x: (p0.x + p1.x) / 2,
y: (p0.y + p1.y) / 2,
}
p12 := point{
x: (p1.x + p2.x) / 2,
y: (p1.y + p2.y) / 2,
}
p23 := point{
x: (p2.x + p3.x) / 2,
y: (p2.y + p3.y) / 2,
}
p012 := point{
x: (p01.x + p12.x) / 2,
y: (p01.y + p12.y) / 2,
}
p123 := point{
x: (p12.x + p23.x) / 2,
y: (p12.y + p23.y) / 2,
}
p0123 := point{
x: (p012.x + p123.x) / 2,
y: (p012.y + p123.y) / 2,
}
p.cubicTo(p01, p012, p0123, level+1)
p.cubicTo(p123, p23, p3, level+1)
}
2022-10-14 15:36:31 +02:00
func normalize(p point) point {
len := float32(math.Hypot(float64(p.x), float64(p.y)))
return point{x: p.x / len, y: p.y / len}
2021-07-16 09:58:20 +02:00
}
2022-10-14 15:36:31 +02:00
func cross(p0, p1 point) float32 {
return p0.x*p1.y - p1.x*p0.y
2021-07-17 09:41:12 +02:00
}
// ArcTo adds an arc curve to the path.
// (x1, y1) is the first control point, and (x2, y2) is the second control point.
2021-07-16 09:58:20 +02:00
func (p *Path) ArcTo(x1, y1, x2, y2, radius float32) {
p0, ok := p.currentPosition()
if !ok {
p0 = point{x: x1, y: y1}
}
2022-10-14 15:36:31 +02:00
d0 := point{
x: p0.x - x1,
y: p0.y - y1,
2022-10-14 15:36:31 +02:00
}
d1 := point{
x: x2 - x1,
y: y2 - y1,
}
if d0 == (point{}) || d1 == (point{}) {
p.LineTo(x1, y1)
return
}
2022-10-14 15:36:31 +02:00
d0 = normalize(d0)
d1 = normalize(d1)
// theta is the angle between two vectors d0 and d1.
theta := math.Acos(float64(d0.x*d1.x + d0.y*d1.y))
2021-07-16 09:58:20 +02:00
// TODO: When theta is bigger than π/2, the arc should be split into two.
// dist is the distance between the control point and the arc's beginning and ending points.
2021-07-16 09:58:20 +02:00
dist := radius / float32(math.Tan(theta/2))
// TODO: What if dist is too big?
// (ax0, ay0) is the start of the arc.
2022-10-14 15:36:31 +02:00
ax0 := x1 + d0.x*dist
ay0 := y1 + d0.y*dist
2021-07-16 09:58:20 +02:00
2021-07-17 09:41:12 +02:00
var cx, cy, a0, a1 float32
var dir Direction
2022-10-14 15:36:31 +02:00
if cross(d0, d1) >= 0 {
cx = ax0 - d0.y*radius
cy = ay0 + d0.x*radius
a0 = float32(math.Atan2(float64(-d0.x), float64(d0.y)))
a1 = float32(math.Atan2(float64(d1.x), float64(-d1.y)))
2021-07-17 09:41:12 +02:00
dir = CounterClockwise
} else {
2022-10-14 15:36:31 +02:00
cx = ax0 + d0.y*radius
cy = ay0 - d0.x*radius
a0 = float32(math.Atan2(float64(d0.x), float64(-d0.y)))
a1 = float32(math.Atan2(float64(-d1.x), float64(d1.y)))
2021-07-17 09:41:12 +02:00
dir = Clockwise
}
p.Arc(cx, cy, radius, a0, a1, dir)
2021-07-16 09:58:20 +02:00
}
2021-07-16 18:29:41 +02:00
// Arc adds an arc to the path.
// (x, y) is the center of the arc.
2021-07-17 09:41:12 +02:00
func (p *Path) Arc(x, y, radius, startAngle, endAngle float32, dir Direction) {
2021-07-16 18:29:41 +02:00
// Adjust the angles.
2021-07-17 09:41:12 +02:00
var da float64
if dir == Clockwise {
for startAngle > endAngle {
endAngle += 2 * math.Pi
}
da = float64(endAngle - startAngle)
} else {
for startAngle < endAngle {
startAngle += 2 * math.Pi
}
da = float64(startAngle - endAngle)
2021-07-16 18:29:41 +02:00
}
2021-07-17 09:41:12 +02:00
2021-07-16 18:29:41 +02:00
if da >= 2*math.Pi {
da = 2 * math.Pi
2021-07-17 09:41:12 +02:00
if dir == Clockwise {
endAngle = startAngle + 2*math.Pi
} else {
startAngle = endAngle + 2*math.Pi
}
2021-07-16 18:29:41 +02:00
}
// If the angle is big, splict this into multiple Arc calls.
if da > math.Pi/2 {
const delta = math.Pi / 3
a := float64(startAngle)
2021-07-17 09:41:12 +02:00
if dir == Clockwise {
for {
p.Arc(x, y, radius, float32(a), float32(math.Min(a+delta, float64(endAngle))), dir)
if a+delta >= float64(endAngle) {
break
}
a += delta
}
} else {
for {
p.Arc(x, y, radius, float32(a), float32(math.Max(a-delta, float64(endAngle))), dir)
if a-delta <= float64(endAngle) {
break
}
a -= delta
2021-07-16 18:29:41 +02:00
}
}
return
}
sin0, cos0 := math.Sincos(float64(startAngle))
x0 := x + radius*float32(cos0)
y0 := y + radius*float32(sin0)
sin1, cos1 := math.Sincos(float64(endAngle))
x1 := x + radius*float32(cos1)
y1 := y + radius*float32(sin1)
p.LineTo(x0, y0)
// Calculate the control points for an approximated Bézier curve.
// See https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/curves/beziers.
l := radius * float32(math.Tan(da/4)*4/3)
2021-07-17 09:41:12 +02:00
var cx0, cy0, cx1, cy1 float32
if dir == Clockwise {
cx0 = x0 + l*float32(-sin0)
cy0 = y0 + l*float32(cos0)
cx1 = x1 + l*float32(sin1)
cy1 = y1 + l*float32(-cos1)
} else {
cx0 = x0 + l*float32(sin0)
cy0 = y0 + l*float32(-cos0)
cx1 = x1 + l*float32(-sin1)
cy1 = y1 + l*float32(cos1)
}
2021-07-16 18:29:41 +02:00
p.CubicTo(cx0, cy0, cx1, cy1, x1, y1)
}
// Close adds a new line from the last position of the current subpath to the first position of the current subpath,
// and marks the current subpath closed.
// Following operations for this path will start with a new subpath.
func (p *Path) Close() {
if len(p.subpaths) == 0 {
return
}
subpath := p.subpaths[len(p.subpaths)-1]
subpath.close()
}
// AppendVerticesAndIndicesForFilling appends vertices and indices to fill this path and returns them.
// AppendVerticesAndIndicesForFilling works in a similar way to the built-in append function.
// If the arguments are nils, AppendVerticesAndIndicesForFilling returns new slices.
//
// The returned vertice's SrcX and SrcY are 0, and ColorR, ColorG, ColorB, and ColorA are 1.
//
// The returned values are intended to be passed to DrawTriangles or DrawTrianglesShader with the fill rule NonZero or EvenOdd
// in order to render a complex polygon like a concave polygon, a polygon with holes, or a self-intersecting polygon.
//
// The returned vertices and indices should be rendered with a solid (non-transparent) color with the default Blend (source-over).
// Otherwise, there is no guarantee about the rendering result.
func (p *Path) AppendVerticesAndIndicesForFilling(vertices []ebiten.Vertex, indices []uint16) ([]ebiten.Vertex, []uint16) {
// TODO: Add tests.
2019-04-13 17:16:18 +02:00
base := uint16(len(vertices))
for _, subpath := range p.subpaths {
if subpath.pointCount() < 3 {
continue
}
for i, pt := range subpath.points {
vertices = append(vertices, ebiten.Vertex{
DstX: pt.x,
DstY: pt.y,
SrcX: 0,
SrcY: 0,
ColorR: 1,
ColorG: 1,
ColorB: 1,
ColorA: 1,
})
if i < 2 {
continue
}
indices = append(indices, base, base+uint16(i-1), base+uint16(i))
}
base += uint16(subpath.pointCount())
2019-04-13 17:16:18 +02:00
}
return vertices, indices
2019-04-13 17:16:18 +02:00
}
2022-10-14 17:23:48 +02:00
// LineCap represents the way in which how the ends of the stroke are rendered.
type LineCap int
const (
LineCapButt LineCap = iota
LineCapRound
LineCapSquare
)
2022-10-14 12:28:01 +02:00
// LineJoin represents the way in which how two segments are joined.
type LineJoin int
const (
LineJoinMiter LineJoin = iota
LineJoinBevel
LineJoinRound
)
// StrokeOptions is options to render a stroke.
type StrokeOptions struct {
2022-10-14 12:06:33 +02:00
// Width is the stroke width in pixels.
//
// The default (zero) value is 0.
Width float32
2022-10-14 12:28:01 +02:00
2022-10-14 17:23:48 +02:00
// LineCap is the way in which how the ends of the stroke are rendered.
// Line caps are not rendered when the subpath is marked as closed.
//
2022-10-14 17:23:48 +02:00
// The default (zero) value is LineCapButt.
LineCap LineCap
2022-10-14 12:28:01 +02:00
// LineJoin is the way in which how two segments are joined.
//
2022-10-14 12:28:01 +02:00
// The default (zero) value is LineJoiMiter.
LineJoin LineJoin
2022-10-14 16:20:16 +02:00
// MiterLimit is the miter limit for LineJoinMiter.
// For details, see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit.
//
// The default (zero) value is 0.
MiterLimit float32
}
// AppendVerticesAndIndicesForStroke appends vertices and indices to render a stroke of this path and returns them.
// AppendVerticesAndIndicesForStroke works in a similar way to the built-in append function.
// If the arguments are nils, AppendVerticesAndIndicesForStroke returns new slices.
//
// The returned vertice's SrcX and SrcY are 0, and ColorR, ColorG, ColorB, and ColorA are 1.
//
2022-10-21 13:40:11 +02:00
// The returned values are intended to be passed to DrawTriangles or DrawTrianglesShader with a solid (non-transparent) color
// with the FillAll fill rule (not NonZero or EvenOdd fill rule).
func (p *Path) AppendVerticesAndIndicesForStroke(vertices []ebiten.Vertex, indices []uint16, op *StrokeOptions) ([]ebiten.Vertex, []uint16) {
2022-10-14 12:28:01 +02:00
if op == nil {
return vertices, indices
}
for _, subpath := range p.subpaths {
if subpath.pointCount() < 2 {
continue
}
var rects [][4]point
for i := 0; i < subpath.pointCount()-1; i++ {
pt := subpath.points[i]
nextPt := subpath.points[i+1]
dx := nextPt.x - pt.x
dy := nextPt.y - pt.y
dist := float32(math.Sqrt(float64(dx*dx + dy*dy)))
extX := (dy) * op.Width / 2 / dist
extY := (-dx) * op.Width / 2 / dist
rects = append(rects, [4]point{
{
x: pt.x + extX,
y: pt.y + extY,
},
{
x: nextPt.x + extX,
y: nextPt.y + extY,
},
{
x: pt.x - extX,
y: pt.y - extY,
},
{
x: nextPt.x - extX,
y: nextPt.y - extY,
},
})
}
for i, rect := range rects {
idx := uint16(len(vertices))
for _, pt := range rect {
vertices = append(vertices, ebiten.Vertex{
DstX: pt.x,
DstY: pt.y,
SrcX: 0,
SrcY: 0,
ColorR: 1,
ColorG: 1,
ColorB: 1,
ColorA: 1,
})
}
indices = append(indices, idx, idx+1, idx+2, idx+1, idx+2, idx+3)
// Add line joints.
var nextRect [4]point
if i < len(rects)-1 {
nextRect = rects[i+1]
} else if subpath.closed {
nextRect = rects[0]
} else {
continue
}
// c is the center of the 'end' edge of the current rect (= the second point of the segment).
c := point{
x: (rect[1].x + rect[3].x) / 2,
y: (rect[1].y + rect[3].y) / 2,
}
// Note that the Y direction and the angle direction are opposite from math's.
a0 := float32(math.Atan2(float64(rect[1].y-c.y), float64(rect[1].x-c.x)))
a1 := float32(math.Atan2(float64(nextRect[0].y-c.y), float64(nextRect[0].x-c.x)))
da := a1 - a0
for da < 0 {
da += 2 * math.Pi
}
if da == 0 {
continue
}
2022-10-14 12:28:01 +02:00
switch op.LineJoin {
case LineJoinMiter:
delta := math.Pi - da
2022-10-14 16:20:16 +02:00
exceed := float32(math.Abs(1/math.Sin(float64(delta/2)))) > op.MiterLimit
2022-10-14 12:28:01 +02:00
var quad Path
quad.MoveTo(c.x, c.y)
if da < math.Pi {
quad.LineTo(rect[1].x, rect[1].y)
if !exceed {
pt := crossingPointForTwoLines(rect[0], rect[1], nextRect[0], nextRect[1])
quad.LineTo(pt.x, pt.y)
}
quad.LineTo(nextRect[0].x, nextRect[0].y)
} else {
quad.LineTo(rect[3].x, rect[3].y)
if !exceed {
pt := crossingPointForTwoLines(rect[2], rect[3], nextRect[2], nextRect[3])
quad.LineTo(pt.x, pt.y)
}
quad.LineTo(nextRect[2].x, nextRect[2].y)
}
vertices, indices = quad.AppendVerticesAndIndicesForFilling(vertices, indices)
case LineJoinBevel:
var tri Path
tri.MoveTo(c.x, c.y)
if da < math.Pi {
tri.LineTo(rect[1].x, rect[1].y)
tri.LineTo(nextRect[0].x, nextRect[0].y)
} else {
tri.LineTo(rect[3].x, rect[3].y)
tri.LineTo(nextRect[2].x, nextRect[2].y)
}
vertices, indices = tri.AppendVerticesAndIndicesForFilling(vertices, indices)
case LineJoinRound:
var arc Path
arc.MoveTo(c.x, c.y)
if da < math.Pi {
arc.Arc(c.x, c.y, op.Width/2, a0, a1, Clockwise)
} else {
arc.Arc(c.x, c.y, op.Width/2, a0+math.Pi, a1+math.Pi, CounterClockwise)
}
vertices, indices = arc.AppendVerticesAndIndicesForFilling(vertices, indices)
}
}
2022-10-14 17:23:48 +02:00
if len(rects) == 0 {
continue
}
// If the subpath is closed, do not render line caps.
if subpath.closed {
continue
}
2022-10-14 17:23:48 +02:00
switch op.LineCap {
case LineCapButt:
// Do nothing.
case LineCapRound:
startR, endR := rects[0], rects[len(rects)-1]
{
c := point{
x: (startR[0].x + startR[2].x) / 2,
y: (startR[0].y + startR[2].y) / 2,
}
a := float32(math.Atan2(float64(startR[0].y-startR[2].y), float64(startR[0].x-startR[2].x)))
var arc Path
arc.MoveTo(startR[0].x, startR[0].y)
arc.Arc(c.x, c.y, op.Width/2, a, a+math.Pi, CounterClockwise)
vertices, indices = arc.AppendVerticesAndIndicesForFilling(vertices, indices)
}
{
c := point{
x: (endR[1].x + endR[3].x) / 2,
y: (endR[1].y + endR[3].y) / 2,
}
a := float32(math.Atan2(float64(endR[1].y-endR[3].y), float64(endR[1].x-endR[3].x)))
var arc Path
arc.MoveTo(endR[1].x, endR[1].y)
arc.Arc(c.x, c.y, op.Width/2, a, a+math.Pi, Clockwise)
vertices, indices = arc.AppendVerticesAndIndicesForFilling(vertices, indices)
}
case LineCapSquare:
startR, endR := rects[0], rects[len(rects)-1]
{
a := math.Atan2(float64(startR[0].y-startR[1].y), float64(startR[0].x-startR[1].x))
s, c := math.Sincos(a)
dx, dy := float32(c)*op.Width/2, float32(s)*op.Width/2
var quad Path
quad.MoveTo(startR[0].x, startR[0].y)
quad.LineTo(startR[0].x+dx, startR[0].y+dy)
quad.LineTo(startR[2].x+dx, startR[2].y+dy)
quad.LineTo(startR[2].x, startR[2].y)
vertices, indices = quad.AppendVerticesAndIndicesForFilling(vertices, indices)
}
{
a := math.Atan2(float64(endR[1].y-endR[0].y), float64(endR[1].x-endR[0].x))
s, c := math.Sincos(a)
dx, dy := float32(c)*op.Width/2, float32(s)*op.Width/2
var quad Path
quad.MoveTo(endR[1].x, endR[1].y)
quad.LineTo(endR[1].x+dx, endR[1].y+dy)
quad.LineTo(endR[3].x+dx, endR[3].y+dy)
quad.LineTo(endR[3].x, endR[3].y)
vertices, indices = quad.AppendVerticesAndIndicesForFilling(vertices, indices)
}
}
}
2022-10-14 17:23:48 +02:00
return vertices, indices
}