Branchwell

PulseCanvas / app · pulsecanvas.ai / experiments / metal-studies / RenderSmoke.swift

1import Foundation
2import Metal
3
4private struct StudyFrame {
5 var phase: Float
6 var beat: Float
7}
8
9private enum Study: String {
10 case backlitRift = "backlit-rift"
11 case undersurface = "undersurface"
12 case mercuryFold = "mercury-fold"
13 case emberFront = "ember-front"
14 case anvilFlyover = "anvil-flyover"
15 case pigmentStrata = "pigment-strata"
16
17 var kernel: String {
18 switch self {
19 case .backlitRift: "smokeFrame"
20 case .undersurface: "undersurface"
21 case .mercuryFold: "mercuryFold"
22 case .emberFront: "emberFront"
23 case .anvilFlyover: "anvilFlyover"
24 case .pigmentStrata: "pigmentStrata"
25 }
26 }
27}
28
29private enum RenderError: Error {
30 case usage
31 case metalUnavailable
32 case kernelMissing
33 case frameFailed(Error?)
34}
35
36let arguments = CommandLine.arguments
37guard (5...6).contains(arguments.count),
38 let width = Int(arguments[1]), (1...4096).contains(width),
39 let height = Int(arguments[2]), (1...4096).contains(height),
40 let frameCount = Int(arguments[3]), frameCount > 0,
41 let firstFrame = Int(arguments[4]), (0..<480).contains(firstFrame),
42 frameCount <= 480 - firstFrame,
43 let study = Study(rawValue: arguments.count == 6 ? arguments[5] : "backlit-rift") else {
44 FileHandle.standardError.write(Data("Usage: render-study width height frame-count first-frame [study-name]\n".utf8))
45 throw RenderError.usage
46}
47
48guard let device = MTLCreateSystemDefaultDevice(),
49 let queue = device.makeCommandQueue() else {
50 throw RenderError.metalUnavailable
51}
52let source = try String(contentsOfFile: "Sources/PulseCanvas/Resources/NativeExpansionAtmospheric.metal", encoding: .utf8)
53let options = MTLCompileOptions()
54options.preprocessorMacros = ["PULSECANVAS_STUDY": 1 as NSNumber]
55let library = try device.makeLibrary(source: source, options: options)
56guard let function = library.makeFunction(name: study.kernel) else {
57 throw RenderError.kernelMissing
58}
59let pipeline = try device.makeComputePipelineState(function: function)
60let descriptor = MTLTextureDescriptor.texture2DDescriptor(
61 pixelFormat: .rgba8Unorm, width: width, height: height, mipmapped: false
62)
63descriptor.storageMode = .shared
64descriptor.usage = .shaderWrite
65guard let output = device.makeTexture(descriptor: descriptor) else {
66 throw RenderError.metalUnavailable
67}
68
69let rowBytes = width * 4
70let region = MTLRegionMake2D(0, 0, width, height)
71var pixels = Data(count: rowBytes * height)
72var gpuSeconds = 0.0
73for index in firstFrame..<(firstFrame + frameCount) {
74 let phase = Float(index) * 2 * .pi / 480
75 // The preview uses sixteen evenly spaced beats over its eight-second loop.
76 var frame = StudyFrame(phase: phase, beat: pow(max(0, cos(16 * phase)), 9))
77 guard let command = queue.makeCommandBuffer(),
78 let encoder = command.makeComputeCommandEncoder() else {
79 throw RenderError.metalUnavailable
80 }
81 encoder.setComputePipelineState(pipeline)
82 encoder.setTexture(output, index: 0)
83 encoder.setBytes(&frame, length: MemoryLayout<StudyFrame>.stride, index: 0)
84 encoder.dispatchThreads(
85 MTLSize(width: width, height: height, depth: 1),
86 threadsPerThreadgroup: MTLSize(width: pipeline.threadExecutionWidth, height: 4, depth: 1)
87 )
88 encoder.endEncoding()
89 command.commit()
90 command.waitUntilCompleted()
91 guard command.status == .completed else {
92 throw RenderError.frameFailed(command.error)
93 }
94 gpuSeconds += command.gpuEndTime - command.gpuStartTime
95 pixels.withUnsafeMutableBytes { bytes in
96 output.getBytes(bytes.baseAddress!, bytesPerRow: rowBytes, from: region, mipmapLevel: 0)
97 }
98 try FileHandle.standardOutput.write(contentsOf: pixels)
99}
100let milliseconds = gpuSeconds * 1_000 / Double(frameCount)
101let summary = "\(study.rawValue) on \(device.name): \(frameCount) frames at \(width)×\(height), mean GPU time \(String(format: "%.2f", milliseconds)) ms/frame\n"
102FileHandle.standardError.write(Data(summary.utf8))