fork download
  1. #include<stdio.h>
  2. #include<math.h>
  3.  
  4. #define MAX_POINTS 10
  5.  
  6. FILE* set_plot(int n,double p[][2])
  7. {
  8. FILE* gp=popen("gnuplot -persistent","w");
  9. fprintf(gp,"set title 'bezier curve'\n");
  10. fprintf(gp,"set xrange[0:150]\n");
  11. fprintf(gp,"set yrange[0:150]\n");
  12. fprintf(gp,"set grid\n");
  13.  
  14. fprintf(gp, "plot '-' with linespoints dt 2 pointsize 1.5 linewidth 2 linecolor rgb 'red' title 'Control Points', "
  15. "'-' with linespoints pointtype 7 pointsize 1.5 linewidth 3 linecolor rgb 'blue' title 'Bezier Curve'\n");
  16.  
  17. // Control points
  18. for(int i = 0; i <= n; i++) {
  19. fprintf(gp, "%f %f\n", p[i][0], p[i][1]);
  20. }
  21. fprintf(gp, "e\n");
  22.  
  23. return gp;
  24. }
  25.  
  26. void plot_curve(FILE* gp,double result[2])
  27. {
  28. fprintf(gp, "%f %f\n", result[0], result[1]);
  29. }
  30.  
  31. // De Casteljau Algorithm
  32. void de_casteljau(double points[][2],int n, double t,double result[2])
  33. {
  34. double temp[MAX_POINTS][2];
  35.  
  36. // Copy original points
  37. for(int i = 0; i <= n; i++)
  38. {
  39. temp[i][0] = points[i][0];
  40. temp[i][1] = points[i][1];
  41. }
  42.  
  43. // Iteratively interpolate
  44. for(int k = 1; k <= n; k++)
  45. {
  46. for(int i = 0; i <= n - k; i++)
  47. {
  48. temp[i][0] = (1 - t) * temp[i][0] + t * temp[i+1][0];
  49. temp[i][1] = (1 - t) * temp[i][1] + t * temp[i+1][1];
  50. }
  51. }
  52.  
  53. // Final point
  54. result[0] = temp[0][0];
  55. result[1] = temp[0][1];
  56. }
  57.  
  58. int main()
  59. {
  60. int n = 3; // cubic Bezier (4 control points)
  61.  
  62. double points[MAX_POINTS][2] = {
  63. {10, 10},
  64. {30, 120},
  65. {100, 120},
  66. {140, 20}
  67. };
  68.  
  69. FILE* gp = set_plot(n, points);
  70.  
  71. double result[2];
  72.  
  73. // Generate curve points
  74. for(double t = 0.0; t <= 1.0; t += 0.01)
  75. {
  76. de_casteljau(points, n, t, result);
  77. plot_curve(gp, result);
  78. }
  79.  
  80. fprintf(gp, "e\n"); // end Bezier curve data
  81. pclose(gp);
  82.  
  83. return 0;
  84. }
Success #stdin #stdout #stderr 0s 5316KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
sh: 1: gnuplot: not found