#include "socks.hpp" #import #import #include #include #include #include #include "renderer.hpp" @interface Screen : NSObject @property NSWindow *window; @property MTKView *view; @property id queue; @property id pipeline; @property id texture; @property id lastDraw; - (BOOL)setup; - (id)present; @end @implementation Screen - (BOOL)setup { id device = MTLCreateSystemDefaultDevice(); if (!device) return NO; self.queue = [device newCommandQueue]; self.pipeline = buildPipeline(device); if (!self.pipeline) return NO; NSRect rect = NSMakeRect(0, 0, 800, 600); self.window = [[NSWindow alloc] initWithContentRect:rect styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable backing:NSBackingStoreBuffered defer:NO]; self.view = [[MTKView alloc] initWithFrame:rect device:device]; self.view.colorPixelFormat = MTLPixelFormatBGRA8Unorm; self.view.clearColor = MTLClearColorMake(0, 0, 0, 1); self.view.paused = YES; self.view.enableSetNeedsDisplay = YES; self.view.delegate = self; self.window.delegate = self; self.window.contentView = self.view; self.window.title = @"RPS · Подключение"; [self.window center]; [self.window makeKeyAndOrderFront:nil]; return YES; } - (void)windowWillClose:(NSNotification *)note { [NSApp terminate:nil]; } - (void)mtkView:(MTKView *)view drawableSizeWillChange:(CGSize)size { [view setNeedsDisplay:YES]; } - (void)drawInMTKView:(MTKView *)view { self.lastDraw = [self present]; } - (id)present { if (!self.texture) return nil; auto pass = self.view.currentRenderPassDescriptor; auto drawable = self.view.currentDrawable; if (!pass || !drawable) return nil; auto cmd = [self.queue commandBuffer]; if (!encodeImage(cmd, pass, self.texture, self.pipeline)) return nil; [cmd presentDrawable:drawable]; [cmd commit]; return cmd; } @end static void status(Screen *screen, NSString *title) { dispatch_async(dispatch_get_main_queue(), ^{ screen.window.title = title; }); } static void observe(Screen *screen, std::string raw, Config c, std::string ca, int proxy, int port, const std::string &remoteHost, const std::string &tlsName) { auto ctx = context(true); SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr); sslok(SSL_CTX_load_verify_locations(ctx.get(), ca.c_str(), nullptr), "CA certificate"); FD sock(socket(AF_INET, SOCK_STREAM, 0)); socks(sock.fd, proxy, port, remoteHost); auto tls = session(ctx.get(), sock.fd); sslok(SSL_set_tlsext_host_name(tls.get(), tlsName.c_str()), "TLS SNI"); sslok(SSL_set1_host(tls.get(), tlsName.c_str()), "TLS name"); sslok(SSL_connect(tls.get()), "TLS handshake"); Bytes config(raw.begin(), raw.end()); sendMsg(tls.get(), CONFIG, config); require(receive(tls.get(), {ACCEPTED, ERROR_MSG}).second == config, "config echo mismatch"); u64 frameId = 0, prev = 0; __block u64 uploadNs = 0; auto start = std::chrono::steady_clock::now(); do { @autoreleasepool { auto data = receive(tls.get(), {FRAME, ERROR_MSG}).second; auto b = data.data(); u64 gen = get(b + 8, 8); require(data.size() == 32 + c.bytes() && get(b, 8) == frameId + 1 && (frameId ? gen > prev : gen == 0) && gen <= c.g && get(b + 16, 4) == c.aw() && get(b + 20, 4) == c.ah() && get(b + 24, 4) == c.k && get(b + 28, 4) == 1, "invalid FRAME"); __block id cmd = nil; dispatch_sync(dispatch_get_main_queue(), ^{ auto texDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm width:c.aw() height:c.ah() mipmapped:NO]; texDesc.storageMode = MTLStorageModeShared; auto tex = [screen.view.device newTextureWithDescriptor:texDesc]; const auto uploadStart = std::chrono::steady_clock::now(); [tex replaceRegion:MTLRegionMake2D(0, 0, c.aw(), c.ah()) mipmapLevel:0 withBytes:b + 32 bytesPerRow:4 * c.aw()]; uploadNs += std::chrono::duration_cast( std::chrono::steady_clock::now() - uploadStart) .count(); screen.texture = tex; screen.lastDraw = nil; [screen.view draw]; cmd = screen.lastDraw; }); require(cmd != nil, "Metal drawable or texture unavailable"); [cmd waitUntilCompleted]; if (cmd.status != MTLCommandBufferStatusCompleted) throw std::runtime_error(cmd.error.localizedDescription.UTF8String ?: "Metal presentation failed"); Bytes ack; put(ack, ++frameId, 8); sendMsg(tls.get(), ACK, ack); prev = gen; status(screen, [NSString stringWithFormat:@"RPS · Поколение %llu / %u", (unsigned long long)gen, c.g]); } } while (prev < c.g); auto done = receive(tls.get(), {FINISHED, ERROR_MSG}).second; require(get(done.data(), 8) == c.g && get(done.data() + 8, 4) == 0, "invalid FINISHED"); auto durationNs = std::chrono::duration_cast( std::chrono::steady_clock::now() - start) .count(); std::cerr << "metal_upload_ns=" << uploadNs << " milli_fps=" << uint64_t(__uint128_t(frameId) * 1000000000000ULL / durationNs) << " finished frames=" << frameId << " generation=" << prev << " elapsed_ms=" << std::chrono::duration_cast( std::chrono::steady_clock::now() - start) .count() << "\n"; status(screen, [NSString stringWithFormat:@"RPS · Завершено · Поколение %u", c.g]); SSL_shutdown(tls.get()); } int main(int argc, char **argv) { @autoreleasepool { try { signal(SIGPIPE, SIG_IGN); std::map opts; require(argc % 2 == 1, "expected option value"); for (int i = 1; i < argc; i += 2) opts[argv[i]] = argv[i + 1]; auto port = [&](const char *key, int fallback) { int n = opts.count(key) ? std::stoi(opts.at(key)) : fallback; require(n > 0 && n <= 65535, "port range"); return n; }; [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; [NSApp activateIgnoringOtherApps:YES]; if (!opts.count("--config")) { auto panel = [NSOpenPanel openPanel]; panel.message = @"Выберите JSON конфигурации симуляции"; if ([panel runModal] != NSModalResponseOK) return 0; opts["--config"] = panel.URL.fileSystemRepresentation; } const bool sharedProxy = opts.count("--host") != 0; if (!opts.count("--ca")) { NSString *path = sharedProxy ? @"~/.config/skeleton/pki/root-ca.crt" : @"~/Library/Application Support/rps-cuda/server.crt"; path = [path stringByExpandingTildeInPath]; if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { auto panel = [NSOpenPanel openPanel]; panel.message = @"Выберите доверенный сертификат CA"; if ([panel runModal] != NSModalResponseOK) return 0; path = panel.URL.path; } opts["--ca"] = path.fileSystemRepresentation; } auto raw = readConfig(opts.at("--config")); auto c = parse(raw); auto ca = opts.at("--ca"); int proxy = port("--socks-port", sharedProxy ? 11082 : 11080), remote = port("--port", 7443); const std::string remoteHost = sharedProxy ? opts.at("--host") : "127.0.0.1"; const std::string tlsName = sharedProxy ? remoteHost : "infra-gpu"; Screen *screen = [Screen new]; require([screen setup], "cannot initialize Metal"); [NSApp activateIgnoringOtherApps:YES]; dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ @autoreleasepool { try { observe(screen, raw, c, ca, proxy, remote, remoteHost, tlsName); } catch (const std::exception &e) { std::cerr << e.what() << "\n"; status(screen, [NSString stringWithFormat:@"RPS · Ошибка · %s", e.what()]); } } }); [NSApp run]; return 0; } catch (const std::exception &e) { std::cerr << e.what() << "\n"; return 1; } } }