OpenGL pixel shader: Difference between revisions

Content added Content deleted
(add JavaScript/WebGL (based on OpenGL example))
m (→‎{{header|C}}: less flaky noise function (still pretty flaky))
Line 11: Line 11:
Getting a true (pseudo) random number is surprisingly tricky. The following code makes something noisy, but not at all random:
Getting a true (pseudo) random number is surprisingly tricky. The following code makes something noisy, but not at all random:
<lang c>#include <stdio.h>
<lang c>#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/glut.h>


GLuint ps, vs, prog, r_mod;
float angle = 0;
float angle = 0;
void render(void)
void render(void)
{
{
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT);
glUniform1f(r_mod, rand() / (float)RAND_MAX);


glLoadIdentity();
glLoadIdentity();
glRotatef(angle, .3, 1, 0);
glRotatef(angle, angle * .1, 1, 0);
glBegin(GL_TRIANGLES);
glBegin(GL_TRIANGLES);
glVertex3f(-.5, -.5, 0);
glVertex3f(-1, -.5, 0);
glVertex3f(0, .5, 0);
glVertex3f(0, 1, 0);
glVertex3f(.5, 0, 0);
glVertex3f(1, 0, 0);
glEnd();
glEnd();
angle += .01;
angle += .02;
glutSwapBuffers();
glutSwapBuffers();
}
}
Line 32: Line 35:
void set_shader()
void set_shader()
{
{
GLuint ps, vs, prog;
const char *f =
const char *f =
"varying float x, y, z;"
"varying float x, y, z;"
"uniform float r_mod;"
"float rand(float s) { return mod(abs(s) * 7654321 + 1, 1); }"
"void main() { gl_FragColor = vec4(rand(x), rand(y), rand(z), 1); }";
"float rand(float s) { return mod(pow(abs(s * 7.654321) + 1, 1 + r_mod), 1); }"
"void main() {"
" gl_FragColor = vec4(rand(gl_FragCoord.x + x), rand(gl_FragCoord.y + y), rand(gl_FragCoord.z + z), 1);"
"}";
const char *v =
const char *v =
"varying float x, y, z;"
"varying float x, y, z;"
Line 42: Line 47:
" gl_Position = ftransform();"
" gl_Position = ftransform();"
" x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;"
" x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;"
" x *= z; y *= x; z += (x + y);"
" x += y; y -= x; z += x - y;"
"}";
"}";


Line 59: Line 64:
glLinkProgram(prog);
glLinkProgram(prog);
glUseProgram(prog);
glUseProgram(prog);
r_mod = glGetUniformLocation(prog, "r_mod");
}
}


Line 65: Line 71:
glutInit(&argc, argv);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(0, 0);
glutInitWindowSize(200, 200);
glutInitWindowSize(200, 200);
glutCreateWindow("Stuff");
glutCreateWindow("Stuff");
Line 73: Line 78:
if (!glewIsSupported("GL_VERSION_2_0")) {
if (!glewIsSupported("GL_VERSION_2_0")) {
fprintf(stderr, "GL 2.0 unsupported\n");
fprintf(stderr, "GL 2.0 unsupported\n");
exit(1);
return 1;
}
}