diff --git a/linux/templates/CL_GLUT.ico b/linux/templates/CL_GLUT.ico new file mode 100644 index 00000000..2a515ce7 Binary files /dev/null and b/linux/templates/CL_GLUT.ico differ diff --git a/linux/templates/CL_GLUT.template b/linux/templates/CL_GLUT.template new file mode 100644 index 00000000..520c13ce --- /dev/null +++ b/linux/templates/CL_GLUT.template @@ -0,0 +1,29 @@ +[Template] +ver=2 +Name=GLUT +Icon=CL_GLUT.ico +Description=A simple GLUT program +Description[zh_CN]=一个简单的GLUT程序 +Category=3D +Category[zh_CN]=3D + +[Unit0] +CName=main.c +C=CL_GLUT_shapes.c.txt + +[Unit1] +CName=glmatrix.h +C=CL_GLUT_glmatrix.h.txt + +[Unit2] +CName=glmatrix.c +C=CL_GLUT_glmatrix.c.txt + +[Project] +UnitCount=3 +Type=0 +IsCpp=0 +linker=-lm -lfreeglut -lopengl32 -lwinmm -lgdi32_@@__@@_ + + + diff --git a/linux/templates/CL_GLUT_glmatrix.c.txt b/linux/templates/CL_GLUT_glmatrix.c.txt new file mode 100644 index 00000000..b3dad22d --- /dev/null +++ b/linux/templates/CL_GLUT_glmatrix.c.txt @@ -0,0 +1,219 @@ +#include +#define _USE_MATH_DEFINES +#include +#include "glmatrix.h" + +#ifndef M_PI +#define M_PI 3.141592653589793 +#endif + +#define MMODE_IDX(x) ((x) - GL_MODELVIEW) +#define MAT_STACK_SIZE 32 +#define MAT_IDENT {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1} + +static int mm_idx = 0; +static float mat_stack[3][MAT_STACK_SIZE][16] = {{MAT_IDENT}, {MAT_IDENT}, {MAT_IDENT}}; +static int stack_top[3]; + +void gl_matrix_mode(int mm) +{ + mm_idx = MMODE_IDX(mm); +} + +void gl_push_matrix(void) +{ + int top = stack_top[mm_idx]; + + memcpy(mat_stack[mm_idx][top + 1], mat_stack[mm_idx][top], 16 * sizeof(float)); + stack_top[mm_idx]++; +} + +void gl_pop_matrix(void) +{ + stack_top[mm_idx]--; +} + +void gl_load_identity(void) +{ + static const float idmat[] = MAT_IDENT; + int top = stack_top[mm_idx]; + float *mat = mat_stack[mm_idx][top]; + + memcpy(mat, idmat, sizeof idmat); +} + +void gl_load_matrixf(const float *m) +{ + int top = stack_top[mm_idx]; + float *mat = mat_stack[mm_idx][top]; + + memcpy(mat, m, 16 * sizeof *mat); +} + +#define M4(i, j) ((i << 2) + j) + +void gl_mult_matrixf(const float *m2) +{ + int i, j; + int top = stack_top[mm_idx]; + float *m1 = mat_stack[mm_idx][top]; + float res[16]; + + for(i=0; i<4; i++) { + for(j=0; j<4; j++) { + res[M4(i,j)] = m1[M4(i,0)] * m2[M4(0,j)] + + m1[M4(i,1)] * m2[M4(1,j)] + + m1[M4(i,2)] * m2[M4(2,j)] + + m1[M4(i,3)] * m2[M4(3,j)]; + } + } + + memcpy(m1, res, sizeof res); +} + +void gl_translatef(float x, float y, float z) +{ + float mat[] = MAT_IDENT; + + mat[12] = x; + mat[13] = y; + mat[14] = z; + + gl_mult_matrixf(mat); +} + +void gl_rotatef(float angle, float x, float y, float z) +{ + float mat[] = MAT_IDENT; + + float angle_rad = (float)M_PI * angle / 180.f; + float sina = (float)sin(angle_rad); + float cosa = (float)cos(angle_rad); + float one_minus_cosa = 1.f - cosa; + float nxsq = x * x; + float nysq = y * y; + float nzsq = z * z; + + mat[0] = nxsq + (1.f - nxsq) * cosa; + mat[4] = x * y * one_minus_cosa - z * sina; + mat[8] = x * z * one_minus_cosa + y * sina; + mat[1] = x * y * one_minus_cosa + z * sina; + mat[5] = nysq + (1.f - nysq) * cosa; + mat[9] = y * z * one_minus_cosa - x * sina; + mat[2] = x * z * one_minus_cosa - y * sina; + mat[6] = y * z * one_minus_cosa + x * sina; + mat[10] = nzsq + (1.f - nzsq) * cosa; + + gl_mult_matrixf(mat); +} + +void gl_scalef(float x, float y, float z) +{ + float mat[] = MAT_IDENT; + + mat[0] = x; + mat[5] = y; + mat[10] = z; + + gl_mult_matrixf(mat); +} + +void gl_ortho(float left, float right, float bottom, float top, float znear, float zfar) +{ + float mat[] = MAT_IDENT; + + float dx = right - left; + float dy = top - bottom; + float dz = zfar - znear; + + float tx = -(right + left) / dx; + float ty = -(top + bottom) / dy; + float tz = -(zfar + znear) / dz; + + float sx = 2.f / dx; + float sy = 2.f / dy; + float sz = -2.f / dz; + + mat[0] = sx; + mat[5] = sy; + mat[10] = sz; + mat[12] = tx; + mat[13] = ty; + mat[14] = tz; + + gl_mult_matrixf(mat); +} + +void gl_frustum(float left, float right, float bottom, float top, float znear, float zfar) +{ + float mat[] = MAT_IDENT; + + float dx = right - left; + float dy = top - bottom; + float dz = zfar - znear; + + float a = (right + left) / dx; + float b = (top + bottom) / dy; + float c = -(zfar + znear) / dz; + float d = -2.f * zfar * znear / dz; + + mat[0] = 2.f * znear / dx; + mat[5] = 2.f * znear / dy; + mat[8] = a; + mat[9] = b; + mat[10] = c; + mat[11] = -1.f; + mat[14] = d; + mat[15] = 0; + + gl_mult_matrixf(mat); +} + +void glu_perspective(float vfov, float aspect, float znear, float zfar) +{ + float vfov_rad = (float)M_PI * vfov / 180.f; + float x = znear * (float)tan(vfov_rad / 2.f); + gl_frustum(-aspect * x, aspect * x, -x, x, znear, zfar); +} + +/* return the matrix (16 elements, 4x4 matrix, row-major order */ +float* get_matrix(int mm) +{ + int idx = MMODE_IDX(mm); + int top = stack_top[idx]; + return mat_stack[idx][top]; +} + + +#define M3(i, j) ((i * 3) + j) +static float inv_transpose_result[9]; + +/* return the inverse transpose of the left-upper 3x3 of a matrix + The returned pointer is only valid until the next time this function is + called, so make a deep copy when you want to keep it around. + */ +float* get_inv_transpose_3x3(int mm) +{ + int idx = MMODE_IDX(mm); + int top = stack_top[idx]; + float *m1 = mat_stack[idx][top]; + + + float determinant = +m1[M4(0,0)]*(m1[M4(1,1)]*m1[M4(2,2)]-m1[M4(2,1)]*m1[M4(1,2)]) + -m1[M4(0,1)]*(m1[M4(1,0)]*m1[M4(2,2)]-m1[M4(1,2)]*m1[M4(2,0)]) + +m1[M4(0,2)]*(m1[M4(1,0)]*m1[M4(2,1)]-m1[M4(1,1)]*m1[M4(2,0)]); + + float invdet = 1/determinant; + + inv_transpose_result[M3(0,0)] = (m1[M4(1,1)]*m1[M4(2,2)]-m1[M4(2,1)]*m1[M4(1,2)])*invdet; + inv_transpose_result[M3(1,0)] = -(m1[M4(0,1)]*m1[M4(2,2)]-m1[M4(0,2)]*m1[M4(2,1)])*invdet; + inv_transpose_result[M3(2,0)] = (m1[M4(0,1)]*m1[M4(1,2)]-m1[M4(0,2)]*m1[M4(1,1)])*invdet; + inv_transpose_result[M3(0,1)] = -(m1[M4(1,0)]*m1[M4(2,2)]-m1[M4(1,2)]*m1[M4(2,0)])*invdet; + inv_transpose_result[M3(1,1)] = (m1[M4(0,0)]*m1[M4(2,2)]-m1[M4(0,2)]*m1[M4(2,0)])*invdet; + inv_transpose_result[M3(2,1)] = -(m1[M4(0,0)]*m1[M4(1,2)]-m1[M4(1,0)]*m1[M4(0,2)])*invdet; + inv_transpose_result[M3(0,2)] = (m1[M4(1,0)]*m1[M4(2,1)]-m1[M4(2,0)]*m1[M4(1,1)])*invdet; + inv_transpose_result[M3(1,2)] = -(m1[M4(0,0)]*m1[M4(2,1)]-m1[M4(2,0)]*m1[M4(0,1)])*invdet; + inv_transpose_result[M3(2,2)] = (m1[M4(0,0)]*m1[M4(1,1)]-m1[M4(1,0)]*m1[M4(0,1)])*invdet; + + return inv_transpose_result; +} diff --git a/linux/templates/CL_GLUT_glmatrix.h.txt b/linux/templates/CL_GLUT_glmatrix.h.txt new file mode 100644 index 00000000..7cf2c68a --- /dev/null +++ b/linux/templates/CL_GLUT_glmatrix.h.txt @@ -0,0 +1,31 @@ +#ifndef GLMATRIX_H_ +#define GLMATRIX_H_ + +#ifndef GL_MODELVIEW +#define GL_MODELVIEW 0x1700 +#endif +#ifndef GL_PROJECTION +#define GL_PROJECTION 0x1701 +#endif +#ifndef GL_TEXTURE +#define GL_TEXTURE 0x1702 +#endif + +void gl_matrix_mode(int mmode); +void gl_push_matrix(void); +void gl_pop_matrix(void); +void gl_load_identity(void); +void gl_load_matrixf(const float *mat); +void gl_mult_matrixf(const float *mat); +void gl_translatef(float x, float y, float z); +void gl_rotatef(float angle, float x, float y, float z); +void gl_scalef(float x, float y, float z); +void gl_ortho(float left, float right, float bottom, float top, float znear, float zfar); +void gl_frustum(float left, float right, float bottom, float top, float znear, float zfar); +void glu_perspective(float vfov, float aspect, float znear, float zfar); + +/* getters */ +float* get_matrix(int mm); +float* get_inv_transpose_3x3(int mm); + +#endif /* GLMATRIX_H_ */ diff --git a/linux/templates/CL_GLUT_shapes.c.txt b/linux/templates/CL_GLUT_shapes.c.txt new file mode 100644 index 00000000..09fb5efa --- /dev/null +++ b/linux/templates/CL_GLUT_shapes.c.txt @@ -0,0 +1,946 @@ +/*! \file shapes.c + \ingroup demos + + This program is a test harness for the various shapes + in OpenGLUT. It may also be useful to see which + parameters control what behavior in the OpenGLUT + objects. + + Spinning wireframe and solid-shaded shapes are + displayed. Some parameters can be adjusted. + + Keys: + - Esc   Quit + - q Q   Quit + - i I   Show info + - p P   Toggle perspective or orthographic projection + - r R   Toggle fixed or animated rotation around model X-axis + - s S   Toggle toggle fixed function or shader render path + - n N   Toggle visualization of object's normal vectors + - = +   Increase \a slices + - - _   Decreate \a slices + - , <   Decreate \a stacks + - . >   Increase \a stacks + - 9 (   Decreate \a depth (Sierpinski Sponge) + - 0 )   Increase \a depth (Sierpinski Sponge) + - up    Increase "outer radius" + - down  Decrease "outer radius" + - left  Decrease "inner radius" + - right Increase "inner radius" + - PgUp  Next shape-drawing function + - PgDn  Prev shape-drawing function + + \author Written by Nigel Stewart November 2003 + + \author Portions Copyright (C) 2004, the OpenGLUT project contributors.
+ OpenGLUT branched from freeglut in February, 2004. + + \image html openglut_shapes.png OpenGLUT Geometric Shapes Demonstration + \include demos/shapes/shapes.c +*/ + +#include + +#include +#include +#include +#include + +#include "glmatrix.h" + +#ifdef _MSC_VER +/* DUMP MEMORY LEAKS */ +#include +#endif + +/* report GL errors, if any, to stderr */ +void checkError(const char *functionName) +{ + GLenum error; + while (( error = glGetError() ) != GL_NO_ERROR) { + fprintf (stderr, "GL error 0x%X detected in %s\n", error, functionName); + } +} + +/* + * OpenGL 2+ shader mode needs some function and macro definitions, + * avoiding a dependency on additional libraries like GLEW or the + * GL/glext.h header + */ +#ifndef GL_FRAGMENT_SHADER +#define GL_FRAGMENT_SHADER 0x8B30 +#endif + +#ifndef GL_VERTEX_SHADER +#define GL_VERTEX_SHADER 0x8B31 +#endif + +#ifndef GL_COMPILE_STATUS +#define GL_COMPILE_STATUS 0x8B81 +#endif + +#ifndef GL_LINK_STATUS +#define GL_LINK_STATUS 0x8B82 +#endif + +#ifndef GL_INFO_LOG_LENGTH +#define GL_INFO_LOG_LENGTH 0x8B84 +#endif + +typedef ptrdiff_t ourGLsizeiptr; +typedef char ourGLchar; + +#ifndef APIENTRY +#define APIENTRY +#endif + +#ifndef GL_VERSION_2_0 +typedef GLuint (APIENTRY *PFNGLCREATESHADERPROC) (GLenum type); +typedef void (APIENTRY *PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const ourGLchar **string, const GLint *length); +typedef void (APIENTRY *PFNGLCOMPILESHADERPROC) (GLuint shader); +typedef GLuint (APIENTRY *PFNGLCREATEPROGRAMPROC) (void); +typedef void (APIENTRY *PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRY *PFNGLLINKPROGRAMPROC) (GLuint program); +typedef void (APIENTRY *PFNGLUSEPROGRAMPROC) (GLuint program); +typedef void (APIENTRY *PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); +typedef void (APIENTRY *PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, ourGLchar *infoLog); +typedef void (APIENTRY *PFNGLGETPROGRAMIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRY *PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, ourGLchar *infoLog); +typedef GLint (APIENTRY *PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const ourGLchar *name); +typedef GLint (APIENTRY *PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const ourGLchar *name); +typedef void (APIENTRY *PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRY *PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#endif + +PFNGLCREATESHADERPROC gl_CreateShader; +PFNGLSHADERSOURCEPROC gl_ShaderSource; +PFNGLCOMPILESHADERPROC gl_CompileShader; +PFNGLCREATEPROGRAMPROC gl_CreateProgram; +PFNGLATTACHSHADERPROC gl_AttachShader; +PFNGLLINKPROGRAMPROC gl_LinkProgram; +PFNGLUSEPROGRAMPROC gl_UseProgram; +PFNGLGETSHADERIVPROC gl_GetShaderiv; +PFNGLGETSHADERINFOLOGPROC gl_GetShaderInfoLog; +PFNGLGETPROGRAMIVPROC gl_GetProgramiv; +PFNGLGETPROGRAMINFOLOGPROC gl_GetProgramInfoLog; +PFNGLGETATTRIBLOCATIONPROC gl_GetAttribLocation; +PFNGLGETUNIFORMLOCATIONPROC gl_GetUniformLocation; +PFNGLUNIFORMMATRIX4FVPROC gl_UniformMatrix4fv; +PFNGLUNIFORMMATRIX3FVPROC gl_UniformMatrix3fv; + +void initExtensionEntries(void) +{ + gl_CreateShader = (PFNGLCREATESHADERPROC) glutGetProcAddress ("glCreateShader"); + gl_ShaderSource = (PFNGLSHADERSOURCEPROC) glutGetProcAddress ("glShaderSource"); + gl_CompileShader = (PFNGLCOMPILESHADERPROC) glutGetProcAddress ("glCompileShader"); + gl_CreateProgram = (PFNGLCREATEPROGRAMPROC) glutGetProcAddress ("glCreateProgram"); + gl_AttachShader = (PFNGLATTACHSHADERPROC) glutGetProcAddress ("glAttachShader"); + gl_LinkProgram = (PFNGLLINKPROGRAMPROC) glutGetProcAddress ("glLinkProgram"); + gl_UseProgram = (PFNGLUSEPROGRAMPROC) glutGetProcAddress ("glUseProgram"); + gl_GetShaderiv = (PFNGLGETSHADERIVPROC) glutGetProcAddress ("glGetShaderiv"); + gl_GetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) glutGetProcAddress ("glGetShaderInfoLog"); + gl_GetProgramiv = (PFNGLGETPROGRAMIVPROC) glutGetProcAddress ("glGetProgramiv"); + gl_GetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) glutGetProcAddress ("glGetProgramInfoLog"); + gl_GetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC) glutGetProcAddress ("glGetAttribLocation"); + gl_GetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) glutGetProcAddress ("glGetUniformLocation"); + gl_UniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) glutGetProcAddress ("glUniformMatrix4fv"); + gl_UniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC) glutGetProcAddress ("glUniformMatrix3fv"); + if (!gl_CreateShader || !gl_ShaderSource || !gl_CompileShader || !gl_CreateProgram || !gl_AttachShader || !gl_LinkProgram || !gl_UseProgram || !gl_GetShaderiv || !gl_GetShaderInfoLog || !gl_GetProgramiv || !gl_GetProgramInfoLog || !gl_GetAttribLocation || !gl_GetUniformLocation || !gl_UniformMatrix4fv || !gl_UniformMatrix3fv) + { + fprintf (stderr, "glCreateShader, glShaderSource, glCompileShader, glCreateProgram, glAttachShader, glLinkProgram, glUseProgram, glGetShaderiv, glGetShaderInfoLog, glGetProgramiv, glGetProgramInfoLog, glGetAttribLocation, glGetUniformLocation, glUniformMatrix4fv or gl_UniformMatrix3fv not found"); + exit(1); + } +} + +const ourGLchar *vertexShaderSource[] = { + "/**", + " * From the OpenGL Programming wikibook: http://en.wikibooks.org/wiki/GLSL_Programming/GLUT/Smooth_Specular_Highlights", + " * This file is in the public domain.", + " * Contributors: Sylvain Beucler", + " */", + "attribute vec3 fg_coord;", + "attribute vec3 fg_normal;", + "varying vec4 position; /* position of the vertex (and fragment) in world space */", + "varying vec3 varyingNormalDirection; /* surface normal vector in world space */", + "uniform mat4 m, p; /* don't need v, as always identity in our demo */", + "uniform mat3 m_3x3_inv_transp;", + " ", + "void main()", + "{", + " vec4 fg_coord4 = vec4(fg_coord, 1.0);", + " position = m * fg_coord4;", + " varyingNormalDirection = normalize(m_3x3_inv_transp * fg_normal);", + " ", + " mat4 mvp = p*m; /* normally p*v*m */", + " gl_Position = mvp * fg_coord4;", + "}" +}; + +const ourGLchar *fragmentShaderSource[] = { + "/**", + " * From the OpenGL Programming wikibook: http://en.wikibooks.org/wiki/GLSL_Programming/GLUT/Smooth_Specular_Highlights", + " * This file is in the public domain.", + " * Contributors: Martin Kraus, Sylvain Beucler", + " */", + "varying vec4 position; /* position of the vertex (and fragment) in world space */", + "varying vec3 varyingNormalDirection; /* surface normal vector in world space */", + "/* uniform mat4 v_inv; // in this demo, the view matrix is always an identity matrix */", + " ", + "struct lightSource", + "{", + " vec4 position;", + " vec4 diffuse;", + " vec4 specular;", + " float constantAttenuation, linearAttenuation, quadraticAttenuation;", + " float spotCutoff, spotExponent;", + " vec3 spotDirection;", + "};", + "lightSource light0 = lightSource(", + " vec4(2.0, 5.0, 5.0, 0.0),", + " vec4(1.0, 1.0, 1.0, 1.0),", + " vec4(1.0, 1.0, 1.0, 1.0),", + " 0.0, 1.0, 0.0,", + " 180.0, 0.0,", + " vec3(0.0, 0.0, 0.0)", + ");", + "vec4 scene_ambient = vec4(0.2, 0.2, 0.2, 1.0);", + " ", + "struct material", + "{", + " vec4 ambient;", + " vec4 diffuse;", + " vec4 specular;", + " float shininess;", + "};", + "material frontMaterial = material(", + " vec4(1.0, 0.0, 0.0, 1.0),", + " vec4(1.0, 0.0, 0.0, 1.0),", + " vec4(1.0, 1.0, 1.0, 1.0),", + " 100.0", + ");", + " ", + "void main()", + "{", + " vec3 normalDirection = normalize(varyingNormalDirection);", + " /* vec3 viewDirection = normalize(vec3(v_inv * vec4(0.0, 0.0, 0.0, 1.0) - position)); */", + " vec3 viewDirection = normalize(vec3(vec4(0.0, 0.0, 0.0, 1.0) - position)); /* in this demo, the view matrix is always an identity matrix */", + " vec3 lightDirection;", + " float attenuation;", + " ", + " if (0.0 == light0.position.w) /* directional light? */", + " {", + " attenuation = 1.0; /* no attenuation */", + " lightDirection = normalize(vec3(light0.position));", + " } ", + " else /* point light or spotlight (or other kind of light) */", + " {", + " vec3 positionToLightSource = vec3(light0.position - position);", + " float distance = length(positionToLightSource);", + " lightDirection = normalize(positionToLightSource);", + " attenuation = 1.0 / (light0.constantAttenuation", + " + light0.linearAttenuation * distance", + " + light0.quadraticAttenuation * distance * distance);", + " ", + " if (light0.spotCutoff <= 90.0) /* spotlight? */", + " {", + " float clampedCosine = max(0.0, dot(-lightDirection, light0.spotDirection));", + " if (clampedCosine < cos(radians(light0.spotCutoff))) /* outside of spotlight cone? */", + " {", + " attenuation = 0.0;", + " }", + " else", + " {", + " attenuation = attenuation * pow(clampedCosine, light0.spotExponent); ", + " }", + " }", + " }", + " ", + " vec3 ambientLighting = vec3(scene_ambient) * vec3(frontMaterial.ambient);", + " ", + " vec3 diffuseReflection = attenuation ", + " * vec3(light0.diffuse) * vec3(frontMaterial.diffuse)", + " * max(0.0, dot(normalDirection, lightDirection));", + " ", + " vec3 specularReflection;", + " if (dot(normalDirection, lightDirection) < 0.0) /* light source on the wrong side? */", + " {", + " specularReflection = vec3(0.0, 0.0, 0.0); /* no specular reflection */", + " }", + " else /* light source on the right side */", + " {", + " specularReflection = attenuation * vec3(light0.specular) * vec3(frontMaterial.specular) ", + " * pow(max(0.0, dot(reflect(-lightDirection, normalDirection), viewDirection)), frontMaterial.shininess);", + " }", + " ", + " gl_FragColor = vec4(ambientLighting + diffuseReflection + specularReflection, 1.0);", + "}" +}; + +GLint getAttribOrUniformLocation(const char* name, GLuint program, GLboolean isAttrib) +{ + if (isAttrib) + { + GLint attrib = gl_GetAttribLocation(program, name); + if (attrib == -1) + { + fprintf(stderr, "Warning: Could not bind attrib %s\n", name); + } + + checkError ("getAttribOrUniformLocation"); + return attrib; + } + else + { + GLint uniform = gl_GetUniformLocation(program, name); + if (uniform == -1) + { + fprintf(stderr, "Warning: Could not bind uniform %s\n", name); + } + + checkError ("getAttribOrUniformLocation"); + return uniform; + } +} + +GLuint program; +GLint attribute_fg_coord = -1, attribute_fg_normal = -1; +GLint uniform_m = -1, uniform_p = -1, uniform_m_3x3_inv_transp = -1; +GLint shaderReady = 0; /* Set to 1 when all initialization went well, to -1 when shader somehow unusable. */ + + + +void compileAndCheck(GLuint shader) +{ + GLint status; + gl_CompileShader (shader); + gl_GetShaderiv (shader, GL_COMPILE_STATUS, &status); + if (status == GL_FALSE) { + GLint infoLogLength; + ourGLchar *infoLog; + gl_GetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLength); + infoLog = (ourGLchar*) malloc (infoLogLength); + gl_GetShaderInfoLog (shader, infoLogLength, NULL, infoLog); + fprintf (stderr, "compile log: %s\n", infoLog); + free (infoLog); + } + checkError ("compileAndCheck"); +} + +GLuint compileShaderSource(GLenum type, GLsizei count, const ourGLchar **string) +{ + GLuint shader = gl_CreateShader (type); + gl_ShaderSource (shader, count, string, NULL); + + checkError ("compileShaderSource"); + + compileAndCheck (shader); + return shader; +} + +void linkAndCheck(GLuint program) +{ + GLint status; + gl_LinkProgram (program); + gl_GetProgramiv (program, GL_LINK_STATUS, &status); + if (status == GL_FALSE) { + GLint infoLogLength; + ourGLchar *infoLog; + gl_GetProgramiv (program, GL_INFO_LOG_LENGTH, &infoLogLength); + infoLog = (ourGLchar*) malloc (infoLogLength); + gl_GetProgramInfoLog (program, infoLogLength, NULL, infoLog); + fprintf (stderr, "link log: %s\n", infoLog); + free (infoLog); + } + checkError ("linkAndCheck"); +} + +void createProgram(GLuint vertexShader, GLuint fragmentShader) +{ + program = gl_CreateProgram (); + if (vertexShader != 0) { + gl_AttachShader (program, vertexShader); + } + if (fragmentShader != 0) { + gl_AttachShader (program, fragmentShader); + } + + checkError ("createProgram"); + + linkAndCheck (program); +} + +void initShader(void) +{ + const GLsizei vertexShaderLines = sizeof(vertexShaderSource) / sizeof(ourGLchar*); + GLuint vertexShader = + compileShaderSource (GL_VERTEX_SHADER, vertexShaderLines, vertexShaderSource); + + const GLsizei fragmentShaderLines = sizeof(fragmentShaderSource) / sizeof(ourGLchar*); + GLuint fragmentShader = + compileShaderSource (GL_FRAGMENT_SHADER, fragmentShaderLines, fragmentShaderSource); + + checkError ("initShader - 1"); + + createProgram (vertexShader, fragmentShader); + + gl_UseProgram (program); + + attribute_fg_coord = getAttribOrUniformLocation("fg_coord" , program, GL_TRUE); + attribute_fg_normal = getAttribOrUniformLocation("fg_normal" , program, GL_TRUE); + uniform_m = getAttribOrUniformLocation("m" , program, GL_FALSE); + uniform_p = getAttribOrUniformLocation("p" , program, GL_FALSE); + uniform_m_3x3_inv_transp= getAttribOrUniformLocation("m_3x3_inv_transp" , program, GL_FALSE); + + gl_UseProgram (0); + + if (attribute_fg_coord==-1 || attribute_fg_normal==-1 || + uniform_m==-1 || uniform_p==-1 || uniform_m_3x3_inv_transp==-1) + shaderReady = -1; + else + shaderReady = 1; + + checkError ("initShader - 2"); +} + +/* + * This macro is only intended to be used on arrays, of course. + */ +#define NUMBEROF(x) ((sizeof(x))/(sizeof(x[0]))) + +/* + * These global variables control which object is drawn, + * and how it is drawn. No object uses all of these + * variables. + */ +static int function_index; +static int slices = 16; +static int stacks = 16; +static double irad = .25; +static double orad = 1.0; /* doubles as size for objects other than Torus */ +static int depth = 4; +static double offset[ 3 ] = { 0, 0, 0 }; +static GLboolean show_info = GL_TRUE; +static float ar; +static GLboolean persProject = GL_TRUE; +static GLboolean animateXRot = GL_FALSE; +static GLboolean useShader = GL_FALSE; +static GLboolean visNormals = GL_FALSE; +static GLboolean flat; + +/* + * Enum to tell drawSizeInfo what to draw for each object + */ +#define GEO_NO_SIZE 0 +#define GEO_SIZE 1 +#define GEO_SCALE 2 +#define GEO_INNER_OUTER_RAD 4 +#define GEO_RAD 8 +#define GEO_BASE_HEIGHT 16 +#define GEO_RAD_HEIGHT 32 + +/* + * These one-liners draw particular objects, fetching appropriate + * information from the above globals. They are just thin wrappers + * for the FreeGLUT objects. + */ +static void drawSolidTetrahedron(void) { glutSolidTetrahedron (); } +static void drawWireTetrahedron(void) { glutWireTetrahedron (); } +static void drawSolidCube(void) { glutSolidCube(orad); } /* orad doubles as size input */ +static void drawWireCube(void) { glutWireCube(orad); } /* orad doubles as size input */ +static void drawSolidOctahedron(void) { glutSolidOctahedron (); } +static void drawWireOctahedron(void) { glutWireOctahedron (); } +static void drawSolidDodecahedron(void) { glutSolidDodecahedron (); } +static void drawWireDodecahedron(void) { glutWireDodecahedron (); } +static void drawSolidRhombicDodecahedron(void) { glutSolidRhombicDodecahedron (); } +static void drawWireRhombicDodecahedron(void) { glutWireRhombicDodecahedron (); } +static void drawSolidIcosahedron(void) { glutSolidIcosahedron (); } +static void drawWireIcosahedron(void) { glutWireIcosahedron (); } +static void drawSolidSierpinskiSponge(void) { glutSolidSierpinskiSponge (depth, offset, orad);} /* orad doubles as size input */ +static void drawWireSierpinskiSponge(void) { glutWireSierpinskiSponge (depth, offset, orad); } /* orad doubles as size input */ +static void drawSolidTorus(void) { glutSolidTorus(irad,orad,slices,stacks); } +static void drawWireTorus(void) { glutWireTorus (irad,orad,slices,stacks); } +static void drawSolidSphere(void) { glutSolidSphere(orad,slices,stacks); } /* orad doubles as size input */ +static void drawWireSphere(void) { glutWireSphere(orad,slices,stacks); } /* orad doubles as size input */ +static void drawSolidCone(void) { glutSolidCone(irad,orad,slices,stacks); } /* irad doubles as base input, and orad as height input */ +static void drawWireCone(void) { glutWireCone(irad,orad,slices,stacks); } /* irad doubles as base input, and orad as height input */ +static void drawSolidCylinder(void) { glutSolidCylinder(irad,orad,slices,stacks); } /* irad doubles as radius input, and orad as height input */ +static void drawWireCylinder(void) { glutWireCylinder(irad,orad,slices,stacks); } /* irad doubles as radius input, and orad as height input */ +/* per Glut manpage, it should be noted that the teapot is rendered + * with clockwise winding for front facing polygons... + * Same for the teacup and teaspoon + */ +static void drawSolidTeapot(void) +{ glFrontFace(GL_CW); glutSolidTeapot(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawWireTeapot(void) +{ glFrontFace(GL_CW); glutWireTeapot(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawSolidTeacup(void) +{ glFrontFace(GL_CW); glutSolidTeacup(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawWireTeacup(void) +{ glFrontFace(GL_CW); glutWireTeacup(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawSolidTeaspoon(void) +{ glFrontFace(GL_CW); glutSolidTeaspoon(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} +static void drawWireTeaspoon(void) +{ glFrontFace(GL_CW); glutWireTeaspoon(orad); glFrontFace(GL_CCW); /* orad doubles as size input */} + +#define RADIUSFAC 0.70710678118654752440084436210485f + +static void drawSolidCuboctahedron(void) +{ + GLfloat radius = RADIUSFAC*(GLfloat)orad; /* orad doubles as size */ + glBegin( GL_TRIANGLES ); + glNormal3d( 0.577350269189, 0.577350269189, 0.577350269189); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius ); glVertex3d( radius, 0.0, radius ); + glNormal3d( 0.577350269189, 0.577350269189,-0.577350269189); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius ); + glNormal3d( 0.577350269189,-0.577350269189, 0.577350269189); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius ); + glNormal3d( 0.577350269189,-0.577350269189,-0.577350269189); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius ); glVertex3d( radius, 0.0,-radius ); + glNormal3d(-0.577350269189, 0.577350269189, 0.577350269189); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0, radius, radius ); + glNormal3d(-0.577350269189, 0.577350269189,-0.577350269189); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, 0.0,-radius ); + glNormal3d(-0.577350269189,-0.577350269189, 0.577350269189); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius, 0.0, radius ); + glNormal3d(-0.577350269189,-0.577350269189,-0.577350269189); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius ); + glEnd(); + + glBegin( GL_QUADS ); + glNormal3d( 1.0, 0.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0,-radius ); + glNormal3d(-1.0, 0.0, 0.0 ); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0, radius ); + glNormal3d( 0.0, 1.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius ); + glNormal3d( 0.0,-1.0, 0.0 ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius ); + glNormal3d( 0.0, 0.0, 1.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0, radius, radius ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius ); + glNormal3d( 0.0, 0.0,-1.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius ); + glEnd(); +} + +static void drawWireCuboctahedron(void) +{ + GLfloat radius = RADIUSFAC*(GLfloat)orad; /* orad doubles as size */ + glBegin( GL_LINE_LOOP ); + glNormal3d( 1.0, 0.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( radius, 0.0,-radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d(-1.0, 0.0, 0.0 ); glVertex3d(-radius, radius, 0.0 ); glVertex3d(-radius, 0.0,-radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d(-radius, 0.0, radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d( 0.0, 1.0, 0.0 ); glVertex3d( radius, radius, 0.0 ); glVertex3d( 0.0, radius,-radius ); glVertex3d(-radius, radius, 0.0 ); glVertex3d( 0.0, radius, radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d( 0.0,-1.0, 0.0 ); glVertex3d( radius,-radius, 0.0 ); glVertex3d( 0.0,-radius, radius ); glVertex3d(-radius,-radius, 0.0 ); glVertex3d( 0.0,-radius,-radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d( 0.0, 0.0, 1.0 ); glVertex3d( radius, 0.0, radius ); glVertex3d( 0.0, radius, radius ); glVertex3d(-radius, 0.0, radius ); glVertex3d( 0.0,-radius, radius ); + glEnd(); + glBegin( GL_LINE_LOOP ); + glNormal3d( 0.0, 0.0,-1.0 ); glVertex3d( radius, 0.0,-radius ); glVertex3d( 0.0,-radius,-radius ); glVertex3d(-radius, 0.0,-radius ); glVertex3d( 0.0, radius,-radius ); + glEnd(); +} + +#undef RADIUSFAC + +/* + * This structure defines an entry in our function-table. + */ +typedef struct +{ + const char * const name; + void (*solid) (void); + void (*wire) (void); + int drawSizeInfoFlag; +} entry; + +#define ENTRY(e,f) {#e, drawSolid##e, drawWire##e,f} +static const entry table [] = +{ + ENTRY (Tetrahedron,GEO_NO_SIZE), + ENTRY (Cube,GEO_SIZE), + ENTRY (Octahedron,GEO_NO_SIZE), + ENTRY (Dodecahedron,GEO_NO_SIZE), + ENTRY (RhombicDodecahedron,GEO_NO_SIZE), + ENTRY (Icosahedron,GEO_NO_SIZE), + ENTRY (SierpinskiSponge,GEO_SCALE), + ENTRY (Teapot,GEO_SIZE), + ENTRY (Teacup,GEO_SIZE), + ENTRY (Teaspoon,GEO_SIZE), + ENTRY (Torus,GEO_INNER_OUTER_RAD), + ENTRY (Sphere,GEO_RAD), + ENTRY (Cone,GEO_BASE_HEIGHT), + ENTRY (Cylinder,GEO_RAD_HEIGHT), + ENTRY (Cuboctahedron,GEO_SIZE) /* This one doesn't work when in shader mode and is then skipped */ +}; +#undef ENTRY + +/*! + Does printf()-like work using freeglut + glutBitmapString(). Uses a fixed font. Prints + at the indicated row/column position. + + Limitation: Cannot address pixels. + Limitation: Renders in screen coords, not model coords. +*/ +static void shapesPrintf (int row, int col, const char *fmt, ...) +{ + static char buf[256]; + int viewport[4]; + void *font = GLUT_BITMAP_9_BY_15; + va_list args; + + va_start(args, fmt); +#if defined(WIN32) && !defined(__CYGWIN__) + (void) _vsnprintf (buf, sizeof(buf), fmt, args); +#else + (void) vsnprintf (buf, sizeof(buf), fmt, args); +#endif + va_end(args); + + glGetIntegerv(GL_VIEWPORT,viewport); + + glPushMatrix(); + glLoadIdentity(); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + + glOrtho(0,viewport[2],0,viewport[3],-1,1); + + glRasterPos2i + ( + glutBitmapWidth(font, ' ') * col, + - glutBitmapHeight(font) * row + viewport[3] + ); + glutBitmapString (font, (unsigned char*)buf); + + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); +} + +/* Print info about the about the current shape and render state on the screen */ +static void DrawSizeInfo(int *row) +{ + switch (table [function_index].drawSizeInfoFlag) + { + case GEO_NO_SIZE: + break; + case GEO_SIZE: + shapesPrintf ((*row)++, 1, "Size Up Down : %f", orad); + break; + case GEO_SCALE: + shapesPrintf ((*row)++, 1, "Scale Up Down : %f", orad); + break; + case GEO_INNER_OUTER_RAD: + shapesPrintf ((*row)++, 1, "Inner radius Left Right: %f", irad); + shapesPrintf ((*row)++, 1, "Outer radius Up Down : %f", orad); + break; + case GEO_RAD: + shapesPrintf ((*row)++, 1, "Radius Up Down : %f", orad); + break; + case GEO_BASE_HEIGHT: + shapesPrintf ((*row)++, 1, "Base Left Right: %f", irad); + shapesPrintf ((*row)++, 1, "Height Up Down : %f", orad); + break; + case GEO_RAD_HEIGHT: + shapesPrintf ((*row)++, 1, "Radius Left Right: %f", irad); + shapesPrintf ((*row)++, 1, "Height Up Down : %f", orad); + break; + } +} + +static void drawInfo() +{ + int row = 1; + shapesPrintf (row++, 1, "Shape PgUp PgDn: %s", table [function_index].name); + shapesPrintf (row++, 1, "Slices +-: %d Stacks <>: %d", slices, stacks); + shapesPrintf (row++, 1, "nSides +-: %d nRings <>: %d", slices, stacks); + shapesPrintf (row++, 1, "Depth (): %d", depth); + DrawSizeInfo(&row); + if (persProject) + shapesPrintf (row++, 1, "Perspective projection (p)"); + else + shapesPrintf (row++, 1, "Orthographic projection (p)"); + if (useShader) { + shapesPrintf (row++, 1, "Using shader (s)"); + } else { + shapesPrintf (row++, 1, "Using fixed function pipeline (s)"); + if (flat) + shapesPrintf (row++, 1, "Flat shading (f)"); + else + shapesPrintf (row++, 1, "Smooth shading (f)"); + } + if (animateXRot) + shapesPrintf (row++, 1, "2D rotation (r)"); + else + shapesPrintf (row++, 1, "1D rotation (r)"); + shapesPrintf (row++, 1, "visualizing normals: %i (n)",visNormals); +} + +/* GLUT callback Handlers */ +static void +resize(int width, int height) +{ + ar = (float) width / (float) height; + + glViewport(0, 0, width, height); +} + +static void display(void) +{ + const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0; + const double a = t*89.0; + const double b = (animateXRot?t:1)*67.0; + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glutSetOption(GLUT_GEOMETRY_VISUALIZE_NORMALS,visNormals); /* Normals visualized or not? */ + + glShadeModel(flat ? GL_FLAT : GL_SMOOTH); /* flat or gouraud shading */ + + if (useShader && !shaderReady) + initShader(); + + if (useShader && shaderReady) + { + /* setup use of shader (and vertex buffer by FreeGLUT) */ + gl_UseProgram (program); + glutSetVertexAttribCoord3(attribute_fg_coord); + glutSetVertexAttribNormal(attribute_fg_normal); + /* There is also a glutSetVertexAttribTexCoord2, which is used only when drawing the teapot, teacup or teaspoon */ + + gl_matrix_mode(GL_PROJECTION); + gl_load_identity(); + if (persProject) + gl_frustum(-ar, ar, -1.f, 1.f, 2.f, 100.f); + else + gl_ortho(-ar*3, ar*3, -3.f, 3.f, 2.f, 100.f); + gl_UniformMatrix4fv (uniform_p, 1, GL_FALSE, get_matrix(GL_PROJECTION)); + + + gl_matrix_mode(GL_MODELVIEW); + gl_load_identity(); + + gl_push_matrix(); + /* Not in reverse order like normal OpenGL, our util library multiplies the matrices in the order they are specified in */ + gl_rotatef((float)a,0,0,1); + gl_rotatef((float)b,1,0,0); + gl_translatef(0,1.2f,-6); + gl_UniformMatrix4fv (uniform_m , 1, GL_FALSE, get_matrix(GL_MODELVIEW)); + gl_UniformMatrix3fv (uniform_m_3x3_inv_transp, 1, GL_FALSE, get_inv_transpose_3x3(GL_MODELVIEW)); + table [function_index].solid (); + gl_pop_matrix(); + + gl_push_matrix(); + gl_rotatef((float)a,0,0,1); + gl_rotatef((float)b,1,0,0); + gl_translatef(0,-1.2f,-6); + gl_UniformMatrix4fv (uniform_m , 1, GL_FALSE, get_matrix(GL_MODELVIEW)); + gl_UniformMatrix3fv (uniform_m_3x3_inv_transp, 1, GL_FALSE, get_inv_transpose_3x3(GL_MODELVIEW)); + table [function_index].wire (); + gl_pop_matrix(); + + gl_UseProgram (0); + glutSetVertexAttribCoord3(-1); + glutSetVertexAttribNormal(-1); + + checkError ("display"); + } + else + { + /* fixed function pipeline */ + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + if (persProject) + glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0); + else + glOrtho(-ar*3, ar*3, -3.0, 3.0, 2.0, 100.0); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glEnable(GL_LIGHTING); + + glColor3d(1,0,0); + + glPushMatrix(); + glTranslated(0,1.2,-6); + glRotated(b,1,0,0); + glRotated(a,0,0,1); + table [function_index].solid (); + glPopMatrix(); + + glPushMatrix(); + glTranslated(0,-1.2,-6); + glRotated(b,1,0,0); + glRotated(a,0,0,1); + table [function_index].wire (); + glPopMatrix(); + + glDisable(GL_LIGHTING); + glColor3d(0.1,0.1,0.4); + } + + if( show_info ) + /* print info to screen */ + drawInfo(); + else + /* print to command line instead */ + printf ( "Shape %d slides %d stacks %d\n", function_index, slices, stacks ) ; + + glutSwapBuffers(); +} + + +static void +key(unsigned char key, int x, int y) +{ + switch (key) + { + case 27 : + case 'Q': + case 'q': glutLeaveMainLoop () ; break; + + case 'I': + case 'i': show_info=!show_info; break; + + case '=': + case '+': slices++; break; + + case '-': + case '_': if( slices > -1 ) slices--; break; + + case ',': + case '<': if( stacks > -1 ) stacks--; break; + + case '.': + case '>': stacks++; break; + + case '9': + case '(': if( depth > -1 ) depth--; break; + + case '0': + case ')': ++depth; break; + + case 'P': + case 'p': persProject=!persProject; break; + + case 'R': + case 'r': animateXRot=!animateXRot; break; + + case 'S': + case 's': + useShader=!useShader; + /* Cuboctahedron can't be shown when in shader mode, move to next */ + if (useShader && NUMBEROF (table)-1 == ( unsigned )function_index) + function_index = 0; + break; + + case 'F': + case 'f': + flat ^= 1; + break; + + case 'N': + case 'n': visNormals=!visNormals; break; + + default: + break; + } + + glutPostRedisplay(); +} + +static void special (int key, int x, int y) +{ + switch (key) + { + case GLUT_KEY_PAGE_UP: ++function_index; break; + case GLUT_KEY_PAGE_DOWN: --function_index; break; + case GLUT_KEY_UP: orad *= 2; break; + case GLUT_KEY_DOWN: orad /= 2; break; + + case GLUT_KEY_RIGHT: irad *= 2; break; + case GLUT_KEY_LEFT: irad /= 2; break; + + default: + break; + } + + if (0 > function_index) + function_index = NUMBEROF (table) - 1; + + if (NUMBEROF (table) <= ( unsigned )function_index) + function_index = 0; + + /* Cuboctahedron can't be shown when in shader mode, skip it */ + if (useShader && NUMBEROF (table)-1 == ( unsigned )function_index) + { + if (key==GLUT_KEY_PAGE_UP) + function_index = 0; + else + function_index -= 1; + } +} + + +static void +idle(void) +{ + glutPostRedisplay(); +} + +const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f }; +const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; +const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; +const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f }; + +const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f }; +const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f }; +const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; +const GLfloat high_shininess[] = { 100.0f }; + +/* Program entry point */ + +int +main(int argc, char *argv[]) +{ + glutInitWindowSize(800,600); + glutInitWindowPosition(40,40); + glutInit(&argc, argv); + glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE); + + glutCreateWindow("FreeGLUT Shapes"); + + glutReshapeFunc(resize); + glutDisplayFunc(display); + glutKeyboardFunc(key); + glutSpecialFunc(special); + glutIdleFunc(idle); + + glutSetOption ( GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION ) ; + + glClearColor(1,1,1,1); + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); + + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LESS); + + glEnable(GL_LIGHT0); + glEnable(GL_NORMALIZE); + glEnable(GL_COLOR_MATERIAL); + + glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); + glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); + glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); + glLightfv(GL_LIGHT0, GL_POSITION, light_position); + + glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); + glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); + glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); + glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess); + + initExtensionEntries(); + + glutMainLoop(); + +#ifdef _MSC_VER + /* DUMP MEMORY LEAK INFORMATION */ + _CrtDumpMemoryLeaks () ; +#endif + + return EXIT_SUCCESS; +} diff --git a/linux/templates/GLFW.ico b/linux/templates/GLFW.ico new file mode 100644 index 00000000..2a515ce7 Binary files /dev/null and b/linux/templates/GLFW.ico differ diff --git a/linux/templates/GLFW.template b/linux/templates/GLFW.template new file mode 100644 index 00000000..e577055e --- /dev/null +++ b/linux/templates/GLFW.template @@ -0,0 +1,39 @@ +[Template] +ver=2 +Name=GLFW +Description=A simple GLFW program +Description[zh_CN]=一个简单的GLFW程序 +Icon=GLFW.ico +Category=3D +Category[zh_CN]=3D + +[Unit0] +CppName=main.cpp +Cpp=GLFW_main.cpp.txt + +[Unit1] +CppName=shader.h +Cpp=GLFW_shader.h.txt + +[Unit2] +CppName=shader.frag +Cpp=GLFW_shader.frag.txt + +[Unit3] +CppName=shader.vs +Cpp=GLFW_shader.vs.txt + +[Project] +UnitCount=4 +Type=1 +IsCpp=1 +Compiler= +CppCompiler= +Linker=-lglfw3 -lglew32 -lopengl32 -lwinmm -lgdi32_@@__@@_ +CompilerSettings=0000000000110000000001000 +CompilerSet=1 +UseUTF8=0 +StaticLink=1 +AddCharset=1 +IncludeVersionInfo=0 +SupportXPThemes=0 diff --git a/linux/templates/GLFW_main.cpp.txt b/linux/templates/GLFW_main.cpp.txt new file mode 100644 index 00000000..3d5cfdae --- /dev/null +++ b/linux/templates/GLFW_main.cpp.txt @@ -0,0 +1,111 @@ +#include +// GLEW +#define GLEW_STATIC +#include +// GLFW +#include +// Other includes +#include "shader.h" + +// Function prototypes +void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); + +// Window dimensions +const GLuint WIDTH = 800, HEIGHT = 600; + +// The MAIN function, from here we start the application and run the game loop +int main() +{ + // Init GLFW + glfwInit(); + // Set all the required options for GLFW + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); + + // Create a GLFWwindow object that we can use for GLFW's functions + GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); + glfwMakeContextCurrent(window); + + // Set the required callback functions + glfwSetKeyCallback(window, key_callback); + + // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions + glewExperimental = GL_TRUE; + // Initialize GLEW to setup the OpenGL Function pointers + glewInit(); + + // Define the viewport dimensions + glViewport(0, 0, WIDTH, HEIGHT); + + + //ȡshaderļ룬shader.h + Shader ourShader("shader.vs", "shader.frag"); + + + // һά飬ÿһԣǰλԣɫ + GLfloat vertices[] = { + // Positions // Colors + 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Right + -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // Bottom Left + 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // Top + }; + GLuint VBO, VAO;//㻺壬ڹ + glGenVertexArrays(1, &VAO);//飬һһ޶ʶ + glGenBuffers(1, &VBO);//㻺壬һһ޶ʶ + + glBindVertexArray(VAO);//󶨶 + glBindBuffer(GL_ARRAY_BUFFER, VBO);//󶨶㻺 + //ָԴΪverticesĸԿιݣGL_STATIC_DRWAı + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); + + // ָԵĽʽδӶ㻺ȡӦĶԺӦɫԡ˵ɫ֪ȥĸԷɫ + //ÿһԣ2֣һλԣɫԣÿһλúɫ + + //ɫʹlayout(location = 0)positionԵλֵ(Location)˵һԷ + //λԵάȣͣ:Ƿ׼壬λԵֽڳȣڻеƫʼλ + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); + glEnableVertexAttribArray(0);//0ΪĬǽõ + + // һӦɫеlayout (location = 1) in vec3 color;˵ɫԵƫverticesһ + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); + glEnableVertexAttribArray(1);//1. + + //(Vertex Array Object, VAO)ĺôǣöָʱֻҪĴִһΣ֮ٻʱֻҪӦVAOˡѭеİٽ + glBindVertexArray(0); // VAO + // Game loop + while (!glfwWindowShouldClose(window)) + { + // ¼ӦĻصĵkey_callback + glfwPollEvents(); + + // Render + // Clear the colorbuffer + glClearColor(0.2f, 0.3f, 0.3f, 1.0f);//Ⱦɫ̨ + glClear(GL_COLOR_BUFFER_BIT);//ǰ̨ + + // Draw the triangle + ourShader.Use();//ɫ + glBindVertexArray(VAO);//ÿѭã󶨺VAO + glDrawArrays(GL_TRIANGLES, 0, 3); + glBindVertexArray(0);// + + // Swap the screen buffers + glfwSwapBuffers(window); + } + // Properly de-allocate all resources once they've outlived their purpose + glDeleteVertexArrays(1, &VAO); + glDeleteBuffers(1, &VBO); + // Terminate GLFW, clearing any resources allocated by GLFW. + glfwTerminate(); + return 0; +} + + +// Is called whenever a key is pressed/released via GLFW +void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) +{ + if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) + glfwSetWindowShouldClose(window, GL_TRUE); +} diff --git a/linux/templates/GLFW_shader.frag.txt b/linux/templates/GLFW_shader.frag.txt new file mode 100644 index 00000000..00bbbd11 --- /dev/null +++ b/linux/templates/GLFW_shader.frag.txt @@ -0,0 +1,8 @@ +#version 330 core +in vec3 ourColor; +out vec4 color; + +void main() +{ + color = vec4(ourColor, 1.0f); +} diff --git a/linux/templates/GLFW_shader.h.txt b/linux/templates/GLFW_shader.h.txt new file mode 100644 index 00000000..01387630 --- /dev/null +++ b/linux/templates/GLFW_shader.h.txt @@ -0,0 +1,98 @@ +#ifndef SHADER_H +#define SHADER_H + +#include +#include +#include +#include + +#include + +class Shader +{ +public: + GLuint Program; + // Constructor generates the shader on the fly + Shader(const GLchar* vertexPath, const GLchar* fragmentPath) + { + // 1. Retrieve the vertex/fragment source code from filePath + std::string vertexCode; + std::string fragmentCode; + std::ifstream vShaderFile; + std::ifstream fShaderFile; + // ensures ifstream objects can throw exceptions: + vShaderFile.exceptions(std::ifstream::badbit); + fShaderFile.exceptions(std::ifstream::badbit); + try + { + // Open files + vShaderFile.open(vertexPath); + fShaderFile.open(fragmentPath); + std::stringstream vShaderStream, fShaderStream; + // Read file's buffer contents into streams + vShaderStream << vShaderFile.rdbuf(); + fShaderStream << fShaderFile.rdbuf(); + // close file handlers + vShaderFile.close(); + fShaderFile.close(); + // Convert stream into string + vertexCode = vShaderStream.str(); + fragmentCode = fShaderStream.str(); + } + catch (std::ifstream::failure e) + { + std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl; + } + const GLchar* vShaderCode = vertexCode.c_str(); + const GLchar * fShaderCode = fragmentCode.c_str(); + // 2. Compile shaders + GLuint vertex, fragment; + GLint success; + GLchar infoLog[512]; + // Vertex Shader + vertex = glCreateShader(GL_VERTEX_SHADER);//ɫ + glShaderSource(vertex, 1, &vShaderCode, NULL);//ָԴ + glCompileShader(vertex);//ɫ + // Print compile errors if any + glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);//鿴Ƿɹ + if (!success) + { + glGetShaderInfoLog(vertex, 512, NULL, infoLog); + std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; + } + // Fragment Shader + fragment = glCreateShader(GL_FRAGMENT_SHADER);//Ƭɫ + glShaderSource(fragment, 1, &fShaderCode, NULL); + glCompileShader(fragment); + // Print compile errors if any + glGetShaderiv(fragment, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(fragment, 512, NULL, infoLog); + std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; + } + // Shader Program + this->Program = glCreateProgram();//ɫ + glAttachShader(this->Program, vertex);//ɫ + glAttachShader(this->Program, fragment);//Ƭɫ + glLinkProgram(this->Program);//ӱ + // Print linking errors if any + glGetProgramiv(this->Program, GL_LINK_STATUS, &success); + if (!success) + { + glGetProgramInfoLog(this->Program, 512, NULL, infoLog); + std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; + } + // Delete the shaders as they're linked into our program now and no longer necessery + glDeleteShader(vertex); + glDeleteShader(fragment); + + } + // Uses the current shader + void Use() + { + glUseProgram(this->Program); + } +}; + +#endif diff --git a/linux/templates/GLFW_shader.vs.txt b/linux/templates/GLFW_shader.vs.txt new file mode 100644 index 00000000..b2141e1b --- /dev/null +++ b/linux/templates/GLFW_shader.vs.txt @@ -0,0 +1,11 @@ +#version 330 core +layout (location = 0) in vec3 position;//in locationĶйء +layout (location = 1) in vec3 color; + +out vec3 ourColor;//out 3άΪƬɫ룬 + +void main() +{ + gl_Position = vec4(position, 1.0f); + ourColor = color; +} diff --git a/linux/templates/raylib.ico b/linux/templates/raylib.ico new file mode 100644 index 00000000..14db8eab Binary files /dev/null and b/linux/templates/raylib.ico differ diff --git a/linux/templates/raylib.template b/linux/templates/raylib.template new file mode 100644 index 00000000..999d68b7 --- /dev/null +++ b/linux/templates/raylib.template @@ -0,0 +1,28 @@ +[Template] +ver=2 +Name=raylib +Name[zh_CN]=raylib +Icon=raylib.ico +Description=A simple program using raylib ( https://raylib.com ) +Description[zh_CN]=简单的raylib绘图程序 ( https://raylib.com ) +Category=Multimedia +Category[zh_CN]=多媒体 + +[Unit0] +CName=main.c +C=raylib_c.txt + +[Unit1] +Source=raylib_boom.wav +Target=boom.wav + +[Unit2] +Source=raylib_explosion.png +Target=explosion.png + +[Project] +UnitCount=3 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm_@@__@@_ + diff --git a/linux/templates/raylib_3d.template b/linux/templates/raylib_3d.template new file mode 100644 index 00000000..1a4e7134 --- /dev/null +++ b/linux/templates/raylib_3d.template @@ -0,0 +1,20 @@ +[Template] +ver=2 +Name=raylib 3D +Name[zh_CN]=raylib 3D +Icon=raylib.ico +Description=A simple 3D program using raylib ( https://raylib.com ) +Description[zh_CN]=简单的raylib 3D程序 ( https://raylib.com ) +Category=3D +Category[zh_CN]=3D + +[Unit0] +CName=main.c +C=raylib_3d_c.txt + +[Project] +UnitCount=1 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm_@@__@@_ + diff --git a/linux/templates/raylib_3d_c.txt b/linux/templates/raylib_3d_c.txt new file mode 100644 index 00000000..6cba4009 --- /dev/null +++ b/linux/templates/raylib_3d_c.txt @@ -0,0 +1,112 @@ +/******************************************************************************************* +* +* raylib [models] example - Waving cubes +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Example contributed by Codecat (@codecat) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 Codecat (@codecat) and Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include + +#include + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [models] example - waving cubes"); + + // Initialize the camera + Camera3D camera = { 0 }; + camera.position = (Vector3){ 30.0f, 20.0f, 30.0f }; + camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; + camera.fovy = 70.0f; + camera.projection = CAMERA_PERSPECTIVE; + + // Specify the amount of blocks in each direction + const int numBlocks = 15; + + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + double time = GetTime(); + + // Calculate time scale for cube position and size + float scale = (2.0f + (float)sin(time))*0.7f; + + // Move camera around the scene + double cameraTime = time*0.3; + camera.position.x = (float)cos(cameraTime)*40.0f; + camera.position.z = (float)sin(cameraTime)*40.0f; + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawGrid(10, 5.0f); + + for (int x = 0; x < numBlocks; x++) + { + for (int y = 0; y < numBlocks; y++) + { + for (int z = 0; z < numBlocks; z++) + { + // Scale of the blocks depends on x/y/z positions + float blockScale = (x + y + z)/30.0f; + + // Scatter makes the waving effect by adding blockScale over time + float scatter = sinf(blockScale*20.0f + (float)(time*4.0f)); + + // Calculate the cube position + Vector3 cubePos = { + (float)(x - numBlocks/2)*(scale*3.0f) + scatter, + (float)(y - numBlocks/2)*(scale*2.0f) + scatter, + (float)(z - numBlocks/2)*(scale*3.0f) + scatter + }; + + // Pick a color with a hue depending on cube position for the rainbow color effect + Color cubeColor = ColorFromHSV((float)(((x + y + z)*18)%360), 0.75f, 0.9f); + + // Calculate cube size + float cubeSize = (2.4f - scale)*blockScale; + + // And finally, draw the cube! + DrawCube(cubePos, cubeSize, cubeSize, cubeSize, cubeColor); + } + } + } + + EndMode3D(); + + DrawFPS(10, 10); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/linux/templates/raylib_3d_shader.template b/linux/templates/raylib_3d_shader.template new file mode 100644 index 00000000..5fe22e98 --- /dev/null +++ b/linux/templates/raylib_3d_shader.template @@ -0,0 +1,28 @@ +[Template] +ver=2 +Name=raylib 3D Shader +Name[zh_CN]=raylib 3D 着色器 +Icon=raylib.ico +Description=A 3D Shader program using raylib ( https://raylib.com ) +Description[zh_CN]=带着色器的raylib 3D程序 ( https://raylib.com ) +Category=3D +Category[zh_CN]=3D + +[Unit0] +CPPName=main.c +C=raylib_3d_shader_c.txt + +[Unit1] +Source=raylib_base.vs +Target=vertices_shader.vs + +[Unit2] +Source=raylib_base.fs +Target=fragment_shader.fs + +[Project] +UnitCount=3 +Type=1 +IsCpp=0 +linker=-lraylib -lopengl32 -lgdi32 -lwinmm_@@__@@_ + diff --git a/linux/templates/raylib_3d_shader_c.txt b/linux/templates/raylib_3d_shader_c.txt new file mode 100644 index 00000000..50a0250a --- /dev/null +++ b/linux/templates/raylib_3d_shader_c.txt @@ -0,0 +1,67 @@ +#include +#include + +int main(void) +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) + InitWindow(screenWidth, screenHeight, "raylib shader"); + + // Define the camera to look into our 3d world + Camera camera = { 0 }; + camera.position = (Vector3){ 2.0f, 4.0f, 6.0f }; // Camera position + camera.target = (Vector3){ 0.0f, 0.5f, 0.0f }; // Camera looking at point + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) + camera.fovy = 45.0f; // Camera field-of-view Y + camera.projection = CAMERA_PERSPECTIVE; // Camera mode type + + // Load plane model from a generated mesh + Model model = LoadModelFromMesh(GenMeshCube(10.0f, 10.0f, 3.3)); + + Shader shader = LoadShader("vertices_shader.vs","fragment_shader.fs"); + + // Assign out lighting shader to model + model.materials[0].shader = shader; + + SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + UpdateCamera(&camera); // Update camera + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawModel(model, Vector3Zero(), 1.0f, WHITE); + + DrawGrid(10, 1.0f); + + EndMode3D(); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + UnloadModel(model); // Unload the model + UnloadShader(shader); // Unload shader + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/linux/templates/raylib_base.fs b/linux/templates/raylib_base.fs new file mode 100644 index 00000000..6b500622 --- /dev/null +++ b/linux/templates/raylib_base.fs @@ -0,0 +1,25 @@ +#version 330 + +// Input vertex attributes (from vertex shader) +in vec2 fragTexCoord; +in vec4 fragColor; + +// Input uniform values +uniform sampler2D texture0; +uniform vec4 colDiffuse; + +// Output fragment color +out vec4 finalColor; + +// NOTE: Add here your custom variables + +void main() +{ + // Texel color fetching from texture sampler + vec4 texelColor = texture(texture0, fragTexCoord); + + // NOTE: Implement here your fragment shader code + + finalColor = texelColor*colDiffuse; +} + diff --git a/linux/templates/raylib_base.vs b/linux/templates/raylib_base.vs new file mode 100644 index 00000000..8cc2abb2 --- /dev/null +++ b/linux/templates/raylib_base.vs @@ -0,0 +1,26 @@ +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexColor; + +// Input uniform values +uniform mat4 mvp; + +// Output vertex attributes (to fragment shader) +out vec2 fragTexCoord; +out vec4 fragColor; + +// NOTE: Add here your custom variables + +void main() +{ + // Send vertex attributes to fragment shader + fragTexCoord = vertexTexCoord; + fragColor = vertexColor; + + // Calculate final vertex position + gl_Position = mvp*vec4(vertexPosition, 1.0); +} \ No newline at end of file diff --git a/linux/templates/raylib_boom.wav b/linux/templates/raylib_boom.wav new file mode 100644 index 00000000..fd18137d Binary files /dev/null and b/linux/templates/raylib_boom.wav differ diff --git a/linux/templates/raylib_c.txt b/linux/templates/raylib_c.txt new file mode 100644 index 00000000..4d58dec3 --- /dev/null +++ b/linux/templates/raylib_c.txt @@ -0,0 +1,123 @@ +/******************************************************************************************* +* +* raylib [textures] example - sprite explosion +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2019 Anata and Ramon Santamaria (@raysan5) +* Copyright (c) 2022 Roy Qu (royqh1979@gmail.com) +* +********************************************************************************************/ + +#include + +#define NUM_FRAMES_PER_LINE 5 +#define NUM_LINES 5 + +int main(void) +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [textures] example - sprite explosion"); + + InitAudioDevice(); + + // Load explosion sound + Sound fxBoom = LoadSound("boom.wav"); + + // Load explosion texture + Texture2D explosion = LoadTexture("explosion.png"); + + // Init variables for animation + float frameWidth = (float)(explosion.width/NUM_FRAMES_PER_LINE); // Sprite one frame rectangle width + float frameHeight = (float)(explosion.height/NUM_LINES); // Sprite one frame rectangle height + int currentFrame = 0; + int currentLine = 0; + + Rectangle frameRec = { 0, 0, frameWidth, frameHeight }; + Vector2 position = { 0.0f, 0.0f }; + + bool active = false; + int framesCounter = 0; + + SetTargetFPS(120); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + + // Check for mouse button pressed and activate explosion (if not active) + if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT) ) + { + position = GetMousePosition(); + active = true; + + position.x -= frameWidth/2.0f; + position.y -= frameHeight/2.0f; + + PlaySound(fxBoom); + } + + // Compute explosion animation frames + if (active) + { + framesCounter++; + + if (framesCounter > 2) + { + currentFrame++; + + if (currentFrame >= NUM_FRAMES_PER_LINE) + { + currentFrame = 0; + currentLine++; + + if (currentLine >= NUM_LINES) + { + currentLine = 0; + active = false; + } + } + + framesCounter = 0; + } + } + + frameRec.x = frameWidth*currentFrame; + frameRec.y = frameHeight*currentLine; + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + // Draw explosion required frame rectangle + if (active) DrawTextureRec(explosion, frameRec, position, WHITE); + + DrawText("Click to explode!", 440, 400, 40, DARKGRAY); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + UnloadTexture(explosion); // Unload texture + UnloadSound(fxBoom); // Unload sound + + CloseAudioDevice(); + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/linux/templates/raylib_explosion.png b/linux/templates/raylib_explosion.png new file mode 100644 index 00000000..6df1cf36 Binary files /dev/null and b/linux/templates/raylib_explosion.png differ