Skip to main content

Crate libretro_core

Crate libretro_core 

Source
Expand description

Minimal libretro wrapper for implementing Rust cores.

The crate exposes typed Rust wrappers for libretro.h plus a trait/macro pair for exporting the required retro_* symbols from a Rust core.

Methodology:

  • Keep public APIs Rust-first even when the underlying libretro ABI is C-first.
  • Prefer strings, slices, enums, and return values over raw pointers or mutable out-params whenever the wrapper can do that conversion centrally.
  • Keep raw ABI details private unless exposing them is necessary for a real core-development use case.
  • Match libretro/OpenGL naming where it helps recognition, but not at the cost of forcing callers back into manual FFI plumbing.

API map:

  • Core, Runtime, Environment, and export_core! are the primary core authoring surface.
  • ContentContract, SystemInfo, GameInfo, and SystemAvInfo describe startup metadata, content loading, geometry, and timing.
  • Input polling uses Runtime helpers with typed devices such as JoypadButton, AnalogStick, MouseButton, and PointerAxis.
  • Event-shaped frontend callbacks are registered through CoreEventConfig with DOM-style listener methods such as CoreEventConfig::add_keyboard_event_listener; callback-shaped frontend hooks with one active registration, such as frame timing, use explicit set_*_callback methods.
  • Optional frontend services are exposed as typed interfaces such as VfsInterface, MidiInterface, MicrophoneInterface, PerfInterface, SensorInterface, LocationInterface, and CameraInterface.
  • Hardware rendering uses HwRenderConfig for context negotiation and Gl for typed OpenGL access.
use libretro::{
    ContentContract, Core, CoreEventConfig, Environment, GameGeometry, HwRenderConfig,
    JoypadButton, KeyboardEvent, PixelFormat, Runtime, SystemAvInfo, SystemInfo, SystemTiming,
    VariableDefinition,
};

#[derive(Default)]
struct GlCore {
    width: u32,
    height: u32,
}

impl Core for GlCore {
    fn system_info(&self) -> SystemInfo {
        let mut info = SystemInfo::new("TestCore GL", "v1");
        info.need_fullpath = false;
        info
    }

    fn av_info(&self) -> SystemAvInfo {
        SystemAvInfo {
            geometry: GameGeometry {
                base_width: 320,
                base_height: 240,
                max_width: 1024,
                max_height: 1024,
                aspect_ratio: 4.0 / 3.0,
            },
            timing: SystemTiming {
                fps: 60.0,
                sample_rate: 0.0,
            },
        }
    }

    fn configure_events(&mut self, events: &mut CoreEventConfig<Self>) {
        events.add_keyboard_event_listener(Self::keyboard_event);
    }

    fn on_set_environment(&mut self, env: &mut Environment<'_>) {
        ContentContract::new("bin")
            .with_support_no_game(true)
            .with_persistent_data(true)
            .register_environment(env);
        env.set_variables(&[VariableDefinition::new(
            "testgl_resolution",
            "Internal resolution; 320x240|640x480|1024x768",
        )]);
    }

    fn load_game(
        &mut self,
        _game: Option<libretro::GameInfo<'_>>,
        runtime: &mut Runtime<'_>,
    ) -> bool {
        let mut env = runtime.environment();
        env.set_pixel_format(PixelFormat::Xrgb8888)
            && env
                .set_hw_render_from_candidates(&[
                    HwRenderConfig::opengl()
                        .with_depth(true)
                        .with_stencil(true)
                        .with_bottom_left_origin(true),
                    HwRenderConfig::opengles3()
                        .with_depth(true)
                        .with_stencil(true)
                        .with_bottom_left_origin(true),
                ])
                .is_some()
    }

    fn run(&mut self, runtime: &mut Runtime<'_>) {
        runtime.poll_input();
        if runtime.joypad_pressed(0, JoypadButton::Up) {
            // update state
        }
        runtime.video_refresh_hw(self.width, self.height, 0);
    }

    fn keyboard_event(&mut self, event: KeyboardEvent) {
        if event.down {
            // handle typed keyboard event
        }
    }
}

libretro::export_core!(GlCore::default());

Macros§

export_core
Export a Core implementation as the required libretro retro_* symbols.

Structs§

AudioBufferOccupancy
AudioBufferStatus
AudioLatencyMillis
AudioSampleRateHz
CameraFrameSize
CameraInterface
CameraRawFrame
CameraRequest
CameraTextureFrame
CameraTextureId
CameraTextureTarget
CheatCode
CheatIndex
CompatGl
GLES2-era drawing symbols for simple compatibility rendering.
CompatGlClear
Minimal GL entry points needed for legal hardware framebuffer setup.
CompatTextureGl
Texture/uniform/blend symbols layered on top of CompatGl.
ContentContract
ContentInfoOverride
Per-extension content override registered with the frontend.
ControllerDescription
ControllerDeviceSubclass
ControllerInfo
CoreEventConfig
Event-listener registration for frontend-to-core notifications.
CoreOptionCategory
CoreOptionDefinition
CoreOptionDisplay
CoreOptionValue
CoreOptions
CoreOptionsVersion
CoreProcAddress
DevicePower
DiskControlInterfaceVersion
DiskIndex
EmulatedAddress
Environment
Typed wrapper around libretro environment commands.
ExtendedGameInfo
ExtendedMessage
FakeAttachShaderCall
FakeBindAttribLocationCall
FakeBindBufferBaseCall
FakeBindBufferRangeCall
FakeBlendEquationSeparateCall
FakeBlendFuncSeparateCall
FakeCopyBufferSubDataCall
FakeCreateShaderCall
FakeDrawArraysCall
FakeDrawElementsCall
FakeGlConfig
FakeGlSnapshot
FakeVertexAttribPointerCall
FastForwardRatio
FastForwardingOverride
FrameTime
GameGeometry
GameInfo
Gl
Ergonomic OpenGL access for libretro hardware-rendered cores.
GlBuffer
GlBufferBindingIndex
GlBufferByteOffset
GlBufferByteSize
GlBufferRange
GlColorWriteMask
GlDrawRange
GlElementByteOffset
GlElementRange
GlElementVertexRange
GlFramebuffer
GlInstanceCount
GlPolygonOffset
GlProgram
GlQuery
GlRect
GlRenderbuffer
GlRenderbufferSize
GlShader
GlStencilMask
GlStencilReference
GlSync
GlSyncTimeout
GlTexture
GlTextureLevel
GlTextureOffset2D
GlTextureOffset3D
GlTextureSize2D
GlTextureSize3D
GlTextureUnit
GlUniformLocation
GlVersionInfo
GlVertexArray
GlVertexAttribByteOffset
GlVertexAttribDivisor
GlVertexAttribF32Layout
GlVertexAttribLocation
GlVertexAttribStride
HwRenderConfig
Hardware-rendering context request sent to the frontend.
HwRenderContextNegotiationInterface
HwRenderInterface
InputDescriptor
InputDescriptorId
InputDescriptorIndex
InputPort
JoypadButtonSet
KeyboardCharacter
KeyboardEvent
LedIndex
LedInterface
LocationInterface
LocationIntervalMeters
LocationIntervalMillis
LocationPosition
Logger
Frontend logger with stderr fallback.
MemoryMapDescriptor
MemoryMapLen
MemoryMapMask
MemoryMapOffset
Microphone
MicrophoneInterface
MicrophoneParams
MicrophoneRateHz
MidiDeltaMicros
MidiInterface
Netpacket
NetpacketFlags
NetpacketSession
NetplayClientId
PerfCounter
PerfInterface
PerfTick
PerfTimeMicros
PerformanceLevel
PointerIndex
PreferredHwRender
RawAudioBufferStatusCallback
RawAudioCallback
RawContentInfoOverride
RawFrameTimeCallback
RawGameInfo
RawHwRenderCallback
RawInputDescriptor
RawKeyboardCallback
RawLogCallback
RawMessage
RawSystemInfo
RawVariable
RefreshRateHz
RumbleInterface
RumbleStrength
RunLoopRateHz
Runtime
Per-frame access to frontend callbacks and services.
SensorInterface
SensorRateHz
SoftwareFramebuffer
SoftwareFramebufferRequest
SubsystemId
SubsystemInfo
SubsystemMemoryInfo
SubsystemMemoryType
SubsystemRomInfo
SystemAvInfo
SystemInfo
Static metadata returned to the frontend by Core::system_info.
SystemTiming
ThrottleState
VariableDefinition
VfsDirectory
VfsFile
VfsInterface
VfsInterfaceVersion
VfsMetadata
glsym
Typed OpenGL symbol table resolved from libretro’s hardware-render callbacks.

Enums§

AnalogAxis
AnalogStick
AudioCallbackState
AvEnable
CameraCapability
ControllerDevice
CoreMemory
CoreOptionsBuildError
CpuFeature
DiskTrayState
FramebufferMemoryAccess
FramebufferMemoryType
GlBlendEquation
GlBlendFactor
GlBufferTarget
GlBufferUsage
GlCapability
GlCullFaceMode
GlDepthFunction
GlDrawMode
GlFramebufferAttachment
GlFramebufferBuffer
GlFramebufferTarget
GlFramebufferTexture2DTarget
GlFrontFaceWinding
GlIndexType
GlIndexedBufferTarget
GlPixelStoreAlignment
GlQueryTarget
GlRenderbufferInternalFormat
GlRenderbufferTarget
GlShaderStage
GlStencilFace
GlStencilFunction
GlStencilOperation
GlSyncWaitResult
GlTextureDataType
GlTextureFilter
GlTextureFormat
GlTextureInternalFormat
GlTextureMagFilter
GlTextureMinFilter
GlTextureTarget
GlTextureWrap
GlVertexAttribF32Components
HwContextType
HwRenderContextNegotiationInterfaceType
HwRenderInterfaceType
InputDeviceCapability
JoypadButton
KeyboardKey
KeyboardModifier
Language
LedState
LightgunAxis
LightgunButton
LogLevel
MemoryDescriptorAlignment
MemoryDescriptorFlag
MemoryDescriptorMinAccessSize
MemoryRegion
MessageKind
MessageProgress
MessageTarget
MicrophoneReadError
MouseAxis
MouseButton
MouseWheel
NetpacketDelivery
NetpacketTarget
PixelFormat
PointerAxis
PowerState
Region
RumbleEffect
SavestateContext
Sensor
SensorAction
SensorInput
SerializationQuirk
ThrottleMode
VfsFileAccess
VfsFileAccessHint
VfsSeekPosition
VfsStatFlag
VideoRotation

Constants§

OPENGL_COMPATIBILITY_HW_RENDER_LABEL
OPENGL_MODERN_PREFERRED_HW_RENDER_LABEL
RETRO_API_VERSION
RETRO_DEVICE_ANALOG
RETRO_DEVICE_ID_ANALOG_X
RETRO_DEVICE_ID_ANALOG_Y
RETRO_DEVICE_ID_JOYPAD_A
RETRO_DEVICE_ID_JOYPAD_B
RETRO_DEVICE_ID_JOYPAD_DOWN
RETRO_DEVICE_ID_JOYPAD_L
RETRO_DEVICE_ID_JOYPAD_L2
RETRO_DEVICE_ID_JOYPAD_L3
RETRO_DEVICE_ID_JOYPAD_LEFT
RETRO_DEVICE_ID_JOYPAD_MASK
RETRO_DEVICE_ID_JOYPAD_R
RETRO_DEVICE_ID_JOYPAD_R2
RETRO_DEVICE_ID_JOYPAD_R3
RETRO_DEVICE_ID_JOYPAD_RIGHT
RETRO_DEVICE_ID_JOYPAD_SELECT
RETRO_DEVICE_ID_JOYPAD_START
RETRO_DEVICE_ID_JOYPAD_UP
RETRO_DEVICE_ID_JOYPAD_X
RETRO_DEVICE_ID_JOYPAD_Y
RETRO_DEVICE_ID_LIGHTGUN_IS_OFFSCREEN
RETRO_DEVICE_ID_LIGHTGUN_SCREEN_X
RETRO_DEVICE_ID_LIGHTGUN_SCREEN_Y
RETRO_DEVICE_ID_LIGHTGUN_TRIGGER
RETRO_DEVICE_ID_MOUSE_LEFT
RETRO_DEVICE_ID_MOUSE_WHEELUP
RETRO_DEVICE_ID_MOUSE_X
RETRO_DEVICE_ID_POINTER_PRESSED
RETRO_DEVICE_ID_POINTER_Y
RETRO_DEVICE_INDEX_ANALOG_BUTTON
RETRO_DEVICE_INDEX_ANALOG_LEFT
RETRO_DEVICE_JOYPAD
RETRO_DEVICE_KEYBOARD
RETRO_DEVICE_LIGHTGUN
RETRO_DEVICE_MOUSE
RETRO_DEVICE_NONE
RETRO_DEVICE_POINTER
RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER
RETRO_ENVIRONMENT_GET_GAME_INFO_EXT
RETRO_ENVIRONMENT_GET_LOG_INTERFACE
RETRO_ENVIRONMENT_GET_PREFERRED_HW_RENDER
RETRO_ENVIRONMENT_GET_VARIABLE
RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE
RETRO_ENVIRONMENT_SET_CONTENT_INFO_OVERRIDE
RETRO_ENVIRONMENT_SET_CONTROLLER_INFO
RETRO_ENVIRONMENT_SET_FASTFORWARDING_OVERRIDE
RETRO_ENVIRONMENT_SET_GEOMETRY
RETRO_ENVIRONMENT_SET_HW_RENDER
RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS
RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK
RETRO_ENVIRONMENT_SET_MESSAGE
RETRO_ENVIRONMENT_SET_PIXEL_FORMAT
RETRO_ENVIRONMENT_SET_PROC_ADDRESS_CALLBACK
RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME
RETRO_ENVIRONMENT_SET_VARIABLES
RETRO_HW_FRAME_BUFFER_VALID
RETRO_MEMORY_ROM
RETRO_MEMORY_RTC
RETRO_MEMORY_SAVE_RAM
RETRO_MEMORY_SYSTEM_RAM
RETRO_MEMORY_VIDEO_RAM
RETRO_REGION_NTSC
RETRO_REGION_PAL

Traits§

Core
Trait implemented by a Rust libretro core.

Functions§

bounded_game_geometry
configure_fake_gl_for_testing
exact_audio_frames_per_video_frame
fake_get_proc_address_for_testing
Returns fake GL procedure addresses for tests.
fixed_system_av_info
game_geometry
opengl_compatibility_hw_render_candidates
opengl_modern_preferred_hw_render_candidates
reset_fake_gl_for_testing
silent_stereo_frames
silent_stereo_frames_for_video_frame
snapshot_fake_gl_for_testing
system_av_info

Type Aliases§

AvEnableFlags
CameraCapabilities
CpuFeatures
FramebufferMemoryAccessFlags
FramebufferMemoryTypes
InputDeviceCapabilities
KeyboardModifiers
MemoryDescriptorFlags
SerializationQuirks
VfsFileAccessFlags
VfsFileAccessHints
VfsStatFlags
retro_audio_sample_batch_t
retro_audio_sample_t
retro_environment_t
retro_input_poll_t
retro_input_state_t
retro_video_refresh_t