d2scene

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: MPL-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package d2scene defines the renderer-neutral scene representation used by D2's raster export pipeline.

A Document is owned by its builder and is treated as immutable once it is handed to a renderer. Renderers may therefore read the same document concurrently at different animation times.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AnimationProperty

type AnimationProperty uint8
const (
	AnimateOpacity AnimationProperty = iota
	AnimateTransform
	AnimateStrokeDashOffset
	AnimateFillColor
	AnimateStrokeColor
	AnimateDropShadow
)

type AnimationValue

type AnimationValue struct {
	Kind      AnimationValueKind
	Number    float64
	Transform Matrix
	Color     color.NRGBA
	Shadow    DropShadow
}

AnimationValue is a small tagged union so renderers must handle every value kind explicitly. Unused fields are ignored.

func ColorValue

func ColorValue(value color.NRGBA) AnimationValue

func NumberValue

func NumberValue(value float64) AnimationValue

func ShadowValue

func ShadowValue(value DropShadow) AnimationValue

func TransformValue

func TransformValue(value Matrix) AnimationValue

type AnimationValueKind

type AnimationValueKind uint8
const (
	NumberAnimationValue AnimationValueKind = iota
	TransformAnimationValue
	ColorAnimationValue
	ShadowAnimationValue
)

type AspectAlign

type AspectAlign uint8
const (
	AlignNone AspectAlign = iota
	AlignXMinYMin
	AlignXMidYMin
	AlignXMaxYMin
	AlignXMinYMid
	AlignXMidYMid
	AlignXMaxYMid
	AlignXMinYMax
	AlignXMidYMax
	AlignXMaxYMax
)

type AspectFit

type AspectFit uint8
const (
	AspectMeet AspectFit = iota
	AspectSlice
)

type AspectRatio

type AspectRatio struct {
	Align AspectAlign
	Fit   AspectFit
}

type Asset

type Asset interface {
	// contains filtered or unexported methods
}

Asset is a closed set of fully resolved, network-free scene resources. Asset byte slices are retained by the Document and must not be mutated after construction. Builders copy mutable caller data before retention; immutable process-owned resources may be shared across Documents.

type AssetID

type AssetID string

type BlendMode

type BlendMode uint8
const (
	BlendNormal BlendMode = iota
	BlendMultiply
	BlendDarken
	BlendColorBurn
	BlendOverlay
	BlendLighten
)

type Bounds

type Bounds struct {
	Min   Point
	Max   Point
	Valid bool
}

Bounds is an axis-aligned bounding box. Valid distinguishes an empty set from a zero-area bound such as a point or a horizontal line.

func BoundsFromPoints

func BoundsFromPoints(points ...Point) Bounds

BoundsFromPoints returns the smallest bounds containing points.

func NewBounds

func NewBounds(x0, y0, x1, y1 float64) Bounds

NewBounds constructs valid bounds and normalizes the two corners.

func PrimitiveBounds

func PrimitiveBounds(primitive Primitive, m Matrix) (Bounds, error)

PrimitiveBounds returns conservative painted bounds after applying m. Path and ellipse geometry extrema are analytic; stroke expansion is deliberately conservative until the stroker computes its exact outline.

func (Bounds) Box

func (b Bounds) Box() Box

func (Bounds) Expand

func (b Bounds) Expand(x, y float64) Bounds

Expand grows bounds in both directions. A negative amount shrinks it and may produce invalid bounds.

func (Bounds) Height

func (b Bounds) Height() float64

func (Bounds) Include

func (b Bounds) Include(p Point) Bounds

Include returns bounds containing b and p.

func (Bounds) Intersect

func (b Bounds) Intersect(other Bounds) Bounds

Intersect returns the common area of two bounds, or invalid bounds when they do not overlap.

func (Bounds) IsFinite

func (b Bounds) IsFinite() bool

func (Bounds) Transform

func (b Bounds) Transform(m Matrix) Bounds

Transform returns the axis-aligned bounds of the transformed corners.

func (Bounds) Translate

func (b Bounds) Translate(v Point) Bounds

Translate returns bounds shifted by v.

func (Bounds) Union

func (b Bounds) Union(other Bounds) Bounds

Union returns the smallest bounds containing both operands.

func (Bounds) Width

func (b Bounds) Width() float64

type Box

type Box struct {
	X      float64
	Y      float64
	Width  float64
	Height float64
}

Box is an axis-aligned rectangle expressed as an origin and size. Width and Height may be zero, but must not be negative in a valid scene.

func (Box) Bounds

func (b Box) Bounds() Bounds

Bounds converts b to min/max form. Negative sizes are normalized here so geometry helpers remain total; render preflight rejects them in scenes.

type CenterArc

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

CenterArc is SVG endpoint arc geometry converted to a center parameterization. Its fields remain private so callers cannot construct an inconsistent arc; renderers use the accessors below.

func EndpointArcToCenter

func EndpointArcToCenter(start Point, command PathCommand) (CenterArc, bool, error)

EndpointArcToCenter implements SVG 2's endpoint-to-center conversion. The boolean is false for the two specified degeneracies: identical endpoints (omit the arc) and a zero radius (draw a line). Ratio exponents are normalized before division, so finite tiny radii can be corrected without overflowing to infinity first.

func (CenterArc) DeltaAngle

func (a CenterArc) DeltaAngle() float64

func (CenterArc) PointAt

func (a CenterArc) PointAt(theta float64) Point

func (CenterArc) StartAngle

func (a CenterArc) StartAngle() float64

func (CenterArc) TransformedRadiusBound

func (a CenterArc) TransformedRadiusBound(m Matrix) float64

TransformedRadiusBound returns a conservative second-derivative bound after applying the linear part of m. It is used to prove a device-space chord error during adaptive flattening.

type Clip

type Clip struct {
	Path      Path
	Transform Matrix
}

type Document

type Document struct {
	ViewBox       Box
	LogicalWidth  float64
	LogicalHeight float64
	ViewportFit   ViewportFit
	ViewportAlign ViewportAlign
	Root          *Node
	Assets        map[AssetID]Asset
	Links         []LinkRegion
}

func NewDocument

func NewDocument(viewBox Box, root *Node) *Document

type DropShadow

type DropShadow struct {
	OffsetX float64
	OffsetY float64
	SigmaX  float64
	SigmaY  float64
	Color   color.NRGBA
}

type Easing

type Easing struct {
	Kind EasingKind
	X1   float64
	Y1   float64
	X2   float64
	Y2   float64
}

Easing describes an outgoing keyframe easing. CubicBezier uses CSS-style control points (0,0), (X1,Y1), (X2,Y2), (1,1).

type EasingKind

type EasingKind uint8
const (
	EaseLinear EasingKind = iota
	EaseCubicBezier
	EaseStepStart
	EaseStepEnd
)

type Ellipse

type Ellipse struct {
	Center  Point
	RadiusX float64
	RadiusY float64
	Fill    Paint
	Stroke  *Stroke
}

type FillRule

type FillRule uint8
const (
	NonZero FillRule = iota
	EvenOdd
)

type Filter

type Filter interface {
	// contains filtered or unexported methods
}

type Font

type Font struct {
	Family string
	Style  string
	Weight int
	Size   float64
	Asset  AssetID
}

type FontAsset

type FontAsset struct {
	MIMEType string
	Data     []byte
	// FaceIndex selects one face from an OpenType collection. It is zero for a
	// single-face TTF/OTF and for the first face of a TTC. Keeping the index in
	// the resolved asset lets a scene retain host fallback fonts without asking
	// the network-free rasterizer to rediscover which collection face was used.
	FaceIndex uint16
}

type GaussianBlur

type GaussianBlur struct {
	SigmaX float64
	SigmaY float64
}

type Glyph

type Glyph struct {
	ID uint32
	// Empty retains an invisible shaper output (for example a default-
	// ignorable control) so its placement and advance survive in the scene.
	// Empty glyphs use ID zero and are never sent to the outline rasterizer.
	Empty bool
	// Asset overrides TextRun.Font.Asset for this glyph. An empty value keeps
	// the primary asset. This makes explicit shaping capable of retaining
	// mixed-font fallback decisions in the scene itself.
	Asset    AssetID
	Position Point
	Advance  float64
	Ink      Bounds
}

Glyph optionally carries a shaper's exact glyph placement. Ink is relative to Origin+Position. A renderer may shape Text itself when Glyphs is empty.

type GradientStop

type GradientStop struct {
	Offset float64
	Color  color.NRGBA
}

type Image

type Image struct {
	Asset  AssetID
	Box    Box
	Aspect AspectRatio
}

type Keyframe

type Keyframe struct {
	Offset float64
	Value  AnimationValue
	Easing Easing
}

type LineCap

type LineCap uint8
const (
	CapButt LineCap = iota
	CapRound
	CapSquare
)

type LineJoin

type LineJoin uint8
const (
	JoinMiter LineJoin = iota
	JoinRound
	JoinBevel
)

type LinearGradient

type LinearGradient struct {
	Start     Point
	End       Point
	Stops     []GradientStop
	Units     PaintUnits
	Transform Matrix
	Spread    SpreadMethod
}

type LinkRegion

type LinkRegion struct {
	// Box is expressed in the same logical coordinate space as Document.ViewBox.
	Box Box
	// URL is an external or opaque link destination. Target instead names a
	// D2 board destination. At most one of URL and Target may be set; a region
	// with neither is valid when it carries tooltip-only metadata.
	URL     string
	Tooltip string
	Target  string
}

type Mask

type Mask struct {
	Type      MaskType
	Root      *Node
	Transform Matrix
}

type MaskType

type MaskType uint8
const (
	MaskAlpha MaskType = iota
	MaskLuminance
)

type Matrix

type Matrix struct {
	A float64
	B float64
	C float64
	D float64
	E float64
	F float64
}

Matrix is an SVG-style affine transform:

x' = A*x + C*y + E
y' = B*x + D*y + F

The zero value is the zero transform, not identity. Use Identity explicitly.

func AspectRatioMatrix

func AspectRatioMatrix(source, destination Box, aspect AspectRatio) (Matrix, error)

AspectRatioMatrix maps source coordinates into destination using SVG's preserveAspectRatio rules. Source must have positive dimensions; destination may be empty so zero-sized image primitives remain valid and paint no pixels.

func Identity

func Identity() Matrix

func Rotate

func Rotate(radians float64) Matrix

Rotate returns a counter-clockwise rotation in radians in Cartesian coordinates. In D2's screen coordinate system (positive Y down), it appears clockwise, matching SVG transform behavior.

func RotateAround

func RotateAround(radians, x, y float64) Matrix

func Scale

func Scale(x, y float64) Matrix

func SkewX

func SkewX(radians float64) Matrix

func SkewY

func SkewY(radians float64) Matrix

func Translate

func Translate(x, y float64) Matrix

func (Matrix) Determinant

func (m Matrix) Determinant() float64

func (Matrix) Inverse

func (m Matrix) Inverse() (Matrix, error)

func (Matrix) IsFinite

func (m Matrix) IsFinite() bool

func (Matrix) MaxScale

func (m Matrix) MaxScale() float64

MaxScale is the largest singular value of the linear portion of m. It is used to conservatively transform stroke and filter radii.

func (Matrix) Mul

func (m Matrix) Mul(right Matrix) Matrix

Mul composes m and right. The right transform is applied to a point first.

func (Matrix) Point

func (m Matrix) Point(p Point) Point

func (Matrix) Vector

func (m Matrix) Vector(v Point) Point

Vector transforms a vector, excluding translation.

type Node

type Node struct {
	ID         string
	Classes    []string
	Transform  Matrix
	Opacity    float64
	Blend      BlendMode
	Clip       *Clip
	Mask       *Mask
	Filters    []Filter
	Primitive  Primitive
	Children   []*Node
	Animations []Track
}

Node is one immutable-ish scene layer. Transform maps node-local coordinates into its parent's coordinates. Callers constructing nodes directly must use Identity for an untransformed node; NewNode supplies that default.

func NewNode

func NewNode(primitive Primitive) *Node

type Paint

type Paint interface {
	// contains filtered or unexported methods
}

Paint is a closed set of renderer-neutral D2 paints. A nil Paint means no paint. The closed interface makes unsupported paint kinds fail at compile time instead of disappearing in a renderer.

type PaintUnits

type PaintUnits uint8
const (
	ObjectBoundingBox PaintUnits = iota
	UserSpaceOnUse
)

type Path

type Path struct {
	Commands []PathCommand
	FillRule FillRule
	Fill     Paint
	Stroke   *Stroke
}

Path is both typed path geometry and a paintable scene primitive.

func (Path) GeometryBounds

func (p Path) GeometryBounds() (Bounds, error)

GeometryBounds computes exact analytic bounds of the centerline geometry.

type PathCommand

type PathCommand struct {
	Kind PathCommandKind
	P1   Point
	P2   Point
	P3   Point

	RadiusX  float64
	RadiusY  float64
	Rotation float64
	LargeArc bool
	Sweep    bool
}

PathCommand stores absolute, typed path geometry. P1 is the endpoint for a move or line; P1/P2 are control/end for a quadratic; P1/P2/P3 are the two controls/end for a cubic; and P1 is the endpoint for an arc. Arc rotation is in radians.

func ArcTo

func ArcTo(rx, ry, rotation float64, largeArc, sweep bool, x, y float64) PathCommand

func ClosePath

func ClosePath() PathCommand

func CubicTo

func CubicTo(c1x, c1y, c2x, c2y, x, y float64) PathCommand

func LineTo

func LineTo(x, y float64) PathCommand

func MoveTo

func MoveTo(x, y float64) PathCommand

func QuadraticTo

func QuadraticTo(cx, cy, x, y float64) PathCommand

type PathCommandKind

type PathCommandKind uint8
const (
	MoveCommand PathCommandKind = iota
	LineCommand
	QuadraticCommand
	CubicCommand
	ArcCommand
	CloseCommand
)

type PatternPaint

type PatternPaint struct {
	Tile      Box
	Root      *Node
	Units     PaintUnits
	Transform Matrix
}

PatternPaint repeats Root over Tile. Root is in Tile's local coordinate system and is subject to Transform before the pattern is sampled.

type Point

type Point struct {
	X float64
	Y float64
}

Point is a point or vector in logical D2 coordinates.

type Primitive

type Primitive interface {
	// contains filtered or unexported methods
}

Primitive is the closed set of paintable scene leaves. Groups are Nodes with a nil Primitive and one or more Children.

type RadialGradient

type RadialGradient struct {
	Center      Point
	Radius      float64
	Focal       Point
	FocalRadius float64
	Stops       []GradientStop
	Units       PaintUnits
	Transform   Matrix
	Spread      SpreadMethod
}

type RasterAsset

type RasterAsset struct {
	MIMEType    string
	Data        []byte
	PixelWidth  int
	PixelHeight int
	// DecodedBytes is the resolver-proven decoded first-frame canvas footprint.
	// A zero value uses a conservative 4-byte-per-pixel estimate for callers
	// that have already normalized the asset to 8-bit RGBA. Values below that
	// minimum are invalid.
	DecodedBytes int64
}

RasterAsset retains one encoded raster resource. Native rendering uses the first animation frame of GIF, APNG, and WebP data on its logical canvas and normalizes JPEG pixels and dimensions using EXIF Orientation.

type Rect

type Rect struct {
	Box     Box
	RadiusX float64
	RadiusY float64
	Fill    Paint
	Stroke  *Stroke
}

type SolidPaint

type SolidPaint struct {
	Color color.NRGBA
}

type SpreadMethod

type SpreadMethod uint8
const (
	SpreadPad SpreadMethod = iota
	SpreadReflect
	SpreadRepeat
)

type Stroke

type Stroke struct {
	Paint      Paint
	Width      float64
	Cap        LineCap
	Join       LineJoin
	MiterLimit float64
	Dashes     []float64
	DashOffset float64
}

Stroke describes path stroking in logical coordinates. Dashes alternate on and off lengths and are interpreted before DashOffset, as in SVG.

type TextAnchor

type TextAnchor uint8
const (
	AnchorStart TextAnchor = iota
	AnchorMiddle
	AnchorEnd
)

type TextRun

type TextRun struct {
	Text   string
	Origin Point
	Anchor TextAnchor
	Font   Font
	// Fallbacks is an ordered list of already-resolved font assets. Renderers
	// may use them for missing glyphs but must never perform font discovery or
	// filesystem I/O while painting a document. It lives on TextRun rather than
	// Font so Font remains comparable and usable as a map key.
	Fallbacks []AssetID
	Fill      Paint
	Stroke    *Stroke
	Underline bool
	Strike    bool
	Glyphs    []Glyph
	Ink       Bounds
}

TextRun is one consistently styled baseline run. Ink is the exact measured node-local ink bounds when available. Underline and Strike are explicit so link and label decoration does not require renderer-specific child nodes.

type Track

type Track struct {
	Property AnimationProperty
	// TargetIndex selects an entry for indexed properties such as a drop
	// shadow in Node.Filters. It is zero for scalar node properties.
	TargetIndex int
	Delay       time.Duration
	Duration    time.Duration
	Repeat      bool
	Keyframes   []Keyframe
}

Track describes one typed animation. Repeat loops forever. Renderers resolve tracks without changing the track or its node, so a scene can be rendered at multiple times concurrently.

type VectorAsset

type VectorAsset struct {
	ViewBox Box
	Root    *Node
}

type ViewportAlign

type ViewportAlign uint8

ViewportAlign controls placement when a uniform viewport fit leaves letterbox space. The zero value anchors content at the viewport origin.

const (
	ViewportAlignXMinYMin ViewportAlign = iota
	ViewportAlignXMidYMid
)

type ViewportFit

type ViewportFit uint8

ViewportFit controls how a document viewbox maps into its output viewport. The zero value selects independent-axis stretching.

const (
	ViewportStretch ViewportFit = iota
	ViewportMeet
)

Jump to

Keyboard shortcuts

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