instanced.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. R3D_Init(GetScreenWidth(), GetScreenHeight(), 0);
  15. SetTargetFPS(60);
  16. mesh = R3D_GenMeshCube(1, 1, 1, true);
  17. material = R3D_GetDefaultMaterial();
  18. //GenMeshTangents(&mesh);
  19. for (int i = 0; i < INSTANCE_COUNT; i++) {
  20. Matrix translate = MatrixTranslate(
  21. (float)GetRandomValue(-50000, 50000) / 1000,
  22. (float)GetRandomValue(-50000, 50000) / 1000,
  23. (float)GetRandomValue(-50000, 50000) / 1000
  24. );
  25. Matrix rotate = MatrixRotateXYZ((Vector3) {
  26. (float)GetRandomValue(-314000, 314000) / 100000,
  27. (float)GetRandomValue(-314000, 314000) / 100000,
  28. (float)GetRandomValue(-314000, 314000) / 100000
  29. });
  30. Matrix scale = MatrixScale(
  31. (float)GetRandomValue(100, 2000) / 1000,
  32. (float)GetRandomValue(100, 2000) / 1000,
  33. (float)GetRandomValue(100, 2000) / 1000
  34. );
  35. transforms[i] = MatrixMultiply(MatrixMultiply(scale, rotate), translate);
  36. colors[i] = ColorFromHSV((float)GetRandomValue(0, 360000) / 1000, 1.0f, 1.0f);
  37. }
  38. camera = (Camera3D){
  39. .position = (Vector3) { 0, 2, 2 },
  40. .target = (Vector3) { 0, 0, 0 },
  41. .up = (Vector3) { 0, 1, 0 },
  42. .fovy = 60,
  43. };
  44. R3D_Light light = R3D_CreateLight(R3D_LIGHT_DIR);
  45. {
  46. R3D_SetLightDirection(light, (Vector3) { 0, -1, 0 });
  47. R3D_SetLightActive(light, true);
  48. }
  49. DisableCursor();
  50. return "[r3d] - Instanced rendering example";
  51. }
  52. void Update(float delta)
  53. {
  54. UpdateCamera(&camera, CAMERA_FREE);
  55. }
  56. void Draw(void)
  57. {
  58. R3D_Begin(camera);
  59. R3D_DrawMeshInstancedEx(&mesh, &material, transforms, colors, INSTANCE_COUNT);
  60. R3D_End();
  61. DrawFPS(10, 10);
  62. }
  63. void Close(void)
  64. {
  65. R3D_UnloadMaterial(&material);
  66. R3D_UnloadMesh(&mesh);
  67. R3D_Close();
  68. }