diff --git a/app/src/androidTest/java/com/hinnka/mycamera/processor/OglBokehProcessorShaderTest.kt b/app/src/androidTest/java/com/hinnka/mycamera/processor/OglBokehProcessorShaderTest.kt index e160accd..b3975a69 100644 --- a/app/src/androidTest/java/com/hinnka/mycamera/processor/OglBokehProcessorShaderTest.kt +++ b/app/src/androidTest/java/com/hinnka/mycamera/processor/OglBokehProcessorShaderTest.kt @@ -3,6 +3,8 @@ package com.hinnka.mycamera.processor import android.graphics.Bitmap import android.graphics.Color import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.hinnka.mycamera.ml.RelativeDepthMap +import com.hinnka.mycamera.ml.SubjectMask import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue @@ -13,19 +15,22 @@ import org.junit.runner.RunWith class OglBokehProcessorShaderTest { @Test fun productionBokehShadersCompileAndLinkOnDevice() { - val processor = OglBokehProcessor() - try { - assertEquals(1922 to 2560, invokePrivate(processor, "resolveBokehRenderSize", 4098, 5458)) - invokePrivate(processor, "initEGL", 32, 32) - invokePrivate(processor, "initGL") + for (style in listOf(BokehStyle.DEFAULT, BokehStyle.NATURAL)) { + val processor = OglBokehProcessor() + try { + assertEquals(1922 to 2560, invokePrivate(processor, "resolveBokehRenderSize", 4098, 5458, 2560)) + invokePrivate(processor, "initEGL", 32, 32) + invokePrivate(processor, "initGL", style, null) - assertTrue(readPrivateInt(processor, "compactHighlightProgramId") != 0) - assertTrue(readPrivateInt(processor, "bokehProgramId") != 0) - assertTrue(readPrivateInt(processor, "bokehCompositeProgramId") != 0) - assertTrue(readPrivateInt(processor, "jbuUpsampleProgramId") != 0) - assertTrue(readPrivateInt(processor, "depthSharpenProgramId") != 0) - } finally { - invokePrivate(processor, "releaseGL") + assertEquals(style == BokehStyle.DEFAULT, readPrivateInt(processor, "compactHighlightProgramId") != 0) + assertEquals(style == BokehStyle.DEFAULT, readPrivateInt(processor, "analyticHighlightProgramId") != 0) + assertTrue(readPrivateInt(processor, "bokehProgramId") != 0) + assertTrue(readPrivateInt(processor, "bokehCompositeProgramId") != 0) + assertTrue(readPrivateInt(processor, "jbuUpsampleProgramId") != 0) + assertTrue(readPrivateInt(processor, "depthRefineProgramId") != 0) + } finally { + invokePrivate(processor, "releaseGL") + } } } @@ -40,9 +45,9 @@ class OglBokehProcessorShaderTest { val result = try { OglBokehProcessor().applyBokeh( originalImage = input, - lowResDepthMap = depth, - focusX = 0.5f, - focusY = 0.5f, + lowResDepthMap = RelativeDepthMap.fromBitmap(depth), + subjectMask = SubjectMask(1, 1, floatArrayOf(0f)), + focusDepth = 128f / 255f, aperture = 1.4f, ) } finally { @@ -86,9 +91,9 @@ class OglBokehProcessorShaderTest { val result = try { OglBokehProcessor().applyBokeh( originalImage = input, - lowResDepthMap = depth, - focusX = 0.5f, - focusY = 0.5f, + lowResDepthMap = RelativeDepthMap.fromBitmap(depth), + subjectMask = SubjectMask(1, 1, floatArrayOf(0f)), + focusDepth = 224f / 255f, aperture = 1.2f, ) } finally { @@ -160,9 +165,9 @@ class OglBokehProcessorShaderTest { val result = try { OglBokehProcessor().applyBokeh( originalImage = input, - lowResDepthMap = depth, - focusX = 0.5f, - focusY = 0.5f, + lowResDepthMap = RelativeDepthMap.fromBitmap(depth), + subjectMask = SubjectMask(1, 1, floatArrayOf(0f)), + focusDepth = 224f / 255f, aperture = 1.2f, ) } finally { @@ -223,7 +228,7 @@ class OglBokehProcessorShaderTest { ) / 256 } - private fun invokePrivate(target: Any, methodName: String, vararg args: Any): Any? { + private fun invokePrivate(target: Any, methodName: String, vararg args: Any?): Any? { return target.javaClass.declaredMethods.first { it.name == methodName && it.parameterCount == args.size }.run { diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PhysicalBokehShaders.kt b/app/src/main/java/com/hinnka/mycamera/lut/PhysicalBokehShaders.kt new file mode 100644 index 00000000..cb2ad3f9 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/PhysicalBokehShaders.kt @@ -0,0 +1,274 @@ +package com.hinnka.mycamera.lut + +import com.hinnka.mycamera.processor.BokehDefocusModel + +/** Pupil-derived PSF integration over the shared, premultiplied complement layer. */ +internal object PhysicalBokehShaders { + /** Opening (erosion followed by dilation) estimates the extended background + * under finite lights. Unlike a surrounding maximum it survives neighbouring + * lights; unlike a surrounding minimum it preserves a straight bright step. + */ + fun emitterEnvironment(erosion: Boolean) = """#version 300 es + precision highp float; + in vec2 vTexCoord; + out vec4 fragColor; + uniform highp sampler2D uInputTexture; + uniform highp sampler2D uDepthTexture; + uniform vec2 uTexelSize; + uniform float uBaseCocRadius; + float valueAt(ivec2 pixel) { + vec4 value = texelFetch(uInputTexture, pixel, 0); + return ${if (erosion) "max(value.r, max(value.g, value.b)) / max(value.a, 0.0001)" else "value.r"}; + } + void main() { + ivec2 size = textureSize(uInputTexture, 0); + ivec2 center = clamp(ivec2(vTexCoord * vec2(size)), ivec2(0), size - 1); + float depth = texelFetch(uDepthTexture, center, 0).b; + float result = valueAt(center); + for (int i = 0; i < 32; ++i) { + float angle = float(i % 16) * 0.392699081699; + float radius = (i < 16 ? 0.5 : 1.0) * 0.4 * uBaseCocRadius; + // Use the identical discrete, symmetric element in both passes. + // Bilinear min/max probes would erode a straight step twice. + ivec2 offset = ivec2(round(radius * uTexelSize * vec2(size) * vec2(cos(angle), sin(angle)))); + ivec2 pixel = clamp(center + offset, ivec2(0), size - 1); + vec4 layer = texelFetch(uDepthTexture, pixel, 0); + if (abs(layer.b - depth) > 0.04 || layer.a > 0.05) continue; + result = ${if (erosion) "min" else "max"}(result, valueAt(pixel)); + } + fragColor = vec4(result, 0.0, 0.0, 1.0); + } + """.trimIndent() + + /** Positive compact-source radiance. The complement is subtracted using the + * exact same texture and LOD in gather; alpha remains geometric coverage. + * The opened environment rejects extended surfaces. This pass retains the + * observed footprint; subsequent reconstruction integrates accepted sources + * into point flux, while ambiguous light keeps the finite-source path. + */ + val separateEmitters = """#version 300 es + precision highp float; + in vec2 vTexCoord; + out vec4 fragColor; + uniform highp sampler2D uLayerColorTexture; + uniform highp sampler2D uDepthTexture; + uniform highp sampler2D uEmitterEnvironment; + uniform float uFocusDepth; + uniform float uAperture; + uniform vec2 uTexelSize; + ${BokehDefocusModel.GLSL_SOURCE} + float brightness(vec3 rgb) { return max(rgb.r, max(rgb.g, rgb.b)); } + float probe(vec2 uv, float depth, float centerBrightness) { + if (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0)))) return centerBrightness; + vec4 layer = textureLod(uDepthTexture, uv, 0.0); + vec4 source = textureLod(uLayerColorTexture, uv, 0.0); + if (abs(layer.b - depth) > 0.04 || source.a < 0.95) return centerBrightness; + return brightness(source.rgb / source.a); + } + void main() { + vec4 source = textureLod(uLayerColorTexture, vTexCoord, 0.0); + vec4 layer = textureLod(uDepthTexture, vTexCoord, 0.0); + float peak = brightness(source.rgb / max(source.a, 0.0001)); + float eligible = smoothstep(0.015, 0.04, uFocusDepth - layer.b) + * smoothstep(0.04, 0.12, computeCoc(layer.b) / uBaseCocRadius) + * smoothstep(0.95, 1.0, source.a); + if (eligible <= 0.0 || peak <= 0.0) { fragColor = vec4(0.0, 0.0, 0.0, source.a); return; } + float surround = textureLod(uEmitterEnvironment, vTexCoord, 0.0).r; + float seedPeak = peak; + for (int i = 0; i < 8; ++i) { + float angle = float(i) * 0.392699081699; + vec2 offset = vec2(cos(angle), sin(angle)) * uTexelSize * (0.4 * uBaseCocRadius); + // Include the wings of a finite light, not only its bright core. + // Otherwise its untransported wings fill the new caustic's centre. + vec2 seedOffset = offset * 0.375; + seedPeak = max(seedPeak, max(probe(vTexCoord + seedOffset, layer.b, 0.0), + probe(vTexCoord - seedOffset, layer.b, 0.0))); + } + float fraction = eligible * smoothstep(0.16, 0.5, seedPeak) * max(peak - surround, 0.0) / peak; + fragColor = vec4(source.rgb * fraction, source.a); + } + """.trimIndent() + + private val tableSampling = """ + uniform highp sampler2D uPsfCdf; + uniform highp sampler2D uPsfSupport; + uniform float uPsfBinWidth; + uniform float uMaxBlurRadius; + + vec3 depthRows(float depth) { + float row = clamp(depth, 0.0, 1.0) * float(textureSize(uPsfCdf, 0).y - 1); + return vec3(floor(row), min(floor(row) + 1.0, float(textureSize(uPsfCdf, 0).y - 1)), fract(row)); + } + float support(float depth) { + vec3 rows = depthRows(depth); + return max(texelFetch(uPsfSupport, ivec2(0, int(rows.x)), 0).r, + texelFetch(uPsfSupport, ivec2(0, int(rows.y)), 0).r); + } + float rowEnergy(int row, float radius) { + int bins = textureSize(uPsfCdf, 0).x - 1; + float position = clamp(radius / uPsfBinWidth, 0.0, float(bins)); + int bin = min(int(position), bins - 1); + float inner = float(bin); + // Each annulus has constant area density, so its CDF interpolates in r². + float fraction = (position * position - inner * inner) / (2.0 * inner + 1.0); + return mix(texelFetch(uPsfCdf, ivec2(bin, row), 0).r, + texelFetch(uPsfCdf, ivec2(bin + 1, row), 0).r, fraction); + } + float energy(float depth, float radius) { + vec3 rows = depthRows(depth); + return mix(rowEnergy(int(rows.x), radius), rowEnergy(int(rows.y), radius), rows.z); + } + float density(float depth, float radius, float halfFootprint) { + float inner = max(0.0, radius - halfFootprint); + float outer = radius + halfFootprint; + return (energy(depth, outer) - energy(depth, inner)) + / (3.14159265359 * (outer * outer - inner * inner)); + } + vec4 layersAt(vec2 uv) { + vec4 layers = textureLod(uDepthTexture, uv, 0.0); + ivec2 size = textureSize(uDepthTexture, 0); + layers.gb = texelFetch(uDepthTexture, clamp(ivec2(uv * vec2(size)), ivec2(0), size - 1), 0).gb; + return layers; + } + """.trimIndent() + + val gather = """#version 300 es + precision highp float; + in vec2 vTexCoord; + out vec4 fragColor; + uniform highp sampler2D uDepthTexture; + uniform highp sampler2D uLayerColorTexture; + uniform highp sampler2D uEmitterTexture; + uniform bool uSubtractEmitters; + uniform vec2 uTexelSize; + uniform float uFocusDepth; + uniform float uAperture; + ${BokehDefocusModel.GLSL_SOURCE} + $tableSampling + + void main() { + vec4 center = layersAt(vTexCoord); + if (center.a >= 0.999) { fragColor = vec4(0.0); return; } + float centerDepth = center.a >= 0.5 ? center.g : center.b; + float localRadius = min(uMaxBlurRadius, max(1.0, support(center.b) + uPsfBinWidth)); + float globalPdf = 0.25 / (3.14159265359 * uMaxBlurRadius * uMaxBlurRadius); + float localPdf = 0.75 / (3.14159265359 * localRadius * localRadius); + vec2 workingPixel = 1.0 / vec2(textureSize(uLayerColorTexture, 0)); + float outputPixelsPerWorkingPixel = workingPixel.x / uTexelSize.x; + vec3 sum = vec3(0.0); + float weightSum = 0.0; + // Two uniform-area proposals: dense local PSF support, plus full support + // for sources at other depths. The mixture PDF removes sampling bias. + for (int i = 0; i < 512; ++i) { + bool local = i < 384; + float index = float(local ? i : i - 384) + 0.5; + float count = local ? 384.0 : 128.0; + float radius = sqrt(index / count) * (local ? localRadius : uMaxBlurRadius); + float angle = index * 2.39996322973 + (local ? 0.0 : 1.57079632679); + vec2 offset = radius * vec2(cos(angle), sin(angle)); + vec2 sourceUv = vTexCoord + offset * uTexelSize; + // Unknown off-frame radiance is excluded together with its support. + // Clamping would duplicate border colors over an entire blur disc. + if (any(lessThan(sourceUv, vec2(0.0))) || any(greaterThan(sourceUv, vec2(1.0)))) continue; + float pdf = globalPdf + (radius <= localRadius ? localPdf : 0.0); + float footprint = max(outputPixelsPerWorkingPixel, sqrt(1.0 / (512.0 * pdf))); + vec4 sourceLayers = layersAt(sourceUv); + // Pixel integration is fixed by output resolution, independent + // of the proposal density. Sparse far taps must not widen rings. + float kernel = density(sourceLayers.b, radius, outputPixelsPerWorkingPixel * 0.5); + if (kernel <= 0.0) continue; + float lod = max(0.0, log2(footprint / outputPixelsPerWorkingPixel)); + vec4 source = textureLod(uLayerColorTexture, sourceUv, lod); + if (uSubtractEmitters) source.rgb -= textureLod(uEmitterTexture, sourceUv, lod).rgb; + // Shared layered-depth visibility model; it is independent of the PSF. + float centerOccludes = smoothstep(0.025, 0.075, centerDepth - sourceLayers.b); + float focusedProtection = 1.0 - smoothstep(0.8, 4.0, computeCoc(centerDepth)); + float visibility = 1.0 - centerOccludes * mix(0.28, 1.0, focusedProtection); + float weight = kernel * visibility / pdf; + sum += source.rgb * weight; + weightSum += source.a * weight; + } + fragColor = weightSum > 0.0 ? vec4(sum / weightSum, 1.0) : vec4(0.0); + } + """.trimIndent() + + val emitterVertex = """#version 300 es + precision highp float; + in vec2 aCenter; + in float aDepth; + in vec3 aFlux; + in float aSupport; + uniform vec2 uTexelSize; + out vec2 vTexCoord; + out vec2 vOffset; + flat out float vDepth; + flat out vec3 vFlux; + void main() { + const vec2 corners[6] = vec2[](vec2(-1,-1),vec2(1,-1),vec2(-1,1), + vec2(-1,1),vec2(1,-1),vec2(1,1)); + vOffset = corners[gl_VertexID] * aSupport; + vTexCoord = aCenter + vOffset * uTexelSize; + vDepth = aDepth; + vFlux = aFlux; + gl_Position = vec4(vTexCoord * 2.0 - 1.0, 0.0, 1.0); + } + """.trimIndent() + + /** Re-images an inferred point source once, instead of blurring its old PSF. + * RGB is integrated source flux in output-pixel units, never peak brightness. + * Additive blending also lets overlapping emitters retain their own rings. + */ + val emitterFragment = """#version 300 es + precision highp float; + in vec2 vTexCoord; + in vec2 vOffset; + flat in float vDepth; + flat in vec3 vFlux; + out vec4 fragColor; + uniform highp sampler2D uDepthTexture; + uniform float uPixelFootprint; + uniform float uFocusDepth; + uniform float uAperture; + ${BokehDefocusModel.GLSL_SOURCE} + $tableSampling + void main() { + vec4 center = layersAt(vTexCoord); + if (center.a >= 0.999) discard; + float centerDepth = center.a >= 0.5 ? center.g : center.b; + float occludes = smoothstep(0.025, 0.075, centerDepth - vDepth); + float protection = 1.0 - smoothstep(0.8, 4.0, computeCoc(centerDepth)); + float visibility = 1.0 - occludes * mix(0.28, 1.0, protection); + fragColor = vec4(vFlux * density(vDepth, length(vOffset), uPixelFootprint * 0.5) * visibility, 0.0); + } + """.trimIndent() + + fun composite(colorTransfer: String) = """#version 300 es + precision highp float; + in vec2 vTexCoord; + out vec4 fragColor; + uniform highp sampler2D uOriginalTexture; + uniform highp sampler2D uBokehTexture; + uniform highp sampler2D uEmitterBokehTexture; + uniform highp sampler2D uDepthTexture; + uniform float uFocusDepth; + uniform float uAperture; + ${BokehDefocusModel.GLSL_SOURCE} + $tableSampling + $colorTransfer + void main() { + vec4 original = texture(uOriginalTexture, vTexCoord); + vec4 background = texture(uBokehTexture, vTexCoord); + if (background.a <= 0.0) { fragColor = original; return; } + vec4 layers = layersAt(vTexCoord); + // Resolve coverage at full output resolution, retaining protected detail. + // CoC controls the shared focus transition. PSF support also includes + // residual aberration and belongs only to integration bounds. + float coverage = (1.0 - layers.a) * smoothstep(0.2, 1.2, computeCoc(layers.b)); + vec4 emitters = texture(uEmitterBokehTexture, vTexCoord); + vec3 transported = background.rgb / background.a; + if (emitters.a > 0.0) transported += emitters.rgb / emitters.a; + vec3 linear = mix(decodeColor(original.rgb), transported, coverage); + fragColor = vec4(encodeColor(linear), original.a); + } + """.trimIndent() +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt b/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt index 8683733b..29ce91c8 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt @@ -1,5 +1,7 @@ package com.hinnka.mycamera.lut +import com.hinnka.mycamera.processor.BokehDefocusModel + /** * GLSL 着色器源代码 */ @@ -505,21 +507,26 @@ object Shaders { """.trimIndent() /** 在线性域预乘非主体覆盖率,然后生成 mipmap,避免主体颜色进入背景采样足迹。 */ - val BOKEH_LAYER_COLOR_FRAGMENT_SHADER = """#version 300 es + val BOKEH_LAYER_COLOR_FRAGMENT_SHADER = bokehLayerColorFragmentShader() + + /** Shared coverage reconstruction; optical styles supply the source's exact transfer. */ + fun bokehLayerColorFragmentShader(colorTransfer: String? = null) = """#version 300 es precision highp float; + precision highp sampler2D; in vec2 vTexCoord; out vec4 fragColor; uniform sampler2D uInputTexture; uniform sampler2D uDepthTexture; uniform int uLinearInput; + ${colorTransfer ?: ""} + vec4 premultipliedSourceTexel(ivec2 position) { ivec2 size = textureSize(uInputTexture, 0); position = clamp(position, ivec2(0), size - 1); vec2 uv = (vec2(position) + 0.5) / vec2(size); vec3 color = texelFetch(uInputTexture, position, 0).rgb; - vec3 linear = uLinearInput != 0 ? max(color, vec3(0.0)) - : pow(clamp(color, 0.0, 1.0), vec3(2.2)); + vec3 linear = ${if (colorTransfer != null) "decodeColor(color)" else "uLinearInput != 0 ? max(color, vec3(0.0)) : pow(clamp(color, 0.0, 1.0), vec3(2.2))"}; float coverage = 1.0 - textureLod(uDepthTexture, uv, 0.0).a; return vec4(linear * coverage, coverage); } @@ -558,9 +565,7 @@ object Shaders { * 使用由近到远的完整环形探针验证中心是严格局部亮点。选中的圆环上任一方向 * 不暗于中心都会拒绝;多尺度半径则允许探针越过较宽的光源亮区。 */ - val COMPACT_BOKEH_HIGHLIGHT_FRAGMENT_SHADER = """ - #version 300 es - #define SOAP_BUBBLE_BOKEH 0 + val COMPACT_BOKEH_HIGHLIGHT_FRAGMENT_SHADER = """#version 300 es precision highp float; in vec2 vTexCoord; @@ -609,21 +614,7 @@ object Shaders { return dot(color, vec3(0.2126, 0.7152, 0.0722)); } - float computeCoc(float depth) { - float gap = max(abs(uFocusDepth - depth) - 0.015, 0.0); - float availableFocusSpan = max( - max(uFocusDepth, 1.0 - uFocusDepth) - 0.015, - 0.15 - ); - float normalizedGap = clamp(gap / availableFocusSpan, 0.0, 1.0); - float defocus = pow(normalizedGap, 1.25); - float apertureScale = min(1.4 / max(uAperture, 0.7), 1.25); - return clamp( - defocus * uMaxBlurRadius * apertureScale, - 0.0, - uMaxBlurRadius - ); - } + ${BokehDefocusModel.GLSL_SOURCE} int evaluateDarkRing( vec2 centerUV, @@ -764,31 +755,6 @@ object Shaders { return; } - float peakProbeRadius = clamp(coc * 0.10, 5.0, 12.0); - float localPeakSurroundLuma = 0.0; - for (int i = 0; i < 16; i++) { - vec2 peakProbeUV = vTexCoord + PROBE_DIRECTIONS[i] - * peakProbeRadius * uTexelSize; - localPeakSurroundLuma += luminance(toLinear( - textureLod(uInputTexture, peakProbeUV, 0.0).rgb - )); - } - localPeakSurroundLuma *= 1.0 / 16.0; - float localPeakContrast = max( - centerLuma - localPeakSurroundLuma, - 0.0 - ); - float compactCoreGate = smoothstep( - 0.008, - 0.055, - localPeakContrast - ); - float removalCoreGate = smoothstep( - 0.002, - 0.025, - localPeakContrast - ); - float maximumCoreDepthDelta = 0.0; for (int i = 0; i < 16; i++) { vec2 coreDepthUV = clamp( @@ -867,44 +833,29 @@ object Shaders { * pointShapeGate * neighborhoodContrastGate * depthCoherenceGate; - #if SOAP_BUBBLE_BOKEH == 1 - float broadHighlightSignal = classifiedHighlight - * removalCoreGate; - float compactHighlight = classifiedHighlight * compactCoreGate; - compactHighlight = pow(clamp(compactHighlight, 0.0, 1.0), 1.6); - - fragColor = vec4( - centerLinear * broadHighlightSignal, - compactHighlight - ); - #else vec3 residual = max(centerLinear - surroundLinear, vec3(0.0)); vec3 sourceSignal = mix(residual, centerLinear, 0.24); fragColor = vec4( sourceSignal * classifiedHighlight, classifiedHighlight ); - #endif } """.trimIndent() /** * 后期处理专用的圆形 PSF gather。 * - * Vogel 分布保留完整输入辐射;自然与泡泡模式使用中心亮、边缘暗的径向 PSF, - * 泡泡模式再由真实高光位置生成解析光环,避免随机贴片产生悬浮感。 + * Vogel 分布保留完整输入辐射;自然模式使用中心亮、边缘暗的径向 PSF, + * 默认模式额外合成紧凑高光的解析光斑。 */ - val PSF_SPLAT_FRAGMENT_SHADER = """ - #version 300 es + val PSF_SPLAT_FRAGMENT_SHADER = """#version 300 es #define NATURAL_BOKEH 0 - #define SOAP_BUBBLE_BOKEH 0 precision highp float; in vec2 vTexCoord; out vec4 fragColor; uniform sampler2D uDepthTexture; - uniform sampler2D uHighlightSourceTexture; uniform sampler2D uLayerColorTexture; uniform mat4 uDepthMatrix; @@ -918,21 +869,7 @@ object Shaders { const float GOLDEN_ANGLE = 2.39996323; const int SAMPLES = 640; - float computeCoc(float depth) { - float gap = max(abs(uFocusDepth - depth) - 0.015, 0.0); - float availableFocusSpan = max( - max(uFocusDepth, 1.0 - uFocusDepth) - 0.015, - 0.15 - ); - float normalizedGap = clamp(gap / availableFocusSpan, 0.0, 1.0); - float defocus = pow(normalizedGap, 1.25); - float apertureScale = min(1.4 / max(uAperture, 0.7), 1.25); - return clamp( - defocus * uMaxBlurRadius * apertureScale, - 0.0, - uMaxBlurRadius - ); - } + ${BokehDefocusModel.GLSL_SOURCE} vec2 biotarAperturePosition( vec2 offsetPixels, @@ -980,15 +917,7 @@ object Shaders { vec2 p = biotarAperturePosition(offsetPixels, sourceUV, coc); float lenP = length(p); - #if SOAP_BUBBLE_BOKEH == 1 - float softEdge = 1.0 - smoothstep(0.68, 1.06, lenP); - float radialEnergy = exp(-lenP * lenP * 1.48); - return softEdge * mix( - 0.14, - 1.0, - radialEnergy - ); - #elif NATURAL_BOKEH == 1 + #if NATURAL_BOKEH == 1 float softEdge = 1.0 - smoothstep(0.70, 1.05, lenP); float radialEnergy = exp(-lenP * lenP * 1.55); float centerWeightedTransmission = mix( @@ -1012,30 +941,6 @@ object Shaders { #endif } - float bubbleOpticalRimWeight( - vec2 offsetPixels, - vec2 sourceUV, - float coc - ) { - vec2 p = biotarAperturePosition(offsetPixels, sourceUV, coc); - float lenP = length(p); - float support = 1.0 - smoothstep(0.90, 1.05, lenP); - float transparentCore = mix( - 0.16, - 0.09, - smoothstep(0.0, 0.70, lenP) - ); - float innerShoulder = smoothstep(0.54, 0.76, lenP) - * (1.0 - smoothstep(0.90, 1.02, lenP)); - float broadOpticalRim = smoothstep(0.70, 0.84, lenP) - * (1.0 - smoothstep(0.97, 1.05, lenP)); - return support * ( - transparentCore - + innerShoulder * 0.18 - + broadOpticalRim * 0.64 - ); - } - float foregroundDefocusPotential(vec2 depthUV, float centerDepth) { float weightedPotential = 0.0; float totalWeight = 0.0; @@ -1108,17 +1013,11 @@ object Shaders { 0.0, log2(sampleFootprintUv * float(textureSize(uLayerColorTexture, 0).x)) ); - #if SOAP_BUBBLE_BOKEH == 1 float sceneIntegrationLod = inputIntegrationLod; - #else - float sceneIntegrationLod = inputIntegrationLod; - #endif vec3 accColor = centerLayerColor.rgb * centerWeight; float accWeight = centerLayerColor.a * centerWeight; - #if SOAP_BUBBLE_BOKEH == 1 - float softBase = max(4.5, uMaxBlurRadius * 0.16); - #elif NATURAL_BOKEH == 1 + #if NATURAL_BOKEH == 1 float softBase = max(3.5, uMaxBlurRadius * 0.12); #else float softBase = max(2.5, uMaxBlurRadius * 0.08); @@ -1190,44 +1089,6 @@ object Shaders { sampleUV, max(sCoc, centerCoc) ); - #if SOAP_BUBBLE_BOKEH == 1 - float compactSignalLod = clamp( - inputIntegrationLod - 0.25, - 0.0, - 2.5 - ); - float compactHighlightConfidence = textureLod( - uHighlightSourceTexture, - sampleUV, - compactSignalLod - ).a; - float expandedCompactConfidence = smoothstep( - 0.006, - 0.16, - compactHighlightConfidence - ); - float broadHighlightHint = smoothstep( - 0.42, - 0.86, - sampleLuma - ) * 0.34; - float bubbleMix = clamp( - expandedCompactConfidence * 0.88 - + broadHighlightHint, - 0.0, - 1.0 - ); - float bubbleRimResponse = bubbleOpticalRimWeight( - offsetPixels, - sampleUV, - max(sCoc, centerCoc) - ); - apertureResponse = mix( - apertureResponse, - bubbleRimResponse, - bubbleMix - ); - #endif float weight = commonWeight * apertureResponse * sampleLayerColor.a; if (weight > 0.0001) { @@ -1237,19 +1098,11 @@ object Shaders { 0.92, sampleLuma ) * smoothstep(8.0, 24.0, max(sCoc, centerCoc)); - #if SOAP_BUBBLE_BOKEH == 1 - float radianceWeight = mix( - 1.0, - 1.68, - highlightRecovery * bubbleMix - ); - #else float radianceWeight = mix( 1.0, 1.35, highlightRecovery ); - #endif accColor += baseLinear * weight * radianceWeight; accWeight += weight; } @@ -1269,7 +1122,6 @@ object Shaders { */ val ANALYTIC_BOKEH_HIGHLIGHT_VERTEX_SHADER = """ #version 300 es - #define SOAP_BUBBLE_BOKEH 0 precision highp float; in vec2 aPosition; @@ -1281,8 +1133,6 @@ object Shaders { out vec2 vAperturePosition; out float vFieldStrength; - flat out float vBubblePhase; - flat out float vCocPixels; flat out vec3 vSignal; void main() { @@ -1294,15 +1144,9 @@ object Shaders { : vec2(0.0, 1.0); vec2 tangential = vec2(-radial.y, radial.x); float fieldStrength = smoothstep(0.12, 1.15, fieldRadius); - #if SOAP_BUBBLE_BOKEH == 1 - float radialScale = mix(1.0, 0.78, fieldStrength); - float tangentialScale = mix(1.0, 1.02, fieldStrength); - float swirlShear = 0.03; - #else float radialScale = mix(1.0, 0.54, fieldStrength); float tangentialScale = mix(1.0, 1.08, fieldStrength); float swirlShear = 0.10; - #endif float shearedRadial = aPosition.y * radialScale - aPosition.x * swirlShear * fieldStrength * radialScale; vec2 offsetPixels = ( @@ -1314,21 +1158,16 @@ object Shaders { gl_Position = vec4(centerNdc + offsetNdc, 0.0, 1.0); vAperturePosition = aPosition; vFieldStrength = fieldStrength; - vBubblePhase = dot(aCenterUv, vec2(17.0, 29.0)) * 6.28318531; - vCocPixels = aCocPixels; vSignal = aSignal; } """.trimIndent() val ANALYTIC_BOKEH_HIGHLIGHT_FRAGMENT_SHADER = """ #version 300 es - #define SOAP_BUBBLE_BOKEH 0 precision highp float; in vec2 vAperturePosition; in float vFieldStrength; - flat in float vBubblePhase; - flat in float vCocPixels; flat in vec3 vSignal; out vec4 fragColor; @@ -1336,63 +1175,6 @@ object Shaders { float apertureTransmission(vec2 aperturePosition) { float normalizedDistance = length(aperturePosition); - #if SOAP_BUBBLE_BOKEH == 1 - float edgeWidth = max( - fwidth(normalizedDistance) * 1.10, - 0.0025 - ); - float support = 1.0 - smoothstep( - 0.992 - edgeWidth, - 1.0 + edgeWidth, - normalizedDistance - ); - float angle = atan(aperturePosition.y, aperturePosition.x); - float profileVariation = 0.5 + 0.5 * sin(vBubblePhase * 1.37); - float ringModulation = clamp( - 0.92 - + 0.08 * sin(angle * 2.0 + vBubblePhase) - + 0.04 * cos(angle * 3.0 - vBubblePhase * 0.7), - 0.80, - 1.08 - ); - float transparentCore = mix( - 0.085, - 0.052, - smoothstep(0.0, 0.84, normalizedDistance) - ); - float innerGlow = smoothstep( - mix(0.62, 0.72, profileVariation) - edgeWidth, - mix(0.78, 0.84, profileVariation) + edgeWidth, - normalizedDistance - ) * (1.0 - smoothstep( - 0.955 - edgeWidth, - 0.99 + edgeWidth, - normalizedDistance - )); - float rimBody = smoothstep( - mix(0.74, 0.82, profileVariation) - edgeWidth, - mix(0.86, 0.90, profileVariation) + edgeWidth, - normalizedDistance - ) * (1.0 - smoothstep( - 0.985 - edgeWidth, - 1.0 + edgeWidth, - normalizedDistance - )); - float rimPeak = smoothstep( - 0.89 - edgeWidth, - 0.94 + edgeWidth, - normalizedDistance - ) * (1.0 - smoothstep( - 0.982 - edgeWidth, - 0.998 + edgeWidth, - normalizedDistance - )); - return support * ( - transparentCore + innerGlow * 0.12 - + (rimBody * 0.42 + rimPeak * 0.30) - * ringModulation - ); - #else float support = 1.0 - smoothstep(0.38, 1.0, normalizedDistance); float softInterior = mix( 0.34, @@ -1403,7 +1185,6 @@ object Shaders { * (1.0 - smoothstep(0.68, 1.0, normalizedDistance)); float shoulderStrength = mix(0.025, 0.045, vFieldStrength); return support * (softInterior + shoulder * shoulderStrength); - #endif } void main() { @@ -1411,89 +1192,19 @@ object Shaders { if (normalizedDistance >= 1.0) discard; float transmission = apertureTransmission(vAperturePosition); - #if SOAP_BUBBLE_BOKEH == 1 - float signalLuma = dot(vSignal, vec3(0.2126, 0.7152, 0.0722)); - float instanceVariation = 0.78 + 0.22 * ( - 0.5 + 0.5 * sin(vBubblePhase * 2.17 + 0.73) - ); - float sourceTransmission = mix( - 0.48, - 1.0, - smoothstep(0.04, 0.72, signalLuma) - ) * instanceVariation; - transmission *= sourceTransmission; - #endif if (uLinearInput != 0) { // HDR keeps linear scene radiance; overlapping discs add energy. - #if SOAP_BUBBLE_BOKEH == 1 - float edgeTintAmount = smoothstep( - 0.72, - 0.96, - normalizedDistance - ); - float spectralMix = 0.5 + 0.5 * sin( - atan(vAperturePosition.y, vAperturePosition.x) - + vBubblePhase - ); - vec3 spectralTint = mix( - vec3(1.05, 1.01, 0.94), - vec3(0.93, 1.02, 1.08), - spectralMix - ); - vec3 edgeTint = mix( - vec3(1.0), - spectralTint, - edgeTintAmount * 0.24 - ); - fragColor = vec4( - vSignal * edgeTint * (0.44 * transmission), - 0.0 - ); - #else fragColor = vec4(vSignal * transmission, 0.0); - #endif } else { // LDR uses the same bounded highlight reconstruction as the // previous path, but the opacity now comes from one analytic disc. - #if SOAP_BUBBLE_BOKEH == 1 - float edgeTintAmount = smoothstep( - 0.72, - 0.96, - normalizedDistance - ); - float spectralMix = 0.5 + 0.5 * sin( - atan(vAperturePosition.y, vAperturePosition.x) - + vBubblePhase - ); - vec3 spectralTint = mix( - vec3(1.05, 1.01, 0.94), - vec3(0.93, 1.02, 1.08), - spectralMix - ); - vec3 edgeTint = mix( - vec3(1.0), - spectralTint, - edgeTintAmount * 0.24 - ); - vec3 reconstructedHighlight = vSignal - * edgeTint - * (0.50 * transmission); - #else vec3 reconstructedHighlight = vSignal * (0.55 * transmission); - #endif vec3 compressedHighlight = reconstructedHighlight / (vec3(1.0) + reconstructedHighlight * 2.0); - #if SOAP_BUBBLE_BOKEH == 1 - vec3 highlightOpacity = min( - vec3(0.24), - vec3(1.0) - exp(-compressedHighlight * 1.18) - ); - #else vec3 highlightOpacity = min( vec3(0.18), vec3(1.0) - exp(-compressedHighlight * 1.8) ); - #endif fragColor = vec4(highlightOpacity, 0.0); } } @@ -1505,8 +1216,7 @@ object Shaders { * 主体 mask 决定原图覆盖率,非主体深度决定 CoC,两者保持独立。 * 焦前散焦物仍可遮挡焦点层;背景高光不能借该覆盖率溢入主体。 */ - val BOKEH_COMPOSITE_FRAGMENT_SHADER = """ - #version 300 es + val BOKEH_COMPOSITE_FRAGMENT_SHADER = """#version 300 es precision highp float; in vec2 vTexCoord; @@ -1525,21 +1235,7 @@ object Shaders { $BOKEH_LAYER_SAMPLING - float computeCoc(float depth) { - float gap = max(abs(uFocusDepth - depth) - 0.015, 0.0); - float availableFocusSpan = max( - max(uFocusDepth, 1.0 - uFocusDepth) - 0.015, - 0.15 - ); - float normalizedGap = clamp(gap / availableFocusSpan, 0.0, 1.0); - float defocus = pow(normalizedGap, 1.25); - float apertureScale = min(1.4 / max(uAperture, 0.7), 1.25); - return clamp( - defocus * uMaxBlurRadius * apertureScale, - 0.0, - uMaxBlurRadius - ); - } + ${BokehDefocusModel.GLSL_SOURCE} float foregroundDefocusCoverage(vec2 depthUV, float centerDepth) { float weightedCoverage = 0.0; @@ -1625,31 +1321,8 @@ object Shaders { } """.trimIndent() - fun psfSplatFragmentShader( - naturalStyle: Boolean, - soapBubbleStyle: Boolean = false, - ): String = - PSF_SPLAT_FRAGMENT_SHADER - .withBokehStyleDefine("NATURAL_BOKEH", naturalStyle) - .withBokehStyleDefine("SOAP_BUBBLE_BOKEH", soapBubbleStyle) - - fun compactBokehHighlightFragmentShader(soapBubbleStyle: Boolean): String = - COMPACT_BOKEH_HIGHLIGHT_FRAGMENT_SHADER.withBokehStyleDefine( - "SOAP_BUBBLE_BOKEH", - soapBubbleStyle, - ) - - fun analyticBokehHighlightVertexShader(soapBubbleStyle: Boolean): String = - ANALYTIC_BOKEH_HIGHLIGHT_VERTEX_SHADER.withBokehStyleDefine( - "SOAP_BUBBLE_BOKEH", - soapBubbleStyle, - ) - - fun analyticBokehHighlightFragmentShader(soapBubbleStyle: Boolean): String = - ANALYTIC_BOKEH_HIGHLIGHT_FRAGMENT_SHADER.withBokehStyleDefine( - "SOAP_BUBBLE_BOKEH", - soapBubbleStyle, - ) + fun psfSplatFragmentShader(naturalStyle: Boolean): String = + PSF_SPLAT_FRAGMENT_SHADER.withBokehStyleDefine("NATURAL_BOKEH", naturalStyle) private fun String.withBokehStyleDefine(define: String, enabled: Boolean): String = if (enabled) { diff --git a/app/src/main/java/com/hinnka/mycamera/processor/BokehDefocusModel.kt b/app/src/main/java/com/hinnka/mycamera/processor/BokehDefocusModel.kt new file mode 100644 index 00000000..59f5ed89 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/BokehDefocusModel.kt @@ -0,0 +1,60 @@ +package com.hinnka.mycamera.processor + +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.math.pow +import kotlin.math.sign + +/** + * Shared virtual calibration from normalized relative depth to geometric defocus. + * + * Relative depth is not a measured object distance. This contract preserves the + * aperture control's established strength across styles; a lens's pupil model + * determines the energy distribution and support around that base defocus. + */ +object BokehDefocusModel { + const val FOCUS_DEPTH_DEAD_BAND = 0.015f + private const val RADIUS_DIVISOR = 26.0 + + fun baseRadiusPixels(imageLongEdge: Int): Float { + require(imageLongEdge > 0) + return imageLongEdge / RADIUS_DIVISOR.toFloat() + } + + /** Signed geometric ray radius as a fraction of the image's long edge. */ + fun signedRadiusFraction(depth: Double, focus: Double, aperture: Double): Double { + require(depth.isFinite() && depth in 0.0..1.0) + require(focus.isFinite() && focus in 0.0..1.0) + require(aperture.isFinite() && aperture > 0.0) + val deadBand = FOCUS_DEPTH_DEAD_BAND.toDouble() + val gap = max(abs(depth - focus) - deadBand, 0.0) + val availableFocusSpan = max(max(focus, 1.0 - focus) - deadBand, 0.15) + val normalizedGap = (gap / availableFocusSpan).coerceIn(0.0, 1.0) + val apertureScale = min(1.4 / max(aperture, 0.7), 1.25) + return sign(depth - focus) * + min(normalizedGap.pow(1.25) * apertureScale, 1.0) / RADIUS_DIVISOR + } + + fun radiusPixels(depth: Float, focus: Float, aperture: Float, imageLongEdge: Int): Float { + require(imageLongEdge > 0) + return (abs(signedRadiusFraction(depth.toDouble(), focus.toDouble(), aperture.toDouble())) * + imageLongEdge).toFloat() + } + + /** Caller declares uFocusDepth and uAperture before including this source. */ + val GLSL_SOURCE = """ + uniform float uBaseCocRadius; + + float computeCoc(float depth) { + float gap = max(abs(uFocusDepth - depth) - $FOCUS_DEPTH_DEAD_BAND, 0.0); + float availableFocusSpan = max( + max(uFocusDepth, 1.0 - uFocusDepth) - $FOCUS_DEPTH_DEAD_BAND, + 0.15 + ); + float normalizedGap = clamp(gap / availableFocusSpan, 0.0, 1.0); + float apertureScale = min(1.4 / max(uAperture, 0.7), 1.25); + return uBaseCocRadius * clamp(pow(normalizedGap, 1.25) * apertureScale, 0.0, 1.0); + } + """.trimIndent() +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/DepthBokehProcessor.kt b/app/src/main/java/com/hinnka/mycamera/processor/DepthBokehProcessor.kt index 2ebbe581..118100e0 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/DepthBokehProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/DepthBokehProcessor.kt @@ -9,8 +9,11 @@ import com.hinnka.mycamera.ml.RelativeDepthMapFile import com.hinnka.mycamera.ml.SharedDepthEstimator import com.hinnka.mycamera.ml.SharedSubjectMaskEstimator import com.hinnka.mycamera.utils.PLog +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import java.util.concurrent.CancellationException /** * Handles the post-processing of the Depth Map for high-quality optical bokeh. @@ -44,6 +47,9 @@ class DepthBokehProcessor(context: Context) { aperture: Float, bokehStyle: BokehStyle = BokehStyle.DEFAULT, ): Bitmap = mutex.withLock { + val coroutineContext = currentCoroutineContext() + val checkCancellation = { coroutineContext.ensureActive() } + checkCancellation() if (aperture > 16.0f || aperture <= 0f) { return originalImage } @@ -60,6 +66,7 @@ class DepthBokehProcessor(context: Context) { null } } + checkCancellation() // Existing photos may only have the former 8-bit PNG cache. Read it // once and migrate it without changing its already-quantized values. @@ -80,6 +87,7 @@ class DepthBokehProcessor(context: Context) { if (depthMap == null) { depthMap = SharedDepthEstimator.estimateDepth(appContext, originalImage) + checkCancellation() if (depthMap != null && floatDepthFile != null) { try { @@ -100,6 +108,7 @@ class DepthBokehProcessor(context: Context) { var result: Bitmap? = null if (depthMap != null) { val subjectMask = SharedSubjectMaskEstimator.estimateMask(appContext, originalImage, depthMap) + checkCancellation() if (subjectMask == null) { PLog.e(TAG, "U2NetP subject mask unavailable; bokeh was not applied") return@withLock originalImage @@ -125,8 +134,17 @@ class DepthBokehProcessor(context: Context) { aperture, bokehStyle, protectSubject = focusMask >= 0.5f, + checkCancellation = checkCancellation, ) result = bokehResult + try { + checkCancellation() + } catch (error: CancellationException) { + if (bokehResult != null && bokehResult !== originalImage && !bokehResult.isRecycled) { + bokehResult.recycle() + } + throw error + } } return result ?: originalImage diff --git a/app/src/main/java/com/hinnka/mycamera/processor/OglBokehProcessor.kt b/app/src/main/java/com/hinnka/mycamera/processor/OglBokehProcessor.kt index 999e0b3d..0b1c3e0f 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/OglBokehProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/OglBokehProcessor.kt @@ -9,10 +9,16 @@ import android.os.SystemClock import android.util.Half import com.hinnka.mycamera.lut.GlUtils import com.hinnka.mycamera.lut.Shaders +import com.hinnka.mycamera.lut.PhysicalBokehShaders import com.hinnka.mycamera.ml.RelativeDepthMap import com.hinnka.mycamera.ml.SubjectMask +import com.hinnka.mycamera.processor.optics.OpticalColorTransfer +import com.hinnka.mycamera.processor.optics.OpticalLensProfile +import com.hinnka.mycamera.processor.optics.OpticalPsfTable +import com.hinnka.mycamera.processor.optics.OpticalEmitterReconstruction import com.hinnka.mycamera.utils.LargeDirectBuffer import com.hinnka.mycamera.utils.PLog +import java.util.concurrent.CancellationException import java.nio.ByteOrder import kotlin.math.ceil import kotlin.math.floor @@ -22,12 +28,12 @@ class OglBokehProcessor { companion object { private const val TAG = "OglBokehProcessor" private const val MAX_BOKEH_RENDER_EDGE = 2560 + private const val OPTICAL_BOKEH_RENDER_EDGE = 1280 // Keep analytic highlights as a restrained supplement to the sampled PSF. private const val ANALYTIC_BOKEH_HIGHLIGHTS_ENABLED = true private const val HIGHLIGHT_MASK_THRESHOLD = 0.03f private const val MIN_ANALYTIC_COC_PIXELS = 20f - private const val MIN_BUBBLE_ANALYTIC_COC_PIXELS = 10f - private const val FOCUS_DEPTH_DEAD_BAND = 0.015f + private const val FOCUS_DEPTH_DEAD_BAND = BokehDefocusModel.FOCUS_DEPTH_DEAD_BAND // Synthetic-highlight defocus gate. A depth sample is accepted when // its absolute focus gap is >= X. The low-depth branch retains the // established far-background allowance for normalized disparity maps. @@ -37,7 +43,6 @@ class OglBokehProcessor { // Tunable highlight-quality gate measured in linear RGB. private const val MIN_HIGHLIGHT_NEIGHBOR_LUMA_DIFFERENCE = 0.11f private const val HIGHLIGHT_MIN_CENTER_SPACING_SCALE = 0.9f - private const val BUBBLE_HIGHLIGHT_MIN_CENTER_SPACING_SCALE = 0.82f private const val HIGHLIGHT_PEAK_DISCOVERY_CELL_SCALE = 0.5f private const val PREEXISTING_BOKEH_RADIUS_SCALE = 0.05f private const val MAX_PREEXISTING_BOKEH_RADIUS_SCALE = 1.5f @@ -95,6 +100,12 @@ class OglBokehProcessor { private var depthRefineProgramId = 0 private var depthReadbackProgramId = 0 private var layerColorProgramId = 0 + private var emitterSeparationProgramId = 0 + private var emitterErosionProgramId = 0 + private var emitterDilationProgramId = 0 + private var reconstructedEmitterProgramId = 0 + + private data class ReconstructedEmitters(val remainingTexture: Int, val instances: FloatArray) private var vertexBufferId = 0 private var texCoordBufferId = 0 private var indexBufferId = 0 @@ -112,22 +123,65 @@ class OglBokehProcessor { aperture: Float, bokehStyle: BokehStyle = BokehStyle.DEFAULT, protectSubject: Boolean = true, + checkCancellation: () -> Unit = {}, ): Bitmap? { + checkCancellation() val startedAtMs = SystemClock.elapsedRealtime() + var resultBitmap: Bitmap? = null try { + checkCancellation() val halfFloatOutput = originalImage.config == Bitmap.Config.RGBA_F16 val linearInput = originalImage.colorSpace?.id == ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB).id + val physicalBubble = bokehStyle == BokehStyle.BUBBLE val (bokehWidth, bokehHeight) = resolveBokehRenderSize( originalImage.width, originalImage.height, + if (physicalBubble) OPTICAL_BOKEH_RENDER_EDGE else MAX_BOKEH_RENDER_EDGE, ) + val psf = if (physicalBubble) OpticalPsfTable.build( + OpticalLensProfile.SOAP_BUBBLE, aperture, focusDepth, + maxOf(originalImage.width, originalImage.height), maxOf(bokehWidth, bokehHeight), + checkCancellation, + ) else null + val emitterPsf = if (physicalBubble) OpticalPsfTable.build( + OpticalLensProfile.SOAP_BUBBLE_EMITTER, aperture, focusDepth, + maxOf(originalImage.width, originalImage.height), maxOf(bokehWidth, bokehHeight), + checkCancellation, sceneReferenceProfile = OpticalLensProfile.SOAP_BUBBLE, + ) else null + val colorTransfer = if (physicalBubble) OpticalColorTransfer( + originalImage.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB), + ).shaderFunctions() else null PLog.d( TAG, "Bokeh working resolution: ${bokehWidth}x${bokehHeight}, output=${originalImage.width}x${originalImage.height}" ) initEGL(originalImage.width, originalImage.height) - initGL(bokehStyle) + initGL(bokehStyle, colorTransfer) + + // R32F nearest lookups preserve annular CDF mass; interpolation is + // explicitly in squared radius, not ordinary linear texture filtering. + val psfCdfTex = psf?.let { createScalarTexture( + it.radialBinCount + 1, it.depthCount, it.cumulativeEnergy, "optical PSF CDF", true, + ) } ?: 0 + val psfSupportTex = psf?.let { createScalarTexture( + 1, it.depthCount, it.supportPixels, "optical PSF support", true, + ) } ?: 0 + val emitterCdfTex = emitterPsf?.let { createScalarTexture( + it.radialBinCount + 1, it.depthCount, it.cumulativeEnergy, "emitter PSF CDF", true, + ) } ?: 0 + val emitterSupportTex = emitterPsf?.let { createScalarTexture( + 1, it.depthCount, it.supportPixels, "emitter PSF support", true, + ) } ?: 0 + if (psf != null) PLog.d(TAG, + "Optical PSF: lens=${OpticalLensProfile.SOAP_BUBBLE.id}, f=$aperture, " + + "focus=$focusDepth, support=${psf.tableSupportPixels}, " + + "table=${psf.radialBinCount}x${psf.depthCount}, bin=${psf.binWidthPixels}, " + + "samples=512, calibration=shared-defocus, propagation=geometrical-annular-energy, subjectProtection=$protectSubject") + if (emitterPsf != null) PLog.d(TAG, + "Optical emitters: lens=${emitterPsf.lens.profile.id}, " + + "support=${emitterPsf.tableSupportPixels}, separation=positive-compact-radiance, " + + "transport=two-path-subtract-and-redistribute, samples=512") val inputTex = createTexture(originalImage, mipmap = true) val lowResDepthTex = createScalarTexture( @@ -181,6 +235,7 @@ class OglBokehProcessor { GLES30.glUniform1i(GLES30.glGetUniformLocation(jbuUpsampleProgramId, "uLinearInput"), if (linearInput) 1 else 0) drawQuad(jbuUpsampleProgramId) + checkCancellation() requireNoGlError("subject mask / layered upsample RGBA16F") // Refine the RGB-guided mask and each depth layer independently. @@ -215,6 +270,7 @@ class OglBokehProcessor { GLES30.glUniform1i(GLES30.glGetUniformLocation(depthRefineProgramId, "uProtectSubject"), if (protectSubject) 1 else 0) drawQuad(depthRefineProgramId) + checkCancellation() requireNoGlError("RGB mask / layered depth refine RGBA16F") val finalDepthTex = refinedDepthTex[0] @@ -227,163 +283,205 @@ class OglBokehProcessor { "depth=${lowResDepthMap.width}x${lowResDepthMap.height}, " + "mask=${subjectMask.width}x${subjectMask.height}, region=${subjectMask.region}, protect=$protectSubject, " + "working=${bokehWidth}x${bokehHeight}, focus=$focusDepth, linear=$linearInput") - val maxBlurRadius = originalImage.width.toFloat() / 26.0f + val baseCocRadius = BokehDefocusModel.baseRadiusPixels(maxOf(originalImage.width, originalImage.height)) + val emitterSourceTex = if (physicalBubble) { + var environment = layerColorTex + for (program in intArrayOf(emitterErosionProgramId, emitterDilationProgramId)) { + checkCancellation() + val target = createOpticalRenderTexture(bokehWidth, bokehHeight) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fbo[0]) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, target, 0) + requireFramebufferComplete("optical emitter environment") + GLES30.glViewport(0, 0, bokehWidth, bokehHeight) + GLES30.glUseProgram(program) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, environment) + GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uInputTexture"), 0) + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uDepthTexture"), 1) + GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uBaseCocRadius"), baseCocRadius) + GLES30.glUniform2f(GLES30.glGetUniformLocation(program, "uTexelSize"), + 1f / originalImage.width, 1f / originalImage.height) + drawQuad(program) + requireNoGlError("optical emitter environment RGBA16F") + if (environment != layerColorTex) GLES30.glDeleteTextures(1, intArrayOf(environment), 0) + environment = target + } + val texture = createOpticalRenderTexture(bokehWidth, bokehHeight, mipmap = true) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fbo[0]) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, texture, 0) + requireFramebufferComplete("optical emitter separation") + GLES30.glViewport(0, 0, bokehWidth, bokehHeight) + GLES30.glUseProgram(emitterSeparationProgramId) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, layerColorTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(emitterSeparationProgramId, "uLayerColorTexture"), 0) + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(emitterSeparationProgramId, "uDepthTexture"), 1) + GLES30.glActiveTexture(GLES30.GL_TEXTURE2) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, environment) + GLES30.glUniform1i(GLES30.glGetUniformLocation(emitterSeparationProgramId, "uEmitterEnvironment"), 2) + GLES30.glUniform1f(GLES30.glGetUniformLocation(emitterSeparationProgramId, "uBaseCocRadius"), baseCocRadius) + GLES30.glUniform1f(GLES30.glGetUniformLocation(emitterSeparationProgramId, "uFocusDepth"), focusDepth) + GLES30.glUniform1f(GLES30.glGetUniformLocation(emitterSeparationProgramId, "uAperture"), aperture) + GLES30.glUniform2f(GLES30.glGetUniformLocation(emitterSeparationProgramId, "uTexelSize"), + 1f / originalImage.width, 1f / originalImage.height) + drawQuad(emitterSeparationProgramId) + GLES30.glDeleteTextures(1, intArrayOf(environment), 0) + GLES30.glActiveTexture(GLES30.GL_TEXTURE6) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D) + requireNoGlError("optical emitter radiance RGBA16F / mipmaps") + texture + } else 0 + val reconstructedEmitters = if (emitterPsf != null) reconstructOpticalEmitters( + emitterSourceTex, finalDepthTex, bokehWidth, bokehHeight, + originalImage.width, originalImage.height, emitterPsf, checkCancellation, + ) else null + val maxBlurRadius = psf?.let { it.tableSupportPixels + + 0.5f * originalImage.width / bokehWidth } + ?: baseCocRadius val identity = FloatArray(16) android.opengl.Matrix.setIdentityM(identity, 0) val compactHighlightTex = IntArray(1) - val analyticHighlights = if (ANALYTIC_BOKEH_HIGHLIGHTS_ENABLED) { - val depthClassification = if (bokehStyle == BokehStyle.DEFAULT) { - // Only the default style performs CPU highlight topology. Its - // RGBA8 depth/mask copy never feeds the renderer; finalDepthTex - // remains RGBA16F. Avoid this synchronizing readback for the fully - // GPU-integrated natural and bubble styles. - GLES30.glGenTextures(1, depthReadbackTex, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, depthReadbackTex[0]) - GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA8, bokehWidth, bokehHeight, 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) - GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, depthReadbackTex[0], 0) - requireFramebufferComplete("depth classification resolve") - GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) - GLES30.glUseProgram(depthReadbackProgramId) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, refinedDepthTex[0]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(depthReadbackProgramId, "uDepthTexture"), 0) - drawQuad(depthReadbackProgramId) - readDepthClassification(bokehWidth, bokehHeight) - } else { - null - } + val analyticHighlights = if (ANALYTIC_BOKEH_HIGHLIGHTS_ENABLED && bokehStyle == BokehStyle.DEFAULT) { + // Only the default style performs CPU highlight topology. Its + // RGBA8 depth/mask copy never feeds the renderer; finalDepthTex + // remains RGBA16F. Avoid this synchronizing readback for the fully + // GPU-integrated natural and bubble styles. + GLES30.glGenTextures(1, depthReadbackTex, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, depthReadbackTex[0]) + GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA8, bokehWidth, bokehHeight, 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, depthReadbackTex[0], 0) + requireFramebufferComplete("depth classification resolve") + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + GLES30.glUseProgram(depthReadbackProgramId) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, refinedDepthTex[0]) + GLES30.glUniform1i(GLES30.glGetUniformLocation(depthReadbackProgramId, "uDepthTexture"), 0) + drawQuad(depthReadbackProgramId) + val depthClassification = readDepthClassification(bokehWidth, bokehHeight) GLES30.glEnable(GLES30.GL_DITHER) - // Step 3: Classify only compact, isolated highlights. This prevents - // large bright regions from entering the inferred-radiance bokeh path. - // Natural bokeh has no analytic overlay and its PSF does not sample - // the compact-highlight texture, so skip the complete pass there. - if (bokehStyle != BokehStyle.NATURAL) { - GLES30.glGenTextures(1, compactHighlightTex, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, compactHighlightTex[0]) - GLES30.glTexImage2D( - GLES30.GL_TEXTURE_2D, - 0, - if (halfFloatOutput) GLES30.GL_RGBA16F else GLES30.GL_RGBA8, - bokehWidth, - bokehHeight, - 0, - GLES30.GL_RGBA, - if (halfFloatOutput) GLES30.GL_HALF_FLOAT else GLES30.GL_UNSIGNED_BYTE, - null - ) - GLES30.glTexParameteri( - GLES30.GL_TEXTURE_2D, - GLES30.GL_TEXTURE_MIN_FILTER, - GLES30.GL_LINEAR_MIPMAP_LINEAR, - ) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + // Classify compact, isolated highlights only for DEFAULT. + GLES30.glGenTextures(1, compactHighlightTex, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, compactHighlightTex[0]) + GLES30.glTexImage2D( + GLES30.GL_TEXTURE_2D, + 0, + if (halfFloatOutput) GLES30.GL_RGBA16F else GLES30.GL_RGBA8, + bokehWidth, + bokehHeight, + 0, + GLES30.GL_RGBA, + if (halfFloatOutput) GLES30.GL_HALF_FLOAT else GLES30.GL_UNSIGNED_BYTE, + null + ) + GLES30.glTexParameteri( + GLES30.GL_TEXTURE_2D, + GLES30.GL_TEXTURE_MIN_FILTER, + GLES30.GL_LINEAR_MIPMAP_LINEAR, + ) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) - GLES30.glFramebufferTexture2D( - GLES30.GL_FRAMEBUFFER, - GLES30.GL_COLOR_ATTACHMENT0, - GLES30.GL_TEXTURE_2D, - compactHighlightTex[0], - 0 - ) - requireFramebufferComplete("compact bokeh highlight") - GLES30.glViewport(0, 0, bokehWidth, bokehHeight) - GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) - GLES30.glUseProgram(compactHighlightProgramId) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, + GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, + compactHighlightTex[0], + 0 + ) + requireFramebufferComplete("compact bokeh highlight") + GLES30.glViewport(0, 0, bokehWidth, bokehHeight) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + GLES30.glUseProgram(compactHighlightProgramId) + GLES30.glUniform1f(GLES30.glGetUniformLocation(compactHighlightProgramId, "uBaseCocRadius"), baseCocRadius) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTex) - GLES30.glUniform1i( - GLES30.glGetUniformLocation(compactHighlightProgramId, "uInputTexture"), - 0 - ) - GLES30.glActiveTexture(GLES30.GL_TEXTURE1) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex) - GLES30.glUniform1i( - GLES30.glGetUniformLocation(compactHighlightProgramId, "uDepthTexture"), - 1 - ) - GLES30.glUniformMatrix4fv( - GLES30.glGetUniformLocation(compactHighlightProgramId, "uDepthMatrix"), - 1, - false, - identity, - 0 - ) - GLES30.glUniform1f( - GLES30.glGetUniformLocation(compactHighlightProgramId, "uMaxBlurRadius"), - maxBlurRadius - ) - GLES30.glUniform1f( - GLES30.glGetUniformLocation(compactHighlightProgramId, "uAperture"), - HIGHLIGHT_CLASSIFICATION_F_NUMBER - ) - GLES30.glUniform1f( - GLES30.glGetUniformLocation(compactHighlightProgramId, "uFocusDepth"), - focusDepth - ) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(compactHighlightProgramId, "uTexelSize"), - 1.0f / originalImage.width, - 1.0f / originalImage.height - ) - GLES30.glUniform1f( - GLES30.glGetUniformLocation( - compactHighlightProgramId, - "uMinNeighborhoodLumaDifference", - ), - MIN_HIGHLIGHT_NEIGHBOR_LUMA_DIFFERENCE, - ) - GLES30.glUniform1i( - GLES30.glGetUniformLocation(compactHighlightProgramId, "uLinearInput"), - if (linearInput) 1 else 0 - ) - drawQuad(compactHighlightProgramId) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, compactHighlightTex[0]) - GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D) - } + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTex) + GLES30.glUniform1i( + GLES30.glGetUniformLocation(compactHighlightProgramId, "uInputTexture"), + 0 + ) + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex) + GLES30.glUniform1i( + GLES30.glGetUniformLocation(compactHighlightProgramId, "uDepthTexture"), + 1 + ) + GLES30.glUniformMatrix4fv( + GLES30.glGetUniformLocation(compactHighlightProgramId, "uDepthMatrix"), + 1, + false, + identity, + 0 + ) + GLES30.glUniform1f( + GLES30.glGetUniformLocation(compactHighlightProgramId, "uMaxBlurRadius"), + maxBlurRadius + ) + GLES30.glUniform1f( + GLES30.glGetUniformLocation(compactHighlightProgramId, "uAperture"), + HIGHLIGHT_CLASSIFICATION_F_NUMBER + ) + GLES30.glUniform1f( + GLES30.glGetUniformLocation(compactHighlightProgramId, "uFocusDepth"), + focusDepth + ) + GLES30.glUniform2f( + GLES30.glGetUniformLocation(compactHighlightProgramId, "uTexelSize"), + 1.0f / originalImage.width, + 1.0f / originalImage.height + ) + GLES30.glUniform1f( + GLES30.glGetUniformLocation( + compactHighlightProgramId, + "uMinNeighborhoodLumaDifference", + ), + MIN_HIGHLIGHT_NEIGHBOR_LUMA_DIFFERENCE, + ) + GLES30.glUniform1i( + GLES30.glGetUniformLocation(compactHighlightProgramId, "uLinearInput"), + if (linearInput) 1 else 0 + ) + drawQuad(compactHighlightProgramId) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, compactHighlightTex[0]) + GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D) - if (bokehStyle == BokehStyle.NATURAL) { - PLog.d(TAG, "Natural bokeh uses integrated radial PSF") - emptyList() - } else if (bokehStyle == BokehStyle.BUBBLE) { - PLog.d(TAG, "Bubble bokeh uses integrated optical PSF") - emptyList() - } else { - extractAnalyticHighlights( - width = bokehWidth, - height = bokehHeight, - halfFloat = halfFloatOutput, - refinedDepthPixels = checkNotNull(depthClassification) { - "Default bokeh requires resolved depth topology" - }.otherDepth, - subjectMaskPixels = depthClassification.subjectMask, - originalWidth = originalImage.width, - originalHeight = originalImage.height, - focusDepth = focusDepth, - aperture = aperture, - maxBlurRadius = maxBlurRadius, - bokehStyle = bokehStyle, - ).also { extraction -> - PLog.d( - TAG, - "Analytic bokeh highlights: style=$bokehStyle, fNumber=$aperture, " + - "minNeighborLumaDelta=$MIN_HIGHLIGHT_NEIGHBOR_LUMA_DIFFERENCE, " + - "candidates=${extraction.eligibleCandidateCount}, " + - "depthGateRejected=${extraction.depthGateRejectedCount}, " + - "preExisting=${extraction.preExistingBokehCount}, " + - "densitySuppressed=${extraction.densitySuppressedCount}, " + - "accepted=${extraction.highlights.size}" - ) - }.highlights - } + extractAnalyticHighlights( + width = bokehWidth, + height = bokehHeight, + halfFloat = halfFloatOutput, + refinedDepthPixels = depthClassification.otherDepth, + subjectMaskPixels = depthClassification.subjectMask, + originalWidth = originalImage.width, + originalHeight = originalImage.height, + focusDepth = focusDepth, + aperture = aperture, + maxBlurRadius = maxBlurRadius, + ).also { extraction -> + PLog.d( + TAG, + "Analytic bokeh highlights: style=$bokehStyle, fNumber=$aperture, " + + "minNeighborLumaDelta=$MIN_HIGHLIGHT_NEIGHBOR_LUMA_DIFFERENCE, " + + "candidates=${extraction.eligibleCandidateCount}, " + + "depthGateRejected=${extraction.depthGateRejectedCount}, " + + "preExisting=${extraction.preExistingBokehCount}, " + + "densitySuppressed=${extraction.densitySuppressedCount}, " + + "accepted=${extraction.highlights.size}" + ) + }.highlights } else { GLES30.glEnable(GLES30.GL_DITHER) PLog.d(TAG, "Analytic bokeh highlights disabled") @@ -417,17 +515,12 @@ class OglBokehProcessor { GLES30.glViewport(0, 0, bokehWidth, bokehHeight) GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) GLES30.glUseProgram(bokehProgramId) + GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uBaseCocRadius"), baseCocRadius) GLES30.glActiveTexture(GLES30.GL_TEXTURE1) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex) GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uDepthTexture"), 1) - GLES30.glActiveTexture(GLES30.GL_TEXTURE2) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, compactHighlightTex[0]) - GLES30.glUniform1i( - GLES30.glGetUniformLocation(bokehProgramId, "uHighlightSourceTexture"), - 2, - ) GLES30.glActiveTexture(GLES30.GL_TEXTURE3) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, layerColorTex) GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uLayerColorTexture"), 3) @@ -438,9 +531,52 @@ class OglBokehProcessor { GLES30.glUniform2f(GLES30.glGetUniformLocation(bokehProgramId, "uTexelSize"), 1.0f / originalImage.width, 1.0f / originalImage.height) GLES30.glUniformMatrix4fv(GLES30.glGetUniformLocation(bokehProgramId, "uDepthMatrix"), 1, false, identity, 0) + if (psf != null) bindPsf(bokehProgramId, psf, psfCdfTex, psfSupportTex) + if (physicalBubble) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE6) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, emitterSourceTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uEmitterTexture"), 6) + GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uSubtractEmitters"), 1) + } + drawQuad(bokehProgramId) requireNoGlError("PSF linear background / support RGBA16F") + val emitterBokehTex = if (emitterPsf != null) { + checkCancellation() + val texture = createOpticalRenderTexture(bokehWidth, bokehHeight) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fbo[0]) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, texture, 0) + requireFramebufferComplete("optical emitter transport") + GLES30.glViewport(0, 0, bokehWidth, bokehHeight) + GLES30.glUseProgram(bokehProgramId) + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uDepthTexture"), 1) + GLES30.glActiveTexture(GLES30.GL_TEXTURE3) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, checkNotNull(reconstructedEmitters).remainingTexture) + GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uLayerColorTexture"), 3) + GLES30.glActiveTexture(GLES30.GL_TEXTURE6) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, emitterSourceTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uEmitterTexture"), 6) + GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uSubtractEmitters"), 0) + GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uBaseCocRadius"), baseCocRadius) + GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uMaxBlurRadius"), + emitterPsf.tableSupportPixels + 0.5f * originalImage.width / bokehWidth) + GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uAperture"), aperture) + GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uFocusDepth"), focusDepth) + GLES30.glUniform2f(GLES30.glGetUniformLocation(bokehProgramId, "uTexelSize"), + 1f / originalImage.width, 1f / originalImage.height) + bindPsf(bokehProgramId, emitterPsf, emitterCdfTex, emitterSupportTex) + drawQuad(bokehProgramId) + requireNoGlError("optical emitter transport RGBA16F") + drawReconstructedEmitters(checkNotNull(reconstructedEmitters).instances, + emitterPsf, emitterCdfTex, emitterSupportTex, finalDepthTex, + originalImage.width, originalImage.height, bokehWidth, aperture, focusDepth, baseCocRadius) + texture + } else 0 + // Keep analytic bokeh on its own transparent layer. It is combined // with the blurred background only in the final, foreground-aware // composite, so neither pass can overwrite the other. @@ -527,6 +663,7 @@ class OglBokehProcessor { GLES30.glViewport(0, 0, originalImage.width, originalImage.height) GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) GLES30.glUseProgram(bokehCompositeProgramId) + GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehCompositeProgramId, "uBaseCocRadius"), baseCocRadius) GLES30.glActiveTexture(GLES30.GL_TEXTURE0) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTex) @@ -569,18 +706,29 @@ class OglBokehProcessor { if (linearInput) 1 else 0, ) + if (psf != null) bindPsf(bokehCompositeProgramId, psf, psfCdfTex, psfSupportTex) + if (physicalBubble) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE6) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, emitterBokehTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehCompositeProgramId, "uEmitterBokehTexture"), 6) + } drawQuad(bokehCompositeProgramId) + checkCancellation() GLES30.glFinish() val renderFinishedAtMs = SystemClock.elapsedRealtime() // Read back to Bitmap - val resultBitmap = Bitmap.createBitmap(originalImage.width, originalImage.height, + resultBitmap = Bitmap.createBitmap(originalImage.width, originalImage.height, if (halfFloatOutput) Bitmap.Config.RGBA_F16 else Bitmap.Config.ARGB_8888, false, originalImage.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB)) val bytesPerPixel = if (halfFloatOutput) 8L else 4L val bufferByteCount = originalImage.width.toLong() * originalImage.height.toLong() * bytesPerPixel - val buffer = LargeDirectBuffer.allocate(bufferByteCount, "OGL bokeh readback") ?: return null + val buffer = LargeDirectBuffer.allocate(bufferByteCount, "OGL bokeh readback") + if (buffer == null) { + resultBitmap.recycle() + return null + } try { GLES30.glReadPixels( 0, @@ -601,6 +749,11 @@ class OglBokehProcessor { GLES30.glDeleteTextures(1, intArrayOf(inputTex), 0) GLES30.glDeleteTextures(1, intArrayOf(lowResDepthTex), 0) GLES30.glDeleteTextures(1, intArrayOf(subjectMaskTex), 0) + GLES30.glDeleteTextures(2, intArrayOf(psfCdfTex, psfSupportTex), 0) + GLES30.glDeleteTextures(4, intArrayOf(emitterCdfTex, emitterSupportTex, emitterSourceTex, emitterBokehTex), 0) + if (reconstructedEmitters != null && reconstructedEmitters.remainingTexture != emitterSourceTex) { + GLES30.glDeleteTextures(1, intArrayOf(reconstructedEmitters.remainingTexture), 0) + } GLES30.glDeleteTextures(1, highResDepthTex, 0) GLES30.glDeleteTextures(1, refinedDepthTex, 0) GLES30.glDeleteTextures(1, intArrayOf(layerColorTex), 0) @@ -619,8 +772,13 @@ class OglBokehProcessor { "readback=${readbackFinishedAtMs - renderFinishedAtMs}ms, " + "working=${bokehWidth}x${bokehHeight}, output=${originalImage.width}x${originalImage.height}" ) + checkCancellation() return resultBitmap + } catch (e: CancellationException) { + resultBitmap?.takeIf { !it.isRecycled }?.recycle() + throw e } catch (e: Exception) { + resultBitmap?.takeIf { !it.isRecycled }?.recycle() PLog.e(TAG, "Error applying OGL Bokeh: ${e.message}") return null } finally { @@ -709,7 +867,6 @@ class OglBokehProcessor { focusDepth: Float, aperture: Float, maxBlurRadius: Float, - bokehStyle: BokehStyle, ): AnalyticHighlightExtraction { val pixelCount = width.toLong() * height.toLong() check(pixelCount == refinedDepthPixels.size.toLong()) { @@ -794,7 +951,6 @@ class OglBokehProcessor { val originalPixelsPerWorkingY = originalHeight.toFloat() / height.toFloat() val minimumSpacing = minimumHighlightCenterSpacing( maxBlurRadius, - bokehStyle, ) val discoveryCellSize = maxOf( minimumSpacing * HIGHLIGHT_PEAK_DISCOVERY_CELL_SCALE, @@ -826,43 +982,21 @@ class OglBokehProcessor { interpolate = false, ) - val depthCocPixels = computeCocPixels( + val depthCocPixels = BokehDefocusModel.radiusPixels( depth = centerDepth, - focusDepth = focusDepth, + focus = focusDepth, aperture = aperture, - maxBlurRadius = maxBlurRadius, + imageLongEdge = maxOf(originalWidth, originalHeight), ) - val minimumCocPixels = if (bokehStyle == BokehStyle.BUBBLE) { - MIN_BUBBLE_ANALYTIC_COC_PIXELS - } else { - MIN_ANALYTIC_COC_PIXELS - } + val minimumCocPixels = MIN_ANALYTIC_COC_PIXELS if (depthCocPixels < minimumCocPixels && !isPreExistingBokeh) return - if (bokehStyle != BokehStyle.BUBBLE && - !isSyntheticHighlightDefocusedDepth(centerDepth, focusDepth) - ) { + if (!isSyntheticHighlightDefocusedDepth(centerDepth, focusDepth)) { depthGateRejectedCount++ return } val cocPixels = if (isPreExistingBokeh) { maxOf(depthCocPixels, sourceRadiusPixels * 1.05f) .coerceAtMost(maxBlurRadius * 1.2f) - } else if (bokehStyle == BokehStyle.BUBBLE) { - val brightnessScale = (peak.score / 0.32f).coerceIn(0.0f, 1.0f) - val confidenceScale = sqrt(peak.alpha.coerceIn(0.0f, 1.0f)) - val sourceExtentScale = sqrt( - (sourceRadiusPixels / maxOf(maxBlurRadius, 1.0f)) - .coerceIn(0.0f, 1.0f) - ) - val opticalPhase = centerX * 0.7548777f + centerY * 0.5698403f - val stableLensVariation = 0.84f + - (opticalPhase - floor(opticalPhase)) * 0.32f - val opticalSizeScale = ( - 0.38f + brightnessScale * 0.28f + - confidenceScale * 0.28f + sourceExtentScale * 0.18f - ) * stableLensVariation - (depthCocPixels * opticalSizeScale) - .coerceIn(minimumCocPixels, maxBlurRadius * 1.18f) } else { depthCocPixels } @@ -878,9 +1012,6 @@ class OglBokehProcessor { centerY = centerY, focusDepth = focusDepth, cocPixels = cocPixels, - aperture = aperture, - maxBlurRadius = maxBlurRadius, - bokehStyle = bokehStyle, ) ) { depthGateRejectedCount++ @@ -888,11 +1019,7 @@ class OglBokehProcessor { } // Default optical discs are premultiplied by classifier alpha. - // Bubble RGB instead carries the wider removal signal while alpha - // identifies the compact center, so it must not be divided again. - val sourceSignalScale = if (bokehStyle == BokehStyle.BUBBLE) { - 1.0f - } else if (isPreExistingBokeh) { + val sourceSignalScale = if (isPreExistingBokeh) { 1.0f / maxOf( peak.alpha, 0.001f, @@ -1041,7 +1168,6 @@ class OglBokehProcessor { val selectedCandidates = selectDensityLimitedHighlights( candidates, maxBlurRadius, - bokehStyle, ) val highlights = ArrayList(candidates.size) var preExistingBokehCount = 0 @@ -1071,7 +1197,6 @@ class OglBokehProcessor { private fun selectDensityLimitedHighlights( candidates: List, maxBlurRadius: Float, - bokehStyle: BokehStyle, ): BooleanArray { if (candidates.isEmpty()) return BooleanArray(0) @@ -1080,7 +1205,6 @@ class OglBokehProcessor { // their full physical CoC for the requested f-number. val minimumSpacing = minimumHighlightCenterSpacing( maxBlurRadius, - bokehStyle, ) val minimumSpacingSquared = minimumSpacing * minimumSpacing val cellSize = minimumSpacing @@ -1142,14 +1266,9 @@ class OglBokehProcessor { private fun minimumHighlightCenterSpacing( maxBlurRadius: Float, - bokehStyle: BokehStyle, ): Float = maxOf( - maxBlurRadius * if (bokehStyle == BokehStyle.BUBBLE) { - BUBBLE_HIGHLIGHT_MIN_CENTER_SPACING_SCALE - } else { - HIGHLIGHT_MIN_CENTER_SPACING_SCALE - }, + maxBlurRadius * HIGHLIGHT_MIN_CENTER_SPACING_SCALE, 1.0f, ) @@ -1181,24 +1300,6 @@ class OglBokehProcessor { return top * (1.0f - fy) + bottom * fy } - private fun computeCocPixels( - depth: Float, - focusDepth: Float, - aperture: Float, - maxBlurRadius: Float, - ): Float { - val gap = (kotlin.math.abs(focusDepth - depth) - FOCUS_DEPTH_DEAD_BAND) - .coerceAtLeast(0.0f) - val availableFocusSpan = ( - maxOf(focusDepth, 1.0f - focusDepth) - FOCUS_DEPTH_DEAD_BAND - ).coerceAtLeast(0.15f) - val normalizedGap = (gap / availableFocusSpan).coerceIn(0.0f, 1.0f) - val defocus = Math.pow(normalizedGap.toDouble(), 1.25).toFloat() - val apertureScale = (1.4f / maxOf(aperture, 0.7f)).coerceAtMost(1.25f) - return (defocus * maxBlurRadius * apertureScale) - .coerceIn(0.0f, maxBlurRadius) - } - private fun isSyntheticHighlightDefocusedDepth( depth: Float, focusDepth: Float, @@ -1218,9 +1319,6 @@ class OglBokehProcessor { centerY: Float, focusDepth: Float, cocPixels: Float, - aperture: Float, - maxBlurRadius: Float, - bokehStyle: BokehStyle, ): Boolean { val originalPixelsPerWorkingX = originalWidth.toFloat() / width.toFloat() val originalPixelsPerWorkingY = originalHeight.toFloat() / height.toFloat() @@ -1249,34 +1347,167 @@ class OglBokehProcessor { if ((subjectMaskPixels[sampleY * width + sampleX].toInt() and 0xff) > 2) return false val depthByte = refinedDepthPixels[sampleY * width + sampleX].toInt() and 0xff val depth = depthByte / 255.0f - val eligibleDepth = if (bokehStyle == BokehStyle.BUBBLE) { - computeCocPixels( - depth = depth, - focusDepth = focusDepth, - aperture = aperture, - maxBlurRadius = maxBlurRadius, - ) >= MIN_BUBBLE_ANALYTIC_COC_PIXELS * 0.38f - } else { - isSyntheticHighlightDefocusedDepth(depth, focusDepth) - } + val eligibleDepth = isSyntheticHighlightDefocusedDepth(depth, focusDepth) if (!eligibleDepth) return false } } return true } - private fun resolveBokehRenderSize(width: Int, height: Int): Pair { + private fun resolveBokehRenderSize(width: Int, height: Int, limit: Int): Pair { val maxEdge = maxOf(width, height) - if (maxEdge <= MAX_BOKEH_RENDER_EDGE) return width to height + if (maxEdge <= limit) return width to height return if (width >= height) { - MAX_BOKEH_RENDER_EDGE to - (height.toLong() * MAX_BOKEH_RENDER_EDGE / width).toInt().coerceAtLeast(1) + limit to (height.toLong() * limit / width).toInt().coerceAtLeast(1) } else { - (width.toLong() * MAX_BOKEH_RENDER_EDGE / height).toInt().coerceAtLeast(1) to - MAX_BOKEH_RENDER_EDGE + (width.toLong() * limit / height).toInt().coerceAtLeast(1) to limit } } + private fun bindPsf(program: Int, psf: OpticalPsfTable, cdf: Int, support: Int) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE4) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, cdf) + GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uPsfCdf"), 4) + GLES30.glActiveTexture(GLES30.GL_TEXTURE5) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, support) + GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uPsfSupport"), 5) + GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uPsfBinWidth"), psf.binWidthPixels) + } + + private fun reconstructOpticalEmitters( + sourceTexture: Int, depthTexture: Int, width: Int, height: Int, + imageWidth: Int, imageHeight: Int, psf: OpticalPsfTable, checkCancellation: () -> Unit, + ): ReconstructedEmitters { + val started = SystemClock.elapsedRealtime() + val bytes = LargeDirectBuffer.allocate(width.toLong()*height*8, "optical source reconstruction") + ?: error("Unable to read optical light footprints") + try { + bytes.order(ByteOrder.nativeOrder()) + fun read(texture: Int) { + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, texture, 0) + requireFramebufferComplete("optical footprint readback") + bytes.position(0) + GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, bytes) + requireNoGlError("optical footprint RGBA16F readback") + } + read(sourceTexture) + var peak=0f + val rgba = FloatArray(width*height*4) { + val value=Half.toFloat(bytes.getShort(it*2)) + if (it%4 < 3) peak=maxOf(peak,value) + value + } + if (peak < OpticalEmitterReconstruction.MIN_PEAK) { + PLog.d(TAG,"Optical reconstructed sources: count=0, total=${SystemClock.elapsedRealtime()-started}ms") + return ReconstructedEmitters(sourceTexture,FloatArray(0)) + } + read(depthTexture) + val depth = FloatArray(width*height) { Half.toFloat(bytes.getShort(it*8+4)) } + val scale = imageWidth.toFloat()/width + fun sourceDepth(source: OpticalEmitterReconstruction.Source): Float = + depth[source.y.toInt().coerceIn(0,height-1)*width+source.x.toInt().coerceIn(0,width-1)] + val reconstruction = OpticalEmitterReconstruction.reconstruct(width,height,rgba, + maxOf(width,height)/65f,checkCancellation,depth) { source -> + psf.supportAt(sourceDepth(source)) > source.radius*scale*1.2f + } + val instances = FloatArray(reconstruction.sources.size*7) + for ((i,source) in reconstruction.sources.withIndex()) { + val d = sourceDepth(source) + val offset=i*7 + instances[offset]=source.x/width + instances[offset+1]=source.y/height + instances[offset+2]=d + val pixelArea=scale*(imageHeight.toFloat()/height) + instances[offset+3]=source.red*pixelArea + instances[offset+4]=source.green*pixelArea + instances[offset+5]=source.blue*pixelArea + instances[offset+6]=psf.supportAt(d)+scale + } + if (instances.isEmpty()) return ReconstructedEmitters(sourceTexture,instances).also { + PLog.d(TAG,"Optical reconstructed sources: count=0, total=${SystemClock.elapsedRealtime()-started}ms") + } + bytes.position(0) + for (i in 0 until width*height) { + val remove = reconstruction.ownership[i].toInt() != 0 + for (channel in 0..3) bytes.putShort(Half.toHalf( + if (remove && channel < 3) 0f else rgba[i*4+channel])) + } + bytes.position(0) + val remaining = createOpticalRenderTexture(width,height,mipmap=true) + GLES30.glTexSubImage2D(GLES30.GL_TEXTURE_2D,0,0,0,width,height,GLES30.GL_RGBA,GLES30.GL_HALF_FLOAT,bytes) + GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D) + requireNoGlError("remaining finite optical sources") + PLog.d(TAG,"Optical reconstructed sources: count=${reconstruction.sources.size}, " + + "ownedPixels=${reconstruction.ownership.count { it.toInt()!=0 }}, " + + "total=${SystemClock.elapsedRealtime()-started}ms, flux=integrated-linear, profile=${psf.lens.profile.id}") + return ReconstructedEmitters(remaining,instances) + } finally { + LargeDirectBuffer.free(bytes) + } + } + + private fun drawReconstructedEmitters(instances: FloatArray, psf: OpticalPsfTable, + cdfTexture: Int, supportTexture: Int, depthTexture: Int, + imageWidth: Int, imageHeight: Int, renderWidth: Int, + aperture: Float, focusDepth: Float, baseCocRadius: Float) { + if (instances.isEmpty()) return + val program=reconstructedEmitterProgramId + GLES30.glUseProgram(program) + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D,depthTexture) + GLES30.glUniform1i(GLES30.glGetUniformLocation(program,"uDepthTexture"),1) + GLES30.glUniform2f(GLES30.glGetUniformLocation(program,"uTexelSize"),1f/imageWidth,1f/imageHeight) + GLES30.glUniform1f(GLES30.glGetUniformLocation(program,"uPixelFootprint"),imageWidth.toFloat()/renderWidth) + GLES30.glUniform1f(GLES30.glGetUniformLocation(program,"uAperture"),aperture) + GLES30.glUniform1f(GLES30.glGetUniformLocation(program,"uFocusDepth"),focusDepth) + GLES30.glUniform1f(GLES30.glGetUniformLocation(program,"uBaseCocRadius"),baseCocRadius) + bindPsf(program,psf,cdfTexture,supportTexture) + val buffer=LargeDirectBuffer.allocate(instances.size.toLong()*4,"reconstructed optical instances") + ?: error("Unable to allocate optical instances") + val attributes=arrayOf("aCenter","aDepth","aFlux","aSupport").map { GLES30.glGetAttribLocation(program,it) } + try { + buffer.order(ByteOrder.nativeOrder()).asFloatBuffer().put(instances).position(0) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER,highlightInstanceBufferId) + GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER,instances.size*4,buffer,GLES30.GL_STREAM_DRAW) + val sizes=intArrayOf(2,1,3,1); val offsets=intArrayOf(0,2,3,6) + for (i in attributes.indices) { + GLES30.glEnableVertexAttribArray(attributes[i]) + GLES30.glVertexAttribPointer(attributes[i],sizes[i],GLES30.GL_FLOAT,false,28,offsets[i]*4) + GLES30.glVertexAttribDivisor(attributes[i],1) + } + GLES30.glEnable(GLES30.GL_BLEND) + GLES30.glBlendEquation(GLES30.GL_FUNC_ADD) + GLES30.glBlendFunc(GLES30.GL_ONE,GLES30.GL_ONE) + GLES30.glDrawArraysInstanced(GLES30.GL_TRIANGLES,0,6,instances.size/7) + requireNoGlError("reconstructed pupil PSF instances") + } finally { + GLES30.glDisable(GLES30.GL_BLEND) + GLES30.glBlendFunc(GLES30.GL_ONE,GLES30.GL_ZERO) + for (attribute in attributes) { + GLES30.glVertexAttribDivisor(attribute,0) + GLES30.glDisableVertexAttribArray(attribute) + } + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER,0) + LargeDirectBuffer.free(buffer) + } + } + + private fun createOpticalRenderTexture(width: Int, height: Int, mipmap: Boolean = false): Int { + val texture = IntArray(1) + GLES30.glGenTextures(1, texture, 0) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture[0]) + GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, + width, height, 0, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, + if (mipmap) GLES30.GL_LINEAR_MIPMAP_LINEAR else GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + return texture[0] + } + private fun requireFramebufferComplete(label: String) { val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) check(status == GLES30.GL_FRAMEBUFFER_COMPLETE) { @@ -1289,7 +1520,7 @@ class OglBokehProcessor { check(error == GLES30.GL_NO_ERROR) { "$label: GL error 0x${error.toString(16)}" } } - private fun createScalarTexture(width: Int, height: Int, values: FloatArray, label: String): Int { + private fun createScalarTexture(width: Int, height: Int, values: FloatArray, label: String, fullPrecision: Boolean = false): Int { val byteCount = values.size.toLong() * Float.SIZE_BYTES val uploadBuffer = LargeDirectBuffer.allocate(byteCount, "OGL $label upload") ?: throw IllegalStateException("Unable to allocate $label upload buffer") @@ -1303,14 +1534,14 @@ class OglBokehProcessor { GLES30.glGenTextures(1, texture, 0) GLES30.glActiveTexture(GLES30.GL_TEXTURE0) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture[0]) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, if (fullPrecision) GLES30.GL_NEAREST else GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, if (fullPrecision) GLES30.GL_NEAREST else GLES30.GL_LINEAR) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) GLES30.glTexImage2D( GLES30.GL_TEXTURE_2D, 0, - GLES30.GL_R16F, + if (fullPrecision) GLES30.GL_R32F else GLES30.GL_R16F, width, height, 0, @@ -1318,7 +1549,7 @@ class OglBokehProcessor { GLES30.GL_FLOAT, floatBuffer, ) - requireNoGlError("$label R16F upload") + requireNoGlError("$label scalar upload (fullPrecision=$fullPrecision)") return texture[0] } catch (error: Throwable) { if (texture[0] != 0) GLES30.glDeleteTextures(1, texture, 0) @@ -1547,37 +1778,44 @@ class OglBokehProcessor { check(maxOf(width, height) <= textureLimit[0]) { "Bokeh image exceeds GL_MAX_TEXTURE_SIZE" } } - private fun initGL(bokehStyle: BokehStyle) { + private fun initGL(bokehStyle: BokehStyle, colorTransfer: String?) { val naturalPsfStyle = bokehStyle != BokehStyle.DEFAULT - val soapBubbleStyle = bokehStyle == BokehStyle.BUBBLE - val needsCompactHighlights = bokehStyle != BokehStyle.NATURAL + val physicalBubble = bokehStyle == BokehStyle.BUBBLE + val needsCompactHighlights = bokehStyle == BokehStyle.DEFAULT val needsAnalyticOverlay = bokehStyle == BokehStyle.DEFAULT val vs = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.SIMPLE_VERTEX_SHADER) check(vs != 0) { "Bokeh vertex shader compilation failed" } try { + if (physicalBubble) emitterSeparationProgramId = createProgram( + vs, PhysicalBokehShaders.separateEmitters, "optical emitter separation", + ) + if (physicalBubble) { + emitterErosionProgramId = createProgram(vs, PhysicalBokehShaders.emitterEnvironment(true), "emitter environment erosion") + emitterDilationProgramId = createProgram(vs, PhysicalBokehShaders.emitterEnvironment(false), "emitter environment dilation") + } if (ANALYTIC_BOKEH_HIGHLIGHTS_ENABLED && needsCompactHighlights) { compactHighlightProgramId = createProgram( vs, - Shaders.compactBokehHighlightFragmentShader(soapBubbleStyle), + Shaders.COMPACT_BOKEH_HIGHLIGHT_FRAGMENT_SHADER, "compact bokeh highlight" ) } bokehProgramId = createProgram( vs, - Shaders.psfSplatFragmentShader( + if (physicalBubble) PhysicalBokehShaders.gather else Shaders.psfSplatFragmentShader( naturalStyle = naturalPsfStyle, - soapBubbleStyle = soapBubbleStyle, ), "PSF bokeh", ) bokehCompositeProgramId = createProgram( vs, - Shaders.BOKEH_COMPOSITE_FRAGMENT_SHADER, + if (physicalBubble) PhysicalBokehShaders.composite(checkNotNull(colorTransfer)) + else Shaders.BOKEH_COMPOSITE_FRAGMENT_SHADER, "bokeh composite", ) jbuUpsampleProgramId = createProgram(vs, Shaders.JBU_UPSAMPLE_FRAGMENT_SHADER, "depth upsample") depthRefineProgramId = createProgram(vs, Shaders.DEPTH_REFINE_FRAGMENT_SHADER, "depth refine") - layerColorProgramId = createProgram(vs, Shaders.BOKEH_LAYER_COLOR_FRAGMENT_SHADER, "premultiplied bokeh layer") + layerColorProgramId = createProgram(vs, Shaders.bokehLayerColorFragmentShader(colorTransfer), "premultiplied bokeh layer") if (ANALYTIC_BOKEH_HIGHLIGHTS_ENABLED && needsAnalyticOverlay) { depthReadbackProgramId = createProgram( vs, @@ -1592,7 +1830,7 @@ class OglBokehProcessor { if (ANALYTIC_BOKEH_HIGHLIGHTS_ENABLED && needsAnalyticOverlay) { val analyticHighlightVertexShader = GlUtils.compileShader( GLES30.GL_VERTEX_SHADER, - Shaders.analyticBokehHighlightVertexShader(soapBubbleStyle), + Shaders.ANALYTIC_BOKEH_HIGHLIGHT_VERTEX_SHADER, ) check(analyticHighlightVertexShader != 0) { "Analytic bokeh highlight vertex shader compilation failed" @@ -1600,7 +1838,7 @@ class OglBokehProcessor { try { analyticHighlightProgramId = createProgram( analyticHighlightVertexShader, - Shaders.analyticBokehHighlightFragmentShader(soapBubbleStyle), + Shaders.ANALYTIC_BOKEH_HIGHLIGHT_FRAGMENT_SHADER, "analytic bokeh highlight", ) } finally { @@ -1608,6 +1846,14 @@ class OglBokehProcessor { } } + if (physicalBubble) { + val emitterVertex = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER,PhysicalBokehShaders.emitterVertex) + check(emitterVertex != 0) { "Reconstructed emitter vertex shader compilation failed" } + try { + reconstructedEmitterProgramId=createProgram(emitterVertex,PhysicalBokehShaders.emitterFragment,"reconstructed optical sources") + } finally { GLES30.glDeleteShader(emitterVertex) } + } + vertexBufferId = GlUtils.createBuffer(Shaders.FULL_QUAD_VERTICES) texCoordBufferId = GlUtils.createBuffer(Shaders.TEXTURE_COORDS) @@ -1668,6 +1914,10 @@ class OglBokehProcessor { if (depthRefineProgramId != 0) GLES30.glDeleteProgram(depthRefineProgramId) if (depthReadbackProgramId != 0) GLES30.glDeleteProgram(depthReadbackProgramId) if (layerColorProgramId != 0) GLES30.glDeleteProgram(layerColorProgramId) + if (emitterSeparationProgramId != 0) GLES30.glDeleteProgram(emitterSeparationProgramId) + if (emitterErosionProgramId != 0) GLES30.glDeleteProgram(emitterErosionProgramId) + if (emitterDilationProgramId != 0) GLES30.glDeleteProgram(emitterDilationProgramId) + if (reconstructedEmitterProgramId != 0) GLES30.glDeleteProgram(reconstructedEmitterProgramId) if (vertexBufferId != 0) GLES30.glDeleteBuffers(1, intArrayOf(vertexBufferId), 0) if (texCoordBufferId != 0) GLES30.glDeleteBuffers(1, intArrayOf(texCoordBufferId), 0) if (indexBufferId != 0) GLES30.glDeleteBuffers(1, intArrayOf(indexBufferId), 0) @@ -1692,6 +1942,10 @@ class OglBokehProcessor { depthRefineProgramId = 0 depthReadbackProgramId = 0 layerColorProgramId = 0 + emitterSeparationProgramId = 0 + emitterErosionProgramId = 0 + emitterDilationProgramId = 0 + reconstructedEmitterProgramId = 0 vertexBufferId = 0 texCoordBufferId = 0 indexBufferId = 0 diff --git a/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalColorTransfer.kt b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalColorTransfer.kt new file mode 100644 index 00000000..18f85d25 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalColorTransfer.kt @@ -0,0 +1,69 @@ +package com.hinnka.mycamera.processor.optics + +import android.graphics.ColorSpace +import java.util.Locale +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.pow + +/** Keep the source RGB primaries; only its declared transfer function is removed and restored. */ +internal class OpticalColorTransfer(colorSpace: ColorSpace) { + private val rgb = colorSpace as? ColorSpace.Rgb + ?: error("Optical bokeh requires an RGB color space") + private val parameters = rgb.transferParameters + ?: error("Optical bokeh does not support the non-parametric transfer of ${rgb.name}") + private val signed: Boolean + + init { + val p = parameters + require(p.a > 0.0 && p.g > 0.0 && p.c >= 0.0) + fun decode(value: Double, useSign: Boolean): Double { + val x = if (useSign) abs(value) else value + val y = if (x < p.d) p.c * x + p.f else (p.a * x + p.b).pow(p.g) + p.e + return if (useSign && value < 0.0) -y else y + } + val minimum = rgb.getMinValue(0).toDouble() + val probes = listOf(minimum, 0.0, 0.018, 0.04, 0.18, 0.5, 1.0) + .filter { it >= minimum && it <= rgb.getMaxValue(0) } + fun matches(useSign: Boolean) = probes.all { x -> + val expected = rgb.eotf.applyAsDouble(x) + val actual = decode(x, useSign) + actual.isFinite() && abs(actual - expected) <= 1e-6 * max(1.0, abs(expected)) + } + signed = when { + matches(false) -> false + matches(true) -> true + else -> error("Color-space transfer parameters disagree with ${rgb.name}") + } + } + + fun shaderFunctions(): String { + val p = parameters + fun Double.glsl() = String.format(Locale.US, "%.17e", this) + val decodeInput = if (signed) "abs(value)" else "value" + val resultSign = if (signed) "sign(value) * result" else "result" + val linearEncode = if (p.c > 0.0) "(x - ${p.f.glsl()}) / ${p.c.glsl()}" else "0.0" + return """ + float decodeChannel(float value) { + float x = $decodeInput; + float result = x < ${p.d.glsl()} + ? ${p.c.glsl()} * x + ${p.f.glsl()} + : pow(max(${p.a.glsl()} * x + ${p.b.glsl()}, 0.0), ${p.g.glsl()}) + ${p.e.glsl()}; + return $resultSign; + } + float encodeChannel(float value) { + float x = $decodeInput; + float result = x < ${(p.c * p.d + p.f).glsl()} + ? $linearEncode + : (pow(max(x - ${p.e.glsl()}, 0.0), ${(1.0 / p.g).glsl()}) - ${p.b.glsl()}) / ${p.a.glsl()}; + return $resultSign; + } + vec3 decodeColor(vec3 value) { + return vec3(decodeChannel(value.r), decodeChannel(value.g), decodeChannel(value.b)); + } + vec3 encodeColor(vec3 value) { + return vec3(encodeChannel(value.r), encodeChannel(value.g), encodeChannel(value.b)); + } + """.trimIndent() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalEmitterReconstruction.kt b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalEmitterReconstruction.kt new file mode 100644 index 00000000..58324004 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalEmitterReconstruction.kt @@ -0,0 +1,105 @@ +package com.hinnka.mycamera.processor.optics + +import kotlin.math.max +import kotlin.math.sqrt + +/** Estimates unresolved emitters from already imaged, compact light footprints. + * Geometry selects evidence; the rendering profile remains the pupil-derived PSF. + * Accepted pixels are removed once and their integrated linear RGB is transported + * once. Neither the observed peak brightness nor the old blur radius is copied + * into the new PSF. Extended/ambiguous light retains the finite-source path. + */ +internal object OpticalEmitterReconstruction { + const val MIN_PEAK = .12f + data class Source(val x: Float, val y: Float, val red: Float, val green: Float, val blue: Float, + val radius: Float) + data class Result(val sources: List, val ownership: ByteArray) + + fun reconstruct(width: Int, height: Int, rgba: FloatArray, maxRadius: Float, + checkCancellation: () -> Unit = {}, depths: FloatArray? = null, + acceptSource: (Source) -> Boolean = { true }): Result { + require(width > 0 && height > 0 && rgba.size == width * height * 4 && maxRadius > 0f) + val count = width * height + require(depths == null || depths.size == count) + val light = FloatArray(count) { i -> max(rgba[i*4], max(rgba[i*4+1], rgba[i*4+2])).coerceAtLeast(0f) } + if (light.none { it >= MIN_PEAK }) return Result(emptyList(),ByteArray(count)) + // Smooth discovery only; integration always uses the unfiltered source. + val smooth = FloatArray(count) + for (y in 0 until height) { + if (y % 32 == 0) checkCancellation() + for (x in 0 until width) { + var sum = 0f + for (dy in -1..1) for (dx in -1..1) sum += light[ + (y+dy).coerceIn(0,height-1)*width+(x+dx).coerceIn(0,width-1)] * + (if (dx == 0) 2f else 1f) * (if (dy == 0) 2f else 1f) + smooth[y*width+x] = sum/16f + } + } + val parent = IntArray(count) { it } + for (y in 0 until height) for (x in 0 until width) { + val i=y*width+x + if (light[i] < .002f) continue + var best=i + for (dy in -1..1) for (dx in -1..1) { + val xx=x+dx; val yy=y+dy + if (xx !in 0 until width || yy !in 0 until height) continue + val j=yy*width+xx + if (light[j] < .002f) continue + if (depths != null && kotlin.math.abs(depths[j]-depths[i]) > .025f) continue + if (smooth[j] > smooth[best] || smooth[j] == smooth[best] && j < best) best=j + } + parent[i]=best + } + fun root(index: Int): Int { + var r=index + while (parent[r] != r) r=parent[r] + var i=index + while (parent[i] != i) { val next=parent[i]; parent[i]=r; i=next } + return r + } + val peaks=FloatArray(count) + for (i in 0 until count) if (light[i] >= .002f) { + val r=root(i); peaks[r]=max(peaks[r],light[i]) + } + class Moments { + var weight=0.0; var x=0.0; var y=0.0; var xx=0.0; var yy=0.0; var xy=0.0 + var red=0.0; var green=0.0; var blue=0.0; var pixels=0 + var minX=Int.MAX_VALUE; var maxX=0; var minY=Int.MAX_VALUE; var maxY=0 + var minDepth=1f; var maxDepth=0f + } + val moments=HashMap() + for (i in 0 until count) { + if (i % (width*32) == 0) checkCancellation() + val r=parent[i] + if (peaks[r] < MIN_PEAK || light[i] < max(.002f,peaks[r]*.04f)) continue + val m=moments.getOrPut(r) { Moments() }; val x=i%width; val y=i/width; val w=light[i].toDouble() + m.weight+=w; m.x+=w*x; m.y+=w*y; m.xx+=w*x*x; m.yy+=w*y*y; m.xy+=w*x*y + m.red+=rgba[i*4]; m.green+=rgba[i*4+1]; m.blue+=rgba[i*4+2]; m.pixels++ + m.minX=minOf(m.minX,x); m.maxX=maxOf(m.maxX,x); m.minY=minOf(m.minY,y); m.maxY=maxOf(m.maxY,y) + if (depths != null) { m.minDepth=minOf(m.minDepth,depths[i]); m.maxDepth=maxOf(m.maxDepth,depths[i]) } + } + val accepted=HashSet(); val sources=ArrayList() + for ((r,m) in moments) { + if (m.pixels < 6 || m.minX == 0 || m.minY == 0 || m.maxX == width-1 || m.maxY == height-1) continue + if (depths != null && m.maxDepth-m.minDepth > .04f) continue + val cx=m.x/m.weight; val cy=m.y/m.weight + val vx=max(0.0,m.xx/m.weight-cx*cx); val vy=max(0.0,m.yy/m.weight-cy*cy); val cov=m.xy/m.weight-cx*cy + val gap=sqrt((vx-vy)*(vx-vy)+4*cov*cov) + val major=(vx+vy+gap)*.5; val minor=max(0.0,(vx+vy-gap)*.5) + val radius=2*sqrt(major) // equivalent uniform-disc radius along its major axis + val fill=m.pixels.toDouble()/((m.maxX-m.minX+1)*(m.maxY-m.minY+1)) + if (radius < 1.2 || radius > maxRadius || minor < major*.3 || fill < .3) continue + val source=Source((cx+.5).toFloat(),(cy+.5).toFloat(),m.red.toFloat(),m.green.toFloat(),m.blue.toFloat(),radius.toFloat()) + if (!acceptSource(source)) continue + accepted+=r + sources+=source + } + val ownership=ByteArray(count) + for (i in 0 until count) { + val r=parent[i] + if (r in accepted && light[i] >= max(.002f,peaks[r]*.04f)) ownership[i]=(-1).toByte() + } + checkCancellation() + return Result(sources,ownership) + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalLensProfile.kt b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalLensProfile.kt new file mode 100644 index 00000000..486a4a2d --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalLensProfile.kt @@ -0,0 +1,117 @@ +package com.hinnka.mycamera.processor.optics + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.pow + +/** Physical lengths are metres. The reference pupil specifies a fixed phase plate, not a PSF. */ +data class OpticalLensProfile( + val id: String, + val focalLengthMeters: Double, + val sensorLongEdgeMeters: Double, + val referenceFNumber: Double, + val referenceSphericalOpdMeters: Double, + val nominalFocusMeters: Double, + val sphericalOrder: Int = 4, +) { + init { + require(id.isNotBlank()) + require(focalLengthMeters.isFinite() && focalLengthMeters > 0.0) + require(sensorLongEdgeMeters.isFinite() && sensorLongEdgeMeters > 0.0) + require(referenceFNumber.isFinite() && referenceFNumber > 0.0) + require(referenceSphericalOpdMeters.isFinite()) + require(nominalFocusMeters.isFinite() && nominalFocusMeters > focalLengthMeters) + require(sphericalOrder in 4..8 && sphericalOrder % 2 == 0) + } + + val referencePupilRadiusMeters get() = focalLengthMeters / (2.0 * referenceFNumber) + val sphericalCoefficient get() = referenceSphericalOpdMeters / referencePupilRadiusMeters.pow(sphericalOrder) + + fun atAperture(fNumber: Double, imageLongEdge: Int): OpticalLensState { + require(fNumber.isFinite() && fNumber > 0.0) + require(imageLongEdge > 0) + val pupil = focalLengthMeters / (2.0 * fNumber) + val spherical = sphericalCoefficient * pupil.pow(sphericalOrder) + // Focus is defined by minimum geometrical RMS ray radius. Minimizing + // integral_0^1 (A*rho+B*rho^(n-1))^2 2*rho d(rho) gives A=-4B/(n+2). + // The focus adjustment is a quadratic phase term in this thin optical system. + val focusOpd = -2.0 * sphericalOrder * spherical / (sphericalOrder + 2.0) + val imageDistance = 1.0 / (1.0 / focalLengthMeters - 1.0 / nominalFocusMeters) + return OpticalLensState( + profile = this, + fNumber = fNumber, + pupilRadiusMeters = pupil, + imageDistanceMeters = imageDistance, + pixelPitchMeters = sensorLongEdgeMeters / imageLongEdge, + sphericalOpdMeters = spherical, + focusOpdMeters = focusOpd, + ) + } + + companion object { + /** A declared virtual optical system; not a recovered prescription of the reference photograph. */ + val SOAP_BUBBLE = OpticalLensProfile( + id = "phase-plate-135mm-order4-balanced", + focalLengthMeters = 0.135, + sensorLongEdgeMeters = 0.036, + referenceFNumber = 1.8, + referenceSphericalOpdMeters = 5.6915283203125e-6, + nominalFocusMeters = 2.0, + sphericalOrder = 4, + ) + + /** Telephoto pupil used only to transport separated compact-source radiance. + * The diffuse layer keeps SOAP_BUBBLE. This is a computational two-path + * exposure, not a brightness-dependent property of a single real lens. + */ + val SOAP_BUBBLE_EMITTER = SOAP_BUBBLE.copy( + id = "phase-plate-200mm-emitter", + focalLengthMeters = 0.200, + referenceSphericalOpdMeters = 22.76611328125e-6, + ) + } +} + +data class OpticalLensState( + val profile: OpticalLensProfile, + val fNumber: Double, + val pupilRadiusMeters: Double, + val imageDistanceMeters: Double, + val pixelPitchMeters: Double, + val sphericalOpdMeters: Double, + val focusOpdMeters: Double, +) { + val defocusPixelsPerDiopter = pupilRadiusMeters * imageDistanceMeters / pixelPitchMeters + val focusRayPixels = 2.0 * imageDistanceMeters * focusOpdMeters / (pupilRadiusMeters * pixelPitchMeters) + val sphericalRayPixels = profile.sphericalOrder * imageDistanceMeters * sphericalOpdMeters / (pupilRadiusMeters * pixelPitchMeters) + + fun defocusOpdMeters(inverseDepthDifference: Double) = + 0.5 * pupilRadiusMeters * pupilRadiusMeters * inverseDepthDifference + focusOpdMeters + + fun opticalPathMeters(rho: Double, inverseDepthDifference: Double): Double { + val rho2 = rho * rho + return defocusOpdMeters(inverseDepthDifference) * rho2 + sphericalOpdMeters * rho.pow(profile.sphericalOrder) + } + + fun signedRayRadiusPixels(rho: Double, inverseDepthDifference: Double) = + (defocusPixelsPerDiopter * inverseDepthDifference + focusRayPixels) * rho + + sphericalRayPixels * rho.pow(profile.sphericalOrder - 1) + + fun supportRadiusPixels(inverseDepthDifference: Double): Double { + val a = defocusPixelsPerDiopter * inverseDepthDifference + focusRayPixels + val b = sphericalRayPixels + var radius = abs(a + b) + if (b != 0.0) { + val criticalPower = -a / ((profile.sphericalOrder - 1) * b) + if (criticalPower > 0.0 && criticalPower < 1.0) { + val rho = criticalPower.pow(1.0 / (profile.sphericalOrder - 2)) + radius = max(radius, abs(signedRayRadiusPixels(rho, inverseDepthDifference))) + } + } + return radius + } + + fun phaseRadians(rho: Double, inverseDepthDifference: Double, wavelengthMeters: Double) = + 2.0 * PI * opticalPathMeters(rho, inverseDepthDifference) / wavelengthMeters +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalPsfTable.kt b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalPsfTable.kt new file mode 100644 index 00000000..f5c3fbf9 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalPsfTable.kt @@ -0,0 +1,146 @@ +package com.hinnka.mycamera.processor.optics + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.pow +import kotlin.math.sqrt + +/** + * Finite-area geometrical PSFs, obtained by transporting a uniformly illuminated pupil. + * + * Rows run from disparity 0 to 1. Columns are concentric, equal-width annuli in output + * pixels. Each texel stores energy per square output pixel, not energy per radial bin. + * Consequently a caustic remains finite and each row integrates to unit energy without + * choosing a ring profile, applying a brightness gain, or discarding crossing rays. + * + * Sample radial columns with nearest lookup and interpolate only between depth rows. + * Radial linear texture filtering would change the annular energy represented here. + */ +class OpticalPsfTable private constructor( + val lens: OpticalLensState, + val calibration: OpticalSceneCalibration, + val radialBinCount: Int, + val depthCount: Int, + val binWidthPixels: Float, + val densities: FloatArray, + /** Row-major energy at annulus edges; each row has radialBinCount + 1 entries. */ + val cumulativeEnergy: FloatArray, + val supportPixels: FloatArray, + val maximumSupportPixels: Float, +) { + /** Includes the finite annulus containing the outermost ray. */ + val tableSupportPixels: Float get() = radialBinCount * binWidthPixels + + /** Integrate finite annular density; interpolate within a bin by radius squared. */ + fun cumulativeEnergyAt(disparity: Float, radiusPixels: Float): Float { + require(disparity.isFinite() && radiusPixels.isFinite()) + if (radiusPixels <= 0f) return 0f + if (radiusPixels >= tableSupportPixels) return 1f + val radialPosition = radiusPixels / binWidthPixels + val bin = floor(radialPosition).toInt().coerceAtMost(radialBinCount - 1) + val annularFraction = ((radialPosition * radialPosition - bin.toFloat() * bin) / + (2f * bin + 1f)).coerceIn(0f, 1f) + val depthPosition = disparity.coerceIn(0f, 1f) * (depthCount - 1) + val low = floor(depthPosition).toInt() + val high = (low + 1).coerceAtMost(depthCount - 1) + fun rowEnergy(row: Int): Float { + val start = row * (radialBinCount + 1) + bin + val a = cumulativeEnergy[start] + return a + (cumulativeEnergy[start + 1] - a) * annularFraction + } + val a = rowEnergy(low) + return a + (rowEnergy(high) - a) * (depthPosition - low) + } + + /** Reference for the shader's nearest-radius, linear-depth lookup. */ + fun densityAt(disparity: Float, radiusPixels: Float): Float { + require(disparity.isFinite() && radiusPixels.isFinite()) + if (radiusPixels < 0f || radiusPixels >= tableSupportPixels) return 0f + val bin = floor(radiusPixels / binWidthPixels).toInt() + if (bin >= radialBinCount) return 0f + val depthPosition = disparity.coerceIn(0f, 1f) * (depthCount - 1) + val low = floor(depthPosition).toInt() + val high = (low + 1).coerceAtMost(depthCount - 1) + val fraction = depthPosition - low + val a = densities[low * radialBinCount + bin] + val b = densities[high * radialBinCount + bin] + return a + (b - a) * fraction + } + + /** Conservative support of both rows used in a lookup, including annulus width. */ + fun supportAt(disparity: Float): Float { + require(disparity.isFinite()) + val position = disparity.coerceIn(0f, 1f) * (depthCount - 1) + val low = floor(position).toInt() + val high = ceil(position).toInt() + val physicalSupport = max(supportPixels[low], supportPixels[high]) + return max(1f, ceil(physicalSupport / binWidthPixels)) * binWidthPixels + } + + companion object { + private const val DEPTH_ROWS = 257 + private const val PUPIL_SAMPLES = 16_384 + + fun build( + profile: OpticalLensProfile, + aperture: Float, + focusDepth: Float, + imageLongEdge: Int, + renderLongEdge: Int, + checkCancellation: () -> Unit = {}, + sceneReferenceProfile: OpticalLensProfile? = null, + ): OpticalPsfTable { + checkCancellation() + require(imageLongEdge > 0 && renderLongEdge > 0) + val lens = profile.atAperture(aperture.toDouble(), imageLongEdge) + val calibration = OpticalSceneCalibration(focusDepth.toDouble(), sceneReferenceProfile) + // Resolve a quarter of a working pixel, without pretending to resolve + // finer than half an output pixel in the geometrical approximation. + val binWidth = max(0.5, 0.25 * imageLongEdge / renderLongEdge).toFloat() + val maximumSupport = calibration.maximumSupportPixels(lens) + val bins = max(1, ceil(maximumSupport / binWidth).toInt()) + val densities = FloatArray(bins * DEPTH_ROWS) + val cumulativeEnergy = FloatArray((bins + 1) * DEPTH_ROWS) + val supports = FloatArray(DEPTH_ROWS) + val counts = IntArray(bins) + // t = rho^2 has uniform pupil-area measure. Midpoint quadrature never + // samples the singular axis or assigns special weight to a caustic. + val rho = DoubleArray(PUPIL_SAMPLES) { sqrt((it + 0.5) / PUPIL_SAMPLES) } + val sphericalRay = DoubleArray(PUPIL_SAMPLES) { + lens.sphericalRayPixels * rho[it].pow(profile.sphericalOrder - 1) + } + val densityPerRay = DoubleArray(bins) { + 1.0 / (PUPIL_SAMPLES * PI * binWidth.toDouble() * binWidth * (2.0 * it + 1.0)) + } + repeat(DEPTH_ROWS) { row -> + checkCancellation() + val disparity = row.toDouble() / (DEPTH_ROWS - 1) + val delta = calibration.inverseDepthDifference(disparity, lens) + val defocusRay = lens.defocusPixelsPerDiopter * delta + lens.focusRayPixels + supports[row] = lens.supportRadiusPixels(delta).toFloat() + counts.fill(0) + repeat(PUPIL_SAMPLES) { pupil -> + // A negative signed radius crosses the axis. Its energy belongs + // at the positive radius with the opposite azimuth, not at zero. + val radius = abs(defocusRay * rho[pupil] + sphericalRay[pupil]) + val bin = floor(radius / binWidth).toInt().coerceAtMost(bins - 1) + counts[bin]++ + } + var cumulativeCount = 0 + repeat(bins) { bin -> + densities[row * bins + bin] = (counts[bin] * densityPerRay[bin]).toFloat() + cumulativeCount += counts[bin] + cumulativeEnergy[row * (bins + 1) + bin + 1] = cumulativeCount.toFloat() / PUPIL_SAMPLES + } + } + checkCancellation() + return OpticalPsfTable( + lens, calibration, bins, DEPTH_ROWS, binWidth, densities, cumulativeEnergy, supports, + maximumSupport.toFloat(), + ) + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalSceneCalibration.kt b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalSceneCalibration.kt new file mode 100644 index 00000000..bc4577fd --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/optics/OpticalSceneCalibration.kt @@ -0,0 +1,32 @@ +package com.hinnka.mycamera.processor.optics + +import com.hinnka.mycamera.processor.BokehDefocusModel + +/** + * The normalized monocular map has already had its polarity resolved (larger = nearer). + * Converts the shared computational defocus control to a quadratic optical path. + * The map is not metric depth: its dead band, nonlinearity and aperture limits are + * the same image-space calibration used by natural/swirl bokeh. Inverting av/p + * calibrates the incoming wavefront; it does not resize an already formed PSF. + */ +data class OpticalSceneCalibration( + val focusDisparity: Double, + val referenceProfile: OpticalLensProfile? = null, +) { + init { + require(focusDisparity.isFinite() && focusDisparity in 0.0..1.0) + } + + fun inverseDepthDifference(disparity: Double, lens: OpticalLensState): Double { + // Both paths observe the same virtual scene. The longer emitter lens + // must not recalibrate those distances back to the diffuse CoC. + val reference = referenceProfile?.atAperture(lens.fNumber, 1) ?: lens + return BokehDefocusModel.signedRadiusFraction(disparity, focusDisparity, lens.fNumber) * + reference.profile.sensorLongEdgeMeters / (reference.pupilRadiusMeters * reference.imageDistanceMeters) + } + + fun maximumSupportPixels(lens: OpticalLensState): Double = maxOf( + lens.supportRadiusPixels(inverseDepthDifference(0.0, lens)), + lens.supportRadiusPixels(inverseDepthDifference(1.0, lens)), + ) +} diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt index 6a16e12c..a14d6390 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -471,6 +471,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) private var bokehJob: Job? = null fun setComputationalAperture(value: Float?) { + if (editComputationalAperture.value == value) return editComputationalAperture.value = value updateBokehPhoto() } @@ -534,46 +535,76 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) return updated } + private val bokehUpdateMutex = Mutex() + private fun updateBokehPhoto() { - bokehJob?.cancel() + val previousJob = bokehJob + previousJob?.cancel() + val photoData = getCurrentPhoto() ?: return + val aperture = editComputationalAperture.value + val focusPointX = editFocusPointX.value + val focusPointY = editFocusPointY.value + val bokehStyle = editBokehStyle.value bokehJob = viewModelScope.launch(Dispatchers.IO) { - val context = getApplication() - val photoData = getCurrentPhoto() ?: return@launch - val aperture = editComputationalAperture.value - if (aperture == null || aperture <= 0) { - GalleryManager.getBokehFile(context, photoData.id).takeIf { it.exists() }?.delete() - GalleryManager.deleteDetailHdrFile(context, photoData.id) - return@launch + // Finish ownership of the previous image/file write before this + // request can replace or delete it. Rendering checks cancellation. + bokehUpdateMutex.lock() + try { + ensureActive() + val context = getApplication() + val metadata = GalleryManager.loadMetadata(context, photoData.id) ?: photoData.metadata ?: MediaMetadata() + if (aperture == null || aperture <= 0) { + GalleryManager.getBokehFile(context, photoData.id).takeIf { it.exists() }?.delete() + GalleryManager.deleteDetailHdrFile(context, photoData.id) + GalleryManager.updateThumbnail(context, photoData.id, contentRepository.photoProcessor, metadata = metadata) + ensureActive() + photoRefreshKeys[photoData.id] = System.currentTimeMillis() + return@launch + } + var bitmap: Bitmap? = null + var bokeh: Bitmap? = null + try { + val source = if (metadata.hasAiDenoisedBase) { + GalleryManager.loadBitmap(context, Uri.fromFile(GalleryManager.getAiDenoiseFile(context, photoData.id))) + } else { + GalleryManager.loadOriginalBitmap(context, photoData.id) + } + ?: GalleryManager.loadBitmap(context, photoData.uri) ?: return@launch + bitmap = source + ensureActive() + val rendered = contentRepository.depthBokehProcessor.applyHighQualityBokeh( + context, + photoData.id, + source, + focusPointX, + focusPointY, + aperture, + bokehStyle, + ) + bokeh = rendered + ensureActive() + GalleryManager.saveBokehPhoto(context, photoData.id, rendered) + GalleryManager.deleteDetailHdrFile(context, photoData.id) + GalleryManager.updateThumbnail( + context = context, + photoId = photoData.id, + photoProcessor = contentRepository.photoProcessor, + metadata = metadata, + inputBitmap = rendered, + ) + ensureActive() + photoRefreshKeys[photoData.id] = System.currentTimeMillis() + } finally { + bokeh?.let { rendered -> + if (rendered !== bitmap && !rendered.isRecycled) rendered.recycle() + } + bitmap?.let { sourceBitmap -> + if (!sourceBitmap.isRecycled) sourceBitmap.recycle() + } + } + } finally { + bokehUpdateMutex.unlock() } - val focusPointX = editFocusPointX.value - val focusPointY = editFocusPointY.value - val metadata = GalleryManager.loadMetadata(context, photoData.id) ?: photoData.metadata ?: MediaMetadata() - val bitmap = if (metadata.hasAiDenoisedBase) { - GalleryManager.loadBitmap(context, Uri.fromFile(GalleryManager.getAiDenoiseFile(context, photoData.id))) - } else { - GalleryManager.loadOriginalBitmap(context, photoData.id) - } - ?: GalleryManager.loadBitmap(context, photoData.uri) ?: return@launch - if (!isActive) return@launch - val bokeh = contentRepository.depthBokehProcessor.applyHighQualityBokeh( - context, - photoData.id, - bitmap, - focusPointX, - focusPointY, - aperture, - editBokehStyle.value, - ) - if (!isActive) return@launch - GalleryManager.saveBokehPhoto(context, photoData.id, bokeh) - GalleryManager.deleteDetailHdrFile(context, photoData.id) - GalleryManager.updateThumbnail( - context = context, - photoId = photoData.id, - photoProcessor = contentRepository.photoProcessor, - metadata = metadata - ) - photoRefreshKeys[photoData.id] = System.currentTimeMillis() } } diff --git a/app/src/test/java/com/hinnka/mycamera/lut/BokehShadersTest.kt b/app/src/test/java/com/hinnka/mycamera/lut/BokehShadersTest.kt index b429b3ae..13806238 100644 --- a/app/src/test/java/com/hinnka/mycamera/lut/BokehShadersTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/lut/BokehShadersTest.kt @@ -1,6 +1,7 @@ package com.hinnka.mycamera.lut import com.hinnka.mycamera.processor.BokehStyle +import com.hinnka.mycamera.processor.BokehDefocusModel import java.io.File import java.util.Properties import org.junit.Assert.assertEquals @@ -15,7 +16,6 @@ class BokehShadersTest { val shader = Shaders.PSF_SPLAT_FRAGMENT_SHADER val expectedUniforms = listOf( "uDepthTexture", - "uHighlightSourceTexture", "uLayerColorTexture", "uDepthMatrix", "uMaxBlurRadius", @@ -56,212 +56,52 @@ class BokehShadersTest { } @Test - fun bubbleBokehUsesIntegratedCenterWeightedPsf() { - val bokehShader = Shaders.PSF_SPLAT_FRAGMENT_SHADER - - assertTrue(bokehShader.contains("float softEdge = 1.0 - smoothstep(0.70, 1.05, lenP)")) - assertTrue(bokehShader.contains("float radialEnergy = exp(-lenP * lenP * 1.55)")) - assertTrue(bokehShader.contains("float centerWeightedTransmission = mix(")) - assertFalse(bokehShader.contains("centerHighlightLinear")) - assertFalse(bokehShader.contains("integratedHighlight")) - assertFalse(bokehShader.contains("bubbleHighlightWeight")) - assertFalse(bokehShader.contains("highlightAccColor")) - assertFalse(bokehShader.contains("highlightKernelWeight")) + fun naturalBokehKeepsItsCenterWeightedPsf() { + val shader = Shaders.psfSplatFragmentShader(naturalStyle = true) + assertTrue(shader.contains("#define NATURAL_BOKEH 1")) + assertTrue(shader.contains("float softEdge = 1.0 - smoothstep(0.70, 1.05, lenP)")) + assertTrue(shader.contains("float radialEnergy = exp(-lenP * lenP * 1.55)")) + assertTrue(shader.contains("float centerWeightedTransmission = mix(")) + assertTrue(shader.contains("float softBase = max(3.5, uMaxBlurRadius * 0.12)")) + assertEquals(Shaders.PSF_SPLAT_FRAGMENT_SHADER, Shaders.psfSplatFragmentShader(false)) } @Test - fun bokehOnlyReconstructsCompactHighlightsWithDefinedApertureEdges() { - val bokehShader = Shaders.PSF_SPLAT_FRAGMENT_SHADER - val compactHighlightShader = Shaders.COMPACT_BOKEH_HIGHLIGHT_FRAGMENT_SHADER - val analyticHighlightShader = Shaders.ANALYTIC_BOKEH_HIGHLIGHT_FRAGMENT_SHADER - - assertFalse( - "ordinary bokeh samples must not receive a blanket HDR boost", - bokehShader.contains("hdrBoost"), - ) - assertFalse( - "reverse smoothstep has undefined GLSL results", - bokehShader.contains("smoothstep(1.0, 0.88"), - ) - assertTrue(compactHighlightShader.contains("PROBE_DIRECTIONS[16]")) - assertTrue(compactHighlightShader.contains("if (centerLuma <=")) - assertTrue(compactHighlightShader.contains("if (ringLuma > centerLuma) return -1")) - assertTrue(compactHighlightShader.contains("allRingSamplesAreDarker")) - assertTrue(compactHighlightShader.contains("nearRingRadius")) - assertTrue(compactHighlightShader.contains("middleRingRadius")) - assertTrue(compactHighlightShader.contains("farRingRadius")) - assertTrue(compactHighlightShader.contains("if (ringResult != 1)")) - assertTrue(compactHighlightShader.contains("A complete ring cannot be observed")) - assertTrue( - compactHighlightShader.contains( - "MIN_HIGHLIGHT_CORE_RADIUS_PIXELS = 2.5" - ) - ) - assertTrue( - compactHighlightShader.contains( - "MIN_HIGHLIGHT_CORE_DIRECTION_COUNT = 12.0" - ) - ) - assertTrue(compactHighlightShader.contains("coreBrightnessThreshold")) - assertTrue(compactHighlightShader.contains("brightCoreSampleCount")) - assertFalse(compactHighlightShader.contains("darkerDirectionCount")) - assertFalse(compactHighlightShader.contains("darkDirectionRatio")) - assertTrue(compactHighlightShader.contains("mediumHighlightGate")) - assertTrue(compactHighlightShader.contains("strongPointGate")) - assertTrue(compactHighlightShader.contains("smoothstep(0.34, 0.62, centerLuma)")) - assertTrue(compactHighlightShader.contains("smoothstep(0.68, 0.92, centerLuma)")) - assertFalse(compactHighlightShader.contains("smoothstep(0.07, 0.26, centerLuma)")) - assertTrue(compactHighlightShader.contains("ringProbeRadius")) - assertTrue(compactHighlightShader.contains("maxRingLuma")) - assertTrue(compactHighlightShader.contains("relativeContrast")) - assertTrue(compactHighlightShader.contains("neighborhoodContrastGate")) - assertTrue( - compactHighlightShader.contains( - "uMinNeighborhoodLumaDifference + 0.04" - ) - ) - assertTrue(compactHighlightShader.contains("* neighborhoodContrastGate")) - assertTrue(compactHighlightShader.contains("localMaximumGate")) - assertTrue(compactHighlightShader.contains("centerednessGate")) - assertTrue(compactHighlightShader.contains("float compactCoreGate = smoothstep(")) - assertTrue(compactHighlightShader.contains("float removalCoreGate = smoothstep(")) - assertTrue(compactHighlightShader.contains("float classifiedHighlight = highlightGate")) - assertTrue(compactHighlightShader.contains("float broadHighlightSignal = classifiedHighlight")) - assertTrue(compactHighlightShader.contains("compactHighlight = pow(")) - assertTrue(compactHighlightShader.contains("centerLinear * broadHighlightSignal")) - assertTrue(compactHighlightShader.contains("sourceSignal * classifiedHighlight")) - assertTrue(bokehShader.contains("radialTransmission")) - assertTrue(bokehShader.contains("biotarAperturePosition")) - assertTrue(bokehShader.contains("vec2 tangential = vec2(-radial.y, radial.x)")) - assertTrue(bokehShader.contains("float radialScale = mix(1.0, 0.54, fieldStrength)")) - assertTrue(bokehShader.contains("float tangentialScale = mix(1.0, 1.08, fieldStrength)")) - assertTrue(bokehShader.contains("const float rotation = 0.0")) - assertFalse(bokehShader.contains("float hash(")) - assertTrue(bokehShader.contains("centerOccludesSource")) - assertTrue(bokehShader.contains("sourceVisibility")) - assertTrue(bokehShader.contains("focusedSurfaceProtection")) - assertTrue(bokehShader.contains("float occlusionStrength = mix(")) - assertTrue(bokehShader.contains("float radianceWeight = mix(")) - assertTrue(bokehShader.contains("smoothstep(0.64, 1.0, lenP)")) - assertTrue(bokehShader.contains("shoulder * 0.075")) - assertTrue(bokehShader.contains("#if NATURAL_BOKEH == 1")) - assertTrue(bokehShader.contains("#if SOAP_BUBBLE_BOKEH == 1")) - assertTrue(bokehShader.contains("float broadOpticalRim = smoothstep(")) - assertTrue(bokehShader.contains("transparentCore")) - assertTrue(bokehShader.contains("float compactHighlightConfidence = textureLod(")) - assertTrue(bokehShader.contains("float bubbleMix = clamp(")) - assertTrue(bokehShader.contains("float sceneIntegrationLod = inputIntegrationLod;")) - assertTrue(bokehShader.contains("float expandedCompactConfidence = smoothstep(")) - assertTrue(bokehShader.contains(") * 0.34;")) - assertTrue(bokehShader.contains("float softBase = max(4.5, uMaxBlurRadius * 0.16)")) - assertTrue(bokehShader.contains("float centerWeightedTransmission = mix(")) - assertFalse(bokehShader.contains("vec4 integratedHighlight = textureLod(")) - assertFalse(bokehShader.contains("float bubbleHighlightWeight(")) - assertTrue(bokehShader.contains("float compactSignalLod = clamp(")) - assertFalse(bokehShader.contains("highlightConfidence")) - assertFalse(bokehShader.contains("float irregularRadius = lenP")) - assertFalse(bokehShader.contains("bubbleRim * arcVisibility")) - assertTrue(bokehShader.contains("float softBase = max(3.5, uMaxBlurRadius * 0.12)")) - assertTrue(bokehShader.contains("float foregroundDefocusPotential")) - assertTrue(bokehShader.contains("float radialScale = mix(1.0, 0.78, fieldStrength)")) - assertFalse(bokehShader.contains("isSharpForeground")) - assertFalse(bokehShader.contains("reconstructionGain")) - assertTrue(analyticHighlightShader.contains("normalizedDistance")) - assertTrue(analyticHighlightShader.contains("highlightOpacity")) - assertTrue(analyticHighlightShader.contains("compressedHighlight")) - assertTrue(analyticHighlightShader.contains("vAperturePosition")) - assertTrue(analyticHighlightShader.contains("vFieldStrength")) - assertTrue(analyticHighlightShader.contains("softInterior")) - assertTrue(analyticHighlightShader.contains("vec3(0.18)")) - assertTrue(analyticHighlightShader.contains("vSignal * (0.55 * transmission)")) - assertTrue(analyticHighlightShader.contains("fwidth(normalizedDistance)")) - assertTrue(analyticHighlightShader.contains("float transparentCore = mix(")) - assertTrue(analyticHighlightShader.contains("float innerGlow = smoothstep(")) - assertTrue(analyticHighlightShader.contains("float rimBody = smoothstep(")) - assertTrue(analyticHighlightShader.contains("float rimPeak = smoothstep(")) - assertTrue(analyticHighlightShader.contains("float ringModulation = clamp(")) + fun compactHighlightsKeepNeighborhoodAndDepthGates() { + val shader = Shaders.COMPACT_BOKEH_HIGHLIGHT_FRAGMENT_SHADER + assertTrue(shader.contains("PROBE_DIRECTIONS[16]")) + assertTrue(shader.contains("if (ringLuma > centerLuma) return -1")) + assertTrue(shader.contains("allRingSamplesAreDarker")) + assertTrue(shader.contains("if (ringResult != 1)")) + assertTrue(shader.contains("brightCoreSampleCount")) + assertTrue(shader.contains("depthCoherenceGate")) + assertTrue(shader.contains("maximumCoreDepthDelta")) + assertTrue(shader.contains("* neighborhoodContrastGate")) + assertTrue(shader.contains("sourceSignal * classifiedHighlight")) } @Test - fun analyticHighlightsUseTheSameFieldDependentBiotarShapeAsBackgroundBokeh() { - val vertexShader = Shaders.ANALYTIC_BOKEH_HIGHLIGHT_VERTEX_SHADER - val fragmentShader = Shaders.ANALYTIC_BOKEH_HIGHLIGHT_FRAGMENT_SHADER - - assertTrue(vertexShader.contains("vec2 field = (aCenterUv * 2.0 - 1.0)")) - assertTrue(vertexShader.contains("vec2 tangential = vec2(-radial.y, radial.x)")) - assertTrue(vertexShader.contains("smoothstep(0.12, 1.15, fieldRadius)")) - assertTrue(vertexShader.contains("float radialScale = mix(1.0, 0.54, fieldStrength)")) - assertTrue(vertexShader.contains("float tangentialScale = mix(1.0, 1.08, fieldStrength)")) - assertTrue(vertexShader.contains("float radialScale = mix(1.0, 0.78, fieldStrength)")) - assertTrue(vertexShader.contains("float tangentialScale = mix(1.0, 1.02, fieldStrength)")) - assertTrue(fragmentShader.contains("smoothstep(0.38, 1.0, normalizedDistance)")) - assertTrue(fragmentShader.contains("float shoulderStrength = mix(0.025, 0.045, vFieldStrength)")) - assertTrue(fragmentShader.contains("transparentCore + innerGlow * 0.12")) - assertTrue(fragmentShader.contains("flat in float vBubblePhase")) - assertTrue(fragmentShader.contains("vec3(0.24)")) - assertTrue(fragmentShader.contains("0.44 * transmission")) - assertTrue(fragmentShader.contains("float sourceTransmission = mix(")) - assertTrue(fragmentShader.contains("float profileVariation = 0.5")) - assertTrue(fragmentShader.contains("vec3(0.93, 1.02, 1.08)")) - assertFalse(fragmentShader.contains("float irregularDistance")) - assertFalse(vertexShader.contains("uniform int uBokehStyle")) - assertFalse(fragmentShader.contains("uniform int uBokehStyle")) - assertTrue( - Shaders.analyticBokehHighlightVertexShader(true) - .contains("#define SOAP_BUBBLE_BOKEH 1") - ) - assertTrue( - Shaders.analyticBokehHighlightFragmentShader(true) - .contains("#define SOAP_BUBBLE_BOKEH 1") - ) - assertFalse(fragmentShader.contains("smoothstep(0.86, 1.0, normalizedDistance)")) + fun defaultHighlightsKeepFieldDependentApertureAndBoundedLdrOutput() { + val vertex = Shaders.ANALYTIC_BOKEH_HIGHLIGHT_VERTEX_SHADER + val fragment = Shaders.ANALYTIC_BOKEH_HIGHLIGHT_FRAGMENT_SHADER + assertTrue(vertex.contains("float radialScale = mix(1.0, 0.54, fieldStrength)")) + assertTrue(vertex.contains("float tangentialScale = mix(1.0, 1.08, fieldStrength)")) + assertTrue(fragment.contains("smoothstep(0.38, 1.0, normalizedDistance)")) + assertTrue(fragment.contains("float shoulderStrength = mix(0.025, 0.045, vFieldStrength)")) + assertTrue(fragment.contains("vec3(0.18)")) + assertTrue(fragment.contains("vSignal * (0.55 * transmission)")) + assertTrue(fragment.contains("vec4(vSignal * transmission, 0.0)")) } @Test - fun bokehRadiusUsesSceneDepthSpanAndApertureScale() { - val shaders = listOf( + fun ordinaryBokehRadiusUsesSceneDepthSpanAndApertureScale() { + listOf( Shaders.COMPACT_BOKEH_HIGHLIGHT_FRAGMENT_SHADER, Shaders.PSF_SPLAT_FRAGMENT_SHADER, Shaders.BOKEH_COMPOSITE_FRAGMENT_SHADER, - ) - - shaders.forEach { shader -> - assertTrue(shader.contains("float availableFocusSpan = max(")) - assertTrue(shader.contains("float normalizedGap = clamp(gap / availableFocusSpan")) - assertTrue(shader.contains("float defocus = pow(normalizedGap, 1.25)")) - assertTrue(shader.contains("float apertureScale = min(1.4 / max(uAperture, 0.7), 1.25)")) - assertTrue(shader.contains("defocus * uMaxBlurRadius * apertureScale")) + ).forEach { shader -> + assertTrue(shader.contains(BokehDefocusModel.GLSL_SOURCE)) } - - val renderer = File( - "src/main/java/com/hinnka/mycamera/processor/OglBokehProcessor.kt" - ).readText() - assertTrue(renderer.contains("originalImage.width.toFloat() / 26.0f")) - assertTrue(renderer.contains("val normalizedGap = (gap / availableFocusSpan)")) - assertTrue(renderer.contains("sourceRadiusPixels * 1.05f")) - assertTrue(renderer.contains("MIN_BUBBLE_ANALYTIC_COC_PIXELS = 10f")) - assertTrue(renderer.contains("BUBBLE_HIGHLIGHT_MIN_CENTER_SPACING_SCALE = 0.82f")) - assertTrue(renderer.contains("val confidenceScale = sqrt(peak.alpha.coerceIn(0.0f, 1.0f))")) - assertTrue(renderer.contains("val sourceExtentScale = sqrt(")) - assertTrue(renderer.contains("val stableLensVariation = 0.84f +")) - assertTrue(renderer.contains("val opticalSizeScale = (")) - assertTrue(renderer.contains("if (bokehStyle == BokehStyle.BUBBLE)")) - assertTrue(renderer.contains("val sourceSignalScale = if (bokehStyle == BokehStyle.BUBBLE)")) - assertTrue(renderer.contains("MIN_BUBBLE_ANALYTIC_COC_PIXELS * 0.38f")) - assertFalse(renderer.contains("Bubble highlights integrated into PSF gather")) - assertTrue(renderer.contains("Natural bokeh uses integrated radial PSF")) - assertTrue(renderer.contains("Bubble bokeh uses integrated optical PSF")) - assertTrue(renderer.contains("soapBubbleStyle = soapBubbleStyle")) - assertTrue(renderer.contains("bokehStyle == BokehStyle.BUBBLE")) - assertTrue(renderer.contains("Analytic bokeh highlights: style=\$bokehStyle")) - assertTrue(renderer.contains("compactBokehHighlightFragmentShader(soapBubbleStyle)")) - assertTrue(renderer.contains("\"uHighlightSourceTexture\"")) - assertTrue(renderer.contains("GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D)")) - assertTrue(renderer.contains("if (bokehStyle == BokehStyle.DEFAULT)")) - assertTrue(renderer.contains("if (bokehStyle != BokehStyle.NATURAL)")) - assertTrue(renderer.contains("val needsCompactHighlights = bokehStyle != BokehStyle.NATURAL")) - assertTrue(renderer.contains("val needsAnalyticOverlay = bokehStyle == BokehStyle.DEFAULT")) - assertFalse(renderer.contains("originalImage.width.toFloat() / 45.0f")) } @Test @@ -374,17 +214,10 @@ class BokehShadersTest { "frag" to Shaders.DEPTH_READBACK_FRAGMENT_SHADER, "frag" to Shaders.BOKEH_LAYER_COLOR_FRAGMENT_SHADER, "frag" to Shaders.COMPACT_BOKEH_HIGHLIGHT_FRAGMENT_SHADER, - "frag" to Shaders.compactBokehHighlightFragmentShader(true), "frag" to Shaders.PSF_SPLAT_FRAGMENT_SHADER, "frag" to Shaders.psfSplatFragmentShader(true), - "frag" to Shaders.psfSplatFragmentShader( - naturalStyle = true, - soapBubbleStyle = true, - ), "vert" to Shaders.ANALYTIC_BOKEH_HIGHLIGHT_VERTEX_SHADER, "frag" to Shaders.ANALYTIC_BOKEH_HIGHLIGHT_FRAGMENT_SHADER, - "vert" to Shaders.analyticBokehHighlightVertexShader(true), - "frag" to Shaders.analyticBokehHighlightFragmentShader(true), "frag" to Shaders.BOKEH_COMPOSITE_FRAGMENT_SHADER, ) shaders.forEachIndexed { index, (stage, shader) -> diff --git a/app/src/test/java/com/hinnka/mycamera/lut/PhysicalBokehShadersTest.kt b/app/src/test/java/com/hinnka/mycamera/lut/PhysicalBokehShadersTest.kt new file mode 100644 index 00000000..6cd92e49 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/lut/PhysicalBokehShadersTest.kt @@ -0,0 +1,102 @@ +package com.hinnka.mycamera.lut + +import java.io.File +import java.util.Properties +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test + +class PhysicalBokehShadersTest { + @Test + fun everyOpticalShaderVariantCompilesWithNdkValidator() { + val localPropertiesSdk = listOf(File("local.properties"), File("../local.properties")) + .firstOrNull(File::isFile) + ?.inputStream() + ?.use { input -> Properties().apply { load(input) }.getProperty("sdk.dir") } + val sdkRoot = System.getenv("ANDROID_SDK_ROOT") + ?: System.getenv("ANDROID_HOME") + ?: localPropertiesSdk + val validator = sdkRoot?.let(::File) + ?.resolve("ndk") + ?.listFiles() + ?.sortedByDescending { it.name } + ?.asSequence() + ?.mapNotNull { ndk -> + ndk.resolve("shader-tools") + .walkTopDown() + .firstOrNull { it.isFile && it.nameWithoutExtension == "glslc" } + } + ?.firstOrNull() + assumeTrue("Android NDK glslc is unavailable", validator != null) + + val transfer = """ + vec3 decodeColor(vec3 encoded) { return encoded; } + vec3 encodeColor(vec3 linear) { return linear; } + """.trimIndent() + // Compile the injected piecewise transfer and its signed extended-range + // form as well as linear RGB. ColorSpace itself needs Android at runtime; + // these functions exercise the same scalar/vector injection contract. + val srgbTransfer = """ + float decodeChannel(float value) { + float x = value; + return x < 0.04045 ? x / 12.92 : pow(max((x + 0.055) / 1.055, 0.0), 2.4); + } + float encodeChannel(float value) { + float x = value; + return x < 0.00313080495356037 ? x * 12.92 : 1.055 * pow(max(x, 0.0), 1.0 / 2.4) - 0.055; + } + vec3 decodeColor(vec3 value) { + return vec3(decodeChannel(value.r), decodeChannel(value.g), decodeChannel(value.b)); + } + vec3 encodeColor(vec3 value) { + return vec3(encodeChannel(value.r), encodeChannel(value.g), encodeChannel(value.b)); + } + """.trimIndent() + val signedSrgbTransfer = srgbTransfer + .replace("float x = value;", "float x = abs(value);") + .replace("return x <", "return sign(value) * (x <") + .replace("2.4);", "2.4));") + .replace("- 0.055;", "- 0.055);") + val shaders = listOf( + "vert" to Shaders.SIMPLE_VERTEX_SHADER, + "frag" to PhysicalBokehShaders.gather, + "frag" to PhysicalBokehShaders.separateEmitters, + "frag" to PhysicalBokehShaders.emitterEnvironment(true), + "frag" to PhysicalBokehShaders.emitterEnvironment(false), + "vert" to PhysicalBokehShaders.emitterVertex, + "frag" to PhysicalBokehShaders.emitterFragment, + "frag" to Shaders.bokehLayerColorFragmentShader(), + ) + listOf(transfer, srgbTransfer, signedSrgbTransfer).flatMap { colorTransfer -> + listOf( + "frag" to PhysicalBokehShaders.composite(colorTransfer), + "frag" to Shaders.bokehLayerColorFragmentShader(colorTransfer), + ) + } + + shaders.forEachIndexed { index, (stage, shader) -> + assertTrue("shader $index must use GLSL ES 3.00", shader.startsWith("#version 300 es")) + val sourceFile = File.createTempFile("offline-optical-$index-", ".$stage") + val outputFile = File.createTempFile("offline-optical-$index-", ".spv") + try { + // glslc's validator copy requires ES 3.10; production remains ES 3.00. + sourceFile.writeText(shader.replaceFirst("#version 300 es", "#version 310 es")) + val process = ProcessBuilder( + checkNotNull(validator).absolutePath, + "--target-env=opengl", + "-fauto-map-locations", + "-fauto-bind-uniforms", + "-fshader-stage=$stage", + sourceFile.absolutePath, + "-o", + outputFile.absolutePath, + ).redirectErrorStream(true).start() + val output = process.inputStream.bufferedReader().use { it.readText() } + assertEquals("shader $index: $output", 0, process.waitFor()) + } finally { + sourceFile.delete() + outputFile.delete() + } + } + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/BokehDefocusModelTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/BokehDefocusModelTest.kt new file mode 100644 index 00000000..fac705c7 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/BokehDefocusModelTest.kt @@ -0,0 +1,73 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class BokehDefocusModelTest { + @Test + fun reportedBackgroundRetainsEstablishedApertureStrength() { + assertEquals(38.807f, BokehDefocusModel.radiusPixels(0.06f, 0.33435f, 1.8f, 4096), 0.002f) + assertEquals(4096f / 26f, BokehDefocusModel.baseRadiusPixels(4096), 0f) + } + + @Test + fun frontAndBackKeepTheirSignAtEqualRelativeDepthSeparation() { + val front = BokehDefocusModel.signedRadiusFraction(0.65, 0.4, 1.8) + val back = BokehDefocusModel.signedRadiusFraction(0.15, 0.4, 1.8) + assertTrue(front > 0.0) + assertTrue(back < 0.0) + assertEquals(front, -back, 1e-15) + } + + @Test + fun focusDeadBandHasNoGeometricDefocus() { + for (depth in listOf(0.0, 0.01, BokehDefocusModel.FOCUS_DEPTH_DEAD_BAND.toDouble())) { + assertEquals(0.0, BokehDefocusModel.signedRadiusFraction(depth, 0.0, 1.8), 0.0) + } + assertTrue(BokehDefocusModel.signedRadiusFraction(0.016, 0.0, 1.8) > 0.0) + assertEquals(0.0, BokehDefocusModel.signedRadiusFraction(0.49, 0.5, 1.8), 0.0) + } + + @Test + fun apertureUsesTheEstablishedWideLimitAndInverseScaling() { + val reference = BokehDefocusModel.signedRadiusFraction(0.1, 0.5, 1.4) + assertEquals(reference * 0.5, BokehDefocusModel.signedRadiusFraction(0.1, 0.5, 2.8), 1e-15) + assertEquals(reference * 1.25, BokehDefocusModel.signedRadiusFraction(0.1, 0.5, 0.5), 1e-15) + assertEquals( + BokehDefocusModel.signedRadiusFraction(0.1, 0.5, 0.5), + BokehDefocusModel.signedRadiusFraction(0.1, 0.5, 1.0), + 0.0, + ) + assertEquals(1.0 / 26.0, BokehDefocusModel.signedRadiusFraction(1.0, 0.0, 1.0), 0.0) + } + + @Test + fun resolutionChangesPixelRadiusWithoutChangingRelativeStrength() { + val radius = BokehDefocusModel.radiusPixels(0.06f, 0.33435f, 1.8f, 4096) + assertEquals(radius / 2f, BokehDefocusModel.radiusPixels(0.06f, 0.33435f, 1.8f, 2048), 0f) + assertEquals(2048f / 26f, BokehDefocusModel.baseRadiusPixels(2048), 0f) + } + + @Test + fun invalidCalibrationInputsAreRejected() { + val invalidCalls = listOf<() -> Unit>( + { BokehDefocusModel.signedRadiusFraction(Double.NaN, 0.5, 1.8) }, + { BokehDefocusModel.signedRadiusFraction(-0.1, 0.5, 1.8) }, + { BokehDefocusModel.signedRadiusFraction(0.5, 1.1, 1.8) }, + { BokehDefocusModel.signedRadiusFraction(0.5, Double.POSITIVE_INFINITY, 1.8) }, + { BokehDefocusModel.signedRadiusFraction(0.5, 0.5, 0.0) }, + { BokehDefocusModel.signedRadiusFraction(0.5, 0.5, Double.NaN) }, + { BokehDefocusModel.radiusPixels(0.1f, 0.5f, 1.8f, 0) }, + { BokehDefocusModel.baseRadiusPixels(-1) }, + ) + for (invalidCall in invalidCalls) { + try { + invalidCall() + throw AssertionError("Invalid calibration input was accepted") + } catch (_: IllegalArgumentException) { + // Expected: invalid depth must not silently acquire a blur scale. + } + } + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalEmitterReconstructionTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalEmitterReconstructionTest.kt new file mode 100644 index 00000000..ae26e677 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalEmitterReconstructionTest.kt @@ -0,0 +1,47 @@ +package com.hinnka.mycamera.processor.optics + +import kotlin.math.exp +import org.junit.Assert.* +import org.junit.Test + +class OpticalEmitterReconstructionTest { + @Test fun neighbouringLightFootprintsBecomeDistinctSourcesWithConservedColorFlux() { + val w=80; val h=60 + val input=FloatArray(w*h*4) + for (y in 0 until h) for (x in 0 until w) { + val light=listOf(25,45).sumOf { cx -> .8*exp(-((x-cx)*(x-cx)+(y-30)*(y-30))/18.0) }.toFloat() + val i=(y*w+x)*4 + input[i]=light; input[i+1]=light*.6f; input[i+2]=light*.2f; input[i+3]=1f + } + val result=OpticalEmitterReconstruction.reconstruct(w,h,input,12f) + assertEquals(2,result.sources.size) + for (channel in 0..2) { + val removed=(0 until w*h).filter { result.ownership[it].toInt()!=0 }.sumOf { input[it*4+channel].toDouble() } + val integrated=result.sources.sumOf { when(channel) { 0->it.red; 1->it.green; else->it.blue }.toDouble() } + assertEquals(removed,integrated,1e-4) + } + val centers=result.sources.sortedBy { it.x } + assertEquals(25.5f,centers[0].x,.15f) + assertEquals(45.5f,centers[1].x,.15f) + } + + @Test fun flatBrightSurfaceAndElongatedLineAreNotPointEmitters() { + for (line in listOf(false,true)) { + val input=FloatArray(48*48*4) { index -> + val x=(index/4)%48 + if (index%4==3) 1f else if (!line || x in 22..25) .8f else 0f + } + assertTrue(OpticalEmitterReconstruction.reconstruct(48,48,input,12f).sources.isEmpty()) + } + } + + @Test fun rejectedTargetDoesNotRemoveAnyOldFootprint() { + val input=FloatArray(32*32*4) { index -> + val x=index/4%32; val y=index/4/32 + if (index%4==3) 1f else .8f*exp(-((x-16)*(x-16)+(y-16)*(y-16))/18f) + } + val result=OpticalEmitterReconstruction.reconstruct(32,32,input,12f,acceptSource={false}) + assertTrue(result.sources.isEmpty()) + assertTrue(result.ownership.all { it.toInt()==0 }) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalFourierTransform.kt b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalFourierTransform.kt new file mode 100644 index 00000000..74da6cfd --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalFourierTransform.kt @@ -0,0 +1,104 @@ +package com.hinnka.mycamera.processor.optics + +import kotlin.math.cos +import kotlin.math.sin + +/** In-place square two-dimensional radix-2 discrete Fourier transform. */ +object OpticalFourierTransform { + /** + * Transforms [real] and [imaginary] in row-major order. + * The forward transform uses exp(-i 2 pi k n / N); the inverse is scaled by 1/N. + */ + fun transform2D( + real: DoubleArray, + imaginary: DoubleArray, + size: Int, + inverse: Boolean = false, + ) { + require(size > 0 && size and (size - 1) == 0) { + "FFT size must be a positive power of two" + } + val elementCount = size.toLong() * size + require(elementCount <= Int.MAX_VALUE) { "FFT size is too large" } + require(real.size == elementCount.toInt() && imaginary.size == elementCount.toInt()) { + "FFT arrays must each contain size * size elements" + } + + for (row in 0 until size) { + transform1D(real, imaginary, row * size, 1, size, inverse) + } + for (column in 0 until size) { + transform1D(real, imaginary, column, size, size, inverse) + } + } + + private fun transform1D( + real: DoubleArray, + imaginary: DoubleArray, + offset: Int, + stride: Int, + length: Int, + inverse: Boolean, + ) { + var j = 0 + for (i in 1 until length) { + var bit = length shr 1 + while (j and bit != 0) { + j = j xor bit + bit = bit shr 1 + } + j = j xor bit + if (i < j) { + val first = offset + i * stride + val second = offset + j * stride + val realValue = real[first] + real[first] = real[second] + real[second] = realValue + val imaginaryValue = imaginary[first] + imaginary[first] = imaginary[second] + imaginary[second] = imaginaryValue + } + } + + var blockLength = 2 + val sign = if (inverse) 1.0 else -1.0 + while (blockLength <= length) { + val angle = sign * 2.0 * Math.PI / blockLength + val stepReal = cos(angle) + val stepImaginary = sin(angle) + var blockStart = 0 + while (blockStart < length) { + var twiddleReal = 1.0 + var twiddleImaginary = 0.0 + val halfBlock = blockLength shr 1 + for (offsetInBlock in 0 until halfBlock) { + val first = offset + (blockStart + offsetInBlock) * stride + val second = offset + (blockStart + offsetInBlock + halfBlock) * stride + val productReal = twiddleReal * real[second] - twiddleImaginary * imaginary[second] + val productImaginary = twiddleReal * imaginary[second] + twiddleImaginary * real[second] + val firstReal = real[first] + val firstImaginary = imaginary[first] + real[first] = firstReal + productReal + imaginary[first] = firstImaginary + productImaginary + real[second] = firstReal - productReal + imaginary[second] = firstImaginary - productImaginary + + val nextTwiddleReal = twiddleReal * stepReal - twiddleImaginary * stepImaginary + twiddleImaginary = twiddleReal * stepImaginary + twiddleImaginary * stepReal + twiddleReal = nextTwiddleReal + } + blockStart += blockLength + } + blockLength = blockLength shl 1 + } + + if (inverse) { + val scale = 1.0 / length + for (index in 0 until length) { + val position = offset + index * stride + real[position] *= scale + imaginary[position] *= scale + } + } + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalFourierTransformTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalFourierTransformTest.kt new file mode 100644 index 00000000..bca06ef2 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalFourierTransformTest.kt @@ -0,0 +1,90 @@ +package com.hinnka.mycamera.processor.optics + +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.sin +import org.junit.Assert.assertEquals +import org.junit.Test + +class OpticalFourierTransformTest { + @Test + fun transformMatchesBruteForceDft() { + val size = 2 + val real = doubleArrayOf(1.0, 2.0, 3.0, 4.0) + val imaginary = doubleArrayOf(0.5, -1.0, 2.0, -0.25) + val expected = bruteForce(real, imaginary, size, inverse = false) + + OpticalFourierTransform.transform2D(real, imaginary, size) + + expected.first.indices.forEach { index -> + assertEquals(expected.first[index], real[index], EPSILON) + assertEquals(expected.second[index], imaginary[index], EPSILON) + } + } + + @Test + fun forwardAndInverseRoundTripComplexInput() { + val originalReal = DoubleArray(16) { index -> (index * 3 - 5) / 7.0 } + val originalImaginary = DoubleArray(16) { index -> (index * index - 4) / 11.0 } + val real = originalReal.copyOf() + val imaginary = originalImaginary.copyOf() + + OpticalFourierTransform.transform2D(real, imaginary, 4) + OpticalFourierTransform.transform2D(real, imaginary, 4, inverse = true) + + originalReal.indices.forEach { index -> + assertEquals(originalReal[index], real[index], EPSILON) + assertEquals(originalImaginary[index], imaginary[index], EPSILON) + } + } + + @Test + fun forwardTransformSatisfiesParsevalEnergy() { + val real = DoubleArray(16) { index -> (index + 1) / 5.0 } + val imaginary = DoubleArray(16) { index -> (index - 3) / 9.0 } + val inputEnergy = energy(real, imaginary) + + OpticalFourierTransform.transform2D(real, imaginary, 4) + + assertEquals(16.0 * inputEnergy, energy(real, imaginary), 1e-9) + } + + private fun bruteForce( + real: DoubleArray, + imaginary: DoubleArray, + size: Int, + inverse: Boolean, + ): Pair { + val outputReal = DoubleArray(real.size) + val outputImaginary = DoubleArray(real.size) + val sign = if (inverse) 1.0 else -1.0 + for (ky in 0 until size) { + for (kx in 0 until size) { + var sumReal = 0.0 + var sumImaginary = 0.0 + for (y in 0 until size) { + for (x in 0 until size) { + val angle = sign * 2.0 * PI * (kx * x + ky * y) / size + val index = y * size + x + val c = cos(angle) + val s = sin(angle) + sumReal += real[index] * c - imaginary[index] * s + sumImaginary += real[index] * s + imaginary[index] * c + } + } + val outputIndex = ky * size + kx + val scale = if (inverse) 1.0 / (size * size) else 1.0 + outputReal[outputIndex] = sumReal * scale + outputImaginary[outputIndex] = sumImaginary * scale + } + } + return outputReal to outputImaginary + } + + private fun energy(real: DoubleArray, imaginary: DoubleArray): Double = + real.indices.sumOf { index -> real[index] * real[index] + imaginary[index] * imaginary[index] } + + private companion object { + const val EPSILON = 1e-10 + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalLensPhysicsTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalLensPhysicsTest.kt new file mode 100644 index 00000000..bae3f394 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalLensPhysicsTest.kt @@ -0,0 +1,194 @@ +package com.hinnka.mycamera.processor.optics + +import com.hinnka.mycamera.processor.BokehDefocusModel + +import kotlin.math.abs +import kotlin.math.pow +import kotlin.math.sqrt +import kotlin.math.exp +import kotlin.math.cos +import kotlin.math.PI +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class OpticalLensPhysicsTest { + @Test + fun emitterLensUsesTheSameSceneWithoutChangingDiffuseDefocus() { + val diffuse = OpticalLensProfile.SOAP_BUBBLE.atAperture(1.8, 4096) + val emitter = OpticalLensProfile.SOAP_BUBBLE_EMITTER.atAperture(1.8, 4096) + val scene = OpticalSceneCalibration(.33435, OpticalLensProfile.SOAP_BUBBLE) + val delta = scene.inverseDepthDifference(.06, diffuse) + assertEquals(delta, scene.inverseDepthDifference(.06, emitter), 1e-12) + assertEquals(35.4742, diffuse.supportRadiusPixels(delta), .001) + assertTrue("Only the separated emitter reaches the large caustic", emitter.supportRadiusPixels(delta) in 70.0..80.0) + val rho = .63 + val step = 1e-6 + val derivative = (emitter.opticalPathMeters(rho + step, delta) - + emitter.opticalPathMeters(rho - step, delta)) / (2 * step) + assertEquals(derivative * emitter.imageDistanceMeters / (emitter.pupilRadiusMeters * emitter.pixelPitchMeters), + emitter.signedRayRadiusPixels(rho, delta), 1e-8) + } + + @Test + fun everyStyleSharesTheSameDefocusBeforePupilAberration() { + for (aperture in listOf(1.0, 1.4, 1.8, 2.8, 8.0, 16.0)) { + val lens = OpticalLensProfile.SOAP_BUBBLE.atAperture(aperture, 4096) + for (focus in listOf(0.0, .33435, .5, 1.0)) { + val calibration = OpticalSceneCalibration(focus) + for (depth in listOf(0.0, .06, .2, .3, focus, .7, 1.0)) { + val delta = calibration.inverseDepthDifference(depth, lens) + val expected = BokehDefocusModel.signedRadiusFraction(depth, focus, aperture) * 4096 + assertEquals(expected, lens.defocusPixelsPerDiopter * delta, 1e-10) + // The ray's signed defocus component is the common CoC at + // every pupil coordinate, not a resized output kernel. + val rho = .73 + val defocusRay = lens.signedRayRadiusPixels(rho, delta) - lens.signedRayRadiusPixels(rho, 0.0) + assertEquals(expected * rho, defocusRay, 1e-10) + } + } + } + } + + @Test + fun rayRadiusMatchesFiniteDifferenceOfOpticalPath() { + val lens = OpticalLensProfile.SOAP_BUBBLE.atAperture(2.8, 4000) + val rho = 0.63 + val delta = 0.21 + val step = 1e-6 + val derivative = (lens.opticalPathMeters(rho + step, delta) - + lens.opticalPathMeters(rho - step, delta)) / (2.0 * step) + val expectedPixels = derivative * lens.imageDistanceMeters / + (lens.pupilRadiusMeters * lens.pixelPitchMeters) + + assertEquals(expectedPixels, lens.signedRayRadiusPixels(rho, delta), 1e-8) + } + + @Test + fun stoppingDownScalesDefocusAndFixedPhysicalAberrationByTheirOrders() { + val wide = OpticalLensProfile.SOAP_BUBBLE.atAperture(1.4, 4000) + val stopped = OpticalLensProfile.SOAP_BUBBLE.atAperture(2.8, 4000) + + assertEquals(wide.defocusPixelsPerDiopter / 2.0, stopped.defocusPixelsPerDiopter, 1e-12) + assertEquals(wide.sphericalRayPixels / 2.0.pow(wide.profile.sphericalOrder - 1), stopped.sphericalRayPixels, 1e-12) + } + + @Test + fun signedFrontAndBackDefocusDifferForTheSameLens() { + val lens = OpticalLensProfile.SOAP_BUBBLE.atAperture(2.0, 4000) + + assertTrue(abs(lens.signedRayRadiusPixels(0.7, 0.3)) != abs(lens.signedRayRadiusPixels(0.7, -0.3))) + } + + @Test + fun marginalRayStationarityConcentratesEnergyAtTheRim() { + val lens = OpticalLensProfile.SOAP_BUBBLE.atAperture(1.4, 2560) + val order = lens.profile.sphericalOrder + val delta = (-(order - 1) * lens.sphericalRayPixels - lens.focusRayPixels) / lens.defocusPixelsPerDiopter + val radius = (order - 2) * lens.sphericalRayPixels + assertEquals(radius, lens.supportRadiusPixels(delta), 1e-10) + val bins = PupilPropagator.geometricalRadialEnergy(lens, delta, radius / 100.0) + // Divide annular energy by its area before comparing irradiance. The + // outer 1% of the radius has a greater area but also a greater density. + val innerDensity = bins[0] + val outerDensity = bins[99] / (100.0 * 100.0 - 99.0 * 99.0) + assertTrue(outerDensity > innerDensity * 3.0) + assertEquals(1.0, bins.sum(), 1e-10) + } + + @Test + fun supportIncludesInternalCriticalRadius() { + val lens = OpticalLensProfile.SOAP_BUBBLE.atAperture(1.4, 4000) + val delta = (-(lens.profile.sphericalOrder - 2) * lens.sphericalRayPixels - lens.focusRayPixels) / + lens.defocusPixelsPerDiopter + val endpoint = abs(lens.signedRayRadiusPixels(1.0, delta)) + val criticalPower = -(lens.defocusPixelsPerDiopter * delta + lens.focusRayPixels) / + ((lens.profile.sphericalOrder - 1) * lens.sphericalRayPixels) + assertTrue(criticalPower in 0.0..1.0) + assertTrue(lens.supportRadiusPixels(delta) > endpoint) + } + + @Test + fun geometricalRadialEnergyConservesAndIdealDiscHasAreaDistribution() { + val profile = OpticalLensProfile( + id = "ideal", + focalLengthMeters = 0.05, + sensorLongEdgeMeters = 0.036, + referenceFNumber = 2.0, + referenceSphericalOpdMeters = 0.0, + nominalFocusMeters = 2.0, + ) + val lens = profile.atAperture(2.0, 4000) + val delta = 0.4 + val scale = abs(lens.defocusPixelsPerDiopter * delta + lens.focusRayPixels) + val energy = PupilPropagator.geometricalRadialEnergy(lens, delta, scale / 4.0, 200_000) + + assertEquals(1.0, energy.sum(), 1e-12) + assertEquals(1.0 / 16.0, energy[0], 0.002) + assertEquals(3.0 / 16.0, energy[1], 0.002) + assertEquals(5.0 / 16.0, energy[2], 0.002) + assertEquals(7.0 / 16.0, energy[3], 0.002) + } + + @Test + fun idealCircularPupilHasUnitEnergyAndAiryFirstZeroEncircledEnergy() { + val profile = OpticalLensProfile( + id = "ideal-diffraction", + focalLengthMeters = 0.05, + sensorLongEdgeMeters = 0.036, + referenceFNumber = 2.0, + referenceSphericalOpdMeters = 0.0, + nominalFocusMeters = 2.0, + ) + val lens = profile.atAperture(2.0, 4000) + val wavelength = 550e-9 + val psf = PupilPropagator.propagate(lens, 0.0, wavelength, 128, 2) + val firstZeroMeters = 1.22 * wavelength * lens.imageDistanceMeters / + (2.0 * lens.pupilRadiusMeters) + + assertEquals(1.0, psf.energy.sum(), 1e-12) + assertEquals(0.838, psf.energyWithinRadius(firstZeroMeters), 0.03) + } + + @Test + fun undersampledPupilPhaseIsRejected() { + val lens = OpticalLensProfile.SOAP_BUBBLE.atAperture(1.4, 4000) + + try { + PupilPropagator.propagate(lens, 1.0, pupilDiameterSamples = 16, padding = 2) + throw AssertionError("Expected undersampled pupil phase to be rejected") + } catch (_: IllegalArgumentException) { + // Expected validation failure. + } + } + + @Test + fun finiteHighlightsRetainARimWithoutLosingTheFocusedCore() { + val lens = OpticalLensProfile.SOAP_BUBBLE.atAperture(1.8, 4096) + val delta = OpticalSceneCalibration(0.33435).inverseDepthDifference(0.06, lens) + // At the shared defocus scale, compact (sigma=8 px) highlights can + // retain a rim. Broad, pre-blurred highlights are not enlarged to force one. + val radius = lens.supportRadiusPixels(delta) + fun irradiance(at: Double): Double { + var sum = 0.0 + repeat(2048) { radial -> + val r = lens.signedRayRadiusPixels(sqrt((radial + 0.5) / 2048), delta) + repeat(128) { angular -> + val theta = 2 * PI * (angular + 0.5) / 128 + sum += exp(-(at * at + r * r - 2 * at * r * cos(theta)) / (2 * 8.0 * 8.0)) + } + } + return sum / (2048 * 128) + } + val peak = (20..40).maxOf { irradiance(radius * it / 40.0) } + assertTrue(peak > irradiance(0.0) * 1.25) + val focusedRadii = DoubleArray(65536) { i -> + abs(lens.signedRayRadiusPixels(sqrt((i + 0.5) / 65536), 0.0)) + }.sortedArray() + // This phase plate retains residual spherical aberration at its minimum-RMS + // focus: stronger background rims cost focused optical concentration. The + // shared subject compositor preserves protected detail independently; it + // does not imply that this lens's own focused PSF is a delta function. + assertTrue("80% of focused ray energy remains within 2.2 px", focusedRadii[(focusedRadii.size * .8).toInt()] < 2.2) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalPsfTableTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalPsfTableTest.kt new file mode 100644 index 00000000..30b7df33 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/optics/OpticalPsfTableTest.kt @@ -0,0 +1,139 @@ +package com.hinnka.mycamera.processor.optics + +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.exp +import kotlin.math.sqrt +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class OpticalPsfTableTest { + @Test + fun emitterTableTransportsUnitEnergyOverTheLargerOpticalSupport() { + val diffuse = table() + val emitter = OpticalPsfTable.build(OpticalLensProfile.SOAP_BUBBLE_EMITTER, + 1.8f, .33435f, 4096, 1280, sceneReferenceProfile = OpticalLensProfile.SOAP_BUBBLE) + assertTrue(emitter.supportAt(.06f) > diffuse.supportAt(.06f) * 2f) + for (depth in listOf(0f, .06f, .33435f, .7f, 1f)) { + var energy = 0.0 + repeat(emitter.radialBinCount) { bin -> + val radius = (bin + .5f) * emitter.binWidthPixels + val density = emitter.densityAt(depth, radius) + energy += density * annularArea(emitter, bin) + if (radius >= emitter.supportAt(depth)) assertEquals(0f, density, 0f) + } + assertEquals(1.0, energy, 1e-6) + assertEquals(1f, emitter.cumulativeEnergyAt(depth, emitter.tableSupportPixels), 0f) + } + } + + private fun table(profile: OpticalLensProfile = OpticalLensProfile.SOAP_BUBBLE) = + OpticalPsfTable.build(profile, 1.8f, 0.33435f, 4096, 1280) + + private fun annularArea(table: OpticalPsfTable, bin: Int): Double = + PI * table.binWidthPixels * table.binWidthPixels * (2.0 * bin + 1) + + @Test + fun allDepthRowsAndTheirInterpolationsConservePupilEnergy() { + val table = table() + repeat(table.depthCount) { row -> + val energy = (0 until table.radialBinCount).sumOf { bin -> + table.densities[row * table.radialBinCount + bin] * annularArea(table, bin) + } + assertEquals("row $row", 1.0, energy, 1e-6) + } + for (depth in listOf(0f, .06f, .33435f, .7f, 1f)) { + val energy = (0 until table.radialBinCount).sumOf { bin -> + table.densityAt(depth, (bin + .5f) * table.binWidthPixels) * annularArea(table, bin) + } + assertEquals("interpolated depth $depth", 1.0, energy, 1e-6) + assertEquals(0f, table.densityAt(depth, table.tableSupportPixels), 0f) + } + } + + @Test + fun frontFocusAndBackSupportBoundTransportedEnergy() { + val table = table() + for (depth in listOf(0f, .06f, .33435f, .7f, 1f)) { + val bound = table.supportAt(depth) + assertTrue(bound <= table.tableSupportPixels + 1e-4) + repeat(table.radialBinCount) { bin -> + val radius = (bin + .5f) * table.binWidthPixels + if (radius >= bound) assertEquals(0f, table.densityAt(depth, radius), 0f) + } + } + val near = table.lens.supportRadiusPixels(.1) + val far = table.lens.supportRadiusPixels(-.1) + assertTrue("The phase plate distinguishes front and rear defocus", near != far) + assertTrue(table.supportAt(.33435f) < table.supportAt(.06f)) + } + + @Test + fun cumulativeEnergyMatchesFiniteAnnularDensityAcrossDepths() { + val table = table() + for (depth in listOf(0f, .06f, .33435f, .7f, 1f)) { + var integrated = 0.0 + assertEquals(0f, table.cumulativeEnergyAt(depth, 0f), 0f) + repeat(table.radialBinCount) { bin -> + val inner = bin * table.binWidthPixels.toDouble() + val outer = inner + table.binWidthPixels + // Half of this annulus's area lies below its RMS edge radius. + val midpoint = sqrt((inner * inner + outer * outer) * .5).toFloat() + val density = table.densityAt(depth, midpoint) + val energy = density * annularArea(table, bin) + assertEquals(integrated + energy * .5, table.cumulativeEnergyAt(depth, midpoint).toDouble(), 2e-6) + integrated += energy + } + assertEquals(1f, table.cumulativeEnergyAt(depth, table.tableSupportPixels), 0f) + } + } + + @Test + fun idealPupilGivesUniformDiscAndFiniteFocusedCell() { + val ideal = OpticalLensProfile.SOAP_BUBBLE.copy(referenceSphericalOpdMeters = 0.0) + val table = table(ideal) + val delta = table.calibration.inverseDepthDifference(0.0, table.lens) + val radius = table.lens.supportRadiusPixels(delta) + val expected = 1.0 / (PI * radius * radius) + // Interior annuli have the same irradiance. Skip the unresolved axis and + // the partially occupied outermost annulus, whose averages differ. + for (fraction in listOf(.2f, .4f, .6f, .8f)) { + assertEquals(expected, table.densityAt(0f, radius.toFloat() * fraction).toDouble(), expected * .015) + } + val exactlyFocused = OpticalPsfTable.build(ideal, 1.8f, .5f, 4096, 1280) + val focusedDensity = exactlyFocused.densityAt(.5f, 0f) + assertTrue(focusedDensity.isFinite()) + assertEquals(1.0, focusedDensity * annularArea(exactlyFocused, 0), 1e-6) + } + + @Test + fun compactHighlightRetainsARimWithoutEnlargingBroadHighlights() { + val table = table() + val depth = .06f + // Preserve compact highlights at the common scene scale; a broad source + // must remain broad rather than acquire an artificially enlarged ring. + fun irradiance(at: Double, sigma: Double = 8.0): Double { + var sum = 0.0 + repeat(table.radialBinCount) { bin -> + val density = table.densityAt(depth, (bin + .5f) * table.binWidthPixels) + if (density > 0f) { + val inner = bin * table.binWidthPixels.toDouble() + val outer = inner + table.binWidthPixels + val radius = sqrt((inner * inner + outer * outer) / 2) + var angular = 0.0 + repeat(128) { angle -> + val theta = 2 * PI * (angle + .5) / 128 + angular += exp(-(at * at + radius * radius - 2 * at * radius * cos(theta)) / (2.0 * sigma * sigma)) + } + sum += density * annularArea(table, bin) * angular / 128 + } + } + return sum + } + val peak = (10..40).maxOf { irradiance(it.toDouble()) } + assertTrue("A finite input highlight still has a brighter rim", peak > irradiance(0.0) * 1.25) + val broadPeak = (0..50).maxOf { irradiance(it.toDouble(), 16.0) } + assertTrue("Broad source must not force extra defocus", broadPeak <= irradiance(0.0, 16.0) * 1.05) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/optics/PupilPropagator.kt b/app/src/test/java/com/hinnka/mycamera/processor/optics/PupilPropagator.kt new file mode 100644 index 00000000..2fa23d48 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/optics/PupilPropagator.kt @@ -0,0 +1,97 @@ +package com.hinnka.mycamera.processor.optics + +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.max +import kotlin.math.sin +import kotlin.math.sqrt + +/** Test-only double-precision propagation reference for the production optical model. */ +object PupilPropagator { + data class Psf( + val size: Int, + val pixelSpacingMeters: Double, + /** Integrated energy per Fourier sample, fft-shifted, with unit sum. */ + val energy: DoubleArray, + val pupilSampleCount: Int, + val maximumPhaseStepRadians: Double, + ) { + fun energyWithinRadius(radiusMeters: Double): Double { + var sum = 0.0 + val limit2 = radiusMeters * radiusMeters / (pixelSpacingMeters * pixelSpacingMeters) + for (y in 0 until size) for (x in 0 until size) { + val dx = x - size / 2 + val dy = y - size / 2 + if (dx.toDouble() * dx + dy.toDouble() * dy <= limit2) sum += energy[y * size + x] + } + return sum + } + } + + fun propagate( + lens: OpticalLensState, + inverseDepthDifference: Double, + wavelengthMeters: Double = 550e-9, + pupilDiameterSamples: Int = 128, + padding: Int = 2, + ): Psf { + require(inverseDepthDifference.isFinite()) + require(wavelengthMeters.isFinite() && wavelengthMeters > 0.0) + require(pupilDiameterSamples >= 16 && pupilDiameterSamples.countOneBits() == 1) + require(padding >= 2 && padding.countOneBits() == 1) + val sizeLong = pupilDiameterSamples.toLong() * padding + require(sizeLong <= 4096) { "Diffraction reference exceeds its declared memory budget" } + val size = sizeLong.toInt() + val pupilStep = 2.0 * lens.pupilRadiusMeters / pupilDiameterSamples + // Bound the phase gradient using the ray displacement (x = v grad W). + val maxGradient = lens.supportRadiusPixels(inverseDepthDifference) * + lens.pixelPitchMeters / lens.imageDistanceMeters + val phaseStep = 2.0 * PI * maxGradient * pupilStep / wavelengthMeters + require(phaseStep <= PI / 2.0) { + "Undersampled pupil phase: step=$phaseStep radians; increase pupilDiameterSamples" + } + val real = DoubleArray(size * size) + val imaginary = DoubleArray(size * size) + var pupilSamples = 0 + for (y in 0 until size) for (x in 0 until size) { + val ux = (x - size / 2 + 0.5) * 2.0 / pupilDiameterSamples + val uy = (y - size / 2 + 0.5) * 2.0 / pupilDiameterSamples + val rho2 = ux * ux + uy * uy + if (rho2 <= 1.0) { + val phase = lens.phaseRadians(sqrt(rho2), inverseDepthDifference, wavelengthMeters) + real[y * size + x] = cos(phase) + imaginary[y * size + x] = sin(phase) + pupilSamples++ + } + } + OpticalFourierTransform.transform2D(real, imaginary, size) + // Parseval supplies the absolute discrete normalization. No peak or rim normalization. + val totalEnergy = size.toDouble() * size * pupilSamples + val energy = DoubleArray(size * size) + for (y in 0 until size) for (x in 0 until size) { + val source = ((y + size / 2) % size) * size + (x + size / 2) % size + energy[y * size + x] = (real[source] * real[source] + imaginary[source] * imaginary[source]) / totalEnergy + } + check(abs(energy.sum() - 1.0) < 1e-8) { "Diffraction energy conservation failed" } + return Psf(size, wavelengthMeters * lens.imageDistanceMeters / (size * pupilStep), energy, pupilSamples, phaseStep) + } + + /** Reference energy histogram. Bin finite pupil energy, never divide by a singular Jacobian. */ + fun geometricalRadialEnergy( + lens: OpticalLensState, + inverseDepthDifference: Double, + binWidthPixels: Double, + sampleCount: Int = 262144, + ): DoubleArray { + require(binWidthPixels.isFinite() && binWidthPixels > 0.0 && sampleCount > 0) + val bins = max(1, kotlin.math.ceil(lens.supportRadiusPixels(inverseDepthDifference) / binWidthPixels).toInt() + 1) + val energy = DoubleArray(bins) + for (i in 0 until sampleCount) { + val rho = sqrt((i + 0.5) / sampleCount) + val radius = abs(lens.signedRayRadiusPixels(rho, inverseDepthDifference)) + energy[(radius / binWidthPixels).toInt()] += 1.0 / sampleCount + } + return energy + } +} diff --git a/docs/optical-soap-bubble-bokeh-design.md b/docs/optical-soap-bubble-bokeh-design.md new file mode 100644 index 00000000..13ed3eab --- /dev/null +++ b/docs/optical-soap-bubble-bokeh-design.md @@ -0,0 +1,235 @@ +# 泡泡焦:光学核与共享虚化管线 + +## 范围与实现状态 + +用户要求泡泡光斑由光学原理形成,并明确允许其余虚化算法参考和复用已有实现。因此,生产入口仍为 `OglBokehProcessor.applyBokeh`:复用深度极性解析、U2NetP 主体保护、RGB 引导的分层深度、预乘颜色重建、工作分辨率渲染、原分辨率输出。仅 BUBBLE 使用独立计算的光学 PSF,DEFAULT / NATURAL 保持原风格路径。持久化名称不变。 + +**主体保护和高光/背景分离是计算摄影的合成选择;两个光斑核分别是声明的虚拟镜头的几何光学结果。** 整张输出不能宣称来自同一枚真实镜头或精确的逐瞳孔遮挡积分。主体开启保护时,其清晰度来自共享的主体合成,而不是声称有强球差的镜头在合焦处仍然无像差。 + +旧泡泡焦的拟合亮边、高光增益、尺寸修正及独立逐瞳孔渲染器已删除。生产目录只保留 OpticalLensProfile、OpticalSceneCalibration、OpticalPsfTable 和 OpticalColorTransfer,以及共享管线使用的 PhysicalBokehShaders。PupilPropagator / OpticalFourierTransform 已移到 src/test,仅作为数值测试基准,不随应用打包。当前生产 PSF 采用几何近似,尚不模拟衍射、光谱色差、镜筒口径蚀、场依赖像差。 + +## 1. 弥散圆为什么形成 + +理想近轴透镜满足 `1/f = 1/z + 1/v`。传感器固定于对焦距离 `z_f` 的像面 `v_f` 时,其他物距的光束未在传感器上收束到一点,传感器截得一个光锥截面。入瞳半径 `a=f/(2N)` 时,其几何半径为: + +``` +c = a |1 - v_f/v(z)| = a v_f |1/z - 1/z_f| +``` + +除以像素间距 `p` 得到像素半径。均匀透射的理想圆孔在大离焦极限下产生均匀实心盘,**理想圆孔本身不会自动产生亮边**。光源不是数学点时,其成像是光源形状与 PSF 的积分,宽亮片和已经虚化的亮点会填平光斑中心。 + +波动光学以复瞳函数 `P = T exp(i 2πW/λ)` 定义像面振幅,PSF 为传播后振幅的模平方。不同非相干光源的强度相加。基础关系可核对 [爱丁堡大学 Operation of a Simple Lens](https://www2.ph.ed.ac.uk/~wjh/teaching/mo/psf.pdf),本文的瞳面模型、符号、数值核与工程实现独立建立,不参考现有泡泡焦实现。 + +## 2. 从瞳面光程到亮环 + +采用理想近轴聚焦系统与固定径向薄相位元件,残余光程为偶次幂: + +``` +a = f/(2N) +S = c_n a^n +W(ρ, Δq) = [a² Δq/2 + D_focus] ρ² + S ρ^n +0 ≤ ρ ≤ 1, Δq = 1/z - 1/z_f +``` + +`c_n` 固定,收光圈只改变被使用的实际瞳孔范围。这可对应厚度变化为 `r^n` 的薄折射相位片,不把参数解释为参考照片某支真实镜头的反求处方。 + +几何光线横向位移由光程梯度确定。以带符号的径向像素坐标表示: + +``` +r(ρ) = v/(a p) ∂W/∂ρ = Aρ + Bρ^(n-1) +A = (a v/p) Δq + A0 +A0 = 2v D_focus/(a p) +B = n v S/(a p) +``` + +最小化均匀瞳孔下的几何 RMS 光线半径 `∫r(ρ)² 2ρ dρ`,得到: + +``` +A0 = -4B/(n+2) +D_focus = -2nS/(n+2) +``` + +这定义每次调整光圈后的几何最佳焦点;它不等同于最佳 Strehl 焦点。改变球差必须同时改变合焦核、焦前核、焦后核,不能只改背景环宽。 + +均匀瞳孔中 `dE = 2ρ dρ`。映射到半径 `R=|r|` 的像面环带 `dArea=2πR dR` 后,各个原像分支的面积密度相加: + +``` +PSF(R) = Σ ρ / [π R |dr/dρ|] +``` + +当 `dr/dρ = A+(n-1)Bρ^(n-2)` 接近零,宽瞳孔环带被压缩到窄像面环带,形成焦散和亮边。穿轴光线保留能量,在相反方位到达 `|r|`,不能裁成零半径。焦前与焦后的 `A` 符号不同,PSF 因而不对称。 + +几何焦散处公式会发散,所以程序不直接除零或截断峰值,而将有限瞳孔面积投到有限像面环带;每个环带存真实光能和面积。波动传播及像素面积在现实中也会限制无限峰值。 + +## 3. 参考图与参数选择 + +参考图可见:局部亮点具有较亮边缘和非零内部;高光重叠自然相加;较大亮区不应自动拆成小圆;主体清晰;部分离轴光斑略有形变。当前模型覆盖径向明暗、尺寸、有限光源、叠加及焦前后差异,未实现离轴猫眼与色边,不能用任意椭圆或 RGB 偏移冒充这些光学现象。 + +报告问题的猫照片本身已经具有较宽背景亮点。在 `4096` 长边、`f/1.8`、焦点视差 `.33435`、背景视差 `.06` 下,旧 75 mm 配置的支持半径约 22 px,与原图亮点宽度接近,额外卷积后很难保留亮环。 + +普通背景的固定虚拟镜头选择 `phase-plate-135mm-order4-balanced`: + +| 参数 | 数值 | +| --- | --- | +| 焦距 / 虚拟像面长边 | 135 mm / 36 mm | +| 名义对焦距离 | 2 m | +| 参考光圈 | f/1.8 | +| 径向光程阶数 | 4 | +| 参考瞳孔边缘残余光程 S | 5.6915283203125 μm | +| 4096 长边参考 A0 / B | −6.6667 px / 10 px | +| 逆物距差到像素的系数 | 617.6944 px / m⁻¹ | + +归一化视差通过共享 BokehDefocusModel 标定为带符号的基础离焦半径 C,再由 Δq=C/(av/p) 得到光程中的二次离焦项。它复用自然、旋焦的焦点死区、归一化深度跨度和计算光圈响应;不是实测米制深度,也不是固定的 .5 m⁻¹/disparity。焦点与计算光圈的界面标定会影响这个虚拟 Δq,不能将其宣称为固定真实场景的逆距离。三种风格使用相同基础离焦量,泡泡的球差能量由固定相位片另行决定。 + +对背景视差 `.06`、焦点 `.33435`、4096 长边及 f/1.8,共享基础离焦半径为 38.8075 px,普通背景 PSF 支持半径为 35.4742 px(此前 71.5549 px)。四阶模型在最小 RMS 焦点附近满足 RMS²=C²/2+B²/36,基础离焦与残余球差不再通过一个风格独有的全局深度比例混在一起。对 σ=8 px 的紧凑光源仍可保留亮环;σ=16 px 的宽光源在这个较小尺度下可能无明显亮环,因此局部高光能量进入下面声明的独立传播路径。 + +该镜头在 f/1.8 合焦 E80 半径约 2.07 px、支持半径 3.33 px(4096 长边)。收放光圈仍按实际瞳孔改变固定相位片的球差,不能保证不同核的视觉锐度完全相同。共享 CoC 决定焦点附近的原图合成权重,PSF 支持半径只负责积分范围;不能把含残余球差的支持半径用作离焦强度。参考图无法唯一确定镜头、绝对深度或丢失的 HDR 信息。 + +### 大尺度高光与当前背景强度共存 + +同一深度的一枚真实线性镜头不能只给亮点一个大 PSF、同时给其余纹理一个小 PSF。为满足保留当前背景强度且恢复大泡泡的目标,显式采用双路径计算摄影: + +``` +L = 预乘背景线性 RGB +E = 受局部背景、亮点证据、离焦和覆盖率限制的正高光能量,0 ≤ E ≤ L +R = L - E +E_remaining = E 中未被可靠识别为紧凑光源的部分 +F_i = 第 i 个已识别光斑的线性 RGB 积分 +输出背景 = Gather(K_background, R) + Gather(K_emitter, E_remaining) + + Σ F_i K_emitter(x - center_i, depth_i) +``` + +两个 gather 输入均保留原有效覆盖率作为归一化支持,不能把 E 的亮度当作 alpha,否则求积会重新放大稀疏高光。R 在 gather 内用相同坐标、相同 LOD 从 L 扣除完整 E;mipmap 的线性使这一步保持分解关系。已识别像素从 E_remaining 中移除,其 RGB 积分只进入新光源一次。两个 PSF 行都具有单位能量,不复制光源、不补 HDR、不附加峰值增益。 + +`OpticalEmitterReconstruction` 在工作分辨率上识别已有光斑:轻度平滑仅用于寻找局部峰值,沿亮度上升方向划分相邻光源;颜色积分始终读取未经平滑的 E。以亮度加权质心定位,协方差、区域填充率、尺寸、深度一致性和画框完整性判定紧凑性。目标 PSF 支持半径必须大于观测等效半径的 1.2 倍,才接收重建。所有权掩码与光通量积分使用同一批像素,拒绝的候选保持原路径。 + +这一步假设可靠的紧凑亮斑是已经经过相机 PSF 的未分辨光源,从而避免把旧光斑再次与新 PSF 卷积、填平亮环。它是受约束的光源估计,无法从单张照片唯一恢复真实光源;较大亮面及无法可靠识别的部分继续保留有限形状。新光斑由瞳面 PSF 决定,观测半径只用于分类,不用来拟合圆环。 + +局部背景用深度/覆盖率约束的灰度开运算估计(先腐蚀、后膨胀,中心及两圈共 33 个采样点,外半径为图像长边 / 65)。该估计将相邻亮点与延展亮面分开,正差形成高光候选。亮点证据同时检查邻域,以保留有限光源较暗的外围,否则留下的外围会在小 PSF 下填平大环的中心。亮度采用线性 RGB 最大通道,证据的平滑区间为 .16–.5;这些是计算摄影分类参数,不是光学定律。仅焦后、充分离焦且背景覆盖完整的源像素可进入 E;所有光线仍按源深度计算。 + +高光镜头 `phase-plate-200mm-emitter` 使用 200 mm 焦距、36 mm 虚拟像面、2 m 名义对焦距离、f/1.8 参考孔径和 22.76611328125 μm 四阶边缘光程。它读取 **135 mm 背景标定得到的同一个 Δq**;如果再次按 200 mm 反算 Δq,会把大光斑又压回普通背景尺度。光线位移仍由 `v/(ap) ∂W/∂ρ` 计算,源像素中心保留在共同图像坐标中。这是两套已配准 PSF 的合成,不是改变真实相机焦距却声称视角不变。 + +上述示例深度下,高光支持半径约 75 px,背景仍约 35 px。高光尺度变化来自另一套明确的虚拟光学参数,不来自形成后的圆环半径缩放。高光周围的局部结构和对比会随能量传播改变,不能声称整张照片的感知虚化完全不变。 + +## 4. 光学 PSF 表 + +`OpticalPsfTable` 每次根据镜头、光圈、焦点和输出尺寸构建: + +1. 257 个视差节点覆盖 `[0,1]`。每个节点使用 16,384 个等面积瞳孔中点 `ρ=sqrt((i+.5)/M)`。 +2. 对所有光线计算 `|Aρ+Bρ^(n-1)|`,累计到等宽像面环带;每环密度等于光能除以 `π(r_outer²-r_inner²)`。 +3. 环带宽度为 `max(0.5 输出像素, 0.25 工作像素)`。表边界包括端点和内部驻点,绝不只用边缘光线估算支持范围。 +4. 每一行严格累计全部瞳孔样本,因此总质量为 1。两深度行线性插值仍保持单位总质量。 +5. 上传累计能量 CDF 和支持半径为 `R32F`,使用 nearest sampler。环带内 CDF 按半径平方插值,不能让普通线性过滤改变面积积分。 +6. 对一个有限径向采样区间,以 CDF 差除以环带面积计算平均密度,避免直接采样奇异峰。径向区间由工作像素宽度确定,不随远处稀疏采样而任意增宽。 + +CDF 区间平均是几何核的数值滤波,不能宣称等价于精确二维方形像素积分。生产图片还受深度插值、图像过滤和有限空间求积影响;CPU 表的单位质量不等于整张分层照片严格保光通量。 + +## 5. 复用的生产管线 + +``` +输入原图 + 已解析极性的深度 + U2NetP 蒙版 + → RGB 引导上采样与分层细化 + → 预乘背景线性颜色 / 有效覆盖率 + → 局部背景估计与正高光能量分离 + → 紧凑光斑识别、中心与线性 RGB 积分、剩余高光纹理 + → 普通背景残差与剩余高光分别由瞳面 PSF 表驱动积分(最长边 1280) + → 已识别光源通过实例化四边形绘制同一物理 PSF + → 在线性空间相加 + → 原分辨率主体覆盖合成、源色彩空间编码 + → Bitmap 输出、保存及缩略图 +``` + +分层深度使用共享契约:`R=可见深度,G=主体深度,B=补集深度,A=主体覆盖率`。颜色在去除输入传递函数后才与覆盖率相乘,避免主体颜色提前混入背景。采用 `OpticalColorTransfer` 对真实输入 RGB 色彩空间解码/编码,保留原色与 RGBA_F16 输出,非参数化传递函数会明确拒绝。 + +两条路径复用 `PhysicalBokehShaders.gather`,各使用 512 次空间求积:384 点覆盖目标像素的局部光斑支持圆,128 点覆盖全局支持圆。两个提议分布的混合密度为: + +``` +q(x) = 0.75/(π R_local²) × 1[|x|≤R_local] + + 0.25/(π R_global²) × 1[|x|≤R_global] +weight = PSF_sourceDepth(|x|) / q(x) +``` + +这样在当前背景的有效范围内分配更多样本,同时仍允许其他深度的散焦光线进入。光学权重取**源像素深度**,不是简单按目标像素挑一个模糊半径。纹理 LOD 根据求积密度确定源面积,禁止随离中心距离增加而直接抹宽亮点。 + +沿用共享分层的深度可见性规则和预乘支持归一化;它们是计算摄影的遮挡近似,不是逐瞳孔精确可见性。整块保护主体直接保留原图,边缘按共享覆盖率合成。没有可用背景支持时保留原像素,不凭空制造隐藏内容。 + +画框外颜色未知,生产求积同时排除越界颜色与其支持权重;不把图像边缘无限复制到一个光斑,也不引入另一颜色的远平面。此处是有声明的有限视野边界条件,无法恢复真实画框外光源。 + +一般风格仍使用原有工作分辨率和 PSF。BUBBLE 的背景最长边为 1280,输出、主体细节与像素尺寸仍为原分辨率;这会限制背景最窄光斑的空间分辨率。 + +## 6. 性能、取消与所有权 + +旧生产路径每个 tile 重画数百次 RGB-D 网格,用户日志为 88 tile、平均 593.45 个瞳孔样本、9 个 tile 到 1024 仍未达到变化阈值,耗时 14.319 s。继续加样本既不能解决原图亮点尺寸,也无法满足交互速度。 + +主路径包含两份 PSF 表、两次共享 gather 和三个高光背景估计/分离 draw。光源重建读回工作分辨率 RGBA16F 高光和深度,CPU 识别后上传剩余纹理与实例数据;无亮点证据时跳过深度读回和区域分析。已识别光源通过一次实例化 draw 在线性 RGBA16F 目标上相加,alpha 不累加。读回会引入 GPU 同步成本,日志单独报告光源数量、所有权像素数与重建耗时。逐瞳孔 RGB-D 渲染器、分块支持范围计算、独立 EGL/FBO、累计误差归约 shader 和旧采样器已移除,正常处理不再包含这些资源与收敛日志。 + +取消从 ViewModel 传递到深度准备、PSF 表生成和 GPU pass 之间。已提交的 GPU draw 不能中途撤销,取消检查在结果保存前阻止旧结果继续写入。ViewModel 的图片/文件作业使用互斥锁串行所有权,避免快速连续调整或关闭虚化时发生旧作业覆盖新文件。临时 Bitmap 在 finally 释放。生成后的虚化图用于缩略图,关闭虚化恢复原图缩略图。 + +## 7. 验证与局限 + +Kotlin 编译、光学及测试目录内的 Fourier 数值测试、PSF 表的质量/支持/CDF/有限光源测试、当前光学及默认/自然风格 shader 变体的 NDK 编译均有独立检查。GLES 遵守 [驱动兼容性手册](gles-driver-compatibility.md),并使用独立 `app_process` 执行生产 Kotlin/GLES,无 APK 安装卸载、无 Android Test。 + +真实照片诊断复用原始 `4096×3072` JPEG、`518×518` 浮点深度以及应用原有 U2NetP `320×320` 模型/推理实现。诊断仅替代日志和 direct-buffer 分配工具,不替代光学、shader、深度或合成逻辑。模型推理、图片虚化、最终 JPEG 保存和图库刷新应分别计时,不能用单独 shader 时间冒充端到端交互时间。 + +最终设备测量与验收结果记录于本节后续条目。几何 PSF 的径向对称、虚拟深度、分层遮挡近似及输入原有模糊仍然是明确边界;高光分类只选择被重新传播的输入能量,不决定亮环形状,不通过拟合描边或增益掩盖光学限制。 + +### 统一强度前的设备结果(历史记录,2026-09-10) + +PMA110 / Adreno 840 / GLES 3.2 V@0842.44,`phase-plate-135mm-order4`、f/1.8: + +- 同一猫照片、焦点 `.33435`:工作 `1280×960`、输出 `4096×3072`。PSF 表 `274×257`、环带 `.8 px`。虚化总计 **456 ms**(表构建/设置/上传 258 ms,GPU 渲染及等待 113 ms,读回 85 ms)。旧相同照片与设备的逐瞳孔路径实测 14,389 ms,用户日志为 14,319 ms。 +- 真实 U2NetP 完整蒙版推理阶段 **602 ms**,包含推理 567 ms。两阶段合计约 1.06 s,不包括冷模型初始化、原图读取、输出文件压缩保存及图库刷新。 +- 最终 PNG 已读回目检:背景可见亮环,猫的脸、身体与爪子由主体保护保留;原先左边与下边的异色框线未重现。 +- 实际 GLES 完整管线,1024×768、零主体蒙版、均匀棕色输入,视差 `.06/.33435/.65` 三组共 2,359,296 像素:所有位置(含四边)最大 RGB 色码误差均为 **0**。 +- 同尺寸、σ=4 px 的有限亮点(对应 4096 图的 σ=16 px),上述三组输出/输入线性总能量分别为 **.999461/.999333/.998599**。背景组亮环/中心 **1.76988**,合焦及前景组中心为最大值。总能量检查包含 8-bit 编解码量化。 +- 主体保护与下采样是生产输出选择,有限光斑核正确不代表任何复杂遮挡和细蒙版边缘都无误;仍需结合其他照片评估这些共享算法的边界。 + +旧配置仓库检查:`compileDefaultDebugKotlin` 成功;`testDefaultDebugUnitTest --tests '*Optical*' --tests '*BokehShader*'` 共 **30 项通过、零失败、零跳过**;`git diff --check` 通过。旧风格测试仅更新高光分类入口预期:它现在仅属于 DEFAULT,光学 BUBBLE 不进入该路径。未进行 APK 安装。 + +### 旧路径清理验证 + +已移除旧泡泡焦 shader 分支及配套 CPU 修正、逐瞳孔整图渲染器和独立 shader、分块与采样工具;双精度传播及 FFT 仅保留在测试源集。当前物理光学路径与 DEFAULT/NATURAL 共用生产渲染器。 + +清理后 `compileDefaultDebugKotlin`、`compileDefaultDebugAndroidTestKotlin` 成功;29 项光学/虚化 JVM 测试通过、零跳过。AndroidTest 仅编译,未执行。另对默认/自然 PSF、高光分类、解析高光顶点/片段及合成共 6 个实际 shader 变体做清理前后 NDK 编译与预处理源码对照:移除未使用项及空白后,有效代码一致。 + +### 三风格强度标定统一 + +生产 CPU 和 GLSL 共用 `BokehDefocusModel`: + +``` +gap = max(abs(depth-focus)-.015, 0) +span = max(max(focus,1-focus)-.015, .15) +normalizedGap = clamp(gap/span, 0, 1) +apertureScale = min(1.4/max(N,.7), 1.25) +C = sign(depth-focus) × imageLongEdge/26 + × clamp(normalizedGap^1.25 × apertureScale, 0, 1) +``` + +`uBaseCocRadius` 表示基础强度,`uMaxBlurRadius` 表示当前算法需要搜索的范围,二者分开绑定。自然/旋焦的强度曲线保留,尺寸基准统一为图像长边,竖图不再因为使用宽度而弱于同尺寸横图。泡泡光斑由共同 C 校准入射波前后进行瞳孔传播,没有对形成后的光斑做半径压缩、峰值增益或按亮度调尺寸。 + +默认风格的 CPU 高光几何、三个风格的 GPU CoC 和焦内过渡使用同一公式;泡泡的局部/全局采样仍使用完整 PSF 支持半径,球差能量不会被截断。本轮同时将固定相位板参考光程降为此前四分之一,减少小离焦区域被残余球差过度模糊的问题。 + +此次设备未连接,未做更新后实机照片验收;上方 456 ms、宽亮点亮环比及截图结论仅适用于此前配置。 + +统一标定后 `compileDefaultDebugKotlin` 与 `testDefaultDebugUnitTest --tests '*Optical*' --tests '*Bokeh*'` 通过,共 38 项测试、零失败、零跳过,涵盖共享 CoC、光学传播、PSF 表和 shader 编译;`git diff --check` 通过。 + +### 保留背景强度的大光斑验证(2026-09-10) + +在同一 PMA110 / Adreno 840 上通过独立 `app_process` 执行最终生产代码,未安装 APK 或运行 Android Test: + +- 猫照片 4096×3072、工作尺寸 1280×960、f/1.8、焦点 .33435:**604 ms**,包括表生成/设置/上传 298 ms、渲染及等待 182 ms、读回 124 ms。此次 U2NetP 蒙版阶段另为 **605 ms**,合计约 1.21 s;不包括冷模型初始化、文件读取、PNG/JPEG 压缩与图库保存。调整前单背景路径本次同设备测得 390 ms。 +- 读回猫图右上方可见较大环状光斑;主体和窗框使用当前背景/主体合成。高光附近的纹理会随重新分配能量变化,不能把“普通背景核不变”解释成整幅输出感知完全相同。 +- 1024×768、σ=4 px(相当于 4096 图 σ=16 px)的有限亮点:焦后 .06 的亮环/中心 **1.92018**,输出/输入线性能量 **.999177**;合焦仍中心最亮,不生成泡泡。 +- 均匀棕色图在焦后、合焦、焦前三组的全画面(包括四边)色码误差均为 **0**。 +- 512×384 非高光纹理与延展亮阶跃,对比调整前的当前强度输出,分别 196,608 像素全部一致;两个相邻亮点的总能量比 **.999972**。开运算用相同整数采样偏移和 texelFetch,避免双线性 min/max 破坏直线阶跃。 +- `compileDefaultDebugKotlin` 与光学/虚化筛选的 **40 项 JVM 测试通过、零失败、零跳过**;shader 检查包含腐蚀、膨胀、高光分离、共享 gather、三种传递函数与合成变体。 + +这组检查不证明任意深度边界、复杂遮挡或亮面分类都无误。背景估计、亮点证据门限、有限工作分辨率和支持归一化仍是明确的计算摄影近似。 + +### 已成像光斑重建验证(2026-09-10) + +- Kotlin 编译及光学/虚化相关 43 项 JVM 测试通过;新增相邻光源区分、RGB 所有权积分守恒、延展亮面拒绝和目标拒绝后保留原光斑检查。新实例化顶点/片元 shader 通过 NDK 编译检查。 +- PHK110 / Adreno 730 上通过独立 `app_process` 执行生产 Kotlin/GLES:1024×768、f/1.8、焦点 .33435、背景 .06、σ=4 px 的合成亮点识别为一个光源,拥有 325 像素;亮环/中心为 **5.79187**,线性输出/输入能量 **.999461**。一次运行总耗时 **607 ms**,其中重建读回与分析 **295 ms**。这是合成图测量,不代表 4096 原图的端到端速度。 +- 同设备合焦亮点能量比 1.0,前景 .65 为 .999047,均保持中心最亮。三个深度的均匀色块全画面最大编码误差为 0,包含边缘;未发现新的 GLES 驱动兼容性问题。 +- 提供的花朵照片在本机做固定深度 .06、焦点 .33435、f/1.8 的局部数值对照:新流程在原亮斑中心出现更大的可辨认亮环。识别使用生产 Kotlin 模型,光斑使用生产 PSF CDF;局部背景分离与卷积采用 CPU 对照计算。该对照没有截图对应的真实深度和主体蒙版,不能等同完整 App 输出。 +- 原图没有传到当前连接设备;设备验证仅使用合成图。读回同步和复杂照片中的光源误判仍是后续实图性能与质量评估重点。