Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / NativeGallery.swift

Raw 22.0 KB on 23ffa4e102ea595ec83f2b18683b75332fc815c3
1import AppKit
2import Foundation
3@preconcurrency import Metal
4
5/// Developer gallery for native effects: stills, motion frame sequences, continuity,
6/// Chaos isolation and timing. Build with scripts/native-gallery.sh.
7@main struct NativeGallery {
8 struct Failure: LocalizedError {
9 let text: String
10 var errorDescription: String? { text }
11 }
12
13 struct Options {
14 var command = "stills"
15 var scenes: [Int] = []
16 var width = 640, height = 360
17 var time = 12.3, start = 10.0, duration = 4.0
18 var fps = 30
19 var chaos: Float? = nil
20 var zoomSpeed: Float? = nil
21 var palette = -1
22 var output = ".build/native-gallery"
23 var silence = false
24 var brightness: Float? = nil
25 var fog: Float? = nil
26
27 @MainActor init(_ arguments: [String]) throws {
28 var index = 1
29 if arguments.count > 1 { command = arguments[1]; index = 2 }
30 while index < arguments.count {
31 let key = arguments[index], value = index + 1 < arguments.count ? arguments[index + 1] : ""
32 switch key {
33 case "--scenes": scenes = Self.parseScenes(value).filter { !NativeEffects.isRetired($0) }
34 case "--size":
35 let parts = value.split(separator: "x").compactMap { Int($0) }
36 guard parts.count == 2 else { throw Failure(text: "Size must be WIDTHxHEIGHT") }
37 width = parts[0]; height = parts[1]
38 case "--time": time = Double(value) ?? time
39 case "--start": start = Double(value) ?? start
40 case "--duration": duration = Double(value) ?? duration
41 case "--fps": fps = Int(value) ?? fps
42 case "--chaos": chaos = Float(value)
43 case "--zoom-speed": zoomSpeed = Float(value)
44 case "--palette": palette = Int(value) ?? palette
45 case "--out": output = value
46 case "--silence": silence = true; index -= 1
47 case "--brightness": brightness = Float(value)
48 case "--fog": fog = Float(value)
49 default: throw Failure(text: "Unknown option \(key)")
50 }
51 index += 2
52 }
53 if scenes.isEmpty { scenes = NativeEffects.activeIDs }
54 }
55
56 static func parseScenes(_ text: String) -> [Int] {
57 text.split(separator: ",").flatMap { part -> [Int] in
58 let bounds = part.split(separator: "-").compactMap { Int($0) }
59 if bounds.count == 2 { return Array(bounds[0]...bounds[1]) }
60 return bounds
61 }
62 }
63 }
64
65 @MainActor static func main() async {
66 NSApplication.shared.setActivationPolicy(.accessory)
67 do { try run(Options(CommandLine.arguments)) } catch {
68 print("FAIL: \(error.localizedDescription)"); exit(1)
69 }
70 }
71
72 static func pixels(_ texture: MTLTexture) -> [UInt8] {
73 var bytes = [UInt8](repeating: 0, count: texture.width * texture.height * 4)
74 bytes.withUnsafeMutableBytes {
75 texture.getBytes($0.baseAddress!, bytesPerRow: texture.width * 4,
76 from: MTLRegionMake2D(0, 0, texture.width, texture.height), mipmapLevel: 0)
77 }
78 return bytes
79 }
80
81 static func png(_ bytes: [UInt8], width: Int, height: Int, to url: URL) throws {
82 let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height,
83 bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
84 colorSpaceName: .deviceRGB, bytesPerRow: width * 4, bitsPerPixel: 32)!
85 for pixel in stride(from: 0, to: bytes.count, by: 4) {
86 bitmap.bitmapData![pixel] = bytes[pixel + 2]
87 bitmap.bitmapData![pixel + 1] = bytes[pixel + 1]
88 bitmap.bitmapData![pixel + 2] = bytes[pixel]
89 bitmap.bitmapData![pixel + 3] = 255
90 }
91 try bitmap.representation(using: .png, properties: [:])!.write(to: url)
92 }
93
94 /// Mean absolute channel difference, 0...255.
95 static func difference(_ a: [UInt8], _ b: [UInt8]) -> Double {
96 var total = 0
97 for index in stride(from: 0, to: min(a.count, b.count), by: 4) {
98 total += abs(Int(a[index]) - Int(b[index])) + abs(Int(a[index + 1]) - Int(b[index + 1])) + abs(Int(a[index + 2]) - Int(b[index + 2]))
99 }
100 return Double(total) / Double(a.count / 4 * 3)
101 }
102
103 struct Coverage { var cells: Int; var lit: Double; var mean: Double }
104 static func coverage(_ bytes: [UInt8], width: Int, height: Int) -> Coverage {
105 var cells = Set<Int>(), lit = 0, sum = 0
106 for index in stride(from: 0, to: bytes.count, by: 4) {
107 let value = max(bytes[index], max(bytes[index + 1], bytes[index + 2]))
108 sum += Int(bytes[index]) + Int(bytes[index + 1]) + Int(bytes[index + 2])
109 if value > 20 {
110 lit += 1
111 let x = (index / 4) % width, y = (index / 4) / width
112 cells.insert((y * 4 / height) * 4 + x * 4 / width)
113 }
114 }
115 let count = Double(width * height)
116 return Coverage(cells: cells.count, lit: Double(lit) / count, mean: Double(sum) / (count * 3))
117 }
118
119 @MainActor static func configure(_ state: RenderState, scene: Int, options: Options) {
120 state.scene = scene
121 VisualPreset.defaults(for: scene).apply(to: state)
122 if let chaos = options.chaos { state.chaos = chaos }
123 if let zoomSpeed = options.zoomSpeed { state.zoomSpeed = zoomSpeed }
124 if let brightness = options.brightness { state.brightness = brightness }
125 if let fog = options.fog { state.fog = fog }
126 state.motionBlur = 0
127 state.strobeEnabled = false
128 if options.palette >= 0 { state.palette = options.palette }
129 }
130
131 @MainActor static func render(_ renderer: VisualizerRenderer, analyzer: SoundtrackAnalyzer, time: Double, silence: Bool) throws -> [UInt8] {
132 let features = silence ? AudioFeatures.silence : try analyzer.frame(at: time, clipStart: 0, clipEnd: 10_000)
133 let texture = try renderer.renderOffscreen(time: time, audioBands: features.bands, audioPulse: features.pulse,
134 audioMomentum: features.momentum, audioBeatMotionTime: features.beatMotionTime, audioEnvelopes: features.envelopes, audioSwell: features.swell)
135 return pixels(texture)
136 }
137
138 @MainActor static func run(_ options: Options) throws {
139 let root = URL(fileURLWithPath: options.output, isDirectory: true)
140 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
141 let analyzer = try SoundtrackAnalyzer(url: URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3"))
142 let names = RenderState.nativeSceneNames
143 let state = RenderState()
144 let renderer = VisualizerRenderer(state: state)
145 let compileStart = ProcessInfo.processInfo.systemUptime
146 try renderer.prepareOffscreen(width: options.width, height: options.height)
147 print(String(format: "LIBRARY attach and native compile: %.0f ms", (ProcessInfo.processInfo.systemUptime - compileStart) * 1000))
148 switch options.command {
149 case "stills":
150 for scene in options.scenes {
151 configure(state, scene: scene, options: options)
152 let bytes = try render(renderer, analyzer: analyzer, time: options.time, silence: options.silence)
153 try png(bytes, width: options.width, height: options.height, to: root.appendingPathComponent(String(format: "%03d.png", scene)))
154 let c = coverage(bytes, width: options.width, height: options.height)
155 print(String(format: "STILL %3d %-22@ cells %2d lit %5.1f%% mean %5.1f", scene, names[scene] as NSString, c.cells, c.lit * 100, c.mean))
156 }
157 case "frames":
158 for scene in options.scenes {
159 configure(state, scene: scene, options: options)
160 let folder = root.appendingPathComponent(String(format: "%03d", scene), isDirectory: true)
161 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
162 let count = Int(options.duration * Double(options.fps))
163 for frame in 0..<count {
164 let time = options.start + Double(frame) / Double(options.fps)
165 let bytes = try render(renderer, analyzer: analyzer, time: time, silence: options.silence)
166 try png(bytes, width: options.width, height: options.height, to: folder.appendingPathComponent(String(format: "%05d.png", frame)))
167 }
168 print("FRAMES \(scene) \(names[scene]): \(count)")
169 }
170 case "audit":
171 // Chaos isolation, element response and continuity at zero and full Chaos.
172 var failures: [String] = []
173 for scene in options.scenes {
174 configure(state, scene: scene, options: options)
175 state.chaos = 0
176 let quietMusic = try render(renderer, analyzer: analyzer, time: options.time, silence: false)
177 let quietSilence = try render(renderer, analyzer: analyzer, time: options.time, silence: true)
178 let isolation = difference(quietMusic, quietSilence)
179 state.chaos = 1
180 // Same music clock, with and without the instantaneous levels: isolates
181 // element response from the integrated clock.
182 let features = try analyzer.frame(at: options.time, clipStart: 0, clipEnd: 10_000)
183 let withLevels = pixels(try renderer.renderOffscreen(time: options.time, audioBands: features.bands, audioPulse: features.pulse,
184 audioMomentum: features.momentum, audioBeatMotionTime: features.beatMotionTime, audioEnvelopes: features.envelopes, audioSwell: features.swell))
185 let withoutLevels = pixels(try renderer.renderOffscreen(time: options.time, audioBands: [Float](repeating: 0, count: 32), audioPulse: 0,
186 audioMomentum: 0, audioBeatMotionTime: features.beatMotionTime))
187 let response = difference(withLevels, withoutLevels)
188 var summaries: [String] = []
189 var minimumMean = 255.0, minimumCells = 16
190 for chaos in [Float(0), 1] {
191 state.chaos = chaos
192 var steps: [Double] = []
193 var previous: [UInt8]? = nil
194 for frame in 0..<Int(options.duration * Double(options.fps)) {
195 let bytes = try render(renderer, analyzer: analyzer, time: options.start + Double(frame) / Double(options.fps), silence: false)
196 let c = coverage(bytes, width: options.width, height: options.height)
197 minimumMean = min(minimumMean, c.mean); minimumCells = min(minimumCells, c.cells)
198 if let previous { steps.append(difference(previous, bytes)) }
199 previous = bytes
200 }
201 let sorted = steps.sorted()
202 let median = sorted.isEmpty ? 0 : sorted[sorted.count / 2]
203 let peak = sorted.last ?? 0
204 let at = steps.firstIndex(of: peak).map { $0 + 1 } ?? 0
205 summaries.append(String(format: "c%.0f step %5.2f/%6.2f x%4.1f @%3d", chaos, median, peak, peak / max(0.01, median), at))
206 }
207 print(String(format: "AUDIT %3d %-22@ zeroChaos %.3f levels %6.2f ", scene, names[scene] as NSString, isolation, response) + summaries.joined(separator: " ") + String(format: " minMean %5.1f cells %2d", minimumMean, minimumCells))
208 if isolation > 0.001 { failures.append("\(names[scene]): music changes output at zero Chaos (\(isolation))") }
209 if minimumMean < 4 { failures.append("\(names[scene]): near-black frame (mean \(minimumMean))") }
210 if minimumCells < 14 { failures.append("\(names[scene]): sparse frame (\(minimumCells)/16 cells)") }
211 }
212 if !failures.isEmpty { throw Failure(text: failures.joined(separator: "\n")) }
213 case "features":
214 var time = options.start
215 while time < options.start + options.duration {
216 let f = try analyzer.frame(at: time, clipStart: 0, clipEnd: 10_000)
217 func mean(_ r: Range<Int>) -> Float { r.map { f.bands[$0] }.reduce(0, +) / Float(r.count) }
218 print(String(format: "t %6.2f low %.2f lowMid %.2f highMid %.2f high %.2f pulse %.2f momentum %.2f motion %.2f | envelopes %.2f %.2f %.2f %.2f swell %.2f",
219 time, mean(0..<6), mean(6..<14), mean(14..<23), mean(23..<32), f.pulse, f.momentum, f.beatMotionTime,
220 f.envelopes.x, f.envelopes.y, f.envelopes.z, f.envelopes.w, f.swell))
221 time += 1 / Double(options.fps)
222 }
223 case "zoomcheck":
224 // Mirrors scripts/ZoomSmoke.swift with numbers, to locate failures.
225 for scene in options.scenes {
226 state.scene = scene; state.chaos = 0; state.zoomSpeed = 0
227 func frame(_ time: Double) throws -> [UInt8] { pixels(try renderer.renderOffscreen(time: time, audioBands: [Float](repeating: 0, count: 32))) }
228 let flat = try frame(2.3), moving = try frame(2.7)
229 state.zoomSpeed = 1; let travel = try frame(2.3)
230 state.zoomSpeed = 3; let fast = try frame(2.3)
231 state.zoomSpeed = 0; let restored = try frame(2.3)
232 let a = difference(flat, moving), b = difference(flat, travel), d = difference(travel, fast)
233 let ok = a > 0.05 * 255 / 255 && b > 0.5 && d > 0.5 && flat == restored
234 print(String(format: "ZOOM %3d %-22@ animate %.3f travel %.3f fast %.3f restored %@ %@", scene, names[scene] as NSString, a, b, d, flat == restored ? "yes" : "NO", ok ? "" : "<-- FAIL"))
235 }
236 case "beatcheck":
237 // Mirrors scripts/AudioSyncSmoke.swift: an attack must visibly change each scene.
238 let frameFeatures = try analyzer.frame(at: 1.33, clipStart: 0, clipEnd: 4)
239 for scene in options.scenes {
240 state.scene = scene; state.zoom = 1; state.brightness = 1; state.strobeEnabled = false
241 let idle = pixels(try renderer.renderOffscreen(time: 1.33, audioBands: frameFeatures.bands, audioPulse: 0))
242 let beat = pixels(try renderer.renderOffscreen(time: 1.33, audioBands: frameFeatures.bands, audioPulse: 1, audioSwell: 1))
243 let changed = zip(idle, beat).filter { abs(Int($0) - Int($1)) > 8 }.count
244 if changed <= 400 { print("BEAT \(scene) \(names[scene]) changed \(changed) <-- weak") }
245 }
246 case "covercheck":
247 // Mirrors scripts/CanvasCoverageSmoke.swift spans and occupancy.
248 let settings: [(Double, Float, Float)] = [(2.3, 1, 0), (0, 0.6, 2.7), (8, 1.55, -2.7), (24, 1, 1.1)]
249 for scene in options.scenes {
250 state.scene = scene; state.speed = 1; state.brightness = 1; state.particleSize = 1; state.palette = 0
251 for (time, zoom, rotation) in settings {
252 if [0, 1, 2, 5, 7].contains(scene) && time != 2.3 { continue }
253 state.zoom = zoom; state.rotation = rotation
254 let p = pixels(try renderer.renderOffscreen(time: time, audioBands: Array(repeating: 0.2, count: 32)))
255 var count = 0, minX = options.width, maxX = 0, minY = options.height, maxY = 0
256 var cells = Set<Int>()
257 for i in stride(from: 0, to: p.count, by: 4) where max(p[i], max(p[i+1], p[i+2])) > 16 {
258 let x = (i/4) % options.width, y = (i/4) / options.width
259 count += 1; minX = min(minX, x); maxX = max(maxX, x); minY = min(minY, y); maxY = max(maxY, y)
260 cells.insert((y * 4 / options.height) * 4 + x * 4 / options.width)
261 }
262 let w = Double(maxX - minX) / Double(options.width), h = Double(maxY - minY) / Double(options.height)
263 let lit = Double(count) / Double(options.width * options.height)
264 if w <= 0.95 || h <= 0.95 || lit <= 0.05 || cells.count < 14 {
265 print(String(format: "COVER %3d %-22@ t=%.1f zoom=%.2f rot=%.1f span %.2f x %.2f lit %.2f cells %d <-- FAIL", scene, names[scene] as NSString, time, zoom, rotation, w, h, lit, cells.count))
266 }
267 }
268 state.zoom = 1; state.rotation = 0
269 }
270 case "palcheck":
271 // Accents can dominate a frame; verify each shared palette actually
272 // changes the GPU output instead of requiring monochromatic ratios.
273 let frameFeatures = try analyzer.frame(at: 1.33, clipStart: 0, clipEnd: 4)
274 for scene in options.scenes {
275 state.scene = scene; state.zoom = 1; state.brightness = 1; state.strobeEnabled = false
276 var outputs = Set<Data>()
277 for palette in VisualPalette.allCases {
278 state.palette = palette.rawValue
279 let image = pixels(try renderer.renderOffscreen(time: 1.33, audioBands: frameFeatures.bands))
280 outputs.insert(Data(image))
281 }
282 guard outputs.count == VisualPalette.allCases.count else {
283 throw Failure(text: "Palettes must produce distinct outputs for \(names[scene])")
284 }
285 }
286 print("PASS: \(options.scenes.count * VisualPalette.allCases.count) distinct GPU palette outputs across \(options.scenes.count) effects")
287 case "wrapcheck":
288 // Isolated jumps: a frame step far larger than both neighbouring steps. Run at
289 // zero Chaos and high Zoom speed so travel wraps are crossed many times.
290 for scene in options.scenes {
291 configure(state, scene: scene, options: options)
292 state.chaos = 0
293 if options.zoomSpeed == nil { state.zoomSpeed = 3 }
294 var steps: [Double] = [], previous: [UInt8]? = nil
295 let count = Int(options.duration * Double(options.fps))
296 for frame in 0..<count {
297 let bytes = pixels(try renderer.renderOffscreen(time: options.start + Double(frame) / Double(options.fps), audioBands: [Float](repeating: 0, count: 32)))
298 if let previous { steps.append(difference(previous, bytes)) }
299 previous = bytes
300 }
301 var spikes: [String] = []
302 for i in 1..<max(1, steps.count - 1) {
303 let local = max(steps[i - 1], steps[i + 1])
304 if steps[i] > local * 2.5 + 2 { spikes.append(String(format: "%.2fs:%.1f/%.1f", options.start + Double(i + 1) / Double(options.fps), steps[i], local)) }
305 }
306 if !spikes.isEmpty { print("WRAP \(scene) \(names[scene]) spikes \(spikes.count): " + spikes.prefix(4).joined(separator: " ")) }
307 }
308 case "musiccheck":
309 // How much the soundtrack moves each design at its default look, over nine song
310 // times. levels = instantaneous bands, attack swell and energy at the same music
311 // clock; total = everything music adds over silence, including the music clock.
312 // area = share of pixels the instantaneous levels change by more than 12/255.
313 let silent = [Float](repeating: 0, count: 32)
314 for scene in options.scenes {
315 configure(state, scene: scene, options: options)
316 var levels = 0.0, total = 0.0, area = 0.0
317 let times = stride(from: 10.0, through: 90.0, by: 10.0).map { $0 + options.start - 10 }
318 for time in times {
319 let f = try analyzer.frame(at: time, clipStart: 0, clipEnd: 10_000)
320 let full = pixels(try renderer.renderOffscreen(time: time, audioBands: f.bands, audioPulse: f.pulse, audioMomentum: f.momentum,
321 audioBeatMotionTime: f.beatMotionTime, audioEnvelopes: f.envelopes, audioSwell: f.swell))
322 let clockOnly = pixels(try renderer.renderOffscreen(time: time, audioBands: silent, audioBeatMotionTime: f.beatMotionTime))
323 let none = pixels(try renderer.renderOffscreen(time: time, audioBands: silent))
324 levels += difference(full, clockOnly); total += difference(full, none)
325 var changed = 0
326 for index in stride(from: 0, to: full.count, by: 4) where max(abs(Int(full[index]) - Int(clockOnly[index])), abs(Int(full[index + 1]) - Int(clockOnly[index + 1])), abs(Int(full[index + 2]) - Int(clockOnly[index + 2]))) > 12 { changed += 1 }
327 area += Double(changed) / Double(full.count / 4)
328 }
329 let n = Double(times.count)
330 print(String(format: "MUSIC %3d %-22@ chaos %.2f levels %6.2f area %5.1f%% total %6.2f", scene, names[scene] as NSString, state.chaos, levels / n, area / n * 100, total / n))
331 }
332 case "timing":
333 for scene in options.scenes {
334 configure(state, scene: scene, options: options)
335 let first = ProcessInfo.processInfo.systemUptime
336 _ = try renderer.renderOffscreen(time: 12, audioBands: [Float](repeating: 0.25, count: 32))
337 let firstMs = (ProcessInfo.processInfo.systemUptime - first) * 1000
338 let begin = ProcessInfo.processInfo.systemUptime
339 let frames = 10
340 for frame in 0..<frames {
341 _ = try renderer.renderOffscreen(time: 12 + Double(frame) / 60, audioBands: [Float](repeating: 0.3, count: 32), audioPulse: 0.5, audioMomentum: 0.6)
342 }
343 let ms = (ProcessInfo.processInfo.systemUptime - begin) * 1000 / Double(frames)
344 print(String(format: "TIMING %3d %-22@ %dx%d %6.2f ms (first frame incl. pipeline %6.1f ms)", scene, names[scene] as NSString, options.width, options.height, ms, firstMs))
345 }
346 default:
347 throw Failure(text: "Unknown command \(options.command)")
348 }
349 }
350}