GitHub快速开始

API 参考取自源码中的 Go 文档注释,以英文书写。

package quality

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

概述

Package quality picks a game's low, medium or high quality preset (resolution scale, particle budget, effects and shadows) from the device it runs on and the frame times it measures, and lets the player override the choice in settings.

A Config, written in YAML, holds the three presets, rules that place known device models, and how frame times move the level. A Selector starts at the level the Config gives the Device, steps down when frames run slower than the target and up when they keep well inside it, and holds whatever level the player picks instead of "auto".

索引

常量

const (
	// DefaultTargetFPS is the frame rate the Selector holds when Adapt.TargetFPS is 0.
	DefaultTargetFPS = 30
	// DefaultWindowFrames is how many frames the Selector judges at a time when Adapt.WindowFrames is 0.
	DefaultWindowFrames = 90
	// DefaultUpgradeWindows is how many fast windows in a row the Selector waits for before stepping up when Adapt.UpgradeWindows is 0.
	DefaultUpgradeWindows = 4
)

Defaults that apply when a Config's Adapt leaves a field at 0.

const FormatVersion = 1

FormatVersion is the schema version of the quality YAML file, the one ParseConfig accepts and EncodeConfig writes.

const SettingAuto = "auto"

SettingAuto is the setting that lets the Selector choose the level from the device and its frame times.

函数

func EncodeConfig(c Config) ([]byte, error)

EncodeConfig validates c and writes it as deterministic 2-space YAML in field order, so a file read by ParseConfig and written back is unchanged.

func NormalizeSetting(s string) (string, error)

NormalizeSetting returns the canonical form of a player's quality setting: "auto" for s empty or "auto", or the name of the level s names, ignoring case and surrounding space. It returns an error for anything else.

类型

type Adapt struct {
	// Off keeps the starting level for the whole run, ignoring frame times.
	Off bool `yaml:"off,omitempty"`
	// TargetFPS is the frame rate to hold, in [3, 240]; below 3 fps a slow frame would be longer than the half second past which the Selector ignores frames, so it could never step down. DefaultTargetFPS when 0. More than a quarter of a window's frames running slower steps the level down.
	TargetFPS int `yaml:"target_fps,omitempty"`
	// WindowFrames is how many frames the Selector judges at a time, in [10, 3600]; DefaultWindowFrames when 0.
	WindowFrames int `yaml:"window_frames,omitempty"`
	// UpgradeWindows is how many windows in a row must run with nine in ten frames inside 60% of the target frame time before the level steps up, in [1, 100]; DefaultUpgradeWindows when 0.
	UpgradeWindows int `yaml:"upgrade_windows,omitempty"`
}

Adapt controls how the Selector moves the level from measured frame times. Zero fields take the defaults.

type Config struct {
	// Version is the schema version; it must be FormatVersion.
	Version int `yaml:"version"`
	// Presets holds the preset for each level.
	Presets Presets `yaml:"presets"`
	// Devices places device models at a starting level ahead of Classify's heuristic; the first rule that matches wins.
	Devices []DeviceRule `yaml:"devices,omitempty"`
	// Adapt controls how measured frame times move the level while the setting is auto.
	Adapt Adapt `yaml:"adapt,omitempty"`
}

Config is a game's quality configuration: its presets, the device rules that place known models, and how measured frame times move the level. It is written in YAML (see ParseConfig) and validated by Validate.

func DefaultConfig() Config

DefaultConfig returns the built-in configuration: DefaultPreset for each level, no device rules and the default adaptation.

func ParseConfig(data []byte) (Config, error)

ParseConfig decodes a quality YAML document and validates it. Unknown fields, a missing or other version, and trailing documents are refused.

func (c Config) StartLevel(d Device) Level

StartLevel returns the level a device starts at: the level of the first device rule that matches it, else Classify's.

func (c Config) Validate() error

Validate reports the first way c breaks the schema: a version other than FormatVersion, a preset scale outside (0, 1], a device rule with no model, an unknown OS or level or the same model and OS twice, or an adapt field out of range.

type Device struct {
	// OS is the operating system, such as core.OSAndroid; empty when unknown.
	OS core.OS
	// Idiom is the kind of device, such as core.IdiomPhone.
	Idiom core.Idiom
	// Model is the hardware model as core.Env.DeviceModel reports it, such as "iPhone15,2" or "Google Pixel 8"; empty when unknown.
	Model string
	// OSVersion is the operating system's version; on Android its Major is the API level.
	OSVersion core.OSVersion
	// CPUs is how many logical CPUs the process can use; 0 when unknown.
	CPUs int
}

Device describes the hardware a game runs on, as far as Classify needs it.

func DeviceFromEnv(env *core.Env) Device

DeviceFromEnv returns the Device env describes, with CPUs from runtime.NumCPU.

type DeviceRule struct {
	// Model is the start of core.Env.DeviceModel to match, such as "Google Pixel 8" or "iPhone12,".
	Model string `yaml:"model"`
	// OS limits the rule to one operating system, such as "android" or "ios"; empty matches any.
	OS core.OS `yaml:"os,omitempty"`
	// Level is the level matching devices start at.
	Level Level `yaml:"level"`
}

DeviceRule starts devices whose model begins with Model, ignoring case, at Level, optionally only on one OS.

func (r DeviceRule) Matches(d Device) bool

Matches reports whether d's model starts with r.Model, ignoring case, on r.OS when it is set.

type Level uint8

Level is a quality tier, from Low to High.

const (
	// Low is the tier for low-end phones and anything that cannot hold its frame rate higher.
	Low Level = iota
	// Medium is the tier for mid-range devices and for hardware the Selector cannot place.
	Medium
	// High is the tier for capable desktops, recent phones and tablets.
	High
)
func Classify(d Device) Level

Classify returns the level a device starts at when no device rule places it.

Android starts Low, since NSGo reports neither its memory nor its GPU and core counts do not tell a budget phone from a flagship; measured frame times step it up. iPhones start High from the iPhone 13 (model iPhone14,x) on, Medium from the iPhone 11 (iPhone12,x) and Low before; iPads High from model iPad13,x on, Medium from iPad11,x and Low before. Desktops start High with 8 or more CPUs, Medium with 4 to 7 and Low with fewer. TVs and watches start Low, and the web and anything unknown start Medium.

func Levels() []Level

Levels returns every level from Low to High.

func ParseLevel(s string) (Level, error)

ParseLevel returns the level named s ("low", "medium" or "high"), ignoring case and surrounding space.

func (l Level) MarshalText() ([]byte, error)

MarshalText returns the level's name, so YAML and JSON write it as "low", "medium" or "high".

func (l Level) String() string

String returns the level's name: "low", "medium" or "high".

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText reads a level's name as ParseLevel does.

func (l Level) Valid() bool

Valid reports whether l is Low, Medium or High.

type Preset struct {
	// ResolutionScale scales the resolution of buffers the game renders or rasterizes itself, such as render3d.OcclusionBuffer and procedurally drawn images, in (0, 1]. Read it through Scale and ScaleSize. It does not lower the resolution of a core.Canvas itself: NSGo v0.3.0 draws a canvas at the display's full pixel density and has no setting to render it smaller and upscale it. Nothing in this module applies it for the game; the game sizes its own buffers with it.
	ResolutionScale float32 `yaml:"resolution_scale"`
	// ParticleScale scales particle budgets and burst counts, in (0, 1]. Read it through Particles.
	ParticleScale float32 `yaml:"particle_scale"`
	// Effects turns on effects that only decorate the frame, such as screen flashes, parallax backdrops, post effects and trails.
	Effects bool `yaml:"effects"`
	// Shadows turns on shadow casting, such as lights2d's occluder clipping (lights2d.Scene.DisableShadows is its inverse).
	Shadows bool `yaml:"shadows"`
}

Preset is what one quality level turns on and how far it scales the game's costs.

func DefaultPreset(l Level) Preset

DefaultPreset returns the built-in preset for l: Low renders at half resolution with a quarter of the particles and no effects or shadows, Medium at three quarters with 60% of the particles and effects, and High at full resolution with everything on. It returns the Medium preset for an invalid level.

func (p Preset) Particles(n int) int

Particles returns n scaled by ParticleScale and rounded, at least 1 when n is positive, so it can set a particles.Emitter's MaxParticles (where 0 means the default of 256) or a Burst's count. It returns n unchanged when ParticleScale is not a valid scale, and 0 when n is not positive.

func (p Preset) Scale(n int) int

Scale returns n, a pixel count, scaled by ResolutionScale and rounded, at least 1 when n is positive. It returns n unchanged when ResolutionScale is not a valid scale, and 0 when n is not positive.

func (p Preset) ScaleSize(size core.Size) core.Size

ScaleSize returns size scaled by ResolutionScale, or size unchanged when ResolutionScale is not a valid scale.

func (p Preset) Validate() error

Validate reports an error when a scale is not finite or lies outside (0, 1].

type Presets struct {
	// Low is the preset for Low.
	Low Preset `yaml:"low"`
	// Medium is the preset for Medium.
	Medium Preset `yaml:"medium"`
	// High is the preset for High.
	High Preset `yaml:"high"`
}

Presets holds one Preset per level.

func (p Presets) For(l Level) Preset

For returns the preset for l, or Medium's for an invalid level.

type Selector struct {
	// OnChange, when set, is called with the new level and its preset whenever the level changes, from Observe or SetSetting.
	OnChange func(Level, Preset)
	// contains filtered or unexported fields
}

Selector chooses the quality level a game runs at: the level its Config gives the Device to start, moved by measured frame times while the setting is auto, or the level the player sets.

Feed it each frame's length with Observe, for example from game.Loop.FrameTime. While auto, it judges frames a window at a time: when more than a quarter of a window's frames run slower than the target frame rate it steps down a level, and after Adapt.UpgradeWindows windows in a row with nine in ten frames inside 60% of the target frame time it steps up one. It never steps back up to a level it stepped down from, so it settles rather than swinging between two levels.

A Selector is not safe for concurrent use; use it from the scope that runs the loop.

func NewSelector(cfg Config, d Device) (*Selector, error)

NewSelector returns a Selector for d that starts at cfg.StartLevel(d) with the setting auto. It returns an error when cfg is not valid.

func (s *Selector) Auto() bool

Auto reports whether the setting is auto, so frame times move the level.

func (s *Selector) Level() Level

Level returns the current level.

func (s *Selector) Observe(dt time.Duration) bool

Observe records one frame's length and reports whether it changed the level. It does nothing while the setting holds a fixed level or Config.Adapt.Off is set, and ignores lengths that are not positive or longer than half a second.

func (s *Selector) Preset() Preset

Preset returns the current level's preset.

func (s *Selector) SetSetting(setting string) error

SetSetting applies a player's setting as NormalizeSetting reads it: "auto" (or empty) returns to the starting level and lets frame times move it again, and a level's name holds that level. It returns an error, changing nothing, for anything else.

func (s *Selector) Setting() string

Setting returns the setting to store in the player's settings: "auto" or the fixed level's name.

func (s *Selector) StartLevel() Level

StartLevel returns the level the device started at, the one auto returns to.