metaballs.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <QVector2D.h>
  2. #include "VG/openvg.h"
  3. #include <math.h>
  4. #pragma once
  5. /**
  6. * Ported to C++ (Qt for vector class) from original python code:
  7. *
  8. # An example implementation of the algorithm described at
  9. # http://www.niksula.cs.hut.fi/~hkankaan/Homepages/metaballs.html
  10. #
  11. # The code contains some references to the document above, in form
  12. # ### Formula (x)
  13. # to make clear where each of the formulas is implemented (and what
  14. # it looks like in Python)
  15. #
  16. # Since Python doesn't have an in-built vector type, I used complex
  17. # numbers for coordinates (x is the real part, y is the imaginary part)
  18. #
  19. # Made by Hannu Kankaanpää. Use for whatever you wish.
  20. */
  21. class Ball
  22. {
  23. public:
  24. bool active;
  25. int sharedBall;
  26. QVector2D dir;
  27. QVector2D pos;
  28. QVector2D pos0;
  29. QVector2D edgePos;
  30. bool tracking;
  31. float size;
  32. VGubyte commands[1024];
  33. VGfloat vertices[1024];
  34. int verticeCount;
  35. /**Single metaball. */
  36. Ball(QVector2D _pos0, float size0) : pos(_pos0), size(size0), tracking(false), dir((float)(rand()&255)/128.0f-1.0f,(float)(rand()&255)/128.0f-1.0f)
  37. {
  38. dir*=40.0f;
  39. active = true;
  40. }
  41. Ball() : tracking(false), dir((float)(rand()&255)/128.0f-1.0f,(float)(rand()&255)/128.0f-1.0f)
  42. {
  43. size = 2.0f;
  44. pos = QVector2D( 0, 0);
  45. dir*=40.0f;
  46. active = true;
  47. }
  48. };
  49. /**A class that manages the metaballs and can calculate
  50. several useful values from the system.
  51. */
  52. class MetaballSystem
  53. {
  54. public:
  55. MetaballSystem(int ballCount0, Ball *balls0, float goo0, float threshold0);
  56. float calcForce(QVector2D pos);
  57. QVector2D calcNormal(QVector2D pos);
  58. QVector2D calcTangent(QVector2D pos);
  59. float stepOnceTowardsBorder(QVector2D &pos);
  60. QVector2D trackTheBorder(QVector2D pos);
  61. QVector2D eulerTangent(QVector2D pos, float h);
  62. QVector2D rungeKutta2Tangent(QVector2D pos, float h);
  63. float minSize;
  64. int ballCount;
  65. Ball *balls;
  66. float goo;
  67. float threshold;
  68. };