Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Cosmos9// File : App/Sources/LaunchCommands.swift10// Description : Automated verification modes selected by launch arguments:11// --render-test renders a renderer test scene offscreen to12// an image and exits; --benchmark runs the live viewport for13// N seconds (renderer test scenes, or the real solar system)14// and writes the measured frame statistics as JSON. The15// --screenshot mode lives in CosmosUI.16// Module : App17// Repository : https://git.spboucher.ai/orix-cosmos18// Project Website : https://www.orixlab.dev19// Created : 2026-11-2420// Last Modified : 2026-11-2421//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import AppKit95import CosmosRender96import CosmosUI97import Foundation98import Metal99100struct RenderTestOptions {101 var output: URL102 var width = 1_920103 var height = 1_080104 var scene = RendererTestScenes.Name.demo105 var pointScale = 1.0106}107108struct BenchmarkOptions {109 var seconds: Double110 var output: URL111 var scene = RendererTestScenes.Name.demo112 /// Real-data scene assembled by CosmosUI; replaces `scene` when set.113 var solarSystem: SolarSystemBenchmark.Scene?114 /// Drawable size in pixels; nil selects the built-in display's native panel resolution.115 var width: Int?116 var height: Int?117}118119enum LaunchCommand {120 case renderTest(RenderTestOptions)121 case benchmark(BenchmarkOptions)122123 struct ParseError: Error, CustomStringConvertible { var description: String }124125 static let usage = """126 usage:127 ORIX Cosmos --render-test <output.png|.exr> [--width W --height H] [--scene <name>] [--point-scale S]128 ORIX Cosmos --benchmark <seconds> <output.json> [--scene <name>] [--width W --height H]129 \(CaptureRequest.usage)130 renderer test scenes (synthetic): \(RendererTestScenes.Name.allCases.map(\.rawValue).joined(separator: ", "))131 real-data benchmark scenes: \(SolarSystemBenchmark.Scene.allCases.map(\.rawValue).joined(separator: ", "))132 """133134 /// Returns nil when no verification mode was requested (normal launch).135 static func parse(_ arguments: [String]) throws -> LaunchCommand? {136 guard let first = arguments.firstIndex(where: { $0 == "--render-test" || $0 == "--benchmark" }) else { return nil }137 var rest = Array(arguments[(first + 1)...])138 func option(_ name: String) throws -> String? {139 guard let i = rest.firstIndex(of: name) else { return nil }140 guard i + 1 < rest.count else { throw ParseError(description: "\(name) needs a value") }141 let value = rest[i + 1]142 rest.removeSubrange(i...(i + 1))143 return value144 }145 func integer(_ name: String) throws -> Int? {146 guard let text = try option(name) else { return nil }147 guard let value = Int(text), value > 0 else { throw ParseError(description: "\(name): '\(text)' is not a positive integer") }148 return value149 }150 var scene = RendererTestScenes.Name.demo151 var solarSystem: SolarSystemBenchmark.Scene?152 if let name = try option("--scene") {153 if let real = SolarSystemBenchmark.Scene(rawValue: name) {154 solarSystem = real155 } else {156 guard let parsed = RendererTestScenes.Name(rawValue: name) else { throw ParseError(description: "unknown scene '\(name)'") }157 scene = parsed158 }159 }160 let width = try integer("--width"), height = try integer("--height")161 let pointScale = try option("--point-scale").map { text -> Double in162 guard let v = Double(text), v > 0 else { throw ParseError(description: "--point-scale: '\(text)' is not a positive number") }163 return v164 }165 func url(_ path: String) -> URL { URL(fileURLWithPath: (path as NSString).expandingTildeInPath) }166167 if arguments[first] == "--render-test" {168 guard let path = rest.first, !path.hasPrefix("--") else { throw ParseError(description: "--render-test needs an output path") }169 guard solarSystem == nil else { throw ParseError(description: "--render-test draws renderer test scenes; use --screenshot for the real interface") }170 var options = RenderTestOptions(output: url(path))171 options.scene = scene172 if let width { options.width = width }173 if let height { options.height = height }174 if let pointScale { options.pointScale = pointScale }175 return .renderTest(options)176 }177 guard rest.count >= 2, let seconds = Double(rest[0]), seconds > 0, seconds <= 3_600 else {178 throw ParseError(description: "--benchmark needs <seconds> and <output.json>")179 }180 var options = BenchmarkOptions(seconds: seconds, output: url(rest[1]))181 options.scene = scene182 options.solarSystem = solarSystem183 options.width = width184 options.height = height185 return .benchmark(options)186 }187}188189// MARK: - Offscreen render test190191enum RenderTestCommand {192 /// Renders one test scene offscreen, writes the image, prints a one-line JSON summary. Returns the exit code.193 static func run(_ options: RenderTestOptions) -> Int32 {194 do {195 let renderer = try CosmosRenderer()196 RendererTestScenes.registerTextures(in: renderer.textures)197 let scene = RendererTestScenes.scene(options.scene, aspectRatio: Double(options.width) / Double(options.height), time: 0)198 let exr = options.output.pathExtension.lowercased() == "exr"199 let begin = Date()200 let image = try renderer.renderImage(scene: scene, width: options.width, height: options.height,201 options: OffscreenOptions(pointScale: options.pointScale, format: exr ? .rgba16Float : .rgba8sRGB))202 let elapsed = Date().timeIntervalSince(begin)203 try FileManager.default.createDirectory(at: options.output.deletingLastPathComponent(), withIntermediateDirectories: true)204 if exr { try image.writeEXR(to: options.output) } else { try image.writePNG(to: options.output) }205 let s = renderer.statistics()206 let summary: [String: Any] = [207 "output": options.output.path, "scene": options.scene.rawValue, "note": RendererTestScenes.disclaimer,208 "width": image.width, "height": image.height, "gpu": renderer.capabilities.deviceName,209 "shaders": renderer.shaderOrigin, "sampleCount": renderer.sampleCount, "drawCalls": s.drawCalls,210 "passes": s.passes, "renderSeconds": elapsed,211 ]212 let data = try JSONSerialization.data(withJSONObject: summary, options: [.sortedKeys])213 print(String(decoding: data, as: UTF8.self))214 return 0215 } catch {216 FileHandle.standardError.write(Data("render test failed: \(error)\n".utf8))217 return 1218 }219 }220}221222// MARK: - Live benchmark223224struct BenchmarkReport: Codable {225 struct Machine: Codable {226 var model: String227 var chip: String228 var cpuCores: Int229 var memoryGigabytes: Double230 var operatingSystem: String231 }232 struct Display: Codable {233 var name: String234 var isBuiltIn: Bool235 var refreshHertz: Int236 var panelPixelWidth: Int237 var panelPixelHeight: Int238 var extendedDynamicRange: Bool239 var edrHeadroom: Double240 }241 var title = "ORIX Cosmos renderer benchmark — values measured in this run on this machine"242 var date: String243 var buildConfiguration: String244 var scene: String245 var sceneNote: String246 var machine: Machine247 var gpu: String248 var display: Display249 var drawablePixelWidth: Int250 var drawablePixelHeight: Int251 var pointScale: Double252 var presentation: String253 var windowVisibleAtEnd: Bool254 var requestedSeconds: Double255 var measuredSeconds: Double256 var warmupSeconds: Double257 var dynamicResolution: Bool258 var shaders: String259 var statistics: FrameStatisticsSnapshot260 var textures: TextureStatistics261 /// Main-actor time spent assembling the scene each frame (ephemerides, orientations, labels, markers), ms. Real-data scenes only.262 var sceneAssembly: TimingSummary?263 var sceneBodies: Int?264 var orbitCacheRefreshes: Int?265 var machineLoadAverage1Minute: Double?266 var processMemoryFootprintBytes: Int267 var capabilities: DeviceCapabilities268}269270enum SystemInfo {271 static func sysctlString(_ name: String) -> String {272 var size = 0273 guard sysctlbyname(name, nil, &size, nil, 0) == 0, size > 0 else { return "unknown" }274 var buffer = [UInt8](repeating: 0, count: size)275 guard sysctlbyname(name, &buffer, &size, nil, 0) == 0 else { return "unknown" }276 return String(decoding: buffer.prefix { $0 != 0 }, as: UTF8.self)277 }278279 /// Physical memory footprint of this process (the figure Activity Monitor reports as "Memory").280 static func memoryFootprint() -> Int {281 var info = task_vm_info_data_t()282 var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)283 let result = withUnsafeMutablePointer(to: &info) { pointer in284 pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) }285 }286 return result == KERN_SUCCESS ? Int(info.phys_footprint) : 0287 }288289 /// One-minute load average of the machine (other processes competing for CPU and GPU during the run).290 static var loadAverage: Double? {291 var load = [Double](repeating: 0, count: 3)292 return getloadavg(&load, 3) > 0 ? load[0] : nil293 }294295 static var machine: BenchmarkReport.Machine {296 BenchmarkReport.Machine(model: sysctlString("hw.model"), chip: sysctlString("machdep.cpu.brand_string"),297 cpuCores: ProcessInfo.processInfo.processorCount,298 memoryGigabytes: Double(ProcessInfo.processInfo.physicalMemory) / 1_073_741_824,299 operatingSystem: ProcessInfo.processInfo.operatingSystemVersionString)300 }301}302303@MainActor304final class BenchmarkController: NSObject, NSApplicationDelegate {305 private let options: BenchmarkOptions306 private var window: NSWindow?307 private var view: CosmosMetalView?308 private var sceneStart: Double?309 private var measureStart: Double?310 private let warmup = 1.5311 private var finished = false312 private var solarSystem: SolarSystemBenchmark?313314 init(options: BenchmarkOptions) { self.options = options }315316 func applicationDidFinishLaunching(_ notification: Notification) {317 // The built-in display when there is one, otherwise the main screen.318 let screen = NSScreen.screens.first { screen in319 (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID).map { CGDisplayIsBuiltin($0) != 0 } ?? false320 } ?? NSScreen.main ?? NSScreen.screens[0]321 let displayID = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID) ?? CGMainDisplayID()322 let panel = Self.panelPixelSize(displayID) ?? (Int(screen.frame.width * screen.backingScaleFactor), Int(screen.frame.height * screen.backingScaleFactor))323 let width = options.width ?? panel.0, height = options.height ?? panel.1324325 var configuration = RendererConfiguration()326 configuration.dynamicResolution = DynamicResolutionController(enabled: false) // fixed full resolution: comparable numbers327 let view = CosmosMetalView(frame: CGRect(origin: .zero, size: screen.frame.size), configuration: configuration)328 guard let renderer = view.renderer else {329 fail("no renderer: \(view.initializationError.map { String(describing: $0) } ?? "Metal unavailable")")330 return331 }332 if let real = options.solarSystem {333 do {334 let benchmark = try SolarSystemBenchmark(scene: real)335 benchmark.attach(renderer: renderer)336 solarSystem = benchmark337 } catch {338 fail("solar-system scene: \(error)")339 return340 }341 } else {342 RendererTestScenes.registerTextures(in: renderer.textures)343 }344 view.autoResizeDrawable = false345 view.drawableSize = CGSize(width: width, height: height)346 let scene = options.scene347 let aspect = Double(width) / Double(height)348 view.sceneProvider = { [weak self] context in349 guard let self else { return SceneDescription() }350 if self.sceneStart == nil { self.sceneStart = context.time }351 if let solarSystem = self.solarSystem { return solarSystem.frame(context) }352 return RendererTestScenes.scene(scene, aspectRatio: aspect, time: context.time - (self.sceneStart ?? context.time))353 }354 view.onFrame = { [weak self] view in self?.tick(view, screen: screen, displayID: displayID, panel: panel) }355356 // The window covers the display but is ordered behind every other window and never activated: the357 // benchmark must not take the screen or the keyboard from whoever is using the machine.358 let window = NSWindow(contentRect: screen.frame, styleMask: [.borderless], backing: .buffered, defer: false, screen: screen)359 window.isReleasedWhenClosed = false360 window.ignoresMouseEvents = true361 window.isOpaque = true362 window.backgroundColor = .black363 window.contentView = view364 window.setFrame(screen.frame, display: false)365 window.orderBack(nil)366 self.window = window367 self.view = view368369 // Safety net: if the display link never fires (for instance a sleeping display), stop instead of hanging.370 DispatchQueue.main.asyncAfter(deadline: .now() + warmup + options.seconds + 20) { [weak self] in371 guard let self, !self.finished else { return }372 self.fail("no frame was presented within \(Int(self.warmup + self.options.seconds + 20)) s (display asleep or window not drawable)")373 }374 }375376 private static func panelPixelSize(_ display: CGDirectDisplayID) -> (Int, Int)? {377 let options = [kCGDisplayShowDuplicateLowResolutionModes: kCFBooleanTrue] as CFDictionary378 guard let modes = CGDisplayCopyAllDisplayModes(display, options) as? [CGDisplayMode] else { return nil }379 // The panel's native resolution: the mode IOKit flags as native (kDisplayModeNativeFlag). Scaled HiDPI modes380 // have larger backing stores than the panel and must not be mistaken for it.381 let nativeFlag: UInt32 = 0x0200_0000382 let native = modes.filter { $0.ioFlags & nativeFlag != 0 }383 guard let best = native.max(by: { $0.pixelWidth * $0.pixelHeight < $1.pixelWidth * $1.pixelHeight }) else { return nil }384 return (best.pixelWidth, best.pixelHeight)385 }386387 private func tick(_ view: CosmosMetalView, screen: NSScreen, displayID: CGDirectDisplayID, panel: (Int, Int)) {388 guard !finished, let renderer = view.renderer, let sceneStart else { return }389 let now = CACurrentMediaTime()390 if measureStart == nil {391 guard now - sceneStart >= warmup else { return }392 renderer.resetStatistics() // discard pipeline compilation and texture streaming393 solarSystem?.resetStatistics()394 measureStart = now395 return396 }397 guard let measureStart, now - measureStart >= options.seconds else { return }398 finished = true399 view.isPaused = true400 // Let the frames still in flight report their GPU time before reading the statistics.401 DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [self] in402 let statistics = renderer.statistics()403 let report = BenchmarkReport(404 date: ISO8601DateFormatter().string(from: Date()),405 buildConfiguration: Self.buildConfiguration,406 scene: solarSystem?.scene.rawValue ?? options.scene.rawValue, sceneNote: solarSystem?.note ?? RendererTestScenes.disclaimer,407 machine: SystemInfo.machine, gpu: renderer.capabilities.deviceName,408 display: .init(name: screen.localizedName, isBuiltIn: CGDisplayIsBuiltin(displayID) != 0,409 refreshHertz: screen.maximumFramesPerSecond, panelPixelWidth: panel.0, panelPixelHeight: panel.1,410 extendedDynamicRange: view.isExtendedDynamicRangeActive,411 edrHeadroom: Double(screen.maximumExtendedDynamicRangeColorComponentValue)),412 drawablePixelWidth: Int(view.drawableSize.width), drawablePixelHeight: Int(view.drawableSize.height),413 pointScale: Double(view.drawableSize.height) / Double(max(view.bounds.height, 1)),414 presentation: "MTKView, display-synchronised (frame interval is capped at the refresh interval; GPU and CPU times show the headroom)",415 windowVisibleAtEnd: window?.occlusionState.contains(.visible) ?? false,416 requestedSeconds: options.seconds, measuredSeconds: now - measureStart, warmupSeconds: warmup,417 dynamicResolution: false, shaders: renderer.shaderOrigin, statistics: statistics,418 textures: renderer.textures.statistics, sceneAssembly: solarSystem?.assemblyStatistics(),419 sceneBodies: solarSystem?.bodyCount, orbitCacheRefreshes: solarSystem?.orbitRefreshes,420 machineLoadAverage1Minute: SystemInfo.loadAverage, processMemoryFootprintBytes: SystemInfo.memoryFootprint(),421 capabilities: renderer.capabilities)422 do {423 let encoder = JSONEncoder()424 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]425 try FileManager.default.createDirectory(at: options.output.deletingLastPathComponent(), withIntermediateDirectories: true)426 try encoder.encode(report).write(to: options.output, options: .atomic)427 print("benchmark written to \(options.output.path): \(statistics.frameCount) frames, "428 + String(format: "%.1f fps, GPU median %.2f ms, CPU median %.2f ms", statistics.framesPerSecond, statistics.gpu.median, statistics.cpu.median)429 + (report.sceneAssembly.map { String(format: ", scene assembly median %.3f ms (p95 %.3f)", $0.median, $0.p95) } ?? ""))430 exit(0)431 } catch {432 fail("cannot write \(options.output.path): \(error)")433 }434 }435 }436437 private static var buildConfiguration: String {438 #if DEBUG439 "Debug"440 #else441 "Release"442 #endif443 }444445 private func fail(_ message: String) {446 FileHandle.standardError.write(Data("benchmark failed: \(message)\n".utf8))447 exit(1)448 }449}450451enum BenchmarkCommand {452 static func run(_ options: BenchmarkOptions) {453 MainActor.assumeIsolated {454 let application = NSApplication.shared455 application.setActivationPolicy(.accessory) // no Dock icon, no menu bar, never frontmost456 let controller = BenchmarkController(options: options)457 application.delegate = controller458 withExtendedLifetime(controller) { application.run() }459 }460 }461}462