[Solved] Trying making 2D Lighting Shaders with normal maps


#1

Hi,
I’m new to shaders. I’m trying to use shaders to do 2D Lighting with normal maps, but I’m missing something.

I googled and saw this.

I tried doing it :

class TestShader extends hxsl.Shader {
static var SRC = {
    @:import h3d.shader.Base2d;
	
	@param var normal : Sampler2D;
	@param var texture : Sampler2D;
	@param var mp : Vec3; // Mouse Position
	
	function fragment() {
		if (texture.get(input.uv).a == 0) return;
		
		var lightradius:Int = 250;
		
		// Convert normal coords [-1,1] to [0,1]
		var rgb_normal:Vec4 = normal.get(input.uv) * 0.5 + 0.5; 
		
		// Distance between mousePos and pixelPos
		var dist:Vec3 = abs(vec3(mp.x - absolutePosition.x, mp.y - absolutePosition.y, mp.z));
		
		var brightness:Float = clamp(dot(normalize(vec3(dist.x, dist.y, dist.z)), rgb_normal.rgb), 0., 1. );
		brightness *= clamp(1.0 - (length(dist.xyz) / lightradius), 0.0, 1.0);
		
		var lightColor = vec4(1, 1, 1, 1);
		
		output.color = vec4(pixelColor.xyz * lightColor.xyz * brightness,1);
	}
    }
}

Using images used in this article(p.1 and p.10), I get this :
2019-04-30_00-56-11

The shape is weird. There’s something I’m doing wrong but I don’t know what it is.

Will really appreciate your help. (and sorry if I have bad english)


#2

The images weren’t good and didn’t really understand anything.

Here’s what I finally used :

class TestShader extends hxsl.Shader {
static var SRC = {
    @:import h3d.shader.Base2d;
	
	@param var normal : Sampler2D;
	@param var texture : Sampler2D;
	@param var mp : Vec3; // Mouse Position
	
	function fragment() {
		if (texture.get(input.uv).a == 0) return;
		
		var lightradius:Float = 450;
		
		var normal:Vec4 = vec4(unpackNormal(normal.get(input.uv)), 1);
		
		var dist:Vec3 = vec3(abs(mp.x - absolutePosition.x), abs(mp.y - absolutePosition.y), mp.z);
		
		var brightness:Float = clamp(dot(dist, normal.rgb),0,1);
		brightness *= clamp(1-(length(dist) / lightradius),0,1);
		
		var lightColor = vec3(0, 0.5, 0);
		
		output.color.rgb += lightColor * brightness;
	}
}

#3

Looks like your normal map is not working.
image


#4

I solved my problem by using other images and the code in the 2nd post.