feat: optical soap bubble bokeh and physical pupil-derived PSF integration
This commit is contained in:
1 parent
d0d2528b36
commit
ab0a0e19ff
22 files changed
+2565
-867
No files matched your search
+27
-22
@@ -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 {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
}
|
||||
}
|
||||
+105
@@ -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<Source>, 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<Int,Moments>()
|
||||
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<Int>(); val sources=ArrayList<Source>()
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)),
|
||||
)
|
||||
}
|
||||
@@ -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<Application>()
|
||||
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<Application>()
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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) ->
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
@@ -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 })
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<DoubleArray, DoubleArray> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user