PageRenderTime 23ms CodeModel.GetById 14ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/extra/bunny/cel-shaded/cel-shaded.factor

http://github.com/abeaumont/factor
Unknown | 96 lines | 77 code | 19 blank | 0 comment | 0 complexity | d4755fed5e12e2c3b638279aab75fc92 MD5 | raw file
 1USING: arrays bunny.model continuations destructors kernel
 2multiline opengl opengl.shaders opengl.capabilities opengl.gl
 3sequences accessors combinators ;
 4IN: bunny.cel-shaded
 5
 6STRING: vertex-shader-source
 7varying vec3 position, normal, viewer;
 8
 9void
10main()
11{
12    gl_Position = ftransform();
13
14    position = gl_Vertex.xyz;
15    normal = gl_Normal;
16    viewer = vec3(0, 0, 1) * gl_NormalMatrix;
17}
18
19;
20
21STRING: cel-shaded-fragment-shader-lib-source
22varying vec3 position, normal, viewer;
23uniform vec3 light_direction;
24uniform vec4 color;
25uniform vec4 ambient, diffuse;
26uniform float shininess;
27
28float
29modulate(vec3 direction, vec3 normal)
30{
31    return dot(direction, normal) * 0.5 + 0.5;
32}
33
34float
35cel(float m)
36{
37    return smoothstep(0.25, 0.255, m) * 0.4 + smoothstep(0.695, 0.70, m) * 0.5;
38}
39
40vec4
41cel_light()
42{
43    vec3 direction = normalize(light_direction - position);
44    vec3 reflection = reflect(direction, normal);
45    vec4 ad = (ambient + diffuse * vec4(vec3(cel(modulate(direction, normal))), 1));
46    float s = cel(pow(max(dot(-reflection, viewer), 0.0), shininess));
47    return ad * color + vec4(vec3(s), 0);
48}
49
50;
51
52STRING: cel-shaded-fragment-shader-main-source
53vec4 cel_light();
54
55void
56main()
57{
58    gl_FragColor = cel_light();
59}
60
61;
62
63TUPLE: bunny-cel-shaded program ;
64
65: cel-shading-supported? ( -- ? )
66    "2.0" { "GL_ARB_shader_objects" }
67    has-gl-version-or-extensions? ;
68
69: <bunny-cel-shaded> ( gadget -- draw )
70    drop
71    cel-shading-supported? [
72        bunny-cel-shaded new
73        vertex-shader-source <vertex-shader> check-gl-shader
74        cel-shaded-fragment-shader-lib-source <fragment-shader> check-gl-shader
75        cel-shaded-fragment-shader-main-source <fragment-shader> check-gl-shader
76        3array <gl-program> check-gl-program
77        >>program
78    ] [ f ] if ;
79
80: (draw-cel-shaded-bunny) ( geom program -- )
81    [
82        {
83            [ "light_direction" glGetUniformLocation 1.0 -1.0 1.0 glUniform3f ]
84            [ "color"           glGetUniformLocation 0.6 0.5 0.5 1.0 glUniform4f ]
85            [ "ambient"         glGetUniformLocation 0.2 0.2 0.2 0.2 glUniform4f ]
86            [ "diffuse"         glGetUniformLocation 0.8 0.8 0.8 0.8 glUniform4f ]
87            [ "shininess"       glGetUniformLocation 100.0 glUniform1f ]
88        } cleave bunny-geom
89    ] with-gl-program ;
90
91M: bunny-cel-shaded draw-bunny
92    program>> (draw-cel-shaded-bunny) ;
93
94M: bunny-cel-shaded dispose
95    program>> delete-gl-program ;
96