instanced.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "./common.h"
  2. #include "r3d.h"
  3. /* === Constants === */
  4. #define INSTANCE_COUNT 1000
  5. /* === Resources === */
  6. static Camera3D camera = { 0 };
  7. static R3D_Mesh mesh = { 0 };
  8. static R3D_Material material = { 0 };
  9. static Matrix transforms[INSTANCE_COUNT] = { 0 };
  10. static Color colors[INSTANCE_COUNT] = { 0 };
  11. /* === Example === */
  12. const char* Init(void)
  13. {
  14. /* --- Initialize R3D with its internal resolution --- */
  15. R3D_Init(GetScreenWidth(), GetScreenHeight(), 0);
  16. SetTargetFPS(60);
  17. /* --- Generates a cube mesh and a default material to render it --- */
  18. mesh = R3D_GenMeshCube(1, 1, 1, true);
  19. material = R3D_GetDefaultMaterial();
  20. /* --- Randomly generate the transformation and color of each cube instance --- */
  21. for (int i = 0; i < INSTANCE_COUNT; i++) {
  22. Matrix translate = MatrixTranslate(
  23. (float)GetRandomValue(-50000, 50000) / 1000,
  24. (float)GetRandomValue(-50000, 50000) / 1000,
  25. (float)GetRandomValue(-50000, 50000) / 1000
  26. );
  27. Matrix rotate = MatrixRotateXYZ((Vector3) {
  28. (float)GetRandomValue(-314000, 314000) / 100000,
  29. (float)GetRandomValue(-314000, 314000) / 100000,
  30. (float)GetRandomValue(-314000, 314000) / 100000
  31. });
  32. Matrix scale = MatrixScale(
  33. (float)GetRandomValue(100, 2000) / 1000,
  34. (float)GetRandomValue(100, 2000) / 1000,
  35. (float)GetRandomValue(100, 2000) / 1000
  36. );
  37. transforms[i] = MatrixMultiply(MatrixMultiply(scale, rotate), translate);
  38. colors[i] = ColorFromHSV((float)GetRandomValue(0, 360000) / 1000, 1.0f, 1.0f);
  39. }
  40. /* --- Setup the scene lighting --- */
  41. R3D_Light light = R3D_CreateLight(R3D_LIGHT_DIR);
  42. {
  43. R3D_SetLightDirection(light, (Vector3) { 0, -1, 0 });
  44. R3D_SetLightActive(light, true);
  45. }
  46. /* --- Setup the camera --- */
  47. camera = (Camera3D){
  48. .position = (Vector3) { 0, 2, 2 },
  49. .target = (Vector3) { 0, 0, 0 },
  50. .up = (Vector3) { 0, 1, 0 },
  51. .fovy = 60,
  52. };
  53. /* --- Capture the mouse and ready to go! --- */
  54. DisableCursor();
  55. return "[r3d] - Instanced rendering example";
  56. }
  57. void Update(float delta)
  58. {
  59. UpdateCamera(&camera, CAMERA_FREE);
  60. }
  61. void Draw(void)
  62. {
  63. R3D_Begin(camera);
  64. R3D_DrawMeshInstancedEx(&mesh, &material, transforms, colors, INSTANCE_COUNT);
  65. R3D_End();
  66. DrawFPS(10, 10);
  67. }
  68. void Close(void)
  69. {
  70. R3D_UnloadMaterial(&material);
  71. R3D_UnloadMesh(&mesh);
  72. R3D_Close();
  73. }