gameui

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 24 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 gameui provides stylized in-canvas menus, spatial focus navigation, virtual-resolution scaling, and world-anchored native NSGo overlays.

Build a widget tree from containers (Panel, VBox, HBox) and widgets (Label, Button, Toggle, Slider, List, ProgressBar, ImageProgress, Spacer), wrap it in a Root, and drive layout, input, and drawing from your game's Canvas:

  • Call Root.Layout(bounds) to compute exact non-overlapping widget rectangles with padding, spacing, fixed/flex sizing, and alignment.
  • Configure Root.Viewport (or Viewport.Draw / Viewport.WindowToVirtual) for virtual-resolution Fit/Letterbox/Fill/Stretch/Integer scaling and accurate pointer/touch hit-testing.
  • Route pointer/touch events via OnPointerMove, OnPointerDown, OnPointerUp, or OnPress, and keyboard/gamepad navigation via SpatialNavigator (2D spatial lookup, explicit NavOverrides, StepActions, OnConfirm/OnBack, and customizable FocusRingStyle) or Root.OnKeyDown.
  • Call Root.Draw(d, bounds) inside Canvas.Draw; all operations run inside Save/Restore using Path fills and strokes so caller drawing state is never mutated.
  • Customize visuals with Theme (starting from DefaultTheme), NineSlice / FrameDrawer hooks, and custom TextDrawer / TextMeasurer hooks for bitmap fonts.
  • Drop in SettingsMenu for a ready-to-use Audio, Video, Controls (rebinding), Language, and Accessibility screen persisted through save.DefaultSettingsStore and playable with mouse, touch, keyboard, and gamepad alone.
  • Mount AnchorOverlay over your game Canvas and call Sync(proj) each frame to pin native NSGo views (name tags, speech bubbles, text inputs) to 2D world positions with automatic off-screen hiding.

Index

Examples

Constants

View Source
const (
	// MinTouchTargetSize is the minimum touch target diameter in points required on phones and tablets.
	MinTouchTargetSize float32 = 44
	// MinTextContrastRatio is the minimum WCAG 2.1 contrast ratio required for screen text against its fill.
	MinTextContrastRatio float64 = 4.5
)
View Source
const (
	// SettingsCustomResolution is the key inside save.Settings.Custom storing the selected resolution ID.
	SettingsCustomResolution = "resolution"
	// SettingsCustomReduceFlashes is the legacy key inside save.Settings.Custom that stored the flash-reduction toggle before save.AccessibilitySettings.ReduceFlashes existed.
	//
	// Deprecated: Use save.AccessibilitySettings.ReduceFlashes directly.
	SettingsCustomReduceFlashes = "reduce_flashes"
)
View Source
const DefaultScreenFontSize float32 = 12

DefaultScreenFontSize is the default virtual font size in points used for screen files when a node omits fontSize.

View Source
const ScreenFormatVersion = 1

ScreenFormatVersion is the *.screen.yaml schema version this package reads and writes.

View Source
const ScreenSchemaComment = "# yaml-language-server: $schema=" + ScreenSchemaURL

ScreenSchemaComment is the first line EncodeScreen writes: a YAML comment pointing a YAML language server at ScreenSchemaURL. ParseScreen ignores it like any other comment.

View Source
const ScreenSchemaURL = "https://game.nsgo.dev/schemas/screen.v1.json"

ScreenSchemaURL is where the JSON Schema of version 1 screen documents is published. EncodeScreen writes it in a yaml-language-server comment on the first line so editors and AI tools validate and complete screen files as they are written.

Variables

This section is empty.

Functions

func ApplyBindingsToActions

func ApplyBindingsToActions(a *input.Actions, bindings map[string][]string, preserveRegions bool)

ApplyBindingsToActions updates a's action bindings from save.Settings.Bindings. When preserveRegions is true, existing TouchRegion and MouseRegion inputs on each action are preserved alongside the rebound keyboard, mouse-button, and gamepad bindings.

func ApplyInputAssistsToActions

func ApplyInputAssistsToActions(a *input.Actions, s save.Settings)

ApplyInputAssistsToActions applies s.InputAssists and s.Accessibility.HoldToToggle (expanding a.ToggleableActions() when HoldToToggle is true) onto a.

func ApplySettingsResolution

func ApplySettingsResolution(v *screen.Video, s save.Settings, resolutions ...SettingsResolution)

ApplySettingsResolution reads the persisted resolution ID from s.Custom["resolution"], resolves its dimensions against resolutions (falling back to ParseSettingsResolution), and applies it to v via v.ApplyResolution. A nil v is a no-op.

func DrawFocusRing

func DrawFocusRing(d *core.Drawing, bounds core.Bounds, radius float32, style *FocusRingStyle, theme *Theme)

DrawFocusRing renders a customizable focus ring around bounds using style and theme defaults.

func EncodeScreen

func EncodeScreen(doc *ScreenDoc) ([]byte, error)

EncodeScreen validates doc and writes it as deterministic 2-space YAML prefixed with ScreenSchemaComment. A document EncodeScreen writes loads with ParseScreen and saves back byte-for-byte unchanged.

func FormatBindingLabel

func FormatBindingLabel(token string) string

FormatBindingLabel returns a concise human-readable label for a binding token (for example "Space", "A", "Pad A/South", or "Mouse Left").

func FormatBindingToken

func FormatBindingToken(in input.Input) string

FormatBindingToken encodes an input.Input into a portable string token suitable for save.Settings.Bindings. Returns "" for region inputs or zero inputs.

func GamepadButtonToken

func GamepadButtonToken(b gamepad.Button) string

GamepadButtonToken returns the canonical binding token stored in save.Settings.Bindings for b (such as "gamepad:south" or "gamepad:dpad_left"), or "" if b is out of range.

func InputAssistsFromSettings

func InputAssistsFromSettings(s save.Settings, toggleable ...string) input.Assists

InputAssistsFromSettings converts s.InputAssists (and s.Accessibility.HoldToToggle, expanding toggleable actions when enabled) into an input.Assists value.

func MeasureScreenText

func MeasureScreenText(text string, fontSize float32) (width, height float32)

MeasureScreenText estimates single-line text width and height in virtual points for screen layout and overflow checks. Full-width CJK and East Asian glyphs measure at 1.0× fontSize, spaces at 0.25× fontSize, and other glyphs at 0.5× fontSize. When fontSize <= 0, DefaultScreenFontSize (12) is used.

func ParseBindingToken

func ParseBindingToken(token string) (input.Input, bool)

ParseBindingToken decodes a binding token from save.Settings.Bindings into an input.Input. Supported forms are "key:<name>", "keycode:<code>", "gamepad:<button>", "mouse:<button>", and bare key names (such as "space" or "Escape") treated as keyboard keys.

func ParseSettingsResolution

func ParseSettingsResolution(id string) (width, height int, ok bool)

ParseSettingsResolution parses a persisted resolution ID (such as "1280x720", "1280×720", "native", or "") into target dimensions in points. "native" and "" return (0, 0, true).

func SetSettingsReduceFlashes deprecated

func SetSettingsReduceFlashes(s *save.Settings, reduce bool)

SetSettingsReduceFlashes sets s.Accessibility.ReduceFlashes and clears any legacy s.Custom["reduce_flashes"] entry.

Deprecated: Set save.AccessibilitySettings.ReduceFlashes directly.

func SetSettingsResolution

func SetSettingsResolution(s *save.Settings, id string)

SetSettingsResolution writes id into s.Custom["resolution"].

func SettingsReduceFlashesFrom deprecated

func SettingsReduceFlashesFrom(s save.Settings) bool

SettingsReduceFlashesFrom reports whether flash reduction is enabled in s, reading s.Accessibility.ReduceFlashes and falling back to legacy s.Custom["reduce_flashes"].

Deprecated: Read save.AccessibilitySettings.ReduceFlashes directly.

func SettingsResolutionFrom

func SettingsResolutionFrom(s save.Settings) string

SettingsResolutionFrom reads the persisted resolution ID from s.Custom["resolution"], or "" if unset.

func ValidateScreen

func ValidateScreen(doc *ScreenDoc) error

ValidateScreen validates doc against the version 1 *.screen.yaml schema and invariants.

Types

type Align

type Align uint8

Align controls cross-axis placement in VBox and HBox, and child placement inside Panel.

const (
	// AlignDefault inherits the container's Align, or stretches when unset on a container.
	AlignDefault Align = iota
	// AlignStretch expands the child to fill the available cross-axis size unless it sets a fixed size.
	AlignStretch
	// AlignStart aligns the child to the start (left in VBox, top in HBox).
	AlignStart
	// AlignCenter centers the child along the cross axis.
	AlignCenter
	// AlignEnd aligns the child to the end (right in VBox, bottom in HBox).
	AlignEnd
)

type AnchorOverlay

type AnchorOverlay struct {
	// TestID optionally sets the TestID on the overlay container view.
	TestID string
	// contains filtered or unexported fields
}

AnchorOverlay renders native NSGo views anchored to 2D world positions inside a non-blocking overlay (PointerEventsNone on the overlay container, PointerEventsOn on each anchored view). Call Sync(proj) each frame to update screen coordinates in the same commit and automatically hide off-screen anchors.

func NewAnchorOverlay

func NewAnchorOverlay(cx *core.Scope) *AnchorOverlay

NewAnchorOverlay creates a signal-driven AnchorOverlay bound to cx.

func (*AnchorOverlay) Add

func (o *AnchorOverlay) Add(anchor *WorldAnchor)

Add registers or replaces anchor by its ID. If Sync has already been called, the new anchor is immediately projected with the last WorldProjection.

func (*AnchorOverlay) Get

func (o *AnchorOverlay) Get(id string) *WorldAnchor

Get returns the registered WorldAnchor with id, or nil if not found.

func (*AnchorOverlay) Remove

func (o *AnchorOverlay) Remove(id string) bool

Remove deletes the anchor with id from the overlay. Returns true if it existed.

func (*AnchorOverlay) ScreenPosition

func (o *AnchorOverlay) ScreenPosition(id string) (core.Point, bool)

ScreenPosition returns the last synced screen position (including OffsetX/OffsetY) and on-screen visibility for id.

func (*AnchorOverlay) SetVisible

func (o *AnchorOverlay) SetVisible(id string, visible bool) bool

SetVisible updates an anchor's logical visibility flag. Call Sync to apply.

func (*AnchorOverlay) SetWorldPosition

func (o *AnchorOverlay) SetWorldPosition(id string, worldX, worldY float32) bool

SetWorldPosition updates an anchor's world coordinates. Call Sync to project and commit updated screen positions.

func (*AnchorOverlay) Sync

func (o *AnchorOverlay) Sync(proj WorldProjection)

Sync projects all registered anchors through proj and atomically updates their screen positions and visibility signals in a single batch so anchored views stay aligned within the same frame and off-screen anchors are hidden immediately.

func (*AnchorOverlay) View

func (o *AnchorOverlay) View(_ *core.Scope) core.View

View returns the non-blocking absolute overlay core.View rendering all currently visible world anchors. The container uses PointerEventsNone so clicks pass through to the game canvas underneath, while each anchored wrapper re-enables interaction with PointerEventsOn.

type AnchoredItem

type AnchoredItem struct {
	ID          string
	Widget      Widget
	Anchor      ScreenAnchor
	Offset      ScreenOffsetDoc
	SafeArea    bool
	SizeMode    SizeMode
	FixedWidth  float32
	FixedHeight float32
	// PassThrough marks an unsized container whose children anchor directly against the parent's full bounds and safe area.
	PassThrough bool
}

AnchoredItem pairs a child Widget with its anchor, offset, safe-area inset preference, and sizing mode inside a ScreenCanvas.

type BuiltScreen

type BuiltScreen struct {
	// Root is the interactive gameui.Root configured with the screen's Viewport and theme.
	Root *Root
	// Navigator is a SpatialNavigator attached to Root with explicit focus-order overrides wired.
	Navigator *SpatialNavigator
	// Doc is a clone of the ScreenDoc this screen was built from.
	Doc *ScreenDoc
	// Canvas is the root ScreenCanvas child of Root.
	Canvas *ScreenCanvas
	// Nodes maps every node ID in the screen to its built Widget.
	Nodes map[string]Widget
	// FocusOrder lists focusable widgets that declared an explicit focusOrder, sorted ascending.
	FocusOrder []Widget
	// contains filtered or unexported fields
}

BuiltScreen is the runtime UI tree constructed from a *.screen.yaml document.

func BuildScreen

func BuildScreen(doc *ScreenDoc, opts ScreenBuildOptions) (*BuiltScreen, error)

BuildScreen constructs a runtime BuiltScreen (including a configured gameui.Root, Viewport, safe-area anchoring, localized text, device-class visibility, and focus-order navigation) from doc.

func (*BuiltScreen) ApplyCatalog

func (s *BuiltScreen) ApplyCatalog(cat *l10n.Catalog, locale string)

ApplyCatalog refreshes all localized text nodes from cat for locale (or cat's fallback locale when locale is empty).

func (*BuiltScreen) Draw

func (s *BuiltScreen) Draw(d *core.Drawing, bounds core.Bounds)

Draw delegates to s.Root.Draw(d, bounds).

func (*BuiltScreen) Layout

func (s *BuiltScreen) Layout(bounds core.Bounds)

Layout delegates to s.Root.Layout(bounds).

func (*BuiltScreen) SetDeviceClass

func (s *BuiltScreen) SetDeviceClass(class DeviceClass)

SetDeviceClass updates conditional visibility for all nodes carrying deviceClasses restrictions. Passing an empty DeviceClass makes all non-disjoint nodes visible.

func (*BuiltScreen) SetSafeArea

func (s *BuiltScreen) SetSafeArea(insets core.Edges)

SetSafeArea updates the safe-area insets used by subsequent Layout and Draw calls.

func (*BuiltScreen) SetTextLookup

func (s *BuiltScreen) SetTextLookup(fn func(key string) string)

SetTextLookup refreshes all localized text nodes using fn (or the raw textKey when fn is nil).

func (*BuiltScreen) Widget

func (s *BuiltScreen) Widget(id string) Widget

Widget returns the built Widget with id, or nil if no node has that ID.

type Button

type Button struct {
	Text           string
	OnClick        func()
	Disabled       bool
	Font           core.Font
	TextColor      core.Color
	Background     core.Color
	CornerRadius   float32
	Padding        core.Edges
	FocusOrder     int
	TouchHitSize   float32
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

Button is a clickable and focusable action trigger.

func (*Button) Bounds

func (b *Button) Bounds() core.Bounds

Bounds returns the button's laid-out rectangle.

func (*Button) HitBounds

func (b *Button) HitBounds() core.Bounds

HitBounds returns the button's interactive hit area, expanded to TouchHitSize when larger than Bounds.

type ColorRect

type ColorRect struct {
	Color        core.Color
	CornerRadius float32
	Width        float32
	Height       float32
	MinWidth     float32
	MinHeight    float32
	Flex         float32
	Align        Align
	Hidden       bool
	// contains filtered or unexported fields
}

ColorRect draws a solid or translucent filled rectangle (such as a modal backdrop or HUD plate).

func (*ColorRect) Bounds

func (c *ColorRect) Bounds() core.Bounds

Bounds returns the rectangle's laid-out bounds.

type Container

type Container interface {
	Widget
	// ChildWidgets returns the container's direct children in layout order.
	ChildWidgets() []Widget
}

Container is a Widget that lays out child widgets. Panel, VBox, and HBox implement Container.

type DeviceClass

type DeviceClass string

DeviceClass identifies a target device form factor for conditional visibility and reference layout checks.

const (
	DevicePhone     DeviceClass = "phone"
	DeviceTablet    DeviceClass = "tablet"
	DeviceDesktop   DeviceClass = "desktop"
	DeviceUltrawide DeviceClass = "ultrawide"
)

type DeviceProfile

type DeviceProfile struct {
	// ID is the machine identifier (for example "phone", "tablet", "desktop", "ultrawide").
	ID string
	// Name is the human-readable profile name (for example "Phone 19.5:9 (notch)").
	Name string
	// Class is the device class matched against ScreenNodeDoc.DeviceClasses.
	Class DeviceClass
	// Width and Height are the virtual canvas dimensions in points at this aspect ratio.
	Width  float32
	Height float32
	// SafeArea specifies the notch, rounded-corner, and home-indicator insets in virtual points.
	SafeArea core.Edges
	// Touch reports whether this device uses touch input (and enforces minimum touch target size).
	Touch bool
}

DeviceProfile describes a reference display size, safe-area insets, and device class used to preview and validate screens.

func ReferenceDevices

func ReferenceDevices() []DeviceProfile

ReferenceDevices returns the four standard reference profiles for a 640×360 design canvas: Phone 19.5:9 with a notch (780×360), Tablet 4:3 (640×480), Desktop 16:9 (640×360), and Ultrawide 21:9 (840×360).

func ReferenceDevicesFor

func ReferenceDevicesFor(designW, designH float32) []DeviceProfile

ReferenceDevicesFor returns the four standard reference profiles scaled to match a screen's design size: Phone 19.5:9 with a notch, Tablet 4:3, Desktop 16:9, and Ultrawide 21:9.

type FillMode

type FillMode uint8

FillMode picks how an ImageProgress reveals its progress image as the value grows.

const (
	// FillLeftToRight reveals the progress image from the left edge to the right (the default).
	FillLeftToRight FillMode = iota
	// FillRightToLeft reveals the progress image from the right edge to the left.
	FillRightToLeft
	// FillTopToBottom reveals the progress image from the top edge to the bottom.
	FillTopToBottom
	// FillBottomToTop reveals the progress image from the bottom edge to the top.
	FillBottomToTop
	// FillCenterHorizontal reveals the progress image from the horizontal center outward to both sides.
	FillCenterHorizontal
	// FillCenterVertical reveals the progress image from the vertical center outward to both edges.
	FillCenterVertical
	// FillClockwise reveals the progress image along a clockwise pie sweep from StartAngle.
	FillClockwise
	// FillCounterClockwise reveals the progress image along a counter-clockwise pie sweep from StartAngle.
	FillCounterClockwise
)

func ParseFillMode

func ParseFillMode(s string) (FillMode, bool)

ParseFillMode maps a screen-file fill name (such as "clockwise") to its FillMode, reporting whether s was recognized.

func (FillMode) String

func (m FillMode) String() string

String returns the screen-file name of m (such as "clockwise"), or "left_to_right" for an unknown mode.

type FocusManager

type FocusManager = SpatialNavigator

FocusManager is an alias for SpatialNavigator.

type FocusRingStyle

type FocusRingStyle struct {
	// Color overrides Theme.FocusedBorder when non-zero. Set core.Transparent to disable the default stroke.
	Color core.Color
	// Width overrides Theme.FocusWidth when > 0.
	Width float32
	// Outset expands the ring outward from the widget bounds by Outset points (negative insets it).
	Outset float32
	// CornerRadius overrides the corner radius (0 uses widget/theme default; < 0 uses square corners).
	CornerRadius float32
	// Dash sets an optional line dash pattern for the focus ring stroke.
	Dash []float32
	// Draw replaces the default stroke when non-nil, running inside Save/Restore.
	Draw func(d *core.Drawing, bounds core.Bounds, theme *Theme)
}

FocusRingStyle customizes the focus indicator drawn around the currently focused widget.

type FrameDrawer

type FrameDrawer func(d *core.Drawing, bounds core.Bounds, state WidgetState)

FrameDrawer draws a stylized background frame (such as a nine-slice sprite or custom skin) for a widget in its current interaction state.

func NineSliceStateFrame

func NineSliceStateFrame(normal, hover, pressed, disabled *NineSlice) FrameDrawer

NineSliceStateFrame returns a state-aware FrameDrawer that selects the matching NineSlice for Disabled, Pressed, Hovered, or Normal state, falling back to normal when a state slice is nil.

type HBox

type HBox struct {
	Children       []Widget
	Spacing        float32
	Padding        core.Edges
	Align          Align
	Justify        Justify
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	// contains filtered or unexported fields
}

HBox arranges Children horizontally from left to right with Spacing and Padding.

func (*HBox) Bounds

func (b *HBox) Bounds() core.Bounds

Bounds returns the HBox's laid-out rectangle.

func (*HBox) ChildWidgets

func (b *HBox) ChildWidgets() []Widget

ChildWidgets returns the HBox's direct children.

type ImageProgress

type ImageProgress struct {
	Value      float32
	Min        float32
	Max        float32
	Under      *NineSlice
	Progress   *NineSlice
	Over       *NineSlice
	Fill       FillMode
	StartAngle float32 // degrees, 0 = right, positive clockwise; radial fills only
	Span       float32 // degrees, 0 defaults to 360; radial fills only
	FillColor  core.Color
	TrackColor core.Color
	Width      float32
	Height     float32
	MinWidth   float32
	MinHeight  float32
	Flex       float32
	Align      Align
	Hidden     bool
	// contains filtered or unexported fields
}

ImageProgress displays a read-only progress meter in [Min, Max] (or [0, 1] when both Min and Max are 0) built from up to three layered images: Under drawn in full first, Progress revealed by the value along Fill, and Over drawn in full last (such as an ornate frame over a boss bar).

Each layer is a NineSlice: a plain image when its insets are zero, or a nine-patch that keeps its cap sizes when the widget is wider or taller than the source. Linear fills clip the progress layer to the revealed rectangle, so a nine-slice progress image keeps its caps at any value; radial fills (FillClockwise and FillCounterClockwise) clip it to a pie from StartAngle degrees (0 points right, positive is clockwise) sweeping Span degrees (0 defaults to 360). When a layer is nil the widget falls back to a flat fill: TrackColor (or Theme.Track) for Under and FillColor (or Theme.Accent) for Progress.

func (*ImageProgress) Bounds

func (p *ImageProgress) Bounds() core.Bounds

Bounds returns the image progress's laid-out rectangle.

func (*ImageProgress) Fraction

func (p *ImageProgress) Fraction() float32

Fraction returns Value normalized into [0, 1].

type Justify

type Justify uint8

Justify controls main-axis distribution in VBox and HBox when extra space remains and no child has Flex > 0.

const (
	// JustifyStart packs children at the start of the main axis.
	JustifyStart Justify = iota
	// JustifyCenter centers children as a group along the main axis.
	JustifyCenter
	// JustifyEnd packs children at the end of the main axis.
	JustifyEnd
	// JustifySpaceBetween spreads remaining space evenly between adjacent children.
	JustifySpaceBetween
)

type Label

type Label struct {
	Text           string
	Color          core.Color
	Background     core.Color
	CornerRadius   float32
	Padding        core.Edges
	Font           core.Font
	TextAlign      core.TextAlign
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

Label displays non-interactive text. Focus navigation skips labels automatically.

func (*Label) Bounds

func (l *Label) Bounds() core.Bounds

Bounds returns the label's laid-out rectangle.

type List

type List struct {
	Items          []string
	Selected       int
	ItemHeight     float32
	Spacing        float32
	OnSelect       func(index int, item string)
	Disabled       bool
	Font           core.Font
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

List is a focusable vertical list of selectable items supporting pointer and keyboard/gamepad selection.

func (*List) Bounds

func (l *List) Bounds() core.Bounds

Bounds returns the list's laid-out rectangle.

func (*List) ItemAt

func (l *List) ItemAt(p core.Point) int

ItemAt returns the 0-based index of the item containing p, or -1 if none.

func (*List) ItemBounds

func (l *List) ItemBounds(index int) core.Bounds

ItemBounds returns the laid-out rectangle for item at index, or zero Bounds if out of range.

func (*List) Select

func (l *List) Select(index int) bool

Select updates Selected to index (clamped into [0, len(Items)-1]) and invokes OnSelect. Returns false when the list is disabled or empty.

type NavAction uint8

NavAction identifies a logical UI navigation action from keyboard, gamepad, or virtual controls.

const (
	// NavNone is the zero value representing no action.
	NavNone NavAction = iota
	// NavUp moves focus upward.
	NavUp
	// NavDown moves focus downward.
	NavDown
	// NavLeft moves focus left (or decrements a focused Slider when SliderSteps is enabled).
	NavLeft
	// NavRight moves focus right (or increments a focused Slider when SliderSteps is enabled).
	NavRight
	// NavConfirm activates the currently focused widget and invokes OnConfirm.
	NavConfirm
	// NavBack invokes OnBack (e.g. closing a submenu or canceling an action).
	NavBack
)
func (a NavAction) String() string

String returns a human-readable name for a.

type NavOverrides struct {
	Up    Widget
	Down  Widget
	Left  Widget
	Right Widget
}

NavOverrides specifies explicit per-widget directional neighbors that take precedence over automatic 2D spatial lookup.

func (o NavOverrides) For(dir NavAction) Widget

For returns the explicit neighbor configured for dir, or nil if unset or non-directional.

type NineSlice

type NineSlice struct {
	Image  core.ImageSource
	Src    core.Bounds
	Left   float32
	Top    float32
	Right  float32
	Bottom float32
}

NineSlice describes a 9-patch sprite frame with fixed corner margins (Left, Top, Right, Bottom) inside Src of Image. Corners stay unstretched while edges and center scale to fill destination bounds.

func (NineSlice) Draw

func (ns NineSlice) Draw(d *core.Drawing, dst core.Bounds)

Draw renders the 9-patch image stretched into dst. Corner insets clamp proportionally if dst is smaller than Left+Right or Top+Bottom.

func (NineSlice) FrameDrawer

func (ns NineSlice) FrameDrawer() FrameDrawer

FrameDrawer adapts a single NineSlice into a FrameDrawer callback.

type Panel

type Panel struct {
	Child          Widget
	Padding        core.Edges
	Align          Align
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	Background     core.Color
	Border         core.Color
	CornerRadius   float32 // 0 uses Theme.CornerRadius; < 0 uses square corners.
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	// contains filtered or unexported fields
}

Panel frames a single optional Child with padding, background fill, and border.

func (*Panel) Bounds

func (p *Panel) Bounds() core.Bounds

Bounds returns the panel's laid-out rectangle.

func (*Panel) ChildWidgets

func (p *Panel) ChildWidgets() []Widget

ChildWidgets returns the panel's child if non-nil.

type ProgressBar

type ProgressBar struct {
	Value          float32
	Min            float32
	Max            float32
	Label          string
	FillColor      core.Color
	TrackColor     core.Color
	Font           core.Font
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

ProgressBar displays a read-only progress meter in [Min, Max] (or [0, 1] when both Min and Max are 0).

Example

A ProgressBar shows how far a value is between Min and Max, such as a loading screen's progress.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
)

func main() {
	bar := &gameui.ProgressBar{Min: 0, Max: 200, Value: 50}
	fmt.Println(bar.Fraction())
}
Output:
0.25

func (*ProgressBar) Bounds

func (p *ProgressBar) Bounds() core.Bounds

Bounds returns the progress bar's laid-out rectangle.

func (*ProgressBar) Fraction

func (p *ProgressBar) Fraction() float32

Fraction returns Value normalized into [0, 1].

type Root

type Root struct {
	// Child is the root widget of the UI tree (typically a Panel, VBox, or HBox).
	Child Widget
	// Theme styles all widgets under this Root; nil uses DefaultTheme.
	Theme *Theme
	// Viewport optionally maps a fixed virtual resolution onto the physical window bounds,
	// applying scaling and letterboxing in Draw and mapping window pointer/touch input into virtual coordinates.
	Viewport *Viewport
	// FocusRing optionally overrides the focus ring style drawn around the focused widget.
	FocusRing *FocusRingStyle
	// contains filtered or unexported fields
}

Root manages layout, focus navigation, pointer/touch interaction, and rendering for a game UI widget tree.

Example

A Root lays out a widget tree, moves focus between the focusable widgets and activates the focused one, as a pause menu driven by a gamepad does.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	volume := &gameui.Slider{Label: "Volume", Min: 0, Max: 10, Value: 5, Step: 1, Height: 40}
	resume := &gameui.Button{Text: "Resume", Height: 40, OnClick: func() { fmt.Println("resume clicked") }}
	menu := &gameui.VBox{
		Spacing: 10,
		Padding: core.All(20),
		Children: []gameui.Widget{
			&gameui.Label{Text: "Paused", Height: 30},
			resume,
			volume,
		},
	}
	root := gameui.NewRoot(menu)
	root.Layout(core.Bounds{Size: core.Size{Width: 320, Height: 240}})
	fmt.Println(resume.Bounds().Origin, volume.Bounds().Origin)

	root.FocusNext()
	fmt.Println(root.Focused() == resume)
	root.Activate()
	root.FocusNext()
	root.Adjust(1)
	fmt.Println(volume.Value, volume.Fraction())
}
Output:
{20 60} {20 110}
true
resume clicked
6 0.6

func NewRoot

func NewRoot(child Widget) *Root

NewRoot returns a Root wrapping child with the default theme.

func (*Root) Activate

func (r *Root) Activate() bool

Activate triggers the currently focused widget (clicks a Button or flips a Toggle).

func (*Root) Adjust

func (r *Root) Adjust(delta float32) bool

Adjust steps the currently focused adjustable widget by delta steps (e.g. -1 or +1). For a Slider, Value moves by delta * step within [Min, Max]. For a Toggle, delta > 0 checks it and delta < 0 unchecks it. For a List, Selected steps by delta clamped to the available items.

func (*Root) Bounds

func (r *Root) Bounds() core.Bounds

Bounds returns the bounds from the last Layout or Draw call.

func (*Root) ClearFocus

func (r *Root) ClearFocus()

ClearFocus removes keyboard/gamepad focus from the active widget.

func (*Root) Draw

func (r *Root) Draw(d *core.Drawing, bounds core.Bounds)

Draw lays out the tree into bounds and draws every visible widget into d. When Viewport is set, Draw renders letterbox bars and transforms d into the virtual resolution. Caller drawing state (transform, colors, stroke settings, alpha, text align/baseline, and current path) is preserved.

func (*Root) DrawWithViewport

func (r *Root) DrawWithViewport(d *core.Drawing, vp Viewport)

DrawWithViewport renders the UI tree using vp without permanently replacing r.Viewport.

func (*Root) FocusIndex

func (r *Root) FocusIndex() int

FocusIndex returns the index of the focused widget in the current list of enabled, visible focusable widgets, or -1 if none is focused.

func (*Root) FocusNext

func (r *Root) FocusNext() bool

FocusNext moves focus to the next enabled, focusable widget, wrapping from the end to the beginning.

func (*Root) FocusPrev

func (r *Root) FocusPrev() bool

FocusPrev moves focus to the previous enabled, focusable widget, wrapping from the beginning to the end.

func (*Root) Focused

func (r *Root) Focused() Widget

Focused returns the currently focused widget, or nil if none is focused.

func (*Root) HitTest

func (r *Root) HitTest(p core.Point) Widget

HitTest returns the topmost enabled, focusable widget containing p, or nil. When Viewport is set, p is mapped from window coordinates into virtual coordinates and points inside letterbox bars return nil.

func (*Root) Hovered

func (r *Root) Hovered() Widget

Hovered returns the currently hovered interactive widget, or nil.

func (*Root) Layout

func (r *Root) Layout(bounds core.Bounds)

Layout computes exact rectangles for every widget in the tree inside bounds and refreshes the focusable widget list. When Viewport is set, bounds specifies the physical window rectangle and the widget tree is laid out in virtual coordinates.

func (*Root) MoveFocus

func (r *Root) MoveFocus(dx, dy int) bool

MoveFocus moves focus geometrically in direction (dx, dy) (for arrow keys and gamepad D-pad/stick), checking explicit per-widget NavOverrides first, wrapping along the axis when reaching an edge, and falling back to linear order if layout has not run.

func (*Root) OnKeyDown

func (r *Root) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown handles keyboard navigation, activation, and slider adjustment. Returns true if the event was consumed by the UI.

func (*Root) OnPointerDown

func (r *Root) OnPointerDown(p core.Point) bool

OnPointerDown focuses and presses the interactive widget under p, beginning a drag if it is a Slider. Returns true if an interactive widget was hit.

func (*Root) OnPointerMove

func (r *Root) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state and smoothly drags any active Slider. Returns true if the pointer is over an interactive widget or dragging a Slider.

func (*Root) OnPointerUp

func (r *Root) OnPointerUp(p core.Point) bool

OnPointerUp finishes any active press or Slider drag, activating a Button, Toggle, or List item when released inside it. Returns true if a press or drag was handled.

func (*Root) OnPress

func (r *Root) OnPress(ev core.PressEvent) bool

OnPress handles a core.Canvas PressEvent directly (tapping/clicking a Button, Toggle, Slider, or List, or activating the focused widget on keyboard press).

func (*Root) Pressed

func (r *Root) Pressed() Widget

Pressed returns the currently pressed interactive widget, or nil.

func (*Root) SetFocus

func (r *Root) SetFocus(w Widget) bool

SetFocus focuses w if it is visible and focusable in this tree.

func (*Root) SetFocusIndex

func (r *Root) SetFocusIndex(index int) bool

SetFocusIndex focuses the focusable widget at index, or clears focus when index < 0.

func (*Root) StateOf

func (r *Root) StateOf(w Widget) WidgetState

StateOf returns the current hover, pressed, focused, and disabled state of w.

type ScaleMode

type ScaleMode uint8

ScaleMode controls how a Viewport maps a virtual resolution into a physical window size.

const (
	// ScaleFit uniformly scales the virtual canvas to fit inside the window, adding letterbox or pillarbox bars as needed.
	ScaleFit ScaleMode = iota
	// ScaleFill uniformly scales the virtual canvas to cover the entire window, cropping any overflow symmetrically.
	ScaleFill
	// ScaleStretch scales X and Y independently to fill the window without preserving aspect ratio.
	ScaleStretch
	// ScaleInteger uniformly scales by the largest integer factor >= 1 that fits inside the window,
	// falling back to ScaleFit when the window is smaller than the virtual resolution.
	ScaleInteger

	// ScaleLetterbox is an alias for ScaleFit.
	ScaleLetterbox = ScaleFit
	// IntegerScale is an alias for ScaleInteger.
	IntegerScale = ScaleInteger
)

type ScreenAnchor

type ScreenAnchor string

ScreenAnchor positions a node against one of nine reference points or fills its parent bounds.

const (
	AnchorTopLeft      ScreenAnchor = "top_left"
	AnchorTopCenter    ScreenAnchor = "top_center"
	AnchorTopRight     ScreenAnchor = "top_right"
	AnchorCenterLeft   ScreenAnchor = "center_left"
	AnchorCenter       ScreenAnchor = "center"
	AnchorCenterRight  ScreenAnchor = "center_right"
	AnchorBottomLeft   ScreenAnchor = "bottom_left"
	AnchorBottomCenter ScreenAnchor = "bottom_center"
	AnchorBottomRight  ScreenAnchor = "bottom_right"
	AnchorFill         ScreenAnchor = "fill"
)

type ScreenBuildOptions

type ScreenBuildOptions struct {
	// SafeArea specifies the display safe-area insets in virtual points (for notches, rounded corners, and home indicators).
	SafeArea core.Edges
	// DeviceClass selects which conditional nodes (ScreenNodeDoc.DeviceClasses) are visible.
	// When empty, no device-class filtering is applied and all nodes remain visible.
	DeviceClass DeviceClass
	// ViewportWidth and ViewportHeight optionally override the Viewport's virtual dimensions (for example 780×360 for a 19.5:9 phone).
	// When zero, the document's DesignWidth and DesignHeight are used.
	ViewportWidth  float32
	ViewportHeight float32
	// Text resolves localization textKey values. When nil and Catalog is set, Catalog.T(Locale, key) is used; when both are nil, the key itself is displayed.
	Text func(key string) string
	// Catalog optionally resolves textKey values when Text is nil.
	Catalog *l10n.Catalog
	// Locale optionally selects the locale in Catalog (empty uses Catalog's active locale).
	Locale string
	// Theme optionally overrides the built Root's theme; nil uses DefaultTheme tuned for DefaultScreenFontSize and screen text measurement.
	Theme *Theme
	// OnClick optionally binds click callbacks by node ID for button and touch_button nodes.
	OnClick map[string]func()
	// Sprites optionally resolves a node's Sprite path (and optional SpriteFrame) into a core.ImageSource and source rectangle.
	Sprites func(path, frame string) (core.ImageSource, core.Bounds, bool)
}

ScreenBuildOptions configures BuildScreen.

type ScreenCanvas

type ScreenCanvas struct {
	SafeArea     core.Edges
	Items        []AnchoredItem
	Background   core.Color
	CornerRadius float32
	Width        float32
	Height       float32
	MinWidth     float32
	MinHeight    float32
	Flex         float32
	Align        Align
	Hidden       bool
	// contains filtered or unexported fields
}

ScreenCanvas lays out children using nine-point anchors or fill, optional safe-area insets, and offsets. It implements Container and Widget.

func (*ScreenCanvas) Bounds

func (c *ScreenCanvas) Bounds() core.Bounds

Bounds returns the canvas's laid-out rectangle.

func (*ScreenCanvas) ChildWidgets

func (c *ScreenCanvas) ChildWidgets() []Widget

ChildWidgets returns the direct child widgets in render order.

type ScreenCheckOptions

type ScreenCheckOptions struct {
	// Locales maps normalized locale tags to their message string maps (for example from l10n.StringTable.Strings).
	Locales map[string]map[string]string
	// Plurals optionally maps normalized locale tags to their CLDR plural entries (for example from l10n.StringTable.Plurals).
	Plurals map[string]map[string]l10n.PluralForms
	// Devices optionally overrides the reference device profiles; empty uses ReferenceDevicesFor(doc.DesignWidth, doc.DesignHeight).
	Devices []DeviceProfile
	// Theme optionally overrides the theme used for default text/button colors and text measurement.
	Theme *Theme
	// FallbackBackdrop is the backdrop color used to composite translucent fills when no opaque ancestor fill exists (defaults to #101216).
	FallbackBackdrop core.Color
}

ScreenCheckOptions configures CheckScreen.

type ScreenDoc

type ScreenDoc struct {
	// Version is the schema version; it must equal ScreenFormatVersion (1).
	Version int `yaml:"version" schema:"required"`
	// UID is an optional stable ID for the screen file, kept across renames by game index and game mv.
	UID string `yaml:"uid,omitempty"`
	// Name is the screen's human-readable name (for example "hud" or "pause").
	Name string `yaml:"name,omitempty"`
	// DesignWidth is the authored reference canvas width in virtual points (for example 640).
	DesignWidth float32 `yaml:"designWidth" schema:"required,exclusiveMinimum=0"`
	// DesignHeight is the authored reference canvas height in virtual points (for example 360).
	DesignHeight float32 `yaml:"designHeight" schema:"required,exclusiveMinimum=0"`
	// ScaleMode controls how the screen scales to different window sizes: fit (default), fill, stretch, or integer.
	ScaleMode ScreenScaleMode `yaml:"scaleMode,omitempty" schema:"enum=fit|fill|stretch|integer"`
	// Nodes are the top-level UI nodes of the screen, rendered in slice order.
	Nodes []ScreenNodeDoc `yaml:"nodes,omitempty"`
}

ScreenDoc is the root of a versioned *.screen.yaml HUD or menu screen definition.

func LoadScreenFS

func LoadScreenFS(fsys fs.FS, name string) (*ScreenDoc, error)

LoadScreenFS reads and parses a *.screen.yaml file from fsys, attaching name to any returned error.

func ParseScreen

func ParseScreen(data []byte) (*ScreenDoc, error)

ParseScreen decodes and validates a versioned *.screen.yaml document. Unknown fields, fields unsupported by a node's type, disjoint nested deviceClasses, trailing YAML documents, YAML anchors/aliases/merge keys, missing or unsupported versions, duplicate node IDs, duplicate focus orders, invalid enums or colors, and non-finite numbers are refused.

Errors are *loaderr.Error values carrying line, column, field path, and fix guidance; callers that read from a file can attach the file path with loaderr.WithFile.

func (*ScreenDoc) Clone

func (doc *ScreenDoc) Clone() *ScreenDoc

Clone returns a deep copy of doc.

func (*ScreenDoc) EffectiveScaleMode

func (doc *ScreenDoc) EffectiveScaleMode() ScaleMode

EffectiveScaleMode maps doc.ScaleMode to a gameui.ScaleMode, defaulting to ScaleFit.

type ScreenIssue

type ScreenIssue struct {
	// Code classifies the issue.
	Code ScreenIssueCode
	// NodeID is the ScreenNodeDoc.ID at fault.
	NodeID string
	// NodePath holds the YAML path steps from the document root to the offending node or field (for example ["nodes", "3", "textKey"]).
	NodePath []string
	// Locale is the BCP-47 locale tag involved, when the issue is locale-specific.
	Locale string
	// Devices names the reference device profiles involved, when the issue is device-specific.
	Devices []string
	// Message describes the issue for diagnostics and UI panels.
	Message string
}

ScreenIssue is one problem CheckScreen finds in a ScreenDoc.

func CheckScreen

func CheckScreen(doc *ScreenDoc, opts ScreenCheckOptions) []ScreenIssue

CheckScreen checks doc against the HUD/menu screen quality rules:

  • touch areas under 44 pt on phones and tablets;
  • localized text overflowing its box at any reference device size (Phone 19.5:9 with notch, Tablet 4:3, Desktop 16:9, Ultrawide 21:9);
  • textKey entries missing from any project locale;
  • text under 4.5:1 WCAG contrast against its own fill.

type ScreenIssueCode

type ScreenIssueCode string

ScreenIssueCode identifies the category of a screen check diagnostic.

const (
	// IssueTouchAreaTooSmall flags a touch control whose hit area is below MinTouchTargetSize (44 pt) on phones or tablets.
	IssueTouchAreaTooSmall ScreenIssueCode = "touch_area_too_small"
	// IssueTextOverflow flags a text node whose localized string exceeds its laid-out box width at one or more reference sizes.
	IssueTextOverflow ScreenIssueCode = "text_overflow"
	// IssueMissingTextKey flags a textKey absent from a project locale table.
	IssueMissingTextKey ScreenIssueCode = "missing_text_key"
	// IssueLowContrast flags text whose contrast ratio against its fill is under 4.5:1.
	IssueLowContrast ScreenIssueCode = "low_contrast"
)

type ScreenNodeDoc

type ScreenNodeDoc struct {
	// ID uniquely identifies this node within the screen.
	ID string `yaml:"id" schema:"required,minLength=1"`
	// Type selects the widget or container kind.
	Type ScreenNodeType `` /* 129-byte string literal not displayed */
	// Anchor positions the node relative to the screen or safe area: one of the nine anchor points or fill.
	Anchor ScreenAnchor `` /* 143-byte string literal not displayed */
	// Offset shifts the node from its anchor in virtual points. For right and bottom anchors, positive values inset inward from that edge.
	Offset *ScreenOffsetDoc `yaml:"offset,omitempty"`
	// SafeArea keeps the node inside the display safe area (away from notches and home indicators). Nil defaults to true for non-fill anchors and false for fill.
	SafeArea *bool `yaml:"safeArea,omitempty"`
	// SizeMode selects whether width is fixed ("fixed", the default) or sizes to fit localized text ("fit_text") on label and button nodes.
	SizeMode SizeMode `yaml:"sizeMode,omitempty" schema:"enum=fixed|fit_text"`
	// Width is the node's fixed width in virtual points (0 uses intrinsic or container-determined width).
	Width float32 `yaml:"width,omitempty" schema:"minimum=0"`
	// Height is the node's fixed height in virtual points (0 uses intrinsic or container-determined height).
	Height float32 `yaml:"height,omitempty" schema:"minimum=0"`
	// Padding is the node's inner padding in virtual points (vbox, hbox, label, button).
	Padding *ScreenPaddingDoc `yaml:"padding,omitempty"`
	// Spacing is the gap between children of a vbox, hbox, or sprite_row in virtual points.
	Spacing float32 `yaml:"spacing,omitempty" schema:"minimum=0"`
	// TextKey names a localized string in the project's l10n tables (such as "hud.hint.lever") for label, button, and touch_button nodes. Screen files store localization keys rather than literal text.
	TextKey string `yaml:"textKey,omitempty"`
	// FocusOrder sets the explicit keyboard/gamepad focus traversal order (1-based; 0 means not explicitly ordered) on button and touch_button nodes.
	FocusOrder int `yaml:"focusOrder,omitempty" schema:"minimum=0"`
	// TouchHitSize is the touch target diameter in virtual points for touch_stick, touch_button, or touch-interactive buttons.
	TouchHitSize float32 `yaml:"touchHitSize,omitempty" schema:"minimum=0"`
	// DeviceClasses optionally restricts the node and its subtree to the listed device classes (for example [phone, tablet]). Empty shows on all devices; nested nodes must overlap their parent's allowed classes.
	DeviceClasses []DeviceClass `yaml:"deviceClasses,omitempty"`
	// Sprite is a project-relative path to a sprite image or atlas file (for example "art/ui/heart.png") for sprite_row nodes, followed by refs and game mv.
	Sprite string `yaml:"sprite,omitempty"`
	// SpriteFrame optionally names a frame inside a sprite atlas when Sprite points to an atlas JSON file on a sprite_row node.
	SpriteFrame string `yaml:"spriteFrame,omitempty"`
	// SpriteCount is the number of repeated icons in a sprite_row (defaults to 1 when Sprite is set).
	SpriteCount int `yaml:"spriteCount,omitempty" schema:"minimum=0"`
	// Under is a project-relative path to the image_progress background layer image, drawn in full first.
	Under string `yaml:"under,omitempty"`
	// Progress is a project-relative path to the image_progress fill layer image, revealed by the value along Fill.
	Progress string `yaml:"progress,omitempty"`
	// Over is a project-relative path to the image_progress foreground layer image, drawn in full last.
	Over string `yaml:"over,omitempty"`
	// Fill picks how an image_progress reveals its progress image: left_to_right (the default), right_to_left, top_to_bottom, bottom_to_top, center_h, center_v, clockwise, or counter_clockwise.
	Fill string `` /* 137-byte string literal not displayed */
	// StartAngle is the image_progress radial fill's starting angle in degrees (0 points right, positive is clockwise).
	StartAngle float32 `yaml:"startAngle,omitempty"`
	// Span is the image_progress radial fill's full sweep in degrees (0 defaults to 360).
	Span float32 `yaml:"span,omitempty" schema:"minimum=0,maximum=360"`
	// Min is the image_progress range's lower bound (defaults to 0).
	Min float32 `yaml:"min,omitempty"`
	// Max is the image_progress range's upper bound (defaults to 1 when both min and max are 0).
	Max float32 `yaml:"max,omitempty"`
	// Value is the image_progress node's initial value; game code updates the widget's Value at runtime.
	Value float32 `yaml:"value,omitempty"`
	// FontSize overrides the text font size in virtual points for label, button, and touch_button nodes.
	FontSize float32 `yaml:"fontSize,omitempty" schema:"minimum=0"`
	// TextColor is an optional CSS color string parsed with core.ParseColor for text (label, button, touch_button) or the thumbstick knob (touch_stick).
	TextColor string `yaml:"textColor,omitempty"`
	// Background is an optional CSS color string parsed with core.ParseColor for the node's fill (all node types except image_progress; icon fallback tint on sprite_row and ring base on touch_stick).
	Background string `yaml:"background,omitempty"`
	// CornerRadius is an optional corner radius in virtual points (vbox, hbox, container, label, button, color_rect).
	CornerRadius float32 `yaml:"cornerRadius,omitempty" schema:"minimum=0"`
	// Children are nested child nodes for container types (vbox, hbox, container).
	Children []ScreenNodeDoc `yaml:"children,omitempty"`
}

ScreenNodeDoc is one node in a *.screen.yaml tree.

func (*ScreenNodeDoc) EffectiveAnchor

func (n *ScreenNodeDoc) EffectiveAnchor() ScreenAnchor

EffectiveAnchor returns n.Anchor, defaulting to AnchorTopLeft when empty.

func (*ScreenNodeDoc) KeepInSafeArea

func (n *ScreenNodeDoc) KeepInSafeArea() bool

KeepInSafeArea reports whether the node stays inside the display safe area. When SafeArea is nil, non-fill anchors default to true and AnchorFill defaults to false.

type ScreenNodeType

type ScreenNodeType string

ScreenNodeType identifies the widget or container kind of a ScreenNodeDoc.

const (
	// NodeVBox stacks children vertically.
	NodeVBox ScreenNodeType = "vbox"
	// NodeHBox arranges children horizontally.
	NodeHBox ScreenNodeType = "hbox"
	// NodeLabel displays localized non-interactive text.
	NodeLabel ScreenNodeType = "label"
	// NodeButton displays a focusable, clickable button.
	NodeButton ScreenNodeType = "button"
	// NodeSpriteRow displays a horizontal row of repeated sprite icons (such as health hearts).
	NodeSpriteRow ScreenNodeType = "sprite_row"
	// NodeColorRect draws a filled rectangle (such as a modal dim backdrop or HUD plate).
	NodeColorRect ScreenNodeType = "color_rect"
	// NodeTouchStick displays an on-screen virtual thumbstick for touch devices.
	NodeTouchStick ScreenNodeType = "touch_stick"
	// NodeTouchButton displays an on-screen circular/rounded touch action button.
	NodeTouchButton ScreenNodeType = "touch_button"
	// NodeContainer groups child nodes with optional device-class filtering or anchored sub-bounds.
	NodeContainer ScreenNodeType = "container"
	// NodeImageProgress displays a read-only progress meter built from layered under/progress/over images with a directional or radial fill.
	NodeImageProgress ScreenNodeType = "image_progress"
)

func (ScreenNodeType) IsContainer

func (t ScreenNodeType) IsContainer() bool

IsContainer reports whether t can hold child nodes.

type ScreenOffsetDoc

type ScreenOffsetDoc struct {
	// X is the horizontal offset in virtual points.
	X float32 `yaml:"x,omitempty"`
	// Y is the vertical offset in virtual points.
	Y float32 `yaml:"y,omitempty"`
}

ScreenOffsetDoc is an offset from a node's anchor point in virtual points. For right and bottom anchors, positive X and Y values move inward away from that edge.

type ScreenPaddingDoc

type ScreenPaddingDoc struct {
	// Top is the top inner padding in virtual points.
	Top float32 `yaml:"top,omitempty" schema:"minimum=0"`
	// Right is the right inner padding in virtual points.
	Right float32 `yaml:"right,omitempty" schema:"minimum=0"`
	// Bottom is the bottom inner padding in virtual points.
	Bottom float32 `yaml:"bottom,omitempty" schema:"minimum=0"`
	// Left is the left inner padding in virtual points.
	Left float32 `yaml:"left,omitempty" schema:"minimum=0"`
}

ScreenPaddingDoc holds inner padding in virtual points.

func (*ScreenPaddingDoc) Edges

func (p *ScreenPaddingDoc) Edges() core.Edges

Edges converts p into core.Edges (returning zero edges when p is nil).

type ScreenScaleMode

type ScreenScaleMode string

ScreenScaleMode selects the Viewport scaling behavior for a screen file.

const (
	// ScreenScaleFit uniformly scales the design canvas to fit inside the window (default).
	ScreenScaleFit ScreenScaleMode = "fit"
	// ScreenScaleFill uniformly scales the design canvas to cover the window.
	ScreenScaleFill ScreenScaleMode = "fill"
	// ScreenScaleStretch scales X and Y independently to fill the window.
	ScreenScaleStretch ScreenScaleMode = "stretch"
	// ScreenScaleInteger uniformly scales by the largest integer factor >= 1 that fits.
	ScreenScaleInteger ScreenScaleMode = "integer"
)

type SettingsAction

type SettingsAction struct {
	// Name is the action key stored in save.Settings.Bindings (for example "jump", "left", "pause").
	Name string
	// Label is displayed in the Controls tab; defaults to Name when empty.
	Label string
	// Defaults lists default binding tokens (for example "key:space", "gamepad:south") restored on Reset.
	Defaults []string
	// AllowToggle reports whether the Controls tab offers a per-action Hold to Toggle assist switch for this action.
	AllowToggle bool
	// AllowMash reports whether the Controls tab offers a per-action Hold to Mash assist switch for this action.
	AllowMash bool
}

SettingsAction describes a rebindable input action shown in the Controls tab.

type SettingsAudioBus

type SettingsAudioBus struct {
	// Name is the key inside save.AudioSettings.Groups (for example "music", "sfx", "ui").
	Name string
	// Label is shown next to the slider; defaults to Name when empty.
	Label string
}

SettingsAudioBus describes an audio group slider shown in the Audio tab.

type SettingsLocale

type SettingsLocale struct {
	// Tag is the BCP-47 locale tag stored in save.Settings.Locale ("" selects the system default).
	Tag string
	// Label is displayed in the Language tab; defaults to Tag or SystemDefault.
	Label string
}

SettingsLocale describes a selectable language entry in the Language tab.

type SettingsMenu

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

SettingsMenu is a ready-to-use, gameui-based settings screen covering Audio, Video, Controls (rebinding), Language, and Accessibility, persisted via save.DefaultSettingsStore and operable with mouse, touch, keyboard, and gamepad alone.

Example

A SettingsMenu provides ready-to-use Audio, Video, Controls, Language, and Accessibility tabs driven by mouse, touch, keyboard, or gamepad alone.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
	"github.com/nsgo-dev/nsgo/gamepad"
)

func main() {
	menu := gameui.NewSettingsMenu(gameui.SettingsMenuConfig{})
	menu.Layout(core.Bounds{Size: core.Size{Width: 960, Height: 540}})

	// Switch to Video tab with RB and toggle Fullscreen with D-pad Right.
	menu.OnGamepadButton(gamepad.ButtonRB)
	menu.OnGamepadButton(gamepad.ButtonDPadRight)
	fmt.Println(menu.Tab(), menu.Settings().Display.Fullscreen)
}
Output:
video true

func NewSettingsMenu

func NewSettingsMenu(cfg SettingsMenuConfig) *SettingsMenu

NewSettingsMenu constructs a SettingsMenu wired to cfg and ready to draw and receive input.

func (*SettingsMenu) Apply

func (m *SettingsMenu) Apply() error

Apply validates the working settings and dispatches them to Targets, Video (for resolution), and OnApply.

func (*SettingsMenu) Back

func (m *SettingsMenu) Back()

Back cancels capture if active; otherwise invokes OnBack.

func (*SettingsMenu) BeginCapture

func (m *SettingsMenu) BeginCapture(actionName string) bool

BeginCapture enters control-rebinding capture mode for actionName.

func (*SettingsMenu) CancelCapture

func (m *SettingsMenu) CancelCapture()

CancelCapture exits control-rebinding capture mode without modifying bindings.

func (*SettingsMenu) CaptureBinding

func (m *SettingsMenu) CaptureBinding(token string) bool

CaptureBinding assigns token to the currently capturing action, replacing the existing binding of the same input device class (keyboard vs gamepad vs mouse) while keeping other classes intact.

func (*SettingsMenu) CapturingAction

func (m *SettingsMenu) CapturingAction() string

CapturingAction returns the action name currently awaiting a key or gamepad button press, or "".

func (*SettingsMenu) Dirty

func (m *SettingsMenu) Dirty() bool

Dirty reports whether the working settings have unsaved changes.

func (*SettingsMenu) Draw

func (m *SettingsMenu) Draw(d *core.Drawing, bounds core.Bounds)

Draw lays out and renders the settings menu into d within bounds.

func (*SettingsMenu) Err

func (m *SettingsMenu) Err() error

Err returns the last error produced by Load, Apply, or Save.

func (*SettingsMenu) FooterButtons

func (m *SettingsMenu) FooterButtons() (apply, saveBtn, reset, back *Button)

FooterButtons returns the Apply, Save, Reset, and Back buttons in order.

func (*SettingsMenu) HandleAction

func (m *SettingsMenu) HandleAction(action NavAction) bool

HandleAction dispatches a logical NavAction through the menu, supporting slider adjustment, toggle switching, cycle-option stepping on NavLeft/NavRight, and capture cancellation on NavBack.

func (*SettingsMenu) Layout

func (m *SettingsMenu) Layout(bounds core.Bounds)

Layout lays out the menu inside bounds.

func (*SettingsMenu) Navigator

func (m *SettingsMenu) Navigator() *SpatialNavigator

Navigator returns the menu's SpatialNavigator.

func (*SettingsMenu) NextTab

func (m *SettingsMenu) NextTab()

NextTab switches to the next settings tab, wrapping from Accessibility back to Audio.

func (*SettingsMenu) OnGamepadButton

func (m *SettingsMenu) OnGamepadButton(btn gamepad.Button) bool

OnGamepadButton processes a single gamepad button press (rising edge). While capturing a control rebind, any valid button is captured; otherwise D-pad, South (confirm), East (back), and LB/RB (previous/next tab) drive the menu.

func (*SettingsMenu) OnKeyDown

func (m *SettingsMenu) OnKeyDown(ev core.KeyEvent) bool

OnKeyDown handles keyboard navigation, slider/option stepping, and control rebinding capture.

func (*SettingsMenu) OnPointerDown

func (m *SettingsMenu) OnPointerDown(p core.Point) bool

OnPointerDown focuses and presses the control under p.

func (*SettingsMenu) OnPointerMove

func (m *SettingsMenu) OnPointerMove(p core.Point) bool

OnPointerMove updates hover state and drags any active slider.

func (*SettingsMenu) OnPointerUp

func (m *SettingsMenu) OnPointerUp(p core.Point) bool

OnPointerUp finishes any press or slider drag, activating controls released inside their bounds.

func (*SettingsMenu) OnPress

func (m *SettingsMenu) OnPress(ev core.PressEvent) bool

OnPress handles a completed core.PressEvent directly.

func (*SettingsMenu) OnTouch

func (m *SettingsMenu) OnTouch(ev core.TouchEvent) bool

OnTouch routes touch start, move, end, and cancel events to sliders, toggles, and buttons.

func (*SettingsMenu) PrevTab

func (m *SettingsMenu) PrevTab()

PrevTab switches to the previous settings tab, wrapping from Audio to Accessibility.

func (*SettingsMenu) Reset

func (m *SettingsMenu) Reset()

Reset restores all settings to their configured defaults and refreshes the UI.

func (*SettingsMenu) ResetControls

func (m *SettingsMenu) ResetControls()

ResetControls restores all configured actions' bindings and motor assists to their default values.

func (*SettingsMenu) Root

func (m *SettingsMenu) Root() *Root

Root returns the menu's underlying gameui Root.

func (*SettingsMenu) Save

func (m *SettingsMenu) Save() error

Save validates the working settings, persists them through Store (when configured), applies them to Targets/Video/OnApply, and invokes OnSave.

func (*SettingsMenu) SetSettings

func (m *SettingsMenu) SetSettings(s save.Settings)

SetSettings replaces the menu's working settings and refreshes all controls.

func (*SettingsMenu) SetTab

func (m *SettingsMenu) SetTab(tab SettingsTab)

SetTab switches the active settings tab, cancelling any in-progress control capture and updating focus and directional navigation cleanly.

func (*SettingsMenu) SetText

func (m *SettingsMenu) SetText(text SettingsText)

SetText updates the menu's user-visible strings (for example after changing locale).

func (*SettingsMenu) Settings

func (m *SettingsMenu) Settings() save.Settings

Settings returns a deep copy of the menu's current working player settings.

func (*SettingsMenu) StepActions

func (m *SettingsMenu) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions (such as from input.Actions.JustPressed) and dispatches them in deterministic order.

func (*SettingsMenu) StepGamepad

func (m *SettingsMenu) StepGamepad(pads []gamepad.Pad) bool

StepGamepad polls connected gamepads once per frame, driving navigation, tab switching, value adjustment, and control-rebinding capture on button and left-stick rising edges.

func (*SettingsMenu) SyncGamepad

func (m *SettingsMenu) SyncGamepad(pads []gamepad.Pad)

SyncGamepad records the currently held buttons and left-stick position on pads as the baseline without triggering any actions. Call it when opening the menu so buttons held to open the screen do not immediately fire inside it.

func (*SettingsMenu) Tab

func (m *SettingsMenu) Tab() SettingsTab

Tab returns the currently active SettingsTab.

func (*SettingsMenu) TabButton

func (m *SettingsMenu) TabButton(tab SettingsTab) *Button

TabButton returns the tab-bar Button for tab.

func (*SettingsMenu) TabControls

func (m *SettingsMenu) TabControls(tab SettingsTab) []Widget

TabControls returns the ordered focusable widgets inside tab.

type SettingsMenuConfig

type SettingsMenuConfig struct {
	// Store optionally loads initial player settings and persists changes when Save is called.
	Store *save.DefaultSettingsStore
	// Targets optionally receives validated settings via save.Apply when Apply or Save is called.
	Targets save.SettingsTargets
	// Video optionally receives the selected windowed resolution via ApplySettingsResolution whenever Apply or Save runs.
	Video *screen.Video
	// Env optionally supplies the platform environment so the Video tab hides controls that cannot apply on the current platform (hiding Window Mode where screen.CanFullScreen is false and hiding Resolution where screen.SupportsWindowResolution is false) and keeps Window Mode synchronized with Env.FullScreen. When nil, desktop capabilities are assumed unless HideResolution is set.
	Env *core.Env
	// Initial supplies starting settings when Store is nil (or if Store.Load fails).
	Initial *save.Settings
	// Defaults supplies baseline settings restored by Reset.
	Defaults *save.Settings

	// AudioBuses configures group volume sliders in the Audio tab (defaults to music, sfx, ui).
	AudioBuses []SettingsAudioBus
	// Resolutions configures selectable resolutions in the Video tab (defaults to Native, 960x540, 1280x720, 1920x1080).
	Resolutions []SettingsResolution
	// HideResolution omits the Resolution row from the Video tab even on desktop or when Env is nil.
	HideResolution bool
	// ShowVSync includes the VSync toggle in the Video tab. False by default because NSGo v0.3.4 does not yet expose swap-interval control; enable only when wiring save.DisplaySettings.VSync to a real backend control.
	ShowVSync bool
	// ScaleModes configures scale mode options in the Video tab (defaults to fit, fill, stretch, expand).
	ScaleModes []SettingsOptionItem
	// QualityPresets configures quality preset options in the Video tab (defaults to auto, low, medium, high).
	QualityPresets []SettingsOptionItem
	// FrameCaps configures selectable FPS caps in the Video tab; 0 means uncapped (defaults to 0, 30, 60, 120).
	FrameCaps []int
	// Actions configures rebindable input actions in the Controls tab.
	Actions []SettingsAction
	// Locales configures selectable languages in the Language tab.
	Locales []SettingsLocale
	// ColorBlindModes configures color-blind palette modes in the Accessibility tab.
	ColorBlindModes []SettingsOptionItem

	// Text customizes displayed labels; unset fields inherit DefaultSettingsText.
	Text SettingsText
	// Theme optionally overrides the Theme used by the menu's Root.
	// When nil, DefaultTheme is used and switches automatically to HighContrastTheme while Accessibility.HighContrast is true.
	Theme *Theme
	// Viewport optionally attaches virtual-resolution scaling to the menu's Root.
	Viewport *Viewport

	// AutoApply dispatches Targets and OnApply immediately whenever any control changes.
	AutoApply bool
	// AutoSave persists changes to Store immediately whenever any control changes.
	AutoSave bool

	// OnChange runs whenever any setting changes in the working copy.
	OnChange func(save.Settings)
	// OnApply runs when Apply or Save applies settings.
	OnApply func(save.Settings) error
	// OnSave runs after Save succeeds.
	OnSave func(save.Settings) error
	// OnReset runs after Reset restores defaults.
	OnReset func(save.Settings)
	// OnBack runs when Back or NavBack is triggered outside capture mode.
	OnBack func()
	// OnResolutionChange runs when the selected resolution changes.
	OnResolutionChange func(SettingsResolution)
}

SettingsMenuConfig configures a ready-to-use SettingsMenu. Every field is optional.

type SettingsOptionItem

type SettingsOptionItem struct {
	Value string
	Label string
}

SettingsOptionItem pairs a persisted setting value with a user-visible display label.

type SettingsResolution

type SettingsResolution struct {
	// ID is persisted in save.Settings.Custom["resolution"] (for example "native" or "1280x720").
	ID string
	// Label is displayed in the Video tab; defaults to ID when empty.
	Label string
	// Width and Height optionally carry the target dimensions in points/pixels (0 for native/auto).
	Width  int
	Height int
}

SettingsResolution describes a selectable resolution entry in the Video tab.

type SettingsTab

type SettingsTab uint8

SettingsTab identifies one of the five built-in sections of a SettingsMenu.

const (
	// SettingsTabAudio edits mute, master volume, audio bus volumes, mono audio, and left/right balance.
	SettingsTabAudio SettingsTab = iota
	// SettingsTabVideo edits window mode, resolution (on desktop), scale mode, integer scale, quality preset, frame cap, and (when enabled via ShowVSync) VSync.
	SettingsTabVideo
	// SettingsTabControls edits keyboard and gamepad action bindings with capture and reset.
	SettingsTabControls
	// SettingsTabLanguage selects the active locale.
	SettingsTabLanguage
	// SettingsTabAccessibility edits captions, SFX captions, text scale, high contrast, reduced motion, screen shake, flash reduction, color-blind mode, game speed, invincibility, auto-aim, and hold-to-toggle.
	SettingsTabAccessibility
)

func (SettingsTab) String

func (t SettingsTab) String() string

String returns the canonical lowercase name of tab.

type SettingsText

type SettingsText struct {
	Title string

	TabAudio         string
	TabVideo         string
	TabControls      string
	TabLanguage      string
	TabAccessibility string

	MuteAll       string
	MasterVolume  string
	MonoAudio     string
	MonoOn        string
	MonoOff       string
	Balance       string
	BalanceLeft   string
	BalanceCenter string
	BalanceRight  string

	WindowMode    string
	Windowed      string
	Fullscreen    string
	Resolution    string
	ScaleMode     string
	IntegerScale  string
	QualityPreset string
	VSync         string
	FrameCap      string
	Uncapped      string

	ControlsHint  string
	CapturePrompt string
	Unbound       string
	ResetControls string
	ActionToggle  string
	ActionMash    string
	MinPressTime  string
	AcceptDelay   string
	AssistOff     string

	LanguageHint  string
	SystemDefault string

	Subtitles     string
	SFXCaptions   string
	TextScale     string
	HighContrast  string
	ReduceMotion  string
	ScreenShake   string
	ReduceFlashes string
	ColorBlind    string
	GameSpeed     string
	Invincibility string
	AutoAim       string
	HoldToToggle  string

	Apply string
	Save  string
	Reset string
	Back  string

	SavedStatus   string
	AppliedStatus string
	ResetStatus   string
}

SettingsText holds every user-visible string displayed by SettingsMenu, so a game can localize it. Partial structs passed via SettingsMenuConfig.Text inherit unset fields from DefaultSettingsText.

func DefaultSettingsText

func DefaultSettingsText() SettingsText

DefaultSettingsText returns the English strings used by SettingsMenu.

type SizeMode

type SizeMode string

SizeMode controls whether a node uses a fixed width or sizes horizontally to fit localized text.

const (
	// SizeFixed keeps the node's declared Width (the default when omitted).
	SizeFixed SizeMode = "fixed"
	// SizeFitText expands or contracts width to fit the node's localized text plus horizontal padding.
	SizeFitText SizeMode = "fit_text"
)

type Slider

type Slider struct {
	Label          string
	Min            float32
	Max            float32
	Value          float32
	Step           float32
	OnChange       func(value float32)
	Disabled       bool
	Font           core.Font
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

Slider is a horizontal draggable and left/right steppable value control in [Min, Max]. When Min and Max are both 0, the range defaults to [0, 1]. When Step <= 0, keyboard and Adjust steps default to (Max - Min) / 10.

func (*Slider) Bounds

func (s *Slider) Bounds() core.Bounds

Bounds returns the slider's laid-out rectangle.

func (*Slider) Fraction

func (s *Slider) Fraction() float32

Fraction returns the slider's current Value normalized into [0, 1].

func (*Slider) SetValue

func (s *Slider) SetValue(v float32) bool

SetValue clamps v into [Min, Max], updates Value, and invokes OnChange if Value changed.

func (*Slider) TrackBounds

func (s *Slider) TrackBounds() core.Bounds

TrackBounds returns the slider's interactive track rectangle from the last Layout pass.

type Spacer

type Spacer struct {
	Width     float32
	Height    float32
	MinWidth  float32
	MinHeight float32
	Flex      float32
	Hidden    bool
	// contains filtered or unexported fields
}

Spacer reserves empty space inside a VBox or HBox. A zero-value Spacer defaults to Flex: 1 so it expands to push siblings apart; setting Width or Height without Flex creates a fixed gap.

func (*Spacer) Bounds

func (s *Spacer) Bounds() core.Bounds

Bounds returns the spacer's laid-out rectangle.

type SpatialNavigator

type SpatialNavigator struct {
	// Root is the UI root whose focusable widgets are navigated.
	Root *Root
	// WrapAround enables edge wrap-around when no widget exists further in the requested direction.
	WrapAround bool
	// SliderSteps causes NavLeft and NavRight to adjust a focused Slider by -1/+1 step
	// unless an explicit Left/Right neighbor override is configured for that Slider.
	SliderSteps bool
	// OnConfirm is invoked after NavConfirm activates the focused widget (or when Confirm is called).
	OnConfirm func(focused Widget)
	// OnBack is invoked when NavBack is triggered.
	OnBack func()
	// OnFocusChange is invoked whenever navigation moves focus from prev to next.
	OnFocusChange func(prev, next Widget)
	// FocusRing customizes the focus ring drawn by DrawFocusRing (or attached to Root).
	FocusRing *FocusRingStyle
	// contains filtered or unexported fields
}

SpatialNavigator drives 2D spatial focus navigation, explicit neighbor overrides, action-based keyboard/gamepad input, and customizable focus ring rendering over a Root.

Example

A SpatialNavigator moves focus to the nearest widget in the pressed direction, so a grid of buttons works with a d-pad.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	buttons := make([]*gameui.Button, 4)
	row := func(a, b int) gameui.Widget {
		return &gameui.HBox{Spacing: 10, Children: []gameui.Widget{buttons[a], buttons[b]}}
	}
	for i := range buttons {
		buttons[i] = &gameui.Button{Text: fmt.Sprint("slot ", i), Width: 100, Height: 40}
	}
	root := gameui.NewRoot(&gameui.VBox{Spacing: 10, Children: []gameui.Widget{row(0, 1), row(2, 3)}})
	root.Layout(core.Bounds{Size: core.Size{Width: 400, Height: 300}})

	nav := gameui.NewSpatialNavigator(root)
	nav.OnConfirm = func(w gameui.Widget) { fmt.Println("confirm", w.(*gameui.Button).Text) }
	nav.SetFocus(buttons[0])
	for _, a := range []gameui.NavAction{gameui.NavRight, gameui.NavDown, gameui.NavLeft, gameui.NavConfirm} {
		nav.HandleAction(a)
		fmt.Println(a, nav.Focused().(*gameui.Button).Text)
	}
}
Output:
NavRight slot 1
NavDown slot 3
NavLeft slot 2
confirm slot 2
NavConfirm slot 2

func NewSpatialNavigator

func NewSpatialNavigator(root *Root) *SpatialNavigator

NewSpatialNavigator returns a SpatialNavigator attached to root with wrap-around and slider stepping enabled.

func (*SpatialNavigator) Back

func (n *SpatialNavigator) Back() bool

Back triggers the OnBack callback if configured.

func (*SpatialNavigator) ClearFocus

func (n *SpatialNavigator) ClearFocus()

ClearFocus clears focus on Root.

func (*SpatialNavigator) ClearOverrides

func (n *SpatialNavigator) ClearOverrides(w Widget)

ClearOverrides removes any navigator-level overrides registered for w.

func (*SpatialNavigator) Confirm

func (n *SpatialNavigator) Confirm() bool

Confirm activates the currently focused widget and calls OnConfirm if configured.

func (*SpatialNavigator) DrawFocusRing

func (n *SpatialNavigator) DrawFocusRing(d *core.Drawing)

DrawFocusRing draws a customizable focus ring around the currently focused widget in Root.

func (*SpatialNavigator) Focused

func (n *SpatialNavigator) Focused() Widget

Focused returns the currently focused widget in Root, or nil.

func (*SpatialNavigator) HandleAction

func (n *SpatialNavigator) HandleAction(action NavAction) bool

HandleAction executes a single NavAction (directional move, slider step, confirm, or back).

func (*SpatialNavigator) Move

func (n *SpatialNavigator) Move(dir NavAction) bool

Move navigates focus in the directional NavAction (NavUp, NavDown, NavLeft, NavRight). It checks explicit per-widget overrides first, then falls back to 2D spatial navigation.

func (*SpatialNavigator) Overrides

func (n *SpatialNavigator) Overrides(w Widget) NavOverrides

Overrides returns the navigator-level overrides registered for w (or zero value if none).

func (*SpatialNavigator) SetFocus

func (n *SpatialNavigator) SetFocus(w Widget) bool

SetFocus focuses w if it is visible and focusable in Root.

func (*SpatialNavigator) SetOverrides

func (n *SpatialNavigator) SetOverrides(w Widget, ov NavOverrides)

SetOverrides registers explicit directional neighbor overrides for w on this navigator. Navigator overrides take precedence over widget-level Nav fields and automatic spatial search.

func (*SpatialNavigator) StepActions

func (n *SpatialNavigator) StepActions(pressed func(NavAction) bool) bool

StepActions polls logical UI navigation actions using pressed (for example, wrapping input.Actions.JustPressed) and dispatches any triggered actions in deterministic order. Returns true if any action was handled.

type SpriteRow

type SpriteRow struct {
	SpritePath  string
	SpriteFrame string
	Image       core.ImageSource
	Src         core.Bounds
	HasImage    bool
	Count       int
	Spacing     float32
	Color       core.Color
	Width       float32
	Height      float32
	MinWidth    float32
	MinHeight   float32
	Flex        float32
	Align       Align
	Hidden      bool
	// contains filtered or unexported fields
}

SpriteRow displays a horizontal row of repeated sprite icons (such as health hearts or ammo pips).

func (*SpriteRow) Bounds

func (s *SpriteRow) Bounds() core.Bounds

Bounds returns the sprite row's laid-out bounds.

type TextDrawParams

type TextDrawParams struct {
	Text     string
	X, Y     float32
	Font     core.Font
	Color    core.Color
	Align    core.TextAlign
	Baseline core.TextBaseline
	Bounds   core.Bounds
}

TextDrawParams carries the text string, anchor position, font, color, alignment, baseline, and widget bounds passed to a custom TextDrawer hook.

type TextDrawer

type TextDrawer func(d *core.Drawing, params TextDrawParams)

TextDrawer renders widget text into d, allowing custom bitmap or stylized font renderers without circular imports.

type TextMeasurer

type TextMeasurer func(text string, font core.Font) (width, height float32)

TextMeasurer measures text width and height for layout when using a custom TextDrawer.

type Theme

type Theme struct {
	// PanelBackground and PanelBorder style Panel containers.
	PanelBackground core.Color
	PanelBorder     core.Color

	// Background, Hover, Active, Disabled, Border, and FocusedBorder style interactive controls.
	Background    core.Color
	Hover         core.Color
	Active        core.Color
	FocusedBorder core.Color
	Disabled      core.Color
	Border        core.Color

	// Text, DisabledText, MutedText, Accent, AccentHover, AccentActive, and Track style labels, toggles, sliders, and progress bars.
	Text         core.Color
	DisabledText core.Color
	MutedText    core.Color
	Accent       core.Color
	AccentHover  core.Color
	AccentActive core.Color
	Track        core.Color

	// Padding is the default inner padding used for widget intrinsic sizing and spacing.
	Padding float32
	// CornerRadius is the default corner radius for rounded widget surfaces.
	CornerRadius float32
	// BorderWidth is the stroke width for widget borders.
	BorderWidth float32
	// FocusWidth is the stroke width for the focused outline.
	FocusWidth float32
	// Font is the default font used by text-bearing widgets.
	Font core.Font

	// PanelFrame optionally draws stylized or nine-slice frames for Panel widgets.
	PanelFrame FrameDrawer
	// ButtonFrame optionally draws stylized or nine-slice frames for Button widgets.
	ButtonFrame FrameDrawer
	// FrameDrawer optionally draws stylized or nine-slice frames when a widget has no specific frame drawer.
	FrameDrawer FrameDrawer
	// TextDrawer optionally replaces default Canvas FillText rendering (for example, with a bitmap font renderer).
	TextDrawer TextDrawer
	// TextMeasurer optionally provides text dimensions for layout when using a custom TextDrawer.
	TextMeasurer TextMeasurer
	// FocusRing optionally customizes the focus ring drawn around focused widgets.
	FocusRing *FocusRingStyle
}

Theme holds the colors, spacing, corner radius, borders, and default font used to lay out and draw a game UI.

func DefaultTheme

func DefaultTheme() Theme

DefaultTheme returns a high-contrast dark theme suited for in-game overlays and menus.

func HighContrastTheme

func HighContrastTheme() Theme

HighContrastTheme returns a high-contrast dark gameui Theme suitable when Accessibility.HighContrast is enabled.

type Toggle

type Toggle struct {
	Label          string
	Checked        bool
	Style          ToggleStyle
	OnChange       func(checked bool)
	Disabled       bool
	Font           core.Font
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Align          Align
	Hidden         bool
	Nav            NavOverrides
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	TextDrawer     TextDrawer
	// contains filtered or unexported fields
}

Toggle is a focusable boolean checkbox or switch control.

Example

A Toggle flips when activated and reports the change through OnChange.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	sound := &gameui.Toggle{Label: "Sound", Checked: true, Height: 40, OnChange: func(on bool) { fmt.Println("sound:", on) }}
	root := gameui.NewRoot(&gameui.VBox{Children: []gameui.Widget{sound}})
	root.Layout(core.Bounds{Size: core.Size{Width: 200, Height: 100}})
	root.SetFocus(sound)
	root.Activate()
	fmt.Println(sound.Checked)
}
Output:
sound: false
false

func (*Toggle) Bounds

func (t *Toggle) Bounds() core.Bounds

Bounds returns the toggle's laid-out rectangle.

type ToggleStyle

type ToggleStyle uint8

ToggleStyle picks the visual presentation of a Toggle widget.

const (
	// ToggleCheckbox draws a square checkbox with a checkmark when checked.
	ToggleCheckbox ToggleStyle = iota
	// ToggleSwitch draws a sliding pill switch.
	ToggleSwitch
)

type TouchButton

type TouchButton struct {
	Text       string
	HitSize    float32
	OnClick    func()
	Disabled   bool
	Font       core.Font
	TextColor  core.Color
	Background core.Color
	FocusOrder int
	Nav        NavOverrides
	Width      float32
	Height     float32
	MinWidth   float32
	MinHeight  float32
	Flex       float32
	Align      Align
	Hidden     bool
	TextDrawer TextDrawer
	// contains filtered or unexported fields
}

TouchButton is an on-screen circular touch action button with an expanded touch hit target.

func (*TouchButton) Bounds

func (b *TouchButton) Bounds() core.Bounds

Bounds returns the touch button's visual bounds.

func (*TouchButton) HitBounds

func (b *TouchButton) HitBounds() core.Bounds

HitBounds returns the touch button's interactive hit area, expanded to HitSize when larger than Bounds.

type TouchStick

type TouchStick struct {
	HitSize   float32
	BaseColor core.Color
	KnobColor core.Color
	ValueX    float32
	ValueY    float32
	OnMove    func(x, y float32)
	Disabled  bool
	Width     float32
	Height    float32
	MinWidth  float32
	MinHeight float32
	Flex      float32
	Align     Align
	Hidden    bool
	// contains filtered or unexported fields
}

TouchStick is an on-screen virtual thumbstick with an optional expanded circular touch hit area.

func (*TouchStick) Bounds

func (t *TouchStick) Bounds() core.Bounds

Bounds returns the stick's visual bounds.

func (*TouchStick) HitBounds

func (t *TouchStick) HitBounds() core.Bounds

HitBounds returns the stick's interactive touch target bounds, expanded to HitSize when larger than Bounds.

type VBox

type VBox struct {
	Children       []Widget
	Spacing        float32
	Padding        core.Edges
	Align          Align
	Justify        Justify
	Width          float32
	Height         float32
	MinWidth       float32
	MinHeight      float32
	Flex           float32
	Hidden         bool
	DrawBackground func(*core.Drawing, core.Bounds)
	FrameDrawer    FrameDrawer
	NineSlice      *NineSlice
	// contains filtered or unexported fields
}

VBox arranges Children vertically from top to bottom with Spacing and Padding.

func (*VBox) Bounds

func (b *VBox) Bounds() core.Bounds

Bounds returns the VBox's laid-out rectangle.

func (*VBox) ChildWidgets

func (b *VBox) ChildWidgets() []Widget

ChildWidgets returns the VBox's direct children.

type Viewport

type Viewport struct {
	VirtualWidth  float32
	VirtualHeight float32
	WindowWidth   float32
	WindowHeight  float32
	ScaleMode     ScaleMode
	// LetterboxColor fills letterbox/pillarbox bars in Draw and DrawLetterbox.
	// Zero defaults to opaque black; set core.Transparent to skip drawing bars.
	LetterboxColor core.Color
}

Viewport maps a fixed virtual UI resolution onto a physical window size with scaling, letterboxing, drawing transform setup, and window-to-virtual coordinate conversion.

Example

A Viewport fits a fixed virtual resolution into the window, adding bars on the sides that do not fit, and maps window points back to virtual ones.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/gameui"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	vp := gameui.NewViewport(320, 180, gameui.ScaleFit).WithWindowSize(1280, 1024)
	fmt.Println(vp.Scale(), vp.Rect())
	fmt.Println(len(vp.LetterboxBars()))
	p, inside := vp.WindowToVirtual(core.Point{X: 640, Y: 512})
	fmt.Println(p, inside)
}
Output:
4 {{0 152} {1280 720}}
2
{160 90} true

func NewViewport

func NewViewport(virtualW, virtualH float32, mode ScaleMode) Viewport

NewViewport returns a Viewport configured for virtualW x virtualH using mode.

func (Viewport) Apply

func (v Viewport) Apply(d *core.Drawing)

Apply clips d to VisibleBounds and applies the viewport's translation and scale transform. Callers should wrap Apply in d.Save() / d.Restore().

func (Viewport) Draw

func (v Viewport) Draw(d *core.Drawing, drawFn func(d *core.Drawing, virtualBounds core.Bounds))

Draw renders letterbox bars, sets up the viewport clip and transform inside Save/Restore, and invokes drawFn with the virtual canvas bounds.

func (Viewport) DrawLetterbox

func (v Viewport) DrawLetterbox(d *core.Drawing)

DrawLetterbox fills any active letterbox/pillarbox bars into d unless LetterboxColor is core.Transparent.

func (Viewport) LetterboxBars

func (v Viewport) LetterboxBars() []core.Bounds

LetterboxBars returns the non-empty, non-overlapping bar rectangles inside the window outside Rect().

func (Viewport) Rect

func (v Viewport) Rect() core.Bounds

Rect returns the projected virtual canvas rectangle in physical window coordinates. For ScaleFill, Rect may extend outside [0, WindowWidth] x [0, WindowHeight].

func (Viewport) Scale

func (v Viewport) Scale() float32

Scale returns the uniform scale factor (or min(sx, sy) for ScaleStretch).

func (Viewport) ScaleXY

func (v Viewport) ScaleXY() (sx, sy float32)

ScaleXY returns the horizontal and vertical scale factors from virtual coordinates to window coordinates.

func (*Viewport) SetWindowSize

func (v *Viewport) SetWindowSize(size core.Size)

SetWindowSize updates the viewport's physical window dimensions.

func (Viewport) VirtualBounds

func (v Viewport) VirtualBounds() core.Bounds

VirtualBounds returns the layout rectangle in virtual coordinates: (0, 0, VirtualWidth, VirtualHeight).

func (Viewport) VirtualToWindow

func (v Viewport) VirtualToWindow(p core.Point) core.Point

VirtualToWindow maps a point in virtual coordinates into physical window coordinates.

func (Viewport) VisibleBounds

func (v Viewport) VisibleBounds() core.Bounds

VisibleBounds returns the intersection of Rect() with the window bounds [0, WindowWidth] x [0, WindowHeight]. For ScaleFit and ScaleInteger this equals Rect(); for ScaleFill it equals the full window bounds.

func (Viewport) WindowToVirtual

func (v Viewport) WindowToVirtual(p core.Point) (core.Point, bool)

WindowToVirtual maps a physical window point into virtual coordinates. ok is false when p falls outside the active viewport (for example, inside letterbox/pillarbox bars or outside the window).

func (Viewport) WithWindowSize

func (v Viewport) WithWindowSize(w, h float32) Viewport

WithWindowSize returns a copy of v with WindowWidth and WindowHeight set to w and h.

type VirtualViewport

type VirtualViewport = Viewport

VirtualViewport is an alias for Viewport.

type Widget

type Widget interface {
	// Bounds returns the widget's rectangle from the last Layout pass.
	Bounds() core.Bounds
	// contains filtered or unexported methods
}

Widget is a node in a game UI layout and focus tree.

type WidgetState

type WidgetState struct {
	Hovered  bool
	Pressed  bool
	Focused  bool
	Disabled bool
}

WidgetState describes the current interaction state of a widget during Draw or StateOf queries.

type WorldAnchor

type WorldAnchor struct {
	// ID uniquely identifies this anchor inside an AnchorOverlay.
	ID string
	// WorldX and WorldY are the anchor's coordinates in 2D game world space.
	WorldX, WorldY float32
	// OffsetX and OffsetY shift the anchored view in screen points after world projection.
	OffsetX, OffsetY float32
	// AnchorX and AnchorY position the view relative to the projected point as fractions of the view's own size:
	// (0, 0) = top-left at point, (0.5, 0.5) = centered on point, (0.5, 1.0) = centered directly above point.
	AnchorX, AnchorY float32
	// Visible toggles whether this anchor is shown when on-screen.
	Visible bool
	// View builds the native NSGo view mounted at this anchor's screen position.
	View func(*core.Scope) core.View
	// TestID optionally assigns a TestID to the positioned anchor wrapper view.
	TestID string
}

WorldAnchor binds a native NSGo View (such as a name tag, speech bubble, or text input) to a 2D world position with optional screen-space pixel offset and normalized anchor pivot.

func NewWorldAnchor

func NewWorldAnchor(id string, worldX, worldY float32, view func(*core.Scope) core.View) *WorldAnchor

NewWorldAnchor returns a visible WorldAnchor at (worldX, worldY) rendering view.

type WorldProjection

type WorldProjection struct {
	// WorldToScreen converts a world position (worldX, worldY) to screen/window coordinates (screenX, screenY).
	WorldToScreen func(worldX, worldY float32) (screenX, screenY float32)
	// ScreenBounds is the visible screen rectangle in window coordinates.
	// When non-zero, projected positions outside ScreenBounds are treated as off-screen and hidden.
	ScreenBounds core.Bounds
}

WorldProjection maps 2D game world coordinates into screen/window coordinates and defines the visible screen bounds used to automatically hide off-screen world anchors.

func NewCameraViewportProjection

func NewCameraViewportProjection(camX, camY, zoom, viewW, viewH float32, vp Viewport) WorldProjection

NewCameraViewportProjection creates a WorldProjection combining a 2D camera centered at (camX, camY) with zoom and view dimensions (viewW, viewH) with a virtual-resolution Viewport (including scaling and letterboxing). Points projecting into letterbox bars or outside the window fall outside ScreenBounds.

func NewWorldProjection

func NewWorldProjection(worldToScreen func(worldX, worldY float32) (screenX, screenY float32), screenBounds core.Bounds) WorldProjection

NewWorldProjection constructs a WorldProjection from a custom projection function and visible screen bounds.

func (WorldProjection) Project

func (p WorldProjection) Project(worldX, worldY float32) (pt core.Point, onScreen bool)

Project maps (worldX, worldY) to screen coordinates and reports whether the projected point is on-screen.

Jump to

Keyboard shortcuts

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