diff --git a/examples/Makefile b/examples/Makefile index 6ca8b6cf..a218cf9e 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -488,7 +488,8 @@ SHADERS = \ shaders/shaders_basic_lighting \ shaders/shaders_fog \ shaders/shaders_simple_mask \ - shaders/shaders_spotlight + shaders/shaders_spotlight \ + shaders/shaders_rlgl_mesh_instanced AUDIO = \ audio/audio_module_playing \ diff --git a/examples/shaders/resources/shaders/glsl330/base_lighting_instanced.vs b/examples/shaders/resources/shaders/glsl330/base_lighting_instanced.vs new file mode 100644 index 00000000..5e5430b3 --- /dev/null +++ b/examples/shaders/resources/shaders/glsl330/base_lighting_instanced.vs @@ -0,0 +1,36 @@ +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexColor; + +layout (location = 12) in mat4 instance; + +// Input uniform values +uniform mat4 mvp; + +// Output vertex attributes (to fragment shader) +out vec3 fragPosition; +out vec2 fragTexCoord; +out vec4 fragColor; +out vec3 fragNormal; + +// NOTE: Add here your custom variables + +void main() +{ + // Send vertex attributes to fragment shader + fragPosition = vec3(instance * vec4(vertexPosition, 1.0)); + fragTexCoord = vertexTexCoord; + fragColor = vertexColor; + + mat3 normalMatrix = transpose(inverse(mat3(instance))); + fragNormal = normalize(normalMatrix * vertexNormal); + + mat4 mvpi = mvp * instance; + + // Calculate final vertex position + gl_Position = mvpi * vec4(vertexPosition, 1.0); +} diff --git a/examples/shaders/shaders_rlgl_mesh_instanced.c b/examples/shaders/shaders_rlgl_mesh_instanced.c new file mode 100644 index 00000000..6ef421f2 --- /dev/null +++ b/examples/shaders/shaders_rlgl_mesh_instanced.c @@ -0,0 +1,140 @@ +/******************************************************************************************* +* +* raylib [shaders] example - rlgl module usage for instanced meshes +* +* This example uses [rlgl] module funtionality (pseudo-OpenGL 1.1 style coding) +* +* This example has been created using raylib 3.0 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2018 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#define GRAPHICS_API_OPENGL_33 +#define GLSL_VERSION 330 + +#include +#include "raylib.h" +#include "raymath.h" +#include "rlgl.h" + +#define RLIGHTS_IMPLEMENTATION +#include "rlights.h" + +//------------------------------------------------------------------------------------ +// Program main entry point +//------------------------------------------------------------------------------------ +int main(void) +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 1024; + const int screenHeight = 768; + + SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) + InitWindow(screenWidth, screenHeight, "raylib [shaders] example - rlgl module usage for instanced meshes"); + + // Define the camera to look into our 3d world + Camera camera = { 0 }; + camera.position = (Vector3){ 125.0f, 125.0f, 125.0f }; + camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; + camera.fovy = 45.0f; + camera.type = CAMERA_PERSPECTIVE; + + SetCameraMode(camera, CAMERA_FREE); + + const int count = 10000; // Number of instances to display + Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f); + + Matrix* rotations = RL_MALLOC(count * sizeof(Matrix)); // Rotation state of instances + Matrix* rotationsInc = RL_MALLOC(count * sizeof(Matrix)); // Per-frame rotation animation of instances + Matrix* translations = RL_MALLOC(count * sizeof(Matrix)); // Locations of instances + + // Scatter random cubes around + for (int i = 0; i < count; i++) + { + float x = GetRandomValue(-50, 50); + float y = GetRandomValue(-50, 50); + float z = GetRandomValue(-50, 50); + translations[i] = MatrixTranslate(x, y, z); + + x = GetRandomValue(0, 360); + y = GetRandomValue(0, 360); + z = GetRandomValue(0, 360); + Vector3 axis = Vector3Normalize((Vector3){x, y, z}); + float angle = (float)GetRandomValue(0, 10) * DEG2RAD; + + rotationsInc[i] = MatrixRotate(axis, angle); + + rotations[i] = MatrixIdentity(); + } + + Matrix* transforms = RL_MALLOC(count * sizeof(Matrix)); // Pre-multiplied transformations passed to rlgl + + Shader shader = LoadShader(FormatText("resources/shaders/glsl%i/base_lighting_instanced.vs", GLSL_VERSION), + FormatText("resources/shaders/glsl%i/lighting.fs", GLSL_VERSION)); + + // Get some shader loactions + shader.locs[LOC_MATRIX_MVP] = GetShaderLocation(shader, "mvp"); + shader.locs[LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos"); + shader.locs[LOC_MATRIX_MODEL] = GetShaderLocationAttrib(shader, "instance"); + + // ambient light level + int ambientLoc = GetShaderLocation(shader, "ambient"); + SetShaderValue(shader, ambientLoc, (float[4]){ 0.2f, 0.2f, 0.2f, 1.0f }, UNIFORM_VEC4); + + CreateLight(LIGHT_DIRECTIONAL, (Vector3){ 50, 50, 0 }, Vector3Zero(), WHITE, shader); + + Material material = LoadMaterialDefault(); + material.shader = shader; + material.maps[MAP_DIFFUSE].color = RED; + + 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 the light shader with the camera view position + float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z }; + SetShaderValue(shader, shader.locs[LOC_VECTOR_VIEW], cameraPos, UNIFORM_VEC3); + + // Apply per-instance rotations + for (int i = 0; i < count; i++) + { + rotations[i] = MatrixMultiply(rotations[i], rotationsInc[i]); + transforms[i] = MatrixMultiply(rotations[i], translations[i]); + } + + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + rlDrawMeshInstanced(cube, material, transforms, count); + EndMode3D(); + + DrawText("A CUBE OF DANCING CUBES!", 400, 10, 20, MAROON); + DrawFPS(10, 10); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/src/raylib.h b/src/raylib.h index 499650c6..15ff9554 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1372,6 +1372,7 @@ RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Def // Shader configuration functions RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location +RLAPI int GetShaderLocationAttrib(Shader shader, const char *attribName); // Get shader attribute location RLAPI void SetShaderValue(Shader shader, int uniformLoc, const void *value, int uniformType); // Set shader uniform value RLAPI void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int uniformType, int count); // Set shader uniform value vector RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) diff --git a/src/raymath.h b/src/raymath.h index 3e5e1973..783c4449 100644 --- a/src/raymath.h +++ b/src/raymath.h @@ -114,13 +114,16 @@ float z; } Vector3; - // Quaternion type - typedef struct Quaternion { + // Vector4 type + typedef struct Vector4 { float x; float y; float z; float w; - } Quaternion; + } Vector4; + + // Quaternion type + typedef Vector4 Quaternion; // Matrix type (OpenGL style 4x4 - right handed, column major) typedef struct Matrix { diff --git a/src/rlgl.h b/src/rlgl.h index 0869d118..44bcf381 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -560,6 +560,7 @@ RLAPI void rlLoadMesh(Mesh *mesh, bool dynamic); // Upl RLAPI void rlUpdateMesh(Mesh mesh, int buffer, int count); // Update vertex or index data on GPU (upload new data to one buffer) RLAPI void rlUpdateMeshAt(Mesh mesh, int buffer, int count, int index); // Update vertex or index data on GPU, at index RLAPI void rlDrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform +RLAPI void rlDrawMeshInstanced(Mesh mesh, Material material, Matrix *transforms, int count); // Draw a 3d mesh with material and transform RLAPI void rlUnloadMesh(Mesh mesh); // Unload mesh data from CPU and GPU // NOTE: There is a set of shader related functions that are available to end user, @@ -582,6 +583,7 @@ RLAPI Rectangle GetShapesTextureRec(void); // Get // Shader configuration functions RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location +RLAPI int GetShaderLocationAttrib(Shader shader, const char *attribName); // Get shader attribute location RLAPI void SetShaderValue(Shader shader, int uniformLoc, const void *value, int uniformType); // Set shader uniform value RLAPI void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int uniformType, int count); // Set shader uniform value vector RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) @@ -2860,6 +2862,113 @@ void rlDrawMesh(Mesh mesh, Material material, Matrix transform) #endif } +// Draw a 3d mesh with material and transform +void rlDrawMeshInstanced(Mesh mesh, Material material, Matrix *transforms, int count) +{ +#if defined(GRAPHICS_API_OPENGL_33) + + if (!RLGL.ExtSupported.vao) { + TRACELOG(LOG_ERROR, "VAO: Instanced rendering requires VAO support"); + return; + } + + // Bind shader program + glUseProgram(material.shader.id); + + // Upload to shader material.colDiffuse + if (material.shader.locs[LOC_COLOR_DIFFUSE] != -1) + glUniform4f(material.shader.locs[LOC_COLOR_DIFFUSE], (float)material.maps[MAP_DIFFUSE].color.r/255.0f, + (float)material.maps[MAP_DIFFUSE].color.g/255.0f, + (float)material.maps[MAP_DIFFUSE].color.b/255.0f, + (float)material.maps[MAP_DIFFUSE].color.a/255.0f); + + // Upload to shader material.colSpecular (if available) + if (material.shader.locs[LOC_COLOR_SPECULAR] != -1) + glUniform4f(material.shader.locs[LOC_COLOR_SPECULAR], (float)material.maps[MAP_SPECULAR].color.r/255.0f, + (float)material.maps[MAP_SPECULAR].color.g/255.0f, + (float)material.maps[MAP_SPECULAR].color.b/255.0f, + (float)material.maps[MAP_SPECULAR].color.a/255.0f); + + // Bind active texture maps (if available) + for (int i = 0; i < MAX_MATERIAL_MAPS; i++) + { + if (material.maps[i].texture.id > 0) + { + glActiveTexture(GL_TEXTURE0 + i); + if ((i == MAP_IRRADIANCE) || (i == MAP_PREFILTER) || (i == MAP_CUBEMAP)) + glBindTexture(GL_TEXTURE_CUBE_MAP, material.maps[i].texture.id); + else glBindTexture(GL_TEXTURE_2D, material.maps[i].texture.id); + + glUniform1i(material.shader.locs[LOC_MAP_DIFFUSE + i], i); + } + } + + // Bind vertex array objects (or VBOs) + glBindVertexArray(mesh.vaoId); + + // At this point the modelview matrix just contains the view matrix (camera) + // For instanced shaders "mvp" is not premultiplied by any instance transform, only RLGL.State.transform + glUniformMatrix4fv(material.shader.locs[LOC_MATRIX_MVP], 1, false, MatrixToFloat( + MatrixMultiply(MatrixMultiply(RLGL.State.transform, RLGL.State.modelview), RLGL.State.projection) + )); + + float16* instances = RL_MALLOC(count * sizeof(float16)); + + for (int i = 0; i < count; i++) + instances[i] = MatrixToFloatV(transforms[i]); + + // This could alternatively use a static VBO and either glMapBuffer or glBufferSubData. + // It isn't clear which would be reliably faster in all cases and on all platforms, and + // anecdotally glMapBuffer seems very slow (syncs) while glBufferSubData seems no faster + // since we're transferring all the transform matrices anyway. + unsigned int instancesB; + glGenBuffers(1, &instancesB); + glBindBuffer(GL_ARRAY_BUFFER, instancesB); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(float16), instances, GL_STATIC_DRAW); + + // Instances are put in LOC_MATRIX_MODEL attribute location with space for 4x Vector4, eg: + // layout (location = 12) in mat4 instance; + unsigned int instanceA = material.shader.locs[LOC_MATRIX_MODEL]; + + for (unsigned int i = 0; i < 4; i++) + { + glEnableVertexAttribArray(instanceA+i); + glVertexAttribPointer(instanceA+i, 4, GL_FLOAT, GL_FALSE, sizeof(Matrix), (void*)(i * sizeof(Vector4))); + glVertexAttribDivisor(instanceA+i, 1); + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + + // Draw call! + if (mesh.indices != NULL) { + // Indexed vertices draw + glDrawElementsInstanced(GL_TRIANGLES, mesh.triangleCount*3, GL_UNSIGNED_SHORT, 0, count); + } else { + glDrawArraysInstanced(GL_TRIANGLES, 0, mesh.vertexCount, count); + } + + glDeleteBuffers(1, &instancesB); + RL_FREE(instances); + + // Unbind all binded texture maps + for (int i = 0; i < MAX_MATERIAL_MAPS; i++) + { + glActiveTexture(GL_TEXTURE0 + i); // Set shader active texture + if ((i == MAP_IRRADIANCE) || (i == MAP_PREFILTER) || (i == MAP_CUBEMAP)) glBindTexture(GL_TEXTURE_CUBE_MAP, 0); + else glBindTexture(GL_TEXTURE_2D, 0); // Unbind current active texture + } + + // Unind vertex array objects (or VBOs) + glBindVertexArray(0); + + // Unbind shader program + glUseProgram(0); + +#else + TRACELOG(LOG_ERROR, "VAO: Instanced rendering requires GRAPHICS_API_OPENGL_33"); +#endif +} + // Unload mesh data from CPU and GPU void rlUnloadMesh(Mesh mesh) { @@ -3183,6 +3292,19 @@ int GetShaderLocation(Shader shader, const char *uniformName) return location; } +// Get shader attribute location +int GetShaderLocationAttrib(Shader shader, const char *attribName) +{ + int location = -1; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + location = glGetAttribLocation(shader.id, attribName); + + if (location == -1) TRACELOG(LOG_WARNING, "SHADER: [ID %i] Failed to find shader attribute: %s", shader.id, attribName); + else TRACELOG(LOG_INFO, "SHADER: [ID %i] Shader attribute (%s) set at location: %i", shader.id, attribName, location); +#endif + return location; +} + // Set shader uniform value void SetShaderValue(Shader shader, int uniformLoc, const void *value, int uniformType) {