rcheevos

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: MIT Imports: 4 Imported by: 8

README

go-rcheevos

Go bindings for rcheevos, the RetroAchievements client library. This package enables Go-based emulators to integrate with RetroAchievements for achievement and leaderboard support.

Features

  • Authentication - Login with password or token
  • Game Identification - Hash ROMs and identify games in the RetroAchievements database
  • Achievements - Track, unlock, and display achievement progress
  • Leaderboards - Submit scores and fetch leaderboard entries
  • Rich Presence - Generate dynamic status messages
  • Multi-disc Support - Handle disc changes for multi-disc games
  • Progress Serialization - Save/restore achievement progress for savestates
  • Subsets - Support for bonus and DLC achievement sets

Requirements

  • Go 1.20+
  • CGO enabled
  • C compiler (gcc, clang, etc.)

Installation

go get github.com/user-none/go-rcheevos

The rcheevos C library is included as a git submodule and compiled automatically via CGO.

Quick Start

package main

import (
    "fmt"
    "net/http"
    "io"

    rcheevos "github.com/user-none/go-rcheevos"
)

func main() {
    // Create client with memory read and HTTP callbacks
    client := rcheevos.NewClient(
        // Memory read callback - return bytes read from emulator memory
        func(address uint32, buffer []byte) uint32 {
            // Read from your emulator's memory here
            return 0
        },
        // Server callback - make HTTP requests to RetroAchievements API
        func(req *rcheevos.ServerRequest) {
            go func() {
                resp, err := http.Get(req.URL)
                if err != nil {
                    req.Respond(nil, 0)
                    return
                }
                defer resp.Body.Close()
                body, _ := io.ReadAll(resp.Body)
                req.Respond(body, resp.StatusCode)
            }()
        },
    )
    defer client.Destroy()

    // Set up event handler for achievement notifications
    client.SetEventHandler(func(event *rcheevos.Event) {
        switch event.Type {
        case rcheevos.EventAchievementTriggered:
            fmt.Printf("Achievement Unlocked: %s\n", event.Achievement.Title)
        case rcheevos.EventGameCompleted:
            fmt.Println("All achievements unlocked!")
        }
    })

    // Login
    done := make(chan error, 1)
    client.LoginWithPassword("username", "password", func(result int, errMsg string) {
        if result != rcheevos.OK {
            done <- fmt.Errorf("login failed: %s", errMsg)
            return
        }
        done <- nil
    })
    if err := <-done; err != nil {
        panic(err)
    }

    // Hash and load game
    hash := rcheevos.HashFromFile(rcheevos.ConsoleNES, "/path/to/rom.nes")
    client.LoadGame(hash, func(result int, errMsg string) {
        // Game loaded, achievements are now active
    })

    // In your emulator's main loop, call DoFrame() every frame
    // client.DoFrame()
}

API Overview

Client Lifecycle
client := rcheevos.NewClient(readMemoryFunc, serverCallFunc)
defer client.Destroy()
Authentication
client.LoginWithPassword(username, password, callback)
client.LoginWithToken(username, token, callback)  // Use stored token for re-login
client.Logout()
user := client.GetUser()  // Get current user info
Game Loading
// Hash a ROM file
hash := rcheevos.HashFromFile(consoleID, "/path/to/rom")
hash := rcheevos.HashFromBuffer(consoleID, romData)

// Load by hash
client.LoadGame(hash, callback)

// Or identify and load in one step
client.IdentifyAndLoadGame(consoleID, filePath, data, callback)

client.UnloadGame()
game := client.GetGame()  // Get current game info
Achievements
client.HasAchievements()
client.GetAchievement(id)
list := client.CreateAchievementList(category, grouping)
defer list.Destroy()
summary := client.GetUserGameSummary()
Leaderboards
client.HasLeaderboards()
client.GetLeaderboard(id)
list := client.CreateLeaderboardList(grouping)
defer list.Destroy()
client.FetchLeaderboardEntries(id, firstEntry, count, callback)
client.FetchLeaderboardEntriesAroundUser(id, count, callback)
Frame Processing
// Call every frame during gameplay
client.DoFrame()

// Call when emulator is paused
client.Idle()

// Reset achievement state (e.g., when user resets the game)
client.Reset()
Rich Presence
if client.HasRichPresence() {
    message := client.GetRichPresenceMessage()
}
Progress Serialization
// Save progress (include in savestates)
data, result := client.SerializeProgress()

// Restore progress (when loading savestates)
result := client.DeserializeProgress(data)
Configuration
client.SetHardcoreEnabled(true)
client.EnableLogging(rcheevos.LogLevelInfo, logFunc)
client.SetReadMemoryFunc(readFunc)

Supported Consoles

The library supports all consoles available in RetroAchievements, including:

  • Nintendo: NES, SNES, N64, Game Boy, GBC, GBA
  • Sega: Master System, Genesis/Mega Drive, Game Gear, Sega CD, 32X
  • Sony: PlayStation
  • NEC: PC Engine/TurboGrafx-16
  • And many more

Use the console constants (e.g., rcheevos.ConsoleNES, rcheevos.ConsoleSNES) when hashing ROMs.

Building

# Build the library
make build

# Run tests
make test

# Build the example
make example

# Update rcheevos submodule to latest
make update-rcheevos

Example

See the example directory for a complete working example that demonstrates login, game loading, and achievement display.

API Coverage

This library wraps the rc_client API from rcheevos, which is the recommended integration path for emulators. The bindings cover approximately 98% of the rc_client functionality.

Not Supported

The following features are not currently exposed:

  • Custom hash callbacks (rc_client_set_hash_callbacks) - For custom file format handling (ZIP, CHD, encrypted ROMs). The default file/CD readers work for standard ROM formats.
  • Achievement iterator (rc_client_get_next_achievement_info) - For iterating achievements by bucket. Use CreateAchievementList() instead.
  • RAIntegration - Windows-only developer tools for achievement creation. Not applicable to cross-platform Go applications.

These are advanced features that most emulator integrations don't require. The core achievement/leaderboard gameplay loop is fully supported.

License

MIT License. See LICENSE for details.

The underlying rcheevos C library has its own license terms.

Documentation

Index

Constants

View Source
const (
	AchievementListGroupingLockState = C.RC_CLIENT_ACHIEVEMENT_LIST_GROUPING_LOCK_STATE
	AchievementListGroupingProgress  = C.RC_CLIENT_ACHIEVEMENT_LIST_GROUPING_PROGRESS
)

Achievement list grouping options

View Source
const (
	AchievementCategoryNone              = C.RC_CLIENT_ACHIEVEMENT_CATEGORY_NONE
	AchievementCategoryCore              = C.RC_CLIENT_ACHIEVEMENT_CATEGORY_CORE
	AchievementCategoryUnofficial        = C.RC_CLIENT_ACHIEVEMENT_CATEGORY_UNOFFICIAL
	AchievementCategoryCoreAndUnofficial = C.RC_CLIENT_ACHIEVEMENT_CATEGORY_CORE_AND_UNOFFICIAL
)

Achievement categories

View Source
const (
	AchievementBucketUnknown          = C.RC_CLIENT_ACHIEVEMENT_BUCKET_UNKNOWN
	AchievementBucketLocked           = C.RC_CLIENT_ACHIEVEMENT_BUCKET_LOCKED
	AchievementBucketUnlocked         = C.RC_CLIENT_ACHIEVEMENT_BUCKET_UNLOCKED
	AchievementBucketUnsupported      = C.RC_CLIENT_ACHIEVEMENT_BUCKET_UNSUPPORTED
	AchievementBucketUnofficial       = C.RC_CLIENT_ACHIEVEMENT_BUCKET_UNOFFICIAL
	AchievementBucketRecentlyUnlocked = C.RC_CLIENT_ACHIEVEMENT_BUCKET_RECENTLY_UNLOCKED
	AchievementBucketActiveChallenge  = C.RC_CLIENT_ACHIEVEMENT_BUCKET_ACTIVE_CHALLENGE
	AchievementBucketAlmostThere      = C.RC_CLIENT_ACHIEVEMENT_BUCKET_ALMOST_THERE
	AchievementBucketUnsynced         = C.RC_CLIENT_ACHIEVEMENT_BUCKET_UNSYNCED
)

Achievement bucket types

View Source
const (
	AchievementTypeStandard    = C.RC_CLIENT_ACHIEVEMENT_TYPE_STANDARD
	AchievementTypeMissable    = C.RC_CLIENT_ACHIEVEMENT_TYPE_MISSABLE
	AchievementTypeProgression = C.RC_CLIENT_ACHIEVEMENT_TYPE_PROGRESSION
	AchievementTypeWin         = C.RC_CLIENT_ACHIEVEMENT_TYPE_WIN
)

Achievement types

View Source
const (
	AchievementUnlockedNone     = C.RC_CLIENT_ACHIEVEMENT_UNLOCKED_NONE
	AchievementUnlockedSoftcore = C.RC_CLIENT_ACHIEVEMENT_UNLOCKED_SOFTCORE
	AchievementUnlockedHardcore = C.RC_CLIENT_ACHIEVEMENT_UNLOCKED_HARDCORE
	AchievementUnlockedBoth     = C.RC_CLIENT_ACHIEVEMENT_UNLOCKED_BOTH
)

Achievement unlock states

View Source
const (
	OK                    = C.RC_OK
	InvalidFuncOperand    = C.RC_INVALID_FUNC_OPERAND
	InvalidMemoryOperand  = C.RC_INVALID_MEMORY_OPERAND
	InvalidConstOperand   = C.RC_INVALID_CONST_OPERAND
	InvalidFPOperand      = C.RC_INVALID_FP_OPERAND
	InvalidConditionType  = C.RC_INVALID_CONDITION_TYPE
	InvalidOperator       = C.RC_INVALID_OPERATOR
	InvalidRequiredHits   = C.RC_INVALID_REQUIRED_HITS
	DuplicatedStart       = C.RC_DUPLICATED_START
	DuplicatedCancel      = C.RC_DUPLICATED_CANCEL
	DuplicatedSubmit      = C.RC_DUPLICATED_SUBMIT
	DuplicatedValue       = C.RC_DUPLICATED_VALUE
	DuplicatedProgress    = C.RC_DUPLICATED_PROGRESS
	MissingStart          = C.RC_MISSING_START
	MissingCancel         = C.RC_MISSING_CANCEL
	MissingSubmit         = C.RC_MISSING_SUBMIT
	MissingValue          = C.RC_MISSING_VALUE
	InvalidLboardField    = C.RC_INVALID_LBOARD_FIELD
	MissingDisplayString  = C.RC_MISSING_DISPLAY_STRING
	OutOfMemory           = C.RC_OUT_OF_MEMORY
	InvalidValueFlag      = C.RC_INVALID_VALUE_FLAG
	MissingValueMeasured  = C.RC_MISSING_VALUE_MEASURED
	MultipleMeasured      = C.RC_MULTIPLE_MEASURED
	InvalidMeasuredTarget = C.RC_INVALID_MEASURED_TARGET
	InvalidComparison     = C.RC_INVALID_COMPARISON
	InvalidState          = C.RC_INVALID_STATE
	InvalidJSON           = C.RC_INVALID_JSON
	APIFailure            = C.RC_API_FAILURE
	LoginRequired         = C.RC_LOGIN_REQUIRED
	NoGameLoaded          = C.RC_NO_GAME_LOADED
	HardcoreDisabled      = C.RC_HARDCORE_DISABLED
	Aborted               = C.RC_ABORTED
	NoResponse            = C.RC_NO_RESPONSE
	AccessDenied          = C.RC_ACCESS_DENIED
	InvalidCredentials    = C.RC_INVALID_CREDENTIALS
	ExpiredToken          = C.RC_EXPIRED_TOKEN
	InsufficientBuffer    = C.RC_INSUFFICIENT_BUFFER
	InvalidVariableName   = C.RC_INVALID_VARIABLE_NAME
	UnknownVariableName   = C.RC_UNKNOWN_VARIABLE_NAME
	NotFound              = C.RC_NOT_FOUND
)

Result codes

View Source
const (
	LeaderboardStateInactive = C.RC_CLIENT_LEADERBOARD_STATE_INACTIVE
	LeaderboardStateActive   = C.RC_CLIENT_LEADERBOARD_STATE_ACTIVE
	LeaderboardStateTracking = C.RC_CLIENT_LEADERBOARD_STATE_TRACKING
	LeaderboardStateDisabled = C.RC_CLIENT_LEADERBOARD_STATE_DISABLED
)

Leaderboard states

View Source
const (
	LeaderboardFormatTime  = C.RC_CLIENT_LEADERBOARD_FORMAT_TIME
	LeaderboardFormatScore = C.RC_CLIENT_LEADERBOARD_FORMAT_SCORE
	LeaderboardFormatValue = C.RC_CLIENT_LEADERBOARD_FORMAT_VALUE
)

Leaderboard formats

View Source
const (
	LeaderboardListGroupingNone     = C.RC_CLIENT_LEADERBOARD_LIST_GROUPING_NONE
	LeaderboardListGroupingTracking = C.RC_CLIENT_LEADERBOARD_LIST_GROUPING_TRACKING
)

Leaderboard list grouping options

View Source
const (
	LeaderboardBucketUnknown     = C.RC_CLIENT_LEADERBOARD_BUCKET_UNKNOWN
	LeaderboardBucketInactive    = C.RC_CLIENT_LEADERBOARD_BUCKET_INACTIVE
	LeaderboardBucketActive      = C.RC_CLIENT_LEADERBOARD_BUCKET_ACTIVE
	LeaderboardBucketUnsupported = C.RC_CLIENT_LEADERBOARD_BUCKET_UNSUPPORTED
	LeaderboardBucketAll         = C.RC_CLIENT_LEADERBOARD_BUCKET_ALL
)

Leaderboard bucket types

View Source
const (
	LoadGameStateNone            = C.RC_CLIENT_LOAD_GAME_STATE_NONE
	LoadGameStateAwaitLogin      = C.RC_CLIENT_LOAD_GAME_STATE_AWAIT_LOGIN
	LoadGameStateIdentifying     = C.RC_CLIENT_LOAD_GAME_STATE_IDENTIFYING_GAME
	LoadGameStateFetchingData    = C.RC_CLIENT_LOAD_GAME_STATE_FETCHING_GAME_DATA
	LoadGameStateStartingSession = C.RC_CLIENT_LOAD_GAME_STATE_STARTING_SESSION
	LoadGameStateDone            = C.RC_CLIENT_LOAD_GAME_STATE_DONE
	LoadGameStateAborted         = C.RC_CLIENT_LOAD_GAME_STATE_ABORTED
)

Load game state constants

View Source
const (
	ConsoleUnknown      = C.RC_CONSOLE_UNKNOWN
	ConsoleMegaDrive    = C.RC_CONSOLE_MEGA_DRIVE
	ConsoleNintendo64   = C.RC_CONSOLE_NINTENDO_64
	ConsoleSNES         = C.RC_CONSOLE_SUPER_NINTENDO
	ConsoleGameBoy      = C.RC_CONSOLE_GAMEBOY
	ConsoleGBA          = C.RC_CONSOLE_GAMEBOY_ADVANCE
	ConsoleGBC          = C.RC_CONSOLE_GAMEBOY_COLOR
	ConsoleNES          = C.RC_CONSOLE_NINTENDO
	ConsolePCEngine     = C.RC_CONSOLE_PC_ENGINE
	ConsoleSegaCD       = C.RC_CONSOLE_SEGA_CD
	ConsoleSega32X      = C.RC_CONSOLE_SEGA_32X
	ConsoleMasterSystem = C.RC_CONSOLE_MASTER_SYSTEM
	ConsolePlayStation  = C.RC_CONSOLE_PLAYSTATION
	ConsoleGameGear     = C.RC_CONSOLE_GAME_GEAR
	ConsoleSG1000       = C.RC_CONSOLE_SG1000
)

Console IDs

View Source
const (
	LogLevelNone    = C.RC_CLIENT_LOG_LEVEL_NONE
	LogLevelError   = C.RC_CLIENT_LOG_LEVEL_ERROR
	LogLevelWarn    = C.RC_CLIENT_LOG_LEVEL_WARN
	LogLevelInfo    = C.RC_CLIENT_LOG_LEVEL_INFO
	LogLevelVerbose = C.RC_CLIENT_LOG_LEVEL_VERBOSE
)

Log levels

View Source
const (
	EventAchievementTriggered               = C.RC_CLIENT_EVENT_ACHIEVEMENT_TRIGGERED
	EventLeaderboardStarted                 = C.RC_CLIENT_EVENT_LEADERBOARD_STARTED
	EventLeaderboardFailed                  = C.RC_CLIENT_EVENT_LEADERBOARD_FAILED
	EventLeaderboardSubmitted               = C.RC_CLIENT_EVENT_LEADERBOARD_SUBMITTED
	EventAchievementChallengeIndicatorShow  = C.RC_CLIENT_EVENT_ACHIEVEMENT_CHALLENGE_INDICATOR_SHOW
	EventAchievementChallengeIndicatorHide  = C.RC_CLIENT_EVENT_ACHIEVEMENT_CHALLENGE_INDICATOR_HIDE
	EventAchievementProgressIndicatorShow   = C.RC_CLIENT_EVENT_ACHIEVEMENT_PROGRESS_INDICATOR_SHOW
	EventAchievementProgressIndicatorHide   = C.RC_CLIENT_EVENT_ACHIEVEMENT_PROGRESS_INDICATOR_HIDE
	EventAchievementProgressIndicatorUpdate = C.RC_CLIENT_EVENT_ACHIEVEMENT_PROGRESS_INDICATOR_UPDATE
	EventLeaderboardTrackerShow             = C.RC_CLIENT_EVENT_LEADERBOARD_TRACKER_SHOW
	EventLeaderboardTrackerHide             = C.RC_CLIENT_EVENT_LEADERBOARD_TRACKER_HIDE
	EventLeaderboardTrackerUpdate           = C.RC_CLIENT_EVENT_LEADERBOARD_TRACKER_UPDATE
	EventReset                              = C.RC_CLIENT_EVENT_RESET
	EventGameCompleted                      = C.RC_CLIENT_EVENT_GAME_COMPLETED
	EventServerError                        = C.RC_CLIENT_EVENT_SERVER_ERROR
	EventDisconnected                       = C.RC_CLIENT_EVENT_DISCONNECTED
	EventReconnected                        = C.RC_CLIENT_EVENT_RECONNECTED
)

Event types

View Source
const (
	AchievementStateInactive = C.RC_CLIENT_ACHIEVEMENT_STATE_INACTIVE
	AchievementStateActive   = C.RC_CLIENT_ACHIEVEMENT_STATE_ACTIVE
	AchievementStateUnlocked = C.RC_CLIENT_ACHIEVEMENT_STATE_UNLOCKED
	AchievementStateDisabled = C.RC_CLIENT_ACHIEVEMENT_STATE_DISABLED
)

Achievement states

Variables

This section is empty.

Functions

func ConsoleName

func ConsoleName(consoleID uint32) string

ConsoleName returns the name for a console ID

func ErrorString

func ErrorString(result int) string

ErrorString returns the error message for a result code

func HashFromBuffer

func HashFromBuffer(consoleID uint32, data []byte) string

HashFromBuffer generates a hash from ROM data for a specific console

func HashFromFile

func HashFromFile(consoleID uint32, path string) string

HashFromFile generates a hash from a ROM file for a specific console

func LoadGameStateName

func LoadGameStateName(state int) string

LoadGameStateName returns a human-readable name for a load game state

Types

type Achievement

type Achievement struct {
	ID               uint32
	Title            string
	Description      string
	BadgeName        string
	Points           uint32
	State            uint8
	Category         uint8
	Bucket           uint8
	Unlocked         uint8
	Type             uint8
	MeasuredProgress string
	MeasuredPercent  float32
	Rarity           float32
	RarityHardcore   float32
	UnlockTime       int64
}

Achievement represents achievement information

type AchievementBucket

type AchievementBucket struct {
	Achievements []*Achievement
	Label        string
	SubsetID     uint32
	BucketType   uint8
}

AchievementBucket represents a group of achievements

type AchievementList

type AchievementList struct {
	Buckets []*AchievementBucket
	// contains filtered or unexported fields
}

AchievementList represents a list of achievement buckets

func (*AchievementList) Destroy

func (l *AchievementList) Destroy()

Destroy releases resources associated with the achievement list.

func (*AchievementList) GetAllAchievements

func (l *AchievementList) GetAllAchievements() []*Achievement

GetAllAchievements returns a flat slice of all achievements across all buckets.

type AllUserProgress

type AllUserProgress struct {
	Entries []*UserProgressEntry
	// contains filtered or unexported fields
}

AllUserProgress represents a user's progress across all games for a console

func (*AllUserProgress) Destroy

func (l *AllUserProgress) Destroy()

Destroy releases resources associated with the user progress list.

type AsyncHandle

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

AsyncHandle represents an async operation that can be aborted

type ChangeMediaCallback

type ChangeMediaCallback func(result int, errorMessage string)

ChangeMediaCallback is called when media change completes

type Client

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

Client wraps the rc_client

func NewClient

func NewClient(readMemory ReadMemoryFunc, serverCall ServerCallFunc) *Client

NewClient creates a new rcheevos client

func (*Client) AbortAsync

func (c *Client) AbortAsync(handle *AsyncHandle)

AbortAsync marks an async process as aborted. The associated callback will not be called. Pass the async handle returned by login/load game functions.

func (*Client) CanPause

func (c *Client) CanPause() (allowed bool, framesRemaining uint32)

CanPause determines if a sufficient number of frames have been processed since the last call to CanPause. This is used for hardcore anti-cheat to prevent pausing mid-leaderboard attempt.

Returns true if pausing is allowed, false if not. If false, framesRemaining indicates how many more frames must be processed before pausing is allowed (can be converted to seconds for display).

Only call this when the user is actually trying to pause.

func (*Client) ChangeMedia

func (c *Client) ChangeMedia(hash string, callback ChangeMediaCallback)

ChangeMedia changes the active disc in a multi-disc game using a known hash. This allows achievements to span multiple discs.

func (*Client) CreateAchievementList

func (c *Client) CreateAchievementList(category, grouping int) *AchievementList

CreateAchievementList creates a list of achievements matching the specified category and grouping. Category should be one of AchievementCategoryCore, AchievementCategoryUnofficial, or AchievementCategoryCoreAndUnofficial. Grouping should be AchievementListGroupingLockState or AchievementListGroupingProgress. The returned list must be destroyed by calling Destroy() when no longer needed.

func (*Client) CreateLeaderboardList

func (c *Client) CreateLeaderboardList(grouping int) *LeaderboardList

CreateLeaderboardList creates a list of leaderboards matching the specified grouping. Grouping should be LeaderboardListGroupingNone or LeaderboardListGroupingTracking. The returned list must be destroyed by calling Destroy() when no longer needed.

func (*Client) CreateSubsetList

func (c *Client) CreateSubsetList() *SubsetList

CreateSubsetList creates a list of all subsets for the currently loaded game. The returned list must be destroyed by calling Destroy() when no longer needed.

func (*Client) DeserializeProgress

func (c *Client) DeserializeProgress(data []byte) int

DeserializeProgress restores the runtime state from a buffer. This should be called when loading a savestate to restore achievement progress. Returns OK on success, or an error code on failure.

func (*Client) Destroy

func (c *Client) Destroy()

Destroy releases resources associated with the client

func (*Client) DoFrame

func (c *Client) DoFrame()

DoFrame processes achievements for the current frame

func (*Client) EnableLogging

func (c *Client) EnableLogging(level int, logFunc LogFunc)

EnableLogging enables logging at the specified level

func (*Client) FetchAllUserProgress

func (c *Client) FetchAllUserProgress(consoleID uint32, callback FetchAllUserProgressCallback)

FetchAllUserProgress fetches the user's progress for all games on a console. This is useful for displaying a game browser with completion percentages. The callback receives an allocated list that must be destroyed by calling Destroy().

func (*Client) FetchGameTitles

func (c *Client) FetchGameTitles(gameIDs []uint32, callback FetchGameTitlesCallback)

FetchGameTitles fetches titles and badges for the specified game IDs. This is useful for displaying a library with game names/icons. The callback receives an allocated list that must be destroyed by calling Destroy().

func (*Client) FetchHashLibrary

func (c *Client) FetchHashLibrary(consoleID uint32, callback FetchHashLibraryCallback)

FetchHashLibrary fetches all known hashes for a console. This can be used to build a game database or identify ROMs offline. The callback receives an allocated library that must be destroyed by calling Destroy().

func (*Client) FetchLeaderboardEntries

func (c *Client) FetchLeaderboardEntries(leaderboardID uint32, firstEntry, count uint32, callback LeaderboardEntriesCallback)

FetchLeaderboardEntries fetches leaderboard entries from the server. firstEntry is 1-based (1 = first entry). count is the number of entries to fetch. The callback receives an allocated list that must be destroyed by calling Destroy().

func (*Client) FetchLeaderboardEntriesAroundUser

func (c *Client) FetchLeaderboardEntriesAroundUser(leaderboardID uint32, count uint32, callback LeaderboardEntriesCallback)

FetchLeaderboardEntriesAroundUser fetches leaderboard entries surrounding the current user. count is the total number of entries to fetch (user will be approximately in the middle). The callback receives an allocated list that must be destroyed by calling Destroy().

func (*Client) GetAchievement

func (c *Client) GetAchievement(id uint32) *Achievement

GetAchievement returns achievement info by ID

func (*Client) GetAchievementImageURL

func (c *Client) GetAchievementImageURL(achievement *Achievement, state int) string

GetAchievementImageURL returns the URL for an achievement's badge image. Pass AchievementStateUnlocked for the unlocked badge, or AchievementStateLocked for the locked/grayscale badge.

func (*Client) GetEncoreModeEnabled

func (c *Client) GetEncoreModeEnabled() bool

GetEncoreModeEnabled returns whether encore mode is enabled.

func (*Client) GetGame

func (c *Client) GetGame() *Game

GetGame returns the current game info, or nil if no game is loaded

func (*Client) GetGameImageURL

func (c *Client) GetGameImageURL() string

GetGameImageURL returns the URL for the game's badge/box art image.

func (*Client) GetHardcoreEnabled

func (c *Client) GetHardcoreEnabled() bool

GetHardcoreEnabled returns whether hardcore mode is enabled

func (*Client) GetLeaderboard

func (c *Client) GetLeaderboard(id uint32) *Leaderboard

GetLeaderboard returns leaderboard info by ID

func (*Client) GetLoadGameState

func (c *Client) GetLoadGameState() int

GetLoadGameState returns the current progress of the asynchronous load game process.

func (*Client) GetRichPresenceMessage

func (c *Client) GetRichPresenceMessage() string

GetRichPresenceMessage returns the current rich presence message

func (*Client) GetSpectatorModeEnabled

func (c *Client) GetSpectatorModeEnabled() bool

GetSpectatorModeEnabled returns whether spectator mode is enabled.

func (*Client) GetSubsetInfo

func (c *Client) GetSubsetInfo(subsetID uint32) *Subset

GetSubsetInfo returns information about a specific subset.

func (*Client) GetUnofficialEnabled

func (c *Client) GetUnofficialEnabled() bool

GetUnofficialEnabled returns whether unofficial achievements are enabled.

func (*Client) GetUser

func (c *Client) GetUser() *User

GetUser returns the current user info, or nil if not logged in

func (*Client) GetUserAgentClause

func (c *Client) GetUserAgentClause() string

GetUserAgentClause returns a string that can be added to the User-Agent header to identify the rcheevos version being used.

func (*Client) GetUserGameSummary

func (c *Client) GetUserGameSummary() *UserGameSummary

GetUserGameSummary returns a summary of the user's progress in the current game. This is used for displaying "You have unlocked X of Y achievements" messages.

func (*Client) GetUserImageURL

func (c *Client) GetUserImageURL() string

GetUserImageURL returns the URL for the current user's avatar.

func (*Client) GetUserSubsetSummary

func (c *Client) GetUserSubsetSummary(subsetID uint32) *UserGameSummary

GetUserSubsetSummary returns a summary of the user's progress in a specific subset.

func (*Client) GetUserdata

func (c *Client) GetUserdata() unsafe.Pointer

GetUserdata returns the client-specific data attached to the runtime.

func (*Client) HasAchievements

func (c *Client) HasAchievements() bool

HasAchievements returns whether the game has achievements

func (*Client) HasLeaderboards

func (c *Client) HasLeaderboards() bool

HasLeaderboards returns whether the game has leaderboards

func (*Client) HasRichPresence

func (c *Client) HasRichPresence() bool

HasRichPresence returns whether the game supports rich presence

func (*Client) IdentifyAndChangeMedia

func (c *Client) IdentifyAndChangeMedia(filePath string, data []byte, callback ChangeMediaCallback)

IdentifyAndChangeMedia identifies and changes the active disc in a multi-disc game. Either filePath or data should be provided (not both).

func (*Client) IdentifyAndLoadGame

func (c *Client) IdentifyAndLoadGame(consoleID uint32, filePath string, data []byte, callback LoadGameCallbackFunc)

IdentifyAndLoadGame identifies a game by ROM data and loads it

func (*Client) Idle

func (c *Client) Idle()

Idle processes the periodic queue (call when paused)

func (*Client) IsGameLoaded

func (c *Client) IsGameLoaded() bool

IsGameLoaded returns whether a game is currently loaded

func (*Client) IsProcessingRequired

func (c *Client) IsProcessingRequired() bool

IsProcessingRequired returns whether there are any active achievements, leaderboards, or rich presence that need processing. Can be used to skip DoFrame calls when nothing needs to be evaluated.

func (*Client) LoadGame

func (c *Client) LoadGame(hash string, callback LoadGameCallbackFunc)

LoadGame starts loading a game by hash

func (*Client) LoginWithPassword

func (c *Client) LoginWithPassword(username, password string, callback LoginCallbackFunc)

LoginWithPassword starts a login with username and password

func (*Client) LoginWithToken

func (c *Client) LoginWithToken(username, token string, callback LoginCallbackFunc)

LoginWithToken starts a login with username and token

func (*Client) Logout

func (c *Client) Logout()

Logout logs out the current user

func (*Client) ProgressSize

func (c *Client) ProgressSize() int

ProgressSize returns the number of bytes needed to serialize the runtime state. Use this to allocate a buffer for SerializeProgress.

func (*Client) Reset

func (c *Client) Reset()

Reset resets the runtime state

func (*Client) SerializeProgress

func (c *Client) SerializeProgress() ([]byte, int)

SerializeProgress serializes the runtime state into a buffer. This should be called when creating a savestate to preserve achievement progress. Returns the serialized data, or nil and an error code on failure.

func (*Client) SetAllowBackgroundMemoryReads

func (c *Client) SetAllowBackgroundMemoryReads(allowed bool)

SetAllowBackgroundMemoryReads specifies whether rcheevos is allowed to read memory outside of DoFrame/Idle calls. This is used for async processing.

func (*Client) SetEncoreModeEnabled

func (c *Client) SetEncoreModeEnabled(enabled bool)

SetEncoreModeEnabled enables or disables encore mode. When enabled, achievements can be re-triggered even if already unlocked. Must be set before loading a game.

func (*Client) SetEventHandler

func (c *Client) SetEventHandler(handler EventFunc)

SetEventHandler sets the event callback

func (*Client) SetGetTimeMillisecsFunction

func (c *Client) SetGetTimeMillisecsFunction(fn GetTimeMillisecsFunc)

SetGetTimeMillisecsFunction sets a custom function to get the current time in milliseconds. This is used for accurate leaderboard timing. If not set, the default system time is used.

func (*Client) SetHardcoreEnabled

func (c *Client) SetHardcoreEnabled(enabled bool)

SetHardcoreEnabled enables or disables hardcore mode

func (*Client) SetHost

func (c *Client) SetHost(hostname string)

SetHost sets the server hostname to use. Pass empty string to use the default RetroAchievements server.

func (*Client) SetReadMemoryFunction

func (c *Client) SetReadMemoryFunction(fn ReadMemoryFunc)

SetReadMemoryFunction changes the memory read callback. This allows changing the memory source after the client is created.

func (*Client) SetSpectatorModeEnabled

func (c *Client) SetSpectatorModeEnabled(enabled bool)

SetSpectatorModeEnabled enables or disables spectator mode. In spectator mode, events fire locally but nothing is submitted to the server. Can be toggled while a game is loaded.

func (*Client) SetUnofficialEnabled

func (c *Client) SetUnofficialEnabled(enabled bool)

SetUnofficialEnabled enables or disables loading of unofficial achievements. Unofficial achievements are community-created and not part of the official set. Must be set before loading a game.

func (*Client) SetUserdata

func (c *Client) SetUserdata(userdata unsafe.Pointer)

SetUserdata attaches client-specific data to the runtime. This can be retrieved later with GetUserdata.

func (*Client) UnloadGame

func (c *Client) UnloadGame()

UnloadGame unloads the current game

type Event

type Event struct {
	Type                  uint32
	Achievement           *Achievement
	Leaderboard           *Leaderboard
	LeaderboardTracker    *LeaderboardTracker
	LeaderboardScoreboard *LeaderboardScoreboard
	ServerError           *ServerError
	Subset                *EventSubset
}

Event represents an achievement event

type EventFunc

type EventFunc func(event *Event)

EventFunc is called when achievement events occur

type EventSubset

type EventSubset struct {
	ID    uint32
	Title string
}

EventSubset represents subset info in an event

type FetchAllUserProgressCallback

type FetchAllUserProgressCallback func(result int, errorMessage string, progress *AllUserProgress)

FetchAllUserProgressCallback is called when the user progress fetch completes

type FetchGameTitlesCallback

type FetchGameTitlesCallback func(result int, errorMessage string, titles *GameTitleList)

FetchGameTitlesCallback is called when the game titles fetch completes

type FetchHashLibraryCallback

type FetchHashLibraryCallback func(result int, errorMessage string, library *HashLibrary)

FetchHashLibraryCallback is called when the hash library fetch completes

type Game

type Game struct {
	ID        uint32
	ConsoleID uint32
	Title     string
	Hash      string
	BadgeName string
}

Game represents game information

type GameTitleEntry

type GameTitleEntry struct {
	GameID    uint32
	Title     string
	BadgeName string
	BadgeURL  string
}

GameTitleEntry represents a game's title and badge information

type GameTitleList

type GameTitleList struct {
	Entries []*GameTitleEntry
	// contains filtered or unexported fields
}

GameTitleList represents a collection of game titles

func (*GameTitleList) Destroy

func (l *GameTitleList) Destroy()

Destroy releases resources associated with the game title list.

type GetTimeMillisecsFunc

type GetTimeMillisecsFunc func() uint64

GetTimeMillisecsFunc returns the current time in milliseconds. Used for accurate leaderboard timing.

type HashIterator

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

HashIterator is used to generate hashes for ROM identification

func NewHashIterator

func NewHashIterator(path string) *HashIterator

NewHashIterator creates a new hash iterator for a file path

func NewHashIteratorFromBuffer

func NewHashIteratorFromBuffer(path string, data []byte) *HashIterator

NewHashIteratorFromBuffer creates a new hash iterator from memory

func (*HashIterator) Destroy

func (h *HashIterator) Destroy()

Destroy releases resources associated with the iterator

func (*HashIterator) GenerateHash

func (h *HashIterator) GenerateHash(consoleID uint32) string

GenerateHash generates a hash for the specified console from the iterator

func (*HashIterator) Next

func (h *HashIterator) Next() string

Next generates the next hash. Returns empty string if no more hashes.

type HashLibrary

type HashLibrary struct {
	Entries []*HashLibraryEntry
	// contains filtered or unexported fields
}

HashLibrary represents a collection of hash-to-game mappings for a console

func (*HashLibrary) Destroy

func (l *HashLibrary) Destroy()

Destroy releases resources associated with the hash library.

type HashLibraryEntry

type HashLibraryEntry struct {
	Hash   string
	GameID uint32
}

HashLibraryEntry represents a mapping from hash to game ID

type Leaderboard

type Leaderboard struct {
	ID            uint32
	Title         string
	Description   string
	TrackerValue  string
	State         uint8
	Format        uint8
	LowerIsBetter bool
}

Leaderboard represents leaderboard information

type LeaderboardBucket

type LeaderboardBucket struct {
	Leaderboards []*Leaderboard
	Label        string
	SubsetID     uint32
	BucketType   uint8
}

LeaderboardBucket represents a group of leaderboards

type LeaderboardEntriesCallback

type LeaderboardEntriesCallback func(result int, errorMessage string, entries *LeaderboardEntryList)

LeaderboardEntriesCallback is called when leaderboard entries are fetched

type LeaderboardEntry

type LeaderboardEntry struct {
	User      string
	Display   string
	Submitted time.Time
	Rank      uint32
	Index     uint32
}

LeaderboardEntry represents a single entry in a leaderboard

func (*LeaderboardEntry) GetUserImageURL

func (e *LeaderboardEntry) GetUserImageURL() string

GetUserImageURL returns the URL for a leaderboard entry user's avatar.

type LeaderboardEntryList

type LeaderboardEntryList struct {
	Entries      []*LeaderboardEntry
	TotalEntries uint32
	UserIndex    int32 // -1 if user not in list
	// contains filtered or unexported fields
}

LeaderboardEntryList represents a list of leaderboard entries

func (*LeaderboardEntryList) Destroy

func (l *LeaderboardEntryList) Destroy()

Destroy releases resources associated with the leaderboard entry list.

type LeaderboardList

type LeaderboardList struct {
	Buckets []*LeaderboardBucket
	// contains filtered or unexported fields
}

LeaderboardList represents a list of leaderboard buckets

func (*LeaderboardList) Destroy

func (l *LeaderboardList) Destroy()

Destroy releases resources associated with the leaderboard list.

func (*LeaderboardList) GetAllLeaderboards

func (l *LeaderboardList) GetAllLeaderboards() []*Leaderboard

GetAllLeaderboards returns a flat slice of all leaderboards across all buckets.

type LeaderboardScoreboard

type LeaderboardScoreboard struct {
	LeaderboardID  uint32
	SubmittedScore string
	BestScore      string
	NewRank        uint32
	NumEntries     uint32
	TopEntries     []*LeaderboardScoreboardEntry
}

LeaderboardScoreboard represents scoreboard data after a leaderboard submission

type LeaderboardScoreboardEntry

type LeaderboardScoreboardEntry struct {
	Username string
	Rank     uint32
	Score    string
}

LeaderboardScoreboardEntry represents a single entry in the scoreboard

type LeaderboardTracker

type LeaderboardTracker struct {
	ID      uint32
	Display string
}

LeaderboardTracker represents a leaderboard tracker display

type LoadGameCallbackFunc

type LoadGameCallbackFunc func(result int, errorMessage string)

LoadGameCallbackFunc is called when game loading completes

type LogFunc

type LogFunc func(message string)

LogFunc is called for logging

type LoginCallbackFunc

type LoginCallbackFunc func(result int, errorMessage string)

LoginCallbackFunc is called when login completes

type ReadMemoryFunc

type ReadMemoryFunc func(address uint32, buffer []byte) uint32

ReadMemoryFunc is called by rcheevos to read emulator memory

type ServerCallFunc

type ServerCallFunc func(request *ServerRequest)

ServerCallFunc is called by rcheevos to make HTTP requests to the RetroAchievements API

type ServerError

type ServerError struct {
	ErrorMessage string
	API          string
	Result       int
	RelatedID    uint32
}

ServerError represents an API error

type ServerRequest

type ServerRequest struct {
	URL         string
	PostData    string
	ContentType string
	// contains filtered or unexported fields
}

ServerRequest represents an HTTP request to the RetroAchievements API

func (*ServerRequest) Respond

func (r *ServerRequest) Respond(body []byte, httpStatus int)

Respond sends the server response back to rcheevos

type Subset

type Subset struct {
	ID              uint32
	Title           string
	BadgeName       string
	NumAchievements uint32
	NumLeaderboards uint32
}

Subset represents a game subset (e.g., "Base Game", "Bonus", "Challenge Mode")

type SubsetList

type SubsetList struct {
	Subsets []*Subset
	// contains filtered or unexported fields
}

SubsetList represents a list of subsets for the current game

func (*SubsetList) Destroy

func (l *SubsetList) Destroy()

Destroy releases resources associated with the subset list.

type User

type User struct {
	DisplayName   string
	Username      string
	Token         string
	Score         uint32
	ScoreSoftcore uint32
}

User represents user information

type UserGameSummary

type UserGameSummary struct {
	NumCoreAchievements        uint32
	NumUnofficialAchievements  uint32
	NumUnlockedAchievements    uint32
	NumUnsupportedAchievements uint32
	PointsCore                 uint32
	PointsUnlocked             uint32
}

UserGameSummary contains summary information about the user's progress in the current game.

type UserProgressEntry

type UserProgressEntry struct {
	GameID                          uint32
	NumAchievements                 uint32
	NumUnlockedAchievements         uint32
	NumUnlockedAchievementsHardcore uint32
}

UserProgressEntry represents a user's progress in a single game

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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