GitHubGet started

package text

import "github.com/nsgo-dev/game/pkg/text"

Overview

Package text draws bitmap fonts (AngelCode BMFont) through sprite batches, signed-distance-field fonts that stay sharp at any size on the screen or in 3D world space (SDFFont, WorldText), and platform-rendered text through core.Drawing.

Index

Functions

func AppendRichToBatch(batch *sprite.Batch, layout RichLayout, pos core.Point, opts RichOptions) int

AppendRichToBatch appends sprites from layout whose resolved atlas matches batch.Atlas (both bitmap glyphs and inline icons on that atlas) into batch, positioned at pos with per-glyph effects evaluated at opts.Elapsed.

It returns the number of sprites appended to batch. Placements requiring a different atlas or faux-italic shear transform are skipped.

func DefaultPunctuationPause() map[rune]float32

DefaultPunctuationPause returns a standard dialogue punctuation pause table (4x step after sentence terminators, 2x step after clause separators).

func DrawPlatform(d *core.Drawing, text string, x, y float32, style PlatformStyle)

DrawPlatform draws text at (x, y) into d using core.Drawing.FillText.

It draws inside the drawing's active transform stack so text scales automatically with a game view's virtual resolution transform, and wraps its style changes in Save/Restore so fill color, alpha, alignment, and baseline never leak to subsequent draw calls.

func DrawRich(d *core.Drawing, font *Font, rt RichText, pos core.Point, opts RichOptions)

DrawRich lays out and draws rt at pos into d.

When font is non-nil, bitmap glyph rendering is used (with cached pixel tinting for colored spans when the page image provides Pixels or Data, and sprite.Batch grouping for glyphs and inline icons). When font is nil and opts.Platform is set, platform-text rich span rendering is used.

func DrawRichLayout(d *core.Drawing, layout RichLayout, pos core.Point, opts RichOptions)

DrawRichLayout draws a previously computed RichLayout at pos into d, applying per-glyph effects evaluated at opts.Elapsed.

func DrawRichPlatform(d *core.Drawing, rt RichText, pos core.Point, style PlatformStyle, opts RichOptions)

DrawRichPlatform lays out and draws rt at pos into d using platform text (core.Drawing.FillText) for styled text spans and inline images/atlas frames for icons.

func EvalGlyphTransform(effect GlyphEffect, glyphIndex int, elapsed float32) (dx, dy float32, colorOverride *core.Color)

EvalGlyphTransform evaluates effect for glyphIndex at time elapsed (in seconds).

The result is completely deterministic for any (effect.Seed, glyphIndex, elapsed) tuple and uses pure integer/float math without global RNG state.

func MeasurePlatform(d *core.Drawing, text string, style PlatformStyle) core.Size

MeasurePlatform returns the bounding width and height of text laid out with style on d.

func MeasureRich(font *Font, rt RichText, opts RichOptions) core.Size

MeasureRich returns the bounding width and height of rt laid out with font and opts.

Types

type Align uint8

Align controls horizontal alignment of laid-out text lines.

const (
	// AlignLeft aligns lines to the left edge (x). This is the zero value.
	AlignLeft Align = iota
	// AlignCenter centers each line horizontally.
	AlignCenter
	// AlignRight aligns lines to the right edge.
	AlignRight
)
type EffectKind uint8

EffectKind identifies a per-glyph animation effect.

const (
	// EffectNone disables per-glyph motion and color overrides.
	EffectNone EffectKind = iota
	// EffectWave displaces glyphs vertically along a smooth sine wave.
	EffectWave
	// EffectShake jitters glyphs deterministically in X and Y.
	EffectShake
	// EffectCustom invokes GlyphEffect.Custom to compute offsets and color overrides.
	EffectCustom
)
type Facing uint8

Facing is how text placed in a 3D world turns.

const (
	// FacingBillboard turns the text to face the camera, upright on the screen, as name labels and damage numbers do. This is the zero value.
	FacingBillboard Facing = iota
	// FacingFixed lays the text in a plane of the world that WorldText.Rot sets, as a sign on a wall is: seen from the side it is foreshortened, seen from behind it is mirrored unless CullBackFace is set.
	FacingFixed
)
type FieldType uint8

FieldType is how a signed-distance-field atlas stores the distance to a glyph's outline.

const (
	// FieldSDF is a true signed distance field in one channel, read from red (a grayscale image's gray).
	FieldSDF FieldType = iota
	// FieldPSDF is a pseudo signed distance field in one channel, read from red, as FieldSDF is.
	FieldPSDF
	// FieldMSDF is a multi-channel signed distance field: the outline is the median of red, green and blue, which keeps corners sharp.
	FieldMSDF
	// FieldMTSDF is FieldMSDF with a true signed distance field in alpha, which outlines read for rounder corners.
	FieldMTSDF
)
func (t FieldType) String() string

String returns the name msdf-atlas-gen and msdf-bmfont-xml give the field type: sdf, psdf, msdf or mtsdf.

type Font struct {
	// Face is the font face name from the info record.
	Face string
	// Size is the font size from the info record.
	Size float32
	// LineHeight is the distance between consecutive lines, in points.
	LineHeight float32
	// Base is the distance from the top of a line to the characters' baseline, in points.
	Base float32
	// Pages maps each BMFont page ID to the sprite.Atlas holding that page's glyphs.
	Pages map[int]*sprite.Atlas
	// Glyphs maps each rune to its Glyph metrics and frame.
	Glyphs map[rune]Glyph
	// Kernings maps pairs of consecutive runes to their horizontal kerning adjustment.
	Kernings map[KerningPair]float32
}

Font is a parsed AngelCode BMFont: one sprite.Atlas per texture page, glyph metrics, and kerning pairs.

func LoadBMFont(data []byte, pageImage func(id int, file string) core.ImageSource) (*Font, error)

LoadBMFont parses AngelCode BMFont data in either plain-text or XML format.

For each texture page defined in the font, pageImage is called with the page ID and filename (in ascending page ID order) to obtain its core.ImageSource. If pageImage is nil, each page's atlas receives a zero core.ImageSource.

Its errors are *loaderr.Error values that give the line of the record at fault and how to fix it; a caller that read data from a file names it with loaderr.WithFile.

func LoadBMFontImage(img core.ImageSource, data []byte) (*Font, error)

LoadBMFontImage parses a single-page AngelCode BMFont (plain-text or XML) backed by img. It returns an error if the font declares more than one page.

func (f *Font) Draw(d *core.Drawing, s string, x, y float32, opts Options)

Draw draws s at (x, y) into d through sprite.Batch (one batch per texture page used, preserving order; single-page fonts use one sprite.Batch).

func (f *Font) Kerning(first, second rune) float32

Kerning returns the horizontal kerning adjustment when second follows first, or 0 if no kerning pair is defined.

func (f *Font) Layout(s string, x, y float32, opts Options) []GlyphPlacement

Layout computes the screen placements of all visible glyphs in s starting at (x, y).

func (f *Font) Measure(s string, opts Options) core.Size

Measure returns the bounding width and height of s laid out with opts.

type Glyph struct {
	// ID is the Unicode code point of the glyph.
	ID rune
	// Frame is the glyph's rectangle in its page's sprite.Atlas.
	Frame sprite.Frame
	// XOffset and YOffset displace the glyph's drawn rectangle from the cursor.
	XOffset, YOffset float32
	// XAdvance is how far the cursor advances after this glyph.
	XAdvance float32
	// Page is the BMFont texture page ID holding this glyph.
	Page int
}

Glyph is one character in a bitmap font: its atlas frame, placement offsets, cursor advance, and texture page ID.

type GlyphEffect struct {
	Kind      EffectKind
	Seed      uint64
	Amplitude float32
	Frequency float32
	Speed     float32
	// Custom is invoked when Kind == EffectCustom.
	Custom GlyphEffectFunc
}

GlyphEffect configures a deterministic per-glyph animation effect.

type GlyphEffectFunc func(effect GlyphEffect, glyphIndex int, elapsed float32) (dx, dy float32, colorOverride *core.Color)

GlyphEffectFunc computes a deterministic per-glyph translation (dx, dy) and optional color override for EffectCustom.

type GlyphPlacement struct {
	// Rune is the character this placement came from.
	Rune rune
	// Glyph is the font's glyph metrics and atlas frame.
	Glyph Glyph
	// X and Y are the top-left position of the drawn glyph rectangle, in points.
	X, Y float32
	// W and H are the drawn width and height of the glyph rectangle, in points.
	W, H float32
	// Line is the zero-based line index containing this glyph.
	Line int
}

GlyphPlacement is one visible glyph positioned by Font.Layout.

type Icon struct {
	// Image is the texture containing the icon. When empty and Atlas != nil,
	// Atlas.Image is used.
	Image core.ImageSource
	// Atlas optionally identifies the sprite.Atlas holding Frame for sprite.Batch grouping.
	Atlas *sprite.Atlas
	// Frame is the sub-rectangle in Image/Atlas. When Frame.W == 0 && Frame.H == 0,
	// the entire Image is drawn.
	Frame sprite.Frame
	// Width and Height are the icon's drawn size in points at scale 1.
	// When 0, they default to Frame.Width/Frame.Height (or Frame.W/Frame.H, or Image size).
	Width, Height float32
	// Advance is the horizontal cursor advance in points at scale 1.
	// When <= 0, it defaults to Width.
	Advance float32
	// BaselineOffset shifts the icon vertically relative to the text baseline
	// (positive moves down, negative moves up). With 0, the bottom of the icon
	// sits on the text baseline.
	BaselineOffset float32
}

Icon describes an inline image or sprite atlas frame embedded inside rich text.

type IconResolver func(name string) (Icon, bool)

IconResolver resolves an inline icon name (from [icon=name]) to an Icon.

func AtlasIconResolver(atlas *sprite.Atlas) IconResolver

AtlasIconResolver returns an IconResolver that looks up named frames in atlas.

type KerningPair struct {
	First, Second rune
}

KerningPair identifies an ordered pair of consecutive runes that carry a horizontal kerning adjustment.

type Options struct {
	// MaxWidth wraps lines to fit within MaxWidth points when > 0, and defines
	// the alignment box [x, x+MaxWidth] for AlignCenter and AlignRight.
	// When MaxWidth <= 0, lines do not wrap and AlignCenter/AlignRight align
	// relative to x directly (centered at x, or right edge at x).
	MaxWidth float32
	// Align is the horizontal alignment of each line.
	Align Align
	// Scale multiplies glyph positions and sizes; 0 means 1.
	// A negative scale measures and draws nothing.
	Scale float32
	// Alpha is the text opacity from 0 to 1; 0 means 1 (fully opaque).
	// A negative alpha draws nothing.
	Alpha float32
	// LineSpacing is extra vertical space added between lines, in points.
	LineSpacing float32
	// Z is passed to each sprite in the underlying sprite.Batch.
	Z int
}

Options configures how a Font measures, lays out, and draws text.

Its zero value draws left-aligned at scale 1 and full opacity with no wrapping.

type PlatformStyle struct {
	// Font selects the platform font family, size, weight, italic, and language.
	// When Font.Size <= 0, core.DefaultFontSize is used.
	Font core.Font
	// Color sets the text fill color when non-zero; when 0, the drawing's
	// current fill color is kept.
	Color core.Color
	// Alpha sets the text opacity from 0 to 1; 0 means 1 (keep full opacity).
	// A negative value draws nothing.
	Alpha float32
	// Align aligns each line horizontally (AlignLeft, AlignCenter, AlignRight).
	Align Align
	// Baseline sets which line of text sits at y (zero value is core.BaselineAlphabetic).
	Baseline core.TextBaseline
	// MaxWidth wraps lines to fit within MaxWidth points when > 0, and defines
	// the alignment box [x, x+MaxWidth] for AlignCenter and AlignRight.
	// When MaxWidth <= 0, lines do not wrap and AlignCenter/AlignRight align
	// relative to x directly.
	MaxWidth float32
	// LineHeight overrides the distance between consecutive lines in points when > 0.
	// When <= 0, it uses the font's measured line height from d.TextMetrics.
	LineHeight float32
	// LineSpacing adds extra vertical space between lines, in points.
	LineSpacing float32
}

PlatformStyle configures platform-rendered text drawn with DrawPlatform.

Its zero value draws in core.DefaultFontSize at full opacity, left-aligned, on the alphabetic baseline, keeping the drawing's current fill color, with no wrapping.

type RichLayout struct {
	// Size is the overall bounding width and height of the laid-out rich text.
	Size core.Size
	// Lines holds per-line metrics and alignment offsets.
	Lines []RichLine
	// Placements holds every visible glyph and inline icon in reading order.
	Placements []RichPlacement
	// TotalUnits is the total number of revealable units (non-newline glyphs + icons).
	TotalUnits int
	// contains filtered or unexported fields
}

RichLayout is the laid-out geometry of a RichText.

func LayoutRich(font *Font, rt RichText, opts RichOptions) RichLayout

LayoutRich computes line wrapping, alignment, and per-glyph/per-icon placements for rt using bitmap font and opts.

Inline icons are measured and wrapped identically to glyphs using their resolved advance width, and aligned to each line's baseline.

func LayoutRichPlatform(d *core.Drawing, rt RichText, style PlatformStyle, opts RichOptions) RichLayout

LayoutRichPlatform lays out rt using platform text measurements from d, treating inline icons as glyphs aligned to the text baseline.

type RichLine struct {
	// Index is the zero-based line index.
	Index int
	// X is the aligned starting X offset of the line relative to origin.
	X float32
	// Y is the top Y coordinate of the line relative to origin.
	Y float32
	// Width is the measured advance width of the line in points.
	Width float32
	// Height is the total line height in points.
	Height float32
	// Baseline is the distance from Y down to the line's baseline in points.
	Baseline float32
}

RichLine summarizes one wrapped line of a RichLayout.

type RichOptions struct {
	// Options holds MaxWidth, Align, Scale, Alpha, LineSpacing, and Z.
	Options
	// Color is the default foreground color when a token has no [color=...] tag.
	// Zero means untinted for bitmap fonts, or the drawing's current fill color
	// for platform text.
	Color core.Color
	// Icons resolves [icon=name] tags. When nil or unresolved, icons are skipped.
	Icons IconResolver
	// BoldFont, ItalicFont, and BoldItalicFont are optional alternate bitmap fonts
	// used for [b], [i], and [b][i] spans. When nil, faux-bold or faux-italic
	// rendering is applied using the base font.
	BoldFont       *Font
	ItalicFont     *Font
	BoldItalicFont *Font
	// Elapsed is the animation time in seconds used when evaluating per-glyph
	// effects ([wave], [shake], or EffectCustom).
	Elapsed float32
	// Platform optionally supplies platform text rendering settings when drawing
	// via DrawRich with a nil bitmap Font.
	Platform *PlatformStyle
}

RichOptions configures layout and rendering of RichText.

Its zero value draws all tokens left-aligned at scale 1 and full opacity with no wrapping.

type RichPlacement struct {
	// Index is the zero-based revealable unit index used by Typewriter and
	// EvalGlyphTransform.
	Index int
	// Kind is TokenGlyph or TokenIcon.
	Kind RichTokenKind
	// Rune is the character when Kind == TokenGlyph.
	Rune rune
	// Glyph is the bitmap glyph metrics when laid out with a bitmap Font.
	Glyph Glyph
	// Font is the resolved bitmap font for this glyph (base or Bold/Italic variant).
	Font *Font
	// Icon is the resolved inline icon when Kind == TokenIcon.
	Icon Icon
	// Style is the active RichStyle on this placement.
	Style RichStyle
	// Scale is the combined scale (baseScale * tokenScale).
	Scale float32
	// X and Y are the top-left position of the drawn glyph/icon rectangle, in points.
	X, Y float32
	// W and H are the drawn width and height of the glyph/icon rectangle, in points.
	W, H float32
	// BaselineY is the Y coordinate of this placement's line baseline, in points.
	BaselineY float32
	// Line is the zero-based line index containing this placement.
	Line int
	// FauxBold is true when Bold is active without a dedicated BoldFont/BoldItalicFont.
	FauxBold bool
	// FauxItalic is true when Italic is active without a dedicated ItalicFont/BoldItalicFont.
	FauxItalic bool
	// PlatformFont is set when laid out via LayoutRichPlatform.
	PlatformFont core.Font
	// contains filtered or unexported fields
}

RichPlacement is one laid-out visible glyph or inline icon in a RichLayout. Positions are relative to the layout's origin (0, 0).

type RichRun struct {
	Kind RichTokenKind
	// Text holds the run's runes when Kind == TokenGlyph.
	Text string
	// IconName, IconWidth, IconHeight are set when Kind == TokenIcon.
	IconName              string
	IconWidth, IconHeight float32
	// PauseSeconds is set when Kind == TokenPause.
	PauseSeconds float32
	// Style is the shared RichStyle for this run.
	Style RichStyle
}

RichRun groups contiguous glyphs sharing identical style into a string, or represents a single inline icon or pause token.

type RichStyle struct {
	// Color is the token's foreground color; 0 means inherit the default color.
	Color core.Color
	// Scale multiplies the base text scale; 0 means 1.
	Scale float32
	// Bold requests bold rendering (BoldFont/BoldItalicFont, faux-bold, or
	// core.FontWeightBold on platform text).
	Bold bool
	// Italic requests italic rendering (ItalicFont/BoldItalicFont, faux-italic
	// skew, or core.Font.Italic on platform text).
	Italic bool
	// Effect configures a deterministic per-glyph animation effect.
	Effect GlyphEffect
}

RichStyle holds the active visual attributes of a parsed rich text token.

type RichText struct {
	Tokens []RichToken
}

RichText is a parsed rich text document consisting of styled tokens.

func ParseRich(src string) RichText

ParseRich parses forgiving inline rich text markup into a RichText.

Supported tags:

  • [color=#RRGGBB] / [color=#RRGGBBAA] / [color=gold] ... [/color]
  • [scale=1.25] ... [/scale], [size=1.25] ... [/size]
  • [b] ... [/b], [i] ... [/i]
  • [icon=coin] or [icon=coin w=16 h=16]
  • [wave amp=3 freq=4 speed=6] ... [/wave]
  • [shake amp=2 speed=30] ... [/shake]
  • [pause=0.2]
  • [[ escapes a literal '['

Any invalid, unknown, malformed, mismatched, or unclosed markup never errors or panics and falls back cleanly to plain text.

func (rt RichText) Empty() bool

Empty reports whether rt has no tokens.

func (rt RichText) PlainText() string

PlainText returns all text runes in rt with markup tags, icons, and pauses removed.

func (rt RichText) Runs() []RichRun

Runs groups contiguous glyph tokens with matching style into string runs, preserving inline icons and pauses in order.

type RichToken struct {
	Kind RichTokenKind
	// Rune is set when Kind == TokenGlyph.
	Rune rune
	// IconName is set when Kind == TokenIcon.
	IconName string
	// IconWidth and IconHeight override the resolved icon's intrinsic dimensions when > 0.
	IconWidth, IconHeight float32
	// PauseSeconds is the pause duration in seconds when Kind == TokenPause.
	PauseSeconds float32
	// Style holds the color, scale, bold, italic, and effect active on this token.
	Style RichStyle
}

RichToken is one parsed unit in a RichText document.

type RichTokenKind uint8

RichTokenKind distinguishes text glyphs, inline icons, and typewriter pauses.

const (
	// TokenGlyph is a single Unicode rune with an active RichStyle.
	TokenGlyph RichTokenKind = iota
	// TokenIcon is an inline icon ([icon=name ...]) with an active RichStyle.
	TokenIcon
	// TokenPause is a zero-width typewriter pause ([pause=seconds]).
	TokenPause
)
type SDFFont struct {
	// Face is the font face name.
	Face string
	// Size is the font's em size in atlas pixels: the size the atlas was generated at.
	Size float32
	// LineHeight is the distance between consecutive lines, in atlas pixels.
	LineHeight float32
	// Base is the distance from the top of a line to the baseline, in atlas pixels.
	Base float32
	// Field is how the atlas stores the distance.
	Field FieldType
	// DistanceRange is the width, in atlas pixels, of the band around each outline the field covers. With a DistanceRangeMiddle of 0, a field value of 0 is DistanceRange/2 pixels outside the outline, 0.5 on it and 1 DistanceRange/2 pixels inside.
	DistanceRange float32
	// DistanceRangeMiddle is how far, in atlas pixels, the middle of the field's band lies inside the outline: msdf-atlas-gen's distanceRangeMiddle, non-zero for an atlas generated with an asymmetric range (-apxrange or -aemrange). The outline is at the field value 0.5 - DistanceRangeMiddle/DistanceRange, and the field reaches DistanceRange/2 - DistanceRangeMiddle atlas pixels outside it.
	DistanceRangeMiddle float32
	// Glyphs maps each rune to its metrics and its rectangle in its page, all in atlas pixels.
	//
	// Measure, Layout, Draw and LayoutWorld read Size, LineHeight, Base, Glyphs and Kernings on every call, and a glyph's image is cached under its rectangle and the field's settings, so these fields can be changed between calls.
	Glyphs map[rune]Glyph
	// Kernings maps pairs of consecutive runes to their horizontal kerning adjustment, in atlas pixels.
	Kernings map[KerningPair]float32
	// CacheBytes bounds the memory of resolved glyph images kept between draws; 0 means 16 MiB. The least recently drawn glyph images go first.
	CacheBytes int
	// contains filtered or unexported fields
}

SDFFont is a signed-distance-field font: glyph metrics in atlas pixels and, for each texture page, the distance field those glyphs are drawn from.

Its glyphs stay sharp at any size, because a glyph is resolved from the field at the size it is drawn at rather than stretched from one bitmap. Draw and DrawWorld keep the glyphs they resolve in a cache bounded by CacheBytes, so an SDFFont is not safe for concurrent use: draw with it from one goroutine, as a canvas's Draw does.

func LoadSDFFont(data []byte, page func(id int, file string) (image.Image, error)) (*SDFFont, error)

LoadSDFFont parses a signed-distance-field font in any of the forms the common generators write:

  • msdf-atlas-gen's JSON (-json), whose glyphs are named by Unicode code point (-charset or the default, not -glyphset);
  • AngelCode BMFont in plain text, XML or JSON with a distanceField record, as msdf-bmfont-xml writes.

For each texture page, in ascending page ID order, page is called with the page ID and the file the font names for it (empty for msdf-atlas-gen's single atlas) and returns the page's decoded image, such as image/png's. LoadSDFFont reads the distance out of the images, so it does not keep them.

func LoadSDFFontImage(img image.Image, data []byte) (*SDFFont, error)

LoadSDFFontImage parses a single-page signed-distance-field font, as LoadSDFFont does, whose page is img. It returns an error if the font declares more than one page.

func (f *SDFFont) CachedGlyphs() (count, bytes int)

CachedGlyphs returns how many resolved glyph images the font keeps and their size in bytes.

func (f *SDFFont) ClearCache()

ClearCache drops every resolved glyph image the font keeps.

func (f *SDFFont) Draw(d *core.Drawing, s string, x, y float32, opts SDFOptions)

Draw draws s at (x, y), the top left of its first line, into d, each glyph resolved from the distance field at the size it is drawn at, so it stays sharp at any Size and PixelScale.

The current transform of d is not known to Draw: under a scaling transform, set PixelScale to the device pixels a point then covers.

func (f *SDFFont) DrawLayout(d *core.Drawing, l WorldLayout)

DrawLayout draws world-space text that LayoutWorld projected into d.

func (f *SDFFont) DrawWorld(d *core.Drawing, cam *scene3d.Camera, viewport core.Bounds, t WorldText)

DrawWorld projects t through cam onto viewport, as LayoutWorld does, and draws it into d. To draw overlapping labels back to front, lay them out with LayoutWorld, sort them by Depth and draw them with DrawLayout instead.

func (f *SDFFont) Kerning(first, second rune) float32

Kerning returns the horizontal kerning adjustment, in atlas pixels, when second follows first, or 0 if no kerning pair is defined.

func (f *SDFFont) Layout(s string, x, y float32, opts SDFOptions) []GlyphPlacement

Layout computes the placements, in points, of all visible glyphs in s starting at (x, y), the top left of its first line.

func (f *SDFFont) LayoutWorld(cam *scene3d.Camera, viewport core.Bounds, t WorldText) (WorldLayout, bool)

LayoutWorld projects t through cam onto viewport, the camera's view in the drawing's points (as render3d.ProjectSegment's), and reports whether any of it is visible.

FacingBillboard text is hidden as a whole when its anchor is outside the camera's near and far planes. FacingFixed text is hidden glyph by glyph: a glyph reaching behind the near plane or past the far plane is left out. Glyphs wholly outside the viewport are left out of both.

func (f *SDFFont) Measure(s string, opts SDFOptions) core.Size

Measure returns the bounding width and height, in points, of s laid out with opts.

type SDFOptions struct {
	// Size is the em size the text is drawn at, in points; 0 means the font's Size. DrawWorld ignores it and takes the size from WorldText.
	Size float32
	// MaxWidth wraps lines to fit within MaxWidth when > 0 and defines the alignment box [x, x+MaxWidth] for AlignCenter and AlignRight, as Options.MaxWidth does. It is in points for Draw and in world units for DrawWorld.
	MaxWidth float32
	// Align is the horizontal alignment of each line.
	Align Align
	// LineSpacing is extra vertical space between lines, in ems.
	LineSpacing float32
	// Color is the text's fill color; 0 means opaque white.
	Color core.Color
	// Alpha is the text's opacity from 0 to 1; 0 means 1, and a negative alpha draws nothing. Changing it, as a fading damage number does, reuses the glyphs already resolved.
	Alpha float32
	// Outline is the width of an outline around each glyph, in ems; 0 draws none. It cannot reach past the font's distance field, DistanceRange/2 - DistanceRangeMiddle atlas pixels outside the outline, and stops there.
	Outline float32
	// OutlineColor is the outline's color; 0 draws no outline.
	OutlineColor core.Color
	// PixelScale is the device pixels a point covers, so glyphs are resolved at the screen's density; 0 means 1.
	PixelScale float32
}

SDFOptions configures how an SDFFont lays out and draws text.

Its zero value draws opaque white, left-aligned, at the font's own size, with no outline or wrapping.

type Typewriter struct {
	// CharsPerSecond is the reveal rate in units (glyphs or inline icons) per second.
	CharsPerSecond float32
	// PunctuationPause optionally defines step multipliers after punctuation runes
	// (e.g., '.' -> 4.0 waits 3 extra character steps after revealing '.').
	// Use DefaultPunctuationPause() for common dialogue pacing, or leave nil for
	// uniform character timing.
	PunctuationPause map[rune]float32
	// OnReveal is called once as each unit becomes visible. For inline icons, r is 0.
	OnReveal func(glyphIndex int, r rune)
	// OnComplete is called strictly once when all units have been revealed.
	OnComplete func()
	// contains filtered or unexported fields
}

Typewriter reveals a RichText progressively at a deterministic rate while tracking elapsed animation time for per-glyph effects.

func NewTypewriter(rt RichText, charsPerSecond float32) *Typewriter

NewTypewriter creates a Typewriter revealing rt at charsPerSecond units per second.

func NewTypewriterString(markup string, charsPerSecond float32) *Typewriter

NewTypewriterString parses markup via ParseRich and creates a Typewriter revealing it at charsPerSecond units per second.

func (tw *Typewriter) Done() bool

Done reports whether all units have been revealed.

func (tw *Typewriter) Draw(d *core.Drawing, font *Font, pos core.Point, opts RichOptions)

Draw draws only the currently revealed glyphs and inline icons at pos into d, keeping the full wrapped layout stable while evaluating per-glyph effects at the typewriter's Elapsed time.

When font is nil and opts.Platform is set, platform-text rendering is used.

func (tw *Typewriter) DrawPlatform(d *core.Drawing, pos core.Point, style PlatformStyle, opts RichOptions)

DrawPlatform draws only the currently revealed glyphs and inline icons at pos into d using platform text rendering, keeping the full wrapped layout stable.

func (tw *Typewriter) Elapsed() float32

Elapsed returns the total elapsed time in seconds accumulated via Update.

func (tw *Typewriter) Progress() float32

Progress returns the reveal fraction in [0, 1]. For empty text it returns 1.

func (tw *Typewriter) Reset(rt RichText)

Reset replaces the typewriter's RichText and resets reveal progress, timers, elapsed time, and completion state while preserving speed and callbacks.

func (tw *Typewriter) RichText() RichText

RichText returns the Typewriter's parsed RichText.

func (tw *Typewriter) Skip()

Skip immediately reveals all remaining units and invokes OnComplete once if it has not already fired.

func (tw *Typewriter) TotalCount() int

TotalCount returns the total number of revealable units (non-newline glyphs and icons).

func (tw *Typewriter) Update(dt float32)

Update advances the typewriter deterministically by dt seconds.

Elapsed time continues advancing after the text is fully revealed so active per-glyph effects ([wave], [shake]) keep animating. OnReveal fires once per newly revealed unit and OnComplete fires strictly once when fully revealed.

func (tw *Typewriter) VisibleCount() int

VisibleCount returns the number of currently revealed units (glyphs and icons).

type WorldGlyph struct {
	// Glyph is the font's glyph.
	Glyph Glyph
	// Transform maps the glyph's atlas rectangle, in atlas pixels from its top left, into the drawing's points. For FacingFixed text it is the affine transform closest to the perspective at the glyph's center, which, for glyphs small on the screen, the perspective across one glyph cannot tell apart.
	Transform math2d.Affine
}

WorldGlyph is one glyph of world-space text projected onto the screen.

type WorldLayout struct {
	// Depth is the anchor's depth from the camera's near plane (0) to its far plane (1), for drawing labels back to front: sort by Depth, highest first. For FacingFixed text whose anchor is behind the camera or past the far plane, it is the mean depth of the visible glyphs' centers.
	Depth float32
	// Glyphs are the glyphs that reach the viewport, in the text's order.
	Glyphs []WorldGlyph
	// Options are the WorldText's options the glyphs draw with.
	Options SDFOptions
}

WorldLayout is world-space text projected onto the screen by SDFFont.LayoutWorld, ready for SDFFont.DrawLayout.

type WorldText struct {
	// Text is the text, with "\n" between lines.
	Text string
	// Pos is the anchor's position in the world.
	Pos math3d.Vec3
	// Facing is how the text turns.
	Facing Facing
	// Rot orients FacingFixed text: its lines run along Rot's +X, its glyphs stand along +Y, and it reads from the +Z side. The zero Quat means the identity, text in the XY plane read from +Z.
	Rot math3d.Quat
	// Size is the em size in world units, so the text shrinks with distance under a perspective camera.
	Size float32
	// ScreenSize, when > 0, makes FacingBillboard text keep an em of ScreenSize points at any distance, in place of Size; Options.MaxWidth is then in points.
	ScreenSize float32
	// AnchorX and AnchorY are the point of the text's box that sits at Pos, as fractions of its width and height from its top left: (0, 0) is the top left, (0.5, 0.5) the center and (0.5, 1) the bottom middle. The box is [0, MaxWidth] wide when Options.MaxWidth > 0, else the widest line's, placed as Options.Align places a line at x.
	AnchorX, AnchorY float32
	// CullBackFace draws nothing of FacingFixed text seen from behind.
	CullBackFace bool
	// Options sets the color, outline, alignment, wrapping, opacity and pixel density; its Size is ignored and its MaxWidth is in world units.
	Options SDFOptions
}

WorldText is text placed in a 3D world, drawn by SDFFont.DrawWorld.