in vec2 uv;
in vec2 uvn;

layout (location = 0) out vec4 C;
layout (location = 1) out uvec2 outN_MatId;


void main(){
	bool debug = all(equal(ivec2(U), ivec2(1,1)));

	if(debug){
		dbg_print_buff[print_idx].cnt = 0;
	}



	vec4 C = vec4(0);

	vec3 ro;
	vec3 rd;
	get_ro_and_rd(ro, rd, uv, true);

	vec3 p = ro;


	TraceRes res = trace( ro, rd );
	bool hit = res.success;
	float t = res.dist;
	p = ro + rd * t;

	if(hit){
//		march_c += 0.2;
		vec3 n = get_norm(p);

//		if(int(U.x) == 200 && int(U.y) == 200){
//			vec3 z = p;
//			for(float i = 0; i < 100; i++){
//				z += n*0.02;
//				dbg_plot_ws(z);
//			}
//		}
		uint n_enc = octahedral_16(n);
		outN_MatId.x = n_enc;
//		float mat_id = res.mat_id;
		outN_MatId.y = uint(round(res.mat_id));

		#define ao(d,a,m) mix(1.,smoothstep(0.,1.,sdf(p + normalize(d)*a).x/a),m)
		C.xyz = 0.5 + 0.5 * sin(vec3(3,2,1) + 23.*dot(sin(p.xyz*0.5),sin(p.zxy)));
		C.rgb = pow(C.rgb, vec3(0.5,4,2.));
		vec3 sun_dir = vec3(2,1,1);
		sun_dir = normalize(sun_dir);
		C.xyz *= ao(n*0.5 + sun_dir, 2.0,1.0);
		C.xyz *= ao(n + sun_dir, 0.3,0.8);
		C.xyz *= ao(n + sun_dir, 0.2,0.8);
		C.xyz *= ao(n + sun_dir, 0.05,0.8);
		C.xyz *= ao(n + sun_dir, 0.01,0.8);
		C.xyz *= ao(n + sun_dir, 0.002,0.8);
		C.xyz *= ao(n*0.2 + sun_dir, 0.002,0.8);

		gl_FragDepth = linear_to_depth(t);

		vec3 q = p;
		q = sin(q + sin(q*2));
		float cd = length(q) - 0.9;
		if(cd < -0.3 && p.y > 0.01){
			C = 0.5 + 0.5 * vec4(4,4,4,1) * sin(
				dot(p.xyz,p.zxy)*0.0 + p.xyzz
			);
			C = vec4(1);
			C *= 10.;
		}
		C = vec4(0.5);
//		C.xyz = n * 0.5 + 0.5;
//		gl_FragDepth = cam_far;
//		gl_FragDepth = cam_far;
	} else {
		gl_FragDepth = cam_far;
	}



}
