// TruVisuals - CRT Scanlines
// Subtle, keyframeable CRT scanline filter for DaVinci Resolve (Studio).
// Dark horizontal scanlines (periodic brightness dip along Y) plus a soft
// bright "refresh" band that slowly rolls DOWN the frame over time.
// Per-pixel effect: uses the plain (p_R,p_G,p_B) transform signature.

DEFINE_UI_PARAMS(intensity, Intensity,             DCTLUI_SLIDER_FLOAT, 0.18, 0.0, 1.0,  0.01)
DEFINE_UI_PARAMS(lineSpacing, Line Spacing px,     DCTLUI_SLIDER_FLOAT, 4.0,  2.0, 12.0, 0.5)
DEFINE_UI_PARAMS(rollSpeed, Roll Speed px, DCTLUI_SLIDER_FLOAT, 2.0,  0.0, 30.0, 0.5)
DEFINE_UI_PARAMS(refreshBright, Refresh Band,          DCTLUI_SLIDER_FLOAT, 0.06, 0.0, 1.0,  0.01)

// Smooth Hermite interpolation between edges e0 and e1 (matches numpy preview).
__DEVICE__ float smoothstep_t(float e0, float e1, float x)
{
    float t = _saturatef((x - e0) / (e1 - e0));
    return t * t * (3.0f - 2.0f * t);
}

__DEVICE__ float3 transform(int p_Width, int p_Height, int p_X, int p_Y, float p_R, float p_G, float p_B)
{
    float fy = (float)p_Y;

    // --- Dark scanlines ---
    // Raised-cosine dip: 0 at bright line centers, 1 at dark troughs.
    // Period along Y equals Line Spacing in pixels.
    float spacing = _fmaxf(lineSpacing, 1.0f);
    float phase = (fy / spacing) * 2.0f * 3.14159265358979f;
    float dip = 0.5f - 0.5f * _cosf(phase);
    float scanMul = 1.0f - intensity * dip;   // 1 at center -> (1-intensity) at trough

    // --- Refresh band (soft bright band rolling DOWN over time) ---
    float H = (float)p_Height;
    float bandH = H * 0.18f;                          // soft band width in px
    float center = _fmod((float)TIMELINE_FRAME_INDEX * rollSpeed, H);
    float d = _fabs(fy - center);
    d = _fminf(d, H - d);                             // wrap-around distance
    float band = 1.0f - smoothstep_t(0.0f, bandH, d); // 1 at center -> 0 at edge
    band = band * band;                               // soften into a bump
    float bandAdd = refreshBright * band;

    float r = _saturatef(p_R * scanMul + bandAdd);
    float g = _saturatef(p_G * scanMul + bandAdd);
    float b = _saturatef(p_B * scanMul + bandAdd);

    return make_float3(r, g, b);
}
