// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.

CCEffect %{
  techniques:
  - passes:
    - vert: vs:vert
      frag: fs:frag
      depthStencilState:
        depthTest: false
        depthWrite: false
      blendState:
        targets:
        - blend: true
          blendSrc: src_alpha
          blendDst: one_minus_src_alpha
          blendDstAlpha: one_minus_src_alpha
      rasterizerState:
        cullMode: none
      properties:
        alphaThreshold: { value: 0.5 }
        outlineSize: {value: 0.0}
        outlineColor: {value: [1,1,1,1]}
}%


CCProgram vs %{
  precision highp float;

  #include <cc-global>
  #if USE_LOCAL
    #include <cc-local>
  #endif

  in vec3 a_position;
  in vec2 a_texCoord;
  in vec4 a_color;

  out vec4 v_color;
  out vec2 v_uv0;

  vec4 vert () {
    vec4 pos = vec4(a_position, 1);

    #if USE_LOCAL
      pos = cc_matViewProj * cc_matWorld * pos;
    #else
      pos = cc_matViewProj * pos;
    #endif

    #if USE_TEXTURE
      v_uv0 = a_texCoord;
    #endif

    v_color = a_color;

    return pos;
  }
}%


CCProgram fs %{
  #if CC_SUPPORT_standard_derivatives
    #extension GL_OES_standard_derivatives : enable
  #endif

  precision highp float;

  #include <alpha-test>

  in vec4 v_color;

  #if USE_TEXTURE
    in vec2 v_uv0;
    #pragma builtin(local)
      layout(set = 2, binding = 10) uniform sampler2D cc_spriteTexture;
  #endif

  #if USE_SDF
  uniform Outline {
    vec4 outlineColor;
    float outlineSize;
  };
  #endif

  vec4 frag () {
      #if USE_SDF
        #if USE_TEXTURE_ALPHAONLY
          float dist = texture(cc_spriteTexture, v_uv0).a;
        #else
          float dist = texture(cc_spriteTexture, v_uv0).r;
        #endif

        #if USE_SDF_EXTEND
          const float EDGE_VALUE = 0.45;
        #else
          const float EDGE_VALUE = 0.5;
        #endif

        #if CC_SUPPORT_standard_derivatives
          float smoothing = fwidth(dist);
        #else
          float smoothing = 0.05;
        #endif

        float outEdge = EDGE_VALUE - outlineSize;
        float bg = smoothstep(outEdge - smoothing, outEdge, dist);
        float fg = smoothstep(EDGE_VALUE - smoothing, EDGE_VALUE, dist);
        vec4 fgColor = outlineColor * (1.0 - fg) + v_color * fg;
        return vec4(fgColor.rgb, fgColor.a * bg);

      #else
        vec4 o = vec4(1, 1, 1, 1);
        #if USE_TEXTURE
          #if USE_TEXTURE_ALPHAONLY
            o.a *= texture(cc_spriteTexture, v_uv0).a;
          #else
            o *= texture(cc_spriteTexture, v_uv0);
          #endif
          #if CC_USE_ALPHA_ATLAS_TEXTURE
            o.a *= texture2D(cc_spriteTexture, v_uv0 + vec2(0, 0.5)).r;
          #endif
        #endif

        o *= v_color;
        ALPHA_TEST(o);
        return o;
      #endif
  }
}%
