local posteffect={}

local vertex_shader=[[
#version 450
layout (location=0) in vec2 pos;
layout (location=1) in vec2 texcoord;
uniform vec2 mulsize;
out vec2 otexcoord;
void main()
{
	gl_Position=vec4(pos,0.0,1.0);
	otexcoord=vec2(texcoord.x*mulsize.x,texcoord.y*mulsize.y);
}]]

local fragment_shader=[[
#version 450
uniform sampler2D tex;
in vec2 otexcoord;
out vec4 ocolor;
void main()
{
	vec4 color=texture(tex,otexcoord);
	ocolor=color;
}]]

posteffect.new=function(w,shad)
	local obj={win=w,objs={}}
	if shad==nil then
		obj.shader=w:shader(w:vertexshader(vertex_shader),w:fragmentshader(fragment_shader))
	else
		obj.shader=w:shader(w:vertexshader(vertex_shader),w:fragmentshader(shad))
	end
	local shader_pos=obj.shader:vertex("pos")
	shader_pos:add(-1.0,-1.0)
	shader_pos:add(1.0,-1.0)
	shader_pos:add(1.0,1.0)
	shader_pos:add(1.0,1.0)
	shader_pos:add(-1.0,1.0)
	shader_pos:add(-1.0,-1.0)
	local shader_texcoord=obj.shader:vertex("texcoord")
	shader_texcoord:add(0.0,0.0)
	shader_texcoord:add(1.0,0.0)
	shader_texcoord:add(1.0,1.0)
	shader_texcoord:add(1.0,1.0)
	shader_texcoord:add(0.0,1.0)
	shader_texcoord:add(0.0,0.0)
	local pos_vbo=shader_pos:vbo()
	local texcoord_vbo=shader_texcoord:vbo()
	obj.vao=w:vao("triangles",pos_vbo,texcoord_vbo)
	obj.w,obj.h=w:getsize()
	obj.ftex=w:texture(obj.w,obj.h)
	obj.fdepth=w:depthtexture(obj.w,obj.h)
	obj.fstencil=w:stenciltexture(obj.w,obj.h)
	obj.fb=w:framebuffer(obj.ftex,obj.fdepth,obj.fstencil)
	return setmetatable(obj,{__index=posteffect})
end

posteffect.bind=function(self)
	self.fb:bind()
end

posteffect.draw=function(self,tt)
	local w,h=self.win:getsize()
	self.win:cleardepth()
	local t={tex=self.ftex.tex,mulsize={w/self.w,h/self.h}}
	if type(tt)=="table" then
		for i,v in pairs(tt) do
			t[i]=v
		end
	end
	self.vao:draw(t)
end

return posteffect