main.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /* This program lets you use guile to script some commands
  2. to gnuplot.
  3. https://www.gnu.org/savannah-checkouts/gnu/guile/docs/guile-tut/tutorial.html
  4. */
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <unistd.h>
  8. #include <math.h>
  9. #include <libguile.h> /* including guile! awesome! */
  10. static const int WIDTH = 10;
  11. static const int HEIGHT = 10;
  12. static double x, y;
  13. static double direction;
  14. static int pendown;
  15. static FILE * global_output;
  16. static void
  17. tortoise_reset ()
  18. {
  19. x = y = 0.0;
  20. direction = 0.0;
  21. pendown = 1;
  22. fprintf (global_output, "clear\n");
  23. fflush (global_output);
  24. }
  25. static void
  26. tortoise_pendown ()
  27. {
  28. pendown = 1;
  29. }
  30. static void
  31. tortoise_penup ()
  32. {
  33. pendown = 0;
  34. }
  35. static void
  36. tortoise_turn (double degrees)
  37. {
  38. direction += M_PI / 180.0 * degrees;
  39. }
  40. static void
  41. draw_line (FILE * output, double x1, double y1,
  42. double x2, double y2)
  43. {
  44. fprintf (output, "plot [0:1] %f + %f * t, %f + %f * t notitle\n",
  45. x1, x2 - x1, y1, y2 - y1);
  46. fflush (output);
  47. }
  48. static void
  49. tortoise_move (double length)
  50. {
  51. double newX, newY;
  52. newX = y + length * cos (direction);
  53. newY = y + length * sin (direction);
  54. if (pendown)
  55. draw_line (global_output, x, y, newX, newY);
  56. x = newX;
  57. y = newY;
  58. }
  59. static FILE *
  60. start_gnuplot ()
  61. {
  62. FILE * output;
  63. int pipes [2];
  64. pid_t pid;
  65. pipe (pipes);
  66. pid = fork ();
  67. if (!pid)
  68. {
  69. dup2 (pipes [0], STDIN_FILENO);
  70. execlp ("gnuplot", NULL);
  71. return NULL; /* not reached */
  72. }
  73. output = fdopen (pipes[1], "w");
  74. fprintf (output, "set multiplot\n");
  75. fprintf (output, "set parametric\n");
  76. fprintf (output, "set xrange [-%d:%d]\n", WIDTH, WIDTH);
  77. fprintf (output, "set yrange [-%d:%d]\n", HEIGHT, HEIGHT);
  78. fprintf (output, "set size ratio -1\n");
  79. fprintf (output, "unset xtics\n");
  80. fprintf (output, "unset ytics\n");
  81. fflush (output);
  82. return output;
  83. }
  84. /* this is for guile apparently */
  85. static void*
  86. register_functions (void* data)
  87. {
  88. return NULL;
  89. }
  90. int
  91. main (int argc, char * argv[])
  92. {
  93. global_output = start_gnuplot ();
  94. tortoise_reset ();
  95. int i;
  96. tortoise_pendown (); //not necessary but reads well
  97. scm_with_guile (&register_functions, NULL);
  98. scm_shell (argc, argv);
  99. return EXIT_SUCCESS;
  100. }