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.

80 lines
2.2 KiB

  1. /**
  2. * Hierarchical Repulsion Solver
  3. */
  4. class HierarchicalRepulsionSolver {
  5. /**
  6. * @param {Object} body
  7. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  8. * @param {Object} options
  9. */
  10. constructor(body, physicsBody, options) {
  11. this.body = body;
  12. this.physicsBody = physicsBody;
  13. this.setOptions(options);
  14. }
  15. /**
  16. *
  17. * @param {Object} options
  18. */
  19. setOptions(options) {
  20. this.options = options;
  21. }
  22. /**
  23. * Calculate the forces the nodes apply on each other based on a repulsion field.
  24. * This field is linearly approximated.
  25. *
  26. * @private
  27. */
  28. solve() {
  29. var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j;
  30. var nodes = this.body.nodes;
  31. var nodeIndices = this.physicsBody.physicsNodeIndices;
  32. var forces = this.physicsBody.forces;
  33. // repulsing forces between nodes
  34. var nodeDistance = this.options.nodeDistance;
  35. // we loop from i over all but the last entree in the array
  36. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
  37. for (i = 0; i < nodeIndices.length - 1; i++) {
  38. node1 = nodes[nodeIndices[i]];
  39. for (j = i + 1; j < nodeIndices.length; j++) {
  40. node2 = nodes[nodeIndices[j]];
  41. // nodes only affect nodes on their level
  42. if (node1.level === node2.level) {
  43. dx = node2.x - node1.x;
  44. dy = node2.y - node1.y;
  45. distance = Math.sqrt(dx * dx + dy * dy);
  46. var steepness = 0.05;
  47. if (distance < nodeDistance) {
  48. repulsingForce = -Math.pow(steepness * distance, 2) + Math.pow(steepness * nodeDistance, 2);
  49. }
  50. else {
  51. repulsingForce = 0;
  52. }
  53. // normalize force with
  54. if (distance === 0) {
  55. distance = 0.01;
  56. }
  57. else {
  58. repulsingForce = repulsingForce / distance;
  59. }
  60. fx = dx * repulsingForce;
  61. fy = dy * repulsingForce;
  62. forces[node1.id].x -= fx;
  63. forces[node1.id].y -= fy;
  64. forces[node2.id].x += fx;
  65. forces[node2.id].y += fy;
  66. }
  67. }
  68. }
  69. }
  70. }
  71. export default HierarchicalRepulsionSolver;