GitHubEmpezar

La referencia de API proviene de los comentarios de documentación de Go en el código fuente y está redactada en inglés.

package steamworks

import "github.com/nsgo-dev/game/pkg/online/steamworks"

Resumen

Package steamworks is experimental: its API and documented formats may change in a minor release. See the API stability policy. provides one process-wide Steamworks client for desktop targets (macOS, Linux, and Windows) loaded dynamically through purego without cgo or hand-written C. On non-desktop targets (web, iOS, Android, and experimental targets) Open returns ErrUnavailable unless a custom Driver is supplied in Options.

Call Open once on the game's root core.Scope to load the Steamworks shared library, optionally invoke SteamAPI_RestartAppIfNecessary, initialize Steamworks with SteamAPI_InitFlat, enable SteamAPI_ManualDispatch, and pump callbacks once per display frame on the engine goroutine. Disposing the last scope that opened the client calls SteamAPI_Shutdown.

Subsystem integrations such as github.com/nsgo-dev/game/pkg/online/presence and github.com/nsgo-dev/game/pkg/modding attach to the shared *Client so they never initialize, pump, or shut down Steamworks independently.

Índice

Constantes

const (
	// CallbackGetTicketForWebApiResponse is GetTicketForWebApiResponse_t (k_iSteamUserCallbacks + 68).
	CallbackGetTicketForWebApiResponse int32 = 168
	// CallbackGameOverlayActivated is GameOverlayActivated_t (k_iSteamFriendsCallbacks + 31).
	CallbackGameOverlayActivated int32 = 331
	// CallbackGameLobbyJoinRequested is GameLobbyJoinRequested_t (k_iSteamFriendsCallbacks + 33).
	CallbackGameLobbyJoinRequested int32 = 333
	// CallbackGameRichPresenceJoinRequested is GameRichPresenceJoinRequested_t (k_iSteamFriendsCallbacks + 37).
	CallbackGameRichPresenceJoinRequested int32 = 337
	// CallbackAPICallCompleted is SteamAPICallCompleted_t (k_iSteamUtilsCallbacks + 3).
	CallbackAPICallCompleted int32 = 703
	// CallbackSteamShutdown is SteamShutdown_t (k_iSteamUtilsCallbacks + 4).
	CallbackSteamShutdown int32 = 704
	// CallbackGamepadTextInputDismissed is GamepadTextInputDismissed_t (k_iSteamUtilsCallbacks + 14).
	CallbackGamepadTextInputDismissed int32 = 714
	// CallbackItemInstalled is ItemInstalled_t (k_iSteamUGCCallbacks + 5).
	CallbackItemInstalled int32 = 3405
)

Steamworks callback IDs from Valve's Steamworks SDK headers.

Variables

var (
	// ErrUnavailable is returned when Steamworks is not available on the current
	// platform, the shared library cannot be loaded, or Steam initialization fails.
	ErrUnavailable = errors.New("steamworks: unavailable")
	// ErrRestartRequired is returned by [Open] when Options.RestartIfNecessary is
	// true and SteamAPI_RestartAppIfNecessary reports that Steam is relaunching
	// the game; the caller should exit immediately.
	ErrRestartRequired = errors.New("steamworks: restart through Steam required")
	// ErrClosed is returned by operations on a [Client] after its owning scope has
	// been disposed and SteamAPI_Shutdown has run.
	ErrClosed = errors.New("steamworks: client closed")
	// ErrAppIDMismatch is returned by [Open] when a Steamworks client is already
	// open in this process with a different non-zero AppID.
	ErrAppIDMismatch = errors.New("steamworks: already initialized with a different AppID")
	// ErrDriverConflict is returned by [Open] when a Steamworks client is already
	// open in this process with a different explicit Driver.
	ErrDriverConflict = errors.New("steamworks: already initialized with a different driver")
	// ErrAuthTicket is returned when Steamworks rejects an auth ticket request.
	ErrAuthTicket = errors.New("steamworks: auth ticket request failed")
)

Funciones

func ParseConnectArg(args []string) (string, bool)

ParseConnectArg extracts the +connect launch argument value passed by Steam when the game is started from a friend's "Join Game" action. It recognizes `["+connect", "<value>"]`, `["+connect=<value>"]`, and `["+connect <value>"]`.

func ParseConnectLobbyArg(args []string) (uint64, bool)

ParseConnectLobbyArg extracts the 64-bit Steam lobby ID passed by Steam via +connect_lobby <lobbyID> or +connect_lobby=<lobbyID>.

Tipos

type AuthTicket struct {
	Handle uint32
	Bytes  []byte
}

AuthTicket holds a Steam Web API session ticket returned by Client.AuthTicketForWebAPI for server-side verification with ISteamUserAuth/AuthenticateUserTicket.

func (t AuthTicket) Hex() string

Hex returns the uppercase hexadecimal encoding expected by Steam's ISteamUserAuth/AuthenticateUserTicket Web API endpoint.

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

Client is the process-wide Steamworks client owned by one or more NSGo scopes. Obtain it via Open or read the currently active client via Current.

Lock ordering: processMu -> c.drvMu -> c.mu. User event handlers are never called while holding any lock.

func Current() *Client

Current returns the currently open process-wide Steamworks client, or nil if no scope holds an open client.

func Open(cx *core.Scope, opts Options) (*Client, error)

Open initializes or attaches to the process-wide Steamworks client for cx.

Only one SteamAPI_InitFlat runs per process: if a client is already open, Open attaches cx to the existing client (refusing a conflicting non-zero AppID or explicit Driver) and reference-counts shutdown. Manual dispatch runs once per display frame on the engine goroutine until the last attached scope is disposed, at which point SteamAPI_Shutdown runs.

func (c *Client) AppID() uint32

AppID returns the Steam application ID reported by Steamworks (or Options.AppID when Steamworks reports 0).

func (c *Client) AuthTicketForWebAPI(ctx context.Context, identity string) (AuthTicket, error)

AuthTicketForWebAPI requests a Steam session ticket for server-side verification (ISteamUserAuth/AuthenticateUserTicket) and waits for GetTicketForWebApiResponse_t. Pass the same identity string your backend verifies (empty string is allowed by Steamworks).

func (c *Client) AwaitCall(ctx context.Context, call uint64, expectedCallback int32) ([]byte, error)

AwaitCall waits for a SteamAPICall_t asynchronous result to arrive via the shared client's manual-dispatch callback pump, returning the raw callback payload bytes.

func (c *Client) CallbackPack() int

CallbackPack returns the struct packing alignment used by Steamworks callback structures on this platform (4 on macOS/Linux, 8 on Windows).

func (c *Client) CancelAuthTicket(handle uint32)

CancelAuthTicket cancels a previously issued auth ticket handle.

func (c *Client) ClearRichPresence()

ClearRichPresence calls ISteamFriends::ClearRichPresence on the shared client.

func (c *Client) Closed() bool

Closed reports whether the client's owning scopes have all been disposed.

func (c *Client) LaunchConnect() string

LaunchConnect returns the +connect launch argument value captured when the client opened, or "" if none was present.

func (c *Client) OnCallback(callbackID int32, fn func(data []byte)) (stop func())

OnCallback registers fn to run on the engine goroutine whenever Steamworks broadcasts a callback with the given callbackID. Subsystem packages (such as Workshop for CallbackItemInstalled) use this to receive broadcast callbacks from the shared manual-dispatch pump.

func (c *Client) OnGamepadTextInput(fn func(GamepadTextInputEvent)) (stop func())

OnGamepadTextInput registers fn to run on the engine goroutine when the Steam Big Picture / Steam Deck on-screen keyboard closes.

func (c *Client) OnJoin(fn func(JoinEvent)) (stop func())

OnJoin registers fn to run on the engine goroutine when a friend join is requested (GameRichPresenceJoinRequested_t) or when the game was launched with +connect. A pending +connect launch join is delivered on the next pumped frame once at least one handler is registered.

func (c *Client) OnLobbyJoin(fn func(LobbyJoinEvent)) (stop func())

OnLobbyJoin registers fn to run on the engine goroutine when a lobby invite is accepted (GameLobbyJoinRequested_t) or when the game was launched with +connect_lobby.

func (c *Client) OnOverlay(fn func(OverlayEvent)) (stop func())

OnOverlay registers fn to run on the engine goroutine whenever the Steam Overlay opens or closes. The returned function unregisters fn.

func (c *Client) OnShutdown(fn func(ShutdownEvent)) (stop func())

OnShutdown registers fn to run on the engine goroutine when Steam broadcasts SteamShutdown_t.

func (c *Client) OpenOverlay(dialog string) bool

OpenOverlay activates the Steam Overlay to the specified dialog (for example "friends", "community", "players", "settings", "officialgamegroup", "stats", or "achievements", or "" for the default overlay).

func (c *Client) OpenOverlayURL(url string) bool

OpenOverlayURL activates the Steam Overlay web browser directly to url.

func (c *Client) OverlayActive() bool

OverlayActive reports whether the Steam Overlay is currently open as last reported by GameOverlayActivated_t.

func (c *Client) OverlayEnabled() bool

OverlayEnabled reports whether the Steam Overlay is enabled for this session (ISteamUtils::IsOverlayEnabled).

func (c *Client) PauseOnOverlay(loop *game.Loop) (stop func())

PauseOnOverlay pauses loop while the Steam Overlay is open and resumes it when the overlay closes, preserving any pause that was already active before the overlay opened (such as an open pause menu). Calling the returned stop function unregisters the listener and restores the loop if this helper had paused it.

func (c *Client) PersonaName() string

PersonaName returns the signed-in user's Steam persona name, or "" if closed.

func (c *Client) Pump()

Pump runs one manual-dispatch frame: calls SteamAPI_ManualDispatch_RunFrame, drains all queued callbacks, resolves completed SteamAPICall_t and Web API auth tickets, and delivers typed events to registered listeners.

Open runs Pump automatically once per display frame on the engine goroutine; callers normally do not need to invoke it directly.

func (c *Client) ResolveSymbol(names ...string) (uintptr, error)

ResolveSymbol resolves the first available symbol name from the shared Steamworks library handle loaded by this client. Subsystem packages (such as modding.SteamWorkshop) use this instead of opening libsteam_api a second time.

func (c *Client) RunningOnSteamDeck() bool

RunningOnSteamDeck reports whether Steamworks reports the game is running on a Steam Deck (ISteamUtils::IsSteamRunningOnSteamDeck).

func (c *Client) SetRichPresence(key, value string) bool

SetRichPresence calls ISteamFriends::SetRichPresence on the shared client.

func (c *Client) ShowGamepadTextInput(desc, existing string, maxChars uint32, multiLine, password bool) bool

ShowGamepadTextInput opens the Steam Big Picture / Steam Deck on-screen keyboard. When the player submits or cancels, [OnGamepadTextInput] fires.

func (c *Client) SteamID() uint64

SteamID returns the signed-in user's 64-bit SteamID, or 0 if closed.

type Driver interface {
	RestartAppIfNecessary(appID uint32) bool
	Init() (InitResult, string, error)
	Shutdown() error

	RunFrame()
	NextCallback() (RawCallback, bool)
	FreeLastCallback()
	GetAPICallResult(call uint64, expectedCallback int32, size int32) (data []byte, failed bool, ok bool)

	AppID() uint32
	SteamID() uint64
	PersonaName() string
	RunningOnSteamDeck() bool
	OverlayEnabled() bool
	ActivateGameOverlay(dialog string) bool
	ActivateGameOverlayToWebPage(url string) bool

	SetRichPresence(key, value string) bool
	ClearRichPresence()

	GetAuthTicketForWebAPI(identity string) uint32
	CancelAuthTicket(handle uint32)

	ShowGamepadTextInput(desc, existing string, maxChars uint32, multiLine, password bool) bool
	GetEnteredGamepadTextInput() (string, bool)

	ResolveSymbol(names ...string) (uintptr, error)
	CallbackPack() int
}

Driver abstracts the low-level Steamworks shared library so Client can be tested deterministically without Steam installed.

type FakeDriver struct {

	// Configurable behavior before Open.
	RestartRequired bool
	InitResult      InitResult
	InitMessage     string
	InitErr         error
	Pack            int

	// Configurable environment/user state.
	AppIDValue   uint32
	SteamIDValue uint64
	Persona      string
	SteamDeck    bool
	OverlayOK    bool

	// Optional symbol resolver for tests that exercise ResolveSymbol.
	Symbols map[string]uintptr
	// contains filtered or unexported fields
}

FakeDriver is an in-process Driver for deterministic unit and integration tests without a Steamworks shared library or running Steam client. All methods are safe for concurrent use.

func NewFakeDriver() *FakeDriver

NewFakeDriver returns a ready-to-use FakeDriver with sensible defaults (AppID 480, SteamID 76561198000000001, Persona "Player", OverlayOK true, CallbackPack 4).

func (f *FakeDriver) ActivateGameOverlay(dialog string) bool

ActivateGameOverlay implements Driver.

func (f *FakeDriver) ActivateGameOverlayToWebPage(url string) bool

ActivateGameOverlayToWebPage implements Driver.

func (f *FakeDriver) AppID() uint32

AppID implements Driver.

func (f *FakeDriver) AuthRequests() []string

AuthRequests returns the identities passed to GetAuthTicketForWebAPI, in order.

func (f *FakeDriver) CallbackPack() int

CallbackPack implements Driver.

func (f *FakeDriver) CancelAuthTicket(handle uint32)

CancelAuthTicket implements Driver.

func (f *FakeDriver) CanceledTickets() []uint32

CanceledTickets returns the auth ticket handles passed to CancelAuthTicket, in order.

func (f *FakeDriver) ClearRichPresence()

ClearRichPresence implements Driver.

func (f *FakeDriver) CompleteAPICall(call uint64, callbackID int32, data []byte, failed bool)

CompleteAPICall queues a SteamAPICallCompleted_t callback for call with result payload data (or failed = true to simulate an I/O failure).

func (f *FakeDriver) EmitAuthTicket(handle uint32, eResult int32, ticket []byte)

EmitAuthTicket queues a GetTicketForWebApiResponse_t callback for handle. Pass eResult = 1 for k_EResultOK.

func (f *FakeDriver) EmitCallback(callbackID int32, data []byte)

EmitCallback queues a raw Steamworks callback for delivery on the next frame.

func (f *FakeDriver) EmitGamepadTextInput(submitted bool, text string, appID uint32)

EmitGamepadTextInput queues a GamepadTextInputDismissed_t callback and sets the text returned by GetEnteredGamepadTextInput.

func (f *FakeDriver) EmitJoin(friendID uint64, connect string)

EmitJoin queues a GameRichPresenceJoinRequested_t callback.

func (f *FakeDriver) EmitLobbyJoin(lobbyID, friendID uint64)

EmitLobbyJoin queues a GameLobbyJoinRequested_t callback.

func (f *FakeDriver) EmitOverlay(active, userInitiated bool, appID uint32)

EmitOverlay queues a GameOverlayActivated_t callback.

func (f *FakeDriver) EmitShutdown()

EmitShutdown queues a SteamShutdown_t callback.

func (f *FakeDriver) FreeLastCallback()

FreeLastCallback implements Driver.

func (f *FakeDriver) FreedCallbackCount() int

FreedCallbackCount returns how many dequeued callbacks were freed.

func (f *FakeDriver) GetAPICallResult(call uint64, expectedCallback int32, size int32) ([]byte, bool, bool)

GetAPICallResult implements Driver.

func (f *FakeDriver) GetAuthTicketForWebAPI(identity string) uint32

GetAuthTicketForWebAPI implements Driver.

func (f *FakeDriver) GetEnteredGamepadTextInput() (string, bool)

GetEnteredGamepadTextInput implements Driver.

func (f *FakeDriver) InFlightCallbackCount() int

InFlightCallbackCount returns how many dequeued callbacks have not been freed yet.

func (f *FakeDriver) Init() (InitResult, string, error)

Init implements Driver.

func (f *FakeDriver) InitCount() int

InitCount returns how many times Init was called.

func (f *FakeDriver) NextCallback() (RawCallback, bool)

NextCallback implements Driver.

func (f *FakeDriver) OverlayDialogs() []string

OverlayDialogs returns the dialogs passed to ActivateGameOverlay, in order.

func (f *FakeDriver) OverlayEnabled() bool

OverlayEnabled implements Driver.

func (f *FakeDriver) OverlayURLs() []string

OverlayURLs returns the URLs passed to ActivateGameOverlayToWebPage, in order.

func (f *FakeDriver) PersonaName() string

PersonaName implements Driver.

func (f *FakeDriver) ResolveSymbol(names ...string) (uintptr, error)

ResolveSymbol implements Driver.

func (f *FakeDriver) RestartAppIfNecessary(appID uint32) bool

RestartAppIfNecessary implements Driver.

func (f *FakeDriver) RestartCount() int

RestartCount returns how many times RestartAppIfNecessary was called.

func (f *FakeDriver) RichPresence() map[string]string

RichPresence returns a copy of the rich presence keys currently set.

func (f *FakeDriver) RichPresenceClearCount() int

RichPresenceClearCount returns how many times ClearRichPresence was called.

func (f *FakeDriver) RunFrame()

RunFrame implements Driver.

func (f *FakeDriver) RunFrameCount() int

RunFrameCount returns how many manual-dispatch frames ran.

func (f *FakeDriver) RunningOnSteamDeck() bool

RunningOnSteamDeck implements Driver.

func (f *FakeDriver) SetRichPresence(key, value string) bool

SetRichPresence implements Driver.

func (f *FakeDriver) ShowGamepadTextInput(desc, existing string, maxChars uint32, multiLine, password bool) bool

ShowGamepadTextInput implements Driver.

func (f *FakeDriver) Shutdown() error

Shutdown implements Driver.

func (f *FakeDriver) ShutdownCount() int

ShutdownCount returns how many times Shutdown was called.

func (f *FakeDriver) SteamID() uint64

SteamID implements Driver.

type GamepadTextInputEvent struct {
	Submitted bool
	Text      string
	AppID     uint32
}

GamepadTextInputEvent is delivered when the Steam Big Picture / Steam Deck on-screen keyboard closes (GamepadTextInputDismissed_t).

type InitError struct {
	Result  InitResult
	Message string
}

InitError reports a SteamAPI_InitFlat failure, preserving both the ESteamAPIInitResult code and the human-readable SteamErrMsg text returned by Steamworks. It wraps ErrUnavailable so callers that degrade gracefully can check errors.Is(err, steamworks.ErrUnavailable).

func (e *InitError) Error() string

Error returns the init result and Steam's message.

func (e *InitError) Unwrap() error

Unwrap returns ErrUnavailable, so errors.Is(err, ErrUnavailable) matches an init failure.

type InitResult int32

InitResult matches Steamworks' ESteamAPIInitResult returned by SteamAPI_InitFlat.

const (
	// InitOK indicates SteamAPI_InitFlat succeeded.
	InitOK InitResult = 0
	// InitFailedGeneric indicates an unspecified Steamworks initialization failure.
	InitFailedGeneric InitResult = 1
	// InitNoSteamClient indicates the Steam client is not running or cannot be reached.
	InitNoSteamClient InitResult = 2
	// InitVersionMismatch indicates a Steamworks SDK/client version mismatch.
	InitVersionMismatch InitResult = 3
)
func (r InitResult) String() string

String returns the Steamworks name for r.

type JoinEvent struct {
	FriendID   uint64
	Connect    string
	FromLaunch bool
}

JoinEvent is delivered when a friend invite or Join Game action triggers GameRichPresenceJoinRequested_t, or when the game was launched with +connect.

type LobbyJoinEvent struct {
	LobbyID    uint64
	FriendID   uint64
	FromLaunch bool
}

LobbyJoinEvent is delivered when a friend lobby invite triggers GameLobbyJoinRequested_t, or when the game was launched with +connect_lobby.

type Options struct {
	// AppID is the game's Steam application ID. When RestartIfNecessary is true
	// and AppID is non-zero, Open calls SteamAPI_RestartAppIfNecessary(AppID)
	// before initializing Steamworks.
	AppID uint32
	// RestartIfNecessary calls SteamAPI_RestartAppIfNecessary(AppID) before
	// SteamAPI_InitFlat when AppID is non-zero. If Steam requests a relaunch,
	// Open returns [ErrRestartRequired] without initializing Steamworks.
	RestartIfNecessary bool
	// LibraryPath overrides the shared library path loaded on desktop targets
	// (libsteam_api.dylib, libsteam_api.so, or steam_api64.dll). When empty,
	// standard locations beside the executable, Contents/Frameworks on macOS,
	// lib64 on Linux, and the system loader path are tried.
	LibraryPath string
	// Args overrides the command-line arguments scanned for +connect and
	// +connect_lobby launch joins. When nil, os.Args[1:] is scanned; pass an
	// empty non-nil slice []string{} to disable launch-argument scanning.
	Args []string
	// Driver replaces dynamic purego library loading with a custom or fake
	// [Driver] (such as [NewFakeDriver] in tests).
	Driver Driver
}

Options configures Open.

type OverlayEvent struct {
	Active        bool
	UserInitiated bool
	AppID         uint32
}

OverlayEvent is delivered when the Steam Overlay opens or closes (GameOverlayActivated_t).

type RawCallback struct {
	SteamUser  int32
	CallbackID int32
	Data       []byte
}

RawCallback is one callback payload dequeued by Driver.NextCallback.

type ShutdownEvent struct{}

ShutdownEvent is delivered when the Steam client notifies the game that it is shutting down (SteamShutdown_t).