scene

package
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 35 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package scene provides scene components and runtime systems built on ecs, including transforms, common cameras, 2D rendering, animation, and input. The ui package owns container layouts and widget constraints. The scene/render3d package owns the optional 3D renderer and binds its camera settings through RenderWorld.RegisterCameraRenderer. Applications install the systems they use.

Index

Constants

This section is empty.

Variables

View Source
var (
	AnchorBottomLeft   = Anchor{-0.5, -0.5}
	AnchorBottomCenter = Anchor{0, -0.5}
	AnchorBottomRight  = Anchor{0.5, -0.5}
	AnchorCenterLeft   = Anchor{-0.5, 0}
	AnchorCenter       = Anchor{}
	AnchorCenterRight  = Anchor{0.5, 0}
	AnchorTopLeft      = Anchor{-0.5, 0.5}
	AnchorTopCenter    = Anchor{0, 0.5}
	AnchorTopRight     = Anchor{0.5, 0.5}
)
View Source
var (
	ErrOutputCapacity = errors.New("scene: render output lease capacity reached")
	ErrOutputReleased = errors.New("scene: render output lease released")
)
View Source
var ErrIncompatibleValUnits = errors.New("ecs: incompatible Val units")
View Source
var ErrWebViewUnavailable = errors.New("ecs: webview is unavailable on this platform")

ErrWebViewUnavailable indicates that the current target has no browser backend. WeChat builds intentionally return this error.

Functions

func ActiveTaskCount

func ActiveTaskCount[Tag, T any](world *ecs.World, dependency uint64, ready func(*ecs.World, ecs.Entity, *T) bool) int

ActiveTaskCount counts scoped, active entities satisfying ready. Tag identifies the predicate; dependency changes invalidate inputs it reads outside T. Unchanged inputs reuse the count without scanning entities or allocating.

func AnimationTaskCount

func AnimationTaskCount(world *ecs.World) int

func AppendTextUnderlineRects2D

func AppendTextUnderlineRects2D(dst []TextRangeRect2D, text *Text2D, lineIndex, start, end int, thickness float32) ([]TextRangeRect2D, TextRangeRect2D, bool)

AppendTextUnderlineRects2D appends baseline-aligned underline segments for a byte range on one visual line, leaving gaps around ink crossing the underline. The returned bounds include those gaps. Reusing dst avoids allocations.

func Bounds2D

func Bounds2D(transform mgl32.Mat4, anchor Anchor, width, height float32) (float32, float32, float32, float32, bool)

func BoundsInSpace2D

func BoundsInSpace2D(transform mgl32.Mat4, anchor Anchor, width, height float32, ui bool) (float32, float32, float32, float32, bool)

func DispatchInputEvent

func DispatchInputEvent(world *ecs.World, event InputEvent)

DispatchInputEvent delivers an event to its target path and publishes the result. Handlers may stop propagation or consume the event; nested dispatch reuses scratch storage.

func DispatchInputEvents2DSystem

func DispatchInputEvents2DSystem(name string) ecs.SystemConfig

func Draw2D

func Draw2D(c *graphics.Canvas2D, world *ecs.World, views DrawViews2D)

Draw2D draws every registered 2D renderer using explicit world and UI views.

func Draw2DSubtree

func Draw2DSubtree(c *graphics.Canvas2D, world *ecs.World, root ecs.Entity, views DrawViews2D)

Draw2DSubtree draws registered 2D render items owned by root or one of its descendants. Filtering reuses the frame render-item buffer.

func DrawScreenText2D

func DrawScreenText2D(c *graphics.Canvas2D, text *Text2D, transform mgl32.Mat4, anchor Anchor) bool

func EvalWebView

func EvalWebView(world *ecs.World, entity ecs.Entity, script string) error

EvalWebView evaluates script in a materialized WebView.

func ExtractCameras

func ExtractCameras(context *ecs.SystemContext) error

ExtractCameras refreshes snapshots of active registered cameras. Pipelines can call it directly without constructing a SystemConfig.

func ExtractCamerasSystem

func ExtractCamerasSystem(name string) ecs.SystemConfig

func ExtractRender2DSystem

func ExtractRender2DSystem(name string) ecs.SystemConfig

ExtractRender2DSystem extracts items for the renderers registered in world.

func GetUIScrollOffset

func GetUIScrollOffset(world *ecs.World, entity ecs.Entity) (mgl32.Vec2, bool)

func IsActive

func IsActive(world *ecs.World, entity ecs.Entity) bool

func IsInteractive

func IsInteractive(world *ecs.World, entity ecs.Entity) bool

IsInteractive requires both activity and visibility along the parent chain. Hidden UI cannot retain keyboard focus or receive semantic form input.

func IsVisible

func IsVisible(world *ecs.World, entity ecs.Entity) bool

IsVisible allows paused overlay backgrounds to render without enabling their simulation or input. Query scopes determine scene participation.

func MeasureText2D

func MeasureText2D(text *Text2D) (float32, float32, bool)

func MeasureTextLineOffsets2D

func MeasureTextLineOffsets2D(text *Text2D, value string, offsets []int, widths []float32) bool

MeasureTextLineOffsets2D writes prefix widths for sorted UTF-8 byte offsets in a single pass. Callers supply storage so repeated measurements allocate nothing, including lines with many highlighted ranges.

func MeasureTextMinimumWidth2D

func MeasureTextMinimumWidth2D(text *Text2D) (float32, bool)

func MeasureTextValue2D

func MeasureTextValue2D[V piecetree.Value](text *Text2D, inputValue V) (float32, float32, bool)
func NavigateWebView(world *ecs.World, entity ecs.Entity, url string) error

NavigateWebView updates a WebView URL and applies it immediately when its native handle already exists. A later synchronization pass retries the operation when the component was not materialized yet.

func ParticleEmitterBounds2D

func ParticleEmitterBounds2D(emitter *ParticleEmitter2D, transform mgl32.Mat4, ui bool) (float32, float32, float32, float32, bool)

func ParticleTaskCount

func ParticleTaskCount(world *ecs.World) int

func PrepareText2D

func PrepareText2D(text *Text2D) bool

PrepareText2D shapes and rasterizes the current glyph window without uploading its atlas. Call on the owning loop thread after layout has settled.

func PrimaryCamera2D

func PrimaryCamera2D(world *ecs.World) (ecs.Entity, bool)

func PrimaryCamera2DView

func PrimaryCamera2DView(world *ecs.World) (Camera, Projection, GlobalTransform, bool)

func QueueMaterial2DUploads

func QueueMaterial2DUploads(queue *graphics.UploadQueue, world *ecs.World, entity ecs.Entity)

QueueMaterial2DUploads uses the same registered generic material readers as rendering, including the entity's shader override.

func RegisterCameraRenderer2D

func RegisterCameraRenderer2D(world *ecs.World)

func RegisterParticleRenderer2D

func RegisterParticleRenderer2D(world *ecs.World)

func RegisterSpineRenderer2D

func RegisterSpineRenderer2D(world *ecs.World)

func RegisterSpriteLayersRenderer2D

func RegisterSpriteLayersRenderer2D(world *ecs.World)

func RegisterSpriteRenderer2D

func RegisterSpriteRenderer2D(world *ecs.World)

func RegisterSpriteTrailRenderer2D

func RegisterSpriteTrailRenderer2D(world *ecs.World)

func RegisterTextRenderer2D

func RegisterTextRenderer2D(world *ecs.World)

func RegisterTilemapRenderer2D

func RegisterTilemapRenderer2D(world *ecs.World)

func RegisterUIRenderer2D

func RegisterUIRenderer2D(world *ecs.World)

func RemapInputEntity2D

func RemapInputEntity2D(world *ecs.World, previous, current ecs.Entity)

RemapInputEntity2D preserves pointer tracking when a retained UI control is rebuilt with a new entity identity during an active input.

func RenderCamerasSystem

func RenderCamerasSystem(name string) ecs.SystemConfig

RenderCamerasSystem submits every registered camera pipeline in camera order.

func RenderDebugInfoSystem

func RenderDebugInfoSystem(name string) ecs.SystemConfig

func SampleAnimationProgress

func SampleAnimationProgress(tween AnimationTween, curve AnimationCurve, progress float32) float32

SampleAnimationProgress applies a keyframe tween to normalized progress. Time is clamped to [0, 1]; Back, Elastic and Bezier may overshoot in value.

func ScrollThumbSize

func ScrollThumbSize(trackSize, viewportSize, contentSize, minThumbSize float32) float32

ScrollThumbSize resolves the proportional scrollbar thumb within its track.

func SetUIShapeFragment2D added in v0.1.8

func SetUIShapeFragment2D(world *ecs.World, entity ecs.Entity, index int, fragment UIShapeFragment2D)

SetUIShapeFragment2D updates the geometry and paint of a single fragment.

func SetUIShapeFragmentFill2D added in v0.1.8

func SetUIShapeFragmentFill2D(world *ecs.World, entity ecs.Entity, index int, color graphics.ColorRGBA)

SetUIShapeFragmentFill2D updates the fill of a single fragment.

func SetUIShapeFragments2D added in v0.1.8

func SetUIShapeFragments2D(world *ecs.World, entity ecs.Entity, fragments []UIShapeFragment2D)

SetUIShapeFragments2D replaces the paint fragments, reusing their storage.

func SortedCameraEntities

func SortedCameraEntities(world *ecs.World) []ecs.Entity

func SpawnCamera2D

func SpawnCamera2D(world *ecs.World) ecs.Entity

func SpawnDebugInfo

func SpawnDebugInfo(world *ecs.World) ecs.Entity

func SpineModelMatrix2D

func SpineModelMatrix2D(transform mgl32.Mat4, ui bool) mgl32.Mat4

func SpineTaskCount

func SpineTaskCount(world *ecs.World) int

func SpriteBounds2D

func SpriteBounds2D(sprite *Sprite2D, anchor Anchor, transform mgl32.Mat4, ui bool) (float32, float32, float32, float32, bool)

func SpriteTrailTaskCount

func SpriteTrailTaskCount(world *ecs.World) int

func SyncGlobalTransformSystem

func SyncGlobalTransformSystem(name string) ecs.SystemConfig

func SyncPointerCursor2D added in v0.1.4

func SyncPointerCursor2D(world *ecs.World)

SyncPointerCursor2D refreshes the hovered entity's cursor after UI style updates. It reuses the input dispatcher's hit result without another hit-test traversal.

func SyncUIGlobalTransformSystem

func SyncUIGlobalTransformSystem(name string) ecs.SystemConfig

func SyncWebViews

func SyncWebViews(world *ecs.World) error

SyncWebViews runs one WebView synchronization pass immediately.

func TextBounds2D

func TextBounds2D(text *Text2D, anchor Anchor, transform mgl32.Mat4, ui bool) (float32, float32, float32, float32, bool)

func TextCaretIndex2D

func TextCaretIndex2D[V piecetree.Value](text *Text2D, inputValue V, x, y float32) int

func TextCaretRect2D

func TextCaretRect2D[V piecetree.Value](text *Text2D, inputValue V, caret int) (x, y, width, height float32, ok bool)

TextCaretRect2D returns the local caret rectangle for a rune index. It uses the text layout's actual line ranges, so wrapped lines and explicit newlines share the same geometry as rendering and hit testing.

func TextLineCount2D

func TextLineCount2D(text *Text2D) int

TextLineCount2D returns the number of visual lines without allocating.

func TextSelectionRects2D

func TextSelectionRects2D[V piecetree.Value](text *Text2D, inputValue V, start, end int, top, bottom float32) iter.Seq[TextRangeRect2D]

TextSelectionRects2D visits the selected visual rows in a vertical viewport. Selection offsets are runes; bottom <= top disables viewport culling. It searches cached line ranges and measures only the selected visible rows.

func UIScrollScrollbarActive

func UIScrollScrollbarActive(world *ecs.World, entity ecs.Entity, axis uint8) bool

UIScrollScrollbarActive keeps a thumb expanded while hovered or captured. axis is 0 for horizontal and 1 for vertical.

func UIScrollSystem

func UIScrollSystem(name string) ecs.SystemConfig

func UIScrollTrackSize

func UIScrollTrackSize(scroll *UIScroll, viewport mgl32.Vec2) mgl32.Vec2

UIScrollTrackSize excludes the shared corner when both overlay bars are visible.

func UpdateParticleEmitter2DSystem

func UpdateParticleEmitter2DSystem(name string) ecs.SystemConfig

func UpdateSpine2DSystem

func UpdateSpine2DSystem(name string) ecs.SystemConfig

func UpdateSpriteTrail2DSystem

func UpdateSpriteTrail2DSystem(name string) ecs.SystemConfig

func UpdateUIAnimatorSystem

func UpdateUIAnimatorSystem(name string) ecs.SystemConfig

UpdateUIAnimatorSystem updates UI animators after layout has authored the frame's base positions and before UI global transforms are synchronized.

func UpdateWorldAnimatorSystem

func UpdateWorldAnimatorSystem(name string) ecs.SystemConfig

UpdateWorldAnimatorSystem updates animators that own world-space nodes. It is scheduled before global transform propagation so animated locals are visible to the same frame's hierarchy sync.

func ValidateAnimationTimeCurve

func ValidateAnimationTimeCurve(tween AnimationTween, curve AnimationCurve) error

ValidateAnimationTimeCurve checks a track's normalized playback time mapping. Spline interpolation needs value tangents and cannot be used as a time curve.

func ViewportToWorld2D

func ViewportToWorld2D(world *ecs.World, viewportPosition mgl32.Vec2) (mgl32.Vec2, bool)

func WebViewSystem

func WebViewSystem(name string) ecs.SystemConfig

WebViewSystem synchronizes WebView components into the runtime resource. It is intended for an update stage after scene/component mutations.

func WebViewTaskCount

func WebViewTaskCount(world *ecs.World) int

WebViewTaskCount keeps native browser callbacks serviced while a view exists. Installing the feature without any browser surfaces does not prevent idle.

func WorldToViewport2D

func WorldToViewport2D(world *ecs.World, worldPosition mgl32.Vec2) (mgl32.Vec2, bool)

Types

type Activity

type Activity struct{ Active bool }

Activity controls simulation independently of visibility. An entity may be invisible while running; suspended scene content must do neither.

type Anchor

type Anchor [2]float32

func (Anchor) TopLeft

func (a Anchor) TopLeft(width, height float32, screenSpace bool) (float32, float32)

TopLeft returns the local offset from this anchor to the rectangle's corner. Screen coordinates grow down; world coordinates grow up.

func (Anchor) X

func (a Anchor) X() float32

func (Anchor) Y

func (a Anchor) Y() float32

type AnimationBinding

type AnimationBinding struct {
	Path   string          `json:"path,omitempty"`
	Target AnimationTarget `json:"target"`
}

type AnimationClip

type AnimationClip struct {
	BoolTracks    []AnimationTrack[bool]
	TextureTracks []AnimationTrack[*graphics.Texture]
	Events        []AnimationEvent
	FloatTracks   []AnimationTrack[float32]

	Duration float32
	// contains filtered or unexported fields
}

func (*AnimationClip) Prepare

func (c *AnimationClip) Prepare() error

Prepare validates and freezes the clip's compiled track metadata. Project loaders call it once before instances share the clip, keeping playback free of setup allocations.

func (*AnimationClip) RequiresSprite2D

func (c *AnimationClip) RequiresSprite2D() (bool, error)

RequiresSprite2D reports whether root tracks require a Sprite2D target.

type AnimationClipValue added in v0.1.11

type AnimationClipValue interface {
	float32 | bool | *graphics.Texture
}

AnimationClipValue is a value stored in a playable scene clip.

type AnimationCurve

type AnimationCurve struct {
	X1 float32 `json:"x1"`
	Y1 float32 `json:"y1"`
	X2 float32 `json:"x2"`
	Y2 float32 `json:"y2"`
}

AnimationCurve maps normalized time to normalized animation progress using a cubic Bezier curve with fixed endpoints (0, 0) and (1, 1).

func EaseInAnimationCurve

func EaseInAnimationCurve() AnimationCurve

func EaseInOutAnimationCurve

func EaseInOutAnimationCurve() AnimationCurve

func EaseOutAnimationCurve

func EaseOutAnimationCurve() AnimationCurve

func LinearAnimationCurve

func LinearAnimationCurve() AnimationCurve

func (AnimationCurve) Sample

func (c AnimationCurve) Sample(progress float32) float32

func (AnimationCurve) Validate

func (c AnimationCurve) Validate() error

type AnimationEvent

type AnimationEvent struct {
	Name  string
	Value string
	Time  float32
}

type AnimationEventMessage

type AnimationEventMessage struct {
	Name   string
	Value  string
	Entity ecs.Entity
}

type AnimationKeyframe

type AnimationKeyframe[T any] struct {
	Value            T
	InTangent        T
	OutTangent       T
	Tween            AnimationTween
	QuaternionSpline AnimationQuaternionSpline
	Curve            AnimationCurve
	Time             float32
	InverseSpan      float32
}

type AnimationQuaternionSpline

type AnimationQuaternionSpline struct {
	Value      [4]float32
	InTangent  [4]float32
	OutTangent [4]float32
	Component  uint8
}

AnimationQuaternionSpline preserves glTF quaternion cubic data while the public transform bindings continue to target individual Euler components. Component is one-based; zero disables quaternion sampling for the key.

type AnimationTarget

type AnimationTarget string
const (
	AnimationTargetSpriteTexture      AnimationTarget = "sprite.texture"
	AnimationTargetSpriteAlpha        AnimationTarget = "sprite.alpha"
	AnimationTargetTransformPositionX AnimationTarget = "transform.position.x"
	AnimationTargetTransformPositionY AnimationTarget = "transform.position.y"
	AnimationTargetTransformPositionZ AnimationTarget = "transform.position.z"
	AnimationTargetTransformScaleX    AnimationTarget = "transform.scale.x"
	AnimationTargetTransformScaleY    AnimationTarget = "transform.scale.y"
	AnimationTargetTransformScaleZ    AnimationTarget = "transform.scale.z"
	AnimationTargetTransformRotationX AnimationTarget = "transform.rotation.x"
	AnimationTargetTransformRotationY AnimationTarget = "transform.rotation.y"
	AnimationTargetTransformRotationZ AnimationTarget = "transform.rotation.z"
	AnimationTargetVisibility         AnimationTarget = "visibility.visible"
)

type AnimationTrack

type AnimationTrack[T any] struct {
	Binding AnimationBinding
	// TimeTween remaps elapsed time over the first-to-last keyframe interval.
	// Discrete tracks still select frames; the curve changes their playback pace.
	TimeTween AnimationTween
	Keyframes []AnimationKeyframe[T]
	TimeCurve AnimationCurve
	// contains filtered or unexported fields
}

func NewAnimationTrack

func NewAnimationTrack[T any](binding AnimationBinding, keyframes []AnimationKeyframe[T]) AnimationTrack[T]

func (AnimationTrack[T]) Sample

func (track AnimationTrack[T]) Sample(time float32, interpolate func(T, T, float32) T) (T, bool)

type AnimationTween

type AnimationTween string

AnimationTween controls the curve applied from one keyframe to the next.

const (
	AnimationStep        AnimationTween = "step"
	AnimationLinear      AnimationTween = "linear"
	AnimationEaseIn      AnimationTween = "easeIn"
	AnimationEaseOut     AnimationTween = "easeOut"
	AnimationEaseInOut   AnimationTween = "easeInOut"
	AnimationBezier      AnimationTween = "bezier"
	AnimationCubicSpline AnimationTween = "cubicSpline"
)
const (
	AnimationEaseInSine       AnimationTween = "easeInSine"
	AnimationEaseOutSine      AnimationTween = "easeOutSine"
	AnimationEaseInOutSine    AnimationTween = "easeInOutSine"
	AnimationEaseInCubic      AnimationTween = "easeInCubic"
	AnimationEaseOutCubic     AnimationTween = "easeOutCubic"
	AnimationEaseInOutCubic   AnimationTween = "easeInOutCubic"
	AnimationEaseInQuart      AnimationTween = "easeInQuart"
	AnimationEaseOutQuart     AnimationTween = "easeOutQuart"
	AnimationEaseInOutQuart   AnimationTween = "easeInOutQuart"
	AnimationEaseInQuint      AnimationTween = "easeInQuint"
	AnimationEaseOutQuint     AnimationTween = "easeOutQuint"
	AnimationEaseInOutQuint   AnimationTween = "easeInOutQuint"
	AnimationEaseInExpo       AnimationTween = "easeInExpo"
	AnimationEaseOutExpo      AnimationTween = "easeOutExpo"
	AnimationEaseInOutExpo    AnimationTween = "easeInOutExpo"
	AnimationEaseInCirc       AnimationTween = "easeInCirc"
	AnimationEaseOutCirc      AnimationTween = "easeOutCirc"
	AnimationEaseInOutCirc    AnimationTween = "easeInOutCirc"
	AnimationEaseInBack       AnimationTween = "easeInBack"
	AnimationEaseOutBack      AnimationTween = "easeOutBack"
	AnimationEaseInOutBack    AnimationTween = "easeInOutBack"
	AnimationEaseInElastic    AnimationTween = "easeInElastic"
	AnimationEaseOutElastic   AnimationTween = "easeOutElastic"
	AnimationEaseInOutElastic AnimationTween = "easeInOutElastic"
	AnimationEaseInBounce     AnimationTween = "easeInBounce"
	AnimationEaseOutBounce    AnimationTween = "easeOutBounce"
	AnimationEaseInOutBounce  AnimationTween = "easeInOutBounce"
)

func (AnimationTween) Valid

func (t AnimationTween) Valid() bool

Valid reports whether the tween is supported by the runtime sampler.

type Animator

type Animator struct {
	Clip *AnimationClip

	Speed float32

	Playing bool
	Loop    bool
	// contains filtered or unexported fields
}

func NewAnimator

func NewAnimator(clip *AnimationClip, loop bool) Animator

func NewBoundAnimator

func NewBoundAnimator(clip *AnimationClip, loop bool, owner ecs.Entity, floatTargets, textureTargets, boolTargets []ecs.Entity) Animator

NewBoundAnimator creates one playback state for a shared clip and binds its typed tracks to concrete scene entities. The target slices are copied once at instantiation; subsequent updates perform only ECS component access.

func (*Animator) Advance

func (a *Animator) Advance(delta float32)

func (*Animator) BindTargets

func (a *Animator) BindTargets(owner ecs.Entity, floatTargets, textureTargets, boolTargets []ecs.Entity)

BindTargets attaches concrete entities to an existing animator. It is useful for pooled entities whose clip is unchanged but hierarchy IDs are assigned only when the pool slot is activated.

func (*Animator) CurrentTexture

func (a *Animator) CurrentTexture() *graphics.Texture

func (*Animator) IsBound

func (a *Animator) IsBound() bool

func (*Animator) Pause

func (a *Animator) Pause()

func (*Animator) Play

func (a *Animator) Play()

func (*Animator) Restart

func (a *Animator) Restart()

func (*Animator) Seek

func (a *Animator) Seek(time float32)

func (*Animator) Time

func (a *Animator) Time() float32

type Camera

type Camera struct {
	Viewport   CameraViewport
	Order      int
	Active     bool
	Clear      bool
	ClearColor graphics.ColorRGBA
	// Fallback is reserved for the engine camera used without an authored 2D camera.
	Fallback bool
	// contains filtered or unexported fields
}

func NewCamera

func NewCamera() Camera

func (Camera) ClipFromWorld

func (c Camera) ClipFromWorld(transform GlobalTransform, projection Projection) mgl32.Mat4

func (Camera) ResolvedViewport

func (c Camera) ResolvedViewport() CameraViewport

func (*Camera) UpdateViewport

func (c *Camera) UpdateViewport(width, height int)

func (Camera) ViewportSize

func (c Camera) ViewportSize() (float32, float32)

func (Camera) ViewportToWorld2D

func (c Camera) ViewportToWorld2D(transform GlobalTransform, projection Projection, viewportPosition mgl32.Vec2) (mgl32.Vec2, bool)

func (Camera) WorldToViewport2D

func (c Camera) WorldToViewport2D(transform GlobalTransform, projection Projection, worldPosition mgl32.Vec2) (mgl32.Vec2, bool)

type Camera2D

type Camera2D struct{}

type CameraPipeline

type CameraPipeline uint8
const (
	CameraPipeline2D CameraPipeline = iota
	CameraPipeline3D
)

type CameraRenderOptions

type CameraRenderOptions struct {
	Target     *render.RenderTarget
	ViewMode   render.RenderViewMode
	DepthClear float32
}

CameraRenderOptions contains the output settings shared by camera pipelines.

type CameraRenderer

type CameraRenderer func(*graphics.Canvas2D, *ecs.World, ExtractedCamera) error

CameraRenderer submits the prepared render data for one extracted camera.

type CameraViewport

type CameraViewport struct {
	X      float32 `json:"x"`
	Y      float32 `json:"y"`
	Width  float32 `json:"width"`
	Height float32 `json:"height"`
}

func (CameraViewport) PlacementMatrix

func (viewport CameraViewport) PlacementMatrix(width, height float32) mgl32.Mat4

PlacementMatrix maps local clip coordinates into this viewport's output region.

type ClipExempt2D

type ClipExempt2D struct {
	// ParentOnly skips the immediate parent's clip while retaining ancestor clips.
	ParentOnly bool
}

type ClipRect2D

type ClipRect2D struct {
	X      float32
	Y      float32
	Width  float32
	Height float32
}

type CompositeSettings2D

type CompositeSettings2D struct{ MaxCacheBytes int64 }

CompositeSettings2D bounds the persistent viewport cache. A negative budget disables it; zero selects 64 MiB. Dense animation uses direct drawing.

type CompositeStatistics2D

type CompositeStatistics2D struct {
	Tiles, DirtyTiles            int
	ReusedTiles                  int
	RasterPixels                 int
	Submitted, Occluded          int
	PreparedItems, PreparedTiles int
	CacheBytes                   int64
	Direct                       bool
}

CompositeStatistics2D distinguishes cached pixels from draw submission work. RasterPixels is the area redrawn, not a GPU time or fragment-count estimate.

type DebugInfo

type DebugInfo struct {
	Scale           float32
	Margin          float32
	Padding         float32
	TextColor       graphics.ColorRGBA
	BackgroundColor graphics.ColorRGBA
}

DebugInfo enables a compact frame statistics overlay in the top-left corner. Zero-valued fields use the defaults returned by NewDebugInfo.

func NewDebugInfo

func NewDebugInfo() DebugInfo

type DrawViews2D

type DrawViews2D struct {
	World mgl32.Mat4
	UI    mgl32.Mat4
}

type ExtractedCamera

type ExtractedCamera struct {
	Target       *render.RenderTarget
	RenderLayers RenderLayers
	Camera       Camera
	Scene        SceneLayer
	Entity       ecs.Entity
	Projection   Projection
	Transform    GlobalTransform
	OutputSize   mgl32.Vec2
	DepthClear   float32
	Pipeline     CameraPipeline
	ViewMode     render.RenderViewMode
}

func (ExtractedCamera) ClipFromWorld

func (camera ExtractedCamera) ClipFromWorld() mgl32.Mat4

ClipFromWorld includes viewport placement for draws into the full output surface.

type FixedTime

type FixedTime struct {
	Timestep time.Duration
	Overstep time.Duration
	Delta    time.Duration
	Elapsed  time.Duration
	Frame    uint64
}

func NewFixedTime

func NewFixedTime(timestep time.Duration) *FixedTime

func (*FixedTime) Accumulate

func (t *FixedTime) Accumulate(delta time.Duration, maxDelta time.Duration)

func (*FixedTime) DeltaSeconds

func (t *FixedTime) DeltaSeconds() float32

func (*FixedTime) ElapsedSeconds

func (t *FixedTime) ElapsedSeconds() float32

func (*FixedTime) Expend

func (t *FixedTime) Expend() bool

func (*FixedTime) OverstepFraction

func (t *FixedTime) OverstepFraction() float32

func (*FixedTime) SetTimestep

func (t *FixedTime) SetTimestep(timestep time.Duration)

type FocusedInputContext

type FocusedInputContext struct {
	World   *ecs.World
	Event   input.Event
	Entity  ecs.Entity
	Handled bool
}

func (*FocusedInputContext) Consume

func (c *FocusedInputContext) Consume()

type FocusedInputEvent

type FocusedInputEvent struct {
	Event   input.Event
	Entity  ecs.Entity
	Handled bool
}

FocusedInputEvent routes one keyboard or text event to the focused entity.

type FocusedInputHandler

type FocusedInputHandler struct {
	Handle func(*FocusedInputContext)
}

FocusedInputHandler handles keyboard/text input synchronously on the focused entity.

type GlobalTransform

type GlobalTransform struct {
	Matrix mgl32.Mat4
}

type Hierarchy

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

Hierarchy is the world-owned parent/child index shared by scene systems. It includes suspended scenes and never retains component storage pointers.

func HierarchyFor

func HierarchyFor(world *ecs.World) *Hierarchy

HierarchyFor synchronizes topology and invalidates inherited state only in affected subtrees. Borrowed lists remain valid until the next synchronization.

func (*Hierarchy) Depth added in v0.1.5

func (h *Hierarchy) Depth(entity ecs.Entity) int

Depth returns the number of live ancestors, including ancestors outside the current query scope. Missing entities and cycles return -1.

func (*Hierarchy) Entities

func (h *Hierarchy) Entities() []ecs.Entity

Entities returns the borrowed live entity list, independent of query scopes.

func (*Hierarchy) FirstChild

func (h *Hierarchy) FirstChild(entity ecs.Entity) ecs.Entity

FirstChild and NextSibling traverse ascending SiblingOrder with entity ties.

func (*Hierarchy) IsActive added in v0.1.11

func (h *Hierarchy) IsActive(entity ecs.Entity) bool

IsActive reads inherited activity as of the last HierarchyFor call.

func (*Hierarchy) MaintainCache

func (h *Hierarchy) MaintainCache()

func (*Hierarchy) NextSibling

func (h *Hierarchy) NextSibling(entity ecs.Entity) ecs.Entity

func (*Hierarchy) Parent

func (h *Hierarchy) Parent(entity ecs.Entity) ecs.Entity

func (*Hierarchy) Version

func (h *Hierarchy) Version() uint64

Version changes for live entity membership or an actual parent change.

func (*Hierarchy) WalkSubtree added in v0.1.9

func (h *Hierarchy) WalkSubtree(root ecs.Entity, visit func(ecs.Entity) bool)

WalkSubtree visits root and its descendants in sibling order. Returning false skips that entity's descendants. The visitor may read the hierarchy; collect entities before changing parentage or despawning them.

type InputBlocker2D

type InputBlocker2D struct {
	Width       float32
	Height      float32
	Receiver    ecs.Entity
	Cursor      input.Cursor
	InputFilter InputFilter
	PassThrough bool
}

type InputCapture2D

type InputCapture2D struct {
	Target   ecs.Entity
	Receiver ecs.Entity
	Camera   ecs.Entity
}

InputCapture2D describes the active 2D input capture. A capture keeps receiving move/release/cancel events after the input leaves its bounds.

type InputEvent

type InputEvent struct {
	File string
	Text string
	// Path contains the receiver followed by its parents for bubbling.
	Path        []ecs.Entity
	Composition input.TextComposition
	Selection   input.TextSelection
	Seq         uint64
	Entity      ecs.Entity
	Key         input.KeyCode
	X           float32
	Y           float32
	DeltaX      float32
	DeltaY      float32
	WheelX      float32
	WheelY      float32
	// Handled is set when a synchronous handler consumes the event.
	Handled bool
	Kind    InputEventKind
	Device  input.PointerDevice
	Button  input.MouseButton
	Command input.TextCommand
}

InputEvent is the unified ECS input delivered to scripts and systems. Entity and Path are populated for hit-tested pointer input and remain zero for global keyboard, text, and file input.

func InputEventFromPlatform

func InputEventFromPlatform(event input.Event) (InputEvent, bool)

InputEventFromPlatform converts non-pointer platform input into the unified ECS representation. Pointer input is emitted after 2D hit testing instead.

type InputEventContext

type InputEventContext struct {
	Event   *InputEvent
	Target  ecs.Entity
	Current ecs.Entity
	Handled bool
}

func (*InputEventContext) Consume

func (c *InputEventContext) Consume()

type InputEventKind

type InputEventKind uint8
const (
	InputEventKeyDown InputEventKind = iota + 1
	InputEventKeyUp
	InputEventTextInput
	InputEventTextComposition
	InputEventTextCommand
	InputEventTextSelection
	InputEventFilesDropped
	InputEventEnter
	InputEventLeave
	InputEventPress
	InputEventMove
	InputEventRelease
	InputEventTap
	InputEventWheel
	InputEventCancel
)

func (InputEventKind) IsPointer

func (kind InputEventKind) IsPointer() bool

func (InputEventKind) Mask

func (kind InputEventKind) Mask() InputMask

func (InputEventKind) String

func (kind InputEventKind) String() string

type InputFilter

type InputFilter uint8
const (
	InputFilterStop InputFilter = iota
	InputFilterPass
	InputFilterIgnore
)

type InputFocus

type InputFocus struct {
	Keyboard ecs.Entity
}

InputFocus is the currently focused ECS entity for keyboard/text input. Zero means that no entity owns keyboard focus.

type InputHandler2D

type InputHandler2D struct {
	Handle func(*InputEventContext)
}

InputHandler2D handles events synchronously along the target path.

type InputMask

type InputMask uint8
const (
	InputMaskPointer InputMask = 1 << iota
	InputMaskKeyboard
	InputMaskText
	InputMaskFiles
	InputMaskAll = InputMaskPointer | InputMaskKeyboard | InputMaskText | InputMaskFiles
)

func (InputMask) Intersects

func (mask InputMask) Intersects(other InputMask) bool

type InputRoute2D added in v0.1.8

type InputRoute2D struct {
	Handle func(*ecs.World, *InputEventContext)
}

InputRoute2D routes input to a retained owner associated with an entity.

type InputState2D

type InputState2D struct {
	Hovered bool
	Pressed bool
}

InputState2D is the input state shared by ordinary render entities and composed controls. The input dispatcher is its only writer.

type InputTarget2D

type InputTarget2D struct {
	Width       float32
	Height      float32
	Receiver    ecs.Entity
	Cursor      input.Cursor
	InputFilter InputFilter
	PassThrough bool
	Disabled    bool
	// AllowDisabledInput keeps non-editing inputs (for example
	// scrolling a read-only textarea) available while suppressing editing.
	AllowDisabledInput bool
}

type MeshMaterial2D

type MeshMaterial2D[T graphics.Material2D] struct {
	Material *T
}

type Name

type Name struct {
	Value string
}

type NineSlice2D

type NineSlice2D struct {
	Left   float32
	Right  float32
	Top    float32
	Bottom float32
}

type OrthographicArea

type OrthographicArea struct {
	MinX float32
	MinY float32
	MaxX float32
	MaxY float32
}

type OrthographicProjection

type OrthographicProjection struct {
	// ReverseZ uses a [0,1] depth range, with positive Near/Far distances,
	// for 3D cameras. The default matrix retains the 2D [-1,1] depth range.
	ReverseZ       bool
	Near           float32
	Far            float32
	ViewportOrigin mgl32.Vec2
	ScalingMode    ScalingMode
	Scale          float32
	Area           OrthographicArea
}

func NewOrthographicProjection2D

func NewOrthographicProjection2D() OrthographicProjection

func (OrthographicProjection) Matrix

func (p OrthographicProjection) Matrix() mgl32.Mat4

func (*OrthographicProjection) Update

func (p *OrthographicProjection) Update(width, height float32)

type PainterGroup2D

type PainterGroup2D uint64

PainterGroup2D keeps a subtree in one stable painter group. Groups sort before local UIStackIndex/RenderOrder2D values and are inherited by children.

type Parent

type Parent struct {
	Entity ecs.Entity
}

type ParticleAppearance2D

type ParticleAppearance2D struct {
	Texture *graphics.Texture
	Color   graphics.ColorRGBA
}

ParticleAppearance2D pairs a particle element's texture with its colour.

type ParticleEmitter2D

type ParticleEmitter2D struct {
	Texture *graphics.Texture

	Colors      []graphics.ColorRGBA
	Appearances []ParticleAppearance2D
	Count       int
	SizeMin     float32
	GravityX    float32
	Lifetime    float32
	SpeedMin    float32
	SpeedMax    float32
	Width       float32
	SizeMax     float32
	Direction   float32
	Spread      float32
	Rate        float32
	GravityY    float32
	AlphaStart  float32
	AlphaEnd    float32

	Height float32
	Loop   bool
	// contains filtered or unexported fields
}

func NewParticleEmitter2D

func NewParticleEmitter2D() ParticleEmitter2D

func (*ParticleEmitter2D) Active

func (e *ParticleEmitter2D) Active() bool

func (*ParticleEmitter2D) Normalize

func (e *ParticleEmitter2D) Normalize()

func (*ParticleEmitter2D) Reserve

func (e *ParticleEmitter2D) Reserve(maxParticles int)

Reserve preallocates particle storage for pooled effects.

func (*ParticleEmitter2D) Restart

func (e *ParticleEmitter2D) Restart()

Restart clears live particles and arms a non-looping emitter for another burst.

func (*ParticleEmitter2D) Stop

func (e *ParticleEmitter2D) Stop()

Stop clears live particles and disarms a burst emitter until it is restarted.

type PerspectiveProjection

type PerspectiveProjection struct {
	Fov  float32
	Near float32
}

func NewPerspectiveProjection

func NewPerspectiveProjection() PerspectiveProjection

func (PerspectiveProjection) Matrix

func (p PerspectiveProjection) Matrix(aspect float32) mgl32.Mat4

type Projection

type Projection struct {
	Kind         ProjectionKind
	Orthographic OrthographicProjection
	Perspective  PerspectiveProjection
}

func OrthographicProjection2D

func OrthographicProjection2D() Projection

func PerspectiveProjection3D

func PerspectiveProjection3D() Projection

func (Projection) Matrix

func (p Projection) Matrix(width, height float32) mgl32.Mat4

type ProjectionKind

type ProjectionKind uint8
const (
	ProjectionOrthographic ProjectionKind = iota
	ProjectionPerspective
)

type RenderLayers

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

func LayersForEntity

func LayersForEntity(world *ecs.World, entity ecs.Entity) RenderLayers

LayersForEntity returns authored render layers or the default layer zero.

func RenderLayer

func RenderLayer(layer uint) RenderLayers

func RenderLayersNone

func RenderLayersNone() RenderLayers

func (RenderLayers) Contains

func (layers RenderLayers) Contains(layer uint) bool

func (RenderLayers) Intersects

func (layers RenderLayers) Intersects(other RenderLayers) bool

func (RenderLayers) With

func (layers RenderLayers) With(layer uint) RenderLayers

func (RenderLayers) Without

func (layers RenderLayers) Without(layer uint) RenderLayers

type RenderOrder2D

type RenderOrder2D int
const DefaultParticleRenderOrder RenderOrder2D = 500

type RenderOutput2D

type RenderOutput2D struct{ Handle RenderOutputHandle }

type RenderOutputHandle

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

RenderOutputHandle is one lease on immutable logical drawing data. Copying a handle borrows that lease; Retain creates an independently releasable lease. Pools and handles are used on the engine's single logic/render thread.

func (RenderOutputHandle) Empty

func (h RenderOutputHandle) Empty() bool

func (RenderOutputHandle) Release

func (h RenderOutputHandle) Release() error

func (RenderOutputHandle) Retain

func (RenderOutputHandle) Size

func (h RenderOutputHandle) Size() (float32, float32, bool)

func (RenderOutputHandle) Valid

func (h RenderOutputHandle) Valid() bool

type RenderOutputPool

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

Fixed storage makes cached-output Retain/Release allocation-free and rejects capacity overflow explicitly rather than silently growing the hot path.

func NewRenderOutputPool

func NewRenderOutputPool(capacity int) *RenderOutputPool

func (*RenderOutputPool) Leases

func (p *RenderOutputPool) Leases() int

func (*RenderOutputPool) Text

func (p *RenderOutputPool) Text(value Text2D, release func() error) (RenderOutputHandle, error)

Text prepares glyph geometry once. The caller keeps the font alive until release runs after the final lease. No font or mutable draw callback is exposed through the resulting handle. Atlas textures use driver retirement.

func (*RenderOutputPool) TextBox

func (p *RenderOutputPool) TextBox(value Text2D, bounds Size2D, release func() error) (RenderOutputHandle, error)

TextBox limits painted output to positive logical bounds. Zero is unbounded.

type RenderPreparation2D

type RenderPreparation2D struct {
	Extracted         int
	Reused            int
	Sorted            bool
	PropertiesUpdated int
	PaintUpdated      int
}

RenderPreparation2D counts CPU preparation work for the latest extraction.

type RenderRequest

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

func NewRenderRequest

func NewRenderRequest(wake func()) *RenderRequest

func (*RenderRequest) Pending

func (r *RenderRequest) Pending() bool

func (*RenderRequest) Request

func (r *RenderRequest) Request()

func (*RenderRequest) Take

func (r *RenderRequest) Take() bool

type RenderSettings2D

type RenderSettings2D struct {
	ClearColor graphics.ColorRGBA
}

type RenderWorld

type RenderWorld struct {
	Cameras []ExtractedCamera
	Items2D []renderItem2D

	Composite2D   CompositeStatistics2D
	Preparation2D RenderPreparation2D
	// contains filtered or unexported fields
}

func NewRenderWorld

func NewRenderWorld() *RenderWorld

func RenderWorldFor

func RenderWorldFor(world *ecs.World) *RenderWorld

RenderWorldFor returns the world's render state, creating it on first use.

func (*RenderWorld) Dispose

func (state *RenderWorld) Dispose() error

Dispose releases retained GPU output while the window's device is alive.

func (*RenderWorld) RegisterCameraRenderer

func (state *RenderWorld) RegisterCameraRenderer[T any](pipeline CameraPipeline, describe func(*T) CameraRenderOptions, draw CameraRenderer)

RegisterCameraRenderer binds a typed camera component to a render pipeline. Registration is idempotent for the same type and pipeline. Extraction borrows the component and stores only output settings; stable frames do not allocate.

func (*RenderWorld) RegisterMaterial2D

func (state *RenderWorld) RegisterMaterial2D[T graphics.Material2D]()

RegisterMaterial2D enables extraction of MeshMaterial2D[T] components. It mirrors Bevy's Material2dPlugin<T> registration boundary.

type ResolvedUIRect

type ResolvedUIRect struct {
	Left   float32
	Right  float32
	Top    float32
	Bottom float32
}

func (ResolvedUIRect) Horizontal

func (r ResolvedUIRect) Horizontal() float32

func (ResolvedUIRect) Vertical

func (r ResolvedUIRect) Vertical() float32

type RoundedClip2D

type RoundedClip2D struct {
	X         float32
	Y         float32
	Width     float32
	Height    float32
	Radius    float32
	MaskColor graphics.ColorRGBA
}

RoundedClip2D adds a uniform corner radius to a local clip rectangle. It is consumed by the built-in sprite pipeline in addition to ClipRect2D; keeping the rectangle separate preserves the existing scissor/culling fast path.

type ScalingMode

type ScalingMode struct {
	Kind   ScalingModeKind
	Width  float32
	Height float32
}

func AutoMaxScaling

func AutoMaxScaling(maxWidth, maxHeight float32) ScalingMode

func AutoMinScaling

func AutoMinScaling(minWidth, minHeight float32) ScalingMode

func FixedHorizontalScaling

func FixedHorizontalScaling(viewportWidth float32) ScalingMode

func FixedScaling

func FixedScaling(width, height float32) ScalingMode

func FixedVerticalScaling

func FixedVerticalScaling(viewportHeight float32) ScalingMode

type ScalingModeKind

type ScalingModeKind uint8
const (
	ScalingModeWindowSize ScalingModeKind = iota
	ScalingModeFixed
	ScalingModeAutoMin
	ScalingModeAutoMax
	ScalingModeFixedVertical
	ScalingModeFixedHorizontal
)

type SceneLayer

type SceneLayer struct {
	ID, Order uint64
	Overlay   bool
}

SceneLayer separates camera content and orders complete scenes before local world/UI order. Descendants inherit the scene root's layer.

func LayerForEntity

func LayerForEntity(world *ecs.World, entity ecs.Entity) SceneLayer

type Shader

type Shader[T graphics.Material2DShader | graphics.MeshShader] struct {
	Program *T
	Custom  [4][4]float32
}

Shader attaches a shared GPU program and per-element uniforms to geometry. T is graphics.Material2DShader for sprites or graphics.MeshShader for meshes.

type Shape2D

type Shape2D struct {
	Kind        render.ShapeKind
	Fill        graphics.ColorRGBA
	Border      graphics.ColorRGBA
	Radius      float32
	BorderWidth float32
}

func CheckmarkShape2D

func CheckmarkShape2D(fill graphics.ColorRGBA) Shape2D

func OutlinedRoundedRectShape2D

func OutlinedRoundedRectShape2D(fill, border graphics.ColorRGBA, radius, borderWidth float32) Shape2D

func RoundedRectShape2D

func RoundedRectShape2D(fill graphics.ColorRGBA, radius float32) Shape2D

func TriangleShape2D

func TriangleShape2D(fill graphics.ColorRGBA, direction uint8) Shape2D

type SiblingOrder

type SiblingOrder int

SiblingOrder preserves authored sibling order. Runtime-created nodes fall back to their Entity value.

type Size2D

type Size2D struct {
	Width  float32
	Height float32
}

type Spine2D

type Spine2D struct {
	Player *spine.Player
}

type Sprite2D

type Sprite2D struct {
	Texture *graphics.Texture
	Slice   *NineSlice2D
	Shape   Shape2D
	Tint    graphics.ColorRGBA
	Width   float32
	Height  float32
	Alpha   float32
}

func NewColorSprite2D

func NewColorSprite2D(clr graphics.ColorRGBA, width, height int) Sprite2D

func NewSprite2D

func NewSprite2D() Sprite2D

func Sprite2DFromTexture

func Sprite2DFromTexture(texture *graphics.Texture) Sprite2D

func (*Sprite2D) Size

func (s *Sprite2D) Size() (width, height float32)

Size resolves logical dimensions, using texture dimensions for omitted axes.

type SpriteLayer2D

type SpriteLayer2D struct {
	ID        string
	Sprite    Sprite2D
	Order     int
	Transform SpriteLayerTransform2D
	Anchor    Anchor
	Visible   bool
}

type SpriteLayerTransform2D

type SpriteLayerTransform2D struct {
	X, Y, Z                float32
	ScaleX, ScaleY, ScaleZ float32
	RotationX, RotationY   float32
	Rotation               float32
}

SpriteLayerTransform2D describes the local transform of a standalone sprite layer. It is intentionally independent of animation playback.

func (SpriteLayerTransform2D) LocalMatrix

func (t SpriteLayerTransform2D) LocalMatrix() mgl32.Mat4

type SpriteLayers2D

type SpriteLayers2D struct {
	Layers []SpriteLayer2D
	// contains filtered or unexported fields
}

SpriteLayers2D is a collection of independently rendered sprite or shape fragments sharing one entity's transform, clip and paint order.

func (*SpriteLayers2D) InvalidateMatrices

func (a *SpriteLayers2D) InvalidateMatrices()

func (*SpriteLayers2D) LayerMatrix

func (a *SpriteLayers2D) LayerMatrix(index int) mgl32.Mat4

type SpriteTrail2D

type SpriteTrail2D struct {
	MaxSamples int

	Lifetime    float32
	Interval    float32
	MinDistance float32
	AlphaStart  float32
	AlphaEnd    float32
	// contains filtered or unexported fields
}

SpriteTrail2D records resolved transform snapshots and renders them as fading afterimages. Component presence enables the effect; remove it to disable and discard the trail.

func NewSpriteTrail2D

func NewSpriteTrail2D() SpriteTrail2D

func (*SpriteTrail2D) Clear

func (t *SpriteTrail2D) Clear()

func (*SpriteTrail2D) Reserve

func (t *SpriteTrail2D) Reserve(maxSamples int)

Reserve allocates storage for up to maxSamples trail snapshots. It is useful for pooled effects that need allocation-free updates after activation.

func (*SpriteTrail2D) SampleCount

func (t *SpriteTrail2D) SampleCount() int

type Text2D

type Text2D struct {

	// Source supplies immutable document text; Value is used when Source is empty.
	Source piecetree.Snapshot
	// Index optionally shares a document's indexed text buffer for caret lookup.
	Index TextIndex

	Font *onixtext.Font
	// LineLayout spaces visual lines without inserting characters into Value.
	LineLayout *TextLineLayout2D

	Value string

	// Spans are sorted, non-overlapping UTF-8 byte ranges.
	Spans []TextSpan2D

	InlineObjects []TextInlineObject2D
	// Prelayout uses positions already computed by a layout engine for one line.
	// Its producer increments Revision whenever those positions or Value change.
	Prelayout TextPrelayout2D

	DPI float64

	FontSize float64

	OutlineColor graphics.ColorRGBA
	Color        graphics.ColorRGBA
	ShadowColor  graphics.ColorRGBA

	ShadowX float32

	WrapWidth    float32
	OutlineWidth float32
	ShadowY      float32

	LetterSpacing float32
	Alpha         float32
	MaxWidth      float32

	// TabWidth is the distance between tab stops in logical pixels.
	TabWidth float32

	// InkOffsetY shifts painted glyphs without changing line or caret geometry.
	InkOffsetY float32
	LineHeight float32

	TextAlignment TextAlignment

	// LCD enables RGB-stripe antialiasing on an opaque UI surface.
	LCD bool

	WrapMode TextWrapMode
	// contains filtered or unexported fields
}

func NewText2D

func NewText2D(value string) Text2D

func (*Text2D) QueueUploads

func (t *Text2D) QueueUploads(queue *graphics.UploadQueue)

QueueUploads adds resources referenced by CPU-side text layout. Layout and rasterization stay on the owning loop thread; the queue budgets first upload.

func (Text2D) Text

func (t Text2D) Text() piecetree.Snapshot

Text returns the authoritative immutable text used for geometry and paint.

type TextAlignment

type TextAlignment uint8
const (
	TextAlignLeft TextAlignment = iota
	TextAlignCenter
	TextAlignRight
)

type TextHiddenLines2D added in v0.1.10

type TextHiddenLines2D struct{ Start, End int }

TextHiddenLines2D omits hard lines whose start byte falls in [Start, End). Start and End are line starts. Use document length + 1 to include the final line. Supply sorted, disjoint ranges and keep at least the first line visible.

type TextIndex

type TextIndex interface {
	MatchesSnapshot(piecetree.Snapshot) bool
	ByteOffset(int) int
}

TextIndex resolves rune offsets against a matching immutable snapshot.

type TextInlineObject2D

type TextInlineObject2D struct {
	Start    int
	End      int
	Width    float32
	Height   float32
	Baseline float32
}

type TextInlineObjectRect2D

type TextInlineObjectRect2D struct {
	Start int
	End   int
	Rect  TextRangeRect2D
}

func TextInlineObjectRects2D

func TextInlineObjectRects2D(text *Text2D) ([]TextInlineObjectRect2D, bool)

type TextLineLayout2D

type TextLineLayout2D struct {
	Hidden        []TextHiddenLines2D
	Offsets       []float32
	Width, Height float32
	Revision      uint64
}

TextLineLayout2D hides source lines, adds vertical gaps and sets a minimum extent. Owners increment Revision whenever ranges, offsets or dimensions change; unchanged layouts require no slice comparison or allocation during measurement.

type TextPrelayout2D

type TextPrelayout2D struct {
	Glyphs           []font.PositionedGlyph
	OriginX, OriginY float64
	Width, Height    float32
	Revision         uint64
}

type TextRangeRect2D

type TextRangeRect2D struct {
	X      float32
	Y      float32
	Width  float32
	Height float32
}

func MeasureTextRangeRects2D

func MeasureTextRangeRects2D(text *Text2D, start, end int) ([]TextRangeRect2D, bool)

func TextLineRange2D

func TextLineRange2D(text *Text2D, index int) (start, end int, rect TextRangeRect2D, ok bool)

TextLineRange2D exposes byte offsets and geometry of one cached visual line.

func TextLineRects2D

func TextLineRects2D(text *Text2D) ([]TextRangeRect2D, bool)

type TextSpan2D

type TextSpan2D struct {
	Start int
	End   int
	Color graphics.ColorRGBA
}

type TextWrapMode

type TextWrapMode uint8
const (
	TextWrapWords TextWrapMode = iota
	TextWrapNewlines
	TextWrapNone
	// TextWrapCharacters wraps every line at WrapWidth, including long words.
	TextWrapCharacters
	// TextWrapTokens wraps at word/identifier and punctuation boundaries without
	// discarding whitespace. A token wider than WrapWidth remains on one line.
	TextWrapTokens
)

type Tilemap2D

type Tilemap2D struct {
	Texture    *graphics.Texture
	Tiles      []int
	Revision   uint64
	Width      int
	Height     int
	TileWidth  int
	TileHeight int
	Columns    int
	Alpha      float32
}

func (*Tilemap2D) PixelHeight

func (t *Tilemap2D) PixelHeight() float32

func (*Tilemap2D) PixelWidth

func (t *Tilemap2D) PixelWidth() float32

func (*Tilemap2D) Valid

func (t *Tilemap2D) Valid() bool

func (*Tilemap2D) ValidFor

func (t *Tilemap2D) ValidFor(device *render.Device) bool

type Time

type Time struct {
	Delta   time.Duration
	Elapsed time.Duration
	Frame   uint64
	// contains filtered or unexported fields
}

func NewTime

func NewTime() *Time

func (*Time) Advance

func (t *Time) Advance(now time.Time)

func (*Time) DeltaSeconds

func (t *Time) DeltaSeconds() float32

func (*Time) ElapsedSeconds

func (t *Time) ElapsedSeconds() float32

func (*Time) Set

func (t *Time) Set(delta time.Duration, elapsed time.Duration, frame uint64)

type Transform

type Transform struct {
	Translation mgl32.Vec3
	Rotation    mgl32.Quat
	Scale       mgl32.Vec3
}

Transform is the local spatial transform shared by 2D and 3D world entities. Two-dimensional entities use the Z translation for depth ordering and normally rotate around Z with a unit Z scale.

func NewTransform

func NewTransform() Transform

func TransformFromTranslation

func TransformFromTranslation(translation mgl32.Vec3) Transform

func TransformFromXYZ

func TransformFromXYZ(x, y, z float32) Transform

func (Transform) LocalMatrix

func (t Transform) LocalMatrix() mgl32.Mat4

func (Transform) LookingAt

func (t Transform) LookingAt(target, up mgl32.Vec3) Transform

type UIBackground2D

type UIBackground2D struct {
	Shape Shape2D
	Alpha float32
}

UIBackground2D is the background layer of a UI node.

func NewUIBackground2D

func NewUIBackground2D(shape Shape2D) UIBackground2D

type UIBorder2D

type UIBorder2D struct {
	Shape Shape2D
	Alpha float32
}

UIBorder2D is the border layer of a UI node.

func NewUIBorder2D

func NewUIBorder2D(shape Shape2D) UIBorder2D

type UIBoxPaint2D added in v0.1.8

type UIBoxPaint2D struct {
	Text                UIStaticText2D
	Stack               int
	Shape               Shape2D
	X, Y, Width, Height float32
	Order               uint32
}

UIBoxPaint2D holds the paint of one passive UI box in surface coordinates. The solid border uses the shape's border parameters.

type UIGlobalTransform

type UIGlobalTransform struct {
	Matrix mgl32.Mat4
	// contains filtered or unexported fields
}

func (UIGlobalTransform) ClipRect

func (t UIGlobalTransform) ClipRect() (ClipRect2D, bool)

ClipRect returns the inherited clipping bounds in world UI coordinates. The boolean distinguishes an empty clipping rectangle from no clipping.

type UIImage2D

type UIImage2D struct {
	Texture *graphics.Texture
	Slice   *NineSlice2D
	Mode    UIImageMode
	Tint    graphics.ColorRGBA
	Alpha   float32
}

UIImage2D is the image layer of a UI node.

func NewUIImage2D

func NewUIImage2D(texture *graphics.Texture) UIImage2D

type UIImageMode

type UIImageMode uint8

UIImageMode controls how a UI image is fitted into its node.

const (
	// UIImageAuto preserves the source aspect ratio and fits inside the node.
	UIImageAuto UIImageMode = iota
	// UIImageStretch stretches the source image to the node bounds.
	UIImageStretch
	// UIImageSliced stretches the center while preserving the configured borders.
	UIImageSliced
)

type UIPaint2D added in v0.1.8

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

UIPaint2D owns the paint fragments attached to one UI entity.

func (*UIPaint2D) Fragments added in v0.1.8

func (paint *UIPaint2D) Fragments() []UIShapeFragment2D

Fragments returns the entity's fragments for read-only access.

type UIPaintList2D added in v0.1.8

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

UIPaintList2D stores paint on its surface entity. Slots are addressed by the layout producer and may be replaced without moving other boxes.

func (*UIPaintList2D) Boxes added in v0.1.10

func (list *UIPaintList2D) Boxes(yield func(UIBoxPaint2D) bool)

Boxes iterates live paint slots. The layout glyph slices are borrowed for the visit.

func (*UIPaintList2D) Capacity added in v0.1.8

func (list *UIPaintList2D) Capacity() (boxes, free, glyphs int)

Capacity reports the capacity of the slot table, free list, and glyph runs.

func (*UIPaintList2D) Compact added in v0.1.8

func (list *UIPaintList2D) Compact() []uint32

Compact reclaims slot storage after substantial shrinkage and reports the new IDs so the layout producer can keep its surviving slots addressable.

func (*UIPaintList2D) Len added in v0.1.8

func (list *UIPaintList2D) Len() int

func (*UIPaintList2D) RemoveBox added in v0.1.8

func (list *UIPaintList2D) RemoveBox(id uint32)

func (*UIPaintList2D) Reset added in v0.1.8

func (list *UIPaintList2D) Reset()

func (*UIPaintList2D) SetBox added in v0.1.8

func (list *UIPaintList2D) SetBox(id uint32, box UIBoxPaint2D) uint32

SetBox updates a slot and returns its ID. Zero creates a slot.

func (*UIPaintList2D) SetOrder added in v0.1.8

func (list *UIPaintList2D) SetOrder(id uint32, stack int, order uint32)

SetOrder updates the stacking position and document order of a slot.

type UIRect

type UIRect struct {
	Left   Val `json:"left,omitzero"`
	Right  Val `json:"right,omitzero"`
	Top    Val `json:"top,omitzero"`
	Bottom Val `json:"bottom,omitzero"`
}

func UIRectAll

func UIRectAll(value Val) UIRect

func UIRectPercent

func UIRectPercent(left, right, top, bottom float32) UIRect

func UIRectPx

func UIRectPx(left, right, top, bottom float32) UIRect

func (UIRect) IsZero

func (r UIRect) IsZero() bool

type UIResolveContext

type UIResolveContext struct {
	ScaleFactor float32
	BaseSize    mgl32.Vec2
	Viewport    mgl32.Vec2
}

type UIScroll

type UIScroll struct {
	Position     mgl32.Vec2
	Momentum     mgl32.Vec2
	ViewportSize mgl32.Vec2
	ContentSize  mgl32.Vec2
	WheelStep    float32
	// ScrollbarSize enables native scrollbar-thumb dragging for this viewport.
	// A zero value keeps the legacy content-drag behavior for bare UIScroll
	// components that do not render scrollbar parts.
	ScrollbarSize         float32
	ScrollbarMinThumbSize float32
	ScrollbarThin         bool
	// Overlay bars lie inside the viewport without reserving content space.
	ScrollbarOverlay bool
	DisableInput     bool
	DisableDrag      bool
	// DisableContentDrag leaves left-button gestures to text selection while
	// preserving scrollbar dragging, the wheel and middle-button panning.
	DisableContentDrag bool
	ConsumeWheel       bool
	Horizontal         bool
	Vertical           bool
	// contains filtered or unexported fields
}

UIScroll stores allocation-free scrolling state for an absolute-positioned UI viewport. Position is the non-positive offset applied by the caller to its content transform.

type UIScrollContainerData

type UIScrollContainerData struct {
	Scroll       *UIScroll
	ViewportSize mgl32.Vec2
	ContentSize  mgl32.Vec2
	Horizontal   bool
	Vertical     bool
}

func GetUIScrollContainerData

func GetUIScrollContainerData(world *ecs.World, entity ecs.Entity) (UIScrollContainerData, bool)

type UIShapeFragment2D added in v0.1.8

type UIShapeFragment2D struct {
	StackOffset         int
	Shape               Shape2D
	X, Y, Width, Height float32
}

UIShapeFragment2D is a paint-only rectangle in a UI entity's local coordinates. It shares the entity's transform, clipping and camera routing.

type UIStackIndex

type UIStackIndex int

type UIStaticText2D added in v0.1.8

type UIStaticText2D struct {
	Font          *onixtext.Font
	Layout        TextPrelayout2D
	FontSize, DPI float64
	Color         graphics.ColorRGBA
	X, Y          float32
	LCD           bool
}

UIStaticText2D describes a single prelaid-out run. The glyph positions are borrowed from the layout producer and must stay valid until the next update.

type UITargetCamera

type UITargetCamera struct {
	Entity ecs.Entity
}

type UITransform

type UITransform struct {
	Translation Val2
	Scale       mgl32.Vec2
	Rotation    float32
	Skew        mgl32.Vec2
	// Pivot is the local point around which rotation, skew, and scale are applied.
	Pivot mgl32.Vec2
	// LinearMatrix overrides rotation, skew, and scale when nonzero. It preserves
	// exact composition, including singular scales; pivot and translation still apply.
	LinearMatrix mgl32.Mat4
}

func NewUITransform

func NewUITransform() UITransform

func UITransformFromXY

func UITransformFromXY(x, y float32) UITransform

func (UITransform) LocalMatrix

func (t UITransform) LocalMatrix(context UIResolveContext) mgl32.Mat4

type UIVisualRects2D added in v0.1.8

type UIVisualRects2D []TextRangeRect2D

UIVisualRects2D repeats a node's background, image and border over local rectangles. An empty collection emits no visuals.

type Val

type Val struct {
	Kind  ValKind
	Value float32
}

func Auto

func Auto() Val

func ParseVal

func ParseVal(value string) (Val, error)

func Percent

func Percent(value float32) Val

func Px

func Px(value float32) Val

func VMax

func VMax(value float32) Val

func VMin

func VMin(value float32) Val

func Vh

func Vh(value float32) Val

func Vw

func Vw(value float32) Val

func (Val) Add

func (v Val) Add(other Val) (Val, error)

func (Val) IsZero

func (v Val) IsZero() bool

func (Val) MarshalJSON

func (v Val) MarshalJSON() ([]byte, error)

func (Val) Mul

func (v Val) Mul(factor float32) Val

func (Val) Resolve

func (v Val) Resolve(scaleFactor, baseValue float32, viewport mgl32.Vec2) (float32, bool)

func (Val) String

func (v Val) String() string

func (Val) Sub

func (v Val) Sub(other Val) (Val, error)

func (*Val) UnmarshalJSON

func (v *Val) UnmarshalJSON(data []byte) error

type Val2

type Val2 struct {
	X Val `json:"x,omitzero"`
	Y Val `json:"y,omitzero"`
}

func Percent2

func Percent2(x, y float32) Val2

func Px2

func Px2(x, y float32) Val2

func (Val2) IsZero

func (v Val2) IsZero() bool

func (Val2) Resolve

func (v Val2) Resolve(context UIResolveContext) mgl32.Vec2

type ValKind

type ValKind uint8
const (
	ValAuto ValKind = iota
	ValPx
	ValPercent
	ValVw
	ValVh
	ValVMin
	ValVMax
)

type ViewportSize

type ViewportSize struct {
	Width       float32
	Height      float32
	ScaleFactor float32
}

type Visibility

type Visibility struct {
	Visible bool
}

type WebView

type WebView struct {
	OnMessage WebViewHandler
	OnInvoke  WebViewMessageHandler
	Bindings  map[string]WebViewHandler
	HTML      string
	URL       string
	// Bounds is an alternate grouped form of X/Y/Width/Height. When it is
	// non-zero it takes precedence over the scalar fields.
	Bounds      WebViewBounds
	Y           float32
	Height      float32
	Width       float32
	X           float32
	Visible     bool
	DevTools    bool
	Transparent bool
}

WebView is a native browser surface owned by an ECS entity. URL and HTML are mutually exclusive; URL takes precedence when both are set. Bounds are expressed in logical window pixels.

The component is deliberately independent of any platform UI type. Install a WebViewRuntime resource and WebViewSystem to materialize it.

func NewWebView

func NewWebView(url string) WebView

NewWebView creates a visible WebView that navigates to url.

func NewWebViewHTML

func NewWebViewHTML(html string) WebView

NewWebViewHTML creates a visible WebView containing inline HTML.

func (*WebView) Bind

func (w *WebView) Bind(name string, handler WebViewHandler) bool

Bind adds or replaces a named JavaScript invocation handler. Bindings are resolved from the current component on invocation, so changing the map does not recreate the native view.

func (*WebView) Unbind

func (w *WebView) Unbind(name string) bool

Unbind removes a named JavaScript invocation handler.

type WebViewBackend

type WebViewBackend interface {
	Create(options WebViewOptions, invoke WebViewInvoke, events func(WebViewEvent)) (WebViewHandle, error)
}

WebViewBackend creates browser surfaces. The callback may be called by the backend at any time while the returned handle is alive.

type WebViewBounds

type WebViewBounds struct {
	X      float32
	Y      float32
	Width  float32
	Height float32
}

WebViewBounds is the logical rectangle occupied by a browser surface.

type WebViewEvent

type WebViewEvent struct {
	Name    string
	Payload string
	Message string
	URL     string
	Error   string
	Entity  ecs.Entity
	Kind    WebViewEventKind
}

WebViewEvent is emitted through the ECS message queue by WebViewRuntime. Message contains the raw JSON payload for WebViewEventMessage. Error is a stable text copy so events remain safe after a backend callback returns.

type WebViewEventKind

type WebViewEventKind uint8

WebViewEventKind identifies a platform event delivered to ECS.

const (
	WebViewEventReady WebViewEventKind = iota + 1
	WebViewEventMessage
	WebViewEventNavigation
	WebViewEventError
	WebViewEventClosed
)

type WebViewHandle

type WebViewHandle interface {
	Navigate(url string) error
	SetHTML(html string) error
	Eval(script string) error
	SetBounds(bounds WebViewBounds) error
	SetVisible(visible bool) error
	Destroy() error
}

WebViewHandle is the platform-owned browser surface.

type WebViewHandler

type WebViewHandler func(payload string) (result string, err error)

WebViewHandler handles a named invocation from a web page. Payload is the JSON text supplied by the page and the returned string is resolved back to the JavaScript Promise. Returning an error rejects that Promise.

type WebViewInvoke

type WebViewInvoke func(name, payload string) (result string, err error)

WebViewInvoke dispatches a named JavaScript bridge call to Go. The backend must call it on the platform UI thread and use the returned result to settle the JavaScript Promise.

type WebViewMessageHandler

type WebViewMessageHandler func(name, payload string) (result string, err error)

WebViewMessageHandler handles every bridge invocation, including its name.

type WebViewOptions

type WebViewOptions struct {
	URL         string
	HTML        string
	Bounds      WebViewBounds
	Visible     bool
	DevTools    bool
	Transparent bool
}

WebViewOptions is passed to a platform backend when an instance is created.

type WebViewRuntime

type WebViewRuntime struct {
	Backend WebViewBackend
	// contains filtered or unexported fields
}

WebViewRuntime owns native handles for all WebView components in one world. It is safe to reuse a runtime across frames; synchronization only invokes backend methods when component state has changed.

func NewWebViewRuntime

func NewWebViewRuntime(backend WebViewBackend) *WebViewRuntime

NewWebViewRuntime creates a runtime using backend. A nil backend is valid and causes WebViewSystem to emit one unavailable event per entity.

func (*WebViewRuntime) Close

func (r *WebViewRuntime) Close() error

Close destroys every materialized browser surface. It is idempotent.

func (*WebViewRuntime) Eval

func (r *WebViewRuntime) Eval(entity ecs.Entity, script string) error

Eval evaluates script in an existing browser surface.

func (*WebViewRuntime) Handle

func (r *WebViewRuntime) Handle(entity ecs.Entity) (WebViewHandle, bool)

Handle returns the native handle for entity after synchronization. The handle is owned by the runtime and must not be destroyed by the caller.

func (*WebViewRuntime) Navigate

func (r *WebViewRuntime) Navigate(world *ecs.World, entity ecs.Entity, url string) error

Navigate requests navigation without changing the authored component. The component's URL is updated as well, so the request remains stable across the next synchronization pass.

Directories

Path Synopsis
Package render3d owns meshes, camera settings, lights, deformation, shadows, post-processing, and the 3D extract/prepare/sort/draw pipeline.
Package render3d owns meshes, camera settings, lights, deformation, shadows, post-processing, and the 3D extract/prepare/sort/draw pipeline.

Jump to

Keyboard shortcuts

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