vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.0 KiB

  1. class RepulsionSolver {
  2. constructor(body, physicsBody, options) {
  3. this.body = body;
  4. this.physicsBody = physicsBody;
  5. this.setOptions(options);
  6. }
  7. setOptions(options) {
  8. this.options = options;
  9. }
  10. /**
  11. * Calculate the forces the nodes apply on each other based on a repulsion field.
  12. * This field is linearly approximated.
  13. *
  14. * @private
  15. */
  16. solve() {
  17. var dx, dy, distance, fx, fy, repulsingForce, node1, node2;
  18. var nodes = this.body.nodes;
  19. var nodeIndices = this.physicsBody.physicsNodeIndices;
  20. var forces = this.physicsBody.forces;
  21. // repulsing forces between nodes
  22. var nodeDistance = this.options.nodeDistance;
  23. // approximation constants
  24. var a = (-2 / 3) / nodeDistance;
  25. var b = 4 / 3;
  26. // we loop from i over all but the last entree in the array
  27. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
  28. for (let i = 0; i < nodeIndices.length - 1; i++) {
  29. node1 = nodes[nodeIndices[i]];
  30. for (let j = i + 1; j < nodeIndices.length; j++) {
  31. node2 = nodes[nodeIndices[j]];
  32. dx = node2.x - node1.x;
  33. dy = node2.y - node1.y;
  34. distance = Math.sqrt(dx * dx + dy * dy);
  35. // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping.
  36. if (distance === 0) {
  37. distance = 0.1*Math.random();
  38. dx = distance;
  39. }
  40. if (distance < 2 * nodeDistance) {
  41. if (distance < 0.5 * nodeDistance) {
  42. repulsingForce = 1.0;
  43. }
  44. else {
  45. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness))
  46. }
  47. repulsingForce = repulsingForce / distance;
  48. fx = dx * repulsingForce;
  49. fy = dy * repulsingForce;
  50. forces[node1.id].x -= fx;
  51. forces[node1.id].y -= fy;
  52. forces[node2.id].x += fx;
  53. forces[node2.id].y += fy;
  54. }
  55. }
  56. }
  57. }
  58. }
  59. export default RepulsionSolver;