Created
March 4, 2025 08:01
-
-
Save pusewicz/1e0c249528f2b90ba60c72b38d3a4586 to your computer and use it in GitHub Desktop.
A simple SDL3 demo using the new GPU API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CSDL3 | |
public class Game { | |
let window: OpaquePointer! | |
let gpuDevice: OpaquePointer! | |
public init() { | |
guard SDL_Init(SDL_INIT_EVENTS | SDL_INIT_VIDEO) else { | |
fatalError("Failed to initialize SDL: \(String(cString: SDL_GetError()))") | |
} | |
self.window = SDL_CreateWindow("Game", 800, 600, 0) | |
guard let window else { | |
fatalError("Failed to create window: \(String(cString: SDL_GetError()))") | |
} | |
let supportFlags = SDL_GPU_SHADERFORMAT_MSL | |
self.gpuDevice = SDL_CreateGPUDevice(supportFlags, true, nil) | |
guard let gpuDevice else { | |
fatalError("Failed to create GPU device: \(String(cString: SDL_GetError()))") | |
} | |
SDL_ClaimWindowForGPUDevice(gpuDevice, window) | |
} | |
public func run() { | |
var running = true | |
while running { | |
var event = SDL_Event() | |
while SDL_PollEvent(&event) { | |
switch event.type { | |
case SDL_EVENT_QUIT.rawValue: | |
running = false | |
default: | |
break | |
} | |
} | |
let commandBuffer = SDL_AcquireGPUCommandBuffer(gpuDevice) | |
var swapchainTexture: OpaquePointer? | |
guard | |
SDL_WaitAndAcquireGPUSwapchainTexture(commandBuffer, window, &swapchainTexture, nil, nil) | |
else { | |
fatalError("Failed to acquire swapchain texture: \(String(cString: SDL_GetError()))") | |
} | |
if let swapchainTexture { | |
let currentTime = Double(SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency()) | |
var colorTargetInfo = SDL_GPUColorTargetInfo() | |
let color = SDL_FColor( | |
r: Float(0.5 + 0.5 * SDL_sin(currentTime)), | |
g: Float(0.5 + 0.5 * SDL_sin(currentTime + 2.09439510239)), | |
b: Float(0.5 + 0.5 * SDL_sin(currentTime + 4.18879020479)), | |
a: 1.0 | |
) | |
colorTargetInfo.texture = swapchainTexture | |
colorTargetInfo.clear_color = color | |
colorTargetInfo.load_op = SDL_GPU_LOADOP_CLEAR | |
colorTargetInfo.store_op = SDL_GPU_STOREOP_STORE | |
let renderPass = SDL_BeginGPURenderPass(commandBuffer, &colorTargetInfo, 1, nil) | |
SDL_EndGPURenderPass(renderPass) | |
SDL_SubmitGPUCommandBuffer(commandBuffer) | |
} else { | |
SDL_CancelGPUCommandBuffer(commandBuffer) | |
} | |
} | |
} | |
deinit { | |
SDL_ReleaseWindowFromGPUDevice(gpuDevice, window) | |
SDL_DestroyGPUDevice(gpuDevice) | |
SDL_DestroyWindow(window) | |
SDL_Quit() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment