lights.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include "./common.h"
  2. /* === Resources === */
  3. static R3D_Mesh plane = { 0 };
  4. static R3D_Mesh sphere = { 0 };
  5. static R3D_Material material = { 0 };
  6. static Camera3D camera = { 0 };
  7. static Matrix* transforms = NULL;
  8. static R3D_Light lights[100] = { 0 };
  9. /* === Example === */
  10. const char* Init(void)
  11. {
  12. /* --- Initialize R3D with its internal resolution --- */
  13. R3D_Init(GetScreenWidth(), GetScreenHeight(), 0);
  14. SetTargetFPS(60);
  15. /* --- Generates a plane and sphere meshes and a default material to render them --- */
  16. plane = R3D_GenMeshPlane(1000, 1000, 1, 1);
  17. sphere = R3D_GenMeshSphere(0.35f, 16, 16);
  18. material = R3D_GetDefaultMaterial();
  19. /* --- Calculating transformations for all sphere instances --- */
  20. transforms = RL_MALLOC(100 * 100 * sizeof(Matrix));
  21. if (transforms == NULL) {
  22. TraceLog(LOG_FATAL, "EXAMPLE: Failed to allocate transforms buffer");
  23. exit(-1);
  24. }
  25. for (int x = -50; x < 50; x++) {
  26. for (int z = -50; z < 50; z++) {
  27. int index = (z + 50) * 100 + (x + 50);
  28. transforms[index] = MatrixTranslate((float)x, 0, (float)z);
  29. }
  30. }
  31. /* --- Setup 100 omni-directional lights --- */
  32. for (int x = -5; x < 5; x++) {
  33. for (int z = -5; z < 5; z++) {
  34. int index = (z + 5) * 10 + (x + 5);
  35. lights[index] = R3D_CreateLight(R3D_LIGHT_OMNI);
  36. R3D_SetLightPosition(lights[index], (Vector3) { (float)x * 10, 10, (float)z * 10 });
  37. R3D_SetLightColor(lights[index], ColorFromHSV((float)index / 100 * 360, 1.0f, 1.0f));
  38. R3D_SetLightRange(lights[index], 20.0f);
  39. R3D_SetLightActive(lights[index], true);
  40. }
  41. }
  42. /* --- Setup the camera --- */
  43. camera = (Camera3D) {
  44. .position = (Vector3) { 0, 2, 2 },
  45. .target = (Vector3) { 0, 0, 0 },
  46. .up = (Vector3) { 0, 1, 0 },
  47. .fovy = 60,
  48. };
  49. return "[r3d] - Many lights example";
  50. }
  51. void Update(float delta)
  52. {
  53. UpdateCamera(&camera, CAMERA_ORBITAL);
  54. }
  55. void Draw(void)
  56. {
  57. R3D_Begin(camera);
  58. R3D_DrawMesh(&plane, &material, MatrixTranslate(0, -0.5f, 0));
  59. R3D_DrawMeshInstanced(&sphere, &material, transforms, 100 * 100);
  60. R3D_End();
  61. if (IsKeyDown(KEY_SPACE)) {
  62. BeginMode3D(camera);
  63. for (int i = 0; i < 100; i++) {
  64. R3D_DrawLightShape(lights[i]);
  65. }
  66. EndMode3D();
  67. }
  68. DrawFPS(10, 10);
  69. DrawText("Press SPACE to show the lights", 10, GetScreenHeight() - 34, 24, BLACK);
  70. }
  71. void Close(void)
  72. {
  73. R3D_UnloadMesh(&plane);
  74. R3D_UnloadMesh(&sphere);
  75. R3D_Close();
  76. }