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.

78 lines
2.2 KiB

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