Custom Shader Examples

From GiderosMobile
Revision as of 21:33, 5 November 2023 by MoKaLux (talk | contribs) (Created page with "__NOTOC__ '''Parent:''' Writing Custom Shaders<br/> === A Grey Shader === The code below defines a Grey shader consisting of: * mycshaders/vShaderGrey.glsl vertex shader...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Parent: Writing Custom Shaders

A Grey Shader

The code below defines a Grey shader consisting of:

  • mycshaders/vShaderGrey.glsl vertex shader
  • mycshaders/fShaderGrey.glsl fragment shader

Here the shader files are in the assets/mycshaders directory.

GLSL Vertex Shader: mycshaders/vShaderGrey.glsl

uniform highp mat4 vMatrix;
attribute highp vec3 vVertex;
attribute mediump vec2 vTexCoord;
varying mediump vec2 fTexCoord;

void main() {
	vec4 vertex = vec4(vVertex, 0.8); // vertex coords, scale
	gl_Position = vMatrix*vertex;
	fTexCoord = vTexCoord;
}

GLSL Fragment Shader: mycshaders/fShaderGrey.glsl

//precision highp float;
#ifdef GLES2
	precision highp float;
#endif
uniform lowp vec4 fColor;
uniform lowp sampler2D fTexture;
varying mediump vec2 fTexCoord;
 
void main() {
	lowp vec4 frag = fColor*texture2D(fTexture, fTexCoord);
	float color;
	if (frag.a == 0.0) {
		gl_FragColor = vec4(1.0, 0.5, 1.0, 1.0); // purple
	} else {
		color = dot(frag.rgb, vec3(0.299, 0.587, 0.114));
		gl_FragColor = vec4(color, color, color, frag.a); // gray
	}
}

Lua Code

-- open gl shader
local shadergrey = Shader.new("mycshaders/vShaderGrey", "mycshaders/fShaderGrey", 0,
	{
	{name="vMatrix", type=Shader.CMATRIX, sys=Shader.SYS_WVP, vertex=true},
	{name="fColor", type=Shader.CFLOAT4, sys=Shader.SYS_COLOR, vertex=false},
	{name="fTexture", type=Shader.CTEXTURE, vertex=false},
	},
	{
	{name="vVertex", type=Shader.DFLOAT, mult=3, slot=0, offset=0},
	{name="vColor", type=Shader.DUBYTE, mult=4, slot=1, offset=0},
	{name="vTexCoord", type=Shader.DFLOAT, mult=2, slot=2, offset=0},
	}
)

application:setBackgroundColor(0x333333)

local bitmap = Bitmap.new(Texture.new("gfx/test.png"))
local bitmap2 = Bitmap.new(Texture.new("gfx/arrow_0001.png"))
-- position
bitmap:setPosition(32*1, 32*4)
bitmap2:setPosition(32*6, 32*1)
-- shaders
bitmap:setShader(shadergrey)
bitmap2:setShader(shadergrey)
-- order
stage:addChild(bitmap)
stage:addChild(bitmap2)