shader_type spatial;


uniform float width : hint_range(0.0, 16.0);
uniform vec4 outline_color : source_color;
uniform sampler2D albedo_texture : source_color, filter_nearest;


void vertex() {
     MODELVIEW_MATRIX = VIEW_MATRIX * mat4(INV_VIEW_MATRIX[0], vec4(0, 1, 0, 0), INV_VIEW_MATRIX[2], MODEL_MATRIX[3]);
}

/* thanks gdquest */
void fragment() {
    vec2 size = vec2(width) / vec2(textureSize(albedo_texture, 0));

    vec4 sprite_color = texture(albedo_texture, UV);

    float alpha = sprite_color.a;
    alpha += texture(albedo_texture, UV + vec2(0.0, -size.y)).a;
    alpha += texture(albedo_texture, UV + vec2(size.x, -size.y)).a;
    alpha += texture(albedo_texture, UV + vec2(size.x, 0.0)).a;
    alpha += texture(albedo_texture, UV + vec2(size.x, size.y)).a;
    alpha += texture(albedo_texture, UV + vec2(0.0, size.y)).a;
    alpha += texture(albedo_texture, UV + vec2(-size.x, size.y)).a;
    alpha += texture(albedo_texture, UV + vec2(-size.x, 0.0)).a;
    alpha += texture(albedo_texture, UV + vec2(-size.x, -size.y)).a;

    vec3 final_color = mix(outline_color.rgb, sprite_color.rgb, sprite_color.a);
    ALBEDO = final_color;
	ALPHA = clamp(alpha, 0.0, 1.0);
}
