shader_type spatial;
render_mode unshaded;

group_uniforms Albedo_Settings;
uniform vec4 albedo_color : source_color = vec4(1.0);
uniform sampler2D albedo_texture : source_color, filter_nearest;
uniform bool use_texture = true;
uniform vec2 uv_scale = vec2(1.0, 1.0);

group_uniforms Toon_Lighting;
uniform vec3 light_direction = vec3(0.5, 1.0, 0.5);
uniform float light_steps : hint_range(1.0, 10.0, 1.0) = 3.0;
uniform float step_softness : hint_range(0.01, 1.0) = 0.1;
uniform vec4 shadow_color : source_color = vec4(0.4, 0.4, 0.6, 1.0);
uniform float shadow_offset : hint_range(-1.0, 1.0) = 0.0;

group_uniforms Emission_Settings;
uniform vec4 emission_color : source_color = vec4(0.0, 0.0, 0.0, 1.0); // Nero di default
uniform float emission_energy : hint_range(0.0, 16.0) = 0.0; // A 0 l'emissione è spenta

void fragment() {
	// 1. Albedo
	vec4 tex = texture(albedo_texture, UV * uv_scale);
	vec3 base_color = albedo_color.rgb;
	if (use_texture) base_color *= tex.rgb;
	
	// 2. Luce (World Space Fix)
	vec3 world_light_dir = normalize(light_direction);
	vec3 view_light_dir = (VIEW_MATRIX * vec4(world_light_dir, 0.0)).xyz;
	float n_dot_l = dot(NORMAL, normalize(view_light_dir));
	
	// 3. Toon Stepping
	float intensity = clamp(n_dot_l + shadow_offset, 0.0, 1.0);
	float raw_step = intensity * light_steps;
	float lower_step = floor(raw_step);
	float fract_step = fract(raw_step);
	float lerp_step = smoothstep(0.5 - step_softness, 0.5 + step_softness, fract_step);
	float stepped_intensity = (lower_step + lerp_step) / light_steps;
	
	// 4. Mixing base
	vec3 light_part = base_color * 1.2;
	vec3 shaded_part = base_color * shadow_color.rgb;
	vec3 final_rgb = mix(shaded_part, light_part, clamp(stepped_intensity, 0.0, 1.0));
	
	ALBEDO = final_rgb;
	
	// 5. Emission
	// Moltiplica il colore per l'energia impostata dall'utente
	EMISSION = emission_color.rgb * emission_energy;
}