helloWorld.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. Simple hello world for small3dlib. Renders a triangle in terminal as ASCII.
  3. by drummyfish, released under CC0 1.0, public domain
  4. */
  5. #include <stdio.h> // for IO
  6. // This tells the library the resolution of our ASCII screen.
  7. #define S3L_RESOLUTION_X 64
  8. #define S3L_RESOLUTION_Y 30
  9. // This tells the library the name of a function we use to write pixels.
  10. #define S3L_PIXEL_FUNCTION drawPixel
  11. #include "../small3dlib.h" // now include the library
  12. #define U S3L_F // this is the library unit, like e.g. 1 meter
  13. S3L_Unit triangleVertices[] = { // x, y, z
  14. U, 0, 0, // vertex 1
  15. 0, U, 0, // vertex 2
  16. -U, U/2, 0 }; // vertex 3
  17. S3L_Index triangleTriangles[] = { 0, 1, 2 }; // our single triangle
  18. #undef U
  19. #define SCREEN_SIZE (S3L_RESOLUTION_X * S3L_RESOLUTION_Y)
  20. char screen[SCREEN_SIZE]; // our ASCII screen
  21. /* This function will be called by the library to draw individual rasterized
  22. pixels to our screen. We should try to make this function as fast as possible
  23. as it tends to be the performance bottle neck. */
  24. void drawPixel(S3L_PixelInfo *p)
  25. {
  26. screen[p->y * S3L_RESOLUTION_X + p->x] = 'X';
  27. }
  28. int main()
  29. {
  30. for (int i = 0; i < SCREEN_SIZE; ++i) // init the screen
  31. screen[i] = '.';
  32. S3L_Model3D triangleModel; // 3D model representing our triangle
  33. S3L_model3DInit(triangleVertices,9,triangleTriangles,1,&triangleModel);
  34. S3L_Scene scene; // scene of 3D models (we only have 1)
  35. S3L_sceneInit(&triangleModel,1,&scene);
  36. // shift the camera a little bit so that we can see the triangle
  37. scene.camera.transform.translation.z = -2 * S3L_F;
  38. scene.camera.transform.translation.y = S3L_F / 2;
  39. S3L_newFrame(); // has to be called before each frame
  40. S3L_drawScene(scene); /* this starts the scene rendering, the library
  41. will now start calling our drawPixel function to
  42. render the camera view */
  43. int index = 0;
  44. for (int y = 0; y < S3L_RESOLUTION_Y; ++y) // now display the screen
  45. {
  46. for (int x = 0; x < S3L_RESOLUTION_X; ++x)
  47. {
  48. putchar(screen[index]);
  49. index++;
  50. }
  51. putchar('\n');
  52. }
  53. return 0; // done!
  54. }