import Folding import Foundation import Metal import simd public enum RendererError: Error, Equatable, Sendable { case shadersMissing case allocationFailed } /// Draws a render mesh with Metal. /// /// Each coplanar cluster is drawn back to front in its order with the depth test on and depth /// writes off, so that its stacked faces resolve by layer order, then drawn again depth-only, so /// that clusters drawn after it are hidden behind it. Faces in different clusters resolve by depth. /// /// Facets are two-sided. Unless `faceColours` is given, the side a FOLD face's normal points toward /// is drawn in `frontColour` and the other in `backColour`, shaded by a light along the view /// direction. public final class PaperRenderer { public static let frontColour = SIMD4(0.80, 0.22, 0.18, 1) public static let backColour = SIMD4(0.96, 0.94, 0.89, 1) /// The clear colour. public static let background = SIMD4(0, 0, 0, 0) /// The shade of a face seen edge-on; a face square to the view direction has its full colour. private static let edgeOnShade: Float = 0.35 public let device: MTLDevice /// The queue `render` commits to. Work committed to it afterwards runs after the frame. public let commandQueue: MTLCommandQueue private let vertexFunction: MTLFunction private let fragmentFunction: MTLFunction /// Depth test on, writes off: a cluster's colour pass. private let colourPass: MTLDepthStencilState /// Depth test and writes on: a cluster's depth pass. private let depthPass: MTLDepthStencilState /// Per colour pixel format, the pipeline that draws colour and the one that draws depth only. private var pipelines: [MTLPixelFormat: (colour: MTLRenderPipelineState, depth: MTLRenderPipelineState)] = [:] private var depthTexture: MTLTexture? /// The vertex buffer, reused while it is large enough. private var vertexBuffer: MTLBuffer? /// The last frame's commands, which read `vertexBuffer`. private var lastFrame: MTLCommandBuffer? private struct PaperVertex { var position: SIMD3 var normal: SIMD3 } private struct Shading { var front: SIMD4 var back: SIMD4 var light: SIMD4 } public init(device: MTLDevice) throws { guard let url = Bundle.module.url(forResource: "Shaders", withExtension: "metal") else { throw RendererError.shadersMissing } let library = try device.makeLibrary(source: String(contentsOf: url, encoding: .utf8), options: nil) guard let vertexFunction = library.makeFunction(name: "paperVertex"), let fragmentFunction = library.makeFunction(name: "paperFragment") else { throw RendererError.shadersMissing } let depth = MTLDepthStencilDescriptor() depth.depthCompareFunction = .lessEqual depth.isDepthWriteEnabled = false let colourPass = device.makeDepthStencilState(descriptor: depth) depth.isDepthWriteEnabled = true guard let queue = device.makeCommandQueue(), let colourPass, let depthPass = device.makeDepthStencilState(descriptor: depth) else { throw RendererError.allocationFailed } self.device = device commandQueue = queue self.vertexFunction = vertexFunction self.fragmentFunction = fragmentFunction self.colourPass = colourPass self.depthPass = depthPass } /// Draws `mesh` with its vertices at `positions` into `target`, cleared to `background`. /// Faces in no cluster are not drawn. `faceColours`, when given, draws FOLD face i in /// `faceColours[i]`, unlit, on both sides. Waits for the previous frame to finish, since it /// reuses that frame's vertex buffer, then commits to `commandQueue` without waiting for this one. public func render(positions: [SIMD3], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera, faceColours: [SIMD4]? = nil, into target: MTLTexture) throws { let (vertices, ranges) = groupedVertices(positions: positions, mesh: mesh) let pipeline = try pipelines(for: target.pixelFormat) guard let buffer = vertexBuffer(holding: vertices), let depth = depthTexture(width: target.width, height: target.height), let commands = commandQueue.makeCommandBuffer() else { throw RendererError.allocationFailed } let pass = MTLRenderPassDescriptor() let b = Self.background pass.colorAttachments[0].texture = target pass.colorAttachments[0].loadAction = .clear pass.colorAttachments[0].clearColor = MTLClearColor(red: Double(b.x), green: Double(b.y), blue: Double(b.z), alpha: Double(b.w)) pass.colorAttachments[0].storeAction = .store pass.depthAttachment.texture = depth pass.depthAttachment.loadAction = .clear pass.depthAttachment.clearDepth = 1 pass.depthAttachment.storeAction = .dontCare guard let encoder = commands.makeRenderCommandEncoder(descriptor: pass) else { throw RendererError.allocationFailed } let d = SIMD3(camera.viewDirection) let lit = Shading(front: Self.frontColour, back: Self.backColour, light: SIMD4(d, Self.edgeOnShade)) let vp = camera.viewProjection(aspect: Double(target.width) / Double(target.height)) var viewProjection = simd_float4x4(columns: (SIMD4(vp.columns.0), SIMD4(vp.columns.1), SIMD4(vp.columns.2), SIMD4(vp.columns.3))) encoder.setFrontFacing(.counterClockwise) encoder.setCullMode(.none) encoder.setVertexBuffer(buffer, offset: 0, index: 0) encoder.setVertexBytes(&viewProjection, length: MemoryLayout.stride, index: 1) func draw(_ face: Int) { guard ranges.indices.contains(face), !ranges[face].isEmpty else { return } encoder.drawPrimitives(type: .triangle, vertexStart: ranges[face].lowerBound, vertexCount: ranges[face].count) } func setShading(_ shading: Shading) { var shading = shading encoder.setFragmentBytes(&shading, length: MemoryLayout.stride, index: 0) } if faceColours == nil { setShading(lit) } for cluster in clusters { encoder.setRenderPipelineState(pipeline.colour) encoder.setDepthStencilState(colourPass) for face in cluster.faces { if let colour = faceColours?[face] { setShading(Shading(front: colour, back: colour, light: SIMD4(d, 1))) } draw(face) } encoder.setRenderPipelineState(pipeline.depth) encoder.setDepthStencilState(depthPass) for face in cluster.faces { draw(face) } } encoder.endEncoding() commands.commit() lastFrame = commands } /// `vertexBuffer` filled with `vertices`, after the last frame has finished reading it; a new /// one when it is too small. private func vertexBuffer(holding vertices: [PaperVertex]) -> MTLBuffer? { let length = vertices.count * MemoryLayout.stride lastFrame?.waitUntilCompleted() if (vertexBuffer?.length ?? 0) < length { vertexBuffer = device.makeBuffer(length: length, options: .storageModeShared) } guard let vertexBuffer else { return nil } memcpy(vertexBuffer.contents(), vertices, length) return vertexBuffer } /// Three vertices per triangle, each with its triangle's normal, grouped by FOLD face; and /// each FOLD face's range in them. private func groupedVertices(positions: [SIMD3], mesh: RenderMesh) -> ([PaperVertex], [Range]) { let faceCount = (mesh.faceOf.max() ?? -1) + 1 var start = Array(repeating: 0, count: faceCount + 1) for f in mesh.faceOf { start[f + 1] += 3 } for f in 0..(length(n) > 0 ? normalize(n) : .zero) let f = mesh.faceOf[t] for v in [a, b, c] { vertices[next[f]] = PaperVertex(position: SIMD3(positions[v]), normal: normal) next[f] += 1 } } return (vertices, (0.. (colour: MTLRenderPipelineState, depth: MTLRenderPipelineState) { if let cached = pipelines[format] { return cached } let descriptor = MTLRenderPipelineDescriptor() descriptor.vertexFunction = vertexFunction descriptor.fragmentFunction = fragmentFunction descriptor.colorAttachments[0].pixelFormat = format descriptor.depthAttachmentPixelFormat = .depth32Float let colour = try device.makeRenderPipelineState(descriptor: descriptor) descriptor.colorAttachments[0].writeMask = [] let depth = try device.makeRenderPipelineState(descriptor: descriptor) pipelines[format] = (colour, depth) return (colour, depth) } private func depthTexture(width: Int, height: Int) -> MTLTexture? { if let depthTexture, depthTexture.width == width, depthTexture.height == height { return depthTexture } let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width, height: height, mipmapped: false) descriptor.usage = .renderTarget #if os(iOS) descriptor.storageMode = .memoryless #else descriptor.storageMode = .private #endif depthTexture = device.makeTexture(descriptor: descriptor) return depthTexture } }