diff --git a/Sources/UntoldEngine/Renderer/RenderPasses.swift b/Sources/UntoldEngine/Renderer/RenderPasses.swift index 4db3df444..3a8387afd 100644 --- a/Sources/UntoldEngine/Renderer/RenderPasses.swift +++ b/Sources/UntoldEngine/Renderer/RenderPasses.swift @@ -630,6 +630,25 @@ public enum RenderPasses { refuseTileLightStage(state, reason: "the stage's imageblock needs \(tileMemoryNeeded) bytes in a 16×16 tile, the GPU's tile memory holds \(renderInfo.device.maxThreadgroupMemoryLength)") return nil } + // Left at 0×0 (auto), Metal sometimes picks a tile whose thread count + // (dispatchThreadsPerTile covers it one thread per pixel) exceeds this very + // pipeline's own maxTotalThreadsPerThreadgroup -- seen under ARKit camera + // capture, where the GPU's tile budget is squeezed by the capture pipeline. + // Request the largest square tile that fits both the memory budget above and + // the pipeline's thread budget, so the dispatch below can never overrun it. + var tileSide = 16 + while tileSide * 2 * (tileSide * 2) <= state.maxTotalThreadsPerThreadgroup, + bytesPerSample * max(1, renderInfo.opaqueSampleCount) * (tileSide * 2) * (tileSide * 2) + <= renderInfo.device.maxThreadgroupMemoryLength + { + tileSide *= 2 + } + guard tileSide * tileSide <= state.maxTotalThreadsPerThreadgroup else { + refuseTileLightStage(state, reason: "the smallest 16×16 tile needs \(tileSide * tileSide) threads, the pipeline's budget is \(state.maxTotalThreadsPerThreadgroup)") + return nil + } + descriptor.tileWidth = tileSide + descriptor.tileHeight = tileSide descriptor.imageblockSampleLength = state.imageblockSampleLength return state #endif @@ -5276,8 +5295,29 @@ public enum RenderPasses { renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreAction.store renderPassDescriptor.depthAttachment.loadAction = MTLLoadAction.load renderPassDescriptor.depthAttachment.storeAction = MTLStoreAction.store - renderPassDescriptor.tileWidth = 32 - renderPassDescriptor.tileHeight = 32 + + // A fixed 32x32 tile dispatches 1024 threads (dispatchThreadsPerTile below covers + // the tile one thread per pixel); on a GPU whose tile budget for this pipeline is + // squeezed below that (seen under ARKit camera capture — see the identical fix for + // the light-tile stage above), that overruns initializePipelineState's own + // maxTotalThreadsPerThreadgroup, which hangs or kills the app with no Metal + // validation message to explain why. Pick the largest square tile, up to 32x32, + // that fits both this pipeline's thread budget and its imageblock's memory budget. + let gaussianBytesPerSample = (initializePipelineState.imageblockSampleLength + 15) / 16 * 16 + var gaussianTileSide = 16 + while gaussianTileSide < 32, + gaussianTileSide * 2 * (gaussianTileSide * 2) <= initializePipelineState.maxTotalThreadsPerThreadgroup, + gaussianBytesPerSample * (gaussianTileSide * 2) * (gaussianTileSide * 2) + <= renderInfo.device.maxThreadgroupMemoryLength + { + gaussianTileSide *= 2 + } + guard gaussianTileSide * gaussianTileSide <= initializePipelineState.maxTotalThreadsPerThreadgroup else { + handleError(.pipelineStateNulled, "Gaussian TBDR initialize pipeline's thread budget (\(initializePipelineState.maxTotalThreadsPerThreadgroup)) is too small even for a 16x16 tile") + return + } + renderPassDescriptor.tileWidth = gaussianTileSide + renderPassDescriptor.tileHeight = gaussianTileSide renderPassDescriptor.imageblockSampleLength = initializePipelineState.imageblockSampleLength // Snapshot the opaque depth before the pass so splats can be occluded by it. @@ -5319,7 +5359,7 @@ public enum RenderPasses { renderEncoder.pushDebugGroup("Initialize") renderEncoder.setRenderPipelineState(initializePipelineState) - renderEncoder.dispatchThreadsPerTile(MTLSize(width: 32, height: 32, depth: 1)) + renderEncoder.dispatchThreadsPerTile(MTLSize(width: renderEncoder.tileWidth, height: renderEncoder.tileHeight, depth: 1)) profileTotals.dispatchCount += 1 renderEncoder.popDebugGroup() diff --git a/Sources/UntoldEngine/Renderer/UntoldEngine.swift b/Sources/UntoldEngine/Renderer/UntoldEngine.swift index ee957a32c..dd97cba89 100644 --- a/Sources/UntoldEngine/Renderer/UntoldEngine.swift +++ b/Sources/UntoldEngine/Renderer/UntoldEngine.swift @@ -951,7 +951,10 @@ public class UntoldRenderer: NSObject, MTKViewDelegate { renderInfo.reverseZEnabled = true renderInfo.colorPixelFormat = view.colorPixelFormat renderInfo.depthPixelFormat = view.depthStencilPixelFormat - renderInfo.viewPort = simd_float2(Float(view.bounds.size.width), Float(view.bounds.size.height)) + // Pixels, not points — matches the non-AR create(device:view:) above; drawRectResized + // corrects this on the first resize callback regardless, but starting from the same + // units as the working path avoids a transient wrong-aspect first frame. + renderInfo.viewPort = simd_float2(Float(view.drawableSize.width), Float(view.drawableSize.height)) renderInfo.fence = renderInfo.device.makeFence() renderInfo.bufferAllocator = MTKMeshBufferAllocator(device: renderInfo.device) diff --git a/Sources/UntoldEngine/Shaders/ARShader.metal b/Sources/UntoldEngine/Shaders/ARShader.metal index 3c7aaa539..e010d387b 100644 --- a/Sources/UntoldEngine/Shaders/ARShader.metal +++ b/Sources/UntoldEngine/Shaders/ARShader.metal @@ -64,9 +64,18 @@ fragment float4 capturedImageFragmentShader(ImageColorInOut in [[stage_in]], // Sample Y and CbCr textures to get the YCbCr color at the given texture coordinate float4 ycbcr = float4(capturedImageTextureY.sample(colorSampler, in.texCoord).r, capturedImageTextureCbCr.sample(colorSampler, in.texCoord).rg, 1.0); - - // Return converted RGB color - return ycbcrToRGBTransform * ycbcr; + + float4 rgb = ycbcrToRGBTransform * ycbcr; + + // The camera feed is gamma (display-referred); this pass's target holds linear scene + // radiance (see fragmentEnvironmentShader, which writes HDR values straight through to + // the same attachment). Decode sRGB gamma to linear so the two sources agree, or the + // tonemap/exposure pipeline downstream reads the camera image as far brighter than it is. + float3 linearColor = select(rgb.rgb / 12.92f, + powr((rgb.rgb + 0.055f) / 1.055f, 2.4f), + rgb.rgb > 0.04045f); + + return float4(linearColor, rgb.a); } diff --git a/Sources/UntoldEngine/Systems/RenderingSystem.swift b/Sources/UntoldEngine/Systems/RenderingSystem.swift index 841b95557..be17698d2 100644 --- a/Sources/UntoldEngine/Systems/RenderingSystem.swift +++ b/Sources/UntoldEngine/Systems/RenderingSystem.swift @@ -175,6 +175,27 @@ func UpdateXRRenderingSystem(commandBuffer: MTLCommandBuffer, passDescriptor: MT commandBuffer.label = "XR Rendering Command Buffer" + // The AR path renders its single eye through this callback with no eye loop around it (see + // the HZB build below), so it never goes through executeXRSystemPass's once-before-the-eyes + // render prep — without this, visibleEntityIds is never snapshotted from this frame's cull + // (every mesh pass filters by it, so nothing draws, not just Gaussian splats), and frustum + // culling, the Gaussian cull/preprocess, and the radix sort that feeds + // GaussianSharedWorkingSet never run (gaussianExecution's first guard then silently skips + // the pass forever, with no error). Mirrors executeXRSystemPass's once-before-the-eyes + // block exactly; the stereo XR path already ran that once, so it must not run again here. + if renderInfo.immersionStyle == .ar { + renderInfo.currentInFlightFrameSlot = acquireUniformFrameSlot() + let loading = AssetLoadingGate.shared.isLoadingAny + if !loading { + visibleEntityIds = tripleVisibleEntities.snapshotForRead(frame: cullFrameIndex) + SceneRootTransform.shared.updateIfNeeded() + performFrustumCulling(commandBuffer: commandBuffer) + executeGaussianFrustumCulling(commandBuffer) + executeGaussianPreprocess(commandBuffer) + executeRadixSort(commandBuffer) + } + } + do { // This eye's sub-pixel jitter (temporal anti-aliasing), before anything reads the projection. TemporalAntiAliasing.shared.applyJitter() diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-ios.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-ios.metallib index 5ad3ad8df..a9a49f87c 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-ios.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-ios.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-iossim.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-iossim.metallib index ae3820f51..b62d457bf 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-iossim.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-iossim.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvos.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvos.metallib index 434a6a2d6..4279b21d7 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvos.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvos.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvossim.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvossim.metallib index 77643557f..19790bb34 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvossim.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvossim.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xros.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xros.metallib index 980224947..ba99f9f66 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xros.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xros.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xrossim.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xrossim.metallib index 6cb75714c..737048261 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xrossim.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xrossim.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels.metallib index 4f5c2031f..4acff19c7 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels.metallib differ diff --git a/Sources/UntoldEngine/Utils/MathUtils.swift b/Sources/UntoldEngine/Utils/MathUtils.swift index b896113f7..a1f1049bc 100644 --- a/Sources/UntoldEngine/Utils/MathUtils.swift +++ b/Sources/UntoldEngine/Utils/MathUtils.swift @@ -258,6 +258,24 @@ public func matrix_float4x4_from_double4x4(_ m: simd_double4x4) -> matrix_float4 ) } +/// Converts a standard (forward-Z, near→0 far→1) right-hand perspective matrix — e.g. one +/// ARKit hands back from `ARCamera.projectionMatrix(for:viewportSize:zNear:zFar:)` — into this +/// engine's reverse-Z convention (near→1 far→0), for use where `renderInfo.reverseZEnabled` is +/// true (every depth compare, HZB occlusion test, and shadow depth in the renderer assumes it). +/// Only the Z-mapping terms change (see `matrixPerspectiveRightHand` vs +/// `matrixPerspectiveRightHandReverseZ`, which differ solely in these two entries); the X/Y +/// terms — including any principal-point offset a real camera's matrix carries that an +/// idealized symmetric FOV does not — are passed through untouched. +public func matrixPerspectiveReverseZ( + fromForwardZ projection: matrix_float4x4, nearZ: Float, farZ: Float +) -> matrix_float4x4 { + var m = projection + let zs = nearZ / (farZ - nearZ) + m.columns.2.z = zs + m.columns.3.z = zs * farZ + return m +} + public func matrixPerspectiveRightHand( fovyRadians fovy: Float, aspectRatio: Float, nearZ: Float, farZ: Float ) -> matrix_float4x4 { diff --git a/Sources/UntoldEngineAR/UntoldEngineAR.swift b/Sources/UntoldEngineAR/UntoldEngineAR.swift index 186d3099d..b4aca5a95 100644 --- a/Sources/UntoldEngineAR/UntoldEngineAR.swift +++ b/Sources/UntoldEngineAR/UntoldEngineAR.swift @@ -135,7 +135,17 @@ currentARCamera = currentFrame.camera.viewMatrix(for: .landscapeRight) let vpSize = CGSize(width: CGFloat(renderInfo.viewPort.x), height: CGFloat(renderInfo.viewPort.y)) - currentARProjection = currentFrame.camera.projectionMatrix(for: .landscapeRight, viewportSize: vpSize, zNear: 0.001, zFar: 1000) + let arZNear: CGFloat = 0.001 + let arZFar: CGFloat = 1000 + let forwardZProjection = currentFrame.camera.projectionMatrix(for: .landscapeRight, viewportSize: vpSize, zNear: arZNear, zFar: arZFar) + // Every depth compare, HZB occlusion test, and shadow depth downstream assumes + // reverseZEnabled's near->1/far->0 mapping (see matrixPerspectiveRightHandReverseZ); + // ARKit's matrix is the standard near->0/far->1 one, so it must be converted here — + // there is no other camera path in the engine that hands reverseZEnabled a + // non-reversed projection. + currentARProjection = renderInfo.reverseZEnabled + ? matrixPerspectiveReverseZ(fromForwardZ: forwardZProjection, nearZ: Float(arZNear), farZ: Float(arZFar)) + : forwardZProjection EngineProfiler.shared.beginScope(.renderPrep) updateARStates(currentFrame: currentFrame) @@ -220,7 +230,8 @@ capturedImagePipelineStateDescriptor.vertexFunction = capturedImageVertexFunction capturedImagePipelineStateDescriptor.fragmentFunction = capturedImageFragmentFunction capturedImagePipelineStateDescriptor.vertexDescriptor = imagePlaneVertexDescriptor - capturedImagePipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm_srgb + capturedImagePipelineStateDescriptor.colorAttachments[0].pixelFormat = + textureResources.environmentColorMap?.pixelFormat ?? .bgra8Unorm_srgb capturedImagePipelineStateDescriptor.depthAttachmentPixelFormat = .depth32Float // capturedImagePipelineStateDescriptor.stencilAttachmentPixelFormat = .depth32Float_stencil8 diff --git a/Tests/UntoldEngineRenderTests/TileLightStageTests.swift b/Tests/UntoldEngineRenderTests/TileLightStageTests.swift index 49349ecde..874dc248b 100644 --- a/Tests/UntoldEngineRenderTests/TileLightStageTests.swift +++ b/Tests/UntoldEngineRenderTests/TileLightStageTests.swift @@ -166,7 +166,13 @@ final class TileLightStageTests: BaseRenderSetup { setRendering(.tileLightStage(.enabled)) drawFrame() XCTAssertTrue(renderInfo.tileLightStageUsed) - XCTAssertEqual(renderInfo.offscreenRenderPassDescriptor.tileWidth, 0, "the tile size is left to Metal") + // No longer left at 0 for Metal to auto-pick: Metal can choose a tile whose thread + // count overruns the pipeline's own maxTotalThreadsPerThreadgroup (seen on device + // under ARKit camera capture, where the GPU's tile budget is squeezed below what it + // picks by default) — tileLightStage now requests an explicit square tile sized to + // fit both the memory and thread budgets, at least the 16x16 floor. + XCTAssertEqual(renderInfo.offscreenRenderPassDescriptor.tileWidth, renderInfo.offscreenRenderPassDescriptor.tileHeight, "the stage requests a square tile") + XCTAssertGreaterThanOrEqual(renderInfo.offscreenRenderPassDescriptor.tileWidth, 16, "never below the smallest tile the memory check already assumed") XCTAssertGreaterThan(renderInfo.offscreenRenderPassDescriptor.imageblockSampleLength, 0, "the stage tells the pass its imageblock") } }