#include <metal_stdlib>
using namespace metal;

struct BrightSpot {
    float2 position;   // UV 좌표
    float brightness;  // 밝기
};

kernel void Lens_BrightSpot(
    texture2d<float, access::read> inTexture [[texture(0)]],
    device BrightSpot *outSpots [[buffer(0)]],
    constant float &threshold [[buffer(1)]],
    uint2 gid [[thread_position_in_grid]],
    device atomic_uint &spotCounter [[buffer(2)]])
{
    uint width = inTexture.get_width();
    uint height = inTexture.get_height();
    
    if (gid.x >= width || gid.y >= height) return;
    
    float2 uv = float2(gid) / float2(width, height);
    
    float4 color = inTexture.read(gid);
    //float luminance = dot(color.rgb, float3(0.299, 0.587, 0.114));
    float luminance = dot(color.rgb, float3(0.2126, 0.7152, 0.0722));
    
    // 밝기가 임계값보다 크면 처리 시작
    if (luminance >= threshold) {
        // 현재 스레드의 고유 ID 가져오기
        uint spotIndex = atomic_fetch_add_explicit(&spotCounter, 1, memory_order_relaxed);
        
        // 결과 버퍼에 저장 (최대 저장 크기를 초과하지 않도록 주의)
        if (spotIndex < 200) { // 최대 100개 지점 저장 (버퍼 크기에 따라 조정 필요)
            outSpots[spotIndex].position = uv;
            outSpots[spotIndex].brightness = luminance;
        }
    }
}
















#include <metal_stdlib>
using namespace metal;

struct BrightSpot {
    float2 position;
    float brightness;
    float size;
};

constant float laplacianKernel[9] = {
    0.5, 1.0, 0.5,
    1.0, -6.0, 1.0,
    0.5, 1.0, 0.5
};

constant float gaussianKernel[9] = {
    0.0625, 0.125, 0.0625,
    0.125,  0.25,  0.125,
    0.0625, 0.125, 0.0625
};

float toGrayscale(float3 color) {
    return dot(color, float3(0.2126, 0.7152, 0.0722));
}

// 최소 거리 확인
bool isTooClose(float2 newPosition, device BrightSpot *spots, uint spotCount, float minDistance) {
    for (uint i = 0; i < spotCount; i++) {
        if (length(newPosition - spots[i].position) < minDistance) {
            return true;
        }
    }
    return false;
}

kernel void Lens_BrightSpot(
    texture2d<float, access::read> inTexture [[texture(0)]],
    device BrightSpot *outSpots [[buffer(0)]],
    constant float &threshold [[buffer(1)]],
    uint2 gid [[thread_position_in_grid]],
    device atomic_uint &spotCounter [[buffer(2)]]) {
    
    uint width = inTexture.get_width();
    uint height = inTexture.get_height();
    if (gid.x >= width || gid.y >= height) return;

    float2 uv = float2(gid) / float2(width, height);
    float3 originalColor = inTexture.read(gid).rgb;
    float grayscale = toGrayscale(originalColor);

    // 3x3 가우시안 블러 적용
    float blurredGrayscale = 0.0;
    float edgeBrightness = 0.0;
    
    for (int i = 0; i < 9; i++) {
        int x = i % 3 - 1;
        int y = i / 3 - 1;
        
        uint2 samplePos = uint2(
            uint(clamp(int(gid.x) + x, 0, int(width) - 1)),
            uint(clamp(int(gid.y) + y, 0, int(height) - 1))
        );

        float3 sampleColor = inTexture.read(samplePos).rgb;
        float sampleGray = toGrayscale(sampleColor);

        blurredGrayscale += sampleGray * gaussianKernel[i]; // 가우시안 블러 연산
        edgeBrightness += sampleGray * laplacianKernel[i];  // 라플라시안 필터 연산
    }

    edgeBrightness = pow(abs(edgeBrightness), 0.75);  // 경계 감지 결과 보정
    float contrast = pow(blurredGrayscale, 1.5); // 대비 강조

    bool isBrightSpot = contrast > (threshold + edgeBrightness * 0.5);
    
    if (isBrightSpot) {
        uint currentSpotCount = atomic_load_explicit(&spotCounter, memory_order_relaxed);
        
        float minDistance = 0.; // 화면 비율 기준 최소 거리

        if (!isTooClose(uv, outSpots, currentSpotCount, minDistance)) {
            uint spotIndex = atomic_fetch_add_explicit(&spotCounter, 1, memory_order_relaxed);
            if (spotIndex < 100) {
                outSpots[spotIndex] = { uv, contrast, 1.0 };
            }
        }
    }
}

