You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

482 lines
19 KiB

  1. /*******************************************************************************************
  2. *
  3. * raylib [shaders] example - Standard lighting (materials and lights)
  4. *
  5. * NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
  6. * OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
  7. *
  8. * NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
  9. * on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
  10. * raylib comes with shaders ready for both versions, check raylib/shaders install folder
  11. *
  12. * This example has been created using raylib 1.7 (www.raylib.com)
  13. * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
  14. *
  15. * Copyright (c) 2016-2017 Ramon Santamaria (@raysan5)
  16. *
  17. ********************************************************************************************/
  18. #include "raylib.h"
  19. #include <stdlib.h> // Required for: NULL
  20. #include <string.h> // Required for: strcpy()
  21. #include <math.h> // Required for: vector math
  22. //----------------------------------------------------------------------------------
  23. // Defines and Macros
  24. //----------------------------------------------------------------------------------
  25. #define MAX_LIGHTS 8 // Max lights supported by standard shader
  26. //----------------------------------------------------------------------------------
  27. // Types and Structures Definition
  28. //----------------------------------------------------------------------------------
  29. // Light type
  30. typedef struct LightData {
  31. unsigned int id; // Light unique id
  32. bool enabled; // Light enabled
  33. int type; // Light type: LIGHT_POINT, LIGHT_DIRECTIONAL, LIGHT_SPOT
  34. Vector3 position; // Light position
  35. Vector3 target; // Light direction: LIGHT_DIRECTIONAL and LIGHT_SPOT (cone direction target)
  36. float radius; // Light attenuation radius light intensity reduced with distance (world distance)
  37. Color diffuse; // Light diffuse color
  38. float intensity; // Light intensity level
  39. float coneAngle; // Light cone max angle: LIGHT_SPOT
  40. } LightData, *Light;
  41. // Light types
  42. typedef enum { LIGHT_POINT, LIGHT_DIRECTIONAL, LIGHT_SPOT } LightType;
  43. //----------------------------------------------------------------------------------
  44. // Global Variables Definition
  45. //----------------------------------------------------------------------------------
  46. static Light lights[MAX_LIGHTS]; // Lights pool
  47. static int lightsCount = 0; // Enabled lights counter
  48. static int lightsLocs[MAX_LIGHTS][8]; // Lights location points in shader: 8 possible points per light:
  49. // enabled, type, position, target, radius, diffuse, intensity, coneAngle
  50. //----------------------------------------------------------------------------------
  51. // Module Functions Declaration
  52. //----------------------------------------------------------------------------------
  53. static Light CreateLight(int type, Vector3 position, Color diffuse); // Create a new light, initialize it and add to pool
  54. static void DestroyLight(Light light); // Destroy a light and take it out of the list
  55. static void DrawLight(Light light); // Draw light in 3D world
  56. static void GetShaderLightsLocations(Shader shader); // Get shader locations for lights (up to MAX_LIGHTS)
  57. static void SetShaderLightsValues(Shader shader); // Set shader uniform values for lights
  58. // Vector3 math functions
  59. static float VectorLength(const Vector3 v); // Calculate vector lenght
  60. static void VectorNormalize(Vector3 *v); // Normalize provided vector
  61. static Vector3 VectorSubtract(Vector3 v1, Vector3 v2); // Substract two vectors
  62. //https://www.gamedev.net/topic/655969-speed-gluniform-vs-uniform-buffer-objects/
  63. //https://www.reddit.com/r/opengl/comments/4ri20g/is_gluniform_more_expensive_than_glprogramuniform/
  64. //http://cg.alexandra.dk/?p=3778 - AZDO
  65. //https://developer.apple.com/library/content/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/BestPracticesforShaders/BestPracticesforShaders.html
  66. //------------------------------------------------------------------------------------
  67. // Program main entry point
  68. //------------------------------------------------------------------------------------
  69. int main()
  70. {
  71. // Initialization
  72. //--------------------------------------------------------------------------------------
  73. int screenWidth = 800;
  74. int screenHeight = 450;
  75. SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available)
  76. InitWindow(screenWidth, screenHeight, "raylib [shaders] example - model shader");
  77. // Define the camera to look into our 3d world
  78. Camera camera = {{ 4.0f, 4.0f, 4.0f }, { 0.0f, 1.5f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f };
  79. Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
  80. Model dwarf = LoadModel("resources/model/dwarf.obj"); // Load OBJ model
  81. Material material;// = LoadStandardMaterial();
  82. material.shader = LoadShader("resources/shaders/glsl330/standard.vs", "resources/shaders/glsl330/standard.fs");
  83. // Try to get lights location points (if available)
  84. GetShaderLightsLocations(material.shader);
  85. material.texDiffuse = LoadTexture("resources/model/dwarf_diffuse.png"); // Load model diffuse texture
  86. material.texNormal = LoadTexture("resources/model/dwarf_normal.png"); // Load model normal texture
  87. material.texSpecular = LoadTexture("resources/model/dwarf_specular.png"); // Load model specular texture
  88. material.colDiffuse = WHITE;
  89. material.colAmbient = (Color){0, 0, 10, 255};
  90. material.colSpecular = WHITE;
  91. material.glossiness = 50.0f;
  92. dwarf.material = material; // Apply material to model
  93. Light spotLight = CreateLight(LIGHT_SPOT, (Vector3){3.0f, 5.0f, 2.0f}, (Color){255, 255, 255, 255});
  94. spotLight->target = (Vector3){0.0f, 0.0f, 0.0f};
  95. spotLight->intensity = 2.0f;
  96. spotLight->diffuse = (Color){255, 100, 100, 255};
  97. spotLight->coneAngle = 60.0f;
  98. Light dirLight = CreateLight(LIGHT_DIRECTIONAL, (Vector3){0.0f, -3.0f, -3.0f}, (Color){255, 255, 255, 255});
  99. dirLight->target = (Vector3){1.0f, -2.0f, -2.0f};
  100. dirLight->intensity = 2.0f;
  101. dirLight->diffuse = (Color){100, 255, 100, 255};
  102. Light pointLight = CreateLight(LIGHT_POINT, (Vector3){0.0f, 4.0f, 5.0f}, (Color){255, 255, 255, 255});
  103. pointLight->intensity = 2.0f;
  104. pointLight->diffuse = (Color){100, 100, 255, 255};
  105. pointLight->radius = 3.0f;
  106. // Set shader lights values for enabled lights
  107. // NOTE: If values are not changed in real time, they can be set at initialization!!!
  108. SetShaderLightsValues(material.shader);
  109. //SetShaderActive(0);
  110. // Setup orbital camera
  111. SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
  112. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  113. //--------------------------------------------------------------------------------------
  114. // Main game loop
  115. while (!WindowShouldClose()) // Detect window close button or ESC key
  116. {
  117. // Update
  118. //----------------------------------------------------------------------------------
  119. UpdateCamera(&camera); // Update camera
  120. //----------------------------------------------------------------------------------
  121. // Draw
  122. //----------------------------------------------------------------------------------
  123. BeginDrawing();
  124. ClearBackground(RAYWHITE);
  125. Begin3dMode(camera);
  126. DrawModel(dwarf, position, 2.0f, WHITE); // Draw 3d model with texture
  127. DrawLight(spotLight); // Draw spot light
  128. DrawLight(dirLight); // Draw directional light
  129. DrawLight(pointLight); // Draw point light
  130. DrawGrid(10, 1.0f); // Draw a grid
  131. End3dMode();
  132. DrawText("(c) Dwarf 3D model by David Moreno", screenWidth - 200, screenHeight - 20, 10, GRAY);
  133. DrawFPS(10, 10);
  134. EndDrawing();
  135. //----------------------------------------------------------------------------------
  136. }
  137. // De-Initialization
  138. //--------------------------------------------------------------------------------------
  139. UnloadMaterial(material); // Unload material and assigned textures
  140. UnloadModel(dwarf); // Unload model
  141. // Destroy all created lights
  142. DestroyLight(pointLight);
  143. DestroyLight(dirLight);
  144. DestroyLight(spotLight);
  145. // Unload lights
  146. if (lightsCount > 0)
  147. {
  148. for (int i = 0; i < lightsCount; i++) free(lights[i]);
  149. lightsCount = 0;
  150. }
  151. CloseWindow(); // Close window and OpenGL context
  152. //--------------------------------------------------------------------------------------
  153. return 0;
  154. }
  155. //--------------------------------------------------------------------------------------------
  156. // Module Functions Definitions
  157. //--------------------------------------------------------------------------------------------
  158. // Create a new light, initialize it and add to pool
  159. Light CreateLight(int type, Vector3 position, Color diffuse)
  160. {
  161. Light light = NULL;
  162. if (lightsCount < MAX_LIGHTS)
  163. {
  164. // Allocate dynamic memory
  165. light = (Light)malloc(sizeof(LightData));
  166. // Initialize light values with generic values
  167. light->id = lightsCount;
  168. light->type = type;
  169. light->enabled = true;
  170. light->position = position;
  171. light->target = (Vector3){ 0.0f, 0.0f, 0.0f };
  172. light->intensity = 1.0f;
  173. light->diffuse = diffuse;
  174. // Add new light to the array
  175. lights[lightsCount] = light;
  176. // Increase enabled lights count
  177. lightsCount++;
  178. }
  179. else
  180. {
  181. // NOTE: Returning latest created light to avoid crashes
  182. light = lights[lightsCount];
  183. }
  184. return light;
  185. }
  186. // Destroy a light and take it out of the list
  187. void DestroyLight(Light light)
  188. {
  189. if (light != NULL)
  190. {
  191. int lightId = light->id;
  192. // Free dynamic memory allocation
  193. free(lights[lightId]);
  194. // Remove *obj from the pointers array
  195. for (int i = lightId; i < lightsCount; i++)
  196. {
  197. // Resort all the following pointers of the array
  198. if ((i + 1) < lightsCount)
  199. {
  200. lights[i] = lights[i + 1];
  201. lights[i]->id = lights[i + 1]->id;
  202. }
  203. }
  204. // Decrease enabled physic objects count
  205. lightsCount--;
  206. }
  207. }
  208. // Draw light in 3D world
  209. void DrawLight(Light light)
  210. {
  211. switch (light->type)
  212. {
  213. case LIGHT_POINT:
  214. {
  215. DrawSphereWires(light->position, 0.3f*light->intensity, 8, 8, (light->enabled ? light->diffuse : GRAY));
  216. DrawCircle3D(light->position, light->radius, (Vector3){ 0, 0, 0 }, 0.0f, (light->enabled ? light->diffuse : GRAY));
  217. DrawCircle3D(light->position, light->radius, (Vector3){ 1, 0, 0 }, 90.0f, (light->enabled ? light->diffuse : GRAY));
  218. DrawCircle3D(light->position, light->radius, (Vector3){ 0, 1, 0 },90.0f, (light->enabled ? light->diffuse : GRAY));
  219. } break;
  220. case LIGHT_DIRECTIONAL:
  221. {
  222. DrawLine3D(light->position, light->target, (light->enabled ? light->diffuse : GRAY));
  223. DrawSphereWires(light->position, 0.3f*light->intensity, 8, 8, (light->enabled ? light->diffuse : GRAY));
  224. DrawCubeWires(light->target, 0.3f, 0.3f, 0.3f, (light->enabled ? light->diffuse : GRAY));
  225. } break;
  226. case LIGHT_SPOT:
  227. {
  228. DrawLine3D(light->position, light->target, (light->enabled ? light->diffuse : GRAY));
  229. Vector3 dir = VectorSubtract(light->target, light->position);
  230. VectorNormalize(&dir);
  231. DrawCircle3D(light->position, 0.5f, dir, 0.0f, (light->enabled ? light->diffuse : GRAY));
  232. //DrawCylinderWires(light->position, 0.0f, 0.3f*light->coneAngle/50, 0.6f, 5, (light->enabled ? light->diffuse : GRAY));
  233. DrawCubeWires(light->target, 0.3f, 0.3f, 0.3f, (light->enabled ? light->diffuse : GRAY));
  234. } break;
  235. default: break;
  236. }
  237. }
  238. // Get shader locations for lights (up to MAX_LIGHTS)
  239. static void GetShaderLightsLocations(Shader shader)
  240. {
  241. char locName[32] = "lights[x].\0";
  242. char locNameUpdated[64];
  243. for (int i = 0; i < MAX_LIGHTS; i++)
  244. {
  245. locName[7] = '0' + i;
  246. strcpy(locNameUpdated, locName);
  247. strcat(locNameUpdated, "enabled\0");
  248. lightsLocs[i][0] = GetShaderLocation(shader, locNameUpdated);
  249. locNameUpdated[0] = '\0';
  250. strcpy(locNameUpdated, locName);
  251. strcat(locNameUpdated, "type\0");
  252. lightsLocs[i][1] = GetShaderLocation(shader, locNameUpdated);
  253. locNameUpdated[0] = '\0';
  254. strcpy(locNameUpdated, locName);
  255. strcat(locNameUpdated, "position\0");
  256. lightsLocs[i][2] = GetShaderLocation(shader, locNameUpdated);
  257. locNameUpdated[0] = '\0';
  258. strcpy(locNameUpdated, locName);
  259. strcat(locNameUpdated, "direction\0");
  260. lightsLocs[i][3] = GetShaderLocation(shader, locNameUpdated);
  261. locNameUpdated[0] = '\0';
  262. strcpy(locNameUpdated, locName);
  263. strcat(locNameUpdated, "radius\0");
  264. lightsLocs[i][4] = GetShaderLocation(shader, locNameUpdated);
  265. locNameUpdated[0] = '\0';
  266. strcpy(locNameUpdated, locName);
  267. strcat(locNameUpdated, "diffuse\0");
  268. lightsLocs[i][5] = GetShaderLocation(shader, locNameUpdated);
  269. locNameUpdated[0] = '\0';
  270. strcpy(locNameUpdated, locName);
  271. strcat(locNameUpdated, "intensity\0");
  272. lightsLocs[i][6] = GetShaderLocation(shader, locNameUpdated);
  273. locNameUpdated[0] = '\0';
  274. strcpy(locNameUpdated, locName);
  275. strcat(locNameUpdated, "coneAngle\0");
  276. lightsLocs[i][7] = GetShaderLocation(shader, locNameUpdated);
  277. }
  278. }
  279. // Set shader uniform values for lights
  280. // NOTE: It would be far easier with shader UBOs but are not supported on OpenGL ES 2.0
  281. // TODO: Replace glUniform1i(), glUniform1f(), glUniform3f(), glUniform4f():
  282. //SetShaderValue(Shader shader, int uniformLoc, float *value, int size)
  283. //SetShaderValuei(Shader shader, int uniformLoc, int *value, int size)
  284. static void SetShaderLightsValues(Shader shader)
  285. {
  286. int tempInt[8] = { 0 };
  287. float tempFloat[8] = { 0.0f };
  288. for (int i = 0; i < MAX_LIGHTS; i++)
  289. {
  290. if (i < lightsCount)
  291. {
  292. tempInt[0] = lights[i]->enabled;
  293. SetShaderValuei(shader, lightsLocs[i][0], tempInt, 1); //glUniform1i(lightsLocs[i][0], lights[i]->enabled);
  294. tempInt[0] = lights[i]->type;
  295. SetShaderValuei(shader, lightsLocs[i][1], tempInt, 1); //glUniform1i(lightsLocs[i][1], lights[i]->type);
  296. tempFloat[0] = (float)lights[i]->diffuse.r/255.0f;
  297. tempFloat[1] = (float)lights[i]->diffuse.g/255.0f;
  298. tempFloat[2] = (float)lights[i]->diffuse.b/255.0f;
  299. tempFloat[3] = (float)lights[i]->diffuse.a/255.0f;
  300. SetShaderValue(shader, lightsLocs[i][5], tempFloat, 4);
  301. //glUniform4f(lightsLocs[i][5], (float)lights[i]->diffuse.r/255, (float)lights[i]->diffuse.g/255, (float)lights[i]->diffuse.b/255, (float)lights[i]->diffuse.a/255);
  302. tempFloat[0] = lights[i]->intensity;
  303. SetShaderValue(shader, lightsLocs[i][6], tempFloat, 1);
  304. switch (lights[i]->type)
  305. {
  306. case LIGHT_POINT:
  307. {
  308. tempFloat[0] = lights[i]->position.x;
  309. tempFloat[1] = lights[i]->position.y;
  310. tempFloat[2] = lights[i]->position.z;
  311. SetShaderValue(shader, lightsLocs[i][2], tempFloat, 3);
  312. tempFloat[0] = lights[i]->radius;
  313. SetShaderValue(shader, lightsLocs[i][4], tempFloat, 1);
  314. //glUniform3f(lightsLocs[i][2], lights[i]->position.x, lights[i]->position.y, lights[i]->position.z);
  315. //glUniform1f(lightsLocs[i][4], lights[i]->radius);
  316. } break;
  317. case LIGHT_DIRECTIONAL:
  318. {
  319. Vector3 direction = VectorSubtract(lights[i]->target, lights[i]->position);
  320. VectorNormalize(&direction);
  321. tempFloat[0] = direction.x;
  322. tempFloat[1] = direction.y;
  323. tempFloat[2] = direction.z;
  324. SetShaderValue(shader, lightsLocs[i][3], tempFloat, 3);
  325. //glUniform3f(lightsLocs[i][3], direction.x, direction.y, direction.z);
  326. } break;
  327. case LIGHT_SPOT:
  328. {
  329. tempFloat[0] = lights[i]->position.x;
  330. tempFloat[1] = lights[i]->position.y;
  331. tempFloat[2] = lights[i]->position.z;
  332. SetShaderValue(shader, lightsLocs[i][2], tempFloat, 3);
  333. //glUniform3f(lightsLocs[i][2], lights[i]->position.x, lights[i]->position.y, lights[i]->position.z);
  334. Vector3 direction = VectorSubtract(lights[i]->target, lights[i]->position);
  335. VectorNormalize(&direction);
  336. tempFloat[0] = direction.x;
  337. tempFloat[1] = direction.y;
  338. tempFloat[2] = direction.z;
  339. SetShaderValue(shader, lightsLocs[i][3], tempFloat, 3);
  340. //glUniform3f(lightsLocs[i][3], direction.x, direction.y, direction.z);
  341. tempFloat[0] = lights[i]->coneAngle;
  342. SetShaderValue(shader, lightsLocs[i][7], tempFloat, 1);
  343. //glUniform1f(lightsLocs[i][7], lights[i]->coneAngle);
  344. } break;
  345. default: break;
  346. }
  347. }
  348. else
  349. {
  350. tempInt[0] = 0;
  351. SetShaderValuei(shader, lightsLocs[i][0], tempInt, 1); //glUniform1i(lightsLocs[i][0], 0); // Light disabled
  352. }
  353. }
  354. }
  355. // Calculate vector lenght
  356. float VectorLength(const Vector3 v)
  357. {
  358. float length;
  359. length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z);
  360. return length;
  361. }
  362. // Normalize provided vector
  363. void VectorNormalize(Vector3 *v)
  364. {
  365. float length, ilength;
  366. length = VectorLength(*v);
  367. if (length == 0.0f) length = 1.0f;
  368. ilength = 1.0f/length;
  369. v->x *= ilength;
  370. v->y *= ilength;
  371. v->z *= ilength;
  372. }
  373. // Substract two vectors
  374. Vector3 VectorSubtract(Vector3 v1, Vector3 v2)
  375. {
  376. Vector3 result;
  377. result.x = v1.x - v2.x;
  378. result.y = v1.y - v2.y;
  379. result.z = v1.z - v2.z;
  380. return result;
  381. }