Remove per-call overhead from API access and text conversion

Two hot-path optimizations for the device's Cortex-M7 (and debug simulator
builds):

- The ten sub-API pointers are cached once in Playdate.initialize(with:);
  wrapper accessors now return UnsafePointer and call sites read a single
  field through it, instead of unwrapping the optional API struct and
  copying a whole sub-API struct of function pointers on every call.
  Nested sub-APIs (sound classes, effects, video, tilemap, http/tcp)
  derive from the cached pointers with one field load.

- String -> C conversions (withPlaydateCString, and a new withPlaydateUTF8
  used by the text drawing/measuring APIs) use withUnsafeTemporaryAllocation
  instead of building a ContiguousArray, so logging and drawText in the
  update loop no longer heap-allocate per call. Verified within the
  Embedded Swift subset by the device cross-compile.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-25 07:23:19 +02:00
co-authored by Claude Fable 5
parent e4e99cc894
commit d914e0f8fb
20 changed files with 682 additions and 643 deletions
+23
View File
@@ -24,6 +24,19 @@ public enum Playdate {
/// need to pass the `PlaydateAPI*` back to C.
public internal(set) nonisolated(unsafe) static var apiPointer: UnsafeMutablePointer<PlaydateAPI>!
// Sub-API pointers cached once at initialization, so wrapper calls are a
// single field load off a pointer instead of re-walking `api` per call.
nonisolated(unsafe) static var systemAPI: UnsafePointer<playdate_sys>!
nonisolated(unsafe) static var displayAPI: UnsafePointer<playdate_display>!
nonisolated(unsafe) static var graphicsAPI: UnsafePointer<playdate_graphics>!
nonisolated(unsafe) static var spriteAPI: UnsafePointer<playdate_sprite>!
nonisolated(unsafe) static var soundAPI: UnsafePointer<playdate_sound>!
nonisolated(unsafe) static var fileAPI: UnsafePointer<playdate_file>!
nonisolated(unsafe) static var jsonAPI: UnsafePointer<playdate_json>!
nonisolated(unsafe) static var luaAPI: UnsafePointer<playdate_lua>!
nonisolated(unsafe) static var scoreboardsAPI: UnsafePointer<playdate_scoreboards>!
nonisolated(unsafe) static var networkAPI: UnsafePointer<playdate_network>!
/// Stores the API pointer handed to the game's `eventHandler`.
///
/// Call this first, on the `.initialize` event, before using any other
@@ -31,6 +44,16 @@ public enum Playdate {
public static func initialize(with pointer: UnsafeMutableRawPointer) {
apiPointer = pointer.assumingMemoryBound(to: PlaydateAPI.self)
api = apiPointer.pointee
systemAPI = api.system
displayAPI = api.display
graphicsAPI = api.graphics
spriteAPI = api.sprite
soundAPI = api.sound
fileAPI = api.file
jsonAPI = api.json
luaAPI = api.lua
scoreboardsAPI = api.scoreboards
networkAPI = api.network
}
}